The Array example is {4, 5, 3, 6, 1}
The user will input the index number and the array will be rotated left from the given index number.
Example: If the user input(index number) is 2, the result is: 3 6 1 4 5.
Any better approach?
public static void Main(string[] args)
{
int[] a = { 4, 2, 8, 3, 1 };
int l = a.Length;
int[] b = new int[l];
int x = 0;
x = Convert.ToInt32(Console.ReadLine());
int i = 0;
for (int j = x; j < l; j++)
{
b[i] = a[j];
i++;
}
for (int k = 0; k < x; k++)
{
int v = a[k];
b[i] = a[k];
i++;
}
for (int m = 0; m < b.Length; m++)
{
Console.Write("{0}, ", b[m]);
}
Console.ReadKey();
}
I will use this method
public static int[] CircularShiftLeft(int[] arr, int shifts)
{
var dest = new int[arr.Length];
Array.Copy(arr, shifts, dest, 0, arr.Length - shifts);
Array.Copy(arr, 0, dest, arr.Length - shifts, shifts);
return dest;
}
Usage in your code, i didnt changed the naming
public static void Main(string[] args)
{
int[] a = { 4, 2, 8, 3, 1 };
int x = 0;
x = Convert.ToInt32(Console.ReadLine());
var b = ShiftLeft(a, x);
for (int m = 0; m < b.Length; m++)
{
Console.Write("{0}, ", b[m]);
}
Console.ReadKey();
}
Related
I am trying to randomize a sett of predetermine elements in a 2d array.
using System;
namespace array
{
public class tiles
{
static void Main(string[] args)
{
Random random = new Random();
int[,] tilearr = { { 0, 1, 2 }, { 3, 4, 5 }, { 6, 7, 8 } };
for (int i = 0; i < 3; i++)
{
for (int j = 0; j < 3; j++)
{
Console.Write(tilearr[i, j] + " ");
}
Console.WriteLine();
}
Console.ReadLine();
}
}
}
My problem is if I do something like tilearr[i, j] = random.Next(0, 8); it randomizes the array but doesn't care if there are any duplicates of the same element.
2 6 7
1 1 3
2 7 0
what I am after is more like this:
2 4 8 1 3 0
0 3 1 5 6 8
6 7 5, 2 4 7
A simple and to the point solution would be to have a list of available numbers and then go position by position and randomly select the numbers out of the list.
Like this:
var numbers = new List<int> { 0, 1, 2, 3, 4, 5, 6, 7, 8 };
for(int x = 0; x < 3; ++x) {
for(int y = 0; y < 3; ++y) {
// select a random number from the list ...
int rand = random.Next(0, numbers.Count - 1);
tilearr[x, y] = numbers[rand];
// ... and remove it from the list
numbers.RemoveAt(rand);
}
}
As user Wai Ha Lee stated in the comments a shuffle will achieve what you are looking for. I would recommend the Fisher Yates Shuffle.
public static void Shuffle<T>(Random random, T[,] array)
{
int lengthRow = array.GetLength(1);
for (int i = array.Length - 1; i > 0; i--)
{
int i0 = i / lengthRow;
int i1 = i % lengthRow;
int j = random.Next(i + 1);
int j0 = j / lengthRow;
int j1 = j % lengthRow;
T temp = array[i0, i1];
array[i0, i1] = array[j0, j1];
array[j0, j1] = temp;
}
}
I retrieved this implementation from this answer.
This should be implemented in your code like this,
using System;
namespace array
{
public class tiles
{
static void Main(string[] args)
{
Random random = new Random();
int[,] tilearr = { { 0, 1, 2 }, { 3, 4, 5 }, { 6, 7, 8 } };
Shuffle<int>(random, tilearr);
for (int i = 0; i < 3; i++)
{
for (int j = 0; j < 3; j++)
{
Console.Write(tilearr[i, j] + " ");
}
Console.WriteLine();
}
Console.ReadLine();
}
}
}
Make sure to place the shuffle generic function within your class.
HERE is an example of my implementation on dotnetfiddle.net.
If you generate the array from scratch, it's easier to randomize a one dimensional array, and then load it into a 2D array.
static int[,] GenerateArray(int size)
{
Random r = new Random();
var arr = new int[size, size];
var values = Enumerable.Range(0, size * size).OrderBy(x => r.Next()).ToArray();
for (int i = 0; i < size; i++)
for (int j = 0; j < size; j++)
arr[i, j] = values[i * size + j];
return arr;
}
One way to Randomize would be flatten the 2d array, shuffle it and then recreate based on original dimension. If you want to use Linq/Extension methods, you could do the following
Random random = new Random();
int[,] tilearr = {{ 0, 1, 2 }, { 3, 4, 5 }, { 6, 7, 8 }};
var result = tilearr.OfType<int>()
.OrderBy(x=> random.Next())
.ChunkBy(tilearr.GetLength(1))
.To2DArray();
Where ChunkBy and To2DArray are defined as
public static class Extensions
{
public static IEnumerable<IEnumerable<T>> ChunkBy<T>(this IEnumerable<T> source, int chunkSize)
{
return source
.Select((x, i) => new { Index = i, Value = x })
.GroupBy(x => x.Index / chunkSize)
.Select(x => x.Select(v => v.Value));
}
public static T[,] To2DArray<T>(this IEnumerable<IEnumerable<T>> source)
{
var data = source
.Select(x => x.ToArray())
.ToArray();
var res = new T[data.Length, data.Max(x => x.Length)];
for (var i = 0; i < data.Length; ++i)
{
for (var j = 0; j < data[i].Length; ++j)
{
res[i,j] = data[i][j];
}
}
return res;
}
}
Sample Demo
I am learning C#, and I am doing Multidimensional Arrays at the moment. I want to write a program that reads a matrix and then finds the biggest sum of 2x2 submatrix and prints it.
int[] dimensions = Console.ReadLine()
.Split(", ", StringSplitOptions.RemoveEmptyEntries)
.Select(int.Parse)
.ToArray();
int rows = dimensions[0];
int columns = dimensions[1];
int[,] matrix = new int[rows,columns];
for (int i = 0; i < rows; i++)
{
int[] numbers = Console.ReadLine()
.Split(", ", StringSplitOptions.RemoveEmptyEntries)
.Select(int.Parse)
.ToArray();
for (int j = 0; j < columns; j++)
{
matrix[i, j] = numbers[j];
}
}
int maxSum = int.MinValue;
int selectedRow = -1;
int selectedCol = -1;
for (int row = 0; row < matrix.GetLength(0) - 1; row++)
{
for (int col = 0; col < matrix.GetLength(1) - 1; col++)
{
int currentSum = matrix[row, col] + matrix[row, col + 1] + matrix[row + 1, col] + matrix[row + 1, col + 1];
if (currentSum > maxSum)
{
maxSum = currentSum;
selectedRow = row;
selectedCol = col;
}
}
}
Console.WriteLine($"{matrix[selectedRow, selectedCol]} {matrix[selectedRow, selectedCol + 1]}");
Console.WriteLine($"{matrix[selectedRow + 1, selectedCol]} {matrix[selectedRow + 1, selectedCol + 1]}");
Console.WriteLine(maxSum);
So, I read the matrix, but I am not sure how to start finding the submatrices and compare their sums. I would be very grateful if you could give me some hints.
You need to check values only current, under positions of your i and current, right positions of your j.
I mean it will check like this:
[7,1] [1,3] [3,3]
[1,3] [3,9] [9,8]
And so on.
After every compare, calculate sum of this 2x2 matrix and save it to dictionary.
For return, you just need to find the max value of key and get value of it key.
public class MatrixTest
{
public static IEnumerable<object[]> TestData =>
new List<object[]>
{
new object[]
{
new int[,]
{
{7, 1, 3, 3, 2, 1},
{1, 3, 9, 8, 5, 6},
{4, 6, 7, 9, 1, 0}
},
new int[,]
{
{9, 8},
{7, 9}
},
33
},
new object[]
{
new int[,]
{
{10, 11, 12, 13},
{14, 15, 16, 17}
},
new int[,]
{
{12, 13},
{16, 17}
},
58
}
};
[Theory]
[MemberData(nameof(TestData))]
public void Test(int[,] input, int[,] expectedArray, int expectedSum)
{
MatrixHandler m = new MatrixHandler();
var resp = m.GetMax2x2Matrix(input);
resp.Item1.Should().Be(expectedSum);
resp.Item2.Should().BeEquivalentTo(expectedArray);
}
}
public class MatrixHandler
{
public (int, int[,]) GetMax2x2Matrix(int[,] source)
{
var sumsPlusTempArrays = new Dictionary<int, int[,]>();
int[,] temp;
int sum = 0;
for (int i = 0, n0 = source.GetLength(0) - 1; i <= n0; i++)
{
for (int j = 0, n1 = source.GetLength(1) - 1; j <= n1; j++)
{
if (i + 1 <= n0 && j + 1 <= n1)
{
temp = new int[2,2];
temp[0, 0] = source[i, j];
temp[0, 1] = source[i, j + 1];
temp[1, 0] = source[i + 1, j];
temp[1, 1] = source[i + 1, j + 1];
sum = CalculateSum(temp);
sumsPlusTempArrays.TryAdd(sum, temp);
}
}
}
var key = sumsPlusTempArrays.Select(x => x.Key).Max();
var value = sumsPlusTempArrays[key];
return (key, value);
}
private int CalculateSum(int[,] source)
{
int sum = 0;
for (int i = 0, n0 = source.GetLength(0); i < n0; i++)
{
for (int j = 0, n1 = source.GetLength(1); j < n1; j++)
{
sum += source[i, j];
}
}
return sum;
}
}
I am trying to make a matrix addition program through multithreading, in which i have to divide the rows of both matrices and run them in a separate thread, after that combine all the threads to get the final addition matrix.
i have made the program through single thread but unable to get that done with multiple threads.
this code is for addition with single thread
class Program
{
static void matrixAdd()
{
int[,] a = { { 1, 2, 3 }, { 4, 5, 6 }, { 7, 8, 9 } };
int[,] b = { { 4, 8, 7 }, { 6, 5, 4 }, { 3, 2, 1 } };
int[,] c = new int[3, 3];
int f = c.Length;
int i, m = 0;
int j = 0;
int n = 0;
for (i = 0; i < 3; i++)
{
Console.WriteLine(" ");
for (j = 0; j < 3; j++)
{
Console.Write(" " + a[i, j]);
}
}
Console.Write("\n");
for (m = 0; m < 3; m++)
{
Console.WriteLine(" ");
for (n = 0; n < 3; n++)
{
Console.Write(" " + b[m, n]);
}
}
Console.Write("\n");
for (int k = 0; k < 3; k++)
{
Console.WriteLine("");
for (int l = 0; l < 3; l++)
{
Console.Write(a[k, l] + b[k, l] + "\t");
}
}
}
static void Main(string[] args)
{
Thread t1 = new Thread(matrixAdd);
t1.Start();
Console.ReadLine();
}
I am just sorting an array and my code seem to be fine but I am unable to resolve the Array Out of Bound Exception. Any ideas.
static void Main(string[] args)
{
int temp = 0; // For temporary holding array values for swapping
int [] num = new int[] {1, 4, 7, 6, 9, 3, 0, 8, 5, 2 };
for (int i = 0; i <= 9; i++) //Outer loop
{
for (int j = 0; j < 9; j++) // Inner loop
{
if (num[j] > num[j + 1])
{
temp = num[j + 1];
num[j + 1] = num[j];
num[j] = temp;
}
}
}
//Displaying the array
for (int i = 0; i < 9; i++)
Console.WriteLine(num[i]);
Console.ReadKey();
}
Modifying the second loop to "j < loopSize - i" (instead of j < loopSize) will double the efficiency of your bubble sort. :)
int[] num = new int[] { 1, 4, 7, 6, 9, 3, 0, 8, 5, 2 };
//int comparisons = 0;
int loopSize = num.Length - 1;
for (int i = 0; i <= loopSize; i++) //Outer loop
{
for (int j = 0; j < loopSize - i; j++) // Inner loop
{
//comparisons++;
if (num[j] > num[j + 1])
{
temp = num[j + 1];
num[j + 1] = num[j];
num[j] = temp;
}
}
}
//Displaying the array
for (int i = 0; i < num.Length; i++)
Console.WriteLine(num[i]);
//Console.WriteLine("comp: {0}", comparisons);
//Console.ReadKey();
}
I have some problems with comparison of matrix elements. Here is the code:
int coll = 0;
for (int i = 0; i < 9; i++)
{
for (int j = 0; j < 9; j++)
{
int tmp = 0;
for (int k = 0; k < 9; k++)
{
if (matrix[i, j] == matrix[i, k])
{
tmp++;
Console.WriteLine("{0},{1} coll {2},{3}-al", i, j, i, k);
}
coll += tmp;
}
}
}
The code wants to compare the elements of an array called matrix. When 2 elements in a column are the same, I'll increase the tmp value. At the end coll will be increased by the number of the collisions of the actual element of the array. The problem is that the program will find only the collisions of the element with itself. For example, for a matrix like
1234
1342
2341
2413
the 0:0 position will collide only with itself and not with 1:0. Can anyone tell me why?
Try this logic:
class Program
{
static void Main(string[] args)
{
int[,] matrix=new int[,] {
{ 1, 2, 3, 4 },
{ 1, 3, 4, 2 },
{ 2, 3, 4, 1 },
{ 2, 4, 1, 3 } };
// This returns the #of collisions in each column
Debug.WriteLine(CheckColumn(matrix, 0)); // 2
Debug.WriteLine(CheckColumn(matrix, 1)); // 1
Debug.WriteLine(CheckColumn(matrix, 2)); // 1
Debug.WriteLine(CheckColumn(matrix, 3)); // 0
}
static int CheckColumn(int[,] matrix, int column)
{
int[] data=new int[matrix.GetLength(0)];
for(int i=0; i<data.Length; i++)
{
data[i]=matrix[i, column];
}
var hist=data.GroupBy(i => i)
.OrderByDescending(g => g.Count())
.Select(g => new { Num=g.Key, Dupes=g.Count()-1 })
.Where(h=>h.Dupes>0);
return hist.Count()>0?hist.Sum(h=>h.Dupes):0;
}
}
I used code from https://stackoverflow.com/a/10335326/380384