Randomly fill 100 grid of 100X100 matrix by 1 - c

I have a matrix for M[100][100], all filled with ZERO. Now I want to fill randomly 100 grids by '1'. How do I do that?
Challenge I am facing:
When I randomly select any position (x, y), that position can be already filled by 1. I have to minimise rand() call count. Is it possible to fill within 100 rand() call limit?
The question was marked as duplicated with another question but that does not solve my problem? Any generalised idea for 2D matrix?

Use the Fisher-Yates solution from this answer. Specifically you'd want to once create an array that contains numbers 0 ... 9999, where x = i % 100 and y = i / 100, say.
Or if you want, you could as well use an array of struct coords { char x, y; }.
Then you shuffle only the first (or last) 100 elements, after which those first (last) 100 elements will be your coordinates. You can reuse the same array without subsequent initialization. Each 100 random fillings require only exactly 100 random numbers being generated.

Related

Caseless way of calculating volume of an intersection between an array and a square in multiple dimensions

I have a multidimensional array and while iterating through its every element, I need to calculate the volume of the square, cube, or other respective objects in case of dimensions higher than 3, in each element, the size of 2r. If I'm iterating through elements near the boundaries of the array, part of that square/cube is going to stick outside the array - and I need the volume of the intersection between the array and the object.
This is how the problem looks in 2D - I need to calculate the red area.
I know two ways so far of doing that:
Cases and if-statements. For 2D, I could calculate the coordinates of the corners of the intersection, but since this isn't strictly a 2D problem, but a multidimensional one, where the number of dimensions is given on input, cases and if-statements and subsequent hardcoding are out of question.
Manually iterating through every element in the square and checking if it belongs to the array. While this is easy to do, it is also incredibly slow, even in 2D, because I'm iterating through an n-dimensional array, and in each iteration, I'm again doing n loops the size of 2r^n. Bigger the radius, slower the execution.
Is there any way that would allow me to calculate the volume of those intersections fast?
If I understand your question correctly, you want to calculate the intersection volume between two axis-aligned hyperrectangles.
The first rectangle (your array) is defined by the position of its lower corner (arrayLower, an nD vector) and its size (arraySize, again an nD vector). The second rectangle is defined by its center (p, an nD vector) and an extent of r units in each direction.
For given dimensionality d, this can be done in a very structured way since you only have to multiply the extents in each dimension:
volume = 1
for each d:
lower = max(p[d] - r, arrayLower[d])
upper = min(p[d] + r, arrayLower[d] + arraySize[d])
if(lower > upper)
volume = 0 //no intersection
else
volume *= upper - lower

Index exceeds matrix dimension when applied to an array of values

I wrote the following problem in Matlab to get the first 3 digits of a number.
Let x be a real number.
function [y]=mifl(x) % mifl=my float
s=num2str(x);
y=sscanf(s(1:4),'%f');
end
So function mifl returns the first 3 digits of a number.
For example,
mifl(pi)=3.14
But when I tried to apply this function to all the values of the vector v I got "Index exceeds matrix dimensions". I can't figure out why.
I used
v=linspace(0.1, 99.9, 1000);
w=[]
for i=1:5
w(i)=mifl(v(i))
end
That's when I get the "Index exceeds matrix dimensions".
At the end, what I want is, given a vector
v=linspace(0.1, 99.9, 1000);
to get a vector
w=[mifl(0.1),...mifl(99.9)]
The reason is because you are specifying a number in your function that doesn't have three significant digits. Specifically, try 0.1 from your vector. This doesn't have 3 digits and so you get an out of bounds error because you're assuming it does.
As such, in your function, check the length of the string and ensure that there are 4 characters to extract. If not, then get whatever is available:
function [y]=mifl(x) % mifl=my float
s=num2str(x);
m = min(numel(s), 4); %// Change
y=sscanf(s(1:m),'%f');
end
If you try the above, your code should now work.
I'd like to also suggest that you pre-allocate your arrays before populating them for speed.
Specifically:
v=linspace(0.1, 99.9, 1000);
w=zeros(numel(v),1);
for i=1:numel(v)
w(i)=mifl(v(i));
end
w is initialized to be an array of 0s that is as long as v, then we'll go through each value in v and call mifl, then store this result in the corresponding location in w.
You can use Matlabs rand function.
y = round(x,3,'significant');
This will return the first 3 significant digits of each number in a vector x. This code will also be easy for another person to comprehend since round is a built in Matlab function, which is used for rounding. The argument 'significant' should be clear enough. This will also work for numbers larger than 100, which makes it more general. That is of course if it was 3 significant digits you were after and not the first three digits in the number. In that case this will not work. The number 1001 would then be 1000 and not 100, which your solution would give.

Custom Function with array input printing wrong result in certain cases?

