mardi 31 octobre 2017

generate a matrix with random zeros

Using C I am trying to generate a matrix which has to have more number of zero elements than non zero elements. The zero elements should be random how to generate it.

I am able to generate random numbers

int main(){
     srand(time(NULL));
     int Intarray[25];
     int i;
     for (i=0;i<s;i++){
         array[i] = rand();
     }
 }

is the generated matrix sparse matrix ? how can I understand the difference ?




generate 1000 random birthdays between 1 and 365 and count the number of same birthdays

generate 1000 random birthdays (numbers) between 1 and 365 and then count how many people have that same birthday output a display of each day of the year (1 – 365) followed by the number of people with that birthday, and then a listing of the days that have the most birthdays and the days that have the fewest birthdays.




Random questions & highscores in swift quiz app

Hey guys im new in swift and i search a function that displays a high score in my quiz app and i also search for a function that randomize the questions without repeating one of them. the score should appear on another view controller after finishing the quiz (or after you answered a question wrong, but that is for the future). thx for your help and sorry for my bad english!

let questions = ["best mother?", "best father?", "best sister?"]
let answers = [["Josi", "Maria", "Annika"], ["Andi", "Uwe", "Jupp"], ["Claudia", "Anna", "Lena"]]

// Variables
var currentQuestion = 0
var rightAnswerPlacement:UInt32 = 0
var points = 0;

//Label
@IBOutlet weak var label: UILabel!

//Button
@IBAction func action(_ sender: Any)
{
    if ((sender as AnyObject).tag == Int(rightAnswerPlacement))
    {
        print ("Right!")
        points += 1
    }
    else
    {
        print ("Wrong!")
    }

    if (currentQuestion != questions.count)
    {
        newQuestion()
    }
    else
    {
        performSegue(withIdentifier: "showScore", sender: self)
    }
}

override func viewDidAppear(_ animated: Bool)
{
    newQuestion()
}

//Function that displays new question
func newQuestion()
{
    label.text = questions[currentQuestion]

    rightAnswerPlacement = arc4random_uniform(3)+1

    //Create a button
    var button:UIButton = UIButton()

    var x = 1

    for i in 1...3
    {
        //Create a button
        button = view.viewWithTag(i) as! UIButton

        if (i == Int(rightAnswerPlacement))
        {
            button.setTitle(answers[currentQuestion][0], for: .normal)
        }
        else
        {
            button.setTitle(answers[currentQuestion][x], for: .normal)
            x = 2
        }
    }
        currentQuestion += 1
}




Using `numpy.random.randint()` for another distribution, only one input

I think I am misunderstanding something, so hopefully someone on this forum can straighten me out. I have an array foo. Based on the length of the array, I am drawing random numbers from a discrete Uniform distribution:

import numpy as np 
random_draw = np.random.randint(length(foo))

which draws a random integer from [0, length(foo)]

What would be the equivalent for another distribution, e.g. a Gaussian or Poisson? I believe certain distributions which require several parameters would not be feasible with this approach.

The idea would be to only provide this input length(foo) to draw from this distribution. In the case of Gaussian, perhaps mean=length(foo)/2 and standard deviation np.std(length(foo))?




Why is my list assignment index out of range in my python app?

So imagine I have this code in python:

import pickle
import numpy as np
import pandas as pd
x_u = []
load_model = open('dt.plk', 'rb')
dt = pickle.load(load_model)
cuantos = int(input('cuantas observaciones: '))
x_u[0] =pd.DataFrame(np.random.randint(341, size = 1))
x_u[1] =pd.DataFrame(np.random.randint(291, size = 1))
x_u[2] =pd.DataFrame(np.random.randint(150, size = 1))
x_u[3] =pd.DataFrame(np.random.randint(301, size = 1))
x_u[4] =pd.DataFrame(np.random.randint(341, size = 1))
x_u[5] =pd.DataFrame(np.random.randint(299, size = 1))
x_u[6] =pd.DataFrame(np.random.randint(150, size = 1))
x_u[7] =pd.DataFrame(np.random.randint(301, size = 1))
ps = dt.predict(x_u)
for d in x_u[0].tolist():
    if d == 0:
        print('Se queda')
    else:
        print('Se va')

When I run it I get this error. I've been modifying the index range with no success can you figure out what it is?

Traceback (most recent call last):
File "app.py", line 8, in <module>
x_u[0] =pd.DataFrame(np.random.randint(341, size = 1))
IndexError: list assignment index out of range




How to generate a binomial vector of n correlated items?

I want to generate binomial vectors based on a number of correlated items each with a defined probability. When I use e. g. rbinom(1e3, size = 4, prob = c(p.x1, p.x2, p.x3, p.x4)) I'm getting something like 3 3 0 0 2 4 1 0 4 4 0 1 4.... Now these x_i have already defined probabilities but are not yet correlated.

Five years ago Josh O'Brien contributed a great approach to generate correlated binomial data. I think it is close to my needs, but it is designed for pairs. I tried to modify the function to produce a greater number of variables but with no success so far and I'm frequently facing

Error in commonprob2sigma(commonprob, simulvals) : 
Matrix commonprob not admissible. 

which is sent by the imported bindata package.

My idea is to define in Josh's function four (or better an arbitrary number of) probabilities and rhos, something like

rmvBinomial3 <- function(n, size, p1, p2, p3, p4, rho) {
  X <- replicate(n, {
    colSums(rmvbin(size, c(p1,p2,p3,p4), bincorr=(1-rho)*diag(4)+rho))
  })
  t(X)
}

Sure--more rhos are needed and I guess a probabililty matrix should be included somehow as it can be done with the bindata package.

rho1 <- -0.89; rho2 <- -0.75; rho3 <- -0.62; rho4 <- -0.59
m <- matrix(c(1, rho1, rho2, rho3,
     rho1, 1, rho4, rho2,
     rho2, rho4, 1, rho1,
     rho3, rho2, rho1, 1), ncol = 4) 
#       [,1]  [,2]  [,3]  [,4]
# [1,]  1.00 -0.89 -0.75 -0.62
# [2,] -0.89  1.00 -0.59 -0.75
# [3,] -0.75 -0.59  1.00 -0.89
# [4,] -0.62 -0.75 -0.89  1.00

Unfortunately each matrix I check with bindata::check.commonprob(m) it throws me the same error as above. I also couldn't accomplish to let bindata::commonprob2sigma() create a matrix.

A drawback is the range of rmvBinomial(), it seems to work only between values for p.X_i= 0.2--0.8 something and I need smaller values e.g. 0.01--0.1, too.

It seems I'm really stuck. Hopefully anybody could help and show me how to do this?

Edit: To clarify, the expected outcome is indeed just one single vector 3 3 0 0 2 4 1 0 4 4 0 1 4... as shown in the beginning, but the items from which it's derived should be correlated to a definable degree (i. e. one of the items could have no correlation at all).




Select different random elements from an ArrayList of array of strings in java

I am Rookie. I have to select randomly different elements from an ArrayList which has an array of strings. I tried couple different ways but it is selecting the same array every time.Here are the ways I tried.

 public static void RandomSchedules(ArrayList<String[]> list)
{
    Random randomizer = new Random();
    for(int i=1; i<11; i++)
   {

    String[] random = list.get(new Random().nextInt(list.size()));
    System.out.println("Random Schedule " +  ":" + Arrays.toString(random));
    }
}

I also tried this in the above code.

   String[] random = list.get(randomizer.nextInt(list.size()));

But the result is same.

This is the other approach I have tried from Stack Overflow

 public static List<String[]> pickNRandom(ArrayList<String[]> lst, int n) {
List<String[]> copy = new LinkedList<String[]>(lst);
Collections.shuffle(copy);
return copy.subList(0, n);
 }

I am calling the above function as,

    List<String[]> randomPicks = pickNRandom(lst, 10);

Could anyone guide me how to get different elements.




create N random points all more distant than given length L (python)

Similar questions:
Generating N random points with certain predefined distance between them

choose n most distant points in R

But they are either in matlab or does not fullfill the required task.

I have to create N number of points inside a box of length that the distance between any two points is larger than delta.

For example: Let's say I have a box of length 10 Angstrom on x,y,z axis.
I want to have 10 random points inside this box so that minimum distance between any two points is larger than 3 Angstrom.

Attempt:

#!python
# -*- coding: utf-8 -*-#
import numpy as np
np.random.seed(100)
np.set_printoptions(2)

box_length = 10
d = box_length
threshold = 6
num_points = 5
x1, y1, z1 = np.random.random(num_points)* box_length, np.random.random(num_points)* box_length, np.random.random(num_points)* box_length
x2, y2, z2 = np.random.random(num_points)* box_length, np.random.random(num_points)* box_length, np.random.random(num_points)* box_length

# print(len(x1))

# just for checking make ponts integers
for i in range(len(x1)):
    x1[i] = int(x1[i])
    x2[i] = int(x2[i])
    y1[i] = int(y1[i])
    y2[i] = int(y2[i])
    z1[i] = int(z1[i])
    z2[i] = int(z2[i])


print(x1)
print(y1)
print(z1)
print("\n")

pt1_lst = []
pt2_lst = []
for i in range(len(x1)):
    a, b, c    = x1[i], y1[i], z1[i]
    a2, b2, c2 = x2[i], y2[i], z2[i]
    dist2      = (a-a2)**2 + (b-b2)**2 + (c-c2)**2

    print("\n")
    print(a,b,c)
    print(a2,b2,c2)
    print(dist2)

    if dist2 > threshold**2:
        pt1 = (a,b,c)
        pt2 = (a2,b2,c2)
        pt1_lst.append(pt1)
        pt2_lst.append(pt2)



print("points")
print(pt1_lst)
print(pt2_lst)

Problem on Code: This code compares points from points1 to points2 but does not compare within itself inside points1 and points2.

There might be better algorithms to solve this problem and hats off to those guys who come with the brilliant idea to solve the problem.

Thanks.

PS: I did some research and try to find related links, however was unable to solve the problem. Still some related links are:

All paths of length L from node n using python
Create Random Points Inside Defined Rectangle with Python




How to change value of item in list

How do I change a value that is stored in a list. I'm making a program with weighted numbers. the program will pick a weighted number and add it to the picked numbers variable. it will do this twice. i wanted so that when a number if picked and the sum of both of the numbers is greater than the last sum then the weight for the numbers that were picked will go up making them more likely to be picked again. comment if you need a better explanation. this is the code i'm using just now.

