I'm still learning c#, and I need my code to only run less than 2 seconds to be accepted. I have a look and say sequence and after the last number is found, the code sums it all up, and it takes so long if the element in the sequence is big.
Example:
Input: 2
Output: takes less than a second
Input: 50
Output: takes 4 or so seconds.
I have only tried doing is changing foreach loops into for loops. I don't know what else to change. Anyone can point me in the right direction? Thanks all.
namespace SumOfLookAndSaySequence
{
class Program
{
static void Main(string[] args)
{
string input = Console.ReadLine();
if (Int32.TryParse(input, out int nthTerm) && nthTerm > 0)
{
string lastSequence = GetSequence(nthTerm).Last();
char[] digits = lastSequence.ToCharArray();
int[] itemToSum = new int[digits.Length];
int result = 0;
for(int i = 0; i < digits.Length; i++)
{
itemToSum[i] = int.Parse(digits[i].ToString());
result = result + itemToSum[i];
}
Console.WriteLine(lastSequence);
Console.WriteLine(result);
}
}
static IEnumerable<string> GetSequence(int nthTerm)
{
List<string> sequence = new List<string>() { "1" };
for(int i = 1; i < nthTerm; i++)
{
sequence.Add(GetNextNumberSequence(sequence[i - 1]));
}
return sequence;
}
static string GetNextNumberSequence(string number)
{
StringBuilder stringBuilder = new StringBuilder();
int count = 1;
char digit = number[0];
for(int i = 1; i < number.Length; i++)
{
if(number[i] == digit)
{
count++;
}
else
{
stringBuilder.Append(string.Concat(count, Char.GetNumericValue(digit)));
count = 1;
digit = number[i];
}
}
stringBuilder.Append(string.Concat(count, digit));
return stringBuilder.ToString();
}
}
}