生成包含一些数字并排除一些数字的随机数字符串

时间:2018-10-02 07:00:09

标签: javascript

我在使用javascript生成字符串时遇到问题。 我有一个数字数组,字符串应包含至少1,以及一个不能包含在字符串中的1个数字(最多7位)。字符串长度必须为7。

var incNumber = ["15","51","14","41","55","39","23"];
var exclude = ... //input from user

我试图通过从数组,随机位置以及所选数字周围随机其他数字的随机选择来生成它。然后检查字符串是否包含排除的数字,然后再次生成。

//random select number
var getRandom = incNumber[Math.floor(Math.random() * incNumber.length)];

//random position of number 
var position = Math.floor(Math.random() * 6);

//length of other string after selected number
var afterlen = 7 - (position+2);

//genNum(...) is my function that use to generate string of number in specific length.
var nstr = genNum(position)+getRandom+genNum(afterlen);

while (nstr.includes(exclude)) {
nstr = genNum(position)+getRandom+genNum(afterlen);
}

,但是这样做会花费很长时间,甚至有时会冻结我的浏览器。我该如何解决??

编辑:这是我关于电话号码的作业。 最终字符串应类似于“ 37915002”

2 个答案:

答案 0 :(得分:0)

再次编辑我的代码

现在符合您的需求吗?它已经很混乱了,我不确定它是否正确(我不确定。.xD)希望您能从中得到一些启发。

// Variables
var initialList = ["100", "5", "19", "88", "10", "90"];
var excludeList = ["9", "10"];
var resultLength = 7;
var finalString = "";

// Create a third final array that is filtered
var finalList = initialList.filter(element => {
  let shouldBeIncluded = true;
  excludeList.forEach(excluder => {
    Array.from(excluder).forEach(excluderFragment => {
      if (element.includes(excluderFragment)) shouldBeIncluded = false;
    });
  });
  if (shouldBeIncluded) return true;
});

// Check if all were excluded
if (finalList.length == 0) {
  // Do error handling here
} else {
  // Create the list
  for (let i = 0; i < resultLength; i++) {
    finalString += finalList[Math.floor(Math.random() * finalList.length)];
  }
  // Shorten the list because multiple digits values
  finalString = finalString.slice(0, 7);
  console.log(finalString);
}

答案 1 :(得分:0)

您可以先从incNumber中过滤掉不需要的数字,然后以相同的方式进行操作,但在新数组上进行操作

var incNumber = ["15","51","14","41","55","39","23"];
var exclude = "12";

var filteredNumbber =incNumber.filter(number=> number!==exclude);
var random = filteredNumbber[Math.floor(Math.random() * filteredNumbber.length)];

如果我们假设exclude不是值,而是值的数组,则可以将公式更改为

var incNumber = ["15","51","14","41","55","39","23"];
var exclude = ["15"];

var filteredNumbber =incNumber.filter(number=> !exclude.includes(number));
var random = filteredNumbber[Math.floor(Math.random() * filteredNumbber.length)];

有些人建议,如果我们排除incNumber中的所有数字,则随机变量可能最终以undefined结尾,如果是这种情况,我们应该在发生这种情况的情况下添加额外的检查

if (random!==undefined) var nstr = genNum(position)+random+genNum(afterlen);