如何从有序列表中选择随机起始位置?

时间:2019-04-07 03:47:54

标签: java oop collections enums

我正在做轮盘游戏,我为插槽创建了一个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();
        }
    }

2 个答案:

答案 0 :(得分:2)

您可以使用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
}

答案 1 :(得分:2)

两个简单的选项:

  • 使用java.util.Random在数组的可能索引范围内生成一个随机整数。
  • 使用Collections.shuffle()将列表简单地置于随机顺序,然后每次选择第一个条目。
相关问题