I'm beginner to Rcpp I had this error message to run the following R code. I use Windows 10.
"Error in compileCode(f, code, language = language, verbose = verbose) :
Compilation ERROR, function(s)/method(s) not created! Warning message:"
incltxt <- '
int fibonacci(const int x) {
if (x == 0) return(0);
if (x == 1) return(1);
return fibonacci(x - 1) + fibonacci(x - 2);
}'
fibRcpp <- cxxfunction(signature(xs="int"),
plugin="Rcpp",
incl=incltxt,
body='
int x = Rcpp::as<int>(xs);
return Rcpp::wrap( fibonacci(x) );
')
Consider the simpler and newer cppFunction():
R> library(Rcpp)
R> cppFunction('int f(int n) { if (n < 2) return n; return f(n-1) + f(n-2);}')
R> f(10)
[1] 55
R>
Edit: And here is your repaired code. You need to also load Rcpp to have its plugin registered:
R> library(Rcpp)
R> library(inline)
R> incltxt <- '
+ int fibonacci(const int x) {
+ if (x == 0) return(0);
+ if (x == 1) return(1);
+ return fibonacci(x - 1) + fibonacci(x - 2);
+ }'
R> bodytxt <- '
+ int x = Rcpp::as<int>(xs);
+ return Rcpp::wrap( fibonacci(x) );
+ '
R> fibRcpp <- inline::cxxfunction(signature(xs="int"), incl=incltxt, body=bodytxt, plugin="Rcpp")
R> fibRcpp(10)
R> 55
Related
When using the crossterm library with this code:
fn draw_box(stdout: &mut Stdout, x: u16, y: u16) -> Result<()> {
let size = 5;
let outline = (x..x + size)
.map(|i| (i, y))
.chain((y + 1..y + size - 1).map(|i| (x + size - 1, i)))
.chain((y + 1..y + size - 1).map(|i| (x, i)))
.chain((x..x + size).map(|i| (i, y + size - 1)))
.collect::<Vec<_>>();
for (a, b) in outline {
stdout
.queue(cursor::MoveTo(a, b))?
.queue(style::Print("x"))?;
}
stdout.flush()?;
stdout
.queue(cursor::MoveTo(x + 2, y + 2))?
.queue(style::Print("o"))?;
stdout.flush()?;
Ok(())
}
The last draw command clears the rest of the output to give this:
xxxxx
x x
x o%
If I remove that command I get the full box:
xxxxx
x x
x x
x x
xxxxx%
How can I draw the box and then draw the circle inside of the box?
I have tried to implement stratified sampling in my ray tracer. But nothing is changed.
First I simply change my sampler from
while (s ++ < 100)
sampling(v, x, y);
to
while (s ++ < 10)
{
t = 0;
while (t ++ < 10)
stratified_sampling(v, x, y, s, t);
}
and in the sampling function,
u = ((double)x + random_double(0, 1))
v = ((double)y + random_double(0, 1))
this code changed to
u = ((double)x + ((double)s + random_double(0, 1)) / 10)
v = ((double)y + ((double)t + random_double(0, 1)) / 10)
so the 100 sampling should be done in the 10 x 10 grid in one pixel as i expected.
but the result image is not changed at all, at least in my opinion. what's the problem? Is it normal?? (first one is before stratified sampling)
Heres what I want (image):
Main Idea is:
InputField is a function that calls something if input value changed.
For example: you have text input field in game and you add text to it, when value doesnt change until like 1 second it will call code like g_Engine.ChangeName()
Heres also callback class, but I dont know how to do it still please help
Code:
typedef void (*fn_callback)(void);
class pCallback
{
public:
pCallback(fn_callback callback);
fn_callback callback_void{ nullptr };
};
class CMenu
{
private:
void InputField(int x, int y, char* text, int maxLen, int& out, ...);
};
extern CMenu g_Menu;
void CMenu::InputField(int x, int y, char* text, int maxLen, int& out, ...)
{
unsigned int w = 220;
unsigned int h = 16;
g_pISurface->DrawSetColor(cvar.cheat_global_color_r, cvar.cheat_global_color_g, cvar.cheat_global_color_b, 255);
g_pISurface->DrawOutlinedRect(x - 2, y - 2, x + w + 2, y + h + 2);
bool clicked = false;
static DWORD dwTemporaryBlockTimer = 0;
static std::string value;
if (GetTickCount() - dwPaletteBlockedTime > 200 && GetTickCount() - dwListBlockedTime > 200 && !bCursorInPalette && !bCursorInList && keys[VK_LBUTTON] && !IsDragging && CursorX >= x && CursorX <= x + w && CursorY >= y && CursorY <= y + h)
{
if (GetTickCount() - dwTemporaryBlockTimer > 200)
{
clicked = true;
dwTemporaryBlockTimer = GetTickCount();
}
}
if (clicked || CursorX >= x && CursorX <= x + w && CursorY >= y && CursorY <= y + h)
{
g_pISurface->DrawSetColor(cvar.cheat_global_color_r, cvar.cheat_global_color_g, cvar.cheat_global_color_b, 255);
g_pISurface->DrawOutlinedRect(x - 1, y - 1, x + w + 1, y + h + 1);
}
if (text)
g_Drawing.DrawString(MENU, x + 1, y - 10, 215, 215, 215, 255, FONT_LEFT, text);
if (GetTickCount() - dwInputfieldBlockedTime > 200 && !bCursorInPalette && !bCursorInList && !IsDragging && CursorX >= x && CursorX <= x + w && CursorY >= y && CursorY <= y + h)
{
if (maxLen != 0)
{
if (!(value.length() > maxLen))
value.append(GetPressedNumKeyString());
}
if (keys[VK_BACK])
{
if (!value.empty())
value.erase(std::prev(value.end()));
}
dwInputfieldBlockedTime = GetTickCount();
}
int iVal = std::atoi(value.c_str());
if (out != iVal)
out = iVal;
if (!value.empty())
g_Drawing.DrawString(MENU, x + w / 2, y + (h / 2), 220, 220, 220, 255, FONT_CENTER, value.c_str());
else
g_Drawing.DrawString(MENU, x + w / 2, y + (h / 2), 81, 81, 81, 255, FONT_CENTER, "N/A");
}
I think I did it
void CMenu::InputField(int x, int y, char* text, int maxLen, int& out, std::function<void()>&& Callback)
{
if (out != iVal)
{
out = iVal;
Callback();
}
}
InputField(x + box_indent_x, y + line_y, "SteamID", 31, SID, []() { g_SteamID.Apply(SID); });
I am fairly new learner to Rcpp, primarily needing it to speed up slow R code that is not easily parallelized because of dependencies within for loop iterations.
I wish to convert the following R code to C++ code to be directly used via Rcpp.
migrate_r <- function(pop) {
if (m != 0) {
if (model == "Step") {
for (i in 1:K) {
for (j in 1:K) {
for (k in 2:(K - 1)) {
i <- sample(perms, size = ceiling(perms * m/2), replace = FALSE)
j <- sample(perms, size = ceiling(perms * m/2), replace = FALSE)
tmp <- pop[i,, sample(k)]
pop[i,, sample(k)] <- pop[j,, sample(k)]
pop[j,, sample(k)] <- tmp
}
}
}
}
}
pop
}
My attempt is as follows:
// [[Rcpp::depends(RcppArmadillo)]]
#define ARMA_DONT_PRINT_OPENMP_WARNING
#include <RcppArmadillo.h>
#include <RcppArmadilloExtensions/sample.h>
#include <set>
using namespace Rcpp;
// [[Rcpp::export]]
arma::Cube<int> migrate_cpp(arma::Cube<int> pop) {
String model;
int i, j, k, K, perms, tmp;
double m;
if (m != 0) {
if (model == "Step") {
for (i = 0; i < K; i++) {
for (j = 0; j < K; j++) {
for(k = 1; k < (K - 1); k++) {
i = RcppArmadillo::sample(perms, ceil(perms * m / 2), false);
j = RcppArmadillo::sample(perms, ceil(perms * m / 2), false);
tmp = pop[i, RcppArmadillo::sample(k, K, true)];
pop[i, RcppArmadillo::sample(k, K, true)] = pop[j, RcppArmadillo::sample(k, K, true)];
pop[j, RcppArmadillo::sample(k, K, true)] = tmp;
}
}
}
}
}
return pop;
}
Essentially both functions swap random rows in an 3-dimensional array ('pop') via a temporary variable. The C++ code doesn't run.
I know I am close to getting the C++ code to work, which will result in massive speedup compared to the R for loop.
Is there something I am missing here? Any assistance is greatly appreciated and warmly welcomed.
A reproducible example
##### Load packages #####
library(Rcpp)
library(RcppArmadillo)
### Set parameters ###
K <- 2
N <- 6
Hstar <- 5
probs <- rep(1/Hstar, Hstar)
m <- 0.20
perms <- 2 # number of permutations
num.specs <- ceiling(N / K)
haps <- 1:Hstar
specs <- 1:num.specs
gen.perms <- function() {
sample(haps, size = num.specs, replace = TRUE, prob = probs)
}
pop <- array(dim = c(perms, num.specs, K))
for (i in 1:K) {
pop[,, i] <- replicate(perms, gen.perms())
}
pop
, , 1
[,1] [,2] [,3]
[1,] 3 5 1
[2,] 2 3 3
, , 2
[,1] [,2] [,3]
[1,] 2 5 3
[2,] 3 5 3
migrate_r(pop) # notice rows have been swapped between subarrays
, , 1
[,1] [,2] [,3]
[1,] 3 5 1
[2,] 2 5 3
, , 2
[,1] [,2] [,3]
[1,] 3 5 3
[2,] 2 3 3
I have a string s containing different types of brackets : () and [] . How can I balance a string of this type with the minimum possible number of reversals ? I can replace any bracket with any other one.
For example : Cost for [)(] is 2, it becomes [()]. Cost for [](( is 1, it becomes []() . [(]) is not balanced.
A more complex example : )[)([)())] can be turned to ([])[(())] in 4 changes, but can also be turned to [()(()())] in 3 steps, which is the least number of modifications to make it balanced.
How can I solve the problem ?
First approach I came with is O(n^3) dynamic programming.
Let match(i, j) be the number of replaces you have to make in order to make s[i] and s[j] as () or []. So match(i, j) can be either 0, 1 or 2.
Consider dp[i][j] = the minimum cost to balance the subsequence from i to j in your brackets array. Now you will define dp[i][i + 1] as:
dp[i][i + 1] = match(i, i + 1)
Now the general rule is that we take the overall minimum between dp[i + 1][j - 1] + match(i, j) and min(dp[i][j], dp[i][p] + dp[p + 1][j]) for any i < p < j. Obviously, the result will be held in dp[1][n]. There is a C++ solution (I'll also upload a python program in about 15 minutes when I'll be done with it - not so strong with python :P).
#include <iostream>
#include <string>
using namespace std;
int dp[100][100];
string s;
int n;
int match(char a, char b) {
if (a == '(' && b == ')') {
return 0;
}
if (a == '[' && b == ']') {
return 0;
}
if ((a == ')' || a == ']') && (b == '(' || b == '[')) {
return 2;
}
return 1;
}
int main() {
cin >> s;
n = s.length();
s = " " + s;
for (int i = 0; i <= n; ++i) {
for (int j = 0; j <= n; ++j) {
dp[i][j] = 0x3f3f3f3f;
}
}
for (int i = 1; i < n; ++i) {
dp[i][i + 1] = match(s[i], s[i + 1]);
}
for (int k = 3; k <= n; k += 2) {
for (int i = 1; i + k <= n; ++i) {
int j = i + k;
dp[i][j] = min(dp[i][j], dp[i + 1][j - 1] + match(s[i], s[j]));
for (int p = i + 1; p <= j; p += 2) {
dp[i][j] = min(dp[i][j], dp[i][p] + dp[p + 1][j]);
}
}
}
cout << dp[1][n] << '\n';
/*for (int i = 1; i <= n; ++i) {
for (int j = 1; j <= n; ++j) {
cout << dp[i][j] << ' ';
}
cout << '\n';
}*/
return 0;
}
Edit:
Here you go Python :)
s = input()
n = len(s)
inf = 0x3f3f3f3f
def match(x, y):
if x == '(' and y == ')':
return 0
if x == '[' and y == ']':
return 0
if (x == ')' or x == ']') and (y == '(' or y == '['):
return 2
return 1
# dp[i][j] = min. cost for balancing a[i], a[i + 1], ..., a[j]
dp = [[inf for j in range(n)] for i in range(n)]
for i in range(n - 1):
dp[i][i + 1] = match(s[i], s[i + 1])
for k in range(3, n, 2):
i = 0
while i + k < n:
j = i + k
dp[i][j] = min(dp[i][j], dp[i + 1][j - 1] + match(s[i], s[j]))
for p in range(i + 1, j, 2):
dp[i][j] = min(dp[i][j], dp[i][p] + dp[p + 1][j])
i += 1
print(dp[0][n - 1])
#for i in range(n):
# for j in range(n):
# print(dp[i][j], end = ' ')
# print()