-
Notifications
You must be signed in to change notification settings - Fork 0
/
Problem42.cs
76 lines (64 loc) · 2.26 KB
/
Problem42.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
using System.Collections.Generic;
using System.Linq;
namespace Miller.ProjectEuler.Solutions
{
/// <summary>
/// Coded triangle numbers
/// </summary>
/// <seealso cref="https://projecteuler.net/problem=42"/>
public class Problem42
{
private List<int> triangleNumbers = new List<int>() { 1, 3, 6, 10, 15, 21, 28, 36, 45, 55 };
private List<int> TriangleNumbers => triangleNumbers;
/// <summary>
/// Counts the number of "triangle words" found in <paramref name="words"/>.
/// </summary>
/// <param name="words">A comma delimited string containing words.</param>
/// <returns>
/// The number of triangle words found in <paramref name="words"/>.
/// </returns>
/// <remarks>
/// A "triangle word" is defined as a word whose value is a triangle number.
/// The word's value is derived from assigning a value to each letter based on its alphabetical position and taking the sum.
/// A triangle number is a number calculated from 0.5 * n * (n + 1)
/// </remarks>
public int Solve(string words)
{
int triangleWords = 0;
string[] wordsList = words
.Replace("\"", "")
.Split(',');
foreach (string word in wordsList)
{
int value = word.AlphabeticalSum();
triangleWords += IsTriangleNumber(value) ? 1 : 0;
}
return triangleWords;
}
private bool IsTriangleNumber(int wordValue)
{
if (triangleNumbers.Contains(wordValue))
{
return true;
}
int maxTriNumber = triangleNumbers.Last();
if (wordValue < maxTriNumber)
{
return false;
}
int index = triangleNumbers.Count() + 1;
while (wordValue > maxTriNumber)
{
int triNumber = index * (index + 1) / 2;
triangleNumbers.Add(triNumber);
maxTriNumber = triNumber;
if (wordValue == maxTriNumber)
{
return true;
}
index += 1;
}
return false;
}
}
}