Insert elements into an array in sorted order - c#

What I would like to do is as I take input from user, insert that input into the array in a sorted order, eg. user inputs 22,3,9,10,33
output would be: 3,9,10,22,33.
The code I have below is working except for the fact that for the last element being added is at the wrong index. This was a test for school(which is why the array is 50 elements big and theres a whole class with getters and setters & lack of error checking) and I'm trying to see where I'm going wrong, I've tried both insertion and selection sort which both produce this result. From my understanding, it should be forty five consecutive zeros and then my elements in ascending order.
eg) This is the output I get(wether i use selection or insertion sort after calling my print method
Sorted Array: 0 0 0 0 33 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 3 9 10 22
public class test
{
private int [] arr;
private int maxSize;
private int numItems;
public test(int maxSize)
{
this.maxSize = maxSize;
numItems = 0;
arr = new int[maxSize];
}
public bool addItem(int key)
{
if (numItems < maxSize)
{
selectionSort(key);
arr[numItems] = key;
numItems++;
return true;
}
return false;
}
public bool insertionSort(int key)
{
int n = arr.Length - 1;
for (int i = 1; i < n; i++)
{
key = arr[i];
int j = i - 1;
while(j>=0 && arr[j] > key)
{
arr[j+1] = arr[j];
j --;
}
arr[j + 1] = key;
}
return true;
}
public bool selectionSort(int key)
{
int n = arr.Length - 1;
for (int i = 0; i < n; i++)
{
key = i;
for(int j = i + 1; j < n; j++)
{
if (arr[j] < arr[key])
{
key = j;
}
}
int temp = arr[key];
arr[key] = arr[i];
arr[i] = temp;
}
return true;
}
static void Main(string[] args)
{
test x = new test(50);
int count = 0;
int element;
while (count < 5)
{
Console.WriteLine("Enter an element to add into the array");
element = Convert.ToInt32(Console.ReadLine());
x.addItem(element);
count++;
}}

I found two issues with your code and these were minor.
Update addItem function to move selectionSort below the assignment operation.
public bool addItem(int key)
{
if (numItems < maxSize)
{
arr[numItems] = key;
selectionSort(key); // below the arr[numItems] assignment.
numItems++;
return true;
}
return false;
}
and in the selectionSort method, change two things.
a. for loop for j should go all the way to n and
b. break when k=j;
public bool selectionSort(int key)
{
int n = arr.Length - 1;
for (int i = 0; i < n; i++)
{
key = i;
for (int j = i + 1; j <= n; j++) // <= n instead of < n
{
if (arr[j] < arr[key])
{
key = j;
break; // break here once you have k = j.
}
}
int temp = arr[key];
arr[key] = arr[i];
arr[i] = temp;
}
return true;
}
This should take care of your issues.

i think you are looking for insertion sort here is an example.
static void Main(string[] args)
{
int[] numbers = new int[10] {22,1,34,20,12,10,5,33,11,5};
Console.WriteLine("\nOriginal Array Elements :");
Show(numbers);
Console.WriteLine("\nSorted Array Elements :");
Show(InsertionSort(numbers));
Console.ReadKey();
}
static int[] InsertionSort(int[] inputArray)
{
for (int i = 0; i < inputArray.Length - 1; i++)
{
for (int j = i + 1; j > 0; j--)
{
if (inputArray[j - 1] > inputArray[j])
{
int temp = inputArray[j - 1];
inputArray[j - 1] = inputArray[j];
inputArray[j] = temp;
}
}
}
return inputArray;
}
public static void Show(int[] array)
{
foreach (int i in array)
{
Console.Write(i.ToString() + " ");
}
}

Related

Custome Size 2D Array with Fitting For Loops

I am creating a 2D array that can have any custom size 1x1, 2x2, 3x3 .... nxn and depending on what the size of the array is, it gets filled with 0 to (n^2)-1, so if it is 2x2 it outputs:
3 2
1 0
It should be something like this int[,] arr = new int [n, n];, to create the 2d array, but how would the for loops be constructed?
what I have tried
using System;
namespace moveElement {
public class move {
static void Main(string[] args) {
int n = 3;
int[, ] arr = new int[n, n];
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
Console.Write(arr[i, j] + " ");
}
Console.WriteLine();
}
}
}
}
The result of the code:
0 0 0
0 0 0
0 0 0
int k = 0;
for(int i=0;i<n;i++)
{
for(int j=0;j<n;j++)
{
arr[i,j] = k++;
}
}
full code to the question:
using System;
namespace moveElement
{
public class move
{
static void Main(string[] args)
{
int n = 3;
int[,] arr = new int [n, n];
//Ivan Smyrnov solution
int k = (n * n) - 1;
for(int i=0;i<n;i++)
{
for(int j=0;j<n;j++)
{
arr[i,j] = k--;
}
}
//Ivan Smyrnov solution
for (int i = 0; i < n; i++)
{
for (int j = 0; j < n; j++)
{
Console.Write(arr[i, j] + " ");
}
Console.WriteLine();
}
}
}
}
Output when n is 3:
8 7 6
5 4 3
2 1 0

