dimanche 30 avril 2017

generate random list C

I have created a list in C with 28 elements, and I want to clutter the elements of the list. Any way to do it? I have implemented this algorithm but I does not work.

Hola tengo creada una lista en C con 28 elementos, y quiero desordenar los elementos que hay inseridos en ella. Alguna idea? he creado este algoritmo pero no funciona.

void LOGICA_fichasRandom(ListaPDI * l) {
    int numero_random;
    int i,j,u;
    Ficha aux;

    i = 0;
    while(i < 29) {
        LISTAPDI_irInicio(l);
        for(u = 0; u< i-1; u++) {
            LISTAPDI_avanzar(l);
        }

        numero_random = (rand() % 29) - i;
        aux = LISTAPDI_consultar(*l);
        LISTAPDI_borrar(l);
        for (j = 0; j<numero_random; j++) {
            LISTAPDI_avanzar(l);
        }

        LISTAPDI_inserir(l, aux);
        i++;
    }
}




Inputting text file to an array, randomizing data from text file in array, outputting randomized data to separate text file

I have successfully copied the code into the array (which is actually a list of all 201 countries and their level of internet usage). The list is in alphabetical order and I want to randomize the data so that there is no order to the data in the array. Here is my code:

import java.util.*;
import java.io.*;

public class Unsort {
public static void main(String[] args) throws IOException {

    String[] countries = new String[201];
    String[] percentages = new String[201];
    String[] line = new String[201];

    Scanner keyboard = new Scanner(System.in);

    Scanner fileIN = new Scanner(new File("F:/CountrySortedAlpha.txt"));
    PrintWriter out = new PrintWriter("F:/CountryUnsortedAlpha.txt");

    while(fileIN.hasNext()){
        for(int i = 0; i < 201; i++){
            line[i] = fileIN.nextLine();
            System.out.print(line[i] + " " + i + "\n");
        }
        for(int i = 0; i < 201; i ++){
            int randomize = (int) (Math.random() * 201);
            System.out.print("\n" + randomize);
        }
    }
}
}

The way that I have been trying is to make a random number to access the array at, but it ends up with so many collisions. The second loop was just to make sure that the random variable worked. So my question is: how do I randomize the data in the array without collisions while using the random number generator?




Unity c#: How to prevent same object from being picked from array twice in a row

Good Afternoon all.

I am having a bit of a problem figuring out how to randomly get an object out of a list that wasn't picked on the last update of a script. When this randomly instantiated object is spawned and reaches a certain y value, it will set itself to inactive. So when this object is not active, it will go through an array and pick another object at random. However, I do not want to include the previous active object.

example: blue ball was first active. Moves on the Y axis. Becomes inactive. Next object spawn should have no chance of being a blue ball. Any ideas and help will be greatly appreciated.

My code is below

using UnityEngine;
using System.Collections;
using System.Collections.Generic;

public class ballGeneratorShooter : MonoBehaviour
{

    private int ballSelector;
    private TagNumber theTagNumber;
    public ObjectPooler[] theObjectballPools;//In my inspector, I have 5 prefab gameObjects attached
    List<ObjectPooler> changingBalls;

    public bool changeBalls;

    public GameObject currentBall;
    public GameObject newBall;

    // Use this for initialization
    void Start()
    {

        changingBalls = new List<ObjectPooler>();
        currentBall = newBall;
    }

    // Update is called once per frame
    void Update()
    {

        if (newBall == null)
        {

            ballSelector = Random.Range(0, theObjectballPools.Length);

            newBall = theObjectballPools[ballSelector].GetPooledObject();

            newBall.transform.position = transform.position;
            newBall.transform.rotation = transform.rotation;
            newBall.SetActive(true);
        }

        if (newBall.activeInHierarchy == false)
        {
            if (changeBalls)
            {
                for (int i = 0; i < theObjectballPools.Length; i++)
                {
                    if (theObjectballPools[i].GetPooledObject().GetComponent<TagNumber>().tag != currentBall.GetComponent<TagNumber>().tag)
                    {
                        changingBalls.Add(theObjectballPools[i]);
                    }
                    //changingballs.Add(theObjectballPools[i]);
                }

                ballSelector = Random.Range(0, changingBalls.Count);
                newBall = theObjectballPools[ballSelector].GetPooledObject();
                Debug.Log(changingBalls.Count);
                newBall.transform.position = transform.position;
                newBall.transform.rotation = transform.rotation;
                newBall.SetActive(true);
                currentBall = newBall;
                changeBalls = false;
                changingBalls.Clear();
            }

        }

    }

}




about Java game tic tac toe

I have the problem about TicTacToe, how to teach a computer to play with human, I have already done it with Random numbers, but I want to do it more advanced, and I don't have any ideas, please, help me




Moving Image randomly multiple times

I found a nice answer about moving images multiple times here:

http://ift.tt/2qhHXL2

It's really helpful for what i want to achieve in my program but I need one more thing. Fireballs are stored in List and they are painted when we press SPACE. I want to generate them randomly. Is there any simple way to do that?

Code from topic:

import java.awt.*;
import java.awt.event.*;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.net.URL;
import java.util.*;
import java.util.List;
import java.util.logging.*;
import javax.imageio.ImageIO;
import javax.swing.*;
import javax.swing.Timer;

public class WannaBeStreetFighter extends JPanel {

private static final int D_W = 700;
private static final int D_H = 250;
private static final int X_INC = 10;

List<Fireball> fireBalls;
BufferedImage ryu;
BufferedImage fireball;
BufferedImage background;

public WannaBeStreetFighter() {

    try {
        ryu = ImageIO.read(new URL("http://ift.tt/2pu4n8X"));
        background = ImageIO.read(new URL("http://ift.tt/2qi3xPr"));
        fireball = ImageIO.read(new URL("http://ift.tt/2pujXkM"));
    } catch (IOException ex) {
        Logger.getLogger(WannaBeStreetFighter.class.getName()).log(Level.SEVERE, null, ex);
    }

    fireBalls = new LinkedList<>();

    Timer timer = new Timer(40, new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e) {
            Iterator<Fireball> it = fireBalls.iterator();
            while (it.hasNext()) {
                Fireball ball = it.next();
                if (ball.x > D_W) {
                    it.remove();
                    System.out.println(fireBalls.size());
                } else {
                    ball.x += X_INC;
                    repaint();
                }
            }
        }
    });
    timer.start();

    InputMap inputMap = getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW);
    inputMap.put(KeyStroke.getKeyStroke("SPACE"), "hadouken");
    getActionMap().put("hadouken", new AbstractAction() {
        @Override
        public void actionPerformed(ActionEvent e) {
            fireBalls.add(new Fireball(fireball));
        }
    });

}

@Override
protected void paintComponent(Graphics g) {
    super.paintComponent(g);
    g.drawImage(background, 0, 0, D_W, D_H, this);
    g.drawImage(ryu, 50, 125, 150, 115, this);
    for (Fireball ball : fireBalls) {
        ball.drawFireball(g);
    }
}

@Override
public Dimension getPreferredSize() {
    return new Dimension(D_W, D_H);
}

private class Fireball {

    Image fireball;
    int x = 150;
    int y = 125;

    public Fireball(Image image) {
        fireball = image;
    }

    public void drawFireball(Graphics g) {
        g.drawImage(fireball, x, y, 75, 50, null);
    }
}

public static void main(String[] args) {
    SwingUtilities.invokeLater(new Runnable() {
        public void run() {
            JFrame frame = new JFrame("Best Street Fighter ever");
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            frame.add(new WannaBeStreetFighter());
            frame.pack();
            frame.setLocationRelativeTo(null);
            frame.setVisible(true);
        }
    });
}
}




Mysql random unique number not working

I'm trying to get a unique code number which doesn't exists in the "codes" table using a query I found in several other SO threads:

http://ift.tt/2qi1Yku http://ift.tt/2pugzGB

I'm currently trying to use this sqlfiddle:

http://ift.tt/2qhX5I8

With lots of issues:

  1. if no codes are in the table, I get no results at all.
  2. if there ARE any codes, the results is not unique. I can get a result already in the table...

Any idea on how to make this work?

Thanks!




how to make multiple instances in JavaScript

i was trying to generate random numbers to pick random items from array to update collage of pictures, i noticed that sometimes generated number is same to a previously generated number causing one picture to update 2-3 times so to check this i thought it would be great if i store last generated random number into an variable and make a function that checks if last generated value is equal to current generated value, it continue to generate numbers till a non-equal value is generated.

it is working fine until i wanted multiple instances ... as variable that stores last value is same, i am getting same numbers.

var bgs = document.getElementById('collage').getElementsByClassName('bg');
var images = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];

var lv = null;
function get_random(length) {
    arr = [];
    while (arr.length < 1) {
        var cv = Math.floor(Math.random() * length);
        if (lv === cv) {
            arr = [];
            continue;
        }
        else if (lv !== cv) {
            arr.push(cv);
            break;
        }
    }
    lv = arr[0];
    return arr[0];
}

function update_collage() {
    var img = images[get_random(images.length)];
    var target = bgs[get_random(bgs.length)];
    target.style.background = "url('assets/img/thumbs/" + img + ".jpg') no-repeat center";
    target.style.backgroundSize = "cover";
}
window.setInterval(function(){
    update_collage();
}, 1200);

how can i correct this, how can i create multiple instances of function or variable




Generating random numbers in C with different seed in every loop?

Note: This post is not a duplicate of how to generate random numbers in C, it does not answer my question.

I have a function which is:

double generator(double * ran_i) {
  srand(time(NULL));
  return ran_i[rand()%1000];
}

which takes an array containing 1000 numbers, then I try to call:

for(i=0; i< 1000; ++i) {
  printf("%lf", generator(ran[0]));
}

However in that loop it always gives me the same number. I figured out that time(NULL) does not change the seed fast enough. How can I change this seed faster or even better change it in every loop? Also I can only use libraries compatible with ANSI C standard.




C# Get random value by chance - small number with high chance, big number with low chance

As i described above, i want to get small number alot and big number for few times.

some kind of two graph crossing.

any possible ways or internal math stuff?




How do I multiply or gather random numbers?

Can someone help me and tell me how to multiply these random numbers. As you can see in the code, I gave the condition that only 6 numbers appear. I need that when the last figure appears I will make an input to indicate the result of multiplying these numbers. Now I only need an idea how to make them multiply or gather. Thanks.

This is my code:

     using System.Collections;
     using System.Collections.Generic;
     using UnityEngine.UI;
     using UnityEngine;

    public class RandomNumbers : MonoBehaviour {

    public Transform mCanvas;
    public Text[] numbers;
    bool activate = true;
    public int suma;
    int idx = 0;

    void Start()
    {
        Shuffle(numbers);
        StartCoroutine("CreateNum");
    }

    IEnumerator CreateNum()
    {
    yield return new WaitForSeconds(3f);

    while (idx < numbers.Length)
        {
            if (activate)
            {
                Text g = Instantiate(numbers[idx], new Vector3(Random.Range(-450, 450), Random.Range(-450, 450), 0), Quaternion.identity);
                g.transform.SetParent(mCanvas, false);
            }
                yield return new WaitForSeconds(2f);
                ++idx;
            if(idx >= 6)
            {
                activate = false;
            }
        }
    }
    public void Shuffle<T>(IList<T> list)
    {
        int n = list.Count;
        while (n > 1)
        {
            n--;
            int k = Random.Range(0, n + 1);
            T value = list[k];
            list[k] = list[n];
            list[n] = value;
        }

    }
// Update is called once per frame
void Update() {

}

}




