I am trying to figure out how to randomly assign two separate ints as variables. How to choose between them randomly makes sense (r.nextInt(02)), but I can not seem to find anything on how to assign one versus the other. I'm also trying to assign a third variable based on the sum of the first two, which I think I understand int c = (int a + b). But how do you set the third randomly each time? So that it could either be A, B or C?
Working on a game idea but I'm also constrained by the requirements that I've been given by one of the guys that I'm working under (who isn't available).
Try adding the 3 int A, B, C to an array and randomly selecting an index.
int[] numbers = new int[3];
numbers[0] = a;
numbers[1] = b;
numbers[2] = c;
int index = rand.nextInt(3);
int yourNumber = numbers[index];
Related
in java if we have:
int[][] x = new int[3][3];
the memory address of x is different from the memory address of x[0]. As x[0] gives the memory address of the first column. So the memory address of x[0][0] is different than the memory address of x[0].
are there any computer languages that store a 2d array as a matrix and not as an array of arrays?
would the address of x always be different from x[0] and the address of x[0] equal x[0][0]?
are there any computer languages that store a 2d array as a matrix and
not as an array of arrays?
Yes. Or, at least, there used to be.
There is the possibility of using an assembler language, where the programmer has extreme control over how arrays might be handled. But, let's assume the question is about high-level languages (>=3GL).
I don't know about modern version of Fortran, but the early versions of FORTRAN stored any array, including multi-dimensional arrays, in consecutive storage locations. So, for example, if you declared an array as INTEGER FOO (3,4,5), then FOO and FOO (1,1,1) would have the same memory address. FOO would occupy a block of 60 INTEGER sized locations. The compiler generates code to find, from the subscript values, the location of an element in a manner similar to what #Jesse described in a comment on the question. It's slightly different to allow for the fact that FORTRAN subscripts started at one instead of zero.
By the way, FORTRAN subscript are in opposite order of most other languages. In Java, C, C++, and COBOL, the major subscripts are to the left. In FORTRAN, they were to the right.
FORTRAN syntax didn't allow missing subscripts. So, continuing the example, something like FOO (2,3) would generate a compiler error.
Now, suppose there was the following method:
REAL FUNCTION MEAN (ARR, N)
INTEGER N, ARR (N)
REAL SUM
DO 400 I = 1,N,1
SUM = SUM + ARR (I)
400 CONTINUE
RETURN SUM / N
END
A programmer could it use to calculate the mean of the entire FOO array, or any part of it:
REAL ALLMEAN, LEVEL3MEAN, ROWMEAN
ALLMEAN = MEAN (FOO(1,1,1), 60)
LEVEL3MEAN = MEAN (FOO(1,1,3), 12)
ROWMEAN = MEAN (FOO(1,2,3), 4)
Suppose, for some strange reason, there was this:
AVGPART = MEAN (FOO (2,3,2), 20)
This would use 20 consecutive elements of FOO, even if those elements were in different rows or levels.
When I took a C++ course, someone didn't like having to type separate [x] subscripts for multidimensional arrays. Instead of foo [2][1][0], he would rather type something like foo.get (2,1,0), so wrote a convenience wrapper class for an array. Such code might still have foo [t][r][c] inside the wrapper class. Or, it could allocate a 1D array. Once the class was created, it allowed him to specify subscripts as arguments in a call to a method.
Code in Java to do that, using the 1D array option, might look like this:
public class Block {
// class for regular 3D Array
private int [] array;
private int rows, int columns, int levels;
public Block (int t, int r, int c) {
rows = r;
columns = c;
levels = t;
array = new array [ t * r * c];
}
public int get (int t, int r, int c) {
return array [ t * rows * columns + r * columns + c ];
}
public void set (int value, int t, int r, int c) {
array [ t * rows * columns + r * columns + c ] = value;
}
...
}
I looked up the solution to this problem yesterday and tried to solve on my own today but found myself trying to solve this problem in a different way. I feel I may be overcomplicating the problem but I still want an answer to my possible solution just because it is bugging me to know (I am sure everyone has experienced this at some point or another). Anyway here is the problem:
https://www.hackerrank.com/challenges/ctci-array-left-rotation/problem?h_l=interview&playlist_slugs%5B%5D=interview-preparation-kit&playlist_slugs%5B%5D=arrays
My idea is that you would first check to see if your array length was equal to the rotations you want then you would simply return the original. There is no work needed to be done.
My next idea would be to check to see if our rotations is greater than our array length. If this is the case, we can either do rotations - array length or ABS VALUE(array length - rotations), which gives us the same result. We can reassign this value to D.
Next, we can create a case to rotate right instead of left. When your rotation is greater than your array length / 2, then we would not to rotate left since we are doing extra work. We instead would want to rotate right. For example:
Array Length 4
Rotations 3 (LEFT)
We can simply rotate right once instead of rotating left 3 times. We could set the rotateRight boolean to true (otherwise set to false which indicated to rotateLeft as normal)
Anyway this is the part I get caught on. I am unsure of how to rotate my elements here. I was thinking of returning a new array. How can I get the correct values for my new array? I am facing issues with IndexOutOfBounds exceptions. Can I also use try catches in this example or is it overkill?
Here is the code I have currently it should match my thoughts from up above:
static int[] rotLeft(int[] a, int d) {
int aLength = a.length;
int counter = 0;
int[] newArray = new int[aLength];
boolean rotateRight = false;
if (aLength == d) {
return a;
}
if (a.length - d < 0) {
d = Math.abs(a.length - d);
}
if(d > a.length/2) {
rotateRight = true;
}
return newArray;
}
If you need any more info let me know.
There is little benefit to trying to simplify the maths, if it leads to a harder-to-write program -- especially since you do not want to rotate the array at all, and can simply place the correct values in the correct places directly.
If the old position of element i was i, after d left-rotations of an array of size len, its new position will be (i-d)%len. If d == len+1 this is indeed equivalent to (i+1)%len -- easier for humans, but computers calculate either expression just as happily.
So the suggested code is:
static int[] rotLeft(int[] a, int d) {
int[] b = new int[a.length];
for (int s=d, t=0; t<a.length; s++, t++) {
// t is target position; s is source position
b[t] = a[s%a.length];
}
return b;
}
Note: code is untested
I'm trying to put a certain amount of integers into an array in random spots without putting them in the same place.
My combine method concatenates two given integers and returns the Int.
Places is an arrayList to keep the locations of the integers already put into the array.
The random method returns a random integer in between the two given ints.
The combine method works and so does the random method, but I'm not sure why it isn't working.
public void fillOne(int b)
{
for(int x = 0; x < b; x++)
{
int kachow = random(0, 5);
int kachigga = random(0, 5);
int skrrt = combine(kachow, kachigga);
if(notInArray(skrrt))
{
locations[kachow][kachigga] = 1;
places.add(skrrt);
}
}
}
You haven't really explained what isn't working. But an obvious flaw in your algorithm is that it isn't guaranteed to set b elements to 1. If your algorithm generates a duplicate position then it will set fewer than b elements.
Your logic for storing the combined positions is overly complex. One solution would be to reverse the logic: generate a single integer representing both dimensions then divide it into two when you are setting the location. That makes the checks a lot simpler.
For example, if your array is 5x5:
Set<Integer> positions = new HashSet<>();
while (positions.size() < n)
positions.add(random.nextInt(25));
for (int p: positions)
locations[p/5][p%5] = 1;
Because positions is a set it automatically excludes duplicates which means the code will keep adding random positions until their are n distinct positions in the set.
Even simpler, if you are using Java 8:
random.ints(0, 25)
.distinct().limit(n)
.forEach(p -> locations[p/5][p%5] = 1);
I've come across this piece of code in a program I'm editing for an assignment:
double[] colour = new double [3];
colour[0] = 255; colour[1] = 0; colour[2] = 0;
I think it means that the value colour is a double which is made by combining three other values. Is there anything more that needs to be said about this? I mean, is that why the double has the [] brackets directly after it - to specify that it needs to take more than one value? I'm slightly confused by this...
The [] means that you have an array of doubles. Arrays let you have multiple things in a sort of list, so you can have three numbers: [255, 0, 0]
More info is available in the Java array documentation: http://docs.oracle.com/javase/tutorial/java/nutsandbolts/arrays.html
The [] indicates you are creating an "array of double". This is primitive array which means the size is fixed. In your case an array of size 3 is being allocated.
An alternate method would be to use the List interface:
List<Double> colour = new ArrayList<Double>(3);
colour.add(255);
colour.add(0);
colour.add(0);
For this example you could also have a class:
public class Colour {
double r;
double g;
double b;
public Colour(double r, double g, double b) {
this.r = r;
this.g = g;
this.b = b;
}
....
}
A double[] is an array of double values.
In your particular case, colour is an array of size 3 (as specified on the right hand side of the assignment), and so you will access the three components using colour[0], colour[1] and colour[2] respectively.
In Java the [] after a type denote Array data structures.
In your case, you are creating an array of 3 double values.
Please refer to this Oracle tutorial for more information regarding the matter.
The line:
double[] colour = new double [3];
say: length colour[] = 3, datatype double,
and:
colour[0] = 255; colour[1] = 0; colour[2] = 0;
asign to colour the values [255, 0, 0]
PD: I can't comment sorry.
Keeping in mind that [] denotes array, which can be thought of as a collection of objects (in this case, numbers of the double data type), you can think of it in layman's terms like this:
The double[] colour part of the statement kind of says "I am going to have this collection called colour and it's going to be a type of double number, but I don't know what values or how many it's going to have." Emphasis on the word collection, since that's what an array is.
The new double [3] part says "I am creating 3 new doubles". Since you never said what the 3 doubles are, you begin to state them:
"The first one is 255, the second one is 0, and the third one is 0.", which in the code looks like this now:
colour[0] = 255; colour[1] = 0; colour[2] = 0
And I'm sure you might already know, but in computers, the numbers start counting up from 0 instead of 1.
[0] [1] [2]
First Element Second Element Third Element
Another example that helped me better understand arrays when I first started programming was thinking of a box of Oreos that has different flavors inside. The box is an array, the type of cookie is Oreos, the order in which they sit in the box represents their position (a.k.a. it's index), and the values are the flavor.
I have two integers, let them be
int a = 35:
int b = 70;
I want to pick one of them randomly at runtime and assign to another variable. I.e.
int c = a or b:
One of the ways that come into my mind is to create an array with these two integers and find a random integer between 0 and 1 and use it as the index of the array to get the number..
Or randomize boolean and use it in if-else.
My question is that is there a better and more efficient way to achieve this? I.e. pick a number from two previously defined integers?
Is there a specific reason you are asking for a more efficient solution? Unless this functionality sits in a very tight inner loop somewhere (e.g. in a ray tracer), you might be trying to prematurely optimize your code.
If you would like to avoid the array, and if you don't like the "bloat" of an if-statement, you can use the ternary choice operator to pick between the two:
int a = 35;
int b = 70;
int c = random.nextBoolean() ? a : b;
where random is an instance of java.util.Random. You can store this instance as a final static field in your class to reuse it.
If you don't require true randomness, but just want to switch between the two numbers in each invocation of the given block of code, you can get away with just storing a boolean and toggling it:
...
int c = toggle ? a : b;
toggle = !toggle;
Since I can't comment on other answers, I'd like to point out an issue with some of the other answers that suggest generating a random integer in a bigger range and making a decision based on whether the result is odd or even, or if it's lower or greater than the middle value. This is in effect the exact same thing as generating a random integer between 0 and 1, except overly complicated. The nextInt(n) method uses the modulo operator on a randomly generated integer between -2^31 and (2^31)-1, which is essentially what you will be doing in the end anyway, just with n = 2.
If you are using the standard library methods like Collections.shuffle(), you will again be overcomplicating things, because the standard library uses the random number generator of the standard library.
Note that all of the suggestions (so far) are less efficient than my simple nextBoolean() suggestion, because they require unnecessary method calls and arithmetic.
Another way to do this is, store the numbers into a list, shuffle, and take the first element.
ArrayList<Integer> numbers=new ArrayList<Integer>();
numbers.add(35);
numbers.add(70);
Collections.shuffle(numbers);
numbers.get(0);
In my opinion, main problem here is entropy for two numbers rather than making use of that entropy. Indexed array or boolean are essentially the same thing. What else you can do (and, hopefully, it will be more random) is to make Java give you a random number between limits say 0 to 100. Now, if the chosen random number is odd, you pick int c = a. Pick b otherwise. I could be wrong, but picking random between 0 to 100 seems more random as compared to picking random between two numbers.
You can simply use secure random generator(java.security.SecureRandom ).
try {
r = SecureRandom.getInstance("SHA1PRNG");
boolean b1 = r.nextBoolean();
if (b1) {
c = a;
} else {
c = b;
}
} catch (NoSuchAlgorithmException nsae) {
// Process the exception in some way or the other
}
Refer this link for more information
Randomize an integer between 1 and 10, if it's more than 5 then take the value of b other wise go with a. As far as I know there are no other ways to select from integers.
int a=1;
int b=2;
int get = new Random().nextBoolean()? a : b;