【发布时间】:2016-03-17 12:48:40
【问题描述】:
我有一个任务,就是打乱一个大于 3 个字母的单词。
打乱后的单词不能和原来的相等,而且单词的首尾字母要保持一致。
例如,单词stack,可能会给出以下结果之一:
- satck
- scatk
- stcak
- sactk
- 等
虽然像is 或hey 这样的词会因为太小而保持不变。
我的尝试如下所示。我有一个 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