随机非数字赋值,不使用数组重复?

内容来源于 Stack Overflow,并遵循CC BY-SA 3.0许可协议进行翻译与使用

  • 回答 (1)
  • 关注 (0)
  • 查看 (37)

我正在尝试创建一个程序,为一件衣服分配一个随机,独特的颜色。我使用数组存储已经选择的颜色并尝试(使用'for'和'while')来消除重复的颜色。

我知道我的错误。似乎一旦发现颜色不重复就不会再次测试,因此偶尔会导致重复。

有人可以帮助我做到这一点吗?如果可能的话,我想避免使用花哨的库。我很擅长编码,想要更清楚地学习“为什么”和“如何”。谢谢。

<!DOCTYPE html>
<html lang="en-us">

<head>

  <!-- the goal is to randomly assign a color to a piece of clothing and have no duplicate colors -->
  <meta charset="utf-8">

  <!-- displays the clothing and color on-screen -->
  shirt: <span id="shirt"></span><br> shorts: <span id="shorts"></span><br> hat: <span id="hat"></span><br> coat: <span id="coat"></span>
  <br><br>

  <!-- testing prints to track what's going on-->
  colorPicked first: <span id="pickedColor"></span><br>

  <br><br> colors so far: <span id="soFar"></span>

</head>

<body>

  <script>
    // establish an array with seven color options
    var colors = ['orange', 'red', 'blue', 'green', 'yellow', 'pink', 'purple'];
    // array to track colors picked so far
    var colorPicked = [];
    // variable to track place in array
    var colorNumber = 0

    // assign a random color to 'shirt'
    var shirtColor = colors[Math.floor(Math.random() * colors.length)];
    colorPicked[colorNumber] = shirtColor;
    document.getElementById('shirt').innerHTML = shirtColor;

    document.getElementById('pickedColor').innerHTML = colorPicked[colorNumber];


    // assign a random color to 'shorts' - a loop (that doesn't quite work right) checks for duplicates
    var shortsColor = colors[Math.floor(Math.random() * colors.length)];


    while (shortsColor == colorPicked[i]) {
      for (var i = 0; i <= colorNumber; i++) {
        document.getElementById('pickedColor').innerHTML = "same";
        document.getElementById('shorts').innerHTML = shortsColor;
        shortsColor = colors[Math.floor(Math.random() * colors.length)];
      }
    }

    if (shortsColor != colorPicked[colorNumber]) {
      document.getElementById('shorts').innerHTML = shortsColor;
      colorNumber = colorNumber + 1;
      colorPicked[colorNumber] = shortsColor;
    }



    // assigns a random, non-repeating color to 'hat'
    var hatColor = colors[Math.floor(Math.random() * colors.length)];

    while (hatColor == colorPicked[i]) {
      for (var i = 0; i <= colorNumber; i++) {
        document.getElementById('pickedColor').innerHTML = "same";
        document.getElementById('hat').innerHTML = hatColor;
        hatColor = colors[Math.floor(Math.random() * colors.length)];
      }
    }

    if (hatColor != colorPicked[colorNumber]) {
      document.getElementById('hat').innerHTML = hatColor;
      colorNumber = colorNumber + 1;
      colorPicked[colorNumber] = hatColor;
    }



    // assigns a random, non-repeating color to 'coat'
    var coatColor = colors[Math.floor(Math.random() * colors.length)];

    while (coatColor == colorPicked[i]) {
      for (var i = 0; i <= colorNumber; i++) {
        document.getElementById('pickedColor').innerHTML = "same";
        document.getElementById('coat').innerHTML = coatColor;
        coatColor = colors[Math.floor(Math.random() * colors.length)];
      }
    }

    if (coatColor != colorPicked[colorNumber]) {
      document.getElementById('coat').innerHTML = coatColor;
      colorNumber = colorNumber + 1;
      colorPicked[colorNumber] = coatColor;
    }

    // show values in the log
    for (var i = 0; i <= colorNumber; i++) {
      //document.getElementById('soFar').innerHTML = colorPicked[i];
      console.log(colorPicked[i]);
    }
  </script>


</body>

</html>
提问于
用户回答回答于

一个简单的解决方案是简单地从阵列中删除拾取的颜色,这样就不能选择它作为副本。那么您也不必担心检查重复项。

此代码假定colors始终与其需要的时间长或长。

let colors = ['red', 'white', 'blue'];
const shirts = [{ name: 'shirt1' }, { name: 'shirt2' }];

const shirtsWithColors = shirts.map((shirt) => {
  // Make a copy of shirt so that we don't modify the one in the `shirts` array
  const newShirt = {...shirt};

  // Pick a color index
  const colorToUseIndex = Math.floor(Math.random() * colors.length);
  const colorToUse = colors[colorToUseIndex];

  // Remove the picked color from the color array
  colors.splice(colorToUseIndex, 1);

  // Assign the color and return
  newShirt.color = colorToUse;
  return newShirt;
});

PS如果您选择不使用此解决方案,并继续沿着您当前所拥有的行,我至少建议您切换到使用地图(对象)来查看是否使用了颜色。这将使检查更简单:

const colors = ['red', 'white', 'blue'];
const usedColors = {};
...
// When you assign a color:
usedColors[colorIndex] = true;
...
// When checking if the color has been used:
if (usedColors[colorIndex]) {
  // Try picking a different color
}

扫码关注云+社区

领取腾讯云代金券