lundi 31 décembre 2018

A difference between Seed and Rand.Seed

The golang docs says that

Seed, unlike the Rand.Seed method, is safe for concurrent use.

The rand.Seed is actually from math/rand package, but what is Seed? If Seed is another function then it's not present in math/rand so it's unclear from where that function comes from?




div img src not displaying random image

I have code for a random image in the php section of my page

$imagesDir = 'images/eggs/';
$images = glob($imagesDir . '*.{jpg,jpeg,png,gif}', GLOB_BRACE);
$randomImage = $images[array_rand($images)];

it will display an image with this code

echo "<img src='$randomImage'>";

but when i try to do this in the body section of the page like this

<body>';
}
function template_body_above()
{
global $context, $settings, $options, $scripturl, $txt, $modSettings;
echo !empty($settings['forum_width']) ? '
<div id="wrapper" style="width: ' . $settings['forum_width'] . '">' : '', '
<div class="forest">
    <div id="egg1"></div>
</div>
<div id="header"><div class="frame">
    <div id="baloon1">
            <img src="egg.php"/> //tried including seperate php code
            <img src="<?php echo $randomImage ?>"> //php on same page
    </div>

I am showing for the image source ...%3C?php... Any help on where I'm going wrong ?




8 dice to be thrown simultaneously write the MIPs assembly language to provide this final sum [on hold]

] A new board game is to be created which requires 8 dice to be thrown simultaneously. All the numbers on the 8 dice are to be added up in order to allow game pieces to move around a board. e.g. 8 dice are thrown and they fall randomly face up as follows: 2,3,6,1,3,5,3,4. The sum of this total “throw” is 27. A very simple, microprocessor based handheld device is to be provided with the board game which simulates 8 dice being thrown at once and displaying the final sum of all dice. Using the “random” Syscall combined with a loop structure, write the MIPs assembly language to provide this final sum.




Javascript Input Form with Output Random Word Question

How can I create a form with an input where you can enter some text and a submit button.

When the user inputs some text and submits, below the form you should get the text with the letters of the text arranged in random order.

For instance if the input is Hello, the output could be olelH. I could manage to code a form with textbox, and I also know how to random it but I couldn't merge them together.




dimanche 30 décembre 2018

Randonly select numbers from a range of cells i have 8 numbers and i want to randonly select 7 in different cells

I have data in cells J3:R3

I want to randomly select 7 of them and put them into a table B2:H18 where in B2:H2 there are no duplicates.

=INDEX($J$3:$R$3,RANDBETWEEN(1,7)) this works but cant handle duplicates =CHOOSE(RANDBETWEEN(1,7),J$3:R$3) this didn't work




Java Code isn't working properly when it should

So i have been trying to help myself learn a japanese by making a randomizer. when i run this code it says there are errors but ive looked through and can't find any. for some reason it doesn't see that the Ename is the same as answer. they are both string variables so i don't understand why it wont work properly. I would love to learn why it isn't working. Thank you for those more knowledgable than me.

import java.util.Random; import java.util.Scanner;

public class Game { Scanner in = new Scanner(System.in);

public int enemyCount = 4; // always need to be one less than the enemy

public String Jname;//Japanese Character
public String Ename;//English Character


public static void main(String[] args) 
{

    new Game();

}

public Game(){

    battleMainMenu();
}

public void RandomEnemy() 
{


    Random random = new Random();

    int rnd = random.nextInt(enemyCount);

    if (rnd == 0)
    {

        Jname= "あ";

        Ename= "a";

    }
    else if (rnd == 1)
    {

        Jname ="い";

        Ename ="i";


    }
    else if (rnd == 2)
    {

        Jname="う";

        Ename="u";

    }
    else if (rnd == 3)
    {

        Jname="え";

        Ename="e";

    }
    else if (rnd == 4)
    {

        Jname="お";

        Ename="o";

    }

    System.out.println("\nYou walk around and encounter a "+ Jname );

}

public void battleMainMenu() 
{
    RandomEnemy();

    System.out.println("\nTo defeat this enemy you must write "+ Jname +"'s name in english. " + Ename);// Enames here for debugging purposes
    System.out.println("Your options are : 'a', 'i', 'u', 'e', 'o' ");
    System.out.println("Type one of the options in lower case. ");

    String answer = in.nextLine();
    System.out.println(answer);
    System.out.println(Ename);
    if (answer == Ename)
    {
        System.out.println("\nCorrect!\n");

    }
    else
    {
        System.out.println("\nIncorrect!\n");
        battleMainMenu();
    }
}

}




Randint won't execute

Why does this error pop at the first line:

NameError: name 'random' is not defined

correctPath = random.randint(1,2,3)

if chosenPath == str(correctPath):
   print("Thank you for your help")
   print("this has been altered for creative purposes")
elif chosenPath != str(correctPath):
    print("Thanks in advance.")
else:
   print ("code to be written")




How to create a list with a random number of random integers in Python

I want to create a list that is a random length of randomly chosen integers. What I have so far is: a = [random.randint, random.randint, random.randint] and it goes on, but I want it so that it isn't however many times I typed "random.randint", but it uses the random function to generate a random number of random integers.




How do I select a random word within a cell on Google Sheet?

Other questions tend to answer how to select a random cell, but I want to randomly select a random word from a cell that is generated by a form field using the "paragraph" answer option.




How to generate a random number that is evenly divisible by another randomly generated number in JavaScript

I'm working on a simple math flashcards app using JavaScript and jQuery. The available operations are addition, subtraction, multiplication, and division, each of which have functions that use generateTop() and generateBottom() to assign values to HTML elements.

I'm having trouble figuring out how to use my division problem function to generate random numbers so that the topNumber is evenly divisible by the bottomNumber. I'm using the following code to generate random numbers for each problem:

let topNumber = 0;
let bottomNumber = 0;

function generateTop(max, min){
  topNumber = Math.floor(Math.random() * (max - min) + min);
  return topNumber;
};

function generateBottom(max, min){
  bottomNumber = Math.floor(Math.random() * (max - min) + min);
  return bottomNumber;
};

Here is my current division problem generator:

function division(){
  problemTop.html(generateTop(1, 144));
  problemBottom.html(generateBottom(1, topNumber));
  opSym.html("÷");
}

I can adjust the max and min to get a positive integer for addition, subtraction, and multiplication problems but am stuck on how to ensure that I get a positive integer for division problems. I've tried messing with some different loop ideas but haven't gotten anything to work. I want to keep min at 1 and max at 144.

I've checked SO for solutions but can only find how to generate random numbers divisible by one other explicit, hard-coded number. How can I adjust my division function so that the topNumber can be divided evenly by the bottomNumber? Any help is greatly appreciated.




What are use cases to hand over different numbers in random.seed( 0 )

What are use cases to hand over different numbers in random.seed(0)?

import random
random.seed(0)
random.random() 

For example, to use random.seed(17) or random.seed(9001) instead of always using random.seed(0). Both return the same "pseudo" random numbers that can be used for testing.

import random
random.seed(17)
random.random() 

Why dont use always random.seed(0)?




samedi 29 décembre 2018

Converting a Uniform Distribution to a Fat-tailed Distribution

This previous SO question regards converting a Uniform distribution to a Normal distribution.

For Monte-Carlo simulations, I have a need not only for Normal (Gaussian), but for some computationally efficient ways to generate samples from "fat-tailed" or heavy-tailed distributions, using a given (64-bit or double) uniform RNG as input. Examples of the distributions needed may include: Log-normal, Pareto, Student-T, Cauchy, et.al.

Use of inverse CDFs is acceptable given computationally efficient means of computing the inverse CDF as needed.

The tag is for a language-independant algorithms, but the implementations needed are for basic procedural programming languages (C, Basic, procedural Swift, Python, et.al.)




Can't make this random number generator to work properly

I'm trying to make a random number generator and return the random generated number, but this code returns all the numbers before the random number. How can I return only the last string printed?

import random

from_num = int(input('Generate a random number:\nFrom:'))
to_num = int(input('To:'))

for num in range(random.randrange(from_num,to_num+1)):
    if True:
        print(f'Random number: {num}')
    else:
        print('You did not entered valid min/max numbers')

Output for from_num = 0 and to_num = 20 by exemple, instead of '11' can return any number between these two given.

Random number: 0
Random number: 1
Random number: 2
Random number: 3
Random number: 4
Random number: 5
Random number: 6
Random number: 7
Random number: 8
Random number: 9
Random number: 10
Random number: 11




Creating random numbers for a multidimensional array in an instantiated class

I'm creating a bingo game where the users choose how many players will be playing and how many tickets every player will be having. I have two classes, one for players and another one for bingo tickets. When the users have written the amount of players and tickets i instantiate both classes. The BingoTicket class have a multi-dimensional array which gets initialised to [3,5] automatically. I tried to create unique random numbers for each bingo ticket but i get the same numbers in each ticket.

I have created a variable ticketId for the Player and BingoTicket classes and my intention was to connect each ticket to a player, but I can't find the way to do it either. The ticket count doesn't seem to work and every ticket gets the same number

