Split number in pieces of particular size

Refresh

February 2019

Views

903 time

1

I have the number 33 and want to split it in pieces of 10 to get the list 30,20,10,0 and I also need the number 3 i removed.

Of course all numbers are examples, they can change.

How do I do that? The math part of my brain took a day off.

3 answers

1

This will break up an integer into chunks of any size (not just 10):

static public IEnumerable<int> BreakUpInteger(int input, int chunkSize)
{
    if(chunkSize <= 0)
    {
        throw new ArgumentException("Chunk size must be greater than zero.", "chunkSize");
    }

    if(input <= 0)
    {
        throw new ArgumentException("Input must be greater than zero.", "input");
    }

    for (var i = 1; i <= input / chunkSize; i++)
    {
        yield return i * chunkSize;
    }
}
1
List<int> Splitter(int num, int mult)
{
   if(mult<=0)
       return null;

   int sign = 1;
   if(num < 0)
   {
       num = - num;
       sign = -1;
   }
   var result = new List<int>(num / mult);

   num = num - num % mult;
   while(num >= 0)
   {
       result.Add(num);
       num -= mult;
   }
   return result;
}

But there's no fun in this. Let's try to LINQ it. I'll assume everything is positive.

Enumerable.Range((num + mult - 1) /mult).Select(x=>x*mult).Reverse();

The Range parameter is num/mult rounded up.

2

Subtract the modulus of 10 into the number from the number, then divide by ten. Create a list that increments by values of ten, and of length n/10.

Num = num - (num % 10);
list<int> stuff;
for (int i = 0; i == (num /10); i++)
     stuff.add((i*10));

It's a bit late and I had a beer, so my code may be a bit off.