0

Disclaimer: Still very new to code and have only basic skills with java. Trying to learn as much as i can on my own and from others. Not currently studying at uni.

Hello everyone.

I am trying to create an array with a small capacity (5 integers) to store a randomly generated integer in each array element. The randomly generated integer is in a set range (0-75) which ive no issue with.

What i cant figure out how to do is how to Generate a new integer, then check it against the current existing integers in each array element, before storing it and moving on to the next.

What i tried was this:

public class ItemSet
{
public static void main(String []args)
 {
 int[] itemSet;
 itemSet = new int[5];

 itemSet[0] = 0; /* to initialise the array elements. Im not sure if i actually have to do this or not */
 itemSet[1] = 0;
 itemSet[2] = 0;
 itemSet[3] = 0;
 itemSet[4] = 0;

 int count = 1;
 int assignItem = 0;
 int countTwo = 1;
 while (count > 5) {  
   while (countTwo == 1) {  
     assignItem = (int)(Math.random()*76); 
  // here is where i get totally lost
     if (assignItem.compareTo(itemSet)) { 
       countTwo = 1;
     } else {
       itemSet[(count--)] = assignItem; 
       countTwo = 0; 
     }
     }
     count = count++;
    }
 }
}

Ive been looking at this so long my head is starting to hurt. I'd appreciate any advice you can give me. :) Thank you in advance. xx

