比较多个int变量以查找对或三元组

时间:2013-11-12 04:23:30

标签: java integer compare

我正在为一个作业写一个快速的小程序,我想知道是否有人可以告诉我是否有一个方法可以比较多个int值并找到彼此匹配的方法,如对或三元组,当然,使用布尔值意味着您只能使用两个值。 把它放在上下文中,我正在写一个非常基本的老虎机游戏,看起来像这样:

//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!");
        }

3 个答案:

答案 0 :(得分:1)

您可以尝试使用cantor配对功能为一对或元组创建一个唯一的数字,然后您可以创建一个包含所有可赢组合的矩阵

wiki:cantor pairing

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

基本上可以说胜出组合是(7,7,7)

  1. 首先我们做对(7,7)为(7 + 7)*(7 + 7 + 1)/ 2 + 7 =(14 * 15)/ 2 + 7 = 112
  2. 然后取(112,7)为(112 + 7)*(112 + 7 + 1)/ 2 + 7 = 7147
  3. 然后你可以使用7147作为获胜的钥匙
  4. 当他们滚动随机化时,您只需计算元组并检查您的获胜矩阵。

答案 1 :(得分:0)

这就是我要做的事情:

  • 初始化空HashSet<Integer>
  • 在循环中生成每个随机int
  • 如果新的int在HashSet中,则打印“Jackpot”(有各种方法可以检查,我会让你想出那部分)
  • 否则,请将其添加到HashSet

答案 2 :(得分:0)

您可以使用数组或HashSet或者您有什么,但由于您只有三个数字,并且不需要将其推广到更大的数组,我认为这是执行此操作的最佳方法是你的方式,除了添加必要条件,如下所示:

if ((rand1 == rand2) || (rand2 == rand3) || (rand1 == rand3))
{
     System.out.println("JACKPOT!");
}

你说你担心这很慢,但我想不出一种计算效率更高的方法。

相关问题