I wrote a code for a 3x3 bingo game. It check for line, bingo or nothing for a given input where I get a 3x3 bingo card and next 15 numbers extracted.
Basically I use a 2D user inputed array for the 3x3 bingo card, then I have a function which asks me to input 15 numbers. If all the numbers from the 3x3 bingo card are present in those 15 extracted numbers then I have "bingo". If I have numbers from a line but not all numbers then the program will output "line". And if i will not have bingo neither line the program will output "nothing".
Here is the input:
1 2 3
90 91 92
93 94 95
1
2
3
4
5
6
7
8
10
11
12
13
14
15
16
The program should return "line" but instead I get "nothing"
using System;
class Program
{
static void Main()
{
const int numberOfRows = 3;
const int numberOfColumnns = 3;
const int numbersExtracted = 15;
int[,] bingoCard = ReadBingoCard(numberOfRows, numberOfColumnns);
int[] numbers = ReadNumbersExtracted(numbersExtracted);
PrintResult(bingoCard, numbers);
Console.ReadLine();
}
static int[,] ReadBingoCard(int rowsNumber, int columnNumber)
{
int[,] card = new int[rowsNumber, columnNumber];
for (int i = 0; i < rowsNumber; i++)
{
string[] array = Console.ReadLine().Split(' ');
for (int j = 0; j < columnNumber; j++)
{
card[i, j] = Convert.ToInt32(array[j]);
}
}
return card;
}
static int[] ReadNumbersExtracted(int numbersExtracted)
{
int[] numbers = new int[numbersExtracted];
for (int i = 0; i < numbersExtracted; i++)
{
numbers[i] = Convert.ToInt32(Console.ReadLine());
}
return numbers;
}
static bool CheckForBingo(int[,] bingoCard, int[] numbers)
{
int numMatchesFound = 0;
foreach (var number in bingoCard)
{
for (int numIndex = 0; numIndex < numbers.Length; numIndex++)
{
if (number == numbers[numIndex])
{
numMatchesFound++;
break;
}
}
}
return numMatchesFound == bingoCard.Length;
}
static bool CheckForLine(int[,] bingoCard, int[] numbers)
{
for (int row = 0; row < bingoCard.GetLength(0); row++)
{
int colMatchesInRow = 0;
for (int col = 0; col < bingoCard.GetLength(1); col++)
{
if (Index(bingoCard, row, col, numbers, ref colMatchesInRow))
{
continue;
}
break;
}
if (colMatchesInRow == bingoCard.GetLength(1))
{
return true;
}
}
return false;
}
static bool Index(int[,] bingoCard, int row, int col, int[] numbers, ref int colMatchesInRow)
{
for (int numIndex = 0; numIndex < numbers.Length; numIndex++)
{
if (bingoCard[row, col] != numbers[numIndex])
{
continue;
}
colMatchesInRow++;
break;
}
return colMatchesInRow == bingoCard.GetLength(1);
}
static void PrintResult(int[,] bingoCard, int[] numbersExtracted)
{
if (CheckForBingo(bingoCard, numbersExtracted))
{
Console.WriteLine("bingo");
}
else if (CheckForLine(bingoCard, numbersExtracted))
{
Console.WriteLine("line");
}
else
{
Console.WriteLine("nothing");
}
}
}
Checking if one line has matched numbers is the same as checking for bingo (all input numbers) but for one row only.
Try to implement the function CheckForLine() this way :
static bool CheckForLine(int[,] bingoCard, int[] numbers)
{
int numMatchesFound = 0;
foreach (var number in bingoCard)
{
for (int numIndex = 0; numIndex < numbers.Length; numIndex++)
{
if (number == numbers[numIndex])
{
numMatchesFound++;
break;
}
}
if (numMatchesFound == bingoCard.GetLength(1))
{
return true;
}
}
return false;
}
The 2 bingo-card cases below will work :
1 97 99
90 2 92
93 94 3
and
1 2 3
90 91 92
93 94 95
Related
I wrote a code for a 3x3 bingo game. It check for line, bingo or nothing for a given input where I get a 3x3 bingo card and next 15 numbers extracted.
Basically I use a 2D user inputed array for the 3x3 bingo card, then I have a function which asks me to input 15 numbers. If all the numbers from the 3x3 bingo card are present in those 15 extracted numbers then I have "bingo". If I have numbers from a line but not all numbers then the program will output "line". And if i will not have bingo neither line the program will output "nothing".
I don't like the CheckForLine() function using 3 nested loops. I can't use Linq, due to Sonar analyzer limitation.
using System;
class Program
{
static void Main()
{
const int numberOfRows = 3;
const int numberOfColumnns = 3;
const int numbersExtracted = 15;
int[,] bingoCard = ReadBingoCard(numberOfRows, numberOfColumnns);
int[] numbers = ReadNumbersExtracted(numbersExtracted);
PrintResult(bingoCard, numbers);
}
static int[,] ReadBingoCard(int rowsNumber, int columnNumber)
{
int[,] card = new int[rowsNumber, columnNumber];
for (int i = 0; i < rowsNumber; i++)
{
string[] array = Console.ReadLine().Split(' ');
for (int j = 0; j < columnNumber; j++)
{
card[i, j] = Convert.ToInt32(array[j]);
}
}
return card;
}
static int[] ReadNumbersExtracted(int numbersExtracted)
{
int[] numbers = new int[numbersExtracted];
for (int i = 0; i < numbersExtracted; i++)
{
numbers[i] = Convert.ToInt32(Console.ReadLine());
}
return numbers;
}
static bool CheckForBingo(int[,] bingoCard, int[] numbers)
{
int numMatchesFound = 0;
foreach (var number in bingoCard)
{
for (int numIndex = 0; numIndex < numbers.Length; numIndex++)
{
if (number == numbers[numIndex])
{
numMatchesFound++;
break;
}
}
}
return numMatchesFound == bingoCard.Length;
}
static bool CheckForLine(int[,] bingoCard, int[] numbers)
{
for (int row = 0; row < bingoCard.GetLength(0); row++)
{
int colMatchesInRow = 0;
for (int col = 0; col < bingoCard.GetLength(1); col++)
{
for (int numIndex = 0; numIndex < numbers.Length; numIndex++)
{
if (bingoCard[row, col] != numbers[numIndex])
{
continue;
}
colMatchesInRow++;
break;
}
}
if (colMatchesInRow == bingoCard.GetLength(1))
{
return true;
}
}
return false;
}
static void PrintResult(int[,] bingoCard, int[] numbersExtracted)
{
if (CheckForBingo(bingoCard, numbersExtracted))
{
Console.WriteLine("bingo");
}
else if (CheckForLine(bingoCard, numbersExtracted))
{
Console.WriteLine("line");
}
else
{
Console.WriteLine("nothing");
}
}
}
I'm trying to make a simple lotto/bingo game in c#.
Trying to make something like this:
Game where user types in 10 numbers which gets stored to an array.
Then the game makes a "lotto card" which is a 2 dimensional array with random numbers, like this:
10 | 13 | 14 | 17 | 16
18 | 24 | 21 | 23 | 8
1 | 3 | 6 | 25 | 9
7 | 22 | 15 | 12 | 2
4 | 5 | 11 | 19 | 20
Now i want to compare the contents of both arrays. I cant seem to find a way to do this with both 1 and 2 dimensionall arrays? Right now i've only managed to check if one of the numbers match.
Have tried using Linq and enumerabl and different loops in a couple of ways but with no success.
I want the game to register bingo if i match the numbers horizontally, vertically and diagonally.
This is my code so far:
static void Main(string[] args)
{
// Greet and explain the rules
Console.WriteLine("Welcome to bingo!");
string input; // Variabel for input by user
int inputnmr; // Variabel for nmrinput by user
int low = 1;
int high = 25;
int[] userNmr = new int[7]; // Creates a new array for the player
// Loop - asks user to type in their lotto numbers and stores them in variable "userNmr"
for (int i = 0; i < userNmr.Length; i++)
{
Console.Write("Type in a number between {0} - {1}:", low, high);
input = Console.ReadLine();
inputnmr = int.Parse(input);
userNmr[i] = inputnmr;
}
//Prints your lotto numbers:
Console.Write("These are your numbers :");
foreach (int i in userNmr)
{
Console.Write(i);
Console.Write(", ");
}
//Asks if continue:
Console.WriteLine("Are you sure about your numbers?");
Console.WriteLine("Do you want a bingo card?");
int x = 5; // Variable for size of x-axis
int y = 5; //Variable for the size of y-axis
//Variable for 2 dimensional array:
int[,] lottoCard = new int[x, y];
//Create random
Random randomnmr = new Random();
//Prints the lotto cards x-axis
for (int i = 0; i < 5; i++)
{
Console.WriteLine(" |------------------------|");
Console.Write(" | ");
//Prints the lotto card y-axis
for (int j = 0; j < 5; j++)
{
//Fills lotto card with random ints:
lottoCard[i, j] = randomnmr.Next(1, 26);
Console.Write(lottoCard[i, j] + " | ");
}
Console.WriteLine(" ");
}
Console.WriteLine(" |------------------------|");
// --- This is where im stuck ---
bool oneMatch = false;
while (oneMatch == false)
{
foreach (var numberA in userNmr)
{
foreach (var numberB in lottoCard)
{
if (numberA == numberB)
{
oneMatch = true;
}
}
}
}
if (oneMatch == true)
{
Console.WriteLine("BINGO!");
}
else
{
Console.WriteLine("No win . . .");
}
Things i've tried:
1:
bool equal = lottoCard.Rank == userNmr.Rank && Enumerable.Range(0, lottoCard.Rank).All(dimension => lottoCard.GetLength(dimension) == lottoCard.GetLength(dimension)) && lottoCard.Cast<double>().SequenceEqual(lottoCard.Cast<double>());
if (equal == true)
{
Console.WriteLine("Bingo");
}
else
{
Console.WriteLine("no win");
}
2:
bool IsContain(int[][] lottoCard, int[] userNmr)
{
foreach (int[] row in lottoCard)
{
int curlIndex = 0;
foreach (int item in row)
{
if (item == userNmr[curlIndex])
{
if (curlIndex == userNmr.Length - 1)
{
return true;
}
curlIndex++;
}
else
{
curlIndex = 0;
}
return false;
}
}
}
if (IsContain(lottoCard, userNmr))
{
Console.WriteLine("BINGO");
}
else
{
Console.WriteLine("No win");
}
Above does not work, would really appreciate some help!
Here's how I would have done it:
class Program
{
public static void Main(string[] args)
{
Console.WriteLine("Welcome to Bingo!");
int[] userNmr = getUserInput();
int[,] bingoCard = genBingoCard();
Console.WriteLine();
Console.WriteLine("Your number selections are:");
Console.WriteLine(String.Join(", ", userNmr));
Console.WriteLine();
Console.WriteLine("Here is your Bingo Card!");
displayBingoCard(bingoCard);
bool bingo = checkForBingo(userNmr, bingoCard);
if (bingo)
{
Console.WriteLine("Congratulations! You had a Bingo!");
}
else
{
Console.WriteLine("Sorry, no Bingos. Better luck next time!");
}
Console.WriteLine();
Console.WriteLine("Press Enter to Quit.");
Console.ReadLine();
}
public static int[] getUserInput()
{
int low = 1;
int high = 25;
string input;
int inputnmr;
int[] userNmr = new int[7];
// Loop - asks user to type in their lotto numbers and stores them in variable "userNmr"
bool valid;
for (int i = 0; i < userNmr.Length; i++)
{
valid = false;
while (!valid)
{
Console.WriteLine();
Console.WriteLine("User Selection #" + (i + 1));
Console.Write("Select a number between {0} - {1}: ", low, high);
input = Console.ReadLine();
if (int.TryParse(input, out inputnmr))
{
if (inputnmr >= low && inputnmr <= high)
{
if (!userNmr.Contains(inputnmr))
{
userNmr[i] = inputnmr;
valid = true;
}
else
{
Console.WriteLine("You already picked that number!");
}
}
else
{
Console.WriteLine("Number must be between {0} and {1}!", low, high);
}
}
else
{
Console.WriteLine("Invalid Number.");
}
}
}
return userNmr;
}
public static int[,] genBingoCard()
{
Random randomnmr = new Random();
int x = 5; // Variable for size of x-axis
int y = 5; //Variable for the size of y-axis
//Variable for 2 dimensional array:
int[,] bingoCard = new int[y, x];
List<int> numbers = Enumerable.Range(1, x * y).ToList();
numbers = numbers.OrderBy(z => randomnmr.Next()).ToList();
int counter = 0;
for (int r = 0; r < y; r++)
{
for (int c = 0; c < x; c++)
{
bingoCard[r, c] = numbers[counter++];
}
}
return bingoCard;
}
public static void displayBingoCard(int[,] bingoCard)
{
int x = bingoCard.GetUpperBound(1) + 1; // Variable for size of x-axis
int y = bingoCard.GetUpperBound(0) + 1; //Variable for the size of y-axis
string line = "";
for (int c = 0; c < x; c++)
{
line = line + "+----";
}
line = line + "+";
Console.WriteLine(line);
for (int r = 0; r < y; r++)
{
Console.Write("|");
for (int c = 0; c < x; c++)
{
Console.Write(" " + bingoCard[r, c].ToString("00") + " |");
}
Console.WriteLine();
Console.WriteLine(line);
}
}
public static bool checkForBingo(int[] userNmr, int[,] bingoCard)
{
int x = bingoCard.GetUpperBound(1) + 1; // Variable for size of x-axis
int y = bingoCard.GetUpperBound(0) + 1; //Variable for the size of y-axis
bool bingo;
// check each row
for (int r = 0; r < y; r++)
{
bingo = true; // until proven otherwise
for (int c = 0; c < x && bingo; c++)
{
int number = bingoCard[r, c];
bingo = userNmr.Contains(number);
}
if (bingo)
{
Console.WriteLine("Horizontal Bingo at Row: " + (r+1));
return true;
}
}
// check each column
for (int c = 0; c < x; c++)
{
bingo = true; // until proven otherwise
for (int r = 0; r < y && bingo; r++)
{
int number = bingoCard[r, c];
bingo = userNmr.Contains(number);
}
if (bingo)
{
Console.WriteLine("Vertical Bingo at Column: " + (c+1));
return true;
}
}
// check diagonals
// top left to bottom right
bingo = true; // until proven otherwise
for (int c = 0; c < x && bingo; c++)
{
for (int r = 0; r < y && bingo; r++)
{
int number = bingoCard[r, c];
bingo = userNmr.Contains(number);
}
}
if (bingo)
{
Console.WriteLine("Diagonal Bingo from Top Left to Bottom Right.");
return true;
}
// top right to bottom left
bingo = true; // until proven otherwise
for (int c = (x-1); c >= 0 && bingo; c--)
{
for (int r = 0; r < y && bingo; r++)
{
int number = bingoCard[r, c];
bingo = userNmr.Contains(number);
}
}
if (bingo)
{
Console.WriteLine("Diagonal Bingo from Top Right to Bottom Left.");
return true;
}
// no bingos were found!
return false;
}
}
I'm trying to make a lottery console app, but have a problem with duplicated numbers in some rows.
A lottery coupon is 10 row with 7 numbers, min number is 0, max number is 36.
How can i check if the number is exist in same row in my for loop?
here is my code
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Obligatorisk_Opgave_2
{
class Program
{
static void Main(string[] args)
{
int min = 0; // minimum number
int max = 36; // maximum number
int rows = 10; // number of rows in my copun
int col = 7; // number of column in my copun
// Get the date of PC
string NameDate;
NameDate = DateTime.Now.ToString("yyyy.MM.dd");
string Week = "1-uge";
string ComName = "LYN LOTTO";
Random rnd = new Random();
Console.WriteLine("{0,22} \n {1,15} \n{2,18}", NameDate, Week, ComName);
for (int i = 0; i < rows; i++)
{
Console.Write($"{i + 1}.");
for (int j = 0; j < col; j++)
Console.Write("{1,4}", i, rnd.Next(min, max));
Console.WriteLine();
}
Console.WriteLine("***** JOKER TAL *****");
for (int i = 0; i < 2; i++)
{
for (int j = 0; j < col; j++)
Console.Write("{0,4}", rnd.Next(1,9));
Console.WriteLine();
}
}
}
}
You can use a recursive function to do this:
private static List<int> GetRandomRow(List<int> row, int colCount, int min, int max)
{
if(colCount <= 0)
{
return row;
}
var next = rnd.Next(min, max);
if(row.Contains(next))
{
return GetRandomRow(row, colCount, min, max);
}
row.Add(next);
return GetRandomRow(row, colCount - 1, min, max);
}
Then you can use your program like:
private static Random rnd = new Random();
static void Main(string[] args)
{
int min = 0; // minimum number
int max = 36; // maximum number
int rows = 10; // number of rows in my copun
int col = 7; // number of column in my copun
// Get the date of PC
string NameDate;
NameDate = DateTime.Now.ToString("yyyy.MM.dd");
string Week = "1-uge";
string ComName = "LYN LOTTO";
Random rnd = new Random();
Console.WriteLine("{0,22} \n {1,15} \n{2,18}", NameDate, Week, ComName);
for (int i = 0; i < rows; i++)
{
Console.Write($"{i + 1}.");
var row = new List<int>();
var currentRow = GetRandomRow(row, col, min, max);
foreach (var currentCol in currentRow)
{
Console.Write("{1,4}", i, currentCol);
}
Console.WriteLine();
}
Console.WriteLine("***** JOKER TAL *****");
for (int i = 0; i < 2; i++)
{
for (int j = 0; j < col; j++)
Console.Write("{0,4}", rnd.Next(1, 9));
Console.WriteLine();
}
}
Instead of random numbers you could Shuffle your List.
Shuffle Function:
public static List<T> Shuffle<T> (List<T> list) {
Random rnd = new Random();
for (int i = 0; i < list.Count; i++)
{
int k = rnd.Next(0, i);
T value = list[k];
list[k] = list[i];
list[i] = value;
}
return list;
}
Now you can call that function and shuffle the content of your List.
Example:
int min = 0;
int max = 36;
int rows = 10;
List<int> mylist = new List<int>();
for (int i = max; i >= min; i--) {
mylist.Add(i);
}
mylist = Shuffle(mylist);
for (int i = 0; i < rows; i++) {
Console.WriteLine(mylist[i]);
}
Console.ReadLine();
simply you can define variable from string data type and add each column in this variable but before add operation you should check if this column exists in this string or not
code is updated
i have definde rndNumber as an integer type before check then i have assigned rnd.Next(min, max) to it, because if i check for rnd.Next(min, max) and if it was not exist so when add it in checkNumber may be it changed again for example...
if(checkNumber.Contains(rnd.Next(min, max))) // if value of rnd.Next(min, max) was 15 and this number not exist in checkNumber so i can add it
{
checkNumber += rnd.Next(min, max); // maybe value of rnd.Next(min, max) change to will be 20
}
notice that every time you call rnd.Next(min, max) it's value will be changed
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Obligatorisk_Opgave_2
{
class Program
{
static void Main(string[] args)
{
int min = 0; // minimum number
int max = 36; // maximum number
int rows = 10; // number of rows in my copun
int col = 7; // number of column in my copun
string checkColumn = ""; // string variable for storing rows values
// Get the date of PC
string NameDate;
NameDate = DateTime.Now.ToString("yyyy.MM.dd");
string Week = "1-uge";
string ComName = "LYN LOTTO";
Random rnd = new Random();
Console.WriteLine("{0,22} \n {1,15} \n{2,18}", NameDate, Week, ComName);
for (int i = 0; i < rows; i++)
{
Console.Write($"{i + 1}.");
for (int j = 0; j < col; j++)
{
// check here if string does not contains this random value then add this it into string and write this number, else will be written duplicated number
int rndNumber = rnd.Next(min, max);
if ( !checkColumn.Contains(rndNumber.ToString()+", ") )
{
checkColumn += rndNumber.ToString()+", ";
Console.Write("{1,4}", i, rndNumber);
}
else
{
Console.Write("duplicated number");
}
}
checkColumn += "\n";
Console.WriteLine();
}
Console.WriteLine("***** JOKER TAL *****");
for (int i = 0; i < 2; i++)
{
for (int j = 0; j < col; j++)
Console.Write("{0,4}", rnd.Next(1,9));
Console.WriteLine();
}
}
}
}
I'd use something more like:
for (int i = 1; i <= rows; i++)
{
Console.Write((i + ".").PadRight(3));
var row = Enumerable.Range(min, (max - min) + 1).OrderBy(x => rnd.Next()).Take(col).ToList();
foreach(var num in row) {
Console.Write(num.ToString("00").PadLeft(3));
}
Console.WriteLine();
}
Producing:
1. 33 14 24 27 07 29 30
2. 12 31 03 19 04 02 30
3. 34 03 14 23 20 09 04
4. 09 11 24 07 00 30 17
5. 26 04 22 02 25 20 12
6. 28 26 12 08 04 25 35
7. 09 26 20 34 17 03 23
8. 25 26 35 08 29 06 01
9. 29 33 00 04 09 35 36
10. 00 14 19 25 03 21 33
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
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() + " ");
}
}