【问题标题】:Random index entry in an array数组中的随机索引条目
【发布时间】:2015-05-03 13:54:08
【问题描述】:

我正在尝试将带有数字“1”的数组填充到随机索引中!谁能帮助我?提前谢谢你:)


    int[] array = new int[5]; //main array
    int[] tempArray = new int[array.length]; //temporary array
    boolean isThere;
    int randomIndex;

    for (int i = 0; i < array.length; i++) {
        isThere = false;
        randomIndex = (int) (Math.random() * array.length);
        for (int j = 0; j < array.length; j++) {
            if (tempArray[j] == randomIndex) {
                isThere = true;
                break;
            }
        }
        if (!isThere) {
            array[randomIndex] = 1;
            tempArray[i] = randomIndex;
        }
    }

    for (int i = 0; i < array.length; i++) {
        System.out.println("\n" + array[i]);
    }

【问题讨论】:

  • 您有什么具体问题吗?
  • 请提供更多细节。您的代码有什么问题?有什么例外吗?
  • 在随机索引处填充数组没有多大意义,您要在随机索引处插入一个值吗?
  • "你想在随机索引处插入一个值吗?"是的..这正是我想要的!

标签: java arrays indexing


【解决方案1】:

我猜你想以(特定的)随机顺序填充数组。

你可以试试这个:

List<Integer> list = new ArrayList<Integer>(5);
for (int i = 0; i < 5; i++){
    list.add(i);
}
Collections.shuffle(list);
// now that the list has been shuffled.
for (Integer item:list){
    array[i] = 1;
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-08-06
    • 2016-11-06
    • 2014-07-25
    • 2014-04-21
    • 2019-05-04
    相关资源
    最近更新 更多