retrieving data into a 2D array in C# - c#

I have a text file that has:
1 2 3 4 0 5 6 7 8
How do I show the data in a 2D array of size [3,3]?
I'm new to C# and any help would be great!
I've tried the code below but it doesn't work:
int i = 0, j = 0;
int[,] result = new int[3, 3];
foreach (var row in input.Split('\n'))
{
j = 0;
foreach (var col in row.Trim().Split(' '))
{
result[i, j] = int.Parse(col.Trim());
j++;
}
i++;
}
Console.WriteLine(result);

divide by 3 and convert to integer to get row, use modulo 3 to get col.
j=0;
foreach (var col in input.Trim().Split(' '))
{
result[j/3, j%3] = int.Parse(col.Trim());
j++;
}

If all your 9 numbers are on the same line, then splitting by new line will not help. You can do:
foreach (var num in input.Split(' '))
{
result[i / 3, i % 3] = int.Parse(num.Trim());
i++;
}
because:
i i / 3 (div) i % 3 (mod)
0 0 0
1 0 1
2 0 2
3 1 0
4 1 1
5 1 2
6 2 0
7 2 1
8 2 2

Related

Fall down elements in 2d array

Hello looking for simple loop where numbers will fall down in 2d array for example
0 0 0 3 3
2 1 3 1 1
1 1 5 1 1
1 2 0 0 0
0 0 0 0 2
expected:
0 0 0 0 0
0 0 0 0 3
2 1 0 3 1
1 1 3 1 1
1 2 5 1 2
Do you have suggestions? Thank you.
Hint: Fall down means non-zero items must go down in each column!
Here is a solution:
void FallDown(ref int[,] numbers)
{
var rowCount = numbers.GetLength(0);
for (var c = 0; c < numbers.GetLength(1); c++)
{
var colValues = new List<int>();
for (var r = 0; r < rowCount; r++)
{
var colValue = numbers[r, c];
if (colValue > 0)
{
colValues.Add(colValue); // collect only non-zero values
}
}
if (colValues.Count < rowCount) // there were zeroes ...
{
do
{
colValues.Insert(0, 0); // fill it up with leading zeroes.
} while (colValues.Count < rowCount);
for (var r = 0; r < rowCount; r++) {
numbers[r, c] = colValues[r]; // put numbers back into original array
}
}
}
}
The result will be replaced in the original array, which is why it is passed in by ref.
Found this.
public void FallDown()
{
for (var row = 0; row < RowCount - 1; row++)
{
for (var column = 0; column < ColumnCount; column++)
{
if (tiles[row + 1, column] == 0 && tiles[row, column] != 0)
{
tiles[row + 1, column] = tiles[row, column];
tiles[row, column] = 0;
row = 0;
column = 0;
}
}
}
}

How to increment i in for loop in C#

I'm trying to modify the code below so each first number in column is based on the row number.
int i, sum = 0;
for (int row = 0; row < 7; row++)
{
for (i = 1; i < 6; i++)
{
sum = sum + i;
Console.Write("{0} ", i);
}
Console.WriteLine(sum);
sum = 0;
}
Console.Read();
presents this in console:
1 2 3 4 5 15
1 2 3 4 5 15
1 2 3 4 5 15
1 2 3 4 5 15
1 2 3 4 5 15
1 2 3 4 5 15
1 2 3 4 5 15
But I'm trying get like this:
1 2 3 4 5 sum
2 3 4 5 6 sum
3 4 5 6 7 sum
4 5 6 7 8 sum
and so on..
......
....
Any idea on how to solve this?
Change the inner loop to be
for (int i = row + 1; i < row + 6; i++)
Replace
sum = sum + i;
Console.Write("{0} ", i);
enter code here
with
number = number + row
sum = sum + number;
Console.Write("{0} ", number);
This way you use the variable row to keep track of the starting number for the row.
If you don't need the console statements and just the sum, you can just use no inner loop and:
sum = Enumerable.Sum(Enumerable.Range(row+1, 5));
It's LINQ
or, if you need the console statement:
Enumerable.Range(row+1, 5).ToList().ForEach(c => sum += c; Console.Write(c));

Finding unknown repeating patterns in a string consisting numbers

I've been struggling with this for a week.
I have a string like this: 1 1 0 1 1 0 1 1 0 1 1 0 1 1 0 1 1 0 1 1 0 1 1 0 1.....
What I need to find: 1 1 0
example 2: 1 1 2 0 2 2 1 0 1 1 2 0 2 2 1 0 1 1 2 0 2 2 1 0 1 1 2 0 2 2 1 0 ....
What I need to find: 1 1 2 0 2 2 1 0
example 3: 1 1 2 3 1 0 1 1 2 3 1 0 1 1 2 3 1 0 1 1 2 3 1 0 1 1 2 3 1 0...
112310
etc. etc.
My code as now:
private string tekrarArama(double[] mods)
{
string part1 = "";
string part2 = "";
string patern = "";
int number1 = mods.Length;
for (int i = 0; i < mods.Length; i++)
{
part1 = "";
part2 = "";
for (int j = 0; j < number1; j++)
{
part1 += mods[j] + ",";
}
for (int k = 0; k < mods.Length; k++)
{
part2 += mods[k] + ",";
}
int actualcount = Regex.Matches(part2, part1).Count;
int count = part2.Replace(",", "").Length / part1.Replace(",", "").Length;
if (part2.IndexOf(bolum1) >= 0 && actualcount == count )
{
patern = part2.Substring(part2.IndexOf(part1),part1.Length);
}
number1--;
}
return patern;
}
It creates two copies of the string and deletes 1 character at a time from one of the strings in each iteration, to find the smallest repeating pattern.
It's a mess and doesn't work very well at all.
How can I do this? Thanks in advance.
If you're looking for something simple and don't need optimal complexity, here's a concise way to represent the query.
string FindPattern(string text)
{
if (text == null)
{
return null;
}
return Enumerable
.Range(1, text.Length / 2)
.Where(n => text.Length % n == 0)
.Select(n => text.Substring(0, n))
.Where(pattern => Enumerable
.Range(0, text.Length / pattern.Length)
.SelectMany(i => pattern)
.SequenceEqual(text))
.FirstOrDefault();
}
Note that the complexity here is quadratic in the worst case, so it's not a good idea to use it for very long strings.

