Random number in array - java

int[] integers = new int[12];
Random r = new Random();
for (int i = 0; i < integers.length; i++) {
integers[i] = r.nextInt((10 - (-10) + 1) + (-10));
}
I'm executing it using online compiler and it throws an error at random.
can anyone help me to solve that problem? I don't know how to write that half of it be negative and half positive. And that random number can't be 0

First of all, to generate a number between -10 and 10, the correct code is :
integers[i] = r.nextInt(21)-10;
r.nextInt(21) will generate numbers between 0 and 20, so subtracting 10 will give you the desired range.
Now, you must validate the random numbers you generated, to make sure you don't generate too many positives or negative, and no zeroes.
int posCount=0;
int negCount=0;
for (int i = 0; i < integers.length; i++) {
integers[i] = r.nextInt(21)-10;
if (integers[i]>0)
posCount++;
else if (integers[i]<0)
negCount--;
if (posCount>6||negCount>6||integers[i]==0)
i--; // redo the current iteration of the loop, since the last generated
// number should be replaced
}
Another alternative, which will run faster, is to generate first 6 positive integers (r.nextInt(10)+1) and then 6 negative integers (-1-r.nextInt(10)), but I'm not sure whether the order of the generated numbers is important (i.e. is it acceptable that all the positives will come before all of the negatives).

1+ r.nextInt(10) gives integers 1-10. For negative integers, just put minus sign to the result of this calculation. Call it six times for positives and six times for negatives. What kind of error you get?

check this :
Random r = new Random();
int[] integers = new int[10];
boolean isEven=false;
int i = 0;
while(true){
int check = r.nextInt(10)*(isEven?-1:1);
if (check != 0){
isEven = !isEven;
integers[i] = check;
System.out.println(integers[i]);
i++;
}
if(i == 10){
break;
}
}

Keeping it simple:
Fill the current index with a random number from (1 to 10);
Fill the next index with a random number from (-1 to -10);
int[] integers = new int[12];
Random r = new Random();
for (int i = 0; i < integers.length; i+=2) {
integers[i] = r.nextInt(10) + 1;
if((i+1)<integers.length){
integers[i+1] = r.nextInt(10) -10;
}
}

Related

eliminating repeated random numbers [duplicate]

This question already has answers here:
How can I prevent the overlapping random numbers
(8 answers)
Closed 2 years ago.
I need to get the numbers 0-11 in a random order and make sure each number is only gotten once. It is still sending same numbers into my Line2 class though. How do I make sure that the int variable lineChoice is completely different every time?
My problem is the if/else is not properly making sure that I don't send an already selected lineChoice to my Line2 class.
for(int i = 0; i < 12; i++){
//get a random line choice 0-11
lineChoice = (int)(Math.random() * 11); //0-11;
//if that number was already chosen
//get a new random number and add it to the array
if(randomNumbers.contains(lineChoice)){
lineChoice = (int)(Math.random() * 11); //0-11;
randomNumbers.add(lineChoice);
}else{
//if not already in array, add to array
randomNumbers.add(lineChoice);
}
//make a Line based on the random lineChoice number
line = new Line2(lineChoice);
//add the line to the string poem
poem += "\n" + line + "\n\n\n";
}
You can create a List of Int from 1 to 11, and then randomize it.
List<Integer> ints = IntStream.range(1,12).boxed().collect(Collectors.toList());
Collections.shuffle(ints);
System.out.println(ints);
Here is the recommended way of doing it.
int [] nums = {0,1,2,3,4,5,6,7,8,9,10,11};
for (int i = nums.length-1; i >= 0; i--) {
int s = (int)(Math.random()*(i+1));
System.out.println(nums[s]); // here is where you get your number
nums[s] = nums[i];
}
or if you just want to shuffle the array.
for (int i = nums.length-1; i >= 0; i--) {
int s = (int)(Math.random()*(i+1));
int t = nums[s];
nums[s] = nums[i];
nums[i] = t;
}
You need an array to do so,
Follow the following code, you just need to generate 11 (out of 12) random numbers in total. The last number will be selected automatically.
int[] rn = new int[12];
for(int i=0; i<12; i++) rn[i]=i; // 0 to 11
Random rNumber = new Random();
int t, z;
for(int i=11; i>0; i--) {
z = rNumber.nextInt(i+1);
t = rn[i];
rn[i] = rn[z];
rn[z] = t;
}
System.out.println(Arrays.toString(rn));

