gpt4 book ai didi

Reverse an array without using Array.Reverse()(在不使用Array.Reverse()的情况下反转数组)

转载 作者:bug小助手 更新时间:2023-10-25 23:14:39 27 4
gpt4 key购买 nike



How to reverse an array (in C#) without using Array.Reverse() method?

如何在不使用Array.Reverse()方法的情况下反转数组(在C#中)?



For example,

例如,



int[] arr = {1,3,4,9,8};
// some code here
Console.WriteLine(string.Join(",", arr));


should result in

应该会导致



8,9,4,3,1


I got this as an interview task.

这是我的面试任务。


更多回答

@BoltClock - maybe we mean unicode... ɹɹɐ

@BoltClock-也许我们指的是Unicode...ɹɹɐ

优秀答案推荐

The code to be substituted in place of // some code here in the question is:

在问题中替换//某些代码的代码是:



for (int i = 0; i < arr.Length / 2; i++)
{
int tmp = arr[i];
arr[i] = arr[arr.Length - i - 1];
arr[arr.Length - i - 1] = tmp;
}


You should iterate only through the first half of the array (arr.Length / 2). If you iterate through the whole array (arr.Length), it will be reversed twice, yielding the same element order as before it started.

您应该只迭代数组的前半部分(arr.Length/2)。如果遍历整个数组(arr.Length),它将被反转两次,生成与开始之前相同的元素顺序。



Basically, you are asked to reimplement Array.Reverse(Array). If you look at how it is implemented in the framework itself and ignore many technical details around, you’ll find that it just calls its three-parameter version (which reverses specified part of an array) on the whole array.

基本上,您需要重新实现Array.Reverse(数组)。如果您查看它是如何在框架本身中实现的,而忽略周围的许多技术细节,您会发现它只是在整个数组上调用它的三参数版本(颠倒数组的指定部分)。



Array.Reverse(Array,Int32,Int32) is a while-loop that swaps elements and maintains two indexes:

Array.Reverse(Array,Int32,Int32)是一个WHILE循环,它交换元素并维护两个索引:




  1. i points to the first element of the reversed part, and

  2. j points to the last element of the reversed part.



Rewritten to be substituted in place of // some code here in the question:

重写以替换问题中//此处的一些代码:



int i = 0;
int j = arr.Length - 1;
while (i < j)
{
var temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
i++;
j--;
}


This is easier to grasp than the implementation using for-loop, does less arithmetic and elegantly evades the gotcha with double reversion.

这比使用for-loop的实现更容易掌握,做的算术更少,并且通过双重回归优雅地避开了陷阱。



That is So Simple Start loop from Array legth and so on watch code and you will get understand :)))

这是来自数组、LEGTH等观察代码的如此简单的开始循环,您将理解:)



        int[] arr = new int[5] { 1, 2, 3, 4, 5 };

for (int i = arr.Length-1; i >= 0; i--)
{
Console.WriteLine(arr[i]);
}


int[] arr1 = {1,3,4,9,8};
int[] arr2 = new int[5];

int j = 0;

for(int i = arr1.Length - 1; i >= 0; i--)
{
arr2[j] = arr1[i];
j++;
}


Well, obviously you can just copy to a new array, in reverse order.

显然,您只需以相反的顺序复制到新的数组中。



To do the operation "in place", you can work from both ends towards the middle: Load the first and last elements, then store them back, the first into the last location, and the last into the first location. Then do the second and the next-to-last, etc. If you have an even number of elements you do N/2 iterations. If an odd number you do (N-1)/2 iterations and leave the middle element where it was.

要进行“就地”操作,您可以从两端向中间操作:加载第一个和最后一个元素,然后将它们存储回去,第一个元素存储到最后一个位置,最后一个元素存储到第一个位置。然后做第二个和倒数第二个,依此类推。如果你有偶数个元素,你就做N/2次迭代。如果是奇数,则进行(N-1)/2次迭代,并将中间的元素保留在原来的位置。



There are probably other algorithms that would be marginally faster when considering cache line size and other memory characteristics, but they wouldn't be worth it unless you were in a really performance-critical situation.

在考虑高速缓存线大小和其他内存特征时,可能有其他算法会稍微快一些,但除非您处于真正的性能关键型情况下,否则它们不值得这么做。



for (int i = 0; i < array.Length - i; i++)
{
var value = array[array.Length - i - 1];
array[array.Length - i - 1] = array[i];
array[i] = value;
}


// without using Reverse method and without using additional array
// try yield operator starting from the last element

//不使用反转方法,不使用额外的数组//尝试从最后一个元素开始的Year运算符



public IEnumerable<int> Reverse (int[] array)
{
for (int i = array.Length - 1; i >= 0; i--) {
yield return array [i];
}
}


char[] strx = { '1','2','3','4','5','6','7','8','9' };
int i = strx.Length;
string ktr ="";

while (i>0)
{
i--;
ktr += strx[i];

if (i==0)
{
i = strx.Length;

while (i > 0)
{
i--;
strx[i] = ktr[i];
}

}
}
int j;
Console.WriteLine("Array strx in reverse order: ");
for (j = 0; j < strx.Length; j++ )
{
Console.Write("{0}", strx[j]);
}


try something like:

试着这样做:



var counter = 1;
var newArr = new int[arr.length];
for(int i = 0; i < arr.length; i++)
{
newArr[i] = arr[arr.length - counter];
counter++;
}


I didn't test that but it should be on the right track. Any reason you dont want to use Array.Reverse? Its probably a well-optimized version of the algorithm.

我没有测试这一点,但它应该是在正确的轨道上。有任何不想使用数组的原因吗?它可能是该算法的优化版本。



You can do this in many ways, from the most fast to the most stupid like:

你可以用很多方法来做到这一点,从最快的到最愚蠢的,比如:



int[] arr = new int[] { 1,2,3 };
arr = (from a in arr orderby a descending select a).ToArray();


But I cannot understand why are you pursuing such a futile quest, if that is to impress someone somewhere then use this instead of the for loops :)

但我不明白你为什么要追求如此徒劳的追求,如果这是为了在某个地方给某人留下深刻印象,那么就使用这个而不是For循环:)



I am not good at loops at all. But this is what seems simple to me -

我一点也不擅长弧圈球。但在我看来这很简单--



 int[] array1 = { 1, 2, 3, 4, 5 };

int[] reverseArray = new int[array1.Length];

for (int i = 0; i <= array1.Length - 1; i++)
{
reverseArray[i] = array1[array1.Length - i - 1];
}


This is the dynamic solution for reversing the array of any datatype.Some of the key points in my algorithm is first calculate the half of array length and add check to stop iteration when array indexes have same value.The stage having same indexes depict that it start the reverse operation again.So at this stage break the outer loop by using "goto Statement".

该算法的关键点之一是先计算数组长度的一半,当数组索引相同时增加检查停止迭代,索引相同的阶段描述再次开始反转操作,所以在这个阶段使用GOTO语句来中断外循环。



string[] unreversed = {"A","B","C","D","E","F","G","H","I","J","K"};
int q=unreversed.Length;
int t = q / 2;
var temp1 = "A";
for(int i = 0;i<unreversed.Length;i++)
{
q = q - 1;
for(int k=q;k<=q;k++)
{
if (unreversed[k] != unreversed[i] && i!=t)
{
temp1 = unreversed[i];
unreversed[i] = unreversed[k];
unreversed[k] = temp1;

}
else
{
goto printarray;

}

}

}
printarray:
foreach (var k in unreversed)
{
Console.WriteLine(k);

}


//Create temp array with the same size.
int[] arrTemp = new int[arr.Length];
int i = 0;
//Assign last value of arr to first value of arrTemp
for (int j = arr.Length - 1; j >= 0; j--)
{
arrTemp[i] = arr[j];
i++;
}
arr = arrTemp;


I prefer a LINQ expression that uses an index:

我更喜欢使用索引的LINQ表达式:


using System.Linq;

int[] arr = { 1, 3, 4, 9, 8 };
arr = arr.Select((n, idx) => new {n, idx})
.OrderByDescending(r => r.idx)
.Select(r => r.n).ToArray();


You can try this, Without using additional temporary variable:

您可以尝试这样做,而无需使用其他临时变量:


for(int i = left; i < right/2; i++)
{
(nums[i], nums[right - i - 1]) = (nums[right - i - 1], nums[i]);
}


C# Solution

C#解决方案


using System;
public class Program { public static void Main() { int[] arr = new int[] { 1, 2, 3, 4, 5, 6 };
//---------------------------------------------------------------------------------------------------------------------
// 1 Print Array as 1, 2, 3, 4, 5, 6
//---------------------------------------------------------------------------------------------------------------------
Console.WriteLine(string.Join(",", arr));
//---------------------------------------------------------------------------------------------------------------------
// 2> Write code to reverse it
//---------------------------------------------------------------------------------------------------------------------
int temp=0;
int left=0,right=arr.Length-1;
while(left<right)
{
temp=arr[left];
arr[left]=arr[right];
arr[right]=temp;
left++;
right--;
}
//---------------------------------------------------------------------------------------------------------------------
// 3> Print reversed Array as 6, 5, 4, 3, 2, 1
//---------------------------------------------------------------------------------------------------------------------
Console.WriteLine(string.Join(",", arr));
}


Stack stack=new Stack;
var newArr = new int[arr.length];

for(int i = 0; i < arr.length; i++)
{
stack.push(arrr[i])
}
for(int i = 0; i < arr.length; i++)
{
newarr[i]= stack.pop()
}


int[] array1 = { 1, 2, 3, 4, 5 };

for (int x = 4; x < array1.Length && x != -1; x--)
{
int tmp;
tmp=array1[x];
Console.Write("{0} ", tmp);
}


That's my solution for this.

这就是我的解决方案。



It is better to use Array.Reverse method

最好使用Arrae.Reverse方法



int[] arr ={1,3,4,9,8};
Array.Reverse(arr);


You can read more description Here

你可以阅读更多描述这里



int[] triangles = new int[]{0,1,2,3}    
for (int j = triangles.Length; j > (triangles.Length / 2); j--)
{
var temp = triangles[j - 1];
triangles[j - 1] = triangles[triangles.Length - j];
triangles[triangles.Length - j] = temp;
}


I would prefer to reverse an array from the end of it. My solution's above.

我更喜欢从数组的末尾反转数组。我的解决方案在上面。



    public int[] Reverse(params int[] numbers)
{
for (int i = 0; i < numbers.Length / 2; i++)
{
int tmp = numbers[i];
numbers[i] = numbers[numbers.Length - i - 1];
numbers[numbers.Length - i - 1] = tmp;
}

return numbers;
}


Here is an example of reversing an array using the Length() function and a simple for loop.

下面是使用Long()函数和一个简单的for循环来反转数组的示例。


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text.RegularExpressions;

namespace Rextester
{
public class Program
{
public static void Main(string[] args)
{
int[] arr = new int[] {4, 8, 2, 9, 5, 5};

int length = arr.Length;

for(int i = 0; i < arr.Length; i++)
{
Console.WriteLine(arr[length-1] + " ");
length = length - 1;
}
}
}
}


Console.WriteLine("Enter a string");
string input = Console.ReadLine();

string s = "";
for (int i = input.Length-1 ; i >= 0; i--)
{
s = s + input[i];
}
Console.WriteLine(s);


Can do this with single for loop..

可以使用单个for循环来实现这一点。


   int[] arr ={1,3,4,9,8};


for(int i=arr.length-1;i>=0;i--)
{
Console.Write(arr[i]);
}

更多回答

for (int i = 0; i < arr.Length; i++) Console.WriteLine(arr[i] + ",");

For(int i=0;i

By the way, CoreCLR adds a generic Array.Reverse<T>() that performs better and is simpler to read. It was proposed in issue #2352.

顺便说一下,CoreReader添加了一个通用的Array.Reverse(),它的性能更好,更易于阅读。在第2352号问题中提出。

This prints out the elements of the array in reverse order, but that is not what was asked for. The question was how to reverse the array.

这将以相反的顺序打印出数组的元素,但这并不是所要求的。问题是如何反转阵列。

This does not reverse an array. It creates a new array in reverse order.

这不会反转数组。它以相反的顺序创建一个新数组。

Okay, so assign arr2 back to arr1 at the end. The basic gist is there.

好的,那么在最后将arr2赋值回arr1。基本的要点就在这里。

that still doesn't reverse the original array.

这仍然不能反转原始数组。

Please add also an explanation what your answer (meaning code) does.

还请添加一个解释,说明您的答案(意思是代码)是做什么的。

Hi Mohammad; your code might work, but with some context it would make a better answer; for example, you could explain how and why this proposed change would resolve the questioner's problem, perhaps including a link to the relevant documentation. That would make it more useful to them, and also more useful to other site readers who are looking for solutions to similar problems.

您好,Mohammad;您的代码可能可以工作,但在某些上下文中它会提供更好的答案;例如,您可以解释这个提议的更改将如何以及为什么将解决提问者的问题,也许包括相关文档的链接。这将使它对他们更有用,也对其他正在寻找类似问题解决方案的网站读者更有用。

What does this add that was not already provided by this answer 5 years earlier?

这增加了什么是5年前这个答案没有提供的?

While interesting it does not actually work as answer - OP asked to reverse the array and not to produce new array/sequence in reverse order.

虽然很有趣,但它实际上并不像Answer-op所要求的那样反转数组,并且不以相反的顺序生成新的数组/序列。

Note that - apart from this being limited to string - this uses a lot of new string allocations in ktr += strx[i]; (why not rather use a StringBuilder then?) .. it still doesn't reverse the original input like Array.Reverse which is what the question was about

请注意,除了仅限于字符串之外,它还在ktr+=strx[i]中使用了大量新的字符串分配;(那么为什么不使用StringBuilder呢?)它仍然不能像Array那样反转原始输入。

You do know that you can assign more than one variable in for loop? for(int i=0,counter = 1; i < arr.Length; i++,counter++)

您知道在for循环中可以为多个变量赋值吗?For(int i=0,count=1;i

@TheMuffinMan That is really useful and even after years of C# coding i have never come across that. Or maybe i have but have forgotten about it, either way, i feel like i learned something today.

@TheMuffinMan,这真的很有用,即使在多年的C#编码之后,我也从未遇到过这样的情况。或者也许我已经忘记了,不管怎样,我觉得我今天学到了一些东西。

I get asked these types of questions all the time in interviews.

在面试中,我总是被问到这样的问题。

this crates a new array instead of actually reversing the array.

这将创建一个新数组,而不是实际反转数组。

This is probably the most common interview question for programming jobs :) Using .reverse() does not cut it for that situation :)

这可能是编程工作中最常见的面试问题:)在这种情况下,使用.verse()并不能解决问题:)

This code doesn't work for his example (1, 3, 4, 9, 8)!

此代码不适用于他的示例(1,3,4,9,8)!

No actually it doesn't. What this linq expression does is to crate a new array and assign it to the address of the arr variable. That's not sorting the existing array.

不,实际上不是。这个Linq表达式所做的是创建一个新的数组,并将其赋给arr变量的地址。这不是对现有数组进行排序。

Here's the reason that they're assigned this 'futile quest'. Yes, it can be done automatically. But the interviewer is not looking for 'Can you tell me the function to use?' They're looking for the candidate's grasp on the actual workings of that function. Can they take the logical steps to get there? Basically, these types of questions can be answered the same way in any language, or in pseudocode, or in organizing a deck of physical cards.

