mercredi 31 juillet 2019

A question about implementation of std::shuffle using URBG

With reference to the (possible) implementation of the third version of std::shuffle template as outlined in std::random_shuffle, std::shuffle,

template<class RandomIt, class URBG>
void shuffle(RandomIt first, RandomIt last, URBG&& g)
{
    typedef typename std::iterator_traits<RandomIt>::difference_type diff_t;
    typedef std::uniform_int_distribution<diff_t> distr_t;
    typedef typename distr_t::param_type param_t;

    distr_t D;
    diff_t n = last - first;
    for (diff_t i = n-1; i > 0; --i) {
        using std::swap;
        swap(first[i], first[D(g, param_t(0, i))]);
    }
}

I was trying to understand how the URBG object g is used along with std::uniform_int_distribution<diff_t> to get a result within the closed range [g, param_t(0, i)]:

swap(first[i], first[D(g, param_t(0, i))]);

Based on the explanation for distr_t::param_type provided under C++ named requirements: RandomNumberDistribution:

Given

  • P, the type named by D::param_type
  • d, a value of type D
  • p, a (possibly const) value of type P
  • g, g1, g2, lvalues of a type satisfying UniformRandomBitGenerator

The following expressions must be valid and have their specified effects:

d(g,p) The sequence of numbers returned by successive invocations of this call with the same g are randomly distributed according to the distribution parametrized by p

since in the above invocation:

swap(first[i], first[D(g, param_t(0, i))]);

the distribution parametrized by param_t(0, i) always falls within the required distribution range, the invocation of g should also generate a random result type (int) within the distribution range.

Is this understanding correct?




Why does MersenneTwister seem to generate different sequences for the same seed?

Executing:

using Random

rng1 = MersenneTwister(42)
rng2 = MersenneTwister(42)

v = [ x for _ = 1:4, x = rand(rng1) ]
w = [ rand(rng2) for _ = 1:4 ]

print("$(v)\n$(w)\n")

generates the following output:

[0.533183, 0.533183, 0.533183, 0.533183]
[0.533183, 0.454029, 0.0176868, 0.172933]

Shouldn't the two sequences be the same? What am I missing?

I get identical results on multiple systems, and with no regard to whether I create v first or w.




How to generate a random list of strings from an array

I want to generate a random list of 5 string values from an array of string.
type options. I have an string[] called 'Items':

private static string[] Items = new[]
{
    "Widgets", "Wotsits", "Grommits"
};

Using the options in this array, I want to instantiate a List<string> collection with 5 random strings. I am trying to do it like this:

    public List<string> List()
    {
        var r = new Random();
        return Enumerable.Range(1, 5).Select(index => new List<string>()
        {
           Items[r.Next(Items.Length)]

        });
    }

I cannot get it to work. One problem I have is I use Enumerable.Range but this creates a type error which I have been unable to solve with .ToList().

Is there a way to do it?




How can I re-prompt a random number generator if it does not give me the number I want

I basically set up a boolean matrix that goes up to 5x5 dimensions and defined each box in the matrix to be either true or false.

to display:

    {
    s[0][0] = false; s[0][1] = true; s[0][2] = false; s[0][3] = true; s[0][4] = false; s[0][5] = false;
    s[1][0] = false; s[1][1] = true; s[1][2] = false; s[1][3] = false; s[1][4] = false; s[1][5] = true;
    s[2][0] = true; s[2][1] = false; s[2][2] = true; s[2][3] = true; s[2][4] = true; s[2][5] = true;
    s[3][0] = true; s[3][1] = false; s[3][2] = true; s[3][3] = false; s[3][4] = false; s[3][5] = true;
    s[4][0] = false; s[4][1] = true; s[4][2] = false; s[4][3] = true; s[4][4] = true; s[4][5] = true;
    s[5][0] = false; s[5][1] = true; s[5][2] = true; s[5][3] = false; s[5][4] = true; s[5][5] = false;
    }

Have tried making the while loop into an if statement, but that caused other problems.

    public void matrix(){

        Random r = new Random();

        for(j=0;j<5;j++){
            i = r.nextInt(6);
            while(s[i][j]){
                if(i==0){System.out.println((j+1) + " period: Teach kindergarden.");}
                if(i==1){System.out.println((j+1) + " period: Teach " + i + "st grade.");}
                if(i==2){System.out.println((j+1) + " period: Teach " + i + "nd grade.");}
                if(i==3){System.out.println((j+1) + " period: Teach " + i + "rd grade.");}
                if(i==4){System.out.println((j+1) + " period: Teach " + i + "th grade.");}
                if(i==5){System.out.println((j+1) + " period: Teach " + i + "th grade.");}
                else{System.out.println();}
                break;
            }
        }
    }

How can I make it where if s[i][j] is false, then the code goes back to the generator and keeps asking for an i value where s[i][j] would be TRUE?




How to choose nodes with same value in monte carlo tree search?

I implement Monte carlo tree search for a 2 person strategic game(Where you can win/lose/draw).

I search through the tree following the node with the highest UCB(Upper confidence bound for trees) value. If I find a node with no children, I add all possible moves to it, select one and go into simulation. I have three questions:

  1. How do I choose children when I have multiple children nodes with same UCB value? Should I randomly select one or should I select the node that occurs the first time in the for loop(max search)?(Does it even matter?)

  2. Which values should I choose for backpropagation? For example if I win in a simulation, should I backpropagate a 10 or 1? If I draw I backpropagate a 0(Only increase visit). Which value should I backpropagate if I lose in a simulation? A 0(like in draw) or a -1/-10 ?




Is there a way to call a public int from another class?

Is there a way to use a non static public int in another class?

I want to have classes where I have useful functions and static information that I use in many other classes in different packages.

info.longrandom

Does not work because it is non static.

package common.info

public class info {
public int veryshortrandom = (int)(Math.random() * 500 + 1001);
public int shortrandom = (int)(Math.random() * 1000 + 2001);
public int mediumrandom = (int)(Math.random() * 1500 + 3001);
public int longrandom = (int)(Math.random() * 3000 + 6001);
public int verylongrandom = (int)(Math.random() * 6000 + 1201);
}

I am hopeing for something that would be akin to:

return info.longrandom




Filling a multidimensional array with random bytes in one line in C

I want to initialize a 2D matrix by filling it with random numbers (doubles).

So, for example, this code

#define N 1000

int main(void){
  double A[N];

  arc4random_buf(A,N*sizeof(double));

  return 0;
}

runs and produces a 1D array filled with random numbers as expected.

However, this

#define N 1000

int main(void){
  double A[N][N];

  arc4random_buf(A,N*N*sizeof(double));

  return 0;
}

produces a segmentation fault. I've tried initializing A with zeroes on the previous line, to no avail.

Is the only solution to use a loop here?




How to randomize text to label?

I need help on this simple task. How can I make a program that takes one random phrase from a hidden list and prints it on a label by pressing a button on c#?




How can I display an image embedded in my program using the value from a random number generator?

I'm trying to build a Russian Roulette style program where you click a button and it randomly selects one of 25 images to display on screen but I can't seem to figure out how to call the images using the generator.

It works fine when I select an image manually, as seen in my code below, but anything else seems to return an error.

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Timers;
using System.Threading.Tasks;
using System.IO;
using System.Windows.Forms;
using System.Security.Cryptography;

namespace WindowsFormsApp1
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void label_click(object sender, EventArgs e)
        {
            Close();
        }

        int mouseX = 0, mouseY = 0;
        bool mouseDown;



        private void panel1_MouseDown(object sender, MouseEventArgs e)
        {
            mouseDown = true;
        }

        private void panel1_MouseUp(object sender, MouseEventArgs e)
        {
            mouseDown = false;
        }

        private void GOBUTN_Paint(object sender, PaintEventArgs e)
        {



        }
        //Sharing is caring: Communism goes here
        private System.Windows.Forms.Timer timtim;
        int rand0;
        PictureBox Rooskie = new PictureBox();
        Label test = new Label();
        Random rando = new Random();
        List<int> duplicheck = new List<int>();


        private void boopthesnoot(object sender, EventArgs e)
        {
        dingding:
            //Hell yeah, random numbers here
            rand0 = rando.Next(1, 26);



            /*string combowombo = string.Join(", ", duplicheck.ToArray());
            test.Text = combowombo;
            test.Font = new Font("Calibri", 20);
            Controls.Add(test);
            test.Location = new Point(0, 200);
            test.Height = 1000;
            test.Width = 1000;*/
            if(duplicheck.Contains(rand0))
            {
                goto dingding;
            }
            else
            {
                GOBUTTON.Hide();
                pictureBox1.Hide();
                pictureBox2.Hide();

                //Fuckin image code goes here my dood
                Rooskie.Width = 1160;
                Rooskie.Height = 620;
                Bitmap image = new Bitmap(WindowsFormsApp1.Properties.Resources._1);
                Rooskie.Dock = DockStyle.Fill;
                Rooskie.Image = (Image)image;
                Controls.Add(Rooskie);
                Rooskie.SizeMode = PictureBoxSizeMode.CenterImage;


                //Aww shit, it's that timer time
                timtim = new System.Windows.Forms.Timer();
                timtim.Tick += new EventHandler(clockfinish);
                timtim.Interval = 3000;
                timtim.Start();
                duplicheck.Add(rand0);
                if (duplicheck.Count == 25)
                {
                    duplicheck = new List<int>();
                }
            }


        }

        private void clockfinish(object sender, EventArgs e)
        {
            //CEASE THE TIMER AND GIVE ME BACK MY BUTTON
            Rooskie.Image = null;
            timtim.Stop();
            GOBUTTON.Show();
            pictureBox1.Show();
            pictureBox2.Show();
        }

The expected result is when the user presses the button it calls up the image without having to load it from a folder.




How to generate deterministic batches of pseudo-random numbers in python 3?

In python 3, random.jumpahead was deprecated (without much warning). How should this functionality be replaced?

I want to perform a large numerical experiment, aggregating many individual simulations:

  1. Each simulation is pseudo-random (i.e. internally depends at several points on PRNG input, which should be different and somewhat-independent for each simulation).
  2. My set of simulations is trivially-parallelisable, and so I want to be able to run separate simulations in different threads (or even as batch jobs on different machines at different times).
  3. I want to use a deterministic PRNG and a fixed seed, to ensure my results are reproducible (and do not depend on how the experiment is parallelised).

Previously these criteria were met by each simulation using the same seed but a unique jumpahead (based from an id or enumeration of the simulations). Is there a recommended alternative or should I still try to implement this approach?




mardi 30 juillet 2019

Random numbers with Gamma Distribution in Python

I defined a gamma distribution with following parameters: shape,scale = 4.2503, 7037. This dribuation is used to generate random numbers. The random numbers will be recalculated to the x-asix value.

I have another discrete number list (Please use this link Cars DataFrame to create this list. Sorry for this inconvenience.), which has only 59 numbers from 6800 to 112000. This 59 numbers are not equality divided in this range. I cut the discrete number list into 25 parts. So I have 26 bins. Every time when I generate a gamma random numbers, I use this number to find the corresponding bin in the discrete list. And then, use np.random to choose a number from [bin-1] to [bin]. Since the number is from a list, so it also have an index. The histogram above is actually the corresponding number.

