循环创建相同长度字符串的数组
Posted
技术标签:
【中文标题】循环创建相同长度字符串的数组【英文标题】:loop to create array of arrays of same-length strings 【发布时间】:2020-02-12 12:09:34 【问题描述】:我正在尝试创建一个数组数组,这些数组根据它们的长度(字符串)分组,如下面的数组:
var testA = ["carts","carts","cars","cars","ca","ca", "ca","a","a","a","a"];
会变成:
var sortedArrays = [["carts","carts"], ["cars","cars"],["ca","ca","ca"], ["a","a","a","a"]]
我目前正在尝试下面的循环,但根本无法让它工作。我知道这将是一件简单的事情,但我花了很长时间试图完成它,但事实证明这非常令人沮丧。
var testA = ["carts","carts","cars","cars","ca","ca", "ca","a","a","a","a"];
var sortedArrays = [];
for(i=0; i < testA.length; i++)
longestWord = 0;
wordHolder = []
wordHolder.push(testA[i])
if (testA[i].length > longestWord)
longestWord = testA[i].length
wordHolder.push(testA[i])
sortedArrays.push(wordHolder)
任何帮助将不胜感激
【问题讨论】:
javascript?另外,我们得到 testA 已排序? wordHolder = [] 无法在每次看到一个新词(可能是同一个词)时设置 【参考方案1】:下面的代码怎么样(Swift,但用其他语言重新编写它应该很容易):
let testA = ["carts","carts","cars","cars","ca","ca", "ca","a","a","a","a"]
var maxLength = 0
for string in testA
if string.count > maxLength maxLength = string.count
var sortedArrays: [[String]] = []
for nextLength in 0 ... maxLength
let invertedLength = maxLength - nextLength
let nextArray = testA.filter $0.count == invertedLength
sortedArrays.append(nextArray)
此代码还创建空数组,当然可以轻松跳过。
当然,问题是您的要求是什么。上面的代码很紧凑,但对于大型数组来说速度并不快... 对于大数组,最好先对testA进行排序,然后提取元素。
【讨论】:
【参考方案2】:坚持使用 java 脚本,我能够做到以下几点。我的假设是单词已经按长度降序排序,并且每个长度只有一个单词。那是基于你在做什么。我认为发生的事情是每次循环都被初始化或重置太多。
var testA = ["carts", "carts", "cars", "cars", "ca", "ca", "ca", "a", "a", "a", "a"];
var sortedArrays = [];
var wordHolder = []; // took outside loop to ensure initialized
var curLength = testA[0].length;// assuming here that testA not empty
for (var i = 0; i < testA.length; i++)
if (testA[i].length === curLength) // more of the same
wordHolder.push(testA[i]);
else // new block starts
curLength = testA[i].length;
sortedArrays.push(wordHolder);
// alert (wordHolder)
// alert (sortedArrays)
wordHolder = [];
wordHolder.push(testA[i]);
sortedArrays.push(wordHolder);// add the last one
【讨论】:
这成功了!感谢 Jeremy,尤其是注释,它们为我澄清了一些事情。以上是关于循环创建相同长度字符串的数组的主要内容,如果未能解决你的问题,请参考以下文章