10 elements twice in a 20-position array - c#

I'm really struggling to find a way to put 10 int numbers ( from 1 to 10) twice in a 20-position array on a random position in C#.Everything I have already tried takes too much time and makes my programme run really slow.
Ok here's the code I have already tried but doesn't really work well.
for (int j = 1; j <= 10; j++)
{
k = 0;
while (k < 2)
{
rnd = new Random();
numb = rnd.Next(1, 20);
//w = numbers[numb].ToString(); not actually working as well
if (numbers[numb] == '\0')
{
numbers[numb] = j;
k++;
}
}
}
So what I'm really trying to do here,is to put all the int numbers from 1 to 10
twice in this 20-position array on random position.Sorry for not posting my code before,but I was from my phone and it was really late.For example:
[1,3,7,9,5,3,4,10,7,8,8,2,1,4,5,6,10,9,2,6]

Try something like this:
int[] array = new int[20];
Random rand = new Random();
for (int i = 0; i < 20; i++)
{
int num = rand.Next(1, 10);
int pos = rand.Next(0, 19);
while (array[pos] != 0)
{
if (pos == 19)
pos = 0;
else
pos++;
}
array[pos] = num;
}
or if you want the positions to be random, but not the numbers and exactly two of each number, try this:
int[] array = new int[20];
Random rand = new Random();
for (int i = 1; i <= 10; i++)
{
int num = i;
int pos1 = rand.Next(0, 19);
while (array[pos1] != 0)
{
if (pos1 == 19)
pos1 = 0;
else
pos1++;
}
array[pos1] = num;
int pos2 = rand.Next(0, 19);
while (array[pos2] != 0)
{
if (pos2 == 19)
pos2 = 0;
else
pos2++;
}
array[pos2] = num;
}

Related

Looping through a large array and adding the values together C#

I'm trying to loop through an array of 180 elements and add the first 60 elements together and store it in a list. Then add the next 60 elements together and store them in the list and repeat that for the final 60. So far my code will only add the first 60 and store them in the list. the problem seems to be the "i % 60 == 0" in the else if statement but I'm not sure why
Random r = new Random();
int[] arr = new int[180];
List<int> MyList = new List<int>();
int[] array2 = new int[2];
//intialize random numbers in 60 length array
for (int i = 0; i < arr.Length; i++)
{
arr[i] = r.Next(1, 10);
}
int score = 0;
//looping through arr
for (int i = 0; i < arr.Length; i++)
{
if (i % 60 != 0 || i == 0 )
{
score = score + arr[i];
i++;
}
else if (i % 60 == 0 && i != 0)
{
//adding the values to a list
MyList.Add(score);
//resetting score after score is added to the list
score = 0;
}
}
// converting list to my second array
array2 = MyList.ToArray();
//printing values in array
for (int i = 0; i < array2.Length; i++)
{
Console.WriteLine(array2[i]);
}
Your original loop and conditions have several problems and actually need to be:
int score = 0;
for (int i = 0; i < arr.Length; i++)
{
score = score + arr[i];
if ((i + 1) % 60 == 0)
{
MyList.Add(score);
score = 0;
}
}
But I strongly advise you to use much simpler LINQ approach (instead of doing all the stuff manually):
var array2 = new[]
{
arr.Take(60).Sum(),
arr.Skip(60).Take(60).Sum(),
arr.Skip(120).Sum()
};

Returns incorrect output

