I am currently building a sorting program. I have made three different ways to create an array: Random, In Order and Reverse. I am currently undergoing problems with the In Order and Reverse arrays. Every time an In Order array is created it starts with a 1, I am not sure how come is doing so. Also my Reverse array will display digits out of order not every time but after some clicks. How can I fix these two issues?
namespace sortingMachine
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
//Class Level Variables --------------------------------------------------------------------------------------
Stopwatch sw = new Stopwatch();
Random r = new Random();
OpenFileDialog open1 = new OpenFileDialog();
long operations = 0;
int size;
int max;
int[] createArray;
int[] sortArray;
int[] copyArray;
//Create Array Methods --------------------------------------------------------------------------------------
public void RandomNumber()
{
size = Convert.ToInt32(textBoxSize.Text);
max = Convert.ToInt32(textBoxMax.Text);
createArray = new int[size];
copyArray = new int[size];
sortArray = new int[size];
for (int i = 0; i < size; i++)
{
createArray[i] = r.Next(1, max);
}
textBoxResults.AppendText("-------------------------------------------------------------------------------" + Environment.NewLine + "Random" + Environment.NewLine + Environment.NewLine);
DisplayArrays();
}
public void InOrder()
{
size = Convert.ToInt32(textBoxSize.Text);
max = Convert.ToInt32(textBoxMax.Text);
createArray = new int[size];
copyArray = new int[size];
sortArray = new int[size];
createArray[0] = 1;
for (int i = 1; i < size; i++)
{
createArray[i] = createArray[i - 1] + r.Next(1, max);
}
for (int i = 1; i < size; i++)
{
if (r.Next(1, 101) < Convert.ToInt32(textBoxPercentage.Text))
{
for (int x = 1; x < size; x++)
{
createArray[x] = r.Next(1, createArray[size - 1]);
}
}
}
textBoxResults.AppendText("-------------------------------------------------------------------------------" + Environment.NewLine + "In Order" + Environment.NewLine + Environment.NewLine);
DisplayArrays();
}
public void ReverseOrder()
{
size = Convert.ToInt32(textBoxSize.Text);
max = Convert.ToInt32(textBoxMax.Text);
createArray = new int[size];
copyArray = new int[size];
sortArray = new int[size];
createArray[size - 1] = 1;
for (int i = size - 1; i > 0; i--)
{
createArray[i - 1] = createArray[i] + r.Next(1, max);
}
for (int i = size - 1; i > 0; i--)
{
if (r.Next(1, 101) < createArray[0])
{
for (int x = size - 1; x > 0; x--)
{
createArray[x] = r.Next(1, createArray[0]);
}
}
}
textBoxResults.AppendText("-------------------------------------------------------------------------------" + Environment.NewLine + "Reverse Order" + Environment.NewLine + Environment.NewLine);
DisplayArrays();
}
private void buttonCreateArray_Click(object sender, EventArgs e)
{
if ((textBoxSortKey.Text != "") && (textBoxCreateKey.Text != ""))
{
if (radioButtonRandom.Checked == true)
{
RandomNumber();
}
if (radioButtonInOrder.Checked == true)
{
InOrder();
}
if (radioButtonReverseOrder.Checked == true)
{
ReverseOrder();
}
}
else
{
MessageBox.Show("Type a key into the Key textbox.");
}
}
}
}
Display Results:
The order array I am not sure why it always start with one:
-------------------------------------------------------------------------------
In Order
1
2
4
6
10
There are times the reverse order array will be like this:
-------------------------------------------------------------------------------
Reverse Order
10
2
7
6
5
Windows Form:
If you look at how you are assigning values to the array you'll see that the first element is assigned zero, but in your loop you start at the second element (i.e. 1) so you never re-assign the first element.
createArray[0] = 1;
for (int i = 1; i < size; i++)
{
createArray[i] = createArray[i - 1] + r.Next(1, max);
}
Try writing the first element assignment like this:
createArray[0] = r.Next(1, max);
As for your reverse function, there's too much weirdness in there to really see what you're trying to do. Try thinking thru it a few more times. Especially be careful with code like this: if (r.Next(1, 101) < createArray[0]) - it has random behaviour and also magic numbers in it.
In the function InOrder you initialize your first index of your array to 1. As for the Reverse Order, in the if statement in between the two fors, each time you are comparing a random number between 1-101 with the first number in your array. What you should be doing instead is compare the numbers in your array with each other.
Related
I tried everything i could find online and spent a lot of time on this but I cant do it.
It's a form with a ListBox with random numbers from 20 to 30 and I need to find the min and show its position. The hard part is that if i have 2 of the same number or 3 of them, then I don't know what to do and I tried almost everything.
This is the code i did so far:
Random r = new Random();
int[] a;
private void button2_Click(object sender, EventArgs e)
{
int i;
a = new int[10];
listBox1.Items.Clear();
for (i = 0; i < 10; i++)
{
a[i] = r.Next(20, 31);
listBox1.Items.Add(a[i]);
}
}
private void button1_Click(object sender, EventArgs e)
{
int[] b;
b = new int[10];
int mini=3435, i,index=0;
b = (int[])a.Clone();
for (i = 1; i < 10; i++)
{
if (b[i] < mini)
{
mini = b[i];
}
}
index = Array.IndexOf(b, mini);
label2.Text = Convert.ToString("la pozitia: " + index);
label1.Text = Convert.ToString("Minimul este: " +mini );
}
This is how it should look:
Since you simply want to output the positions as a comma seperate list, you can use a separate string for the list of positions that match:
int[] b;
b = new int[10];
int mini = int.MaxValue, i, index = 0;
string miniList = "";
b = (int[])a.Clone();
for (i = 0; i < 10; i++)
{
if (b[i] < mini)
{
mini = b[i];
miniList = "";
}
if (b[i] == mini)
{
if (!string.IsNullOrEmpty(miniList))
{
miniList += ", ";
}
miniList += i;
}
}
label1.Text = Convert.ToString("Minimul este: " + mini);
label2.Text = Convert.ToString("la pozitia: " + miniList);
NOTE: I also set the mini value to int.MaxValue to begin with so code should work with any number range
I am trying to solve an exercise in C# as follows:
Write a program that generates 20 random integers between 0 and 9 and displays the count for each number.
Use an array of ten integers, say counts, to store the counts for the number of 0s, 1s, ..., 9s.)
This is what i come up with which kind of work but i have a problem with the 0's counting 1 extra all the time.
using System.Collections.Generic;
using System.Text;
namespace ArrayExercises
{
class TaskFive
{
public static void FindNumberCount()
{
int c0=0,c1=02,c2=0,c3=0,c4=0,c5=0,c6=0,c7=0,c8=0,c9=0;
int[] arr = new int[20];
Random rand = new Random();
Console.WriteLine("Numbers generated ");
for (int i = 0; i < 19; i++)
{
arr[i] = rand.Next(0, 10);
Console.WriteLine(arr[i]);
}
foreach(int number in arr)
{
if (number == 0) { c0++; }
else if (number == 1) { c1++; }
else if (number == 2) { c2++; }
else if (number == 3) { c3++; }
else if (number == 4) { c4++; }
else if (number == 5) { c5++; }
else if (number == 6) { c6++; }
else if (number == 7) { c7++; }
else if (number == 8) { c8++; }
else if (number == 9) { c9++; }
}
Console.WriteLine
(
$"Number of 0's: {c0} \n" +
$"Number of 1's: {c1} \n" +
$"Number of 2's: {c2} \n" +
$"Number of 3's: {c3} \n" +
$"Number of 4's: {c4} \n" +
$"Number of 5's: {c5} \n" +
$"Number of 6's: {c6} \n" +
$"Number of 7's: {c7} \n" +
$"Number of 8's: {c8} \n" +
$"Number of 9's: {c9}"
);
}
}
}
Thanks in advance :)
You could shorten it like this
public static void FindNumberCount()
{
int[] count = new int[10];
Random rand = new Random();
int[] arr = new int[20];
for (int i = 0; i < arr.Length; i++)
{
arr[i] = rand.Next(0, 10);
Console.WriteLine(arr[i]);
count[arr[i]]++;
}
for (int i = 0; i < count.Length; i++)
{
Console.WriteLine($"Number of {i}'s: {count[i]}");
}
}
If you want draw 20 numbers you should for (int i = 0; i < 20; i++) not 19.
int[] counts = new int[10];
int[] numbers = new int[20];
var random = new Random();
for (int i = 0; i < numbers.Length; i++)
{
// Generate random numbers
numbers[i] = random.Next(0, 9);
// Increment the count of the generated number
counts[numbers[i]]++;
}
the for loop you use loops only 19 times.
You must change the "i < 19" to "i < 20".
In your program, the for loop leaves the last int in the array at it's default value (0),
this also explains, why you always have one more zero.
Hope this helped.
The issues is in this line
for (int i = 0; i < 19; i++)
You initialized an array with 20 int and set only value to 19 of them.
If you don't set the value int defaults to Zero and hence you always get one extra zero
Change your code as below
for (int i = 0; i <= 19; i++)
The halting condition of the first for loop should be i<20. Then your program should work.
This is how I would solve it:
static void Main(string[] args)
{
Random random = new Random();
//Fill array with random numbers
int[] array = new int[20];
for (int i = 0; i < array.Length; i++)
array[i] = random.Next(0, 10);
//Count how many times a number occurs
int[] numberCounts = new int[10];
for (int i = 0; i < array.Length; i++)
numberCounts[array[i]]++;
//Print the count of the numbers
for(int i = 0; i < numberCounts.Length; i++)
Console.WriteLine("Number of " + i + "'s: " + numberCounts[i]);
//Keep the console open
Console.ReadLine();
}
Im currently writing code to sort an array through bubble sort. I've previously written it using a set array that i created and it worked perfectly. However, i tried to change it to a randomly generated array and its now broken. wondered if anyone could give me a hand. thanks in advance.
using System;
namespace BubbleSot_Fin
{
class Program
{
static void Main(string[] args)
{
int N = 5;
int m = 100;
int i = 1; //n = number of values m = max value in array
Random Rand = new Random();
int[] array = new int[N + 1];
for ( i = 1; i <= N; i++)
{
array[i] = Rand.Next(1, m); //Randomise the array
Console.WriteLine("This is the unsorted array");
Console.WriteLine("");
for (i = 0; i < array.Length; i++)
{
Console.WriteLine("A[" + i + "] = " + array[i] ); // shows the unsorted numbers
}
int[] Bubble = BubbleSort(array);
Console.WriteLine("");
Console.WriteLine("Array after Bubble Sort");
Console.WriteLine("");
for ( i = 0; i < Bubble.Length; i++)
{
Console.WriteLine("A[" + i + "] = " + Bubble[i]); // shows the numbers after sorting
}
Console.ReadLine();
}
private static int[] BubbleSort(int[] BSArray)
{
int length = array.Length;
for ( i = 0; i < length - 1; i++)
{
for (int j = 0; j < length - 1 - i; j++)
{
if (array[j] > array[j + 1])
{
int number = array[j];
array[j] = array[j + 1];
array[j + 1] = number;
}
}
}
return BSArray;
}
}
}
The errors i'm having are that the private and static word for the bubble sort are incorrect.
The errors are :
- CS0106 The modifier 'Private' is not valid for this item
- CS0106 The modifier 'Static' is not valid for this item
I'm writing a mastermind game and I need to update the value of an array size using a variable inside a while loop which increments on each loop is there any way i can do this?
bool game = false;
do
{
int codeSize;
int colourSize;
int guessNumber = 1;
int userGuess;
int black = 0;
int white = 0;
int count = 1;
Console.WriteLine("Welcome to Mastermind coded by ****");
Console.Write("How many positions > ");
codeSize = Convert.ToInt32(Console.ReadLine());
Console.Write("How many colours > ");
colourSize = Convert.ToInt32(Console.ReadLine());
Random rand = new Random();
int[] code = new int[codeSize];
int[] guess = new int[codeSize];
for (int i = 0; i < codeSize; i++)
{
code[i] = rand.Next(1, colourSize + 1);//filling the secret code array
}
Console.WriteLine("O.k. - I've generated a code -- guess it!");
while (black < codeSize)
{
int[,] history = new int[count, codeSize + 2];
Console.WriteLine("Next guess please.");
for (int n = 0; n < codeSize; n++)
{
Console.Write("Position " + guessNumber + " >");
userGuess = Convert.ToInt32(Console.ReadLine());
guess[n] = userGuess;
history[count - 1, n] = guess[n];
guessNumber++;
}
for (int x = 0; x < codeSize; x++)
{
int caseSwitch = 1;
switch (caseSwitch)
{
case 1:
{
if (guess[x] == code[x])
{
black++;
break;
}
goto case 2;
}
case 2:
{
if (guess[x] == code[x])
{
break;
}
int i = 0;
while (i < codeSize)
{
if ((guess[x] == code[i]) && (guess[i] != code[i]))
{
white++;
break;
}
i++;
}
break;
}
}
}
guessNumber = 1;
if (black == codeSize)
{
white = 0;
}
history[count - 1, codeSize + 1] = white;
history[count - 1, codeSize] = black;
count++;
Debug.WriteLine("-----------\nSecret code\n-----------");
for (int x = 0; x < codeSize; x++)
{
Debug.WriteLine(code[x]);
}
Console.WriteLine("Correct positions : {0}", black);
Console.WriteLine("Correct colours : {0}\n", white);
Console.WriteLine("History");
for (int t = 1; t < codeSize + 1; t++)
{
Console.Write(t + " ");
}
Console.WriteLine("B W");
for (int g = 0; g < codeSize + 3; g++)
{
Console.Write("--");
}
Console.Write("\n");
for (int t = 0; t < count - 1; t++)
{
for (int g = 0; g < codeSize + 2; g++)
{
Console.Write("{0} ", history[t, g]);
}
Console.WriteLine("\n");
}
if (codeSize > black)//reseting values for next turn
{
black = 0;
white = 0;
}
}
int play;
Console.WriteLine("\nYou Win!\n\nPress 1 to play again or any other number to quit");
play = Convert.ToInt32(Console.ReadLine());
if (play == 1)
game = true;
} while (game == true);
Arrays have a fixed size when you declare them and you cannot change the size afterwards without creating a new array. Try using a strongly typed List instead.
List<int> MyList = new List<int>();
// Add the value "1"
MyList.Add(1);
or the following for a table:
List<List<int>> MyTable = new List<List<int>>();
// Add a new row
MyTable.Add(new List<int>());
// Add the value "1" to the 1st row
MyTable[0].Add(1);
I believe you are asking whether you can change the length property of an array from within a loop, extending it as required.
Directly, no. There are helpers and classes which provide for such functionality, allocating more memory as needed, but I doubt this is what you really need. You could try using an array of fixed dimensions (the maximum codeSize your program will tolerate or expect), and then an integer next to it to record the length/position.
Alternatively, if you really need to expand to arbitrary sizes and store all codes, just use a List.
List<int[]> theList = new List<int[]>();
theList.Add(code);
Creates a list of integer arrays (your codes) that you can keep adding onto, and index just like any simple array.
There is a way to resize array size:
Array.Resize<T>
method. Details there: http://msdn.microsoft.com/en-us/library/bb348051(v=vs.110).aspx
But it's usually a pretty bad idea to resize the arrays loop based. You need to select another data structure to save your data or i.e. create an array of bigger size filled i.e. with zeroes.
You also need to add the items to the list as so. The list will dynamically grow based on it's size.
int myInt = 6;
List<int> myList = new List<int>();
myList.Add(myInt);
I am currently trying to implement binary sort logic. I start by generating random numbers. Then create a copy of that array which will be then sorted out with the Binary Sort method. The problem is that the sort is not working properly. I am not sure if my comparisons are being done correctly. Any ideas why is not sorting properly?
namespace binarySort
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
Stopwatch sw = new Stopwatch();
Random r = new Random();
OpenFileDialog open1 = new OpenFileDialog();
long operations = 0;
int size;
int max;
int[] createArray;
int[] sortArray;
int[] copyArray;
public void RandomNumber()
{
size = Convert.ToInt32(textBoxSize.Text);
max = Convert.ToInt32(textBoxMax.Text);
createArray = new int[size];
copyArray = new int[size];
sortArray = new int[size];
for (int i = 0; i < size; i++)
{
createArray[i] = r.Next(1, max);
}
textBoxResults.AppendText("-------------------------------------------------------------------------------" + Environment.NewLine + "Random" + Environment.NewLine + Environment.NewLine);
DisplayArrays();
}
public void BinarySort()
{
operations = 0;
sw.Reset();
sw.Start();
int low = 0;
int high = 0;
int temp = 0;
int mid = 0;
for (int i = 0; i < size; i++)
{
copyArray[i] = createArray[i];
}
for (int i = 1; i < size; i++)
{
high = i - 1;
temp = copyArray[i];
while (low <= high)
{
operations++;
mid = (low + high) / 2;
if (temp < copyArray[mid])
{
high = mid - 1;
}
else
{
low = mid + 1;
}
}
operations++;
for (int j = i - 1; j >= low; j--)
{
copyArray[j + 1] = copyArray[j];
}
copyArray[low] = temp;
}
for (int i = 0; i < size; i++)
{
sortArray[i] = copyArray[i];
}
textBoxResults.AppendText("-------------------------------------------------------------------------------" + Environment.NewLine + "Binary Insertion" + Environment.NewLine + Environment.NewLine);
DisplaySorted();
}
private void buttonSortArray_Click(object sender, EventArgs e)
{
BinarySort();
}
}
}
For example:
EDIT: Sorry, your original code is OK, you just need to add this line low = 0; after high = i - 1; so it should be
for (int i = 1; i < size; i++)
{
high = i - 1;
low = 0;
temp = copyArray[i];