C#: Build 3D-Array and fill it with data - c#

The code I tried so far below:
private static List<List<List<int>>> threeDArrayToThreeDList(int [,,] letters) {
// 3d-array to 3d-list
List<List<List<int>>> letterslist = new List<List<List<int>>>();
List<List<int>> sublist = new List<List<int>> ();
List<int> subsublist = new List<int> ();
for (int i = 0; i < 2; i++) {
letterslist.Add (sublist);
for (int j = 0; j < 2; j++) {
letterslist[i].Add (subsublist);
for (int k = 0; k < 2; k++) {
Console.WriteLine (letterslist [i][j][k]); // Element not found
Console.WriteLine (letters [i,j,k]);
letterslist [i] [j] [k] = letters [i,j,k];
}
}
}
return letterslist;
}
Why letterslist [i][j][k] isn't found?

Your code is wrong. You need to create a list for each "index". You're code only creates 3 lists altogether.
Here's how it should work:
private static List<List<List<int>>> threeDArrayToThreeDList(int [,,] letters) {
// 3d-array to 3d-list
List<List<List<int>>> letterslist = new List<List<List<int>>>();
for (int i = 0; i < 2; i++) {
letterslist.Add (new List<List<int>> ());
for (int j = 0; j < 2; j++) {
letterslist[i].Add (new List<int> ());
for (int k = 0; k < 2; k++) {
Console.WriteLine (letters [i,j,k]);
letterslist [i] [j].Add(letters [i,j,k]);
}
}
}
return letterslist;
}

This because the letterslist [i][j] list has no elements in it.
Add an element to it, and it will get you through the line that causes the exception.
Change the code in the innermost loop as follows:
for (int k = 0; k < 2; k++) {
letterslist[i][j].Add (letters[i, j, k]);
Console.WriteLine(letterslist[i][j][k]); // Should work fine
Console.WriteLine(letters[i, j, k]);
}

Related

Problem when trying to sort an array with multiple threads in c#

I am new to c# and I am trying to print parts of an integer array sorted by multiple threads. For that I use bubble sort inside my function mySort which takes part of the array as a parameter and stores it to a list that I want to display afterwards. The division of the original array is in a loop where I also start the threads. The problem is that the resulting parts are all the same although I pass the different parts of the array to a function to be executed on a thread. The resulting parts includes just numbers of the last part of the original sorted array. I would be glad for any help.
int[] myArray = new int[100];
for (int i = 0; i < myArray.Length; i++)
{
myArray[i] = r.Next(0, 100);
}
parts = new List<int[]>();
Thread[] t = new Thread[5];
int[] tmp = new int[myArray.Length/5];
int k = 0;
for (int i = 0; i < 5; i++)
{
for (int j = 0; j < tmp.Length; j++)
{
tmp[j] = myArray[k];
k++;
}
Thread myT = new Thread(() => mySort(tmp));
t[i] = myT;
t[i].Start();
}
Function for sorting
static void mySort(int [] arr)
{
for (int i = 0; i < arr.Length - 1; i++)
{
for (int j = 0; j < arr.Length - i - 1; j++)
{
if (arr[j + 1] < arr[j])
{
int tmp = arr[j + 1];
arr[j + 1] = arr[j];
arr[j] = tmp;
}
}
}
parts.Add(arr);
}
EDIT:
By declaring tmp array inside for loop the problem is solved.
for (int i = 0; i < 5; i++)
{
int[] tmp = new int[myArray.Length/5];
for (int j = 0; j < tmp.Length; j++)
{
tmp[j] = myArray[k];
k++;
}
Thread myT = new Thread(() => mySort(tmp));
t[i] = myT;
t[i].Start();
}

c# 2 Dimension Array Random Numbers