Now I have a question: if I generate 460 random numbers at once, the histogram of those numbers doesn't look perfectly but it looks like a gamma distribution as I defined.

460 random numbers generated at once.

But if I generate 200, 200, 50 and 10 random numbers, and use the histogram to present all of them, I got such a wierd graph.

200-200-50-10

I'm not very good at math. But can anyone explain why would the difference between these two methods are too big? Thank you very much. Apart from this, if you have any suggestions for implementing the idea that I described above, please share it to me. Thank you!

import pandas as pd
import numpy as np
cats, bins = pd.cut(Cars['Preis'], 25, retbins=True)
list1 = Cars['Preis'].tolist()
for i in range(0,460):
    sample = np.random.gamma(shape, scale)
    while sample < min(list1) or sample > max(list1): # list1 is the discrete number list
        sample = np.random.gamma(shape, scale)
    bin_idx = np.digitize(sample,bins)
    if  0 < bin_idx < len(bins):
        for index, row in Cars.iterrows():
            if bins[bin_idx-1] < row.Preis <= bins[bin_idx]:
                choice_idx.append(index)
            else:
                pass
        if len(choice_idx) != 0:
            randomchoice = np.random.choice(choice_idx)
    else:
        target = min(list1, key=lambda x:abs(x-sample))
        randomchoice = list1.index(target)
    test.append(randomchoice)




Is there a way to manipulate the shuffle function?

I am shuffling an array of, say, 8760 numbers sorted by their respective values (from low to high) to generate a quasi-stochastic time series. However, I want higher values to have a higher chance of appearing within the first quarter and last of the resulting array and lower values within the second and third half. My questions are:

  1. Is there a way to manipulate the shuffle function so it works with custom probabilities or do I have to "do it myself" afterwards?
  2. Is there some other package I do not know yet which can do this?
  3. Am I possibly blind and overlooking another much easier way to do this?
a = np.array([0, 0, 0, 0, 0, ...
              1, 1, 1, ...
              ...
              14, 14, 14, 14, 14, 14])

a_shuff = random.shuffle(a)

# desired resultwould be something like 
a_shuff = [14, 14, 8, 12, ... 0, 4, 2, 6, 3, ... 13, 14, 9, 11, 12]

It may be important to note that each value has a different number of occurances within the array.

I hope that describes my problem well enough - I am new to both Python and Stackoverflow. I'm happy to answer any further questions on this matter.




How to find the best combination of two random parameters

Sorry if this is a general question I'm a bit of a beginner and I'm looking for a simple and uncomplicated library or way to do the following

I have some code that eventually depends on two parameters eg:

param1 = 12
param2 = 5

and at the end I get a variable that changes depending on these parameters

score = 5031

I want an easy way to loop over the code with randomized parameters until it finds the combination that gives the highest score




RANDOM INSERT IN JOIN TABLE (SQL SERVER)

I have two tables:

TableA and TableB And I have an AB jointable I want to randomly insert ids from my table B. And I want to do it 5 times for each id in my table A

How can I do this? Can you give me an example?




Array of eight Integers where each Integer has a difference of at least 15 from all others in the array?

I am trying to write a method that creates and returns an array of random Integers that has a length of eight.

Every Integer must be higher or lower than each other Integer in the array by at least 15.

I set up a main method that checks the output of my method 100,000 times, and throws an Exception if there are any Integers that are too close.

How can I create a method that will return an array of Integers with a difference between each other of at least 15?

public class Test {

public static void main(String[] args) throws Exception{

   Integer[] distances = new Integer[8];

   for (int i = 0; i < 100000; i++) {

      distances = createPlanetDistances(distances.length);

      // check distances for values within 15
      for (int x = 0; x < distances.length; x++) {

         for (int y = 0; y < distances.length; y++) {

            if (x == y)
               continue;

            if (Math.abs(distances[x] - distances[y]) < 15) {

               System.out.println(distances[x] + " " + distances[y]);
               throw new Exception("Doesn't work");
            }
         }
      }

      for (int distance : distances)
         System.out.print(distance + " ");

      System.out.println(System.lineSeparator());
   }
}

/**
 * Creates an array of distances-from-the-sun for a given number of Planets.
 * It does not allow distances to be within 15 of any other distance.
 *
 * @param planetAmount The number of distances to return.
 * @return An array of distances-from-the-sun.
 */
private static Integer[] createPlanetDistances(int planetAmount) {

   SplittableRandom random = new SplittableRandom();

   final int min = 25;
   final int max = 726;

   HashSet<Integer> distanceSet = new HashSet<>();

   // make sure there are no duplicate Integers

   for(int i = 0; i < planetAmount; i++) {

      int num = random.nextInt(min, max);

      while (distanceSet.contains(num))
         num = random.nextInt(min, max);

      distanceSet.add(num);
   }

   // make sure each distance is 15 away from all others

   Integer[] distances = distanceSet.toArray(new Integer[]{});

   for(int i = 0; i < distances.length; i++) {

      // check distances[i] with all other Integers
      for (int j = 0; j < distances.length; j++) {

         // do not compare an element with itself
         if (j == i)
            continue;

         int difference = Math.abs(distances[i] - distances[j]);

         if (difference < 15) {

            while (difference < 15) {

               distances[i] = random.nextInt(min, max);
               difference = Math.abs(distances[i] - distances[j]);
            }

            // check all Integers again
            System.out.println("HERE " + i + " " + j);
            i = 0;
            break;
         }
      }
   }

   return distanceSet.toArray(new Integer[]{});
}
}




How can I select random N number of questions from array containing many questions?

I am trying to make a quiz with React that displays random 100 questions from a javascript file.

Here are the questions inside javascript file.

const quizQuestions = [
        
        {
                question: "Grand Central Terminal, Park Avenue, New York is the world's",
                options: ["largest railway station", "highest railway station", "longest railway station", "None of the above"],
                answer: "largest railway station"
        },
        {
                question: "Entomology is the science that studies",
                options: ["Behavior of human beings", "Insects", "The origin and history of technical and scientific terms", "The formation of rocks"],
                answer: "The origin and history of technical and scientific terms"
        },
        {
                question: "Eritrea, which became the 182nd member of the UN in 1993, is in the continent of",
                options: ["Asia", "Africa", "Europe", "Australia"],
                answer: "Africa"
        },
        {
                question: "Garampani sanctuary is located at",
                options: ["Junagarh, Gujarat", "Diphu, Assam", "Kohima, Nagaland", "Gangtok, Sikkim"],
                answer: "Diphu, Assam"
        },
        {
                question: "Hitler party which came into power in 1933 is known as",
                options: ["Labour Party", "Nazi Party", "Ku-Klux-Klan","Democratic Party"],
                answer: "Nazi Party"
        }
        
]

export default quizQuestions;

1. I need javascript code to select for example 3 random questions in random order from above file. Similarly randomize options without repetition of question

2. And I want to execute the following function as many times as the no of questions by calling the component MCQ and passing the question and option as props

function MCQ(props) {

        return(
                <div>
                        <div>{props.question}</div>
                        <div> 
                                <input type="radio" name="answer" id=??? /><label for="???"> {props.options[0]}</label>
                                <input type="radio" name="answer" id=??? /><label for="???"> {props.options[1]}</label>
                                <input type="radio" name="answer" id=??? /><label for="???"> {props.options[2]}</label>
                                <input type="radio" name="answer" id=??? /><label for="???"> {props.options[3]}</label>
                        </div>
                </div>
                )
}

What id and name should i give?

THANK YOU




How to get random value from struct

How to pick out random constant value from the struct?

struct randomMessage {

    static let message1 = "Message1"
    static let message2 = "Message2"
    static let message3 = "Message3"
    static let message4 = "Message4"
    static let message5 = "Message5"
}

the only way is all the values to array and pick the randomElement ?




Is SecureRandom.ints() secure?

It is known that SecureRandom class provide strong cryptographic security for generated random number. java.util.Random is insecure for the situation which requires cryptographic security. The typical usage of SecureRandom is:

SecureRandom random = new SecureRandom();
byte bytes[] = new byte[20];
random.nextBytes(bytes);

However, I met a case:

SecureRandom random = new SecureRandom();
int number = random.ints();

The method ints() is inherited from the java.util.Random class. I am confused when SecureRandom which is a secure random number generator uses a method inherited from the insecure random number generator, whether it is secure?




lundi 29 juillet 2019

segmentation fault in random data stream generator

I'm attempting to initialize two random 512-byte blocks of data, each byte in the block is represented with a defined data type 'byte' which is an unsigned char.

Included here, I have listed my definitions and functions. I keep getting segmentation fault 11. Any ideas about directions I could go to figure out why this isnt working?

I have been trying to go line by line with this but have been having no luck...

#include <stdio.h>
#include <stdlib.h>
#include <time.h>
typedef unsigned char byte;
//define the primary object, each block is a linked-list that represents 512 bytes of unsigned chars
struct block
{

  byte res;

  int i;
  int j;
  int k;

  struct block* next;

  };

//function to generate a pointer to randomized 512 byte stream.

struct block* fivetwelvegen(){
  struct block* r;
  int w=32;
  int l=16;
  int ran;
  char hex[] = "0123456789ABCDEF";
  byte g = 1;
  r=0;
for(r->i=1;r->i<=w;r->i++){
  for(r->j=1;r->j<=l;r->j++){
    for(r->k=1;r->k<=(l*w);r->k++){
      ran = rand()%l;
      g = hex[ran];
      r->next->k = g;
      r=r->next;
    }
      if(r->i==(w+1))
        r->i=1;
      }
    }
return r;
}
int main(void){

  srand((unsigned)time(NULL));

  struct block* one;
  struct block* two;
  int w=32;
  int l=16;

  printf("Creating two random 512-byte data streams...\n");

  one = fivetwelvegen();
  two = fivetwelvegen();

  printf("The intializing value of block A is: %hhu\n", one->res);
  printf("The intializing value of block B is: %hhu\n", two->res);
}

Expected to print the initializing (first) value of the 512-byte stream, essestially the value of the first byte of data. Currently I am receiving a segmentation fault 11




How to generate a Gaussian curve using 2 user inputted values?

I am trying to plot a Gaussian curve for 1 day using 2 points named basepoint and peak. Both the basepoint and peak are to be taken as user input and based on those values a curve has to be generated with the peak value occurring at 14:00h.

The curve must start with the basepoint value and end again at the basepoint value with the numbers between the basepoint and peak being some randomly generated numbers

Is there a way this can be done?

enter image description here




updating dictionary with a random nested dictionary

I have a program, however, I need to update the dict with a random key (the key is a nested dict). However, whenever I do, It gives me an error.

I have tried to use the .update, and used random.choice(dict), however this does nothing but give an error

dictA = { 1 : 2, 2 : 3, 3 : 4}
dictB = {}
dictB.update(random.choice(list(dictA)))

I excpet dictB to have a random key, however what I get is ValueError: dictionary update sequence element #0 has length 1; 2 is required




How do I combine 2 random randints? [on hold]

I'm making a Python script and random.randints are a major part of it. But I want to add another part of my code where it combines both of my random.randint values. How do I do it?

I was going to do some sort of append but I don't know how to make that work.

Here's my code without any code trying to combine the random.randint values:

import random
LOL = raw_input('Do you want a meme or a prank idea? ')
if LOL == 'meme' or LOL == 'Meme' or LOL == 'MEME':
  x = random.randint(1, 6)
 if x == 1:
   print('Meme:')
   print('Yee')
 elif x == 2:
   print('Meme:')
   print('Yeet!')
 elif x == 3:
   print('Meme:')
   print('I got the horses in the back')
 elif x == 4:
   print('Meme:')
   print('AND HIS NAME IS JOHN CENA!!!!')
 elif x == 5:
   print('Meme:')
   print('IT\'S OVER 9000!')
 elif x == 6:
   print('Meme:')
   print('Do u no de wae?')
elif LOL == 'prank' or LOL == 'Prank' or LOL == 'PRANK' or LOL == 'prank               Idea' or LOL == 'Prank idea' or LOL == 'Prank Idea' or LOL == 'PRANK IDEA':
 y = random.randint(1, 5)
 if y == 1:
   print('''Prank:
   Replace their Oreo frosting with toothpaste, make sure they don\'t eat it!''')
elif y == 2:
  print('''Prank:
  Blast into their room with an air horn, but it won\'t work if they\'re deaf!''')
elif y == 3:
  print('''Prank:
  Blast the FBI meme on max volume with a loud speaker, hopefully they don\'t have sensitive ears!''')
elif y == 4:
  print('''Prank:
  Dump a bucket of cold/icy water on their head, if the weathers freezing then that\'s too cruel!''')
elif y == 5:
  print('''Prank:
  Cover their car with sticky notes, make sure it\'s a non-windy environment!''')




PySpark DataFrame - Append Random Permutation of a Single Column

I'm using PySpark (a new thing for me). Now, suppose I Have the following table: +-------+-------+----------+ | Col1 | Col2 | Question | +-------+-------+----------+ | val11 | val12 | q1 | | val21 | val22 | q2 | | val31 | val32 | q3 | +-------+-------+----------+ and I would like to append to it a new column, random_qustion which is in fact a permutation of the values in the Question column, so the result might look like this: +-------+-------+----------+-----------------+ | Col1 | Col2 | Question | random_question | +-------+-------+----------+-----------------+ | val11 | val12 | q1 | q2 | | val21 | val22 | q2 | q3 | | val31 | val32 | q3 | q1 | +-------+-------+----------+-----------------+ I'v tried to do that as follow: python df.withColumn( 'random_question' ,df.orderBy(rand(seed=0))['question'] ).createOrReplaceTempView('with_random_questions') The problem is that the above code does append the required column by WITHOUT permuting the values in it.

What am I doing wrong and how can I fix this?

Thank you,

Gilad




dimanche 28 juillet 2019

How can I assign a random number to each object in an array in javascript?

