【问题标题】:How to scramble a word, keeping first and last characters the same? (JS)如何打乱一个单词,保持第一个和最后一个字符相同? (JS)
【发布时间】:2016-03-17 12:48:40
【问题描述】:

我有一个任务,就是打乱一个大于 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 秒的时间限制,所以我肯定需要改进这个解决方案,但是我看不到我可以在哪里做。

有什么想法吗?

【问题讨论】:

  • 写一个函数来打乱字符串中的所有个字母。然后编写一个函数,它返回你给它的字符串的副本,除了第一个和最后一个字符被切掉。然后做function scramble_all_but_ends(s){return first_char(s) + scramble_all(chop_off_ends(s)) + last_char(s));}
  • 单词的最大大小是多少?
  • 为轻率的评论道歉,但我认为您的意思是“我有一个 tsak,这是为了 slinge wrod,woshe szie is gtreear tahn 3 ltreets。”
  • @sudomakeinstall2 没有最大字数:D
  • @AntonKnyazyev 一个……的儿子实际上做得很好!干得好....我像魅力一样通读了它,直到我写评论时才意识到双关语:P kudos++ 先生!

标签: javascript string algorithm performance


【解决方案1】:

有一个答案Here 处理快速改组字符串的方法。然后你需要做的就是像你一样取下第一个和最后一个字母,使用这种方法来打乱字符串,然后将你的第一个和最后一个字母重新粘上。

为了完整起见,我会检查您得到的答案是否与原始答案不同,以防万一,并检查字符串是否超过 3 个字符,因为这些字符是您的要求所独有的。

这应该比你已经拥有的快得多,因为你的随机洗牌一直在花时间!

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-08-03
    • 1970-01-01
    • 2017-05-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-01-03
    • 2021-03-18
    相关资源
    最近更新 更多