微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

如何在for循环内的数组值中进行+5或任何+数字跳转?

如何解决如何在for循环内的数组值中进行+5或任何+数字跳转?

所以我有一列由数字组成的数据,我必须在其中找到相同数字的 5 个实例。

所以,例如,8,8,9,5,6,4,7,2,3,等等。在这个 8 中已经发生了 9 次。 所以我只想增加一次计数,因为即使有 9 个 8,我的代码正在做的是取前 8 个并获得 5 个连续的数字正在增加。然后它需要下一个 8 并增加计数等等,计数变为 5,但我希望它是 1。我想要的是任何数字的第一次出现作为基值并取 5 个连续数字并增加计数.然后取第 6 个 8 并计算是否有 5 个连续的 8 或该特定数字。因此,例如 8,1,1。这里的计数应该是4。 >

   **count=0;
count1=0;
for i=1:length(data)-4
for j=i+1:i+4
if data(i)~=data(j)
count1=0;
break;
else
count1=count1+1;
end
if count1==5    % line 0
count=count+1;
%data(i,1)=data(i+5,1); //line 1   <=comment
%data(i)=data(i+5);     //line 2   <=comment
else
continue;
end
end**

If(count_consecutive==5){
count_main=count_main+1; ...
a[i]=a[i+5];// continue for the base value. It should skip all the numbers that were counted in the consecutive count one and take the next number as the base for counting the consecutive numbers}

任何语言的逻辑都可以,因为我的错误在于逻辑 谢谢你的帮助。将不胜感激:)

额外的细节

所以第一个只有 5 个连续的 8 以我指定的方式。因此,第一个将有一个输出计数 =1 。在第二个中,相同起始号码的5个连续号码中有4个。因此输出将是 4,我可以给出的另一个例子是 8,8(十个 8),6. 在此,计数应该是 3,因为它有 10 个 8 将计数增加到 2 和另外 5 个连续的 6 增加计数一次.总数为 3。

现在的错误是我无法将数组索引从 a[i] 跳转到 a[i+5]。所以第一个只有 5 个连续的 8 以我指定的方式。因此,第一个将有一个输出计数 =1 。在第二个中,相同起始号码的5个连续号码中有4个。因此输出将是 4,我可以给出的另一个例子是 8,6. 在此,计数应该是 3,因为它有 10 个 8 将计数增加到 2 和另外 5 个连续的 6 增加计数一次.总计数为 3。我的问题是,当我的条件得到满足时,我无法在 for 循环中跳过/跳转数组索引从 x 到 x+5

解决方法

计算包含相同元素 consecutive 的子序列的长度会更简单,一旦子序列完成,就将结果计数器增加由子序列中的 N 个元素组成的组数: result += consecutive / n

public static int countConsecutiveN(int n,int ... arr) {
    if (null == arr || arr.length < n) {
        return 0;
    }
    int result = 0;
    int previous = arr[0];
    int consecutive = 1;
    for (int i = 1; i < arr.length; i++) {
        if (arr[i] == previous) {
            consecutive++;
        } else { // consecutive sequence ended
            result += consecutive / n; // increment by the count of N elements in the subsequence
            consecutive = 1;
        }
        previous = arr[i];
    }
    // check the trailing subsequence
    result += consecutive / n;

    return result;
}

测试

System.out.println(countConsecutiveN(5,8,// six 8s
        9,9,// ten 9s - 2 groups
        5,5,// five 5s
        1,1,2,4,3,6,7,// seven 2s
        1,1             // six 1s
));

输出

6
,

我附上了 Matlab 中的代码(也适用于 Octave):

vector = [8,1]

count = 1;
result = 0;
for i = 2:length(vector)
    if vector(i-1) == vector(i)
        count = count+1;
    else
        count = 1;
    end
    if count == 5
        result = result+1;
        count = 1;
    end
end

主要是计算一个值出现的次数,如果出现5次就增加结果。

,

如果你想计算最小长度为 N 的相等值,在 Matlab 中,这可以很容易地用 diff(连续差异)和 find(非零条目的索引):

N = 5; % mininum desired run length
x = [8,1];
result = sum(diff(find([true diff(x)]))>=N);

如果运行 在达到长度 N 时立即结束(例如,11 个连续相等的值算作 两次 运行长度 N=5):

result = sum(floor(diff(find([true diff(x)]))/N));

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。