Search

Categories

 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Send mail to the author(s) E-mail

# Thursday, December 16, 2010
( Euler )

Find the largest Product.. I got product wrong initially.  I summed instead.  Unit testing was great as when I realised my mistake was an easy fix, and had confidence in the code.

 

[TestClass]
public class UnitTest1
{
[TestMethod]
public void findGreatestProductOf5ConsecutiveDigitsInSimpleString()
{
string stringOfNumbers = "1111112341111";
ProductFinder productFinder = new ProductFinder();
int result = productFinder.findGreatestProduct(stringOfNumbers);
Assert.AreEqual(11, result);

}

[TestMethod]
public void findGreatestProductOf5ConsecutiveDigitsInLongString()
{
string stringOfNumbers = "731671765313306249192251196744265747423553...";
ProductFinder productFinder = new ProductFinder();
int result = productFinder.findGreatestProduct(stringOfNumbers);
Assert.AreEqual(123, result);
}
}

public class ProductFinder
{
public int findGreatestProduct(string stringOfNumbers)
{
//try first 3
int lengthOfString = stringOfNumbers.Count();
List<int> listOfResults = new List<int>();

char[] numbers = stringOfNumbers.ToArray();
for (int i = 0; i < lengthOfString-6; i++)
{
int first = Convert.ToInt32(stringOfNumbers.Substring(i, 1));
int second = Convert.ToInt32(stringOfNumbers.Substring(i+1, 1));
int third = Convert.ToInt32(stringOfNumbers.Substring(i+2, 1));
int fourth = Convert.ToInt32(stringOfNumbers.Substring(i+3, 1));
int fifth = Convert.ToInt32(stringOfNumbers.Substring(i+4, 1));

int result = first * second * third * fourth * fifth;
listOfResults.Add(result);
}

int largestProduct = listOfResults.Max();
return largestProduct;
}
}

All comments require the approval of the site owner before being displayed.
Name
E-mail
Home page

Comment (Some html is allowed: a@href@title, strike) where the @ means "attribute." For example, you can use <a href="" title=""> or <blockquote cite="Scott">.  

Enter the code shown (prevents robots):

Live Comment Preview