I needed to make a function that takes an array as input (and its dimensions X,Y or ROW,COL) and calculates the sum of all lines (storing each sum in a cell of the newarray.
For an input of NxN array seems to be working perfectly.
For an input of KxN array where K>N seems to be working perfectly.
int* linesum(int *ar,int X,int Y)
{
int i,j,lsum=0;
int *new=malloc(X*sizeof(int));
for(i=0;i<X;i++){
for(j=0;j<Y;j++){
lsum+=*(ar+i*X+j);
}
*(new+i)=lsum;
lsum=0;
}
return new;
}
lsum+=*(ar+i*X+j);
should be
lsum += *(ar+i*Y+j);
or
lsum += *(ar+i+j*X);
The difference between these two is the chosen memory layout. i counts the current row, while j counts the current column. There are now two possible (simple) memory layouts for the matrix (assume X=3 and Y=4 as an example):
0 1 2 3
4 5 6 7
8 9 10 11
or
0 3 6 9
1 4 7 10
2 5 8 11
where numbers are the indexes of the linear array storing the matrix elements. In the first case you get the the next element of a given row by simply adding 1, but you need to jump 4 (the number of columns Y) to get to the next row.
In the second case you need to jump X=3 (the number of rows) to get to the next element in a given row, but if you want to get to the next row, you simply have to add 1.
These two layouts give you the two different pointer arithmetics shown above. You decided the layout when you initialized your array, which you haven't posted, so I cannot know which one is correct in your case.
Note that from a performance viewpoint (if your matrix is very large) the first case is better for your particular access pattern, because the array can be read element by element, while the second layout would require repeatedly jumping Y elements in memory.
You could also use double arrays / pointers to get around such pointer arithmetic. Also I guess it would be good to avoid new as a variable name, even if this is C. If somebody would try to compile your code with a C++ compiler it would throw errors, because new is a reserved keyword there.

How to pick a random element in a 2 dimensional array

Ok I want to pick a random point in the 2d array so it can be filled. Ive seen how to do this for a 1d array, and am wondering how this would be possible in a 2d array. All I have seen about this method is that the same position comes up again, which is a slight problem, but I don't know how to do it in the first place. The 2d array is essentially a grid, with the dimensions being the x and y coordinates. And the random element selecting a point within the boundaries (which is user selected but for the purposes of this problem can be 30x50.
EDIT:
import java.util.Random;
class pickRand{
public static String get (int x, int y){
int rndx = generator.nextInt(x) + 2;
int rndy = generator.nextInt(y) + 2;
}
}
So would this work, the x and y will correspond to the user generated number and have a raised boundary of 2 either side to prevent any objects going (partially outside or of the grid. Nothing needs to be returned right?
If you grid is of size M by N
Generate a random number between 0 and M-1 say i
Generate another random between 0 and N-1 say j
(i,j) will be a random element of the 2d array
What role does the array play here?
Essentially, the task is to pick... random integer 2D coordinates.
So if you want two coordinates, say i in 0...W-1 and j in 0...H-1, just draw two random integers. If you need more for higher dimensionality, draw more randoms.
Obviously, you can then access array[i][j].
In most languages, arrays can however be ragged, i.e. the rows/columns may have different lengths. This is however just as trivial to handle...

How to identify the duplicated number, in an array, with minimum compexity?

There is an array of size 10,000. It store the number 1 to 10,000 in randomly order.
Each number occurs one time only.
Now if any number is removed from that array and any other number is duplicated into array.
How can we identify the which number is duplicated, with minimum complexity?
NOTE : We can not use another array.
The fastest way is an O(N) in-place pigeonhole sort.
Start at the first location of the array, a[0]. Say it has the value 5. You know that 5 belongs at a[4], so swap locations 0 and 4. Now a new value is in a[0]. Swap it to where it needs to go.
Repeat until a[0] == 1, then move on to a[1] and swap until a[1] == 2, etc.
If at any point you end up attempting to swap two identical values, then you have found the duplicate!
Runtime: O(N) with a very low coefficient and early exit. Storage required: zero.
Bonus optimization: count how many swaps have occurred and exit early if n_swaps == array_size. This resulted in a 15% improvement when I implemented a similar algorithm for permuting a sequence.
Compute the sum and the sum of the squares of the elements (you will need 64 bit values for the sum of the squares). From these you can recover which element was modified:
Subtract the expected values for the unmodified array.
If x was removed and y duplicated you get the difference y - x for the sum and y2 - x2 = (y + x) (y - x) for the sum of squares.
From that it is easy to recover x and y.
Edit: Note that this may be faster than pigeonhole sort, because it runs linearly over the array and is thus more cache friendly.
Why not simply using a second array or other data structure like hash table (hash table if you like, depending on the memory/performance tradeoff). This second array would simply store the count of a number in the original array. Now just add a +/- to the access function of the original array and you have your information immediately.
ps when you wrote "we can not use another array" - I assume, you can not change the ORIGINAL data structure. However the use of additional data structures is possible....
Sort the array, then iterate through until you hit two of the same number in a row.

Resources