How to refactor this code to combine several sections? - c#

Let's say I have these 3 not so different codes.
How can I combine them, or let's just say I want to enter 10 numbers once I open the application.
I want those numbers to be added to each other, and at the same time show me if the number is even or not.
Here is the input code:
int[] dizi = new int[10];
for (int i=0; i<=10; i++)
{
dizi[i] = Convert.ToInt32(Console.ReadLine());
}
Here is the addition code:
int[] dizi[i]
int toplam=0;
foreach(int sayi in dizi)
{
toplam=toplam+sayi;
}
Console.WriteLine("Dizideki sayıların toplamı = " + toplam);
Here is the even number code:
int[] dizi[i]
int toplam=0;
foreach(int sayi in dizi)
{
if (sayi%2 ==0)
Console.WriteLine(sayi);
}

All code in one for loop.
For input 10 elements you need for from 0 to i < array.Length
because array int[10] access by index from 0 to 9
var array = new int[10];
var sum = 0;
for (var i = 0; i < array.Length; i++)
{
var number = Convert.ToInt32(Console.ReadLine());
sum += number;
if (number % 2 == 0)
Console.WriteLine($"The number {number} is even");
}
Console.WriteLine($"Sum = {sum}");

Related

Lottery program that generates 6 random numbers between 1 and 59 C#

I have created a simple program which randomly generates 6 winning numbers. While the program works, I would also like for it to ensure that the same number isn't outputted twice as well as sorting them into numerical order when outputted. How would I go about doing such a thing while sticking to similar techniques already used? My code is down below. Any help is very much appreciated.
int temp;
int[] lotto = new int[6];
Random rand = new Random();
for (int i = 0; i < 6; i++)
{
temp = rand.Next(1, 59);
lotto[i] = temp;
}
Console.Write($"The lotterry winning numbers are: ");
for (int i = 0; i < 6; i++)
{
Console.Write(lotto[i] + " ");
}
Console.ReadKey();
Based on a Fisher-Yates shuffle, but saves some work because we know we don't need all the values (if we only need 6 values out of 10 million potentials, we only need to take the first six iterations of the fisher-yates algorithm).
public IEnumerable<int> DrawNumbers(int count, int MaxNumbers)
{
var r = new Random(); //ideally, make this a static member somewhere
var possibles = Enumerable.Range(1, MaxNumbers).ToList();
for (int i = 0; i < count; i++)
{
var index = r.Next(i, MaxNumbers);
yield return possibles[index];
possibles[index] = possibles[i];
}
}
var lottoNumbers = DrawNumbers(6, 59);
Console.Write("The lotterry winning numbers are: ");
Console.WriteLine(string.Join(" ", lottoNumbers.OrderBy(n => n)));
See it work here:
https://dotnetfiddle.net/NXYkpU
You can use Linq to create sequence [1..59] and order it by random to shuffle it.
Random rand = new Random();
var winners = Enumerable.Range(1, 59)
.OrderBy(x => rand.Next())
.Take(6)
.OrderBy(x => x)
.ToList();
Console.WriteLine(String.Join(" ", winners));
int temp;
int[] lotto = new int[6];
Random rand = new Random();
int i = 0;
while(i < 6)
{
temp = rand.Next(1, 59);
//check if lotto contains just generated number, if so skip that number
bool alreadyExist = false;
foreach (int item in lotto)
{
if (item == temp)
{
alreadyExist = true;
break;
}
}
if (alreadyExist)
continue;
lotto[i] = temp;
i++;
}
Console.Write($"The lotterry winning numbers are: ");
// Sort array in ascending order.
Array.Sort(lotto);
for (int j = 0; j < 6; j++)
{
Console.Write(lotto[j] + " ");
}
Console.ReadKey();
I would probably do it Dmitri's way because it is quick and obvious and performance isn't that important with an array this size.
But just for fun, this is slightly more efficient.
IEnumerable<int> GetNumbers(int min, int max, int count)
{
var random = new Random();
var size = max - min + 1;
var numbers = Enumerable.Range(min, size).ToArray();
while (count > 0)
{
size--;
var index = random.Next(0, size);
yield return numbers[index];
numbers[index] = numbers[size];
count--;
}
}
This solution creates an array containing all possible values and selects them randomly. Each time a selection is made, the array is "shrunk" by moving the last element to replace the element that was chosen, preventing duplicates.
To use:
var numbers = GetNumbers(1, 59, 6).ToList();
foreach (var number in numbers.OrderBy(x => x))
{
Console.WriteLine(number);
}

