0

我正在为作业编写一个快速的小程序,我想知道是否有人可以告诉我是否有一种方法可以比较多个 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!");
        }
4

3 回答 3

1

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

wiki:cantor 配对

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

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

  1. 首先我们将 pair(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 作为您的获胜密钥

当他们滚动随机化时,您只需计算元组并检查您的获胜矩阵。

于 2013-11-12T08:33:18.753 回答
0

这是我要做的:

  • 初始化一个空HashSet<Integer>
  • 在循环中生成每个随机整数
  • 如果新的 int 在 中HashSet,打印“Jackpot”(有多种检查方法,我会让你弄清楚那部分)
  • 否则,将其添加到HashSet
于 2013-11-12T04:26:59.980 回答
0

你可以使用一个数组或者HashSet你有什么,但由于你只有三个数字,而且不需要推广到更大的集合,我认为最好的方法就是你这样做的方式, 除了添加必要条件如下:

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

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

于 2013-11-12T04:32:22.913 回答