samedi 29 avril 2017

Geometric distribution values in Forest Fire generation model

I am trying to do implementation (Python) of the Forest Fire graph generation algorithm (http://ift.tt/2qkIwR9).
Here is how pseudo-code looks like: pseudo-code of FF model
The problem I am having with is understanding the second step. How to generate these numbers?

There is an implementation in numpy library http://ift.tt/2qkRTR2 but it requires not just p value but also size (size of what in case of this algorithm? why in the algorithms are given geometric means, why not just p value?)

I found one solution here http://ift.tt/2piA0DU but I am not sure it works right (according to the needs of this algorithm)

Any suggestions? Thank you all very much in advance!

Guys from @igraph, I also tagged you as you have implementation of FF. Maybe you could help.




Trial Handler: Making trial order conditional

I am designing a memory task in Psychopy and I have 4 different types of feature search contained (16 total trials with other conditions). Currently I am using trialHandler but it is very important that I ensure that two of the same trial types can not directly follow eachother. So if I have trial types a, b, c and d, I need to make sure I never get b, a, c, c, a in the randomisation of my order. Is there anyone way to manipulate how trialHandler selects it trial order? Thank you




Basic Python Q - calculating averages of columns in an array (valuation European options)

Pretty new to Python but am really enjoying learning how to code option values.

Pretty easy to calculate this in excel but want to learn how to properly do this in Python. If I want to solve the arithmetic mean of values over the course of N time-steps, am I thinking about the calculation correctly? I should theoretically, get one value (the average value) of each column in the array.

S=S0+cumsum(S0*r*dt+sigma*S0*math.sqrt(dt)*random.standard_normal((Days+1,I)),axis=0)
S[0]=S0
S=S.mean()
print(S)




Python3, get random node from Binary Tree

I built a Binary Search Tree:

import random

class Node(object):
 def __init__(self, key):
    self.key = key
    self.leftChild = None
    self.rightChild = None
    self.parent = None

 def hasLeftChild(self):
    if self.leftChild:
        return True
    else:
        return False

 def hasRightChild(self):
    if self.rightChild:
        return True
    else:
        return False

 def isLeftChild(self):
    if self.parent.leftChild == self:
        return True
    else:
        return False

 def isRightChild(self):
    if self.parent.rightChild == self:
        return True
    else:
        return False

 def isRoot(self):
    if not self.parent:
        return True
    else:
        return False


class BinaryTree(object):
 def __init__(self):
    self.root = None
    self.storage = 0

 def addNode(self, newItem):
    if self.storage == 0:
        self.root = Node(newItem)
    else:
        currentNode = self.root
        self.__addNode(currentNode, newItem)
    self.storage += 1

 def __addNode(self, currentNode, newItem):
    if newItem < currentNode.key:
        if currentNode.hasLeftChild():
            self.__addNode(currentNode.leftChild, newItem)

        else:
            currentNode.leftChild = Node(newItem)
            currentNode.leftChild.parent = currentNode
    if newItem > currentNode.key:
        if currentNode.hasRightChild():
            self.__addNode(currentNode.rightChild, newItem)
        else:
            currentNode.rightChild = Node(newItem)
            currentNode.rightChild.parent = self

 def findNode(self, searchKey):
    if self.storage == 0:
        return None
    else:
        if self.root.key == searchKey:
            return self.root
        else:
            currentNode = self.root
            return self.__findNode(currentNode, searchKey)

 def __findNode(self, currentNode, searchKey):
    if searchKey == currentNode.key:
        return currentNode
    if searchKey < currentNode.key:
        if currentNode.hasLeftChild():
            return self.__findNode(currentNode.leftChild, searchKey)
    if searchKey > currentNode.key:
        if currentNode.hasRightChild():
            return self.__findNode(currentNode.rightCHild, searchKey)
    return None

 def getRandomNode(self):
    randomNum = random.randrange(self.storage)
    currentNode = self.root
    self.__getRandomNode(currentNode, randomNum)

 def __getRandomNode(self, currentNode, numCount):
    if numCount == 0:
        print('Find node {0}'.format(currentNode.key))
        return currentNode, numCount
    else:
        if currentNode.hasLeftChild():
            numCount -= 1
            node, numCount = self.__getRandomNode(currentNode.leftChild, numCount)

        if currentNode.hasRightChild():
            numCount -= 1
            node, numCount = self.__getRandomNode(currentNode.rightChild, numCount)
        return None, numCount

print('-----Add Node to BTree-----')
myBinaryTree = BinaryTree() 
myBinaryTree.addNode(15)
myBinaryTree.addNode(10)
myBinaryTree.addNode(20)
myBinaryTree.addNode(9)
myBinaryTree.addNode(13)
myBinaryTree.addNode(12)
print('-----Get Random Node-----')
myBinaryTree.getRandomNode()

When I was building the getRandom recursive function, for some of reason, I can only print(make finding random node logically work). But this is really not my main purpose, my main purpose is return the "random node" Anyone can help me modified the getRandom function and let the "return Node" really work ?

Thanks




How to get Random numbers to test math equation?

I have trouble with this equation : E * cotangent((q * E)/(k * t)) = nkT/q

I'm looking for the values of E for the equality can be acheived knowing that : q , k are constant and t , n are variables For that I tried this code but apparently is failed

public class Equation {

public static double q = 1.6E-19;
public static double k = 1.38E-23;

    //double y = E * 1/Math.tan(E*q/k*t);
    //DecimalFormat df = new DecimalFormat("#.#####");
public static double[] nktq = new double[]{0.02857,0.02674,0.03118,0.02829,0.02976,0.02898,0.03001,0.02953,0.032};
public static double[] t = new double[]{80,100,150,200,250,280,300,320,350};
public static double[] n = new double[]{4.14,3.1,2.41,1.64,1.38,1.20,1.16,1.07,1.06};
private static DecimalFormat df2 = new DecimalFormat(".##");

public static double genE(){
   double start = 0;
   double end = 30;
   double random = new Random().nextDouble();
   // DecimalFormat df = new DecimalFormat("#.##");
   // df.setRoundingMode(RoundingMode.FLOOR);
    double E = start + (random * (end - start));

    //double E = new Double(df.format(result));
    System.out.println(df2.format(E));
return E;
}



public static void main(String[] args) {
    //double y = E * 1/Math.tan(E*q/k*t);
    //DecimalFormat df = new DecimalFormat("#.#####")
    double E = 0;
    while ( Math.round(E *  1/Math.tan((q * E)/(k * t[0]))*100000)!= nktq[0]){
         genE();
    }
    } 
    }

help please !




c++ function with random always returns identical object

I am working on code for a genetic algorithm (understanding of GA not required). I have a StackingChromosome class which contains a member variable called 'solution' which is a vector of vectors of floats (a vector of 3 coordinates; x, y and z). I have a ChromosomePopulation class which is a vector of StackingChromosomes. Creating new StackingChromsomes is handled by a ChromosomeFactory class. I am trying to test it with this code (more details after the code block):

cout << "Testing the chromosomes are different: " << endl;

std::vector<std::vector<float>> loopChromosome;
// I have used the name firstgene2 because i have already used firstgene
std::vector<float> firstGene2;
float firstGenePos;

for (int i = 0; i < outputPopulation.getPopulationSize(); i++)
{
    loopChromosome = outputSolutions[i].getSolution();
    for (int j = 0; j < 3; j++)
    {
        firstGene2 = loopChromosome[0];
        firstGenePos = firstGene2[j];
        cout << "chromosome " << to_string(i) << " has at gene position " << to_string(j) << " the value " << to_string(firstGenePos) << endl;
    }
}

outputSolutions if defined by:

ChromosomePopulation outputPopulation = ChromosomePopulation(10);
std::vector<StackingChromosome> outputSolutions = outputPopulation.getPopulation();

ChromosomePopulation sets the population variable with this code in the constructor:

ChromosomePopulation::ChromosomePopulation(unsigned int initialPopulationSize)
{
    populationSize = initialPopulationSize;
    cFactory = ChromosomeFactory();
    for (unsigned int i = 0; i < initialPopulationSize; i++)
    {
        StackingChromosome newChromosome = cFactory.createNewChromosome();
        population.push_back(newChromosome);
    }
}

ChromosomeFactory funciton createNewChromosome is defined as:

StackingChromosome ChromosomeFactory::createNewChromosome()
{
    StackingChromosome newChromosome = StackingChromosome();
    std::vector<std::vector<float>> newSolution = std::vector<std::vector<float>>();
    for (int i = 0; i < chromosomeMaxLength; i++)
    {
        std::vector<float> gene = generateRandomGene();
        newSolution.push_back(gene);
    }
    newChromosome.setSolution(newSolution);
    return newChromosome;
}

and the generateRandomGene() function is defined as:

std::vector<float> ChromosomeFactory::generateRandomGene()
{
    //creates an empty gene
    std::vector<float> gene = std::vector<float>();
    //repeats for every space the gene needs filled, 3 in this case. 
    for (int i = 0; i < geneMaxLength; i++)
    {
        //initialise random seed
        srand(time(NULL));
        //generate random number in the range 0-100 inclusive
        float randomWhole = rand() % 101;
        //turns the random number into a percentage
        float randomPercent = randomWhole / 100;
        //the 2 vectors have the max and min values of the x, y and z coordinates. 
        //range is the difference between the max and the min.
        //for example, if the max value is 3 and the min is 1 the range is 2
        float range = geneMaxValues[i] - geneMinValues[i];
        //muliplies the percentage generated randomly ealier with the range of the values
        float randRange = randomPercent * range;
        //adds the generate random amount within the range to the minimum value, giving a number between the max and min values
        float randPoint = geneMinValues[i] + randRange;
        //add the random point to the gene
        gene.push_back(randPoint);
    }
    return gene;
}

My problem is that in the vector of StackingChromosomes that is created, all the chromosomes have the same values. When you run the first code block you will get an output like:

Chromosome 0 has at gene position 0 the value 7
Chromosome 0 has at gene position 1 the value 4
Chromosome 0 has at gene position 2 the value 9
Chromosome 1 has at gene position 0 the value 7
Chromosome 1 has at gene position 1 the value 4
Chromosome 1 has at gene position 2 the value 9
Chromosome 2 has at gene position 0 the value 7
Chromosome 2 has at gene position 1 the value 4
Chromosome 2 has at gene position 2 the value 9

As you can see, the chromosomes all have the same values. How can I make it so the chromosomes have unique values?




Random Array from an array - Java

I have an array : {red, blue, green} . I want to generate other array having random contain ex: {red,red,blue,green,blue} . I want to use a variable length of the random array.




how to make generate random numbers that don't repeat

var randomArray = [];

function random(x) {
    var emptyRandom = null;
    temp = Math.floor(Math.random() * x);
     emptyRandom = temp;
     return emptyRandom;

}

for (var i = 10; i > 0 ; i--) {
    randomArray.push(random(10));
}
console.log(randomArray);
<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8">
        <title>practice</title>

    </head>
    <body>


    <script src="script.js" charset="utf-8"></script>
    </body>
</html>

i want to shuffle the randomArray to make sure numbers don't repeat, All the answers that people post are very hard to understand for a beginner so if you can please explain how you do it that would help me a lot!




Create a random group in JS and PHP

For a project i have to do a matchmaking to create groups of people using only JS or PHP. I have a list of people in my database and have to randomly create a group of 4 people.

can someone help me or give me way to think about it ?




Static variables that are auto-generated and must be passed in constructor for object instantation

Hi i'm new in Java and i have an assignment where for days i couldn't figure out how to have a unique for each object attribute that is random generated.In my class reservation i want kratisid to be unique and random generated for every object but if i do that in the constructor in the main() method i need to pass a arithmetic value and not the auto generated one.Here is the code:

public class reservation{

 String onoma;
 int afixi;
 int mdiam;
 int atoma;
 Domatio domat;//domat prosorinos deiktis sto object Domatio tha balo d meta
 Domatio d;
  Random rand=new Random();//this.kratisid=kratisid; kai stin main bazo random
  //random kratisi id
  static int kratisid=rand.nextInt(500)+100;//It produces a random kratisid between 100 and 500

       String alphabet= "abcdefghijklmnopqrstuvwxyz";      
           String   onoma = "";
              Random random = new Random();
              int randomLen = 1+random.nextInt(9);
             for(int i = 0; i < randomLen; i++) {
              char c = alphabet.charAt(random.nextInt(26));
               onoma+=c;     
           //it produces a random alphabetic string for the onoma variable
        }
      //String onoma = RandomStringUtils.randomAlphabetic(10);
  public reservation(String onoma,int kratisid,int afixi,int mdiam,int atoma,Domatio d)//boolean s)
 { //info for customer of a hotel reservation,d is reference to Domatio objects an another class
      d=null;



       this.onoma=onoma;   //System.out.println("Enter your name please");
           //Scanner scanner1= new Scanner(System.in);
           //onoma=scanner1.nextLine()         



       this.afixi=afixi;
        //System.out.println("Enter your day of arrival please ,it must be from 1 to 30 max");
        //Scanner scanner2=new Scanner(System.in);
        // afixi=scanner2.nextInt();
       // if(afixi<1 && afixi>30){
         //   afixi=0;
          //  System.out.println("Please re-enter your arrival within the month boundaries");
        //}
        this.mdiam=mdiam;
        //System.out.println("Please enter the number of days you will be staying");
       // Scanner scanner3=new Scanner(System.in);
        // mdiam=scanner3.nextInt();
        this.atoma=atoma;//



    }

Now in the main method when i create an object eg r i need to pass the static kratisid as an argument but how i make the object have the static random kratisid without needing to pass it in the object creation in main? In case i didn't tell i try to make a unique random kratisid for each object and an onoma which its random too but if the user wants so he can input his own.




vendredi 28 avril 2017

Can this code be reverse-engineered to find the random seed?

local digits = {'1', '2', '3', '4', '5', '6', '8', '9'} 
math.randomseed(os.time()) 
local result = digits[math.random(8)] 
for i = 2, 50 do 
    result = result..digits[math.random(8)] 
end 
print(result)

--> 88854243421464255299891111895292628431988589634664

This is a Lua script designed to spit out fifty random digits, excluding 0 and 7. I can't seem to find the Lua randomness algorithm. Is it possible to find the value returned by os.time()?

To put it in layman's terms, here's how the script works:

  1. Define a list of eight single-character strings.
  2. Seed the pseudo-random algorithm with the number of seconds since midnight on January 1, 1970.
  3. Select a number between one and eight using the pseudo-random algorithm, then use that to select an item from the list. E.g. the number selected is seven, the algorithm picks the seventh item in the list.
  4. Add that item onto the end of the result. Repeat until the result is fifty digits long.

So because seven is left out, the random algorithm really spit this out:

77754243421464255288781111785282627431877578634664

But because seven is missing, seven and eight became eight and nine, yielding this:

88854243421464255299891111895292628431988589634664

To clarify, I'm trying to figure out how the random algorithm works to find the key that was entered as a random seed.

Also asked here: http://ift.tt/2oUD5rj and here: http://ift.tt/2oHoqDu and here: http://ift.tt/2oUSmZ3




Randomness of shuffled cards

I have an Array List of cards containing 52 cards. I want to shuffle the deck.

This is what I have done.

  1. Created a new Array List.
  2. Generated random index between 0 to deck size.
  3. get card at random index and add to new list.
  4. remove card from deck
  5. repeat untill deck is empty.

Here is my code:

String[] Number = {"A","2","3","4","5","6","7","8","9","10","J","Q","K"};
String[] Suits = {"Club","Diamonds","Hearts","Spades"};
ArrayList<Card> deck = new ArrayList<Card>();

// create a deck    

for(int i=0;i<13;i++){
        for(int j=0;j<4;j++){
            Card card = new Card(Suits[j],Number[i]);
            deck.add(card);
        }    
    }

// shuffle of deck

ArrayList<Card> new_deck = new ArrayList<Card>();
    while(deck.size()!=0){   

        Random rand = new Random();
        int  n = rand.nextInt(deck.size());

        new_deck.add(deck.get(n));
        deck.remove(n);
    }

// Display

for(int i=0;i<52;i++){
        System.out.println(new_deck.get(i).getSuit()+" : "+new_deck.get(i).getValue());
    }

Finally, I get shuffled deck from new ArrayList.

Does it's randomness is enough or not ?

What should I do to increase randomness ?

Any kind of suggestion and help is appreciated.




How can I make function like rand in php

I wanted to know: how does the rand function in php work? can we make something like this ? if someone knows please share the function here.




Generating two standard normal variables with specific correlation (MATLAB)

I want to generate two standard normal variables (mean = 0, variance = 0) with a specific correlation (e.g. .2). To do this I am using the mvnrnd() function. Documentation here

I am having trouble understanding the documentation completely, but I believe this would do the trick: mvnrnd([0,0],[1,.2;.2,1]) with [0,0] representing the mean of the two variables and [1,.2;.2,1] representing the covariance matrix (which is the same as the correlation matrix since the variance for both variables is 1) that looks like this:

1 .2

.2 1

Is that correct?




Choose index of numpy matrix with regard to vector of probabilities

Given an n x n (stochastic) Numpy array A and another Numpy array p in [0,1]^n. For each row A_i of A, I want to compute the smallest index j* such that p_i <= A_i,j*.

How can I implement this efficiently in Numpy? I guess this can somehow be done with numpy.random.choice.




How to count number-sequences

I want to do the following: I want to enter a "random" squence of 1 and 0. Then I want to analyze this squence for sequences of 1's, so that I get the length and number of those squences and that I get in the end something like: there are x chains of n 1's in the squence for all lengths n that appear. For example:

11011100011

-> there are 2 chains of n=2 ('11') and there is 1 chain of n=3 ('111').

Can I realize that with the count function? And if so, how? And if not, how else? I hope my english is good enough for you to get my question : )




C# - How to let the program choose a random number out of preselected numbers

How can i let my program choose a number between 1 - 100 everytime someone presses a button?




How to test std::bitset for randomity?

I create random bitsets with following code below. Now I wanna write some test and asking myself how to test the randomness of bitsets? Is there a good solution to this problem?

As bitsets can not be represented as numbers AFAIK, I don't know hot to apply some sort of test like chi-square or whatever.

Should I count the ocurrences of 1s and 0s like

 1001
+0101
+1110
+0010
 ----
 2222 = good as half of 4 (bitsets) equal 2

Are there other ways?

template <size_t N>
using bitset_t = std::bitset<N>;

and

template <size_t N>
struct random_bitset_t
{
  static_assert(N % 64 == 0, "random_bitset_t<N> only with N % 64 == 0");

  std::bitset<N> operator()() const;
};

template <size_t N>
std::bitset<N> random_bitset_t<N>::operator()() const
{
  static thread_local std::mt19937 g{std::random_device{}()};

  static thread_local std::uniform_int_distribution<uint64_t> d;

  std::bitset<N> bitset;

  for (int i=0,j=N/64; i<j; ++i)
  {
    bitset <<= 64;

    bitset |= std::bitset<N>(d(g));
  }
  return bitset;
}

and

template <size_t N>
using bitsets_t = std::vector<bitset_t<N>>;

and

template <size_t N>
struct random_bitsets_t
{
  random_bitsets_t(size_t);

  bitsets_t<N> operator()() const;

  size_t size;
};

template <size_t N>
random_bitsets_t<N>::random_bitsets_t(size_t size)
: size(size)
{}

template <size_t N>
bitsets_t<N> random_bitsets_t<N>::operator()() const
{
  bitsets_t<N> bitsets;

  bitsets.reserve(size);

  std::generate_n(std::back_inserter(bitsets),size,random_bitset_t<N>());

  return bitsets;
}




AWS Route53 random A-record

Currently, I'm trying to output a random DNS A-record. Unfortunately, I cannot seem to get it to work.

What I'm trying it the following: I have a list of multiple IPv4 addresses. Once a DNS lookup will be made to play.domain.com, I need to output a random A record.

And then, just one, not the entire list of records.

How do I do this?

Any help will be very appreciated!




Creating random wired topology for given arbitrary number of nodes on NS2

I want to create and simulate a wired topology using NS2. Trying to write a tcl and positioning the nodes and links using rand() . My solution was this But the randomization is often creating erroneous links and thus problem in simulation and getting this error :

--- Classfier::no-slot{} default handler (tcl/lib/ns-lib.tcl) ---
_o28: no target for slot 4294967295
_o28 type: Classifier/Hash/Dest
content dump:
classifier _o28
0 offset
0 shift
1073741823 mask
1 slots
slot 5: _o268 (Classifier/Port)
-1 default
---------- Finished standard no-slot{} default handler ----------

But this is also random and does not occur always. When it does not occur , the nam file shows that there have been duplicate definition of nodes. Can someone please just give me some guidance about how to create a random wired topology with random valid links?




Improve random sample function

I have the following function to generate a random sample from an original data set:

def randomSampling(originalData):
    a = np.random.random_integers(0, 500, size=originalData.shape)
    #Number of elements in the result. We split in a half because we want a 50% sample
    N=round(parkinsonData.shape[0]/2)
    result = np.zeros(originalData.shape)
    ia = np.arange(result.size)
    #cast to float the sum of the flat a array
    tw = float(np.sum(a.ravel()))
    result.ravel()[np.random.choice(ia, p=a.ravel()/tw,size=N, replace=False)]=1
    return result

My purpose is to achieve a subset of original data that have the 50% of the size of the original set. This way I can execute this function two times, one to achieve training subset and another test subset.

My problem is that in the original data I have a field called status that have values 0 or 1. And I want to keep the proportionallity between both set of classes in the subsets of training and test.

How can I do this with python? Also I am not sure that the function is achieving to create the samples with the half of the registers of the original set. Theorically, this should ensure that the size is 50%: N=round(parkinsonData.shape[0]/2)




Java homework: Print Arrays with stored random numbers in it

I need some help for a class assignment. I dont want to be given the solution but rather to understand how i can solve this because i really dont get it even if it's simple.

I need to write a program that will have an Array with 10 elements(all of them integers). A random generated number will be set to each element and each number will be from 0-20. Next, i must print the position of the element of the array , the random number and as many asterisks as the value of the array.

It will look like this:

Array Value Asterisks
0     5     *****
1     15    ***************

I can generate the numbers and set store them to the Array but i cant print them according to the description. Could you please tell me what am i doing wrong?.

public class ForTest{
    public static void main(String[] args) {
        //Method 1
        int[] myNumbers = {0,1,2,3,4,5,6,7,8,9};
        //Method 2
        int[] randomNumbers = new int[10];
        String asterisk = "";

        for( int index=0; index < randomNumbers.length; index++)
        {
            randomNumbers[index] = 1 + (int) ( Math.random() *20);
        } // end for

        for ( int index=0; index < randomNumbers.length; index++)
        {
            switch (randomNumbers[index]) {
                case 1:
                asterisk = "*";
                System.out.println(myNumbers[0] + "\t-->\t" + randomNumbers + asterisk);
                break;
                case 2:
                asterisk = "**";
                System.out.println(myNumbers[1] + "\t-->\t" + randomNumbers + asterisk);
                break;
                case 3:
                asterisk = "**";
                System.out.println(myNumbers[2] + "\t-->\t" + randomNumbers + asterisk);
                break;
                case 4:
                asterisk = "**";
                System.out.println(myNumbers[3] + "\t-->\t" + randomNumbers + asterisk);
                break;
            }
        }
    }
}




Random number with range [duplicate]

This question already has an answer here:

Which one is correct for the range 2 - 5 and why?

1.) Math.random()*2) + 3

