srheayns
srheayns

Reputation: 3

comparing multiple int variables to find pairs or triplets

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

Answers (3)

Greg
Greg

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

wiki:cantor pairing

    ((x + y) * (x + y + 1)) / 2 + y;

basically lets say the winning combination is (7,7,7)

  1. first we do the pair(7,7) to be (7+7)*(7+7+1)/2+7 = (14*15)/2 + 7 = 112
  2. then take (112,7) to be (112+7)*(112+7+1)/2 + 7 = 7147
  3. you could then use 7147 as your winning key

as they roll the randomization, you would just calculate the tuple and check against your winning matrix.

Upvotes: 1

Steve P.
Steve P.

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

musical_coder
musical_coder

Reputation: 3896

Here's what I'd do:

  • Initialize an empty HashSet<Integer>
  • Generate each random int inside a loop
  • If the new int is in the HashSet, print "Jackpot" (there are various ways of checking that, I'll let you figure that part out)
  • Else, add it to the HashSet

Upvotes: 0

Related Questions