I tried creating a method inside the BingoTicket class that automatically creates random numbers for each array but I get the same numbers for every ticket. And for connecting the two classes I don't know where to start.

    public static void Main(string[] args)
    {
        int numberOfPlayers = 0;
        int numberOfTickets = 0;
        bool rightAnswer = false;
        Console.WriteLine("Please write how many players are going 
        to play. (1-4 players)");
        while (rightAnswer == false)
        {
            try
            {
                numberOfPlayers = int.Parse(Console.ReadLine());
            }
            catch (Exception)
            {
                Console.WriteLine("Please write a valid number.");
                continue;
            }
            if(numberOfPlayers > 0 && numberOfPlayers <= 4)
            {
                rightAnswer = true;
            }
            else
            {
                Console.WriteLine("Please write a valid number of 
                players from 1 to 4.");
            }

        }
        // Instantiating as many players as the user wants.
        List<Player> players = new List<Player>();

        for (int i = 0; i <= numberOfPlayers; i++)
        {
            Player player = new Player(i, "Player" + i++);
            players.Add(player);
        }


        rightAnswer = false;
        Console.WriteLine("Please write how many tickets every 
        player is going to have. (1 or 2 tickets per person)");
        while (rightAnswer == false)
        {
            try
            {
                numberOfTickets = int.Parse(Console.ReadLine());
            }
            catch (Exception)
            {
                Console.WriteLine("Please write a valid number.");
                continue;
            }
            if(numberOfTickets > 0 && numberOfTickets <= 2)
            {
                rightAnswer = true;
            }
            else
            {
                Console.WriteLine("Please write a valid number of 
                tickets from 1 to 2.");
            }
        }
        // Instantiating as many tickets as the user wants.
        List<BingoTicket> bingoTickets = new List<BingoTicket>();
        numberOfTickets *= numberOfPlayers;
        for(int i = 0; i < numberOfTickets; i++)
        {
            BingoTicket bingoticket = new BingoTicket(i, (new int[3, 
            5]));
            bingoTickets.Add(bingoticket);
        }
    }

    // == BINGOTICKET ==
    public class BingoTicket
    {
        Random rnd = new Random();

        void PrintArray(int[,] array)
        {
            var rowCount = array.GetLength(0);
            var colCount = array.GetLength(1);
            for (int row = 0; row < rowCount; row++)
            {
                for (int col = 0; col < colCount; col++)
                    Console.Write(String.Format("{0}\t", array[row, 
                    col]));
                Console.WriteLine();
            }
        }

        private int ticketId = 0;
        private int[,] ticketNumbers = new int[3, 5];

        public int TicketId
        {
            get { return ticketId; }
            set { ticketId = value; }
        }

        public int[,] TicketNumbers
        {
            get { return ticketNumbers; }
            set { ticketNumbers = value; }
        }

        public BingoTicket(int ticketId, int[,] ticketNumbers)
        {
            this.ticketId = TicketId;
            this.ticketNumbers = TicketNumbers;
            for (int i = 0; i <= 4; i++)
            {
                ticketNumbers[0, i] = rnd.Next(1, 100);
            }
            for (int i = 0; i <= 4; i++)
            {
                ticketNumbers[1, i] = rnd.Next(1, 100);
            }
            for (int i = 0; i <= 4; i++)
            {
                ticketNumbers[2, i] = rnd.Next(1, 100);
            }
            Console.WriteLine("Player ticket number: " + TicketId);
            PrintArray(ticketNumbers);
        }
    }

    // == PLAYER ==
    public class Player
    {
        private int ticketId;
        private string name;

        public int TicketId
        {
            get { return ticketId; }
            set { ticketId = value; }
        }
        public string Name
        {
            get { return Name; }
            set { Name = value; }
        }

        public Player(int ticketId, string name)
        {
            this.ticketId = ticketId;
            this.name = name;
        }
    }
}




filling an array with random numbers in an instantiated class

I'm creating a bingo game where the users choose how many players will be playing and how many tickets every player will be having. I have two classes, one for players and another one for bingo tickets. When the users have written the amount of players and tickets i instantiate both classes. The BingoTicket class have a multi-dimensional array which gets initialised to [3,5] automatically. The problem that I have is that I want to fill that array with random numbers as the classes gets instantiated but as the classes aren't instantiated at the moment of writing the code I can't access the variables inside the class and I can't create that method inside that class either. Which would be the way to do it?

I tried creating a for-loop inside this BingoTicket's class and creating the method in the Main class but i can't do it either way.

This is the code inside Main class:

rightAnswer = false;
        Console.WriteLine("Please write how many tickets every 
player is going to have. (1 or 2 tickets per person)");
        while (rightAnswer == false)
        {
            try
            {
                numberOfTickets = int.Parse(Console.ReadLine());
            }
            catch (Exception)
            {
                Console.WriteLine("Please write a valid number.");
                continue;
            }
            if(numberOfTickets > 0 && numberOfTickets <= 2)
            {
                rightAnswer = true;
            }
            else
            {
                Console.WriteLine("Please write a valid number of tickets from 1 to 2.");
            }
        }
        // Instantiating as many tickets as the user wants.
        List<BingoTicket> bingoTickets = new List<BingoTicket>();

        for(int i = 0; i < numberOfTickets; i++)
        {
            BingoTicket bingoticket = new BingoTicket(i, (new int[3, 
            5]));

            bingoTickets.Add(bingoticket);
        }
    }

This is the class BingoTicket:

public class BingoTicket
    {
        private int ticketId = 0;
        private int[,] ticketNumbers = new int[10, 3];

        public int TicketId
        {
            get { return ticketId; }
            set { ticketId = value; }
        }

        public int[,] TicketNumbers
        {
            get { return ticketNumbers; }
            set { ticketNumbers = value; }
        }

        public BingoTicket(int ticketId, int[,] ticketNumbers)
        {
            this.ticketId = TicketId;
            this.ticketNumbers = TicketNumbers;
        }
    }

The expected result will be that when i instantiate as many tickets as the user wants, the int[,] ticketNumbers array gets automatically filled with random numbers.




Create random minutes date between given hours

Desired output: Time gap in given range of time, namely from 5:30 to 8:15 Something like:

05:17   
07:01        
06:05        
06:09        
05:16        
07:26  

Tried this one: Create random time stamp list in python but getting an error in:

for x in random_date(startDate,10):
  print x.strftime("%d/%m/%y %H:%M")




vendredi 28 décembre 2018

C++ card randomizer

I am making card game with c++ so can i make simpler card randomizer here is code for ace I have made this far

#include <iostream>
#include <string>
using namespace std;

int kort1;
string ko1;

kort1 = rand() % 52 + 1;

if (kort1 == 1 or kort1 == 14 or kort1 == 27 or kort1 == 40){
    ko1 = "| A| ";
}

and thanks




What are some shuffling algorithms I can implement?

I am building a mixnet and right now I am looking for an algorithm that can give me a random, secret permutation when applied to the corresponding inputs. The correspondence of the inputs and outputs should be hidden from observers.




How can i generate random binary trees? (Python/JS)

How can i generate random binary trees with a format like this?

CA
AD
AB
CF
FH
HI
IF
HG

Representation of the tree above

Trees can be unordered and unbalanced.
A tree should not have more than 9 node but it can have less.
The depth of trees can be whatever.
I would prefer using Python or Javascript.

Thank you.




Create a random list from 0-100 with different lengths

I want to generate a list from 0-100 but my criteria is as follows:

  1. The list must start with 0 and end with 0.

  2. No 0 in between.

  3. Different lengths

for example:

ex1.

    print(generated_list)

    [0,1,3,5,6,7,6,8,9,0]

ex2.

    print(generated_list)

    [0,4,7,8,3,4,9,12,44,2,11,56,32,99,0]




random-poisson value for entire list in netlogo

I have agents called 'orders' Within these agents there is a number of devices as an attribute. Depending on the age of each of the devices, a certain number of devices will break in accordance with a random-poisson process. For example:

Orders have attributes:

  • Number of installed devices (amount-installed)
  • Number of broken devices (amount-broken)
  • Number of devices broken this timestep (broken-this-year)
  • Age of the devices in this order (order-age)
  • Average lifespan of the order (average-lifespan)

I have found a few ways on how to implement this using a filter in a list approach:

ask orders [
    let broken-list n-values amount-installed [random-poisson order-age]
    set broken-list filter [s -> s >= average-lifespan] broken-list
    set broken-this-year length broken-list
    set amount-installed amount-installed - broken-this-year
    set amount-broken amount-broken + broken-this-year
]

Another way I have found to implement this is using a while-loop approach:

 ask orders [
    while [amount-checked < amount-installed] [
      if random-poisson order-age >= average-lifespan [
        set broken-this-year broken-this-year + 1
      ]
      set amount-checked amount-checked + 1
    ]
    set amount-installed amount-installed - broken-this-year
    set amount-broken amount-broken + broken-this-year
]

There should therefore be a number of the installed devices that break, while a number of devices still remain working. However, each order consists of several thousands of devices, and there are hundreds of orders in my model. This process therefore takes an extremely long time to the point that the computer freezes. There must be a way to attain the same results without using a loop method. Does anyone know a better way to approach this?




How can I check if every single int in a randomly generated array is even and make it create another random array if it's not?

So I'm trying to create a program that creates a randomly generated array with numbers between 0 and 10. Every time a number inside the 4x4 array is odd I want it to generate a brand new array and print every array discarded aswell until it creates a 4x4 array with only even numbers. The problem right now is that I can't understand how to fix the last "for" and make it work properly with the boolean "b" that is supposed to restart the creation of the array.

    import java.util.Scanner;
    public class EvenArrayGenerator{
public static void main(String a[]){


    Boolean b;
    do{
     b=true;
    int[][] Array = new int[4][4];
    for(int i=0;i<4;i++){
        for(int j=0;j<4;j++)
     Array[i][j] = (int)(Math.random()*11);
    }

    for(int i=0;i<4;i++){
        for(int j=0;j<4;j++){
        System.out.print(Array[i][j] + " ");

    }
        System.out.println();
    }
    for(int i=0;i<4;i++){
        for(int j=0;j<4;j++){
     if(Array[i][j] % 2!=0)
            b=false;

        }
    }

    }while(b);
}

}




jeudi 27 décembre 2018

Error: TypeError: 'str' object cannot be interpreted as an integer while trying to pick a random winner (Python)

I'm kind of new to programming and I've been trying to mess with Python a bit but while I was trying to make a random name picker that picks a random name from a list I always end up getting the same error .I also try to remove the winner that the code chose and add a new name to the 'winners' list but it doesn't seem to work. This is the short code I have right now.

winners = ["Wane", "Trevor", "Franklin", "Martoz"]
winner = random.choice(winners)
winners.pop(winner)
winners.append("Michael")
print(winners)




Rapid Repetative Samples Pandas Dataframe

First, I want to take random samples from 3 small dataframes and concat the results. Second, I want to repeat this process as many times as possible, filter out uninteresting selections and store and examine the interesting results (later on).

For part 1 I use the following approach now:

def get_sample(n_A, n_B, n_C):
    A = df_A.sample(n = n_A, replace=False)
    B = df_B.sample(n = n_B, replace=False)
    C = df_C.sample(n = n_C, replace=False)
    return pd.concat([A, B, C])

For part 2 I use:

def get_picks(n):
    return [pick for pick in [get_sample(5,5,3) for i in range(n)] if (pick_value(pick) > 750 and pick_price(pick) < 90)]

Currently repeating this thing for 50.000 times takes about 1 minute and 40 seconds on my MacBook? Is that the best I can expect?

Part 2 entails a list comprehension (and if clause) that calls get_sample 50.000 times. The get_sample function concatenates random samples from three different dataframes. The 3 dataframes in the get_sample() method are preset, each have a size of about 150 rows and don't change in the course of the experiment. The 3 dataframes differ in one categorical value.

Any advise on how to improve the speed of this process or alternative approaches to take random samples are welcome of course.




Add a random value in a vector in R

I have a numeric vector

vect <- c(0,16,11,132,0,0,0,18,28,245,0,0,55,45,19,30,20,0,0,0,12,0)

There are four series of values not equal to zero.

(16,11,132), (18,28,245), (55,45,19,30,20), (12)

For 1/4 of series (one serie) randomly choosed, I want to add a random integer value between -10 and 10.

For example, if the chosen serie is the second one and the chosen value is -5 the result will be

vect2 <- c(0,16,11,132,0,0,0,13,23,240,0,0,55,45,19,30,20,0,0,0,12,0)

This is an example of only one row, the function will be applied to the entire matrix




How to select randomly from a list of strings a token excluding numbers?

I know that in python in order to randomly pull a word from a token we could do:

In:

import random 
s = 'hi there 3'
words = s.split() 
random.choice(words)

Out:

3

However, how can I choose the next word (in this case hi) instead of a number? I would like to always guarantee that I am pulling a string not a number?.




Repeatedly shuffling a deck of cards in R

I have a problem with writing a code labyrinth, which will repeatedly shuffle the deck of cards. I have a line written that shuffles my waist, but each time the deck is shuffled in the same way. I need help writing the code so that each time the cards are shuffled in a different way.

shuffling <-sample(deck,length(deck))




Drain the entropy of std::random_device

I'm using std::random_device and would like to check for its remaining entropy. According to cppreference.com:

std::random_device::entropy

double entropy() const noexcept;

[...]

Return value

The value of the device entropy, or zero if not applicable.

Notes

This function is not fully implemented in some standard libraries. For example, LLVM libc++ always returns zero even though the device is non-deterministic. In comparison, Microsoft Visual C++ implementation always returns 32, and boost.random returns 10.

The entropy of the Linux kernel device /dev/urandom may be obtained using ioctl RNDGETENTCNT - that's what std::random_device::entropy() in GNU libstdc++ uses as of version 8.1

So under Linux ang g++ >= 8.1, I should be good... but I'm not:

#include <random>
#include <iostream>

void drain_entropy(std::random_device& rd, std::size_t count = 1)
{
    while (count --> 0) {
        volatile const int discard = rd();
        (void) discard;
    }
}

int main()
{
    std::random_device rd;
    std::cout << "Entropy: " << rd.entropy() << '\n'; // Entropy: 32
    drain_entropy(rd, 1'000'000);
    std::cout << "Entropy: " << rd.entropy() << '\n'; // Entropy: 32
}

Live demo on Coliru (which runs under Linux, right?)

What's happening?




Generate random letters

string bolsa_letras::letters_generator(int quantity){
    int already_generated = 0;
    map<char, int> aux = values;
    string out;
    while(already_generated != quantity){
        char generated_char = 'A' + rand()%26;
        if(aux[generated_char] > 0){
            out.push_back(generated_char);
            aux[generated_char]--;
            already_generated++;
        }
    }

    return out;
}

Above is the code that given a number generates random letters.

The map saves the letters and the times that letters can be appeared. The problem is that every time i run the code, it prints the same: NLRBBMQH. Why is so?

I have include cstdlib for the rand function.




mercredi 26 décembre 2018

Dieharder test on custom PRNG

I`m working on a homework assignment , I wrote my custom pseudo random number generator and I was curios to test it with dieharder (linux).

I tried more tests, 10.000, 100.000 , 1.000.000, 10.000.000 numbers and every time all tests fail , and every time all p values are 0.000000 (zero). Every time , every test. I have to generate numbers between 0 - 255

I was thinking that my generator is broken, but how can I be sure, I read about the p value but I can`t find anything about it being 0 , I read that if it is a small value it should be a good thing.

If you need I will post my algorithm for generating the numbers.

My file:

#================================================================== 
 # generator rnd2 seed = 184752158 
 #================================================================== 
 type: d 

 count: 1000000

 numbit: 32 

and my numbers one below the other.

and command: dieharder -g 202 -f myfile.txt -a.




New to arduino. "Random" values are repeating upon reset

I am coding a roulette game in arduino's C based environment that flashes LEDs to represent the ball circling and stopping. My problem is that the ball stops at the same location every time. I am using randomSeed(analogRead(0)) combined with random(min,max) to generate a random number. This random number represents where my ball "enters". However when I reset my arduino, I get the same exact results. Does anyone know where my problem may lie?

Some important notes

-I am calling random in the global scope because I want a single random starting point for my roulette game (where the "ball" enters). Would having randomSeed in the setup and random in the global scope cause a problem when these two work together? I am new to how "setup" interacts with the rest of the code in arduino.

-The random number I am generating is in a very small range (0-4). However I have reset my arduino many times and gotten 2 as the first number about 30 consecutive times.

I've also tried calling randomSeed in the global scope instead of setup but I get hit with the following error when I do so. " exit status 1 expected constructor, destructor, or type conversion before '(' token "

If there is any more details I can provide or if anyone knows of a post on a similar issue please let me know.




Python: Generate n random integer numbers between two values summing up to a given number

I would very much like to generate n random integer numbers between two values(min,max) whose sum is equal to a given number m.

Note: I found similar questions in stackoverflow, however they do not address exactly this problem (use of dirichlet function and thus numbers between 0 and 1).

Example: I need 8 random numbers (integers) between 0 and 24 where the sum of the 8 generated numbers must be equal to 24.

Any help is appreciated. Thanks.




WebGL Resetting vertex positions

I am creating a simple webgl program that puts 3 random vertices on the canvas and connects them into a triangle. I tried to add translation to move the triangle to the right (increase the X value of each vertex), but of course if it goes forever, the triangle will go out of the canvas. Does anyone know how to detect if the vertex has an x value above 1 and if yes, reset the position of the given vertex because my solution doesnt seem to do anything, its like it doesnt even trigger

      <!-- language: lang-js --> 
  var canvas = document.getElementById("canvas");
  var gl = canvas.getContext("webgl");

  gl.clearColor(0.1, 0.2, 0.2, 1.0);
  gl.clear(gl.DEPTH_BUFFER_BIT | gl.COLOR_BUFFER_BIT);

  var indices = [0, 0, 0, 0, 0, 0];
  for(var points = 0; points < 6; points++)
  {
    indices[points] = (Math.random() * 2) - 1;
    //indices[points + 1] = Math.random() < 0.5 ? -1 : 1;
  }

  var buf = gl.createBuffer();
  gl.bindBuffer(gl.ARRAY_BUFFER, buf);
  gl.bufferData(gl.ARRAY_BUFFER, new Float32Array(indices), 
  gl.STATIC_DRAW);

  var vert = gl.createShader(gl.VERTEX_SHADER);
  gl.shaderSource(vert, `
  precision mediump float;

  attribute vec2 position;
  uniform vec2 translation;

  void main(){
    gl_Position = vec4(position + translation, 0.0, 1.0);
  }
  `);
  gl.compileShader(vert);
  var success1 = gl.getShaderParameter(vert, gl.COMPILE_STATUS);
  if (!success1) {
    // Something went wrong during compilation; get the error
    throw gl.getShaderInfoLog(vert);
  }

  var frag = gl.createShader(gl.FRAGMENT_SHADER);
  gl.shaderSource(frag, `
  precision mediump float;
  void main(){
    gl_FragColor = vec4(0.3, 0.6, 0.4, 1.0);
  }
  `);
  gl.compileShader(frag);
  var success2 = gl.getShaderParameter(frag, gl.COMPILE_STATUS);
  if (!success2) {
    // Something went wrong during compilation; get the error
    throw gl.getShaderInfoLog(frag);
  }




  var program = gl.createProgram();
  gl.attachShader(program, vert);
  gl.attachShader(program, frag);
  gl.linkProgram(program);

  var vertLoc = gl.getAttribLocation(program, "position");
  gl.vertexAttribPointer(vertLoc, 2, gl.FLOAT, gl.FALSE, 0, 0);
  gl.enableVertexAttribArray(vertLoc);

  gl.useProgram(program);

  var trans = gl.getUniformLocation(program, "translation");
  var translation = [0.0, 0.0];
  gl.uniform2fv(trans, translation);


  gl.drawArrays(gl.TRIANGLES, 0, 3);
  function loop(){
    gl.clearColor(0.1, 0.2, 0.2, 1.0);
    gl.clear(gl.DEPTH_BUFFER_BIT | gl.COLOR_BUFFER_BIT);
    translation[0] += 0.01;
    gl.uniform2fv(trans, translation);



    gl.drawArrays(gl.TRIANGLES, 0, 3);

    for(var points = 0; points < 6; points++)
    {
      if(indices[points] % 2 == 0){
        if(indices[points] + translation[0] > 1){
          indices[points] = (Math.random() * 2) - 1;
        }
      }
      //indices[points + 1] = Math.random() < 0.5 ? -1 : 1;
    }
    requestAnimationFrame(loop);
  }
  loop();




Drag and drop random image without the source image disappearing

I have the random image working but I would like to drag and drop that image multiple times without (uiimage) disappearing.




mardi 25 décembre 2018

Using a number array to adjust the chances of a specific return value?

I am creating a method called getRandomLetter() that I want to randomly return a single letter from the English alphabet. I want the method to be more likely to return a letter with a higher number associated with it.

I have two arrays. One has chars for each letter in the alphabet. The second has doubles, each representing the chances, out of 100%, that the letter with the same index, in the other array, will be the letter returned by my method.

I am trying to get the method to use the double array to have higher and lower chances to return specific characters.

Unfortunately, my method only returns z and y.

How can I make getRandomLetter() return specific letters/chars according to the numbers I specify for each?

My Code Example:

public class MCVE {
    // each letter's frequency is represented in the next array by
    // the double value at the same index as the letter
    final private static char[] CharArr = "abcdefghijklmnopqrstuvqxyz".toCharArray();
    // Holds each letter's percentage-chance to be chosen
    // For Example: 0.1 is equal to 10%
    // All-together, they add up to 1.0
    final private static double[] DoubleArr = new double[] {
            0.087248322147651, 0.035722017752760335, 0.08010391859709894,
            0.05520675470881143, 0.046763368694522627, 0.018618748646893266,
            0.028144620047629357, 0.021866204806235117, 0.016020783719419788,
            0.07101104135094176, 0.06040268456375839, 0.08703182507036156,
            0.10002164970772895, 0.027711625893050443, 0.009742368478025547,
            0.021433210651656202, 0.0012989824637367395, 0.0458973803853648,
            0.07988742151980949, 0.05260878978133795, 0.0015154795410261962,
            0.022515696038103484, 0.009309374323446633, 0.0012989824637367395,
            0.011690842173630657, 0.006927906473262611};

    private static char getRandomLetter() {
        double randomDouble = ThreadLocalRandom.current().nextDouble(0.0, 1.0);

        char retVal = ' ';
        // subtract each value in DoubleArr from randomDouble until,
        // randomDouble would be < 0, then return the char that is
        // associated with that double
        for(int i = 0; i < CharArr.length; i++) {

            double subtract = DoubleArr[i];
            if (randomDouble - subtract <= 0.0)
                retVal = CharArr[i];
            else
                randomDouble -= subtract;
        }
        return retVal;
    }

    public static void main(String[] args) {
        // get a large sample of chars to test thoroughness
        char[] sampleChars = new char[1000];
        for(int i = 0; i < 1000; i++) {
            sampleChars[i] = getRandomLetter();
        }

        // print 10 characters per line
        int ct = 0;
        for(char c: sampleChars) {
            System.out.print(c + " ");
            ct++;
            if(ct == 10) {
                ct = 0;
                System.out.println();
            }
        }
    }
}




Generate 2 random numbers in MATLAB

How to generate two random numbers α, β ~ U[-1,+1] if β ≥ α?

My first intention was to just generate two vectors and only take the ones which satisfy β ≥ α and discard the rest. However, I think that might change the distribution.




lundi 24 décembre 2018

Generate random numpy array from a given list of elements with at least one repetition of each element

I want to create an array (say output_list) from a given numpy (say input_list) after resampling such that each element from input_list exists in output_list at least once. The length of output_list will be always > the length of input_list.

I tried a few approaches, and I am looking for a faster method. Unfortunately, numpy's random.choice doesn't guarantee that at least one element exists.

Step 1: Generate Data

import string
import random
import numpy as np

size = 150000
chars = string.digits + string.ascii_lowercase
input_list= [
            "".join(
                [random.choice(chars) for i in range(5)]
            ) for j in range(dict_data[1]['unique_len'])]

Option 1: Let's try numpy's random.choice with uniform distribution in terms of probability.

output_list = np.random.choice(
    input_list,
    size=output_size,
    replace=True,
    p=[1/input_list.__len__()]*input_list.__len__()
    )
assert set(input_list).__len__()==set(output_list).__len__(),\
    "Output list has fewer elements than input list"

This raises assertion:

Output list has fewer elements than input list

Option 2 Let's pad random numbers to input_list and then shuffle it.

output_list = np.concatenate((np.array(input_list),np.random.choice(
    input_list,
    size=output_size-input_list.__len__(),
    replace=True,
    p=[1/input_list.__len__()]*input_list.__len__()
)),axis=None)

np.random.shuffle(output_list)
assert set(input_list).__len__()==set(output_list).__len__(),\
    "Output list has fewer elements than input list"

While this doesn't raise any assertion, I am looking for a faster solution than this either algorithmically or using numpy's in-built function.

Thanks for any help.




How secure does a personal password generator have to be?

I'm writing a password generator for my personal use (logins) and i wonder how "secure" it is or how it could be attacked.

The password is generated in the following way:

  1. Input a seed-string (for example: "amazon")
  2. string gets converted to Hash with Rfc2898DeriveBytes
  3. Hash is used to Seed PRNGs
  4. PRNGs select 3 to 4 words from a file with 30k words and insert signs and numbers at some positions
  5. Password is stitched together and copied to Clipboard

I use the hashing funktion so that the PRNGs are always seeded the same way for any given Input. As i never use something like RNGCryptoServiceProvider, i am not sure if this can be exploited in some way. My thoughts are that since only i will run this application on my local machine and not many of my generated passwords will be leaked this should be secure enough.

If a create a new account, ill start the app, input the seed and get a password, if i ever forget that password i can just re-generate it with the seed again, right?




Select random and unique elements from a vector in R

Say a have a simple vector with repeated elements:

a <- c(1,1,1,2,2,3,3,3)

Is there a way to randomly select a unique element from each of the repeated elements? I.e. one random draw pointing which elements to keep would be:

1,4,6 ## here I selected the first 1, the first 2 and the first 3

And another:

1,5,8 ## here I selected the first 1, the second 2  and the third 3

I could do this with a loop for each repeated elements, but I am sure there must be a faster way to do this?

Thanks.




Js: How to pick a corresponding array entry given a randomly selected value

I'm trying to make a story generator for future playthroughs of some of my favourite games. To this end, I want to be able to randomly pick a combat style from an array (which I have succeeded in), but then also pick a corresponding explanation of that style to display in a paragraph.

I have:

function randomValueFromArray(array){
  return array[Math.floor(Math.random()*array.length)];
}
function result() {
    var jobItem = randomValueFromArray(insertJob);
    document.getElementById('jobDisplay').innerHTML = jobItem;
    var newStory = storyText;
    var jobexpItem = randomValueFromArray(insertJobexp),
        yItem = randomValueFromArray(insertY),
        zItem = randomValueFromArray(insertZ);
    newStory = newStory.replace(':insertJob:', jobItem);
    newStory = newStory.replace(':insertJobexp:', jobexpItem);
    newStory = newStory.replace(':inserty:', yItem);
    newStory = newStory.replace(':insertz:', zItem);
}

referring to my arrays, containing lists of potential characteristics.

The jobItem selected might be number 10 on a list of 30. I want to then select entry number 10 in the jobexpItem array, which is an explanation of the entry selected in jobItem. These are listed in different areas for simplicity - I have a table with only the basic descriptors, and a paragraph with explanations included (where the storyText is displayed).

At the moment, I have jobexpItem as a random value just for troubleshooting. How would I link jobexpItem's value to the corresponding random jobItem value chosen?




Which is the best way to generate synthetic data for data science development.

I have a data pipeline in place for streaming and batch data, which collects data from various sources and land it into hadoop's hdfs storage. I want to generate synthetic data with the same schema of the data landed on hdfs as soon as the it's ingested.

Which will be the best architecture to achieve this?




dimanche 23 décembre 2018

How to select a continuous sample at random from a list?

I have input arrays of varying depths, ranging from 20 till 32. I cannot pad them to make them all the same size, so the best option is to randomly select the z-depth of an image at every iteration.

I've read that numpy.random.choice() can be used for this but I get a random arrangement of indices, I want a continuous selection.

z_values = np.arange(img.shape[0]) # get the depth of this sample
z_rand = np.random.choice(z_values, 20) # create an index array for croping

The above gives me:

[22  4 31 19  9 24 13  6 20 17 28  8 11 27 14 15 30 16 12 25]

Which is not useful for me as they are not continuous and I cannot use it to crop my volume.

Is there any way to get a continuous random sample?

Thanks




samedi 22 décembre 2018

How can I evaluate the intersection's volume of a circle and the area above a line. I also would like to apply it. - Python

This is using Python.

I tried to post an image, but failed... So it may be difficult to understand.

I call the intersection of a part inside a circle (of which center is (0, 0) and the radius is 1) and a part above a line (y = x).I call it yellow part.

I would like to evaluate the area of the yellow part with random numbers and without for statement or while statement, but I don't know how to do it.

Plus, I also apply it to 3-D.That is, the intersection of a part inside an ellipse (2x^2+3y^2+z^2-4=0) and a part above plane(x+y+2z-1=0). But this is an additional question. It would be easy to do it if I can do it in 2-D.

I'd like to calculate some of volumes in my experiment. I have tried some of my codes, but they don't work. I appreciate it if you would answer my question.

What I coded↓

import numpy as np
size = 10000

if y - x > 0:
    x = np.random.uniform(-1, 1, size)
    y = np.random.uniform(-1, 1, size)
area = x**2 + y**2
print(len(area[area < 1])/size)

The area of the yellow part would be expected from this code.




How to add a restart button in a bouncing ball game-tkinter python?

I created a bouncing ball game inside python using tkinter and I wanted to add a restart button for when the game ends but I cant get it to work. I created the function in the class game but it cmes up with a type error saying Game() takes no argumens. Can anybody help me please?

TypeError: Game() takes no arguments

Here is my code:

from tkinter import *
import random
import time

class Ball:
def __init__(self, canvas, paddle, score, color):
    self.canvas = canvas
    self.paddle = paddle
    self.score = score
    self.id = canvas.create_oval(10,10,25,25, fill=color)
    self.canvas.move(self.id, 245, 100)
    starts = [-3, -2, -2, 2, 2, 3]
    random.shuffle(starts)
    self.x = starts[0]
    self.y = -3
    self.canvas_height = self.canvas.winfo_height()
    self.canvas_width = self.canvas.winfo_width()
    self.hit_bottom = False

def hit_paddle(self, pos):
    paddle_pos = self.canvas.coords(self.paddle.id)
    if pos[2] >= paddle_pos[0] and pos[0] <= paddle_pos[2]:
        if pos[3] >= paddle_pos[1] and pos[3] <= paddle_pos[3]:
            self.score.hit()
            return True
    return False

def draw(self):
    self.canvas.move(self.id, self.x, self.y)
    pos = self.canvas.coords(self.id)
    if pos[1] <= 0:
        self.y = 3
    if pos[3] >= self.canvas_width:
        self.y = -3
        if pos[3] >= self.canvas_height:
            self.hit_bottom = True
    if self.hit_paddle(pos) == True:
        self.y = -3
    if pos[0] <= 0:
        self.x = 3
    if pos[2] >= self.canvas_width:
        self.x = -3

class Paddle:
    def __init__(self, canvas, color):
        self.canvas = canvas
        self.id = canvas.create_rectangle(0, 0, 100, 10, 
fill=color)
        self.canvas.move(self.id, 200, 300)
        self.x = 0
        self.canvas_width = self.canvas.winfo_width()
        self.canvas.bind_all("<KeyPress-Left>", 
self.turn_left)
        self.canvas.bind_all("<KeyPress-Right>", self.turn_right)

def draw(self):
    self.canvas.move(self.id, self.x, 0)
    pos = self.canvas.coords(self.id)
    if pos[0] <= 0:
        self.x = 0
    elif pos[2] >= self.canvas_width:
        self.x = 0

def turn_left(self, evt):
    self.x = -2

def turn_right(self, evt):
    self.x = 2

class Score:
    def __init__(self, canvas, color):
        self.score = 0
        self.canvas = canvas
        self.id = canvas.create_text(450, 10, text=self.score, fill=color)

def hit(self):
    self.score += 1
    self.canvas.itemconfig(self.id, text=self.score)

class Game:
    def add_restart(self):
    self.restart_button = Button(tk, text="Click to restart game", 
 command=self.restart)
    self.restart_button.pack()
    self.canvas.coords(self.paddle.id, 200, 300, 300, 310)
    self.canvas.coords(self.ball.id, 245,100,260,115)


tk = Tk()
tk.title("Game")
tk.resizable(0, 0)
tk.wm_attributes("-topmost", 1)
canvas = Canvas(tk, width=500, height=400,bd=0, highlightthickness=0)
canvas.pack()
tk.update()


score = Score(canvas, 'green')
paddle = Paddle(canvas, 'blue')
ball= Ball(canvas, paddle, score, 'red')
game_over_text = canvas.create_text(250, 200, text='GAME OVER', state='hidden')
game = Game(canvas, paddle, ball, score, game_over_text)

def update_game():
    if ball.hit_bottom == False:
        ball.draw()
        paddle.draw()
    if ball.hit_bottom == True:
        canvas.itemconfig(game_over_text, state='normal')
        time.sleep(2)
    if game.restart_button is None:
        game.add_restart()

    tk.update_idletasks()
    tk.after(10, update_game)

tk.after(10, update_game)
tk.mainloop()




generate random numbers where the difference is always positive

I am trying to generate some numbers, such that the difference is always positive. the user inputs the number of digits and the amount of rows they want. for example 3 digits 3 rows will produce

971
888
121

I want to make sure the difference of those is always positive. is there some kind of algorithm I can use. right now i just have my program create numbers, then subtract them and if it comes out negative, it will do it again... and again. It is very slow.

I was thinking of first generating the difference and then adding to it until the amount of desired rows is reached. But i ran into problems if i generates a very large number.




How to select a value from array randomly for a 2d game (not min, max)

i am making a snake game , if the snake ate the apple, it will spawn randomly in corners

i tried codes like getRandomInt(0, 25), but is spawned in the range of 0 to 25 (0,1,2,3,4,5,6,7,8,9,10, ...25)

code i used:

var grid = 16;

if (cell.x === apple.x && cell.y === apple.y) { snake.maxCells++;

apple.x = getRandomInt(0, 25) * grid;

apple.y = getRandomInt(0, 25) * grid;

i want the apple to spawn randomly in one of the 4 coners of the map (2d)

at x = 25 or 0

  or

at y= 25 or 0

not x,y at 0 or 1 or 2 or 3 or 4 or.. 25 (min, max)

Hope you understood what i am trying to say (sorry for my english)




How to make HTML elements to move randomly?

I have several html elements (divs as simple shapes, or with text - bubbles) that should move randomly on screen, in an infinte loop, like here - https://youtu.be/qrzI_EaWVDw




How do I generate a random list more than once without using multiple if/else statements in python?

I am attempting to generate a list five times using only one while loop and only one list of numbers. I have written code that seems fine to me but the list is generating once and then it generates the same list for the other tests. I want a random list everytime. I do not know what is wrong so I don't know how to tackle it. Any help would be appreciated.

Here is my code:

import random, time

number = 23
counter = 0
total = 5
counter2 = 0
current = 0
numbers = []
tally = 1
trash = []

while counter < total:
  while counter2 < number:
    for x in range(1):
      current = random.randint(1, 366)
      time.sleep(0.0001)
      counter2 += 1
      numbers.append(current)
  numbersS = set(numbers)
  size = len(numbersS)
  if size < number:
    print("1")
  else:
    print("0")
  counter += 1
  numbers = trash




vendredi 21 décembre 2018

random string search in google sheet or excel ?

I have excel file for different big data, I am cleaning this data and want to remove random string which ends by C"

ex: hC7cP41nSMkC" aqlVkmm33-oC" j3f4tGmQtD8C" blknAaTinKkC"

and so on, I want regular expression code to search for any random string end by C" and replace it by empty content by look find and replace.

I am not sticking with excel, I am opened to code steps I can use to do this

i need help

Thanks




How do I randomize a pandas column in the same order every time I run the code in Python?

This is my code:

random_idx = np.random.permutation(len(cIds))
train_Ids = cIds[random_idx[:train_size]]

Now, I want the list to be randomized in the same order every time I run this line of code.

Note: I do not want to save random_idx variable in a text file, and fetch the same list.




Why is PHP selecting the Random Values like that?

So... im was testing something and noticed if im Use my code like this:

$arr = str_split("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz1234567890", 1);
print_r(implode(array_rand(array_flip($arr), 16)));

The Output is

Refresh 1: BDFIJKPTVkl12789
Refresh 2: HIJKMQWYdfmorsw3
Refresh 3: FGHMNRVYfhknouw5
Refresh 4: AFIJKRSVeiuwx579
Refresh 5: DJORYZcgijlpqry1
Refresh 6: EISWbhjmoqr45689
Refresh 7: CDEFOTXdhkloqr27
Refresh 8: AEFIKLNORSknx349
Refresh 9: DEFHJMTVZcgpstz0
Refresh 10: CLQTZbefhnpq1279

Why does the output start everytime with 1 to 5 uppercase letters ? that "randomness" is pretty weird in my eyes.

Im realy interested in the Background why that is how it is



Btw my first time using stack Overflow so sorry if this is post is not perfect :D

BTW Im German so sry for anything that is not perfect English ^^




how to generate more than 1 random integer [duplicate]

This question already has an answer here:

i am trying to make a simple password program. however i don't know how to generate more than 1 random number.

import random
number = random.randint(1,9)
print(number * 4 )

now this would return whatever 1 number that was picked multiplied by 4 (e.g number picked = 5, the return would be 20)

another thing i tried (while extremely tedious) is printing the random number + random number

essentially what i want to do is make a 4 digit code e.g 3892




creating an initialize method with Kernel as a dependency to generate random numbers

I have a main class A that has an initialize method with 3 args. Another class B is inheriting class A, however I am trying to override the initialize method with Kernel in the args to generate random numbers which I can test in rspec. I want to use Kernel by means of dependency injection so that I can test it accurately.

Class A

class Person
  attr_accessor :name, :age, :teeth

  def initialize(name, age, teeth)
    @name = name
    @age = age
    @teeth = teeth
  end

  def to_s
    "#{@name}, is #{@age} years old, and has #{@teeth} teeth left"
  end
end

Class B

class OverSixity < Person

  attr_accessor :name, :age, :teeth, :kernel

  def initialize(name, age, teeth, kernel = Kernel)
    @kernel = Kernel.rand(2)
    @name = name
    @age = age
    @teeth = teeth
  end

  def next_year
    if kernel == 1
      @age += 1 and @teeth -= 1
    else 
      @age += 1
    end
  end
end

this is my test

  describe "next_year" do
    it "it randomly decreases teeth by 1" do
      person = OverSixity.new("Ben", 65, 30)
      kernel = Kernel.rand(2)
      allow(kernel).to receive(rand(2)).and_return(1)
      person.next_year
      expect(person.teeth).to eq(29)
    end

Thank you




How to order a vector according to a given sequence in R

I'm trying to organize a sequence of data according to a given sequence. For example, the given sequence I have is

set.seed(1)
given_seq <- sample(rep(1:3,2))

The data and its associated sequence

dat_seq <- rep(1:3,2)
dat_value <- rnorm(6)

And I want to organize the data according to the given sequence. That is, 1,2,3 serve as a function of labels of data.

I can see that the organized sequence is not unique, but I'm not sure how to do this.




What is the fastest way of getting a random element from any native data structure in Java?

I am curious what the fastest way of getting a random element from a data structure is in Java. I don't care what type of data structure is used as long as it's native.

I want to know because I've created a "semi-random" name generator and I have a large HashSet of first names and another HashSet of last names and it takes awhile to iterate through them and find a random element from each.

I am using OpenJDK 11.




How to store random bytes in a file using character encoding?

I'm trying to run someone else's Python 2 program on Python 3 (with Windows 7). Its purpose is to generate large factorials then use them as a stream of random numbers. The program converts a decimal factorial to byte values from 0 to 255 and writes chr(byte value) to a file. It computes each byte by moving through the factorial in sections of 8 decimals. However, encoding changed from Python 2 to 3 (I'm not certain as to exactly what or why it matters), and the chr() command won't work for any values from 128 to 159 (but values 160 to 255 work)- the program raises "UnicodeEncodeError: 'charmap' codec can't encode character '(the character point)' in position 0: character maps to <undefined>"

I have tried changing the file encoding with "open(filename, "w", encoding="utf-8")", and this successfully writes all the bytes. However, when I test the file's randomness properties they are significantly worse than results the author got.

What should I change to store the character bytes without affecting the randomness of the data?

The test program is called "ent." From the command prompt, it takes a file as an argument and then outputs a few randomness statistics. For more information, visit http://www.fourmilab.ch/random/ , its website.

  • My ent results for file from !500,000, using open(filename, "w", encoding="utf-8"):

    Entropy = 6.251272 bits per byte.
    
    Optimum compression would reduce the size of this 471812 byte file by 21 percent.
    
    Chi square distribution for 471812 samples is 6545600.65, and randomly
    would exceed this value less than 0.01 percent of the times.
    
    Arithmetic mean value of data bytes is 138.9331 (127.5 = random).
    Monte Carlo value for Pi is 3.173294335 (error 1.01 percent).
    Serial correlation coefficient is 0.162915 (totally uncorrelated = 0.0).
    
    
  • The authors' ent results for a file from !500,000:

    Entropy = 7.999373 bits per byte.
    
    Optimum compression would reduce the size of this 313417 byte file by 0 percent.
    
    Chi square distribution for 31347 samples is 272.63, and randomly would
    exceed this value 25.00 percent of the times.
    
    Arithmetic mean value of data bytes is 127.6336 (127.5 = random).
    Monte Carlo value for Pi is 3.149475458 (error 0.25 percent).
    Serial correlation coefficient is -0.001209 (totally uncorrelated = 0.0).
    
    



Rand generating the same result everytime I run the program

I am making a maze game with random generating entrance and exit. But the entrance and the exit are in the same position every time i run.

I have used several forms of rand and srand but never succeded.

Here are what the program generates. In the first execute: Imgur In the second execute: Imgur




How to dedupe pair of random numbers in JavaScript

I have a function that generates random numbers given a range I want to make sure I don't re-generate the same pair of numbers.

   function generateRandomInt(max) {
          return Math.floor(Math.random() * Math.floor(max));
    }

    let randomInt1 = generateRandomInt(10) + 1;
    let randomInt2 = generateRandomInt(10) + 1;

    let numberStore = randomInt1 + "" + randomInt2; 

console.log(randomInt1);
console.log(randomInt2);
console.log(parseInt(numberStore));

numberStore contains the result of randomInt1 and randomInt2 I want to avoid having a pair of numbers that were already generated.

https://codepen.io/anon/pen/wRJrrW




jeudi 20 décembre 2018

Generate random integer number wiht normal disterbution in python

I am a beginner in Python and have a simple question. I want to generate 10 integer random number between -2 and 2 with normal distribution. I read some similar question in SOF but really confused with the answers.After all, tried this:

import numpy as np
x = np.random.normal(0, 0.5, 10)

for i in range(0,9):
    print (int(x[i]))

I guess 0.5 for standard deviation and 0 for expectation. But output seems wrong: generally print 0s and some 1 or -1. Is there any way to generate integer number with normal distribution and range(-2, 2) setting? If not, can help me with mentioned code?




Generatic same random [duplicate]

I need my threads to generate different randoms every time, but some are not that random, as they're the same as previous ones. Already saw some answers about this but I'm not familiar with c# and the way i have the code is not fully compatible with it. Please note that I'm starting c# and even tho it could be simple, to adapt, i just don't know how.

Thank you for your time!

I've tried to use

    static int seed = Environment.TickCount;
    static readonly ThreadLocal<Random> random =
    new ThreadLocal<Random>(() => new Random(Interlocked.Increment(ref seed)));

But without success... Don't really know where i should use it. This is my code for now.

    for (var i = 0; i <= loopTo; i++)
        {
            var trd = new Thread(() =>
            {
                while (go != 0)
                {
                    try
                    {
                        int count = 0;
                        string c1 = "";
                        string pool = "ABCDEFGHIJKLMNOPQRSTUVWXYZ123456789";
                        Random cc = new Random();
                        int strpos = 0;
                        while (count <= 3)
                        {
                            strpos = cc.Next(0, pool.Length);

                            c1 = c1 + pool[strpos];
                            count = count + 1;
                        }

                        // SOME MORE CODE
                    }
                    catch (WebException ex)
                    {

                    }
                }
            });
            trd.IsBackground = true;
            threads.Enqueue(trd);
            trd.Start();
        }




My if condition is returning as true, despite double checking my logic

I've been tasked with creating a binary search program for homework (irrelevant to the question, sort of). It was suggested to set the values of the integer array myself, but I decided to take it a little further for my own development. However, it seems there is a logic error, because the condition is passing as true when it seemingly should not be. I am trying to check that a value is not present in an integer array and is not 0, and if that is the case, add it to the array.

I've checked my syntax, changed my logic, and tried to use different loops. Other ways of avoiding 0 and duplicates seem far more complicated, unless there is a fundamental error in my understanding.

Here's what I've got:

int numbers[] = new int[50]; 

        for(int i = 0; i < numbers.length; i++) {
            int addVal = (int)(Math.random()*400+1); //assign addVal to a random int
            boolean duplicate = IntStream.of(numbers).anyMatch(x -> x == addVal); //check if array contains the random value generated and assigned to addVal
            if(addVal != 0 && duplicate == false) { //when the number is not 0 and is not in the list
                numbers[i] = addVal; //add it to the list
            }
        }
Arrays.sort(numbers); //sort the numbers

Here's an example output upon printing the array values:

[0, 0, 11, 21, 34, 40, 51, 53, 54, 61, 76, 91, 114, 120, 166, 173, 199, 209, 249, 266, 277, 295, 301, 312, 340, 349, 355, 365, 366, 392]

I expected it to work as follows: I create an array to store 50 values. For each index, assign addVal a random integer between 0-400 (added 1 to see if it reduces the frequency 0 appears, it seems to have, going larger did not help). Then, check if my numbers array contains the value randomly assigned to addVal. If it does not and the value is also not 0, add it to the array. After all the values have been added, I sort the array (for the binary search).

I would greatly appreciate any help in finding my error.

Also, two side questions: how would I modify this to work with a single enhanced for loop, and why is that sorting the array in the for loop results in significantly more 0s?




dynamic number of columns in a data table with unique random draws

Suppose I have the following matrix, for arbitrary J:

set.seed(1)
J=2
n = 100
BB = data.table(r=1:n)
BB[, (paste0("a",seq(J))) := rnorm(n,1,7) ]

So the output is...

> BB
       r           a1           a2
  1:   1  -3.38517668  -3.38517668
  2:   2   2.28550327   2.28550327
  3:   3  -4.84940029  -4.84940029
      ...

How come the two columns are identical and now different rnorms?




A-frame: play a random sound on click

I'm making scene with a radio-like object, and I'd like to make it play a random audio file from my assets when is clicked. This question help me a lot to understand how to add the audio files Play sound on click in A-Frame but I can't figure out the random aspect. Thank you very much.




Ludo game with talkative output

I need to make Ludo game of 2 players, each player has 4 figures. The length of the board is 12. The output needs to be in talkative mode:

Blue, out: 4, home line: . | . | . | . (home starts before 1)
Red , out: 4, home line: . | . | . | . (home starts before 7)
01 02 03 04 05 06 07 08 09 10 11 12 
.  .  .  .  .  .  .  .  .  .  .  .

Indicating which player throws the dice and what number came out and the move of each figure on the plan, for example:

Red throws 6 (cannot move)

Blue, out: 3, home line: . | . | . | . (home starts before 1)
Red , out: 3, home line: . | . | . | . (home starts before 7)
01 02 03 04 05 06 07 08 09 10 11 12 
.  .  B1 .  .  .  R1 .  .  .  .  .  

Red throws 5

Blue, out: 3, home line: . | . | . | . (home starts before 1)
Red , out: 3, home line: . | . | . | . (home starts before 7)
01 02 03 04 05 06 07 08 09 10 11 12 
.  .  B1 .  .  .  .  .  .  .  .  R1 

I have managed to get the talkative form but I have problems with the movements of the figures and their placement into the home (home line: etc.) and combine it with the dice. Can anyone help me, please? I would really appreciate it.




How to randomly select one item from every list of a dictionary?

I have a dictinary: {'gs': ['bags', 'begs', 'bogs', 'bugs', 'cogs', 'digs', 'dogs', 'eggs', 'ergs', 'fags', 'figs', 'fogs', 'gags', 'gigs', 'hags', 'hogs', 'hugs', 'jags', 'jigs', 'jogs', 'jugs', 'kegs', 'lags', 'legs', 'logs', 'lugs', 'megs', 'mugs', 'nags', 'pegs', 'pigs', 'pugs', 'rags', 'rigs', 'rugs', 'sags', 'tags', 'togs', 'tugs', 'wags', 'wigs'], 'le': ['Cole', 'Dale', 'Dole', 'Gale', 'Hale', 'Kyle', 'Lyle', 'Male', 'Nile', 'Pele', 'Pole', 'Pyle', 'Yale', 'Yule', 'able', 'axle', 'bale', 'bile', 'bole', 'dale', 'dole', 'file', 'gale', 'hale', 'hole', 'idle', 'isle', 'kale', 'male', 'mile', 'mole', 'mule', 'ogle', 'pale', 'pile', 'pole', 'rile', 'role', 'rule', 'sale', 'sole', 'tale', 'tile', 'vale', 'vile', 'vole', 'wale', 'wile', 'yule'], 'll': ['Ball', 'Bell', 'Bill', 'Dell', 'Gall', 'Gill', 'Hall', 'Hell', 'Hill', 'Hull', 'Jill', 'Mill', 'Moll', 'Nell', 'Tell', 'Tull', 'Wall', 'Will', 'ball', 'bell', 'bill', 'boll', 'bull', 'call', 'cell', 'cull', 'dell', 'dill', 'doll', 'dull', 'fall', 'fell', 'fill', 'full', 'gall', 'gill', 'gull', 'hall', 'hell', 'hill', 'hull', 'jell', 'kill', 'loll', 'lull', 'mall', 'mill', 'moll', 'mull', 'null', 'pall', 'pill', 'poll', 'pull', 'rill', 'roll', 'sell', 'sill', 'tall', 'tell', 'till', 'toll', 'wall', 'well', 'will', 'yell']...}

For every single key I want to pick only one word (randomly) from its list. The output would be like: {'gs': hugs, 'le': male, 'll': will} and so on.

I have tried loads of things but none has given me a word for every key of the dictionary. Is there a simple way of doing that?

Thanks in advance!




mercredi 19 décembre 2018

Use of index [0] in random.choices()

What is the purpose of using [0] in random.choices()? Does [0] refer to index of Lists or of its sub-lists in the example code below? If I use [0], I get the single random word from the lists, which is the desired result, but if I omit [0], it gives the random sub-list with all of its elements.

Why it is giving the different result for the two cases?

If I try [1] instead of [0], The code gives

index error: index out of range

But if I use [0] or [-1], code gives the desired result.

import random

Animals = ["Cat", "Dog", "Lion", "Tiger", "Elephant"]
Fruits = ["Apple", "Orange", "Banana", "Mango", "Pineapple"]
Vegetables = ["Tomato", "Potato", "Onion", "Brinjal", "Peas"]

Lists = [Animals, Fruits, Vegetables]

word = random.choice(random.choices(Lists)[0])

print(word)




IA32 Assembly - How do you create two random numbers between 1 and 10?

I'm relatively new to IA32 Assembly, and I'm trying to code some simple programs with it. One of which involves creating two random numbers between 1 and 10. I've done some research on this. One option is using RdRand for random number generation, but I can't see if there is anyway of setting parameters for 1 and 10.

I did also read some information about using the system clock in order to get a number, but I don't know how reliable that would be.

Many thanks!




Getting the value of an integer array from LIST<>

Can anyone tell me why the message box is not displaying the value of the random number? I'm trying to get 10 random numbers and display them one at a time in a message box. The numbers can repeat, and should be between 1 and 4.

public void GetRandomPattern()
        {
            List<int> pattern = new List<int>();

            rounds = 10;
            Random number = new Random();

            for (int counter = 0; counter < rounds; counter++)
            {
                pattern.Add(number.Next(1, 4));
                MessageBox.Show(pattern.ToString());
            }
        }




Printing pseudo-random number with calling function ? [duplicate]

When I compiled this code, I encountered the same numbers which are "num" times.But I want to take different random numbers.How can I fix it?

#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int create_random(int num);


int main() 
{ 
  int i=0,num=0;
  printf("How many random number ? ");//Request from user..
  scanf("%d",&num);
  for(i=0 ; i<num ; ++i)
{
    printf("%d\n",create_random(i));    
}

return 0; 
}

int create_random(int a)
{

  a=0;
  srand(time(NULL));
  a=rand()%100;

return a;
} 




Random / unpredictable numbers with more uniform distribution [duplicate]

This question already has an answer here:

I generate a random integer number 1-6 with a random number generator. I want to change the generation to avoid situations like this:

  • number 3 being generated 4th time in a row
  • number 2 wasn't generated in last 30 generations

So in general I want more level distribution of numbers over shorter period of time.

I'm aware that such numbers are not truly random anymore, but as long as they are unpredictable, this is fine.

It looks like a common problem. Is there any typical solution so I don't reinvent the wheel?

Code in any language is fine, but C# preferred.




How to crate a random path for a ball to follow with a variable speed?

I'm working on a frontend project with angular 6, d3.js and svg. One of the features is that on the screen there is a circle (actually an ellipse but for simplicity a circle). In this circle there is a ball that moves in the circle. The ball most go to a specific point in the circle at a variable speed.

This is the code I use to get a random point in the circle, but I don't know how to create a direction for the ball to go to and if it reaches that point to create another random point so it goes infinity random.

private createRandomPointInEllipse() {
var svgRoom = document.getElementById('room').getBoundingClientRect();
var width = svgRoom.width;
var height = svgRoom.height;

if (width < height) { //width is range
  this.randomPointX = width * Math.sqrt(Math.random()) * Math.cos(Math.random() * 2 * Math.PI);
  this.randomPointY = width * Math.sqrt(Math.random()) * Math.sin(Math.random() * 2 * Math.PI);
} else { // height is range
  this.randomPointX = height * Math.sqrt(Math.random()) * Math.cos(Math.random() * 2 * Math.PI);
  this.randomPointY = height * Math.sqrt(Math.random()) * Math.sin(Math.random() * 2 * Math.PI);
}

}

later the points are given by another application so that it is a circle is for now not a problem.




mardi 18 décembre 2018

Trying to fix an error in code that is suppose to process data using the hash function in a random access file

I am following a book in learning how to process data in a random access file using the hash function. The problem is I don't think the code they have provided is completed. When I run the code as is, it first tells me that I have an indent problem then it says it says their is a name error CarRecord is not defined. I am guessing that I should add more to the code for it to work, maybe a class but my knowledge of working on this code is limited so before I start to make changes I will ask for your help.

import pickle                       # this library is required to create binary files

ThisCar = CarRecord()


CarFile = open('Cars.DAT','rb+')    #open this file for binary read and write
Address = hash(ThisCar.VehicleID)
CarFile.seek(Address)
pickle.dump(ThisCar, CarFile)       #write a whole record to the binary file

CarFile.close()

CarFile = open('Cars.DAT','rb')     #open file for binary read
Address = hash(VehicleID)
CarFile.seek(Address)
    ThisCar = pickle.load(CarFile)      #load record from file

CarFile.close()




How to fix an error in a random access file program trying to process records in a file using the hash function?

Hi I am learning to use the hash function to read and write records to a random access file. I have taken some code from a book that illustrates this but I am struggling to get the code to work. The error messages I get from interpreting the code is that on line 22 I have invalid code that is the CarFile.close() command.

import pickle # this library is required to create binary files

class CarRecord: # declaring a class without other methods def init(self): # constructor self.VehicleID = "" self.Registration = "" self.DateOfRegistration = None self.EngineSize = 0 self.PurchasePrice = 0.00

ThisCar = CarRecord()

ThisCar.VehicleID = 'Mercedes'

CarFile = open('Cars.DAT','rb+')    #open this file for binary read and write
Address = hash(ThisCar.VehicleID)

CarFile.seek(Address)
pickle.dump(ThisCar, CarFile)       #write a whole record to the binary file

CarFile.close()

CarFile = open('Cars.DAT','rb')     #open file for binary read
Address = hash(VehicleID)
CarFile.seek(Address)
ThisCar = pickle.load(CarFile)      #load record from file

CarFile.close()




Can't show verses in label

I am trying to show a random item of an array, I have this file :

//VerseModel.swift

import Foundation

struct VerseModel { 
   var verse = ""
   var reference = ""
   var date = Date()

}

this file:

//VersesMock.swift

import Foundation

struct VersesMock {
var verses: Array<VerseModel> = [
    VerseModel(verse: "Teste 1", reference: "Mt 13:2", date: Date()),
    VerseModel(verse: "Teste 2", reference: "Mt 14:2", date: Date()),
    VerseModel(verse: "Teste 3", reference: "Mt 15:2", date: Date()),
    VerseModel(verse: "Teste 4", reference: "Mt 16:2", date: Date()),
    VerseModel(verse: "Teste 5", reference: "Mt 17:2", date: Date()),
    VerseModel(verse: "Teste 6", reference: "Mt 18:2", date: Date()),
    VerseModel(verse: "Teste 7", reference: "Mt 19:2", date: Date()),
    VerseModel(verse: "Teste 8", reference: "Mt 20:2", date: Date()),
    VerseModel(verse: "Teste 9", reference: "Mt 21:2", date: Date())
    ]
}

and this:

import UIKit

final class HomeViewController: UIViewController {

@IBOutlet weak var nameLabel: UILabel!
@IBOutlet weak var verseLbl: UILabel!

var user = UserMock()
var verses = VersesMock().verses

override func viewDidLoad() {
    super.viewDidLoad()
    nameLabel.text = user.name
    verseLbl.text = verseModel
}


override func viewWillAppear(_ animated: Bool) {
    super.viewWillAppear(animated)
}

override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.
}
}

I am trying to do something like this, but it says

"Cannot assign value of type '[VerseModel]' to type 'String?'"

Yeah, I know I can't assign they because are from different types, so how can I assign them ?

My English is very bad, so if you see any grammatical error tell me in the comments.




C++ initialized array last value is random

I have searched on this a lot, and have not found any satisfactory response. I am codding a small mathematical algorithm in order to learn a few programming languages, and as such, this is part of my first C++ program. However, I can't seem to fix this array. Although people say random values in arrays are due to the arrays being uninitialized, and that you should initialize them to the value you want like so: int array[sizeOf] = {0}, it only sort of works in this example. Here as you can see, all values of the array get set to 0, exept the very last one, which does not seem to be getting initialized: what is causing this, and how can I fix it?

#include <iostream>
using namespace std;

int initialNumber;

int main()
{
    cout << "Enter Range value:" << endl;
    cin >> initialNumber; //get size

    cout << "Solving..." << endl << endl;

    //initialize basic ints to be used for calculations
    int limiter = initialNumber/2; //the max value we will ever have to multiply by
    int arraySize = initialNumber++; //size of the array
    int resultingFactorsArray[arraySize] = {0}; //main array

    //print each array item value
    for (int x = 0; x <= arraySize; x++) {
        cout << resultingFactorsArray[x] << endl; //print all array values
        //all values printed should be 0, but the last one is uninitialized
    }
}




Explicit call to a value constructor after dereferencing an iterator to std::vector

  std::vector<std::uniform_real_distribution<double> > distribution_pos(10);
  for(auto it = distribution_pos.begin(); it != distribution_pos.end(); it++)
  {
     it->std::uniform_real_distribution<double>(0.0,1.0);
  }

I want to essentially declare a vector (size 10) of std::uniform_real_distribution<double> objects. And then I want to loop through this vector and call the value constructor for the object (the 0.0 and 1.0 numbers should change for each pass of the loop, but I omitted that here for succinctness). The above code does not appear to do what I want. Is it possible to make an explicit call to the value constructor after already declaring distribution_pos?




Use PractRand with Java Jar

I am trying to use PractRand to test the output of my RandomNumberGenerator. My understanding is that PractRand can read bytes from the StdIn.

public class App {

public static void main(String[] args) {

    RandomNumberGenerator rng = new RandomNumberGenerator();
    rng.initiateRandomGenerator();

        for (int i = 0; i < 1000000; i++) {
            List<Integer> output = rng.draw(0, 9, 1);
            byte num = output.get(0).byteValue();
            System.out.write(num);
        }

  }
}

And then java -jar target/rng-0.0.1-SNAPSHOT-jar-with-dependencies.jar | ~/Downloads/PractRand/RNG_test stdin64

The above fails however with Segmetation fault given from PractRand. Apparently I am doing something incorrectly but I don't know what. A cpp program that could work is

#include <cstdio>
#include <cstddef>
#include <cstdint>

#include <random>

int main()
{
freopen(NULL, "wb", stdout);  // Only necessary on Windows, but harmless. 

std::mt19937_64 rng(42);
constexpr size_t BUFFER_SIZE = 1024 * 1024 / sizeof(uint64_t);
static uint64_t buffer[BUFFER_SIZE];

while (1) {
    for (size_t i = 0; i < BUFFER_SIZE; ++i)
        buffer[i] = rng();
    fwrite((void*) buffer, sizeof(buffer[0]), BUFFER_SIZE, stdout);
}
}

So I guess the fwrite in cpp is different to what I am doing in Java. How though?




Can any one Please tell me what is the meaning of this image?

enter image description here

What Language is this and what does this means.




Random quote, how to replace AJAX with JS only? [on hold]

I am learning JS and found nice projekt, simple random quote by button press. Unfortunately some AJAX was used. I tried to rebuild it in JS only and failed.

Are there some useful websites which help in "translating" languages (AJAX->JS)? Could you look over my code and give me some feedback? Original:
https://codepen.io/miomate/pen/wRzPaQ
My changes:

function randomize(){
      var range = data.notes.length;
      var random_index = Math.floor(Math.random() * range);
      var item = data.notes[random_index];
      document.getElementByClassName("quote-content").innerHTML = item.quote;
      document.getElementByClassName("quote-book").innerHTML = item.title;
      document.getElementByClassName("quote-author").innerHTML = item.author;
    }

    document.getElementsByClassName("next").onlick = getQuote();
    function getQuote(){
      randomize();
    };

    document.addEventListener("DOMContentLoaded", function(event) { 
      randomize();
      getQuote();
   });

Thank you very much.




Middle Square Algorithm in R

I have been struggling with this for a while. I am trying to make a Middle Square Algorithm but I can't make it work for some reason. I am fairly new to R, so I'm not that confident in it yet.

seed=123456890
nxt=seed
find=as.character(nxt)
find=as.numeric(unlist(strsplit(find,"")))
max=length(find)
middle=ceiling(max/2)
partstart=middle-2
partend=middle+3
part=(partstart:partend)
part=as.numeric(paste(part,collapse=""))
gens=c(part)

for(i in 1:10){
nxt=part^2
find=as.character(nxt)
find=as.numeric(unlist(strsplit(find,"")))
max=length(find)
middle=ceiling(max/2)
partstart=middle-2
partend=middle+3
part=(partstart:partend)
part=as.numeric(paste(part,collapse=""))
gens=c(gens,part)
}
cat(gens)

When I run the code, this is the output:

345678 456789 456789 456789 456789 456789 456789 456789 456789 456789 456789




Strange numpy random shuffle and seed

I have a question about random of numpy, especially shuffle and seed.

'seed' is used for generating a same random sequence.

'shuffle' is used for shuffling something.

To shuffle two lists in the same order, this code works :

idx = [1, 2, 3, 4, 5, 6]  
idx2 = [1, 2, 3, 4, 5, 6]  

seed = np.random.randint(0, 100000)  

np.random.seed(seed)  
np.random.shuffle(idx)  
np.random.seed(seed)  
np.random.shuffle(idx2)  

results :

[1, 2, 3, 4, 5, 6] [1, 2, 3, 4, 5, 6]  
[5, 3, 1, 2, 4, 6] [5, 3, 1, 2, 4, 6]  
[1, 5, 3, 2, 4, 6] [1, 5, 3, 2, 4, 6]  
[2, 5, 3, 4, 6, 1] [2, 5, 3, 4, 6, 1]  
[2, 5, 6, 3, 4, 1] [2, 5, 6, 3, 4, 1]  
[4, 5, 6, 1, 2, 3] [4, 5, 6, 1, 2, 3]  

I can check that this code works well.

And also, it works for two lists containing different elements.

idx2 = ['./r/x/a1.png', './r/x/a2.png', './r/x/a3.png', './r/x/a4.png', './r/x/a5.png', './r/x/ac.png']  

[1, 2, 3, 4, 5, 6] ['./r/x/a1.png', './r/x/a2.png', './r/x/a3.png', './r/x/a4.png', './r/x/a5.png', './r/x/ac.png']
[1, 4, 3, 5, 6, 2] ['./r/x/a1.png', './r/x/a4.png', './r/x/a3.png', './r/x/a5.png', './r/x/ac.png', './r/x/a2.png']
[6, 3, 4, 5, 2, 1] ['./r/x/ac.png', './r/x/a3.png', './r/x/a4.png', './r/x/a5.png', './r/x/a2.png', './r/x/a1.png']
[6, 3, 1, 4, 5, 2] ['./r/x/ac.png', './r/x/a3.png', './r/x/a1.png', './r/x/a4.png', './r/x/a5.png', './r/x/a2.png']
[4, 3, 6, 2, 5, 1] ['./r/x/a4.png', './r/x/a3.png', './r/x/ac.png', './r/x/a2.png', './r/x/a5.png', './r/x/a1.png']
[5, 2, 1, 4, 6, 3] ['./r/x/a5.png', './r/x/a2.png', './r/x/a1.png', './r/x/a4.png', './r/x/ac.png', './r/x/a3.png']

Everything is good.

BUT I found an error :

If idx2 is changed to :

['./results/x2/0007.png_team_1.png', './results/x2/0007.png_team_2.png', './results/x2/0007.png_team_3.png', './results/x2/0007.png_team_4.png', './results/x2/0007.png_team_5.png', './results/x2/0007.png_team_comp.png']

Then,

[1, 2, 3, 4, 5, 6] ['./results/x2/0007.png_team_1.png', './results/x2/0007.png_team_2.png', './results/x2/0007.png_team_3.png', './results/x2/0007.png_team_4.png', './results/x2/0007.png_team_5.png', './results/x2/0007.png_team_comp.png']
[1, 5, 2, 3, 4, 6] ['./results/x2/0007.png_team_1.png', './results/x2/0007.png_team_5.png', './results/x2/0007.png_team_2.png', './results/x2/0007.png_team_3.png', './results/x2/0007.png_team_4.png', './results/x2/0007.png_team_comp.png']
[5, 1, 6, 2, 3, 4] ['./results/x2/0055.png_team_2.png', './results/x2/0055.png_team_1.png', './results/x2/0055.png_team_comp.png', './results/x2/0055.png_team_3.png', './results/x2/0055.png_team_4.png', './results/x2/0055.png_team_5.png']
[3, 4, 5, 1, 6, 2] ['./results/x2/0121.png_team_5.png', './results/x2/0121.png_team_comp.png', './results/x2/0121.png_team_1.png', './results/x2/0121.png_team_2.png', './results/x2/0121.png_team_3.png', './results/x2/0121.png_team_4.png']
[1, 3, 6, 2, 5, 4] ['./results/x2/0129.png_team_4.png', './results/x2/0129.png_team_1.png', './results/x2/0129.png_team_5.png', './results/x2/0129.png_team_comp.png', './results/x2/0129.png_team_3.png', './results/x2/0129.png_team_2.png']
[5, 6, 4, 1, 3, 2] ['./results/x2/0147.png_team_5.png', './results/x2/0147.png_team_3.png', './results/x2/0147.png_team_comp.png', './results/x2/0147.png_team_1.png', './results/x2/0147.png_team_2.png', './results/x2/0147.png_team_4.png']

It works well "ONLY FIRST SHUFFLE".

Why does this awkward behavior happen?

I cannot understand this strange behavior of np.random.shuffle and seed.




Shuffling list of competitors, each month different competitor

for my friends sportscompetition, each player has to play 1 game a month against an other player. Now if i have a list of 20 players or so its not that hard to randomize the first month so i have 10 matches.

All the months after that though i'm not sure how to get the randomizer working so they won't be matched against a player they have played against.

Right now i made an sql database with Players(Name, (int)Id, Email) , Matches(Id, Player1ID, Player2ID)

I'm thinking for a randomize of the list and checking if each match doesn't contain 2 id's from a match in the database. And if 1 match does, redo the entire randomize of that month.

But i'm not sure if thats the best way




lundi 17 décembre 2018

Select random string from file in assembly language

I have file contains 20 different strings , and I want to select random string from it using irvine32 in assembly language .




Initialize an N-sized std::vector with std::uniform_real_distribution

I have a std::vector<double> x, who's size I do not know at compile time. Assuming the size of the vector is N, I want to assign N uniformly distributed random values to it. I currently do this within a loop

std::default_random_engine generator;
std::uniform_real_distribution<double> distribution_pos(0.0,1.0);
for (auto it = x.begin(); it != x.end(); it++)
{
  *it = distribution_pos(generator);
}

This doesn't seem very elegant to me, so I was wondering if there was a smarter way to do this?




Expand random range of integers using probability distribution

I tried to solve the classic problem of generating a random integer between 1 and 7, given a function that generates a random integer between 1 and 5. My approach was to add the result of 2 calls to rand5(), effectively turning this into a "sum of dice rolls" problem. The probability of the sum dice rolls is fairly easy to calculate, so I used it here.

My question is: How can I calculate what the values of counter should be? The current values are incorrect, as verified by experiment. Do integer values exist that satisfy the probability? And is there a better way to solve this problem with this approach?

def rand5():
    return random.randint(1,5)

def rand7():
    counter = [1,2,3,4,5,4,3]
    while 0 not in counter:
        sum = rand5() + rand5() - 2
        if sum <= 6:
            counter[sum] -= 1
    return counter.index(0) + 1




Random Number not showing up

I'm currently working on this random number generator and for some reason it does not want to display.

I used console log to make sure the generator was working and it went through perfectly.

What are some good methods I could use to get this to display if anyone has any?




Providing Entropy To JVM

I've been experimenting with the BouncyCastle API for Java and slowly working my way through their "Java Cryptography - Tools and Techniques" ebook. The book contains a short section titled "A Word About Entropy" states the following:

What the JVM is using as an entropy source will vary, on Linux for example, it is normally set to “/dev/random” which may block. Usually installing “rng-tools” or the nearest equivalent will deal with this as it will also expose any underlying hardware supporting RNG generation to be used for seeding “/dev/random”. With some virtual environments hardware RNG may never be available, in that case it is important to find other ways of making entropy available to your JVM. Ways of doing this will vary with the environment you are using.

I might be misunderstanding what this excerpt it saying, but how exactly can I make entropy available to the JVM? The book isn't very specific about this other than stating that the "Ways of doing this will vary with the environment you are using". Is there some kind of Entropy SPI that I am unaware of which can be used to make a source of entropy available to the JVM? My question isn't how to generate entropy or retrieve it from the JVM, but rather, if I already know of and have access to a reliable source of entropy (Such as a file of random bits) how can I make this source of entropy available to the JVM so that it may be used for seeding in cases where other secure sources of entropy are unavailable?




Spectral Test in R

I would like to change my code in a way that 10000 points are placed in a [0,1]^2 plot. I tries changing 256 to 10000 but it generates weird placement. I should change the factors 137 and 187 but not sure how to change it. Anyone knows the logic behind?

Working sample:

nSim = 256
X=rep(0,nSim)
for (i in 2:nSim){
    X[i] = (137*X[i-1]+187)%%256 
}
plot(X[-1],X[-nSim],col="blue",type="p",pch="x",lwd=2)

enter image description here

My code:

nSim = 10000
X=rep(0,nSim)
for (i in 2:nSim){
  X[i] = ((137*X[i-1]+187)%%nSim)
}
plot(X[-1]/nSim,X[-nSim]/nSim,col="blue", type="p",pch=20,lwd=2)

enter image description here




Why is the sum of my blackjack score not working properlly?

I am quite new at programing, and i have been trying to create a Simple BlackJack game on java, however i am having issues with the score counting.

Sometimes it recognizes the actual card value and works fine, others it just defines a random value and messesup with the whole game. i have used numbers from 1 to 52 to randomly define cards into an "array" and so set them as a "jlabel" as the game flows. the score counting is set inside an "switch" which defines the value of each card.

Here is my code please help me:

    public Form2() {
    initComponents();
BilleteraT = Double.toString(Billetera);    
jTextField1.setText("0");
jTextField2.setText(BilleteraT);}



/**
 * This method is called from within the constructor to initialize the form.
 * WARNING: Do NOT modify this code. The content of this method is always
 * regenerated by the Form Editor.
 */
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">                          
private void initComponents() {

    jButton5 = new javax.swing.JButton();
    jTextField1 = new javax.swing.JTextField();
    jLabel1 = new javax.swing.JLabel();
    jLabel2 = new javax.swing.JLabel();
    jLabel3 = new javax.swing.JLabel();
    jLabel4 = new javax.swing.JLabel();
    jLabel7 = new javax.swing.JLabel();
    jLabel8 = new javax.swing.JLabel();
    jLabel9 = new javax.swing.JLabel();
    jLabel10 = new javax.swing.JLabel();
    jTextField2 = new javax.swing.JTextField();
    jTextField3 = new javax.swing.JTextField();
    jTextField4 = new javax.swing.JTextField();
    jLabel11 = new javax.swing.JLabel();
    jLabel12 = new javax.swing.JLabel();
    jLabel5 = new javax.swing.JLabel();
    jButton2 = new javax.swing.JButton();
    jButton3 = new javax.swing.JButton();
    jButton4 = new javax.swing.JButton();
    jLabel6 = new javax.swing.JLabel();

    setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
    setResizable(false);
    getContentPane().setLayout(null);

    jButton5.setBackground(new java.awt.Color(0, 0, 0));
    jButton5.setFont(new java.awt.Font("Helvetica", 1, 48)); // NOI18N
    jButton5.setForeground(new java.awt.Color(255, 255, 255));
    jButton5.setText("Apostar");
    jButton5.addActionListener(new java.awt.event.ActionListener() {
        public void actionPerformed(java.awt.event.ActionEvent evt) {
            jButton5ActionPerformed(evt);
        }
    });
    getContentPane().add(jButton5);
    jButton5.setBounds(218, 187, 230, 60);
    getContentPane().add(jTextField1);
    jTextField1.setBounds(526, 254, 100, 35);

    jLabel1.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
    jLabel1.setIcon(new javax.swing.ImageIcon(getClass().getResource("/img/back.png"))); // NOI18N
    jLabel1.setToolTipText("");
    getContentPane().add(jLabel1);
    jLabel1.setBounds(199, 312, 90, 138);

    jLabel2.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
    jLabel2.setIcon(new javax.swing.ImageIcon(getClass().getResource("/img/back.png"))); // NOI18N
    getContentPane().add(jLabel2);
    jLabel2.setBounds(307, 312, 90, 138);

    jLabel3.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
    jLabel3.setIcon(new javax.swing.ImageIcon(getClass().getResource("/img/back.png"))); // NOI18N
    getContentPane().add(jLabel3);
    jLabel3.setBounds(199, 11, 90, 138);

    jLabel4.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
    jLabel4.setIcon(new javax.swing.ImageIcon(getClass().getResource("/img/back.png"))); // NOI18N
    getContentPane().add(jLabel4);
    jLabel4.setBounds(307, 11, 90, 138);

    jLabel7.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N
    jLabel7.setForeground(new java.awt.Color(255, 255, 255));
    jLabel7.setText("Puntos:");
    getContentPane().add(jLabel7);
    jLabel7.setBounds(20, 340, 120, 14);

    jLabel8.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N
    jLabel8.setForeground(new java.awt.Color(255, 255, 255));
    jLabel8.setText("Puntos:");
    getContentPane().add(jLabel8);
    jLabel8.setBounds(30, 60, 112, 14);

    jLabel9.setFont(new java.awt.Font("Tahoma", 1, 14)); // NOI18N
    jLabel9.setForeground(new java.awt.Color(255, 255, 255));
    jLabel9.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
    jLabel9.setText("Apuesta");
    getContentPane().add(jLabel9);
    jLabel9.setBounds(526, 228, 100, 20);

    jLabel10.setFont(new java.awt.Font("Tahoma", 1, 14)); // NOI18N
    jLabel10.setForeground(new java.awt.Color(255, 255, 255));
    jLabel10.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
    jLabel10.setText("Billetera");
    getContentPane().add(jLabel10);
    jLabel10.setBounds(526, 161, 100, 20);

    jTextField2.setEditable(false);
    getContentPane().add(jTextField2);
    jTextField2.setBounds(526, 187, 100, 35);

    jTextField3.setEditable(false);
    getContentPane().add(jTextField3);
    jTextField3.setBounds(50, 360, 90, 30);

    jTextField4.setEditable(false);
    getContentPane().add(jTextField4);
    jTextField4.setBounds(50, 80, 90, 30);

    jLabel11.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
    getContentPane().add(jLabel11);
    jLabel11.setBounds(415, 312, 90, 138);

    jLabel12.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
    getContentPane().add(jLabel12);
    jLabel12.setBounds(415, 11, 90, 138);

    jLabel5.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
    jLabel5.setIcon(new javax.swing.ImageIcon(getClass().getResource("/img/deck.png"))); // NOI18N
    getContentPane().add(jLabel5);
    jLabel5.setBounds(20, 140, 134, 171);

    jButton2.setText("Pedir");
    jButton2.addActionListener(new java.awt.event.ActionListener() {
        public void actionPerformed(java.awt.event.ActionEvent evt) {
            jButton2ActionPerformed(evt);
        }
    });
    getContentPane().add(jButton2);
    jButton2.setBounds(212, 273, 77, 23);

    jButton3.setText("Plantarse");
    jButton3.addActionListener(new java.awt.event.ActionListener() {
        public void actionPerformed(java.awt.event.ActionEvent evt) {
            jButton3ActionPerformed(evt);
        }
    });
    getContentPane().add(jButton3);
    jButton3.setBounds(306, 273, 77, 23);

    jButton4.setText("Desistir");
    jButton4.addActionListener(new java.awt.event.ActionListener() {
        public void actionPerformed(java.awt.event.ActionEvent evt) {
            jButton4ActionPerformed(evt);
        }
    });
    getContentPane().add(jButton4);
    jButton4.setBounds(397, 273, 77, 23);

    jLabel6.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
    jLabel6.setIcon(new javax.swing.ImageIcon(getClass().getResource("/img/table.png"))); // NOI18N
    getContentPane().add(jLabel6);
    jLabel6.setBounds(0, 0, 650, 470);

    setSize(new java.awt.Dimension(666, 509));
    setLocationRelativeTo(null);
}// </editor-fold>                        
int []card;
int p1,p2,p3,p4,c1,c2,c3,c4,k;
double scoreP=0,scoreC=0,scorep1,scorep2,scorep3,scorep4,scorec1,scorec2,scorec3,scorec4;
Random rnd=new Random();
boolean step1 = false;
boolean step2 = false;


private void jButton5ActionPerformed(java.awt.event.ActionEvent evt) {                                         
card= new int[53];
Amount = Double.parseDouble(Apuesta);
Apuesta = jTextField1.getText();      
BilleteraT = Double.toString(Billetera-Amount); 
jTextField2.setText(BilleteraT);


if (Apuesta.equalsIgnoreCase("0")) {
JOptionPane.showMessageDialog(null, "Por Favor, ingrese una apuesta");}

else {
step2 = false;
if(step1=true){
Apuesta = jTextField1.getText();
Amount = Double.parseDouble(Apuesta);
Billetera=Billetera-Amount;
BilleteraT = Double.toString(Billetera); 
jTextField2.setText(BilleteraT);}


while(Amount <= Billetera && Amount!=0 || Billetera>=0&& Amount!=0){

jButton5.setVisible(false);
jButton5.invalidate();    

for (k=1;k<=6;k++){    
card[k]=rnd.nextInt(53)+1;

switch (k){
    case 1: p1= card[1];
    case 2: p2= card[2];
    case 3: c1= card[3];
    case 4: c2= card[4];
    case 5: p3= card[5];
    case 6: c3= card[6];}}

jLabel1.setIcon(new ImageIcon(getClass().getResource("/img/"+p1+".png")));
jLabel2.setIcon(new ImageIcon(getClass().getResource("/img/"+p2+".png")));
jLabel3.setIcon(new ImageIcon(getClass().getResource("/img/"+c1+".png")));
jLabel4.setIcon(new ImageIcon(getClass().getResource("/img/back.png")));

for (k=1;k<=53;k++){      
switch(k){
    case 1:case 14:case 27:case 40:
    if(k==p1){scorep1=2;} if(k==p2){scorep2=2;}
    if(k==c1){scorec1=2;} if(k==c2){scorec2=2;}

    if (k==p3){scorep3=2;}
    if (k==c3){scorec3=2;}
    break;
    case 2:case 15:case 28:case 41:
    if(k==p1){scorep1=3;} if(k==p2){scorep2=3;}
    if(k==c1){scorec1=3;} if(k==c2){scorec2=3;}

    if (k==p3){scorep3=3;}
    if (k==c3){scorec3=3;}
    break;
    case 3:case 16:case 29:case 42:
    if(k==p1){scorep1=4;} if(k==p2){scorep2=4;}
    if(k==c1){scorec1=4;} if(k==c2){scorec2=4;}

    if (k==p3){scorep3=4;}
    if (k==c3){scorec3=4;}
    break;
    case 4:case 17:case 30:case 43:
    if(k==p1){scorep1=5;} if(k==p2){scorep2=5;}
    if(k==c1){scorec1=5;} if(k==c2){scorec2=5;}

    if (k==p3){scorep3=5;}
    if (k==c3){scorec3=5;}
    break;
    case 5:case 18:case 31:case 44:
    if(k==p1){scorep1=6;} if(k==p2){scorep2=6;}
    if(k==c1){scorec1=6;} if(k==c2){scorec2=6;}

    if (k==p3){scorep3=6;}
    if (k==c3){scorec3=6;} 
    break;
    case 6:case 19:case 32:case 45:
    if(k==p1){scorep1=7;} if(k==p2){scorep2=7;}
    if(k==c1){scorec1=7;} if(k==c2){scorec2=7;}    

    if (k==p3){scorep3=7;}
    if (k==c3){scorec3=7;} 
    break;
    case 7:case 20:case 33:case 46:
    if(k==p1){scorep1=8;} if(k==p2){scorep2=8;}
    if(k==c1){scorec1=8;} if(k==c2){scorec2=8;}

    if (k==p3){scorep3=8;}
    if (k==c3){scorec3=8;} 
    break;
    case 8:case 21:case 34:case 47:
    if(k==p1){scorep1=9;} if(k==p2){scorep2=9;}
    if(k==c1){scorec1=9;} if(k==c2){scorec2=9;}    

    if (k==p3){scorep3=9;}
    if (k==c3){scorec3=9;} 
    break;
    case 9:case 11:case 12:case 13:case 22:case 24:case 25:case 26:case 35:case 37:case 38:case 39:case 48:case 50:case 51:case 52:
    if(k==p1){scorep1=10;} if(k==p2){scorep2=10;}
    if(k==c1){scorec1=10;}  if(k==c2){scorec2=10;}

    if (k==p3){scorep3=10;}
    if (k==c3){scorec3=10;} 
    break;
    case 10:case 23:case 36:case 49:
    if(k==p1){scorep1=1;} if(k==p2){scorep2=1;}
    if(k==c1){scorec1=1;} if(k==c2){scorec2=1;}

    if (k==p3){scorep3=1;}
    if (k==c3){scorec3=1;} 
    break;}}

    scoreP=scorep1+scorep2;
    scoreC=scorec1;
    score1 = Double.toString(scoreP);
    score2 = Double.toString(scoreC);
    jTextField3.setText(score1);
    jTextField4.setText(score2); 
    step1=true;}

    if(Amount!=0&&Billetera>0 || Billetera<=0 ){JOptionPane.showMessageDialog(null,"No podeis apostar lo que no tenes!!!");} 


}

}                                        
/** PEDIR BUTTON  */
private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {                                         

if (step1=true && Billetera>0){

    if (step2=true && Billetera>0){
    p4=rnd.nextInt(53)+1;
     for (k=1;k<=53;k++){      
switch(k){
    case 1:case 14:case 27:case 40:    
    if (k==p4){scorep4=2;}
    if (k==c4){scorec4=2;}
    break;
    case 2:case 15:case 28:case 41:
    if (k==p4){scorep4=3;}
    if (k==c4){scorec4=3;}
    break;
    case 3:case 16:case 29:case 42:
    if (k==p4){scorep4=4;}
    if (k==c4){scorec4=4;}
    break;
    case 4:case 17:case 30:case 43:
    if (k==p4){scorep4=5;}
    if (k==c4){scorec4=5;}
    break;
    case 5:case 18:case 31:case 44:
    if (k==p4){scorep4=6;}
    if (k==c4){scorec4=6;} 
    break;
    case 6:case 19:case 32:case 45:
    if (k==p4){scorep4=7;}
    if (k==c4){scorec4=7;} 
    break;
    case 7:case 20:case 33:case 46:
    if (k==p4){scorep4=8;}
    if (k==c4){scorec4=8;} 
    break;
    case 8:case 21:case 34:case 47:
    if (k==p4){scorep4=9;}
    if (k==c4){scorec4=9;} 
    break;
    case 9:case 11:case 12:case 13:case 22:case 24:case 25:case 26:case 35:case 37:case 38:case 39:case 48:case 50:case 51:case 52:
    if (k==p4){scorep4=10;}
    if (k==c4){scorec4=10;} 
    break;
    case 10:case 23:case 36:case 49:
    if (k==p4){scorep4=1;}
    if (k==c4){scorec4=1;} 
    break;}}
    scoreP=scorep4+scoreP;
    score1 = Double.toString(scoreP);
    jTextField3.setText(score1);
    jLabel11.setIcon(new ImageIcon(getClass().getResource("/img/"+p4+".png")));
    }

    jLabel11.setIcon(new ImageIcon(getClass().getResource("/img/"+p3+".png")));

    scoreP=scorep3+scoreP;
    score1 = Double.toString(scoreP);
    jTextField3.setText(score1);
    step2 = true;


    if (scoreP==21){JOptionPane.showMessageDialog(null,"Felicitaciones, Ganaste!");
    Billetera=Billetera+Amount*2;
    BilleteraT = Double.toString(Billetera); 
    jTextField2.setText(BilleteraT);

    res=JOptionPane.showInputDialog("Queres intentar otra vez?");

    if (res.equalsIgnoreCase("si")){
    JOptionPane.showMessageDialog(null,"Sin problemas, ingrese nueva Aposta");
    jButton5.setVisible(true);
    jButton5.validate();
    jLabel1.setIcon(new ImageIcon(getClass().getResource("/img/back.png")));
    jLabel2.setIcon(new ImageIcon(getClass().getResource("/img/back.png")));
    jLabel3.setIcon(new ImageIcon(getClass().getResource("/img/back.png")));
    jLabel11.setIcon(new ImageIcon(getClass().getResource("")));
    scoreC=0;
    scoreP=0;
    score1 = Double.toString(scoreP);
    score2 = Double.toString(scoreC);
    jTextField3.setText(score1);
    jTextField4.setText(score2);} 

    else if(res.equalsIgnoreCase("no")){
    JOptionPane.showMessageDialog(null,"Bueno, Hasta la proxima! Adios");
    System.exit(0);

    }else{JOptionPane.showMessageDialog(null,"Respuesta Invalida");}}       

    if (scoreP>21){JOptionPane.showMessageDialog(null,"Uhh,Pasaste, mas suerte en la proxima!");

    res=JOptionPane.showInputDialog("Queres intentar otra vez?");
    if (res.equalsIgnoreCase("si")){
    JOptionPane.showMessageDialog(null,"Sin problemas, ingrese nueva Aposta");
    jButton5.setVisible(true);
    jButton5.validate();
    jLabel1.setIcon(new ImageIcon(getClass().getResource("/img/back.png")));
    jLabel2.setIcon(new ImageIcon(getClass().getResource("/img/back.png")));
    jLabel3.setIcon(new ImageIcon(getClass().getResource("/img/back.png")));
    jLabel11.setIcon(new ImageIcon(getClass().getResource("")));
    scoreC=0;
    scoreP=0;
    score1 = Double.toString(scoreP);
    score2 = Double.toString(scoreC);
    jTextField3.setText(score1);
    jTextField4.setText(score2);}

    else if(res.equalsIgnoreCase("no")){
    JOptionPane.showMessageDialog(null,"Bueno, Hasta la proxima! Adios");
    System.exit(0);

    }else{JOptionPane.showMessageDialog(null,"Respuesta Invalida");}}

}
}                                        
/** PLANTARSE BUTTON  */
private void jButton3ActionPerformed(java.awt.event.ActionEvent evt) {                                         
JOptionPane.showMessageDialog(null,"Okay, Mi turno!");

if (step1=true&&Billetera>0){
 scoreC=scorec2+scoreC;
 score2 = Double.toString(scoreC);
 jTextField4.setText(score2);
 jLabel4.setIcon(new ImageIcon(getClass().getResource("/img/"+c2+".png")));

 if(scoreC<=16){resc="hit";

 while(resc.equals("hit")){

 jLabel2.setIcon(new ImageIcon(getClass().getResource("/img/"+c3+".png")));
 scoreC=scorec3+scoreC;
 score2 = Double.toString(scoreC);
 jTextField4.setText(score2);

 if(scoreC<=16){resc="hit";}
 if(scoreC>16){resc="stand";}}

 }else if(scoreC>16){resc="stand";}

 while(resc.equals("stand")){

if (scoreC>scoreP&&scoreC<=21){JOptionPane.showMessageDialog(null,"Gano yo, mas suerte en la proxima!");

    res=JOptionPane.showInputDialog("Queres intentar otra vez?");
    if (res.equalsIgnoreCase("si")){
    JOptionPane.showMessageDialog(null,"Sin problemas, ingrese nueva Aposta");
    jButton5.setVisible(true);
    jButton5.validate();
    jLabel1.setIcon(new ImageIcon(getClass().getResource("/img/back.png")));
    jLabel2.setIcon(new ImageIcon(getClass().getResource("/img/back.png")));
    jLabel3.setIcon(new ImageIcon(getClass().getResource("/img/back.png")));
    jLabel11.setIcon(new ImageIcon(getClass().getResource("")));
    jLabel12.setIcon(new ImageIcon(getClass().getResource("")));
    scoreC=0;
    scoreP=0;
    score1 = Double.toString(scoreP);
    score2 = Double.toString(scoreC);
    jTextField3.setText(score1);
    jTextField4.setText(score2); }

    else if(res.equalsIgnoreCase("no")){
    JOptionPane.showMessageDialog(null,"Bueno, Hasta la proxima! Adios");
    System.exit(0);
    }else{JOptionPane.showMessageDialog(null,"Respuesta Invalida");}}

if(scoreP>scoreC&&scoreP<=21){JOptionPane.showMessageDialog(null,"Felicitaciones, Ganaste!");
    Billetera=Billetera+Amount*2;
    BilleteraT = Double.toString(Billetera); 
    jTextField2.setText(BilleteraT);

    res=JOptionPane.showInputDialog("Queres intentar otra vez?");
    if (res.equalsIgnoreCase("si")){
    JOptionPane.showMessageDialog(null,"Sin problemas, ingrese nueva Aposta");
    jButton5.setVisible(true);
    jButton5.validate();
    jLabel1.setIcon(new ImageIcon(getClass().getResource("/img/back.png")));
    jLabel2.setIcon(new ImageIcon(getClass().getResource("/img/back.png")));
    jLabel3.setIcon(new ImageIcon(getClass().getResource("/img/back.png")));
    jLabel11.setIcon(new ImageIcon(getClass().getResource("")));
    jLabel12.setIcon(new ImageIcon(getClass().getResource("")));
    scoreC=0;
    scoreP=0;
    score1 = Double.toString(scoreP);
    score2 = Double.toString(scoreC);
    jTextField3.setText(score1);
    jTextField4.setText(score2);}

    else if(res.equalsIgnoreCase("no")){
    JOptionPane.showMessageDialog(null,"Bueno, Hasta la proxima! Adios");
    System.exit(0);
    }else{JOptionPane.showMessageDialog(null,"Respuesta Invalida");}}


if(scoreP==scoreC&&scoreP<=21){JOptionPane.showMessageDialog(null,"Es un Empate!");

    res=JOptionPane.showInputDialog("Queres jugar de nuevo?");
    if (res.equalsIgnoreCase("si")){
    JOptionPane.showMessageDialog(null,"Sin problemas, ingrese nueva Aposta");
    jButton5.setVisible(true);
    jButton5.validate();
    jLabel1.setIcon(new ImageIcon(getClass().getResource("/img/back.png")));
    jLabel2.setIcon(new ImageIcon(getClass().getResource("/img/back.png")));
    jLabel3.setIcon(new ImageIcon(getClass().getResource("/img/back.png")));
    jLabel11.setIcon(new ImageIcon(getClass().getResource("")));
    jLabel12.setIcon(new ImageIcon(getClass().getResource("")));
    scoreC=0;
    scoreP=0;
    score1 = Double.toString(scoreP);
    score2 = Double.toString(scoreC);
    jTextField3.setText(score1);
    jTextField4.setText(score2); } 

    else if(res.equalsIgnoreCase("no")){
    JOptionPane.showMessageDialog(null,"Bueno, Hasta la proxima! Adios");
    System.exit(0);
    }else{JOptionPane.showMessageDialog(null,"Respuesta Invalida");}
    }

}
} 
}                                        
 /** DESISTIR BUTTON  */
private void jButton4ActionPerformed(java.awt.event.ActionEvent evt) {                                         
    if (step1=true && Billetera>0){
    JOptionPane.showMessageDialog(null,"Bueno, mas suerte en la proxima!");

    res=JOptionPane.showInputDialog("Queres intentar otra vez?");
    if (res.equalsIgnoreCase("si")){
    JOptionPane.showMessageDialog(null,"Sin problemas, ingrese nueva Aposta");
    jButton5.setVisible(true);
    jButton5.validate();
    jLabel1.setIcon(new ImageIcon(getClass().getResource("/img/back.png")));
    jLabel2.setIcon(new ImageIcon(getClass().getResource("/img/back.png")));
    jLabel3.setIcon(new ImageIcon(getClass().getResource("/img/back.png")));
    jLabel11.setIcon(new ImageIcon(getClass().getResource("")));
    jLabel12.setIcon(new ImageIcon(getClass().getResource("")));
    scoreC=0;
    scoreP=0;
    score1 = Double.toString(scoreP);
    score2 = Double.toString(scoreC);
    jTextField3.setText(score1);
    jTextField4.setText(score2); }

    else if(res.equalsIgnoreCase("no")){
    JOptionPane.showMessageDialog(null,"Bueno, Hasta la proxima! Adios");
    System.exit(0);
    }else{JOptionPane.showMessageDialog(null,"Respuesta Invalida");}}    
}