Reputation: 175
I'm currently working on a project that requires me to overwrite services.
I have 3 lists. List1, List2 and List3. I want all my lists to take care of any numbers in multiples of 3's.
A count will come in. If the number is 1 go to List 1. If the number is 4, go to List1. If the number is 9 go to List 3.
For example:
List1 will deal with 1, 4, 7, 10, 13, 16 etc
List2 will deal with 2, 5, 8, 11, 14, 17 etc
List3 will deal with 3, 6, 9, 12, 15, 18 etc
I hope that makes sense.
Rather than setting up tables or cases, I'd prefer a simple mathematical approach.
Thanks
Upvotes: 1
Views: 304
Reputation: 1510
Something like
var listSelector = number % 3;
switch(listSelector)
{
case 0:
list3.add(number);
break;
case 1:
list1.add(number);
break;
case 2:
list2.add(number);
break;
}
0 would land into list3 as 0 % 3 == 0
Upvotes: 0
Reputation: 1904
var lists = new[] { new List<int>(), new List<int>(), new List<int>() }; var listToDoStuffWith = lists[inputNumber % 3];
Upvotes: 0
Reputation: 48568
Simply use Modulus function. It returns remainder from division operation.
int number = 4;
int result = number % 3;
here result will be 1 which was required and so on.
This is best way to lookup numbers in multiples of 3's C#
Upvotes: 1
Reputation: 27619
You need to use modular maths. To do this you just need something like:
int listNumber = input % 3;
This will output 0, 1 or 2 for any positive integer. 0 will in this case represent list 3.
How you then use this will depend on how your Lists are stored, etc. but hopefully should be a simple exercise.
Upvotes: 2