Can't perambulate indexes in matrix the right way - c#

Hello. I have this task to sum the numbers as shown. Tried everything I can, but still not the right answer. Can I have some guidance?
static void Main(string[] args)
{
string input = Console.ReadLine();
int n = (int)char.GetNumericValue(input[0]);
int m = (int)char.GetNumericValue(input[2]);
int[,] matrix = new int[n, m];
int sum = 0;
//fill matrix
for (int i = 0; i < n; i++)
{
for (int j = 0; j < m; j++)
{
matrix[i, j] = (j * 3 + 1) + i * 3;
}
}
for (int i = 0; i < matrix.GetLength(0) - 1; i+=1)
{
for (int j = 0; j < matrix.GetLength(1) - i; j+=1)
{
if (i % 2 == 0)
{
sum += matrix[i, j + i] + matrix[i + 1, j + 1];
}
}
}
Console.WriteLine(sum);
}

I think you would've a easier time hard coding the input (and naming them as "columns" and "rows" instead, much more readable).
What is the expected output? Not sure I'm following this sum. I'm guessing, 297? If so:
for (int i = 0; i < matrix.GetLength(0); i++)
{
for (int j = 0; j < matrix.GetLength(1); j++)
{
Console.Write(matrix[i, j] + " ");
if(j == 5) Console.WriteLine();
if (matrix[i, j] % 2 != 0)
{
if (i == 0 || i == matrix.GetLength(0) - 1
|| j == 0 || j == matrix.GetLength(0))
{
sum += (matrix[i, j]);
}
else
{
sum += (matrix[i, j] * 2);
}
}
}
}

Related

element swapping in a 4x4 array with numbers

