I am working on a project that I port some Java code into C. Everything has gone well until now but I'm stucked at porting Random.nextInt(int bound) method into C.
My Java code is:
int arr[] = new int[100000];
Random r = new Random(0);
for (int i = 0; i < 100000; i++)
arr[i] = r.nextInt(20);
where arr array has always the same contents (after each execution) which is normal.
My equivalent C code is:
int arr[100000], i;
srand(0);
for (i = 0; i < 100000: i++)
arr[i] = rand() % 20;
The contents of two arr arrays are not same.
I thought to print the generated random numbers to a file in Java code in order to use them (the numbers) as a constant array in C code instead of using rand() function but the size of the array will be so huge which will prevent me to do this because the C code will work on an embedded device (microcontroller).
My question is how can I port that Java code into C where I can obtain the same random numbers?
The Java Random class and rand in C use two different psuedorandom number generators. You will not be able to reproduce the exact same random numbers with C that you did with Java.
The way you are writing your application you shoud avoid depending on having the exact same random numbers.
Java JDK sources are publicly available.
If you want an exact equivalent of Java's random number generator in C, go grab the sources and write/port it yourself.
Related
I'm trying to code the game Minesweeper and for that I need to randomize the bombs locations.
Can someone help change the function a bit so that placing of bombs is randomized?
THE CODE:
void Createbomb(int*** bord, int size)//size+1
{
//bomb num.1
(*bord)[size - 5][size - 1] = 9;
//bomb num.2
(*bord)[size - 4][size - 4] = 9;
//bomb num.3
(*bord)[size - 3][size - 2] = 9;
//bomb num.4
(*bord)[size - 2][size - 2] = 9;
//bomb num.5
(*bord)[size - 1][size - 5] = 9;
}
I wrote a ncurses based Minesweeper a long time ago (around 1993). It's opensource and it's now in Github, If you want hints about how to implement some part of it, you have full source code there. You are free to download, clone, and even to show me better ways to implement something if you get some.
My approach was to use a matrix for the field cells, and to store on them the number of neighbour bombs, while one bit stored the presence of a bomb. I'm afraid it was written so long ago that I have not had a time to translate all the comments and identifiers into english... but probably this is a good time to do so.... let's think on it.
Do not use the modulus to get a pseudo-random number, since with a few trials, we can easily figure out which is going to be the next number. There are several ways of randomize in a good way, this is one way, that is better that using the modulus:
(If you have interest, there are more complex ways to generate random numbers)
#include <stdlib.h>
int random_num(int inf, int sup)
{
if(inf < 0 || sup-inf < 0) return -1; /*Only positive numbers because it is an array */
return inf+(int)(((sup-inf+1.0)*rand())/(RAND_MAX + 1.0));
}
RAND_MAX is a constant value defined in stdlib.h, roughly speaking it is a huge integer constant, i.e, a big integer number.
So, in your program you just have to call:
int x = random_num(0, size); /*Gets a new random number in the desired range*/
Suppose that the number of bombs you need is 5. Also, let initially board contain default value of 1 for all cells, and 9 only if there is a bomb present in the cell. Then you can do something like:
void createBomb(int*** board, int size){
srand(time(0));
int numOfBombsPlaced = 0;
while(numOfBombsPlaced < 5){
int x = rand()%size;
int y = rand()%size;
if ((*board)[x][y]==9):
continue;
numOfBombsPlaced++;
(*board)[x][y] = 9;
}
}
Note that the numbers generated by rand are not truly random, and depend on the initial seed. The seed is provided by srand. Using time for seed is a good option to randomise.
Is there a somewhat easy way to transfer an array of integers from a C program to matlab? I have found several guides online on how to do it between C++ and Matlab, but not for C to Matlab.
I have several arrays of 1180 floats that I produce with a program written in C. Now I want to visualize this data in Matlab. I could have the C program export the Matlab code necessary to create the arrays hard-coded, but this seems unnecesarily devious.
I could just use the C++ method and compile my C program with a C++ compiler but at this point I am just curious if it can also be done in C.
Matlab can import .mat files, but these files seem to be encrypted or in binary format.
Please don't give suggestions on how to visualize the data in C, I have to do it in Matlab. I have a piece of code in Matlab that is returning weird results and I wrote the equivalent code in C, now I want to see if there is a difference in results. This way I can debug my Matlab code, since the end result has to be handed in in Matlab code.
My C code so far. Also I made a mistake in my initial upload, I want to transfer an array of integers.
FILE *f = fopen("Ps.bin", "wb");
for(int n = 1; n < N + 1; n++)
{
converter.asInt = Ps[n];
for(int i = 0; i < 4; i++)
{
fwrite(&converter.asBytes[i], sizeof(char), 1, f);
}
}
fclose(f);
This is what I tried in matlab, but none of it gives the proper result. In all cases matlab makes an array of doubles, which I definately don't want. It just generates an array with values that are one of these three: 0, 0.0000 and 4.925.
Ps = fread(fopen('Ps.bin'))
Ps = fread(fopen('Ps.bin'), 1180)
Ps = fread(fopen('Ps.bin'), 1180, 'uint32')
Ps = fread(fopen('Ps.bin'), 1180, '2 * uint16')
Write a binary file in C (using fwrite, look here). From matlab, you can read it using the procedure here (freadfunction)
I have applied the normal distribution function using the equation given in this link:
http://en.wikipedia.org/wiki/Normal_distribution
I made this code for normal distribution
float m=2.0;
float s=0.5;
float x[3]={1.0, 2.0, 3.0};
float xs[3];
const float pi = 3.141;
for (int i=0; i<3; i++)
{
xs[i]=(1/s*sqrt(2*pi))*exp(-(pow(x[i]-m,2)/2*pow(s,2)));
printf("\n%f",xs[i]);
}
The answer for this code is 4.42, 5.01, 4.42
and I have the same code in Matlab
x_s_new=[1 2 3];
x_s=2+0.5.*randn(1,9);
x_s=x_s_new+0.5.*randn(1,3);
plot(x_s_new)
but the answers in matlab is 0.8 , 1.9 , 3.7
Can anyone tell me where I am going wrong?
I want to apply normal distribution using C
Thanks :)
Your Matlab code is not the analogue of your C code. The C code computes the value of the probability density function of the normal distribution at certain points. The Matlab code generates random numbers from the normal distribution.
The Matlab code corresponding to the C code is
m = 2;
s = 0.5;
x = [1 2 3];
for i = 1 : 3
xs(i) = (1/s*sqrt(2*pi)) * exp(-( (x(i)-m)^2/2*s^2));
fprintf('%f\n',xs(i));
end
and gives the same result
4.424183
5.013257
4.424183
However, there's a mistake because / in Matlab and C only applies to the immediate next operand. Correctly it would be
xs(i) = 1/(s*sqrt(2*pi)) * exp(-( (x(i)-m)^2/(2*s^2)));
and correspondingly in C.
To translate the code using randn to C – to my knowledge there is no standard function in C to generate normally distributed random numbers, you need to find a library that includes such a function, or build it yourself starting from random().
Edit3: Optimized by limiting the initialization of the array to only odd numbers. Thank you #Ronnie !
Edit2: Thank you all, seems as if there's nothing more I can do for this.
Edit: I know Python and Haskell are implemented in other languages and more or less perform the same operation I have bellow, and that the complied C code will beat them out any day. I'm just wondering if standard C (or any libraries) have built-in functions for doing this faster.
I'm implementing a prime sieve in C using Eratosthenes' algorithm and need to initialize an integer array of arbitrary size n from 0 to n. I know that in Python you could do:
integer_array = range(n)
and that's it. Or in Haskell:
integer_array = [1..n]
However, I can't seem to find an analogous method implemented in C. The solution I've come up with initializes the array and then iterates over it, assigning each value to the index at that point, but it feels incredibly inefficient.
int init_array()
{
/*
* assigning upper_limit manually in function for now, will expand to take value for
* upper_limit from the command line later.
*/
int upper_limit = 100000000;
int size = floor(upper_limit / 2) + 1;
int *int_array = malloc(sizeof(int) * size);
// debug macro, basically replaces assert(), disregard.
check(int_array != NULL, "Memory allocation error");
int_array[0] = 0;
int_array[1] = 2;
int i;
for(i = 2; i < size; i++) {
int_array[i] = (i * 2) - 1;
}
// checking some arbitrary point in the array to make sure it assigned properly.
// the value at any index 'i' should equal (i * 2) - 1 for i >= 2
printf("%d\n", int_array[1000]); // should equal 1999
printf("%d\n", int_array[size-1]); // should equal 99999999
free(int_array);
return 0;
error:
return -1;
}
Is there a better way to do this? (no, apparently there's not!)
The solution I've come up with initializes the array and then iterates over it, assigning each value to the index at that point, but it feels incredibly inefficient.
You may be able to cut down on the number of lines of code, but I do not think this has anything to do with "efficiency".
While there is only one line of code in Haskell and Python, what happens under the hood is the same thing as your C code does (in the best case; it could perform much worse depending on how it is implemented).
There are standard library functions to fill an array with constant values (and they could conceivably perform better, although I would not bet on that), but this does not apply here.
Here a better algorithm is probably a better bet in terms of optimising the allocation:-
Halve the size int_array_ptr by taking advantage of the fact that
you'll only need to test for odd numbers in the sieve
Run this through some wheel factorisation for numbers 3,5,7 to reduce the subsequent comparisons by 70%+
That should speed things up.
I'm trying to understand and learn the C language, and since I used to work in Matlab, I'm interested in knowing how this code would be converted into C.
for j=1:n
v=A(:,j);
for i=1:j-1
R(i,j)=Q(:,i)'*A(:,j);
v=v-R(i,j)*Q(:,i);
end
R(j,j)=norm(v);
Q(:,j)=v/R(j,j);
end
Do you know about the Matlab Coder? Matlab can automatically generate c/c++ code for you. It has its limitations, but if are trying to learn c from Matlab, using the coder should be the best way for you to populate many examples.
Arrays are declared and accessed like so:
const int N = 10; // needs to be a constant
double v[N]; // 1-d
double A[N][N]; // 2-d
v[0] = A[1][2]; // indexing starts at 0, not 1
C doesn't do automatic vectorization like matlab, so you have to do it in for-loops manually. Instead of R(i,j)=Q(:,i)'*A(:,j),
for (int k = 0; k < N; ++k) {
R[i][j] += Q[k][i] * A[k][j];
}
That last piece also demonstrates what a for-loop looks like - the first "argument" of the "for" is the initialization of the indexing variable k, the second sets the condition under which the for loop continues, and the third increments k. The code to be executed in the loop is enclosed in braces {}.
The main logical difference is that you have to do everything element-by-element in C.