Can someone explain me this code? About user input, scanner etc

Can someone explain to me how this code works?
It lets the user input numbers up until 1000, then it prints the original inputted numbers, the even and the odd, all in a separate array. But I just don't understand the parts where there is gem++ and gem1++ when it outputs the even and odd not the number of the even and odd numbers.
And after putting this
double even[] = new double[gem];
double odd[] = new double [gem1];
why does it need to repeat gem=0 and gem1=0 again? I'm so sorry if I ask too many question, I'm just confused, I just learned java last week.
public class wutt {
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
System.out.print("Enter no. of elements you want in array : ");
int n = s.nextInt();
if (1 <= n && n <= 1000) {
double a[] = new double[n];
int gem = 0, gem1 = 0;
System.out.println("Enter all the elements : ");
for (int i = 0; i < n; i++) {
a[i] = s.nextInt();
if (a[i] % 2 == 0)
gem++;
else
gem1++;
}
double even[] = new double[gem];
double odd[] = new double[gem1];
gem = 0;
gem1 = 0;
for (int i = 0; i < a.length; i++) {
if (a[i] % 2 == 0) {
even[gem] = a[i];
gem++;
} else {
odd[gem1] = a[i];
gem1++;
}
}
System.out.println("Original: " + Arrays.toString(a));
System.out.println("Odd: " + Arrays.toString(odd));
System.out.println("Even: " + Arrays.toString(even));
} else
System.out.print("Invalid input");
}
}
If you want the program stops after the user enters a number greater than 1000 o less than 0 you need to add the break statement in your if condition.
if (size < 0 || size > 1000) {
System.out.println("Size must be between 0 and 1000");
break;
}
the code before double even[] = new double[gem];
double odd[] = new double [gem1]; is trying to get the number of odds occurred and the number of even occurred and put all inputted elements in array a.
after all that ,now what we got is a array of numbers called a containing all the inputted elements. and two numbers called gem and gem1, which contains the number of odds occurred and the number of even occurred.
so
we get gem(numberOfEvens), gem1(numberOfOdds) and list a
next, we need to put all odds from a to a new array called odd[] with size gem1, and
put all evens from a to a new array called even[] with size gem. at this point, the duty of variable gem1 and gem is done. they become useless.
now we need to go through the list and pick the odd and even out and put them in the array one by one in a sequential way. that's why we need two new variables with 0 initialized.
in this case, because gem and gem1 are useless aready, they are reassigned to help manipulate the tree arrays a , odd[] and even[]
So the user inputs the number of elements he/she wants in the array (n)
double a[] = new double[n]; // a is the array that is initialised to accommodate n elements
int gem = 0, gem1 = 0; // gem is the counter for "even" numbers and "gem1" the counter for odd numbers, and like every good counter, they start at 0
System.out.println("Enter all the elements : ");
for (int i = 0; i < n; i++) { // so we ask the user to input n elements
a[i] = s.nextInt(); // here we read every input and put it in the a array
if (a[i] % 2 == 0) // if the new number is even
gem++; // we increase the even counter "gem"
else // otherwise, when it is an odd number
gem1++; // we increase the odd counter
}
double even[] = new double[gem]; // now we create a new array where we want to hold all the even numbers, we do that by telling it how many even numbers we have counted before (gem)
double odd[] = new double[gem1]; // and a new array for all odd numbers (gem1 was our counter)
gem = 0; // now we reinitialise the counters, because we want to start from the beginning
gem1 = 0;
for (int i = 0; i < a.length; i++) { // in order to copy all numbers from the a array into the two other arrays for even and odd numbers, we iterate over the whole length of the a array. i is the index for the "a" array
if (a[i] % 2 == 0) { // ever even number we encounter
even[gem] = a[i]; // we put in the even array
gem++; // while gem, the "even numbers counter" is our index for the "even" array
} else {
odd[gem1] = a[i]; // odd numbers are for the odd array
gem1++; // while the former "odd numbers counter" now serves as our "odd" array index
}
}
and that's pretty much it. First the user inputs all numbers in a single array and simply counts how many odd and how many even numbers where inputted,
then two new arrays are created, one for the even and one for the odd numbers and since we counted them, we know how big these two new arrays have to be.
And finally all numbers are again iterated over and put in their according array.
At the end you have 3 array, one that holds all numbers, one that holds the even numbers and one with only the odd numbers.
EDIT
here are a few minor changes you could make without changing the nature of that method:
double allNumbers[] = new double[n]; // "allNumbers" is way more specific than "a"
int oddCounter = 0; // "oddCounter" instead of "gem"
int evenCounter = 0; // numbers in variables like "gem1" is really bad practice, because numbers don't say anything about the nature of the variable
System.out.println("Enter all the elements : ");
for (int i = 0; i < n; i++) {
allNumbers[i] = s.nextInt();
if (allNumbers[i] % 2 == 0) {
evenCounter++;
} else {
oddCounter++;
}
}
// until here nothing changes but the names
double even[] = new double[evenCounter];
double odd[] = new double[oddCounter];
int oddIndex = 0; // and here we create new variables, instead of reusing old ones
int evenIndex = 0; // there is absolutely no performance gain in reusing primitives like this - it's just confusing
for (int i = 0; i < allNumbers.length; i++) {
if (allNumbers[i] % 2 == 0) {
even[evenIndex++] = allNumbers[i]; // the "++" can be done directly in the first expression. that's just to make it shorter.
} else {
odd[oddIndex++] = allNumbers[i]; // it is not more performant nor easier to read - just shorter
}
}
EDIT (again)
This is how the arrays look like, say when you enter 4 numbers:
gem = 0
gem1 = 0
n = 4 // user said 4
a = [ , , , ] // array a is empty but holds the space for 4 numbers
a = [1, , , ] // user enters 1
^
i=0
gem1 = 1 // 1 is an odd number -> gem1++
a = [1,4, , ] // user entered "4"
^
i=1
gem = 1 // 4 is an even number -> gem++
a = [1,4,2, ] // user entered "2"
^
i=2
gem = 2 // 24 is an even number -> gem++
a = [1,4,2,7] // user entered "7"
^
i=3
gem1 = 2 // 7 is an odd number -> gem1++
then we fill the other arrays
even = [ , ] // gem is 2, so we have 2 even numbers
odd = [ , ] // gem1 is 2, so we have 2 odd numbers
a = [1,4,2,7]
^
i=0
odd[1, ] // for i=0, a[i] is 1, which is an odd number
a = [1,4,2,7]
^
i=1
even = [4, ] // for i=1, a[i] is 4, which is an even number
a = [1,4,2,7]
^
i=2
even = [4,2] // for i=2, a[i] is 2, which is an even number
a = [1,4,2,7]
^
i=3
odd = [1,7] // for i=3, a[i] is 7, which is an odd number
and in the end you have
a = [1,4,2,7]
even = [4,2]
odd = [1,7]

