Looking for a way to shorten my code - c#

This is my code:
static void Main(string[] args)
{
Console.Write("How many tests would you like to do? 1 to 10: ");
int tests = Convert.ToInt32(Console.ReadLine());
Console.WriteLine();
}
can someone help me out with my code please? i have no idea what im doing
Thanks

Make an array int[] counts = new int[13] and just use counts[total]++;; at the end, loop over it:
for(int i = 2 ; i <= 12 ; i++)
// etc
(note: you could use an array of 11 items and constantly handle the off-by-two, but... it probably isn't worth it)
Something like:
static void Main()
{
Console.WriteLine("Investigation 1");
Console.WriteLine("===============");
Console.WriteLine();
Console.Write("How many sets of tests? 1 to 10: ");
int sets = Convert.ToInt32(Console.ReadLine());
Console.WriteLine();
Random r = new Random();
int[] counts = new int[13];
for (int ctr = 0; ctr < 36 * sets; ctr++)
{
int a = r.Next(1, 7), b = r.Next(1, 7), total = a + b;
Console.WriteLine($"Roll {(ctr + 1)}: {a} + {b} = {total}");
counts[total]++;
}
Console.WriteLine("=======================");
Console.WriteLine();
Console.WriteLine("Total Expected Actual");
Console.WriteLine("===== ======== ======");
for(int i = 2; i <= 12; i++)
{
var expected = sets * (6 - Math.Abs(7 - i));
Console.WriteLine($" {i} {expected} {counts[i]}");
}
}
For a histogram:
var maxCount = counts.Max(); // needs "using System.Linq;" at the top
for (int i = 2; i <= 12; i++)
{
var width = ((Console.WindowWidth - 10) * counts[i]) / maxCount; // make it proportional
Console.WriteLine($"{i}\t{new string('*', width)}");
}

Related

Misunderstanding With If and Else

I'm new to C# and would like some help!
I am working on some code that allows the user to find out if specific cows on his farm aren't producing enough milk.
On line 75 the if statement is supposed to print out the cows that 'are not good enough' or Tell the user that everything is OK. But instead it permanently try's to print the Bad Cows.
Console.WriteLine("How many cows are in your herd?");
int CowNum = int.Parse(Console.ReadLine());
int Temp;
double TempD;
string TempS;
int MinimumVal = 6;
int MDIR = 4;
string[] BadList = new string[CowNum];
int[] Counter = new int[CowNum];
double[] Total = new double[CowNum];
string[] Days = new string[7] {"Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"};
string[] CowID = new string[CowNum];
double[,] CowYield = new double[CowNum, 7];
Random r = new Random();
for (int n = 0; n < CowNum; n++) // Sets Cow ID's
{
Console.WriteLine("What is the ID of Cow: " + (n + 1) + "?" );
TempS = (Console.ReadLine());
CowID[n] = TempS;
}
for (int n = 0; n < CowNum; n++) // Sets the Yield of each cow to a certin day
for (int x = 0; x < Days.GetLength(0); x++)
{
Console.WriteLine("What was the Yeild for Cow: " + CowID[n] + " on " + Days[x] + "?");
TempD = double.Parse(Console.ReadLine());
CowYield[n, x] = TempD;
if (TempD < MinimumVal)
{
Counter[n] = Counter[n] + 1;
Console.WriteLine(Counter[n]);
}
//Console.WriteLine("What was the Yeild for Cow: " + CowID[n] + " on " + Days[x] + "?"); //Randomly Generated 'Saves Time'
//Temp = r.Next(0, 20);
//Console.WriteLine(Temp);
//CowYield[n, x] = Temp;
}
for (int n = 0; n < CowNum; n++)
for (int x = 0; x < Days.GetLength(0); x++)
Total[n] = Total[n] + CowYield[n, x];
for (int n = 0; n < CowNum; n++)
{
if (Counter[n] > MDIR)
{
BadList[n] = CowID[n];
Console.WriteLine("asd" + BadList[n]);
}
}
int index = Array.IndexOf(Total, Total.Max()); // Gets index of Highest producing cow
TempS = CowID[index];
Console.WriteLine("\nThe Highest producing cow is Cow: " + TempS + ". with a whopping " + Total[index] + "L of Milk!\n");
if (BadList.GetLength(0) > 0)
{
Console.WriteLine(BadList.GetLength(0));
for (int n = 0; n < BadList.GetLength(0); n++)
{
Console.WriteLine(BadList[n]);
}
}
else
{
Console.WriteLine("None of your cows had less than 6L of milk for four or more days in a row!");
}
Console.ReadLine();
}
In short your code fails beause
(For ease of all of us, heres a simplified one)
string[] thing = new string[200]
if (thing.Length>0)
{ Console.WriteLine("All wrong");}
else
{ Console.WriteLine("OK");}
Your Length of thing is always 200 because you made it that big. So output is always "All wrong"
However if you had
List<String> thing = new List<String>();
//process list here, and use thing.Add(badcow)
if (thing.Count() >0 )
{ Console.WriteLine("All wrong");}
else
{ Console.WriteLine("OK");}
then it will work because there maybe 0 entries in the list. It may produce both answers and will pick as you expected.