Public Class Form1

    Structure Weighted
        Dim Number As Integer
        Dim Weight As Integer
    End Structure

    Dim Numbers As New List(Of Weighted)
    Dim CurrentNumber As Weighted
    Dim random As New Random
    Dim picked(1) As Integer

    Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load

        For i = 1 To 10
            CurrentNumber.Number = i
            CurrentNumber.Weight = 1

            Numbers.Add(CurrentNumber)
            ListBox1.Items.Add(CurrentNumber.Number & vbTab & ":" & vbTab & CurrentNumber.Weight)
        Next

    End Sub

    Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
        Dim SumOfWeight As Integer
        Dim RandomNumberPicked As Integer

        For i = 0 To 1
            SumOfWeight = 0
            For Each item In Numbers
                SumOfWeight += item.Weight
            Next
            RandomNumberPicked = random.Next(0, SumOfWeight + 1)
            For Each item In Numbers
                If RandomNumberPicked < item.Weight Then
                    picked(i) = item.Number
                    Numbers(picked(i) - 1).Weight += 1 ''error occures here
                    Exit For
                Else
                    RandomNumberPicked -= item.Weight
                End If
            Next
        Next

        MsgBox(picked(0) & " + " & picked(1) & " = " & picked(0) + picked(1))

        ListBox1.Items.Clear()
        For Each item In Numbers
            ListBox1.Items.Add(item.Number & vbTab & ":" & vbTab & item.Weight)
        Next

    End Sub
End Class

Error Message




I want to generate some mathematical questions by using rand and function

I am learning c++ program in my home. So I am not good at using it.

  1. First I want to output the programme like the below statement.
  2. "Question 1: 4 + 5 = 9 correct!
  3. "Question 2: 5 * 5 = 9 fail!
  4. "Question 3: 9 - 5 = 4 correct! I want to produce the question at least 5 and not more than 10 questions. My curiosity is that how can I increase the question number and how can I check that whether I answer this question correct or not. This is so far I'm done. Please do understand my code because I am learning C++ alone in my home

int main()
{
int a, b, digit1, digit2,;
char op, k;
a = digit1;
b = digit2;
op = k;

srand (time (NULL));

generate2Digits(a,b);
generateOperators(op);


}

void generate2Digits (int& a, int& b) 
{
    int digit1;
    int digit2;

    srand (time (NULL));

    digit1= rand ()%10;
    digit2= rand ()%10;

    for(int i = 1; i<= rand()%10; i++) 
    {
        cout << digit1 << endl;
        cout << digit2<< endl;
    }


}

void generateOperators(char& op)

{ int k;

    for(int i=1; i<= 10; i++)
    {
        k = rand () % 4;

        switch(k)
        {
            case 0: cout << "+" << endl;
                break;
            case 1: cout << "-" << endl;
                break;
            case 2: cout << "*" << endl;
                break;
    }

}


}

