各位大神好,
目前再做一個練習, 實現取 8 個小於 31 的亂數, 並將亂數由小到大排列並後由第一個減第二個, 以此類推, 而相減結果不得<= -6, 如果<= -6 就執行 location.reload()刷新頁面.
預期結果如下:
[4, 5, 6, 11, 16, 20, 22, 22], [-1, -1, -5, -5, -4, -2, 0, NaN]
而如果想取多組情況頁面會刷新很久, 觀感不太好.
想請教, 怎麼樣精進可以不用location.reload() 就達到預期的效果呢?
附上程式碼:
function getRandom(x) {
  return Math.floor(Math.random() * x + 1);
};
function getNum() {
  let ansewer = [];
  let check = [];
  let n = 0;
  for (i = 0; i <= 7; i++) {
    let n = getRandom(31);
    if (ansewer.indexOf(n) > 0) {
      i--;
      continue;
    } else {
      ansewer.push(n);
    };
  };
  ansewer.sort((a, b) => {
    return a - b;
  });
  //檢查是否組數相減有小於等於 -6 的
  for (let i = 0; i < ansewer.length; i++) {
    check.push(ansewer[i] - ansewer[i + 1])
  }
  
  if (check.find((el) => el <= -6)) {
    location.reload()
  }
  console.log(ansewer, check);
  return ansewer;
};
getNum()
https://jsfiddle.net/fillano/7rbmnxe6/16/
友善介面版...感覺可以用generator做,所以用無限迴圈配合yield寫一個。
參考看看合不合用
        function getRandom(x) {
          return Math.floor(Math.random() * x + 1);
        };
        function getNum() {
          let ansewer = [];
          let check = [];
					trytimes = 0;
					while (trytimes < 20) {
          let n = 0;
				        	
          for (i = 0; i <= 7; i++) {
            let n = getRandom(31);
            if (ansewer.indexOf(n) >= 0) {
              i--;
              continue;
            } else {
              ansewer.push(n);
            };
          };
          ansewer.sort((a, b) => {
            return a - b;
          });
					//檢查是否組數相減有小於等於 -6 的
          for (let i = 0; i < ansewer.length; i++) {
            check.push(ansewer[i] - ansewer[i + 1])
          }
          if (check.find((el) => el <= -6)) {
            /* location.reload() */
            console.log('try ',++trytimes);            
            ansewer.length = 0;
            check.length = 0;
          } else {
          	trytimes = 9999;
          }
					}
          console.log(ansewer, check);
          return ansewer;
        };
        getNum()