2d array challenge access elements - c#

Attempting the hackerRank Q from https://www.hackerrank.com/challenges/2d-array
static void Main(String[] args)
{
int[][] arr = new int[6][];
for (int arr_i = 0; arr_i < 6; arr_i++)
{
string[] arr_temp = Console.ReadLine().Split(' ');
arr[arr_i] = Array.ConvertAll(arr_temp, Int32.Parse);
}
int[] sum = new int[6];
List<int> n = new List<int>();
for (int i = 0; i + 2 < arr.Length; i++)
{
for (int j = 0; j + 2 < arr.GetLength(0); j++)
{
sum[j] = arr[i][j] + arr[i][j + 1] + arr[i][j + 2] +
arr[i + 1][j + 1] +
arr[i + 2][j] + arr[i + 2][j + 1] + arr[i + 2][j + 2];
n.Add(sum[j]);
}
}
Console.WriteLine(n.Max());
}
}
}
If I run this program and enter the following as contents of 'arr'
111111
222222
333333
444444
555555
666666
Here I am trying to add 1 + 1 + 1
+ 2 +
3 + 3 + 3
using sum[j] = arr[i][j] + arr[i][j + 1] + arr[i][j + 2] +
arr[i + 1][j + 1] +
arr[i + 2][j] + arr[i + 2][j + 1] + arr[i + 2][j + 2];
but arr[i][j] returns 111111
how can I access 1? is this the right answer to the question on hackerrank?

Hope below code helps you
public class Solution {
private static final int _MAX = 6; // size of matrix
private static final int _OFFSET = 2; // hourglass width
private static int matrix[][] = new int[_MAX][_MAX];
private static int maxHourglass = -63; // initialize to lowest possible sum (-9 x 7)
/** Given a starting index for an hourglass, sets maxHourglass
* #param i row
* #param j column
**/
private static void hourglass(int i, int j){
int tmp = 0; // current hourglass sum
// sum top 3 and bottom 3 elements
for(int k = j; k <= j + _OFFSET; k++){
tmp += matrix[i][k];
tmp += matrix[i + _OFFSET][k];
}
// sum middle element
tmp += matrix[i + 1][j + 1];
if(maxHourglass < tmp){
maxHourglass = tmp;
}
}
public static void main(String[] args) {
// read inputs
Scanner scan = new Scanner(System.in);
for(int i=0; i < _MAX; i++){
for(int j=0; j < _MAX; j++){
matrix[i][j] = scan.nextInt();
}
}
scan.close();
// find maximum hourglass
for(int i=0; i < _MAX - _OFFSET; i++){
for(int j=0; j < _MAX - _OFFSET; j++){
hourglass(i, j);
}
}
// print maximum hourglass
System.out.println(maxHourglass);
}
}

Related

The sum for every column and raw in a 2D array with N columns

