如何在保持第一个和最后一个字符相同的情况下对单词进行加扰?(JS)

How to scramble a word, keeping first and last characters the same? (JS)

本文关键字:单词进 情况下 JS 第一个 字符 最后一个      更新时间:2023-09-26

我有一个任务,就是对一个大小大于3个字母的单词进行加扰。

加扰后的单词不能等于原始单词,单词的第一个字母和最后一个字母必须保持不变。

例如,单词stack可以给出以下结果之一:

  • satck
  • scatk
  • stcak
  • sactk
  • 等等

而像ishey这样的单词会因为太小而保持不变。

我的尝试可以在下面看到。我有一个JavaScript函数,它接收了一个要加扰的单词,然后我在一定的限制内选择随机索引来创建一个新的加扰单词并返回它。如果我选择的索引已经被选中,那么我会再次尝试,希望得到新的结果。

/**
 * Returns a scrambled word with the first and last letters unchanged
 * that is NOT EQUAL to the given parameter 'word', provided it has 
 * more than three characters.
 */
function scrambleWord(word){
  if(word.length <= 3)
    return word;
  var selectedIndexes, randomCharIndex, scrambledWord = word;
  while(word === scrambledWord){
    selectedIndexes = [], randomCharIndex, scrambledWord = '';
    scrambledWord += word[0];
    for(var j = 0; j < word.length-2; j++){
      //select random char index making sure it is not repeated
      randomCharIndex = getRandomInt(1, word.length-2);
      while(selectedIndexes.indexOf(randomCharIndex) > -1 && selectedIndexes.length != word.length-2){
        randomCharIndex = getRandomInt(1, word.length-2);
      }
      scrambledWord += word[randomCharIndex];
      selectedIndexes.push(randomCharIndex);
    }
    scrambledWord += word[word.length-1];
  }
  return scrambledWord;
}
/**
 * Returns a random integer between min (inclusive) and max (inclusive)
 * Using Math.round() will give you a non-uniform distribution!
 * See: http://stackoverflow.com/a/1527820/1337392
 */
function getRandomInt(min, max) {
    return Math.floor(Math.random() * (max - min + 1)) + min;
}

这种方法的问题在于速度太慢。我没有通过测试,因为我超过了6秒的时间限制,所以我肯定需要改进这个解决方案,但我不知道在哪里可以做到。

有什么想法吗?

这里有一个答案,它处理快速洗牌字符串的方法。然后你所需要做的就是像你正在做的那样去掉第一个和最后一个字母,用这种方法打乱字符串,然后把你的第一个和第二个字母重新粘上

为了完整性,我会留下你的检查,你得到的答案与原来的不一样,以防万一,以及字符串大于3个字符的检查,因为这些是你的需求所独有的。

这应该比你已经拥有的要快得多,因为这是你的随机洗牌,需要所有的时间!

相关文章: