0

I'm trying to solve a simple algorithm a specific way where it takes the current row and adds it to the top most row. I know there are plenty of ways to solve this but currently I have a text file that gets read line by line. Each line is converted to an sbyte (there's a certain reason why I am using sbyte but it's irrelevant to my post and I won't mention it here) and added to a list. From there, the line is reversed and added to another list. Here's the code I have for that first part:

        List<List<sbyte>> largeNumbers = new List<List<sbyte>>();
        List<string> total = new List<string>();
        string bigIntFile = @"C:\Users\Justin\Documents\BigNumbers.txt";


        string result;

        StreamReader streamReader = new StreamReader(bigIntFile);

        while ((result = streamReader.ReadLine()) != null)
        {
            List<sbyte> largeNumber = new List<sbyte>();
            for (int i = 0; i < result.Length; i++)
            {
                sbyte singleConvertedDigit = Convert.ToSByte(result.Substring(i, 1));
                largeNumber.Add(singleConvertedDigit);
            }
            largeNumber.Reverse();
            largeNumbers.Add(largeNumber);
        }

From there, I want to use an empty list that stores strings which I will be using later for adding my numbers. However, I want to be able to add numbers to this new list named "total". The numbers I'll be adding to it are not all the same length and because so, I need to check if an index exists at a certain location, if it does I'll be adding the value I'm looking at to the number that resides in that index, if not, I need to create that index and set it's value to 0. In trying to do so, I keep getting an IndexOutOfRange exception (obviously because that index doesn't exist). :

        foreach (var largeNumber in largeNumbers)
        {
            int totalIndex = 0;

            foreach (var digit in largeNumber)
            {
                if (total.Count == 0)
                {
                    total[totalIndex] = digit.ToString(); //Index out of Range exception occurs here
                }
                else
                {
                    total[totalIndex] = (Convert.ToSByte(total[totalIndex]) + digit).ToString();
                }

                totalIndex ++;
            }
        }

I'm just at a loss. Any Ideas on how to check if that index exists; if it does not create it and set it's underlying value equal to 0? This is just a fun exercise for me but I am hitting a brick wall with this lovely index portion. I've tried to use SingleOrDefault as well as ElementAtOrDefault but they don't seem to be working so hot for me. Thanks in advance!

justin peterson
  • 367
  • 1
  • 6
  • 17
  • You are incrementing totalIndex each iteration. This means that each iteration you want to add one additional item, right? You you could just use the List.Add method (or why not?). – usr Sep 09 '12 at 21:40
  • Yes, but I'm not using the "Add" function I want to use Addition and add the two values. The logic is not fully there yet, I just need to take care of the index out of range issue, not the addition – justin peterson Sep 09 '12 at 21:43
  • With Add I meant `total.Add(digit.toString())`. Doesn't that work? – usr Sep 09 '12 at 22:26
  • Yes it does. What I ended up doing was just checking if my index is greater than or equal to the count of items in the list and if it was I just did total.Add("0") to create a new index so I can add an underlying object further down in my code – justin peterson Sep 10 '12 at 16:20

1 Answers1

2

Depending on if your result is have small number of missing elements (i.e. have more than 50% elements missing) consider simply adding 0 to the list till you reach neccessary index. You may use list of nullable items (i.e. List<int?>) instead of regular values (List<int>) if you care if item is missing or not.

Something like (non-compiled...) sample:

// List<long> list; int index; long value
if (index >= list.Count) 
{
  list.AddRange(Enumerable.Repeat(0, index-list.Count+1);
}
list[index] = value;

If you have significant number of missing elements use Dictionary (or SortedDictionary) with (index, value) pairs.

Dictionary<int, long> items;
if (items.ContainsKey(index))
{ 
  items[key] = value;
}
else
{
  items.Add(index, value);
}
NetMage
  • 26,163
  • 3
  • 34
  • 55
Alexei Levenkov
  • 98,904
  • 14
  • 127
  • 179
  • well the collection is going to start out with 0 elements. Say the largest number is 12345 and our list we'll be adding to is just 45, the list will only have 2 elements so element [0] and element [1]. I will want to add a 0 to index[2] (which will not exist) and then add the underlying value of "3". – justin peterson Sep 09 '12 at 21:36
  • @JustinPeterson, I've added samples... probably with enough off-by-one errors and may not compile... but should be ok to show my suggestion. – Alexei Levenkov Sep 09 '12 at 21:45
  • awesome :) I get the gist of it, this gives me a way better idea on how to approach it altogether. Thanks a ton! – justin peterson Sep 09 '12 at 21:53