Hello i've got a easy programming task in C# but im stuck on the last part. I need to make 2 arrays that have random numbers (3x3) and on the end i need to sum them up in one number.
So its: array1 with 3 numbers + array2 with 3 numbers = array3 with all the array numbers addition. Can somebody please help me?
My code is:
static void Main(string[] args)
{
int[,] pole1 = new int[3, 3];
int[,] pole2 = new int[3, 3];
int[,] pole3 = new int[3, 3];
Random random1 = new Random();
Console.WriteLine("Pole 1 je: ");
for (int a = 0; a <= 2; a++)
{
for (int b = 0; b <= 2; b++)
{
pole1[a, b] = random1.Next(1, 9);
Console.Write(pole1[a, b]);
}
Console.WriteLine();
}
Console.WriteLine("Pole 2 je: ");
for (int a = 0; a <= 2; a++)
{
for (int b = 0; b <= 2; b++)
{
pole2[a, b] = random1.Next(1, 9);
Console.Write(pole2[a, b]);
}
Console.WriteLine();
}
Console.WriteLine("Součet polí je: ");
for (int a = 0; a <= 2; a++)
{
for (int b = 0; b <= 2; b++)
{
pole3[a, b] = (pole1[a, b] + pole2[a, b]);
Console.Write(pole3[a, b]);
}
Console.WriteLine();
}
Console.ReadKey();
}
}
I've got the two arrays but idk how to sum them up.
I think your code is working properly
Console.Write(pole1[a, b] + "\t"); // Add "\t"
Console.Write(pole2[a, b] + "\t"); // Add "\t"
Console.Write(pole3[a, b] + "\t"); // Add "\t"
UPDATE : if you want like bellow
Array 1 : 373
Array 2 : 176
Result : 549
Last loop will be
for (int a = 0; a <= 2; a++)
{
int sum = (pole1[a, 0] + pole2[a, 0]) * 100 + (pole1[a, 1] + pole2[a, 1]) * 10 + (pole1[a, 2] + pole2[a, 2]) ;
pole3[a, 0] = sum / 100;
pole3[a, 1] = (sum - pole3[a, 0] * 100) / 10;
pole3[a, 2] = sum - (pole3[a, 0] * 100) - (pole3[a, 1] * 10);
Console.Write($"{pole3[a, 0]}" + "\t" + $"{pole3[a, 1]}" + "\t" + $"{pole3[a, 2]}");
Console.WriteLine();
}
The Sum() method in Linq is a good goto if you want to sum up an array, however multi-dimensional arrays do not implement IEnumerable<T> by default, which can cause a few bumps in the road. Luckily Linq provides us a way to specify the type using the Cast<T> method like so:
int total = pole1.Cast<int>().Sum() + pole2.Cast<int>().Sum();
Note that I've replaced <T> with <int> as we are using generics (read more on MSDN).
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 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();
namespace Suma_diagonala_secundara
{
class Program
{
static void Main(string[] args)
{
int n, i, j, s = 0;
Console.Write("n= ");
n = Convert.ToInt32(Console.ReadLine());
int[,] tab = new int[n, n];
for(i=0;i<n;i++)
for (j = 0; j < n; j++)
{
Console.Write("tab[{0}][{1}]= ", i + 1, j + 1);
tab[i, j] = Convert.ToInt32(Console.ReadLine());
}
Console.Write("\nElementele matricii sunt: ");
for (i = 0; i < n; i++)
{
for (j = 0; j < n; j++)
Console.Write("{0} ", tab[i, j]);
Console.WriteLine("");
}
Console.WriteLine("Suma elementelor de pe diagonala secundara este: ");
for (i = 0; i < n; i++)
{
s = s + tab[i, n - i + 1];
}
Console.ReadKey();
}
}
}
In your loop
for (i = 0; i < n; i++)
{
s = s + tab[i, n - i + 1];
}
you are accessing the array out of bounds, since n - 0 + 1 = n + 1 is larger than n - 1 (the largest index in tab).
What you actually want is (note the parentheses)
for (i = 0; i < n; i++)
{
s = s + tab[i, n - (i + 1)];
}
The following line:
s = s + tab[i, n - i + 1];
Is throwing an IndexOutOfRangeException because you are requesting an index higher than the array capacity.
The correct loop code is (with decrement instead increment)
for (i = 0; i < n; i++)
{
s = s + tab[i, n - i - 1];
}
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.
I have the following code in the main() method:
const int Length = 20;
const int NumberOfExperiments = 100;
static void Main(string[] args)
{
Random gen = new Random();
double[][] arr = new double[NumberOfExperiments][];
for (int j = 0; j < NumberOfExperiments; ++j)
{
arr[j] = new double[Length + 4];
for (int i = 0; i < Length; ++i)
{
arr[j][i] = gen.NextDouble();
}
arr[j][Length] = bubbleSort(arr[j]);
arr[j][Length + 1] = insertSort(arr[j]);
arr[j][Length + 2] = arr[j][Length] - arr[j][Length + 1];
arr[j][Length + 3] = arr[j][Length + 2] * arr[j][Length + 2];
foreach(double memb in arr[j]){
Console.WriteLine("{0}", memb);
}
Console.ReadKey();
}
WriteExcel(arr, "sorting");
Console.ReadKey();
}
After the first ReadKey() i have the following output:
0
0
0
0
0.046667384
0.178001223
0.197902503
0.206131403
0.24464349
0.306212793
0.307806501
0.354127458
0.385836004
0.389128544
0.431109518
0.489858235
0.530548627
0.558604611
0.647516463
0.762527595
0.874646365
152
-151.1253536
22838.87251
I don't know why the first several elements of array are filled with 0. The first iteration always begins with i=0(or j=0), so it's Ok.
Functions bubbleSort() and insertSort() work correctly and return the number of swaps.
I have used C# for several years, but I really can't understand why this code doesn't work.
When you create the "row", you do this:
arr[j] = new double[Length + 4];
But then loop like this:
for (int i = 0; i < Length; ++i)
So the last 4 elements are left with the default value (0). When you sort, these elements go to the beginning.
It looks like bubbleSort() gets an array and sorts it, at the time of the call the last 4 elements are empty (set to 0), so they go to the beginning in the result. Check if bubbleSort() uses Array.Length somewhere and make sure it subtracts 4 there.