So I'm trying to make this loop that goes through every index of highscore array(scorelist) to check if the current score(playerScore) is higher than the current index. If the if statement gets a "yes", then it should push all scores down(or is that higher?) along the index and put playerScore at where it should be.
{
Console.Write("input name: ");
string playerName = Console.ReadLine();
Console.Write("input score: ");
int playerScore = Convert.ToInt32(Console.ReadLine());
for (int i = 0; i < 10; i++)
{
if (playerScore > scoreList[i])
{
int nextNo = 9;
for (int n = 10; n > 0; n--)
{
scoreList[n] = scoreList[nextNo];
nameList[n] = nameList[nextNo];
nextNo--;
}
scoreList[i] = playerScore;
nameList[i] = playerName;
}
}
}
With this current code, it just places playerScore on the first index(IF it is higher than what was previously stored there), then copies it along the rest of the index. Any suggestions on how to fix this?
It can be done much easier:
int prev = playerScore;
for (int i = 0; i < 10; i++)
{
if (playerScore > scoreList[i])
{
int temp = scoreList[i];
scoreList[i] = prev;
prev = temp;
}
}
I assumed, that you only need top 10 results (and your array already has 10 elements in it).
Change your array to a List<int> and use this code:
var scorelist = new List<int>();
//populate your scorelist;
var playerScore = someintValue;
var firstlower = scorelist.FirstOrDefault(x => x < playerScore);
if (firstlower != null)
scorelist.Insert(playerScore, scoreList.IndexOf(firstlower);
else
scorelist.add(playerScore);
Edit:
If you need to crop the list to 10 items max after inserting, just:
scorelist = scorelist.Take(10).ToList();
Related
I am trying to count how many times a number appears in an array 1 (a1) and then trying to print out that number by storing it in array 2 (a2) just once and then try to print array 2. But first using for loop and a function, I will check that if a number already exist in array 2 then move to next index in array 1, unfortunateley this code is not working; can someone please help me in trying to fix it, I don't need some complex solutions like dictionaries or lists athe moment, although it might be helpful too. thanks, I am not an expert in programming and I try to practise it in my free time, so please help me.
I just want this code to be fixed for my understanding and knowledge
class Program
{
static void Main(string[] args)
{
int i, j;
int[] a1 = new int[10];
int[] a2 = new int[10];
int[] a3 = new int[10];
//takes an input
for (i = 0; i < a1.Length; i++)
{
a1[i] = Convert.ToInt32(Console.ReadLine());
}
for (i = 0; i < a1.Length; i++)
{
Cn(a1, a2); //calls in function
i++; //increments is if true
int count = 0;
for (j = 0; j < a1.Length; j++)
{
//if a number matches with a number in second array
if (a1[i] == a1[j])
{
//do count ++
count++;
// store that number into second array
a2[i] = a1[i];
}
}
//store the number of counts in third array
a3[i] = count;
}
for (i = 0; i < a2.Length; i++)
{
if (a2[i] != 0)
{
Console.WriteLine(a2[i]);
}
}
Console.ReadLine();
}
//function to check if element at current index of array 1 exists in array 2 if yes than break
public static void Cn (int[] aa1, int [] aa2)
{
int k, j;
for ( k = 0; k < aa1.Length; k++)
{
for (j = 0; j < aa2.Length; j++)
{
if (aa1[k] == aa2[j])
break;
}
}
}
}
You probably want to do a group by count:
int[] a1 = new int[10];
var rnd = new Random();
//takes an input
for (int i = 0; i < a1.Length; i++)
{
a1[i] = Convert.ToInt32(rnd.Next(0, 11)); // or Console.ReadLine()
}
var grouped = a1
.GroupBy(x => x)
.Select(g => new
{
Item = g.Key,
Count = g.Count()
}).ToList(); // ToList() is optional, materializes the IEnumerable
foreach (var item in grouped)
{
Console.WriteLine($"number: {item.Item}, count: {item.Count}");
}
This uses a Hash algorithm internally.
You can solve this without a Hash or Dictionary but it wouldn't be very efficient because you need to do lots of linear searches through the arrays.
The advantage of a Hash algorithm is that your lookups or groupings are much faster than if you loop over a complete array to find / increment an item.
So I'm doing a practical that involves asking the user to input a score between 0 and 100. The program will keep track of the number of scores that have been entered, the total score (sum of all scores) and the average score.
To calculate the total score, I've come up of the idea of using a for loop that will cycle through my listbox and add each score to a variable (below).
int sTotal = 0;
for(int i = 0; i < lstScores.Items.Count; i++)
{
//Calculation occurs here
}
txtScoreTotal.Text = Convert.ToString(sTotal);
Thing is, I don't exactly know how to do it. I've tried searching to no avail. Any help would be greatly appreciated.
int sTotal = 0;
int Average = 0;
for(int i = 0; i < lstScores.Items.Count; i++)
{
bool result = Int16.TryParse(lstScores.Items[i],out int res);
if (result)
{
sTotale += res;
}
}
Average = sTotal / lstScores.Items.Count;
txtScoreTotal.Text = Convert.ToString(sTotal);
See this
int i = 0, result = 0;
while (i < lstScores.Items.Count)
{
result += Convert.ToInt32(lstScores.Items[i++]);
}
txtScoreTotal.Text = Convert.ToString(result);
I havent tried following, but you can try 1 line solution too
var sum = lstScores.Items.OfType<object>().Sum(x => Convert.ToInt32(x));
You need to handle exception if sum exceedes int.Max
Easiest is it to do with a foreach loop like this:
int sTotal = 0;
foreach (string item in lstScores.Items)
{
sTotal += Int32.Parse(item);
}
txtScoreTotal.Text = Convert.ToString(sTotal);
I create an array and fill it from the console.
I print that array in console.
I detect max and min elements in the array and output them in console.
Then I need to switch max and min elements and output the
updated array (without creating a new one).
Optionally I need to output new array that contains switched (max and min) elements.
private static void Main(string[] args)
{
int i;
int MaxElementIndex = 0;
int MinElementIndex = 0;
int temp = 0;
int[] t = new int[5];
for (i = 0; i < 5; i++)
{
Console.WriteLine("enter {0} element array", i + 1);
t[i] = int.Parse(Console.ReadLine());
}
int max = t[0];
for (i = 0; i < 5; i++)
{
if (max < t[i])
{
max = t[i];
MaxElementIndex = i;
}
}
Console.WriteLine("the maximum a value is equal {0} and index number is {1}", max, MaxElementIndex);
int min = t[0];
for (i = 0; i < 5; i++)
{
if (min > t[i])
{
min = t[i];
MinElementIndex = i;
}
}
Console.WriteLine("the minimun value is equal {0} and index number is {1}", min, MinElementIndex);
Console.WriteLine("Initial array: ");
foreach (var item in t)
{
Console.Write(item.ToString());
}
Console.ReadKey();
Console.WriteLine("Changed array:");
MaxElementIndex = temp;
MinElementIndex = MaxElementIndex;
temp = MinElementIndex;
foreach (var newItem in t)
{
Console.Write(newItem.ToString());
}
Console.ReadKey();
}
The problem is that I am not sure how to get the old array with switched elements. The pattern with temp variable returns me "0".
The problem is you are switching your temporary variables. But you want to switch you min and max elements in array. Your switching code should be like following:
temp = t[MaxElementIndex];
t[MaxElementIndex]=t[MinElementIndex];
t[MinElementIndex]=temp;
And then you should loop over your array:
Console.WriteLine("Switched array: ");
foreach (var newItem in t)
{
Console.Write(newItem.ToString());
}
Hope this helps.
This section is wrong in your code:
Console.ReadKey();
Console.WriteLine("Changed array:");
MaxElementIndex = temp;
MinElementIndex = MaxElementIndex;
temp = MinElementIndex;
it should be:
Console.ReadKey();
Console.WriteLine("Changed array:");
temp = t[MaxElementIndex];
t[MaxElementIndex] = t[MinElementIndex];
t[MinElementIndex] = temp;
First you store your t[maxElement] in temp variable then you replace it with t[minElement] and in the end replace minimum with maximum which is stored in temp variable.
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);
This code is buggy but can't figure out why ... want to populate an array with 7 unique random integers without using arraylists or linq! I know the logic is not okay...
class Program
{
static void Main(string[] args)
{ int current;
int[] numbers = new int[7]; // size of that array
Random rNumber = new Random();
current = rNumber.Next(1, 50);
numbers[0] = current;
Console.WriteLine("current number is {0}", current);
for (int i=1;i<7;i++)
{
current = rNumber.Next(1, 50);
for (int j = 0; j < numbers.Length; j++)
{
do
{
if (current == numbers[j])
{
Console.WriteLine("Duplicate Found");
current = rNumber.Next(1, 50);
}
else
{
numbers[j++] = current;
break;
}
}while (current == numbers[j]);
}//inner for
}//outer for
for (int l = 0; l < 7; l++) // DISPLAY NUMBERS
{
Console.WriteLine(numbers[l]);
}
}// main
}//class
want to populate an array with 7 unique integers without using
arraylists or linq!
int[] list = new int[7];
for (int i = 0; i < list.Length; i++)
{
list[i] = i;
}
EDIT
I changed your inner loop, if the random number is already in the array; create a new random and reset j to 0.
for (int i = 1; i < 7; i++)
{
current = rNumber.Next(1, 50);
for (int j = 0; j < numbers.Length; j++)
{
if (current == numbers[j])
{
Console.WriteLine("Duplicate Found");
current = rNumber.Next(1, 50);
j = 0; // reset the index iterator
}
}//inner for
numbers[i] = current; // Store the unique random integer
}//outer for
I presume you are looking for random numbers, so the other answer is not what you are looking for.
There are a couple of issues here.
The inner loop is testing for duplicates. However, it is looking from 0 through the end of the array since it is using numbers.length. This should probably be i, to compare with already set values. numbers.length is always 7 regardless of whether or not you set any of the elements.
the assignment is using j, so presuming the first element is not a duplicate, it will be overwritten each time. That should be numbers[i] = current;. No ++ necessary as the for is handling the incrementing.
if you determine that a number is a duplicate, j should be reset to zer to check against the entire list again rather than having the while in the middle.
Without a complete rewrite, the changes will look something like this:
for (int i=1;i<7;i++)
{
current = rNumber.Next(1, 50);
for (int j = 0; j < i; j++) //----------------- loop through set values
{
if (current == numbers[j])
{
Console.WriteLine("Duplicate Found");
current = rNumber.Next(1, 50);
j = 0; // -----------------------reset the counter to start over
}
}//inner for
// if we got here there is no duplicate --------------------------------
numbers[i] = current;
}//outer for
(Please note that I have not tested this code, just added the changes)
you keep overwriting the same indexes in the else, and also checking too many indices causing the first to show up as a duplicate at all times which was false...
change it to:
for (int i=1;i<7;i++)
{
current = rNumber.Next(1, 50);
for (int j = 0; j < i; j++) ///< change to j < i. no need to check the others
{
do
{
if (current == numbers[j])
{
Console.WriteLine("Duplicate Found");
current = rNumber.Next(1, 50);
}
else
{
numbers[i] = current; ///< not j++ but i to prevent writing at the same locations over and over again
break;
}
}while (current == numbers[j]);
}//inner for
}//outer for
What about this?
int[] list = new int[7];
var rn = new Random(Environment.TickCount);
for (int i = 0; i < 7; i++)
{
var next = rn.Next(1, 50);
while(Contains(list, next))
{
next = rn.Next(1, 50);
}
list[i] = next;
}
private bool Contains(IEnumerable<int> ints, int num)
{
foreach(var i in ints)
{
if(i = num) return true;
}
return false;
}