Generating 1000 random numbers between 13 and 100

I'm trying to generate 1000 random numbers between 13 and 100. So far it's only generating 75% of what I want repeatedly a thousand times. Here's what I have so far:
Random rand = new Random();
for (int j = 0; j < 1000; j++)
{
int pick = rand.nextInt((87) + 13);
pick++;
}
Why isn't it working?
Pay attention to nextInt() covering the 0 inclusively and the specified value exclusively! So it has to be rand.nextInt(88) to make the highest int generated be 87. Here is what you want:
Random rand = new Random();
for (int j = 0; j<1000; j++)
{
int pick = rand.nextInt(88)+13;
}
rand.nextInt(88) + 13; should give you numbers between 13 and 100, and you just put it in your loop.
The line :
So far its only generating 75% of what i want repeatedly a thousand times
Really doesn't add up to me. It might be a seeding issue you're having though. Make sure to always re-seed the random number, using time.
But I agree with Abdul , you need to take the +13 out of that parenthesis:
rand.nextInt(87) + 13;
Because rand.nextInt((87) + 13) is the same as rand.nextInt((67) + 23) as rand.nextInt((1) + 99)
But if you want more "true" randomness, look into something called buzzhash (though that is for hashing ; yet may be modded for number)
I use this in my codes:
public static int randomInteger(int min, int max)
{
java.security.SecureRandom rand = new java.security.SecureRandom();
//get bounded [0, max) from nextInt()
int randomNum = rand.nextInt(max) + min;
return randomNum;
}
value = randomInteger(13,100); //13..99
value = randomInteger(13,101); //13..100

