Remove consecutive numbers from int array - c#

I want to remove consecutive repeated numbers from array like if a sequence of 2 or more instances of the same integer repeated consecutively appears in that array, the sequence should be removed (see example below).
int[] array = {3, 1, 1, 2, 1, 4, 4, 4};
after removal of consecutive repeated numbers
(like 1,1 and 4,4,4)=>{3,2,1}
thus i want to shift consecutive numbers to end and wanna use Array.Resize() function to resize array.
i don't want complete code, approach will be fine.
static void RemoveRepeated(ref int[] array)
{
int count = 0; bool flag;
for (int i = 0; i < array.Length; i++)
{
flag = true;
for (int j = i+1; j < array.Length-1; j++)
{
if (array[i] == array[j] )
{
int temp = array[j];
array[j] = array[j + 1];
array[j + 1] = temp;
if (flag)
{
count++;
flag = false;
}
}
}
}
Array.Resize(ref array,array.Length-count);
}

Here is how you can do that effectively. I think the code is self explanatory.
static void RemoveRepeated(ref int[] array)
{
int count = 0;
for (int i = 0; i < array.Length; )
{
var current = array[i];
int repeatCount = 1;
while (++i < array.Length && array[i] == current)
repeatCount++;
if (repeatCount == 1)
array[count++] = current;
}
Array.Resize(ref array, count);
}

You can push them in a stack one by one, unless the next element in array is equal to the last element in stack.

Related

Getting Time limit Exceed for last 3 Test Cases in a Program:C# [duplicate]

