I want to change the first and last index of every array, so the output in this scenario would be: [2,3,1], [9,4,6] [5,8,4].
Any help would be greatly appreciated!
static void Main(string[] args)
{
int[][] array1 =
{
new []{1,3,2},
new []{6,4,9},
new []{4,8,5}
};
foreach (int i in Snail(array1))
{
Console.WriteLine(i);
}
}
public static int[] Snail(int[][] array)
{
List<int> snail = new List<int>();
foreach (int[] list in array)
{
foreach (int i in list)
{
// how do I change place with first and last index
}
}
CodePudding user response:
You only need one loop since you know the exact two indices you want to operate on
foreach (int[] list in array)
{
if (list.Length < 2) continue; //need 2 elements to swap
int temp = list[0]; //head is stored temporarily
list[0] = list[^1]; //swap happens
list[^1] = temp; //now set tail as temp value (the original head)
}
Note that list[^1]
is the same as saying list[list.Length - 1]
, both meaning the last element