How can I select a random option? - c#

I have an array of ints, that It should like the following:
7 3 2 4 5 6 1 9 10 8 Values
[1 2 3 4 5 6 7 8 9 10] Order In Array
This values should change its order, and every value, it's a random option, for example:
If it chooses that the first value is 6, it chooses the color blue, then, it goes to the second value, if the value is 4, it chooses green.
Every number is equal to a color.
I've been thinking that I can use an if conditional, but I dont know if there's a property to check the value, because if I do a if conditional for each option, it could take like 100+ lines of code!.
Do you have any idea of how can I improve it?.

You can do this almost in one line :
var rnd = new Random();
var orderedNumbers = new int[] {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
var randomizedNumbers = orderedNumbers.OrderBy(c => rnd.Next()).ToArray();

Related

C# Select some lists in many lists that look like a list

Sorry if the header made you confused.
This thread looks similar header but that is actually different Selecting some lists from a list of lists.
I want to Select some lists in many lists that look like a list
Sample:
// data source
List<List<int>> sources = new List<List<int>>();
sources.Add(new List<int>(){1, 2, 3, 4});
sources.Add(new List<int>(){1, 2, 3, 4, 5});
sources.Add(new List<int>(){1, 2, 3, 4, 5, 6});
sources.Add(new List<int>(){1, 2, 99, 3, 4, 5, 6});
sources.Add(new List<int>(){1, 3, 99, 2, 4, 5});
sources.Add(new List<int>(){5, 4, 3, 2, 1});
sources.Add(new List<int>(){1, 2, 4, 5, 6});
sources.Add(new List<int>(){1, 2, 69, 3, 4, 5});
// the list that we want to find lists similar to this
List<int> current = new List<int>() {1, 2, 3, 4, 5};
The list contain not-important element, can be ignored. Updated! In the case its elements are not appeared in current:
List<int> flexible = new List<int>() {99, 66, 123123, 2};// <= updated!
The function I want to write:
void FilterA(List<int> current, List<List<int>> sources, List<int> flexible) {}
How to make FilterA output these list (Lists chosen)? Printing functions are not required.
Lists chosen
1 2 3 4 5 // exactly the same !
1 2 3 4 5 6 // same first 5 elements, the rests are not important
1 2 99 3 4 5 6 // 99 is in flexible list, after ignored that is 1 2 3 4 5 6
// Updated! Ignore 99 because it is not in list current
Lists ignored
1 2 3 4 // missing 5 in current
1 3 99 2 4 5 // 99 is in flexible list, after ignored that is 1 3 2 4 5
5 4 3 2 1 // wrong order
1 2 4 5 6 // missing 3 in current
1 2 69 3 4 5 // 69 is not in flexible list
Thank you very much!
--- Updated ---
If elements in list flexible appeared in list current, they must not be excluded.
The answer of #Sweeper is nice.
p/s: In the case not any element of flexible appear in current, #TheGeneral 's answer is great, runs great performance.
Update after clarification
The premise is, remove flexible with Except, Take n to then compare with SequenceEqual.
Note : All three methods have linear time complexity O(n)
var results = sources.Where(x =>
x.Except(flexible)
.Take(current.Count)
.SequenceEqual(current));
Output
1, 2, 3, 4, 5
1, 2, 3, 4, 5, 6
1, 2, 99, 3, 4, 5, 6
Full demo here
Additional Resources
Enumerable.Except
Produces the set difference of two sequences.
Enumerable.Take
Returns a specified number of contiguous elements from the start of a
sequence.
Enumerable.SequenceEqual
Determines whether two sequences are equal according to an equality
comparer.
You should write a method that determines whether one list (candidate) should be chosen:
public static bool ShouldChoose(List<int> candidate, List<int> current, List<int> flexible) {
int candidateIndex = 0;
foreach (int element in current) {
if (candidateIndex >= candidate.Count) {
return false;
}
// this loop looks for the next index in "candidate" where "element" matches
// ignoring the elements in "flexible"
while (candidate[candidateIndex] != element) {
if (!flexible.Contains(candidate[candidateIndex])) {
return false;
}
candidateIndex++;
}
candidateIndex++;
}
return true;
}
Then you can do a Where filter:
var chosenLists = sources.Where(x => ShouldChoose(x, current, flexible)).ToList();
foreach (var list in chosenLists) {
Console.WriteLine(string.Join(", ", list));
}
This works for me:
var results =
sources
.Where(source => source.Except(flexible).Count() >= current.Count())
.Where(source => source.Except(flexible).Zip(current, (s, c) => s == c).All(x => x))
.ToList();

How to slice elements from 2nd item in a c# array?

Given a 1D array,
double[] arr = { 4, 3, 2, 8, 7, 6, 1 };
I want to get values from 2nd index till last and want to store the array in a variable.
Want to get something like this:
new_arr = {3, 2, 8, 7, 6, 1 }; //first element sliced
You can use C# 8 indices and ranges feature
double[] arr = { 4, 3, 2, 8, 7, 6, 1 };
var slice = arr[1..];
It'll return all items from index 1 till the end of array and give you an expected slice {3, 2, 8, 7, 6, 1 }. Again, it works only with C# 8 and .NET Core 3.x.
For earliest versions of C# you should do this by yourself, using Array.Copy for example or System.Linq
double[] arr = { 4, 3, 2, 8, 7, 6, 1 };
var slice = arr.Skip(1).ToArray();
If you are using C# 8, you can use Indices & Range. It goes something like this:
var newArray = oldArray[1..]; // Takes everything from index 1 until the end.
You can use Linq to skip the fist item and take the rest. This will give you the sequence:
arr.Skip(1);
Which you can convert to a new array like this:
var new_arr = arr.Skip(1).ToArray();

C# Order of Operations Syntax Explanation [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
In a code review of a component library, I found syntax where some calculations for days per month are needed.
The simplified syntax is something like:
int preDays = (new int[] { 0, 1, 2, 3, 4, 5, 6 })[3] - 2;
Where [3] and -2 are variables. In the above example, the result of preDays is 1.
Could somebody please explain how we come to this result?
Break down the code into its individual pieces. Just like in math, we perform operations inside the parenthesis first, so you're creating an array of integers with the values 0 through 6. Next, the code looks at index 3 (arrays in C# are 0-based). The value at index 3 is 3. Lastly, we subtract 2 from 3 to get 1 and assign it to preDays.
You can think of it like this:
int[] myArray = { 0, 1, 2, 3, 4, 5, 6};
int myValue = myArray[3]; // Value is 3
int preDays = myValue - 2; // Value is 1
Does this help:
var array = new int[] { 0, 1, 2, 3, 4, 5, 6 };
int value = array[3]; //3
int preDays = value - 2; //1
This one's quite easy in my opinion:
within the () there's a new anonymous array defined. An array which consists of seven elements being 0,1,2,3,4,5 and 6. From this array you take the 4th element.
([3] refers to the fourth element as counting starts from [0] referring to the first element).
The fourth element of the array is 3, so the expression (new int[] { 0, 1, 2, 3, 4, 5, 6 })[3] resolves to 3. Subtracting 2 from 3 makes preDays to be filled with 1.
you are creating an array an making an arithmetic calculation on the same line and given that
index in c# has a zero as base so if you count 0,1,2,3 you will get a value 3 in the 4 case of the array so 3 minus 2 you will get 1
So take it like that
var myArray = new int[] { 0, 1, 2, 3, 4, 5, 6 };
int myValue = array[3]; //3
int preDays = value - 2;
In int preDays = (new int[] { 0, 1, 2, 3, 4, 5, 6 })[3] - 2;
(new int[] { 0, 1, 2, 3, 4, 5, 6 }) will create temporary integer array of size 7 and with values(0, 1, 2, 3, 4, 5, 6).
(new int[] { 0, 1, 2, 3, 4, 5, 6 })[3] will extract 4th item(item with index 3) i.e value 3.
(new int[] { 0, 1, 2, 3, 4, 5, 6 })[3] - 2 will perform 3 - 2 = 1.

Best way to lookup numbers in multiples of 3's 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

Deleting same elements in array C# [duplicate]

This question already has answers here:
How do I remove duplicates from a C# array?
(28 answers)
Closed 9 years ago.
If I have one array for example [1 4 3 7 4 9 5 1 5 6 3].
How to delete repetitive numbers and give in the output array like this [1 4 3 7 9 5 6]?
Distinct()
var distinctArray = myArray.Distinct().ToArray();
You can call your array in a HashSet<int> constructor. HashSet is a kind of optimized collection. It's constructor eliminates the non-unique elements.
Here an example in LINQPad;
var array = new[]{1, 4, 3, 7, 4, 9, 5, 1, 5, 6, 3};
HashSet<int> h = new HashSet<int>(array);
h.ToArray().Dump();
Here a result;
What about this :
int[] arr = { 1, 4, 3, 7, 4, 9, 5, 1, 5, 6, 3 };
foreach (int item in arr.Distinct())
{
Console.WriteLine(item);
}
and you can also assign in a array like this:
int[] unique = arr.Distinct().ToArray();
Couple of suggestions found searching:
1.)
int[] s = { 1, 2, 3, 3, 4};
int[] q = s.Distinct().ToArray();
2.) The easiest solution will be to simply sort the array (takes O(n log n) with standard implementation if you may use them. otherwise consider making an easy randomized quicksort (code is even on wikipedia)).
Afterwards scan it for one additional time. During that scan simple eliminate consecutive identical elements.
If you want to do it in O(n), you can also use a HashSet with elements you have already seen. Just iterate once over your array, for each element check if it is in your HashSet.
If it isn't in there, add it. If it is in there, remove it from the array.
Note, that this will take some additional memory and the hashing will have a constant factor that contributes to your runtime. Althought the time complexity is better, the practical runtime will only be onyl be faster once you exceed a certain array size
If you, for whatever reason, do not want to use Linq:
List<int> distinctList = new List<int>();
foreach (var num in numberList)
{
if (!distinctList.Contains(num))
{
distinctList.Add(num);
}
}

Categories