void printExpression(int a, int b, char op)
{
    do
    {






}

// how to print the question expression like the above example? // how to check the whether the answer is correct or not?




Stochastic random Data

I am trying to generate stochastic data using different perturbation methods

  1. Probabilistic
  2. Stochastic
  3. polynomial Chaos

I wonder which package of python has all these functionalities. I am confused about which one I have to use:

  1. SimPy
  2. uncertainties
  3. StochPy



Calculating average for numbers generated using Random() method in java

My code is below, everything is working except when I generate the average number of heads and tails per trial, it comes out as 0 every time. the code for it is at the bottom, but I posted everything I did because I am not sure where the mistake is. How can I fix that? Thanks!!!!

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


public class CoinToss{
 public static void main(String [] args)
    {
        int heads = 0;
        int tails = 0;
        int counter = 1;
        double randNum = 0.0;
        Scanner in = new Scanner(System.in);

    //introduction
    System.out.println("Welcome to the coin flip simulator!");
    System.out.println("This program will simulate the average ");
    System.out.println("number of heads and tails for 10, 100  ");
      System.out.print("and 10000 flips of a coin. ");
    //user input
    System.out.println("How many times would you like to flip the coin? ");
    System.out.print("choose 10,100, 1  ");
    System.out.print("or 10000 ");
    //scanner
    int flips = in.nextInt();

    while(counter <= flips)
    {
        randNum = Math.random();
        System.out.print(counter + "\t" + randNum);

        if(randNum < .5)
        {
            heads++;
            System.out.println("\t heads");
        }
        else
        {
            tails++;
            System.out.println("\t tails");
           }
        counter++;      
    }
    System.out.println();
    System.out.println("Number of Heads = " + heads);
    System.out.println("Number of Tails = " + tails);


    //average heads
    System.out.println("Average number of times for 'heads':");
    System.out.println(heads++/flips);


    //average tails
    System.out.println("Average number of times for 'tails':");
    System.out.println(tails++/flips);

} }`




generate random logic functions with 2-4 variables and finding the minterm maxterm for that random logic function

this is a homework assignment. I am suppose to create a website that gives random logic functions for the user to solve and also providing the answer at the end. currently i am just hard coding all the possible questions and answers into database for example F = A + AB, A' + AB and so on. Database

Is there a way that generates random logic functions for 2 variables, 3 variables and so on? I did part of the 2variables logic functions and found out it gets exponentially more when i add in more variables. I know that this requires algorithms and functions but i do not know where to start. Can anyone guide me through this?




lundi 30 octobre 2017

20 Random Strings containing all capital letters

I need to create a procedure that generates a random string of length L, containing all capital letters. When calling the procedure, I need to pass the value of L in EAX, and pass a pointer to an array of byte that will hold the random string. Then I need to write a test program that calls your procedure 20 times and displays the strings in the console window.

The code below wont work it comes back with these errors: Line (33): error A2008: syntax error : main ENDP Line (35): error A2144: cannot nest procedures Line (46): error A2008: syntax error : RandomString Line (48): error A2144: cannot nest procedures Line (59): warning A6001: no return from procedure Line (66): fatal error A1010: unmatched block nesting

I am still very new with Assembly Language...Any ideas on what I'm doing wrong and how to fix these errors? Thank you.

;Random Strings.

INCLUDE Irvine32.inc TAB = 9 ;ASCII code for Tab strLen=10 ;length of the string

.386 .model flat,stdcall .stack 4096 ExitProcess PROTO, dwExitCode:DWORD

.data str1 BYTE"The 20 random strings are:", 0 arr1 BYTE strLen DUP(?)

.code main PROC mov ed x, OFFSET str1 ;"The c20 random strings are:" call WriteString ;Writes string call Crlf ;Writes an end-of-line sequence to the console window. mov ecx,20 ;Create 20 strings

L1: mov esi,OFFSET arr1 ;ESI: array address mov eax,strLen ;EAX: string length call RandomString ;generates the random string call Display mov al,TAB call WriteChar ;leaves a tab space exit main ENDP

 RandomString PROC USES eax esi
 mov ecx,eax                   ;ECX = string length

L1: mov eax, 26 call RandomRange add eax,65 ;EAX gets ASCII value of a capital letter mov arr1[esi],eax inc esi

 loop L1

 RandomString EXDP

 Display PROC USES eax esi     ;Displays the generated random string

 mov ecx,eax                   ;ECX=string length

L1: mov eax, arr1[esi] ;EAX = ASCII value call WriteChar ;writes the letter

 inc esi

 loop L1

 Display ENDP


    call dumpregs

    INVOKE ExitProcess,0

END main




I am trying to create a program in which the computer picks a random number between 1 and 100 and tries to guess it

I am new to Python and I am just programming some random things for fun. I want to write a program in which the computer generates a random number between 1 and 100 and then tries to guess it. I do not want the user to interfere with it in any way. I also want to count how many guesses the computer took. I am also trying to have it run multiple games and calculate the average amount of guesses. I know I need to incorporate a while loop, but I don't know how to have the computer keep guessing random numbers instead of just listing every number within the range. Can someone help?

import random

the_num = random.randint(1, 100)
print('The number to guess is',the_num)
comp_guess = random.randint(1, 100)
print('The computer guesses ', comp_guess)
tries = 1

while comp_guess != the_num:
    print('The computer guesses ', comp_guess)
    tries = tries+1
    if comp_guess > the_num:
        comp_guess = comp_guess-1
    elif comp_guess < the_num:
        comp_guess = comp_guess+1
    elif comp_guess == the_num:
        break

print(tries)
print('The computer guessed it right!')




JavaScript: Why am I getting an undefined value while using random numbers from an array? [on hold]

I am using Javascript to set a element's background image in from a class. The code works for the most part, but I get a undefined variable when I run the code. I am using Math.Random() to get the numbers for the variables. Here is ALL of my Javascript code:

/*
 Name: Bradley [Insert Last Name]
 Date: 10/29/2017
 Prog: JavaScript / Brackets
 File: halloween.js
 Desc: Halloween Javascript code.
*/

// Loaded
function Loaded(){
    var MainDiv = document.getElementsByClassName("main-div")[0];
    var ContentDivs = document.getElementsByClassName("middle-content");
    var BC = document.getElementById("bottom-content-div");
    var BlContent = document.getElementById("bottom-left-content");
    var BrContent = document.getElementById("bottom-right-content");
    var StartDiv = document.getElementById("start-div");
    var MiddleContentDiv = document.getElementById("middle-content-div");
    var PlayButton = document.getElementById("play-button");
    var CountdownDiv = document.getElementById("countdown-div");
    var CountdownNumbers = document.getElementById("countdown-numbers");
    var HalfScreenWidth = (screen.availWidth / 2);
    var HalfScreenHeight = (screen.availHeight / 2);
    var Numbers = 3;
    var Timer = 60;
    var Score = 0;
    var RandomContentDiv = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15];

    PlayButton.addEventListener("mousedown", ClickedPlayButton);
    CountdownNumbers.innerHTML = Numbers;
    window.addEventListener("resize", Resized);
    window.addEventListener("contextmenu", ContextMenu);


    // Width
    if(window.innerWidth <= HalfScreenWidth){
        MainDiv.style.width = HalfScreenWidth + "px";
    } else {
        MainDiv.style.width = "100%";
    }

    // Height
    if(window.innerHeight <= HalfScreenHeight){
        MainDiv.style.height = HalfScreenHeight + "px";
    } else {
        MainDiv.style.height = "100%";
    }

    // Sets StartDiv dimensions.
    StartDiv.style.width = HalfScreenWidth + "px";
    StartDiv.style.height = HalfScreenHeight + "px";
    StartDiv.style.left = "calc(50% - " + (HalfScreenWidth / 2) + "px)";
    StartDiv.style.top = "calc(50% - " + (HalfScreenHeight /  2) + "px)";

    // Sets PlayButton dimensions.
    PlayButton.style.top = "calc(" + (HalfScreenHeight /  2) + "px - 50" + "px)";

    // When CountdownNumbers Loads.
    CountdownNumbers.style.top = "calc(50% - 50px)";

    // Clicked the play button.
    function ClickedPlayButton(e){
        if(e.which == 1 || e.button == 1){
            PlayButton.style.color = "white";
            // Button
            var a = window.setInterval(function ColorIndication(){
                StartDiv.style.display = "none";
                window.clearInterval(a);
                // Delay
                var b = window.setInterval(function StartCountdown(){
                    window.clearInterval(b);
                    CountdownDiv.style.display = "block";
                    // Countdown
                    var c = window.setInterval(function Countdown(){
                        if(Numbers > 1){
                            Numbers--;
                            CountdownNumbers.innerHTML = Numbers;
                        } else if (Numbers == 1){
                            Numbers--;
                            CountdownNumbers.style.color = "orange";
                            CountdownNumbers.innerHTML = "GO!";
                        } else if (Numbers < 1){
                            CountdownNumbers.innerHTML = "";
                            CountdownDiv.style.display = "none";
                            window.clearInterval(c);
                            JackOLantern();
                        }
                    }, 1000);
                    function JackOLantern(){   
                        MiddleContentDiv.style.display = "block";
                        BC.style.display = "block";
                        BlContent.style.display = "block";
                        BrContent.style.display = "block";
                        var cd = RandomContentDiv[Math.round(Math.random()*RandomContentDiv.length)];
                        var storecd = cd;
                        ContentDivs[cd].setAttribute("style", "background-image: url('./Images/JackLantern.png'); cursor: pointer;");
                        ContentDivs[cd].addEventListener("mousedown", ClickedJOL);
                        var d = window.setInterval(function GameTime(){
                            if(Timer > 0){
                                Timer--;   
                            } else if (Timer == 0){
                                window.clearInterval(d);
                            }
                        }, 1000);
                        function ClickedJOL(){
                            Score++;
                            ContentDivs[cd].setAttribute("style", "background-image:none; cursor: default;");
                            ContentDivs[cd].removeEventListener("mousedown", ClickedJOL);
                            while(cd == storecd){
                                cd = RandomContentDiv[Math.round(Math.random()*RandomContentDiv.length-1)];
                                console.log("Number: " + cd);
                            }
                            ContentDivs[cd].setAttribute("style", "background-image: url('./Images/JackLantern.png'); cursor: pointer;");
                            ContentDivs[cd].addEventListener("mousedown", ClickedJOL);
                            storecd = cd;
                        }
                    }
                }, 200);
            }, 100);
        }
    }

    function ContextMenu(e){
        e.preventDefault();
    }
}

// Resized.
function Resized(){
    var MainDiv = document.getElementsByClassName("main-div")[0];
    var CountdownNumbers = document.getElementById("countdown-numbers");
    var HalfScreenWidth = (screen.availWidth / 2);
    var HalfScreenHeight = (screen.availHeight / 2);

    // Width
    if(window.innerWidth <= HalfScreenWidth){
        MainDiv.style.width = HalfScreenWidth + "px";
    } else {
        MainDiv.style.width = "100%";
    }

    // Height
    if(window.innerHeight <= HalfScreenHeight){
        MainDiv.style.height = HalfScreenHeight + "px";
    } else {
        MainDiv.style.height = "100%";
    }

    // When CountdownNumbers Resizes.
    CountdownNumbers.style.top = "calc(50% - 50px)";
}

I put console.log(cd); to see what numbers are being outputted. I get results, but the results are not useful in solving the problem. I will test run the code 2 times to show you what I would typically get.

Test 1:

Number: 5
Number: 13
Number: 10
Number: 1
Number: 10
Number: 6
Number: 10
Number: 3
Number: 2
Number: 15
Number: 2
Number: 3
Number: 8
Number: 15
Number: 12
Number: 7
Number: 9
Number: 2
Number: 0
Number: 8
Number: 10
Number: 3
Number: 14
Number: 13
Number: 9
Number: 1
Number: 15
Number: 13
Number: 3
Number: 2
Number: 4
Number: 14
Number: 11
Number: 0
Number: 15
Number: 7
Number: 6
Number: 1
Number: 4
Number: 7
Number: 8
Number: 6
Number: 7
Number: 4
Number: 10
Number: 0
Number: 12
Number: 11
Number: 2
Number: 7
Number: 2
Number: 11
Number: 13
Number: 6
Number: 0
Number: 5
Number: 1
Number: 2
Number: 7
Number: 8
Number: 2
Number: 13
Number: 4
Number: 3
Number: 7
Number: 15
Number: 5
Number: 1
Number: 0
Number: 2
Number: 11
Number: 8
Number: 10
Number: 12
Number: 11
Number: 1
Number: 12
Number: 11
Number: 12
Number: 0
Number: 6
Number: 8
Number: 1
Number: 11
Number: 1
Number: 12
Number: undefined

Test 2:

Number: 13
Number: 2
Number: 9
Number: 0
Number: 2
Number: 0
Number: 11
Number: 3
Number: 5
Number: 3
Number: 11
Number: 3
Number: 14
Number: 15
Number: 9
Number: 8
Number: 11
Number: 12
Number: 10
Number: 3
Number: 9
Number: 0
Number: undefined

I think the problem is coming from this statement: RandomContentDiv[Math.round(Math.random()*RandomContentDiv.length-1)];, but I don't know how to fix it because I haven't dove deep enough in Math for JavaScript. All I know is that someone said something about Math.Round giving you an inaccurate number when rounded (i.e 1.5 could round to 1), but I don't think that it applies to this. Can anyone tell me if it is the statement that is causing the problem or something else?




Random Sentence Generator in Ruby : How to randomly select values on specific key in hash?

I'm working on a Ruby verison of RSG and somehow stuck on the sentence generating process (...)

so I managed to implement all functions like read, convert to hash...,etc. But problem is how to randomly pick values in hash to generate the sentence?

Now I have a hash here:

hash = {"<start>"=>[["The", "<object>", "<verb>", "tonight."]],
        "<object>"=>[["waves"], ["big", "yellow", "flowers"], ["slugs"]], 
        "<verb>"=>[["sigh", "<adverb>"], ["portend", "like", "<object>"],["die", "<adverb>"]], 
        "<adverb>"=>[["warily"], ["grumpily"]]}

The Objective is to assemble the strings using random values in the hash for example when the function iterates to "<object>", it will take it as a key and search in the hash to find matching key then randomly pick the corresponding values (one of the strings in "<object>"=>[["waves"], ["big", "yellow", "flowers"], ["slugs"]]) and assemble it, then the output would be something like this:

"The waves sigh warily portend like yellow die grumpily tonight" 

My code so far:

hash.each do |_, value|
  value.map{|x| x.map{|y| is_non_terminal?(y) ? (puts value.values_at("SomethingToPutInto")) : (puts y)}}
end

Somehow the logics in the code becomes too complicated and I'm stuck on this step.. Using values_at will cause TypeError: no implicit conversion of String into Integer (TypeError)

For is_non_terminal?(y) is just a function to check whether the string contains < and >:

def is_non_terminal?(s)
   s.include?('<' && '>') ? true : false
end




How to randomly take 4 pieces out of 13 categories in excel?

I might not have the best title but here is what I need. For these 13 categories, I have 74 racks in total. I will have 12 trucks to pick up the racks throughout the day and each truck will take 5/6 racks in average and 10 racks maximum. I need to figure out a way to divide these 74 racks to 12 different orders with random mix and not so random amount. Ideas will be appreciated.

adjusted # racks

A 1 B 1 C 1 D 2 E 3 F 3 G 4 H 5 I 6 J 7 K 15 L 18 M 8




How to generate a random Integer between two values in Eiffel?

I want to simulate dice roll functionality. However, I don't get what I expect. I want to get a Dice with value ranging from 1 to 6 inclusively (dice).

I tried to find it in Eiffel Documentation, but it is very hard to do.




C# picking unique numbers from an array

I am new to this forum and new to C# programming so please bare with me :-)

I am needing help with writing a section of code that will pick unique numbers from an array. For example, I have an array with 10 numbers from 1-10. how do I get my program to cycle through each of the of the numbers in the array randomly say every 10 sec, but only picking each one once.

Thanks in advance for your help.




Visual Basic- Random Numbers

I'm trying to generate 5 random numbers from 1-99 and display them in a ListBox. Can someone tell me where I'm going wrong? Right now my code is displaying all 99 numbers in the ListBox, but I only want 5 of them to display. Here is the code:

'list to store numbers
        Dim numbers As New List(Of Integer)

        'add desired numbers to list
        For count As Integer = 1 To 99
            numbers.Add(count)
        Next


        Dim Rnd As New Random
        Dim SB As New System.Text.StringBuilder
        Dim Temp As Integer

        'select a random number from the list, add to listbox and remove it so it can't be selected again
        For count As Integer = 0 To numbers.Count - 1
            Temp = Rnd.Next(0, numbers.Count)
            SB.Append(numbers(Temp) & "  ")
            ListBox2.Items.Add(numbers(Temp))
            numbers.RemoveAt(Temp)
        Next




Modulo if statement not producing expected output

I have coded a math problem prompter. And want to make sure that in the case of division. the outcome is only whole numbers and not being divided by 0. Using the following code.

while tries < problems:
    print("What is ....")
    print()
    num1 = random.randint(0,9)
    num2 = random.randint(0,9)
    operation = random.randint(1,4)
    if operation == 1:
        op = '-'
    if operation == 2:
        op = '+'
    if operation == 3:
        op = '/'
        while num2 == 0 or num1%num2 > 0:

               num1 = random.randint(0,9)
               num2 = random.randint(0,9)

However. The only problems that are generated are such that the answer is always 1. 0. or the numerator. For instance only: 4/1 5/1 6/1 or 0/5 0/6 0/6 or 3/3 2/2 1/1




An algorithm for creating a random matrix with non-adjacent non-zero entries (with some extra requirements)

It would be great if someone could point me towards an algorithm that would allow me to :

  1. create a random square matrix, with entries 0 and 1, such that
  2. every row and every column contain exactly two non-zero entries,
  3. two non-zero entries cannot be adjacent,
  4. all possible matrices are equiprobable.

Right now I manage to achieve points 1 and 2 doing the following : such a matrix can be transformed, using suitable permutations of rows and columns, into a diagonal block matrix with blocks of the form

1 1 0 0 ... 0
0 1 1 0 ... 0
0 0 1 1 ... 0
.............
1 0 0 0 ... 1

So I start from such a matrix using a partition of [0, ..., n-1] and scramble it by permuting rows and columns randomly. Unfortunately, I can't find a way to integrate the adjacency condition, and I am quite sure that my algorithm won't treat all the matrices equally.




Randomise list of words in variable

I have variable which is list of words separated by comma like this:

$word_list = "word1, word2, word3, word4, word5";

Word list can contain more or less words than in example above.

How to randomise $word_list to get something like this:

word1, word5, word2, word3, word4

or

word4, word5, word3, word1, word2




random_int generating values less than minimum

I am generating passwords with random_int, but I noticed something weird. Sometimes (purely random), it generates a password less than the minimum value. For example, I set 10 and 15 the limits and once every circa 50-70 tries it pops out a 2-3 character long password. Is there something wrong with my script? It's hard to reproduce the output, just refresh the script till you get a similar result.

<?php 

    $r_number = random_int( 10 , 15 );

    function random_str(
        $length,
        $keyspace = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ,./<>?;:"|[]{}-=_+`~!@#$%^&*'
    ) {
        $str = '';
        $max = mb_strlen($keyspace, '8bit') - 1;
        if ($max < 1) {
            throw new Exception('$keyspace must be at least two characters long');
        }
        for ($i = 0; $i < $length; ++$i) {
            $str .= $keyspace[random_int(0, $max)];
        }
        return $str;
    }

    $password = random_str($r_number);

    echo $password;