2.) Math.random()*3) + 3

Can anybody explain this to me?




Php : generate at least one digit and one letter

How can I generate at least one digit and one letter with let's say 5 strings characters?

I know I can randomly generate digits and letters with this :

echo $rand = substr(md5(microtime()),rand(0,26),5);

However, I've just checked it, and it can appear it only gives me simply 5 letters or 5 digits, and I'd like the rand to be always mixed with at least 1 digit and 1 letter.




jeudi 27 avril 2017

getting .\Math.java:4: error: -> expected int y=(); in Head First PhraseOMatic Program

I am new to java and am working out of a Head First book. I have installed the latest version of jdk and setup the path to the bin. Everything has been working fine up until this PhraseOMatic mess.

I keep getting numerous errors when trying to compile this program file.

Here is the code

public class PhraseOMatic1
{
public static void main(String args[])
{
String[] wordListOne={"24/7","multi-tier","30,000foot","B-to-B","winwin","frontend","web-based","pervasive","smart","six-sigma","critical-path","dynamic"};

String[] wordListTwo={"empowered","sticky","value-added","oriented","centric","distributed","clustered","branded","outside-the-box","positioned","networked","focused","leveraged","aligned","targeted","shared","cooperative","accelerated"};

String[] wordListThree={"process","tipping-point","solution","archtecture","corecomputing","strategy","mindshare","portal","space","vision","paradigm","mission"};

int oneLength=wordListOne.length;
int twoLength=wordListTwo.length;
int threeLength=wordListThree.length;
int rand1=(int)(Math.random()*oneLength);
int rand2=(int)(Math.random()*twoLength);
int rand3=(int)(Math.random()*threeLength);

String phrase=wordListOne[rand1]+" "+wordListTwo[rand2]+"   "+wordListThree[rand3];

System.out.println("What we need is a "+phrase);

}
}

