1

For my code I would like to check an array which will be filled many times with 6 random integers. Each time I want to check if all 6 values are different and if this happens for the code to stop. However after trying to use loops I was having problems so I just used a long ass If statement to check each location in the array with each other location. However This is not working. Would love if someone could tell me why i'm being stupid.

if((diceArray[0] != diceArray[1] & diceArray[0]!=diceArray[2] & diceArray[0]!=diceArray[3] & diceArray[0]!=diceArray[4] & diceArray[0]!=diceArray[5] & diceArray[1]!=diceArray[2] & diceArray[1]!=diceArray[3] & diceArray[1]!=diceArray[4] & diceArray[1]!=diceArray[5] & diceArray[2]!=diceArray[3] & diceArray[2]!=diceArray[4] & diceArray[2]!=diceArray[5] & diceArray[3]!=diceArray[4] & diceArray[3]!=diceArray[5] & diceArray[4]!=diceArray[5]))

                {
                    System.out.println("stop babes");
                }
                else
                {
                    System.out.print("Did not work");
                }

There is more to this code but I know the rest works as when I print out each sequence they all pint out no problem. When I run the code with this part Ideally It would print out many sequences with duplicate number and with these print out "did not work" and one of the results should come out with "stop babes" (These will be removed later just using them to test and a return used to stop the code) However when i run the code this happens

how many rolls of 6 dice? 3
LINE 1
 4 1 3 5 5 5
stop babes
LINE 2
 4 4 1 2 6 1
stop babes
LINE 3
 3 6 4 6 4 4
stop babes

JUST a quick edit re on the if statement. I realise It could be shortened to a quick loop I just wanted to brute force the problem. The main problem is the text "stop babes" should only be printing when a code such as 1 2 3 4 5 6 is printed informing me the code works and allowing me to insert a break statement on the main FOR loop.

3
  • 5
    Despite all the answers and comments so far, & is a valid Boolean/logical operator; it just doesn't short-circuit like && does. Commented Nov 5, 2014 at 22:12
  • I had && earlier but changed it when troubleshooting. Didn't work Commented Nov 5, 2014 at 22:15
  • You are usually going to be better served by &&, so you should use that. There are better approaches to your problem, though. Commented Nov 5, 2014 at 22:15

6 Answers 6

2

This should work for you:

public static bool areValuesUnique( int[] values )
{
    for( int i = 0; i < values.length; ++i )
    {
        for( int j = i + 1; j < values.length; ++j )
        {
            if( values[i] == values[j] )
                return false;
        }
    }
    return true;
}

And you would use it like so and has the added benefit of working with an array of any size.

if( areValuesUnique( diceArray ) )
{

}
else
{

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

Comments

1

I think you need to use Set to verify is there is any equals objects in the array. You simply create new HashSet with objects contained in the array and after that verify the length of created set. If length is equal to length of your array than all objects are different.

Set<YOUR_ARRAY_TYPE> set = new HashSet<YOUR_ARRAY_TYPE>();
set.addAll(Arrays.asList(YOUR_ARRAY));
if (set.size() == YOUR_ARRAY.length)
{
    ...
}
else
{
    ...
}

3 Comments

Using sets is like taking the sledgehammer to crack a nut.
@Turing85 You're entitled to your opinion, of course. But in situations where performance is not critical, taking advantage of the properties of a Set like this can lead to code that is easy to read and maintain. The code in this answer is clearly correct (although more verbose than necessary); contrast with solutions using 'for' loops, which require a bit more inspection to verify.
I never said, that the code is incorrect, but for the purpose (this is an exercise for someone, who is trying to learn Java) just a bit too much. And the readability is a matter of opinion :)
1

Consider using a for loop to do this instead of a giant if statement:

for (int i = 0; i < 6; i++)
{
    for (int j = i + 1; j < 6; j++)
    {
        if (diceArray[i] == diceArray[j])
            System.out.println("Did not work!");
    }    
}

Also, it's better to use the && operator for logical AND, rather than &, because && short-circuits - it will stop and return false at the first part of the condition that evaluates to false, while & will calculate all the conditions so it`s less efficient.

1 Comment

I am fairly sure that diceArray[0] == diceArray[0] which would be the first iteration of the inner looop.
0

If your ultimate goal is to remove the sequences that have duplicates, you should consider checking the array at the time you fill it:

Instead of just doing something like this (you didn't provide the code so I'm just guessing):

n = rand.nextInt();
diceArray[nextPosition++] = n;

Do something like:

n = rand.nextInt();
for ( int i = 0; i < nextPosition; i++ ) {
    if ( diceArray[i] == n ) {
        return;  // Or whatever will cause the array to be disqualified.
    }
}

This way you will save yourself rolling numbers that you won't use anyway. Suppose you rolled 2 2. You already know you have to disqualify this array, you don't need to continue rolling to get to 2 2 1 3 4 5 and then loop through the whole thing and disqualify it in the end.

This is also true if you want to count the number of bad arrays you got before you got to a good array.

    Random rand = new Random();
    int[] diceArray = new int[6];

    int badArrays = 0;
    int nextPosition = 0;

    while ( nextPosition < 6 ) {

        boolean goodMove = true;
        int n = rand.nextInt(6) + 1;
        for ( int i = 0; i < nextPosition; i++ ) {
            if ( diceArray[i] == n ) {
                goodMove = false;
                break;
            }
        }
        if ( goodMove ) {
            diceArray[nextPosition++] = n;
        } else {
            nextPosition = 0;
            badArrays++;
        }
    }

    System.out.println( "Got the array: " + Arrays.toString(diceArray)
                        + " after " + badArrays + " failures." );

3 Comments

Actually the aim is to count how many times it took to get a sequence without any duplicates.
Excellent, it works for that as well. I have edited my answer to show you code for counting the number of duplicate arrays without actually filling them all the way.
You are a champion my friend! This works perfectly for me. Very similar to what i was doing but much simpler to work with. Was easily able to adapt it to what I needed. Also how do I say question answered? I'm new :D
0

Another way, kinda fun, using bit masking. This is how we rolled in the old days.

// watch out: only works for dice values 0-30
public static boolean areDiceUnique(int[] diceArray) {
  int mask=0;
  for(int i=0; i<diceArray.length; i++) {
    int orMask = 1<<diceArray[i];
    if((mask & orMask) != 0)
      return false;
    mask |= orMask;
  }
  return true;
}

if you are just looking for unique dice rolls only, then just start with an List<Integer> with 1,2,3,4,5,6 and while(list.size()>0) get the item at rand.nextInt(list.size()).

Comments

-2

I believe you want && versus &

One is a bitwise operation while other is logical.

5 Comments

This is incorrect. In boolean-context, & is the "normal" and while && is the "fast" and, breaking if one expression is "false".
Not sure where I was incorrect seeing as even the Java docs show one as bitwise and the other is logical. docs.oracle.com/javase/tutorial/java/nutsandbolts/…
"one as bitwise and the other is logical" but they both represent AND operator. For boolean arguments one is short-circuit (&&), other is not (&).
They also have different orders of precedence. So in an equation read from left to right, it's quite easy to get different results if using & vs &&.
@Wranorn. You're right that the Oracle Java Tutorial doesn't mention & as a logical operator. However, the Java language is defined in the Java specification, and there (paragraph 15.22.2) & is defined as a logical operator (when the operands are boolean).

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.