get max odd number - c#

class Program
{
static void Main(string[] args)
{
Random rnd = new Random();
int[] mass = new int[10];
for (int i = 0; i < mass.Length; i++)
{
mass[i] = rnd.Next(0, 10);
}
Console.WriteLine("display random Massive: \n");
foreach (var i in mass)
{
Console.Write("{0} ", i);
}
Console.WriteLine("\n");
int max = mass.Max();
Console.WriteLine("max value in Massive = {0}", max);
Console.ReadLine();
}
}
my code gives me max value in massive, I need get max odd value. How to get max odd value?

You can use Linq to do this easily
mass.Where (x => x % 2 != 0).Max ();

You can do this easier using linq:
static void Main(string[] args)
{
Random rnd = new Random();
int[] mass = Enumerable.Range(0, 10).Select(i => rnd.Next(0, 10)).ToArray();
Console.WriteLine("display random Massive: ");
Console.WriteLine(string.Join(" ", mass));
Console.WriteLine();
int max = mass.Where(i => (i & 1) == 1).Max();
Console.WriteLine("max value in Massive = {0}", max);
Console.ReadLine();
}
Explanations:
I initialize the array by generating 10 random numbers, converting them to an array
I output them using string.Join
using Where with testing that the last bit is set filters for odd numbers
calling Max on only these odd numbers.
Note that you don't need to use \n as Console.WriteLine adds a new line at the end.

just change
int max = mass.Max();
to
int max = mass.Where(x=>(x%2)==1).Max();

