【问题标题】:How to select random starting position from ordered list? [duplicate]如何从有序列表中选择随机起始位置? [复制]
【发布时间】:2019-04-07 03:47:53
【问题描述】:

我正在制作一个轮盘游戏,我为插槽创建了一个 Arraylist,它们已在有序列表中定义,有 38 个插槽,位置 (0-37)、颜色和数字。

在“旋转方法”中,我尝试从车轮集合/列表中选择一个随机起始槽,然后根据延迟功能旋转一些槽。

如何从我的收藏中随机选择一个插槽来启动此过程?

我的收藏

    List<Slot> wheel = new ArrayList<Slot>();
    GameEngine gameEngine;

    public GameEngineImpl() {
        Color colorArray[] = new Color[] { Color.GREEN00, Color.RED, Color.BLACK, Color.RED, Color.BLACK, Color.RED,
                Color.BLACK, Color.RED, Color.BLACK, Color.RED, Color.BLACK, Color.RED, Color.BLACK, Color.RED,
                Color.BLACK, Color.RED, Color.BLACK, Color.RED, Color.BLACK, Color.GREEN0, Color.BLACK, Color.RED,
                Color.BLACK, Color.RED, Color.BLACK, Color.RED, Color.BLACK, Color.RED, Color.BLACK, Color.RED,
                Color.BLACK, Color.RED, Color.BLACK, Color.RED, Color.BLACK, Color.RED, Color.BLACK, Color.RED };
        int numberArray[] = new int[] { 00, 27, 10, 25, 29, 12, 8, 19, 31, 18, 6, 21, 33, 16, 4, 23, 35, 14, 2, 0, 28,
                9, 26, 30, 11, 7, 20, 32, 17, 5, 22, 34, 15, 3, 24, 36, 13, 1 };
        for (int position = 0; position < 38; position++) {
            wheel.add(new SlotImpl(position, colorArray[position], numberArray[position]));
        }
    }

旋转法

@Override
    public void spin(int initialDelay, int finalDelay, int delayIncrement) {
        Slot slot;
        while (initialDelay < finalDelay) {

        //  TODO selecting a random starting slot on the wheel 


                }
            }

            // Delay function
            delay(delayIncrement);
            // Increase increment
            initialDelay += delayIncrement;
        }

    }
    // Method to delay spinning
    private void delay(int delay) {
        try {
            Thread.sleep(delay);
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
        }
    }

【问题讨论】:

  • “我如何在 Java 中 random 做一些事情”您在网络上搜索 java random,阅读文章并了解如何操作。

标签: java oop collections enums


【解决方案1】:

您可以使用Random::nextInt 生成随机整数:

int random = new java.util.Random().nextInt(38);
//nextInt: int value between 0 (inclusive) and the specified value (exclusive)

要遍历元素,您可以使用流或 for 循环。下面是一个流的例子:

wheel.subList(random, 37).stream().forEach(e -> {
    // e is the element
});

for循环:

for(int i = random; i < 38; i++) {
    var e = wheel.get(i); // e is the element
}

【讨论】:

    【解决方案2】:

    两个简单的选择:

    • 使用 java.util.Random 在数组的可能索引范围内生成一个随机 int。
    • 使用 Collections.shuffle() 将列表随机排列,然后每次选择第一个条目。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2023-02-02
      • 2017-09-20
      • 2023-01-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-02-22
      • 1970-01-01
      相关资源
      最近更新 更多