问题描述
我解决旋转阵列的这个问题,并得到了算法和code工作
I am solving this problem of rotating an array and got algorithm and code working
int[] Rotate(int[] ar,int k)
{
if (k <= 0 || k > ar.Length - 1)
return ar;
Reverse(ar, 0, k - 1);
Reverse(ar, k, ar.Length - 1);
Reverse(ar, 0, ar.Length - 1);
return ar;
}
void Reverse(int[] ar,int start, int end)
{
while (start < end)
{
int temp = ar[start];
ar[start] = ar[end];
ar[end] = temp;
start++;
end--;
}
}
现在我想这样做LINQ中,我得到了下面的code,我觉得这是可以做到更好。
Now I want to do this in LINQ and I got the below code, I think this can be done much better.
int[] Rotate(int[] ar,int k)
{
if (k <= 0 || k > ar.Length - 1)
return ar;
int[] ar1=ar.Take(k-1).Reverse().ToArray();
int[] ar2=ar.Skip(k - 1).Take(ar.Length - k+1).Reverse().ToArray();
int[] ar3 = ar1.Concat(ar2).Reverse().ToArray();
return ar3;
}
这是从编程珍珠一个众所周知的算法 - <一个href=\"http://books.google.com/books?id=kse_7qbWbjsC&lpg=PA14&ots=DfzTzQCSar&dq=rotate%20an%20array%20programming%20pearls&pg=PA14#v=onepage&q&f=false\" rel=\"nofollow\">http://books.google.com/books?id=kse_7qbWbjsC&lpg=PA14&ots=DfzTzQCSar&dq=rotate%20an%20array%20programming%20pearls&pg=PA14#v=onepage&q&f=false
This is a well known algorithm from Programming pearls - http://books.google.com/books?id=kse_7qbWbjsC&lpg=PA14&ots=DfzTzQCSar&dq=rotate%20an%20array%20programming%20pearls&pg=PA14#v=onepage&q&f=false
而在一般情况如何发展我的LINQ的技能,如果我给出规划问题,现在我只想在循环或foreach循环,怎么想的LINQ运营商而言。我读C#4.0概括地说,比任何练习其他的建议?
And in general how to develop my LINQ skills, if I am given a programming problem, right now I am only thinking in for loops or foreach loops, how to think in terms of linq operators. I am reading C# 4.0 nutshell, other than practicing any advice?
推荐答案
与code开始:
int[] ar1=ar.Take(k-1).Reverse().ToArray();
int[] ar2=ar.Skip(k - 1).Take(ar.Length - k+1).Reverse().ToArray();
int[] ar3 = ar1.Concat(ar2).Reverse().ToArray();
既然你只是想获得的所有剩余的元素,是不是需要在第二行取。
Since you just want to get all of the remaining elements, the Take in the second line isn't needed.
Ar1和Ar2只是列举,所以它们不需要是数组。不需要的ToArray的呼叫。有了一点创造性重命名的抛出,我们有:
ar1 and ar2 are just enumerated, so they don't need to be arrays. The ToArray calls aren't needed. With a bit of creative renaming thrown in, we have:
IEnumerable<int> revFirst = ar.Take(k-1).Reverse();
IEnumerable<int> revLast = ar.Skip(k-1).Reverse();
int[] ar3 = revFirst.Concat(revLast).Reverse().ToArray();
现在我们
转(REV(第一)+ REV(最后))
rev ( rev(first) + rev(last) )
分发外转给
转(REV(最后))+转(REV(第一))
rev ( rev(last) ) + rev ( rev(first) )
这是相同的
last + first
施加相同的操作到code给出
applying the same operations to the code gives
IEnumerable<int> first = ar.Take(k-1);
IEnumerable<int> last = ar.Skip(k-1);
int[] ar3 = last.Concat(first).ToArray();
进一步简化,以
int[] ar3 = ar.Skip(k-1).Concat(ar.Take(k-1)).ToArray();
现在我们已经乔恩斯基特的答案,所以我们必须做到的。
and now we have Jon Skeet's answer so we must be done.
这篇关于旋转使用LINQ语法定义的数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!