how to prevent duplicate random ints [duplicate] - java

This question already has answers here:
Generating Unique Random Numbers in Java
(21 answers)
Closed 6 years ago.
for (int x = 0 ; x < chosenQ.length ; x++)
{
chosenQ [x] = r.nextInt (9);
c.println (chosenQ [x]);
}
This generates 5 ints between 0 and 9. How do i make it so it will not have duplicate ints when generating it?

Create an array with 10 elements from 0 to 9
Shuffle the array
Take the first five elements
In pseudo code
array = [0, 1, ..., 9]
array.shuffle.take(5)

You'll have to keep a record of which numbers were chosen already.
One way you can do that is by storing the values in a boolean array where all values are initialized to false. When a random value is generated, the element at that index is set to true. Then, for each generated number, you can simply check if the element at that index is true or false.
For example,
// array of booleans initialized to false
boolean[] array = new boolean[chosenQ.length];
for (int x = 0 ; x < chosenQ.length ; x++)
{
int i = r.nextInt(9);
// check if value was chosen already
while (array[i] == true)
i = r.nextInt(9);
// set generated value's index in array to true
array[i] = true;
chosenQ[x] = i;
c.println(chosenQ[x]);
}

Related

Why do my loops stop early when iterating through and array

So I am trying to iterate through a 4 by 3 array of objects and set the value of each object according to user input, but I've run into a problem where the iteration through the array stop at 6 instead of the total 12. I've tried a few way of writing the iterators but they always fail. This is the code.
Card[][] field = new Card[3][2];
void setvals(){
Scanner scanner = new Scanner(System.in);
for(int row= 0; row < field.length; row++){
for(int col = 0; col < field[row].length; col++) {
String input = scanner.nextLine();
field[row][col] = new Card();
field[row][col].makeCard(input);
}
}
}
I have also tried <= instead of < but then it gives me array index out of bounds. I have no clue what the problem is.
Your problem is with the array:
Card[][] field = new Card[3][2];
You want the array to be 4 x 3, then set the dimensions as so:
Card[][] field = new Card[4][3];
The reason your code is not working, is since you currently have a 2 x 3 array, evaluating to 6 iterations. A 4 x 3 array would evaluate to 12 iterations, as you want.
You say:
So I am trying to iterate through a 4 by 3 array of objects...
And here is your array: Card[][] field = new Card[3][2];.
That is not a 4x3 array. It is a 3x2 array, which means there should be 6 iterations in your loop, which is what is happening. There is no error here.

How to check index of integer array element in java? [duplicate]

This question already has answers here:
How to find the index of an element in an array in Java?
(15 answers)
Closed 6 years ago.
In the below code I can get the length and element of array. if I have to check what is the index number at run time for every element, how can I check that?
If I print the value of i from loop every time with the array element it will give the same value, will that be correct to consider the value of i as index value of array?
Another confusion in during the debug in eclipse it shows id value of array is different than the loop value.
public class FirstArray {
public static void main(String[] args) {
int[] arr = {11,12,13,14,15,16,17,18,19,20};
int onelength = arr.length;
System.out.println("Size of Array is: " + onelength);
for(int i = 0; i < arr.length; i++){
System.out.println("element of aray is: "+ arr[i]);
}
}
}
Yes, value of i will be the index value. I would suggest you to go through basics of Java arrays.
The question itself is not clear. The loop bounds are definitely different from the index value of the array. If you want to print the loop bounds along with the value at the index, just print i in the loop.
For your question "what is the index number at run time for every element, how can i check that?" Refer to the solution bellow:
Where is Java's Array indexOf?
For your question "If i print the value of i from loop every time with the array element it will give the same value, will that be correct to consider the value of i as index value of array?"
The array index starts from 0, so if your array length is 10 then index values will be 0 to 9. Thus, if you start your loop from i=0 then the index value will be same as i, but if you start your loop from i=1 then the index value will be i-1.
Will that be correct to consider the value of i as index value of
array?
Of course it'll be correct, i is actually the index of the array.
Another confusion in during the debug in eclipse it shows id value of
array is different than the loop value
Yes, it shows because it's really different, take a look:
for(int i = 0; i < arr.length; i++) {
System.out.println("element of aray is "+ arr[i]); // It prints the element itself -> 11 12 13 14 15.. and so on
System.out.println("iteration number "+ i); // It prints the index of iteration -> 0 1 2 3 4 5.. and so on
}
You may want to clarify what exactly you are searching for.
An array stores a value at a given index (starting at index zero, and going up to index length-of-the-array-minus-one).
The traditional way of creating an array is the following:
// Create an empty array that is able to hold 3 values
int[] numbers = new int[3];
numbers[0] = 11;
numbers[1] = 15;
numbers[2] = 13;
If we now print the values in the index order, we receive 11, 15 and 13. Here's the code:
for (int i = 0; i < numbers.length; i++) {
System.out.println(numbers[i]);
}
So, we see with numbers[i] = 14 we can assign the value 14 to the index i of the array. And with System.out.println(numbers[i]), we can print the value the array has stored at index i.
An array has a fixed length which needs to be specified at creation, it is not a flexible data structure (but pretty fast and small). Thus, if you are trying to access numbers[100] but we said numbers can only hold 3 values, then you will get an ArrayIndexOutOfBoundsException.
Your provided code is a short-hand for the traditional way:
int[] arr = {11,12,13};
which does the same as
int[] arr = new int[3];
arr[0] = 11;
arr[1] = 12;
arr[2] = 13;
If you want to search for the index, given the value (assuming the values are unique), you need to search the whole array until you find the index. Here's some code:
public int getIndex(final int[] array, final int value) {
for (int i = 0; i < array.length; i++) {
if (array[i] == value) {
// Value found
return i;
}
}
// Value not found
return -1;
}
Note that the search code is pretty slow, because you may need to search the whole length of the array (worst case). Other data structures may be more useful depending on your usage.

