第n个最长的字符串分拣 [英] nth Longest String Sortation

查看:240
本文介绍了第n个最长的字符串分拣的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经写了code用于确定一个字符串数组的第n个最长的字符串。下面我从codewars卡塔上市的测试用例。

I have written code for determining the nth longest string in an array of strings. Below I have test cases listed from the Codewars kata.

说明实施在那里你会得到一个字符串数组,然后数组中返回第n个最长的字符串函数最长(数组,N)。例如ARR = ['你好','世界','codewars','Katas'] N = 3;应该返回世界,因为codewars'长度= 8,'你好'长度= 5,所以这是第二个最长的单词,然后'世界'(虽然也是5字长,世界是继你好'在数组)。当字具有相同的长度,将它们在它们在阵列中存在的顺序。阵列将永远是空的,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'结尾的数组。我对分拣code线似乎放置'F'在此测试案例的零的位置。我不明白为什么。

I have passed all of the codewars test cases with exception to the last with the array ending in 'l'. My line of code for sortation seems to place the 'f' at the zeroth position for this test case and I don't understand why.

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

我似乎无法弄清楚,为什么我的排序函数将F在当'L'被添加到字符串数组的末尾零的位置。

I cant seem to figure out why my sort function puts "f" at the zeroth position when the 'l' is added to the end of the string array.

推荐答案

您使用内置的排序功能,也许这功能更改排序的算法,根据您的阵列由不与相同长度的字符串相同的行为结束了。也许连这个都依赖于浏览器。

You use the built-in sort function, maybe this function change the algorithm of sort depending of your array ending up by not having the same behaviour with same length strings. And maybe even this is browser dependant.

我建议你使用库确定的排序函数来改变这种(快速排序,无论...)。并检查是否该再次发生。

I suggest you to change this by using a library with a determined sort function (quicksort, whatever...). And check if that happen again.

这篇关于第n个最长的字符串分拣的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