Here is what is returned after trying to compile it.

C:\Users\Admin>javac PhraseOMatic1.java
.\Math.java:4: error: -> expected int y=();
    ^
.\Math.java:4: error: ';' expectedint y=();
     ^
.\Math.java:5: error: illegal start of expressionSystem.out.print(x+3==);
  ^
.\Math.java:5: error: ';' expected System.out.print(x+3==);
      ^
.\Math.java:5: error: illegal start of expressionSystem.out.print(x+3==);
                  ^
PhraseOMatic.java:18: error: cannot find symbolint rand1 =(int)Math.random()*oneLength);method random()  location: class Math
PhraseOMatic.java:19: error: cannot find symbolint rand2 =                                                           (int)(Math.random()*twoLength);symbol:   method random() location: class Math
PhraseOMatic.java:20: error: cannot find symbol int rand3 =(int)Math.random()*threeLength);  symbol:   method random()location: class Math
.\Math.java:4: error: incompatible types: int is not a functional interfaceint y=();
  ^
9 errors

If I run the same code in the online Java IDE it works fine.




Random sampling of 30 rows for each column

I have a very simple MySQL table as below:

CREATE TABLE tdata (
    id varchar(256),
    color varchar(256)
);

This table has data like

bill,orange
bill,orange
bill,umber
(...)
bill,yellow
jerry,blue
jerry,purple
(...)
jerry,blue

I'm looking to select a unique random sample of 20 colors for each id, such that the output would look like:

bill,orange
bill,umber
(...)
bill,chartreuse
jerry,blue
(and so on)

The full table is almost 100k rows, so I can't specify each ID in the query. Is there an elegant MySQL query to do this?




Formatting scanners and random generators

Random deck = new Random();
int cardtype = deck.next(52)+1;

I have an "error: next(int) has protected access in Random" on the period in the second line, I've used code with random generators before but haven't ran into this problem yet, any suggestions? Scanner scanner = new Scanner(System.in); placeholder = scanner.nextInt; the same type of situations is going on in this piece too, but with a scanner. I believe the problem is similar for both, I think this would be a quick fix if I knew how to do it right, suggestions?




Magic 8 ball program loop?

I have created a simple magic 8 ball program. But the issue is every single time I compile my program and run the loop the loop keeps on repeating the same random answer. The issue is not about the loop going on forever its when I compile it and run it, the program gives a random answer but keeps on repeating the same answer till i recompile the file.

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

public class Moreloopex4 {

    public Moreloopex4() {
        // TODO Auto-generated constructor stub
    }

    public static void main(String[] args) {
        // Declaring Random
        Random rand = new Random();

        // Declaring scanner
        Scanner scan = new Scanner(System. in );

        // Declaring variables
        String input;
        int randnum;

        // Declaring randomizer
        randnum = rand.nextInt(6) + 0;

        // Conditional Statements
        while (true) {
            System.out.println("Enter your statement");
            input = scan.nextLine();
            if (randnum == 0) {
                System.out.println("Without a doubt ");
            }
            else if (randnum == 1) {
                System.out.println("I cannot predict now");
            }
            else if (randnum == 2) {
                System.out.println("My sources say no");
            }
            else if (randnum == 3) {
                System.out.println("Signs point to yes");
            }
            else if (randnum == 4) {
                System.out.println("Don't count on it");
            }
            else if (randnum == 5) {
                System.out.println("Better not tell you now");
            }
            else if (randnum == 6) {
                System.out.println("Yes, definetly");
            }
        }
    }
}




Non repeating random numbers in C++

I need to create an array that has a shorter length than the numbers' range that I have to choose among. In the example I have an array made by 10 int and the range is between 20 and 50. That means that most of the asnwers (found on various websites) to this question ("use the shuffle algoritm") couldn't work.

#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <time.h>

using namespace std;

int main() {

const int N = 10;
int arr[N];

srand(time(0));

// Just creates the array, but with repetitions
// for (int i=0; i<N; i++) {
//     arr[i] = (rand()%31)+20;
//     }

for (int i = 0; i <= N; ++i) {
    bool valid = true;
    do {
        arr[i] = ((rand()%31)+20);
        for (int j = 0; j < i; ++j) {
            if (arr[i] == arr[j])
                valid = false;
            else
                valid = true;
        }
    } while(!valid);
}

With the "else" I check the previous value and, if it's the same, it's changed. But if the same numbers are more far than just the previous one, this algoritm doesn't change the last one because the "else" of a previous right number ends the while. If I remove the else, I remain stuck in the cicle, changing every time the number.




Replacing words with dictionary python

I am trying to replace the words in the lyrics file with the ones in the dictionary. However, when i try to execute this, I get a bunch of errors that I don't quite understand. I am trying to first split the words in the text file into a variable and iterate through that so if there is a matching word in the dictionary, it will replace it. If I delete the lyrics sections and just try it with a user input, it works just fine. I also want to keep the format the way it is originally. If anyone has an idea on how to fix this, that would be great. Thanks

import random

file = open("python_asg10_Roget_Thesaurus.txt", "r")
data = file.read()

data_split = data.split("\n")

thesaurus = {}


for line in data_split:
    words = line.split(',')
    thesaurus[words[0]] = words[1:]

lyric_file = open("paris.txt", "r")
lyric_data = lyric_file.read()
lyric_split = lyric_data.split("\n")

lyric = ""

for i in lyric_split:
    word = i.split(' ')
    lyric += str(word)

new_phrase = ""

for char in lyric:
    if char.isalnum() or char.isspace():
        new_phrase += char

phrase_list = new_phrase.split(' ')

final_phrase = ""

for word in phrase_list:
    low = word.lower()
    if low in thesaurus:
        rand_choice = random.choice(thesaurus[low])
        final_phrase += rand_choice.upper() + " "
    else:
        final_phrase += word + " "

print(new_phrase)




Getting wrong sum of random number

I am on dice game in which i need to roll the dice 5 times and sum the random number. Everything is working fine but my sum is not according to the random number which i am getting

for (int i = 1; i <= 5; i++)
{
    printf(" %d time dice rolled = %d \n",i, rand() % s + 1);
    x += rand() % s + 1;

}
printf("--------------------------------------Sum is %d", x);

getch();

}

s is the sides of the dice




Random function in python 3 printing object location to console when program closes

I'm trying to use the random function to make a version of Yahtzee and am having an issue with the following object location being printed to console every time the program exits:

Press any key to roll your dice or quit to leave: quit <__main__.new_game object at 0x105601940>

This location changes every time the program is run so I am assuming it has something to do with the seed that random.randint() is using but I can't be sure. I'm using import random to access the random function and to add to the list holding the dice roll I'm using dice_roll.append(random.randint(1,6)). While it's not a huge issue it is rather annoying... any tips?




numpy.random.choice vs random.choice

Why does numpy.random.choice not work the same as random.choice? When I do this :

 >>> random.choice([(1,2),(4,3)])
 (1, 2)

It works.

But when I do this:

 >>> np.random.choice([(1,2), (3,4)])
 Traceback (most recent call last):
 File "<stdin>", line 1, in <module>
 File "mtrand.pyx", line 1393, in mtrand.RandomState.choice 
 (numpy/random/mtrand/mtrand.c:15450)
 ValueError: a must be 1-dimensional

