Find the first uneven number in random array in c# - 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();
}

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

How to refactor this code to combine several sections?

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

How to print different items in an array with a while loop

I am creating a lotto number generator, with the powerball number at index zero in my array. however I am supposed to print all items in the array with the powerball nuber printing last. If it didn't have to print last I could easily do this with a foreach loop, but I'm stuck on how to do it otherwise.
anyone with any thoughts or ideas.
{
int[] Lotto = new int[6];
int check = 0;
//powerball
Random rand = new Random();
check = rand.Next(5, 64);
Lotto[0] = check;
for (int i = 1; i < Lotto.Length;)
{
check = rand.Next(1, 64);
Lotto[i] = check;
i++;
}
return Lotto;
}
As I commented, to print the first index last, something like…
for (int i = 1; i < Lotto.Length; i++) {
Console.WriteLine(Lotto[i]);
}
Console.WriteLine("PowerBall: " + Lotto[0]);
Or … If order does not matter, then simply loop through the array from the bottom up. Something like…
for (int i = Lotto.Length - 1; i >= 0; i--) {
Console.WriteLine(Lotto[i]);
}
You can use if into for:
{
int[] Lotto = new int[6];
int check = 0;
//powerball
Random rand = new Random();
check = rand.Next(5, 64);
Lotto[0] = check;
for (int i = 1; i < Lotto.Length; i++)
{
check = rand.Next(1, 64);
Lotto[i] = check;
if(Lotto[0] >= 5 ){
Console.WriteLine("The item is "+ Lotto);
}else if(Lotto[0] >= 50 && Lotto[0] <=64){
Console.WriteLine("The item is "+ Lotto);
}
}
//return Lotto;
}

Logging the time it takes to fill a LinkedList and Array

