问题
I have for homework the exercise: Write a program that finds the maximal sequence of equal elements in an array. Example: {2, 1, 1, 2, 3, 3, 2, 2, 2, 1} = {2, 2, 2}. I came up with this:
Console.WriteLine("Enter array lenght");
int arrLenght = int.Parse(Console.ReadLine());
int[] arr = new int[arrLenght];
Console.WriteLine("Enter array elements");
for (int i = 0; i < arr.Length; i++)
{
arr[i] = int.Parse(Console.ReadLine());
}
for (int i = 0; i < arr.Length; i++)
{
if (arr[i] == arr[i + 1] && arr[i] == arr[i + 2])
{
Console.WriteLine("Maximal sequence of numbers is: {0},{1},{2}",arr[i],arr[i+1],arr[i+2]);
break;
}
}
This works only if the sequence is exactly 3 numbers long. I have to search the array and find the largest sequence but i don't know how to code this. I'm sorry if the question is silly but i am a newbie and i couldn't find solution anywhere else. Thanks
回答1:
If you are looking for elegance then use Linq
var seq = new int[] {2, 1, 1, 2, 3, 3, 2, 2, 2, 1};
int[] max = seq.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();
That's why I ♥ Linq
回答2:
With Linq:
int count = seq.Count();
int[] maxSeq = seq
.Select((i, index) => new{
Item = i, index,
PrevEqual = index == 0 || seq.ElementAt(index - 1) == i,
NextEqual = index == count - 1 || seq.ElementAt(index + 1) == i,
})
.Where(x => x.PrevEqual || x.NextEqual)
.GroupBy(x => x.Item)
.OrderByDescending(g => g.Count())
.First().Select(x => x.Item).ToArray();
Explanation.
- select an anonymous type with a
bool
property that indicates if it's the same value as the previous - since we're only interested in those, restrict the query with
Where
GroupBy
the elements with equal values- then order by the count of each group(descending)
- select the values of the first group(the largest)
- create a new array from the values
Demo
回答3:
Try with this method:
int MaximimalSequence<T>(IList<T> list, out T value)
{
T aux = default(T);
value = default(T);
int max = 0, hist = 0;
bool first = true;
foreach (var i in list)
{
if (!first && aux.Equals(i))
{
max++;
}
else
{
first = false;
max = 1;
}
if (hist < max)
{
hist = max;
value = i;
}
aux = i;
}
return hist;
}
To call it:
int value;
var maximumSequence = MaximimalSequence<int>(new List<int> { 2, 1, 1, 2, 3, 3, 2, 2, 2, 1 }, out i);
回答4:
Without completely giving you the answer to your question I can suggest that you take a look at LINQ as there would definitely be some simple ways of figuring this out. You could start by looking at the Group
, Count
, OrderBy
and Select
extension methods which could get you the answer.
回答5:
Since that is a homework maybe there is a need to build an algorythm
int[] arr = new int[30];//your array
Random rand = new Random(100);
int maxCount = 0, curCount, value = 0;
for (int i = 0; i < arr.Length; i++)
arr[i] = rand.Next(15);//fill the aray with random values
arr = arr.OrderBy(a => a).ToArray();
for (int i = 0; i < arr.Length; i++)
{
curCount = 1;//found new value. and now count == 1
for (int j = i+1/*search from next array element*/;
j < arr.Length-1/*to the end*/;
j++)
{
if (arr[i] == arr[j])
curCount++;//counts the count
else
break;//met new value
}
if (curCount > maxCount)//we've found new sequence
{
maxCount = curCount;//new sequence length
value = arr[i];//sequence values
i += maxCount;//we don't need to watch the sequence again
}
}
I have no VS in my hands right now to check this, so I hope that works =) Anyway there is an idea
回答6:
This is a problem that can be solved with a single iteration of the sequence. It is important to make sure that the algorithm works in all the cases, included when the maximal sequence is at the end of the sequence.
private static IEnumerable<int> GetMaxSequence(IList<int> seq)
{
if (seq == null || seq.Count == 0)
{
return new List<int>();
}
int value = seq[0];
int currentSequenceStartIndex = 0;
int currentSequenceLength = 1;
int maxSequenceStartIndex = 0;
int maxSequenceLength = 0;
for (int i = 1; i < seq.Count; i++)
{
if (seq[i] == value)
{
currentSequenceLength++;
continue;
}
if (currentSequenceLength > maxSequenceLength)
{
maxSequenceLength = currentSequenceLength;
maxSequenceStartIndex = currentSequenceStartIndex;
}
currentSequenceStartIndex = i;
currentSequenceLength = 1;
value = seq[i];
}
if (currentSequenceLength > maxSequenceLength)
{
maxSequenceLength = currentSequenceLength;
maxSequenceStartIndex = currentSequenceStartIndex;
}
return seq.Skip(maxSequenceStartIndex).Take(maxSequenceLength);
}
回答7:
// create two list holding ints. One for the temporary value and one for the longest sequence
List<int> longestSequence = new List<int>();
List<int> temp = new List<int>();
// create count to count how many elements are holding the same value
// and counter to assign this value when max is reached
int count = 0;
int counter = 0;
// with for loop compare every element with the elements that follow it
for (int i = 0; i < arr.Length - 1; i++)
{
int nextElement = i+1; // element that follows
count = 0; // ignore for now see the end of the for loop
temp.Clear(); // ignore for now see the end of the for loop
temp.Add(arr[i]); // add the compared element in to the temp list
// while the value is the same as following element add this to the temporary list
// and add count (count++)
while (arr[i] == arr[nextElement])
{
temp.Add(arr[nextElement]);
nextElement++;
count++;
}
// after that see if the count is bigger than counter (maximum amount of elements so far)
// it is set to 0 at the beginning
if (count > counter)
{
longestSequence.Clear();
// if it is bigger assign count value to counter
counter = count;
// and copy the temporary list to the longestSequence list
for (int k = 0; k < temp.Count; k++)
{
longestSequence.Add(temp[k]);
}
}
// at the beggining of the for loop the count will be set to 0 again
// and the temporary list will be cleared
}
Console.WriteLine();
// print the longestSequence list
foreach (int element in longestSequence)
{
Console.Write(element + " ");
}
Console.WriteLine();
回答8:
static int num;
static void Main(string[] args)
{
int[] array;
Console.Write("enter the size of array : ");
int input = int.Parse(Console.ReadLine());
int[] temp;
temp = new int[10];
int a = 0;
int count = 0;
array = new int[input];
for (int i = 0; i < input; i++)
{
Console.Write("enter value ( " + i + ", " + input+") :");
array[i] = int.Parse(Console.ReadLine());
}
for (int i = 0; i < 20; i++)
{
for (int j = 0; j < array.Length; j++)
{
if (i == array[j])//compare i with array
{
count++;
if (a < count)//if greator found
{
a = count;
num = i;
}
}
else
{
count = 0;
}
}
}
Console.WriteLine(num +" repeated " + a +" times");
Console.ReadKey();
}
回答9:
//programmer : Hamza Jany //P - Lang = C#
static int num;
static void Main(string[] args)
{
int[] array;
Console.Write("enter the size of array : ");
int input = int.Parse(Console.ReadLine());
int[] temp;
temp = new int[10];
int a = 0;
int count = 0;
array = new int[input];
for (int i = 0; i < input; i++)
{
Console.Write("enter value ( " + i + ", " + input+") :");
array[i] = int.Parse(Console.ReadLine());
}
for (int i = 0; i < int.MaxValue; i++)
{
for (int j = 0; j < array.Length; j++)
{
if (i == array[j])//compare i with array
{
count++;
if (a < count)//if greator found
{
a = count;
num = i;
}
}
else
{
count = 0;
}
}
}
Console.WriteLine(num +" repeated " + a +" times");
Console.ReadKey();
}
回答10:
static void Main(string[] args)
{
int[] array1 = { 1, 1, 1, 2, 3, 2, 2, 2, 2, 1 };
int start = 0;
int length = 0;
int bestStart = 0;
int bestLength = int.MinValue;
for (int i = 0; i < array1.Length - 1; i++)
{
if ((i == 0) || (array1[i] != array1[i - 1]))
{
start = i;
}
if(array1[start] == array1[start + 1])
{
length++;
if (length > bestLength)
{
bestLength = length;
bestStart = start;
}
}
else
{
length = 0;
}
}
Console.Write("The best sequence is :");
for (int i = bestStart; i < bestLength + bestStart; i++)
{
Console.Write(" " + array1[i]);
}
}
/*
This will give : The best sequence is : 2 2 2 2
*/
回答11:
Following is my solution to the problem in C#. I tried to put as less code as possible to make it more readable and understandable.
public static void Main(string[] args)
{
int[] intList = new int[] { 1, 1, 2, 2, 3, 3, 3, 4, 4, 5 };
foreach (var item in intList) {
Console.Write(item + " ");
}
#region Calculating sequence and printing details
int length = 1, start = 0, finalIndx = 0,
bigSeqNum = 0, finalLen = 0;
for (int i = 1; i < intList.Length; i++) {
if (intList[i] == intList[start]) {
length++;
if (length > finalLen) {
finalLen = length;
finalIndx = start;
bigSeqNum = intList[start];
}
} else {
start = i;
length = 1;
}
}
Console.WriteLine("\nBig Seq. Num: " + bigSeqNum);
Console.WriteLine("Start index: " + finalIndx);
Console.WriteLine("Length: " + finalLen);
Console.WriteLine();
#endregion
}
回答12:
static void Main(string[] args)
{
Console.WriteLine("enter length of the array");
int n = int.Parse(Console.ReadLine());
int[] myarray = new int[n];
for (int i = 0; i < n ; i++)
{
Console.WriteLine("enter value of array" + " " + i);
myarray[i]=int.Parse(Console.ReadLine());
}
int length = 1;
int start = 0;
int bestlength=0;
int beststart=0;
for (int i = 1; i < n; i++)
{
if (myarray[i - 1] == myarray[i])
{
length++;
continue;
}
if (bestlength<length)
{
bestlength = length;
beststart = start;
}
length = 1;
start = i;
}
Console.WriteLine("the best sequence is");
for (int j = beststart; j < bestlength + beststart; j++)
{
Console.Write(myarray[j] + ",");
}
}
}
}
来源:https://stackoverflow.com/questions/13745241/maximal-sequence-of-equal-elements-in-an-array