How do I achieve the same behavior as random.choice() in numpy.random.choice()?




copying a file from assets folder to /sdcard and randomize lines in it

I have a text file to load from assets folder of an android app to "/sdcard/appname/" but i want the lines to be randomize and save while copied to sdcard, here is the code that i write to copy but i struck at the part of how to randomize

    data_path="/sdcard/<appname>/"
    AssetManager assetManager = getAssets();
            InputStream in = assetManager.open("file.txt");
            OutputStream out = new FileOutputStream(data_path + "file.txt");

            // Transfer bytes from in to out
            byte[] buf = new byte[1024];
            int len;
            //while ((lenf = gin.read(buff)) > 0) {
            while ((len = in.read(buf)) > 0) {
                out.write(buf, 0, len);
            }
            in.close();
            //gin.close();
            out.close();

How can i randomize the lines while copying (i'm not a java guy started working on it recently so this is kind of a noob question)




Unable to get gamma_inv property of the worksheetfunction class error

Iam totally new to the VBA, so I would appreciate your help...

My code so far, first part, where I have made random numbers to the specific range:

Dim i As Long
Randomize
     For i = 1 To 20000
         Range("A" & i) = Rnd()
     Next i
      Range("A1") = ("Rand")
      ActiveCell.Range("A1:A20000").Select
    Sheets("Sheet1").Columns("A").Copy
    Sheets("Sheet1").Columns("B").PasteSpecial xlPasteValues
     Sheets("Sheet1").Columns("A").Delete
    Range("A1") = ("Rand")
      MsgBox ("Nagenerovaných 20 000 hodnôt")

Dim alfa As Integer
  Dim beta As Integer
  Dim a As Long
  Range("I2").Value = InputBox("zadaj parameter alfa")
  Range("J2").Value = InputBox("zadaj parameter beta")
  Range("B2").Select

 Range("I2").Value = alfa
 Range("J2").Value = beta
 For a = 1 To 20000
 Range("B" & a) = WorksheetFunction.Gamma_Inv(Rnd(), alfa, beta)
 Next a

The first part of the code works fine, but it takes a while to make these random numbers(something about 8 secs. on my laptop), but its annoying. Is there another way how to do it?

The second part does not work. What Iam trying to do is that, instead of Rnd() in gamma function, i want to use the random number I have already generated in previous step, but I dont know how to do that. I Have tried the second part of the code with the rand(), because I wanted to know, if its gonna work, like the code itself, so I could modify it.

Iam stacked here for 2 days, glad for any help.

PS: its a school project, the each part of the code is started by pressing a click button, if you are wondering why I have separated it to the 2 parts.

Thanks




C - How to generate random numbers between 20 and 30? [duplicate]

I've tried but it doesn't seem to give me the desired numbers. Here's my code so far:

#include <stdio.h>
#include <stdlib.h>

int main()
{
   int n, i;
   printf("Value of n:\n");
   scanf("%d", &n);
   int t[n];
   for(i=0; i<n; i++)
    printf("%d ", rand()%20+30);

return 0;
}




"Mapping" a uint64_t to a uint32_t

I have a RNG function xorshift128plus that takes a Xorshift128PlusKey:

/** 
        * \brief Keys for scalar xorshift128. Must be non-zero.
        * These are modified by xorshift128plus.
        */
        struct Xorshift128PlusKey
        {
            uint64_t s1;
            uint64_t s2;
        };

        /** 
        * \brief Return a new 64-bit random number.
        */
        uint64_t xorshift128plus(Xorshift128PlusKey* key);

I would like to seed my RNG using rdtsc (processor time stamp). The problem is that the __rdtsc intrinsic under msvc returns a 64 bit unsigned integer and the seed must be a 32 bit unsigned integer. What is the best way to convert the rdtsc to a seed while preserving randomness. The conversion must be as fast as possible.

I can't use the std lib or boost. (It's for a game engine)




CUDA Array shuffling?

I'm working on a cuda Kernel that could shuffle an array of size N (N is supposed to be very large, that's why I can't do a shuffle on CPU and then copy the array back to the GPU memory). I'm aware on how to generate random numbers in CUDA but I have no idea on how to randomly shuffle an array of int... Maybe someone has already tried something like this ?

Thanks a lot !




Angular 2: Generate random int throws error

I have a list where I am using a random number to choose an avatar and its throwing the following error:

HelloIonicPage.html:33 ERROR Error: ExpressionChangedAfterItHasBeenCheckedError: Expression has changed after it was checked.

View:

  <ion-list>
    <ion-item *ngFor="let client of clients; let i = index; let r = getRa" >
      <ion-avatar item-left>
        <img [src]="getRandomInt(0, 9)">
      </ion-avatar>
    </ion-item>
  </ion-list>

.ts

getRandomInt(min, max) {
    let num =  Math.floor(Math.random() * (max - min + 1)) + min;
    return "http://ift.tt/2p7J4LM" + num + ".jpg"
}




best way to get a true random number in python

what would be the best way to get a true random number (not pseudo random) in python?




How would I be able to add a score counter to a math quiz that includes functions? Any help is appreciated

Below I have created a Maths quiz in python. It consists of random equations to solve. The questions are generated using random numbers and functions that determine whether the question is add or subtract. I have completed the quiz, but I have tried adding a score counter so that if the user gets a question right, a point is added on. I am unsure how to do this, as I have tried implementing the score into the functions and it does not work. any help would be appreciated. Here is the code:

import random
#Asks for name
name = input("What's your name?")
#Stops user from entering invalid input when entering their class
classchoices = ["A","B","C"]
classname = input("What class are you in?")
while classname not in classchoices:
    classname = input("Not a valid class, try again:")

print(name, ",", classname)
print("Begin quiz!")

questions = 0
a = random.randint(1,12)
b = random.randint(1,12)


def add(a,b):
    addQ =  int(input(str(a) + "+" + str(b) + "="))
    result = int(int(a) + int(b))
    if addQ != result:
        print ("Incorrect! The answer is", result)

    else:
        print("Correct")





def multiply(a,b):
    score = 0
    multQ =  int(input(str(a) + "X" + str(b) + "="))
    results = int(int(a) * int(b))
    if multQ != results:
        print ("Incorrect! The answer is", results)

    else:
        print("Correct")



def subtract(a,b):
    subQ =  int(input(str(a) + "-" + str(b) + "="))
    resultss = int(int(a) - int(b))
    if subQ != resultss:
        print ("Incorrect! The answer is", resultss)
    else:
        print("Correct")

for questions in range(10):
    Qlist = [add, subtract, multiply]
    random.choice(Qlist)(random.randint(1,12), random.randint(1,12))
    questions += 1



if questions == 10:
    print ("End of quiz")




VB.net Random number generator is repeating the same value

I am trying to create an array of random values so that I can bubble sort them. The problem is, the random number generator is not working and repeats the same number over and over. I've used this method of random number generating before and its worked just fine. If I put a breakpoint into the code in the CreateArray() loop, then it works just fine, but I have to step through the code manually. I can't understand how it works with a breakpoint, but doesn't work without one.

Sub Main()
    Dim Value_Array As New List(Of Integer)
    Dim No_Of_Items As Integer = 10
    Dim Pass_No As Integer = 1
    Dim Temp As Integer
    Value_Array = CreateArray(No_Of_Items)
    For Pass_No = 1 To (No_Of_Items - 1)
        For j = 0 To (No_Of_Items - (Pass_No + 1))
            If Value_Array(j) > Value_Array(j + 1) Then
                Temp = Value_Array(j)
                Value_Array(j) = Value_Array(j + 1)
                Value_Array(j + 1) = Temp
            End If
        Next
    Next
    For i = 0 To (No_Of_Items - 1)
        Console.Write(Value_Array(i) & ", ")
    Next
    Console.ReadKey()
End Sub
Function GenerateRandomNumber()
    Dim Random_Number As Random = New Random()
    Dim Random As Integer = Random_Number.Next(0, 101)
    Return Random
End Function
Function CreateArray(No_Of_Items)
    Dim Count As Integer = 0
    Dim Temp_Array As New List(Of Integer)
    Do Until Count = No_Of_Items
        Temp_Array.Add(GenerateRandomNumber())
        Count = Count + 1
    Loop
    Return Temp_Array
End Function




mercredi 26 avril 2017

How do I print a single RANDOM item from multiple lists? and having those items print on the same line?

my original code: simplified: (new to stackflow, so my apologies if this is the wrong way to do this)

import random

count = 0
while count < 50:
    One = ['a', 'b', 'c', 'd', 'e']
    print(random.choice(One))

    Two =['a','b']
    print(random.choice(Two))

    Three =['a','b','c','d','e','f','g','h']
    print(random.choice(Three))

    Four =['a','b']
    print(random.choice(Four))
    count = count +1

The output of my code prints each item on its own line.. if I were to run the code once(without the WHILE COUNT LOOP), the OUTPUT would read:

example:(random everytime I run the code, perfect)

c

b

h

a

multiple times: (random order, which is perfect for what i want)

d

a

f

b

__

c

b

h

a

etc...

problem: what I would like the code to do is, to take a single random item from each of the lists[one,two,three,four]... and print those random items on its own line with spacing..all while using the WHILE COUNT LOOP (to generate n number of tests)

so an example of what i want it to do would look like:

c a g b

b b f a

d a e b

assuming my lists had the correct names and associated values, would read

output:

the dog rolled over

a bird ate seeds

the cat rolled seeds

the car sat down

a snake bit me

the spider ran up

etc.etc.