Bug in random numbers in Android

TreeSet myNumbers = new TreeSet();
Random randGen = new Random();
for (int i = 1; i <= 16; i++) {
// number generation here
int randNum = randGen.nextInt(16 - 1) + 1;
for (;;) {
if (myNumbers.add(randNum))
break;
else
randNum = randGen.nextInt();
}
Toast.makeText(getApplicationContext(), "" + randNum, 100).show();
}
I want to generate random numbers between 1 and 16 and the same number should not be repeated.
The code above gives me output like:
2, 5, 7, 9, 1, 4, 10.4109446, -448831, 98824724, 11, 13, ...
I do not know why it gives me random numbers not in the 1-16 range, please help me out.
You're only generating one number in the range 1-15. You're then generating subsequent numbers with just nextInt:
if (myNumbers.add(randNum))
break;
else
randNum = randGen.nextInt();
That should be:
if (myNumbers.add(randNum))
break;
else
randNum = randGen.nextInt(16) + 1;
... and fix the initial call to nextInt to remove the "-1". (You don't need the 16 - 1, as explained in Josh's answer.)
To generate a random number in a range, it is like:
int min = ...
int max = ...
int randNumber = min + new Random().nextInt(max - min + 1);
So in your example where you want to generate a random number from [1, 16], it would look like:
int randNumber = 1 + new Random().nextInt(16 - 1 + 1);
Or if you choose to simplify:
int randNumber = 1 + new Random().nextInt(16);
Also, you should really be using a while loop instead of an infinite for loop:
final TreeSet<Integer> myNumbers = new TreeSet<>();
final Random rand = new Random();
for(int i = 0; i < 16; i++){
int n = 1 + rand.nextInt(16);
while(!myNumbers.add(n))
n = 1 + rand.nextInt(16);
}
It's not a big issue, if you are working in the range 1-16, but your code results in rejection of some randomly drawn numbers, if they have already been picked before.
In your solution, the expected value of nextInt() calls is proportional to n log(n), where n is the number of total elements you want to shuffle (16 in your case) – and the actual values can be much higher for a single run. You might consider using a more efficient implementation.
A solution which always uses only n calls:
ArrayList<Integer> originalNumbers = new ArrayList<Integer>();
Random randGen = new Random();
int max = 16;
for (int i = 1; i <= max; i++) {
// initializing ordered list so it becomes 1, 2, ..., max
originalNumbers.add(i);
}
for (int i = max; i >= 1; i--) {
// picking a random number from the ordered list, and swapping it
// with the last unpicked element which is placed closer to the
// end of list, where the already picked numbers are stored
int randNum = randGen.nextInt(i);
Collections.swap(originalNumbers, i - 1, randNum);
Toast.makeText(getApplicationContext(), "" + originalNumbers[i - 1], 100).show();
}

I'm getting strange output from java program