Java Copying Data from Array Rather than Reference

In the following code, I am trying to duplicate the 2d array 'cur,' swapping two values in the array, and eventually add it to an arraylist I will be using later in the program. My problem is, every time I switch these values in the array 'temp' (has the cloned values of 'cur') it also switches the values in the array 'cur.' I'm confused because I have tried clone(), Arrays.copyof, even made a new constructor for the PuzzleNode class that takes the values from cur, yet every time 'cur' doesn't reset to its original value when the iteration of the loop finishes. Any help is much appreciated.
Here's the code:
//generate the puzzles and swap the tiles
for (int i = 0; i < possibleSwaps.size(); i++) {
//stores the 2d array of Nodes
PuzzleNode temp = new PuzzleNode();
//instantiate the 2d array and populate it with values of cur
temp.puzzle = new Node[cur.puzzle.length][cur.puzzle[0].length];
for (int j = 0; j < cur.puzzle.length; j++) {
temp.puzzle[j] = cur.puzzle[j].clone();
}
for (int j = 0; j < cur.puzzle.length; j++) {
for (int k = 0; k < cur.puzzle[0].length; k++) {
if (temp.puzzle[j][k].value == possibleSwaps.get(i).value) {
//switch the values, values should always be distinct
int prev = temp.puzzle[zeroNode.x][zeroNode.y].value;
temp.puzzle[zeroNode.x][zeroNode.y].value = possibleSwaps.get(i).value;
temp.puzzle[possibleSwaps.get(i).x][possibleSwaps.get(i).y].value = prev;
}
}
}
//prints out the 2d array that should be the same everytime. But isn't
printPuzzle(cur.puzzle);
}
Example of Print Out:
(Original 2d array I want to always have)
1 2 3
4 6 8
7 [] 5
(Switched the [] and the 6, I NEED the [] to remain where it originally was in the previous iteration, so it can be swapped with the 5 and 7 in the next iterations)
1 2 3
4 [] 8
7 6 5
(Stays where it was swapped in the previous iteration)
1 2 3
4 [] 8
7 5 6
1 2 3
4 [] 8
5 7 6

Testing elements in an array

Hello I have searched for a simple way to check ,
if any number of elements up to 6 in the array add up to seven. I have yet to find one my array is this,
private int[] diceRoll = new int[6];
The question is a bit vague, however, here's my attempt at an answer:
If what you're trying to do is take two indices x and y in diceRoll[] and see if they add up to 7, the simplest thing to do is
if(diceRoll[x] + diceRoll[y] ==7){
return true;}
If you're trying to see if ANY item with any other item adds up to 7, use a double for-loop (these are weird, but very helpful)
for(int i = 0; i < diceRoll.length; i++){
for(int j = 0; i < diceRoll.length; i++){
if(diceRoll[i] + diceRoll[j] != 7){
return false;
}
}
}
Hope this helps!
-katie
It sounds like what you need to do is take every subset of the diceRoll array and see which ones add up to 7. This is how it can be done.
Assuming you know that 1 & 1 = 1, and that 1 & 0 = 0, imagine each element of the array having a number in 0 0 0 0 0, if the element is selected, say element 5, the subset representation in binary form would be 0 0 0 0 1. If element 2 and 3 are selected, the subset representation would be 0 0 1 1 0. If you take a binary one, keep track of its index, and move it from right to left in the array computing index&1 each time, you can get which indexes of the array are in the current subset (if the index&1 computation results in a 1 for that index). Translating this to a smaller array called currSubset, you can sum it up and check if it is equal to 7.
The termination of the outer for loop comes from the maximum value of a 5 digit binary number, which is 11111 = 31 = 2^5-1, hence the use of the less than sign.
int sum = 0;
int index = 0;
ArrayList<ArrayList<Integer>> subsetsThatAddTo7 = new ArrayList<ArrayList<Integer>>();
for(int subsetRep = 0b00001; i < Math.pow(2,5); i++){
ArrayList<Integer> currSubset = new ArrayList<Integer>
for(index = 0; index < 5; index++){
if(subsetRep & (1 << index))
currSubset.add(diceRoll[5-index]);
}
int sum = 0;
for(int num : currSubset)
sum += num;
if(sum == 7)
subsetsThatAddTo7.add(currSubset);
}