Alright, so why am I asking this question? Because I am making a simple evolution simulator. In it, each creature will get a random amount of food each generation. The amount of of food each creature gets is crucial to if it survives or not. Since the only way I see it working is in an array(and I'm not good at arrays) can you help me find a way to assign these numbers to objects within the array?

I've looked through multiple websites for answers and none hit the dot. I also don't have any code so can you submit some code so I can see what I have to do?




samedi 27 juillet 2019

For LOOP and random choice prints one string from a list

For some reason my list doesn't get printed completely, but only word by word each time I run the script.

import random

passwords = ['test', 'password', 'heslo', 'lol']

var = random.choice(passwords).split()

for word in var:
    print word

I wish the for loop to print my whole list in randomized order each time I run my script. Upon removing random.choice it works, but list is not randomized.




How to get a randomized list but a constant result each time when operated

I have a list of string, and I want its elements randomly shuffled. But in the meantime, I also want that would be the same result unless change demanded.

I thought random.seed() is gonna help. So I tried this,

random.seed(30)
random.shuffle(a)

say a is a list of strings. But each time I couldn't get the same result.

But in numpy so would tackle my problem

np.random.seed(30)
np.random.randint(0, 10)

That returns the same int. Oddly enough, when I tried this,

np.random.seed(30)
np.random.shuffle(a)

, that doesn't return the same result.
What's the trick here? Thanks!!!!




Is Random function (in any programming language) biased?

Is the function Random in programming languages not biased? After all, the algorithms need to be based on something, and that can generate bias. According to this website https://mathbits.com/MathBits/CompSci/LibraryFunc/rand.htm, rand() function needs a start number, called seed. It states that

the rand( ) function generates a pseudo-random sequence

I don't completely understand the logic behind it. If it's not really random (pseudo-random), is there a way to make it perfectly random?




Multi layer perception Vs SVM / Random forest

What can be the reason while Multi layer perception is not converging but SVM or Random forest is performing well on same dataset? My Data is 120 features having numeric values between -1 to 1 and need to predict any of 5 classes. Note: I am not aware about what data this is?

SVM accuracy 91% Random forest 86% 2 layer MLP acc 74% after 3500 epoch




Making a guessing game and when I input 100 it says i need to go higher

So im making a guessing game where the computer picks a randomint between 1 - 100 and when guessing if you guess below the number it will tell you to go higher and if you guess above the number it will tell you to guess lower. It works for the most part it's just when I guess 100 it tells me to go higher.

Now before you start the game the computer will add a random number to an array and all you need to do is match the number provided in the array.

I've tried switching the array to a set but then i get this error message: "'dict' object has no attribute 'add'"

That is the code i am working with.

Also when trying to write to a file it doesn't seem to work too well

from random import *
from random import randint
import os

numbers = []
Guesses = []

os.system('CLS')
print("I want you to guess my number between 1 - 100")

f = open("Data.txt", "a")

print("Say 'yes' If You're Ready")

YN = input()



if YN == "yes":
    os.system('CLS')
    for _ in range(1):
        value = randint(1, 101)
        numbers.append(value)
        break



while True:
    Guess = input()
    Guesses.append(Guess)
    print(numbers)

    if Guess < str(value):
        print("Higher")

    elif Guess > str(value):
        print("Lower")

    elif Guess == str(value):
        os.system('CLS')
        f.write(str(Guesses))
        print("That Was Correct!")
        for x in Guesses:
            print(x)
        break

input()






Is there a way to pop link sequentially on click?

I am trying to create a button that will bring users to specific link. For example, I have 5 links, is there a way I can specify that upon each click it will bring user to the saved links sequentially?

On my code below, I have a random link function, that says, upon each click, user will be directed to one of the links randomly.

Is there a way, say, first user who clicks will be directed to link 1, and second user to Link 2, and etc.?

*/


var randomlinks=new Array()

randomlinks[0]="www.Link 1.com"
randomlinks[1]="www.Link 2.com"
randomlinks[2]="www.Link 3.com"
randomlinks[3]="www.Link 4.com"
randomlinks[4]="www.Link 5.com"

function randomlink(){
window.location=randomlinks[Math.floor(Math.random()*randomlinks.length)]
}
//-->
</script>
<form method="post">
<center><p><input type="button" name="B1" value="Start survey here" onclick="randomlink()"></p> </form></center>




vendredi 26 juillet 2019

How should I make my python PRNG work properly?

Everything I find says to use the Random module, but I want to do it from scratch. How would I do that?

I've done some work with messing with the Time module, and muddling the numbers to try to get a random(ish) result. (Returns a Boolean depending on if the rounded final result is divisible by two.)

My original function seems to fluctuate quite a bit. Yesterday it was around a 50/50 split, but now it's only about 10/90.

I'm trying to get it stable, but now it is always returning True 100% of the time...




How much is excluded from the bound when generating pseudo-random doubles with nextDouble()?

I have looked at the SplittableRandom class' nextDouble() info on JavaDocs, but it doesn't tell me how close the return value of the nextDouble(double bound) method can get to the "bound" argument. I don't know if I can get a full range of values between 0.0 and 100.0 inclusive by typing foo.nextDouble(100.0 + Double.MIN_VALUE).

How can I pseudo-randomly return a number from 0.0 to 100.0 using the nextDouble(double bound) method?

/**
 * Returns a getRandom element from this.values.
 * Elements with higher associated percentage-change values (in this.keys)
 * are more likely to be returned.
 * <p>
 * Throws an IllegalArgumentException if this.sum is not equal to 100.
 */
public T getElement() {

   SplittableRandom random = new SplittableRandom();

   if(sum != 100.0)
      throw new IllegalArgumentException("sum of chances must == 100.0");

   final double choice = random.nextDouble(100.0 + Double.MIN_VALUE);

   /* Iterate through this.keys until the sum of traversed elements is less than
    * or equal to the choice variable. Then return the this.value element at the
    * same index as the latest traversed element of this.keys.*/

   double percentageSum = 0.0;
   for (int i = 0; i < this.keys.size(); i++) {

      percentageSum += this.keys.get(i);

      if (choice <= percentageSum)
         return this.values.get(i);
   }

   throw new AssertionError("unreachable code reached");
}




Insert/replace variables from one list into another list

list_x = ["a", "y", "l", "d", "e", "l", "g", "o", "i"]
list_y = ["e", "p", "z"]

I am trying to replace random items from list_x with the items from list_y without adding any duplicates. I've looked into I've looked into random.replace() and random.choice() but I can't seem to figure it out. Example of how the output I am trying to get: new_list_x = ["p", "y", "l", "d", "e", "z", "g", "o", "i"]. The goal is to insert/replace any letters from list_y that are missing in list_x with out exceeding the original number of letters in list_x.




C++: Performance for drawing random boolean values

I am drawing random boolean numbers with

std::mt19937 rng;
std::uniform_int_distribution<int> dis(0, 1);

In extreme cases, drawing these numbers can take up to 40% of the CPU time of my process. Is there any way to make this faster?




Random Number generator in a range and then print length of the sequence

I want the application to create a sequence that generates a series of random numbers from 0 to 9 util a 0 is generated and then display the length of the sequence of the numbers. Right now my program only prints 0 or 9 as I don't know the random number generator method.My question is how do I generate a random integer between 0 and 9(inclusive) unit a 0 is generated.

import java.util.Random;
import java.util.ArrayList;

public class Sequence {
   public static void main(String[] args) {
       ArrayList<Integer>  lista = new ArrayList<Integer>();
       lista.add(0, 9);



       Random r = new Random();
       System.out.println(lista.get(r.nextInt(lista.size())));
      }
   }




randomly flip elements of a Sparse Tensor representing an adjacency matrix

I have a sparse matrix named my_mat. It represents an adjacency matrix, which is symmetrical. It is a sparse tensor

print(type(my_mat))

<class 'tensorflow.python.framework.sparse_tensor.SparseTensor'>

print(my_mat)

SparseTensor(indices=Tensor("Placeholder_11:0", shape=(?, ?), dtype=int64),
values=Tensor("Placeholder_10:0", shape=(?,), dtype=float32),
dense_shape=Tensor("Placeholder_9:0", shape=(?,), dtype=int64))

I want to randomly flip 30% of its elements. For example, if the original value is 1, change it into 0; if the original value is 0, change it into 1. The new matrix should still be symmetrical, because it still should be an adjacency matrix. In addition, I do not want to flip the elements on the main diagonal.

Could you please suggest any ideas?




Performance difference between numpy.random and random.random in Python

I want to see what random number generator package is faster in my neural network.

I am currently changing a code from github, in which both numpy.random and random packages are used to generate random integers, random choices, random samples etc.

The reason that I am changing this code is that for research purposes I would like to set a global seed to be able to compare accuracy performance for different settings of hyperparameters. The problem is that at this moment I have to set 2 global seeds, both for the random package and for the numpy package. Ideally, I would like to set only one seed as drawings from two sequences of random number generators might become correlated more quickly.

However, I do not know what package will perform better (in terms of speed): numpy or random. So I would like to find seeds for both packages that correspond to exactly the same Mersenne Twister sequence. In that way, the drawings for both models are the same and therefore also the number of iterations in each gradient descent step are the same, leading to a difference in speed only caused by the package I use.

I could not find any documentation on pairs of seeds that end up in the same random number sequence for both packages and also trying out all kind of combinations seems a bit cumbersome.

I have tried the following:

np.random.seed(1)
numpy_1=np.random.randint(0,101)
numpy_2=np.random.randint(0,101)
numpy_3=np.random.randint(0,101)
numpy_4=np.random.randint(0,101)
for i in range(20000000):
    random.seed(i)
    random_1=random.randint(0,101)
    if random_1==numpy_1:
        random_2=random.randint(0,101)
        if random_2==numpy_2:
            random_3=random.randint(0,101)
            if random_3==numpy_3:
                random_4=random.randint(0,101)
                if random_4==numpy_4:
                    break
print(np.random.randint(0,101))
print(random.randint(0,101))

But this did not really work, as could be expected.




Why this function couldn't return right result?

Result is not same actual values.For example, in this case from my output only first observation is same as actual.

 import numpy as np
    np.random.seed(0)
    def emil(values):
        output = np.empty(len(values))
        for i in range(len(values)):
            output[i] = 1.0 / values[i]
            print(len(values))
            return output
    values = np.random.randint(1, 10, size=6)
print(emil(values))

Out[1]: array([ 0.16666667, 1. , 0.25 , 0.25 , 0.125 ])




RNG on Google Kubernetes Engine

I need to be able to produce random longs using Java SecureRandom in an application running on Google Kubernetes Engine. The rate may vary based on day and time, perhaps from as low as 1 per minute to as high as 20 per second.

To assist RNG, we would install either haveged or rng-tools in the container.

Will GKE be capable of supporting this scenario with high-quality random distribution of longs without blocking? Which of haveged or rng-tools is more capable for this scenario?

I asked a related question here but didn't get a satisfactory answer: Allocating datastore id using PRNG




What are pythonic methods for implementing random roll tables?

A random roll table is a table used for random generation in tabletop games and the like. While they can be very simple they can also trend towards the complex.

An unusual example of a random roll table would be Wheel of Fortune-style games where certain categories can have a higher chance of occurring.

I'm building a random generator for D&D 5e magic items (see here: https://www.reddit.com/r/dndnext/comments/bg0h46/5e_magic_item_generator/) but I've decided I want to weight the tables to prefer certain results certain times.

A very simple table may look like this:

(1d6)
1: First result
2: Second result
3: Third result
4: Fourth result
5: Fifth Result
6: Sixth result

This can be resolved pretty easily by using a list and randomising between 1 and 6.

A slightly more complex (but still 1d6-based) table may look like this:

(1d6)
1-3: First result
4-5: Second result
6: Third result

My tables are more likely to look like:

(1d20)
1-5: First result
6-15: Second result
16-17: Third result
18: Fourth result
19: Fifth result
20: Sixth result

These tables have higher "weighting" towards certain categories to allow for those categories to be selected more often. In my magic item example, swords should have 6-15 as a "metal" blade whereas 1-5 would be a "bone" blade and 20 would be something very unusual like a "darkness" blade or a "light" blade.

One possible option is to add a "weight" to each category and perform a calculation on each roll to see what weight it lands on by adding together the previous weights but this feels horribly clunky.

I tried to implement this item generator previously in PHP and I used a switch case with comparison operators on the cases to solve this but obviously this does not work in Python.

What would be the recommend Python design for this weighted table implementation or does anyone have any ideas for implementation whatsoever? I'm willing to rewrite my data structure completely to take advantage of any ideas.




Random number for variable when called

I'm fairly new in programming and python in general. I already learned for, ifs, and while, and im trying to make a pretty decent rpg/dungeon game. and i'm wondering how do i make a variable have a random number when used for the "damage"

i used randint(a, b) for the variable but it is only random once

This is a creature example

name_slime = "Red Slime"
slime_hp = randint(100, 200)
slime_atk = randint(1, 2)
slime_crit = 60
slime_evade = 10
slime_exp = randint(1, 5)
slime_chance = randint(50, 60)

And these will get called on another function

def battle(enemy_name, enemy_hp, enemy_atk, enemy_crit, enemy_evade, enemy_exp):# Battle sequence

    while enemy_hp > 0:
        global player_hp, potion_count

        print(f"{enemy_name}'s Stats:")
        print(f"HP: {enemy_hp}  Power: {enemy_atk}  Crit Chance: {enemy_crit}%  Evade: {enemy_evade}%\n")
        print("Your Stats:")
        ....

        print("Action:\n1. Attack\n2. Parry\n3. Use Potion")
        choice = input("> ")


        if choice == "1":
            ....

        elif choice == "2":
            ....

        elif choice == "3":
            ....


    print(f"You gained {enemy_exp} EXP")
    exp_check(enemy_exp)
    print(f"Your EXP is now {player_exp}/{exp_limit}")

P.S: i scraped a lot pf things in this code because it's quite long for there is a lot of lines for the calculation

Here's the full code if anyone can help: https://pastebin.com/iFMZyY4z

I'll just take the exp for this case. In the variable "slime_exp" it should give a number between 1 and 5. But when i tried fighting the creature multiple times in one run (not exiting the terminal) it always give the same amount of exp each time. I'm thinking that the randint(1, 5) is defined when the script is run and not when the variable is used. How can i make it so that it will be random when the variable is used?




About the reputation and how to make newcomers an easy start

I know this has been stated in many topics, but sadly I'm not allowed to respond to them...

I found this beautiful topic about angular here, and wanted to respond with my answer, but hey! I won't respond! I really want, but I can't! Obviously this topic won't make sense to moderators here, and some are already about to lock it and mark it as spam, but seriously - this reputation system is just the absurdest thing I saw on the web. And this thing in such a large community! Guys, I'm disappointed!

My answer would be

You can use <a routerLink="/forum" routerLinkActive="current", to directly jump to /forum, and if /forum is active, then the <a>-tag will be added the class current

Why do I create this topic? Yes, I beg for reputation points with these words, but I also have to share ways for you how you can make this forum better:

  • Instead of completely locking topics, allow a Add Content form, that will allow everyone to add content, which will only be displayed after moderators' review.
  • Mark users with lack of reputation, so all other community members can support them.
  • Newcomer tutorial (or if i missed it, sorry, a 'restart tutorial') showing all the 'secret eggs' (that I have probably missed) and how to use them.
  • User Presentation category: A place where you can 'beg/ask' for reputation.

I know you do this to prevent spam, but you could easily the same way close the site completely to prevent it.

What about us, newcomers that no-one knows? This is a digital death here because of a lack of reputation! Yes, this community can even go more isolated with this system. The sad thing here is, that there are many people who have good content to share, just not enough reputation to respond.

15 reputation for upvote? Okay... 1,500 reputation... for a tag? Okay... It's like paying 200 $ for an email.

Stack overflow has many helpful topics, and has the current reputation system, which prevents the adding of good content - of people, who barely are known. Don't make this site a reputation RPG please!

Thanks to the people who actually read it: Every upvote counts!




jeudi 25 juillet 2019

Is there a faster way, to get random numbers, from a specific pool of numbers

im looking for a faster method, which allows me, to get a random number from a certain pool of numbers which are stored in an array.

I'll need the method multiple times, and the current method is terribly slowing down the code.

#include <cstdlib>
#include <ctime>

int main()
{      
    const int size = 8;
    int numberArray[size] = { 0, 0, 3, 4, 0, 6, 7, 0 };
    srand(time(0));

    int rndIndex;
    int rndNumber;
    do 
    {
        rndIndex = rand() % size;
        rndNumber = numberArray[rndIndex];
    } while (rndNumber <= 0);
}

I like to get a random number from the array, except the random number is less than 0




Select random filesnames without any repeats [duplicate]

This question already has an answer here:

How do I go through a list of 50 names that I have and and pull out 12 at random without any repeats? I can get the names but every once in a while I get duplicates.

files = []

for f in files:
    f = random.choice([
        x for x in os.listdir(path)
        if os.path.isfile(os.path.join(path, x))
        ])
    print(f)




Sampling elements according to common factor between data frames in R

I am trying to populate a dataframe B with random samples from another dataframe A.

dfA

enter image description here

dfB

enter image description here

Each draw would be made according to the elements in common between them.

I have looked into the sample_n function in dplyr, but I have not been able to figure out how to only sample within the same factor in common.

What I would like is to have a random color drawn from dfA and use it to populate the smp column in dfB. The draw, however, is restricted to elements only in common to the factor in dfA. So for the first row in dfB, there is are three choices: two reds and one blue, for the second, there is only one choice: black, for the third row: NA, because I chose no replacement. and so on.

Some example data:

dfA<-cbind(c("blue", 
"red","red","black","blue","red"),c("A","A","A","B","C","C"))
colnames(dfA)<-c("color", "factor")
dfB<-cbind(c("A","B","B","B","B","C","C"),NA)
colnames(dfB)<-c("factor", "smp")

I have tried something along these lines

library(dplyr)
sample_n(dfA, color,?n?, replace = FALSE)

The code is not functional. The ?n? is the part of the command I do not know how to insert, which is basically the factor in common with dfB. Would it be more efficient as aboolean operation or a for loop? I struggle with both, however.

The result is a random draw, but would look something like this:

enter image description here

Any insight will be most welcome, at my level of syntax in R, I am quite stumped.




Random number generation algorithm used in Numpy

What is algorithm that Python Numpy uses to generate random numbers? More specifically, what is the algorithm that is used when we invoke

np.random.uniform() 

Is Linear congruential generator random generation technique being used? What happens when we type

np.random.seed(42)

and why are some numbers like 42 are more popular with np.random.seed?




How to select random rows from R data frame to include all distinct values of two columns

I want to select a random sample of rows from a large R data frame df (around 10 million rows) in such a way that all distinct values of two columns are included in the resulting sample. df looks like:

StoreID      WEEK      Units      Value          ProdID
2001         1         1          3.5            20702
2001         2         2          3              20705
2002         32        3          6              23568
2002         35        5          15             24025
2003         1         2          10             21253

I have the following unique values in the respective columns: StoreID: 1433 and WEEK: 52. When I generate a random sample of rows from df, I must have at least one row each for each StoreID and each WEEK value.

I used the function sample_frac in dplyr in various trials but that does not ensure that all distinct values of StoreID and WEEK are included at least once in the resulting sample. How can I achieve what I want?




Stratified Random Sampling of Points in Polygon depending on Buffer-Mean around the sampled Point (preferably sf-package)

I have to randomly sample 100 spatial points in a spatial polygon. But the random sampled points should be allocated depending on another (underlying shp file) variable.

In other words: I have a country (1st shp file) and a (2nd) shp file with 250x250 grids of the country (which has holes in it as not all are populated). I now have to randomly drop 100 points (within the boundaries of the country and not necessarily within the boundaries of the grid-shp), BUT when drawing a 2km buffer around those points, I have to have at least a certain amount of inhabitants (this information is only in the grid-shp) in the buffer.

I manage to sample the points within the polygon, but did not manage to do this conditioning on the amount of people that should (at least) fall into the buffer.

I am working with the sf package (but did neither find it in the sp). I did randomly distribute the sample with st_sample, and then drew a buffer around with st_buffer. But I haven't manage to find a sampling command which helps me stratifying (?) depending on the inhabitants around this point.

My result should be, that I have 100 spatial points, each of them having at least a certain amount of inhabitants in its buffer.




Pandas: select value from random column on each row

Suppose I have the following Pandas DataFrame:

df = pd.DataFrame({
    'a': [1, 2, 3],
    'b': [4, 5, 6],
    'c': [7, 8, 9]
})

    a   b   c
0   1   4   7
1   2   5   8
2   3   6   9


I want to generate a new pandas.Series so that the values of this series are selected, row by row, from a random column in the DataFrame. So, a possible output for that would be the series:

0    7
1    2
2    9
dtype: int64

(where in row 0 it randomly chose 'c', in row 1 it randomly chose 'a' and in row 2 it randomly chose 'c' again).

I know this can be done by iterating over the rows and using random.choice to choose each row, but iterating over the rows not only has bad performance but also is "unpandonic", so to speak. Also, df.sample(axis=1) would choose whole columns, so all of them would be chosen from the same column, which is not what I want. Is there a better way to do this with vectorized pandas methods?




Program 6 of 49 the first 6 don't include a duplicate and 7th number has to be no one of the 1st 6

The 7th number displayed seperate. So in my oppinion I can't put the 7 numbers in one array.




Haskell sorted random list is infinite

For a small project I want to use Haskell. Need batches of 4 random numbers between 0 and 9, and these [Int] needs to be sorted when done (using: Data.Sort). Code below keeps returning an infinite list despite take 4 xs.

import System.Random 
import Data.Sort 

randomList :: IO () 
randomList = do 
  generator <- getStdGen 
  let rndGen = randomRs (0,9) generator :: [Int]
  getFourDigits <- return (fourDigits rndGen) 
  putStrLn $ show getFourDigits

fourDigits :: Ord a => a -> [a]
fourDigits rndGen = sort $ take 4 (repeat rndGen)

Is this caused by dry-running in stack ghci?




mercredi 24 juillet 2019

How Can I Pick Two Random Instances From a Array?

So there's a array of monsters I created that has a length of 8. And I want to pick two random monsters to be destroyed. How can I achieve this without the possibility of picking the same monster twice?




Is there a way to create persistent random 4 digit numbers in Google Sheets?

I have to create a unique 4-digit numerical ID's through scripts or formulas only in Google Sheets. I am not allowed to copy and paste the values.




Java Random Class nextInt() to return numbers in a pattern

I'm trying to use the Random class to display a series of random numbers from the set 6, 10, 14, 18, 22 by using the nextInt method and without using an array. I know that I can generate random numbers from 6-22 using the method, but is there any way to specify that it should go in increments of 4?

This code displays 100 random numbers in the range 6-22:

    Random rand = new Random();
    rand.setSeed(40);
    Random rand1 = new Random(40);
    for(int i = 0; i < 100; i++)    {
        System.out.println(rand.nextInt((22 - 6) + 1) + 6);
    }

Ignore the seed value, I need it to display the same series every time the program is run.




Select n random rows from table per group of codes

I have a table full of customer details from insurance policies or quotes. Each one is assigned an output code that relates to a marketing campaign and each occurs 4 times, one per "batch" which just represents a week in the month. I need to select a random 25 percent of the rows per code, per batch number (1-4) to put into another table so I can then hold those rows back and prevent the customer being marketed to.

All the solutions I've seen on stack so far instruct how to do this for a specific number of rows per group using a ROW_NUMBER in an initial CTE query then selecting from that where rn <= a given number. I need to do this but select 25 percent of each group instead.

I've tried this solution but the specific row number doesn't move me any further forward;

Select N random rows in group

Using the linked solution, this is how my code currently is without a complete where clause because I know this isn't quite what I need.

;WITH AttributionOutput AS (
SELECT [Output Code], BatchNo, MonthandYear
FROM [dbo].[Direct_Marketing_UK]
WHERE MonthandYear = 'Sep2019'
And [Output Code] NOT IN ('HOMELIVE','HOMELIVENB','HOMENBLE')
GROUP BY [Output Code], BatchNo, MonthandYear
HAVING COUNT(*) >= 60
)

, CodeandBatch AS (
SELECT  dmuk.PK_ID,
    dmuk.MonthandYear,
    dmuk.PackNo,
    dmuk.BatchNo,
    dmuk.CustomerKey,
    dmuk.URN,
    dmuk.[Output Code],
    dmuk.[Quote/Renewal Date],
    dmuk.[Name],
    dmuk.[Title],
    dmuk.[Initial],
    dmuk.[Forename],
    dmuk.[Surname],
    dmuk.[Salutation],
    dmuk.[Address 1],
    dmuk.[Address 2],
    dmuk.[Address 3],
    dmuk.[Address 4],
    dmuk.[Address 5],
    dmuk.[Address 6],
    dmuk.[PostCode],
    ROW_NUMBER() OVER(PARTITION BY dmuk.[Output Code], dmuk.BatchNo ORDER BY newid()) as rn
FROM [dbo].[Direct_Marketing_UK] dmuk INNER JOIN
 AttributionOutput ao ON dmuk.[Output Code] = ao.[Output Code]
                            AND dmuk.BatchNo = ao.BatchNo
                            AND dmuk.MonthandYear = ao.MonthandYear
)

SELECT URN,
   [Output Code],
   [BatchNo]
FROM CodeandBatch
WHERE rn <= 

I can't see how a ROW_NUMBER() can help me to grab 25 percent of the rows from every combination of Output Code and batch number.




How to generate two random integers such that their running sums have a given ratio

I am trying to generate two random integers each with their own potential range of values. I keep a running sum of each value, and need to ensure that the ratio between these sums stays within range of a given value.

For each trial, I want both numbers to be random. Ie. I don't want to generate a single value and then calculate the other value to make the ratio I want.

The best solution I have found is for each trial, to just generate pairs of random numbers until The pair matches my constraints. However its not guaranteed to find a solution, and may loop for a long time.

import random

XMIN, XMAX = 64, 2500
YMIN, YMAX = 16, 2000
GOAL, THRESH =0.90, 0.03

def trial(sumX, sumY):
  x,y=0,0
  while True:
    x = random.randint(XMIN,XMAX)
    y = random.randint(YMIN,YMAX)
    if abs( (sumX+x)/(sumX+x+sumY+y)-GOAL) <= THRESH:
      return x,y


sumX,sumY=0,0
for I in range(10000):
  x,y=trial(sumX,sumY)
  trial_ratio = x/(x+y)

  sumX, sumY = sumX+x, sumY+y
  sum_ratio = sumX/(sumX+sumY)
  print(f"+({x:5d}, {y:5d}) = {trial_ratio:0.2%}      :     ({sumX:8d}, {sumY:8d})  = {sum_ratio:0.2%}")

The snippet is in python, but the language doesn't matter

The above works as expected, however if possible I would like to be able to terminate faster than just making a random guess and throwing out invalid results.




pick random and unique items SQL

We are trying to populate a table with Random (and unqiue) values between 1-37. The following query is not picking unique however.

truncate table [dbo].[webscrape]
declare @date date = '1990-01-01',
@endDate date = Getdate()

while @date<=@enddate
begin
insert into [dbo].[webscrape](date,value1,value2,value3,value4,value5)
SELECT @date date,convert(int,(RAND()*37-1+1)) value1,
convert(int,(RAND()*37-1+1)) value2,
convert(int,(RAND()*37-1+1)) value3,
convert(int,(RAND()*37-1+1)) value4,
convert(int,(RAND()*37-1+1)) value5

set @date = DATEADD(day,1,@date)
end




How to use possion to estimate arrival time (generate random intergers)?

In my assignment, I'm supposed to use a distribution curve to describe how many minutes will the employee come to work in advanced or later than the planed start time.

I decided to use Poisson distribution to solve my case. However, I don't know how should I assign the parameter to the Poisson function. I want my x-axis is from 0 to 60 minute (integer). The peak of the curve should be show up when x is 15. Should I just assign the lambda as 15?

I don't know if it's correct to use Poisson distribution to estimate the arrival time, and also don't know, if Poisson is correct, then should I just let the lambda be 15 and that's it, how can I set up a specific range (0, 60)?




mardi 23 juillet 2019

Filling out a 2D array of pairs based on column and row criteria

I am trying to create a randomized 2D array based on 16 lists called "teams" of 13 elements each, where each element is a 2 character code for a "match up", or a combination of the name of the team and the name of one of the other teams. For example, "ab" represents a match up between team "a" and team "b". If list "a" has "ab", list "b" must also have a matching "ab" element representing that match up.

My goal is to create a 13 column 2D array where each column has each of the 16 teams play exactly one other team and all match ups for each team are used.

For example: If team "A" plays team "B" in the first column, no other team can play either team "A" or team "B" in that column and over the 13 columns team "A" must play teams "B", "C", "D" twice, teams "E", "F", "G", "H" once, and teams "J", "K", "L" once.

On top of that, I'd love for there to be an element of randomness to how the match ups for each team are arranged within the array so that different combinations of the columns can be generated while still maintaining the requirements. I was thinking that a greedy algorithm might be usable here, but I wasn't sure how to get started actually implementing one in this situation. Any suggested reading or articles are also appreciated.

Here is the total list of teams and match ups:

a: ['ab', 'ac', 'ad', 'ab', 'ac', 'ad', 'ae', 'af', 'ag', 'ah', 'aj', 'ak', 'al']
b: ['ab', 'bc', 'bd', 'ab', 'bc', 'bd', 'be', 'bf', 'bg', 'bh', 'bi', 'bk', 'bl']
c: ['ac', 'bc', 'cd', 'ac', 'bc', 'cd', 'ce', 'cf', 'cg', 'ch', 'ci', 'cj', 'cl']
d: ['ad', 'bd', 'cd', 'ad', 'bd', 'cd', 'de', 'df', 'dg', 'dh', 'di', 'dj', 'dk']
e: ['ef', 'eg', 'eh', 'ef', 'eg', 'eh', 'ae', 'be', 'ce', 'de', 'en', 'eo', 'ep']
f: ['ef', 'fg', 'fh', 'ef', 'fg', 'fh', 'af', 'bf', 'cf', 'df', 'fm', 'fo', 'fp']
g: ['eg', 'fg', 'gh', 'eg', 'fg', 'gh', 'ag', 'bg', 'cg', 'dg', 'gm', 'gn', 'gp']
h: ['eh', 'fh', 'gh', 'eh', 'fh', 'gh', 'ah', 'bh', 'ch', 'dh', 'hm', 'hn', 'ho']
i: ['ij', 'ik', 'il', 'ij', 'ik', 'il', 'im', 'in', 'io', 'ip', 'bi', 'ci', 'di']
j: ['ij', 'jk', 'jl', 'ij', 'jk', 'jl', 'jm', 'jn', 'jo', 'jp', 'aj', 'cj', 'dj']
k: ['ik', 'jk', 'kl', 'ik', 'jk', 'kl', 'km', 'kn', 'ko', 'kp', 'ak', 'bk', 'dk']
l: ['il', 'jl', 'kl', 'il', 'jl', 'kl', 'lm', 'ln', 'lo', 'lp', 'al', 'bl', 'cl']
m: ['mn', 'mo', 'mp', 'mn', 'mo', 'mp', 'im', 'jm', 'km', 'lm', 'fm', 'gm', 'hm']
n: ['mn', 'no', 'np', 'mn', 'no', 'np', 'in', 'jn', 'kn', 'ln', 'en', 'gn', 'hn']
o: ['mo', 'no', 'op', 'mo', 'no', 'op', 'io', 'jo', 'ko', 'lo', 'eo', 'fo', 'ho']
p: ['mp', 'np', 'op', 'mp', 'np', 'op', 'ip', 'jp', 'kp', 'lp', 'ep', 'fp', 'gp']

I know this question is pretty general and kind of weird so please let me know if I can clarify anything and thanks in advance!




Generate random characters from range (0-9 and a-Z)

Im trying to generate 5 characters from range (0-9 and a-Z). Is my solution optimal or did I overthink it a little? Would hardcoding a character list be more optimal?

 const numbers=[
            ...Math.random()
                .toString(36)
                .substr(2, 5),
        ].map(element => (Math.random() > 0.5 ? element : element.toUpperCase())).join('');




Random image with javascript doesnt want to give the src

I want to show a random picture with every refresh but I don't know why my code is not working... probably because I'm bad at javascript, haha.

I tried "3" instead of "imgs.length", but it's still not working - I too don't really want to give an exact number, because the image count may vary.. only for my example I use three images.

var imgs = ['img1','img2','img3'];

function getRandomImage(){
 var rnd = Math.floor(Math.random()*imgs.length);
 document.getElementById('pr_randImage').src = imgs[rnd];
}   
</script>   

<img id="pr_randImage">

Quellcode is just not showing any src at all for the img. What am I doing wrong? I'm thankful for every help.




replace a string of n chars with a random string of n chars in bash

I have a file called tmp.txt. It has chars 'a-z' separated by spaces on one side of a tab delimited file and numbers '0-9.' on the other side. for each line I want to do some random replaces of 1-3 characters. my tmp.txt looks like this:

s h e h a d y o u r 0.9472 0.2074 0.4878 0.2227 0.4998 0.2841 0.5323 0.4254 0.539 0.4981  
d o n t a s k m e t o c a r r y 0.9741 0.0999 0.338 0.0572 0.4514 0.223 0.5036 0.3835 0.4844 0.6306 
e v e n t h e n 0.8549 0.1265 0.5248 0.2713 0.622 0.2011 0.4334 0.4137 0.4788 0.5435

I have written this much of a script so far:

cat tmp.txt | while IFS= read -r line; 
    do 
        for i in {1..3}; 
        do 
            a=$(tr -dc 'a-z0-9' | head -c $i);
            b=$(head /dev/urandom | tr -dc 'a-z0-9' | head -c $i);
            sed -i 's/$a/$b/g';
        done; 
    done

The sed doesn't seem to be finding $line since I get:

sed: no input files
sed: no input files
sed: no input files

I thought that I was still within read -r line in this loop but it seems I am wrong. Does anyone know what I am doing wrong?

Thanks in advance




How to show random divs on page load?

I need to show 3 random divs on each page load. PLease help.

<div class="job-block1">
<h1> job block 1's content </h1>
</div>

<div class="job-block2">
<h1> job block 2's content </h1>
</div>

<div class="job-block3">
<h1> job block 3's content </h1>
</div>

<div class="job-block4">
<h1> job block 4's content </h1>
</div>




function to generate and display N random numbers between 0 and 1

I have to generate randoms numbers, i have a code running and working, but it doesnt seems random, it generates sequences, is right anyway? or is there another way to do this

public static void main(String[] args) {

    Scanner teclado = new Scanner(System.in);
    System.out.println("Ingrese el numero N");
    int n = teclado.nextInt();

    for (int i = 1; i <= n; i++){

        double d = numerosAleatorios(i,n);
        System.out.println(d);
    }

}

public static double numerosAleatorios(double b, double c){

     return  b / c;
}




How to randomly sample dataframe (sample_n) and calculate summary statistics after using group_by, and iterate 999 times?

I want to resample my dataframe (test_df) and calculate summary statistics (mean and standard deviation) of a numeric response variable (sp_rich), after grouping data based on two categorical factors (plant_sp = plant species, and site). I would then like this process to be iterated, say 999 times. Additionally, I would like to resample the data frame using multiple sample sizes, and calculate the above statistics and perform the iteration.

Ultimately, I would really like this to be in a dplyr/tidy framework, as I am more familiar with this style, but am open to base R/other options.

So here is an example data frame:

test_df <- structure(list(plant_sp = c("plant_1", "plant_1", "plant_1", "plant_1", "plant_1",
                                       "plant_1", "plant_1", "plant_1", "plant_1", "plant_1", 
                                       "plant_2", "plant_2", "plant_2", "plant_2", "plant_2",
                                       "plant_2", "plant_2", "plant_2", "plant_2", "plant_2"), 
                          site = c("a", "a", "a", "a", "a",  
                                   "b", "b", "b", "b", "b",  
                                   "a", "a", "a", "a", "a",
                                   "b", "b", "b", "b", "b"),
                          sp_rich = c(5, 3, 5, 3, 5, 
                                      7, 8, 8, 8, 10,
                                      1, 4, 5, 6, 3, 
                                      7, 3, 12, 12,11)), 
                     row.names = c(NA, -20L), class = "data.frame", 
                     .Names = c("plant_sp", "site", "sp_rich"))

# I can calculate the summary statistics for one iteration,   
and for one sample size at a time:

mean_calc <- test_df %>%
  group_by(plant_sp, site) %>%
  do(sample_n(., 3)) %>%
  summarise(mean = mean(sp_rich),
            sd = sd((sp_rich))) %>%
  mutate(sample_size = n())
mean_calc

# I can also manually perform the calculations manually for   
each sample size, and put the data together (hack):

# Do this manually for two different samples sizes
mean_calc_3 <- test_df %>%
  group_by(plant_sp, site) %>%
  do(sample_n(., 3)) %>%
  summarise(mean = mean(sp_rich),
            sd = sd((sp_rich))) %>%
  mutate(sample_size = 3)
mean_calc_3

mean_calc_4 <- test_df %>%
  group_by(plant_sp, site) %>%
  do(sample_n(., 4)) %>%
  summarise(mean = mean(sp_rich),
            sd = sd((sp_rich))) %>%
  mutate(sample_size = 4)
mean_calc_4

mean_calc <- bind_rows(mean_calc_3, mean_calc_4) 
(mean_calc <- mean_calc %>%
    group_by(plant_sp, site, sample_size) %>%
    arrange(sample_size, plant_sp, site))

I would really like to automate performing these calculate across multiple sample sizes (e.g. n = 3, n = 4, in this example, the proper data would have ~ 5-10 different sizes classes), and then iterate this entire process 999 times.

The structure of the mean_calc df is ultimately the output that I am looking for, just instead of calculating the mean and sd once, the summary statistics are calculated 999 times and averaged.




Why the rand() command just generates positive integers and on a specific range even if i don't set a range

I am trying to fill a vector with 5000 random numbers. Each number is an integer. But i am wondering why rand() only gives unsigned integers and also it never gives the max values that an integer can hold. Is there a reason for that?

unsigned seed = time(0);
srand(seed);

vector<int> vect(5000);

for (int i = 0; i < vect.size(); i++)
{
    vect[i] = rand();
}




What is the algorithm used in random number generator of go programming language

What exactly is the algorithm used in the pseudo random generator of GO programming language?

I have gone through the documentation of GO, but in vain.




Random list only with -1 and 1

I need to create random list which consists only of -1 and 1 like -1,1,1,-1,-1 (without zeros). My current coding adds 0 that doesn't suite me.

import random
for x in range(10):
    print (random.randint(-1,1))




lundi 22 juillet 2019

How to make a powershell or batch file that picks a random file from a folder, executes it and then deletes it

I'm looking to execute a bunch of similar .ppx files on different cloud windows servers from a single common dropbox folder.

I thus need to make a script that randomly selects a file from a folder, executes it to open the Proxifier profile and then deletes the file from the folder (Dropbox folder) so when I'm setting up the next server, the same script file cannot select the previously opened .ppx file.

So far I have:

Set "SrcDir=C:\Users\Admin\Dropbox\Files"
Set "ExtLst=*.ppx"
Set "i=0"
For /F "Delims=" %%A In ('Where /R "%SrcDir%" %ExtLst%') Do (Set /A i+=1
    Call Set "$[%%i%%]=%%A")
Set /A #=(%Random%%%i)+1
Call Start "" "%%$[%#%]%%"

This picks a random file from the folder but I can't quite figure out what to add to delete that file it picked.




How do you set up the syntax for a random number generator using cpp?

Let me preface by saying I am very new to coding but enjoy learning. I want to randomly generate a number then follow with 700 if statements that will ask a question according to what number is generated. So from the user pov it will randomly ask questions and then will generate another number after.

I've tried the timing random number generators. I can't seem to get rand operator to work. I just want a super basic generator.

#include <iostream>
#include <cstdlib>

using namespace std;

int main()
{
string a = "placeholder";
cout << "Welcome to Basic Strategy Practice" << endl;
cout << "You are given two aces and the dealer is showing a four. Hit, 
double, or split?" << endl;
cin >> a;
if (a == "split"){
    cout << "Correct!" << endl;
}
else {
    cout << "Incorrect" << endl;
}


return 0;
}

Basically, I would encapsulate the above code in an if statement that specifies which number was generated after each question is asked. I would think you would just put the if statement inside a while loop of some sort. Thanks!




Different pseudo random numbers between C++ and Python implementations

I am trying to reproduce the C++ code into Python 3.6, but the sequence of pseudo random numbers is different in each implementation. The seed are the same on both implementation and as far as I know, both use Mersenne Twister algorithm.

What am I doing wrong?

C++:

#include <random>
#include <iostream>
int main(int argc, char* argv[])
{  
    std::mt19937 gen(2);
    std::uniform_int_distribution<> dis(0, 61);

    for (int n=0; n<10; ++n)
        std::cout << dis(gen) << ' ';

    return 0;
}

Python 3.6:

import numpy as np
rng = np.random.RandomState(2)
for i in range(10):
    print(str(rng.randint(0, 62)))

Note: randint has an exclusive upper bound. That is why I use 61 on C++ code, but 62 on Python code.




how to generate random numbers with conditons impose in R?

I would like to generate 500 different combination of a,b,and c meeting the following conditions

  1. a+ b+ c = 1 and
  2. a < b < c

here is a basic sample of generating random numbers, however, I need to generate it based on aforementioned conditions.

Coeff = data.frame(a=runif(500, min = 0, max = 1),
b=runif(500, min = 0, max = 1),
c=runif(500, min = 0, max = 1))




What am i doing wrong? random number generation half working

I am writing a text game I have all the functions working so far except this... and it does work but it doesn't work I don't understand why I can 't make it work the way I want it to.

Made the code work using hard int input no problems.


if (response.ToUpper() == "PLAY") {
int damageCalc = Combat.Dice(Items.Slot1Damage);

Console.WriteLine("You roll a 40 Sided Dice! Damage! {0}",damageCalc);
  break;
}

//Items.Slot1Damage is a public Int that returns 40.

/*
  public static int Slot1Damage;
  Items.Slot1Damage = 40;
*\


//Combat.Dice calls Random.Next Function where the value in Combat.Dice is the high value - 
//Below is Combat.Dice
/*

public class Combat{

public static int Dice(int DiceValue = 0) {

Random r = new Random();

int result = r.Next(1,DiceValue);
return result;

}

public static string FireBall(string target) {

int fireBallDamage = Dice(100);
Console.WriteLine("You Inflicted {0} Damage with your Fire Ball Spell to {1}!",fireBallDamage, target);
return target;
}


}

*/


I want it to roll a 40 sided dice based on the value of the variable being 40




How to generate a random number using an array

I want to generate a random number between range. This is a discord bot btw. So if someone wants to generate a random number they need to write !rn min max example: !rn 1 10. The min and max numbers are going to an array called args. min is in args[0] and max is in args[1]. Now i want to make the bot send the random number using args[0] and args[1]. Here is what i tried to do:

if (msg.startsWith(prefix + 'RANDOMNUM') || msg.startsWith(prefix + 'RN')) { message.channel.send(Math.floor(Math.random() * args[0]) + args[1]); }

It checks if someone writes !rn or !randomnum, and then it's supposed to generate a random number between args[0] and args[1]. Now there are two problems. First one is if the min number is 1, the bot will send the max number the user wrote. So if i write !rn 1 5, it will send the number 5, no matter how many times you try. Second problem if the min number is not 1, it will take the min number, make it to 1, and add to it the max number. Sounds weird but here is an example: if i write !rn 4 8 it will send 18. if i write !rn 2 5 it will send 15. What am i doing wrong?




SHA1PRNG SecureRandom behavior is different after seeding on java11

I am using java.security.SecureRandom with "SHA1PRNG" angorithm to generate encryption keys. This is a historical code used to encrypt lesser important data. Nevertheless when we've switched from java8 to java11, our code stopped working. Here's the test case made to reproduce the situation:

@Test
void srEncryptionSeedTest() throws NoSuchAlgorithmException
{
    final long versionSalt = 1850498708034063014L;
    final long customSalt  = -919666267416765972L;

    final SecureRandom sr = SecureRandom.getInstance("SHA1PRNG");
    sr.setSeed(versionSalt);
    final long l1 = sr.nextLong();
    final long l2 = sr.nextLong();

    sr.setSeed(customSalt);
    final long k1 = sr.nextLong();
    final long k2 = sr.nextLong();

    // check l1 and l2
    Assert.assertEquals(l1, 6338935000439666355L);
    Assert.assertEquals(l2, -7355545655857008441L);

    // Seeding
    // check k1 and k2
    Assert.assertEquals(k1, -2226559466996804670L); // 
    Assert.assertEquals(k2, -3123855249705841778L);
}

This works fine on java11, but on java8 we have k1=-4273821888324981770 and k2=3053251164341917236, so the test fails. As you can see, the test starts failing after setting exactly the same seed after producing the same amount of same random numbers, so I suspect that the state of the RNG is different, but debugging wasn't helped me (I can not understand why it's different). This can be easily reproduced on any operation system.