Edit: Couldnt find the solution i needed in any of the "how can i test if an array contains a certain value" type questions, because i need to be able to have the number randomise again before it stores itself in the array element if it does happen to be the same as another previously generated integer.

  • "check it against the current existing integers in each array element" Check it for what? – Andy Turner Apr 13 '16 at 16:42
  • "Im not sure if i actually have to do this" You don't. By specification, array elements are initialized to the default value for the type, which is zero for `int`. – Andy Turner Apr 13 '16 at 16:43
  • 1
    In short, you dont want to store duplicate element ..right ? – Rahman Apr 13 '16 at 16:43
  • 1
    Possible duplicate of [How can I test if an array contains a certain value?](http://stackoverflow.com/questions/1128723/how-can-i-test-if-an-array-contains-a-certain-value) – Alex Salauyou Apr 13 '16 at 16:44
  • Edited to try and explain how its different to that question. Yes i need to check the elements to ensure no duplicates are stored, but id like it to still keep the minimum array elements, and simply randomise the number again before it stores in the array. I thought to do this by generating the number in its own variable first and then having it check against the array for duplicates, but i was unsure how to accomplish this. – Jamie Maginnis Apr 13 '16 at 16:57

6 Answers6

0

You are doing too much to just fill an array. To fill an array, try using a "for" loop like so:

public class ItemSet {
    public static void main(String []args) {
        int[] itemSet;
        itemSet = new int[5];

        int count = 1;
        int assignItem = 0;
        int countTwo = 1;

        for (int i = 0; i < itemSet.length; i++) {
            itemSet[i] = (int) (Math.random() * 76);
        }
    }
}

To print the values stored in the array, try using an enhanced-for loop:

for (int element : itemSet) {
    System.out.println(element);
}

To check the values BEFORE storing the next integer, (say to see ensure that the new stored value would be unique) you could use a nested for loop that starts at the value beneath the outer loop and walks backwards, comparing each value that came before to the value that was just stored, and if they are the same, it will decrement the outer counter which will then override the data on the next loop:

import java.util.Arrays; // you need this to use Arrays.toString()

public class ItemSet {
    public static void main(String []args) {
        int[] itemSet;
        itemSet = new int[5];

        int count = 1;
        int assignItem = 0;
        int countTwo = 1;

        for (int i = 0; i < itemSet.length; i++) {
            itemSet[i] = (int) (Math.random() * 76);
            for (int j = i - 1; j >= 0; j--) {
                if (itemSet[j] == itemSet[i]) {
                    System.out.println("Comparing " + itemSet[j] +
                        " and " + itemSet[i]);
                    i--;
                    break; // not really needed but illustrates a way to exit a loop immediately
                }
            }
        }

        // this is a handy way to print all the data in an array quickly
        System.out.println(Arrays.toString(itemSet));
    }
}
djs
  • 3,947
  • 3
  • 14
  • 28
  • Ok that does make more sense. Thank you. I thought about doing something similar but i wasnt sure what i can and cant do. So i kind of... try to be safe and do things i know work. Thank you for showing me that though. itemSet.length will return as the number of elements in the array, right? thats why you can i < itemSet.length. But how do i then check to make sure none of the elements are the same? can i use compareTo(itemSet[i]) in another nested loop that will roll the number again if it clashes? – Jamie Maginnis Apr 13 '16 at 16:52
  • itemSet.length does return the number of items in the array, which will be 1 greater than the number of indexes since indexing is 0-based. Check out the edit I just posted, that's one way to go about checking for unique elements in a loop. Plus, using nested loops is a fun challenge! – djs Apr 13 '16 at 16:56
  • OK!! So when you say override the data on the next loop, you mean the outer loop will have generated the number, and stored it, but the nested loop will force it to do THAT iteration again, instead of moving on to the next iteration... Right? ( Sorry for all the questions. Im just trying to make sure i have this all straight in my head before i move on. Thank you so much though.) – Jamie Maginnis Apr 13 '16 at 17:00
  • When the if conditional is true (so when the current element that was just written at index i is equal to the element at j, which will be some element before i) we will decrement the i counter, which will mean that the data at the current value of i will be overwritten on the next loop. I also just added a break statement after this, to emphasize that nothing else will occur (although it isn't needed since there will only be one possible value of i and j that could be equal) – djs Apr 13 '16 at 17:03
  • Also, not that the nested loop counts down from 1 less than the outer-loop, this is something people often forget they can do since loops are generally counting up. – djs Apr 13 '16 at 17:04
  • Thank you so much. You are wonderful and my saviour. Also thank you for illustrating what break actually does. I had an idea but confirmation on its use and purpose is nice anyway – Jamie Maginnis Apr 13 '16 at 17:19
  • No problem, happy coding! – djs Apr 13 '16 at 17:20
  • Ahhhh this is so elegant. My mind is flowing with other things in the past i could have done with this methodology. – Jamie Maginnis Apr 13 '16 at 17:22
  • Check out "The C Book" if you like things like this. Even though its not written in Java, many of the programs in the beginning of the book have cool solutions like the one I posted above. Also, its free! Here's a link, just check out the programs don't bother with the rest, unless you want to learn C (which you should!). http://publications.gbdirect.co.uk/c_book/thecbook.pdf – djs Apr 13 '16 at 17:26
0
public static void main (String[] args){

    //you dont need to initialize the array with zeros
    int[] itemSet = new int[5];

    int counter = 0;

    while(counter < itemSet.length){

        int random = (int)(Math.random() * 76);

        //checks if the array already contains the random number
        if(!Arrays.asList(itemSet).contains(random)){

            itemSet[counter] = random;
            counter++;
        }
    }

    //print the array
    for(int i : itemSet) System.out.println(i);

}
Jefferson Lima
  • 5,186
  • 2
  • 28
  • 28
0

There are many ways you could solve this problem, I would suggest using a helping method that looks for duplicates in your array. This would be a working example:

public static void main(String[] args) {
    int[] itemSet;
    itemSet = new int[5];
    int assignItem;

    for (int i = 0; i < 5; i++) {
        assignItem = (int)(Math.random()*76);
        if(!duplicate(assignItem,itemSet,i)){
            itemSet[i] = assignItem;
        }
    }
}

private static boolean duplicate(int assignItem, int[] itemSet, int i) {
    for (int j = 0; j < i; j++) {
        if (assignItem == itemSet[j])
            return true;
    }
    return false;
}
osocron
  • 102
  • 6
0

I had a hard time understanding what youre asking for but ill give it a go anyway hoping this is what you want:

for (int count = 0; count < 5 ; count++) {
 assignItem = (int)(Math.random()*76);
 if (assignItem==itemSet[count]&&itemSet[count]!=0) {
     //If true do this
 }
 else {
     itemSet[count] = assignItem;

 }
}

Checking if the generated number is equal to a position and if the position is empty (0) if its not equal (a new number) then it will assign value to your array.

FREEDOM
  • 1
  • 4
0

The most straight forward way would be checking through the array for existing value before inserting the current random value.

  1. Generate a random value
  2. Check if value exists in array
  3. If already exist in array, generate another value
  4. If not exist in array, set value to current element

In codes:

public static void main(String[] args){
    int idx = 0;
    int[] myArray = new int[5];
    Random rnd = new Random();
    int val = rnd.nextInt(76);
    do{
        if(numExistInArray(val, myArray))
            val = rnd.nextInt(76);    //if val exist in array, generate another number
        else
            myArray[idx++] = val;     //if val not exist in array, fill array
    }while(idx != myArray.length);    //do not exit loop till all numbers are filled        
}

public static boolean numExistInArray(int val, int[] array){
    for(int x=0; x<array.length; x++)
        if(array[x] == val)
            return true;
    return false;
}
user3437460
  • 17,253
  • 15
  • 58
  • 106
0

If you know your set range (which is 0-75) and space isn't an issue, I would suggest maintaining a pool of unused integers. This would guarantee each value is unique, and would avoid iterating over your array of integers to check for duplicates:

public static void main(String[] args) {

    List<Integer> unusedNumbers = new ArrayList();
    // Populate list with values
    for (int i = 0; i <= 75; i++) unusedNumbers.add(i);

    int[] itemSet = new int[5];

    for (int i = 0; i < 5; i++) {
        int randomIndex = (int) (Math.random() * unusedNumbers.size());
        int randomInt = unusedNumbers.remove(randomIndex);
        itemSet[i] = randomInt;
    }
}
Matthew Diana
  • 1,106
  • 7
  • 14