I know that's easy, but I don't understand how I should do it.
1 23 29 18 43 20 5
to
5 1 23 29 18 43 20
I think we should use for-loop:
for (int i = 0; i < numbers.Count - 1; i++)
{
}
but I don't know what to do in it. Something like numbers[i] = numbers[i - 1] but it isn't working. I think there are some if checks which I miss.
The most straightforward way that comes to mind is a reverse loop.
int[] numbers = { 1, 23, 29, 18, 43, 20, 5};
int lastVal = numbers[numbers.Length - 1];
for (int i = numbers.Length -1; i > 0; i--)
numbers[i] = numbers[i-1];
numbers[0] = lastVal;
Just looping from the end (after saving the last value) and moving "up" the values, finally replacing the first value with the last
Here's a oneliner:
var numbers = new[] {1, 23, 29, 18, 43, 20, 5};
numbers = new[] {numbers.Last()}.Concat(numbers.Take(numbers.Length - 1)).ToArray();
This creates a new array containing the last element, then concatenates it with the original array excluding the last element.
What you want to do is make another array of the same size as the original one, then assign the last element and loop through the array up to the previous to last element.
Something like this:
int[] original = {1, 23, 29, 18, 43, 20, 5};
int[] altered = new int[original.length];
altered[0] = original[original.length - 1];
for (int i = 1; i < original.length - 1; i++)
{
altered[i] = original[i - 1];
}
You can perform a left rotation to the table by six positions on your case and create the requested new table
int[] myArray = new int[] { 1, 23, 29, 18, 43, 20, 5 };
var newArray = LeftRotationByD(myArray, 6);
and your function for the rotation would be:
private static int[] LeftRotationByD(int[] a, int k)
{
int[] b = new int[a.Length];
int index;
int length = a.Length;
int place;
for (int i = 0; i < length; i++)
{
index = i - k;
place = length + index;
if (index >= 0) b[index] = a[i];
else b[place] = a[i];
}
return b;
}
You can use this method to shift right:
void ShiftRight(int[] array, int count)
{
var clone = (int[])array.Clone();
for (var i = 0; i < array.Length; i++)
array[(i + count) % array.Length] = clone[i];
}
And use it this way:
var a = new int[] { 1, 2, 3, 4 };
ShiftRight(a, 1);
Related
I want to make a function that takes an array of integers as input and print an array of int as Fibonaci series like: third element= second element + first element.
Here is my code so far:
static void Result(int[] arr)
{
for (int i = 0; i < arr.Length; i++)
{
if (arr[i] < 0)
Console.WriteLine("arr[i]", arr[i], " number to get must be greater or equal than 0");
var n = arr[i] + 1;
var a = new int[n];
arr[0] = 0;
if (arr[i] == 0)
{
a[1] = 1;
}
for ( i = 2; i < n; i++)
{
a[i] = a[i - 2] + a[i - 1];
}
}
}
public static void Main()
{
int[] arr = {7, 8, 3, 9, 11,16,14,91, };
Result(arr);
}
if input is : 1 ,3 ,4 ,6, 7 ,8 10, 11, 15 ,25 output should be: 1, 3, 4, 7, 11 so 1+3=4, 4+3=7 and so on.
I took a look at your code and you were very close.
The biggest issue was you were starting at i = 0 which would cause errors if you attempted to access arr[-1] and arr[-2].
We can solve that by starting with i = 2.
For example:
static int[] Result(int[] arr)
{
int[] result = arr;
for (int i = 2; i < arr.Length; i++)
{
result[i] = result[i-1] + result[i-2];
}
return result;
}
int[] arr = { 1 ,3 ,4 ,6, 7 ,8, 10, 11, 15 ,25 };
arr = Result(arr);
Console.WriteLine(string.Join(", ",arr));
// outputs: 1, 3, 4, 7, 11, 18, 29, 47, 76, 123
Another side note is that unless you're passing the int[] arr as a reference you will need to return a new int[] as the result since Result()'s changes to arr are not reflected on the array.
I want to pass int a[] values into int b[]. but I'm facing confusion. Can anyone correct me out. The output of b is 0,0,0,45,4,2,1. it supposed to be like 7,6,5,4,45,2,1.
static void Main()
{
int[] a = new int[] { 1, 2, 45, 4, 5, 6, 7 };
int[] b = new int[7];
int temp = 0;
for (int i = 0; i <= a.Length - 1; i++)
{
b[(b.Length - i) - 1] = a[i];
Console.WriteLine(b[i]);
}
}
The problem here is that you're inserting items starting from the last index of b, but you're outputting them starting from the first index. The code to copy the items is correct, but you need to adjust your line that outputs the result to the console to show the items in b using the same index that you just used to insert the item.
Note there are a couple of other improvments you can make, such as using array initializer syntax for a, using a.Length to instantiate b instead of a hard-coded number, removing the unused temp variable, using i < a.Length for the for condition (instead of i <= Length - 1, which does a subtraction operation on each iteration), and storing the b index in a variable instead of calculating it twice:
static void Main()
{
int[] a = new int[] {1, 2, 45, 4, 5, 6, 7};
int[] b = new int[a.Length];
for (int i = 0; i < a.Length; i++)
{
int bIndex = b.Length - i - 1;
b[bIndex] = a[i];
Console.WriteLine(b[bIndex]);
}
Console.ReadLine();
}
However, this will still output the items in the order in which you insert them, which will be the same order as they appear in a. If you want to show that the items in b are the reverse of a, the easiest way is to do it after you've populated b. Note we can make use of the string.Join method here to join each item with a comma:
static void Main()
{
int[] a = new int[] {1, 2, 45, 4, 5, 6, 7};
int[] b = new int[a.Length];
for (int i = 0; i < a.Length; i++)
{
b[b.Length - i - 1] = a[i];
}
Console.WriteLine($"'a' array: {string.Join(",", a)}");
Console.WriteLine($"'b' array: {string.Join(",", b)}");
Console.ReadLine();
}
Output
If you want to create a reverse array from an existing array, you can use Reverse extension method:
//using System.Linq;
int[] a = new int[] { 1, 2, 45, 4, 5, 6, 7 };
int[] b = a.Reverse().ToArray();
You can learn more about Extension Methods.
You can have this syntax
int[] a = {1, 2, 45, 4, 5, 6, 7};
int[] b = new int[7];
for (int i = 0, j = b.Length - 1; i < a.Length; i++, j--)
{
b[i] = a[j];
Console.WriteLine(b[i]);
}
I have a 1D array of ints:
int[] array = { 10, 11, 12, 13, 14, 20, 21, 22, 23, 24, 30, 31, 32,33, 34,40,41,42,43, 44};
I would like to divide this 1D array into a 2D array of 4 rows and 5 columns, where the first 5 values goes into row 1, the next 5 in row 2 and so on. The final result should look like this:
array2D:
[[10, 11, 12, 13, 14]
[20, 21, 22, 23, 24]
[30, 31, 32, 33, 34]
[40, 41, 42, 43, 44]]
In reality the array will be much longer(maybe 100+ rows), but the number of columns is 5 and number of rows is dividable by 5. I have simplified for example. This is what I have tried so far:
int[] array = { 10, 11, 12, 13, 14, 20, 21, 22, 23, 24, 30, 31, 32,33, 34,40,41,42,43, 44};
int[,] array2D = new int[(array.Length/5),5];
int count_0 = 1;
int count_1 = 1;
int count_2 = 1;
int count_3 = 1;
int count_4 = 1;
for (int i = 0; i < array.Length; i++)
{
if (i < 5)
{
// works for the first 5 values:
array2D[0, i] = array[i];
}
// I tried this approach for the rest where I try to say that if Im at index 5,
//and every 5th element from here, append to it to index[i,0] of array2D and so on.
// This do not work, and is what I need help with.
else if (i >= 5 && i % 5 == 0)
{
array2D[count_0, 0] = array[i];
count_0++;
}
else if (i >= 6 && i % 5 == 0)
{
array2D[count_1, 1] = array[i];
count_1++;
}
else if (i >= 7 && i % 5 == 0)
{
array2D[count_2, 2] = array[i];
count_2++;
}
else if (i >= 8 && i % 5 == 0)
{
array2D[count_3, 3] = array[i];
count_3++;
}
else if (i >= 9 && i % 5 == 0)
{
array2D[count_4, 4] = array[i];
count_4++;
}
}
Of course for this example I could just say if > 5 && <10 {append to array2D} and if > 10 && <15 {append to array2D} and so on, but I want something that works for a large array of hundreds of values. If someone has a smarter way to do this please let me know.
Thank you for any help!
You can just calculate the indexes:
for(int i=0;i<array.Length;i++)
array2D[i/5, i%5] = array[i];
You can calculate the indexes easily using simple division. The row is calculated by the dividing i with the wanted column numbers. The column is simply the reminder of that division.
using System;
public class Program
{
public static T[,] SplitInto2DArray<T>(T[] array, int rows, int columns) {
T[,] result = new T[rows, columns];
for (int i = 0; i < array.Length; i++) {
result[i / columns, i % columns] = array[i];
}
return result;
}
public static void PrintArray<T>(T[,] array) {
for (int i = 0; i < array.GetLength(0); i++) {
for (int j = 0; j < array.GetLength(1); j++) {
Console.Write(array[i, j] + " ");
}
Console.WriteLine();
}
}
public static void Main()
{
int[] array = { 10, 11, 12, 13, 14, 20, 21, 22, 23, 24, 30, 31, 32, 33, 34, 40, 41, 42, 43, 44};
int[,] splittedArray = SplitInto2DArray(array, 4, 5);
PrintArray(splittedArray);
}
}
You can accomplish with LINQ using Enumerable.GroupBy.
array.GroupBy(x => x / 5)
.Select(x => x.ToArray())
.ToArray()
assume i create this code to generate the idv-th random number. But i have a difficulty in sorting the array depends on the last column.
let say the individual size is [idv, width] = [8,6]
and i want to sort all the row with column 6th... and i want to take the 4 top list in the array after it sorted. How can i implement this case to the code??
public static void population(double[,] individual, int width, int idv, Random rnd)
{
for (int i = 0; i < idv; i++)
{
Console.Write("individual {0} :\t", i+1);
for (int j = 0; j < width; j++)
{
individual[i, j] = Math.Round(rnd.NextDouble() * 10, 2);
Console.Write("{0} ", individual[i, j]);
}
Console.WriteLine("\n");
}
}
Thank you
I suggest you using jagged arrays double[][] instead of 2d ones double[,]. Jagged array is just an array of array which you can easily sort, filter, etc. usually with a help of Linq:
double[][] individual = new double[][] {
new double[] {81, 82, 83, 84, 85, 86},
new double[] {11, 12, 13, 14, 15, 16},
new double[] {41, 42, 43, 44, 45, 46},
new double[] {31, 32, 33, 34, 35, 36},
new double[] {51, 52, 53, 54, 55, 56},
new double[] {21, 22, 23, 24, 25, 26},
new double[] {61, 62, 63, 64, 65, 66},
new double[] {71, 72, 73, 74, 75, 76},
};
double[][] fragment = individual
.OrderBy(line => line[line.GetUpperBound(0)]) // by last column
.Take(4)
.ToArray();
One more Linq to test the results:
String test = String.Join(Environment.NewLine, fragment
.Select(line => String.Join("\t", line)));
Console.Write(test);
The result is
11 12 13 14 15 16
21 22 23 24 25 26
31 32 33 34 35 36
41 42 43 44 45 46
If you use multidimensional arrays, there's no easy way to work with them using LINQ, you'll need to rely on good old for.
static void Main ()
{
// Input array
double[,] u = {
{ 1, 9, 3 },
{ 0, 3, 4 },
{ 3, 4, 5 },
{ 3, 6, 8 },
{ 3, 5, 7 },
};
// Get dimension sizes, specify column to order by
int count = u.GetLength(0), length = u.GetLength(1), orderBy = 2;
// Result array
double[,] v = new double[count, length];
// Construct a list of indices to sort by
var indices = Enumerable.Range(0, count).OrderBy(i => u[i, orderBy]).ToList();
// Copy values from input to output array, based on these indices
for (int i = 0; i < count; i++)
for (int j = 0; j < length; j++)
v[i, j] = u[indices[i], j];
PrintArray(u);
Console.WriteLine();
PrintArray(v);
}
static void PrintArray (double[,] a)
{
for (int i = 0; i < a.GetLength(0); i++) {
for (int j = 0; j < a.GetLength(1); j++)
Console.Write(a[i, j]);
Console.WriteLine();
}
}
If you need only top 4 rows, you can add Take(4) before ToList() call and adjust result array creation and copying of values into it appropriately.
Multidimenional arrays are more efficient and use less memory, so if your arrays are big enough or you need to work with them faster, you may need to write a little more code and use multidimenional arrays instead of jagged arrays which are easier to work with.
For rectangular array [,] you can copy the desired column in a single-dimensional array together with indices, sort it, and then get rows with first 4 indices.
static IEnumerable<Tuple<int, double>> GetColumn(int columnIndex, double[,] a)
{
for (int i = a.GetLowerBound(0); i <= a.GetUpperBound(0); i++)
yield return Tuple.Create(i, a[i, columnIndex]);
}
double [,] data = ...;
var column = GetColumn(4, data);
var top4Indices = column.OrderBy(v => v.Second)
.Take(4)
.Select(v => v.First);
foreach (int i in top4Indices)
for (int j = data.GetLowerBound(1); j <= data.GetUpperBound(1); j++)
data[i, j]...
I have 2 one dimensional arrays, containing the exact same values:
public int[] start = new int[21] { 0, 1, 1, 1, 1, 1, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 14 };
public int[] end = new int[21] { 0, 1, 1, 1, 1, 1, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 14 };
Below is the code I use to generate a random index, and grab the element from the array with said index, and stick it in a 2D array, with randomly generated X and Y index.
for (int i = 0; i < 21; i++)
{
Random ranNum = new Random();
int genX = 0;
int genY = 5;
int indx = 1;
while (gameBoard[genX, genY].rank > -1)
{
genX = ranNum.Next(0, 9);
genY = ranNum.Next(5, 8);
}
while (start[indx] == -1)
{
indx = ranNum.Next(0, 21);
}
if (gameBoard[genX, genY].rank == -1)
{
gameBoard[genX, genY].rank = start[indx];
start[indx] = -1;
}
while (gameBoard[genX, genY].rank > -1)
{
genX = ranNum.Next(0, 9);
genY = ranNum.Next(0, 3);
}
while (end[indx] == -1)
{
indx = ranNum.Next(0, 21);
}
if (gameBoard[genX, genY].rank == -1)
{
gameBoard[genX, genY].rank = end[indx];
end[indx] = -1;
}
}
Basically, it takes a value from the "start" and "end" arrays, replaces them with a '-1' (so they don't get picked again), scans the 2D array for '-1s' (so it doesn't place the number in a location that already has one), and places it there.
Notice that the min and max value for the random are different for the "start" and "end" arrays. This is to ensure that they end up far away from each other, on the other side of the 2D array.
This code works. Now, I have a code that resets all the variables back to their previous state. A reset function which also works. See, if the user is not content with the random placement, they can reset the arrays, and randomize again.
At which point the program simply hangs / locks up. No error, no messages, it just stops working. Please, could you share any ideas on how / why this happens?
Note: If I remove the entire while loop concerning the "end" array, the program can randomize and reset all it wants.
Anyway, the code for the reset:
int resVal = 0;
for (int i = 0; i < 21; i++)
{
startBoard[i] = resVal;
enemyBoard[i] = resVal;
if (i == 0)
resVal++;
else if (i >= 6 && i < 19)
resVal++;
}
for (int y = 0; y < 8; y++)
{
for (int x = 0; x < 9; x++)
{
gameBoard[x, y] = new classPiece();
gameBoard[x, y].rank = -1;
}
}
Move Random ranNum = new Random(); out of the cycle.