Some facts about the Java8 JVM:

java.vendor -> Oracle Corporation // same goes on OpenJDK builds
java.version -> 1.8.0_202-ea // same goes on 1.8.0_181
java.vm.info -> mixed mode
java.specification.version -> 1.8
java.runtime.name -> Java(TM) SE Runtime Environment

Some facts about the Java11 JVM:

java.vendor -> AdoptOpenJDK
java.version -> 11.0.3
java.vm.info -> mixed mode
java.specification.version -> 11
java.runtime.name -> OpenJDK Runtime Environment

Any help will be appreciated.




Why does the order of output not getting changed when using random and threadpool?

I am trying to learn about using threadpool thru Executors. I am trying to print the factorial result of 10 numbers from 1 to 10 and then i let the thread sleep for 1-5 seconds which will chosen as randomly.

Here is my Callable Task

    @Override
    public Integer call() throws Exception {
        int i= 1, temp = num;
        while (temp > 1){
            i = i*temp;
            temp--;
        }
        int x = ThreadLocalRandom.current().nextInt(1, 6);
        Thread.sleep(x * 1000);
        return i ;
    }

Here is my main class:

public static void main(String[] args) throws InterruptedException, ExecutionException {
    ExecutorService e = Executors.newFixedThreadPool(10);
    Set <Future<Integer>> set= new HashSet<Future<Integer>>();
    int totalSum = 0;
    for (int i = 1; i <= 10; i++) {
        set.add(e.submit(new FactorialCalculator(i)));
    }
    while(!set.isEmpty()) {
        Iterator<Future<Integer>> iter =  set.iterator();
        Future<Integer> fi = iter.next();
        if(fi.isDone()) {
            int temp = fi.get();
            System.out.println(temp);
            iter.remove();  
        }   
    }
}

