c# How to determine possible horsesteps in a(2dim array)? - c#

//Make a method: void MogelijkePaardenSprongen(int[,] schaakbord, Positie positie) This method determines the possible positions where the Horse can jump (value 2). Of course, you do this in a smart way ( with a LOOP). Please note, there are not always 8 possibilities! The parameter position indicates where the horse is located. Test the methods (call from the Start method like the image below?
// this is the code that i have got for so far,
static void Main(string[] args)
{
Program myProgram = new Program();
myProgram.Start();
Console.ReadKey();
}
void Start()
{
int [,] schaakbord = new int [8, 8];
InitSchaakbord(schaakbord);
ToonSchaakBord(schaakbord);
}
void InitSchaakbord(int[,] schaakbord)
{
int leeg = 0;
int bezet = 1;
int mogelijkbezet = 2;
for (int i=0; i<schaakbord.GetLength(0); i++)
{
for (int j=0; j<schaakbord.GetLength(1); j++)
{
schaakbord[i, j] = leeg;
}
}
}
void ToonSchaakBord(int[,] schaakbord)
{Positie positie = new Positie();
for (int i = 0; i < schaakbord.GetLength(0); i++)
{Plaatspaard(schaakbord);
for (int j = 0; j < schaakbord.GetLength(1); j++)
{
if (schaakbord[i, j] == 0)
{
Console.Write(".");
}
else if (schaakbord[i, j] == 1)
{
Console.ForegroundColor = ConsoleColor.Red;
Console.Write("*");
Console.ResetColor();
}
else if (schaakbord[i, j]==2)
{
Console.ForegroundColor = ConsoleColor.Yellow;
Console.Write("*");
Console.ResetColor();
}
Console.Write(" ");
}
Console.WriteLine();
MogelijkePaardenSprongen(schaakbord, positie);
}
}
Positie Plaatspaard(int [,] schaakbord)
{Positie x = new Positie();
Random rnd = new Random();
x.waarde1 = rnd.Next(1, 8);
x.waarde2 = rnd.Next(1, 8);
for (int i = 0; i<schaakbord.GetLength(0);i++ )
{
for (int j=0; j<schaakbord.GetLength(1); j++)
{
if (x.waarde1 == i && x.waarde2 == j)
schaakbord[i, j] = 1;
}
}
return x;
}
class Positie
{
public int waarde1;
public int waarde2;
}
void MogelijkePaardenSprongen(int[,] schaakbord, Positie positie)
{
for (int i =0; i<schaakbord.GetLength(0); i++)
{
for (int j=0; j<schaakbord.GetLength(1); j++)
{
/// possible horsesteps?
/// call from void start method
if (schaakbord[i, j] == 0)
{
}
}
}

Because its assignment I don't want to give you straight whole solution. Please don't hesitate to comment if you need more help.
My suggestion is to create object
class MoveOffset
{
public int OffsetX { get; set; }
public int OffsetY { get; set; }
}
then create collection of them with possible moves
var moves = new List<MoveOffset>()
{
new MoveOffset(){OffsetX = -1, OffsetY = -2},
new MoveOffset(){OffsetX = -2, OffsetY = -1},
new MoveOffset(){OffsetX = 1, OffsetY = -2},
new MoveOffset(){OffsetX = -2, OffsetY = 1},
new MoveOffset(){OffsetX = -1, OffsetY = 2},
new MoveOffset(){OffsetX = 2, OffsetY = -1},
new MoveOffset(){OffsetX = 1, OffsetY = 2},
new MoveOffset(){OffsetX = 2, OffsetY = 1},
};
then cycle through collection and check conditions if its possible to move there from 'horse' location .

Please note that horsestep actually means that the sum of the distances
between that point and the horse should exactly be 3.
Example:
var distanceX = abs(Horse.Position.X - i);
var distanceY = abs(Horse.Position.Y - j);
bool isHorseStep = distanceX + distanceY == 3;
So you can use that assumption in your code to check if it's a horse step or not.
Here is some quickly-written code for your method.
I have not tested it but I guess you'll get the point and do adjustments if needed:
void MogelijkePaardenSprongen(int[,] schaakbord, Positie positie)
{
for (int i =0; i<schaakbord.GetLength(0); i++)
{
for (int j=0; j<schaakbord.GetLength(1); j++)
{
/// possible horsesteps?
/// call from void start method
if (schaakbord[i, j] == 0)
{
var deltaX = waarde1 - i;
var deltaY = waarde2 - j;
if (deltaX < -2 || deltaX > 2
|| deltaY < -2 || deltaY > 2 )
{
// TODO: Write logic here for out of bounds.
}
else
{
if (abs(deltaX) + abs(deltaY) == 3)
{
// TODO: Horse Step. Write your logic here.
}
}
}
}
}
}
P.S. Also for deltaY you might need to reverse the number and use something like this deltaY = j - waarde2, as the Y axis is opposite in the array.

Related

Efficient way to Flip a 2D Array Horizontally or Vertically

The problem is to make a program the flips a 2D (2 by 2) array either horizontally(H) or vertically(V), depending on the input the user puts. For example, if the user puts "HHHVVHVHV", it means to flip 5 times horizontally, and 4 times vertically. The code I attached below works, but I am not sure if there is a built-in method in C# to flip arrays or an easier way to do it.
using System;
using System.Linq;
namespace _2019JuniorQ4
{
class Program
{
static void Main(string[] args)
{
//Varables
int[,] grid = new int[2, 2] { { 1, 2 }, { 3, 4 } };
int[,] flippedGrid = new int[2, 2];
string input = "";
int h = 0;
int v = 0;
int flipHorizontal = 0;
int flipVertical = 0;
//Input
input = Console.ReadLine();
//Count number of times
for (int i=0; i<input.Length; i++)
{
if (input[i] == Convert.ToChar("H"))
{
h++;
}
else if(input[i] == Convert.ToChar("V"))
{
v++;
}
}
//Process
flipHorizontal = h % 2;
flipVertical = v % 2;
//Vertical flip
if (flipVertical == 1)
{
for (int y = 0; y < 2; y++)
{
for (int x = 1; x >= 0; x--)
{
flippedGrid[y, Math.Abs(x - 1)] = grid[y,x];
}
}
grid = flippedGrid.Clone() as int[,];
}
//Horizontal Flip
if (flipHorizontal == 1)
{
for (int x = 0; x < 2; x++)
{
for (int y = 1; y >= 0; y--)
{
flippedGrid[Math.Abs(y - 1), x] = grid[y,x];
}
}
grid = flippedGrid.Clone() as int[,];
}
//Output
for (int x=0; x<2; x++)
{
for (int y=0; y<2; y++)
{
Console.Write(grid[x,y]+" ");
}
Console.WriteLine();
}
}
}
}

Digit difference sort

So I am trying to solve this task "Digit Difference Sort" on Codefights
Given an array of integers, sort its elements by the difference of their largest and smallest digits.
In the case of a tie, that with the larger index in the array should come first.
Example
For a = [152, 23, 7, 887, 243], the output should be digitDifferenceSort(a) = [7, 887, 23, 243, 152].
Here are the differences of all the numbers:
152: difference = 5 - 1 = 4;
23: difference = 3 - 2 = 1;
7: difference = 7 - 7 = 0;
887: difference = 8 - 7 = 1;
243: difference = 4 - 2 = 2.
23 and 887 have the same difference, but 887 goes after 23 in a, so in the sorted array it comes first.
I have an issue with two numbers having the same difference. Here's what I wrote so far:
int[] digitDifferenceSort(int[] a) {
return a.OrderBy(x => difference(x)).ToArray();
}
int difference(int x)
{
int min = 9, max = 0;
do
{
int tmp = x % 10;
min = Math.Min(min, tmp);
max = Math.Max(max, tmp);
} while ((x /= 10) > 0);
return max - min;
}
Didn't do much (for example the output is still [7, 23, 887, 243, 152] rather than [7, 887, 23, 243, 152])
How do I make element with larger index come first in result? What should I use instead of OrderBy?
I don't consider your difference method, i assume it works fine.
To your question: you have to keep revered order of the array (that the items with the same difference arrive will be sorted reverse). To do it, you could just reverse you input array: all items with not identical difference will be ordered correctly, and with the same differece will be ordered reversed:
int[] digitDifferenceSort(int[] a)
{
return a.Reverse().OrderBy(x => difference(x)).ToArray();
}
Following is my code for the above question digit difference sort. I am also getting output when running in Eclipse but when I paste the code on code signal it gives me a null pointer exception.
package NormalPrograms;
import java.util.ArrayList;
import java.util.Collections;
public class DigitDifferenceSort {
// For index wise sorting in descending order
public static int[] sortingnumberindexwise(int[] a, ArrayList<Integer> index) {
int k = 0;
int[] res = new int[index.size()];
int[] finalres = new int[index.size()];
for (int i = a.length - 1; i >= 0; i--) {
for (int j = 0; j < index.size(); j++) {
if (a[i] == (int) index.get(j)) {
res[k] = i;
index.remove(j);
k++;
break;
}
}
}
int g = 0;
k = 0;
for (int i = 0; i < res.length; i++) {
finalres[g] = a[res[k]];
g++;
k++;
}
return finalres;
}
public static int[] finddigitDifferenceandSort(int[] p) {
int[] finres = new int[p.length];
for (int i = 0; i < finres.length; i++) {
finres[i] = p[i];
}
// This finres array act as an temp array and reused to make final result array
int digit = 0;
ArrayList<Integer> A = new ArrayList<Integer>();
ArrayList<ArrayList<Integer>> B = new ArrayList<ArrayList<Integer>>();
for (int i = 0; i < 10; i++) {
B.add(new ArrayList<Integer>());
}
for (int i = 0; i < p.length; i++) {
int temp = 0;
temp = p[i];
while (p[i] > 0) {
digit = p[i] % 10;
p[i] /= 10;
A.add(digit);
}
int b = Collections.max(A);
int c = Collections.min(A);
int diff = b - c;
B.get(diff).add(temp);
A.clear();
}
for (int i = 0; i < B.size(); i++) {
if (B.get(i).size() > 1) {
ArrayList<Integer> C = new ArrayList<Integer>();
for (int k = 0; k < B.get(i).size(); k++) {
C.add(B.get(i).get(k));
}
B.get(i).clear();
for (int j : sortingnumberindexwise(finres, C)) {
B.get(i).add(j);
}
} else {
continue;
}
}
int k = 0;
for (int i = 0; i < B.size(); i++) {
for (int j = 0; j < B.get(i).size(); j++) {
if (B.get(i).size() == 0)
continue;
else {
finres[k] = B.get(i).get(j);
k++;
}
}
}
return finres;
}
public static void main(String[] args) {
int[] a = { 12, 21, 1, 1, 1, 2, 2, 3 };
for (int i : finddigitDifferenceandSort(a)) {
System.out.print(i + " ");
}
}
}

How do I remove elements from a list that is in a dictionary, by the dictionary's keys

This one is kinda long so i put the question on the bottom if you don't think you need context to answer.
I need to calculate which (chess)knights on a board full of only knight attacks other knights and remove the least possible amount of knights so that no one attacks each other.
Input:
5
OKOKO
KOOOK
OOKOO
KOOOK
OKOKO
The first number is the size of the board (rows and cols),'O'-empty spaces,'K'-knights.
So my idea to do this with just one cycle through the matrix(I want it to be as fast as possible) is to save the knights position and the positions of all the knight that he steps on in a list,in a dictionary like this (the string will be the indexes separated by space):
Dictionary<string, List<string>> knightsAttacks = new Dictionary<string, List<string>>();
This way i can just count the number of elements in the list and then remove the one with the most indexes in his list, after that i remove, this knights indexes from all the other knights list and if all the lists of all the knights are empty that means that no knights interfere with one another.In this example given above the dictionary will look something like this:
The selected knight is the one with the biggest count(most hits) so I need to remove him and his index ("2 2") from the other knights lists.
All good and well on theory but i cant execute the removing from the lists part.
This is the code i manged to write so far:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Practice
{
class Program
{
static void Main(string[] args)
{
int n = int.Parse(Console.ReadLine());
char[,] board = new char[n, n];
Dictionary<string, List<string>> knightsAttacks = new Dictionary<string, List<string>>();
for (int i = 0; i < n; i++)
{
char[] line = Console.ReadLine().ToCharArray();
for (int j = 0; j < n; j++)
{
board[i, j] = line[j];
}
}
for (int i = 0; i < n; i++)
{
for (int j = 0; j < n; j++)
{
List<string> list = new List<string>();
bool checker = false;
int x1 = i + 1, y1 = j + 2;
int x2 = i + 1, y2 = j - 2;
int x3 = i - 1, y3 = j + 2;
int x4 = i - 1, y4 = j - 2;
int x5 = i - 2, y5 = j + 1;
int x6 = i - 2, y6 = j - 1;
int x7 = i + 2, y7 = j + 1;
int x8 = i + 2, y8 = j - 1;
if (board[i, j] == 'K')
{
try
{
if (board[i, j] == board[x1, y1])
{
list.Add($"{x1} {y1}");
checker = true;
}
}
catch (Exception e)
{
}
try
{
if (board[i, j] == board[x2, y2])
{
list.Add($"{x2} {y2}");
checker = true;
}
}
catch (Exception e)
{
}
try
{
if (board[i, j] == board[x3, y3])
{
list.Add($"{x3} {y3}");
checker = true;
}
}
catch (Exception e)
{
}
try
{
if (board[i, j] == board[x4, y4])
{
list.Add($"{x4} {y4}");
checker = true;
}
}
catch (Exception e)
{
}
try
{
if (board[i, j] == board[x5, y5])
{
list.Add($"{x5} {y5}");
checker = true;
}
}
catch (Exception e)
{
}
try
{
if (board[i, j] == board[x6, y6])
{
list.Add($"{x6} {y6}");
checker = true;
}
}
catch (Exception e)
{
}
try
{
if (board[i, j] == board[x7, y7])
{
list.Add($"{x7} {y7}");
checker = true;
}
}
catch (Exception e)
{
}
try
{
if (board[i, j] == board[x8, y8])
{
list.Add($"{x8} {y8}");
checker = true;
}
}
catch (Exception e)
{
}
}
if (checker)
{
knightsAttacks[$"{i} {j}"] = list;
}
}
}
var theMostHits
= knightsAttacks.Values.Max( x=> x.Count);
Console.WriteLine();
Console.WriteLine();
}
}
}
My question:
After finding the key with the biggest count of elements in its list how do i remove the key's name (in this case "2 2") from the other lists in the dic?

how to make use of subclass in c#

So Im making tetris and I need to make 7 blocks. The problem is is that I have to copy paste the code in 7 different classes(and then changing the grid) so I thought maybe using subclass would be much easier. The problem is I dont know how to do that.
this is my general block class:
public class Block
{
Color Color;
const int x = 4;
const int y = 4;
bool[,] vorm;
Texture2D block;
float FallTimer;
public bool FallingBlock = false;
Random Random = new Random();
ZBlock zBlock = new ZBlock();
TBlock tBlock = new TBlock();
SBlock sBlock = new SBlock();
OBlock oBlock = new OBlock();
JBlock jBlock = new JBlock();
LBlock lBlock = new LBlock();
IBlock iBlock = new IBlock();
public void HandleInput()
{
if (Tetris.inputHelper.KeyPressed(Keys.Down))
{
FallTimer = 0;
for (int i = 0; i < blokvorm.GetLength(0); i++)
{
for (int j = 0; j < blokvorm.GetLength(1); j++) ;
// blokvorm[i, j] += 15;
}
}
}
public void speed(GameTime gameTime)
{
double SpeedCounter = 3;
int LevelCounter = 1;
if (LevelCounter < Tetris.GameWorld.level)
{
SpeedCounter -= 0.5;
LevelCounter++;
}
FallTimer += (float)gameTime.ElapsedGameTime.TotalSeconds;
if (Math.Round(FallTimer, 1) == SpeedCounter)
{
FallTimer = 0;
//BlockPosition.Y += 15;
}
}
public bool[,] blokvorm
{
get
{
vorm = new bool[x, y];
for (int i = 0; i < x; i++)
for (int j = 0; j < y; j++)
{
vorm[i, j] = false;
}
int r = Random.Next(7);
if (r == 0)
{
vorm = ZBlock.zblock();
}
else if (r == 1)
{
vorm = TBlock.tblock();
}
else if (r == 2)
{
vorm = SBlock.sblock();
}
else if (r == 3)
{
vorm = OBlock.oblock();
}
else if (r == 4)
{
vorm = JBlock.jblock();
}
else if (r == 5)
{
vorm = LBlock.lblock();
}
else if (r == 6)
{
vorm = IBlock.iblock();
}
return vorm;
}
}
public TBlock TBlock
{
get { return tBlock; }
}
public ZBlock ZBlock
{
get { return zBlock; }
}
public SBlock SBlock
{
get { return sBlock; }
}
public OBlock OBlock
{
get { return oBlock; }
}
public JBlock JBlock
{
get { return jBlock; }
}
public LBlock LBlock
{
get { return lBlock; }
}
public IBlock IBlock
{
get { return iBlock; }
}
public void Draw(SpriteBatch spriteBatch, ContentManager Content)
{
block = Content.Load<Texture2D>("Block");
spriteBatch.Begin();
if (!FallingBlock)
{
for (int i = 0; i < blokvorm.GetLength(0); i++)
{
for (int j = 0; j < blokvorm.GetLength(1); j++)
if (blokvorm[i, j])
spriteBatch.Draw(block, new Vector2(30 + (i * 15), 30 + (j * 15)), Color.White);
}
spriteBatch.End();
}
}
}
}
So How can I use this class to create other 7 block classes(T, L, I, O etc) easily?
Edit: My block all looks like this:
{
const int x = 4;
const int y = 4;
public bool[,] tblock()
{
vorm = new bool[x, y];
for (int i = 0; i < x; i++)
for (int j = 0; j <y; j++)
{
vorm[i, j] = false;
vorm[0, 1] = true;
vorm[1, 1] = true;
vorm[1, 0] = true;
vorm[2, 1] = true;
}
Color = Color.Indigo;
return vorm;
}
public void RotationLinks(InputHelper inputhelper)
{
bool[,] nieuw = new bool[x, y];
if (inputhelper.KeyPressed(Keys.Left))
{
for (int a = 0; a < 4; ++a)
for (int b = 0; b < 4; ++b)
nieuw[a, b] = vorm[x - a - 1, b];
vorm = nieuw;
}
}
}
}
So to make other 6 I copied theh whole code and change the grid value. Is there a possible way to make it easier using bock class?

