Comparasion of numbers in an array - c#

I'm stuck at this. I`m beginner into software development.
You get a list of N students and then a list of ratings for each student. A student which has bigger rating than his neighbour from list gets more candies than both of them. For example:
Data input:
3
John
Michael
Sam
9
10
8
Data Output:
John 1
Michael 3
Sam 1
I wrote this code, but I'm missing something:
using System.Diagnostics.CodeAnalysis;
using System.IO.Pipes;
{
int number = Convert.ToInt32(Console.ReadLine());
string[] studentsList = FillArray(number);
int[] studentsGrades = ConvertList(FillArray(number));
PrintResult(studentsList, CountCandies(int number));
}
static string[] FillArray(int number)
{
string[] result = new string[number];
for (int i = 0; i < number; i++)
{
result[i] = Console.ReadLine();
}
return result;
}
static int[] ConvertList(string[] array)
{
int[] result = new int[array.Length];
for (int i = 0; i < array.Length; i++)
{
result[i] = Convert.ToInt32(array[i]);
}
return result;
}
static int[] GetGrades(int number) // give grades of each student
{
int[] result = new int[number];
for (int i = 0; i < number; i++)
{
result[i] = Convert.ToInt32(Console.ReadLine());
}
return result;
}
static int CountCandies(int[] arr, int number) // this is the method where I'm stuck.
{
int sum = 0;
int[] ans = new int[number];
for (int i = 0; i < number; i++)
{
ans[i] = 1;
}
for (int i = 0; i < number-1; i++)
{
if (arr[i+1] > arr[i])
{
ans[i+1] =ans[i] +1;
}
}
for (int i = number-2; i>=0; i--)
{
if (arr[i] > arr[i+1] && ans[i] <= ans[i+1])
{
ans[i] = ans[i+1] +1;
}
sum += ans[i];
}
sum += ans[number-1];
return sum;
}
static void PrintResult(string[] array, int[] array2) // print the final result
{
for (int i = 0; i < array.Length; i++)
{
array[i] += " " + array2[i];
}
foreach (string student in array)
{
Console.WriteLine(student);
}
}

You definitely need an object to hold your data.
public class StudentRating
{
public string StudentName {get;set;}
public int Rating {get;set;}
}
protected List<StudentRating> studentsRating = new List<StudentRating>();
public static void Main(string[] args)
{
GeteringInformation();
//after this do what you want with your data
}
protected static GeteringInformation()
{
Console.WriteLine("Student name:");
int rating =Convert.ToInt32(Console.ReadLine());
Console.WriteLine("Rating");
string name =Console.ReadLine();
studentsRating.Add(new StudentRating(){StudentName=name,Rating=rating});
Console.WriteLine("Next? (Y/N)");
if(Console.ReadLine().ToLower()="y")
GeteringInformation();
}

Related

Function contains multiple control flow statements

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");
}
}
}

how can i sort a matrix's each row from smallest to largest and then find the matrix's peak value?

i need to write a program that takes 1 to 100 integers randomly, then i need to take this program's transpose, then I need to sort this matrix (each row in itself) from smallest to largest.
and finally, i need to find this matrix's peak value. here is what i have written for the program. for now, it creates a random matrix (20x5) and then it takes its transpose. can you help me with finding its peak value and then sort its each row?
PS.: using classes is mandatory!
using System;
namespace my_matrix;
class Program
{
public int[,] Create(int[,] myarray, int Row, int Clm)
{
Random value = new Random();
myarray = new int[Row, Clm];
int i = 0;
int j = 0;
while (i < Row)
{
while (j < Clm)
{
myarray[i, j] = value.Next(1, 100);
j++;
}
i++;
j = 0;
}
return myarray;
}
public int[,] Print(int[,] myarray, int Row, int Clm)
{
Console.WriteLine("=====ARRAY=====");
for (int a = 0; a < Row; a++)
{
for (int b = 0; b < Clm; b++)
{
Console.Write(myarray[a, b] + " ");
}
Console.WriteLine();
}
return null;
}
public int[,] Transpose(int[,] myarray, int Row, int Clm)
{
for (int b = 0; b < Clm; b++)
{
for (int a = 0; a < Row; a++)
{
Console.Write(myarray[a, b] + " ");
}
Console.WriteLine();
}
return myarray;
}
public int[,] Print_Transpose(int[,] myarray, int Row, int Clm)
{
Console.WriteLine("=====TRANSPOSE=====");
for (int b = 0; b < Clm; b++)
{
for (int a = 0; a < Row; a++)
{
Console.Write(myarray[a, b] + " ");
}
Console.WriteLine();
}
return null;
}
static void Main(string[] args)
{
Program x = new Program();
int[,] myarray = new int[20, 5];
int[,] a = x.Create(myarray, 20, 5);
x.Print(a, 20, 5);
x.Print_Transpose(a, 20, 5);
}
}
i don't know how to make a class which sorta each row from smallest to largest and also i dont know how to create a class which finds the matrix's peak value.
You can run over the array, keeping the maxNum:
public int getMax(int[,] fromArray)
{
int maxNum = 0;
for (int b = 0; b < fromArray.GetUpperBound(1); b++)
{
for (int a = 0; a < fromArray.GetUpperBound(0); a++)
{
if (maxNum < fromArray[a,b])
{
maxNum = fromArray[a, b];
}
}
}
return maxNum;
}
Call the function like:
Console.Write("Max number = {0:D}", x.getMax (a));
If you want a sort method, you can place all values in a List, sort them and convert back to array.
public int[] SortArray(int[,] fromArray)
{
List<int> newList = new List<int>(fromArray.Length);
for (int b = 0; b < fromArray.GetUpperBound(1); b++)
{
for (int a = 0; a < fromArray.GetUpperBound(0); a++)
{
newList.Add (fromArray[a, b]);
}
}
newList.Sort();
return newList.ToArray<int>();
}