I ran this program on Eclipse 10 times, output remains same everytime.

Then i compile it thru command prompt and then ran it there. Output came different from eclipse but again running multiple times will produce same output here.

Why the ouput doesn't come randomly?

Thanks in advance.




dimanche 21 juillet 2019

Python Turtle Harmonograph Setup

So recently I've been entertaining the idea of making a harmonograph, but I'm not sure where to start. A harmonograph is basically "a mechanical apparatus that employs pendulums to create a geometric image."

For libraries, I'm guessing turtle, math, and probably random will need to be included, but I'm completely with the actual calculation aspect of it. The random library would be mostly for creating a new image each time.

I would want the user to choose their background color, for the program to be under 100 lines and to watch it draw, not just instantly create the harmonograph.




Random number in guessing game

I am trying to write a Number Guessing Game program, so the program generates a random number, and the program gives prompts as too high, too low, until the user gets its write. However, the Random generator either generates the same random number each time, or it says "too high" for one user input and then "too low" for the user input directly after/before

I have moved the random generator inside my while loop, and in that case, it says the input is "too high", and the number following it is "too low". When I move the Random Generator outside the loop, it just generates the same number for each irritation of the game.

import java.util.Scanner;
import java.util.Random;
public class numberGuessingGame
{

    public static void main (String[] args) 
    {
        int randomNumber, userNumber = 0, guesses = 0;
        final int MAX = 100;
        char playAgain, playGame = 'y'; 


        Random generator = new Random();


    //ask user if they wish to play   
        System.out.println("Would you like to play the Number Guessing" 
                        " y / n");
        Scanner scan = new Scanner (System.in);

        playGame = scan.next().charAt(0); 

//while loop to continue to execute game as long as the user enters 'y'

        while (playGame == 'y'){
        if (playGame != 'y') break;

        randomNumber = generator.nextInt(MAX) + 1;


        System.out.println("Please pick a number between 1 and 100.");
        userNumber = scan.nextInt();

        //high and low sugguestion
        if (userNumber > randomNumber)
        System.out.println("Number is too high, try something lower.");
        if (userNumber < randomNumber)
        System.out.println("Number is too low, try something higher.");
        if (userNumber == randomNumber) {
        System.out.println("That number is correct!");
        System.out.println("Would you like to play again? y/n");
        playGame = scan.next().charAt(0);
    }
        //counter to keep running total of times guessed
        guesses++;
        System.out.println("You have guessed " + guesses + " times!");


    }

    //break statement skips here when 'n' is entered in
    // the game prompting question
    System.out.println("Thanks for playing, have a nice day!");  


}

}

