0

I'm afraid I don't understand collections and data structures enough to process similar questions referring to a hash set. I currently have a loop that in a program that randomizes indexes within an array. The original array passed into the method consists of all prime numbers less than 1,000.

Not including the full program as it's part of a larger homework assignment.

My problem is that the if statement I created is printing out numbers repeatedly even though I thought I coded it to only print out the number if the number is already not in the array.

Can someone point out the mistake in my logic?

public static void shuffle(int[] intArray, String name)
{
    assert intArray != null : "null!";
    long seed = name.hashCode();
    Random random = new Random(seed);

    for(int i = 0; i < 1000; i++)
    {
        int random_m = random.nextInt(intArray.length);
        int random_n = random.nextInt(intArray.length);

        int temp = intArray[random_m];
        intArray[random_m] = intArray[random_n];
        intArray[random_n] = temp;

        int zeroIndex = intArray[0];
        List<Integer> myList = new ArrayList<Integer>();

        if(!myList.contains(zeroIndex))
        {
            System.out.println(zeroIndex);
        }
        myList.add(zeroIndex);
    }
}

Partial example of output:

5821 5821 5821 5821 5821 5821 5821 5821 5821 5821 5821 5821

11
  • Inner loop? There is only one loop. Commented Jan 24, 2019 at 4:07
  • 1
    Your list is reset on every iteration of the for-loop... so you have no state of previous numbers. Commented Jan 24, 2019 at 4:10
  • 1
    a new instantiation of myList will occur for every iteration of the for loop - useless Commented Jan 24, 2019 at 4:10
  • 1
    @CyrusLeung, nextInt(value) is an exclusive upper-bound, so the unmodified intArray.length is correct Commented Jan 24, 2019 at 4:15
  • 1
    @Immersive my bad, thanks for the comment Commented Jan 24, 2019 at 4:16

2 Answers 2

4
        List<Integer> myList = new ArrayList<Integer>();

This Line of Code Creates New memorySpace for myList Through every iteration , so every time you iterate through the loop the myList values will be reset .

So define myList outside the loop.

Sign up to request clarification or add additional context in comments.

Comments

0

Use int zeroIndex = intArray[i];

Hope you get it now :-)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.