Creating a frequency table of dice occurrences in C#

I am fairly new at programming and am currently picking up C#.
What I have is two dice rolled at random for 50 rolls
Both dice totals added together to give a sum for each roll.
My question is, how can I create a frequency table that will count the amount of times a certain number is rolled at the end of 50 dice rolls.
Below is what I am trying to achieve. Tally chart of each number rolled (from both dice)
1: |||
2: ||||
3: ||||||
4: |||||
5: ||||||||
6: ||
Here is my code so far,
class Program
{
const int DICE_ROLLS = 51;
static void Main(string[] args)
{
Random random = new Random();
int[] firstDice = new int[DICE_ROLLS];
int[] secondDice = new int[DICE_ROLLS];
int diceSum = 0;
for (int roll = 1; roll <= 50; roll++)
{
firstDice[roll] = GenerateNumber(random);
secondDice[roll] = GenerateNumber(random);
diceSum = firstDice[roll] + secondDice[roll];
Console.WriteLine("ROLL {0}: {1} + {2} = {3}", roll, firstDice[roll], secondDice[roll], diceSum);
}
Console.WriteLine();
Console.WriteLine("~~~~~~~~~~~~~~~~");
Console.WriteLine("Number Frequency");
}
static int GenerateNumber (Random random)
{
return random.Next(1, 7);
}
}
Try this:
const int DICE_ROLLS = 51;
static void Main(string[] args)
{
Random random = new Random();
int[] firstDice = new int[DICE_ROLLS];
int[] secondDice = new int[DICE_ROLLS];
int[] count = new int[6];
int diceSum = 0;
for (int roll = 0; roll <= DICE_ROLLS - 1; roll++)
{
firstDice[roll] = GenerateNumber(random);
secondDice[roll] = GenerateNumber(random);
diceSum = firstDice[roll] + secondDice[roll];
Console.WriteLine("ROLL {0}: {1} + {2} = {3}", roll + 1, firstDice[roll], secondDice[roll], diceSum);
}
Console.WriteLine();
Console.WriteLine("~~~~~~~~~~~~~~~~");
Console.WriteLine("Number Frequency");
var allRolls = firstDice.Concat(secondDice).ToList();
for(var i = 1; i <= 6; i++)
{
Console.Write(i + ": ");
for(var j = 0; j < allRolls.Count(c => c == i); j++)
Console.Write("|");
Console.WriteLine();
}
}
static int GenerateNumber (Random random)
{
return random.Next(1, 7);
}
Gives:
~~~~~~~~~~~~~~~~
Number Frequency
1: ||||||||||||||||||||
2: |||||||||||
3: ||||||||||||||||||
4: ||||||||||||||||
5: |||||||||||||||||||||
6: ||||||||||||||||
Assuming 6 sided dice, a Dictionary might be a good option.
var rolls = new SortedDictionary<int, int> { {1,0}, {2,0}, {3,0}, {4,0}, {5,0}, {6,0} };
for(int i = 0; i < 50; i++)
{
var first = Random.Next(1, 7);
var second = Random.Next(1, 7);
rolls[first]++;
rolls[second]++;
// Rest of rolling display code
}
// Header display code
foreach(var roll in rolls)
{
Console.Write("{0}: ", roll.Key);
for(int i = 0; i < rolls.Value; i++)
{
Console.Write("|");
}
Console.WriteLine();
}
You could even easily customize it based on different sided dice by generating the initial dictionary values based on a variable like
int sides = 12;
var rolls = new SortedDictionary<int, int>();
foreach(var value in Enumerable.Range(1, sides))
{
rolls.Add(value, 0);
}
The you could replace the Random.Next(1, 7) with Random.Next(1, sides) and have a pretty generic program for rolling dice and counting their frequency.
This works:
var rnd = new Random();
Console.WriteLine(
String.Join(
Environment.NewLine,
Enumerable
.Range(0, 50)
.Select(n => rnd.Next(1, 7))
.ToLookup(x => x)
.Select((xs, n) =>
String.Format("{0}: {1}", n + 1, new String('|', xs.Count())))));
I get this (for example):
1: |||||||
2: |||||||
3: |||||||||||
4: |||||||||
5: ||||||||
6: ||||||||