I am asuming you're a beginner like me and don't understand linq yet
Declare a list for holding odd values
List<int> oddList = new List<int>();
Then in your foreach method
foreach (var i in mass)
{
if (i % 2 != 0) //check that number is odd
{
oddList.Add(i); //add odd randoms to list
{
}
Console. WriteLine(oddList.Max().ToString());

Related

C#: Generate 100 random numbers between 1-1000 and output the max value

I'm very new to coding and I just can't wrap my head around Loops/Arrays/Randoms. I understand the concept but when it comes to applying it, I'm just lost.
Here I'm trying to generate 100 random numbers between 1-1000 and it has to output the maximum value. Here's my code so far:
Random rnd = new Random();
int nums = rnd.Next(0, 1001);
for (int i = 1; i <= 100; i++)
{
}
Console.WriteLine(nums);
Console.ReadLine();
It's only giving me one number. :(
I'd greatly appreciate any help!
Thanks!
You can accumulate your random generated number to the array and then by using Max function of the array you can find the maximum value
class Program
{
public static void Main(string[] args)
{
Random rnd = new Random();
int[] intArr = new int[100];
for (int i = 0; i < intArr.Length; i++)
{
int num = rnd.Next(1, 1000);
intArr[i] = num;
Console.WriteLine(num);
}
Console.WriteLine();
int maxNum = intArr.Max();
Console.WriteLine("The max num is:" + maxNum);
Console.ReadLine();
}
}
Click to watch online demo
You need to call rnd.Next() inside loop.
Random rnd = new Random();
for (int i = 1; i <= 100; i++)
{
int nums = rnd.Next(0, 1001);
Console.WriteLine(nums);
}
Console.ReadLine();
A good approach would be initializing a variable that stores your max. Then generate a random number within your iterative block and if it is greater than your max, set it as the new max.
Random r = new Random();
int max = 0; //declare our max variable
for(int i = 0; i < 100; i++)
{
int rand = r.Next(0, 1001);
if(rand > max) //if the new random value is greater than our max, set max = rand
max = rand;
}
Console.WriteLine(max); //Output the maximum value
Console.ReadLine();
If you want to output every random value and then output the max out of all the values generated, simply modify the code above by outputting rand within your loop as well.
Hope this helps!
I am not sure, are you asking like this?
Random random = new Random();
int[] nums = new int[100];
// when for loop ends, nums are full of 100 numbers
for (int i = 0; i < nums.Length; i++)
{
int newNum = random.Next(1, 1000);
// show every number
Console.WriteLine(newNum);
nums[i] = newNum;
}
// get the max number
var maxNum = nums.Max();
Console.WriteLine(maxNum);
If you want to see the code for Loops/Arrays/Randoms all working together you can use the below with the comments walking through what each line is doing (Working .NET Fiddle Example)
public static void Main()
{
// Pass in what range we want our randomly generated numbers to be in
// In your case, between 1 - 1000 and we want to create 100 of them.
//(See GenerateRandomNumbers())
var random = GenerateRandomNumbers(1, 1000, 100);
//Take our newly returned randomly created numbers and
//pass them to our GetMaxNumber method so it can find the Max number
//See (GetMaxNumber())
var result = GetMaxNumber(random);
//We now have our max number; print it to the Console.
Console.WriteLine("Max: " + result);
}
public static int GetMaxNumber(params int[] inputs)
{
//Create a variable that will store the largest number we find in our array
int max = inputs[0];
//Iterate (loop) through all of the 100 values in our array that we passed in
//Here we define "input" which will hold the value for each value in inputs as we check
//if the value of input is greater than our current value of max. If it is greater than our
//current value of max, then we need to update max to now be equal to the value of our input.
//Note: it will do this comparison 100 times beginning with the first value in the inputs array
foreach (var input in inputs)
{
if (input > max)
{
//input's value is greater than the current value of max; update max so that it is equal to the current value of input.
max = input;
}
//no more code; return to top of foreach loop and set input to the next value in inputs
}
//When we get here, it means our foreach loop has completed going through and comparing all 100 values of inputs to see which value is the largest.
//now return this value to Main()
return max;
}
public static int[] GenerateRandomNumbers(int beginRange, int endRange, int maxNumbers)
{
// Instantiate random number generator
Random rnd = new Random();
//Generate and display
int[] intArr = new int[maxNumbers];
//Generate 100 numbers with numbers between 1 and 1000
for (int i = 0; i < intArr.Length; i++)
{
int num = rnd.Next(beginRange, endRange);
intArr[i] = num;
}
return intArr;
}

C# Random number generator, to display in MessageBox

I'm trying to create a random number generator, ranging from 1 to 1000 for 100 times to achieve the following results on both Console App and popup Windows Message Box (MessageBox.Show) in this format:
100 random numbers in order from smallest to largest
Amount of even numbers generated
Smallest number generated
Largest number generated
The range of numbers
I'm confused at creating the array to store the value and getting the amount of even numbers generated with what I have here, say for example my array name would be "array" and to store the numbers with "n"
string [] array = {item};
string output = string.Join("\n", array);
MessageBox.Show(output)
This is my code, how do I add this in?
using System;
using System.Collections.Generic;
using System.Text;
using System.Windows.Forms;
namespace NumberGenerator
{
class Program
{
static void Main(string[] args)
{
Random number = new Random();
int min = int.MaxValue,
max = int.MinValue;
for (int counter = 0; counter < 100; counter++)
{
int n = number.Next(0, 999);
Console.WriteLine(n);
if (n < min)
min = n;
if (n > max)
max = n;
}
int range = min - max + 1;
string[] array = { "Minimum number is (min)" };
string output = string.Join("\n", array);
Console.WriteLine("Minimum number = {0}, Maximum number = {1}, Range = {2}", min, max, range);
MessageBox.Show(output);
}
}
}
Here is one way to do it.
Code should be self expanatory
static void Main(string[] args)
{
Random number = new Random();
int rangeFrom = 0;
int rangeTo = 999;
List<int> generatedNumbers = new List<int>();
for (int counter = 0; counter < 100; counter++)
{
generatedNumbers.Add(number.Next(rangeFrom, rangeTo));
}
generatedNumbers.Sort();
string output = "generated numbers: {0} \r\n\rmin: {1}\r\n\r\nmax: {2}\r\n\r\nrange: {3}-{4}";
output = string.Format(output,
string.Join(", ", generatedNumbers.ToArray()),
generatedNumbers.Min(),
generatedNumbers.Max(),
rangeFrom,
rangeTo);
MessageBox.Show(output);
}
to summarize:
I have used List for easier manipulation of data and used Linq (make sure you have using System.Linq; in your app).

Random number generator, pick 3 in a range, returns group of 2 in some iterations

i put a random number generator together using Linq. the range of those random numbers needs to be in this case 1-6 inclusive. i want groups of 3 distinct numbers chosen.
i don't understand why this code returns groups that contain only 2 numbers.
do
{
Random rnd = new Random();
int[] myRndNos = Enumerable
.Range(1, 6)
.Select(i => rnd.Next(1, 7))
.Distinct()
.Take(3)
.ToArray();
string test = string.Join(",", myRndNos);
System.Console.WriteLine(test);
Console.ReadKey(true);
} while (true);
it returns a sample like:
4,6,1
5,2,3
2,4,5
3,2
3,5,1
etc...
why in some cases is it taking only 2 numbers? doesn't make sense to me.
tx
You are generating 6 random numbers but if those numbers happen to be duplicates the distinct will eliminate them leaving you with only the list on unique values, if there are only 2 unique items then that's all you will get.
Because you want 3 distinct numbers, I think what you are after is a shuffle.
private static Random rnd = new Random();
int[] myRndNos = Enumerable.Range(1, 6).OrderBy(i => rnd.Next()).Take(3).ToArray();
or
private static Random rng = new Random();
int[] myRndNos = Enumerable.Range(1, 6).Shuffle();
public static void Shuffle<T>(this IList<T> list)
{
int n = list.Count;
while (n > 1) {
n--;
int k = rng.Next(n + 1);
T value = list[k];
list[k] = list[n];
list[n] = value;
}
}
Source of algorithm: Randomize a List<T>
This is because the range that you are generating is not unique numbers
if the range is 2,2,2,6,6,6 the distinct will result as 2 and 6 as you can see in this example
Hope this helps you
Try something like this
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
Take3Distinct take3Distinct = new Take3Distinct();
for (int i = 0; i < 10; i++)
{
Console.WriteLine(string.Join(",", take3Distinct.Take3().ToArray()));
}
Console.ReadLine();
}
}
public class Take3Distinct
{
const int SIZE = 6;
Random rand = new Random();
public List<List<int>> pairs = new List<List<int>>();
public Take3Distinct()
{
for(int i = 1; i <= SIZE; i++)
{
List<int> newPair = new List<int>{i, 0};
pairs.Add(newPair);
}
}
public List<int> Take3()
{
foreach (List<int> pair in pairs)
{
pair[1] = rand.Next();
}
pairs = pairs.OrderBy(x => x[1]).ToList();
return pairs.Select(x => x[0]).Take(3).ToList();
}
}
}
Another option without shuffle is with HashSet
var rnd = new Random();
var myRndNos = new HashSet<int>();
while (myRndNos.Count < 3)
myRndNos.Add(rnd.Next(1, 7));
Debug.Print(string.Join(",", myRndNos));
This is my shuffle extension. It's basically identical in concept to #Daniel's shuffle algorithm, but it has some additional features:
It will yield return an enumerable, which means you actually only need to randomize as many elements as you actually use (e.g. if you do Enumerable.Range(0,100).ToList().Shuffle().Take(5) it actually only randomizes the 5 elements you need, without shuffling the whole array.
Minor optimization to ignore the element swap if the source and target elements are the same.
Option to do either a destructive (i.e. a shuffle modifying the source list) or non-destructive shuffle. The non-destructive shuffle basically generates a list of indices and destructively shuffles that.
Returns IEnumerable<T> so it can be used in a longer expression, such as with .Take() as mentioned.
My extension class for shuffling:
public static class ListShuffle
{
private static Random _random = new Random();
public static IEnumerable<T> ShuffleInPlace<T>(this IList<T> list)
{
for (int n = list.Count - 1; n >= 0; n--)
{
int randIx = _random.Next(n + 1); // Random int from 0 to n inclusive
if (randIx != n)
{
T temp = list[randIx];
list[randIx] = list[n];
list[n] = temp;
}
yield return list[n];
}
}
public static IEnumerable<T> Shuffle<T>(this IList<T> list)
{
List<int> indices = Enumerable.Range(0, list.Count).ToList();
foreach (int index in indices.ShuffleInPlace())
{
yield return list[index];
}
}
}
You are literarily doing rnd.Next(1, 7) 6 times and then DISTINCT and TOP(3); however, it could be "3,3,3,2,2,2" and it will return "3,2" based your codes.
You could use an array (rnd.Next(1, 7).ToArray()) and do random on indexes. When 1 number got hit then replace it with an un-hit number.
for example,
[1,2,3,4,5,6]
Run random and get 3
update array to [1,2,2,4,5,6]
Run random again...
...
you will get 3 distinct numbers with only 3 hits.

Adding the sum of two randomly generated numbers (using arrays)

class Program
{
const int ROLLS = 51;
static void Main(string[] args)
{
Random r = new Random();
int sum = 0;
int[] dice1 = new int[ROLLS];
int[] dice2 = new int[ROLLS];
for (int roll = 0; roll <= 50; roll++)
{
dice1[roll] = GenerateNum(r);
dice2[roll] = GenerateNum(r);
Console.WriteLine("ROLL{0}: {1} + {2} = sum goes here", roll+1, dice1[roll]+1, dice2[roll]+1);
}
}
static int GenerateNum (Random r)
{
return r.Next(1, 7);
}
}
}
So what I have is two arrays to store two different int values that are randomly generated and what I am trying to achieve is the sum of these two randomly generated int values.
Upon execution it should display:
Roll 1: (random number) + (random number) = (sum of the two random numbers)
Just add the two together and store them in sum. Then present sum in the same manner you have presented the rest of the values in the output of the console:
dice1[roll] = GenerateNum(r);
dice2[roll] = GenerateNum(r);
sum = dice1[roll] + dice2[roll];
Console.WriteLine("ROLL{0}: {1} + {2} = {3}", roll + 1, dice1[roll], dice2[roll], sum);