java.lang.ArrayIndexOutOfBoundsException while sorting an integer array [duplicate]

This question already has answers here:
What is the reason for ArrayIndexOutOfBoundsException in my code?
(2 answers)
Closed 7 years ago.
Scenario:
I need to read an array of integers from the standard inputstream, reorder it in such a way that a prime number is always followed by two even numbers ensuring that the prime and even numbers are picked up from the array in the order in which they are present to build the prime-2even set. Any remaining numbers that can't be part of the set can be
placed at the end of the array in the order in which they appear. The input(in multiple lines) and expected output(in multiple lines) as below:
Input:
8 5 9 7 8 5 4 6 8
Expected output:
5 8 4 7 6 8 9 5
Attempt:
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int totalElements = Integer.parseInt(scanner.nextLine());
Integer[] integers = new Integer[totalElements];
Integer[] primeTwoEvens = new Integer[totalElements];
Integer[] leftOvers = new Integer[totalElements];
for (int i = 0; i < integers.length; i++) {
integers[i] = scanner.nextInt();
}
// LOGIC
int notNullCounter = 0; // Variable to track how many elements of integers array has been set to null.
while (notNullCounter != integers.length) { // Repeat this process until all the elements of the integers array are null.
for (int i = 0; i < integers.length; i++) { // Iterate the integers array and check for primeTwoEvens and populate the primeTwoEvens array.
if (integers[i] != null) { // Is the element of integers array to be processed null? If no, proceed.
if (isPrime(integers[i])) { // Is the element of integers array prime? If yes, proceed.
System.out.println(integers[i] + " is prime..."); // Print statement for debugging purpose.
primeTwoEvens[i] = integers[i]; // Since the element of integers array is prime, add it to the primeTwoEvens array.
integers[i] = null; // Set this index of integers array to null.
notNullCounter++; // As one element of integers array has been set to null, increment the null counter.
int evenCounter = 0; // Variable to track even number occurrences.
while (evenCounter != 2) { // Repeat this process until 2 even numbers are not found.
for (int j = ++i; j <= integers.length; j++) { // Iterate the remaining elements of integers array and check for next two even numbers.
if (isEven(integers[j])) { // Is the element of integers array even? If yes, proceed.
System.out.println(integers[j] + " is even..."); // Print statement for debugging purpose.
evenCounter++; // Since the element of integers array is even, increment the even counter.
primeTwoEvens[++i] = integers[j]; // Since the element of integers array is even, add it to the primeTwoEvens array as well.
integers[j] = null; // Set this index of integers array to null.
notNullCounter++; // As one element of integers array has been set to null, increment the null counter.
}
}
}
} /*else { // Element is not prime.
}*/
}
}
//break;
}// End of while
/*System.out.println("############ PRINTING THE FINAL SORTED ARRAY ############");
for (Integer integer : integers) {
System.out.println(integer);
}*/
}
throws me an java.lang.ArrayIndexOutOfBoundsException
Output:
5 is prime...
8 is even...
4 is even...
6 is even...
8 is even...
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 8
at Ideone.main(Ideone.java:125)
Line 125:
if (isEven(integers[j]))
Note: I am restricted to using Java standard API and JDK 7.
How do I solve the problem and the final task?
I think the previous line (before Line 125) should be
for (int j = ++i; j < integers.length; j++)
Not <=
You could try this:
public static void main(String[] args) {
// Read your file (I just copy your example to an array)
Integer[] integers = new Integer[] { 8, 5, 9, 7, 8, 5, 4, 6, 8 };
List<Integer> prime = new ArrayList<Integer>(), even = new ArrayList<Integer>();
List<Integer> other = new ArrayList<Integer>(), ordered = new ArrayList<Integer>();
// Start adding until 1st prime appear
boolean firstPrime = false;
for (Integer number : integers) {
if (isPrime(number)) {
prime.add(number);
firstPrime = true;
} else if (firstPrime && isEven(number)) {
even.add(number);
}
// To have control of the order of appearance
if (firstPrime) other.add(number);
// If I have at least 1 prime and 2 even, then add them
// to my ordered list and remove them from all my other lists
if(prime.size() >= 1 && even.size() >= 2){
ordered.add(prime.get(0));
ordered.add(even.get(0));
ordered.add(even.get(1));
other.remove(prime.get(0));
other.remove(even.get(0));
other.remove(even.get(1));
even.remove(1);
even.remove(0);
prime.remove(0);
}
}
ordered.addAll(other);
System.out.println(ordered);
}
If you run this example, you will have
[5, 8, 4, 7, 6, 8, 9, 5]

Categories