(some of those dont make sense, but thats the "random" idea im working at




randint() only generating high values and not drawing enough objects

For this project, I need to draw 400 different squares at random spots, and are all at least 5 pixels away from eachother. Currently, boxes are mostly drawn on the bottom of the window, and only about half are drawn before the program freezes. I've consulted my professors, and they are stumped.

#Importing things I need
 import random
 from graphics import *

 def enterValue(used_spots, y_spots, corner1, corner2):
     #enters the value where our square starts into the array, if it's a 
 valid value.
     used_spots.append(corner1)
     y_spots.append(corner2)

 def checkPlace(used_spots,y_spots,corner1,corner2):
     #checks the placement of every square to see if our new one is valid.
     # the total size of a square is 20px edge + 5 px Border + 3 px width.  
     # So we need to check based on that number.
     slot=0
     check=0
     for slot in range(0,len(used_spots)):
         #if the distance between the squares is more than 28 pixels, return 
         # true. Else, stop checking and return false
         if abs(corner1-used_spots[slot])<28 and abs(corner2-y_spots[slot]<28):
             check=0
             break
         else:
             check=1
     return check

 def randomCorners():
     #gets us a random variable for x and y of a box's corner
     corner1=random.randint(3,1800-28)
     corner2=random.randint(3,900-28)
     return corner1, corner2

 def drawBox(corner1,corner2,EDGE,WIDTH,colors,win):
     #Draws the box
     point1=Point(corner1,corner2)
     point2=Point(corner1+EDGE,corner2+EDGE)
     square=Rectangle(point1,point2)
     square.setWidth(WIDTH)
     square.setFill(random.choice(colors))
     square.draw(win)

 def main():
     #delcaring variables
     corner1=0
     corner2=0
     used_spots=[]
     y_spots=[]
     WIDTH=3
     EDGE=20
     colors=["red","orange","yellow","blue","pink","green"]
     win=GraphWin("MAINWINDOW",1800,900)
     win.setBackground("white")

     #Draws a random box at a random spot, then makes a spot for a new potential box and tests it
     corner1,corner2=randomCorners()
     drawBox(corner1,corner2,EDGE,WIDTH,colors,win)
     enterValue(used_spots,y_spots,corner1,corner2)
     corner1,corner2=randomCorners()

     while len(used_spots) < 400:
         #If we can draw a box there, draw it and add coords to the lists, 
         #then generates a new set of coordinates.
         if checkPlace(used_spots,y_spots,corner1,corner2)==1:
             drawBox(corner1,corner2,EDGE,WIDTH,colors,win)
             enterValue(used_spots,y_spots,corner1,corner2)

          #otherwise, make a new coordinate and try again.
         corner1,corner2=randomCorners()


 main()




Random number generator loop isnt working [duplicate]

This question already has an answer here:

Theres probably something wrong with the flow of logic in this code, though i thought i would post it here to see if its something simple i am missing. (It probably is, as i am currently quite new to c#).

This script is supposed to generate X amount of random numbers between a High value and a Low value, as well as ensuring it does not generate the same random number twice.

Right now, the script is not having any errors, but is only creating one random number, regardless of the defined 'amount' of numbers to create.

I tried changing "int numberof = 11; to a public int, but apparently that breaks the entire program and i dont know why.

Anyway, support is appreciated. Thanks :)

Code:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Randomnumbers
{
    class Program
    {
        static void Main(string[] args)
        {
            int numberof = 11;
            Console.WriteLine("Numbers Generated:");
            while (numberof > 0) //Repeats this loop once for each "numberof". (until the number hits zero)
            {
                numberof = numberof - 1;
                generatenewnumber(); //Calls the function
            }
            if (numberof == 0)
            {
                Console.ReadLine(); // Here so the program doesnt instantly close
            }
        }

        static void generatenewnumber()
        {
            var rng = new Random();
            int lowrange = 0;
            int highrange = 50;
            int numberof = 11;
            int number = rng.Next(lowrange, highrange); //Sets the number to a random number between the high and low values.
            var generated = new List<int>(); // Creates a list of numbers that have been generated already to prevent double-ups.
            while (numberof > 0)
            {
                if (generated.Contains(number)) // Checks if the rg'd number has already been made.
                {
                    generatenewnumber(); //Calls the function above
                }
                else
                {
                    numberof = numberof - 1;
                    generated.Add(number); // Adds the genereated number to the list.
                    Console.WriteLine(number); // Prints the number. 
                    Console.ReadLine();
                }
            }
        }
    }
}




Combining two samples out of numpy.random does not end up in a random sequence

I implemented the Wald-Wolfowitz runs test in python but during testing I encountered weird behaviour, the steps I take are the following:

  1. I take two samples out of the same distribution:
    import numpy as np
    list_dist_A = np.random.chisquare(2, 1000)
    list_dist_B = np.random.chisquare(2, 1000)

  1. Concatenating the two lists and sorting them, while remembering which number came from which sample. The following function does that and it returns a list of labels ["A","B","A","A", ... "B"]
    def _get_runs_list(list1, list2):
      # Add labels  
      l1 = list(map(lambda x: (x, "A"), list1))
      l2 = list(map(lambda x: (x, "B"), list2))
      # Concatenate
      lst = l1 + l2
      # Sort
      sorted_list = sorted(lst, key=lambda x: x[0])
      # Return only the labels:
      return [l[1] for l in sorted_list]

  1. Now I want to calculate the number of runs (a consecutive sequence of identical labels). e.g.:

    • a,b,a,b has 4 runs
    • a,a,a,b,b has 2 runs
    • a,b,b,b,a,a has 3 runs

    For this I use the following code:

    def _calculate_nruns(labels):
        nruns = 0
        last_seen = None

        for label in labels:
            if label != last_seen:
                nruns += 1
            last_seen = label

        return nruns

Since all elements are randomly drawn I thought that I should roughly end up with a sequence a,b,a,b,a,b... So this would mean that the number of runs is roughly 2000. However as can be seen on repl.it this is not the case, it is always roughly around 1000. Can anyone explain why this is the case?




Random Names Generator

This program needs to randomly create first and middle names for boys and girls (5 for each in a list box) each time the boys button or girls button is pressed. Right now the program is riddled with syntax errors, mostly for there not being arguments given to meet the parameters in the methods. These exact parameters are required for the assignment, I've tried putting arguments for them in places that don't end up changing anything. Also, how can I assign a random to the index of the arrays used in this?

public partial class Form1 : Form
{
    private string[] boys = new string[20];
    private string[] girls = new string[20];

    public Form1()
    {
        InitializeComponent();
    }

    private void boysButton_Click(object sender, EventArgs e)
    {
        for (int i = 0; i <= 5; ++i)
        {
            RandomName();
            namesBox.Items.Add(NewName);
        }

    }
    private void girlsButton_Click(object sender, EventArgs e)
    {
        for (int i = 0; i <= 5; ++i)
        {
            RandomName();
            namesBox.Items.Add(NewName);
        }
    }


    private string ChooseBoys(string[] options)
    {
        Random rand = new Random();


        boys[0] = "Chuck";
        boys[1] = "Stewart";
        boys[2] = "David";
        boys[3] = "Robert";
        boys[4] = "Steven";
        boys[5] = "Patrick";
        boys[6] = "Greg";
        boys[7] = "Austin";
        boys[8] = "Thomas";
        boys[9] = "Dylan";
        boys[10] = "Christopher";
        boys[11] = "Sean";
        boys[12] = "Alexander";
        boys[13] = "Tony";
        boys[14] = "Topher";
        boys[15] = "Lyle";
        boys[16] = "Kyle";
        boys[17] = "Stonewall";
        boys[18] = "Jackson";
        boys[19] = "George";

        for (int i = 0; i < boys.Length; ++i)
        {
            int itemNum = rand.Next(boys.Length);
            return boys[itemNum];

        }

    }

        private string ChooseGirls(string[] options)
    {
        Random rand = new Random();

        girls[0] = "Susan";
        girls[1] = "Katy";
        girls[2] = "Chloe";
        girls[3] = "Darlene";
        girls[4] = "Grace";
        girls[5] = "Brianna";
        girls[6] = "Maddie";
        girls[7] = "Hayden";
        girls[8] = "Jaclyn";
        girls[9] = "Scarlette";
        girls[10] = "Selena";
        girls[11] = "Emilia";
        girls[12] = "Desiree";
        girls[13] = "Carol";
        girls[14] = "Melissa";
        girls[15] = "Peyton";
        girls[16] = "Mary";
        girls[17] = "Lori";
        girls[18] = "Wendy";
        girls[19] = "Claire";

        string rg = girls[rand.Next(girls.Length)];

    }

    private string RandomName(string[] names)
    {

        for (int i = 0; i <=2; ++i)
        {
             ChooseBoys();               
        }

        string NewName = names.ToString() + " " +  names.ToString();



        return NewName;

    }


}

}




Inserting multiple random chars into database table JAVA

I need to insert multiple chars into a database table, the code below inserts one random char(in two different ways) in every table row. But i need like 10 different chars in every row. How can i do that?