Reading a multi-dimensional array in a different order

So I have a number array like this
0 1 2 3
4 5 6 7
8 9 10 11
12 13 14 15
And know what I want to know is how to make it read the number 7 after the number 3, and number 8 after number 4. And so on, like this:
0 -> 1 -> 2 -> 3
|
\/
4 <- 5 <- 6 <- 7
|
\/
8 -> 9 -> 10 -> 11
|
\/
12 <- 13 <- 14 <- 15
However if I use nested incremental for it will read in normal sequential order.
I have no idea how to make it read from 3 to 7, 4 to 8 and so on...
How can I achieve that?
You can store a flag indicating if the next iteration is going to start on the left or right. So...
static void Main(string[] args)
{
// initializing values
int[,] arr = new int[4, 4];
int n = 0;
for (int i = 0; i < 4; i++)
{
for (int j = 0; j < 4; j++)
{
arr[i, j] = n++;
}
}
n = 0;
// initialization end
// starts from the left
bool left = true;
// go line by line
for (int i = 0; i < 4; i++)
{
// if it starts from the left, set start point a index 0
// otherwise start from max index
for (int j = left ? 0 : 3; left ? j < 4 : j >= 0; )
{
arr[i, j] = n++;
// increment/decrements depending on the direction
j = left ? j + 1 : j - 1;
}
// if it started from the left, the next iteration will
// start from the right
left = !left;
}
}
Results:
Initialized:
0 1 2 3
4 5 6 7
8 9 10 11
12 13 14 15
After navigating on it:
0 1 2 3
7 6 5 4
8 9 10 11
15 14 13 12
If you have:
_arr = new int[,] { { 0, 1, 2, 3 }, { 4, 5, 6, 7 }, { 8, 9, 10, 11 }, { 12, 13, 14, 15 } };
Then try:
public void PrintArr()
{
for (int i = 0; i < 4; i++)
{
if (i % 2 == 0)
{
for (int j = 0; j < 4; j++)
Console.Write(_arr[i, j] + " ");
Console.WriteLine();
}
else
{
for (int j = 3; j >= 0; j--)
Console.Write(_arr[i, j] + " ");
Console.WriteLine();
}
}
}
Here's a short, simple solution:
int h = array.GetLength(0), w = array.GetLength(1);
for(int i = 0, j = 0, c = 1; i < h; i++, c = -c, j += c)
{
for(int k = 0; k < w; k++, j += c)
{
Console.WriteLine(array[i, j]);
}
}

Different combinations of an array (C#)

how can we find out different combination of the elements of an array using c# code.
are there any inbuilt library function for this.?
for eg: suppose an array has elements {2,3,4,5,6,7}
then the possible combination would be 2,3,4,5,6,7,2 3,2 3 4,2 3 4 5, etc
so basically wat i need is a function which gives different combination based on its input for eg: comb(array,2) gives output 2 3,1 2,3 4 and comb(array,3) gives output 1 2 3,2 3 4,3 4 5 and so on
Eg: valid comnbination for array= {1, 2, 3} and length = 2 are 1 2,1 3,2 3 .....
static void Main()
{
var cnk = comb(new [] {1,2,3},2);
foreach ( var c in cnk)
{
}
}
public static IEnumerable<int[]> comb(int[] a, int k)
{
if (a == null || a.Length == 0 || k < 1 || k > a.Length)
yield break;
int n = a.Length;
// 1
if ( k == 1)
for ( int i = 0; i < n; i++)
{
yield return new int[] {a[i]};
}
else
{
// k
for ( int i = 0; i < n - k + 1; i++)
{
var res = new int[k];
for (int t = i, c = 0; t < i + k - 1; t++, c++)
res[c] = a[t];
for (int j = i + k - 1; j < n; j++)
{
res[k-1] = a[j];
yield return res;
}
}
}
}
You should take the algorithm from here, my answer doesn't solve your problem
Algorithm to return all combinations of k elements from n
Seemed logic is not absolutely correct as:
var cnk = comb(new[] { 1, 2, 3, 4 }, 3);
This gives 3 variants, but as a matter of fact it is 4:
1 2 3
1 2 4
1 3 4
2 3 4
I guess comb is better to be implemented in recursive way.

Categories