Results 1 to 8 of 8
  1. #1
    lithium002 is offline Member
    Join Date
    Nov 2009
    Posts
    23
    Rep Power
    0

    Default An Array of different integer values

    Hello,

    I'm trying to create a program that creates an integer array of random size between 2 to 10 digits. This array holds digits from 0 to 9 in random order, but once an integer is stored, it can't be used again.

    For example, if I generate an integer array of 6 values, the array will hold 6 digits from 0 to 9 in random order, but the digit cannot be repeated once it's stored.

    I've been trying to figure this out all day and I can't seem to do the last bit.

    What I do is call Math.random to give me an integer size between 2 to 10 and based on that value create the array. Now I can store random integers from 0 to 9 in the array, but I have no idea how to NOT use an integer once it has already been stored.

    This is what my code looks like:
    Java Code:
    import java.util.Scanner;
    
    public class MasterMind
    {
        public static void main (String[] args)
        {
            int size = numberSize();
            printArray(createArray(size));
        }
        
        private static int numberSize()
        {
            return 2 + (int)(Math.random() * 9);
        }
        
        private static int[] createArray(int size)
        {
            int[] randomDigits = new int[size];
            for (int i = 0; i < size; i++)
            {
                randomDigits[i] = randomInteger();
            }
            
            return randomDigits;
        }
        
        private static int randomInteger() // function to get a random integer
        {
            return (int)(Math.random() * 10);
        }    
        
        private static void printArray(int[] array) // function to print an integer array
        {
            for (int i = 0; i < array.length; i++)
            {
                System.out.print(array[i]);
            }
            
            System.out.println();
        }
    
    }
    I have tried to find some algorithm to resolve this but in vain. I thought I could create a loop that would check the Math.random value with the previous array location, but then, that doesn't check the entire array.

    I honestly have NO idea how I can do this. I don't expect a full blown solution but a nudge in the right direction will be very appreciated.

  2. #2
    JohnnyR is offline Member
    Join Date
    Feb 2009
    Posts
    46
    Rep Power
    0

    Default

    Do a check to see if it exists in the current array prior to adding it.
    But that would fail if you randomed a '0' as by default they are all 0.
    I have it working as you want, and can share the code if you want.

    What i've done is set up a boolean 'hasZeroBeenUsed' starting as false
    then inside your loop set up a 'isNumberToBeAdded'
    based on these two boolean values at the end of my inside while statement and checking the list it bases the addition of the value to the array on whether or not the values had already been found in the array..

    I probably confused it all up so If you rather me show you the code let me know :)
    Last edited by JohnnyR; 12-03-2009 at 06:23 AM.

  3. #3
    Fubarable's Avatar
    Fubarable is offline Moderator
    Join Date
    Jun 2008
    Posts
    19,316
    Blog Entries
    1
    Rep Power
    26

    Default

    Quote Originally Posted by lithium002 View Post
    I have tried to find some algorithm to resolve this but in vain. I thought I could create a loop that would check the Math.random value with the previous array location, but then, that doesn't check the entire array.
    This should get you to a decent solution. Continue along these lines. Another method would be to create an ArrayList<Integer>, fill it with your 9 Integers, shuffle it via Collections.shuffle(myArrayList) and then remove and use the Integer at the 0 position.

  4. #4
    lithium002 is offline Member
    Join Date
    Nov 2009
    Posts
    23
    Rep Power
    0

    Default

    Hey JohnnyR,

    That sort of went through my head, but I kind of get an idea of what you're doing.

    Can you please share the code?

  5. #5
    rdtindsm is offline Member
    Join Date
    Feb 2009
    Posts
    92
    Rep Power
    0

    Default

    Fubarable has the right idea. Create an auxillary array, shuffle it, then simply transfer from array[0]...array[9].

    Shuffling can be done in place in linear time. Checking to see if the number is already in the array is requires n^2 time. That is, 1 + 2 + 3 ... comparisons which I believe sums to n*(n-1) / 2. Wikopedia describes the linear shuffling algorithm which was originally created by Knuth.

  6. #6
    JohnnyR is offline Member
    Join Date
    Feb 2009
    Posts
    46
    Rep Power
    0

    Default

    Java Code:
    /**
         * method creates the array to provided size 
         * then sets its values, no duplicates can exist.
         * @param size
         * @return the array of values
         */
        private static int[] createArray(int size) {
            int[] randomDigits = new int[size]; //New Array
            boolean hasZeroBeenUsed = false; //determines if we can add 0 for first time.
    
            for (int i = 0; i < size; i++) { //loops through each position to set the value
    
                boolean isNumToBeAdded = false; //is randomed number to be added to the array?
                while (isNumToBeAdded != true) { //continue while this is not equal to true.
                    isNumToBeAdded = true; //has to be set to true to start
                    int newInt = randomInteger(); //get the new integer value
    
                    for (int j = 0; j < size; j++) { //loop through pre-existing list of values
                        if (newInt == randomDigits[j]) { //if the new int value is the same as a pre-existing value
                            // check if it's 0
                            if (newInt == 0) {
                                if (hasZeroBeenUsed == false) { // if it hasn't been used then its ok to set it to 0
                                    isNumToBeAdded = true;
                                    hasZeroBeenUsed = true; //set value to true so 0 can't be used anymore.
                                } else { //otherwise it's not to be added
                                    isNumToBeAdded = false;
                                }
                            } else { //don't add it as it already exists in array.
                                isNumToBeAdded = false;
                            }
                        }
                    }
    
                    if (isNumToBeAdded == true) { //add the number to the array if true, loop ends.
                        randomDigits[i] = newInt;
                    } else { //if its not then set to false to reloop and try again.
                        isNumToBeAdded = false;
                    }
                }
    
            }
            //return the array of values.
            return randomDigits;
        }
    note* this is lengthy and could be compacted down greatly but i was in a rush..

  7. #7
    lithium002 is offline Member
    Join Date
    Nov 2009
    Posts
    23
    Rep Power
    0

    Default

    JohnnyR,

    that solution doesn't work. It works when there isn't a 0, but when the array generates a zero as the first value, the program doesn't respond. I tried testing your code with 500 different arrays and it stops responding at some point.

    BUT! GOOD NEWS! I was just able to figure out how to do this.

    I basically used my original "for" loop but created an if statement to just add the first value without anything changing and a counter to count total arrays entered so far.

    The second time it gets in the loop, I generate a random number and then call another function that does a check whether the numbers added so far match the randomly generated number. If they do, keep generating, otherwise assign it to the next memory in the array.

    It's simple, and it works.

    Here's the code:
    Java Code:
        private static int[] createArray(int size)
        {
            int[] array = new int[size];
            int count = 0;
            for (int i = 0; i < array.length; i++)
            {
                if(i == 0)
                {
                    array[i] = randomInteger();
                    count++;
                }
                
                else
                {
                    int randomvalue = randomInteger();
                    Boolean doesexist = search(array, randomvalue, count);
                    while (doesexist != true)
                    {
                        randomvalue = randomInteger();
                        doesexist = search(array, randomvalue, count);
                    }
                    
                    array[i] = randomvalue;
                    count++;
                }
            }
            
            return array;
        }
        
        private static boolean search(int array[], int value, int count)
        {
            for (int i = 0; i < count; i++)
            {
                if (value == array[i])
                    return false;
            }
            
            return true;
        }

  8. #8
    JohnnyR is offline Member
    Join Date
    Feb 2009
    Posts
    46
    Rep Power
    0

    Default

    odd works fine for me, oh well you have it working :-)
    *actually i found it :-)
    Last edited by JohnnyR; 12-04-2009 at 06:28 AM.

Similar Threads

  1. How do you store a random integer in an array?
    By Unknown in forum New To Java
    Replies: 6
    Last Post: 03-21-2010, 11:40 PM
  2. change string to array of integer
    By prof.deedee in forum New To Java
    Replies: 4
    Last Post: 11-09-2009, 03:47 AM
  3. Replies: 1
    Last Post: 03-31-2009, 07:40 AM
  4. Passing integer array from javascript to java
    By lavanyashastri in forum New To Java
    Replies: 1
    Last Post: 02-21-2009, 07:02 AM
  5. Getting integer values from a JTable
    By zikojam in forum New To Java
    Replies: 1
    Last Post: 12-11-2008, 03:06 PM

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •