I’m learning C# and trying to solve the following problem:
Return the longest subarray of repeating members e.g. if the array is {1,2,2,3,4,4,4} I should return {4,4,4}. I tried to do this but it returns the first subarray and not the longest. What I know about C# so far:
- Loops
- Conditionals
- Arrays
Any ideas ?
EDIT : My code so far
EDIT : Yes I do know something about multidemensional arrays
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Sequence
{
class Sequence
{
static void Main(string[] args)
{
Console.Write("Enter size:");
int size1 = int.Parse(Console.ReadLine());
int[] array1 = new int[size1];
for (int i = 0; i <= size1-1; i++)
{
Console.Write ("Ënter Number:");
array1[i]=Int32.Parse(Console.ReadLine());
}
int bestLenght = 0;
int bestStart = 0;
int lenght = 0;
int start=0;
for (int i = 0; i < size1 - 2; i++)
{
if (i == 0 && array1[i] == array1[i + 1])
{
start = 0;
lenght = 2;
if (bestLenght < lenght)
{
bestLenght = lenght;
bestStart = 0;
}
}
else if (i != 0 && lenght != 0 && array1[i] == array1[i - 1] && array1[i + 1] == array1[i])
{
lenght++;
if (bestLenght < lenght)
{
bestLenght = lenght;
bestStart = start;
}
}
else if (i != 0 && array1[i - 1] != array1[i] && array1[i] == array1[i + 1])
{
start = i;
lenght = 2;
if (bestLenght < lenght)
{
bestLenght = lenght;
bestStart = start;
}
}
else
{
lenght = 0;
}
}
Console.WriteLine(bestLenght);
}
}
}
Cureently I’m trying just to return the lenght of the longest array
EDIT: The problem with your code is it doesn’t deal with the edge case when the longest list is the last sublist
Change
To Read
Alternatively
You can do this with a linq Agregate
What this essentially does is iterate over the collection using a Tuple to store 2 lists,
Item1represents the longest previous sequence,Item2represents the current sequence.For each item, if the current sequence is not empty and the first item is different then we are in a new sublist so check the length of last sequence, if longer that previous max we replace previous max otherwise just clear the list.
The final part of the agregate checks which of the two lists are longer (as if the longests subcollection is the last the Item1 length check won’t have happened.
This code could be turned into a generic function to handle any type as follows.
or even as an extension function
allowing you to do
var longest= new[] {1,2,2,3,4,4,4}.LongestSubList();