I am making a game like this one : https://i.stack.imgur.com/mnbFw.jpg. I am having trouble coding the algorithm to swap numbers between each others. In my game , the 0 acts as the empty tile. This algorithm was originally for a 3x3 grid but I simply switched the 3's to 4's. I think that this is what's causing issues but I can't seem to find why.
{
int j, i;
for (i = 1; i < 4; i++)
{
for (j = 0; j < 4; j++)
{
if (t1[i, j] == 0)
{
t1[i, j] = t1[i - 1, j];
t1[i - 1, j] = 0;
}
}
}
}
static void scan_above(int[,] t1)
{
int j, i;
for (i = 1; i >= 0; i--)
{
for (j = 0; j < 4; j++)
{
if (t1[i, j] == 0)
{
t1[i, j] = t1[i + 1, j];
t1[i + 1, j] = 0;
}
}
}
}
static void scan_left(int[,] t1)
{
int j, i;
for (j = 1; j >= 0; j--)
{
for (i = 0; i < 4; i++)
{
if (t1[i, j] == 0)
{
t1[i, j] = t1[i, j + 1];
t1[i, j + 1] = 0;
}
}
}
}
static void scan_right(int[,] t1)
{
int j, i;
for (j = 1; j < 4; j++)
{
for (i = 0; i < 4; i++)
{
if (t1[i, j] == 0)
{
t1[i, j] = t1[i, j - 1];
t1[i, j - 1] = 0;
}
}
}
}```
I'm confused about why you're looping through all the values in the matrix. Unless there are considerations that aren't included in the question, this is all it should take:
static void MoveRight(int xOfZero, int yOfZero)
{
int rightValue = spaces[xOfZero, yOfZero + 1];
spaces[xOfZero, yOfZero + 1] = 0;
spaces[xOfZero, yOfZero] = rightValue;
}
FYI I hastily put together my matrix so it's indexed backwards, where x is the row number and y is the column. You could easily follow the same steps to make a move for every direction.

C# [i, j] add the min "j" values ​of matrix to the new array?

[i, j] add the biggest values ​​of matrix to j the new array
its here:
But smallest not working..
Min values in "j" (not working)
for (int i = 0; i < olay; i++)
{
for (int j = 0; j < state; j++)
{
if (minimax[i] > matris[i, j])
{
minimax[i] = matris[i, j];
}
}
}
Console.WriteLine();
for (int i = 0; i < minimax.Length; i++)
{
Console.WriteLine(i + 1 + ". MINIMAX " + minimax[i]);
}
Console.ReadLine();
}
Max VALUES IN "J" (WORKING)
for (int i = 0; i < olay; i++)
{
for (int j = 0; j < state; j++)
{
if (maximax[i] < matris[i, j])
{
maximax[i] = matris[i, j];
}
}
}
/* Olaylar icin en yuksek State degerleri */
Console.WriteLine();
for (int i = 0; i < maximax.Length; i++)
{
Console.WriteLine(i + 1 + ". MAXIMAX " + maximax[i]);
}
Output console:
IMG Lınk: https://pasteboard.co/IKKQlet.jpg
The default values in your arrays are 0.
To calculate the minimum value in each column and write it to an array you can do something like this:
var resultArray = new int[rowLength];
var matrix = new int[rowLength, columnLength];
for (int i = 0; i < rowLength; i++)
{
// you have to set the first value as a minimum and after that compare
resultArray[i] = matrix[i, 0];
for (int j = 1; j < columnLength; j++)
{
if (matrix[i, j] < resultArray[i])
{
resultArray[i] = matrix[i, j];
}
}
}

How to save a pyramid into array of chars?

I need help with checking IF the position in array must save ' ' or '*' for later in program to print out a pyramid.
static void Main(string[] args)
{
Console.WriteLine("Enter size: ");
int s = int.Parse(Console.ReadLine());
char[,] pyramid = new char[s, s * 2 - 1];
FillArray(pyramid);
Out(pyramid);
Console.ReadLine();
}
static void FillArray(char[,] t)
{
for (int i = 0; i < t.GetLength(0); i++)
{
for (int j = 0; j < t.GetLength(1); j++)
{
if (j == t.GetLength(1) / 2 || j == t.GetLength(1) / 2 + i || j == t.GetLength(1) / 2 - i)
{
t[i, j] = '*';
}
else t[i, j] = ' ';
}
}
}
static void Out(char[,] t)
{
for (int i = 0; i < t.GetLength(0); i++)
{
for (int j = 0; j < t.GetLength(1); j++)
{
Console.Write(t[i, j]);
}
Console.WriteLine();
}
}
At the moment I get out something like this:
The code should be like this
int i, j, n;
Console.WriteLine("Enter size: ");
n = int.Parse(Console.ReadLine());
for (i = 0; i < n; i++)
{
for (j = 1; j <= n - i; j++)
Console.Write(" ");
for (j = 1; j <= 2 * i - 1; j++)
Console.Write("*");
Console.Write("\n");
}

How do I set the debugger to catch what changed the variable

I am implementing the NEH algorithm following this slide and video:
http://mams.rmit.edu.au/b5oatq61pmjl.pdf
https://www.youtube.com/watch?v=TcBzEyCQBxw
My problem during the test is the variable Sorted_list got changed which cause different results from what I expect:
This the portion where I have the problem but I couldn't know what it changes it(I used breakpoints and watch variable window):
for (int i = 0; i < kmsList.Count; i++)
{
for (int j = 0; j < kmsList[i].Length - 1; j++)
{
/*
*
* HERE Sorted_list GET MODIFIED UNEXPECTEDLY
*/
if (i == 0 && j == 0)
kmsList[0][0] = Sorted_list[0][0];
else if (i == 0)
kmsList[0][j] = kmsList[0][j - 1] + Sorted_list[0][j];
else if (j == 0)
kmsList[i][0] = kmsList[i - 1][0] + Sorted_list[i][0];
}
}
Complete implementation:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace FINAL_NEH
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("entre the nmbr of jobs : ");
string row = Console.ReadLine();
Console.WriteLine("entre the nmbr of machines : ");
string column = Console.ReadLine();
int job = int.Parse(row.ToString());
int machine = int.Parse(column.ToString());
List<int[]> list = new List<int[]>();
// read the nmbrs and put it in list-----------------------------------------------------
for (int i = 0; i < job; i++)
{
list.Add(new int[machine + 1]);
for (int j = 0; j < machine; j++)
{
list[i][j] = int.Parse(Console.ReadLine());
}
list[i][list[i].Length - 1] = int.Parse((i + 1).ToString()); //Last Elemnt Is Job Number-
}
// show the list----------------------------------------------------------------------------
for (int i = 0; i < job; i++)
{
for (int j = 0; j < machine + 1; j++)
{
Console.Write("\t" + "[" + list[i][j] + "]");
}
Console.WriteLine();
}
// sort the list------------------------------------------------------------------------------
for (int i = 0; i < list.Count; i++)
{
for (int j = i + 1; j < list.Count; j++)
{
int sumI = 0, sumJ = 0;
for (int a = 0; a < list[i].Length - 1; a++)
{
sumI += list[i][a];
}
for (int a = 0; a < list[j].Length - 1; a++)
{
sumJ += list[j][a];
}
if (sumI < sumJ)
{
int[] temp = new int[int.Parse(job.ToString())];
temp = list[i];
list[i] = list[j];
list[j] = temp;
}
}
}
Console.Write("\n\n-----------------after sorting ------------------------------------\n\n");
// shaw the list after sorting------------------------------------------
for (int i = 0; i < job; i++)
{
for (int j = 0; j < machine + 1; j++)
{
Console.Write("\t" + "[" + list[i][j] + "]");
}
Console.WriteLine();
}
// clculate the maxpane of the first 2 jobs---------------------------------------
List<int[]> initMaxpane = new List<int[]>();
initMaxpane.Add((int[])list[0].Clone());
initMaxpane.Add((int[])list[1].Clone());
// calculer maxspan of first jobs..............................................
for (int i = 0; i < initMaxpane.Count; i++)
{
for (int j = 0; j < initMaxpane[i].Length - 1; j++)
{
if (j == 0 && i == 0)
initMaxpane[0][0] = list[i][j];
else if (i == 0)
initMaxpane[0][j] = (int)(initMaxpane[0][j - 1] + list[0][j]);
else if (j == 0)
initMaxpane[i][0] = (int)(initMaxpane[i - 1][0] + list[i][0]);
}
}
for (int i = 1; i < initMaxpane.Count; i++)
{
for (int j = 1; j < initMaxpane[i].Length - 1; j++)
{
if ((initMaxpane[i][j - 1] > initMaxpane[i - 1][j]))
initMaxpane[i][j] = (int)(initMaxpane[i][j - 1] + list[i][j]);
else
initMaxpane[i][j] = (int)(initMaxpane[i - 1][j] + list[i][j]);
}
}
int Cmax = initMaxpane[initMaxpane.Count - 1][initMaxpane[initMaxpane.Count - 1].Length - 2];
Console.WriteLine("\n\n-------the maxpane offirst jobs----------");
for (int i = 0; i < initMaxpane.Count; i++)
{
for (int j = 0; j < initMaxpane[i].Length; j++)
{
Console.Write("\t" + "[" + initMaxpane[i][j] + "]");
}
Console.WriteLine();
}
List<int[]> initMaxpane2 = new List<int[]>();
initMaxpane2.Add(list.ElementAt(1));
initMaxpane2.Add(list.ElementAt(0));
// calculer maxspan of first jobs reverse..............................................
for (int i = 0; i < initMaxpane2.Count; i++)
{
for (int j = 0; j < initMaxpane2[i].Length - 1; j++)
{
if (j == 0 && i == 0)
initMaxpane2[0][0] = list[i][j];
else if (i == 0)
initMaxpane2[0][j] = (int)(initMaxpane2[0][j - 1] + list[0][j]);
else if (j == 0)
initMaxpane2[i][0] = (int)(initMaxpane2[i - 1][0] + list[i][0]);
}
}
for (int i = 1; i < initMaxpane2.Count; i++)
{
for (int j = 1; j < initMaxpane2[i].Length - 1; j++)
{
if ((initMaxpane2[i][j - 1] > initMaxpane2[i - 1][j]))
initMaxpane2[i][j] = (int)(initMaxpane2[i][j - 1] + list[i][j]);
else
initMaxpane2[i][j] = (int)(initMaxpane2[i - 1][j] + list[i][j]);
}
}
int Cmax2 = initMaxpane2[initMaxpane2.Count - 1][initMaxpane2[initMaxpane2.Count - 1].Length - 2];
Console.WriteLine("\n\n-------the maxpane of first jobs (reverse)----------");
for (int i = 0; i < initMaxpane2.Count; i++)
{
for (int j = 0; j < initMaxpane2[i].Length; j++)
{
Console.Write("\t" + "[" + initMaxpane2[i][j] + "]");
}
Console.WriteLine();
}
List<int[]> MaxpaneList = new List<int[]>();
if (Cmax > Cmax2)
{
MaxpaneList.Add((int[])list[1].Clone());
MaxpaneList.Add((int[])list[0].Clone());
}
else
{
MaxpaneList.Add((int[])list[0].Clone());
MaxpaneList.Add((int[])list[1].Clone());
}
List<int[]> bestSequenceList = null;
List<int[]> kmsList = null;
List<int[]> Sorted_list = list.ToList();
int bestCma = 0;
//int maxspan = 0;
for (int jo = 2; jo < job; jo++)
{
for (int ins = 0; ins <= MaxpaneList.Count; ins++)
{
MaxpaneList.Insert(ins, list[jo]);
kmsList = MaxpaneList.ToList();
int Cma = 0;
for (int i = 0; i < kmsList.Count; i++)
{
for (int j = 0; j < kmsList[i].Length - 1; j++)
{
/*
*
* HERE Sorted_list GET MODIFIED UNEXPECTEDLY
*/
if (i == 0 && j == 0)
kmsList[0][0] = Sorted_list[0][0];
else if (i == 0)
kmsList[0][j] = kmsList[0][j - 1] + Sorted_list[0][j];
else if (j == 0)
kmsList[i][0] = kmsList[i - 1][0] + Sorted_list[i][0];
}
}
for (int i = 1; i < kmsList.Count; i++)
{
for (int j = 1; j < kmsList[i].Length - 1; j++)
{
if ((kmsList[i][j - 1] > kmsList[i - 1][j]))
kmsList[i][j] = kmsList[i][j - 1] + Sorted_list[i][j];
else
kmsList[i][j] = kmsList[i - 1][j] + Sorted_list[i][j];
}
}
Cma = kmsList[kmsList.Count - 1][kmsList[kmsList.Count - 1].Length - 2];
Console.WriteLine("\n\n\n------- the maxpane sequence ----------");
for (int i = 0; i < MaxpaneList.Count; i++)
{
for (int j = 0; j < MaxpaneList[i].Length; j++)
{
Console.Write("\t" + "[" + MaxpaneList[i][j] + "]");
}
Console.WriteLine();
}
Console.WriteLine("MAX : " + Cma + "\n\n\n");
if (ins == 0)
{
bestCma = Cma;
}
if (jo == 2 && ins == 0)
{
bestSequenceList = MaxpaneList.ToList();
bestCma = Cma;
}
else
{
if (bestCma > Cma)
{
bestSequenceList = MaxpaneList.ToList();
bestCma = Cma;
}
}
MaxpaneList.RemoveAt(ins);
}
MaxpaneList = bestSequenceList.ToList();
}
Console.ReadLine();
}
}
}
The issue lies in the following code (snippet):
List<int[]> Sorted_list = list.ToList();
ToList will create a new list, but because in this case int[] is a reference type then the new list will contain references to the same arrays as the original list.
Updating a value (of an array) referenced in the new list will also affect the equivalent value in the original list.
kmsList[0][0] = Sorted_list[0][0];
The solution is to create a real copy of 'list' and its items (in this case int[]):
List<int[]> Sorted_list = list.ConvertAll(myArray => (int[])myArray.Clone());
This piece of code clones all arrays within the list to a new variable Sorted_list.
A useful link that explains the difference between value and reference types is: https://msdn.microsoft.com/en-us/library/t63sy5hs.aspx
Reference Types
A reference type contains a pointer to another memory location that holds the data.
Reference types include the following:
String
All arrays, even if their elements are value types Class
types, such as Form
Delegates
When you create a List<> (or any other container) from another container (as you do when you call list.ToList()) you do not create copies of all of the elements in the container. You create new references to the items in the list that you're copying. In CS parlance it's a shallow copy and not a deep copy.
So, if you do this:
int[] ia = new[] {0, 1, 2, 3, 4};
int[] ib = new[] {5, 6, 7, 8, 9};
List<int[]> la = new List<int[]>() { ia, ib };
List<int[]> lb = la.ToList();
Both lists refer to the same two arrays, and if you change one array like this:
la[1][4] = 10;
Then lb[1][4] will also be 10 because the two lists each contain the same arrays. Copying the list does not copy the elements in the list.

create asterisk tree with C#

Hello everyone
I try to solve asterisk tree problem
and found my code is not work correctly and can be improved.
This is output that expected
input : 5
*
* * *
* * * * *
* * *
*
input : 4
* * * *
* *
* * * *
and this is my code
static void Main(string[] args)
{
Console.Write("input:");
char input = Console.ReadKey().KeyChar;
if (char.IsDigit(input))
{
int couter = (int)char.GetNumericValue(input);
Console.WriteLine();
if (couter % 2 != 0)
{
for (int i = 1; i <= couter; i++)
{
for (int j = 3; j > i; j--)
{
Console.Write(" ");
}
for (int k = 1; k <= i; k++)
{
Console.Write(" *");
}
Console.WriteLine();
}
for (int i = couter - 1; i >= 3; i--)
{
for (int j = 1; j <= i; j++)
{
if (j <= couter - i)
{
Console.Write(" ");
}
else
{
Console.Write("* ");
}
}
Console.WriteLine();
}
}
else
{
for (int i = couter; i > 3; i--)
{
for (int j = 1; j <= i; j++)
{
if (couter - i >= j)
{
Console.Write(" ");
}
else
{
Console.Write("* ");
}
}
Console.WriteLine();
}
for (int i = couter - 1; i <= couter; i++)
{
for (int j = 0; j < i; j++)
{
Console.Write("* ");
}
Console.WriteLine();
}
}
}
}
Please could you help me to solve this problem.
Lately, I think I'm poor at algorithms and a little complex problem. Is anybody know useful link or how I can improve this skill, please let me know.
Thanks,
Check this page for input 5 (diamond) : http://www.dreamincode.net/forums/topic/126715-diamond-asterisk/
I've translated it to C# - now it displays diamonds with size that you set in variable 'rows':
int rows = 5;
StringBuilder sb = new StringBuilder();
// top part
for (int i = 1; i <= rows; i++)
{
for (int j = 1; j <= rows - i; j++)
sb.Append(' ');
for (int k = 1; k <= 2 * i - 1; k++)
sb.Append('*');
sb.AppendLine();
}
//bottom part
for (int n = rows - 1; n > 0; n--)
{
for (int l = 1; l <= rows - n; l++)
sb.Append(' ');
for (int m = 1; m <= 2 * n - 1; m++)
sb.Append('*');
sb.AppendLine();
}
Console.Write(sb.ToString());
I was initially reluctant to post it because it definitely smells like homework...
Anyway, here's a piece of working code:
static void Main(string[] args)
{
Console.Write("input:");
char input = Console.ReadKey().KeyChar;
if (char.IsDigit(input))
{
int couter = (int)char.GetNumericValue(input);
Console.WriteLine();
if (couter % 2 != 0)
PrintDiamond(couter);
else
PrintHourGlass(couter);
}
Console.ReadLine();
}
private static void PrintDiamond(int couter)
{
bool moreAsterisks = true;
for (int row = 0; row < couter; row++)
{
int nAsterisks = moreAsterisks ? (2 * row) + 1 : 2 * (couter - row - 1) + 1;
int nSpaces = (couter - nAsterisks) / 2;
if (row == (couter - 1) / 2)
moreAsterisks = false;
for (int i = 0; i < nSpaces; i++)
Console.Write(" ");
for (int i = 0; i < nAsterisks; i++)
Console.Write("*");
for (int i = 0; i < nSpaces; i++)
Console.Write(" ");
Console.WriteLine();
}
}
private static void PrintHourGlass(int couter)
{
bool moreAsterisks = false;
for (int row = 0; row < couter - 1; row++)
{
int nAsterisks = moreAsterisks ? couter - 2 * (couter - row - 2) : couter - (2 * row);
int nSpaces = (couter - nAsterisks) / 2;
if (row == (couter - 2) / 2)
moreAsterisks = true;
for (int i = 0; i < nSpaces; i++)
Console.Write(" ");
for (int i = 0; i < nAsterisks; i++)
Console.Write("*");
for (int i = 0; i < nSpaces; i++)
Console.Write(" ");
Console.WriteLine();
}
}
P.S.:
it works with any number, not just 4-5...
Here's a minified LINQ solution for your problem:
class Program
{
static void Main(string[] args)
{
Console.Write("input: ");
string line = Console.ReadLine();
int n;
if (!int.TryParse(line, out n))
{
Console.WriteLine("Enter a valid integer number.");
return;
}
for (int i = 0; i < n; i++)
{
int l = Math.Abs(n - i * 2 - 1) + 1;
if (n % 2 != 0) l = n - l + 1;
Console.Write(Enumerable.Repeat(" ", n - l).DefaultIfEmpty("").Aggregate((a, b) => a + b));
Console.WriteLine(Enumerable.Repeat("* ", l).DefaultIfEmpty("").Aggregate((a, b) => a + b));
}
}
}
It's pretty simple; inside the loop, first line calculates length of the i-th diamond row if input is even, second one corrects the calculation for odd input. The remaining two lines print i-th row using some LINQ tricks. If you don't like showing off with LINQ, you can replace thoose lines with regular for loops (which is probably going to be faster). Then the code would look like:
class Program
{
static void Main(string[] args)
{
Console.Write("input: ");
string line = Console.ReadLine();
int n;
if (!int.TryParse(line, out n))
{
Console.WriteLine("Enter a valid integer number.");
return;
}
for (int i = 0; i < n; i++)
{
int l = Math.Abs(n - i * 2 - 1) + 1;
if (n % 2 != 0) l = n - l + 1;
//Console.Write(Enumerable.Repeat(" ", n - l).DefaultIfEmpty("").Aggregate((a, b) => a + b));
//Console.WriteLine(Enumerable.Repeat("* ", l).DefaultIfEmpty("").Aggregate((a, b) => a + b));
for (int c = 0; c < n - l; c++) Console.Write(" ");
for (int c = 0; c < l; c++) Console.Write("* ");
Console.WriteLine();
}
}
}

Categories

Resources