Find the first uneven number in random array in c#

i must create array and fill it with random numbers , between 1-100. From there, i must find the 1st uneven number and print it.
Also have to print 0 if no uneven numbers are in the array.
Heres what i did:
int[] tab = new int[10];
int[] uneven = new int[tab.Length];
int i;
for (i = 0; i < tab.Length; i++)
tab[i] = new Random().Next(100) + 1;
do
{
uneven[i] = tab[i];
} while (tab[i] % 2 == 1);
Console.WriteLine(uneven[0]);
So my reasoning is that i add uneven numbers in uneven[i] as long as tab[i] is uneven,then print the first element of the array.
However, i get "out of bonds exception".
Thank you in advance for any help.
Your for loop set i to 10 which is outside the bounds of the array. You need to re-set it to 0 before the do loop. Also, you need to increment i.
i = 0;
do
{
uneven[i] = tab[i];
i++;
} while (tab[i] % 2 != 0);
By the time your do loop starts your "i" variable is stuck on 10. Arrays start at 0 so it only goes up to 9 which is why you're seeing the out of bounds exception. Here's a small example of what you're trying to achieve:
int[] tab = new int[10];
var rnd = new Random();
// Create 10 random numbers
for (int i = 0; i < tab.Length; i++)
{
tab[i] = rnd.Next(100) + 1;
}
// Find the first uneven number
bool found = false;
for (int i = 0; i < tab.Length; i++)
{
if (tab[i] % 2 != 0)
{
Console.WriteLine(tab[i]);
found = true;
break;
}
}
// Didn't generate an uneven number?
if (!found)
{
Console.WriteLine("Nothing found");
}
This creates an array[] with random numbers assigned to each element.
The second for loop checks if the number is even/odd then breaks the loop if it is odd.
static void Main(string[] args)
{
int[] numList = new int[100];
var rand = new Random();
Console.WriteLine(rand.Next(101));
for (int i = 0; i <= 99; i++)
{
numList[i] = rand.Next(101);
Console.WriteLine($"Element; {i}: {numList[i]}");
}
for (int i = 0; i <= 99; i++)
{
int num = numList[i];
if (num / 2 != 0)
{
Console.WriteLine($"The first uneven number is: {num} in element: {i}");
break;
}
if(i == numList.Count())
{
Console.WriteLine("All numbers are even");
break;
}
}
Console.ReadLine();
}

How to count each number that is generated randomly using array in C#

How to count each number that gets generated randomly using array in C#?
Output will be as below:
2
3
5
3
5
Number 1 : 0
Number 2 : 1
Number 3 : 2
Number 4 : 0
Number 5 : 2
I did come out with random numbers but then I'm stuck to figure out how to count each number.
int[] randNum;
randNum = new int[5];
Random randNum2 = new Random();
for (int i = 0; i < randNum.Length; i++)
{
randNum[i] = randNum2.Next(0, 9);
Console.Writeline(randNum[i]);
}
Console.WriteLine();
Usually, we use Dictionary for such problems:
// We build dictionary:
Dictionary<int, int> counts = new Dictionary<int, int>();
// 1000 random numbers
for (int i = 0; i < 1000; ++i) {
int random = randNum2.Next(0, 9);
if (counts.TryGetValue(random, out int count))
counts[random] = count + 1;
else
counts.Add(random, 1);
}
// Then query the dictionary, e.g.
// How many times 4 appeared?
int result = counts.TryGetValue(4, out int value) ? value : 0;
However, if numbers are of a small range (say, 0..8, not -1000000..1000000000) we can use arrays:
int numbersToGenerate = 5;
int max = 9;
int[] counts = new int[max];
for (int i = 0; i < numbersToGenerate; ++i) {
int random = randNum2.Next(0, max);
counts[random] += 1;
}
// Output:
for (int i = 0; i < counts.Length; ++i)
Console.WriteLine($"Number {i} : {counts[i]}");
If i understood you correctly you want an extra array with the counting output of the other array.
Then i think this is a simple solution:
int[] arrResult = new int[9];
foreach(int number in randNum){
if(arrResult[number] == null){
arrResult[number] = 0;
}
arrResult[number] = arrResult[number] + 1;
}
if as i am reading in your code the numbers are from 0 to 8 so 9 numbers, this will output an Array where if the random numbers for example are 0 1 0 2 3 1 0
arrResult[0] == 3
arrResult[1] == 2
arrResult[3] == 1
there probably is a more efficent way with linq and different uses but this should be a solution which would work for your problem

How do i remove the 0 from and array?