This Console-application is a bit strange but kinda funny, if it works. First, I'm clocking the time it takes to fill a LinkedList with 4.000.000 elements, with random numbers. Then I'm searching for 100 random elements in that LinkedList. And between this I'm writing out the time it took to fill and find the elements.
After that I'm trying to do the same thing again, but with an Array. First filling it, then looking for 100 random elements. And then I'm sorting the array, to see the difference between looking for 100 random elements in a unsorted vs sorted array. And then typing the time again.
The problem is, after I've filled the LinkedList, and found the elements in the LinkedList, I'm starting to fill the Array with a loop. And I get a infinite loop. I really don't know what's wrong ATM.
I suggest, if you want to help, that you copy the code I'm pasting into this question, so you understand how it should look for all the parts of the program.
Code:
public static bool sokning(int[] a, int b)
{
bool sant = false;
Random rand = new Random();
Stopwatch watchFindArray = new Stopwatch();
Console.Write("Letar efter tal: ");
watchFindArray.Start();
int myint = 0;
for (int iii = 0; iii < a.Length; iii++)
{
b = rand.Next();
Console.Write("#");
myint = Array.BinarySearch(a, b);
if (myint < 0)
{
sant = false;
}
else
{
sant = true;
}
}
watchFindArray.Stop();
if (sant == true)
{
Console.WriteLine("\nFann alla element efter " + watchFindArray.Elapsed.TotalSeconds + " sekunder.");
return true;
}
else
{
return false;
}
}
public static void körMetod()
{
const int MAX = 40000000;
int[] array = new int[MAX];
int hittamig2 = 0;
Random rand2 = new Random();
Stopwatch watchArray = new Stopwatch();
Console.WriteLine("\nStartar Array...");
watchArray.Start();
Console.Write("Position: ");
for (int ii = 0; ii < MAX; ii++)
{
array[ii] = rand2.Next();
if (array.Length % 1000000 == 0)
{
Console.Write("#");
}
}
watchArray.Stop();
Console.WriteLine("\nTid: " + watchArray.Elapsed.TotalSeconds + " sekunder att fylla en array.");
Console.WriteLine("Letar efter tal: ");
bool sant = sokning(array, hittamig2);
Console.WriteLine("Sorterar arrayen.");
Array.Sort(array);
sant = sokning(array, hittamig2);
if (sant == false)
{
Console.WriteLine("\nHittade inte alla element i arrayen.");
Console.ReadLine();
}
else
{
Console.WriteLine("Klar!");
Console.ReadLine();
}
}
static void Main(string[] args)
{
Random rnd = new Random();
const int MAX = 40000000;
LinkedList<int> lankadLista = new LinkedList<int>();
Stopwatch watchLinkedList = new Stopwatch();
Console.WriteLine("Startar LinkedList...");
watchLinkedList.Start();
Console.Write("Position: ");
for (int i = 0; i < MAX; i++)
{
lankadLista.AddLast(rnd.Next());
if (lankadLista.Count() % 1000000 == 0)
{
Console.Write("#");
}
}
watchLinkedList.Stop();
Console.WriteLine("\nTid: " + watchLinkedList.Elapsed.TotalSeconds + " sekunder att fylla en LinkedList.");
Stopwatch watchFindLinkedList = new Stopwatch();
int hittaMig;
Console.Write("Letar efter tal: ");
watchFindLinkedList.Start();
for (int j = 0; j < 100; j++)
{
hittaMig = rnd.Next();
Console.Write("#");
lankadLista.Find(hittaMig);
}
watchFindLinkedList.Stop();
Console.WriteLine("\nFann alla element efter " +
watchFindLinkedList.Elapsed.TotalSeconds + " sekunder.");
Console.ReadLine();
körMetod();
}
Best Regards.
You are not in an infinite loop, the problem is that it the following code:
for (int ii = 0; ii < MAX; ii++)
{
array[ii] = rand2.Next();
if (array.Length % 1000000 == 0)
{
Console.Write("#");
}
}
The inner condition is array.Length % 1000000 == 0 which is always true because the size of array is always 40000000 as you initialized it:
const int MAX = 40000000;
int[] array = new int[MAX];
When you are doing array[ii] = rand2.Next(); you are not changing the length of the array you are just setting one of its cells with a value equals to rand2.Next();.
This causes the Console.Write("#"); to work in every iteration and also slowing your loop dramatically.
To fix this, just change:
if (array.Length % 1000000 == 0)
to:
if (ii % 1000000 == 0)
You don't want to add new item at the end of the array every time because, resizing the array reallocates the array every time which is super slow but you can do it using the Array.Resize method (no reason for you to do it)
I think you have a big problem in the routine that searches the Array. (sokning)
Where is the code that searches for only 100 elements?
It seems that your are searching a random generated number for 40 millions times. Just fixing the Console.Write("#") to write correctly at every million point is not enough. I think that the big delay that let you think to have an infinite loop is in your code that search 40 millions of random generated numbers in an array of 40 millions of numbers
Of course this is not very "responsive" (considering also that you call this method two times)
public static bool sokning(int[] a, int b)
{
bool sant = false;
Random rand = new Random();
Stopwatch watchFindArray = new Stopwatch();
Console.Write("Letar efter tal: ");
watchFindArray.Start();
int myint = 0;
// Search only 100 numbers like you do in the linked list
for (int iii = 0; iii < 100; iii++)
{
b = rand.Next();
Console.Write("#");
myint = Array.BinarySearch(a, b);
if (myint < 0)
{
sant = false;
}
else
{
sant = true;
}
}
watchFindArray.Stop();
if (sant == true)
{
Console.WriteLine("\nFann alla element efter " + watchFindArray.Elapsed.TotalSeconds + " sekunder.");
return true;
}
else
{
return false;
}
}
There are also two minor problems.
Why passing the variable b inside the sokning method? The original value is never used and when you start the loop to search a random generated number the b variable os overwritten. So I think you could remove it
The second problem is the result of this sokning method. You set the sant variable to true or false at every loop. So the latest loop wins. In other words, if the latest loop finds a match you return true or false if not. If some previous loop has a different result, it is totally lost for the callers of sokning.

Generating random numbers without repeating.C# [duplicate]