?>




Randomize Smarty array in foreach

I am trying to randomize the array 'Small', 'Medium' and 'Large' but do not have the point to implement inside my code.

My foreach code:

{foreach $Item->images as $image}
    {strip}
        <img src="{$image->Small}" />
    {/strip}
{/foreach}

Using {selectRandom(1, 2, 3, ...)} was not the solution. Should I assign at first the arrays and than call them?

Any ideas what else I can use?




(micro)python random module importError

I want to generate a random number between x and y int (micropython for esp), but

import random

gives the following error:

ImportError: no module named 'random'

I've seen some things online about this but no concrete solution. Does anyone have any idea how to fix this?

Thanks!




Random .mp3 songs

I've got this javascript code (it works fine but i would like to play the songs random)... The songs are 20. Can you help me? Have you got any suggestions? Thanks... This is the code

 <script>
var audio;
var playlist;
var tracks;
var current;

init();
function init(){
    current = 0;
    audio = $('audio');
    playlist = $('#playlist');
    tracks = playlist.find('li a');
    len = tracks.length - 1;
    audio[0].volume = .10;
    playlist.find('a').click(function(e){
        e.preventDefault();
        link = $(this);
        current = link.parent().index();
        run(link, audio[0]);
    });
    audio[0].addEventListener('ended',function(e){
        current++;
        if(current == len){
            current = 0;
            link = playlist.find('a')[0];
        }else{
            link = playlist.find('a')[current];    
        }
        run($(link),audio[0]);
    });
}
function run(link, player){
        player.src = link.attr('href');
        par = link.parent();
        par.addClass('active').siblings().removeClass('active');
        audio[0].load();
        audio[0].play();
}
</script>




elasticsearch: get random distinct field values?

We have elastic search document with dealerId "field". Multiple documents can have the same "dealerId". We want to pick "N" random dealers from it.

What I have done so far: The following query would return max 1000 "dealerId" and their count in descending order. We will then randomly pick "N" records client side.

    {
      "from":0,
      "size":0,
          "aggs":{
            "CityIdCount":{
              "terms":{
                "field":"dealerId",
                "size":1000
              }
            }
          }
     }

The downside with this approach is that:

  1. If in future, we have more than 1K unique dealers, this approach would fail as it would pick only top 1K dealerId occurence. What should we put as "size" for this?
  2. We are fetching all the data although we just require random "N" i.e. 3 or 4 random "dealerId" from elastic server to the client. Can we somehow do this randomization in elastic query itself?

I have read something similar here but trying to check if we have some solution for this now.




tf.estimator shuffle - random seed?

When I repeatedly run tf.estimator.LinearRegressor the results are slightly different each time. I'm guessing that's because of the shuffle=True here:

input_fn = tf.estimator.inputs.numpy_input_fn(
    {"x": x_train}, y_train, batch_size=4, num_epochs=None, shuffle=True)

Which is fine as far as it goes, but when I try to make it deterministic by seeding the random number generators in both np and tf:

np.random.seed(1)
tf.set_random_seed(1)

The results are still slightly different each time. What am I missing?




dimanche 29 octobre 2017

choose a file randomly in java

Hi I've been studying java for three weeks and doing a tutorial, where I am trying to emit two kinds of sound randomly using 'Clip' and 'File'. I am thinking of choosing a file randomly but I don't know how. I succeeded to emit sounds by using PlaySound method but can't go further.

Here is my code, which emits only one sound Kurzweil1.

import java.io.File;
import javax.sound.sampled.AudioSystem;
import javax.sound.sampled.Clip;

public class Tutorial {

public static void main(String[] args) {
    // TODO Auto-generated method stub
File Kurzweil1 = new File("C:\\Users\\ponnp\\Downloads\\Kurzweil-K2000-Dual-Bass-C1.wav");
File Kurzweil2 = new File("C:\\Users\\ponnp\\Downloads\\Kurzweil-K2000-Grand-Strings-C3.wav");

PlaySound(Kurzweil1);           
}

static void PlaySound(File Sound) 
{
    try {
        Clip clip = AudioSystem.getClip();
        clip.open(AudioSystem.getAudioInputStream(Sound));
        clip.start();

        Thread.sleep(clip.getMicrosecondLength()/1000);
    }catch(Exception e)
    {           

    }
}

}




making a bingo game and everyone has the same number

I'm making a programme that creates a bingo card for 100 people and gives them all different numbers. but just now the code that i have is giving everyone the exact same 15 numbers. any help would be greatly appreciated, thanks.

  Structure Number
        Dim number As Integer
    End Structure
    Structure Player
        Dim name As String
        Dim numbers() As Number
        Dim numbers_left As Integer
    End Structure
    Dim players As New List(Of Player)
    Dim selectednumber As Integer
    Dim used As New List(Of Integer)
    Dim random As New Random
    Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
        Dim Number As Number
        Dim player As Player
        ReDim player.numbers(14)

        For i = 1 To 100
            For j = 0 To 14
SelectNumber:   Number.number = random.Next(1, 101)
                If player.numbers IsNot Nothing Then
                    For Each item In player.numbers
                        If item.number = Number.number Then
                            GoTo SelectNumber
                        End If
                    Next
                End If
                player.numbers(j).number = Number.number
            Next
            player.name = ("Bill" & i)
            player.numbers_left = 15
            players.Add(player)
        Next

    End Sub




Multiple Random Numbers

Hey how can i make the col1 random on each vehicle created it can be same on some but not all of them can have the same color.

Random r = new Random();

col1 = r.Next(0, 159);

CreateVehicle(-614, -352, 34,col1, col2, 0);
CreateVehicle(-614, -352, 34,col1, col2, 0);
CreateVehicle(-614, -352, 34,col1, col2, 0);
CreateVehicle(-614, -352, 34,col1, col2, 0);
CreateVehicle(-614, -352, 34,col1, col2, 0);
CreateVehicle(-614, -352, 34,col1, col2, 0);
CreateVehicle(-614, -352, 34,col1, col2, 0);
CreateVehicle(-614, -352, 34,col1, col2, 0);
CreateVehicle(-614, -352, 34,col1, col2, 0);
CreateVehicle(-614, -352, 34,col1, col2, 0);




Random point inside annulus with a shifted hole

First of all, will appreciate if someone will give me a proper term for "annulus with a shifted hole", see exactly what kind of shape I mean on a picture below.

Back to main question: I want to pick a random point in the orange area, uniform distribution is not required. For a case of a usual annulus I would've picked random point in (r:R) range and a random angle, then transform those to x,y and it's done. But for this unusual shape... is there even a "simple" formula for that, or should I approach it by doing some kind of polygonal approximation of a shape?

I'm interested in a general approach but will appreciate an example in python, javasctipt or any coding language of your choice.

shifted annulus




Generating Random Numbers Once in Java

I would like to generate random numbers in range [0,6] and only get each number once. For example: 3,4,2,1,5,6,0. How can i implement this in Java without using ArrayList and shuffle methods.An if-statement in which i will be checking the repetition of the numbers would take forever in a longer range i think.

int[][] ts=new int[4][7];
for(int i=0;i<4;i++){
for(int j=0;j<7;j++){
//ts[i][j]=Random in [0,6] once
}
} 




Run a function with a random list element

from roles import Herbalist, Warrior

def makeRolesAct(listOfTheRoles):
    y = 0
    for role in listOfTheRoles:
        print("Role", y, role.describe())
        print(role.act())
        y+=1

def main():
    listOfTheRoles = []
    listOfTheRoles.extend([Warrior('axe', 'dragon'), Herbalist(), Warrior('hammer', 'horse')])

    for x in range(5):
        makeRolesAct(listOfTheRoles)

if __name__ == '__main__':
    main()

describe() describes a role of the current actor. act() makes the actor do his action.

I'd like makeRolesAct() to run with a random listOfTheRoles element. So if I had the function in a loop it would repeat with actions repeating for randomly chosen actors.




need to select random word from each list [duplicate]

This question already has an answer here:

I am new to java and I am struggling with this assignment. The method shoutOutCannedMessage() will return the selected message string. Your shoutOutRandomMessage() method should use a random number generator that selects one word from each data structure to form a random message. The random number generated should not exceed the bounds of your data. In other words, if you only have 5 words in a data structure, the random number generated should not be an index that has no word stored. The method shoutOutRandomMessage() should return a randomly generated message string in accordance with specifications, in the following form: Subject - Verb - Adjective - Object - Adverb (for example, “You read hard books quickly”). Where I am having an issue is how to call a random word from each list. Here is what I have so far. Please forgive me as I am new to Java.

package virtualworld;
import java.util.*;
/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
/**
 *
 * @author SClough
 */

public class Randomwords {


public static void main(String[] args) { 

}

      //holds the words to be generated.

      String[] subject= {" She", " Cat", " School", " Home", " They" };
      String[] verb= {" working", " sleeping", " eating", " playing"," studying" };
      String[] adjective= {" brainy", " calm", " determined", " encouraging", " graceful" };
      String[] object= {" class", " cookie", " book", " flower", " puddle"};
      String[] adverb= {" correctly. ", " loudly. ", " quickly. ", " eagerly. ", " carefully. "};


       Random rand = new Random();//intialize a Random


      //randomly create sentence.




     System.out.println( +randomSentence );

      }




C# - Guessing game - Colder, cold, warm, warmer, hot, very hot

I've killed so many hours for something almost insignificant. I just don't know how to continue with this matter. I did this whole guessing game thing here, but what I need to do to finish it is to make it say if it's warm, hot, cold, colder, etc when the guess comes closer or farther from the randomly generated number. The "warm,hot, cold" part from the code is just to understand, but I actually need to make it more complicated and add these:

<= 3 - very hot

<= 5 - hot

<= 10 - warmer

<= 20 - warm

<= 50 - cold

<= 99 - colder

        int number; 
        Random n = new Random();
        int guessNumber = n.Next(1, 100);
        uint entries = 0;
        int difference = 0;

        Console.WriteLine("It's time to choose Mr.Freeman. Pick a number between 0-100.");
        do
        {
            do
            {
                number = int.Parse(Console.ReadLine());
                if((number < 0) || (number > 100))
                {
                    Console.WriteLine("The number must be between 0 and 100.");
                }
            }
            while ((number < 0) || (number > 100));
            Console.WriteLine(guessNumber);

            if(number > guessNumber)
            {
                difference = (guessNumber - number);
            }
            else if (number < guessNumber)
            {
                difference = (number - guessNumber);
            }

            int onlyPositive = Math.Abs(difference);

            if (number == guessNumber)
            {
                Console.WriteLine("Splendid Mr.Freeman. You are indeed lucky.");
            }
            else if ((onlyPositive - number) <= 50)
            {
                Console.WriteLine("Cold! Try again!");
            }
            else if ((onlyPositive - number) <= 25)
            {
                Console.WriteLine("Warm! Try again!");
            }
            else if ((onlyPositive - number) <= 10)
            {
                Console.WriteLine("Hot! Try again!");
            }

            entries++;

        }while (number != guessNumber);


        Console.WriteLine("Entries : " + entries);
        Console.ReadLine();