the assignment asks me to find the second lowest number from the user input (max 10), and if a 0 is entered the program should stop and find the second lowest, without counting. But I have to declare the size of the array beforehand.
For example, if I type in 4 7 3 8 0 the program also counts all the 0 until there are 10 numbers so it sees this: 4 7 3 8 0 0 0 0 0 0. Is there a way for me to stop the program from seeing the other 0 or to somehow change the array size?
Edit:
Ok, so here is the code I have so far:
int s;
s = 10;
int[] numbers = new int[s];
for (int i = 0; i < numbers.Length; i++)
{
int.TryParse(Console.ReadLine(), out numbers[i]);
}
int firstLowestNumber = numbers[0];
int secondLowestNumber = numbers[0];
for (int i = 0; i < numbers.Length; i++)
{
if (numbers[i] < firstLowestNumber)
{
firstLowestNumber = numbers[i];
}
}
for (int x = 0; x < numbers.Length; x++)
{
if (numbers[x] < secondLowestNumber && firstLowestNumber != numbers[x])
{
secondLowestNumber = numbers[x];
}
}
Console.WriteLine("Second Lowest Number is {0}", secondLowestNumber);
Console.ReadLine();
With the initialization of an int-array all numbers will be 0. This means you only need to stop reading when a 0 is given as input.
So a little change in the first foreach will do:
int input;
int.TryParse(Console.ReadLine(), out input);
if (input == 0) break; //This will jump out of the foreach
number[i] = input;
It depends on goal of your homework.
1) Using of Linq (its possible teacher requested this task for you especially to not use a Linq)
using System.Linq;
/*...*/
List<int> ints = new List<int>();
ints.Add(/*...*/);
/*...*/
ints = ints.Where(x => x != 0).ToList();
/*...*/
2) As #Aldert's answer.
3) change printing mechanics of array
int[] ints = new int[10];
foreach (int element in ints) {
if (element == 0)
continue;
Console.Write("{0} ", element);
}

How to get specific sequence of array given the array size and the beginning

I have the following case :
a list or array .the size is a variable i get from the user between 1 to 12 .
if the size is 3 then the array {1,2,3}
if the size is 5 then the array {1,2,3,4,5}
and so on
Now the beginning is a variable also.
the sequence i wanna to get is :
if the size 12 for example ,and the beginning is 9 for example
i wanna the following result with this specific order.
9,10,11,12,1,2,3,4,5,6,7,8
I mean i begin with the given beginning until the last item then if the beginning not 1 then i continue with 1 until the beginning.
I did that but it was specific to the size 12:
with this code :
int[] arr = new int[12];
int month = 9;//input from the user
List<int> source = new List<int>();
while (month <= 12)
{
source.Add(month);
month++;
}
if (source.Count < 12)
{
for (int i = 1; i < source[0]; i++)
{
source.Add(i);
}
}
I wanna more general solution to allow variable size not just 12
I have tested it and it works
int arrsize = Convert.ToInt32(Console.ReadLine());
int[] arr = new int[arrsize];
int month = Convert.ToInt32(Console.ReadLine());//input from the user
List<int> source = new List<int>();
while (month <= arrsize)
{
source.Add(month);
month++;
}
if (source.Count < arrsize)
{
for (int i = 1; i < source[0]; i++)
{
source.Add(i);
}
}
foreach (int i in source)
Console.Write(i);
Please add some conditions like array size should not be less than month and user always input integer and do it in try catch for good practice... etc etc
After using some logic from other answers i think below code is much better.
int arrsize = Convert.ToInt32(Console.ReadLine());
int month = Convert.ToInt32(Console.ReadLine());//input from the user
List<int> source = new List<int>();
int temp = 0;
for (int i = 0; i < arrsize; i++)
{
temp = i + month;
if (temp != arrsize)
source.Add(((i + month) % arrsize));
else
source.Add(arrsize);
}
The second method has less complexity only O (n) because it uses only one loop rather 2.
Third Solution is even more simpler :)
for (int i = 0; i < size; i++)
{
if (i < month)
source.Add(i + month);
else
source.Add((i - month) + 1);
}
hope it helps.
How about something like this:
static IEnumerable<int> GetSequence(int size, int beginning)
{
return Enumerable.Range(beginning, size).Select(i => 1 + (i - 1) % 12);
}
You can change the number 12 into a third parameter of the method.
static int[] Sequence(int size, int start)
{
start--;
int[] result = new int[size];
for (int i = 0; i < size; i++)
{
result[i] = ((i + start) % size ) + 1;
}
return result;
}

Categories