The program should be generating a new random number for each irritation of the game, which will be prompted after each correct guess of the randomNumber.




A problem with the random library in functions

When I use the random library in functions it doesn't work well at all. it prints inncorrect things like : This and this but if I am not using functions it works completly fine.

I tried to create a function that returns the value of the random number but it fails and prints something weird

Works good:

#include <iostream>
#include <random>
#include <string>
using namespace std;
int main()
{
    random_device rd;
    mt19937 number(rd());
    uniform_int_distribution <>random(1, 3);
    int num = random(number);
    cout << "The computer choose: " << endl;
    if(num == 1){
        cout << "one" << endl;
    }
    if (num == 2) {
        cout << "two" << endl;
    }
    if (num == 3) {
        cout << "three" << endl;
    }
    cout << num; // to check the real number

Doesn't work good:

#include <iostream>
#include <random>
#include <string>
using namespace std;
int random(int num);
int main()
{
    int num = 0;
    cout << "The computer choose: " << endl;
    if(random(num) == 1){
        cout << "one" << endl;
    }
    if (random(num) == 2) {
        cout << "two" << endl;
    }
    if (random(num) == 3) {
        cout << "three" << endl;
    }
    cout << random(num); // to check the real number
}
int random(int num) {

    string call;
    random_device rd;
    mt19937 number(rd());
    uniform_int_distribution <>random(1, 3);
    num = random(number);
    return num;
}




Output of code with a seed differs each run

I have been getting into reinforcement learning lately and wanted to see how the Augmented Random Search would work. I used a code found on github: https://gist.github.com/ZSalloum/61828d5f2b3805b675fb5b34dbf6b73d#file-ars-py

The code works fine but the output differs each run. Even though there is a random seed set at line 143.

I feel like the only line where randomness is used is in line 67 where random matrices are drawn using numpy. When I used that method by itself, the random seed worked just fine.

Is there something I am missing here?

Thanks in advance




How can I set range to the random library

I really don't like the rand() function.I wanted to use the library but I don't really know how to set up a range for example from 1 to 3. I want to "random" these numbers(1,2,3) and not huge numbers like 243245.This code is how you can use the random library and print random numbers

#include <iostream>
#include <string>
#include <random>
using namespace std;
int main()
{
    minstd_rand simple_rand;

    simple_rand.seed(NULL);

    for (int ii = 0; ii < 10; ++ii)
    {
        std::cout << simple_rand() << '\n';
    }
}




How get the categories from the random post widget

I am trying to print the categories attached to the post chosen by the random post widget, but my code do not print those categories, but some else, and the same each time the random post is generated:

// Get the random posts.
    $random = arpw_get_random_posts( $instance, $this->id );


    // Check if the random posts exist
    if ( $random ) : 

        // Output the theme's $before_widget wrapper.
        echo $before_widget;

        // If both title and title url is not empty, display it.
        if ( ! empty( $instance['title_url'] ) && ! empty( $instance['title'] ) ) {
            echo $before_title . '<a href="' . esc_url( $instance['title_url'] ) . '" title="' . esc_attr( $instance['title'] ) . '">' . apply_filters( 'widget_title',  $instance['title'], $instance, $this->id_base ) . '</a>' . $after_title;

        // If the title not empty, display it.
        } elseif ( ! empty( $instance['title'] ) ) {
            echo $before_title . apply_filters( 'widget_title',  $instance['title'], $instance, $this->id_base ) . $after_title;
        }

        // Get the random posts query.

        echo $random;



 for ($x = 0; $x <= 4; $x++) {
  $cat_id =$instance['cat'][$x];
echo  get_cat_name ($cat_id); 

 }




How to extract the seed of PHP random function results?

I know that many random functions on many programming languages are possible to predict via seed extraction from its function results examination.

Can someone please post a function that does it for PHP random function?

Thanks in advance!




TestU01's SmallCrush for PRNG

I haven't found a similiar question anywhere. I've heard that a good linear congruential generator should pass SmallCrush test

I haven't found any information whether it can be used for my own LCG (Python code below)

I downloaded the TestU01 suite but I don't see that it could be used to test my own generator. It is possible?

LCG:

import numpy as np

class LCG(object):

    UZERO: np.uint32 = np.uint32(0)
    UONE : np.uint32 = np.uint32(1)

    def __init__(self, seed: np.uint32, a: np.uint32, c: np.uint32) -> None:
        self._seed: np.uint32 = np.uint32(seed)
        self._a   : np.uint32 = np.uint32(a)
        self._c   : np.uint32 = np.uint32(c)

    def next(self) -> np.uint32:
        self._seed = self._a * self._seed + self._c
        return self._seed

    def seed(self) -> np.uint32:
        return self._seed

    def set_seed(self, seed: np.uint32) -> np.uint32:
        self._seed = seed

    def skip(self, ns: np.int32) -> None:
        """
        Signed argument - skip forward as well as backward

        The algorithm here to determine the parameters used to skip ahead is
        described in the paper F. Brown, "Random Number Generation with Arbitrary Stride,"
        Trans. Am. Nucl. Soc. (Nov. 1994). This algorithm is able to skip ahead in
        O(log2(N)) operations instead of O(N). It computes parameters
        A and C which can then be used to find x_N = A*x_0 + C mod 2^M.
        """

        nskip: np.uint32 = np.uint32(ns)

        a: np.uint32 = self._a
        c: np.uint32 = self._c

        a_next: np.uint32 = LCG.UONE
        c_next: np.uint32 = LCG.UZERO

        while nskip > LCG.UZERO:
            if (nskip & LCG.UONE) != LCG.UZERO:
                a_next = a_next * a
                c_next = c_next * a + c

            c = (a + LCG.UONE) * c
            a = a * a

            nskip = nskip >> LCG.UONE

        self._seed = a_next * self._seed + c_next


#%%
np.seterr(over='ignore')

a = np.uint32(1664525)
c = np.uint32(1013904223)
seed = np.uint32(2**32)

rng = LCG(seed, a, c)
q = [rng.next() for _ in range(0, 2500000)]
# print(q)




samedi 20 juillet 2019

3D plotting in python - random (prng - LCG)

I am trying to create a 3d chart in python for the following linear congruential generator:

import numpy as np

class LCG(object):

    UZERO: np.uint32 = np.uint32(0)
    UONE : np.uint32 = np.uint32(1)

    def __init__(self, seed: np.uint32, a: np.uint32, c: np.uint32) -> None:
        self._seed: np.uint32 = np.uint32(seed)
        self._a   : np.uint32 = np.uint32(a)
        self._c   : np.uint32 = np.uint32(c)

    def next(self) -> np.uint32:
        self._seed = self._a * self._seed + self._c
        return self._seed

    def seed(self) -> np.uint32:
        return self._seed

    def set_seed(self, seed: np.uint32) -> np.uint32:
        self._seed = seed

    def skip(self, ns: np.int32) -> None:
        """
        Signed argument - skip forward as well as backward

        The algorithm here to determine the parameters used to skip ahead is
        described in the paper F. Brown, "Random Number Generation with Arbitrary Stride,"
        Trans. Am. Nucl. Soc. (Nov. 1994). This algorithm is able to skip ahead in
        O(log2(N)) operations instead of O(N). It computes parameters
        A and C which can then be used to find x_N = A*x_0 + C mod 2^M.
        """

        nskip: np.uint32 = np.uint32(ns)

        a: np.uint32 = self._a
        c: np.uint32 = self._c

        a_next: np.uint32 = LCG.UONE
        c_next: np.uint32 = LCG.UZERO

        while nskip > LCG.UZERO:
            if (nskip & LCG.UONE) != LCG.UZERO:
                a_next = a_next * a
                c_next = c_next * a + c

            c = (a + LCG.UONE) * c
            a = a * a

            nskip = nskip >> LCG.UONE

        self._seed = a_next * self._seed + c_next


#%%
np.seterr(over='ignore')

a = np.uint32(1664525)
c = np.uint32(1013904223)
seed = np.uint32(2**32)

rng = LCG(seed, a, c)
q = [rng.next() for _ in range(0, 10000)]
# print(q)

I would like the chart to change every x seconds for a given n - like this (George-Marsaglia).

It's not necessary that it changes over time.

I tried to adapt to the following code butI don't know how to do it with my generator:

from mpl_toolkits.mplot3d import Axes3D
from matplotlib import cm
import matplotlib.pyplot as plt
import numpy as np
import os

def lcg (X, a, c, m):
    return (a * X + c) % m;

X = []
Y = []
Z = []

n = int(input("N : "))

prev = 0
for i in range(n):
    prev = lcg(prev,43,5,4096)
    if i % 3 == 0:
        X.append(prev)
    elif i % 3 == 1:
        Y.append(prev)
    else:
        Z.append(prev)

X = np.array(X)
Y = np.array(Y)
Z = np.array(Z)

fig = plt.figure()
ax = fig.gca(projection='3d')
ax.set_aspect('equal')
ax.set_title('N = ' + str(n))

scat = ax.scatter(X, Y, Z)

max_range = np.array([X.max()-X.min(), Y.max()-Y.min(), Z.max()-Z.min()]).max() / 2.0

mid_x = (X.max()+X.min()) * 0.5
mid_y = (Y.max()+Y.min()) * 0.5
mid_z = (Z.max()+Z.min()) * 0.5
ax.set_xlim(mid_x - max_range, mid_x + max_range)
ax.set_ylim(mid_y - max_range, mid_y + max_range)
ax.set_zlim(mid_z - max_range, mid_z + max_range)

i = 0
while os.path.exists('fig%s.png' % i):
    i += 1

plt.savefig('fig' + str(i) + '.png')
plt.show()

It is possible to adapt the following code to my generator?




Reverse engineer multinomial logistic regression data

I am working on a multinomial logistic regression problem (i.e., where I want to classify some unordered, independent levels of a nominal outcome variable). My issue is that I know the levels of the outcome variable (in this example, y=c('a','b','c')) and I know the predictor variables, their levels, and their class (here, either numeric/integer or nominal). I know what the approximate distributions should be between each predictor and the outcome (e.g., higher values of x appear more frequently with y='a', otherwise low values of x are randomly distributed across the other levels of y).

Essentially, I want to do 4 things: 1) generate a dataset of these variables that approximate my specified distributions; 2) run a multinomial logistic regression on the data, nnet::multinom(y~.,df); 3) use the resulting model to predict() the probability of each y level using new data; and 4) retrieve the probabilities for further processing. I am not interested in the MLR model's accuracy or p-values, so I don't need to split my data into train/test samples and do k-folds cross-validation or anything.

