Im getting a bug where i call for two ints to get randomly generated by the same method but they always return the same number when releasing the code in debug mode
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Kortspil
{
public class Kort
{
public int FåKortNummer()//Get card number
{
System.Random KortNummer = new System.Random();
int kort = KortNummer.Next(1, 14);
ErKortTrukket(kort);//is drawn
return kort;
}
}
class Program
{
static void Main(string[] args)
{
Kort SpillerEt = new Kort();
Kort SpillerTo = new Kort();
int SpillerEtKort = SpillerEt.FåKortNummer();//random number 1
Console.WriteLine("Spiller et har trukket: " + SpillerEtKort.ToString());
int SpillerToKort = SpillerTo.FåKortNummer(); // random number 2
Console.WriteLine("Spiller to har trukket: " + SpillerToKort.ToString());
if (SpillerEtKort <= SpillerToKort)
{
Console.WriteLine("Spiller Et vandt denne runde");//player 1 won this round
}
else
{
Console.WriteLine("Spiller to vandt denne runde");//player 2 won this round
}
Console.WriteLine("Tryk Enter for at lukke...");
Console.ReadLine();
}
}
}
You're problem is that you are creating two different Random instances. By default, if you do not supply a seed number, the current time will be used as a seed. However, you're code is executing so quickly, that the same time is being used as a seed (because you're code is executing faster than the smallest resolution of the clock), so the number you receive is the same each time.
The best fix is to create only a single instance of Random. For example, you could change your code to:
public class Kort
{
public static System.Random KortNummer = new System.Random();
public int FåKortNummer()//Get card number
{
int kort = KortNummer.Next(1, 14);
ErKortTrukket(kort);//is drawn
return kort;
}
}
Related
I was trying to make a lucky dip program where 6 random numbers,1-59, are chosen then printed out in an array. I managed to get this to work, however you needed to use an IndexOf method so that no same number was printed twice by checking if the new number is already in the array.
using System;
namespace LuckyDip
{
class Program
{
static void Main(string[] args)
{
int[] luckyNumbers = new int[6];
Random random = new Random();
for (int x = 0; x<6; x++)
{
num[x] = random.Next(1,59);
Console.WriteLine(num[x]);
}
Console.ReadLine();
}
}
}
It prints out numbers, but sometimes they are the same.
You state that you want to use IndexOf, but that method is used for strings (see docs). Your example has an int array so the solution below uses Contains. This solution adds a check within your loop and generates a new number if this number already exists within your array. If you really need to use IndexOf, create a string array and convert the numbers using String.valueOf(randomNumber)
using System;
using System.Linq;
public class Program
{
public static void Main(string[] args)
{
int[] luckyNumbers = new int[6];
Random random = new Random();
for (int x = 0; x<6; x++)
{
int randomNumber = random.Next(1,59);
while (luckyNumbers.Contains(randomNumber))
{
randomNumber = random.Next(1,59);
}
luckyNumbers[x] = randomNumber;
Console.WriteLine(luckyNumbers[x]);
}
}
}
Another possible solution would be:
using System;
using System.Collections;
using System.Linq;
public class Program
{
public static void Main()
{
int arraySize = 6;
int[] luckyNumbers = Enumerable.Range(1,59).OrderBy(g => Guid.NewGuid()).Take(arraySize).ToArray();
for (int x = 0; x < luckyNumbers.Length; x++)
{
Console.WriteLine(luckyNumbers[x]);
}
}
}
I attempting to create a program that uses multiple methods that would print out base numbers, exponents, and their resulting solutions. I am trying to get it to run and it's nearly completed, but I am encountering a couple issues. The code itself seems to run, but doesn't appear to print out on Visual Studio. I did run it on an online compiler and got this as an output:
It seems I am missing something in my code, but I am unclear as to what I may be missing. This is the code I have created for the project:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Project
{
class Program
{
static void Main(string[] args)
{
//Our initialized variables.
int intMinBase = 1;
int intMaxBase = 100;
int intMinExpo = 1;
int intMaxExpo = 10;
//Our arrays for the project, all at a length of 5.
long[] baseNumbers = new long[5];
long[] exponents = new long[5];
long[] results = new long[5];
//Randomize the baseNumbers and exponents!
Random randInt = new Random();
for (long i = 0; i < 5; i++)
{
baseNumbers[i] = randInt.Next(intMinBase, intMaxBase);
exponents[i] = randInt.Next(intMinExpo, intMaxExpo);
}
PrintArrays(baseNumbers, exponents, results);
}
//This is potentially experimental code for the Power Method.
public static int Power(int baseNum, int exponent)
{
int answer;
if (exponent == 1)
{
answer = 1;
}
else
{
answer = baseNum * Power(baseNum, exponent - 1);
}
return answer;
}
//The new method to be printed. Is this the correct manner to display this?
public static void PrintArrays(long[] baseNum, long[] exponent, long[] result)
{
Console.WriteLine($"Base\tExponent\tResult");
for (int print = 0; print < result.GetUpperBound(0); print++)
{
Console.WriteLine(baseNum[print]+"\t"+exponent[print]+"\t"+result[print]);
}
}
}
}
My question is mainly am I missing something and why isn't it appearing to print in Visual Studio yet it's appearing on an online compiler? I suspect the answer to the first part of the question has to do with the methods I used, but I am unsure.
First error: Nowhere is the method Power called and nowhere is the array results filled.
Solution example:
for (long i = 0; i < 5; i++)
{
baseNumbers[i] = randInt.Next(intMinBase, intMaxBase);
exponents[i] = randInt.Next(intMinExpo, intMaxExpo);
results[i] = Power(baseNumbers[i], exponents[i]);
}
This question already has answers here:
Random number generator only generating one random number
(15 answers)
Closed 4 years ago.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace DieRoller
{
public class Program
{
public static void Main()
{
for (int a = 0; a < 20; a = a + 1)
{
Console.WriteLine(RollDie());
}
Console.ReadLine();
}
public static int RollDie()
{
Random roll = new Random();
int test = roll.Next(1, 6 + 1);
return test;
}
}
}
When I execute this code I get the number 4 multiple times or the number 2 multiple times...etc.
Isn't it supposed to execute the RollDie function for each iteration of the loop? and isn't that supposed to yield a different value each time? pls halp!
EDIT: The thing is guys, I need to generate the randomness only inside the RollDie method, and I can't have any arguments for the RollDie method (Basically I have to generate the randomness only using the random method inside the RollDie method), other questions don't address that.
See comments for explanation of why it doesn't work. Here a possible way to make it work:
public static void Main()
{
Random roll = new Random();
for (int a = 0; a < 20; a = a + 1)
{
Console.WriteLine(RollDie(roll));
}
Console.ReadLine();
}
public static int RollDie(Random roll)
{
int test = roll.Next(1, 6 + 1);
return test;
}
Or, for simplicity, just:
public static void Main()
{
Random roll = new Random();
for (int a = 0; a < 20; a = a + 1)
{
Console.WriteLine(roll.Next(1, 6 + 1));
}
Console.ReadLine();
}
I'm making an application whose job is to generate two lists and display them on demand. As well as update the values every second.
I need to update the list in such a way so that the oldest value in the list is replaced first. How would I do that? Below is my code in it's current state.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Data_Collector
{
//What is needed?
//Need to generate a list of both metric values, and imperial values.
//Need to be able to display a list
public class IMeasuringDevice_Helper
{
private int limit; //Limits the list size.
private float RNDouble;
public void MetricValueGenerator()
{
limit = limit + 1;
Console.WriteLine("Limit Level = " + limit);
if (limit <= 10)
{
List<float> MetricValueGenerated = new List<float>();
Random rnd = new Random();
float rndINT = rnd.Next(1, 10);
RNDouble = rndINT / 10;
Console.WriteLine(RNDouble);
MetricValueGenerated.Add(RNDouble);
}
else
{
Console.WriteLine("limit reached");
}
}
public void ImperialValueGenerator()
{
//TODO
}
}
}
You will need a Queue for this, but you will need to extend it. The default C# Queue is First-In, First-Out (exactly the semantic you want), but does not subscribe to limits the way your code currently handles them. It simply grows by a growth factor if full.
So you will want to extend the Queue object and override the Enqueue method to do what you want. It will probably look a little like this:
public class BoundedQueue<T> : Queue<T>
{
private readonly int _bound;
public BoundedQueue(int bound)
{
_bound = bound;
}
public new void Enqueue(T item)
{
if(Count >= _bound)
{
throw new IndexOutOfRangeException("limit reached");
// If simply throwing an exception isn't cool, you can also do the following to pop off the oldest item:
// base.Dequeue();
}
base.Enqueue(item);
}
}
The only thing to be aware of is when you turn this into some other kind of object for display, you may see it in the reverse order you expect, as the oldest item will be at the 'top' of the queue. You can sort this out by simply calling the Reverse() method that works with most LINQ-enabled objects.
If you don't want to do any class extensions as #YYY has suggested, pretty much replace List with Queue, replace .add() with .Enqueue() and instead of oldestValue = yourList[oldestIndex] use oldestValue = yourQueue.Dequeue().
Aside from your question, your variables should start with a lowercase letter, and RNDouble = rndINT / 10; is going to end up = 0 most of the time because you should divide by 10.0 instead of 10.
Ok so I was bored... (also I wouldn't go with this approach, but I'm guessing you're learning and haven't been taught about Queues, so this might help with Lists):
public class MeasuringDevice_Helper
{
private const int LIMIT = 10; // This is a constant value, so should be defined IN_CAPS in class definition
List<double> metricValues = new List<double>(LIMIT); // This needs to be at class level so it doesn't get lost
Random rnd = new Random(); // This is used frequently so define at class level
public void GenerateMetricValue() // This is now named like the action it performs
{
Console.WriteLine("Current metric values = " + metricValues.Count);
if (metricValues.Count < LIMIT) // This should just be < not <=
{
float rndInt = rnd.Next(1, 10);
double rndDouble = rndInt / 10.0; // An Int divided by Int will = Int
Console.WriteLine("Added " + rndDouble);
metricValues.Add(rndDouble);
}
else
{
Console.WriteLine("limit reached");
}
}
public double PopOldestMetricValue()
{
double value = metricValues[0];
metricValues.RemoveAt(0);
return value;
}
}
I'm having trouble with this method return of the largest integer, compiler says no errors but it won't let me run it
I have no clear idea what you are asking for.. I think at one time you had code but it is now gone?
Anyway, here is a console example for making an array and displaying its max value.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApplication3
{
class Program
{
static void Main(string[] args)
{
//Declare i
int i;
Console.WriteLine("Please enter 5 random numbers");
//Make some array
string[] numbers = new string[5];
for (i = 0; i < 5; i++)
{
Console.Write("\nEnter your number:\t");
//Storing value in an array
numbers[i] = Console.ReadLine();
}
//ta da your array is now completed.. lets see what is the largest..
var converted = numbers.Select(int.Parse);
int largest = converted.Max();
//ta da
Console.WriteLine("The largest number is..." + (largest));
}
}
}