Reputation: 3
I'm writing a quick little program for an assignment, I wondered if anyone could tell me if there is a method that will compare multiple int values and find ones that match each other such as pairs or triplets, naturally, using boolean means you are limited to two values. to put it in context, I'm writing an incredibly basic slot machine game that looks like this:
//the java Random method is the method that will generate the three random numbers
import java.util.Random;
import java.util.Scanner;
public class slotMachine {
public static void main(String[] args) {
//scanner will eventually be used to detect a cue to exit loop
Scanner loopExit = new Scanner(System.in);
int rand1 = (0);
int rand2 = (0);
int rand3 = (0);
Random randGen = new Random();
rand1 = randGen.nextInt(10);
rand2 = randGen.nextInt(10);
rand3 = randGen.nextInt(10);
System.out.print(rand1);
System.out.print(rand2);
System.out.println(rand3);
//this is the part where I need to compare the variables,
//this seems like a slow way of doing it
if ((rand1 == rand2) || (rand2 == rand3))
{
System.out.println("JACKPOT!");
}
Upvotes: 0
Views: 1044
Reputation: 617
you could try using a cantor pairing function to create a unique number for a pair or tuple, you can then create a matrix with all the winnable combinations
((x + y) * (x + y + 1)) / 2 + y;
basically lets say the winning combination is (7,7,7)
as they roll the randomization, you would just calculate the tuple and check against your winning matrix.
Upvotes: 1
Reputation: 14709
You could use an array or HashSet
or what have you, but since you only have three numbers, and this doesn't need to be generalized to a larger set, I think that the best way to do this is the way you're doing it, except to add the necessary condition as follows:
if ((rand1 == rand2) || (rand2 == rand3) || (rand1 == rand3))
{
System.out.println("JACKPOT!");
}
You say that you're worried that this is slow, but I cannot think of a more computationally efficient way to do this.
Upvotes: 0
Reputation: 3896
Here's what I'd do:
HashSet<Integer>
HashSet
, print "Jackpot" (there are various ways of checking that, I'll let you figure that part out)HashSet
Upvotes: 0