So I need to make 2 Dimension Array with random numbers, and expel the numbers like in multiplication table. It should look like this:
My code for now looks like this:
Random random = new Random();
int[,] array = new int[10, 10];
for (int i = 0; i < 10; i++)
{
for (int j = 0; j < 10; j++)
{
array[i, j] = random.Next();
Console.Write("\t{0}\t{1}" ,i,j);
}
EDIT:::This worked for me!
Random random = new Random();
int[,] array = new int[10, 10];
for (int i = 0; i < 10; i++)
{
for (int j = 0; j < 10; j++)
{
array[i, j] = random.Next(10);
Console.Write(array[i,j]+"\t");
}
Console.WriteLine("\n");
A 10x10 array of random numbers could be generated like this:
var rnd = new Random();
var randomArray = Enumerable.Range(0,10).Select(x => {
return Enumerable.Range(0,10).Select(y => rnd.Next()).ToArray();
}).ToArray();
Live example: http://rextester.com/GWTAK54347
As suggested by ThatBrianDude
static void Main(string[] args)
{
Random random = new Random();
int[,] array = new int[10, 10];
for (int i = 0;
i < 10;
i++)
{
for (int j = 0;
j < 10;
j++)
{
array[i,
j] = random.Next();
Console.Write("\t{0}",
array[i,
j]);
}
Console.Write("\n");
}
Console.ReadKey();
}
I think that this should work for you:
private static void RunArrayCode()
{
Random random = new Random();
int[,] array = new int[10, 10];
for (int i = 0; i < 10; i++)
{
for (int j = 0; j < 10; j++)
{
array[i, j] = random.Next();
// No tabs if it's the first item in a row
Console.Write("{0}{1}\t{2}", (j == 0 ? "" : "\t"), i, j);
}
// Each new row goes on its own line
Console.WriteLine();
}
}

how to remake 2d array random unique numbers as 3d?

static void Main(string[] args)
{
Random r = new Random();
int[,] x = new int[10,8];
int[] temp = new int[x.Length];
// two dimensional array and i want for three dimensional array
for(int i = 0; i < temp.Length; i++)
{
temp[i] = r.Next(10, 100);
for(int j = 0; j < i; j++)
{
if(temp[i] == temp[j])
{
i--;
break;
}
}
}
for(int i = 0, index = 0; i < x.GetLength(0); i++)
{
for(int j = 0; j < x.GetLength(1); j++)
{
x[i, j] = temp[index++]; //two dimensional array unique numbers
Console.Write(x[i, j] + " ");
}
}
// i want do it as for 3D and 4 D array unique numbers like that method what can i change or add?
It's pretty straight forward to do what you're doing for higher dimensions.
Here's my code for 3D:
var r = new Random();
int [,,] x = new int[10, 8, 8];
var count =
Enumerable
.Range(0, x.Rank)
.Select(y => x.GetLength(y))
.Aggregate((y, z) => y * z);
var values =
Enumerable
.Range(10, count)
.OrderBy(y => r.Next())
.ToArray();
var v = 0;
for (var i = x.GetLowerBound(0); i <= x.GetUpperBound(0); i++)
for (var j = x.GetLowerBound(1); j <= x.GetUpperBound(1); j++)
for (var k = x.GetLowerBound(2); k <= x.GetUpperBound(2); k++)
x[i, j, k] = values[v++];
To change it to 4D these lines change:
int [,,,] x = new int[10, 8, 8, 12];
// ...
var v = 0;
for (var i = x.GetLowerBound(0); i <= x.GetUpperBound(0); i++)
for (var j = x.GetLowerBound(1); j <= x.GetUpperBound(1); j++)
for (var k = x.GetLowerBound(2); k <= x.GetUpperBound(2); k++)
for (var l = x.GetLowerBound(3); l <= x.GetUpperBound(3); l++)
x[i, j, k, l] = values[v++];
Now, in this code I have explicitly called GetLowerBound as well as GetUpperBound as it is possible in .NET code to have a non-zero based array.
Also, rather than repeatedly re-try getting random numbers until you have unique numbers I simply generated a sequence of unique numbers and then randomly sorted them. That's a little different from your original code. You needed 80 (10 x 8) random values and you were choosing from values ranging from 10 to 99 inclusive. So you had some holes in your numbers.
Random r = new Random();
int[,,] x = new int[10, 8, 8];
int[] temp = new int[x.Length];
#region one dimensional array unique numbers.
for (int i = 0; i < temp.Length; i++)
{
temp[i] = r.Next(10, 650);
for (int j = 0; j < i; j++)
{
if (temp[i] == temp[j])
{
i--;
break;
}
}
}
#endregion
for (int i = 0, index = 0; i < x.GetLength(0); i++)
{
for (int j = 0; j < x.GetLength(1); j++)
{
for (int k = 0; k < x.GetLength(2); k++)
{
x[i, j, k] = temp[index++];
Console.Write(x[i, j, k] + " ");
}
Console.WriteLine();
}
}// i think it's correct code i've changed it

Printing a 2D-array into "squares"

I'm trying to learn how to work with 2D-array and I can't seem to understand how to print them correctly. I want to print them in a "square" like 5x5 but all I get is one line. I've tried both WriteLine and Write and changed some of the variables in the loops but I get either an error or not the result I want to have. The code is supposed to print out a 5x5 with a random sequence of 15 numbers in each column. I get the correct numbers out of it, it's only the layout that is wrong.
static void Main(string[] args)
{
Random rnd = new Random();
int[,] bricka = new int[5, 5];
int num = 0;
int num1 = 1;
for (int i = 0; i < bricka.GetLength(1); i++)
{
num += 16;
for (int j = 0; j < bricka.GetLength(0); j++)
{
bricka[j, i] = rnd.Next(num1, num);
}
num1 += 16;
}
for (int i = 0; i < bricka.GetLength(0); i++)
{
for (int j = 0; j < bricka.GetLength(1); j++)
{
Console.Write(bricka[i, j]+ " " );
}
}
Console.ReadKey();
}
This is my print, I would like to have the the 12 under the 8 and 14 under the 12 and so on.
http://i.imgur.com/tfyRxf1.png
You need to call WriteLine() after each line, so that each line is printed on a separate line:
for (int i = 0; i < bricka.GetLength(0); i++)
{
for (int j = 0; j < bricka.GetLength(1); j++)
{
Console.Write(bricka[i, j]+ " " );
}
Console.WriteLine();
}
That would be one way of doing it, anyway.

How to sort a 2D array filld with random numbers

I'm doing a class assignment,
I need to create an 2D array of random numbers and sort them either bubble or other sorting codes. I'm fine with single array, but the problem is a 2D array filled with random numbers, I just don't get it.
Random numbers should be made of (-I,I) interval it's a user input. Sorry for bad english, haven't gotten any degree. In working on visual C# windows form.
looking for simple couple cicles method.
example. : A[MxN] ->>> B[MxN] (Sorted 1.....n)
Getting the random numbers is trivial:
Random rnd;
for (int y = 0; y < h; y++)
for (int x = 0; x < w; x++)
array[y][x] = l - rnd.Next(2 * l + 1);
Random.Next() will return a random value between 0 and the given parameter (excluding the parameter; which is the reason for the + 1).
A 2D array can be sorted just like a 1D array, it only depends how you want to handle multiple lines, e.g. is it just for display or do you want to sort every line for itself, etc.
Here's a solution which first sorts each row's columns into order, then sorts each row comparing by first column, then second, etc:
namespace StackOverflow.Demos
{
class Program
{
public static void Main(string[] args)
{
new Program();
Console.WriteLine("Done");
Console.ReadKey();
}
Program()
{
double[,] data = GenerateData();
OutputData(data, "Before");
SortData(ref data);
OutputData(data, "After");
}
double[,] GenerateData()
{
Random randomGenerator = new Random(DateTime.UtcNow.Millisecond);
double[,] data = new double[5, 5];
for (int i = 0; i < data.GetLength(0); i++)
{
for (int j = 0; j < data.GetLength(1); j++)
{
data[i, j] = (randomGenerator.NextDouble() * 2) - 1;
}
}
return data;
}
void OutputData(double[,] data, string message)
{
Console.WriteLine("=====================");
Console.WriteLine(message);
Console.WriteLine("=====================");
for (int i = 0; i < data.GetLength(0); i++)
{
for (int j = 0; j < data.GetLength(1); j++)
{
Console.Write(data[i, j]);
Console.Write("\t");
}
Console.WriteLine();
}
}
void SortData(ref double[,] data)
{
//sort sub arrays
SortDataRows(ref data);
//sort this array
for (int i = 0; i < data.GetLength(0)-1; i++)
{
for (int j = i; j < data.GetLength(0); j++)
{
for (int k = 0; k < data.GetLength(1); k++)
{
if (data[i, k].CompareTo(data[j, k]) < 0) //if already in order exit loop
{
break;
} else if (data[i, k].CompareTo(data[j, k]) > 0) //if out of order switch and loop
{
SwapRows(ref data, i, j);
break;
}//else orders are equal so far; continue to loop
}
}
}
}
void SortDataRows(ref double[,] data)
{
for (int row = 0; row < data.GetLength(0); row++)
{
for (int i = 0; i < data.GetLength(1) - 1; i++)
{
for (int j = i; j < data.GetLength(1); j++)
{
if (data[row, i].CompareTo(data[row, j]) > 0)
{
Swap<double>(ref data[row, i], ref data[row, j]);
}
}
}
}
}
void Swap<T>(ref T a, ref T b)
{
T temp = a;
a = b;
b = temp;
}
void SwapRows(ref double[,]data, int i, int j)
{
for (int k = 0; k < data.GetLength(1); k++)
{
Swap<double>(ref data[i, k], ref data[j, k]);
}
}
}
}
The code's not the best (haven't had a cup of tea yet), but should do what you're after.
Here's a better solution (not using a 2D array as such, but using a structure which can easily be converted to/from such an array):
sing System.Diagnostics;
namespace StackOverflow.Demos
{
class Program
{
public static void Main(string[] args)
{
new Program();
Console.WriteLine("Done");
Console.ReadKey();
}
Program()
{
List<List<double>> data = GenerateData(5, 5).ToList<List<double>>();
OutputData(data,"Before");
foreach (List<double> item in data)
{
item.Sort();
}
data.Sort(CompareListOfDoubles);
OutputData(data,"After");
}
private IEnumerable<List<double>> GenerateData(int index1, int index2)
{
Random rnd = new Random(DateTime.UtcNow.Millisecond);
List<double> result;
for (int i = 0; i < index1; i++)
{
result = new List<double>(index2);
for (int j = 0; j < index2; j++)
{
result.Add(rnd.NextDouble() * 2 - 1);
}
yield return result;
}
}
private void OutputData(List<List<double>> data, string message)
{
Console.WriteLine(message);
foreach (List<double> list in data)
{
foreach (double datum in list)
{
Console.Write(datum);
Console.Write("\t");
}
Console.WriteLine();
}
}
static int CompareListOfDoubles(List<double> a, List<double> b)
{
for (int i = 0; i < a.Count; i++)
{
if (i > b.Count) return -1;
if (a[i] > b[i]) return -1;
if (a[i] < b[i]) return 1;
}
if (b.Count > a.Count) return 1;
return 0;
}
double[,] ConvertListListDoubleTo2DArray(List<List<double>> data)
{
double[,] result = new double[data.Count, data[0].Count];
for (int i = 0; i < result.GetLength(0); i++)
{
for (int j = 0; j < result.GetLength(1); j++)
{
result[i, j] = data[i][j];
}
}
return result;
}
}

Categories

Resources