I have a 2D Array in C# with user input to fill the Array. I need help to find the sum for every column and row.
var input = Console.ReadLine();
var n = int.Parse(input);
int[,] intArr = new int[n, 3];
for (int i = 0; i < n; i++)
{
input = Console.ReadLine();
var parts = input.Split(' ');
for (int j = 0; j < 3; j++)
{
intArr[i, j] = int.Parse(parts[j]);
}
}
if (n == 1)
{
Console.WriteLine("Sum of column " + Convert.ToString(n) + ": " + (intArr[n - 1, 0] + intArr[n - 1, 1] + intArr[n - 1, 2]));
Console.WriteLine("Row1: " + (intArr[n - 1, 0]));
Console.WriteLine("Row2: " + (intArr[n - 1, 1]));
Console.WriteLine("Row3: " + (intArr[n - 1, 2]));
}
if (n == 2)
{
Console.WriteLine("Sum of column " + Convert.ToString(n - 1) + ": " + (intArr[n - 2, 0] + intArr[n - 2, 1] + intArr[n - 2, 2]));
Console.WriteLine("Sum of column " + Convert.ToString(n) + ": " + (intArr[n - 1, 0] + intArr[n - 1, 1] + intArr[n - 1, 2]));
Console.WriteLine("Row 1: " + (intArr[n - 2, 0] + intArr[n - 1, 0]));
Console.WriteLine("Row 2: " + (intArr[n - 2, 1] + intArr[n - 1, 1]));
Console.WriteLine("Row 3: " + (intArr[n - 1, 2] + intArr[n - 1, 1]));
}
}
User input:
2
1 2 3
4 5 6
The output:
Sum of column 1: 6
Sum of column 2: 15
Row 1: 5
Row 2: 7
Row 3: 11
I want this output for N columns enter by user, but I am stuck!
Thank you!
Not sure, is your problem that you get an undesired result or that you have a model with a fixed number of elements? An array is a fixed size data container, so if you want any number of columns the architecture perhaps is where you want to change away from array.
Anyway, problem 1 is that you let user chose how many rows they want, but now how many column, so presuming there will be 3 conflicts with you data. So you have on array the .getUpperBound() for that which takes a range parameter and this way we can use a dynamic strucure
//From:
for (int i = 0; i < n; i++)
{
input = Console.ReadLine();
var parts = input.Split(' ');
for (int j = 0; j < 3; j++)
{
intArr[i, j] = int.Parse(parts[j]);
}
}
//TO:
var rows = new List<int[]>();
for (int i = 0; i < n; i++)
{
input = Console.ReadLine();
var parts = input.Split(' ');
var listOf = new List<int>();
for (int j = 0; j < parts.GetUpperBound(0); j++)
{
listOf.Add(int.Parse(parts[j]));
}
rows.Add(listOf.ToArray());
}
from https://learn.microsoft.com/en-us/dotnet/api/system.linq.enumerable.aggregate?view=net-5.0 You get the aggregation capability
[Fact]
public void SumExerciseTest()
{
/*
The output:
Sum of column 1: 6
Sum of column 2: 15
Row 1: 5
Row 2: 7
Row 3: 11 => 9
*/
var testData = new[] { "1 2 3", "4 5 6" };
var input = "2"; // Console.ReadLine();
var n = int.Parse(input);
var rows = new List<int[]>(n);
for (int i = 0; i < n; i++)
{
input = testData[i];
var parts = input.Split(' ');
var listOf = new List<int>();
for (int j = 0; j <= parts.GetUpperBound(0); j++)
{
listOf.Add(int.Parse(parts[j]));
}
rows.Add(listOf.ToArray());
}
var rowSums = new List<int>(n);
foreach (int[] row in rows)
{
rowSums.Add(row.Aggregate((result, item) => result + item));
}
int maxLength = 0;
var rowLengths = new List<int>(n);
foreach (int[] row in rows)
{
rowLengths.Add(row.Length);
}
maxLength = rowLengths.Max();
int[] columnSums = new int[maxLength];
for (int idx = 0; idx < columnSums.Length; idx++){
foreach (var row in rows)
{
if (row.GetUpperBound(0) >= idx)
{
columnSums[idx] += row[idx];
}
}
}
int counter = 0;
//Outputting:
foreach(var sum in rowSums)
{
counter += 1;
System.Diagnostics.Debug.WriteLine($"Row {counter}: {sum}");
}
counter = 0;
foreach(var sum in columnSums)
{
counter += 1;
System.Diagnostics.Debug.WriteLine($"Column {counter}: {sum}");
}
Well, let's implement (extract) methods for summing arbitrary column and row:
private static int SumColumn(int[,] array, int column) {
if (array == null)
throw new ArgumentNullException(nameof(array));
if (column < 0 || column >= array.GetLength(1))
throw new ArgumentOutOfRangeException(nameof(column));
int result = 0;
for (int r = 0; r < array.GetLength(0); ++r)
result += array[r, column];
return result;
}
private static int SumRow(int[,] array, int row) {
if (array == null)
throw new ArgumentNullException(nameof(array));
if (row < 0 || row >= array.GetLength(0))
throw new ArgumentOutOfRangeException(nameof(row));
int result = 0;
for (int c = 0; c < array.GetLength(1); ++c)
result += array[row, c];
return result;
}
then you can put
for (int c = 0; c < intArr.GetLength(1); ++c)
Console.WriteLine($" Sum of column {c + 1}: {SumColumn(intArr, c)}");
for (int r = 0; r < intArr.GetLength(0); ++r)
Console.WriteLine($" Sum of row {r + 1}: {SumRow(intArr, r)}");

Filling a Matrix in windows form from user input

So the problem is that I should be able to first write a value and then it should be passed but, its executing all the code at once and not giving me time to write the value i want to give it
public void FillMatrix(string [,] v) {
for (int i = 2; i <= 4; i+=2) {
for (int j = 2; j <= 4; j++) {
lblFute.Text = "Write the number you want to put on index " + i + " " + j;
v[i, j] = txtVlera.Text;
if (j == 3 ) {
lblFute.Text = "Write the number you want to put on index " + j + " " + i;
v[j, i] = txtVlera.Text;
}
}
}
}

How do I implement a step counter into a bubble sort?

I am trying to implement a step counter into my bubble sort algorithm, but I don't know how to display the counter at the end of the sorting algorithm. If anyone could explain how I should go about this that would be great. Thank You.
My current code: (Bubble Sort):
static int[] bubbleSort(int[] arr, int n)
{
int stepCount = 0; // <- Counter to return and display
for (int i = 0; i < n - 1; i++)
{
for (int j = 0; j < n - 1 - i; j++)
{
if (arr[j + 1] < arr[j])
{
int temp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = temp;
}
stepCount++;
}
}
return arr;
}
public static void DisplayArrayBubble(int[] arr)
{
foreach (int i in arr)
{
Console.Write(i.ToString() + " ");
}
}
Why not just return int - number of steps? I.e.
// arr : will be sorted
// return : number of steps
static int bubbleSort(int[] arr) {
if (null == arr)
return 0;
int stepCount = 0;
for (int i = 0; i < arr.Length - 1; i++)
for (int j = 0; j < arr.Length - 1 - i; j++)
if (arr[j + 1] < arr[j]) {
int temp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = temp;
stepCount += 1;
}
return stepCount;
}
Demo:
int[] sample = new int[] {1, 5, 4, 3, 2, 7};
int steps = bubbleSort(sample);
Console.WriteLine($"Sorted [{string.Join(", ", sample)}] in {steps} steps");
Outcome:
Sorted [1, 2, 3, 4, 5, 7] in 6 steps
There a plethora of ways but one is to make a custom class to hold both pieces of information that you need:
public class BubbleObject
{
public int[] arr { get; set; }
public int stepCount { get; set; }
}
Then adjust the code you have to use that object:
static BubbleObject bubbleSort(int[] arr, int n)
{
int stepCount = 0;
for (int i = 0; i < n - 1; i++)
{
for (int j = 0; j < n - 1 - i; j++)
{
if (arr[j + 1] < arr[j])
{
int temp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = temp;
}
stepCount++;
}
}
BubbleObject bo = new BubbleObject() { arr=arr, stepCount=stepCount}
return bo;
}
public static void DisplayArrayBubble(BubbleObject bo)
{
Console.WriteLine("Number of Steps = " + bo.stepCount);
foreach (int i in bo.arr)
{
Console.Write(i.ToString() + " ");
}
}
That should do it. There are other ways as well.

Unexpected Diamond square Algorithm results

I'm currently trying to implement the Diamond Square algorithm and while the thing is somewhat working, I'm confused by the HeightMap.
Here it is :
As you can see the squares are clearly outlined by brighters values, while the losanges are outlined by darker values.
I really cant understand why. I know that the size of the map is really small but I don't think that's the expected result anyway, and I got the same behavior with larger sizes.
Here's my code :
public class TerrainBuilder
{
private Terrain Terrain = null;
private Random r = new Random();
private int espace;
public void Init(Terrain _terrain)
{
Terrain = _terrain;
espace = Terrain.SIZE - 1;
}
public void DiamondAlgoritm()
{
if (Terrain == null)
return;
//Initialization
Terrain.HeightMap[0, 0] = r.Next() % 255;
Terrain.HeightMap[0, Terrain.SIZE - 1] = r.Next() % 255;
Terrain.HeightMap[Terrain.SIZE - 1, 0] = r.Next() % 255;
Terrain.HeightMap[Terrain.SIZE - 1, Terrain.SIZE - 1] = r.Next() % 255;
//randominess
int decalage = 128;
while (espace > 1)
{
int demiSpace = espace / 2;
//diamond phase
for (int i = demiSpace; i < espace; i = i + espace)
{
for (int j = demiSpace; j < espace; j = j + espace)
{
var avg = Terrain.HeightMap[i + demiSpace, j + demiSpace] + Terrain.HeightMap[i + demiSpace, j - demiSpace] + Terrain.HeightMap[i - demiSpace, j + demiSpace] + Terrain.HeightMap[i - demiSpace, j - demiSpace];
avg /= 4;
Terrain.HeightMap[i, j] = Normalize(avg + r.Next() % decalage);
}
}
//carre phase
for (int i = 0; i < Terrain.SIZE; i += demiSpace)
{
int delay = 0;
if (i % espace == 0)
delay = demiSpace;
for (int j = delay; j < Terrain.SIZE; j += espace)
{
double somme = 0;
int n = 0;
if (i >= demiSpace)
somme = somme + Terrain.HeightMap[i - demiSpace, j];
n = n + 1;
if (i + demiSpace < Terrain.SIZE)
somme = somme + Terrain.HeightMap[i + demiSpace, j];
n = n + 1;
if (j >= demiSpace)
somme = somme + Terrain.HeightMap[i, j - demiSpace];
n = n + 1;
if (j + demiSpace < Terrain.SIZE)
somme = somme + Terrain.HeightMap[i, j + demiSpace];
n = n + 1;
Terrain.HeightMap[i, j] = Normalize(somme / n + r.Next() % decalage);
}
}
espace = demiSpace;
}
}
private double Normalize(double value)
{
return Math.Max(Math.Min(value, 255), 0);
}
}
I would like some help to understand this problem.
During the diamond phase, you don't iterate over the whole map. You only calculate the first square (equal to espace).
Change your loop termination conditions like this:
for (int i = demiSpace; i < Terrain.SIZE; i = i + espace)
{
for (int j = demiSpace; j < Terrain.SIZE; j = j + espace)
{
var avg = Terrain.HeightMap[i + demiSpace, j + demiSpace] +
Terrain.HeightMap[i + demiSpace, j - demiSpace] +
Terrain.HeightMap[i - demiSpace, j + demiSpace] +
Terrain.HeightMap[i - demiSpace, j - demiSpace];
avg /= 4;
Terrain.HeightMap[i, j] = Normalize(avg + r.Next() % decalage);
}
}
Also, you never adjust your randomness variable (decalage), which should get smaller as you reduce the size of espace.

Need help to create a c# bubblesort. Whats wrong with what i have so far?

I am trying to use a bubble sort, to order numbers from least to greatest in c#, whats wrong with what i have so far?
private void Order_Click(object sender, EventArgs e) {
value1 = Convert.ToInt32(textBox1.Text);
value2 = Convert.ToInt32(textBox2.Text);
value3 = Convert.ToInt32(textBox3.Text);
value4 = Convert.ToInt32(textBox4.Text);
value5 = Convert.ToInt32(textBox5.Text);
int[] myarray = { value1, value2, value3, value4, value5 };
int n = 0;
bool swapped = true;
int j = 0;
int tmp;
while (swapped) {
swapped = false;
j++;
for (int i = 0; i < n - j; i++)
{
if (myarray[i] > myarray[i + 1]) {
tmp = myarray[i];
myarray[i] = myarray[i + 1];
myarray[i + 1] = tmp;
swapped = true;
order1.Text = Convert.ToString(myarray[0] + "," +
myarray[1] + "," +
myarray[2] + "," +
myarray[3] + "," +
myarray[4]);
}
}
}
}
First thing which is wrong with your code is:
for (int i = 0; i < n - j; i++)
Your check i < n - j will never let the control to fall through the loop. Because you have initialized n to 0 and j is 1 (after j++), so i is not going to be less then -1, Thus your loop will not work as intended. Since you set the swapped to false, the control will fall out of the while loop, hence no sorting.
You need to change your code to:
while (swapped)
{
swapped = false;
for (int i = 0; i < myarray.Length - 1; i++)
{
if (myarray[i] > myarray[i + 1])
{
int t = myarray[i];
myarray[i] = myarray[i + 1];
myarray[i + 1] = t;
swapped = true;
Console.WriteLine(Convert.ToString(myarray[0] + "," + myarray[1] + "," + myarray[2] + "," + myarray[3] + "," + myarray[4]));
}
}
}
the n and j variables seem unnessesary. leave n and j out of your program, and in your for loop, do this:
for (int i = 0; i < (array1.Length - 1); i++)
Bubble Sort
using System;
class AscendingBubbleSort
{
public static void Main()
{
int i = 0,j = 0,t = 0;
int []c=new int[20];
for(i=0;i<20;i++)
{
Console.WriteLine("Enter Value p[{0}]:", i);
c[i]=int.Parse(Console.ReadLine());
}
// Sorting: Bubble Sort
for(i=0;i<20;i++)
{
for(j=i+1;j<20;j++)
{
if(c[i]>c[j])
{
Console.WriteLine("c[{0}]={1}, c[{2}]={3}", i, c[i], j, c[j]);
t=c[i];
c[i]=c[j];
c[j]=t;
}
}
}
Console.WriteLine("Here comes the sorted array:");
// Print the contents of the sorted array
for(i=0;i<20;i++)
{
Console.WriteLine ("c[{0}]={1}", i, c[i]);
}
}
}
source

Categories

Resources