logo
down
shadow

Random function stuck on one number


Random function stuck on one number

Content Index :

Random function stuck on one number
Tag : c , By : Jody Bannon
Date : January 02 2021, 06:48 AM

hop of those help? You never seed the random number generator.
If rand is called before calling srand, the random number generator is seeded with 1. So you get the same number every time.
srand(time(NULL));
int goal = rand()%50+1;

Comments
No Comments Right Now !

Boards Message :
You Must Login Or Sign Up to Add Your Comments .

Share : facebook icon twitter icon

C# Random Number Generator getting stuck in a cycle


Tag : chash , By : Per
Date : March 29 2020, 07:55 AM
wish helps you If you use only One RNG for multiple threads even if you save the seed, you won't be able to generate the same numbers the next time you launch your application because you won't be sure that the calls to the RNG from the different threads will be in the same order.
If you have a fixed/known number of thread make a RNG per Thread and save each seed.

I'm stuck with while loop on my random number guessing game


Tag : java , By : Arun Thakkar
Date : March 29 2020, 07:55 AM
this one helps. Adding an additional condition in while loop will work. If försök is the number of tries which can have maxium value of 5 (in your case) then condition should be :
while (win == false && försök<5) //if försök starts from 0 
{
   //code
   if(win==true)
   break;
   försök++;
}
if(försök==5)
{
      // display this message: "you failed this mission! do you want to try again?" 
     score=0;
}
else
{
     //display: "congrats you won"
      score=(5-försök)*100;
}
import javax.swing.*;
import java.util.Random;

class Projekt_1
{
public static void main(String[] args) {
        final int maxTries = 5;
        JOptionPane.showMessageDialog(null, "Welcome... " + maxTries + " tries ... 500 krones ");

        final Random rnd = new Random();
        final int hemligtnummer = rnd.nextInt(20) + 1;
        int tryCounter = 0;
        final int pengar = 500;
        String nummer;

        int guess = -1;

        while (guess != hemligtnummer && tryCounter < maxTries) {
            if(tryCounter==0)
            nummer = JOptionPane.showInputDialog("...a number 1 and 20");
            else
            nummer = JOptionPane.showInputDialog("Enter no...");
            guess = Integer.parseInt(nummer);
            if (guess == hemligtnummer) {
                break;
            } else if (guess > hemligtnummer) {
                JOptionPane.showMessageDialog(null, "Try " + (tryCounter+1) + " was too big try a smaller one");
            } else if (guess < hemligtnummer) {
                JOptionPane.showMessageDialog(null, "Try " + (tryCounter+1) + " too small try a bigger one");
            }
            tryCounter++;
        }
        if(tryCounter==5){
            JOptionPane.showMessageDialog(null,"Grattis du vann!" + "\nteh number was " + hemligtnummer + "\nDet tog dig " + tryCounter + " försök");
            JOptionPane.showMessageDialog(null, "Your price is :" + (pengar - tryCounter * 100) + " Krones");
        }
        else
        {
            JOptionPane.showMessageDialog(null,"congrats you won"+"Your price is :" + (pengar - tryCounter * 100) + " Krones" );
        }
    }
}

Random loop works as planned but gets stuck on specific random number after a few calls


Tag : javascript , By : Adrian Codrington
Date : March 29 2020, 07:55 AM
it fixes the issue Your code's main problem is that you are not preventing the same color from being selected multiple times. When you run it the first time, there is a high likelihood that at least one of your colors will be chosen twice. Think of it as simply selecting a number between one and ten at random. It is very difficult to randomly choose a different number ten times and never repeat.
Therefore, when you run your function again you have changed the backgroundColor property of each box, and some of them will have the same color, i.e. you do not have 13 different colors to choose from anymore. This means the second time your function runs you have fewer choices, and this continues and continues until you end up with only one or two possible colors to choose and every box ends up with the same color.
var bloop = document.getElementsByClassName('specs');

for (var i = 0; i < bloop.length; i++) {
  bloop[i].onclick = function() {
    var colours = ['aqua','chartreuse','deeppink','dodgerblue','gold','indigo','lightpink','mediumpurple','coral','springgreen','red','peachpuff','deepskyblue'];
    for (var i = 0; i < bloop.length; i++) {
      var rando = Math.floor(Math.random()*colours.length)
      bloop[i].style.backgroundColor = colours[rando];
      colours.splice(rando, 1);
    }
  }
}
.specs{
  display:inline-block;
	height:100px;
	width:100px;
	border:3px solid white;
}

.aqua1{
	background-color:aqua;
}

.chartreuse1{
	background-color:chartreuse;
}

.deeppink1{
	background-color:deeppink;
}

.dodgerblue1{
	background-color:dodgerblue;
}

.gold1{
	background-color:gold;
}

.indigo1{
	background-color:indigo;
}

.lightpink1{
	background-color:lightpink;
}

.mediumpurple1{
	background-color:mediumpurple;
}

.coral1{
	background-color:coral;
}

.springgreen1{
	background-color:springgreen;
}

.red1{
	background-color:red;
}

.peachpuff1{
	background-color:peachpuff;
}

.deepskyblue1{
	background-color:deepskyblue;
}
<div class="aqua1 specs">
	
</div>

<div class="chartreuse1 specs">
	
</div>

<div class="deeppink1 specs">
	
</div>

<div class="dodgerblue1 specs">
	
</div>

<div class="gold1 specs">
	
</div>

<div class="indigo1 specs">
	
</div>

<div class="lightpink1 specs">
	
</div>