Simple bubble sort c#

int[] arr = {800,11,50,771,649,770,240, 9};
int temp = 0;
for (int write = 0; write < arr.Length; write++)
{
for (int sort = 0; sort < arr.Length - 1; sort++)
{
if (arr[sort] > arr[sort + 1])
{
temp = arr[sort + 1];
arr[sort + 1] = arr[sort];
arr[sort] = temp;
}
}
Console.Write("{0} ", arr[write]);
}
All I am attempting to do is a simple bubble sort with this array. I would like to figure out why the sorting is screwed up.
In example, here is when the array is {800,11,50,771,649,770,240, 9}:
Here is what gets displayed: 11, 50, 649, 9, 649, 770, 771, 800
I am thinking that I might be missing something in the comparison.
No, your algorithm works but your Write operation is misplaced within the outer loop.
int[] arr = { 800, 11, 50, 771, 649, 770, 240, 9 };
int temp = 0;
for (int write = 0; write < arr.Length; write++) {
for (int sort = 0; sort < arr.Length - 1; sort++) {
if (arr[sort] > arr[sort + 1]) {
temp = arr[sort + 1];
arr[sort + 1] = arr[sort];
arr[sort] = temp;
}
}
}
for (int i = 0; i < arr.Length; i++)
Console.Write(arr[i] + " ");
Console.ReadKey();
This one works for me
public static int[] SortArray(int[] array)
{
int length = array.Length;
int temp = array[0];
for (int i = 0; i < length; i++)
{
for (int j = i+1; j < length; j++)
{
if (array[i] > array[j])
{
temp = array[i];
array[i] = array[j];
array[j] = temp;
}
}
}
return array;
}
public static void BubbleSort(int[] a)
{
for (int i = 1; i <= a.Length - 1; ++i)
for (int j = 0; j < a.Length - i; ++j)
if (a[j] > a[j + 1])
Swap(ref a[j], ref a[j + 1]);
}
public static void Swap(ref int x, ref int y)
{
int temp = x;
x = y;
y = temp;
}
int[] arr = { 800, 11, 50, 771, 649, 770, 240, 9 };
int temp = 0;
for (int write = 0; write < arr.Length; write++)
{
for (int sort = 0; sort < arr.Length - 1 - write ; sort++)
{
if (arr[sort] > arr[sort + 1])
{
temp = arr[sort + 1];
arr[sort + 1] = arr[sort];
arr[sort] = temp;
}
}
}
for (int i = 0; i < arr.Length; i++) Console.Write(arr[i] + " ");
Console.ReadKey();
I saw someone use this example as part of a job application test. My feedback to him was that it lacks an escape from the outer loop when the array is mostly sorted.
consider what would happen in this case:
int[] arr = {1,2,3,4,5,6,7,8};
here's something that makes more sense:
int[] arr = {1,2,3,4,5,6,7,8};
int temp = 0;
int loopCount=0;
bool doBreak=true;
for (int write = 0; write < arr.Length; write++)
{
doBreak=true;
for (int sort = 0; sort < arr.Length - 1; sort++)
{
if (arr[sort] > arr[sort + 1])
{
temp = arr[sort + 1];
arr[sort + 1] = arr[sort];
arr[sort] = temp;
doBreak=false;
}
loopCount++;
}
if(doBreak){ break; /*early escape*/ }
}
Console.WriteLine(loopCount);
for (int i = 0; i < arr.Length; i++) Console.Write(arr[i] + " ");
public static int[] BubbleSort(int[] arr)
{
int length = arr.Length();
while (length > 0)
{
int newLength = 0;
for (int i = 1; i < length; i++)
{
if (arr[i - 1] > arr[i])
{
Swap(ref arr[i - 1], ref arr[i]);
newLength = i;
}
}
length = newLength;
}
}
public static void Swap(ref int x, ref int y)
{
int temp = y;
y = x;
x = temp;
}
I wanted to add to the accepted answer something different:
Number of iterations can be reduced as well, as below.
int[] arr = { 800, 11, 50, 771, 649, 770, 240, 9 };
int temp = 0;
int arrLength = arr.Length;
for (int write = 0; write < arr.Length - 1; write++, arrLength--)
{
for (int sort = 0; sort < arrLength - 1; sort++)
{
if (arr[sort] > arr[sort + 1])
{
temp = arr[sort + 1];
arr[sort + 1] = arr[sort];
arr[sort] = temp;
}
}
}
foreach (var item in arr)
{
Console.WriteLine(item);
}
Your Console.Write("{0} ", arr[write]); is too early. You're printing the values while the sort is still in progress. For example, you're printing 9 as being index 3 in the array, yet on the very next iteration of the loop the 9 has moved to index 2 and 240 has moved to index 3... yet you're outer loop has moved forward so it prints 649 the second time and 240 never gets printed.
int[] array = new int[10] { 13, 2, 5, 8, 23, 90, 41, 4, 77, 61 };
for (int i = 10; i > 0; i--)
{
for (int j = 0; j < 9; j++)
{
if (array[j] > array[j + 1])
{
int temp = array[j];
array[j] = array[j + 1];
array[j + 1] = temp;
}
}
}
static bool BubbleSort(ref List<int> myList, int number)
{
if (number == 1)
return true;
for (int i = 0; i < number; i++)
{
if ((i + 1 < number) && (myList[i] > myList[i + 1]))
{
int temp = myList[i];
myList[i] = myList[i + 1];
myList[i + 1] = temp;
}
else
continue;
}
return BubbleSort(ref myList, number - 1);
}
Just another example but with an outter WHILE loop instead of a FOR:
public static void Bubble()
{
int[] data = { 5, 4, 3, 2, 1 };
bool newLoopNeeded = false;
int temp;
int loop = 0;
while (!newLoopNeeded)
{
newLoopNeeded = true;
for (int i = 0; i < data.Length - 1; i++)
{
if (data[i + 1] < data[i])
{
temp = data[i];
data[i] = data[i + 1];
data[i + 1] = temp;
newLoopNeeded = false;
}
loop++;
}
}
}
Bubble sort with sort direction -
using System;
public class Program
{
public static void Main(string[] args)
{
var input = new[] { 800, 11, 50, 771, 649, 770, 240, 9 };
BubbleSort(input);
Array.ForEach(input, Console.WriteLine);
Console.ReadKey();
}
public enum Direction
{
Ascending = 0,
Descending
}
public static void BubbleSort(int[] input, Direction direction = Direction.Ascending)
{
bool swapped;
var length = input.Length;
do
{
swapped = false;
for (var index = 0; index < length - 1; index++)
{
var needSwap = direction == Direction.Ascending ? input[index] > input[index + 1] : input[index] < input[index + 1];
if (needSwap)
{
var temp = input[index];
input[index] = input[index + 1];
input[index + 1] = temp;
swapped = true;
}
}
} while (swapped);
}
}
This is what I wrote using recursive methods:
public static int[] BubbleSort(int[] input)
{
bool isSorted = true;
for (int i = 0; i < input.Length; i++)
{
if (i != input.Length - 1 && input[i] > input[i + 1])
{
isSorted = false;
int temp = input[i];
input[i] = input[i + 1];
input[i + 1] = temp;
}
}
return isSorted ? input : BubbleSort(input);
}
It does the same in a more elegant way.
var arrayValues = new[] { 99, 12, 11, 300, 400, 10, 9, 3, 6, 5, 7, 8};
for (var mainLoop = 0; mainLoop < arrayValues.Length; mainLoop++)
{
for (var innerLoop = mainLoop + 1; innerLoop < arrayValues.Length; innerLoop++)
{
if (arrayValues[mainLoop] <= arrayValues[innerLoop])
{
continue;
}
var temp = arrayValues[mainLoop];
arrayValues[mainLoop] = arrayValues[innerLoop];
arrayValues[innerLoop] = temp;
}
}
So i did mine as a recursive function (no need for the nested loop), perhaps someone could comment if this is inefficient (when compared to the other solutions).
public static int[] BubbleSort(int[] arrayOfValues)
{
var swapOccurred = false;
for (var i = 0; i < arrayOfValues.Length; i++)
{
if (i == arrayOfValues.Length - 1)
continue;
if (arrayOfValues[i] > arrayOfValues[i + 1])
{
//swap values
var current = arrayOfValues[i];
var next = arrayOfValues[i + 1];
arrayOfValues[i] = next;
arrayOfValues[i + 1] = current;
swapOccurred = true;
}
}
if (swapOccurred)
{
// keep going until no further swaps are required:
BubbleSort(arrayOfValues);
}
return arrayOfValues;
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Practice {
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Enter the size");
int n = Convert.ToInt32(Console.ReadLine());
int[] mynum = new int[n];
Console.WriteLine("Enter the Numbers");
for (int p = 0; p < n;p++ )
{
mynum[p] = Convert.ToInt32(Console.ReadLine());
}
Console.WriteLine("The number are");
foreach(int p in mynum)
{
Console.WriteLine(p);
}
for (int i = 0; i < n;i++ )
{
for(int j=i+1;j<n;j++)
{
if(mynum[i]>mynum[j])
{
int x = mynum[j];
mynum[j] = mynum[i];
mynum[i] = x;
}
}
}
Console.WriteLine("Sortrd data is-");
foreach(int p in mynum)
{
Console.WriteLine(p);
}
Console.ReadLine();
}
} }
int[] arr = { 800, 11, 50, 771, 649, 770, 240, 9 };
for (int i = 0; i < arr.Length; i++)
{
for (int j = i; j < arr.Length ; j++)
{
if (arr[j] < arr[i])
{
int temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
}
}
Console.ReadLine();
public void BubbleSortNum()
{
int[] a = {10,5,30,25,40,20};
int length = a.Length;
int temp = 0;
for (int i = 0; i <length; i++)
{
for(int j=i;j<length; j++)
{
if (a[i]>a[j])
{
temp = a[j];
a[j] = a[i];
a[i] = temp;
}
}
Console.WriteLine(a[i]);
}
}

Categories

Resources