C# console application that can find every combination of some numbers but only writes if they can divide by 3

I have to perform a task. pls help me. İ want a c sharp console application that can find every combination of some numbers but only writes if they can divide by 3.
We have 15 card in a bag. we will take 3 cards randomly(without replacement) . After that we will add them(card1+card2+card3) and if their result can divide by 3 then we will write them to console.[(card1+card2+card3)/3]=0
Not sure where to begin with this. Any help is greatly appreciated!
You can get some idea from this I think.
public List<int[]> getCombinations(int[] inArray)
{
List<int[]> outList = new List<int[]>();
for (int i = 0; i < inArray.Length; i++)
for (int j = i + 1; j < inArray.Length; j++)
for (int k = j + 1; k < inArray.Length; k++)
{
int[] outCombination = new int[] { inArray[i], inArray[j], inArray[k] };
outList.Add(outCombination);
}
return outList;
}
static void Main(string[] args)
{
int[] inArray = new int[] { 0, 1, 2, 3, 4, 5 };
// Returned list of combinations...
Program ns = new Program();
List<int[]> Combinations = ns.getCombinations(inArray);
// example: Displaying the results...
foreach (int[] outArray in Combinations)
{
Console.Write(outArray[0] + "," + outArray[1] + "," + outArray[2]);
}
}
Given 3 numbers, you can tell if they are divisible by 3 using the modulus operator:
List<int> numbers = new List<int> {4, 8, 11}; // Represents three random cards
// This will be set to true if the sum of the numbers is evenly divisible by 3
bool numbersAreDivisibleByThree = numbers.Sum() % 3 == 0;
Here is an example of how this could be used:
private static void Main()
{
var cardBag = new List<int>();
var drawnCards = new List<int>();
// Add 15 numbers to the cardBag
for (int i = 1; i <= 15; i++)
{
cardBag.Add(i);
}
// Draw 3 cards at random
var rnd = new Random();
while (drawnCards.Count < 3)
{
var candidateCard = cardBag[rnd.Next(15)];
// In this implementation, we only add unique cards
if (!drawnCards.Contains(candidateCard))
drawnCards.Add(candidateCard);
}
// This will be set to true if the sum of the numbers is evenly divisible by 3
bool numbersAreDivisibleByThree = drawnCards.Sum() % 3 == 0;
// Output results to console
Console.WriteLine("The three random cards drawn from the deck are: {0}",
string.Join(", ", drawnCards));
Console.WriteLine("The sum of the cards is: {0}", drawnCards.Sum());
Console.WriteLine("Is the sum of the cards evenly divisible by three? {0}.",
numbersAreDivisibleByThree);
}
Since you seem like a noob, here is an easy way of looking at it (although not the most efficient and least costly):
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace RandomGeneratorPractice
{
class Program
{
static void Main(string[] args)
{
Random random = new Random();
int randomNumber1 = random.Next(1, 15);
int randomNumber2 = random.Next(1, 15);
int randomNumber3 = random.Next(1, 15);
bool bln = true;
while(bln)
{
if (randomNumber1 == randomNumber2)
{
randomNumber2 = random.Next(1, 15);
bln = true;
}
else if (randomNumber2 == randomNumber3 || randomNumber1==randomNumber3)
{
randomNumber3 = random.Next(1,15);
bln = true;
}
else if ((randomNumber1 != randomNumber2) && (randomNumber1 != randomNumber3) && (randomNumber2 != randomNumber3))
{
bln = false;
}
}
int dividend = randomNumber1 + randomNumber2 + randomNumber3;
double divisor = 3;
double quotient = (randomNumber1 + randomNumber2 + randomNumber3) / 3;
Console.WriteLine("(" + randomNumber1 + "+" + randomNumber2 + "+" + randomNumber3 + ") / 3 = " + (dividend / divisor));
if (dividend % divisor == 0)
{
Console.WriteLine("You CAN divide by 3 evenly");
}
else
{
Console.WriteLine("You CANNOT divide by 3 evenly");
}
Console.WriteLine("Press ENTER to exit...");
Console.Read();
}
}
}

How do I print the output in one row below another?