How to calculate distance between two values from two different 2d array

I have two bool[5,5] arrays which look like this:
1st:
1 1 1 1 1
0 1 0 0 0
0 0 1 1 0
0 0 0 0 0
0 1 0 1 0
2nd:
0 0 0 0 1
0 1 1 1 0
0 0 0 0 0
0 0 1 1 0
1 0 0 0 0
What I have to do is simple calculating distance between 1 from 1st array and 1 from the 2nd one. I had multiple tries to solve this problem, but I can't solve this.
The result should looks like this:
4+3+2+1+0
0+0+0+0+0
0+0+0+0+0
0+0+0+0+0
0+1+0+3+0
Let me name arrays: first[,] and second[,]
There are fiew conditions:
if (first[i,j] == true && second[i,j] == true) distance[i,j] = 0
if (first[i,j] == false) distance[i,j] = 0
if (first[i,j] == true) then I have to calculate distance between closest 1 from second[,] eg. There are 1 in first[1,4] and first[3,4] and there is 1 in second[0,4] (there was mistake), so it means that distance[3,4] = 3 - 0 (because of second array's dimensions).
This is main method to calculate:
` static public int findPicture()
{
int[,] m = new int[testBitmap.GetLength(0),
testBitmap.GetLength(1)];
foreach (var picture in pictures)
{
for (int i = 0; i < 5; i++)
{
for (int j = 0; j < 5; j++)
{
if (testBitmap[i,j] == true)
{
do
{
i = i + 1;
} while (picture.Value[i,j] != true);
m[i,j] += 1;
}
}
}
var total = 0;
for (int a = 0; a < 5; a++)
{
for (int b = 0; b < 5; b++)
{
total += m[a, b];
}
}
return total;
}
return -1;
}`
It was my closest version to solve.
I would be very greatful if you could give some advices to solve this trivial problem.
I'd do something like this:
static int[,] BuildDistanceArray(bool[,] array1, bool[,] array2)
{
if (array1.GetLength(0) != array2.GetLength(0) || array1.GetLength(1) != array2.GetLength(1))
throw new Exception("Array sizes must match.");
int[,] distance = new int[array1.GetLength(0), array1.GetLength(1)];
for (int i = 0; i < array1.GetLength(0); ++i)
{
for (int j = 0; j < array1.GetLength(1); ++j)
{
distance[i, j] = array1[i, j] ? GetDistance(array2, i, j) : 0;
}
}
return distance;
}
static int GetDistance(bool[,] array, int row, int column)
{
int maxColumn = array.GetLength(1);
int distance = 0;
bool again;
do
{
again = false;
if (column - distance >= 0)
{
if (array[row, column - distance])
return distance;
again = true;
}
if (column + distance < maxColumn)
{
if (array[row, column + distance])
return distance;
again = true;
}
distance++;
} while (again);
return 0;
}
It gives the results you're looking for and it works for any size array.
This function calculates distance between 2 rows converted to int32. It's written in java, so some minor transformation will be required.
int distance(int x, int y) {
int count = Integer.bitCount(x);
int totalDist = 0;
for (int offset = 0; offset < 5 && x != 0; offset++) {
x = x ^ (x & (y << offset) & 0b11111);
x = x ^ (x & (y >>> offset));
int nextCount = Integer.bitCount(x);
totalDist += (count - nextCount) * offset;
count = nextCount;
}
return totalDist;
}

C# updating values in two dimensional array

I'm converting an Eight Queens solution from Java to C# just to get my head around C# a bit more. The problem is that I'm stuck with changing values on the board. I can change the value inside the function but it goes back to what it was immediately even when I'm using ref. At the moment I'm using a global variable rather than passing the board as an argument.
Here is the code:
public static int[,] solution;
static void Main()
{
int n = 8;
solution = new int[8,8];
for (int i = 0; i < n; i++)
{
for (int j = 0; j < n; j++)
{
solution[i,j] = 0;
}
}
Solve(n);
Console.ReadKey();
}
public static void Solve(int n)
{
if (placeQueens(0, n))
{
for (int i = 0; i < n; i++)
{
for (int j = 0; j < n; j++)
{
Console.Write(" " + solution[i,j]);
}
Console.WriteLine();
}
}
else
{
Console.WriteLine("No possible solution");
}
}
public static bool placeQueens(int queen, int n)
{
if (queen == n)
{
return true;
}
for (int row = 0; row < n; row++)
{
if (canPlace(row, queen))
{
solution[row,queen] = 1;
for (int i = 0; i < n; i++)
{
for (int j = 0; j < n; j++)
{
Console.Write(" " + solution[i, j]);
}
Console.WriteLine();
}
//When I print the current board here the 1 is set
//When placeQueens is called again it is back to being 0
if (placeQueens(queen + 1, n))
{
return true;
}
solution[row,queen] = 0;
}
}
return false;
}
public static bool canPlace(int row, int col)
{ //Just checks that the position is legal}
What can I do to make the 1 stay as a one once I've changed it in placeQueen?
I changed the static variable to being passed in each method instead of being a static variable, and it works perfectly:
static void Main()
{
int n = 8;
var solution = new int[8, 8];
for (int i = 0; i < n; i++)
{
for (int j = 0; j < n; j++)
{
solution[i, j] = 0;
}
}
Solve(solution, n);
}
public static void Solve(int[,] solution, int n)
{
if (placeQueens(solution, 0, n))
{
Console.WriteLine();
for (int i = 0; i < n; i++)
{
for (int j = 0; j < n; j++)
{
Console.Write(" " + solution[i, j]);
}
Console.WriteLine();
}
}
else
{
Console.WriteLine("No possible solution");
}
}
public static bool placeQueens(int[,] solution, int queen, int n)
{
if (queen == n)
{
return true;
}
for (int row = 0; row < n; row++)
{
if (canPlace(solution, row, queen))
{
solution[row, queen] = 1;
Console.WriteLine();
for (int i = 0; i < n; i++)
{
for (int j = 0; j < n; j++)
{
Console.Write(" " + solution[i, j]);
}
Console.WriteLine();
}
if (placeQueens(solution, queen + 1, n))
{
return true;
}
solution[row, queen] = 0;
}
}
return false;
}
public static bool canPlace(int[,] solution, int row, int col)
{
for (var dx = -1; dx <= 1; dx++)
{
for (var dy = -1; dy <= 1; dy++)
{
if (dx == 0 && dy == 0)
continue;
int r = row, c = col;
while (r >= 0 && r <= solution.GetUpperBound(0) && c >= 0 && c <= solution.GetUpperBound(1))
{
if (solution[r, c] == 1)
return false;
r += dy;
c += dx;
}
}
}
return true;
}
The last line it outputs is a correct solution:
1 0 0 0 0 0 0 0
0 0 0 0 0 0 1 0
0 0 0 0 1 0 0 0
0 0 0 0 0 0 0 1
0 1 0 0 0 0 0 0
0 0 0 1 0 0 0 0
0 0 0 0 0 1 0 0
0 0 1 0 0 0 0 0

Count No Of 1's Colony From [1,0] 2D Array Using C#

I have a 2D array of integers which stores only values [1,0] as shown below.
int[,] INPUT = new int[10, 10] {
{1,1,0,0,0,1,1,1,0,0},
{1,0,0,0,1,0,0,0,1,0},
{0,0,0,1,1,0,0,1,0,1},
{1,1,0,0,0,0,0,1,1,0},
{0,1,0,0,0,1,0,1,1,0},
{0,0,0,0,1,0,1,0,0,0},
{1,0,0,1,0,0,1,1,1,0},
{0,1,0,0,1,1,0,0,1,1},
{0,1,1,1,0,1,0,1,1,0},
{0,0,0,0,0,1,1,0,0,0},
};
I need to identify a Colony count for the input image, where a Colony is defined as a contiguous sequence of 1s (Like in this array, there are 3 colony of 1's). Connection between 1s can be either adjacent or on the diagonal.
I am required to use recursion for this.
class Program
{
public static int count;
public static int colony;
public static int[,] INPUT;
public static int rows = 10;
public static int cols = 10;
static void Main(string[] args)
{
int[,] INPUT = new int[10, 10] {
{1,1,0,0,0,1,1,1,0,0},
{1,0,0,0,1,0,0,0,1,0},
{0,0,0,1,1,0,0,1,0,1},
{1,1,0,0,0,0,0,1,1,0},
{0,1,0,0,0,1,0,1,1,0},
{0,0,0,0,1,0,1,0,0,0},
{1,0,0,1,0,0,1,1,1,0},
{0,1,0,0,1,1,0,0,1,1},
{0,1,1,1,0,1,0,1,1,0},
{0,0,0,0,0,1,1,0,0,0},
};
// Showing All Values From Upper 2D array
Console.WriteLine("Input File Contain: \n");
for (int i = 0; i < rows; i++)
{
for (int j = 0; j < cols; j++)
{
Console.Write(INPUT[i, j]);
}
Console.WriteLine();
}
// Getting Total 1's Count Only
for (int i = 0; i < rows; i++)
{
for (int j = 0; j < cols; j++)
{
if (INPUT[i, j] == 1)
{
count = count + 1;
}
}
Console.WriteLine();
}
// Getting Total 1's Colony Only
for (int i = 0; i < rows; i++)
{
for (int j = 0; j < cols; j++)
{
if (INPUT[i, j] == 1)
{
INPUT[i, j] = 0;
colony = GetColony(i, j);
}
}
}
Console.WriteLine("Counts Of 1 Are: " + count);
Console.WriteLine("Counts Of 1's Colony Are: " + colony );
}
static public int GetColony(int i, int j)
{
if ((i < rows) && (j < cols))
{
if ((INPUT[i - 1, j] == 1) || (INPUT[i + 1, j] == 1) || (INPUT[i, j - 1] == 1) || (INPUT[i, j + 1] == 1))
{
INPUT[i, j] = 0;
return GetColony(i, j);
}
else
{
return 1;
}
}
else
{
return 1;
}
}
}

Shuffling a 2D array without using Collections

I don't know how to shuffle 2D array without duplicate elements. Can anyone help me to shuffle a 2D array?
Here is what I have so far:
public class Shuffle2DArray
{
public Shuffle2DArray ()
{
}
public static void Main(string[] args)
{
int[,] a = new int[3, 3] { { 1, 2, 3, }, { 6, 7, 8 }, { 11, 12, 13 } };
Shuffle2DArray shuffle = new Shuffle2DArray ();
shuffle.getshuffle2D (a);
}
void getshuffle2D(int[,] arr)
{
Random ran = new Random ();
for (int i = 0; i < arr.GetLength (0); i++) {
for (int j = 0; j < arr.GetLength (1); j++) {
int m = ran.Next(arr.GetLength (0)-1);
int n = ran.Next(arr.GetLength (1)-1);
int temp = arr[0,j];
arr[i,0] = arr[m,n+1];
arr[m,n] = temp;
Console.Write(arr[i,j]+ "\t");
}
Console.WriteLine();
}
}
}
Well, I would say shuffle the 2d array the same way as you shuffle the 1d array.
For instance, Fisher–Yates shuffle for 1d array is something like this
public static class Utils
{
public static void Swap<T>(ref T a, ref T b) { var temp = a; a = b; b = temp; }
public static void RandomShuffle<T>(this T[] target, Random random = null)
{
if (target.Length < 2) return;
if (random == null) random = new Random();
for (int i = target.Length - 1; i > 0; i--)
{
int j = random.Next(i + 1);
if (i != j) Swap(ref target[i], ref target[j]);
}
}
}
All you need is to realize that having a 2d array
T[,] array
and accessing the element of the array
array[row, column]
that
row = index / columnCount
column = index % columnCount
where
index = [0, array.Lenght - 1] corresponds to the index in 1d array
columnCount = array.GetLength(1)
adding the 2d version function to the class above is trivial
public static class Utils
{
// ...
public static void RandomShuffle<T>(this T[,] target, Random random = null)
{
if (target.Length < 2) return;
if (random == null) random = new Random();
int columnCount = target.GetLength(1);
for (int i = target.Length - 1; i > 0; i--)
{
int j = random.Next(i + 1);
if (i != j) Swap(ref target[i / columnCount, i % columnCount], ref target[j / columnCount, j % columnCount]);
}
}
}
Sample usage:
int[,] a = new int[3, 3] { { 1, 2, 3, }, { 6, 7, 8 }, { 11, 12, 13 } };
a.RandomShuffle();
You need to first order your array by random sequence of numbers. What you are doing now is just changing two random items of 2d array at each iterate thus it may result in duplicate items.
Look at this Sort algorithm for 1d array.
for (int i = 0; i < arr.Length - 1; i++)
{
for (int j = i + 1; j < arr.Length; j++)
{
if (arr[i] > arr[j]) // ran.Next(-1,1) == 0 // or any random condition
{
int temp = arr[i];
arr[j] = arr[i];
arr[i] = temp;
}
}
}
As you can see we need 2 loops to sort 1d array. So in order to sort 2d array we need 4 loops.
for (int i = 0; i < arr.GetLength(0); i++)
{
for (int j = 0; j < arr.GetLength(0); j++)
{
for (int k = 0; k < arr.GetLength(1); k++)
{
for (int l = 0; l < arr.GetLength(1); l++)
{
if (arr[i, k] > arr[j, l]) // ran.Next(-1,1) == 0
{
int temp = arr[i, k];
arr[i, k] = arr[j, l];
arr[j, l] = temp;
}
}
}
}
}
Then write another algorithm to print items.
for (int i = 0; i < arr.GetLength(0); i++)
{
for (int j = 0; j < arr.GetLength(1); j++)
{
Console.Write(arr[i, j] + "\t");
}
Console.WriteLine();
}
This was Sort algorithm. Now if you just change this condition with random one you sort your array by random.
Change if (arr[i, k] > arr[j, l])
To if (ran.Next(-1,1) == 0). this is just randomly true or false.

Categories