Splitting Array into new arrays and printing them with spaces

This program will sort numbers and depending if they are greater than or less than 100, put them into their own array.
The problem I have is printing this array. I would like the last number on the line, to not be followed by a space. I have tried many many times to get this to work now and figured I'd ask here.
I know of Console.Write("\b"); but I prefer to find a way of editing the loop so I don't have to do this. Here is the code:
using System;
using System.Linq;
class SplitArray
{
public static void Main(string[] args)
{
int[] myArray = GetNumbersFromConsole();
int[] smallNumbers = new int[myArray.Length];
int[] bigNumbers = new int[myArray.Length];
int bigIndex = 0;
int littleIndex = 0;
for (int i = 0; i < myArray.Length; i++)
{
if(myArray[i] > 100)
{
bigNumbers[bigIndex++] = myArray[i];
}
else if(myArray[i] < 100)
{
smallNumbers[littleIndex++] = myArray[i];
}
}
Console.Write("Big: ");
for (int i = 1; i < bigIndex; ++i)
{
Console.Write(bigNumbers[i]);
Console.Write(" ");
}
Console.WriteLine();
//Console.WriteLine($"{bigNumbers[0]}");
Console.Write("Little: ");
for (int i = 0; i < littleIndex; i++)
{
Console.Write($"{smallNumbers[i]}");
Console.Write(" ");
}
Console.ReadLine();
}
static int[] GetNumbersFromConsole()
{
int count = int.Parse(Console.ReadLine());
int[] result = new int[count];
for (int i = 0; i < count; ++i)
{
result[i] = int.Parse(Console.ReadLine());
}
return result;
}
}
You could just capture your Console.Write(" "); in an if statement.
if(i != littleIndex - 1)
{
Console.Write(" ");
}
littleIndex - 1 is the last time your loop executes, so this will just prevent it from adding the trailing white space. Just do the same for your big numbers as you're printing them out.
There is a builtin utility string.Join
var str = string.Join(" ",bigNumbers);
Console.WriteLine("Big: " + str);
I was playing around some more and just thought I'd try posting the first object in the array before running this loop (also changed loop so the first item didn't get printed twice).
Thank you everyone - I solved it! :)
using System;
using System.Linq;
namespace Arrays
{
class SplitArray
{
public static void Main(string[] args)
{
int[] myArray = GetNumbersFromConsole();
int[] smallNumbers = new int[myArray.Length];
int[] bigNumbers = new int[myArray.Length];
int bigIndex = 0;
int littleIndex = 0;
for (int i = 0; i < myArray.Length; i++)
{
if(myArray[i] > 100)
{
bigNumbers[bigIndex++] = myArray[i];
}
else if(myArray[i] < 100)
{
smallNumbers[littleIndex++] = myArray[i];
}
}
Console.Write("Big: ");
Console.Write($"{bigNumbers[0]} ");
for (int i = 1; i < bigIndex; i++)
{
Console.Write(bigNumbers[i]);
if (i != bigIndex - 1)
{
Console.Write(" ");
}
}
Console.WriteLine();
Console.Write("Little: ");
Console.Write($"{smallNumbers[0]} ");
for (int i = 1; i < littleIndex; i++)
{
Console.Write($"{smallNumbers[i]}");
if (i != littleIndex - 1)
{
Console.Write(" ");
}
}
Console.ReadLine();
}
static int[] GetNumbersFromConsole()
{
int count = int.Parse(Console.ReadLine());
int[] result = new int[count];
for (int i = 0; i < count; ++i)
{
result[i] = int.Parse(Console.ReadLine());
}
return result;
}
}
}

calling merge sort c#