public static void insertToTable2(Connection c, String tableName, int numberOfRows) throws UnsupportedEncodingException, SQLException {
            Random rand = new Random();
            String chars = "abcdf";
            StringBuilder sql =
                    new StringBuilder("INSERT INTO " + tableName + " (NR,PIRMAS1,ANTRAS1,TRECIAS1,KETVIRTAS1,PENKTAS1,SESTAS1,SEPTINTAS1,ASTUNTAS1,DEVINTAS1) VALUES ");

            for (int j=0; j < numberOfRows; j++)
            {
                if (j != 0) sql.append (",");
                sql.append ("(" + j +
                        ",'" + chars.charAt(rand.nextInt(chars.length())) + "'" +
                        ",'" + chars.charAt(rand.nextInt(chars.length())) + "'" +
                        ",'" + (char)(rand.nextInt(25)+65) + "'" +
                        ",'" + (char)(rand.nextInt()) + "'" +
                        ",'" + (char)(rand.nextInt()) + "'" +
                        ",'" + (char)(rand.nextInt()) + "'" +
                        ",'" + (char)(rand.nextInt()) + "'" +
                        ",'" + (char)(rand.nextInt()) + "'" +
                        ",'" + (char)(rand.nextInt()) + "'" +
                        ")") ;


            }




Insert in a list random of 0 and 1 with a certain number of 1's

I want to generate a list of length N with random 0 and 1 values , but with a certain number of 1's put randomly in the list.

For example, I want a list of 10 elements(0 and 1) and the numbers of 1's in the list to be 7.

How can I do this?




Pygame sprite group using random.rand

I am working with a sprite group which contains 60 sprite objects. each object represents a asteroid image and all images displayed after each other in the right order creates an animation of a rotating asteroid, in other words i am iterating through the sprite group as seen in code below.

Evcerything works fine until the objects passes the screen height and resets at the top again and the objects then starts appearing at random locations in the x direction. The screen now seem to blit each sprite at random locations and the asteroid now just flickers back and forth horizontally.

Is there a way to get the same new random x location for all the sprites after asteroid obj passes the screen instead of giving each sprite in the group a new x value?

Any suggestions?

import pygame
import sys
import os
import random
import time
import math

black = (0, 0, 0)
white = (255, 255, 255)
red = (200, 40, 60)
green = (50, 180, 50)
blue = (50, 30, 200)
skyblue = (135, 206, 250)
silver = (192, 192, 192)
darkgray = (47, 79, 79)
vegasgold = (197, 179, 88)
nightblue = (25, 25, 112)
steelblue = (70, 130, 180)
deepblue = (0, 26, 51)

screen_width = 1920
screen_height = 1080
half_width = screen_width/2
half_height = screen_height/2

screen = pygame.display.set_mode([screen_width, screen_height])
Title = pygame.display.set_caption('Space Mash')
clock = pygame.time.Clock()

class Spaceship(pygame.sprite.Sprite):

    def __init__(self, width=30, height=30, color=white):
        super(Spaceship, self).__init__()

        self.image = pygame.Surface([width, height])
        self.image.fill(color)
        self.rect = self.image.get_rect()
        self.rect.x = 0
        self.rect.y = 0

    def center_set_position(self, x, y):
        self.rect.x = x - self.rect.center[0]
        self.rect.y = y - self.rect.width

    def rotate_ship(self, dg):
        self.image = pygame.transform.rotate(self.image, dg)

    def set_image(self, filename):
        self.image = pygame.image.load(filename)
        self.rect = self.image.get_rect()

    def draw_ship(self):
        screen.blit(self.image, [self.rect.x, self.rect.y])


player_spaceship = Spaceship()
player_spaceship.set_image("main_ship.png")
player_spaceship.center_set_position(half_width, screen_height)
all_sprites_list = pygame.sprite.Group()
all_sprites_list.add(player_spaceship)


class Asteroids(pygame.sprite.Sprite):
    def __init__(self, nr):
        super(Asteroids, self).__init__()

        self.image = pygame.image.load('Asteroid_{0}.png'.format(nr))
        self.rect = self.image.get_rect()
        self.rect.x = 0
        self.rect.y = 0

    def update(self):
        self.rect.y += 5

        if self.rect.y > screen_height + 50:
            self.rect.y = -50
            self.rect.x = random.randrange(0, (screen_width - (self.rect.width))


asteroids_list = pygame.sprite.LayeredUpdates() 

for i in range(1, 61):
    asteroid = Asteroids(nr=i)

    asteroids_list.add(asteroid)
    all_sprites_list.add(asteroid)



class Stars(pygame.sprite.Sprite):
    def __init__(self):
        super(Stars, self).__init__()

        self.image = pygame.Surface([1, 1])
        self.image.fill(white)
        self.rect = self.image.get_rect()

stars_group = pygame.sprite.Group()


def making_star_objects():

    for i in range(100):
        x_loc = random.randint(0, screen_width - 1)
        y_loc = random.randint(0, screen_height - 1)
        star = Stars()
        star.rect.x = x_loc
        star.rect.y = y_loc

        stars_group.add(star)


def gameloop():
    ending = False
    x_change = 0
    y_change = 0
    making_star_objects()
    frame = 0

    while not ending:

        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                pygame.quit()
                quit()

            if event.type == pygame.KEYDOWN:
                if event.key == pygame.K_RIGHT:
                    x_change = 10
                elif event.key == pygame.K_LEFT:
                    x_change = -10
                elif event.key == pygame.K_UP:
                    y_change = -8
                elif event.key == pygame.K_DOWN:
                    y_change = 8
            if event.type == pygame.KEYUP:
                if event.key == pygame.K_RIGHT:
                    x_change = 0
                elif event.key == pygame.K_LEFT:
                    x_change = 0


        player_spaceship.rect.x += x_change
        player_spaceship.rect.y += y_change
        if frame > 59:
            frame = 0

        asteroids_list.update()


        asteroids_hit_list = pygame.sprite.spritecollide(player_spaceship, asteroids_list, False)

        screen.fill(deepblue)
        stars_group.draw(screen)
        screen.blit(asteroids_list.get_sprite(frame).image, (asteroids_list.get_sprite(frame).rect.x,
                                                        asteroids_list.get_sprite(frame).rect.y))



        frame += 1

        player_spaceship.draw_ship()
        pygame.display.update()
        clock.tick(30)

    pygame.quit()
    quit()

gameloop()




Java inserting random letters into database table [duplicate]

This question already has an answer here:

I have a code that generates random numbers and inserts them into a database, but i want to generate random letters as well. Is there a way to so with some minor changes to the code below or do i need to change it completely?

public static void insertToTable(Connection c, String tableName, int numberOfRows) throws UnsupportedEncodingException, SQLException {
        Random rand = new Random();
        StringBuilder sql =
                new StringBuilder("INSERT INTO " + tableName + " (NR,PIRMAS,ANTRAS,TRECIAS,KETVIRTAS,PENKTAS,SESTAS,SEPTINTAS,ASTUNTAS,DEVINTAS) VALUES ");

        for (int j = 0; j < numberOfRows; j++) {
            if (j != 0) sql.append(",");
            sql.append("(" + j +
                    ",'" + String.valueOf(rand.nextInt()) + "'" +
                    ",'" + String.valueOf(rand.nextInt()) + "'" +
                    ",'" + String.valueOf(rand.nextInt()) + "'" +
                    ",'" + String.valueOf(rand.nextInt()) + "'" +
                    ",'" + String.valueOf(rand.nextInt()) + "'" +
                    ",'" + String.valueOf(rand.nextInt()) + "'" +
                    ",'" + String.valueOf(rand.nextInt()) + "'" +
                    ",'" + String.valueOf(rand.nextInt()) + "'" +
                    ",'" + String.valueOf(rand.nextInt()) + "'" +
                    ")");


        } 




comprehensive way to check for functions that use the random number generator in an R script?

is there a smart way to identify all functions that use .Random.seed (the random number generator state within R) at any point in an R script?

use case: we have a dataset that changes constantly, both the records [rows] and the information [columns] - we add new records often, but we also update information in certain columns. so the dataset is constantly in flux. we fill in some missing data with an imputation, which requires random number generation with the sample() function. so whenever we add a new row or update any information in the column, the randomly imputed numbers all change -- which is expected. we use set.seed() at the start of each random imputation, so if a column changes but zero rows change, the other randomly-generated columns are not affected.

i'm under the impression that the only function within our entire codebase that ever touches a random seed is the sample() function, but i would like to verify this somehow?

thanks




why random generate number is always the same in fortran90?

I would like to generate a random number in fortran90.

I have a program in fortran90 :

PROGRAM PRINCIPAL

REAL(8)::r
INTEGER::i

DO i=1,5
   CALL RANDOM_NUMBER(r)
   write(*,*) u
END DO

STOP "End program"
END PROGRAM PRINCIPAL

My output are :

user@user-desktop:/media/data/test/ ./simple01.sh
3.920868194323862E-007
2.548044275764261E-002
0.352516161261067
0.666914481524251
0.963055531894656

if I run it again :

user@user-desktop:/media/data/test/ ./simple01.sh
3.920868194323862E-007
2.548044275764261E-002
0.352516161261067
0.666914481524251
0.963055531894656

I don't understand why if I run two time the same script I get the same random numbers ?




How to create a custom random distribution function?

Normally I generate values using the built in random functions, but now I need to create a random distribution of the form

f(x) = k*log(x) + m

Is it possible to define a custom random distribution function? Ideally I would like it to work how the current built-in distributions do:

int main() 
{
    std::mt19937 generator;

    std::uniform_real_distribution<> dist(0.0, 1.0);
    my_distribution my_dist(0.0, 10.0); // Distribution using f(x)

    double uni_val = dist(generator);
    double log_val = my_dist(generator);
}




RDieHarder: calling 'dieharder' with 'file_input_raw' leads to 'Error. This cannot happen.'

I'am trying to test my RNG (written in VHDL, numbers stored in binary file) with the RDieHarder package. But when I call the dieharder() function twice (from R) this leads to

> dh <- dieharder(rng = 'file_input_raw', test = 'diehard_runs', inputfile = 'rand.bin')
# file_input_raw(): Error.  This cannot happen.
[user@host ~]$

and drops me to my shell.

Setup

Die Harder Version:

$ dieharder -h
#=============================================================================#
#            dieharder version 3.31.1 Copyright 2003 Robert G. Brown          #
#=============================================================================#
...

R Version:

$ R --version
R version 3.3.3 (2017-03-06) -- "Another Canoe"
Copyright (C) 2017 The R Foundation for Statistical Computing
Platform: x86_64-pc-linux-gnu (64-bit)

RDieHarder Version:

> packageVersion('RDieHarder')
[1] ‘0.1.3’

MWE

To reproduce this, we first generate an appropriate binary file with dieharder and run the die hard tests on it.

$ dieharder -o -O0 -f rand.bin -t 5000000 && dieharder -g file_input_raw -d diehard_runs -f rand.bin
#=============================================================================#
#            dieharder version 3.31.1 Copyright 2003 Robert G. Brown          #
#=============================================================================#
   rng_name    |           filename             |rands/second|
 file_input_raw|                        rand.bin|  4.49e+07  |
#=============================================================================#
        test_name   |ntup| tsamples |psamples|  p-value |Assessment
#=============================================================================#
# The file file_input_raw was rewound 4 times
        diehard_runs|   0|    100000|     100|0.77169947|  PASSED  
        diehard_runs|   0|    100000|     100|0.68299332|  PASSED

All tests where passed, fine. So we switch to R and do the same thing again and asume we want some more tests, like the STS Runs test.

> library('RDieHarder')
> dh <- dieharder(rng = 'file_input_raw', test = 'diehard_runs', verbose = TRUE, inputfile = 'rand.bin')
Dieharder called with gen=201 test=15 seed=2852951401
# 10000000 rands were used in this test
# The file file_input_raw was rewound 2 times
#==================================================================
#                    Diehard Runs Test
#  This is the RUNS test.  It counts runs up, and runs down, 
# in a sequence of uniform [0,1) variables, obtained by float-  
# ing the 32-bit integers in the specified file. This example   
# shows how runs are counted:  .123,.357,.789,.425,.224,.416,.95
# contains an up-run of length 3, a down-run of length 2 and an 
# up-run of (at least) 2, depending on the next values.  The    
# covariance matrices for the runs-up and runs-down are well    
# known, leading to chisquare tests for quadratic forms in the  
# weak inverses of the covariance matrices.  Runs are counted   
# for sequences of length 10,000.  This is done ten times. Then 
# repeated.                                                     
#
# In Dieharder sequences of length tsamples = 100000 are used by
# default, and 100 p-values thus generated are used in a final
# KS test.
#==================================================================
#                        Run Details
# Random number generator tested: file_input_raw
# File rand.bin contains 5000000 rands of  type.
# Samples per test pvalue = 100000 (test default is 100000)
# P-values in final KS test = 100 (test default is 100)
#==================================================================
#                Histogram of p-values
##################################################################
# Counting histogram bins, binscale = 0.100000
#     20|    |    |    |    |    |    |    |    |    |    |
#       |    |    |    |    |    |    |    |    |    |    |
#     18|    |    |    |    |    |    |    |    |    |    |
#       |    |    |    |    |    |    |    |    |    |    |
#     16|    |    |    |    |    |    |    |    |    |    |
#       |    |    |    |    |    |    |    |    |    |    |
#     14|****|    |    |    |    |    |    |    |****|    |
#       |****|    |    |    |    |    |    |    |****|    |
#     12|****|    |****|    |****|    |****|    |****|    |
#       |****|    |****|    |****|    |****|    |****|    |
#     10|****|    |****|    |****|****|****|    |****|    |
#       |****|    |****|    |****|****|****|    |****|    |
#      8|****|    |****|****|****|****|****|****|****|    |
#       |****|    |****|****|****|****|****|****|****|    |
#      6|****|    |****|****|****|****|****|****|****|****|
#       |****|    |****|****|****|****|****|****|****|****|
#      4|****|****|****|****|****|****|****|****|****|****|
#       |****|****|****|****|****|****|****|****|****|****|
#      2|****|****|****|****|****|****|****|****|****|****|
#       |****|****|****|****|****|****|****|****|****|****|
#       |--------------------------------------------------
#       | 0.1| 0.2| 0.3| 0.4| 0.5| 0.6| 0.7| 0.8| 0.9| 1.0|
#==================================================================
# 10000000 rands were used in this test
# The file file_input_raw was rewound 2 times
#==================================================================
#                Histogram of p-values
##################################################################
# Counting histogram bins, binscale = 0.100000
#     20|    |    |    |    |    |    |    |    |    |    |
#       |    |    |    |    |    |    |    |    |    |    |
#     18|    |    |    |    |    |    |    |    |    |    |
#       |    |    |    |    |    |    |    |    |    |    |
#     16|    |    |    |    |    |****|    |    |****|    |
#       |    |    |    |    |    |****|    |    |****|    |
#     14|    |    |    |    |    |****|    |    |****|    |
#       |    |    |    |    |    |****|    |    |****|    |
#     12|    |****|    |    |    |****|    |    |****|    |
#       |    |****|    |    |    |****|    |    |****|    |
#     10|****|****|    |    |****|****|    |    |****|    |
#       |****|****|    |    |****|****|    |    |****|    |
#      8|****|****|****|    |****|****|****|    |****|****|
#       |****|****|****|    |****|****|****|    |****|****|
#      6|****|****|****|****|****|****|****|****|****|****|
#       |****|****|****|****|****|****|****|****|****|****|
#      4|****|****|****|****|****|****|****|****|****|****|
#       |****|****|****|****|****|****|****|****|****|****|
#      2|****|****|****|****|****|****|****|****|****|****|
#       |****|****|****|****|****|****|****|****|****|****|
#       |--------------------------------------------------
#       | 0.1| 0.2| 0.3| 0.4| 0.5| 0.6| 0.7| 0.8| 0.9| 1.0|
#==================================================================
# 10000000 rands were used in this test
# The file file_input_raw was rewound 2 times
> summary(dh)

    Diehard Runs Test

data:  Created by RNG `file_input_raw' with seed=0, sample of size 100
p-value = 0.7717


Summary for test data
   Min. 1st Qu.  Median    Mean 3rd Qu.    Max. 
0.03151 0.23500 0.49970 0.49850 0.75030 0.94720 


Stem and leaf plot for test data

  The decimal point is 1 digit(s) to the left of the |

  0 | 33667788889999
  1 | 3399
  2 | 0011333355
  3 | 0022222266
  4 | 222222446688
  5 | 229999
  6 | 0000224477778899
  7 | 225555
  8 | 0022446666888888
  9 | 003355

NULL

    One-sample Kolmogorov-Smirnov test

data:  object$data
D = 0.06947, p-value = 0.6936
alternative hypothesis: two-sided


    Wilcoxon signed rank test with continuity correction

data:  object$data
V = 2507, p-value = 0.952
alternative hypothesis: true location is not equal to 0.5

Warning:
In ks.test(object$data, "punif", 0, 1, exact = TRUE) :
  ties should not be present for the Kolmogorov-Smirnov test
> # calling dieharder() again yields an error
> dh <- dieharder(rng = 'file_input_raw', test = 'sts_runs', verbose = TRUE, inputfile = 'rand.bin')
Dieharder called with gen=201 test=101 seed=3570434269
# file_input_raw(): Error.  This cannot happen.
[user@host ~]$

So if This cannot happen why does it happen?

Thanks for your time and best regards,

Befedo




I need help generating the Blum Blum Shub in C#

Need help coding the Blum Blum Shub generator in C#. Don't know where to start, so anyone can help pls?




Understanding Mersenne Twister Code Implementation - Python

I'am having trouble understanding this code from http://ift.tt/1SDESKn

def _int32(x):
# Get the 32 least significant bits.  
   return int(0xFFFFFFFF & x)

class MT19937:

def __init__(self, seed):
    # Initialize the index to 0
    self.index = 624
    self.mt = [0] * 624
    self.mt[0] = seed  # Initialize the initial state to the seed
    for i in range(1, 624):
        self.mt[i] = _int32(
            1812433253 * (self.mt[i - 1] ^ self.mt[i - 1] >> 30) + i)

def extract_number(self):
    if self.index >= 624:
        self.twist()

    y = self.mt[self.index]

    # Right shift by 11 bits
    y = y ^ y >> 11
    # Shift y left by 7 and take the bitwise and of 2636928640
    y = y ^ y << 7 & 2636928640
    # Shift y left by 15 and take the bitwise and of y and 4022730752
    y = y ^ y << 15 & 4022730752
    # Right shift by 18 bits
    y = y ^ y >> 18

    self.index = self.index + 1

    return _int32(y)

def twist(self):
    for i in range(624):
        # Get the most significant bit and add it to the less significant
        # bits of the next number
        y = _int32((self.mt[i] & 0x80000000) +
                   (self.mt[(i + 1) % 624] & 0x7fffffff))
        self.mt[i] = self.mt[(i + 397) % 624] ^ y >> 1

        if y % 2 != 0:
            self.mt[i] = self.mt[i] ^ 0x9908b0df
    self.index = 0
    #test

I would really appreciate any help. How do i generate the number and print them ? How do i "generate" the parameter seed for the class? What does def _int32(x) contribute?




Protractor: How to store number text from div element

I'm using Protractor and Angular page. On the page there are each time displayed random 5 selected numbers out of 50 available. How can I store text for each of those 5 numbers into one variable? All selected numbers have one attribute and its value in common.

HTML:

<div class="basic-number-selected" ...</div>

Page object file:

this.selectedNumbers = element.all(by.css('div.basic-number-selected'));

Do any of you have an idea how can I store text of each selected number?

I've tried with each, but without any success:

var numbers = [];

page.selectedNumbers.getText().each(function(num) {
    numbers.push(num);
});

console.log("Selected numbers: " + numbers);




Generating 5 unique coordinates on a grid using 2 arrays

I am using Java to program an application that randomly generates 8 X points in a 5x5 grid.

Both the x and y axis have separate arrays I use to store the coordinates. These 2 arrays are parallel arrays that correlate with each other. The problem I am having is I can not seem to generate 8 unique coordinates.

For example, no matter what I do, I will eventually only have less than 8 unique coordinates because it so happens that the same coordinates are generated twice. I am trying to find an algorithm that can ensure the 8 random generated coordinates to be unique.

Also, For some reason, when I use the Random class to generate random numbers between 1 - 5, I sometimes get a 0 as a randomly generated number. This is how I use the Random class:

Random rand = new Random(System.currentTimeMillis()); coordinate = rand.nextInt(5)+1;

Thank you all for your time!




Select the random row from dataframe and insert into another dataframe

I have two table 1.reason with 9 records and another one is id dataframe with 40k records.

ID

+------+------+
|pc_pid|pc_aid|
+------+------+
|  4569|  1101|
| 63961|  1101|
|140677|  4364|
|127113|     7|
| 96097|   480|
|  8309|  3129|
| 45218|    89|
|147036|  3289|
| 88493|  3669|
| 29973|  3129|
|127444|  3129|
| 36095|    89|
|131001|  1634|
|104731|   781|
| 79219|   244

reasons

+-----------------+
|          reasons|
+-----------------+
|        follow up|
|         skin chk|
|      annual meet|
|review lab result|
|        REF BY DR|
|       sick visit|
|        body pain|
|             test|
|            other|
+-----------------+

I want output like this

|pc_pid|pc_aid| reason 
+------+------+-------------------
|  4569|  1101| body pain
| 63961|  1101| review lab result
|140677|  4364| body pain
|127113|     7| sick visit
| 96097|   480| test
|  8309|  3129| other
| 45218|    89| follow up
|147036|  3289| annual meet
| 88493|  3669| review lab result
| 29973|  3129| REF BY DR
|127444|  3129| skin chk
| 36095|    89|  other

In the reasons I have only 9 records and in the ID dataframe I have 40k records, I want to assign reason randomly to each and every id.




How to generate a random 4 digit number not starting with 0 and having unique digits?

This works almost fine but the number starts with 0 sometimes:

import random
numbers = random.sample(range(10), 4)
print(''.join(map(str, numbers)))

I've found a lot of examples but none of them guarantee that the sequence won't start with 0.




mardi 25 avril 2017

Python Random Match

How can I modify + add from my code so that it prints both the name of the winner and the winning number?! So let's say William with random number 7 matched with winning number 7. Then I want it to print that "William is the winner and the winning number was 7!". In the other hand, if the winning number was 5 and no one had that matching number, I want it to print out "There is no winner". Thanks in advance!

import random
from random import sample
character_count = 5

names = ['John', 'William', 'James', 'George', 'Charles', 'Frank', 'Joseph', 'Henry', 'Robert', 'Thomas', 'Edward',
'Harry', 'Walter', 'Arthur', 'Fred', 'Albert', 'Samuel', 'Clarence', 'Louis', 'David', 'Mary', 'Anna', 'Emma', 'Elizabeth',
'Margaret', 'Minnie', 'Ida', 'Bertha', 'Clara', 'Alice', 'Annie', 'Florence', 'Bessie', 'Grace', 'Ethel', 'Sarah',
'Ella', 'Martha', 'Nellie', 'Mabel']

generate_random_names = (sample(names, k=character_count))

random_number = random.sample(range(1,10), (5))
winning_number = random.sample(range(1,10), (1))

character_status = list(zip(generate_random_names, random_number))

char_one_info = (character_status[0])
char_two_info = (character_status[1])
char_three_info = (character_status[2])
char_four_info = (character_status[3])
char_five_info = (character_status[4])

while True:
    winning_number == char_one_info[1] or winning_number == char_two_info[1] or winning_number == char_three_info[1] or winning_number == char_four_info[1] or winning_number == char_five_info[1]
    print (True)




Confusion regarding RNG and static void main

In our class, we have a task to create a random number generator. The generator is supposed to make X number of randomly generated numbers between a high and a low range. It should also put generated items into an array and check to ensure it doesnt include the same randomly generated number twice.

Visual studio is not coming up with any errors, though there probably are some seeing as the program instantly closes when i attempt to test run it.

The previous error message told me that the program did not have a static main to use, though now its just closing without any feedback.

Any ideas on why this is happening? (could be something obvious, i am quite new to c#)

Code:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Randomnumbers
{
    class Program
    {
        int lowrange = 0; // Establishing the variables for lowest number, highest number, and total numbers generated.
        int highrange = 50;
        int numberof = 10;

        public void Main(string[] args)
        {
            while (numberof > 0) //Repeats this loop once for each "numberof". (until the number hits zero)
            {
                numberof = numberof - 1;
                generatenewnumber(); //Calls the function above
            }
            if (numberof == 0)
            {
                Console.ReadLine(); // Here so the program doesnt instantly close
            }
        }

        public void generatenewnumber()
        {
            var rng = new Random();
            int number = rng.Next(lowrange, highrange); //Sets the number to a random number between the high and low values.
            var generated = new List<int>(); // Creates a list of numbers that have been generated already to prevent double-ups.
            if (!generated.Contains(number)) // Checks if the rg'd number has already been made.
            {
                generatenewnumber(); //Calls the function above
            }
            else
            {
                numberof = numberof - 1;
                generated.Add(number); // Adds the genereated number to the list.
                Console.WriteLine(number); // Prints the number. 
                Console.ReadLine();
            }
        }
    }
}

Thanks :p