Best way to lookup numbers in multiples of 3's C# - c#

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

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.

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#

var lists = new[] {
new List<int>(),
new List<int>(),
new List<int>()
};
var listToDoStuffWith = lists[inputNumber % 3];

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

Related

Check times a value is next to the same value in an array

Lets say I have this array on C#:
int myList = {1,4,6,8,3,3,3,3,8,9,0}
I want to know if a value (lets say from 0-9) is next to itself in the list and how many times. In this case, the value 3 is next to itself and it has 4 repetitions. If I have a list {0,1,2,3,4,5,5,6,7} the value 5 is next to itself and has 2 repetitions.
Repetitions have a limit of 5. No value can be repeated more than 5 times. The far I went is making if statements, but I know there's a better way of doing it.
The standard of question is not that good but writing the answer
int lastValue = myList[0];
int times = 0;
foreach (int value in myList) {
if (lastValue == value) {
times++;
}
else if (times <= 1) {
lastValue = value;
times = 1;
}
else
break;
}
You only have to iterate on your list and keep a counter that will count only the consecutive duplicate integer.
If you want a neater solution, you might look at using an open source library called morelinq (by Jon Skeet and few others) on nuget. It has useful extension methods for LINQ.
One of them is called GroupAdjacent, which is applicable to your problem.
var testList = new[] { 1, 4, 6, 8, 3, 3, 3, 3, 8, 9, 0 };
var groups = testList.GroupAdjacent(t => t);
var groupsWithMoreThanOneMember = groups.Where(g => g.Count() > 1);

Using Recursion to get combinations of Numbers in C# that equal the same sum

