Are there accessible vector interface functions when calling C in R - c

When to use .Call or .C in R related with vector arguments, my current way is to handle some attributes like the length, maximum value, etc., in R and then pass those attributes as arguments to C functions.
From R extension, at least a function names length is available. So are there similar interfaces in C to R vector functions like max, min, rep.

Rcpp has basic functions like min, max and rep. Consider the following example (suppose it's called example.cpp):
#include <Rcpp.h>
using namespace Rcpp;
// [[Rcpp::export]]
NumericVector exampleMinMax(NumericVector x) {
NumericVector out(2);
out[0] = min(x);
out[1] = max(x);
return out;
}
// [[Rcpp::export]]
NumericVector exampleRep(NumericVector x, int n) {
NumericVector out = rep_each(x, n);
return out;
}
Then in R you can do:
library(Rcpp)
sourceCpp("example.cpp")
exampleMinMax(1:10)
[1] 1 10
exampleRep(1:10, 2)
[1] 1 1 2 2 3 3 4 4 5 5 6 6 7 7 8 8 9 9 10 10

Related

Cubes in Cuboids

Helo everybody,
I need a C program to calculate the minimum amount of cuboids of size A by B by C to house a N cubes of side length S, where 1 <= N <= pow(10, 9), 1 <= S <= min(A, B, C), 1 <= A, B, C <= 1000. I did the following:
#include <stdio.h>
int main() {
unsigned long long int cubenum, length, boxnum, a, b, c, cpb;
scanf("%llu %llu %llu %llu %llu", &cubenum, &length, &a, &b, &c); getchar();
// how many cubes per box?
cpb = a/length * b/length * c/length;
// how many boxes given the amount of cubes?
boxnum = (cubenum + (cpb - 1)) / cpb;
printf("%llu\n", boxnum);
return 0;
}
The following testcases are given:
testcase #1
stdin: 24 4 8 8 8
stdout: 3
testcase #2
stdin: 27 3 8 4 10
stdout: 5
I added the following testcases myself:
testcase #3
stdin: 1 1 1 1 1
stdout: 1
testcase #4
stdin: 1000000000 500 999 999 999
stdout: 1000000000
testcase #5
stdin: 1000000000 499 999 999 999
stdout: 125000000
testcase #6
stdin: 1000000000 2 999 999 999
stdout: 9
I compiled with Clang version 10.0.0-4ubuntu1. The given testcases passed correctly on my device, and the ones I added myself seem correct when doing the math manually, however upon submission my program was declared "wrong". Unfortunately, there isn't any feedback as to where, why, or how it failed. The compiler the jury uses is unknown, however my past experience tell me it's likely running Linux (I tried using a Windows specific library function). Therefore, I would like to know, are there any test cases where my code would fail that I haven't caught? Or are there other oversights that I have made?
Thank you for your time.
Side question:
The part I suspect I am getting wrong is here:
boxnum = (cubenum + (cpb - 1)) / cpb;
I have tried using ceil() in math.h, but it feels really hacky with the double casts and then back to unsigned long long int, but it does work on all the testcases. I had to compile with clang -lm main.c -o main instead of clang main.c -o main, but it did run. Could it be that the jury has a modified math.h lib? On a different program, I used sqrt() and pow() and they were both accepted as correct, which tells me either the problem isn't where I suspect it to be, or that the jury indeed does have a modified math.h lib. Or could it be something else?
The line
cpb = a/length * b/length * c/length;
is wrong because this expression is calculated from left to right and truncation may not work well for b and c.
For example, with this input
15 10 100 10 19
The formula will be calculated like
a/length * b/length * c/length
= 100/10 * 10/10 * 19/10
= 10 * 10 / 10 * 19 / 10
= 100 / 10 * 19 / 10
= 10 * 19 / 10
= 190 / 10
= 19
Therefore, your program will output 1 because the required 15 cubes can be covered by 19 cubes while the correct output is 2 because actually only 10 cubes can be created from one box.
Try this:
cpb = (a/length) * (b/length) * (c/length);

Solving code-forces "1A Theatre Square" in C

novice programmer here trying to get better at C, so i began doing code problems on a website called codeforces. However i seem to be stuck, i have written code that appears to work in practice but the website does not accept it as right.
the problem :
Theatre Square in the capital city of Berland has a rectangular shape with the size n × m meters. On the occasion of the city's anniversary, a decision was taken to pave the Square with square granite flagstones. Each flagstone is of the size a × a. What is the least number of flagstones needed to pave the Square? It's allowed to cover the surface larger than the Theatre Square, but the Square has to be covered. It's not allowed to break the flagstones. The sides of flagstones should be parallel to the sides of the Square.1
Source :
https://codeforces.com/problemset/problem/1/A
I did have a hard time completely understanding the math behind the problem and used this source's answer from a user named "Joshua Pan" to better understand the problem
Source :
https://www.quora.com/How-do-I-solve-the-problem-Theatre-Square-on-Codeforces
This is my code :
#include<stdio.h>
#include<math.h>
int main(void)
{
double n,m,a;
scanf("%lf %lf %lf", &n,&m,&a);
printf("%1.lf\n", ceil(n/a)*ceil(m/a));
return 0;
}
I compiled it using "gcc TheatreSquare.c -lm"
When given the sample input 6,6,4 my code produces the correct output 4, however the website does not accept this code as correct, i could be wrong but maybe im using format specifiers incorrectly?
Thanks in advance.
Typical double (IEEE754 64-bit floating point) doesn't have enough accuracy for the problem.
For example, for input
999999999 999999999 1
Your program may give output
999999998000000000
While the actual answer is
999999998000000001
To avoid this, you shouldn't use floating point data type.
You can add #include <inttypes.h> and use 64-bit integer type int64_t for this calculation.
"%" SCNd64 is for reading and "%" PRId64 is for writing int64_t.
cell(n/a) on integers can be done by (n + a - 1) / a.
You can solve this using integers.
#include <stdio.h>
int main()
{
unsigned long n, m, a = 1;
unsigned long na, ma, res = 0;
scanf("%lu %lu %lu", &n, &m, &a);
na = n/a;
if (n%a != 0)
na++;
ma = m/a;
if (m%a != 0)
ma++;
res = na * ma;
printf("%lu", res);
return 0;
}
This code will fail in the Codeforce platform, on the test 9 (see below). But if you compile it and run it locally with the same inputs, the result is correct.
> Test: #9, time: 15 ms., memory: 3608 KB, exit code: 0, checker exit code: 1, verdict: WRONG_ANSWER
> Input 1000000000 1000000000 1
> Output 2808348672 Answer 1000000000000000000
> Checker Log wrong answer 1st numbers differ - expected: '1000000000000000000', found: '2808348672'
EDIT:
The problem described above is due to the fact that I'm running a 64-bit machine and the online compiler is probably using 32-bit. The unsigned long variables overflow.
The following code will pass all the tests.
#include <stdio.h>
int main()
{
unsigned long long n, m, a = 1;
unsigned long long na, ma, res = 0;
scanf("%llu %llu %llu", &n, &m, &a);
na = n/a;
if (n%a != 0)
na++;
ma = m/a;
if (m%a != 0)
ma++;
res = na * ma;
printf("%llu", res);
return 0;
}
Use the code below it will pass all the test cases we need to use long long for all variable declaration to get output.
#include <stdio.h>
#include <math.h>
int main(){
long long n,m,a,l,b;
scanf("%lld%lld%lld",&n,&m,&a);
l= n/a;
if(n%a != 0)
l++;
b= m/a;
if(m%a != 0)
b++;
printf("%lld",l*b);
return 0;
}
Theatre Square in the capital city of Berland has a rectangular shape with the size n × m meters. On the occasion of the city's anniversary, a decision was taken to pave the Square with square granite flagstones. Each flagstone is of the size a × a.
import java.util.Scanner;
public class theatre_square {
public static void main(String[] args) {
long a,b,c;
Scanner s = new Scanner(System.in);
a = s.nextLong();
b = s.nextLong();
c = s.nextLong();
long result = 0;
if(a>=c){
if(a%c==0)
result = a/c;
else
result = a/c + 1; // some part is left
}else{ // area of rectangle < area of square then 1 square is required
result = 1;
}
if(b>=c){
if(b%c==0)
result *= b/c;
else
result *= b/c + 1;
}
System.out.println(result);
}
}
case 1 . 2 2 3 => 1
length = 2 so 2 < 3 then only 1 square required <br>
breadth = 2 so 2 < 3 then covered in previous square so output 1
intial view
0 0
0 0
after adding 1 square ( r= remaining or left)
1 1 r
1 1 r
r r r
case 2 . 6 6 4 => 4
length = 2 so 6 > 4 then only 2 square required <br>
breadth = 2 so 6 > 4 then 2 square required
intial view
0 0 0 0 0 0
0 0 0 0 0 0
0 0 0 0 0 0
0 0 0 0 0 0
0 0 0 0 0 0
0 0 0 0 0 0
after adding 4 square ( r= remaining or left)
1 1 1 1 2 2 r r
1 1 1 1 2 2 r r
1 1 1 1 2 2 r r
1 1 1 1 2 2 r r
3 3 3 3 4 4 r r
3 3 3 3 4 4 r r
r r r r r r r r
r r r r r r r r
You can try the following:
import math
x,y,z=list(map(float, input().split()))
print(math.ceil(x/z)*math.ceil(y/z))
Here is the code for the above problem in CPP. We need a long long variable to store the value as we may have a very large value.
GUIDANCE ABOUT THE QUESTION:
As we are given the hint of edges so we have to cover them nicely. For a rectangle, we know that we have a length and height which is shown as n * m and the square is of a*a so we will try to cover the length first and decide its squares first
for that, we divide it by k, and then if any remainder exists we will add one more and the same for height.
I hope it will help you
HERE IS THE CODE
#include<iostream>
using namespace std;
int main()
{
long long n,m,k,l=0,o=0;
cin>>n>>m>>k;
l=n/k;
if(n%k!=0)
{
l++;
}
o=m/k;
if(m%k!=0)
{
o++;
}
cout<<l*o;
}

Standard C function is slower at the first call, how to solve this properly?

I want to make timing tests for learning how to benchmark using "time.h". But I noticed the first test is always longer.
0 1 2 3 4 5 6 7 8 9
time 0.000138
0 1 2 3 4 5 6 7 8 9
time 0.000008
0 1 2 3 4 5 6 7 8 9
time 0.000007
If I want to do several tests in the same main() function the results will be unreliable.
Here is the stupid code who prints the output above.
#include <stdio.h>
#include <time.h>
const int COUNT = 10;
void test() {
clock_t start = clock();
for(int i = 0; i < COUNT; i++) {
printf("%d ", i);
}
printf("\ntime %lf\n", (double)(clock() - start) / (double)CLOCKS_PER_SEC );
}
int main() {
test();
test();
test();
return 0;
}
I solved this by ignoring the first "test" function. Also, writing a first "printf" who prints some integer before the tests works too. But I guess it's not a proper solution.
CPU has cache. When code and data are not in cache, the code takes longer to run.
It's standard practice to discard the result of first run (or first few runs) when measuring performance. It's sometimes called "cache warmup".

R: how to let .C call update output variable?

I am trying to write a C code to use in R, but found that the .C function call won't update output variable. The real C code is complicated, but here is a simple example to show the behavior:
void doubleMe(const int *input, int *output) {
output[0] = input[0] * 2;
}
Save above C function into file doubleMe.c. Under Linux, compile it to create doubleMe.so file:
R CMD SHLIB doubleMe.c
In R, if I do following:
dyn.load("doubleMe.so") # load it
input = 2
output = 0
.C("doubleMe", as.integer(input), as.integer(output)) # expect output=4
[[1]]
[1] 2
[[2]]
[1] 4
The screen output indicates the input is doubled, but the output in R is still 0:
output
[1] 0
If I do fowllwing
output = .C("doubleMe", as.integer(input), as.integer(output))[[2]]
the output is 4. This should work for the example.
But my real input and output are matrix, and I have to reshape the output to correct dimension. Is there a way to let .C call update output directly?
With the .Call() interface using SEXP data types where P stands for pointer, this is automagic:
R> Rcpp::cppFunction("void doubleMe(NumericVector x) { x = 2*x; } ")
R> x <- 1 # set to one
R> doubleMe(x) # call function we just wrote
R> x # check ...
[1] 2 # and it has doubled as a side-effect
R>
I use Rcpp here as it allows me to do this on one line, you could do the same in a few lines of C code if you wanted to.

passing in R array to C function with "NA"

I work in R using C libraries. I need to pass to a C function an array with numbers between 1 and 10 but that could also be "NA". Then in C, depending on the value I need to set the output.
Here's a simplified code
heredyn.load("ranking.so")
fun <- function(ranking) {
nrak <- length(ranking)
out <- .C("ranking", as.integer(nrak), as.character(ranking), rr = as.integer(vector("integer",nrak)))
out$rr
}
ranking <- sample(c(NA,seq(1,10)),10,replace=TRUE)
rr <- fun(ranking)
The C function could simply be such as
#include <R.h>
void ranking(int *nrak, char *ranking, int *rr) {
int i ;
for (i=0;i<*nrak;i++) {
if (ranking[i] == 'NA')
rr[i] = 1 ;
else
rr[i] = (int) strtol(&ranking[i],(char **)NULL,10) ;
}
}
Due to the "NA" value I set ranking as character but maybe there's another way to do that, using integer and without replacing "NA" to 0 before calling the function?
(The code like this, gives me always an array of zeros...)
Test for whether the value is an NA using R_NaInt, like
#include <R.h>
void ranking_c(int *nrak, int *ranking, int *rr) {
for (int i=0; i < *nrak; i++)
rr[i] = R_NaInt == ranking[i] ? -1 : ranking[i];
}
Invoke from R by explicitly allowing NAs
> x = c(1:2, NA_integer_)
> .C("ranking_c", length(x), as.integer(x), integer(length(x)), NAOK=TRUE)[[3]]
[1] 1 2 -1
Alternatively, use R's .Call() interface. Each R object is represented as an S-expression. There are C-level functions to manipulate S-expressions, e.g., length Rf_length(), data access INTEGER(), and allocation Rf_allocVector() of different types of S-expressions such as INTSXP for integer vectors.
R memory management uses a garbage collector that can run on any call that allocates memory. It is therefore best practice to PROTECT() any R allocation while in scope.
Your function will accept 0 or more S-expressions as input, and return a single S-expression; it might be implemented as
#include <Rinternals.h>
#include <R_ext/Arith.h>
SEXP ranking_call(SEXP ranking)
{
/* allocate space for result, PROTECTing from garbage collection */
SEXP result = PROTECT(Rf_allocVector(INTSXP, Rf_length(ranking)));
/* assign result */
for (int i = 0; i < Rf_length(ranking); ++i)
INTEGER(result)[i] =
R_NaInt == INTEGER(ranking)[i] ? -1 : INTEGER(ranking)[i];
UNPROTECT(1); /* no more need to protect */
return result;
}
And invoked from R with .Call("ranking_call", as.integer(ranking)).
Using .Call is more efficient than .C in terms of speed and memory allocation (.C may copy atomic vectors on the way in), but the primary reason to use it is for the flexibility it offers in terms of working directly with R's data structures. This is especially important when the return values are more complicated than atomic vectors.
You are attempting to address a couple of delicate and non-trivial points, least of all how to compile code with R, and to test for non-finite values.
You asked for help with C. I would like to suggest C++ -- which you do not need to use in a complicated way. Consider this short file with contains a function to process a vector along the lines you suggest (I just test for NA and then assign 42 as a marker for simplicit) or else square the value:
#include <Rcpp.h>
using namespace Rcpp;
// [[Rcpp::export]]
NumericVector foo(NumericVector x) {
unsigned int n = x.size();
for (unsigned int i=0; i<n; i++)
if (NumericVector::is_na(x[i]))
x[i] = 42.0;
else
x[i] = pow(x[i], 2);
return x;
}
/*** R
foo( c(1, 3, NA, NaN, 6) )
*/
If I save this on my box as /tmp/foo.cpp, in order compile, link, load and even run the embedded R use example, I only need one line to call sourceCpp():
R> Rcpp::sourceCpp("/tmp/foo.cpp")
R> foo( c(1, 3, NA, NaN, 6))
[1] 1 9 42 42 36
R>
We can do the same with integers:
// [[Rcpp::export]]
IntegerVector bar(IntegerVector x) {
unsigned int n = x.size();
for (unsigned int i=0; i<n; i++)
if (IntegerVector::is_na(x[i]))
x[i] = 42;
else
x[i] = pow(x[i], 2);
return x;
}

Resources