I wrote a merge sort program, but I have problems calling It from another class. I need help. For some reason after I enter the size and the max number a get a black screen in the output. I believe that the solution is pretty easy, but I can't find the solution by myself
This is the class where It sorts the numbers
class MergeSort
{
public int[] Sort(int[] unsortedSequence)
{
int[] left;
int[] right;
int[] result = new int[unsortedSequence.Length];
if (unsortedSequence.Length <= 1)
return unsortedSequence;
int midPoint = unsortedSequence.Length / 2;
left = new int[midPoint];
if (unsortedSequence.Length % 2 == 0)
right = new int[midPoint];
else
right = new int[midPoint + 1];
for (int i = 0; i < midPoint; i++)
left[i] = unsortedSequence[i];
int x = 0;
for (int i = midPoint; i < unsortedSequence.Length; i++)
{
right[x] = unsortedSequence[i];
x++;
}
left = Sort(left);
right = Sort(right);
result = merge(left, right);
return result;
}
public static int[] merge(int[] left, int[] right)
{
int resultLength = right.Length + left.Length;
int[] result = new int[resultLength];
int indexLeft = 0, indexRight = 0, indexResult = 0;
while (indexLeft < left.Length || indexRight < right.Length)
{
if (indexLeft < left.Length && indexRight < right.Length)
{
if (left[indexLeft] <= right[indexRight])
{
result[indexResult] = left[indexLeft];
indexLeft++;
indexResult++;
}
else
{
result[indexResult] = right[indexRight];
indexRight++;
indexResult++;
}
}
else if (indexLeft < left.Length)
{
result[indexResult] = left[indexLeft];
indexLeft++;
indexResult++;
}
else if (indexRight < right.Length)
{
result[indexResult] = right[indexRight];
indexRight++;
indexResult++;
}
}
return result;
}
}
And this is the class where I'm trying to call the mergesort
class Program
{
static void Main(string[] args)
{
Console.Write("How Many Random Numbers Would you like to Generate : ");
int n = Convert.ToInt32(Console.ReadLine());
Console.Write("What is the Maximum Random Number Would you like to Generate : ");
int max = Convert.ToInt32(Console.ReadLine());
Console.Clear();
int[] unsortedSequence = generateRandomSequence(n, max);
MergeSort mergeSortEngine = new MergeSort();
int[] mergeSortedArray = mergeSortEngine.Sort(unsortedSequence);
Console.Write("Output for Merge Sort: \n\n");
OutputSequence(mergeSortedArray);
Console.WriteLine("\n\nPress Any Key to Continue...");
Console.ReadKey();
Console.Clear();
Because you didn't provide them, I wrote the missing generateRandomSequence() and OutputSequence methods in order to test your code and I can't reproduce your issue. Perhaps you should compare these to your own:
static int[] generateRandomSequence(int count, int max)
{
Random rn = new Random();
int[] seq = new int[count];
for (int i = 0; i < count; ++i)
{
seq[i] = rn.Next(0, max + 1);
}
return seq;
}
static void OutputSequence(int[] array)
{
for (int i = 0; i < array.Length; ++i)
{
if (i > 0)
{
Console.Write(", ");
}
Console.Write(array[i]);
}
Console.WriteLine();
}
Output from your code using the above methods:
It looks like you missing generateRandomSequence(n, max);
It might be like
public static int[] generateRandomSequence(int n, int max)
{
var rnd = new Random();
int[] seq = new int[n];
for (int ctr = 0; ctr < n; ctr++)
{
seq[ctr] = rnd.Next(1, max + 1);
}
return seq;
}
Then, in Program/Test class after Console.Write("Output for Merge Sort: \n\n"); you can iterate with foreach loop to display the sorted array.
foreach (var item in mergeSortedArray)
{
Console.WriteLine("{0}", item);
}
//OutputSequence(mergeSortedArray);

How do i return sum from a class

Im writing a program where the user writes how many times he want to throw x-number dice and how many sides they going to have.
But i cant figure out how to return the sum om the number on each dice game..
this is the main code:
static void Main(string[] args)
{
List<Dice> _Dice = new List<Dice>();
int a = 0;
int ggr = int.Parse(Interaction.InputBox("How many times do you want to repeat:"));
while (a != ggr)
{
int xChoice = int.Parse(Interaction.InputBox("How many dice do you want to throw:"));
int yChoice = int.Parse(Interaction.InputBox("Write how many sides the dice will have:"));
_Dice.Add(new Dice(xChoice,yChoice));
a++;
}
int e = 1;
foreach (var item in _Dice)
{
Interaction.MsgBox(string.Format("Result off game {0}: {1}", e++, item.ToString()));
}
}
This is the Dice class:
static int _xChoice, _yChoice;
static int[,] dice = new int[_xChoice, _yChoice];
public int Tostring()
{
int a = 0;
foreach (var item in dice)
{
a+=item;
}
return a;
}
void throw()
{
Random r = new Random();
for (int i = 0; i <dice.GetLength(0); i++)
{
for (int j = 0; j < dice.GetLength(1); j++)
{
dice[i, j] = r.Next(1, _yChoice);
}
}
}
public Dice(int Xchoice, int Ychoice)
{
_xChoice = Xchoice;
_yChoice = Ychoice;
}
Just for completeness, what you are asking for is the sum of items of a 2D array:
int total = Enumerable.Range(0, _xChoice).Sum(s => Enumerable.Range(0, _yChoice).Sum(p => dice[s, p]));
Well you can do it like this:
void throw()
{
Random r = new Random();
for (int i = 0; i <dice.GetLength(0); i++)
{
int totalSum = 0;
for (int j = 0; j < dice.GetLength(1); j++)
{
dice[i, j] = r.Next(1, _yChoice);
totalSum += dice[i, j];
}
// Here you display totalSum for game with index i.
}
}

Categories