Description of challenge:
Have the function KaprekarsConstant(num) take the num parameter being passed which will be a 4-digit number with at least two distinct digits.
Your program should perform the following routine on the number:
Arrange the digits in descending order and in ascending order (adding
zeroes to fit it to a 4-digit number), and subtract the smaller
number from the bigger number. Then repeat the previous step.
Performing this routine will always cause you to reach a fixed number: 6174.
Then performing the routine on 6174 will always give you 6174 (7641 - 1467 = 6174).
Your program should return the number of times this routine must be performed until 6174 is reached.
For example: if num is 3524 your program should return 3 because of the following steps:
5432 - 2345 = 3087
8730 - 0378 = 8352
8532 - 2358 = 6174
Web-site where I took this challenge Coderbyte
Problem :
All works correctly until returning the result in Foo() I don't know why but it calls this function some times until Count==2
Please help.Sorry please if I made mistakes and my code is really bad because I am schooler(9 Grade) and I have been programming for half a year
using System;
class MainClass
{
public static int Foo(int num,int Counter)
{
int Count = Counter;
int[] arr = new int[4];
arr[0] = num / 1000;
arr[1] = num % 10;
arr[2] = (num / 100) % 10;
arr[3] = (num % 100) / 10;
Array.Sort(arr);
int[] AscArr = new int[4];
arr.CopyTo(AscArr, 0);
Array.Reverse(arr);
int[] DescArr = arr;
int sub = 0;
string AscStr = string.Empty;
string DescStr = string.Empty;
for (int i = 0; i < AscArr.Length; i++)
{
AscStr += AscArr[i];
}
for (int i = 0; i < DescArr.Length; i++)
{
DescStr += DescArr[i];
}
int b = int.Parse(AscStr);
int a = int.Parse(DescStr);
sub = a - b;
if (sub!=6174)
{
Count++;
Foo(sub,Count);
}
if (sub==6174)
{
Count++;
}
return Count;
}
public static int KaprekarsConstant(int num)
{
int[] arr=new int[4];
arr[0] = num / 1000;
arr[1] = num % 10;
arr[2] = (num / 100) % 10;
arr[3] = (num % 100) / 10;
Array.Sort(arr);
int[] AscArr=new int[4];
arr.CopyTo(AscArr,0);
Array.Reverse(arr);
int[] DescArr = arr;
int sub = 0 ;
string AscStr=string.Empty;
string DescStr = string.Empty;
for (int i = 0; i < AscArr.Length; i++)
{
AscStr += AscArr[i];
}
for (int i = 0; i < DescArr.Length; i++)
{
DescStr += DescArr[i];
}
int b = int.Parse(AscStr);
int a = int.Parse(DescStr);
sub = a - b;
int Counter =1;
int Count=0;
if (Count!=6174)
{
Count = Foo(sub, Counter);
}
return Count;
}
static void Main()
{
// keep this function call here
Console.WriteLine(KaprekarsConstant(int.Parse(Console.ReadLine())));
}
}
Your code is too much complex, plus, your way of dividing number to array is giving wrong results.
// this is wrong you can print array, the numbers goes into wrong indexes
arr[0] = num / 1000;
arr[1] = num % 10;
arr[2] = (num / 100) % 10;
arr[3] = (num % 100) / 10;
Use this:
using System;
class MainClass
{
public static int count = 0;
public static void KaprekarsConstant(int num)
{
if (num == 6174) // base case
return;
count++;
string[] Aarr=new string[4];
string[] Darr = new string[4];
string asc = "", dsc = "";
Aarr[3] = (num % 10).ToString();
Darr[3] = (num % 10).ToString();
num /= 10;
Aarr[2] =(num % 10).ToString();
Darr[2] = (num % 10).ToString();
num /= 10;
Aarr[1] = (num % 10).ToString();
Darr[1] = (num % 10).ToString();
num /= 10;
Aarr[0] =(num % 10).ToString();
Darr[0] = (num % 10).ToString();
Array.Sort(Aarr); // ascneding sorted
Array.Sort<string>(Darr, new Comparison<string>( (i1, i2) => i2.CompareTo(i1))); // descending sorted
for(int i = 0; i< 4;i++)
{
asc += Aarr[i];
dsc += Darr[i];
}
KaprekarsConstant(Convert.ToInt32(dsc) -Convert.ToInt32(asc) );
}
static void Main()
{
KaprekarsConstant(int.Parse(Console.ReadLine()));
Console.WriteLine("\nIt took "+count + "times to reach 6174");
}
}

C# user-input size of

I want to be able to create an array with random integers where the size of it is the user's choice and I can transfer the printed out array into a different textbox.
i tried
int listamount; //stores the number
if (int.TryParse(LStextbox.Text, out listamount) && LStextbox.Text.Length > 0)
{
//int.tryparse converts the string into a integer
//text.lentgh > 0 makes sure the box will not be left blank
}
else
{
}
int min = 0;
int max = 100; //i want to make the max an indefinite number, is that posible?
int num = listamount;
Random r = new Random();
int[] ar;
ar = new int[num];
for (i = 0; int =< num - 1; i++)
{
ar[i] = r.Next(min, max);
}
Ypu can use below approach:
You can achieve max int by using Int32.MaxValue statement.
By the way you have some mistakes with in the for loop, I have corrected them.
int listamount; //stores the number
if (int.TryParse(LStextbox.Text, out listamount) && LStextbox.Text.Length > 0)
{
//int.tryparse converts the string into a integer
//text.lentgh > 0 makes sure the box will not be left blank
}
else
{
}
int min = 0;
int max = Int32.MaxValue; //i want to make the max an indefinite number, is that posible?
int num = listamount;
Random r = new Random();
int[] ar;
ar = new int[num];
for (int i = 0; i <= num - 1; i++)
{
ar[i] = r.Next(min, max);
}
foreach(int y in ar)
Console.WriteLine(y);

How to generate a unique random number in a range without repeating a number in 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());
}
}
}

Need help assigning values to array C# (noob)

I am trying to write a method that will assign each day of the year a value for rainfall after checking if it rain at all.
So I want my days array to contain 365 random numbers below 28, 3/4 of them being 0.
note: I have a global random variable
static void Generate()
{
int[] days = new int[365];
int going_to_rain = 0;
for (int i = 0; i < days.Length; i++)
{
going_to_rain = randomValue.Next(3);
if (going_to_rain == 1)
{
days[i] = randomValue.Next(1, 28);
}
else
{
days[i] = 0;
}
}
Console.WriteLine(days);
}
You can create an array that its first 274 cells are 0, and the others are random.
Afterward you shuffle this array randomally:
int[] days = new int[365];
int i = 0;
for(i = 0;i < 274;++i)
{
days[i] = 0;
}
for (i = 275;i < 365; ++i)
{
days[i] = randomValue.Next(1,28);
}
//Shuffle
for (i = 0; i < 365; ++i)
{
int randVal = randomValue.Next(364);
int tmp = day[randVal];
day[randVal] = day[i];
day[i] = tmp;
}

Categories

Resources