I've some strange situation here and i thought that you may help me. I have an int array populated with numbers from 1 to 10. I want to generate random number from this array and save it to another int array. I used class Random to pick any number and since random throws 0 also i modify it like that ( so it throws numbers from 1 to 10 )
randNum = rand.nextInt(numbers.length-min+1)+min;
Following code makes sure that if it generates same random number, it skips it. Program is actually working and i'm getting in another array randomly positioned numbers from 1 to 10. That's what i wanted. But sometimes i'm missing one number from 1 - 10 AND iam Getting ZERO instead. Why??
int[] numbers = {1,2,3,4,5,6,7,8,9,10};
int[] usednum = new int[10];
Random rand = new Random();
int randNum;
int min = 1;
for (int x = 0; x<numbers.length; x++) {
for (int i = 0; i<usednum.length; i++) {
randNum = rand.nextInt(numbers.length-min+1) + min;
for (int f = 0; f<usednum.length; f++) {
if (usednum[f] == randNum) {
break;
} else if (usednum[f] == 0) {
usednum[x] = randNum;
}
}
}
}
for (int c = 0; c<usednum.length; c++) {
System.out.println(usednum[c]);
}
You're inner-most for loop only checks if the current random number is in the usednum[] array. And the for loop immediately outer of that only checks 10 times total. It gives up too quickly because it only tries 10 random numbers. If all 10 are already used, nothing will get stored in that slot of usednum[] (thus it will be 0), try adding a while loop around that and get rid of the extraneous outer-most for loop:
for(int i = 0; i<usednum.length; i++) {
while(usednum[i]==0) {
randNum = rand.nextInt(numbers.length-min+1)+min;
for(int f = 0; f<usednum.length; f++) {
if(usednum[f] == randNum) {
break;
} //if
else if (usednum[f] == 0) {
usednum[i] = randNum;
}
}
}
}
Also note that the assignment is for usednum[i] = randNum;.
This is essentially replacing the middle for loop (the one that goes from i=0 to 9) with the while loop.
If your goal is simply to shuffle an array of numbers, try this instead:
Integer[] numbers = {1,2,3,4,5,6,7,8,9,10};
Collections.shuffle(Arrays.asList(numbers));
It will have the same effect. Unless you are completing a homework assignment that forces you to solve the issue in a more manual fashion, just make use of the standard Java libraries.
The shuffle method writes changes through to the underlying Integer array, thanks to the special type of List returned by Arrays.asList(...). Note you have to use an array of Integer not int (see Why does Collections.shuffle() fail for my array?).
You are generating used numbers through an entire pass, so it doesn't generate a zero is just fails to generate a value it should.
you have one for loop too much.
remove the loop with the i iterator and the program should do what you want.
Oh and remove the -min+1 from the random generator, -1+1=0
Your array usednum is consisted of zeros at the beginning. In some cases, your program doesn't change that initial value, but breaks before at the line:
if(usednum[f] == randNum)
and does that during all iterations with same value x. X increments and there goes your chance to change the zero value.
Edit - followed it and re-wrote it:
List<Integer> numbers = new LinkedList<Integer>(Arrays.asList(new Integer[]{ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 }));
int[] usednum = new int[10];
Random rand = new Random();
int n = numbers.size();
for (int i = 0; i < n; i++) {
int randNum = rand.nextInt(numbers.size());
usednum[i]=numbers.get(randNum);
numbers.remove(randNum);
}
for (int c:usednum) {
System.out.println(c);
}
Actually, you are never using the content of the array numbers. Try changing the array to something like int[] numbers = { 10, 22, 23, 42, 53, 18, 7, 8, 93, 10 };. You will get similar output.
Jon Lin's answer describe why your code is not working but does not address this issue. I think you will want to change your code to something like:
int[] numbers = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
int[] usednum = new int[10];
Random rand = new Random();
int selectedCount = 0;
while (selectedCount < numbers.length) {
int randNum = numbers[rand.nextInt(numbers.length)];
boolean contains = false;
for (int x = 0; x < selectedCount; x++) {
if (usednum[x] == randNum) {
contains = true;
break;
}
}
if (!contains) {
usednum[selectedCount] = randNum;
selectedCount++;
}
}
for (int c = 0; c < usednum.length; c++) {
System.out.println(usednum[c]);
}

Categories

Resources