UPDATE: Okay I've revamped this question due to some negative people that merely want to complain rather than attempt to provide some sort of constructive help.
I know variations of this question have been asked, but I'm fairly certain mine is different.
I'm trying to do something similar to the tic tac toe Magic Box, but with a variation.
Traditionally, the Magic TicTacToe box refers to the numbers 1-9 and you're asked to arrange them in the tictactoe box in such a way that every iteration of the sets of 3 equal the same. In that sense, each run of 3 numbers would have to equal 15. With every possible direction, there's 8 sequences to test. The important part of the calculation is that the total sum of 1-9 is 45 and that divided by 3 is what tells you each run of 3 should equal 15.
Now, as I understand it, there's a form of recursion that would have to take place to run through the combinations of numbers, but I'm not quite sure how to do that. I'd like to be able to put a number (divisible by 3 and 9) in for an input and have it not only determine the unique (non-recurring) numbers it takes to get to that total, but how those numbers should be used.
Example:
I know I can simply divide a number by 9 to determine the median, which in this case already gives me one letter, which would be E in this case. I know I can simply run a couple for loops to get the remaining numbers. What I'm not sure how to do is figure out the recursion process to determine the correct assignment of each number.
Here's the example of the letter assignment:
G | F | A
H | E | B
I | D | C
You'd need the following combinations:
A+B+C
F+E+D
G+H+I
A+E+I
G+E+C
G+F+A
H+E+B
I+D+C
Now, what I'm not sure of, and the effect it could have, is the frequency in which each number is used. I know each of the above sequences would need to equal the number input divided by 3 would in this case would be 30, but I'm not sure what important facts can be used to create the proper nested for loops and/or if statements that sort through the list or array of numbers created and properly assign them based on their relevance.
Considering E is used 4 times (which is why it's the center), A,C,I, and G are used 3 times, and H,B,D, and F are used 2 times.
So, for clarification, I would like all of this to output what A,B,C, etc. should be equal to given the restrictions.
Thanks for any help.
As an additional request, although not required, but extremely appreciated - if you do provide an answer, explaining some of the important portions of the recursions, functions used and how it achieves my desired outcome would be great.
I think I've made my question clear at this point. In regards to someone's comment, yes I'm asking for the code, because I one am not proficient enough to figure out the complex use of recursion it would take to constantly check the needed constraints required, and two, no other questions really get into the kind of detail I feel I'm trying to go to. Most just what a normal statistical use of Combinations and Permutations, but it doesn't seem there's as many restrictions on the results, and/or their end goal is different.
For the sake of making some things clear, here's another edit:
Below is what I have to first generate the list of all the numbers that will be used.
int A, B, C, D, E, F, G, H, I;
Console.WriteLine("Choose a number that's all 9 spots added together.");
Console.WriteLine("Make sure the number is divisble by 3 and 9.");
int myNumber = int.Parse(Console.ReadLine());
int sums = myNumber / 3;
E = myNumber / 9;
if (E%1 != 0)
{
Console.WriteLine("You did not enter a value divisible by 3 and 9");
Console.WriteLine("Try again.");
Console.ReadLine();
}
else
{
List<int> list = new List<int>();
int lowest = E - 4;
for (int x = lowest;x < E; x++)
{
list.Add(x);
}
int highest = E + 4;
for (int y=E;y<highest;y++)
{
list.Add(y+1);
}
//Testing output
foreach (int i in list)
{
Console.WriteLine(i);
}
I made this to first see if I could establish the numbers that would be used, then go into finding all the variations of the numbers that would make all the lines equal the same. For example: if they entered 45, all directions would have to equal 15; if they entered 90, all directions would have to equal 30, etc.
Here you go. Knock yourself out.
Func<IEnumerable<int>, IEnumerable<int[]>> permutate = null;
permutate = ns =>
{
if (!ns.Skip(1).Any())
{
return new [] { ns.ToArray() };
}
else
{
return
from n in ns
from ns2 in permutate(ns.Except(new [] { n }))
select new [] { n }.Concat(ns2).ToArray();
}
};
var results =
permutate(Enumerable.Range(1, 9))
.Where(ns => Enumerable.Range(0, 3).All(n => ns[n * 3] + ns[n * 3 + 1] + ns[n * 3 + 2] == 15))
.Where(ns => Enumerable.Range(0, 3).All(n => ns[n] + ns[3 + n] + ns[6 + n] == 15))
.Where(ns => Enumerable.Range(0, 3).All(n => ns[0] + ns[4] + ns[8] == 15))
.Where(ns => Enumerable.Range(0, 3).All(n => ns[2] + ns[4] + ns[6] == 15));
This gives:
2, 7, 6
9, 5, 1
4, 3, 8
2, 9, 4
7, 5, 3
6, 1, 8
4, 3, 8
9, 5, 1
2, 7, 6
4, 9, 2
3, 5, 7
8, 1, 6
6, 1, 8
7, 5, 3
2, 9, 4
6, 7, 2
1, 5, 9
8, 3, 4
8, 1, 6
3, 5, 7
4, 9, 2
8, 3, 4
1, 5, 9
6, 7, 2
I understand what #tekGiant is asking but I do not know how to answer it yet...
G | F | A
H | E | B
I | D | C
You'd need the following combinations:
A+B+C=X
F+E+D=X
G+H+I=X
A+E+I=X
G+E+C=X
G+F+A=X
H+E+B=X
I+D+C=X
Where X is the initial number that you designate to be the one that each of the different combinations add up to.

get "running average" of a list

Say I've got a list:
List<int> numbers = new List<int>();
and I'm trying to get the "running averages" of it. (Sorry, I don't really know how to call it).
For instance:
The first item in this list is 5, the average of 5 is 5, so the first average is 5.
The second item in this list is 7, the average of 5 and 7 is 6, so the second average is 6.
The third item in this list is 10, the average of 5, 7 and 10 is 7.3, so the third average is 7.3
And so on.
Those first average, second average etc are the averages I'm trying to get. How would I go about doing this? I've been searching the internet but honestly I'm not quite sure what I should be looking for. :(
try this:
string st = Console.ReadLine();
string[] strs = st.Split(' ');
List<int> numbers = new List<int>();
List<double> averages = new List<double>();
for (int i = 0; i < strs.Length; i++)
{
numbers.Add(int.Parse(strs[i]));
averages.Add(numbers.Average());
}
this will read the numbers from the standard input, the numbers are separated by space in input.
You can try something like this:
var averages = Enumerable.Range(1, numbers.Count)
.Select(x => numbers.Take(x).Average())
.ToList();
This will generate a sequence from 1 to numbers.Count. Then using Take it will get X element at each time (you can think X as an index, only difference is it starts from 1 and increases one by one up to the numbers.Count) starting from the first element then get their average.Put them into a list.
The lists
List<int> numbers = new List<int>();
List<double> averages = new List<double>();
test data
numbers.AddRange(new int[]{5, 7, 10});
// get average of current List
averages.Add(numbers.Average());
Such a list of averages all by itself usually doesnt mean much without some other data like number of elements, duration of time or something to qualify it.
This method is better suited when the moving average is not one for one with the values. For instance, the app stores values. Then periodically, say once a minute, the average is calculated and stored.
You need the "Running Average", not the average from the start over all items I assume?
The running average needs a number to tell how far back to look and one to tell how far forward to look.
This will give you the running average:
public List<double> GetRunningAverage(List<double> SourceList, int ItemsBefore, int ItemsAfter)
{
List<double> TargetList = new List<double>() { };
// Only makes sense if the list is > 1 of course
if (SourceList.Count > 1)
{
for (int i = 0; i < SourceList.Count; i++)
{
int LookBack =
(ItemsBefore > i ? i : ItemsBefore);
int LookForward =
(ItemsAfter < SourceList.Count - i
? ItemsAfter : SourceList.Count - i);
TargetList.Add(SourceList.GetRange(i - LookBack, LookBack + LookForward).Average());
}
}
else
{
TargetList.AddRange(SourceList);
}
return TargetList;
}
You can then use it like this:
List<double> FullList = GetRunningAverage(
new List<double>() { 100, 5, 5, 6, 23, 10, 56, 32, 54, 1, 3, 85, 65, 49, 22, 65, 32, 5, 2, 4, 5, 89, 110, 55, 6, 56, 57 },
3, // Looking back 3 items
3); // Looking forward 3 items

How does C#'s random number generator work?

I was just wondering how the random number generator in C# works. I was also curious how I could make a program that generates random WHOLE INTEGER numbers from 1-100.
You can use Random.Next(int maxValue):
Return:
A 32-bit signed integer greater than or equal to zero, and less than
maxValue; that is, the range of return values ordinarily includes zero
but not maxValue. However, if maxValue equals zero, maxValue is
returned.
var r = new Random();
// print random integer >= 0 and < 100
Console.WriteLine(r.Next(100));
For this case however you could use Random.Next(int minValue, int maxValue), like this:
// print random integer >= 1 and < 101
Console.WriteLine(r.Next(1, 101);)
// or perhaps (if you have this specific case)
Console.WriteLine(r.Next(100) + 1);
I was just wondering how the random number generator in C# works.
That's implementation-specific, but the wikipedia entry for pseudo-random number generators should give you some ideas.
I was also curious how I could make a program that generates random WHOLE INTEGER numbers from 1-100.
You can use Random.Next(int, int):
Random rng = new Random();
for (int i = 0; i < 10; i++)
{
Console.WriteLine(rng.Next(1, 101));
}
Note that the upper bound is exclusive - which is why I've used 101 here.
You should also be aware of some of the "gotchas" associated with Random - in particular, you should not create a new instance every time you want to generate a random number, as otherwise if you generate lots of random numbers in a short space of time, you'll see a lot of repeats. See my article on this topic for more details.
I've been searching the internet for RNG for a while now. Everything I saw was either TOO complex or was just not what I was looking for. After reading a few articles I was able to come up with this simple code.
{
Random rnd = new Random(DateTime.Now.Millisecond);
int[] b = new int[10] { 5, 8, 1, 7, 3, 2, 9, 0, 4, 6 };
textBox1.Text = Convert.ToString(b[rnd.Next(10)])
}
Simple explanation,
create a 1 dimensional integer array.
full up the array with unordered numbers.
use the rnd.Next to get the position of the number that will be picked.
This works well.
To obtain a random number less than 100 use
{
Random rnd = new Random(DateTime.Now.Millisecond);
int[] b = new int[10] { 5, 8, 1, 7, 3, 2, 9, 0, 4, 6 };
int[] d = new int[10] { 9, 4, 7, 2, 8, 0, 5, 1, 3, 4 };
textBox1.Text = Convert.ToString(b[rnd.Next(10)]) + Convert.ToString(d[rnd.Next(10)]);
}
and so on for 3, 4, 5, and 6 ... digit random numbers.
Hope this assists someone positively.
so thats kind of easy if you just use it like
Random random = new Random();
int answer = random.Next(0);

C# Calculate items in List<int> values vertically

I have a list of int values some thing like below (upper bound and lower bounds are dynamic)
1, 2, 3
4, 6, 0
5, 7, 1
I want to calculate the column values in vertical wise like
1 + 4 + 5 = 10
2 + 6 + 7 = 15
3 + 0 + 1 = 4
Expected Result = 10,15,4
Any help would be appreciated
Thanks
Deepu
Here's the input data using array literals, but the subsequent code works exactly the same on arrays or lists.
var grid = new []
{
new [] {1, 2, 3},
new [] {4, 6, 0},
new [] {5, 7, 1},
};
Now produce a sequence with one item for each column (take the number of elements in the shortest row), in which the value of the item is the sum of the row[column] value:
var totals = Enumerable.Range(0, grid.Min(row => row.Count()))
.Select(column => grid.Sum(row => row[column]));
Print that:
foreach (var total in totals)
Console.WriteLine(total);
If you use a 2D array you can just sum the first, second,... column of each row.
If you use a 1D array you can simply use a modulo:
int[] results = new results[colCount];
for(int i=0, i<list.Count; list++)
{
results[i%colCount] += list[i];
}
Do you have to use a "List"-object? Elseway, I would use a twodimensional array.
Otherwise, you simply could try, how to reach rows and columns separatly, so you can add the numbers within a simply for-loop. It depends on the methods of the List-object.
Quite inflexible based on the question, but how about:
int ans = 0;
for(int i = 0; i < list.length; i+=3)
{
ans+= list[i];
}
You could either run the same thing 3 times with a different initial iterator value, or put the whole thing in another loop with startValue as an interator that runs 3 times.
Having said this, you may want to a) look at a different way of storing your data if, indeed they are in a single list b) look at more flexible ways to to this or wrap in to a function which allows you to take in to account different column numbers etc...
Cheers,
Adam

Categories