I'm trying to print "x" for the value within the array for example the integer 32 would print 32 x's but I'm not sure how to go about doing so.
Any help or pointers on what to do would be great have looked around but can't seem to find anything that helps me without over complicating it.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
namespace Histogram
{
class Program
{
static void Main(string[] args)
{
string output = "";
int[] x;
x = new int[18];
int[] y = { 32, 27, 64, 18, 95, 14, 90, 70, 60, 37, 17, 56, 99, 34, 75, 36, 12, 8, 100, 77 };
const int ARRAY_SIZE = 18;
int[] z;
z = new int[ARRAY_SIZE];
for (int i = 0; i < z.Length; i++)
z[i] = 2 * i;
Console.WriteLine("Element\t \tValue\t \tHistogram\t\t\n");
for (int i = 0; i < ARRAY_SIZE; i++)
{
output += i + "\t\t" + y[i] + "\t\t" + y[i] + "\t\t" + "\n";
}
Console.WriteLine(output);
Console.ReadKey();
}
}
}
What you are looking for is already built into String class. It has a constructor
to create a string of repeating chars for any length. No need for String Builder or any extra loops, that would be over complicated.
static void Main(string[] args)
{
string output = "";
const int ARRAY_SIZE = 18;
int[] x = new int[ARRAY_SIZE];
int[] z = new int[ARRAY_SIZE];
int[] y = { 32, 27, 64, 18, 95, 14, 90, 70, 60, 37, 17, 56, 99, 34, 75, 36, 12, 8, 100, 77 };
for (int i = 0; i < z.Length; i++)
z[i] = 2 * i;
Console.WriteLine("Element\t \tValue\t \tHistogram\t\t\n");
for (int i = 0; i < ARRAY_SIZE; i++)
{
string bar = new string('X', y[i]);
output += i + "\t\t" + y[i] + "\t\t" + bar + "\t\t" + "\n";
}
Console.WriteLine(output);
Console.ReadKey();
}
I was not entirely sure if I was following what you wanted to do but this piece of code may be something like what you were doing with your loops.
Used StringBuilder because it "doesn't create a new object in the memory but dynamically expands memory to accommodate the modified string"
using System;
using System.Text;
public class Program
{
public static void Main()
{
string output = "";
StringBuilder sb = new StringBuilder("x");
int[] y = { 32, 27, 64, 18, 95, 14, 90, 70, 60, 37, 17, 56, 99, 34, 75, 36, 12, 8, 100, 77 };
//used to determine how many elements in the y array to go through
const int ARRAY_SIZE = 5;
int[] z;
z = new int[ARRAY_SIZE];
for(int i=0; i< z.Length; i++){
if(sb.Length != y[i])
sb.Clear();
for(int j=0; j < y[i]; j++)
sb.Append("x");
output += i + "\t\t" + y[i] + "\t\t" + sb + "\t\t" + "\n";
//clear the string builder var for next set of x's
sb.Clear();
}
Console.WriteLine(output);
}
}
The easiest thing would probably be to put the cout statement into 2 for loops. The first one for the length of the Array you want to print and the second one for the Number that is at that place.
As an example (array is the name of your array and ARRAY_SIZE is the length):
for (int x = 0; x < ARRAY_SIZE; x++) {
for (int y = 0; y <= array[x]; y++) {
output += x + " ";
}
output += "\n";
}
I would use the PadRight method as #TaW suggested. I don't see any reason why you stored your result on the output variable, then printed it.
Please find my solution below(removed unnecessary codes) where I am printing immediately without a need to store anything in the memory:
static void Main(string[] args)
{
const char paddingChar = 'X';
const string tabs = "\t\t";
int[] y = { 32, 27, 64, 18, 95, 14, 90, 70, 60, 37, 17, 56, 99, 34, 75, 36, 12, 8, 100, 77 };
Console.WriteLine($"Element{tabs}Value{tabs}Histogram");
for (int i = 0; i < y.Length; i++)
{
Console.WriteLine($"{i}{tabs}{y[i]}{tabs}{"".PadRight(y[i], paddingChar)}");
}
Console.ReadKey();
}
Related
I have a 1D array of ints:
int[] array = { 10, 11, 12, 13, 14, 20, 21, 22, 23, 24, 30, 31, 32,33, 34,40,41,42,43, 44};
I would like to divide this 1D array into a 2D array of 4 rows and 5 columns, where the first 5 values goes into row 1, the next 5 in row 2 and so on. The final result should look like this:
array2D:
[[10, 11, 12, 13, 14]
[20, 21, 22, 23, 24]
[30, 31, 32, 33, 34]
[40, 41, 42, 43, 44]]
In reality the array will be much longer(maybe 100+ rows), but the number of columns is 5 and number of rows is dividable by 5. I have simplified for example. This is what I have tried so far:
int[] array = { 10, 11, 12, 13, 14, 20, 21, 22, 23, 24, 30, 31, 32,33, 34,40,41,42,43, 44};
int[,] array2D = new int[(array.Length/5),5];
int count_0 = 1;
int count_1 = 1;
int count_2 = 1;
int count_3 = 1;
int count_4 = 1;
for (int i = 0; i < array.Length; i++)
{
if (i < 5)
{
// works for the first 5 values:
array2D[0, i] = array[i];
}
// I tried this approach for the rest where I try to say that if Im at index 5,
//and every 5th element from here, append to it to index[i,0] of array2D and so on.
// This do not work, and is what I need help with.
else if (i >= 5 && i % 5 == 0)
{
array2D[count_0, 0] = array[i];
count_0++;
}
else if (i >= 6 && i % 5 == 0)
{
array2D[count_1, 1] = array[i];
count_1++;
}
else if (i >= 7 && i % 5 == 0)
{
array2D[count_2, 2] = array[i];
count_2++;
}
else if (i >= 8 && i % 5 == 0)
{
array2D[count_3, 3] = array[i];
count_3++;
}
else if (i >= 9 && i % 5 == 0)
{
array2D[count_4, 4] = array[i];
count_4++;
}
}
Of course for this example I could just say if > 5 && <10 {append to array2D} and if > 10 && <15 {append to array2D} and so on, but I want something that works for a large array of hundreds of values. If someone has a smarter way to do this please let me know.
Thank you for any help!
You can just calculate the indexes:
for(int i=0;i<array.Length;i++)
array2D[i/5, i%5] = array[i];
You can calculate the indexes easily using simple division. The row is calculated by the dividing i with the wanted column numbers. The column is simply the reminder of that division.
using System;
public class Program
{
public static T[,] SplitInto2DArray<T>(T[] array, int rows, int columns) {
T[,] result = new T[rows, columns];
for (int i = 0; i < array.Length; i++) {
result[i / columns, i % columns] = array[i];
}
return result;
}
public static void PrintArray<T>(T[,] array) {
for (int i = 0; i < array.GetLength(0); i++) {
for (int j = 0; j < array.GetLength(1); j++) {
Console.Write(array[i, j] + " ");
}
Console.WriteLine();
}
}
public static void Main()
{
int[] array = { 10, 11, 12, 13, 14, 20, 21, 22, 23, 24, 30, 31, 32, 33, 34, 40, 41, 42, 43, 44};
int[,] splittedArray = SplitInto2DArray(array, 4, 5);
PrintArray(splittedArray);
}
}
You can accomplish with LINQ using Enumerable.GroupBy.
array.GroupBy(x => x / 5)
.Select(x => x.ToArray())
.ToArray()
So, i have a two dimensional arrays like this :
double[,] tabel_nilai = new double[,]{{3500, 70, 10, 80, 3000, 36},
{4500, 90, 10, 60, 2500, 48 },
{4000, 80, 9, 90, 2000, 48 },
{4000, 70, 8, 50, 1500, 60 }};
and then, I want to form one dimensional array with the maximum value on the first column (3500, 4500, 4000 and 4000). But, minimum value on the other column.
I did this :
double[] pembagi = new double[kepentingan.Length];
for (int i = 0; i < produk.Length; i++)
{
for(int j=0; j < kriteria.Length; i++)
{
pembagi[i] = Math.Max(tabel_nilai[i,j],tabel_nilai[i,j]);
Console.WriteLine(pembagi);
}
}
but, failed miserably.
I would be very pleased if somebody can give me some logics on how to solve this problem. thanks
You can use LINQ in this case that probably gives the shortest and simplest code to solve this without explicit use of any nested loops.
double[,] tabel_nilai = new double[,]{ {3500, 70, 10, 80, 3000, 36},
{4500, 90, 10, 60, 2500, 48 },
{4000, 80, 9, 90, 2000, 48 },
{4000, 70, 8, 50, 1500, 60 }};
double[] oneDimensionalArray = tabel_nilai.Cast<double>().Select((x, i) => new { x, index = i / tabel_nilai.GetLength(1) })
.GroupBy(x=>x.index)
.Select(x=>x.Select(s=>s.x).ToList().Max())
.ToArray();
What it does is that it converts the 2D array into a list and then groups by each row and finally calculates Max value for that row. You can use it to get Min as well, just replace Max() with Min(). Additionally, it can help you do many other measures if you need using the same expression.
I hope it helps.
First you can use jagged arrays to get "slice" or row of rows.
Then using delegate you can apply function as per requirement, example below:
delegate double maxMin(IEnumerable<double> arr);
public static void GetData()
{
double[][] tableData = new double[][]{
new double[] {3500, 70, 10, 80, 3000, 36},
new double[] {4500, 90, 10, 60, 2500, 48 },
new double[] {4000, 80, 9, 90, 2000, 48 },
new double[] {4000, 70, 8, 50, 1500, 60 }
};
int length = tableData.Length;
double[] requiredValues = new double[length];
maxMin maxMinObj;
for (int i = 0; i < length; i++)
{
if (i == 0)
maxMinObj = x => x.Max();
else
maxMinObj = x => x.Min();
requiredValues[i] = maxMinObj(tableData[i]);
Console.WriteLine(requiredValues[i]);
}
}
Assuming alternating max/min for each column here is the correction to your code. Your code had multiple issues, so I'll just post the code with all the corrections:
using System;
public class Program
{
public static void Main()
{
double[,] tabel_nilai = new double[,]{ {3500, 70, 10, 80, 3000, 36},
{4500, 90, 10, 60, 2500, 48 },
{4000, 80, 9, 90, 2000, 48 },
{4000, 70, 8, 50, 1500, 60 }};
for (int j = tabel_nilai.GetLowerBound(1); j <= tabel_nilai.GetUpperBound(1); j++)
{
var seekingMax = ((j - tabel_nilai.GetLowerBound(1)) % 2) == 0;
var maxmin = tabel_nilai[0, j];
for(int i = tabel_nilai.GetLowerBound(0) + 1; i <= tabel_nilai.GetUpperBound(0); i++)
{
if (seekingMax)
{
maxmin = Math.Max(maxmin,tabel_nilai[i, j]);
}
else
{
maxmin = Math.Min(maxmin,tabel_nilai[i, j]);
}
}
Console.WriteLine("{0}: {1}", seekingMax ? "Max" : "Min", maxmin);
}
}
}
I am trying to determine what the neighbour bets would be for a given number on a roulette wheel.
At the moment I pass a pocket number to a function and below is my code. "pocket_number()[0]" is the value of the number I want to determine the neighbours of.
int[] neightbourbets = neighbourbets(pocket_number()[0]);
neighbourbets() is as follows (this outputs an array of element numbers so elsewhere in my program I can extract them from the same array structure). At the moment I have a crude way of determining the the neighbour bets and getting the function to state which numbers are 6 numbers either side of it.
Is there a better way to do this? I've found one of the problems (that I've overcome with the below) is if I want to know the neighbours for "0" for example which means the code needs to get the numbers from the end of the array.
public int[] neighbourbets(int x)
{
int[] pocket_array = new[] {0, 32, 15, 19, 4, 21, 2, 25, 17, 34, 6, 27, 13, 36, 11, 30, 8, 23, 10, 5, 24, 16, 33, 1, 20, 14, 31, 9, 22, 18, 29, 7, 28, 12, 35, 3, 26};
int predictednum = Array.IndexOf(pocket_array,x); //element number of pocket_array for chosen number
int[] neighbourbets = new[] {0,0,0,0,0,0,0,0,0,0,0,0,0};
neighbourbets[0] = predictednum;
neighbourbets[1] = predictednum+1;
neighbourbets[2] = predictednum+2;
neighbourbets[3] = predictednum+3;
neighbourbets[4] = predictednum+4;
neighbourbets[5] = predictednum+5;
neighbourbets[6] = predictednum+6;
neighbourbets[7] = predictednum-1;
neighbourbets[8] = predictednum-2;
neighbourbets[9] = predictednum-3;
neighbourbets[10] = predictednum-4;
neighbourbets[11] = predictednum-5;
neighbourbets[12] = predictednum-6;
for (int i = 0; i < neighbourbets.Length; i++)
{
//clockwise neighours
if (neighbourbets[i] == -1) {
neighbourbets[i] = 36;
}
if (neighbourbets[i] == -2) {
neighbourbets[i] = 35;
}
if (neighbourbets[i] == -3) {
neighbourbets[i] = 34;
}
if (neighbourbets[i] == -4) {
neighbourbets[i] = 33;
}
if (neighbourbets[i] == -5) {
neighbourbets[i] = 32;
}
if (neighbourbets[i] == -6) {
neighbourbets[i] = 31;
}
//anticlockwise neighbours
if (neighbourbets[i] == 37) {
neighbourbets[i] = 0;
}
if (neighbourbets[i] == 38) {
neighbourbets[i] = 1;
}
if (neighbourbets[i] == 39) {
neighbourbets[i] = 2;
}
if (neighbourbets[i] == 40) {
neighbourbets[i] = 3;
}
if (neighbourbets[i] == 41) {
neighbourbets[i] = 4;
}
if (neighbourbets[i] == 42) {
neighbourbets[i] = 5;
}
}
return neighbourbets;
}
Any helps or guidence is appreciated! :)
Write a small helper function to wrap around the index:
private int GetPocketIndex( int start, int offset, int count )
{
int pos = ( start + offset ) % count;
if( pos >= 0 )
return pos;
else
return count + pos; // pos is negative so we use +
}
The modulus there will help it wrap around when it goes above the maximum, and the if will do it for the minimum. This could probably be done easier though, but it eludes me at the moment.
Then, if you need that specific order, perhaps something like this:
int[] offsets = new int[] { 0,
1, 2, 3, 4, 5, 6,
-1, -2, -3, -4, -5, -6 };
int[] neighbourbets = new int[offsets.Length];
for( int i = 0; i < offsets.Length; i++ )
neighbourbets[i] = GetPocketIndex( predictednum, offsets[i], pocket_array.Length );
Or, if any order will do:
int count = 6;
int[] neighbourbets = new int[count * 2 + 1];
for( int i = 0; i < neighbourbets.Length; i++ )
neightbourbets[i] = GetPocketIndex( predictednum, i - count, pocket_array.Length );
The following would give you the result with the x in the middle of the result array and the neighbours to the left and right of it:
public static int[] neighbourbets2(int x, int neighborCount)
{
int[] pocket_array = new[] { 0, 32, 15, 19, 4, 21, 2, 25, 17, 34, 6, 27, 13, 36, 11, 30, 8, 23, 10, 5, 24, 16, 33, 1, 20, 14, 31, 9, 22, 18, 29, 7, 28, 12, 35, 3, 26 };
int predictednum = Array.IndexOf(pocket_array, x);
// Initialize the result array. Its size is double the neighbour count + 1 for x
int[] result = new int[neighborCount * 2 + 1];
// Calc the start index. We begin at the most left item.
int startAt = predictednum - neighborCount;
// i - position in the result array
// j - position in the pocket_array
for (int i = 0, j = startAt; i < result.Length; i++, j++)
{
// Adjust j if it's less then 0 to wrap around the array.
result[i] = pocket_array[j < 0 ? j + pocket_array.Length : j];
// If we are at the end then start from the beginning.
if (j == pocket_array.Length)
{
j = 0;
}
}
return result;
}
I'm currently learning C# and running into some trouble with multi dimension array.
I can't seem to figure out how to find the sum of all the elements in the array. E.g
int[,] array = { { 52, 76, 65 }, { 98, 87, 93 }, { 43, 77, 62 }, { 72, 73, 74 } };
So the sum should be:
52 + 76 + 65 + 98 + ...
I have tried to use the for loop but that just give me the sum of each array in dimension 1. E.g
private int[,] array = { { 52, 76, 33}, { 98, 87, 93 }, { 43, 77, 62 }, { 72, 73, 74 } };
public void ArraySum()
{
double sum;
for (int i = 0; i < array.GetLength(0); i++)
{
sum = 0;
for (int j = 0; j < array.GetLength(1); j++)
sum += array[i, j];
Console.WriteLine("The sums are for the array {0} is {1}: ", i, sum);
}
}
Any ideas?
The other answer pointed out what's wrong with your code. Here's a short alternative to your loops using LINQ:
int[,] array = { { 52, 76, 65 }, { 98, 87, 93 }, { 43, 77, 62 }, { 72, 73, 74 } };
int sum = array.Cast<int>().Sum();
The Cast is used to convert the multidimensional array to an IEnumerable<int> which then allows you to use the Sum extension method.
Since you're just learning and playing around anyway, you could use a List<int<int>> to store your values instead of a 2-dimensional array, like this:
var array = new List<List<int>>
{
new List<int> {52, 76, 65},
new List<int> {98, 87, 93},
new List<int> {43, 77, 62},
new List<int> {72, 73, 74}
};
Then you could easily use LINQ to get your sum:
var sum = array.SelectMany(x => x).Sum();
If you haven't heard of it yet, you can learn more about LINQ here.
Basically, SelectMany() flattens your multiple lists into one list, and then Sum() just adds them all up.
Simply move the line sum = 0; out of the first loop:
private int[,] array = { { 52, 76, 33}, { 98, 87, 93 }, { 43, 77, 62 }, { 72, 73, 74 } };
public void ArraySum()
{
int sum = 0;
for (int i = 0; i < array.GetLength(0); i++)
{
for (int j = 0; j < array.GetLength(1); j++)
sum += array[i, j];
}
Console.WriteLine("The sum for the whole array is {0}: ", sum);
}
In your code the sum is reset to 0 for each sub-array.
Edit
Since the array contains int values, consider to declare the sum variable as int instead of double.
If all you want is the sum of the entire array, then
private static int[,] array = { { 52, 76, 33}, { 98, 87, 93 }, { 43, 77, 62 }, { 72, 73, 74 } };
public static void Main()
{
double sum = 0;
for (int i = 0; i < array.GetLength(0); i++)
{
for (int j = 0; j < array.GetLength(1); j++)
sum += array[i, j];
}
Console.WriteLine("The sum for the array is {0}: ", sum);
}
I have two 1D arrays :
double A = new double[7] {4, 2, 54, 16, 9, 55, 27}
and
double B = new double[7] {8, 88, 21, 12, 8, 30, 11}
how can i join those array become one 2D array C[2,6], that contain both 1D array above?
probably like this :
double C = new double[2,7] {{4, 2, 54, 16, 9, 55, 27} , {8, 88, 21, 12, 8, 30, 11}};
I tried this code but, only array A printed.
public static double[,] _matrix_byRow(double[] Mat1, double[] Mat2)
{
int i, j, y;
double[,] newMat = new double[2, 7];
for (i = 0; i < 2; i++)
{
for (j = 0; j < 7; j++)
{
newMat[i, j] = Mat1[j];
}
}
for (i = 0; i < 2; i++)
{
for (y = 0; y < 7; y++)
{
newMat[i, y] = Mat2[y];
}
}
return newMat;
}
Try this instead:
public static double[,] _matrix_byRow(double[] Mat1, double[] Mat2)
{
double[,] newMat = new double[2, 7];
for (var j = 0; j < 7; j++)
{
newMat[0, j] = Mat1[j];
newMat[1, j] = Mat2[j];
}
return newMat;
}