Reverse int array return wrong element - c#

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];
}

Related

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;
}

Remove consecutive numbers from int array

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.

How to get the current length of different arrays in jagged arrays using for-loops in c#

static void Main(string[] args)
{
char[][] array = {new char[] {'2','A','3','E'},
new char[] {'F','A'},
new char[] {'F','F','F','F'},
new char[] {'5','A','0','E','9'}};
List<double> arr = new List<double>();
List<double> results = new List<double>();
for (int i = 0; i < array.Length; i++)
{
double result = 0;
for (int index = 0; index < **array.Length**; index++)
{
char c = array[i][index];
if (c > 47 && c < 58)
{
arr.Add(c - 48);
}
else
{
arr.Add((c - 65)+10);
}
}
int power = arr.Count();
for (int ind = 0; ind < power; ind++)
{
arr[ind] = Math.Pow(16, power - 1) * arr[ind];
power--;
result += arr[ind];
}
arr = new List<double>();
results.Add(result);
}
}
My goal is to convert these HEX numeric system numbers to Decimal numeric system numbers.
I know the easy and short way using Console.WriteLine()methods and Standard Numeric Format Strings, but the point is to do this hard way(using jagged arrays). All code work properly , but i dont know how to do change(or get current) value length of different inner arrays in jagged array. If i do it this way usign array.Length - it stay static and doesnt change like i need. I try to use array.GetLength(i) but it dosent work 2.
for (int i = 0; i < array.Length; i++)
...
for (int index = 0; index < **array.Length**; index++)
To get the required length, try
for (int i = 0; i < array.Length; i++)
...
for (int index = 0; index < array[i].Length**; index++)
You are checking the length of the outer array (array.Length), while you meant to read the size of the second, inner array (array[i].Length). Try this:
for (int i = 0; i < array.Length; i++)
{
double result = 0;
for (int index = 0; index < array[i].Length; index++)
I would prefer for each
var array = new[]{new[] {'2','A','3','E'},
new[] {'F','A'},
new[] {'F','F','F','F'},
new[] {'5','A','0','E','9'}};
foreach (var item in array)
{
Console.WriteLine(item.Length);
}

filling multidimensional array with unique numbers in C#

I'm trying to write a code that will fill array with unique numbers.
I could write the code separately for 1, 2 and 3 dimensional arrays but number of for cycles grow to "infinity".
this is the code for 2D array:
static void fillArray(int[,] array)
{
Random rand = new Random();
for (int i = 0; i < array.GetLength(0); i++)
{
for (int j = 0; j < array.GetLength(1); j++)
{
array[i, j] = rand.Next(1, 100);
for (int k = 0; k < j; k++)
if (array[i, k] == array[i, j])
j--;
}
}
print_info(array);
}
Is it possible to do something like this for n-dimensional arrays?
My approach is to start with a 1-d array of unique numbers, which you can shuffle, and then slot into appropriate places in your real array.
Here is the main function:
private static void Initialize(Array array)
{
var rank = array.Rank;
var dimensionLengths = new List<int>();
var totalSize = 1;
int[] arrayIndices = new int[rank];
for (var dimension = 0; dimension < rank; dimension++)
{
var upperBound = array.GetLength(dimension);
dimensionLengths.Add(upperBound);
totalSize *= upperBound;
}
var singleArray = new int[totalSize];
for (int i = 0; i < totalSize; i++) singleArray[i] = i;
singleArray = Shuffle(singleArray);
for (var i = 0; i < singleArray.Length; i++)
{
var remainingIndex = i;
for (var dimension = array.Rank - 1; dimension >= 0; dimension--)
{
arrayIndices[dimension] = remainingIndex%dimensionLengths[dimension];
remainingIndex /= dimensionLengths[dimension];
}
// Now, set the appropriate cell in your real array:
array.SetValue(singleArray[i], arrayIndices);
}
}
The key in this example is the array.SetValue(value, params int[] indices) function. By building up the correct list of indices, you can use this function to set an arbitrary cell in your array.
Here is the Shuffle function:
private static int[] Shuffle(int[] singleArray)
{
var random = new Random();
for (int i = singleArray.Length; i > 1; i--)
{
// Pick random element to swap.
int j = random.Next(i); // 0 <= j <= i-1
// Swap.
int tmp = singleArray[j];
singleArray[j] = singleArray[i - 1];
singleArray[i - 1] = tmp;
}
return singleArray;
}
And finally a demonstration of it in use:
var array1 = new int[2,3,5];
Initialize(array1);
var array2 = new int[2,2,3,4];
Initialize(array2);
My strategy assigns sequential numbers to the original 1-d array to ensure uniqueness, but you can adopt a different strategy for this as you see fit.
You can use Rank property to get the total number of dimentions in your array
To insert use SetValue method
In the first two for loops you are analysing the array properly (i and j go from the start to the end of the corresponding dimension). The problem comes in the most internal part where you introduce a "correction" which actually provokes an endless loop for j.
First iteration:
- First loop: i = 0;
- Second loop: j = 0;
- Third loop: j = -1
Second iteration
- First loop: i = 0;
- Second loop: j = 0;
- Third loop: j = -1
. etc., etc.
(I start my analysis in the moment when the internal loop is used for the first time. Also bear in mind that the exact behaviour cannot be predicted as far as random numbers are involved. But the idea is that you are making the j counter back over and over by following an arbitrary rule).
What you want to accomplish exactly? What is this last correction (the one provoking the endless loop) meant to do?
If the only thing you intend to do is checking the previously stored values, you have to rely on a different variable (j2, for example) which will not affect any of the loops above:
int j2 = j;
for (int k = 0; k < j2; k++)
if (array[i, k] == array[i, j2])
j2--;

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