For example I am trying to print the output in following way:
disk: 1 2 3 4 5
move: 1 3 7 15 31
How can I do that, can someone help me out please?
{
class Program
{
static void Main(string[] args)
{
int n = 2;
for (int j = 1; j <= 5; j++)
Console.WriteLine("disk: {0}", j);
for (int i = 1; i <= 5; i++)
Console.WriteLine("moves: {2:N0}",
n, i,(long)Math.Pow(n, i) - 1);
}
}
}
Console.WriteLine will, as it sounds, write a new line each time. If you don't want that behavior, use Console.Write.
Console.Write("Disk:");
for (int j = 1; j <= 5; j++)
Console.Write(" {0}", j);
Console.WriteLine();
Console.Write("Moves:");
for (int i = 1; i <= 5; i++)
Console.Write(" {2:N0}", (long)Math.Pow(n, i) - 1);
Console.WriteLine();
Use the string.PadLeft() method to justify your text. Of course you can replace the magic numbers with a constant value. This gives you the advantage of not having to count spaces, and automatically adds the right amount of spaces to bring the string up to the desired length.
Note that you can also get rid of the format insertion (i.e. no more curly braces).
static void Main(string[] args)
{
int power = 2;
Console.Write("disk:".PadLeft(8));
for (int j = 1; j <= 5; j++)
Console.Write(j.ToString().PadLeft(5));
Console.WriteLine();
Console.Write("moves:".PadLeft(8));
for (int i = 1; i <= 5; i++)
Console.Write(((long)Math.Pow(power, i) - 1).ToString().PadLeft(5));
Console.WriteLine();
Console.ReadLine();
}
This is the result:
You can use Console.Write and it wont print a carriage return.
However you dont need a for loop in this case. Just use Enumerable.Range
var n = 2;
var disks = Enumerable.Range(1, 5).ToList();
var moves = Enumerable.Range(1, 5).Select(i => (long) Math.Pow(n, i) - 1);
Console.WriteLine("disk: {0}", string.Join(" ", disks));
Console.WriteLine("moves: {0:N0}", string.Join(" ", moves));
Results:
disk: 1 2 3 4 5
moves: 1 3 7 15 31

Finding minimum of several integers

In a program that requires the user to input the number of integers, I cannot find out how to display the minimum of all the values.
static void Main(string[] args)
{
Console.WriteLine("\n Number of values:");
int num = Convert.ToInt32(Console.ReadLine());
int[] number = new int[num];
int i;
for (i = 0; i < number.Length; i++)
{
Console.WriteLine("\n Enter value:");
number[i] = Convert.ToInt32(Console.ReadLine());
}
for (i = 0; i < number.Length; i++)
{
int Min = number[0];
if (number[i + 1] < Min)
{
Min = number[i + 1];
}
}
Console.WriteLine("Smallest is {0}", Min);
}
Declare Min outside for loop
int Min = number[0];
for (i = 1; i < number.Length; i++)
{
if (number[i] < Min)
{
Min = number[i];
}
}
There are methods that do this for you:
int[] number = new int[num];
int min = number.Min();
Use this:
int minNumber = numbers.Min();
You can use the Min method to calculate this.
int min = number.Min();
public static int FindMinimum(int[] values)
{
int result = int.MaxValue;
foreach (int value in values)
result = Math.Min(result, value);
return result;
}
Your current code will overflow the array. You should check index 0 first and then check the rest.
Replace
for (i = 0; i < number.Length; i++)
{
int Min = number[0];
if (number[i + 1] < Min)
{
Min = number[i + 1];
}
}
with
int Min = number[0];
for (i = 1; i < number.Length; i++)
{
if (number[i] < Min)
{
Min = number[i];
}
}
However, you could simply use Enumerable.Min() as int Min = number.Min(x => x)
how about this?!
int[] Numbers = new int[5] { 3, 5, 7, 9, 11, 15 };
var q = (from Num in Numbers
select Num).Min();
Have a look at LINQ samples from MSDN: http://code.msdn.microsoft.com/101-LINQ-Samples-3fb9811b
you can use linq to object.
use Min method
sort your data in descending and take the first one
Declare Min as global static for example - public static int Min
Change the loop condition to for (i = 0; i < number.Length -1 ; i++) you exceed by one index range
Put Console.ReadLine on the end.
Or you don't have to store all numbers
static void Main(string[] args)
{
int min = int.MaxValue;
Console.WriteLine("\n Number of values:");
int num = Convert.ToInt32(Console.ReadLine());
var enteredValue = 0;
for (var i = 0; i < num; i++)
{
Console.WriteLine("\n Enter value:");
enteredValue = Convert.ToInt32(Console.ReadLine());
if (min>enteredValue) min = enteredValue;
}
Console.WriteLine("Smallest is {0}", min);
Console.ReadLine();
}

Categories