【问题标题】:Functions that takes array as argument and generate random numbers以数组为参数并生成随机数的函数
【发布时间】:2019-11-19 11:46:23
【问题描述】:

首先,任何内置方法都不能使用。前任。 pop()shift()。我可以使用的只是循环,数组等。

我想创建一个函数,它将数组作为参数并生成随机数字字符串,其中不包含数组中给出的这些数字。

例如,func([6, 2]) //=> "20353"(不会出现 2 和 6)。 数组长度可能会改变([6, 2, 9][7, 2, 1, 9])。所以函数必须能够容纳任意长度的数组。

为了解决这个练习题,我使用了forwhile 循环。但是,我遇到了一个问题,当检查第二个索引时(在示例中随机生成的数字是否包含 2),如果它包含,我重新生成随机数并且它可以生成第一个索引号(在这个案例,6)我不想要。

请查看我在下面发布的代码并帮助我解决这个问题。最重要的是,如果有另一种方法可以获得相同的结果,这是更好的方法,也请告诉我。

let str = "";
let arr = [];
let tem

const func = arg2 => {
  for (let i = 0; i < 5; i++) {
    arr[i] = Math.floor(Math.random() * 10);
  }

  for (let i = 0; i < arr.length; i++) {
    for (let v = 0; v < arg2.length; v++) {
      if (arg2[v] == arr[i]) {
        do {
          tem = Math.floor(Math.random() * 10);
        } while (tem == arr[i])
        arr[i] = tem;
      }
    }
  }

  for (let i = 0; i < arr.length; i++) str += arr[i]
  return str
}

console.log(func([6, 2]))

// the output will not contain 2, which is the last index element
// however, when the second index number is removed, the output might replace it with 6, which is the first index element

预期输出:

func([6, 3, 8]) //=> "45102"
func([4, 9]) //=> "55108"

【问题讨论】:

  • 字符串结果的长度应该一直是5?
  • “任何内置方法都不能使用。”:你已经在使用两个原生方法了……

标签: javascript arrays function parameters


【解决方案1】:

首先,您已经使用了两种本机方法(floorrandom),但我假设您可以接受。

其次,在您的问题中,术语 digit 在某些情况下会比 number 更合适。有区别……

为避免您仍然选择不允许的数字,您可以先构建一个包含仍然允许的数字的数组,然后从 那个 数组中随机选择值。这样你就不会选错了。

这就是它的样子:

const func = arg2 => {
    const digits = [0,1,2,3,4,5,6,7,8,9];
    // Mark digits that are not allowed with -1
    for (let i=0; i<arg2.length; i++) {
        digits[arg2[i]] = -1;
    }
    // Collect digits that are still allowed
    const allowed = [];
    for (let i=0; i<digits.length; i++) {
        if (digits[i] > -1) allowed[allowed.length] = digits[i];
    }
    // Pick random digits from the allowed digits
    let str = "";
    for(let i=0; i<5; i++) {
        str += allowed[Math.floor(Math.random() * allowed.length)];
    }
    return str;
}

console.log(func([6, 2]));

只是为了好玩,如果你取消了对哪些语言方面不能使用的限制,你可以这样做:

const func = arg2 => {
    const digits = new Set(Array(10).keys());
    for (let digit of arg2) digits.delete(digit);
    const allowed = [...digits];
    return Array.from({length:5}, () => 
        allowed[Math.floor(Math.random() * allowed.length)]
    ).join``;
}

console.log(func([6, 2]));

【讨论】:

    【解决方案2】:

    我怀疑你想多了。基本算法是:

    • 在循环中:
      • 如果输出有5位,返回。
      • 否则
        • 从 0 到 9 中选择一个随机数字 n
        • 如果 n 在排除的数字列表中,则输出

    这直接映射到以下函数:

    function fn(exclude, length = 5) {
      let output = '';
      while (output.length < length) {
        const n = Math.floor(Math.random() * 10)
        if (!exclude.includes(n)) {
          output += n;
        }
      }
      return output;
    }
    
    console.log(fn([6,3,8]));

    当然,还有其他方法可以实现这一点,例如初始化一个包含五个元素的数组,然后joining 元素:

    function fn(exclude, length = 5) {
      return Array.from({ length }, () => {
        let n;
        while (n = Math.floor(Math.random() * 10), exclude.includes(n)) {}
        return n;
      }).join('');
    }
    
    console.log(fn([6,3,8]));

    【讨论】:

      【解决方案3】:

      每次选择一个随机数字时,您都需要遍历整个 arg2 数组。您不能替换 arg2 循环中的值,因为这样您就不会检查较早的元素。

      您不需要arr 数组,您可以在循环中追加到str

      const func = arg2 => {
        let str = "";
        let arr = [];
        for (let i = 0; i < 5; i++) {
          let random;
          while (true) {
            let ok = true;
            random = Math.floor(Math.random() * 10);
            for (let j = 0; j < arg2.length; j++) {
              if (random == arg2[j]) {
                ok = false;
                break;
              }
            }
            if (ok) {
              break;
            }
          }
          str += random
        }
      
        return str
      }
      
      console.log(func([6, 2]))

      【讨论】:

        【解决方案4】:

        除了您自己使用原生数组方法这一事实(其他人也说过)之外,我可能会使用类似这样的方法(仅使用您目前使用的方法):

        const func = without => {
            let result = '';
        
            while (result.length < 5) {
                let rand = Math.floor(Math.random() * 10);
                let add = true;
        
                for (i=0; i<without.length; i++) {
                    if (rand === without[i]) {
                        add = false;
                    }
                }
        
                if (add) {
                    result += rand;
                }
            }
        
            return result;
        }
        
        console.log(func([6, 2]))

        使用原生数组方法的更简洁的版本可能如下所示:

        const func = without => {
            let result = '';
        
            while (result.length < 5) {
                let rand = Math.floor(Math.random() * 10);
        
                if (!without.includes(rand)) {
                    result += rand;
                }
            }
        
            return result;
        }
        
        console.log(func([6, 2]))

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2018-10-18
          • 2014-10-31
          • 1970-01-01
          • 2015-12-20
          • 1970-01-01
          • 1970-01-01
          • 2021-05-15
          • 1970-01-01
          相关资源
          最近更新 更多