My initial thought was that this type of reverse engineering a dataset based on some user-specified distributions cannot be too uncommon, and that there was probably an R package/function that could do this. I haven't found any so far. My approaches so far have been as follows: manually specify the distributions for each level of each predictor against each level of the outcome, like so:

rm(list=ls())
set.seed(123)

# specify vars and levels -- y=outcome var
y <- c('a','b','c')
x <- c(1:5)
p <- c(1:4)
r <- c(1:8)
q <- c('foo','bar','hello','world') # nominal var

# sample data based on user-specified distributions/probs
df1 <- data.frame(x1=sample(x,100,T,prob=c(0.1,0.1,0.2,0.25,0.35)),
                  y='b')
df2 <- data.frame(x1=sample(x,200,T,prob=c(0.35,0.25,0.2,0.1,0.1)),
                  y=sample(c('a','c'),200,T))
df <- rbind(df1,df2)

# check distribution of x1 levels v. y levels
table(df$x1,df$y)
     b  a  c
  1  7 38 30
  2 11 29 26
  3 22 17 22
  4 26 14  7
  5 34 12  5

The issue is that this is tedious as the number of predictors becomes larger and they have more levels. My next approach was to generate a random sample of data, run the MLR model, and tweak the model weights.

# create random sample
df <- ldply(mget(ls()),
            function(x) sample(x,1000,T)) %>% 
  gather(k,v,-`.id`) %>%
  spread(`.id`,v) %>% select(-k)
str(df)
# change back vars to numeric
df[,c('p','r','x')] <- 
  apply(df[,c('p','r','x')],2,function(x) as.numeric(x))

glimpse(df)

Observations: 1,000
Variables: 5
$ p <dbl> 2, 2, 3, 1, 3, 2, 2, 4, 2, 4, 4, 3, 2, 4, 1, 4, 2, 1, 4, 3, 1, 3, 4, 3, 2, 2, 3...
$ q <chr> "bar", "bar", "foo", "bar", "world", "hello", "foo", "hello", "world", "hello",...
$ r <dbl> 2, 2, 1, 6, 6, 3, 4, 8, 6, 6, 2, 2, 8, 7, 7, 6, 3, 2, 4, 5, 2, 7, 1, 6, 3, 7, 8...
$ x <dbl> 2, 5, 1, 3, 3, 5, 2, 4, 1, 3, 5, 1, 5, 5, 2, 1, 1, 4, 4, 1, 5, 1, 5, 4, 4, 3, 2...
$ y <chr> "a", "c", "b", "a", "b", "a", "b", "c", "c", "b", "c", "c", "b", "a", "c", "b",...

# graph distribution of each predictor against each outcome -- not run here
# df %>% gather(k,v,-y) %>% group_by(y,k,v) %>%
#   summarise(n=n()) %>%
#   mutate(prop=n/sum(n)) %>%
#   ggplot(aes(y,prop,fill=v)) + geom_bar(stat='identity',position='dodge') +
#   facet_wrap(~k,scales='free') + theme(legend.position = 'none')

# run MLR model
m <- multinom(y~.,df)
summary(m)$coefficients
m$wts # coefficients from model

# adjust weight 16, which is x against y=b
m$wts[16] <- 1

Again, though, this is tedious when the number of predictors and levels is large. Plus as I continue altering the model weights and predicting new data, I get some unexpected probabilities (obviously, I don't know enough about MLR to confidently use this method).

So, I am more or less stuck at this stage. I have considered using multiple imputation or bootstrapping methods to generate the desired data, but I don't think either method is applicable here. MI will impute data for incomplete cases, whereas I want to specify a limited number of complete cases and extrapolate from there. Similarly, bootstrapping will resample the data assuming that the sample distribution approximates the population distribution. Again, I don't see how I can specify a limited number of cases that will validly do that (perhaps bootstrapping plus permutation/shuffling ?).

Anyways, any help/suggestions are greatly appreciated here. And thanks to anyone that actually reads this lengthy post!