<div class="mediumpurple1 specs">
	
</div>

<div class="coral1 specs">
	
</div>

<div class="springgreen1 specs">
	
</div>

<div class="red1 specs">
	
</div>

<div class="peachpuff1 specs">
	
</div>
<div class="deepskyblue1 specs">
	
</div>

Random number function: how do I set different upper limits for a random number function to adjust difficulty in my gues


Tag : python , By : user176691
Date : March 29 2020, 07:55 AM
it should still fix some issue I created a random number guessing game, and it works fairly well except for two problems. One, I tried to add a function that will allow the user to select difficulty and I couldn't figure it out. Two, when the user wins the game and selects "Y" to continue the game again, it doesn't generate a new random number. , your code should looks like:
def choose_difficulty():
    difficulty = input("Please select a difficulty: (E)asy, (M)edium, (D)ifficult, (G)od Mode")

    if difficulty.upper() == "E":
        upper_limit = 11
    elif difficulty.upper() == "M":
        upper_limit = 26
    elif difficulty.upper() == "D":
        upper_limit = 500
    elif difficulty.upper() == "G":
        upper_limit = 1000000
    return upper_limit

upper_limit = choose_difficulty()
random_number = random.randint(1, upper_limit)

guesses_left = 3
play = True
while True:
    while guesses_left > 0:
        guess = int(input("Guess a number between 1 and {}: ".format(upper_limit)))
        if guess == random_number:
            print("Congratulations! You guessed correctly.")
            retry = input("Try again? Y/N ")
            if retry.upper() == "Y":
                guesses_left = 3
                random_number = random.randint(1, upper_limit)
                upper_limit = choose_difficulty()
                continue
            elif retry == "N":
                break

        elif guess != random_number:
            if guess > random_number:
                if (guess - random_number) < 4:
                    print(hot)
                else:
                    print(cold)
                print("Your guess is too high.")
            elif guess < random_number:
                if (random_number - guess) < 4:
                    print(hot)
                else:
                    print(cold)
                print("Your guess is too low.")
            print("Guess again sucker")
            guesses_left -= 1
            continue
    else:
        print("Sorry, you only had three guesses.")
        retry = input("Try again? Y/N ")
        if retry.upper() == "Y":
            guesses_left = 3
            random_number = random.randint(1, upper_limit)
            upper_limit = choose_difficulty()
            continue

        elif retry == "N":
            break

C# Random number generator stuck in loop


Tag : chash , By : Mariocki
Date : March 29 2020, 07:55 AM
Related Posts Related QUESTIONS :
  • Display processes that access a folder
  • How to printf a time_t variable as a floating point number?
  • Parenthesis operator in C. What is the effect in the following code
  • Is there table with timing(cost) of C functions?
  • How can I access a global pointer outside of a C function?
  • Are fopen/fread/fgets PID-safe in C?
  • How can multiple variables be passed to a function cleanly in C?
  • How to use pthread_atfork() and pthread_once() to reinitialize mutexes in child processes
  • Find function call in a list of binaries
  • How to return a single variable from a CUDA kernel function?
  • How to get number of cores in Win32?
  • Handling aces and finding a segfault in a blackjack program
  • function prototype declarations
  • How to convert from Hex to Decimal using only Integers in C
  • How to parse from char array using yacc?
  • I can not work with linked list inside linked list
  • Finding the index of largest number
  • Decompose a number to product of prime numbers and print it like 18=2*3^2
  • programming EXACT timer which calles a function in c language every x seconds
  • Combining macros generate errors
  • Why am I not getting error when I store values of different types in an array in C language?
  • What is the purpose of the base case dp[0] = -1 of this DP array in the palindromic partitions problem?
  • Having function choose largest number of given ones
  • Data structures layout
  • How to retrieve probuf from C library
  • Printf float number in hexadecimal format returns random vlaue
  • Memory allocation in C from 1 to N
  • Emit signal from separate thread in glib/gtk
  • How to fix Valgrind "Conditional Jump..." error
  • The text to be printed is being printed on the command line rather than print space while using fork on terminal
  • Deleting an element from an array of structures
  • How to read time stamp data from text file using C code?
  • I can't understand this code? Is it normal or I'm not ready?
  • GTK character count vs byte index
  • Summing up integers in an array and storing the result in an array
  • JITtting with limited knowledge of the target architecture
  • Why does global pointers behave erratically in this function?
  • Write a basic half pyramid pattern program
  • Read memory in C
  • void affecting output of the program
  • How to limit scanf while reading input from file
  • Why does the C runtime not call my exit()?
  • Can anyone say why the array is not changed when passed to a function
  • Integer overflow (Smallest file size that will make the integer in program become negative in bits)
  • Array of pointers to strings(base type of pointers)
  • Is there any way to limit integer datatype value range
  • How to print 2-byte unicode characters
  • The execution of open when using O_CREAT
  • Parsing Command Line Arguments for Shell
  • Undefined length of character arrays
  • Do condition formats in if/else if statements have to match in C?
  • Generate ordered passwords for brute forcing in C
  • Problems with pointer into structure
  • Why does this C program print output "10" irrespective of the for loop?
  • taking output 2D array in matrix form
  • sizeof char pointer and pointer to pointer
  • does the following program cause memory leak?
  • Innacurate file readings from fopen and/or fscanf
  • Searching an element in an Array using Recursive Function in C Language
  • Most fastest C code to count recursively directories in Linux ( without files )
  • shadow
    Privacy Policy - Terms - Contact Us © scrbit.com