有没有人知道该怎么做才能找到数组中的序列数?
例如,我的数组是:
var numbers:Array = new Array(banana, banana, apple, banana, banana);
我需要找到的是: *有多少次“香蕉”序列 *和每个序列的长度。
为了获得以下结果我做了什么? 2,1,2(2个香蕉,1个苹果,2个香蕉)
我尝试使用do while循环,但我想我想念一些东西。
一个简短的例子将非常感谢!
感谢名单
答案 0 :(得分:1)
var prev:String = null;
var q:int = 0;
var result:Array = new Array();
for(var i:int=0; i<numbers.length; ++i){
if(prev!=numbers[i]){
if(q>0) result.push(q);
q=1;
prev=numbers[i];
}
else ++q;
}
if(q>0) result.push(q);
这是假设香蕉等是字符串(可能是上面的错字?)。修改为其他类型的对象很简单
答案 1 :(得分:0)
真的你只想知道索引n处的字符串是否等于索引n + 1处的字符串......
var targetIndex:int = numbers.length - 1;
var results:Array = [1];
var resultsIndex:int = 0;
for(var n:int = 0; n < targetIndex; n++) {
if(numbers[n] == numbers[n+1]) {
results[resultsIndex]++;
} else {
results[++resultsIndex] = 1;
}
}
trace(results.join(','));
答案 2 :(得分:0)
function sequencesInArray(array:Array):Array {
var sequence:Array = [];
var currSequenceCount:uint = 1;
for (var i:uint = 1; i < numbers.length; i++) {
if (numbers[i - 1] != numbers[i]) {
sequence.push(currSequenceCount);
currSequenceCount = 1;
} else {
currSequenceCount++;
}
}
return sequence;
}
然后:
var banana:int = 1;
var apple:int = 2;
sequencesInArray([banana, banana, apple, banana, banana]); //returns: [2, 1, 2]
答案 3 :(得分:0)
在您未定义banana
和apple
的问题中,无论如何,我会使用map
或Dictionary
来存储键/值对,并使用键是你想要计算的字符串/对象,值是数组中出现的对象的计数器。
var objectsCounter:Dictionary = new Dictionary();
for (var key:String in numbers)
{
if ( objectsCounter[key] )
objectsCounter[key] = objectsCounter[key] + 1;
else
objectsCounter[key] = 1;
}
这样您就可以在字典中存储任何类型。
编辑:
for (var key:String in objectsCounter)
{
// iterates through each object key
}
for each (var value:Number in objectsCounter)
{
// iterates through each value
}
答案 4 :(得分:0)
我相信这就是你要找的东西:
var array:Array = [
"banana", "banana",
"apple",
"banana", "banana", "banana"
];
var sequences:Array = findSequences(array, "banana");
trace("sequences:", sequences); // prints "sequences: 2,3"
和
private function findSequences(array:Array, searchElement:*):Array
{
var sequences:Array = [];
var currentSequence:int = 0;
for each (var element:* in array) {
if (element == searchElement) {
currentSequence++;
} else if (currentSequence > 0) {
sequences.push(currentSequence);
currentSequence = 0;
}
}
if (currentSequence > 0) {
sequences.push(currentSequence);
}
return sequences;
}