【问题标题】:nth Longest String Sortation第 n 个最长的字符串排序
【发布时间】:2016-08-28 15:45:54
【问题描述】:

我编写了用于确定字符串数组中第 n 个最长字符串的代码。下面我列出了 Codewars kata 中的测试用例。

说明实现函数longest(array,n),你将得到一个字符串数组,然后返回该数组中第n个最长的字符串。例如arr = ['Hello','World','Codewars','Katas'] n = 3;应该返回 'World' 因为 'Codewars' 长度 = 8 , 'Hello' 长度 = 5,所以这是第二长的单词,然后是 'World' (虽然单词长度也是 5,'World' 在 'Hello' 之后大批)。当单词具有相同的长度时,按照它们在数组中的存在顺序来处理它们。数组永远不会为空,并且 n > 0 永远。

Test.assertEquals(longest(['Hello','World','Codewars','Katas'],3),'World');
Test.assertEquals(longest(['Hello','World','Codewars','Katas'],4),'Katas');
Test.assertEquals(longest(['aa', 'bb', 'cc', 'dd', 'eee', 'b', 'f', 'ff', 'hhh', 'gggg'],4),'aa');
Test.assertEquals(longest(['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'k'],1),'a');
Test.assertEquals(longest(['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'k','l'],1),'a');

我已经通过了所有的 codewars 测试用例,但最后一个例外,数组以“l”结尾。我的排序代码行似乎将“f”放在了这个测试用例的第零位,我不明白为什么。

function longest(arr, n) {
  arrLength = [];
  arr.sort(function(a, b){return b.length - a.length});
  console.log(arr);
  arr.forEach(function(numArray){
    return arrLength.push(numArray.length);
  });
  return arr[n-1];
}

console.log(longest(['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'k'],1));
// Sorted Array: ["a", "b", "c", "d", "e", "f", "g", "h", "i", "k"]
// returns a
console.log(longest(['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'k', 'l'],1));
// Sorted Array: ["f", "a", "c", "d", "e", "b", "g", "h", "i", "k", "l"]
// returns f

我似乎无法弄清楚为什么我的排序函数在将“l”添加到字符串数组的末尾时将“f”放在第零位。

【问题讨论】:

  • 您的排序功能正在测量长度。当所有物品的长度相同时,您为什么会期望任何特定的顺序?
  • 非常感谢您的帮助。我非常感谢您对我的问题的贡献...

标签: javascript arrays string sorting string-length


【解决方案1】:

在 MSIE 上运行良好。

对 Microsoft Internet Explorer(任何版本)的快速测试为您提供的功能提供以下结果:

>> longest(['a','b','c','d','e','f','g','h','i','k'],1); 
 a,b,c,d,e,f,g,h,i,k 
"a" 
>> console.log(longest(['a','b','c','d','e','f','g','h','i','k','l'],1)); 
 a,b,c,d,e,f,g,h,i,k,l 
 a 
>> console.log(longest(['a','b','c','d','e','f','g','h','i','k','l',"m","n"],1)); 
 a,b,c,d,e,f,g,h,i,k,l,m,n 
 a 

p.s.:所有非MS浏览器都存在sort()稳定性问题。

【讨论】:

  • 是的,我正在使用 chrome。就像你说的那样, sort() 因浏览器而异。
【解决方案2】:

您使用内置的排序函数,也许这个函数会根据您的数组改变排序算法,最终导致相同长度的字符串不具有相同的行为。甚至可能这取决于浏览器。

我建议您通过使用具有确定排序功能的库(快速排序,无论如何......)来改变这一点。并检查是否再次发生这种情况。

【讨论】:

  • 这应该是评论而不是答案。
  • @bhspencer 这是一个答案:使用原生排序功能以外的其他东西。
猜你喜欢
  • 1970-01-01
  • 2019-01-18
  • 2014-08-18
  • 1970-01-01
  • 2012-01-24
  • 1970-01-01
  • 2014-02-02
  • 1970-01-01
  • 2011-05-11
相关资源
最近更新 更多