C
C#Max

Infinite loop

c#
/// ------------------------------------------------------------
/// <summary>
/// Creates a stack containing unique random numbers</summary>
/// <param name="lower">The lower bound for each number (inclusive)</param>
/// <param name="upper">The upper bound for each number (inclusive)</param>
/// <param name="count">The number of numbers</param>
/// <returns>The stack containing unique random numbers</returns>
/// ------------------------------------------------------------
public static Stack<int> Opdr3RandomNumbers(int lower, int upper, int count)
{
Stack<int> stack = new Stack<int>();
HashSet<int> voorgekomenGetallen = new HashSet<int>();

Random randomNumber = new Random();

while (stack.Count < count)
{
int number = randomNumber.Next(lower, upper);
bool hasOccurred = occurredNumbers.Contains(number);

while (hasOccurred) {
number = randomNumber.Next(lower, upper);
hasOccurred = occurredNumbers.Contains(number);
}

stack.Push(number);
occurredNumbers.Add(number);
}

return stack;
}
c#
/// ------------------------------------------------------------
/// <summary>
/// Creates a stack containing unique random numbers</summary>
/// <param name="lower">The lower bound for each number (inclusive)</param>
/// <param name="upper">The upper bound for each number (inclusive)</param>
/// <param name="count">The number of numbers</param>
/// <returns>The stack containing unique random numbers</returns>
/// ------------------------------------------------------------
public static Stack<int> Opdr3RandomNumbers(int lower, int upper, int count)
{
Stack<int> stack = new Stack<int>();
HashSet<int> voorgekomenGetallen = new HashSet<int>();

Random randomNumber = new Random();

while (stack.Count < count)
{
int number = randomNumber.Next(lower, upper);
bool hasOccurred = occurredNumbers.Contains(number);

while (hasOccurred) {
number = randomNumber.Next(lower, upper);
hasOccurred = occurredNumbers.Contains(number);
}

stack.Push(number);
occurredNumbers.Add(number);
}

return stack;
}
it cannot find a new number, this is the testcase it fails on: [TestCase(100, 100, 1)]
No description
C
canton744d ago
Your message says [TestCase(100, 100, 1)], but your image says [TestCase(1, 100, 4)]?
M
Max44d ago
yes, sorry copied the wrong one but it fails on both gets stuck in an infinite loop
C
canton744d ago
Which of the two loops does it get stuck in?
M
Max44d ago
the hasOccurred loop
C
canton744d ago
C# Online Compiler | .NET Fiddle
Test your C# code online with .NET Fiddle code editor.
C
canton744d ago
Btw, you can simplify it to:
public static Stack<int> Opdr3RandomNumbers(int lower, int upper, int count)
{
Stack<int> stack = new Stack<int>();
HashSet<int> occurredNumbers = new HashSet<int>();

Random randomNumber = new Random();

while (stack.Count < count)
{
int number = randomNumber.Next(lower, upper);
if (occurredNumbers.Add(number))
{
stack.Push(number);
}
}

return stack;
}
public static Stack<int> Opdr3RandomNumbers(int lower, int upper, int count)
{
Stack<int> stack = new Stack<int>();
HashSet<int> occurredNumbers = new HashSet<int>();

Random randomNumber = new Random();

while (stack.Count < count)
{
int number = randomNumber.Next(lower, upper);
if (occurredNumbers.Add(number))
{
stack.Push(number);
}
}

return stack;
}
Or:
public static Stack<int> Opdr3RandomNumbers(int lower, int upper, int count)
{
Stack<int> stack = new Stack<int>();
HashSet<int> occurredNumbers = new HashSet<int>();

Random randomNumber = new Random();

while (stack.Count < count)
{
int number;
do
{
number = randomNumber.Next(lower, upper);
} while (!occurredNumbers.Add(number));

stack.Push(number);
}

return stack;
}
public static Stack<int> Opdr3RandomNumbers(int lower, int upper, int count)
{
Stack<int> stack = new Stack<int>();
HashSet<int> occurredNumbers = new HashSet<int>();

Random randomNumber = new Random();

while (stack.Count < count)
{
int number;
do
{
number = randomNumber.Next(lower, upper);
} while (!occurredNumbers.Add(number));

stack.Push(number);
}

return stack;
}
If you ask it for more values than as possible to generate it will get stuck, for sure: Opdr3RandomNumbers(1, 1, 2) will get caught. You probably want some guards to avoid that. Something like Opdr3RandomNumbers(1, 10000, 10000) might take a while to run, as it will need to generate a lot of random numbers before it happens to stumble across the 10000 that it needs
M
Max44d ago
it gets stuck on Opdr3RandomNumbers(10, 15, 6); aswell
C
canton744d ago
Yep, of course You've said "Give me 6 unique numbers between 10 and 15", and there are only 5 unique numbers between 10 and 15
M
Max44d ago
so if i want to include 10 and 15 i should make the bounds 1 higher and lower?
C
canton744d ago
With Random.Next, the lower bound is inclusive and the upper is exclusive
M
Max44d ago
No description
M
Max44d ago
this is what i am trying to reproduce
C
canton744d ago
So if you want the upper bound to be inclusive, you'll need to add 1 to it, yes
M
Max44d ago
okay thank you
C
canton744d ago
This is how Python's random.sampledoes this FWIW: https://github.com/python/cpython/blob/main/Lib/random.py#L363 That can take what's effectively an ICollection<T> (so something which has a known length, but all items don't need to be listed in advance), and generate a random sample from it
GitHub
cpython/Lib/random.py at main · python/cpython
The Python programming language. Contribute to python/cpython development by creating an account on GitHub.
M
Max44d ago
thank you, it finally works
Want results from more Discord servers?
Add your server
More Posts
How to connect my c# backend with the frontend?Hello, I created a ASP NET Core Web Api project with the command dotnet new webapi -minimal. In my ✅ Using `Func<ReadOnlySpan<char>,bool>` but not allowed due to Pointer TypeI am building a parser, and performance is of concern. So instead of allocating infinite strings wheconcurrency and atomicity Asp.net core web api and efcorelet's say there's an endpoint called AssingUser() ,this endpoint assigns one donation to this currenBuilding a generic repository for mongodbhello folks I was thinking build a generic repository structure for mongodb. but someday if i want Reading large xml file from archive by using XmlReader in Parallel modeHello 👋. I am looking for how can I read data from archive xml file in Parallel mode. I have archiResizing the Console window - Console ApplicationHi there, I'm trying to resize the console window in a Console Application. I have tried multiple ✅ Creating a datetime with a timezoneHow do I create a `DateTime` with `new DateTime(2010, 05, 12);` and give it a specific `TimeZoneInfoCustom Newtonsoft JSON deserializationI have a dictionary where: - The key will always be a string - The value will be either: - string Issue with Form.Close() in WinformsI have a custom form called CustomMessageBox In that form, I have a method that defines a button clIssue with IMGUI.Net.Hello, I am creating an ImGUI application and It doesn't let me move the ui across my entire screen,Issue with deserializing Enums in saved JSONHey, I've been trying to deserialize a list of cards I serialized in C#, the issue I'm having is it From HttpClient, can I save/copy the request to share with someone?Is there a way to copy raw request details? For example, I'm looking for a similar output like: -3D Unity RaycastingHi guys, currently working on a puzzle game involving lasers and mirrors, however, have hit a brick Computer Science - Computer ArchitectureOn a 64 bit system (where the bus length and word size are 64 bits) how would we determine the ammouConnecting SQLite in MAUIHow to connect the database without absolute path? If with it, the program works only on the computeDifferent HttpClient headersWhen I make an HTTP request in my browser (Chrome), I get different response headers than I do in myHttpRequestException:An error occurred while sending the request. WebExceptionHttpRequestException:An error occurred while sending the request. WebException:Unable to connect to ✅ EF does not put datetimes properly to the datebaseI am writing a backend app in asp.net core. This is my service code : ```c# public virtual async TaShadow Prop Error with IdentityDbContextThis is my IdentityDbContext: public class ApplicationUser : IdentityUser { [Required(ErrorMessWpf custom button template probleHi! I am trying to create custom button control, but I have a problem with a content property. Butto