I haven't been able to find anything on google.
I have this piece of code:
Random r = new Random();
int[] output = Enumerable.Range(0, 11).Select(x => x / 2).OrderBy(x => r.Next()).ToArray();
and I am having trouble actually understanding what each element does.
It generates a range of numbers and elements between 0 and 11.
But what does the select(x => x / 2) do ? does it just make pairs of elements,
I know what the whole thing spits out, an array with pairs of numbers, with a single number which has no pair.
but it is a bit above me to fully understand it ?
( is this even okay to ask on here ?? or should I delete the question again ? )
It generates a range of numbers and elements between 0 and 11. But what does the select(x => x / 2) do ? does it just make pairs of elements.
No, Select does what in some programming languages is known as map. It is called on an IEnumerable<T> and has as parameter Func<T,U> a function, and it produces an IEnumerable<U> where each element if the given IEnumerable<T> is processes through the function and the result is emitted in the result.
So in this case, it will take a range from 0 to (excluding) 11, and for each of those integers, perform an integer divsion by two:
csharp> Enumerable.Range(0, 11);
{ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 }
csharp> Enumerable.Range(0, 11).Select(x => x/2);
{ 0, 0, 1, 1, 2, 2, 3, 3, 4, 4, 5 }
Since:
{ 0/2, 1/2, 2/2, 3/2, 4/2, 5/2, 6/2, 7/2, 8/2, 9/2, 10/2 }
== { 0, 0, 1, 1, 2, 2, 3, 3, 4, 4, 5 }
Later then that IEnumerable<int> is reordered (using the OrderBy) by using pseudo-random numbers (so we shuffle them) and converted into a list.
.Range(0, 11) // generate a sequence of integers starting at 0 and incrementing 11 times (i.e. the values 0 up to and including 10)
.Select(x => x / 2) // divide each of those values from previous result by 2 and return them
.OrderBy(x => r.Next()) // then order them randomly using a random number
.ToArray(); // return the end result as an array
Think of Select as doing a transformation to each element of the IEnumerable.
For example, let's say we have a list like this:
0 1 2 3 4 5 6 7 8 9 10
Then we call .Select(x => x / 2), we are saying that for each element x in the list, do the following transformation:
x / 2
We divide each element in the list by two:
Original Transformation Result
0 0 / 2 0
1 1 / 2 0
2 2 / 2 1
3 3 / 2 1
4 4 / 2 2
5 5 / 2 2
6 6 / 2 3
7 7 / 2 3
8 8 / 2 4
9 9 / 2 4
10 10 / 2 5
We get
0 0 1 1 2 2 3 3 4 4 5 5
What Select() does is that it evaluates the given expression for every element of the Enumerable it's called on (the original list), and returns a new Enumerable with the results.
For a list:
[2, 4, 6]
it's going to return:
[2/2, 4/2, 6/2]
where / means "division", so the result of the Select() (not the entire LINQ chain) will be:
[1, 2, 3]
Analogously, if your source list is:
words = ["dog", "child", "building"]
And you call:
words.Select(word => word.Length)
you get a list of all the lengths of the strings in the list in order:
[3, 5, 7]
Related
Lets suppose we have two integer arrays, for example:
var A = new int[] {1, 4, 6, 12, 44};
var B = new int[] {2, 4, 6, 44, 45};
The problem is to describe a transition steps as:
Starting with the array A and continue as following:
STEP 1 : remove index = 0 // result = {4, 6, 12, 44}
STEP 2 : insert index = 0 value = 2 // result = {2, 4, 6, 12, 44}
STEP 3 : remove index = 3 // result = {2, 4, 6, 44}
STEP 4 : insert index = 4 value = 45 // result = {2, 4, 6, 44, 45}
And we now have the array B
My Question is: How can I design this algorithm in any programming language or pseudocode that generates these steps programatically for given array A and B?
common step structure is like :
STEP N : insert/remove index = i [value = v]
Of course removing all elements from A then inserting all elements from B is a solution and like that maybe there will be more than 1 solutions for given A and B, but I am looking for the transition with the fewest steps.
There is the concept of the Levenshtein distance. It is used for comparing two strings (however you can also apply the same principle to integer arrays): minimal number of edits to change one string into another, where one edit is either a deletion, an insertion or a substitution.
The problem can be efficiently solved using dynamic programming. The wiki article shows such an approach.
You can use the same approach for your problem. But since in your case you are not allowed to substitute an element (only remove and insert operations), you can even simplify the the recursion a (tiny) bit:
def edit_distance(s, len_s, t, len_t):
if len_s == 0:
return len_t
if len_t == 0:
return len_s
if s[len_s-1] == t[len_t-1]:
return edit_distance(s, len_s-1, t, len_t-1)
else:
return min(edit_distance(s, len_s-1, t, len_t) + 1,
edit_distance(s, len_s, t, len_t-1) + 1)
The code above is without dynamic programming. To make it efficient, you need to add it.
Also, the code will only compute the number of steps. If you also want to list the steps, you have to store the complete table and backtrack the solution.
Time and memory complexity of the approach: O(len_s * len_t).
Here is an example using your two arrays [1, 4, 6, 12, 44] and [2, 4, 6, 44, 45]. Here is a table that you would get if you apply dynamic programming (e.g. with a bottom first approach) for each of the possible prefix-combination of the strings.
0 1 2 3 4 5
1 2 3 4 5 6
2 3 2 3 4 5
3 4 3 2 3 4
4 5 4 3 4 5
5 6 5 4 3 4
At the bottom right we see that 4 is the optimal number of steps to make both array equal. Now we can backtrack and look at the recursive formula again. Since the last two elements are not equal, it has to be an insert/remove operation. We can see in the table the optimal number of steps for [1, 4, 6, 12], [2, 4, 6, 44, 45] is 5, and for [1, 4, 6, 12, 44], [2, 4, 6, 44] is 3. So the optimal thing here is to remove the last element of the second array, or in other words to insert 45 in the first one.
Now we can thing about the last step that resulted in [1, 4, 6, 12, 44], [2, 4, 6, 44]. Since the last elements are equal, the step is clear. We leave both of them and perform no insert or remove operation.
So what was the last step in [1, 4, 6, 12], [2, 4, 6]? The table shows that the optimal value 3 originated from the position [1, 4, 6], [2, 4, 6], which means a removing 12 in the first array.
And so on.
Interestingly there can be multiple optimal solutions. Here I show you one possible path (which corresponds exactly to your solution):
0-1 2 3 4 5
|
1 2 3 4 5 6
\
2 3 2 3 4 5
\
3 4 3 2 3 4
|
4 5 4 3 4 5
\
5 6 5 4 3-4
I am looking to create a program like the following (c# btw):
int[] arr = new int[9]
//some code that puts values 1, 0, or 2 in each array element
for(int i = 0; i < arr.Length; i++)
{
if (arr[i] == arr[i + 3]) { return true; }
}
So, for each value in the array I am applying a formula that does something with that value and the value 3 indexes ahead of it. Of course, this runs into an out of range exception once i+3>8.
What I'd like to do is if the the desired index is out of range then loop the index values back around to the beginning of the array. So, in an array of length 9 where the last index is 8, if on a given loop i = 7, and i+3 then = 10, I would like i+3 to 'become,' by whatever means, 1, and then when i = 8, and i+3 = 11, I want i+3 to become 2.
So, the index pairs being evaluated would be something like:
i , i+3
0 3
1 4
2 5
3 6
4 7
5 8
6 0
7 1
8 2
how can I go about doing this?
Thanks for any help.
Use the modulo operator like this:
if (arr[i] == arr[(i + 3) % arr.Length]) { return true; }
You could try the following expression inside your if statement.
arr[i] == arr[(i + 3) % arr.Length];
The % Operator
Divides the value of one expression by the value of another, and
returns the remainder.
i am learning C# and LINQ so i am sorry for that question.
how to type in linq to group the same elements in certain array, but when they group it they see if the count of the group is greater than 2 and then division it by 2 and return the value of the group count and then add it to int
what i want the linq to do in code :
s => s > 2
s /= 2
return s;
my original code is that:
int n = Convert.ToInt32(Console.ReadLine());
string[] userinput = Console.ReadLine().Split(' ');
int[] socks = new int[n];
socks = Array.ConvertAll(userinput, Int32.Parse);
var result = socks.GroupBy(s => s > 2).ToArray(); //This is the line which i want help
int total = 0;
foreach (var group in result)
{
total += group.Count();
Console.WriteLine(group.Count());
}
Lets assume we have 10 kinds of socks. which are 10,20,30,40,50,60,70, 80,90,100
now in the first line i enter the number of the socks i have so for example its 5.
in the second line i enter the 5 socks kinds for example. 10 10 20 20 30
now i want the linq code to define that there is 3 keys here which are 10 20 30, the 10 key has more than only 1 count it has 2. the same for 20 but the 30 only have 1 so lets forget about the 30. now the count of they key of each one of them is 2 so lets divide it by 2 for each one then add the divided number to the total so 2/2 for each one equals 1 so total = 2 (this is the my expected output)
If understand you right, you want to count pairs of socks:
int total = socks
.GroupBy(x => x)
.Sum(chunk => chunk.Count() / 2);
According to your example:
[10, 10, 20, 20, 30]
after grouping socks by their sizes
10: [10, 10] - 2 socks, 1 pair (you've put it as "divide by 2")
20: [20, 20] - 2 socks, 1 pair
30: [30] - 1 sock, 0 pairs
-------------------------------
2 pairs in total (the expected value)
My example (from the comments to the question)
1, 2, 2, 2, 3, 4, 5, 5
should return 2 as well (we have 2 pairs: of size 2 and 5)
In case you want to get pairs:
var pairs = socks
.GroupBy(x => x)
.Select(chunk => new {
size = chunk.Key,
count = chunk.Count() / 2, });
//.Where(pair => pair.count > 0); // you may want to filter out single socks
I'm currently learning about PLINQ (Parallel Language Integrated Query) on Visual Studio 2012's C#.
In the one lesson Where(i => i % 2 == 0) was given to me, but I've no idea what it means and the book i'm studying from didn't give any explanation.
Does anyone know what this means?
First hope you know % which is "The % operator computes the remainder after dividing its first operand by its second". Read more about % Operator
if you have a list of numbers
var list = new List<Int32>() {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
var result = list.Where(i => i%2 == 0);
So the result will have 2,4,6,8 and 10.
Same thing can be written as
var ans = new List<Int32>();
foreach (var an in list)
{
if (an%2 == 0)
ans.Add(an);
}
The query is selecting only even numbers, where division by 2 has no remainder.
The % operator computes the remainder after dividing its first
operand by its second. All numeric types have predefined remainder
operators.
http://msdn.microsoft.com/en-us/library/0w4e0fzs.aspx
lambda expressions are a bit weird at 1st however when you experiment a bit in VS (and its intellisense) you'll get used to it in no time. as soon as you type in "i=>" you declare a range variable of your type of object which implements IEnumerable(<T>) interface. In this case i is one element of your list (or other IEnumerable>> list, dictionary....) to investigate this case you search for even numbers...
Let's say this is the case:
List<int> source = new List<int>() { 1, 2, 3, 4 };
var evenNumbers = source.Where(i => i % 2 == 0);
Where is filtering source and returning only it's even numbers.
Where is a Linq extension method that works on any object implementing the IEnumerable interface (likeList).
i => i % 2 == 0 is a lambda expression. In this case it means that for each item i in source, Where will apply the expression i % 2 == 0.
Where selects the items in source for which the lambda expression is true. In this case, the expression is true when i is an even number.
This is because of the modulo operator %, which returns the remainder of the integer division between two numbers a and b: a % b. If a = 4 and b = 3, then a % b values 1, because it is what remains when dividing 4 by 3. If % returns 0, then it means that a is divided by b. If b is 2, then it means that a is even.
Where(i => i % 2 == 0)
it means i goes to where i % 2 == 0 that is if
you are doing it for a list of integer it will return all even numbers from list
This question already has answers here:
How can I get every nth item from a List<T>?
(10 answers)
Closed 8 years ago.
C# 4.0. How can the following be done using lambda expressions?
int[] a = new int[8] { 0, 1, 2, 3, 4, 5, 6, 7 };
// Now fetch every second element so that we get { 0, 2, 4, 6 }
int[] list = a.Where((value, index) => index % 2 == 0)
.ToArray();
It will only select even indexes, as calculate by the % (mod) operator .
5 % 2 // returns 1
4 % 2 // returns 0
According to MSDN:
% Operator
Another approach using Enumerable.Range
var result = Enumerable.Range(0, a.Length/2)
.Select(i => a[2*i])
.ToArray();
Or use bitwise for more efficient to check even:
var result = a.Where((i, index) => (index & 1) == 0)
.ToArray();
The remainder operator is your friend.
int[] everySecond = a.Where((i, ind) => ind % 2 == 0).ToArray();
% Operator (C# Reference)
The % operator computes the remainder after dividing its first operand
by its second. All numeric types have predefined remainder operators.
E.Lippert: What's the difference? Remainder vs Modulus