How to get an element from list of list - c#

I wrote program and I used in that program a list of lists (in int type).
Every list in the big list stores a different number of integers but when I try to approach those integers and use them for division I don't know how.
That's the program:
Console.WriteLine("How many students in the class?");
int students = int.Parse(Console.ReadLine());
List<List<int>> studentsclass = new List<List<int>>();
for (int i = 0; i < students; i++)
{
Console.WriteLine("How many jumps student number " + (i + 1) + " did?");
int studentjumps = int.Parse(Console.ReadLine());
Console.WriteLine("Write student number " + (i+1) + " high jumps: ");
List<int> jumps= new List<int> (studentjumps);
for (int j = 0; j < studentjumps; j++)
{
jumps.Add(int.Parse(Console.ReadLine()));
}
}
for (int k = 0; k < studentsclass.Count; k++)
{
int sum = 0;
for (int m = 0; m < studentsclass[m].Count; m++)
{
(That is a program that calculates student's average high jumps).
The rest of the code should be: sum = sum\index M of index K of the list.
Edit:
I continued my code and then when it came to the division part I've got lots of errors.
this is what I wrote:
for (int k = 0; k < studentsclass.Count; k++)
{
double sum = 0;
for (int m = 0; m < studentsclass[m].Count; m++)
{
sum = sum + studentsclass[k][m];
}
sum = (double)sum \ studentsclass[m]; \\<-- Error
Console.WriteLine("student number " + (k + 1) + " did an average of " + sum + " meter high jumps");
}

simply use.
studentsclass[k][m]
to access the inner list
and use
studentsclass[k].Count
in your second for loop

Using LINQ you can do somthing like the following to get your desired result:
var result = studentsclass.Select((l, i) => new { Id = i, Average = l.Average() });
See THIS fiddle.

Related

Comparison of grades of students and Coins distributions

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 coins than both of them. For example:
Data input:
3
John
Dan
Sam
9
10
8
Data output:
John 1
Dan 3
Sam 1
My output is just the names of the students.
I wrote this code:
using System;
class Program
{
private static void Main(string[] args)
{
int n = Convert.ToInt32(Console.ReadLine());
var numberCoins = new int[n];
string[] studentNames = new string[n];
numberCoins[0] = 1;
for (int i = 0; i < n; i++)
{
studentNames[i] = Console.ReadLine();
}
int[] grades = new int[n];
for (int i = 0; i < n; i++)
{
grades[i] = Convert.ToInt32(Console.ReadLine());
}
for (int i = 1; i < n; i++)
{
if (grades[i] > grades[i - 1])
{
numberCoins[i] = numberCoins[i - 1] + 1;
}
}
for (int i = n - 2; i >= 0; i--)
{
if (grades[i] > grades[i + 1])
{
numberCoins[i] = numberCoins[i + 1] + 1;
}
}
for (int i = 0; i < n; i++)
{
Console.WriteLine(studentNames[i], " ", numberCoins[i]);
}
Console.ReadLine();
}
}
You didn't mention if there is any pattern to give coins to the students. And if we have specific number of coins or not.
If we consider at first no one has any coins the result must be something like the following:
Please specify the number of the students:
3
Please write students' name (after each name hit the ENTER):
John
Dan
Sam
Please write students' ratings (after each rating hit the ENTER):
9
10
8
The result:
John: 0
Dan: 2
Sam: 0
I wrote a piece of code which might help you approach the functionality you want.
using System;
class Program
{
public static void Main(string[] args)
{
Console.WriteLine("Please specify the number of the students:");
int n = int.Parse(Console.ReadLine());
string[] studentNames = new string[n];
int[] studentRatings = new int[n];
int[] studentCoins = new int[n];
Console.WriteLine();
Console.WriteLine("Please write students' name (after each name hit the ENTER):");
for (int i = 0; i < n; i++)
{
studentNames[i] = Console.ReadLine() ?? string.Empty;
}
Console.WriteLine();
Console.WriteLine("Please write students' ratings (after each rating hit the ENTER):");
for (int i = 0; i < n; i++)
{
studentRatings[i] = int.Parse(Console.ReadLine());
}
Console.WriteLine();
Console.WriteLine("The result:");
for (int i = 0; i < n; i++)
{
int coins = 1;
studentCoins[i] = 0;
if (i != 0)
if (studentRatings[i] > studentRatings[i - 1])
coins++;
if (i != n - 1)
if (studentRatings[i] > studentRatings[i + 1])
coins++;
studentCoins[i] = coins;
}
for (int i = 0; i < n; i++)
{
Console.WriteLine($"{studentNames[i]}: {studentCoins[i]}");
}
}
}

Sums not being calculated right

Hi i am trying to calculate the sums of the submatrix of order K from a matrix of order M, but I am getting wrong result from the sums matrix. In my head the logic makes sense, I don't know what the mistake is.
static void Main(string[] args)
{
Console.WriteLine("Shkruani te madhesine e matrices dhe madhesine e submatrices: ");
int M;
int K;
int sum = 0;
M = int.Parse(Console.ReadLine());
K = int.Parse(Console.ReadLine());
int[] sums = new int[M - K + 1];
int[] matrix = new int[M];
Console.WriteLine("Shkruani vlerat e matrices: ");
foreach (int i in matrix)
{
matrix[i] = int.Parse(Console.ReadLine());
}
for (int i = 0; i <= M - K; i++)
{
for (int j = 0; j < K; j++)
{
sum += matrix[i + j];
}
sums[i] = sum;
sum = 0;
}
for (int i = 0; i < (M - K + 1); i++)
{
Console.WriteLine(sums[i]);
}
Console.ReadKey();
}
Instead of using
foreach (int i in matrix)
{
matrix[i] = int.Parse(Console.ReadLine());
}
Use this:
for (int i = 0; i < matrix.Length; i++)
{
matrix[i] = int.Parse(Console.ReadLine());
}
Explanation:
Because For-Each loop works with value (iterate through value) instead of index (May be what you want) while for loop works with index (iterate through index).
Hope this helps.
Thank you.

Bubble sorting issues

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

C# dice game logic errors

I'm learning C# are I am writing a program that makes an array fills it with 50 random numbers1-6 like dice and then checks how many times each value or 'side' comes up. I made a dice game in python earlier in the week and I had a lot of trouble so I made i= j= and match= print outs to test if the loops and matching were iterating correctly, so I did the same here and I noticed a few logic errors:
the i loop seems to iterate fine but for every 1 iteration of i, j should iterate 50 times but i only get it once.
The i OR j loops don't iterate at all unless in line 47 it states while j > dice.Length. Writing as it should be j < dice.Length makes it not iterate at all. The 50 random numbers display on screen so i know dice is 50 in length and j is 0.
Thirdly in line 50 if dice[i] == dice[j] I get an error that j isn't valid unless I declare j above the for loop, and if I do that I can't do int j = 0 in the for loop, so I scrapped the for loop and did a while loop, but it still only adds a value for the first match and not the next possible 49.
I am only coding inside the static void since it's a simple console application, thank you for your help.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace wk8hw2
{
class Program
{
static void Main(string[] args)
{//staticvoid
int size = 50;
int diceSides = 7;
int matchAdd = 0;
int[] dice = new int[size];
int[] match = new int[diceSides];
Random rnd = new Random();
int j = 0;
Console.WriteLine("Press any key to roll the dice " + size + " times.");
Console.ReadKey();
for (int i = 0; i < dice.Length; i++)//roll dice
{
dice[i] = rnd.Next(1, diceSides);
}
for (int i = 0; i < dice.Length; i++)//show dice
{
Console.Write(dice[i] + " ");
}
Console.WriteLine("done showing dice");//DEBUG
for (int i = 0; i < dice.Length; i++)//outer match loop
{
Console.Write("i = " + i);//DEBUG
if (match[dice[i]] == 0)//if not matched add to match array
{
Console.WriteLine("not yet matched");
matchAdd = 1;
}
else//if alerady matched add no more
{
Console.WriteLine("already matched");
matchAdd = 0;
}
j = 0;
while (j > dice.Length)//inner match loopSUPPOSED TRO BE LESS THAN
{
Console.WriteLine("j = " + j);
if (dice[i] == dice[j])//if equal add to match array
{
match[dice[i]] = match[dice[i]] + matchAdd;
Console.WriteLine("val " + match[dice[i]]);
}
j++;
}
}//endFORouter
for (int i = 1; i < match.Length; i++)
{
Console.WriteLine(i + " came up " + match[i] + " times.");
}
Console.ReadKey();
}//endstaticvoid
}
}
I agree with the first answer however...you said you are learning C# and based on the namespace this is a homework assignment and you are most likely learning about arrays so I would rewrite it a bit different
You seem to be doing way to many loops and generally doing to much. Make your code as simple as possible and name your variables to tell anyone reading the code what they do.
int numberOfRolls = 50;
int diceSides = 6;
int[] dice = new int[numberOfRolls];
int[] match = new int[diceSides];
Random random = new Random();
Console.WriteLine("Press any key to roll the dice " + numberOfRolls + " times.");
Console.ReadKey();
for (int rollCount = 0; rollCount < numberOfRolls; rollCount++)
{
var rollResult = random.Next(1, diceSides+1);
match[rollResult-1]++;
}
for (int i = 0; i < match.Length; i++)
{
Console.WriteLine(i+1 + " came up " + match[i] + " times.");
}
Console.ReadKey();
I'd rewrite this whole thing as:
Random rnd = new Random();
const int diceSides = 6;
const int numDice = 50;
Console.WriteLine("Press any key to roll the dice {0} times.", numDice);
Console.ReadKey();
var diceByValue = Enumerable.Range(0, numDice)
.Select(_ => rnd.Next(diceSides) + 1)
.GroupBy(v => v)
.OrderBy(g => g.Key);
foreach (var group in diceByValue)
Console.WriteLine("{0} came up {1} times.", group.Key, group.Count());

total sum of 2d array values c#

Hi guys i am trying to create a retrieve method to retrieve a sum total of my 2d array values i have built the array to fill from user input but not sure how to total all array values as i am still learning.
public int[,] ToysMade = new int[4, 5];
public String[] days = new String[] { "Monday", "Tuesday", "Wednesday", "Thursday", "Friday" };
public void UserInput()
{
String value;
int numCount;
//retrieveing length of ToysMade array dimensions if less than 0 repeat untill last dimension filled
for (int i = 0; i < ToysMade.GetLength(0); i++)
{
for (int ii = 0; ii < ToysMade.GetLength(1); ii++)
{
//taking user input for array dimension 0 "first dimension" then increment it by 1 after input ready for next dimension "i + 1"
value = Microsoft.VisualBasic.Interaction.InputBox("Enter Value For " + days[ii] + " of week " + (i + 1).ToString() + " Enter Value");
try
{
//making sure for only int past through
while (!(int.TryParse(value, out numCount)))
{
MessageBox.Show("Not a valid number, please try again.");
value = Microsoft.VisualBasic.Interaction.InputBox("Enter Value for " + days[i] + " of week " + (i + 1).ToString() + " Enter Value");
}
// taking values enterd from user and set next dimension for next input by incrementing it
ToysMade[i, ii] = numCount;
}
catch (Exception e)
{
MessageBox.Show("Value enterd is not in a valid format");
}
}
}
}
I suggest put either simple foreach loop
int total = 0;
foreach (var item in ToysMade)
total += item;
or nested loops which are typical for 2d arrays
int total = 0;
for (int i = 0; i < ToysMade.GetLength(0); i++)
for (int j = 0; j < ToysMade.GetLength(1); j++)
total += ToysMade[i, j];
You can use Linq by creating an IEnumerable<int>from ToysMade;
var total = ToysMade.Cast<int>().Sum();
Thanks guys awesome works thanks heaps again
public void Sum()
{
int total = 0;
for(int i = 0;i < ToysMade.GetLength(0); i++)
{
for(int j = 0;j < ToysMade.GetLength(1); j++)
{
total += ToysMade[i, j];
}
}
txtOutput.Text += "\r\nThe sum of products is: " + total.ToString();
}

Categories

Resources