Related
When I run this code the array has a new size after, is there anything wrong or bad about it ?
static int[] ExpandArray(int[] input, int add_size)
{
for (int i = 0; i < add_size; i++)
{
int[] temp = input;
input = new int[input.Length + 1];
for (var j = 0; j < temp.Length; j++)
{
input[j] = temp[j];
}
}
return input;
}
static void Main(string[] args)
{
int[] ovride = new int[3] { 1, 2, 3 };
ovride = ExpandArray(ovride, 10);
ovride = ExpandArray(ovride, 10);
Console.WriteLine(ovride.Length);
}
is there anything wrong or bad about it ?
This isn't code review, but:
Yes. You should not resize arrays. This involves a new allocation and a copy of all elements. As does Array.Resize(), by the way.
Hey, there is a method that already does this: Array.Resize(). Don't reinvent the wheel.
You definitely should not do the resize in a loop.
So to clean up the code a little:
static int[] ExpandArray(int[] input, int sizeToAdd)
{
// Create a new array with the desired size
var ouput = new int[input.Length + sizeToAdd];
// Copy all elements from input to output
for (int i = 0; i < input.Length; i++)
{
output[i] = input[i];
}
// Return the new array, having the remaining
// items set to their default (0 for int)
return output;
}
You'd actually want input to be updatable by ref, and then end with input = output.
Ultimately, just use a List<int>, as that allows for more efficient resizing, and does so automatically when necessary.
You can use Array.Resize which:
Changes the number of elements of a one-dimensional array to the specified new size.
int[] ovride = new int[3] { 1, 2, 3 };
Array.Resize(ref ovride, ovride.Length + 10);
Array.Resize(ref ovride, ovride.Length + 10);
Console.WriteLine(ovride.Length); // prints 23
But if you expect collection size changes List can be a more suitable option for your goal.
Consider I have an Array,
int[] i = {1,2,3,4,5};
Here I have assigned values for it. But in my problem I get these values only at runtime.
How can I assign them to an array.
For example:
I get the max size of array from user and the values to them now how do I assign them to the array int [].
Or can I use anyother data types like ArrayList etc which I can cast to Int[] at the end?
Well, the easiest is to use List<T>:
List<int> list = new List<int>();
list.Add(1);
list.Add(2);
list.Add(3);
list.Add(4);
list.Add(5);
int[] arr = list.ToArray();
Otherwise, you need to allocate an array of suitable size, and set via the indexer.
int[] arr = new int[5];
arr[0] = 1;
arr[1] = 2;
arr[2] = 3;
arr[3] = 4;
arr[4] = 5;
This second approach is not useful if you can't predict the size of the array, as it is expensive to reallocate the array every time you add an item; a List<T> uses a doubling strategy to minimize the reallocations required.
You mean?
int[] array = { 1, 2, 3, 4, 5 };
array = new int[] { 1, 3, 5, 7, 9 };
array = new int[] { 100, 53, 25, 787, 39 };
array = new int[] { 100, 53, 25, 787, 39, 500 };
Use List<int> and then call ToArray() on it at the end to create an array. But do you really need an array? It's generally easier to work with the other collection types. As Eric Lippert wrote, "arrays considered somewhat harmful".
You can do it explicitly though, like this:
using System;
public class Test
{
static void Main()
{
int size = ReadInt32FromConsole("Please enter array size");
int[] array = new int[size];
for (int i=0; i < size; i++)
{
array[i] = ReadInt32FromConsole("Please enter element " + i);
}
Console.WriteLine("Finished:");
foreach (int i in array)
{
Console.WriteLine(i);
}
}
static int ReadInt32FromConsole(string message)
{
Console.Write(message);
Console.Write(": ");
string line = Console.ReadLine();
// Include error checking in real code!
return int.Parse(line);
}
}
If you want an array, whose size varies during the execution, then you should use another data structure. A generic List will do. Then, you can dynamically add elements to it.
Edit: Marc posted his answer while I was writing mine. This was exactly what I meant.
You could just use the below line instead of calling a separate function:
using System;
public class Test
{
static void Main()
{
Console.WriteLine("Please enter array size");
int size = Convert.ToInt32(Console.ReadLine());
int[] array = new int[size];
for (int i=0; i < size; i++)
{
Console.WriteLine("Please enter element " + i);
array[i] = Convert.ToInt32(Console.ReadLine());
}
Console.WriteLine("Finished:");
foreach (int i in array)
{
Console.WriteLine(i);
}
}
I want to write a program that takes an array of n dimensions from the user (for example user enters a 4*3*3 array - three dimensions) and prints all its items (the order is not important, maybe all the items over 1 continuous line). I've been able to achieve that for an array of 3 but I don't have the slightest clue where to begin for any array of dimension n.
Here's the code so far:
static void Main(string[] args)
{
int[,,] _numberGrid =
{
{
{1,2,3},
{4,5,6},
{7,8,9},
},
{
{1,2,3},
{4,5,6},
{7,8,9},
},
{
{1,2,3},
{4,5,6},
{7,8,9},
},
{
{1,2,3},
{4,5,6},
{7,8,9},
},
{
{1,2,3},
{4,5,6},
{7,8,9},
}
}; //4*3*3
Console.WriteLine(_numberGrid.Rank);
int numberOfDimentions = _numberGrid.Rank;
int[] newArray = new int[_numberGrid.Rank];
for (int i = 0; i<newArray.Length; i++)
{
newArray[i] = _numberGrid.GetUpperBound(i);
}
for(int i = 0; i <= newArray[0]; i++)
{
Console.Write("\n");
for (int j = 0; j <= newArray[1]; j++)
{
Console.Write("\n");
for (int k = 0; k <= newArray[2]; k++)
{
Console.Write(_numberGrid[i, j, k]);
}
}
}
Console.ReadLine();
}
I suppose it's doable using some sort of recursive call, but I'm not sure how to do it. The order in which the items are printed are not important, they could be printed in one continuous line. just to clarify: by any array of dimension n, I mean any desired array which is of dimension n that user enters as input.
Just use Array.Rank, Array.GetValue, Array.GetUpperBound, and an index array
Here is an example
Given
public static bool Inc(int[,] array, int[] index)
{
for (var i = 0; i < index.Length; i++)
if (++index[i] > array.GetUpperBound(i))
index[i] = 0;
else
return true;
return false;
}
public static void Print(int[,] array, int[] index = null)
{
index = index ?? new int[array.Rank];
do Console.WriteLine(array.GetValue(index) + " = " + string.Join(",", index));
while (Inc(array, index));
}
Usage
var test = new[,] { { 1, 2 }, { 3, 4 }, { 5, 6 }, { 7, 8 } };
Print(test);
Output
1 = 0,0
3 = 1,0
5 = 2,0
7 = 3,0
2 = 0,1
4 = 1,1
6 = 2,1
8 = 3,1
Online Demo
Note : I have used a while loop, though you could use recursion, it depends how you want to display the data or what you want to actually do
You can also access the enumerator of a multidimensional array to get each element
var test = new[,] { { 1, 2, 6 }, { 3, 4, 8 }, { 5, 6, 3 }, { 7, 8, 1 } };
foreach (var item in test)
Console.WriteLine(item);
Output
1
2
6
3
4
8
5
6
3
7
8
1
A couple of points to outline a solution:
Storage: You cannot use a standard n-dimensional array, as n is not known at compile time. There's at least two ways you could address this:
Create your own custom data structure NArray, which consists of an array of either references to NArray (of one dimension less) or you base data type (integer).
Use a 1-dimensional array of integers, and keep track of the dimensions "manually", the way n-dimensional arrays of fixed size are implemented internally. E.g. for a 3-dimensional array of dimensions 5x3x3 as in your example you'd keep track of these dimensions [5,3,3] as a variable-size array. All you need to do then is to create a function that converts a multi-dimensional index into a 1-dimensional one.
Note that option 2 will likely be more efficient, but only works if the dimensions are of fixed size (as they are in your example).
Input: You'll first need to obtain the dimension and the sizes. For fixed-size arrays this could simply be [5,3,3]. Afterwards pass in the numbers in a way that lets you identify the indices they belong to. For fixed size arrays, this could simply be the numbers in order (after all, you're just populating a 1-dimensional array).
Output: Once you have the data structure in place, printing should be fairly straight-forward using recursion on sub-arrays of lower dimension.
Example:
Assume we use the 1-dimensional array approach with your data above, mapping the 3-dimensional index [a,b,c] to a*3*3 + b*3 + c. Then a print function could look something like this:
void printArray(int[] data, int[] dimensions, int[] index) {
if ( index.size == dimensions.size ) {
print(data[map_to_1d(dimensions, index)] + ' ');
} else {
print('[ ');
for (int i = 0; i < dimensions[index.size]; i++) {
int[] subIndex = index + { i }; // append i
printArray(data, dimensions, subindex);
}
print(']');
}
}
PS: A different approach that requires less implementation might be to use a library for json objects, which include multi-dimensional arrays as a special case.
This is the code I was looking for in C#
using System;
namespace _nd_arrays
{
class Program
{
static void Main(string[] args)
{
int[,,,] _numGrid2 =
{
{
{
{0,2,3},
{1,0,3},
{1,2,0}
},
{
{11,22,33},
{44,55,66},
{77,88,99}
},
},
{
{
{1,0,3},
{1,2,0},
{0,2,3}
},
{
{111,222,333},
{111,222,333},
{111,222,33333}
},
},
{
{
{1,2,0},
{1,2,0},
{1,2,0}
},
{
{0,0,0},
{0,0,0},
{0,0,0}
},
}
};
int[] ranks = new int[_numGrid2.Rank]; //index.length --> number of dimentiosn
//index items gives us the upper boud for each dimentino
for (int i= 0; i < _numGrid2.Rank; i++)
{
ranks[i] = _numGrid2.GetUpperBound(i);
}
int[] indeces = new int[_numGrid2.Rank];
Console.WriteLine(PrintCustomArray(_numGrid2, ranks, indeces, 0));
Console.ReadLine();
}
static string PrintCustomArray(Array _initialArray, int[] ranks, int[] printIndeces, int currentDimension )
{
string result = "";
if(currentDimension == ranks.Length - 1)
{
for (int i = 0; i <= ranks[currentDimension]; i++)
{
printIndeces[currentDimension] = i;
result = result + _initialArray.GetValue(printIndeces).ToString();
}
}
else
{ //4
for (int i = 0; i <= ranks[currentDimension]; i++)
{
printIndeces[currentDimension] = i;
// //
result = result + PrintCustomArray(_initialArray, ranks, printIndeces, currentDimension +1);
}
}
return result;
}
}
}
this will print all the items in an n-dimensional array over one line, using recursion
ref: http://csharphelper.com/blog/2017/08/iterate-over-items-in-an-array-with-unknown-dimensions-in-c/
I want to shift one element in an array to the right each time whilst leaving the original elements in their specific order in C#.
Ok so I've been asked to reword the code I can understand why so here we go:
I might have a number 48390
//the ar elements have been commented out to show that we never know what ar contains but only the that I will always want to shift; ar[4]
int[] ar = new int[5];
//ar[0] = 4
//ar[1] = 8
//ar[2] = 3
//ar[3] = 9
//ar[4] = 0
while(ar != 04839)
{
Shift code
}
I might input 5 numbers 48390 if you notice its the same number but one digit is out. I want a while loop to rotate that 4 ar[1] to shift until the number forms 04839
I hope this makes sense. I am posting this question because most pages posting information about shifting based on shifting all elements to the right and I only really want to shift one specific element.
Thanks for looking.
edit: I should have been more specific. What if you don't know what each of the array elements could be? So I couldn't depend on "0" as an anchor. as another set of numbers might include another number for example "00238."
This method will give you a sequence of arrays made by inserting a single element into (between) each position in a given array:
public static IEnumerable<T[]> InsertElementBetweenAllPositions<T>(
T[] array, T element)
{
int newLength = array.Length + 1;
for (int i = 0; i < newLength; i++)
{
T[] rtn = new T[newLength];
rtn[i] = element;
Array.Copy(array, 0, rtn, 0, i);
Array.Copy(array, i, rtn, i + 1, array.Length - i);
yield return rtn;
}
}
For your example, you might call it as
foreach (int[] arr in InsertElementBetweenAllPositions(new[] { 6, 7, 8, 9 }, 0))
{
foreach (int i in arr)
Console.Write(i + " ");
Console.WriteLine();
}
How about this:
List<int> l = new List<int>(){0,6,7,8,9};
for (int i=1;i<5;i++)
{
l.Remove(0);
l.Insert(i, 0);
}
What's in your example is a swap, which can be implemented like:
private void Swap(ref int[] array, int index1, int index2)
{
int temp = array[index1];
array[index1] = array[index2];
array[index2] = temp;
}
Calling Swap(ref source, 0, 1) would exchange the first and second element. What you want then is:
for (int i = 0; i < a.Length-1; i++)
{
Swap(ref a, i, i+1);
}
This "bubbles" the first element up to the last position in each iteration.
From the example you need to shift elements around, and the example is a bit confusing over whether you need to loop them around to the start again. I have provided the below example that will loop around to the start - If you do not need to do that, the you can rework the if the statement.
private int[] Shift(int[] a)
{
int zeroPos = Array.IndexOf(a, 0);
int[] rtn = new int[a.Length];
a.CopyTo(rtn, 0);
if (zeroPos + 1 == a.Length)
{
rtn[0] = 0;
for (int i = 0; i < a.Length - 1; i++)
{
rtn[i + 1] = a[i];
}
}
else
{
rtn[zeroPos] = rtn[zeroPos + 1];
rtn[zeroPos + 1] = 0;
}
return rtn;
}
r=ar[0];
for (int i = 0; ar.lenght;i++)
{
ar[i]=ar[i + 1];
}
ar[ar.lenght] = r;
Have you thought about using a LinkedList instead? A linked list data structure is probably more suited to what you are trying to do than an array. The AddFirst, AddLast, AddAfter and AddBefore methods allow you to insert elements into the list in a much more efficient way than re-organizing your array each time.
The disadvantage of linked lists is that you need to read the elements in order. So, it's very efficient for inserting/deleting elements but inefficient for accessing elements randomly.
There is a good overview of LinkedLists here.
Perhaps
int oldLast = ar[ar.Length - 1];
for (int i = ar.Length - 1; i >= 0; i--)
ar[i] = i == 0 ? oldLast : ar[i - 1];
Demo
It is just a permutation of an item , below is the full source code of permutation algorithm.
static List<string> Put(char s1, string list)
{
List<string> str =new List<string>();
for (int i = 0; i < list.Length+1; i++)
{
string s = list.Substring(0, i) + s1.ToString() + list.Substring(i);
str.Add(s);
}
return str;
}
static List<string> Permute(string list,int x)
{
List<string> Result = new List<string>();
if (list.Length == 1)
{
Result.Add(list[0].ToString());
return Result;
}
else
{
char first = list[0];
list = list.Substring(x+1);
List<string> part = Permute(list,0);
foreach (string str in part)
{
List<string> hasBeenPlaced = Put(first, str);
foreach (string str2 in hasBeenPlaced)
{
Result.Add(str2);
}
}
}
return Result;
}
static void Main(string[] args)
{
List<string> per = Permute("abc",0);
for (int i = 0; i < per.Count; i++)
{
Console.WriteLine(per[i]);
}
Console.ReadKey();
}
Now if I add a break after the foreach , your problem has been solved . (it will writes all permuation for just an item which you want , not all of them....)
So change that to :
foreach (string str in part)
{
List<string> hasBeenPlaced = Put(first, str);
foreach (string str2 in hasBeenPlaced)
{
Result.Add(str2);
}
break;
}
Hope to helps you
If you you linq, that's simple :-) But you need a size larger than the array.
ShiftLeft(ar, 1);
private static int[] ShiftLeft(int[] value, int countOfShift = 1)
{
var length = value.Length;
if (countOfShift > length)
{
throw new InvalidOperationException("countOfShift must less then value's length.");
}
var tempList = new List<int>(value);
tempList.RemoveRange(length - countOfShift, countOfShift);
tempList.InsertRange(0, value.Skip(length - countOfShift));
return tempList.ToArray();
}
How do you retrieve the last element of an array in C#?
LINQ provides Last():
csharp> int[] nums = {1,2,3,4,5};
csharp> nums.Last();
5
This is handy when you don't want to make a variable unnecessarily.
string lastName = "Abraham Lincoln".Split().Last();
With C# 8:
int[] array = { 1, 3, 5 };
var lastItem = array[^1]; // 5
The array has a Length property that will give you the length of the array. Since the array indices are zero-based, the last item will be at Length - 1.
string[] items = GetAllItems();
string lastItem = items[items.Length - 1];
int arrayLength = array.Length;
When declaring an array in C#, the number you give is the length of the array:
string[] items = new string[5]; // five items, index ranging from 0 to 4.
New in C# 8.0 you can use the so-called "hat" (^) operator! This is useful for when you want to do something in one line!
var mystr = "Hello World!";
var lastword = mystr.Split(" ")[^1];
Console.WriteLine(lastword);
// World!
instead of the old way:
var mystr = "Hello World";
var split = mystr.Split(" ");
var lastword = split[split.Length - 1];
Console.WriteLine(lastword);
// World!
It doesn't save much space, but it looks much clearer (maybe I only think this because I came from python?). This is also much better than calling a method like .Last() or .Reverse() Read more at MSDN
Edit: You can add this functionality to your class like so:
public class MyClass
{
public object this[Index indx]
{
get
{
// Do indexing here, this is just an example of the .IsFromEnd property
if (indx.IsFromEnd)
{
Console.WriteLine("Negative Index!")
}
else
{
Console.WriteLine("Positive Index!")
}
}
}
}
The Index.IsFromEnd will tell you if someone is using the 'hat' (^) operator
Use Array.GetUpperBound(0). Array.Length contains the number of items in the array, so reading Length -1 only works on the assumption that the array is zero based.
To compute the index of the last item:
int index = array.Length - 1;
Will get you -1 if the array is empty - you should treat it as a special case.
To access the last index:
array[array.Length - 1] = ...
or
... = array[array.Length - 1]
will cause an exception if the array is actually empty (Length is 0).
Also, starting with .NET Core 3.0 (and .NET Standard 2.1) (C# 8) you can use Index type to keep array's indexes from end:
var lastElementIndexInAnyArraySize = ^1;
var lastElement = array[lastElementIndexInAnyArraySize];
You can use this index to get last array value in any length of array. For example:
var firstArray = new[] {0, 1, 1, 2, 2};
var secondArray = new[] {3, 3, 4, 4, 5, 5, 5, 5, 5, 5, 5, 5, 5};
var index = ^1;
var firstArrayLastValue = firstArray[index]; // 2
var secondArrayLastValue = secondArray[index]; // 5
For more information check documentation
The following will return NULL if the array is empty, else the last element.
var item = (arr.Length == 0) ? null : arr[arr.Length - 1]
say your array is called arr
do
arr[arr.Length - 1]
Is this worth mentioning?
var item = new Stack(arr).Pop();
Array starts from index 0 and ends at n-1.
static void Main(string[] args)
{
int[] arr = { 1, 2, 3, 4, 5 };
int length = arr.Length - 1; // starts from 0 to n-1
Console.WriteLine(length); // this will give the last index.
Console.Read();
}
static void Main(string[] args)
{
int size = 6;
int[] arr = new int[6] { 1, 2, 3, 4, 5, 6 };
for (int i = 0; i < size; i++)
{
Console.WriteLine("The last element is {0}", GetLastArrayIndex(arr));
Console.ReadLine();
}
}
//Get Last Index
static int GetLastArrayIndex(int[] arr)
{
try
{
int lastNum;
lastNum = arr.Length - 1;
return lastNum;
}
catch (Exception ex)
{
return 0;
}
}
This is simplest and works on all versions.
int[] array = { 1, 3, 5 };
int last = array[array.Length - 1];
Console.WriteLine(last);
// 5