This question already has answers here:
Random number generator with no duplicates
(12 answers)
Closed 2 years ago.
Hi everyone I am trying to generate 6 different numbers on the same line in c# but the problem that i face is some of the numbers are repeating on the same line.Here is my code to
var rand = new Random();
List<int> listNumbers = new List<int>();
int numbers = rand.Next(1,49);
for (int i= 0 ; i < 6 ;i++)
{
listNumbers.Add(numbers);
numbers = rand.Next(1,49);
}
somewhere my output is
17 23 23 31 33 48
Check each number that you generate against the previous numbers:
List<int> listNumbers = new List<int>();
int number;
for (int i = 0; i < 6; i++)
{
do {
number = rand.Next(1, 49);
} while (listNumbers.Contains(number));
listNumbers.Add(number);
}
Another approach is to create a list of possible numbers, and remove numbers that you pick from the list:
List<int> possible = Enumerable.Range(1, 48).ToList();
List<int> listNumbers = new List<int>();
for (int i = 0; i < 6; i++)
{
int index = rand.Next(0, possible.Count);
listNumbers.Add(possible[index]);
possible.RemoveAt(index);
}
listNumbers.AddRange(Enumerable.Range(1, 48)
.OrderBy(i => rand.Next())
.Take(6))
Create a HashSet and generate a unique random numbers
public List<int> GetRandomNumber(int from,int to,int numberOfElement)
{
var random = new Random();
HashSet<int> numbers = new HashSet<int>();
while (numbers.Count < numberOfElement)
{
numbers.Add(random.Next(from, to));
}
return numbers.ToList();
}
Make it a while loop and add the integers to a hashset. Stop the loop when you have six integers.
Instead of using a List, you should use an HashSet. The HashSet<> prohibites multiple identical values. And the Add method returns a bool that indicates if the element was added to the list, Please find the example code below.
public static IEnumerable<int> GetRandomNumbers(int count)
{
HashSet<int> randomNumbers = new HashSet<int>();
for (int i = 0; i < count; i++)
while (!randomNumbers.Add(random.Next()));
return randomNumbers;
}
I've switched your for loop with a do...while loop and set the stopping condition on the list count being smaller then 6.
This might not be the best solution but it's the closest to your original code.
List<int> listNumbers = new List<int>();
do
{
int numbers = rand.Next(1,49);
if(!listNumbers.Contains(number)) {
listNumbers.Add(numbers);
}
} while (listNumbers.Count < 6)
The best approach (CPU time-wise) for such tasks is creating an array of all possible numbers and taking 6 items from it while removing the item you just took from the array.
Example:
const int min = 1, max = 49;
List<int> listNumbers = new List<int>();
int[] numbers = new int[max - min + 1];
int i, len = max - min + 1, number;
for (i = min; i < max; i++) numbers[i - min] = i;
for (i = 0; i < 6; i++) {
number = rand.Next(0, len - 1);
listNumbers.Add(numbers[number]);
if (number != (len - 1)) numbers[number] = numbers[len - 1];
len--;
}
If you are not worried about the min, max, and range then you can use this.
var nexnumber = Guid.NewGuid().GetHashCode();
if (nexnumber < 0)
{
nexnumber *= -1;
}
What you do is to generate a random number each time in the loop. There is a chance of course that the next random number may be the same as the previous one. Just add one check that the current random number is not present in the sequence. You can use a while loop like: while (currentRandom not in listNumbers): generateNewRandomNumber
Paste the below in the class as a new method
public int randomNumber()
{
var random = new Random();
int randomNumber = random.Next(10000, 99999);
return randomNumber;
}
And use the below anywhere in the tests wherever required
var RandNum = randomNumber();
driver.FindElement(By.CssSelector("[class='test']")).SendKeys(**RandNum**);
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
int[] que = new int[6];
int x, y, z;
Random ran = new Random();
for ( x = 0; x < 6; x++)
{
que[x] = ran.Next(1,49);
for (y = x; y >= 0; y--)
{
if (x == y)
{
continue;
}
if (que[x] == que[y])
{
que[x] = ran.Next(1,49);
y = x;
}
}
}
listBox1.Items.Clear();
for (z = 0; z < 6; z++)
{
listBox1.Items.Add(que[z].ToString());
}
}
}

Categories