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);
}
Related
So the problem that I'm trying to optimize is to find and print all four-digit numbers of the type ABCD for which: A + B = C + D.
For example:
1001
1010
1102
etc.
I have used four for loops to solve this (one for every digit of the number).
for (int a = 1; a <= 9; a++)
{
for (int b = 0; b <= 9; b++)
{
for (int c = 0; c <= 9; c++)
{
for (int d = 0; d <= 9; d++)
{
if ((a + b) == (c + d))
{
Console.WriteLine(" " + a + " " + b + " " + c + " " + d);
}
}
}
}
}
My question is: how can I solve this using only 3 for loops?
Here's an option with two loops (though still 10,000 iterations), separating the pairs of digits:
int sumDigits(int input)
{
int result = 0;
while (input != 0)
{
result += input % 10;
input /= 10;
}
return result;
}
//optimized for max of two digits
int sumDigitsAlt(int input)
{
return (input % 10) + ( (input / 10) % 10);
}
// a and b
for (int i = 0; i <= 99; i++)
{
int sum = sumDigits(i);
// c and d
for (int j = 0; j <= 99; j++)
{
if (sum == sumDigits(j))
{
Console.WriteLine( (100 * i) + j);
}
}
}
I suppose the while() loop inside of sumDigits() might count as a third loop, but since we know we have at most two digits we could remove it if needed.
And, of course, we can use a similar tactic to do this with one loop which counts from 0 to 9999, and even that we can hide:
var numbers = Enumerable.Range(0, 10000).
Where(n => {
// there is no a/b
if (n < 100 && n == 0) return true;
if (n < 100) return false;
int sumCD = n % 10;
n /= 10;
sumCD += n % 10;
n /= 10;
int sumAB = n % 10;
n /= 10;
sumAB += n % 10;
return (sumAB == sumCD);
});
One approach is to write a method that takes in an integer and returns true if the integer is four digits and the sum of the first two equal the sum of the second two:
public static bool FirstTwoEqualLastTwo(int input)
{
if (input < 1000 || input > 9999) return false;
var first = input / 1000;
var second = (input - first * 1000) / 100;
var third = (input - first * 1000 - second * 100) / 10;
var fourth = input - first * 1000 - second * 100 - third * 10;
return (first + second) == (third + fourth);
}
Then you can write a single loop from 1000-9999 and output the numbers for which this is true with a space between each digit (not sure why that's the output, but it appears that's what you were doing in your sample code):
static void Main(string[] args)
{
for (int i = 1000; i < 10000; i++)
{
if (FirstTwoEqualLastTwo(i))
{
Console.WriteLine(" " + string.Join(" ", i.ToString().ToArray()));
}
}
Console.Write("Done. Press any key to exit...");
Console.ReadKey();
}
We can compute the value of d from the values of a,b,c.
for (int a = 1; a <= 9; a++)
{
for (int b = 0; b <= 9; b++)
{
for (int c = 0; c <= 9; c++)
{
if (a + b >= c && a + b <= 9 + c)
{
int d = a + b - c;
Console.WriteLine(" " + a + " " + b + " " + c + " " + d);
}
}
}
}
We can further optimize by changing the condition of the third loop to for (int c = max(0, a + b - 9); c <= a + b; c++) and getting rid of the if statement.
I'm working on a C# assignment in which i have to create a minimum spanning tree through the use of arrays. My code is made up of three arrays which track the nodes and whether or not they have been reached. I have to find the smallest total for all of the randomly generated links to be added up to visit all of the nodes. However, for some reason it is not quite working. The totals being produced are not correct and just wondered if anyone could help me work out why.I believe the error must be between the calculating of the total or how the minimum value is being decided or possible both however i am unsure.
So far i have tried changing the way it is calculated to involve a sum variable to store the values seperately. Ive attempted to add another if statement that would stop the min value from being anything above 98 ( the void value is 99) i have also tried to alter the earlier code to see if how i am testing the values in the SP array are the desired ones. still no results
int n = 5; //n = number of values
int m = 50; //m = max value in arra
int VoidValue = 99; // if i = j value = void value
int Total = 0; //Total value for spanning tree
int sum = 0; //Sum for total value for spanning tree
Random Rand = new Random(); //Create randomise value
int[,] c = new int[n + 1, n + 1]; //Cost array
int[] SP = new int[n + 1]; //Spanned array
int[,] AD = new int[n + 1, n + 1]; //Adjacency array
for (int i = 1; i <= n; i++)
{
SP[i] = 0;
for (int j = 1; j <= n; j++)
{
if (i == j)
{
c[i, j] = VoidValue; // give void spaces the value of 99
AD[i, j] = 0;
}
else
{
c[i, j] = Rand.Next(1, m); // Populate the array with randomised values
AD[i, j] = 0;
}
}
}
//Output all arrays to screen
Console.WriteLine("Cost Array: At the beginning");
Console.WriteLine("");
for (int i = 1; i <= n; i++)
{
for (int j = 1; j <= n; j++)
{
if (i == j)
{
Console.Write("c[" + i + "," + j + "] = " + "- " + " ");
}
else
{
Console.Write("c[" + i + "," + j + "] = " + c[i, j].ToString("00") + " ");
}
}
Console.WriteLine();
}
Console.ReadLine();
Console.WriteLine("");
Console.WriteLine("Spanned Array : At the beginning");
Console.WriteLine("");
for (int i = 1; i <= n; i++)
{
Console.Write("S[" + i + "] = " + SP[i].ToString("00") + " ");
Console.WriteLine();
}
Console.ReadLine();
Console.WriteLine("");
Console.WriteLine("Adjacency Array : At the beginning");
Console.WriteLine("");
for (int i = 1; i <= n; i++)
{
for (int j = 1; j <= n; j++)
{
if (i == j)
{
Console.Write("A[" + i + "," + j + "] = " + "- " + " ");
}
else
{
Console.Write("A[" + i + "," + j + "] = " + AD[i, j].ToString("00") + " ");
}
}
Console.WriteLine();
}
Console.ReadLine();
// Random Starting Point
int startPoint = Rand.Next(1, n + 1);
Console.WriteLine("Start at node " + startPoint);
SP[startPoint] = 1;
//Check the spanned array
Console.WriteLine("");
Console.WriteLine("Spanned Array : After the starting point has been chosen ");
Console.WriteLine("");
for (int i = 1; i <= n; i++)
{
Console.Write("S[" + i + "] = " + SP[i].ToString("00") + " ");
Console.WriteLine();
}
Console.ReadLine();
// Find minimum vallue link, repeatedly follow these links until spanned array is full
for (int p = 1; p < n; p++) // For every value of the spanned array
{
int MinValue = VoidValue, MinValuei = 0, MinValuej = 0; // declare variables
for (int i = 1; i <= n; i++)
{
for (int j = 1; j <= n; j++) // I and J are for both variables of the cost and adjacent array
if (i != j)
{
if (SP[i] == 1) //Spanned node
{
if (SP[j] == 0) //Unspanned node
{
if (c[i, j] < MinValue)
{
MinValue = c[i, j];
MinValuei = i;
MinValuej = j;
}
}
}
}
AD[MinValuei, MinValuej] = 1;
SP[MinValuej] = 1;
}
Console.WriteLine("");
Console.WriteLine("The min value is: " + MinValue);
Total = Total + MinValue;
Console.WriteLine("");
Console.WriteLine("The total is: " + Total);
}
//Finally output spanned and adjacent arrays
Console.WriteLine("");
Console.WriteLine("Spanned Array: After spanning tree");
Console.WriteLine("");
for (int i = 1; i <= n; i++)
{
Console.Write("S[" + i + "] = " + SP[i].ToString("00") + " ");
Console.WriteLine();
}
Console.ReadLine();
Console.WriteLine("");
Console.WriteLine("Adjacency Array : After spanning tree");
Console.WriteLine("");
for (int i = 1; i <= n; i++)
{
for (int j = 1; j <= n; j++)
{
if (i == j)
{
Console.Write("A[" + i + "," + j + "] = " + "- " + " ");
}
else
{
Console.Write("A[" + i + "," + j + "] = " + AD[i, j].ToString("00") + " ");
}
}
Console.WriteLine();
}
Console.ReadLine();
//Output total value for the spanning tree
Console.WriteLine("");
Console.WriteLine("The total value for the spanning tree: " + Total);
Console.WriteLine("");
Console.ReadLine();
I'm a student and was absent for one meeting so I'm self studying for this topic.
There are 4 activities and this is the last one, but its seems that I'm stuck.
Basically what i want is to display the selected combo box item in the given input number of rows and columns. In my code, it only displays the first row and and first column.
How can I make it display a grid (row x column) of the given character (eg. 4x4, 5x2, 3x4)?
int x, y,z;
y = int.Parse(textBox1.Text);
z = int.Parse(textBox2.Text);
label4.Text = " ";
for (x = 1; x <= y; x++)
{
label4.Text = label4.Text + comboBox1.Text;
}
for (x = 1; x <= z; x++)
{
label4.Text = label4.Text + comboBox1.Text + "\n";
}
Just modify you second loop :)
string line = label4.Text;
// line = "####", now we want to append it three times to Label4 (because first line is already there)
for (x = 1; x < z; x++)
{
label4.Text += "\n" + line;
}
I took example value of lines (rows) to be 4 :) Hope I explained well. Another approach wold be to use nested loops:
for(int i = 0; i < z; i++)
{
for(int j = 0; j < y; j++)
{
label4.Text += comboBox1.Text;
}
label4.Text += "\n";
}
you better use StringBuilder
int x, y, z;
StringBuilder sb = new StringBuilder();
y = int.Parse(textBox1.Text);
z = int.Parse(textBox2.Text);
label4.Text = " ";
for (x = 1; x <= y; x++)
{
sb.Append( label4.Text + comboBox1.Text);
}
sb.Append("\n");
for (x = 1; x <= z; x++)
{
sb.Append(label4.Text + comboBox1.Text + "\n");
}
label4.Text = sb.ToString();
take a look at this:
int x = 4;
int y = 3;
string s = "#";
for (int ix = 0; ix < x; ix++)
{
label2.Text += s;
}
for (int iy = 0; iy < y; iy++)
{
label2.Text += s + "\n";
}
if you need all corner:
int y = 4;
int x = 10;
StringBuilder sb = new StringBuilder();
string s = string.Empty;
for (int i = 1; i < x + 1; i++)
{
sb.Append("#");
}
s = sb.ToString() + "\n";
//Remaining string
String rStr = string.Empty;
for (int i = 0; i < y; i++)
{
rStr += s;
}
label2.Text = rStr;
The code below only makes a right angle triangle, how would I make it into an isosceles triangle?
int height = 4;
string star = "";
for (int i = 0; int i < height; i++)
{
star += "*";
Console.WriteLine(star);
}
Console.ReadLine();
This only displays a right angle triangle. What I attempted to make was a pyramid.
Here you have a cleaner code:
int numberoflayer = 4;
int empty;
int number;
for (int i = 1; i <= numberoflayer; i++)
{
for (empty = 1; empty <= (numberoflayer - i); empty++)
Console.Write(" ");
for (number = 1; number <= i; number++)
Console.Write('*');
for (number = (i - 1); number >= 1; number--)
Console.Write('*');
Console.WriteLine();
}
This draws your christmas tree:
int height = 4;
for (int i = 0; i < height; i++)
{
int countSpaces = (int)Math.Ceiling((height * 2 / 2d) - i);
int countStars = 1 + (i * 2);
string line = new string(' ', countSpaces) + new string('*', countStars);
Console.WriteLine(line);
}
Dirty code but there you go
int height = 4;
string empty = " ";
String star = "";
for(int i = 0; i<height; i++)
{
star += " *";
empty = empty.Length > 0 ? empty.Remove(0,1) : " ";
Console.WriteLine(empty + star);
}
Console.ReadLine();
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.