Найти в массиве целых чисел самую длинную не повторяющуюся последовательность - C#
Формулировка задачи:
Необходимо найти самую длинную серию. Серией называется последовательность различных чисел. Язык C#
Решение задачи: «Найти в массиве целых чисел самую длинную не повторяющуюся последовательность»
textual
Листинг программы
using System;
using System.Text.RegularExpressions;
using System.Collections.Generic;
namespace Cyb6 {
class Program {
static int[] readArray(string strMsg, int i) {
Console.WriteLine(strMsg);
if (i < 0) {
i = int.Parse(read("Укажите количество элементов в одномерном массиве - ",@"^\s*[1-9][0-9]*\s*$"));
}
int[] aArray=new int[i];
for (int j = 0; j < i; j++)
aArray[j] = int.Parse(read(string.Format("\t{0}\t", j+1)));
return aArray;
}
static string read(string strMsg=null, string strPattern=null, object val=null) {
bool isRepeat=true;
string strInput=null;
while (isRepeat) {
if (strMsg!=null)
Console.Write(strMsg, val);
ConsoleColor pColor=Console.ForegroundColor;
Console.ForegroundColor=ConsoleColor.Yellow;
strInput=Console.ReadLine();
Console.ForegroundColor=pColor;
if (strInput.Length==0 && val!=null) {
isRepeat=false;
strInput=string.Format("{0}", val);
} else if (strPattern!=null)
strInput=Regex.Match(strInput, strPattern).Value;
if (strInput.Length>0)
isRepeat=false;
}
return strInput;
}
static void Main() {
//Спрашиваем массив
int[] aA = readArray("Заполните целочисленный массив A:", -1);
if (aA == null)
return;
//Найдем самую длинную серию
int l=aA.Length, len=0, startInd=0;
int maxLen=0, startIndMax=0;
for (int i=0; i<l; i++) {
for (int j=i-1; j>=i-len; j--)
if (aA[i]==aA[j]) {
if (maxLen<len) {
maxLen=len;
startIndMax=startInd;
j=i-len;
}
len=0;
startInd=i;
}
len++;
}
if (maxLen<len) {
maxLen=len;
startIndMax=startInd;
}
Console.WriteLine("Самая длинная серия из {0} чисел:", maxLen);
for (int i=0; i<maxLen;i++)
Console.WriteLine("\t{0}\t{1}", i+startIndMax+1, aA[i+startIndMax]);
Console.ReadLine();
}
}
}