C#C
C#3y ago
AdiZ

✅ Advent of Code Day 1 - Issue with Chars

For this problem, you essentially have to find the first and last digit contained in each line, so for a line
271lonepxp2flbmbz
the first digit would be
2
and the last digit
2
as well. Put 'em together, you get
22
. Now you have to find that value for each of the 1000 lines provided and add them all together.

string input = """
9sixsevenz3
seven1cvdvnhpgthfhfljmnq
6tvxlgrsevenjvbxbfqrsk4seven
9zml
""";

int sum = 0;
foreach(string word in input.Split())
{
    List<int> nums = [];
    foreach(char ch in word)
    {
        if(Char.IsDigit(ch))
        {
            nums.Add(Convert.ToInt32(ch - '0'));
        }
    }

    int firstNumber = nums[0];
    int lastNumber = nums[^1];
    int fullNumber = firstNumber * 10 + lastNumber;
    sum += fullNumber;
}

Console.WriteLine(sum);

This is my code. However, I just keep getting an
Index Out of Range
error on the line that says
int firstNumber = nums[0];
and I just don't get why. I originally had the code a lot more condensed but I expanded it to debug and that appears to be where the issue is. Naturally I initially thought that nothing was being added to the array, but so far I can't figure out why that would be. I'm going to go and
Console.WriteLine
nums
right now to see if it actually contains anything, but either way I'd appreciate it if someone could help me see what I did wrong here.
Was this page helpful?