Given an array of n integers and a number, d, perform left rotations on the array. Then print the updated array as a single line of space-separated integers.
Sample Input:
5 4
1 2 3 4 5
The first line contains two space-separated integers denoting the respective values of n (the number of integers) and d (the number of left rotations you must perform).
The second line contains n space-separated integers describing the respective elements of the array's initial state.
Sample Output:
5 1 2 3 4
static void Main(String[] args)
{
string[] arr_temp = Console.ReadLine().Split(' ');
int n = Int32.Parse(arr_temp[0]);
int d = Int32.Parse(arr_temp[1]);
string[] arr = Console.ReadLine().Split(' ');
string[] ans = new string[n];
for (int i = 0; i < n; ++i)
{
ans[(i + n - d) % n] = arr[i];
}
for (int j = 0; j < n; ++j)
{
Console.Write(ans[j] + " ");
}
}
How to use less memory to solve this problem?
This will use less memory in most cases as the second array is only as big as the shift.
public static void Main(string[] args)
{
int[] n = { 1, 2, 3, 4, 5 };
LeftShiftArray(n, 4);
Console.WriteLine(String.Join(",", n));
}
public static void LeftShiftArray<T>(T[] arr, int shift)
{
shift = shift % arr.Length;
T[] buffer = new T[shift];
Array.Copy(arr, buffer, shift);
Array.Copy(arr, shift, arr, 0, arr.Length - shift);
Array.Copy(buffer, 0, arr, arr.Length - shift, shift);
}
This problem can get a bit tricky but also has a simple solution if one is familiar with Queues and Stacks.
All I have to do is define a Queue (which will contain the given array) and a Stack.
Next, I just have to Push the Dequeued index to the stack and Enqueue the Popped index in the Queue and finally return the Queue.
Sounds confusing? Check the code below:
static int[] rotLeft(int[] a, int d) {
Queue<int> queue = new Queue<int>(a);
Stack<int> stack = new Stack<int>();
while(d > 0)
{
stack.Push(queue.Dequeue());
queue.Enqueue(stack.Pop());
d--;
}
return queue.ToArray();
}
Do you really need to physically move anything? If not, you could just shift the index instead.
Actually you asked 2 questions:
How to efficiently rotate an array?
and
How to use less memory to solve this problem?
Usually efficiency and low memory usage are mutually exclusive. So I'm going to answer your second question, still providing the most efficient implementation under that memory constraint.
The following method can be used for both left (passing negative count) or right (passing positive count) rotation. It uses O(1) space (single element) and O(n * min(d, n - d)) array element copy operations (O(min(d, n - d)) array block copy operations). In the worst case scenario it performs O(n / 2) block copy operations.
The algorithm is utilizing the fact that
rotate_left(n, d) == rotate_right(n, n - d)
Here it is:
public static class Algorithms
{
public static void Rotate<T>(this T[] array, int count)
{
if (array == null || array.Length < 2) return;
count %= array.Length;
if (count == 0) return;
int left = count < 0 ? -count : array.Length + count;
int right = count > 0 ? count : array.Length - count;
if (left <= right)
{
for (int i = 0; i < left; i++)
{
var temp = array[0];
Array.Copy(array, 1, array, 0, array.Length - 1);
array[array.Length - 1] = temp;
}
}
else
{
for (int i = 0; i < right; i++)
{
var temp = array[array.Length - 1];
Array.Copy(array, 0, array, 1, array.Length - 1);
array[0] = temp;
}
}
}
}
Sample usage like in your example:
var array = Enumerable.Range(1, 5).ToArray(); // { 1, 2, 3, 4, 5 }
array.Rotate(-4); // { 5, 1, 2, 3, 4 }
Isn't using IEnumerables better? Since It won't perform all of those maths, won't allocate that many arrays, etc
public static int[] Rotate(int[] elements, int numberOfRotations)
{
IEnumerable<int> newEnd = elements.Take(numberOfRotations);
IEnumerable<int> newBegin = elements.Skip(numberOfRotations);
return newBegin.Union(newEnd).ToArray();
}
IF you don't actually need to return an array, you can even remove the .ToArray() and return an IEnumerable
Usage:
void Main()
{
int[] n = { 1, 2, 3, 4, 5 };
int d = 4;
int[] rotated = Rotate(n,d);
Console.WriteLine(String.Join(" ", rotated));
}
I have also tried this and below is my approach...
Thank you
public static int[] RotationOfArray(int[] A, int k)
{
if (A == null || A.Length==0)
return null;
int[] result =new int[A.Length];
int arrayLength=A.Length;
int moveBy = k % arrayLength;
for (int i = 0; i < arrayLength; i++)
{
int tmp = i + moveBy;
if (tmp > arrayLength-1)
{
tmp = + (tmp - arrayLength);
}
result[tmp] = A[i];
}
return result;
}
I have tried to used stack and queue in C# to achieve the output as follows:
public int[] rotateArray(int[] A, int rotate)
{
Queue<int> q = new Queue<int>(A);
Stack<int> s;
while (rotate > 0)
{
s = new Stack<int>(q);
int x = s.Pop();
s = new Stack<int>(s);
s.Push(x);
q = new Queue<int>(s);
rotate--;
}
return q.ToArray();
}
I've solve the challange from Hackerrank by following code. Hope it helps.
using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
namespace ConsoleApp1
{
class ArrayLeftRotationSolver
{
TextWriter mTextWriter;
public ArrayLeftRotationSolver()
{
mTextWriter = new StreamWriter(#System.Environment.GetEnvironmentVariable("OUTPUT_PATH"), true);
}
public void Solve()
{
string[] nd = Console.ReadLine().Split(' ');
int n = Convert.ToInt32(nd[0]);
int d = Convert.ToInt32(nd[1]);
int[] a = Array.ConvertAll(Console.ReadLine().Split(' '), aTemp => Convert.ToInt32(aTemp))
;
int[] result = rotLeft(a, d);
mTextWriter.WriteLine(string.Join(" ", result));
mTextWriter.Flush();
mTextWriter.Close();
}
private int[] rotLeft(int[] arr, int shift)
{
int n = arr.Length;
shift %= n;
int[] vec = new int[n];
for (int i = 0; i < n; i++)
{
vec[(n + i - shift) % n] = arr[i];
}
return vec;
}
static void Main(string[] args)
{
ArrayLeftRotationSolver solver = new ArrayLeftRotationSolver();
solver.Solve();
}
}
}
Hope this helps.
public static int[] leftrotation(int[] arr, int d)
{
int[] newarr = new int[arr.Length];
var n = arr.Length;
bool isswapped = false;
for (int i = 0; i < n; i++)
{
int index = Math.Abs((i) -d);
if(index == 0)
{
isswapped = true;
}
if (!isswapped)
{
int finalindex = (n) - index;
newarr[finalindex] = arr[i];
}
else
{
newarr[index] = arr[i];
}
}
return newarr;
}
Take the Item at position 0 and add it at the end. remove the item at position 0. repeat n times.
List<int> iList = new List<int>();
private void shift(int n)
{
for (int i = 0; i < n; i++)
{
iList.Add(iList[0]);
iList.RemoveAt(0);
}
}
An old question, but I thought I'd add another possible solution using just one intermediate array (really, 2 if you include the LINQ Take expression). This code rotates to right rather than left, but may be useful nonetheless.
public static Int32[] ArrayRightRotation(Int32[] A, Int32 k)
{
if (A == null)
{
return A;
}
if (!A.Any())
{
return A;
}
if (k % A.Length == 0)
{
return A;
}
if (A.Length == 1)
{
return A;
}
if (A.Distinct().Count() == 1)
{
return A;
}
for (var i = 0; i < k; i++)
{
var intermediateArray = new List<Int32> {A.Last()};
intermediateArray.AddRange(A.Take(A.Length - 1).ToList());
A = intermediateArray.ToArray();
}
return A;
}
O(1) space, O(n) time solution
I think in theory this is as optimal as it gets, since it makes a.Length in-place swaps and 1 temp variable swap per inner loop.
However I suspect O(d) space solutions would be faster in real life due to less code branching (fewer CPU command pipeline resets) and cache locality (mostly sequential access vs in d element steps).
static int[] RotateInplaceLeft(int[] a, int d)
{
var swapCount = 0;
//get canonical/actual d
d = d % a.Length;
if(d < 0) d += a.Length;
if(d == 0) return a;
for (var i = 0; swapCount < a.Length; i++) //we're done after a.Length swaps
{
var dstIdx = i; //we need this becasue of ~this: https://youtu.be/lJ3CD9M3nEQ?t=251
var first = a[i]; //save first element in this group
for (var j = 0; j < a.Length; j++)
{
var srcIdx = (dstIdx + d) % a.Length;
if(srcIdx == i)// circled around
{
a[dstIdx] = first;
swapCount++;
break; //hence we're done with this group
}
a[dstIdx] = a[srcIdx];
dstIdx = srcIdx;
swapCount++;
}
}
return a;
}
If you take a look at constrains you will see that d <= n (number of rotations <= number of elements in array). Because of that this can be solved in 1 line.
static int[] rotLeft(int[] a, int d)
{
return a.Skip(d).Concat(a.Take(d)).ToArray();
}
// using the same same array, and only one temp variable
// shifting everything several times by one
// works, simple, but slow
public static int[] ArrayRotateLeftCyclical(int[] a, int shift)
{
var length = a.Length;
for (int j = 0; j < shift; j++)
{
int t = a[0];
for (int i = 0; i < length; i++)
{
if (i == length - 1)
a[i] = t;
else
a[i] = a[i + 1];
}
}
return a;
}
Let's say if I have a array of integer 'Arr'. To rotate the array 'n' you can do as follows:
static int[] leftRotation(int[] Arr, int n)
{
int tempVariable = 0;
Queue<int> TempQueue = new Queue<int>(a);
for(int i=1;i<=d;i++)
{
tempVariable = TempQueue.Dequeue();
TempQueue.Enqueue(t);
}
return TempQueue.ToArray();`
}
Let me know if any comments. Thanks!
This is my attempt. It is easy, but for some reason it timed out on big chunks of data:
int arrayLength = arr.Length;
int tmpCell = 0;
for (int rotation = 1; rotation <= d; rotation++)
{
for (int i = 0; i < arrayLength; i++)
{
if (arr[i] < arrayElementMinValue || arr[i] > arrayElementMaxValue)
{
throw new ArgumentException($"Array element needs to be between {arrayElementMinValue} and {arrayElementMaxValue}");
}
if (i == 0)
{
tmpCell = arr[0];
arr[0] = arr[1];
}
else if (i == arrayLength - 1)
{
arr[arrayLength - 1] = tmpCell;
}
else
{
arr[i] = arr[i + 1];
}
}
}
what about this?
public static void RotateArrayAndPrint(int[] n, int rotate)
{
for (int i = 1; i <= n.Length; i++)
{
var arrIndex = (i + rotate) > n.Length ? n.Length - (i + rotate) : (i + rotate);
arrIndex = arrIndex < 0 ? arrIndex * -1 : arrIndex;
var output = n[arrIndex-1];
Console.Write(output + " ");
}
}
It's very straight forward answer.
Main thing is how you choose the start index.
public static List<int> rotateLeft(int d, List<int> arr) {
int n = arr.Count;
List<int> t = new List<int>();
int h = d;
for (int j = 0; j < n; j++)
{
if ((j + d) % n == 0)
{
h = 0;
}
t.Add(arr[h]);
h++;
}
return t;
}
using this code, I have successfully submitted to hacker rank problem,
// fast and beautiful method
// reusing the same array
// using small temp array to store replaced values when unavoidable
// a - array, s - shift
public static int[] ArrayRotateLeftWithSmallTempArray(int[] a, int s)
{
var l = a.Length;
var t = new int[s]; // temp array with size s = shift
for (int i = 0; i < l; i++)
{
// save cells which will be replaced by shift
if (i < s)
t[i] = a[i];
if (i + s < l)
a[i] = a[i + s];
else
a[i] = t[i + s - l];
}
return a;
}
https://github.com/sam-klok/ArraysRotation
public static void Rotate(int[] arr, int steps)
{
for (int i = 0; i < steps; i++)
{
int previousValue = arr[arr.Length - 1];
for (int j = 0; j < arr.Length; j++)
{
int currentValue = arr[j];
arr[j] = previousValue;
previousValue = currentValue;
}
}
}
Here is an in-place Rotate implementation of a trick posted by גלעד ברקן in another question. The trick is:
Example, k = 3:
1234567
First reverse in place each of the two sections delineated by n-k:
4321 765
Now reverse the whole array:
5671234
My implementation, based on the Array.Reverse method:
/// <summary>
/// Rotate left for negative k. Rotate right for positive k.
/// </summary>
public static void Rotate<T>(T[] array, int k)
{
ArgumentNullException.ThrowIfNull(array);
k = k % array.Length;
if (k < 0) k += array.Length;
if (k == 0) return;
Debug.Assert(k > 0);
Debug.Assert(k < array.Length);
Array.Reverse(array, 0, array.Length - k);
Array.Reverse(array, array.Length - k, k);
Array.Reverse(array);
}
Live demo.
Output:
Array: 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12
Rotate(5)
Array: 8, 9, 10, 11, 12, 1, 2, 3, 4, 5, 6, 7
Rotate(-2)
Array: 10, 11, 12, 1, 2, 3, 4, 5, 6, 7, 8, 9

SubArray of a 2d array with non-zero lower bounds

The extension :
public static T[,] SubArray<T>(this T[,] values, int row_min, int row_max, int col_min, int col_max)
{
int num_rows = row_max - row_min + 1;
int num_cols = col_max - col_min + 1;
T[,] result = new T[num_rows, num_cols];
int total_cols = values.GetUpperBound(1) + 1;
int from_index = row_min * total_cols + col_min;
int to_index = 0;
for (int row = 0; row <= num_rows - 1; row++)
{
Array.Copy(values, from_index, result, to_index, num_cols);
from_index += total_cols;
to_index += num_cols;
}
return result;
}
work well for 2D arrays arrays whose GetLowerBound(0) and GetLowerBound(1) are equal to zero. For instance if
int[,] arr1 = new int[5, 4];
for (int i = 0; i < 5; ++i)
{
for (int j = 0; j < 4; ++j)
{
arr1[i, j] = i + j;
}
}
var arr1sub = arr1.SubArray(2, 3, 1, 3);
Then arr1sub is the 2d array with 2 rows and 3 colums (boths with indexes starting at 0)
3 4 5
5 6 7
Now if I look at the case where the initial array as indexes not starting at zero :
int[,] arr2 = (int[,])Array.CreateInstance(typeof(int), new int[] { 5, 4 }, new int[] { 3, 1 });
for (int i = arr2.GetLowerBound(0); i <= arr2.GetUpperBound(0); ++i)
{
for (int j = arr2.GetLowerBound(1); j <= arr2.GetUpperBound(1); ++j)
{
arr2[i, j] = i - arr2.GetLowerBound(0) + j - arr2.GetLowerBound(1);
}
}
var arr2sub = arr2.SubArray(5, 6, 2, 4);
the last line of previous code snippet will trigger an exception in the SubArray extension function at the line
Array.Copy(values, from_index, result, to_index, num_cols);
for row equal to zero.
I understand of the 2d array arr1 (with zero based indexes) is layed out in memory but not how the 2d array arr2 (with non-zero-based indexes) is layed out in memory, hence my use of Array.Copy must be wrong in this case, but I don't see why.
You are not calculating total_cols and from_index correctly.
public static T[,] SubArray<T>(this T[,] values, int row_min, int row_max, int col_min, int col_max)
{
int num_rows = row_max - row_min + 1;
int num_cols = col_max - col_min + 1;
T[,] result = new T[num_rows, num_cols];
int total_cols = values.GetLength(1);
int from_index = (row_min - values.GetLowerBound(0)) * total_cols + (col_min - values.GetLowerBound(1)) + values.GetLowerBound(0);
int to_index = 0;
for (int row = 0; row <= num_rows - 1; row++)
{
Array.Copy(values, from_index, result, to_index, num_cols);
from_index += total_cols;
to_index += num_cols;
}
return result;
}
total_cols is the obvious one; as for from_index, I cannot find any documentation on that, but it would appear that sourceIndex in Array.Copy starts counting from sourceArray.GetLowerBound(0) and not from zero, which is not necessarily immediately obvious given that this index keeps growing across rows and columns.

Finding the last repetition index of element in array

How do you retrieve the last repetition index of element in array in C#?
For example you have: int[] array = { 3, 5, 7, 8, 3, 4, 3 , 9 };
And you are searching for
element
3 where index of last repetition is 6.
This is what i have for finding first repetition:
public static int Search(int[] array, int value)
{
for (int i = 0; i < array.Length; i++)
{
if (value == array[i])
{
return i;
}
}
return -1;
}
PS: I can't use any functions or methods. I'm allowed to use only arrays.
Try to search from behind. If you search from the first element of the array, you'll definitely need to search until the end of the array. If you search from behind, you can return the value directly once you find it.
public static int search(int lem, int[] a)
{
for (int i = a.Length - 1; i >= 0; i--)
{
if (lem == a[i])
{
return i;
}
}
return -1;
}
Your question is vague one. If you're looking for any duplicate (not necessary 3) I suggest using HashSet<int> (C# implementation):
int[] array = { 3, 5, 7, 8, 3, 4, 3, 9 };
HashSet<int> used = new HashSet<int>();
int last = -1;
for (int i = 0; i < array.Length; ++i)
if (!used.Add(array[i])) // failed to add to the set, array[i] is a duplicate
last = i;
Console.Write(last);
In case you're looking just for the last ocurrence of 3, try looping backward:
int last = -1;
for (int i = array.Length - 1; i >= 0; --i)
if (array[i] == 3) {
last = i;
break;
}
If you know how to find first repetition, why don't you use array.Reverse(), use the known algorythm, and then subtract found value form array.Length?
But if you want just a single method call, you can modify your solution, to not return the value until it finishes looping through an array:
public static int search(int lem, int[] a)
{
int j = -1;
for (int i = 0; i < a.Length; i++)
{
if (lem == a[i])
{
j = i;
}
}
return j;
}

Reverse int array return wrong element

Here is a simple method in C# to reverse the element of the array. For instance, if I input {1,2,3,4} the result should be {4,3,2,1}.
public int[] reverse(int[] array)
{
int[] new_array = new int[array.Length];
for (int i = 0; i < array.Length-1; i++)
{
new_array[i] = array[array.Length-1 - i];
}
return new_array;
}
However, when I run it and give an input as {1,2,3,4}, it result in {4,3,2,0}, why does the last element become 0 instead of 1?
Issue exists here for (int i = 0; i < array.Length-1; i++).
You have to use <= if you are comparing it with Length-1 or use < sign with Length
Try this code.
public int[] reverse(int[] array)
{
int[] new_array = new int[array.Length];
for (int i = 0; i < array.Length; i++)
{
new_array[i] = array[array.Length-1 - i];
}
return new_array;
}
The problem you are having is that you are checking the array length and subtracting one.
for (int i = 0; i < array.Length - 1; i++)
This says if I is less than the length of your array minus one. There for you will never check the last element in your array.
This may be slightly easier to understand. I am basically running my for loop backwards and keeping a counter for both the new array and the original one.
var array = new int[] { 1, 2, 3, 4 };
int[] new_array = new int[array.Length];
for (int i = array.Length -1, n=0 ; i >= 0 ; i--,n++)
{
new_array[n] = array[i];
}
you can use Linq Instead of Writing Too many lines of code
Using
using System.Linq;
To Reverse Array
var reverse = array.Reverse();
Or
int[] reverse = array.Reverse().ToArray();
You don't need array.Length-1 because this will go beyond the index of array so only array.Length is enough.
int[] array = new int[4] { 4, 3, 2, 1 };
int[] new_array = new int[array.Length];
for (int i = 0; i< array.Length; i++)
{
new_array[i] = array[(array.Length - 1) - i];
}
Try this:
for (int i = array.Length - 1,j=0; i >= 0; i--,j++)
{
new_array[j] = array[i];
}

Reverse an array without using Array.Reverse()

How to reverse an array (in C#) without using Array.Reverse() method?
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.
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.
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,Int32,Int32) is a while-loop that swaps elements and maintains two indexes:
i points to the first element of the reversed part, and
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.
That is So Simple Start loop from Array legth and so on watch code and you will get understand :)))
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++;
}
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;
}
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.
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.
// without using Reverse method and without using additional array
// try yield operator starting from the last element
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 :)
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".
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:
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();
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.
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;
}
}
}
}
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]);
}
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
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.
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);
function printReverse(arr) {
for(var i = arr.length - 1; i >= 0; i--){
console.log(arr[i]);
}
}
printReverse([1, 2, 3, 6, 47, 88]);
function printReverse(arr) {
for (var i = arr.length - 1; i >= 0; i--) {
console.log(arr[i]);
}
}
printReverse([1, 2, 3, 6, 47, 88])
Can do this with single for loop..
int[] arr ={1,3,4,9,8};
for(int i=arr.length-1;i>=0;i--)
{
Console.Write(arr[i]);
}
You can just loop backwards:
int[] arr= new int[] {1, 2, 3, 4, 6};
for(int i=arr.Length-1 ;i>= 0 ; i--)
{
Console.WriteLine(arr[i].ToString());
}

Categories