这就是为什么他们被分配到这个“徒劳的任务”的原因。是的,它可以自动完成。但这位面试官并不是在寻找“你能告诉我该用什么功能吗?”他们正在寻找候选人对这一功能的实际运作的掌握情况。他们能采取合乎逻辑的步骤来实现这一目标吗?基本上,这些类型的问题可以用任何语言、伪代码或组织一副实体卡片的方式来回答。

@bleeptzer True, but the question wasn't to sort the array anyway. It was to reverse it. That's the main reason this answer is wrong.

@bleeptzer True,但问题不在于如何对数组进行排序。这是为了扭转这一局面。这就是这个答案错误的主要原因。

please provide some explanation for your answer for clarification and avoid posting code only answers.

请为您的答案提供一些解释,以求澄清,并避免发布仅限代码的答案。

This solution works but it has the problem that it iterates through the array twice. Furthermore the usage of a stack adds to the inefficiency of the algorithm. An easier way to do it is to swap the first and last, second and second to last and so on elements... by iterating only once through the array and using a 3-way swap.

此解决方案有效,但它有一个问题,即迭代数组两次。此外,堆栈的使用增加了算法的低效。一种更简单的方法是交换第一个和最后一个、第二个和倒数第二个元素,依此类推。只在数组中迭代一次,并使用3向交换。

Better in which regard? Array.Reverse is for generic arrays (including multidimensional) and does a lot of casting and checks internally you can skip if you already know your type .. see this answer

在哪方面更好?Reverse用于泛型数组(包括多维),并在内部执行大量的强制转换和检查,如果您已经知道自己的类型,则可以跳过。请看下面的答案

So far does not look useful - this is essentially the same as accepted answer except for whatever reason you suggesting to iterate down... Please clarify why this is better approach.

到目前为止,这看起来没有什么用处--这基本上与公认的答案相同,除了您建议向下迭代的任何原因...请澄清为什么这是更好的方法。

What was the point of suggesting the same answer as accepted one? That question has already answered and your answer did not add any value to the existing solution.

提出与公认的答案相同的答案有什么意义?这个问题已经得到了回答,而您的回答并没有为现有解决方案增加任何价值。

This is just an overly complicated way of writing this ... and is still not what is asked for .. the question is not "How to print elements of an array in reversed order" .. but rather "How to reverse elements within an array"

这只是写这篇文章的一种过于复杂的方式。仍然不是所要求的..问题不是“如何以相反的顺序打印数组元素”。而是“如何反转数组中的元素”

Wrong answer. The question is about reversing an array, not reversing a string.

回答错误。问题是反转数组,而不是反转字符串。

This neither does what asked in the question (reverse array) nor produces output expected (has extra comma) - not sure why it is posted as answer.

这既不会产生问题中所要求的结果(反数组),也不会产生预期的输出(带有额外的逗号)--不确定为什么会发布为答案。

(and exactly the same as another "answer" to this question stackoverflow.com/a/31829476/477420)

(与这个问题的另一个“答案”完全相同,stackoverflow.com/a/31829476/477420)

@AlexeiLevenkov I have tried it before posting as answer and it produces output as expected with comma (not extra). In this answer [link] (stackoverflow.com/a/31829476/477420) there is no need to use ToString() and also it doesn't produce answer as expected with comma(It will print on new line)

@AlexeiLevenkov我在作为答案发布之前已经尝试过了,它会产生预期的带有逗号的输出(而不是额外的)。在这个答案[链接](stackoverflow.com/a/31829476/477420)中,不需要使用ToString(),也不会像预期的那样生成带有逗号的答案(它将打印在新行上)

I have no idea what you tried, but code in the post has no way to print less commas than numbers.

我不知道您尝试了什么,但是POST中的代码不可能打印比数字少的逗号。

27 4 0