How to put char ('X') to int array? - c#

Hi I have 2D array type of int where I have numbers, for example from 1 to 100.
It's a game - something like Tic-Tac-Toe - but I use bigger array. So I need to put a character 'X' or 'O' from user to this array. But problem is I can't (don't know) how to put these characters in that int array. I wan to use only the console.
I tried make the array type of char but then I can't fill the array with numbers.
I know how to do it if user would have want put some numbers but then It doesn't look good...
I would be happy for any advice how to do it.
public void Napln () { //filling the array
int poc = 1;
for (int i = 0; i < pole.GetLength(1); i++)
{
Console.Write(" ");
for (int j = 0; j < pole.GetLength(0); j++)
{
if (poc < 10)
Console.Write(" " + (pole[j, i] = poc++) + " | ");
else if ( poc < 100 )
Console.Write( (pole[j,i] = poc ++) + " | ");
else
Console.Write((pole[j, i] = poc++) + " | ");
}
Console.WriteLine();
for ( int v = 0; v < roz1; v ++ )
Console.Write("_____|");
Console.WriteLine();
}
Console.WriteLine();
public void Pozice (int vyber) //find the user choice
{
for ( int i = 0; i < pole.GetLength(1); i ++ )
{
for ( int j = 0; j < pole.GetLength(0); j ++ )
{
if (pole[i, j] == vyber)
{
pole[i, j] = 'X';
hraci.Vypis();
}
}
}
}
public void Vypis() //print the same with change of user choice
{
for ( int i = 0; i < pole.GetLength(1); i ++ )
{
Console.Write(" ");
for ( int j = 0; j < pole.GetLength(0); j ++ )
{
if (pole[j,i] < 10)
Console.Write(" " + pole[j, i] + " | ");
else if (pole[j,i] < 100)
Console.Write(pole[j, i] + " | ");
else
Console.Write(pole[j, i] + " | ");
}
Console.WriteLine();
for (int v = 0; v < roz1; v++)
Console.Write("_____|");
Console.WriteLine();
}
}
I am the new one in C# especially the OOP. So if you have any more advice I would be happy.

Just taking your question as it is, I can imagine two ways I'd do it without getting too fancy.
The first one would be to use two arrays. One for holding the numbers (and int array), one for holding the player input (a char array holding "x" and "o"). This could look like this:
public class Program
{
public static void Main()
{
int width = 10;
int height = 10;
char[,] playerBoard = new char[width, height];
int[,] numberedBoard = new int[width, height];
for (int x = 0; x < width; x++) {
for (int y = 0; y < height; y++) {
// Fill the numbered board with 1 to 100
numberedBoard[x, y] = x * width + y + 1;
// And the player board with emptyness
playerBoard[x, y] = ' ';
}
}
System.Console.WriteLine("Number at x = 3 / y = 5: " + numberedBoard[3, 5]);
System.Console.WriteLine("Current owner of x = 3 / y = 5: \"" + playerBoard[3, 5] + "\"");
// Let's change the owner of x = 3 and y = 5
playerBoard[3, 5] = 'X';
System.Console.WriteLine("New owner of x = 3 / y = 5: \"" + playerBoard[3, 5] + "\"");
}
}
A second solution could be to create an object to fit your needs, and have an array of this one. The benefit is that you only have one array, and each cell holds all the information relevant to this cell. Consider the following:
using System;
public class Program
{
struct BoardEntry {
public int number;
public char owner;
}
public static void Main()
{
int width = 10;
int height = 10;
BoardEntry[,] board = new BoardEntry[width, height];
for (int x = 0; x < width; x++) {
for (int y = 0; y < height; y++) {
// For each "cell" of the board, we create a new instance of
// BoardEntry, holding the number for this cell and a possible ownage.
board[x, y] = new BoardEntry() {
number = x * width + y + 1,
owner = ' '
};
}
}
// You can access each of those instances with `board[x,y].number` and `board[x,y].owner`
System.Console.WriteLine("Number at x = 3 / y = 5: " + board[3, 5].number);
System.Console.WriteLine("Current owner of x = 3 / y = 5: \"" + board[3, 5].owner + "\"");
// Let's change the owner of x = 3 and y = 5
board[3, 5].owner = 'X';
System.Console.WriteLine("New owner at x = 3 / y = 5: \"" + board[3, 5].owner + "\"");
}
}
It seems like you are new to programming, so the first solution might be easier to understand and use right now, but I suggest you read at some point a little bit into what structs and classes are, because they let you do some really powerful things, like in this case bundle the relevant information that belongs together.

Related

Magic Square Code Single Even number in C#

can you help me to create a logic for magic square metric. In given example, I have created a code for generate Magic Square for odd numbers like 3x3, 5x5, 7x7 metric and double even numbers like 4×4 , 8×8 but unable to found a proper solution for create single even value magic square metric like 6x6, 10x10 etc.
In current implementation anyone can enter a number (n) in input and it will create a nxn magic square metric. But not working fine with single even numbers
class Program
{
public static void Main(string [] args )
{
Console.WriteLine("Please enter a number:");
int n1 = int.Parse(Console.ReadLine());
// int[,] matrix = new int[n1, n1];
if (n1 <= 0)
{
Negativ();
}
else if (n1 == 2)
{
Zwei();
}
else if ((n1 != 2) && !(n1 < 0) && (n1 % 2 != 0))
{
Odd (n1 );
}
else if ((n1 != 2) && !(n1 < 0) && ((n1 - 2) % 4 == 0))
{//singl Even
SingleEven(n1);
}
else if ((n1 != 2) && !(n1 < 0) && (n1 % 4 == 0))
{
DoubleEven (n1);
}
}
private static void Negativ(){
Console.WriteLine("Sorry, the number must be positive and greater than 3 ");
Console.ReadLine();
}
public static void Zwei(){
Console.WriteLine("Sorry,there is no magic square of 2x2 and the number must be and greater than 3 ");
Console.ReadLine();
}
public static void Odd ( int n)// odd method
{
int[,] magicSquareOdd = new int[n, n];
int i;
int j;
// Initialize position for 1
i = n / 2;
j = n - 1;
// One by one put all values in magic square
for (int num = 1; num <= n * n; )
{
if (i == -1 && j == n) //3rd condition
{
j = n - 2;
i = 0;
}
else
{
//1st condition helper if next number
// goes to out of square's right side
if (j == n)
j = 0;
//1st condition helper if next number is
// goes to out of square's upper side
if (i < 0)
i = n - 1;
}
//2nd condition
if (magicSquareOdd[i, j] != 0)
{
j -= 2;
i++;
continue;
}
else
{
//set number
magicSquareOdd[i, j] = num++;
//1st condition
j++; i--;
}
}
// print magic square
Console.WriteLine("The Magic Square for " + n + " is : ");
Console.ReadLine();
for ( i = 0; i < n; i++)
{
for ( j = 0; j < n; j++)
Console.Write(" " + magicSquareOdd[i, j] + " ");
Console.WriteLine();
Console.ReadLine();
}
Console.WriteLine(" The sum of each row or column is : " + n * (n * n + 1) / 2 + "");
Console.ReadLine();
}
public static void SingleEven(int n )
{
// int n = magic .Length ;
int[,] magicSquareSingleEven = new int[n, n];
int halfN = n / 2;
int k = (n - 2) / 4;
int temp;
int[] swapcol = new int[n];
int index = 0;
int[,] minimagic = new int[halfN, halfN];
*Odd(minimagic) ;* // here is the problem
for (int i = 0; i < halfN; i++)
for (int j = 0; j < halfN; j++)
{
magicSquareSingleEven[i, j] = minimagic[i, j];
magicSquareSingleEven[i+ halfN , j+halfN ] = minimagic[i, j]+ halfN *halfN ;
magicSquareSingleEven[i, j + halfN] = minimagic[i, j] +2* halfN * halfN;
magicSquareSingleEven[i + halfN, j] = minimagic[i, j] +3* halfN * halfN;
}
for (int i =1; i< k ;i ++)
swapcol [index ++]=i ;
for (int i = n-k+2; i <= n ; i++)
swapcol[index++] = i;
for (int i =1; i<=halfN ;i ++)
for (int j = 1; j<= index ; j ++)
{
temp = magicSquareSingleEven[i - 1, swapcol[j - 1] - 1];
magicSquareSingleEven[i-1,swapcol[j-1]-1]=magicSquareSingleEven[i +halfN-1,swapcol[j-1]-1];
magicSquareSingleEven[i+halfN-1,swapcol[j-1]-1]=temp;
}
//swaping noses
temp=magicSquareSingleEven[k,0];
magicSquareSingleEven[k,0]=magicSquareSingleEven[k+halfN,0];
magicSquareSingleEven[k+halfN,0]=temp;
temp=magicSquareSingleEven[k+halfN,k];
magicSquareSingleEven[k+halfN,k]=magicSquareSingleEven[k,k];
magicSquareSingleEven[k,k]=temp;}
//end of swaping
// print magic square
Console.WriteLine("The Magic Square for " + n + " is : ");
Console.ReadLine();
for (int i = 0; i < n; i++)
{
for (int j = 0; j < n; j++)
Console.Write(" " + magicSquareSingleEven[i, j] + " ");
Console.WriteLine();
Console.ReadLine();
}
Console.WriteLine(" The sum of each row or column is : " + n * (n * n + 1) / 2 + "");
Console.ReadLine();
}

Displaying an arrays index number

I need help with C#
I'm currently trying to find the minimum value in a 2D array. I have managed to do this however, after I have found the minimum value I want the corresponding values index number (Where it is stored in my 2D array) to be output. For example, I have a 2D and a 1D array. Once the minimum value has been discovered the index value for the 2D array needs to be changed in the 1D array.
The 2d array is c[i,j]
and the 1D array is a[i]
so how would i be able to display the j number in my c array in my a array. For example, if my minimum value was at c[1,5] I want the value in a[5] to be changed from 0 to 1. Any help would be great thanks!
P.S. if ive made this sound really confusing I apologise I'm new to this !
int n = 5, m = 10, MinValue = 100, MaxValue = 1, Total = 0, Sum = 0; //n = number of values m = max value in array MinValue = Lowest number in array
Random Rand = new Random();
int[] A = new int[n + 1];
for (int i = 1; i < n+1; i++) //Reached and unreached array - creation
{
A[i] = 0;
}
A[1] = 1;
int[,] c = new int[n + 1, n + 1]; //Create array
for (int i = 1; i <= n; i++)
{
for (int j = 1; j <= n; j++)
{
c[i, j] = Rand.Next(1, m); //Randomise the array
if (i == j)
{
c[i, j] = 99; // give void spaces the value of 99
}
if (c[i, j] > MaxValue && c[i, j] < 99)
{
MaxValue = c[i, j]; // max value takes the highest value (that isnt 99)
}
}
}
for (int p = 1; p <= n; p++)
{
for (int i = 1; i <= n+1; i++)
{
for (int j = 1; i <= n+1; i++)
{
if (c[i, j] <= MinValue)
{
if (A[i] == 1)
{
if (A[i] == 0)
{
Total = Sum + MinValue;
Sum = Total;
A[i] = 1;
}
}
}
}
}
}
Console.WriteLine("Total Value = " + Total);
Console.WriteLine("");
Console.WriteLine("The tracking array - what has been reached and what hasn't"); // Output reaching array
Console.WriteLine("");
for (int i = 1; i <= n; i++)
{
Console.WriteLine("A[" + i + "] = " + A[i].ToString("00") + " ");
//Output the array to screen
}
Console.WriteLine("");
Console.WriteLine("The link length array"); // Output link length array
Console.WriteLine("");
for (int i = 1; i <= n; i++)
{
for (int j = 1; j <= n; j++)
{
Console.Write("c[" + i + "," + j + "] = " + c[i, j].ToString("00") + " ");
}
Console.WriteLine();
//Output the array to screen
}
Console.WriteLine("");
Console.ReadLine();

system.IndexOutOfRange exception in C# [duplicate]

This question already has answers here:
What is an IndexOutOfRangeException / ArgumentOutOfRangeException and how do I fix it?
(5 answers)
Closed 5 years ago.
I know this kind of question is asked before, but I am a noob and cannot understand where the array is out of bounds.
P.S this is not the exact duplicate of the every " system.IndexOutOfRange exception in C# " as the situation and the context of the problem is totally different from each other.So please read the question first before reporting it as the " exact duplicate ".
class Program
{
static void Main(string[] args)
{
int highestcount = 0, e = 0, h = 0;
string highest = "", a = "", b = "", j = "";
int y = int.Parse(Console.ReadLine());
e = y - 1;
string[] savArray = new string[e];
for (int count = 0; count < y; count++)
{
var x = Console.ReadLine().Split(' ');
if (count+1 <= y)
{
j = x[count + 1];
savArray[count] = j;
}
}
for (int count1 = 0; count1 < y; count1++)
{
h = 0;
a = savArray[count1];
for (int count2 = 1; count2 < y; count2++)
{
b = savArray[ count2];
if (a == b)
{
h = h + 1;
if (highestcount <= h)
{
highestcount = h;
highest = a;
}
}
}
}
Console.Write(highest);
Console.Read();
}
}
The program is to find the most common sport.
First, the user has to enter how many no: of entries are there on the list.
After that, the user has to enter his name and then his favorite sport.
If you read the program what I meant to do is simply save the 2nd value of x in the array because every second value is the sport which the user has given, as I want to save the sport's name to check which sport is more common.
But the exception is ruining the simple idea and I am stuck with it, please help.
Let's say that savArray has 1 element.
Then you do this:
var x = Console.ReadLine().Split(' ');
//Let's say x is "X" which is creates an array of size 1
if (count + 1 <= y) <----this is true (0+1<=1)
{
j = x[count + 1]; <----- BOOM x[1] when x has only one element.
for (int count = 0; count < y; count++)
{
var x = Console.ReadLine().Split(' ');
if (count+1 <= y)
{
j = x[count + 1];
savArray[count] = j;
}
}
Haven't double checked but...
[count + 1]
Given the for loop constraints (count < y)
the maximum possible value for count is y - 1...
but....
count + 1 when count = y -1... and thus is out of range... I think. Again. Haven't double checked.

Rotating matrices

Objectives
Imagine that, we have matrix like
a11 a12 a13
a21 a22 a23
a31 a32 a33
What I want to do is, from textbox value rotate this matrix so that, for example if I write 2 and press rotate, program must keep both diagonal values of matrix (in this case a11, a22, a33, a13, a31) and rotate 2 times clockwise other values. So result must be like
a11 a32 a13
a23 a22 a21
a31 a12 a33
It must work for all N x N size matrices, and as you see every 4 rotation takes matrix into default state.
What I've done
So idea is like that, I have 2 forms. First takes size of matrix (1 value, for example if it's 5, it generates 5x5 matrix). When I press OK it generates second forms textbox matrix like that
Form 1 code
private void button1_Click(object sender, EventArgs e)
{
int matrixSize;
matrixSize = int.Parse(textBox1.Text);
Form2 form2 = new Form2(matrixSize);
form2.Width = matrixSize * 50 + 100;
form2.Height = matrixSize *60 + 200;
form2.Show();
//this.Hide();
}
Form 2 code generates textbox matrix from given value and puts random values into this fields
public Form2(int matrSize)
{
int counter = 0;
InitializeComponent();
TextBox[] MatrixNodes = new TextBox[matrSize*matrSize];
Random r = new Random();
for (int i = 1; i <= matrSize; i++)
{
for (int j = 1; j <= matrSize; j++)
{
var tb = new TextBox();
int num = r.Next(1, 1000);
MatrixNodes[counter] = tb;
tb.Name = string.Format("Node_{0}{1}", i, j);
Debug.Write(string.Format("Node_{0}{1}", i, j));
tb.Text = num.ToString();
tb.Location = new Point(j * 50, i * 50);
tb.Width = 30;
tb.Visible = true;
this.splitContainer1.Panel2.Controls.Add(tb);
counter++;
}
}
}
Form 2 has 1 textbox for controlling rotation (others are generated on the fly, programmatically). What I want to do is, when I enter rotation count and press Enter on this textbox, I want to rotate textbox matrix as I explained above. Can't figure out how to do it.
Copy both diagonals to separate arrays, then rotate your matrix and replace diagonals. Below code shows each step:
class Program
{
static void Main(string[] args)
{
int matrixSize = 3;
string[,] matrix = new string[matrixSize,matrixSize];
//create square matrix
for (int x = 0; x < matrixSize; x++)
{
for (int y = 0; y < matrixSize; y++)
{
matrix[x, y] = "a" + (x + 1).ToString() + (y + 1).ToString();
}
}
Console.WriteLine(Environment.NewLine + "Base square matrix");
for (int x = 0; x < matrixSize; x++)
{
for (int y = 0; y < matrixSize; y++)
{
Console.Write(matrix[x, y] + " ");
}
Console.Write(Environment.NewLine);
}
Console.ReadKey();
//copy diagonals
string[] leftDiagonal = new string[matrixSize];
string[] rightDiagonal = new string[matrixSize];
for (int x = 0; x < matrixSize; x++)
{
leftDiagonal[x] = matrix[x, x];
rightDiagonal[x] = matrix[matrixSize - 1 - x, x];
}
Console.WriteLine(Environment.NewLine + "Diagonals");
for (int x = 0; x < matrixSize; ++x)
{
Console.Write(leftDiagonal[x] + " " + rightDiagonal[x] + Environment.NewLine);
}
Console.ReadKey();
//rotate matrix
string[,] rotatedMatrix = new string[matrixSize, matrixSize];
for (int x = 0; x < matrixSize; x++)
{
for (int y = 0; y < matrixSize; y++)
{
rotatedMatrix[x, y] = matrix[matrixSize - y - 1, x];
}
}
Console.WriteLine(Environment.NewLine + "Rotated");
for (int x = 0; x < matrixSize; x++)
{
for (int y = 0; y < matrixSize; y++)
{
Console.Write(rotatedMatrix[x, y] + " ");
}
Console.Write(Environment.NewLine);
}
Console.ReadKey();
//rotate matrix again
string[,] rotatedMatrixAgain = new string[matrixSize, matrixSize];
for (int x = 0; x < matrixSize; x++)
{
for (int y = 0; y < matrixSize; y++)
{
rotatedMatrixAgain[x, y] = rotatedMatrix[matrixSize - y - 1, x];
}
}
Console.WriteLine(Environment.NewLine + "Rotated again");
for (int x = 0; x < matrixSize; x++)
{
for (int y = 0; y < matrixSize; y++)
{
Console.Write(rotatedMatrixAgain[x, y] + " ");
}
Console.Write(Environment.NewLine);
}
Console.ReadKey();
//replace diagonals
for (int x = 0; x < matrixSize; x++)
{
rotatedMatrixAgain[x, x] = leftDiagonal[x];
rotatedMatrixAgain[matrixSize - 1 - x, x] = rightDiagonal[x];
}
Console.WriteLine(Environment.NewLine + "Completed" + Environment.NewLine);
for (int x = 0; x < matrixSize; x++)
{
for (int y = 0; y < matrixSize; y++)
{
Console.Write(rotatedMatrixAgain[x, y] + " ");
}
Console.Write(Environment.NewLine);
}
Console.ReadKey();
}
}
I don't know C#, so I can only give a suggestion in pseudocode:
Input: An N by N matrix in
Output: The input matrix rotated as described in the OP out
for i = 1 to N
for j = 1 to N
if N - j != i and i != j // Do not change values on either diagonal
out[j][N-i] = in[i][j]
else
out[i][j] = in[i][j]
Disclaimer: This algorithm is untested. I suggest you use a debugger to check that it works as you want.
This seems like quite an unorthodox UI presentation, but you're not too far off in terms of being able to achieve your functionality. Instead of a linear array, a rectangular array will make your job much easier. The actual rotation could be implemented with a for loop repeating a single rotation (which would be implemented as in the case 1 code), but I've decided to combine them into the four possible cases. This actually allows you to enter a negative number for number of rotations. Which reminds me, you really should do more error checking. At least protect against int.Parse throwing an exception both places it's used (with a try catch block or by switching to int.TryParse) and make sure it returns a meaningful number (greater than 0, possibly set a reasonable maximum other than int.MaxValue) for matrixSize in button1_Click.
namespace RotatingMatrices
{
public class Form2 : Form
{
// note these class fields
private TextBox[,] matrixNodes;
private int matrixSize;
public Form2(int matrSize)
{
InitializeComponent();
// note these inits
matrixSize = matrSize;
matrixNodes = new TextBox[matrixSize, matrixSize];
Random r = new Random();
// note the new loop limits
for (int i = 0; i < matrixSize; i++)
{
for (int j = 0; j < matrixSize; j++)
{
var tb = new TextBox();
int num = r.Next(1, 1000);
// note the change in indexing
matrixNodes[i,j] = tb;
tb.Name = string.Format("Node_{0}_{1}", i, j);
Debug.Write(string.Format("Node_{0}_{1}", i, j));
tb.Text = num.ToString();
tb.Location = new Point(j * 50, i * 50);
tb.Width = 30;
tb.Visible = true;
this.splitContainer1.Panel2.Controls.Add(tb);
}
}
}
private void buttonRotate_Click(object sender, EventArgs e)
{
string[,] matrix = new string[matrixSize, matrixSize];
int rotations = (4 + int.Parse(textBoxRotations.Text)) % 4; // note the addition of and mod by 4
switch(rotations)
{
case 1: // rotate clockwise
for (int i = 0; i < matrixSize; i++)
{
for (int j = 0; j < matrixSize; j++)
{
matrix[j, matrixSize - i - 1] = matrixNodes[i, j].Text;
}
}
break;
case 2: // rotate 180 degrees
for (int i = 0; i < matrixSize; i++)
{
for (int j = 0; j < matrixSize; j++)
{
matrix[i, j] = matrixNodes[matrixSize - i - 1, matrixSize - j - 1].Text;
}
}
break;
case 3: // rotate counter-clockwise
for (int i = 0; i < matrixSize; i++)
{
for (int j = 0; j < matrixSize; j++)
{
matrix[i, j] = matrixNodes[j, matrixSize - i - 1].Text;
}
}
break;
default: // do nothing
return;
}
// restore diagonals
for(int i = 0; i < matrixSize; i++)
{
matrix[i, i] = matrixNodes[i, i].Text;
matrix[i, matrixSize - i - 1] = matrixNodes[i, matrixSize - i - 1].Text;
}
// write strings back to text boxes
for (int i = 0; i < matrixSize; i++)
{
for (int j = 0; j < matrixSize; j++)
{
matrixNodes[i, j].Text = matrix[i, j];
}
}
}
}
}
I decided to tackle the issue using a listView instead of a text box, which makes the logic easier for me. Using this method, I was able to think of the matrix as successive boxes. I start on the outside and move in toward the middle, changing the size of my box each time.
Also, rather than using two forms, I use one. At the top I have a textbox where the user enters the size they want the array to be, and a button labeled "Fill" (button2). And at the bottom I have a textbox where the user enters the degree of rotation. When they click "Rotate," it kicks off a process of adding values to linked lists, combining and shifting the list, and then writing back out to the matrix. I'm sure I made it more convoluted than it has to be, but it was a great learning exercise.
After looking over jerry's code above, I think I'm going to look into rectangular arrays. :)
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace Recycle
{
public partial class Form1 : Form
{
public int size;
public LinkedList<string> topRight = new LinkedList<string>();
public LinkedList<string> bottomLeft = new LinkedList<string>();
public LinkedList<string> myMatrix = new LinkedList<string>();
public LinkedList<string> shiftMatrix = new LinkedList<string>();
public Form1()
{
InitializeComponent();
}
private void button2_Click(object sender, EventArgs e)
{
listView1.Clear();
size = int.Parse(textBox2.Text);
int c = 0;
int q = 0;
int w = 0;
string[] content = new string[size];
Random rnd = new Random();
for (c = 0; c < size; c++)
{
listView1.Columns.Add("", 25);
}
for (q = 0; q < size; q++)
{
for (w = 0; w < size; w++)
{
content[w] = rnd.Next(9,100).ToString();
}
ListViewItem lvi = new ListViewItem(content);
listView1.Items.Add(lvi);
}
}
public bool iseven(int size)
{
if (size % 2 == 0)
{
return true;
}
else
{
return false;
}
}
public void button1_Click(object sender, EventArgs e)
{
if (listView1.Items.Count < 3)
{
MessageBox.Show("Matrix cannot be rotated.");
return;
}
bool even = false;
int shift = int.Parse(textBox1.Text); //amount to shift by
int box = listView1.Items.Count - 1; //size of box
int half = Convert.ToInt32(listView1.Items.Count / 2);
int corner = 0; //inside corner of box
if (shift > listView1.Items.Count)
{
shift = shift % ((listView1.Items.Count - 2) * 4);
}
do
{
eachPass(shift, box, corner);
++corner;
--box;
} while (box >= half + 1);
}
public void eachPass(int shift, int box, int corner)
{
int x;
int i;
//Read each non-diagonal value into one of two lists
for (x = corner + 1; x < box; x++)
{
topRight.AddLast(listView1.Items[corner].SubItems[x].Text);
}
x = box;
for (i = corner + 1; i < box; i++)
{
topRight.AddLast(listView1.Items[i].SubItems[x].Text);
}
for (x = box - 1; x > corner; x--)
{
bottomLeft.AddLast(listView1.Items[box].SubItems[x].Text);
}
x = corner;
for (i = box - 1; i > corner; i--)
{
bottomLeft.AddLast(listView1.Items[i].SubItems[x].Text);
}
string myTest = "";
//join the two lists, so they can be shifted
foreach (string tR in topRight)
{
myMatrix.AddLast(tR);
}
foreach (string bL in bottomLeft)
{
myMatrix.AddLast(bL);
}
int sh;
//shift the list using another list
for (sh = shift; sh < myMatrix.Count; sh++)
{
shiftMatrix.AddLast(myMatrix.ElementAt(sh));
}
for (sh = 0; sh < shift; sh++)
{
shiftMatrix.AddLast(myMatrix.ElementAt(sh));
}
//we need the sizes of the current lists
int trCnt = topRight.Count;
int blCnt = bottomLeft.Count;
//clear them for reuse
topRight.Clear();
bottomLeft.Clear();
int s;
//put the shifted values back
for (s = 0; s < trCnt; s++)
{
topRight.AddLast(shiftMatrix.ElementAt(s));
}
for (s = blCnt; s < shiftMatrix.Count; s++)
{
bottomLeft.AddLast(shiftMatrix.ElementAt(s));
}
int tRn = 0;
int bLn = 0;
//write each non-diagonal value from one of two lists
for (x = corner + 1; x < box; x++)
{
listView1.Items[corner].SubItems[x].Text = topRight.ElementAt(tRn);
++tRn;
}
x = box;
for (i = corner + 1; i < box; i++)
{
listView1.Items[i].SubItems[x].Text = topRight.ElementAt(tRn);
++tRn;
}
for (x = box - 1; x > corner; x--)
{
listView1.Items[box].SubItems[x].Text = bottomLeft.ElementAt(bLn);
++bLn;
}
x = corner;
for (i = box - 1; i > corner; i--)
{
listView1.Items[i].SubItems[x].Text = bottomLeft.ElementAt(bLn);
++bLn;
}
myMatrix.Clear();
shiftMatrix.Clear();
topRight.Clear();
bottomLeft.Clear();
}
}
}

Pythagoras triangle

I would like to ask you about this programing part, is it everything ok?
the task was:
Write the pseudocode or flow diagram and code for the theorem of Pythagoras - for right-angle triangle with three ribs (a, b, and c) of type integer
int KendiA = 0;
int KendiB = 0;
int H = 0;
string Trekendeshi = null;
int gjetja = 0;
for (KendiA = 1; KendiA <= 15; KendiA++)
{
for (KendiB = 1; KendiB <= 15; KendiB++)
{
for (H = 1; H <= 30; H++)
{
if ((Math.Pow(KendiA, 2) + Math.Pow(KendiB, 2) == Math.Pow(H, 2)))
{
gjetja = gjetja + 1;
Trekendeshi = gjetja + "\t" + KendiA + "\t" + KendiB + "\t" + H;
Console.WriteLine(Trekendeshi);
}
}
}
}
It's much easier to find pythagorean triples than to iterate through every set of three. Have a look at http://en.wikipedia.org/wiki/Formulas_for_generating_Pythagorean_triples for instance.
Also, it's better to square integers by multiplying it with itself rather than using pow(i,2).
Your code works well but it prints repeated ones. Count KendiB from KendiA solves your problem
for (KendiA = 1; KendiA <= 15; KendiA++){
for (KendiB = KendiA; KendiB <= 15; KendiB++){
Here is simplest way
for(int i=2; i<10; i++){
int a = 2*i;
int b = i*i-1;
int c = i*i+1;
System.out.println(a + " " + b + " " + c);
}

Categories