gpt4 book ai didi

c# - 分析重复序列

转载 作者:行者123 更新时间:2023-12-03 08:42:58 25 4
gpt4 key购买 nike

假设我有一个包含以下内容的整数数组:[1,2,2,3,1,5,4,4,1,1,1]

我如何编写一个脚本,根据重复的邻居将数组划分为子数组?

例如:[1],[2,2],[3],[1],[5],[4,4],[1,1,1]

更好的是接收一个元组数组,表示值、第一次出现的位置和重复次数,例如:[ (1, 0, 1), (2, 1, 2 ), (3, 3, 1), (1, 4, 1) (5, 5, 1), (4, 6, 2), (1, 8, 3)]

这是我最初尝试编写的内容,但似乎不起作用:

        var array = handStacks;
var analysis = new List<(int, int, int)>();
var subArrayStart = 0;
var subArraySize = 0;
for(var x=0; x < array.Length; x++){
var curr = array[x];

// Last element
if(x == array.Length - 1){
if(subArrayStart == 0) subArraySize++;

analysis.Add( (subArraySize, array[subArrayStart], subArrayStart) );

}
else if(curr != array[subArrayStart]) { // New sub array

analysis.Add( (subArraySize, array[subArrayStart], subArrayStart) );

subArraySize = 1;
subArrayStart = x;
}

subArraySize++;
}

最佳答案

对于您的“更好的解决方案”,我建议:

    int[] arr = { 1, 2, 2, 3, 1, 5, 4, 4, 1, 1, 1 };
var targetsList = new List<(int,int,int)>();
int currentValue = arr[0];
int position = 0;
int repeats =0;
for (int i = 0; i < arr.Length; i++)
{
if (arr[i]!=currentValue)
{
targetsList.Add((currentValue,position,repeats));
position = i;
currentValue = arr[i];
repeats = 0;
}
repeats++;
}
targetsList.Add((currentValue,position,repeats));
foreach(var target in targetsList)
{
Console.WriteLine($"Value {target.Item1},Position {target.Item2},Repeats {target.Item3}");
}

关于c# - 分析重复序列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62280833/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com