php value from random function to stay same after page refresh

is there a way that when I use the random function to get a list of random strings to display, it will stay even after i refreshed the page?

Such as this code:

$a = array("red","green","blue","yellow","brown");
while (............){
    $random_keys = array_rand($a);
    echo $random_keys;
}




Why is this Math.random() statement set out in this format?

I'm complete beginner to Java so I am sorry for what is probably a very stupid question. This is a programme for guessing two random numbers. Why is the Math.random followed by "* (MAX + 1 - MIN))) + MIN;". Also how does the Math.random know to generate a number between 1 and 3 and not anything higher?

  Scanner scan = new Scanner(System.in);
  final int MIN = 1, MAX = 3;
  int firstAnswer = ((int)(Math.random() * (MAX + 1 - MIN))) + MIN;
  int secondAnswer = ((int)(Math.random() * (MAX + 1 - MIN))) + MIN;
  int firstGuess, secondGuess;

Thanks for your help!!




Swap Random Vowels in Python

How can I swap the random vowels in python of below sentence.?

The quick brown fox jumped over the lazy dog




Is it possible to generate a random number that the user cannot manipulate without a connected service?

I figure that generating random numbers offline has a similar situation to the "keeping the key and the lock on the client" problem -- if you seed the generator with a timestamp on the client then the user can manipulate the time. ex. http://ift.tt/2hlLL88




Adding multiple .random classes to multiple divs without a duplication

Trying to add a random class to two classes (.left & .right) but with a rule of the two random divs cannot appear at the same time

JS:

$(document).ready(function(){
var classes = ['random-1','random-2', 'random-3']; //add as many classes as u want
var randomnumber = Math.floor(Math.random()*classes.length);

$('.left').addClass(classes[randomnumber]);
});

HTML:

<div class="left">
  Left
</div>

<div class="right">
  Right
</div>


.left {
  background: blue;
  height: 100vh;
  width: 50%;
  float: left;
  position: relative;
}
.right {
  background: red;
  height: 100vh;
  width: 50%;
  float: right;
}

  .random-1 {
     background: orange;
  }
  .random-2 {
     background: yellow;
  }
  .random-3 {
     background: pink;
  }
  .random-4 {
     background: green;
  }
  .random-5 {
     background: blueviolet;
  }

Ideal result would be

<div class="left random-1">
  Left
</div>

<div class="right random-4">
  Right
</div>

http://ift.tt/2hlzsZu




samedi 28 octobre 2017

How do I convert the double to vector in matlab?

I have a function which only take vector as input; however, I need to use rand(x) as input variable but rand function only returns a double type. Is there any way to convert double to vector?? Thank you very much!




Visual Basic Random Number

I'm trying to create a random number generator (lottery). I have the random numbers generating, but I want to loop through the numbers that are checked in my CheckedListBox. It returns my last number checked, but not the others. Any suggestions?

Public Class Form1
    Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load

    End Sub

    Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
        Dim number1 As Integer
        Dim number2 As Integer
        Dim number3 As Integer
        Dim number4 As Integer
        Dim number5 As Integer
        Dim lottoPick As Integer = 0
        Dim i As Integer
        For i = 0 To LotteryBox.Items.Count - 1
            If (LotteryBox.GetItemChecked(i) = True) Then
                lottoPick = lottoPick + 1
                LabelOutput.Text = (LotteryBox.Items(i))
            End If

            Randomize()
        '     The program will generate a number from 0 to 99                
            number1 = Int(Rnd() * 99) + 1
            number2 = Int(Rnd() * 99) + 1
            number3 = Int(Rnd() * 99) + 1
            number4 = Int(Rnd() * 99) + 1
            number5 = Int(Rnd() * 99) + 1
        Next
        LabelOutput.Text += number1.ToString() + " " + number2.ToString() + " " + number3.ToString() + " " + number4.ToString() + " " + number5.ToString()
    End Sub
End Class




What is the true difference between set.seed(n) and set.seed(n+1)

I am working on figure out how the set.seed() function work in R. I am curious that is set.seed(3) and set.seed(4) more likely to generate duplicate sample than set.seed(3) and set.seed(100)? If yes, how many unique sample set.seed(3) can generate before match the sample generated by set.seed(4)? If not, can I conclude that the different n in set.seed(n) does not mean anything as long as they are different? I heard something related to independent random stream? Is this n related to that? If yes, how can I define a independent random stream?




Open files in specific and random order?

I want to open a certain .mp4 file and then open a file sceneB or sceneC.

If sceneB is selected, then I would then like it to open a random file between three choices (sceneD, sceneE, or sceneF). If sceneC is selected, I would like it to randomly open one of three choices (sceneG, sceneH, or sceneI).

Does anyone know of a link or tutorial that can help me figure this out? Am I going about this completely wrong?

Here is my code so far.

import os

#2 define scene

sceneA = "C:\Users\david\Pictures\Camera Roll\\1.mp4"
sceneB = "C:\Users\david\Pictures\Camera Roll\\2.mp4"
sceneC = "C:\Users\david\Pictures\Camera Roll\\3.mp4"
sceneD = "C:\Users\david\Pictures\Camera Roll\\4.mp4"
sceneE = "C:\Users\david\Pictures\Camera Roll\\5.mp4"

etc...

#3 choose scene order

os.startfile(sceneA)




Basic Roll the Dice number generator [duplicate]

This question already has an answer here:

Hello im very new to C# and coding, so need some basic help. If the user chooses to roll multiple dices, (2,3,4,5,6,7,8 etc), what do you do to make it roll randomly on all the dices? For example: "Dices rolled: 2,5,3". Instead of it now being "Dices rolled: 2,2,2", or "4,4,4", basiaclly the same number.

 static int RollTheDice(Random rndObject)
    {
        Random dice = new Random();
        int nr = dice.Next(1, 7);  // if user requests to roll multiple dices how
                                   // do you make all the rolls random and not the same


        return nr;
    }

    static void Main()
    {
        Random rnd = new Random();
        List<int> dices = new List<int>();

        Console.WriteLine("\n\tWelcome to the dicegenerator!");


        bool go = true;
        while (go)
        {
            Console.WriteLine("\n\t[1] Roll the dice\n" +
                "\t[2] Look what you rolled\n" +
                "\t[3] Exit");
            Console.Write("\tChoose: ");
            int chose;
            int.TryParse(Console.ReadLine(), out chose);

            switch (chose)
            {
                case 1:
                    Console.Write("\n\tHow many dices do you want to roll?: ");
                    bool input = int.TryParse(Console.ReadLine(), out int antal);

                    if (input)
                    {
                        for (int i = 0; i < antal; i++)
                        {
                            dices.Add(RollTheDice(rnd));
                        }
                    }
                    break;
                case 2:
                    Console.WriteLine("\n\tDices rolled: ");
                    foreach (int dice in dices)
                    {
                        Console.WriteLine("\t" + dice);
                    }
                    break;
                case 3:
                    Console.WriteLine("\n\tThank you for rolling the dice!");
                    Thread.Sleep(1000);
                    go = false;
                    break;
                default:
                    Console.WriteLine("\n\tChoose between 1-3 in the menu.");
                    break;




High Quality Random Algorithm in C#

.Net Random.Next()

this Regular Random.Next() calculates all random numbers when program started as you can see in picture. How can I improve to getting random algroithm or in that situation is it safe? I'll use it in a important project. If someone can know randoms before generated with that Random.Next() algorithm ?




Creating a dataframe using pandas and random module

I want to create a dataframe using pandas where 1 column is 'EmployeeID' and the second one is 'skill' set he has ranging form 1 to 5. The 'EmployeeID' column should have unique values whereas the 'skill' column can have repetitive values. 1. I tried to generate the 'EmployeeID' using the below code:

    df = pd.DataFrame({'EmployeeID':[random.sample(range(123456,135000),100)]})

but the result is not what i expected. It generated all the numbers and put them in one row

enter image description here

  1. Random.sample is giving me unique values. How can i generate 100 repetitive values in a given range? Tried using randint but it doesn't have the option of passing the count of numbers to generate



Generating random numbers in c which does not overlap with another range of random numbers

I'm new to programming and just started to learn c. I was hoping to create a simple battleship game but then I face a problem while generating random numbers. I wants to generate a random number that doesn't overlap with another range of number. Let's say I got 40 as my first random number and I don't want 40, 41, 42, 43 and 44 to appear again. So following is my code, I can't figure out what's wrong with it.

srand(time(NULL));
    for(counter = 0; counter < ship_num; counter++){
        checked = 0;
        while (!checked){
            ship_x[counter] = 1 + rand()%56;
            ship_y[counter] = 1 + rand()%20;
            checked = 1;
            for(check = 0; check < counter; check++){
                if(ship_y[counter] == ship_y[check]){
                    int check_x = ship_x[check] + 5;
                    if(ship_x[counter] >= ship_x[check] && ship_x[counter] <= check_x){
                        checked = 0;
                    }
                }
            }
        }
    }

All the variable is defined so I won't define it again here.




How to get a random number in a specific range for C++? [duplicate]

This question already has an answer here:

I have been programming in python for 2 years and recently started learning C++. In python we can use random.randint(32,122) to generate a random which in this case is between 32 and 122. I am aware of rand() in c++ but it requires seeds from the time which can cause duplicates. It also doesn't allow a minimum value as far as i am aware only a maximum. If anyone can help it'd be appreciated. If it helps these numbers will be used in an encryption program so the random number will represent an ASCII key hence the 32 to 122, it is very much needed to not get duplicates. Thanks.




Javascript throw 3 dice even spread

Simulate throwing 3 dice. Tried using

function getRandomInt(min, max) {
    return Math.floor(Math.random() * (max - min + 1)) + min;
}

function dorand2(){
    var odice = document.getElementById("dice");
    var a = 1;//tried without this too just 1 to 6
    var b = 6 * a;
    var r1 = 1+ Math.floor(getRandomInt(1, b)/a);
    var r2 = 1+  Math.floor(getRandomInt(1, b)/a);
    var r3 =  1+ Math.floor(getRandomInt(1, b)/a);
    odice.innerHTML = "Dice A : " + r1 + " &nbsp;  &nbsp; Dice B : " + r2  + " &nbsp;  &nbsp; Dice C : " + r3;
}

Get same numbers for 1 or more in many tries. Am sure its even across runs. But looks odd, that out of 3 dice, get 5 on two of them, then next time 2 on two of them next turn... rarely are all 3 different. Would expect them to be different at least half the time?

Working sample: http://ift.tt/2zWvluz




vendredi 27 octobre 2017

JavaScript - My for loop in a quote machine won't .push() a variable from another for loop into an array

I'm trying to make a weighted random number generator for a quote machine, which, if a certain item is picked, one from another set is picked without having to go in and alter all of the numbers.

Essentially, there's a main array of quotes, with numbers mixed in. These numbers correspond to lists, and they need to be more likely to be picked depending on how many items are in the list. (e.g. If 1 is picked, and corresponds to an array with ten items in it, then it should be ten times as likely to be picked as a string, because it corresponds to ten strings.)

So, I decided to convert the index from a simple unbiased random number generator into what is essentially a raffle ticket machine run by a random number generator, in which each item in the main array puts one "ticket" (or their index number for every string they have. For example, if we use the one from earlier and two other strings, it should work something like this:

input=["I am a string!",1,"Me Too!"];

output=[0,1,1,1,1,1,1,1,1,1,1,2];

A number is then randomly chosen from the output array, which then corresponds to an item in the main array. If 1 is chosen, then a string is chosen from the array 1 corresponds to.

But I plan to have a LOT of items in it. I already have upwards of forty, and plan on adding more, so I made something that makes the output array for me. The only problem is, it doesn't work right. It should output [0,1,2,3,3,3,4,6,6,6,6,7],instead it outputs [3,3,3,7,7,7,7].

//main array
var main=["one","two","three",1,"fourth",2,"fifth",3]
//array corresponding to 1
var first=["a","b","c"];
//array corresponding to 2. 2 will not be par of this array
var second=["1","2","3"];
//array corresponding to 3
var third=["red","yellow","green","blue"];
//weights
var weights=[];
//weight pusher
for (var i = 0; i < main.length; i++) {
  //weight adder
  if (!Number.isNaN(main[i])) { 
    switch (main[i]) { //If it gets to this point, main[i] should be 1, 2, or 3.
      case 1:
        //add i to the array once for every item in first (three times)
        for (var j = 0; j < first.length; j++) {
          weights.push(i)
        }
        break;
      case 2:
        //do nothing
        break;
      case 3:
        //add i to the array once for every item in third (four times)
        for (var j = 0; j < third.length; j++) {
          weights.push(i)
        }
        break;
        
    }
  }else {
    //If it's a regular string, add one i to the array.
    weights.push(i);
  };
};
console.log(weights); //Should output [0,1,2,3,3,3,4,6,6,6,6,7],instead outputs [3,3,3,7,7,7,7]



Python index of a random number in a list?

So I've looked for help elsewhere but couldn't find any solution. I've created a list with 51 elements and would like to pick 10 random, different positions within that list and be able to change the value at those positions(you can see this under the assignCard(person) function). Since I am using the index of the numbers I can't use methods such as random.sample or put the random numbers into a set() because I get an error message. Ive posted my code below, feel free to copy and run it to view the output, everything works except for the repeating numbers so if possible please do not change the code drastically in your answer. Thanks.

""" cardGame.py
    basic card game framework
    keeps track of card locations for as many hands as needed
"""
from random import *
import random

NUMCARDS = 52
DECK = 0
PLAYER = 1
COMP = 2

cardLoc = [0] * NUMCARDS
suitName = ("hearts", "diamonds", "spades", "clubs")
rankName = ("Ace", "Two", "Three", "Four", "Five", "Six", "Seven", 
            "Eight", "Nine", "Ten", "Jack", "Queen", "King")
playerName = ("deck", "player", "computer")

def main():
  clearDeck()

  for i in range(5):
    assignCard(PLAYER)
    assignCard(COMP)

  print(cardLoc)

  print("#  " + " card      " + " location")
  showDeck()
  print("\nDisplaying player hand:")
  showHand(PLAYER)
  print("\nDisplaying computer hand:")
  showHand(COMP)

def clearDeck():
    cardLoc = [0] * NUMCARDS

def assignCard(person):
  x = random.randint(0, 51)
  cardLoc[x] = person

def showDeck():
  for i in range(NUMCARDS):
    y = rankName[i % 13]
    z = suitName[int(i / 13)]
    a = cardLoc[i]
    b = playerName[a]
    print("{:<4}{:<4} of {:<14}{:<7}".format(str(i), y, z, b))

def showHand(person):
  for i in range(NUMCARDS):
    if cardLoc[i] == person:
      print(rankName[i % 13] + suitName[int(i / 13)])

main()




Python: Generate Numbers Based on a Numberical Input

So, quick description as to what I'm trying to do. The code would take an input from the user (a number, like 4) and generate random numbers. These numbers would then be converted to a string.
I'm using randint to generate the numbers, but I get errors when running it.

from random import *
def randomname():
    ag = input("Input a number: \n")
    count = int(ag)
    name = []
    for i in count:
        num = randint(65, 126)
        name.append(num)
        count -= 1
    print(name)

When running this code as-is, I get this error code:

Traceback (most recent call last):  
File "C:/Users/Andrew/Documents/randomname.py", line 11, in <module> 
    randomname()  
File "C:/Users/Andrew/Documents/randomname.py", line 6, in randomname  
    for i in count:
TypeError: 'int' object is not iterable

If anyone could provide an answer/fix to my issue I'd love it.
I'm fairly certain I can do the converting bit myself.

edit: formatting




Sort an array by swaping random positions

I need to do the following: I was given an array with random integers. My task now is to sort the array so that the smallest int comes first and the greatest int at the end of the array. I need to do this by using a rather strange method: As long as the array isn't sorted, take two different random positions in the array and swap them. I then need to print out how many times it swapped two positions. So I've tried to implement that but I doesn't seem to work:

int[] values = new int[] { 50, 10, 20, 4, 5, 1, 5 };
int steps = randomSort(values);

public static int randomSort(int[] values) {
    int steps = 0;
    Random r = new Random();
    int l = values.length;

    sorted = checkIfSorted(values);
    if(sorted = true) {
        return steps;
    } 

    // sort the array
    while(sorted = false) {
        int v = 0;
        int x = r.nextInt(l);
        int y = r.nextInt(l);

        while(x == y) {
            y = r.nextInt(l);
        }

        v = values[x];
        values[x] = values[y];
        values[y] = v;

        sorted = checkIfSorted(values);

        steps = steps + 1;
    }



    return steps;
}

public static boolean checkIfSorted(int[] values) {
    for(int i = 0; i < values.length; i++) {
        if(values[i] > values[i+1]) {
            return false;
        }
    }
    return true;
}

I'm fairly new to Java programming, so I might have made some stupid mistakes xD




How do I avoid specific 3 element combinations using rand and split function?

I have a variable with 7 elements and I need to select 3 elements at random, but here are specific 3 element combinations i want it to avoid. How do I code this? (ex. I need it to avoid the combination [2,5,7] and [1,3,6])

This is what i have so far:

var Allregions = [
'1'
'2'
'3'
'4'
'5'
'6'
'7']


var ShowRegions = [];
    do {
      ShowRegions [ShowRegions.length] = Allregions.splice(
                            Math.floor(Math.random() * Allregions.length)
                          , 1)[0];
} while (ShowRegions.length < 3);




Classification with Neural networks

I am working on big data classification. I have tested many classifiers on big datasets. At the end, I have noticed that two classifiers achieved the best results but with long running time (Bagging & Random Tree). My question is: I want to modify Random Tree to use neural networks, but I want to know before I wast a lot of time on programming for nothing, which type of neural networks should I use for improving the classifier results and running time?

  • Deep learning
  • backpropagation
  • stochastic gradient descent
  • or a combination between them

=======

Thanks in advance for everyone in StackOverflow they are the best




Random int array not printing min and max

I am new to Java (and coding in general). I need to write a method that gets an integer, creates an array made of random numbers of the length of the integer, range 1-50 (inclusive) and finds the maximum and minimum number.

I was able to fill the array with random numbers. However, my min and max are not printing. I have been looking at this for hours with no luck - any advice would be very helpful! Thank you.

import java.util.Scanner;
import java.util.Random;
class MinMax {
  public static void main(String args[]) {

    Scanner in = new Scanner(System.in);
    //user input a number
    System.out.println("Please enter an integer from 1 to 50: ");
    int userNum = in .nextInt();
    System.out.println();

    int x;
    int randNum;
    int y;
    //create random numbers and print
    Random r = new Random();
    for (int i = 1; i <= userNum; i++) {
      randNum = r.nextInt(50) + 1;
      System.out.println(randNum);
      int[] array = new int[userNum];
      for (x = 1; x < 1; x++) {
        array[x] = randNum;
        System.out.println(array[x]);
        //find max
        int largest = array[0];
        int smallest = array[0];
        for (int s = 0; s < array.length; s++) {
          largest = array[s];
          smallest = array[s];
          if (array[s] > largest) {
            System.out.println(largest);
            //find min
          } else if (array[s] < smallest) {
            System.out.println(smallest);


          } //for
        } //if
      } //for
    } //for


  } //main method
} //class



how to create a random list with vaues that are allowed to exist serveral times

I want to create a random list with 100 elements. So far, so good...

Example 1: works fine, because the function has a range which is big enough not to repeat any value

list = random.sample(range(1,200),100)

Example 2: Does not work, because the range is to small (Sample is larger than population)

list = random.sample(range(50,80),100)

I am looking for a solution how to create that random list with more values than the range and it is no Problem that the elements exists several times.

Thanks for your answers !




jeudi 26 octobre 2017

how to count how many iterations it takes to get a random number equal to user input and calculate that average in C?

Using nested loops, We have to create a program that takes a number in range of 0-99 from the user and use a seeded random number generator to try and guess the number. We have to keep track of how many numbers the RNG generates before it generates the user's number. We have to also do this process 50 times to then calculate the average number of tries it takes the RNG to guess our number. This is all i have so far and i'm stumped:

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

int main()
{
    srand(time(NULL));

    int userInput;
    int randoms = rand() % 100;
    int numCalls;
    int i;
    float average = 0.0;

    printf("Please enter a number in between 0 and 99: ");
    scanf(" %d", &userInput);

    for( i = 0; i < 50; i++)
    {

        while (userInput != randoms);
        {

           numCalls = numCalls + 1;

           if (userInput = randoms)
           {
               float average = numCalls/50.0;

           }
        }
        printf("Number of iterations it took for a matching number: %d\n", numCalls);
        printf("Average number of iterations to find a match: %.2f\n", average);

    }

return;
}




Power law random number generator mirror image histogram

I'll be happy to erase this question hopefully after getting some tips. I am trying to follow this post to generate power-law distributed values following the equation from Wolfram MathWorld:

enter image description here

I used R, although the code could be easily translated into any other language:

x1 = 8
x0 = 0
n = 2.5
y = runif(1e5)
x = ((x1^(n+1) - x0^(n+1))*y + x0^(n+1))^(1/(n+1))
hist(x)

enter image description here

yielding a histogram symmetrical to what I expected.

What am I missing?




Generating Random Numbers between a range

So, i'm attempting to generate a random number between 1 and 61 using an overloaded parenthetical operator, however for some reason every time I run my code, I keep getting the same result of 49.

Here's what I have:

double operator()() const
    {
        std::uniform_int_distribution<int> _uniformIntDistribution(1, 61);
        std::default_random_engine _generator;

        double result;

        result = _uniformIntDistribution(_generator);



        return result;
    }

Not sure what i'm doing wrong. Any suggestions?

Thanks in advance!




JavaScript random item from an imported array behaving strangely

The following code seems to be behaving strangely. Basically, I'm importing a list of line-separated sentences from a text file, then making an array out of them. But when I try to choose a random sentence from the array, it doesn't work because sentenceString becomes undefined.

However, when I run Math.floor(Math.random() * (sentenceArr.length) + 1); I get a nice random number as expected.

And when I run sentenceArr.length I get the number 12, which is indeed the length.

What am I missing?

    var sentenceArr = [];

    $.get('sentences.txt', function(data){
        sentenceArr = data.split('\n');
    });

    var rand = Math.floor(Math.random() * (sentenceArr.length) + 1);

    var sentenceString = sentenceArr[rand];

    var sentence = sentenceString.split(' ');




How do I prevent two of the same random numbers being generated from two different variables in Python?

I have posted my code below, I am stuck on the assignCard(person) function. I want to print out 10 random numbers; 5 for the variable x and 5 for the variable y. How can I prevent x from equaling y?

""" cardGame.py
    basic card game framework
    keeps track of card locations for as many hands as needed
"""
from random import *
import random

NUMCARDS = 52
DECK = 0
PLAYER = 1
COMP = 2

cardLoc = [0] * NUMCARDS
suitName = ("hearts", "diamonds", "spades", "clubs")
rankName = ("Ace", "Two", "Three", "Four", "Five", "Six", "Seven", 
            "Eight", "Nine", "Ten", "Jack", "Queen", "King")
playerName = ("deck", "player", "computer")

def main():
  clearDeck()

  for i in range(5):
    assignCard(PLAYER)
    assignCard(COMP)

  print(cardLoc)

  #showDeck()
  #showHand(PLAYER)
  #showHand(COMP)

def clearDeck():
    cardLoc = [0] * NUMCARDS

def assignCard(person):
  x = random.randint(0, 53)
  y = random.randint(0, 53)
  if person == PLAYER:
    cardLoc[x] = 1
  elif person == COMP:
    cardLoc[y] = 2
main()




Random sample in R based on two probabiility vectors

Sampling in R is pretty straightforward, but I am stumbling on the following. I want to generate a random sample of one thousand 0's and 1's where each sample unit of 1 has its own probability of selection. The code I am using is as follows:

Sample <- sample (0:1, 1000, replace = T, prob = c(data$No, data$Yes))

Where data$No is the probability vector of the individual not doing action N with data$Yes being the probability vector that the individual will do it. Where No + Yes = 1

Each of the 1000 individuals has their own unique probability of doing the action.

I want to generate probable outcomes of doing the action based on each individuals unique probability. But R is fighting me every step of the way.




Python - function that changes one letter in a string [on hold]

I was wondering how to write a function that accepts one argument (a string), and returns the same string with one letter changed. So for instance: randomize(hello) would output 'hbllo'.

I was thinking about using list slicing but didn't really know where to start. Could anybody help me?




How do I randomize two links on one page?

i'm trying to have two links on one page that each have a different set of variable urls. i can only get one of the links to work my code looks like this:

<script type="text/javascript">
var url=[
'bear52.html',
'bear53.html'
]; 
window.onload=function()
{document.getElementById('trig').onclick=function(){
location.href=url[Math.floor(Math.random()*url.length)];}}
</script>
<a href="#" id="trig">
YOU OKAY?</a>


<BR><script type="text/javascript">
var url=[
'bear30a.html',
'bear31a.html'
]; 
window.onload=function()
{document.getElementById('trig').onclick=function(){
location.href=url[Math.floor(Math.random()*url.length)];}}
</script>
<a href="#" id="trig">
RUN AWAY</a>

any help?




Buffer overflow attack, possible to regenerate a random canary?

I'm working on a system security project with the topic: buffe roverflow attack. I do have a program and the sourcecode I should gain root permissions with. The problem I have is caused by a random canary, at the beginning ot the program the random number generator is initialized:

srand(time(NULL) ^ (getpid() << 16));

later on the canary gets set by

canary = rand();

My question: Is it possible to regenerate the canary? I would like to regenerate the salt (time(NULL) returns the time since 1970 in seconds and pid is constant as the program starts) and then get the canary by calling rand(). I'm not familiar with any script language and do not have a lot linux experience, so I hope not to waste time with a solution that would never work. Thank you in advance! :)




C++ random utility gets reinitialized, causing duplicated output

I have created a function within my utility namespace to generate a random number to prevent duplicate pieces of code. Unfortunately it not as random as it re initialize the variables each time it's called, so when i loop something it gets the same output from time(0) and so the same value.

As my experience is limited i don't know how to fix it, as a singleton can't being applied due to it not being a class.

#ifndef UTILS_INT_HEADER_INCLUDED
#define UTILS_INT_HEADER_INCLUDED

#include <iostream>
#include <random>
#include <ctime>

namespace utils
{
    static int random(int min, int max, int seed) {
        std::default_random_engine generator;
        generator.seed(seed);
        std::uniform_int_distribution<int> dist(min, max);
        return dist(generator);
    }

    static int random(int max) {
        return random(0, max, time(0));
    }

    static int random(int min, int max) {
        return random(min, max, time(0));
    }
}

#endif




Random Sort does not terminate

Assuming isAscSorted functions as expected (tested) I am doing something silly here which is why random swap never sorts the array - because it is only ever doing 1 swap each time on different arrays?

My test case is int[] values1 = new int[] { 50, 10, 20, 4, 5, 1, 5 };

Hints?

public static boolean isAscSorted (int[] arr){

    for (int i=0; i<arr.length-1; i++){
        if (arr[i]> arr[i+1]){
            return false;
        }
    }
    return true;
}


public static boolean swap(int[]a,int i,int j)
{
    if (i == j){
        return false;
    }
    int temp=a[i];
    a[i]= a[j];
    a[j]=temp;
    return true;

 }


static int randomSort(int[] values) {

    //Ok Array is empty or null
    if( values == null || values.length==0){
        return 0;
    }

    boolean isSorted = false;
    int steps = 0;
    Random r = new Random();
    int limit = values.length-1;


    while (!isAscSorted(values)){
        //choose 2 random positions
        int r1 = r.nextInt(limit);
        int r2 = r.nextInt(limit);

        //swap returns true if successful
        boolean swapRes = swap(values, r1,r2);

        //increment steps counter
        if (swapRes)
            steps++;

    }

    return steps;
}




Using the 1st random number to chose the initial state, X0, at random

I have this probability problem:

On any given day Eric is either cheerful (C), so-so (S), or glum (G).

If he is cheerful today, then he will be C, S, or G tomorrow with respective probabilities 0.5, 0.3, 0.2.

If he is feeling so-so today, then he will be C, S, or G tomorrow with probabilities 0.3, 0.4, 0.3.

If he is glum today, then he will be C, S, or G tomorrow with probabilities 0.2, 0.2, 0.6.

I have generated 50,000 independent pseudo-random numbers (uniform) in R and have printed out the first 40. Now, how do I use the 1st random number to chose the initial state X0 at random (1/3 probability for each state)? I know that this is equivalent to generating a discrete random variable, but I am still confused.




Randomly choose between calling two methods

I am creating a math game for my son that follows a story. I have two methods that will present him with a question. The first is named subtraction and second is named addition. Currently I just call a method at a certain point in the story, but I would prefer to randomly chose either the subtraction or addition method so it is less predictable.




Random position of elements within a defined range

I have three elements (div) within the body.

Each of them should have a randomly generated distance to the left edge of the viewport. In addition, each element should maintain a minimum distance of 20 pixels to the left and 20 pixels to right edge of the viewport - in other words - they should use a specific range of ​​the viewport.

Preparation:

  1. Get elements by their tagname:

layer = document.getElementsByTagName('div');

  1. Determine the area where the layers should be placed:

var min = 20;

var max = window.innerWidth - layer [0] .getBoundingClientRect(). width - 20;

  1. Convert collection to a "real" array:

layer = Array.prototype.slice.call (layer,0);

  1. Execute function "test" once for each element:

layer.forEach (test);

My function:

function test(el) {

distance = Math.floor(Math.random() * (max - min + 1)) + min;

if (distance >= min && distance <= max) {

el.style.left = distance + "px";

}

}

My problem / my question:

My function "test" causes the random value stored in "distance" not to be transmitted in any case, namely whenever the random value can not satisfy the condition. The following should be the solution - I thought ...

do {

distance = Math.floor(Math.random() * (max - min + 1)) + min;

}

while (distance >= min && distance <= max) {

el.style.left = distance + "px";

}

Unfortunately, my experiments are not successful. How can I solve the problem ?




randomly re-sample vector of tuples with weights in C++

I was wondering if somebody could help.

I'm looking for a fairly straightforward and ideally fast way of sampling from a vector of tuples with weights.

e.g. say I have a vector of tuples, each containing a value and a corresponding weight/probability:

vector<tuple<int, double>> foo = { {1,0.04},{2,0.8},{ 3,0.01 },{ 4,0.03 },{ 
5,0.1 },{ 6,0.9 } };

I want to go through foo and randomly re-sample based on the weights, so I would end up with a vector (either a new vector or replacing the elements in foo) that in this case, is problematically mostly going to be 2 and 6. e.g.

 vector<tuple<int, double>> bar = { {2,0.8},{2,0.8},{ 6,0.9},{ 6,0.9 },{ 
6,0.9 },{ 6,0.9 } };

I'm sure this is pretty straight forward using something like std::discrete_distribution, although I've yet to figure out exactly how.




creating a vector of randomly generated numbers based on a previous randomly generated string

I have a set of code that creates a dummy variable matrix of size 3xn. This gives the following combinations- 111 110 101 100 011 010 001 000

    variable1 <- sample (0:1, 1000, replace = T, prob = c(.5,.5))
    variable2 <- sample(0:1, 1000, replace = T, prob = c(.5,.5))
    variable3 <- sample(0:1, 1000, replace = T, prob = c(.5,.5))
    data <- data.frame(cbind(variable1 , variable2 , variable3 ))
    View (data)

What I would like to do is to populate a number of additional columns based off of the randomly generated dummy variables. Particularly I want to create simulated data based off various normal distributions where the mean and standard deviation are different for each dummy code.

e.g. for a new column vector, the code 111 might sample from a distribution of mean 10 and sd 1 while the code 000 would sample from one with mean 5 and sd 2.

I am just having a little trouble.




Random data between start value and end value with min and max as well as standard deviation

How can i generate random walk data between a start value and an end value as well as limiting the minimum/maximum value and the standard deviation/fluctuations?

Here is my attempt to do this but for some reason the min and the max values are broken and sometimes the series goes over or under these values. It seems that the Start and the End value are respected but not the minimum and the maximum value. How can this be fixed? Also i would like to give the standard deviation of the fluctuations. How would that be achieved?

import numpy as np
import matplotlib.pyplot as plt

def generateRandomData(length,randomPerc, min,max,start, end):
    data_np = (np.random.random(length) - randomPerc).cumsum()
    data_np *= (max - min) / (data_np.max() - data_np.min())
    data_np += np.linspace(start - data_np[0], end - data_np[-1], len(data_np))
    return data_np

randomData=generateRandomData(length = 1000, randomPerc = 0.5, min = 50, max = 100, start = 66, end = 80)

## print values
print("Max Value",randomData.max())
print("Min Value",randomData.min())
print("Start Value",randomData[0])
print("End Value",randomData[len(randomData)-1])

## plot values
plt.figure()
plt.plot(range(randomData.shape[0]), randomData)
plt.show()
plt.close()




GoLang Get String at Line N in Byte Slice

In a personal project I am implementing a function that returns a random line from a long file. For it to work I have to create a function that returns a string at line N, a second function that creates a random number between 0 and lines in file. While I was implementing those I figured it may be more efficient to store the data in byte slices by default, rather than storing them in separate files, which have to be read at run time.

Question: How would I go about implementing a function that returns a string at a random line of the []byte representation of my file.

My function for getting a string from a file:

func atLine(n int) (s string) {
    f, err := os.Open("./path/to/file")
    if err != nil {
        panic("Could not read file.")
    }
    defer f.Close()
    r := bufio.NewReader(f)
    for i := 1; ; i++ {
        line, _, err := r.ReadLine()
        if err != nil {
            break
        }
        if i == n {
            s = string(line[:])
            break
        }
    }
    return s
}

Additional info:

  • Lines are not longer than 50 characters at most
  • Lines have no special characters (although a solution handling those is welcome)
  • Number of lines in the files is known and so the same can be applied for []byte



How to run a function randomly in python?

I want to make my program run a few functions randomly. For example, if there's a function, I want it to run 3 times a minute, not at exact times or in a period. It could run at 10:10:20, 10:10:21, 10:10:59 or 10:11:01, 10:11:03, 10:11:49. How can it be done in Python? Does random module support this?




How to produce random Basic Multilingual Plane (BMP) strings in Java?

I'm using RandomStringGenerator from commons-text 1.1.2-SNAPSHOT to produce random user names and passwords for tests (regardless of whether random testing is controversial). Using those generated strings in Selenium with Chrome driver can cause

org.openqa.selenium.WebDriverException: 
unknown error: ChromeDriver only supports characters in the BMP
  (Session info: chrome=62.0.3202.62)
  (Driver info: chromedriver=2.33.506092 (733a02544d189eeb751fe0d7ddca79a0ee28cce4),platform=Linux 4.13.0-16-generic x86_64) (WARNING: The server did not provide any stacktrace information)

Is there any way to produce BMP strings with existing functions already or do I have to go the obvious way to research all BMP codepoints to select randomly from them and risk to reinvent the wheel.

Not a duplicate of How to handle "org.openqa.selenium.WebDriverException: ChromeDriver only supports characters in the BMP" exception? since I'm interested in the solution for other purposes as well.




Restoring randomly generated particle params

I'm writing particle system and should port previous functionality to it. The basic idea is to split particle system into parts such as particle (that stores current state of one particle), particle affector (has some influence to particles during simulation: add velocity etc.) and few other essences. I want to be able to add new affectors without adding new parameters to particle struct. Also, I'm trying to keep particle struct smaller, such as:

    struct Particle
    {
            Vec3 position;
            Vec3 velocity;
            Color color;
            Vec2 size;
    };

The affector probably will look like:

    class ParticleAffector
    {
    public:
            virtual void affectParticles(ParticleContainer& particles) = 0;
    };

Old particle system (which functionality I should keep in new one) had some effects that require particle to have some additional params like wiggler effect time offset (generated randomly from range for each particle on particle creation to keep randomness in particles movement). I'm looking for ability to port these effects without adding custom parameters to particles. One idea was to have parameter such as randomSeed in each particle and to map this seed to required range on the fly for each particle in affector code. But implementing this idea as is can make visibly recognizable dependencies between different particle properties (orientation and speed, for example). The the extension of idea is to have random number generator that takes two numbers as seed (one from particle and one from affector, so there will be different restorable number sequences for different properties) and and gives i'th element of sequence by requested index in constant time, so it will be possible in affector to write something like m_randomNumberGenerator.makeRandomValue(particleSys->getOrientationSeed(), particle.randomSeed, 0) to get first number of sequence and it will be exactly the same number that was used to generate particle's initial orientation. But this value restore should be fast enough to run for each particle on PC and mobile devices. Is there any suggestions for implementing this? I was already reading this question but wondering if it fast enough and how to make two random seeds. Probably, there is some better solutions for not adding custom parameters to particles?




mercredi 25 octobre 2017

Different result after calling srand and rand in two similar executables

I have given a 32bit ELF binary. Meanwhile I created my own executable that does the same as the first one, to test the first one's behavior. The custom code outside of the library calls are very simple, as you can see.

The first executable:

mov     [esp], MySeed ; MySeed = 3255810Dh
call    _srand
call    _rand
; eax now holds 18C818C2h

The second executable, that I created:

push    3255810Dh                       ; seed
call    _srand
call    _rand
; eax now holds 7FFFFFFFh

I debugged them and they both use libc_2.23.so. I also put a breakpoint on _srand and _rand not to miss any hidden call to them, but no luck. They always came out with a different result.

What am I missing?




Rock Paper Scissors PYTHON

Python rock paper scissors working nicely for me. I'm just a bit stumped on how to add up and print the number of times "human" used each weapon....

from random import choice

win = 0
loss = 0
tie = 0


rules = {'Rock': 'Paper', 'Scissors': 'Rock', 'Paper': 'Scissors'}
previous = ['Rock', 'Paper', 'Scissors']


while True:
 human = input('Rock, Paper, Scissors or Quit???: ')
 computer = rules[choice(previous)]  

if human in ('Quit'):
    print("YoU WoN %d TiMEs!" % win)
    print("yOu lOSt %d tImEs!" % loss)
    print("YoU TIeD %d TiMEs!" % tie)
    print("SeE YoU LaTeR!!! :)")

elif human in rules:
    previous.append(human)
    print('tHe CoMPuTeR PlAyEd', computer, end='; ')

    if rules[computer] == human:  
        print('YoU WiN!')
        win += 1
    elif rules[human] == computer:  
        print('ThE CoMpUtER BeAT YOU!!!')
        loss += 1
    else:
        print("It'S A tIE!")
        tie += 1

else: print("that's not a valid choice")




Python Random Generator

basically i need some quick help. I'm making a program where i am using a 2 random generators to generate numbers. First generator, between 2-14 each number representing a card. Numbers 11, 12 13, and 14 represent Jack, Queen, King & Ace respectively.

Second random generator generating numbers 15-18 to represent the type of card for example 15, 16, 17, 18 would represent Hearts, Spades, Diamonds & Clubs respectively.

What the outcome of the generators should come to is basically lets say generator 1 generated a number 8 and generator 2 generated number 17 i want it to say "8 of Diamonds".

So far my code

import random

Player1 = input("Enter Name Of Player1")
Card = random.randint(2, 14)
Suit = random.randint(15,18)
if Card == 11:
    print("Jack")
elif Card == 12:
    print("Queen")
elif Card == 13:
    print("King")
elif Card == 14:
    print("Ace")
else:
    print(Card)




Why is random jitter applied to back-off strategies?

Here is some sample code I've seen.

int expBackoff = (int) Math.pow(2, retryCount);
int maxJitter = (int) Math.ceil(expBackoff*0.2);
int finalBackoff = expBackoff + random.nextInt(maxJitter);

I was wondering what's the advantage of using a random jitter here?




How Do I Compare Random Generated Values Python

Basically i am using a random generator in python to generate a random number 3 times like this

for x in range(1,4):
    Card = random.randint(2, 14)
    print(Card)

However, now i want to compare the 3 random numbers that were generated to output a message stating the highest number that was generated

i.e if 4, 6 and 10 were randomly generated the message i want outputted would be "Your highest number is 10".

How would i attempt to do that i am stuck can someone please help?




How to generate random number from exponential distribution when the sizes are the numbers of Poisson random variable in R?

Suppose we draw a random sample y1, y2,..,y20 of size 20 from Poisson distribution with parameter 5 i.e., y~rpois(20,5). Suppose we got y1=4, y2=7, y3=5,...,y19=3, y20=5. Then, my problem is, how to draw the samples x1~rexp(y1,2), x2~rexp(y2,2),...,x20~rexp(y20,2) so that the sum(x)={sum(x1), sum(x2),...,sum(x20)} which will be again a random sample? I want to find this sum(x) and its mean, i.e., mean(sum(x)) and variance ,i.e., var(sum(x)).

I hope my question is clear to all of you.




How to create random data efficiently

I was creating random byte arrays to test some transport layer. I used to transport data created like this

 public byte[] Read(Data data) {
  var rnd = new Random();
  int size = data.ChunkSize;

  byte[] array = new byte[size];
  rnd.NextBytes(array);
  return array;
}

Because Read() is called many times, and creating a new byte array every time and filling it with random data could be slow, I wanted to come up with a solution, which doesn't use rnd.NextBytes in every call.

So I came up with a Class, which holds a static random array and reads from it. When it comes to the end of that array, it will start from the beginning again:

public class MyBuffer
{
private static readonly Random SRandom = new Random();

private readonly byte[] buffer = new byte[5000000]; // 5mb array with random data to read from
private int currentStart;

public MyBuffer()
{
  SRandom.NextBytes(buffer);
}

public IEnumerable<byte> Latest(int amountOfBytes)
{
  return FetchItems(amountOfBytes).ToArray();
}

private IEnumerable<byte> FetchItems(int amountOfBytes)
{
  IEnumerable<byte> fetchedItems = Enumerable.Empty<byte>();
  int total = 0;

  while (total < amountOfBytes)
  {
    int min = Math.Min(amountOfBytes, buffer.Length - currentStart);
    fetchedItems = fetchedItems.Concat(FetchItems(currentStart, min));

    total += min;
    currentStart += min;
    currentStart = currentStart % buffer.Length;
  }

  return fetchedItems;
}
private IEnumerable<byte> FetchItems(int start, int end)
{
  for (int i = start; i < end; i++)
  {
    yield return buffer[i];
  }
}
}

and the calling code looks like this:

private static readonly MyBuffer SBuffer = new MyBuffer();
private static byte[] array = new byte[0];

public byte[] Read(Data data) {

  int size = data.ChunkSize;

  if (array.Length != size)
  {
    array = new byte[size];
  }

  Array.Copy(SBuffer.Latest(size).ToArray(), array, size);
  return array;
}

But this turns out to be even slower (way slower) than my first attempt, and I can't really see why. Anyone can tell me where my code is inefficient or come up with any other efficient solution to my problem?

Thanks