Total sum/average of random numbers in c#

I am new to programming and i would be delighted if someone could help me with the following question: "Write a program that randomly selects integers whose values range from 0 to 9. The program will calculate the average of the random numbers and print how many of the random numbers are larger than the average. The program's user will specify how many numbers will be randomly generated". How do you get the total sum of random numbers so you can get the average? This is what i got so far:
int ChosenRandom;
Console.Write("Choose a number between 0-10; ");
ChosenRandom = int.Parse(Console.ReadLine());
Random rnd = new Random();
int RandomNumber = rnd.Next(0, 10);
for (int i = 0; i < ChosenRandom; i++)
{
Console.WriteLine("Random numbers: " + rnd.Next(0, 10));
}
int TotalRandom;
TotalRandom = ChosenRandom + (RandomNumber);
Console.WriteLine("Total is:" + TotalRandom);
int avr;
avr = TotalRandom / ChosenRandom;
Console.WriteLine("Average is: " + avr);
if (ChosenRandom > avr)
{
Console.WriteLine("Numbers larger than average" + ChosenRandom);
}
else
{
Console.WriteLine("All numbers under average");
}
simplest way is by using arrays,
store the numbers in an array while generating them
use the array elements to find the total and average
traverse through array comparing each element with that of average
Check if this solution helps for you.
I have used linq to create average and find all numbers above the 'average'.
using System;
using System.Linq;
namespace Test
{
class Program
{
static void Main()
{
int chosenRandom;
Console.WriteLine("Choose a number between 0-10");
chosenRandom = int.Parse(Console.ReadLine());
Random rand = new Random();
double[] randomNumbers = new double[chosenRandom];
for(int i = 0; i < chosenRandom; i++)
{
Console.WriteLine("Random numbers: " + (randomNumbers[i] = rand.Next(0, 10)));
}
double average = randomNumbers.Average(t => t);
var numbersAboveAverage = randomNumbers.Where(t => t > average);
Console.WriteLine("Average of all random numbers - {0}", average);
foreach(var number in numbersAboveAverage)
Console.WriteLine(number);
}
}
}
Your program looks good. But, you understood the question in a wrong way! The question says that the value of random integers should be 0-9. Not the no of random numbers. The number of random numbers can be of any value as given by user.
Please find below the complete implementation.
class Program
{
static void Main(string[] args)
{
//Step 1. Get the no of random numbers (n) to be generated from user.
Console.WriteLine("Enter the no of Random numbers: ");
int n = int.Parse(Console.ReadLine());
//Step 2. Generate 'n' no of random numbers with values rangeing from 0 to 9 and save them in an array.
Random rand = new Random();
int[] randCollection = new int[n];
for (int i = 0; i < n; i++)
{
randCollection[i] = rand.Next(9);
Console.WriteLine("Random No {0} = {1}", i + 1, randCollection[i]);
}
//Step 3. Compute Average
double average = randCollection.Average();
Console.WriteLine("Average = {0}", average);
//Step 4. Find out how many numbers in the array are greated than the average.
int count = 0;
foreach(int i in randCollection){
if (i > average) count++;
}
Console.WriteLine("No of random numbers above their average = {0}", count);
Console.ReadLine();
}
}
Hope this helps. Let me know if you have any questions.

Categories

Resources