【问题标题】:Need help creating 10% random Array for sorting [closed]需要帮助创建 10% 随机数组进行排序 [关闭]
【发布时间】:2020-02-25 01:56:35
【问题描述】:

在 CS 实验室工作,并说我们需要创建一个 10% 的乱序数组和一个 1% 的乱序数组来使用各种算法进行排序。您将如何生成这样的数组?

【问题讨论】:

  • 有点不清楚您要达到的目标。你能举个具体的例子吗?

标签: java arrays random


【解决方案1】:

从排序数组开始。使用 while 循环并选择两个随机索引来选择要在数组中交换的两个项目。记下您移动了多少物品。当你达到 10% 或 1% 的物品移动停止。请务必检查您是否将物品放回原来的位置并相应地更新您的计数器。

Random random = new Random();

int length = 1000;
float maxMisplaced = 0.1f;

int[] data = IntStream.range(1000).toArray();
float misplaced = 0;

while (misplaced / length < maxMisplaced) {

    int randIndex1 = random.nextInt(length);
    int randIndex2 = random.nextInt(length);
    if (randIndex1 == randIndex2) continue;

    int randValue1 = data[randIndex1];
    int randValue2 = data[randIndex2];
    data[randIndex1] = randValue2;
    data[randIndex2] = randValue1;

    // increment if it was moved from its starting spot
    if (randIndex1 == randValue1) {
        misplaced += 1;
    }
    if (randIndex2 == randValue2) {
        misplaced += 1;
    }

    // decrement if it was moved back to its starting spot
    if (randIndex1 == randValue2) {
        misplaced -= 1;
    }
    if (randIndex2 == randValue1) {
        misplaced -= 1;
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-06-28
    • 2014-06-29
    • 2019-12-16
    • 2021-11-08
    • 2013-12-08
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多