如何将数组切片分配给新数组。我试图将最大连续的相等元素分配给一个新数组。
我认为我有正确的基本逻辑,但无法切换到新数组。这是Arrays中的练习4 - 使用c#进行计算机编程的基础知识。
using System;
using System.Collections.Generic;
class ArrayEx4
{
static void Main()
{
int[] testArray = { 1, 1, 2, 3, 2, 2, 2, 1 }; // Output wanted {2,2,2};
int count = 0;
int bestCount = 0;
int startArray = 0;
int endArray = 0;
int first = 0;
for (int i = 0; i < testArray.Length; i++)
{
if (testArray[i] == testArray[i+1])
{
count += 1;
i = first;
if (count > bestCount)
{
count = bestCount;
startArray = first;
endArray = first + bestCount;
}
}
int[] bestArray = testArray.Slice(startArray, endArray);
Console.WriteLine("The best array is {0}", bestArray);
}
}
}
我收到指令错误,所以我添加了System.Collections.Generic;但我仍然遇到这个错误。
C:\Users\Sayth\Documents\Scripts>csc ArrayEx4.cs
Microsoft (R) Visual C# Compiler version 4.0.30319.33440
for Microsoft (R) .NET Framework 4.5
Copyright (C) Microsoft Corporation. All rights reserved.
ArrayEx4.cs(28,32): error CS1061: 'System.Array' does not contain a definition
for 'Slice' and no extension method 'Slice' accepting a first argument
of type 'System.Array' could be found (are you missing a using directive
or an assembly reference?)
修改
我上面的解决方案中的逻辑从未起作用。以下是更新后的代码,包括以下答案。
using System;
using System.Linq;
class Arr4
{
static void Main()
{
int[] testArray = { 1, 1, 2, 3, 2, 2, 2, 1 }; // Output wanted {2,2,2};
int count = 0;
int bestCount = 0;
int start = 0;
int a = 0;
for(int i = 0; i < testArray.Length -1; i++)
{
while (testArray[i] == testArray[a])
{
count += 1;
a += 1;
if (count > bestCount)
{
start = i;
bestCount = count;
}
}
}
int end = bestCount + start;
Console.WriteLine("The start is {0} and count is {1}", start, bestCount);
var bestArray = testArray.Skip(start)
.Take(end - start)
.ToArray();
Console.Write("{ ");
Console.Write(string.Join(", ", bestArray));
Console.Write(" }");
}
}
答案 0 :(得分:5)
使用Linq你可以这样做:
var bestArray = testArray.Skip(startArray)
.Take(endArray - startArray)
.ToArray();
(不要忘记添加using System.Linq
)
答案 1 :(得分:2)
在c#中,您不需要手动遍历数组,只需使用LINQ。
这将为您完成工作:)
int[] testArray = { 1, 1, 2, 3, 2, 2, 2, 1 }; // Output wanted {2,2,2};
int[] maxSequence = testArray.Select((n, i) => new { Value = n, Index = i})
.OrderBy(s => s.Value)
.Select((o, i) => new { Value = o.Value, Diff = i - o.Index } )
.GroupBy(s => new { s.Value, s.Diff})
.OrderByDescending(g => g.Count())
.First()
.Select(f => f.Value)
.ToArray();
答案 2 :(得分:2)