jeudi 31 janvier 2019

How can I restart a CSS animation with random values in a loop?

I have an element which is randomly animated with CSS and JS with the help of CSS custom properties in the following way:

CSS:

:root {
  --animation-name: vibrate-1;
}
#my-element {
  animation: 3.3s 1 alternate var(--animation-name);
}
@keyframes vibrate-1 {
  0% {
    opacity: 0;
    transform: scale(0.95);
  }

  50% {
    opacity: 1;
    transform: scale(1);
  }
  100% {
    opacity: 0;
    transform: scale(0.9);
  }
}
@keyframes vibrate-2 {
  0% {
    opacity: 0;
    transform: scale(0.5);
  }

  50% {
    opacity: 1;
    transform: scale(0.9);
  }
  100% {
    opacity: 0;
    transform: scale(0.5);
  }
}
@keyframes vibrate-3 {
  0% {
    opacity: 0;
    transform: scale(0.3);
  }

  50% {
    opacity: 1;
    transform: scale(1);
  }
  100% {
    opacity: 0;
    transform: scale(0.8);
  }
}

JS:

var my-element = document.querySelector('#my-element');

function setProperty(number) {
  my-element.style.setProperty('--animation-name', 'vibrate-'+ number);
}

function changeAnimation() {
  var number = Math.floor(Math.random() * 3) + 1;
  setProperty(number);
  /* restart the animation */
  var clone = my-element.cloneNode(true);
  my-element.parentNode.replaceChild(clone, my-element);
}

my-element.addEventListener('animationend', changeAnimation, false);

The idea behind is to have a set of animations which switch on each animation’s end randomly to another one. (that for the opacity in the end is always 0 to make a smooth invisible switch.)

Now (surprisingly – as I am quite a newbie to JS;-) this code above runs just fine, except that it does only once and then stop.

I now there are JS loop techniques but I have no idea how to exactly implement them inside this workflow.

Can someone help me? Thanks in advance!

Stefan




Verifiable random number

I need to generate a large set of 10 digit random numbers. The number has to be verifiable in some way that this it was generated by this system. I could thik of some approaches which I describe below

Approach 1: Add some parts of this random number with values that are part of the system internals, example, IP, MAC address, timestamp, hashvalue of customer & others.

This reduces the randomness due to some static/lesser dynamic parts occupying the random number. However, anyone who knows this pattern can generate a number, unless the value is not internal.

Approach 2: Mod-97 10 Attach the digest to this number so that it is verifiable. However, this, I believe, can also be generated by anyone who knows there is digest attached to every random number. Am I right?

Approach 3: Generate the digest including a secret key that is part of the system. Unless someone knows the secret key, they cannot create a random number with a digest.

Have any of you solved this in a different way? Would be glad if you could point be to a direction to this solution, or give me an answer itself.

Cheers




2 threads always have get the same results by using random methods

Thread t1 = new Thread(new Runnable() {
        public void run(){
            int i = 0;
            while(secondsPassed <= 5) {
                while(list.length()<4 && secondsPassed <= 5);
                Random r = new Random();
                if(r.nextInt(100) < 10) {
                    list.removeFirst();
                    i++;                
                    try {
                        Thread.sleep(20);
                    } catch (InterruptedException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }                       
                }
            }
            System.out.println("Thread t1 is finished with  "+ i);
        }
    });

    Thread t2 = new Thread(new Runnable() {
        public void run(){
            int i = 0;
            while(secondsPassed <= 5) {
                Random a = new Random();
                System.out.println("Thread t2 is turn  "+ i + "with" + a.nextInt(100));
                char c = (char)(a.nextInt(23) + 'D');
                if(a.nextInt(100) < 10) {
                    list.insert(c);
                    i++;
                }
                try {
                    Thread.sleep(20);
                } catch (InterruptedException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
            System.out.println("Thread t2 is finished with  " + i);
        }
    });

For my thread 1 and thread 2 they are expecting to remove and adding a node into the linked list, and they are constrainted by Random() method of a possibility of 10%, and after each turn, they will sleep for 20ms. However, everytime I run my program, thread 1 and 2 will always generate the same possiblities.




Produce Random Numbers in Laravel with Vue.js

I'm new in Vue.js and I'm having a hard time producing random numbers. In my Vue file, I have this piece of code under script:

var numeral = require("numeral");
Vue.filter("formatNumber", function(value)
{
    return numeral(value).format("0,0");
});

...calling the method:

getRandomNum()
    {
        this.like = Math.random() * 100;
        this.rate = Math.random() * 10;
        this.comment = Math.random() * 100;
    }

works like a charm that produces the number of likes, ratings and comments in my html:

enter image description here

However, if you'd notice, even though they're random in a sense whenever I refresh my DOM, technically they're still all the same in each rows. My question is, is there a way that I can produce a whole totally different random numbers in each row? Thanks! Please respect, I'm new to Vue.js.




Can i create an object where the value of the property is a randomly generated number?

I want to create an array of objects, and in each object, I want to have the key being an item, and the value to be a randomly generated number, how could I go about this?




jQuery: Sometimes random fails

I have a blog which advertises x3 articles randomly at the bottom of each post. Sometimes, this feature fails to display all 3 (1 missing).

I can't see where the problem lies.

JQuery

$.get("https://www.citychurchchristchurch.co.nz/blog.php", function(data) {
    var $quotes = $(data).find(".container-articles-5"),
      count = $quotes.length,
      $random = function() {
        return $quotes.eq(Math.floor(Math.random() * count));
      };
    $(".blog-ad-1").append($random);
});

HTML (where ads are displayed)

<aside class="blog-ad-4">
    <div class="blog-ad-5">
      <div class="blog-ad-3">
        <div class="blog-ad-1"></div>
      </div>
      <div class="blog-ad-3">
        <div class="blog-ad-1"></div>
      </div>
      <div class="blog-ad-3">
        <div class="blog-ad-1"></div>
      </div>
    </div>
</aside>

All 3 ads should display. View live demo here (near the bottom): https://www.citychurchchristchurch.co.nz/blog/eo-cycling-20181030




How to take a random sample from a data frame based on factors with restrictions in R?

I have been thinking about this for a while, I am sorry if this is too easy but I am just starting R.

I have a basic data set and want to create two "teams" based on three factor columns. I am trying to distribute players in proportionally according to some categories I defined, in this case

Jugador <- c("Player1","Player2","Player3","Player4","Player5","Player6","Player7","Player8","Player9","Player10","Player11","Player12","Player13")
RangoEdad <- c("3","2","2","3","3","2","2","2","3","3","1","1","1")
Sexo <- c("M","F","M","M","F","M","F","M","M","F","F","M","M")
Fam <- c("1","2","2","3","3","3","4","4","5","5","5","5","5")

draft <- cbind(Jugador, RangoEdad,Sexo,Fam)
draft.df <- as.data.frame(draft)

draft.df$RangoEdad <- as.factor(draft.df$RangoEdad)
draft.df$Fam <- as.factor(draft.df$Fam)

All I can think of now is creating selections of combinations of factors and then sampling and "drawing" from each one of them. But I believe there is a better solution.

The expected output should be two teams with at least 1 player from each category (when possible, Player 1 has own category).




Fetch Uint16 from readable stream

In the following example I'm fetching 2 raw bytes.

fetch('https://www.random.org/cgi-bin/randbyte?nbytes=2')
    .then(response=>response.body.getReader())
    .then(reader=>0/*Here convert to Uint16*/)

Any idea how to convert the resulting readable stream Uint16 integer from using 2 bytes?




Random hero header image on refresh

Bear with me, concrete5 NOOBY here! My goal here is to have a page randomly pick a hero header image on refresh from a set of, let's say, 5 images. I also want to have the ability to add a common caption for all images. The caption should be horizontally and vertically centered in the image! Im trying to get away from an image slider. Is this possible?

I already tried using the "Random Image" add-on but that does not allow me to add a caption.

Any help is appreciated!




random_device()() work only for initializing data members

This is typical sequence of declarations/definitions for generating random numbers in C++11:

std::random_device rd
std::default_random_engine gen(rd());
std::uniform_int_distribution<> dist(1, 6);

rd is only used for seeding the generator gen, so I am thinking of not defining it in particular. In stead, I would like to use a temporary for this purpose:

int main() {
    std::default_random_engine gen(std::random_device()());
    std::uniform_int_distribution<> dist(1,6);
}

But compiler gave me an error:

function returns function

But this works if I initialize the engine as a data member:

class A
{
public:
    A();
private:
    std::default_random_engine gen;
    std::uniform_int_distribution<> dist;
}

A::A() : gen(std::random_device()()), dist(1) {}

So why can I not use std::random_device()() in normal statement to initialize a random generator but can use it in initializing data members? How to make it working in normal statement? Thanks.

PS: I am working on Windows 10 using Visual Studio 2015.




Anchoring random numbers

Is there anyway to anchor a random number? I am using a random(). The script runs daily and adds new rows. I want the random number to stay consistent on existing rows and add a new random number on new rows. I am using Amazon Redshift DB, SQL. Thank you Set seed42; Select ID, random() from existing table where --parameters that populate the row--




C# unity generator world hexagon

everything fine ?

Well, right now I'm creating a simple little world generator in hexagons. It works fine, but it has some problems. I would like to create it a bit more together, it makes very large corridors and leaves several holes in the world.

I will leave here my code and an image of what is happening.

MAP IMG

In addition to being very separate, the passages are very narrow.

MAP IMG

//------------------------------------------------------------------------//

public GameObject[] hexTransform;
public List<Vector3> createdHex;



IEnumerator GenerateWorld()
{

    for (int i = 0; i < ammountHex; i++)
    {
        int pos = Random.Range(0, 5);
        int textureMap = Random.Range(0, hexTransform.Length);

        PositionHex(pos);
        SpawnHex(textureMap);
    }

    //      surface.BuildNavMesh();

    yield return 0;
}

//Set Position of hex

private void PositionHex(int pos)
    {
        switch (pos)
        {
            case 0:
                //Cima
                transform.position = new Vector3(transform.position.x - (offsetSize / 2), 0, transform.position.z + 0.75f * offsetSize);
                break;
            case 1:
                //Esquerda
                transform.position = new Vector3(transform.position.x + offsetSize, 0, transform.position.z);
                break;
            case 2:
                //Direta
                transform.position = new Vector3(transform.position.x - offsetSize, 0, transform.position.z);
                break;

            case 3:
                //Baixo
                transform.position = new Vector3(transform.position.x + (offsetSize / 2), 0, transform.position.z - 0.75f * offsetSize);
                break;

        }

    }

//And Finish Spawn Hex

void SpawnHex(int pos)
        {
            if (!createdHex.Contains(transform.position))
            {
                GameObject Hex = Instantiate(hexTransform[pos], transform.position, Quaternion.Euler(0, 0, 0)) as GameObject;
                createdHex.Add(Hex.transform.position);
                Hex.name = "Hex" + transform.position.x + " / " + transform.position.z;

    }
}




R Generate random numbers based on condition

I'd like to generate a sequence of 100 numbers based on the following conditions -

  • The numbers range from 1 to 5, and are whole numbers.
  • The number of 1s and 2s generated as a percentage of the total equals 90%

My Attempt

I attempted to create the sequence using runif. However I am unsure about how to include the second condition.

v=c(1,2,3,4,5)
rep(sample(v),100)

Your help on the second condition would be greatly appreciated




How to use a random number from the weibull distribution?

i am trying to place weibull distributed random numbers in a sector of a circle.

i generated the random number then distributed it in weibull distribution. now i want to use these weibull distributed random numbers.

RadarSpace GetWeibullClutter()
            { 
                Random _randomNumberGenerator = new Random();
                Weibull myweibull = new Weibull(3,2,_randomNumberGenerator);

                int n = 50; // number of clutter elements
                var maxRange = _detectionModel.MaximumRange;
                var centreX = 0; // Centre of the field of view -- X coordinates
                var centreY = 0; // Centre of the field of view -- Y coordinates

                var minimumAngle = Math.PI / 4; // _detectionModel.MinimumPhi;
                var maximumAngle = (3 * Math.PI) / 4; // _detectionModel.MaximumPhir;

                var time = (maximumAngle - minimumAngle) * myweibull + minimumAngle;
                var r = maxRange * Math.Sqrt(_randomNumberGenerator.Next(n));

                var x = centreX + r * Math.Cos(time);
                var y = centreY + r * Math.Sin(time);

i want the weibull distributed random number to be multiplied in the var time but it rather says operator '*' cannot be applied to opperands of type 'double' and 'weibull'




Getting Error: SQLSTATE[42S22]: Column not found: 1247

My question refers to another discussion branch - MySQL select 10 random rows from 600K rows fast.

I have a simple one column table:

+-----------------------+
| keywords              |
+-----------------------+
| Some text 1           |
| Some text 2           |
| Some text 3           |
| Some text 4           |
| Some text 5           |
| Some text 6           |
| Some text 7           |
| Some text 8           |
| Some text 9           |
| Some text 10          |
| Some text 11          |
| Some text 12          |
| ...                   |
| Some text 1200000     |
+-----------------------+

I'm trying to perform a request to some quantity of random lines using the code advised by #Riedsio on the line above, here it goes:

SELECT name
  FROM random AS r1 JOIN
       (SELECT CEIL(RAND() *
                     (SELECT MAX(id)
                        FROM random)) AS id)
        AS r2
 WHERE r1.id >= r2.id
 ORDER BY r1.id ASC
 LIMIT 1

My code is the following:

<?php

class TableRows extends RecursiveIteratorIterator {
    function __construct($it) {
        parent::__construct($it, self::LEAVES_ONLY);
    }

    function current() {
        return "<td style='width:150px;border:1px solid black;'>" . parent::current(). "</td>";
    }
}

$servername = "localhost";
$username = "admin";
$password = "admin_pass";
$dbname = "db_name";

try {
    $conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
    $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
//    $stmt = $conn->prepare("SELECT keywords FROM my_keywords");
    $stmt = $conn->prepare("SELECT keywords FROM my_keywords AS r1 JOIN (SELECT CEIL(RAND() * (SELECT MAX(id) FROM my_keywords)) AS id) AS r2 WHERE r1.id >= r2.id ORDER BY r1.id ASC LIMIT 1");
    $stmt->execute();

    // set the resulting array to associative
    $result = $stmt->setFetchMode(PDO::FETCH_ASSOC);
    foreach(new TableRows(new RecursiveArrayIterator($stmt->fetchAll())) as $k=>$v) {
            echo $v;
        }
    }

catch(PDOException $e) {
    echo "Error: " . $e->getMessage();
}
$conn = null;

?>

As a result getting the following error: "Error: SQLSTATE[42S22]: Column not found: 1247 Reference 'id' not supported (forward reference in item list)".

I'm just starting in MySQL so please don't be offended by this stupid question and thank you for your help.




mercredi 30 janvier 2019

How to use if-statement with randgen [duplicate]

This question already has an answer here:

I'm trying to make sure two randomly generated numbers don't match, is there a way to do this in an if-statement?


i'm fairly new to javascript and couldn't find anything that answered my question, rand2 and rand3 both pick from the same list and it would make the outcome seem odd if they matched. my code also stopped working when i put the if-statement in (if i messed that up i guess it wouldn't matter if i got an answer).

      function sentence() {
        var rand1 = Math.floor(Math.random() * 2);
        var rand2 = Math.floor(Math.random() * 12);
        var rand3 = Math.floor(Math.random() * 12);
        var rand4 = Math.floor(Math.random() * 10);
        var rand5 = Math.floor(Math.random() * 10);
        var rand6 = Math.floor(Math.random() * 10);
        //                var randCol = [rand1,rand2,rand3,rand4,rand5];
        //                var i = randGen();

        if (rand2 == rand3) {
        // whatever changes one
        } else {
        //
        }




2D Square Lattice Random Walker Problem Mean Displacement Vectors

The Question is asking to compute the mean displacement vector by ensemble averaging xN and yN over the M random walks, for different values of N. Plot as a function of N and then the mean squre displacement by ensemble averaging R_N^2 for M-1000 walkers who are all originally at the origin in two-d.

Here is my coder to put the maps of serval independent random walks:

import numpy as np
import pylab 
import random 

# defining the number of steps 
M = 1000

#creating two array for containing x and y coordinate 
#of size equals to the number of size and filled up with 0's 
x = np.zeros(M) 
y = np.zeros(M) 

# filling the coordinates with random variables

for i in range(1, M):
      value = random.randint(1, 4)
      if value == 1:
           x[i] = x[i - 1] + 1
           y[i] = y[i - 1] 
      elif value == 2: 
           x[i] = x[i - 1] - 1
           y[i] = y[i - 1] 
      elif value == 3: 
           x[i] = x[i - 1] 
           y[i] = y[i - 1] + 1
      else: 
           x[i] = x[i - 1] 
           y[i] = y[i - 1] - 1


def compute_SquareMean(value):
   totalsize=len(value)
   msd=[]
  for i in range(totalsize-1):
      j=i+1
      msd.append(np.sum((value[0:-j]      

value[j::])**2)/float(totalsize-j)) msd=np.array(msd) return msd

print(compute_SquareMean)
pylab.title("Random Walk ($n = " + str(M) + "$ steps)") 
pylab.plot(x,y)      
pylab.show() 

Can someone show me the code to compute the mean displacement vector by ensemble averaging xN and yN over the M random walks, for different values of N and the mean squre displacement by ensemble averaging R_N^2. I suspect my compute_SquareMean function is not working properly because it is giving a location as the output. It should be noted that the for loop for the random walker path is working perfectly. Thank you




RSpec Randomized Seed NOT Random

In the last day or two, all my runs of the same test file use the same random seed even though I didn't specify a seed.

    [jim@X230|apoxeia (bootstrap_4_from_responsive_sign_on_and_attornies_clients)]$ bin/rspec spec/system/change_requests_spec.rb  
Running via Spring preloader in process 2564 Environment is test

    Randomized with seed 41303

    ./spec/system/change_requests_spec.rb: Capybara starting Puma...
    * Version 3.12.0 , codename: Llamas in Pajamas
    * Min threads: 0, max threads: 4
    * Listening on tcp://127.0.0.1:36589 .....

    Top 5 slowest examples (51.21 seconds, 100.0% of total time):   Change Requests GET /change_requests displays the user who logged the change when logged in as admin
        17.91 seconds ./spec/system/change_requests_spec.rb:155   Change Requests GET /change_requests does NOT add a Change Request when logged in, and field is blank
        17.28 seconds ./spec/system/change_requests_spec.rb:39   Change Requests GET /change_requests adds a Change Request when logged in and valid params are given
        12.35 seconds ./spec/system/change_requests_spec.rb:106   Change Requests GET /change_requests displays when logged in
        3.37 seconds ./spec/system/change_requests_spec.rb:23   Change Requests GET /change_requests redirects when not logged in
        0.30664 seconds ./spec/system/change_requests_spec.rb:17

    Finished in 51.22 seconds (files took 0.45157 seconds to load) 5 examples, 0 failures

    Randomized with seed 41303

    Coverage report generated for RSpec to /home/jim/development/apps/apoxeia/coverage. 322 / 1933 LOC (16.66%) covered.

Any ideas on why this would be happening, or where I should start looking?

Thanks.




Replace random after count in python 3 with tkinter

I'm creating a 20 questions game which requires a NEW random value to be created for the "answer". I'm having trouble as if I put the randomization OUTSIDE of the command loop, it doesn't change, and if I put it INSIDE it doesn't carry.... Any recommendations? I've deleted all the excess code.

I've tried the random only inside, only outside, and in both, none of which worked. Any other count attempts I've tried have failed. Prior to trying to change the randomizer, everything functioned correctly. I considered trying to add 2 buttons, but it just wasn't what I was looking for...

window = Tk()

window.title("Welcome to LikeGeeks app")
window.geometry('400x200')

answers = ('dog','cat','rock','aki','table','flower','paris','florida', 'jackie chan')
#deleted section of all the string lists start
#deleted section of all the string lists end

aki = Label(window, text="Aki:  ", font=("Tahoma", 14))
aki.grid(column=0, row=0)

sp1 = Label(window, text="Let's play 20 Questions, and you guess first.", fg="blue", font=("Tahoma", 14))
sp1.grid(column=1, row=0, sticky=W)

sp2 = Label(window, text="Try to only say one word answers.", fg="blue", font=("Tahoma", 14))
sp2.grid(column=1, row=1, sticky=W)

sp3 = Label(window, text="If that's alright, type \"okay\"", fg="blue", font=("Tahoma", 14))
sp3.grid(column=1, row=2, sticky=W)

ent = Entry(window,width=15)
ent.grid(column=1, row=3, sticky=W)

#original location of the answertrue = random segment

count = 0
#working that button
def clicked():
    global count
    guess = str(ent.get())
    count = count + 1
    if count == 1:
        sp1.configure(text="Then let's begin!")
        sp2.configure(text="Make your first guess.")
        sp3.configure(text=" ")
        answertrue = random.choice(answers)


#Restart the program
    if count == 20:
        sp1.configure(text="You took too long!")
        sp2.configure(text="Click Sart to choose a new word,")
        sp3.configure(text="or click enter for another 20 guesses!")
        count = 0

    if count == 2:
#this was all the base elifs for seeing if you guessed correctly, it was obnoxiously long, so I deleted it.



btn = Button(window, text="Enter", bg="white", fg="green", command=clicked)
btn.grid(column=0, row=4)

I hope that I can just get it to set back the count to 0 and create a new random value for answertrue from the list answers to come out.




How can I randomly choose a number from an array without duplicates? [duplicate]

This question already has an answer here:

I'm a beginner programmer and I'm trying to make a program where the user inputs 3 numbers and then 3 random numbers appear on screen and if the numbers the user entered match up with the 3 random numbers, the user wins.

Till now, it works fine but I don't want duplicate random numbers because that would cause the game to be impossible to win.

The whole thing is still works in progress but I just wanted it to work for now :)

Thanks guys!

I've tried using If statements but I don't know how to get it to work.

public static void main(String[] args) {

    int[] numbers = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};

    Scanner sc = new Scanner(System.in);
    System.out.print("Enter first number> ");
    int firstNum = Integer.parseInt(sc.nextLine());
    System.out.print("Enter second number> ");
    int secondNum = Integer.parseInt(sc.nextLine());
    System.out.print("Enter third and final number> ");
    int thirdNum = Integer.parseInt(sc.nextLine());

        System.out.println(getRandom1(numbers) + "," + getRandom2(numbers) 
                           + "," + getRandom3(numbers));


    if (firstNum == getRandom1(numbers) && secondNum == getRandom2(numbers)
        && thirdNum == getRandom3(numbers)) {
        System.out.println("Winner!!");
    } else {
        System.out.println("nope");
    }

}

public static int getRandom1(int[] array) {
    int rnd = (int) (Math.random() * array.length);
    return array[rnd];
}

public static int getRandom2(int[] array) {
    int rnd = (int) (Math.random() * array.length);
    return array[rnd];
}

public static int getRandom3(int[] array) {
    int rnd = (int) (Math.random() * array.length);
    return array[rnd];
}

}

I am expecting the output to be like 6, 5, 8. Without any duplicates.




How to specify a random number generator in numpy

I'm building a monte carlo simulation using python, and have thus far been using numpy to generate my random variates. However, I've just learned that numpy uses the Mersenne Twister algorithm to produce its random numbers, which based on my limited understanding is not desireable in monte carlo simulations. I'd much prefer to use MRG32k3a, but I'd also like to take advantage of numpy's distribution functions. Is there any way to make numpy use a generator of my choice, or is there another library that will give me the same functionality with the option of using my preferred generator?




Randomly sampling numerals from a list whose aggregate needs to be at least greater than a given benchmark

I have a list of tuples formed by 1000 object ids and their scores, i.e.:

scored_items = [('14',534.9),('4',86.0),('78',543.21),....].

Let T be the aggregated score of the top 20 highest scoring items.

That's easy. Using python:

top_20 = sorted(score_items, key=lambda k: k[1],reverse = True)[:20] T = sum(n for _, n in top_20)

Next, let t equal a quarter of T. I.e. in python: t = math.ceil(T/4)

My question is: what's the most efficient way to randomly select 20 items (without replacement) from scored_items such that their aggregated score is equal to or greater than (but never lower than) t? They may or may not include items from top_20.

Would prefer an answer in Python, and would prefer to not rely on external libraries much


Background: This is an item-ranking algorithm that is strategy proof according to an esoteric - but useful - Game Theory theorem (source: section 2.5 in this research paper). Strategy proof essentially means it's tough to game it.

I'm a neophyte python programmer and have been mulling how to solve this problem for a while now, but just can't seem to wrap my head around it. Would be great to know how the experts would approach and solve this.

I suppose the most simplistic (and least performant perhaps) way is to keep randomly generating sets of 20 items till their scores' sum exceeds or equals t.

But there has to be a better way to do this right?




R: producing vector with number of times an element appears in sample

I have a homework problem where I have a sample of 30 men, a random sampling of 10 of them:

men [1] 15 18 14 6 22 17 20 3 16 9

And From them, do 12 random samples and determine how many times each man appears.

The problem statement, verbatim, is "Perform 12 samples of 10 men from a population of size 30 and for each man, record the number samples in which he appears."

I have attempted a loop for the problem that would produce a vector of 10 elements, each one lined up with the appropriate index.

mtimes<-rep(0,12)
> repeat{
+ mtimes[menind]<-sum(sample(pop1,12,replace = TRUE) == men[menind])
+ menind = menind + 1
+ if (menind == 10){
+ break
+ }
+ }

This resulted in a vector:

mtimes [1] 0 0 1 0 0 0 0 0 0 0

It seems the 3rd man should not have appeared only once while no one else appeared in the samples.




Why does this code run on nano but not on eclipse?

I wonder why this code works on nano on my Mac but not on eclipse.. I also do not understand why it does not run on eclipse although I know where the wrongs seemingly are..

public class randomnumber {

    public static void main (String [] args) {
        int n = integer.parseInt(args [0]);
        int m = Integer.parseInt(args[1]);

        random = (int) (Math.random() * (m - n + 1)+n);

        System.out.println(random);
        }
    }

Exception in thread "main" java.lang.Error: Unresolved compilation problems:

integer cannot be resolved

random cannot be resolved to a variable

random cannot be resolved to a variable

at Randomnumber.main(Randomnumber.java:5)




Random number generation seemingly not working properly

There's a thing that's happening that I don't understand the reason behind.

In Visual Basic, I've got a 2D Integer array that I populate with random numbers. When I do it with Rnd():

For j = 0 To matrix.GetUpperBound(0)
  For i = 0 To matrix.GetUpperBound(1)
    matrix(j, i) = 1 + CType((Rnd() * 50), Integer)
  Next
Next

It always writes the same numbers in the same position in the matrix.

But when I do it with the Random class:

Dim r As Random = New Random()
For j = 0 To matrica.GetUpperBound(0)
  For i = 0 To matrica.GetUpperBound(1)
    matrica(j, i) = r.Next(0, 100)
  Next
Next

It does what it's supposed to.

I don't understand why in the first case I get the same numbers in the same position every time I run the code.




Is there a random number generator which can skip/drop N draws in O(1)?

Is there any (non-cryptographic) pseudo random number generator that can skip/drop N draws in O(1), or maybe O(log N) but smaller than O(N).


Especially for parallel applications it would be of advantage to have a generator of the above type. Image you want to generate an array of random numbers. One could write a parallel program for this task and seed the random number generator for each thread independently. However, the numbers in the array would then not be the same as for the sequential case (except for the first half maybe).

If a random number generator of the above type would exist, the first thread could seed with the seed used for the sequential implementation. The second thread could also seed with this seed and then drop/skip N/2 samples which are generated by the first thread. The output array would then be identical to the serial case (easy testing) but still generated in less time. Below is some pseudo code.

#define _POSIX_C_SOURCE 1
#include <stdio.h>
#include <stdlib.h>
#include <omp.h>

void rand_r_skip(unsigned int *p_seed, int N)
{
    /* Stupid O(N) Implementation */
    for (int i = 0; i < N; i++)
    {
        rand_r(p_seed);
    }
}

int main()
{
    int N = 1000000;
    unsigned int seed = 1234;
    int *arr = (int *)malloc(sizeof(int) * N);

#pragma omp parallel firstprivate(N, seed, arr) num_threads(2)
    {
        if (omp_get_thread_num() == 1)
        {
            // skip the samples, obviously doesn't exist
            rand_r_skip(&seed, N / 2);
        }
#pragma omp for schedule(static)
        for (int i = 0; i < N; i++)
        {
            arr[i] = rand_r(&seed);
        }
    }
    return 0;
}

Thank you all very much for your help. I do know that there might be a proof that such a generator cannot exist and be "pseudo-random" at the same time. I am very grateful for any hints on where to find further information.




selecting random string column value from a table to insert into another table

enter image description here

I need to select random values from above table where when there are multiple values (ex:- of 3333,4444,6666) .Currenlt I am useing below code which is biased in the final resul.

enter code here

result will give more numbers with value "A" as the district . I need a unbiased random way to select from multiple entries.THank you




java rmi avoid runtime random port usage for communication

I have client machine behind firewall. So added rule for the port used (rmi_server_port) in:

registry=rmi_server_ip: rmi_server_port +"SomeVal";
poInterface = (I_Factory)Naming.lookup(registry);

But when actual communication happens a random port is opened. Cannot add all ports after 1099 to firewall rules.

Found below alternate: Use MyRMISocketFactory

But how to use createServerSocket(int port) method in basic rmi code.




generate 25 random numbers whose sum doesn't overcome a certain range

I set a function "generateRandom" that generates 25 random numbers in a min-max range and returns an array containing the sum of the 25 numbers followed by an array of all the 25 numbers; then I set another function "between" that takes the sum value in the array generated by the "generateRandom" function and returns the sum only if the sum is between a certain set range (8050 and 9050 in the example) otherwise it runs the "between" function until the previous condition is true.

function generateRandom(min,max) {
  let sum=0;
  let ar=[];
  for (let r=0; r<25; r++) {
    let x=Math.floor(Math.random()*(max-min+1)+min);
    sum=sum+x;
    ar.push(x);
  };
  return [sum,ar];
}

function between(x,y,limit) {
  let z=generateRandom(x,y)[0];
  while (z>limit-50||z<limit+50) {
    z=generateRandom(x,y)[0];
  };
  return z;
}

console.log(between(260,480,9000))

Can you tell me why it doesn't work?




ES6 : rolling and testing my own PRNG hash hex key generator?

for building some VNodes based app, I need a function that can generate pseudo random numbers, used as unique IDs, with a 3 or 4 bytes sizes.

Think a random RGB or RBBA, CSS-like string colors like : 'bada55' or '900dcafe'... User could seed the generator by picking a random pixel in a PNG image, for example.

Due to functionnal aspects of my app, generator must a pure function avpoding side effects like : using Math.random...

I'm not aware of artithmetic theories (my courses are so far in past...) but I decided to roll a custom PRNG, using Multiply-With-Carry (MWC) paradigm, and test it empirically with some prime coeffs, and random colors seeds.

My idea is to test it with 1-byte, 2-bytes, 3-bytes, and then 4-bytes outputs : my feelings are :

  • identifiying "good" primes and potential 'bad' seeds when number of bytes is lower
  • and try to test it against a cresing number of bytes

Sadly, performances seems to be poor, but I can't figure what is going wrong... Does anyone have an idea ?

Here's the generators code:

// length of internal state and output
const MAX_CELLS = 2  /// 1, 2, 3, 4

// for output formatting
const fmt = n => {
  const s = n.toString(16)

  if(s.length === 0) return '00'
  if(s.length === 1) return '0' + s

  // lower digits
  return s.substr(s.length - 2, 2)
}

// the lib exports a 'next' function inside it
export const createMWC = params => {

  const Z0 = new Array(MAX_CELLS) // from seed
  const Zi = new Array(MAX_CELLS) // state
  const Xi = new Array(MAX_CELLS) // temp
  const Ci = new Array(MAX_CELLS) // carries

  const M = (params && params.modulus)    ? params.modulus : Math.pow(256, MAX_CELLS)
  const A = (params && params.multiplier) ? params.multiplier : 197
  const C = (params && params.increment)  ? params.increment : 1
  const seed = (params && params.seed) ? params.seed : ('00').repeat(MAX_CELLS)

  for(let i = 0; i < MAX_CELLS; i++) {
    Zi[i] = parseInt(('' + seed).substr(2  * i, 2), 16)
    Z0[i] = Zi[i]
    Ci[i] = (C * i) % M
  }

  // the generator function
  const next = () => {
    turns++

    // main loop
    for (let i = 0; i < MAX_CELLS; i++) {
      Xi[i] = A * Zi[i] + (i > 0 ? Ci[i - 1] : Ci[MAX_CELLS - 1])
      Ci[i] = Math.floor((A * Zi[i] + Ci[i]) /  M)
      Zi[i] = Xi[i] % M
    }

    //if (Zi === Z0) {
    //  throw new Error ('CYCLED at i=' + turns)
    //}

    let output = Zi.map(n => fmt(n)).join('')

    return output
  }

  let turns = 0
  let carry = 0

  return { next }

  } // end of createMWC function
} // end of ES6 module




Keyspace cardinaliy after using statistical randomness tests

I would like to know if there exists any algorithms to evaluate the cardinality of a keyspace containing only random keys ( given that the keys are tested for randomness by a statiscal test suite such as Diehard or Nist). Such algorithm would accept as arguments the keylength and the test parameters and return the cardinality of the corresponding keyspace.




How can I make a random function in JavaScript without using the Math.random function?

I want to generate a random number using 0 and 1.

I've written the code, but the larger the number, the larger the error range. How can I write better code?

My current code

Code to generate 0 and 1

const get_zero_or_one = () => {
  return Math.floor(Math.random() * (2))
}


Code to generate a random number using the above code

const RandomResult = (max_number) => {
    let answer = 0;
    for (let i = 0; i < max_number -1; i++) {
        answer += get_zero_or_one()
    }
    return answer
}

The condition is not to use the Math.random function. Thanks!




Save random values from multi-dimensional NumPy array

I have an 149x5 NumPy array. I need to save some (30%) of values selected randomly from whole array. Additionally selected values will be deleted from data.

What I have so far:

# Load dataset
data = pd.read_csv('iris.csv')

# Select randomly 30%(45) of rows from dataset
random_rows = data.sample(45)

# Object for values to be saved
values = []

# Iterate over rows and select a value randomly.
for index, row in data.iterrows():

   # Random between 1 - 5
   rand_selector = randint(0, 4)

   # Somehow save deleted value and its position in data object
   value = ??                                                 <-------

   values.append(value)

   # Delete random value
   del row[rand_selector]

To add further, the data from value will later be compared to values imputed in its place by other methods(data imputation), therefore I need the position of the deleted value in original dataset.




Shortcode code returns incorrect URL - Wordpress

I'm writing a WP shortcode to disaply random images from a path that's given by input. [random-image pag="" class=""] The code works nicely, but returns the correct url + the page i've put the shortcode. Example: I'm currently renovating my website locally. The actual URL is: https://localhost/z/ But after I've finished coding it will become https://localhost/

If I put the shortcode on /prova page ( https://localhost/z/prova/ ) the image src will show "wp-content/themes/generatepress_child/img/home/2.jpg" which is correct but if I mouse over it it shows the full path like this: "https://localhost/z**/prova/**wp-content/themes/generatepress_child/img/home/2.jpg" instead of "https://localhost/z/wp-content/themes/generatepress_child/img/home/2.jpg"

I've tried changing the $imagesDir in $imagesDir = get_site_url() . 'wp-content/themes/generatepress_child/img/' . esc_attr($values['pag']) .'/'; or $imagesDir = 'z/wp-content/themes/generatepress_child/img/' . esc_attr($values['pag']) .'/'; or even: $imagesDir = 'https://localhost/z/wp-content/themes/generatepress_child/img/' . esc_attr($values['pag']) .'/';

But all of these return with

// Random img 
function random_image(  $atts, $content = null ) {
    $values = shortcode_atts( array(
    'pag'       => 'home',
    'class'     => 'imgrnd',
    ), $atts );

    $imagesDir = 'wp-content/themes/generatepress_child/img/' . esc_attr($values['pag']) .'/';

    $images = glob($imagesDir . '*.{jpg,jpeg,png,gif}', GLOB_BRACE);

    $randomImage = $images[array_rand($images)];

    return '<img src="' . $randomImage . '" class="' . esc_attr($values['class']) . '">';

}
add_shortcode( 'random-image', 'random_image' );




Accessing Random Property of Object

I have a huge object that contains the entire ESV Bible. I am trying to get a random book of the Bible whenever I press a button. Here is a small sample of the object.

var esvObject = {

 "Genesis": {

    "1": {}
    "2": {}
    "3": {}

   },
 "Exodus": {

    "1": {}
    "2": {}
    "3": {}

   }

}

Here is the code that I am using to get a random book.

var randNum = Math.floor(Math.random() * 66);

var randBook = esvObject[randNum];

var output = randBook;

I would expect this to work, but the output I always get is "undefined," where as I would like the output to be "Genesis" or "Exodus" etc. Getting the random number works, but if

randNum = 1

then

randBook = esvObject[1]

the output returns as "undefined" and I don't know why.




Instead of random, it generates sequence of numbers

I want to generate x number of random numbers and everything works except it gives me sequence of numbers.

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

int main(){


int x;
printf("How many  elements do you want?\n");
scanf("%d", &x);
int *array = (int *)malloc(x * sizeof(int));
srand(time(NULL));
for(int y = 0; y < x; y++){

    *(array + y) = 2 +  rand() % 99;
}

for(int y = 0; y <x; y++){
    printf("Array element %d: %d\n", y, (*array+ y));

}

return 0;}

It gives the numbers like; 27 28 29 30 31, only the first number is random.




mardi 29 janvier 2019

Generating sets of unreadable/secure and unique random numbers

In the process of some research I have been doing I stumbled across the following 2 claims on the PokerStars website.

We do record all of the hole cards in all real money hands. This is an important tool to help us investigate fraud and collusion. However, this information is not accessible to anyone until after the conclusion of the hand; it is not transmitted to our database until all action is completed and the pot has been awarded.

To be clear: Nobody in the public or employed by us can obtain information from the servers to find out the hole cards of any hand in progress. Nobody in senior management, none of the software developers, no operational representatives. Nobody at all.

This got me thinking, how would you go about writing such an algorithm?

Lets start with the following requirement:

"Generate a collection of 52 random numbers representing a deck of cards in such a way that no malicious third party could determine which cards were generated even if they had direct access to the memory of the computer generating the sequence. This sequence of encrypted numbers must be reversible but not until the completion of the game."

My first attempt at architecting a solution to this problem went along these lines:

  1. A new hand begins.
  2. Each client in the system generates a new public/private key pair.
  3. Each client in the system makes a request for a tuple of new hole cards. With this request the client sends its public key.
  4. The server receives the request for new hole cards and uses the public key provided by the client to encrypt the random numbers generated and return them to the client.
  5. At the end of the hand the client sends the private key back to the server and the server can now decrypt the hand information.

Unfortunately such a implementation has a number of flaws, chief among them:

  1. If the client disconnects prior to the completion of the hand the server can no longer decrypt the value that was sent to the client, given that it doesn't have the private key.
  2. The requirement that a deck of cards must not contain duplicate values ensures that somewhere in memory, at some point in time you must store a collection representing the cards which have already been dealt. This completely negates the original purpose of this algorithm as this information can now be potentially read by a malicious third party who has access to the device.

If you're going to be able to log the information you need to log in the event of someone disconnecting before the end of a hand, it seems like you're going to have to be able to reconstruct that information server-side? And if sufficient information is stored server side to reconstruct the data you're trying to keep hidden before the end of a hand, then anyone with access to the server should be able to do it before the end of a hand as well - it seems like the ability to compensate for a disconnect and ability to read hidden information before a hand ends go...hand-in-hand...

Can anyone suggest a potential implementation of such an algorithm or definitively prove that such an algorithm is not possible?




not getting random values even with srand(time(NULL))

Even after including srand(time(NULL)) at the start of my function, (function is only called once in main) I get the same random value for r1 every time I run the program. r2 and r3 get random values fine, but I need random decimal values between 0.1 and 10.0 so what's wrong with the line containing r1?

void randNums(float &r1, float &r2, float &r3) {

   srand(time(NULL));

   r1 = (10 * (rand())/ (float)RAND_MAX);
   r2 = 1 + (rand() % 10);
   r3 = 1 + (rand() % 10);

}




Random position outside a box that is inside the circle

I need to find a random position outside a box but is inside a circle, basically the random position between the the box and the circle. What i think of is just rand() a position inside a circle, and check whether the position is outside the box, basically doing a collision check. Is there a more efficient way than this method?




using gsl random number generator in armadillo

I'm writing some code in C++ for scientific computing purposes. The linear algebra library I chose to use is Armadillo. My problem is that Armadillo uses either the simple rand() function or a Mersenne Twister rng, while I need better quality numbers, for example ranlux. GSL provides an implementation of ranulx, and Armadillo allows for an external rng by defining the preprocessor macro ARMA_RNG_ALT and writing an appropriate header file that we will call arma_rng_alt.hpp.

Now, I'm no C++ wizard but I managed to do it by more or less copying and pasting from the existing headers arma_rng_cxx98.hpp and arma_rng_cxx11.hpp. My solution might not be the prettiest but I think it works alright. This is an extract of my header:

#if defined(ARMA_RNG_ALT)
#include <gsl/gsl_rng.h>
#include <gsl/gsl_randist.h>
#define RNG_TYPE gsl_rng_ranlxd1

class arma_rng_alt
{
    public:

    typedef unsigned long int seed_type;

    inline void set_seed(const seed_type val);

    arma_inline int    randi_val();
    arma_inline double randu_val();
    arma_inline double randn_val();


    private:

    gsl_rng* engine;
};

inline
void
arma_rng_alt::set_seed(const arma_rng_alt::seed_type val)
{
    engine = gsl_rng_alloc(RNG_TYPE);
    gsl_rng_set(engine, val);
}

arma_inline
int
arma_rng_alt::randi_val()
{
    return gsl_rng_get(engine);
}

arma_inline
double
arma_rng_alt::randu_val()
{
    return gsl_rng_uniform(engine);
}

arma_inline
double
arma_rng_alt::randn_val()
{
    return gsl_ran_gaussian_ziggurat(engine, 1.);
}

#endif

Now, this would be ok if this external rng was treated by armadillo as a class without a private variable (like in the arma_rng_cxx98.hpp header, that uses rand() and doesn't need to allocate an engine). Instead I need to allocate the engine and call it every time, therefore I need to instantiate the class otherwise I get a "cannot call member function without object" error. So I actually needed to modify a header from the Armadillo library itself, namely arma_rng.hpp. To make things clearer, this is how a typical chunk of the original arma_rng.hpp to generate random integers looks like:

template<typename eT>
struct arma_rng::randi
  {
  arma_inline
  operator eT ()
    {
    #if   defined(ARMA_RNG_ALT)
      {
      return eT( arma_rng_alt::randi_val() );
      }
    #elif defined(ARMA_USE_EXTERN_CXX11_RNG)
      {
      return eT( arma_rng_cxx11_instance.randi_val() );
      }
    #else
      {
      return eT( arma_rng_cxx98::randi_val() );
      }
    #endif
    }

As you can see, if cxx98 or alt is used, the function randi_val is simply called, while if cxx11 is used, randi_val is called on an actual instance of the calss arma_rng_cxx11 (a thread local variable declared earlier in the header). What I need is something similar to cxx11, so this is how I modified the library header arma_rng.hpp for this specific example:

template<typename eT>
struct arma_rng::randi
  {
  arma_inline
  operator eT ()
    {
    #if   defined(ARMA_RNG_ALT)
      {
      return eT( arma_rng_alt_instance.randi_val() );
      }
    #elif defined(ARMA_USE_EXTERN_CXX11_RNG)
      {
      return eT( arma_rng_cxx11_instance.randi_val() );
      }
    #else
      {
      return eT( arma_rng_cxx98::randi_val() );
      }
    #endif
    }

after declaring my own thread local instance of the class arma_rng_alt I've created.

Works like a charm, the catch is that now I need to run my code on a HPC cluster and, while I can create my own arma_rng_alt.hpp, I can't modify the library header arma_rng.hpp itself. So I need a way to make the original header work (so without instantiating the class). Do you have any idea on how to do that? My C++ expertise is frankly stretched to the limit here.

Thanks




How to refresh random number on click listener?

I have managed to create a simple guessing game (this works fine) the only problem is I cant seem to refresh the random number that I generate at the start.

import java.util.Random;

public class MainActivity extends AppCompatActivity {

private TextView hint;
private Button enterGuess;
private EditText chosenNumber;

Random rand = new Random();
int secretNumber = rand.nextInt(99) + 1;

@Override
protected void onCreate(Bundle savedInstanceState) {

    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);


    enterGuess = findViewById(R.id.buttonEnter);
    chosenNumber = findViewById(R.id.etEnterNumber);
    hint = findViewById(R.id.tvHint);

    final String hintHigh = "Guess Higher";
    final String hintLow = "Guess Lower";
    final String correctGuess = "Correct! Guess the new number!";


    enterGuess.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {

            int number = Integer.parseInt(chosenNumber.getText().toString());

            if (number < secretNumber){
                hint.setText(hintHigh);
            }
            else if (number > secretNumber) {
                hint.setText(hintLow);
            }
            else {
                hint.setText(correctGuess);

                Random rand = new Random();
                int secretNumber = rand.nextInt(99) + 1;

            }
        }
    });
}
}




Generating random sequence in tensorflow with another tensor as seed

I have a use-case where I need to generate a sequence of random integers given an input integer. There are many ways to do this in python. The one I am currently using is as follows:

import hashlib
def nextRandom(seed, length, maxval):
    md5 = hashlib.md5(str(hash(seed)).encode('utf-8'))
    for k in range(length):
        md5.update(str(k).encode('utf-8'))
        yield int(md5.hexdigest(), 16) % maxval

seed = 12345
length = 10
maxval = 1000
for randInt in nextRandom(seed, length, maxval):
    print(randInt)

This ensures that the generated sequence is fixed given a seed value.

Now, I need to a similar functionality in tensorflow where seed comes as a tensor and the returned sequence should also be tensor.

I checked this issue in tensorflow github page, but couldn't find a working solution.




Calulate two random numbers in flutter

I'm trying to generate two different random numbers and add those together, but Flutter doesn't seem to like my math. I keep getting the message that '+' isn't defined for the class Random.

import 'package:flutter/material.dart';
import 'dart:math';

void main() => runApp(MaterialApp(
      title: 'Random Numbers',
      theme: ThemeData(primarySwatch: Colors.orange),
      home: MyHome(),
    ));

class MyHome extends StatefulWidget {
  @override
  _MyHomeState createState() => _MyHomeState();
}

class _MyHomeState extends State<MyHome> {
  @override
  Widget build(BuildContext context) {
    var num1 = new Random();
    for (var i = 0; i < 10; i++) {
      print(num1.nextInt(10));
    }
    var num2 = new Random();
    for (var i = 0; i < 10; i++) {
      print(num2.nextInt(10));
    }
    //var sum = num1 + num2;

    return Container();
  }
}

My goal is to display it something like this: "2 + 5 = " where the user will fill in the answer. If correct do this else do that.




Numerically compute MLE for parameters in a model with latent variable

In order to initialize my parameters for a bayesian MCMC, I need to compute the MLE of beta and gamma, defined as follows. Y_1, ..., Y_N are observed, Y_i takes one of J ordered categories. There exists a latent continuous random variable Z_i distributed as N(x_i^T,beta) and we observe Y_i, where Y_i=j if gamma_(j-1)

How could I find those MLE with Python?




Timer jumps randomly from 2 seconds to 50

I want to connect my raspberry pi with my computer. The connection works fine but now I want to check if the computer sends messages and after a couple of minutes without a message the raspi should shutdown. If I start the program manually it works fine but i want to start it on autostart. If I do so the timer jumps from (for example) 2 seconds to 50 and I dont know why.

My Code looks like this:

<!-- language: lang-python -->
import threading
import time
import paho.mqtt.client as mqtt

shutdown = 0

def on_connect(client, userdata, flags, rc):
   print("Connected with result code "+str(rc))
   client.subscribe("CoreElectronics/test")
   client.subscribe("CoreElectronics/topic")

def on_message(client, userdata, msg):
   global shutdown
   shutdown = time.time()
   print(msg.topic+" "+str(msg.payload))

def timer_count():
    global shutdown
    shutdown = time.time()
    elapsed = 0
    while elapsed < 10:
         elapsed = time.time()-shutdown
         print("no Message")
         time.sleep(2)

t1 = threading.Thread(target = timer_count)
t1.start()

client = mqtt.Client()
client.on_connect = on_connect
client.on_message = on_message

client.connect("192.168.xx.xx", 1883, 60)


client.loop_forever()


I printed out the time.time() Funktion and there it randomly jumps 50 seconds ahead. Does somebody knows an answer to this ? Thank you for the help!




lundi 28 janvier 2019

Bitset size inconsistency

so I'm initializing a Bitset variable with a length of 4. When i try to seed this Bitset with the Random's class nextBoolean method. It gives the effect of removing elements. This is more than likely my inexperience with using Bitset. But as far as my understanding each element in the Bitset variable should have a random 0 or 1. Can someone see what it is that I'm doing wrong and explain what that is?

public void seedCandidate()
{
    // Randomly sets bits in the candidate

    for (int i = 0; i < numVals; i++)
        truthVals.set(i, rn.nextBoolean());

}

When I output the length of the bitset it gives random sizes. The length of truthVals(the Bitset variable) should be 4 which is what it got instanced to so it should be {0, 1, 2, 3}. But after the seeding from the method on top I get these different lengths. From different Bitset variables.

{1, 2, 3}, {0, 1, 2, 3}, {0}, {0, 2, 3}




Assigning Random Numbers to Variables Without Duplicates in Python

I am new to Python and need help regarding assigning numbers to variables. How would I assign a random number from 0 to 9 to the variables "a" through "j" so that each variable gets a random number with no duplicates? Thanks in advance!




JS - How can I generate a long random number?

I know that I need to use Math.random() for making random numbers, but today I tried to make a random number between 1 and 9999...(9 repeated 19 times) and my output always ends in 3-5 zeroes. How can I generate more detailed random numbers?

What I've done:

const foo = Math.floor(Math.random() * parseInt("9".repeat(19)));

Also, I'm pretty sure I know how to do this, but if anyone can tell me, how do I pad zeroes to get to a certain digit count? (ex. pad(15,4) becomes 0015 because the you need 2 more digits to make it 4 digits long)




How do random numbers get generated by Programming Languages?

Can anyone explain me how do random numbers get generated ? , well, we all know that computers are based on 0,1 and everything is logical and there is nothing called LUCK, it's all logic, im wondering how could a computer generate a random number ?

for example what really happens in CPU of a server when i call rand() in php ?

where do these numbers come from ? are they really random ? or based on algorithm or what ?




allocate random float numbers to an array withing a range specified by the user

I do not know where the problem lies

int main()
{

    int antalVarde = 0;
    low=0, high=0;
    float* arr;
    srand((int)time(NULL));

    printf("Hur många värden ska skapas: ");
    scanf_s("%d", &antalVarde);
    printf("Ange min-värde: ");
    scanf_s("%d", &low);
    printf("Ange max-värde: ");
    scanf_s("%d", &high);


    arr = (float*)malloc(antalVarde * sizeof(float));

    for (int i = 0; i <= antalVarde; i++)
    {
        *arr = RandomReal(low, high);
    }
    printf("%f", *arr);

    getchar();
    return 0;
}


float RandomReal(float low, float high)
{


    float d;

    d = (float) rand() / ((float) RAND_MAX + 1);
    return (low + d * (high - low));
}




How to remove negative symbols from negative numbers in batch

I'm setting up a line of text that will tell if you have lost or gained something, but whenever the value is negative the (-) symbol is always there. I've attempted to search up how to fix this but have not found anything.

:grocerycomplete
set /a randomsurvivors=%random% %%3 - 1
if %randomsurvivors% LSS 0 (
    set porn=lost
) else (
    set porn=gained
)
echo ========================
echo You have looted the Grocery Store!
echo You have %porn% %randomsurvivors% Survivor(s)!

"randomsurvivors" generates a number between 1 and -1. The number is then read and if it is <0 it will say lost and if it >0 it will say gained. Whenever it is -1 it will say:

========================
You have looted the Grocery Store!
You have lost -1 Survivor(s)!

I want for it to say:

========================
You have looted the Grocery Store!
You have lost 1 Survivor(s)!




Wrong distribution from inverse(CDF) transform sampling

I am trying to simulate a geometric distribution, using the Inverse CDF method, however I am getting slightly wrong results and I am not sure why.

To be more specific, a geometric distribution with a shape factor p = 0.8, should have the following characteristics:

mean: 1.25 
variance: 0.31

However, running the code below, I am getting:

mean: 0.6224363901913519
var: 0.391813011265263
[Finished in 0.3s]

As you can see, I am getting a wildly different mean value compared to the expected one.

np.log(uniform[i])/np.log(1-p) is the result of solving the equation: F(X) = R for X in terms of R, F(X) = CDF of geometric distribution = 1 - (1 - p)^k.

R is a uniform distribution over the interval (0,1).

So solving it results in the following:

X = ln(1-R)/ln(1-p)

However, since both 1-R and R are uniformly distributed on (0,1), we can do the following simplification:

X = ln(R)/ln(1-p)

The above equation is correct and should result in a geometric distribution sample.

import numpy as np

n = 10000
p = 0.8
geo_dist = np.zeros(n,dtype = np.float64)
uniform = np.random.uniform(0, 1, n)
for i in range(n):
    geo_dist[i] = np.log(uniform[i])/np.log(1-p)
print("mean: " +str(geo_dist.mean()))
print("var: " +str(geo_dist.var())) 

I have tried increasing the calculation precision by using np.float64 in a desperate attempt to fix what should be a trivial script, to no avail.

I have also tried generating the uniform distribution using scipy uniform.rvs() instead of np.uniform and the problem persists.

If p = 0.5:

expected mean: 2
expected variance : 2

However, the code I have written has the following result:

mean: 1.4440009653569306
var: 2.0421079966161093
[Finished in 0.3s]

Anybody have any idea why this is not working? Thank you.




Order of random effects in a LME model

I am building an LME model with random effects. My 2 random effects are 'Patient ID' and 'Eye ID'.

I need to nest those 2 random effects because every patient has several visits (is a longitudinal study) and every patient at each visit has 2 eyes. So my question is, in which order should these random effects be nested:

a) ~1|EyeID/PatientID

b)~1|PatientID/EyeID

Thank you very much in advance,

Best regards,

Lili




Randomize seems to miss many possible seeds

I wrote the following in an attempt to implement the Box-Muller transform to generate random normal variables in pure VBA:

Function RandNorm(Optional mean As Double = 0, Optional sd As Double = 1) As Double
    Dim s As Double
    s = Sqr(-2 * Log(Rnd())) * Cos(6.283185307 * Rnd()) '6.28 etc. is 2*pi
    RandNorm = mean + sd * s
End Function

The following somewhat weak test always works, returning a number close to 0:

Sub test1()
    Randomize
    Dim s As Double
    Dim i As Long
    For i = 1 To 17000000
        s = s + RandNorm()
    Next i
    Debug.Print s / 17000000 
End Sub

On the other hand, the following test never works (because it tries to take the log of 0, which is undefined):

Sub test2()
    Randomize
    Dim s As Double
    Dim i As Long
    Debug.Print Rnd() 'just to clock it
    For i = 1 To 17000000
        s = s + RandNorm()
    Next i
    Debug.Print s / 17000000   
End Sub

The problem is that rnd() returns 0 on average once out of every 2^24 (a bit less than 17,000,000) calls. It is of course easy enough to tweak the definition of RandNorm to avoid the zero, but I am still puzzled by the above code. It would make perfect sense to me if each test failed half the time (when the zero is fed into Log()) and worked half the time (when the zero is fed into Cos()). It seems that Randomize avoids at least half of the possible seeds.

Is there a way to seed the random number generator so that each test fails half the time?




Is it possible to generate different random numbers faster than O(n)?

I have a range of numbers from 1-10 and I want to pick out 3 randomly but never the same twice. In lua I used a Fisher-Yates shuffle which is O(n), I know python has a built-in random.sample() also O(n). Can it be done faster with an arbitrary range and number of picks?




Ganerate unsaved random password and send them via email

I want to create a system using PHP, that can generate a number of random passwords respecting a given form (length:12, contains 4 numbers, 2 capital letters, 2 special characters and 4 small letters) something like that. The number of passwords generated correspond to a number of emails imported from a text file. When those passwords are generated, the system will automatically send them with some information details to the imported emails. But is it a logical way to not saving those passwords in a database and when the users try to connect with those passwords, the system will verify is it the correct form or not in order to allow the connection be successful? If this logic is possible, how can I verify if the user did enter the correct password ?




How can you make a random number generator that chooses between the number 2 or 3. (not 1,2,3)

Hi I am working on a monty hall generator and in part of my code I need it to generate random number 2 or 3. It cannot be 1,2,3 but the computer needs to select between 2 or 3. Thanks!

I have tried randomCarDoor = ( rand() % 3 ) + 1; but does not work.

randomCarDoor = ( rand() % 3 ) + 1;

It gives me the number 1,2,3 but I just want 2 and 3




dimanche 27 janvier 2019

Google Sheets Script - One button with two consecutive functions (function 1 runs, ends then function 2 runs)

I want to have two functions inside a funtion rolarD20. The first, rolarDados generates a random number between 1 and 20, and the second, fixar, fixes the number to the cell so that it doesn't get generated constantly, a new random number will only be generated when on the click of the button for rolarD20 again.

However, the way I got it to work makes it necessary to have two buttons with one function each, because when I try to create a "master" function with the two functions working under it, the first it doesn't run:

function rolarD20(){
  rolarDados();
  fixar();
}

function rolarDados() {

  var spreadsheet = SpreadsheetApp.getActive();
  spreadsheet.getRange('S5').setFormula('=RANDBETWEEN(1,20)');

}

function fixar() {
  var spreadsheet = SpreadsheetApp.getActive();
  spreadsheet.getRange('S5').activate();
  spreadsheet.getRange('S5').copyTo(spreadsheet.getActiveRange(), SpreadsheetApp.CopyPasteType.PASTE_VALUES, false);

};

I'm guessing this is because the function is trying to do everything at once. But for the logic to work, it needs to properly run the first one, end it and THEN run the second one.

When I have two buttons, one for rolarDados and another one for fixar, it works. I just need help to simplify this by having just one button click for the two functions in sequence and, if possible, only one value being generated in cell S5. Because as it is with two buttons now, it generates one random number when function rolarDados runs (value which is being discarded by the second button run) and a second random number on the run of fixar, which will be stored in the cell.




Bringing Numbers in Vector from One Function into Another

I am currently trying to create a weighted dice roll system. I am running into some problems with accessing the weighted numbers I have. So in my dice class, I have two functions. The first function creates a weighted dice system with specified parameters for the weights and sides. So when in main, I can do something like:

Die dice1({.5,.1,.1,.1,.1,.1}, 6); //Creates die with higher probability of 1 being rolled, with six sides

The second function I have is a roll function, that returns a roll number given the weight attributes set from the earlier function. It looks something like:

void Die::roll() {
    double random = ((double) rand() / RAND_MAX);
    for (int i = 0; i < SIDES; i++) {
        if (random < new_weights[i]) last_roll = i;
        random -= new_weights[i];
    }
}

Now, my problem is, how do I bring the new_weights vector of weight attributes into the roll() function? Can it be as simple as to pass it by const ref?

Also, I have a function that creates a "normal" six-sided die with fair probability to land any number from 1-6. How can I change roll() to work from the weighted die parameters versus the regular die parameters, given the die the player decides to use?

Thank you so much for any help/tips.




Randomize player turns [duplicate]

This question already has an answer here:

How can I attribute the first player to play? I flip turns with a boolean so that when player1 touchs a cell, it flips to player2 and so on. But I have a fixed turn set to either player1 or player2.

I delcare something:

boolean playerSwitcher;

Then inside the onCreate method:

playerSwitcher = false; //False for player 1

And then on my method which manage tapping:

    @Override
    public void onCellTapped(int x, int y) {
//....
//Do a bunch of things here

            playerSwitcher = !playerSwitcher; //This flips to true then false and so on
//Do a bunch of things here: Drawing circle on the grid, printings position, etc

    }

On initialization, only player1 starts first. I would like to randomize their turns. How can I do that?




samedi 26 janvier 2019

Batch: How to Choose a Random Folder and Store it in a Variable

I'm trying to make a program that will choose a random folder from the directory that it's in, and then it should store that folder path in a variable. I could later check for text files in both folders that share the same name.




How to randomly generate a bunch of sites that have roughly the same amount of space between them?

I included JavaFX as a tag because that's what I use to display the sites, but you shouldn't need to understand JavaFX to answer my question. I wanted to include a full working code-example so you can run it yourself. However, to help me out, you probably only need to look at the randomlyChooseSites() method at the bottom of my example.

In this code I generate a bunch of randomized points on a 2D plane. I would like them to be more equal in distance from each-other without being perfectly equal in distance.

How can I randomly generate points on a 2D plane and have them be closer to equal in distance from each-other than they are now, without being perfectly equal in distance?

public class MCVE extends Application {

private final static int WIDTH = 400;
private final static int HEIGHT = 500;

private final static int AMOUNT_OF_SITES = 50;

private final static SplittableRandom RANDOM = new SplittableRandom();

@Override
public void start(Stage primaryStage) {

   // Create the canvas
   Canvas canvas = new Canvas(WIDTH, HEIGHT);
   GraphicsContext gc = canvas.getGraphicsContext2D();
   drawShapes(gc);

   // Add the canvas to the window
   Group root = new Group();
   root.getChildren().add(canvas);
   primaryStage.setScene(new Scene(root));

   // Show the window
   primaryStage.setTitle("Sweep-Line Test");
   primaryStage.show();
}

/**
 * Draws shapes on the Canvas object.
 *
 * @param gc
 */
private void drawShapes(GraphicsContext gc) {

   gc.setFill(Color.BLACK); // sites should be black

   // create random sites
   HashSet<int[]> siteSet = randomlyChooseSites();

   // add the random sites to the displayed window
   for(int[] i : siteSet) {
      gc.fillRect(i[0], i[1], 5, 5);
   }

}

/**
 * Randomly chooses sites and returns them in a HashSet
 * @return
 */
private HashSet<int[]> randomlyChooseSites() {
   // create a HashSet to hold the sites as two-value int[] arrays.
   HashSet<int[]> siteSet = new HashSet<>();

   int[] point; // holds x and y coordinates
   for(int i = 0; i < AMOUNT_OF_SITES; i++) {
      // randomly choose the coordinates and add them to the HashSet
      point = new int[] {RANDOM.nextInt(WIDTH), RANDOM.nextInt(HEIGHT)};
      siteSet.add(point);
   }

   return siteSet;
}

}




generating random number with normal distribution in VBA

I have problem with generating random numbers with normal distribution in VBA. I’m working on NSGAII. I use “Application.WorksheetFunction.Norm_Inv (Rnd, Mean, Deviation)” to generate rand numbers with normal distribution. But I face this error:

Runtime error ‘1004’: Unable to get the Norm_Inv property of the worksheetfunction class

How can I fix this error?

I’ve already used this code in another simple macro and it works. But by using this code in NSGAII code there is an error! (Large number of variables (double, long, Boolean, etc.) and 2D arrays are defined and used in NSGAII code and it consist of do while, for, etc. loops)

Function GenerateNormRand ()
Dim myrand As Double
randomize
myrand = Application.WorksheetFunction.Norm_Inv(Rnd, 0, 5)
GenerateNormRand = rand
End Function

Error




To define a new Random Variable in MATLAB

I am new to MATLAB. I have been given 2 random variables X and Y with a continuous uniform distribution in the interval (0,1) and I created it using:

X = makedist('Uniform','lower',0,'upper',1); Y = makedist('Uniform','lower',0,'upper',1);

The variable that I am to create should be a combination of X and Y and should be along the line of Z = sqrt(-2*log(1-X))*cos(2*pi*Y)

However, it gives me the following error- Undefined operator '-' for input arguments of type 'prob.UniformDistribution'.

How should I tackle this problem and where am I going wrong with this?




I cant generate different random numbers inside for each looping [duplicate]

This question already has an answer here:

1- Copy and paste following codes into MainWindow.xaml

<Window x:Class="MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="450" Width="450">
<StackPanel>
    <Button x:Name="Button1" Height="20" Width="100" VerticalAlignment="Top" Content="Generate Random"/>
    <DataGrid x:Name="DataGrid1" HorizontalAlignment="Stretch" VerticalAlignment="Stretch"/>
</StackPanel>
</Window>

2- Copy and paste following codes into code behind

Class MainWindow 

Private Sub Button1_Click(sender As Object, e As RoutedEventArgs) Handles Button1.Click

    Dim myDataTable As New System.Data.DataTable

    myDataTable.Columns.Add("Numbers")

    For k As Integer = 1 To 3

        Dim myRandom As New Random
        Dim myList As New List(Of Integer)(New Integer() {"10", "11", "12", "13", "14"})
        myList = myList.OrderBy(Function(i) myRandom.Next).ToList()

        For Each x As Integer In myList
            myDataTable.Rows.Add({x})
        Next

    Next

    DataGrid1.ItemsSource = myDataTable.DefaultView

End Sub

End Class

My question is here;

You will see this (https://prnt.sc/mcj14n) when you run this project and then click Generate Random Button.

I want to see this https://prnt.sc/mcj207

So, why I cant generate different random numbers inside for each looping?




how do i make make a rand num to an img

I'm in the process of making a bank statement, how do I make the black fields in random? I have this code to make the numbers in random

$source = range(1, 90);
shuffle($source);

$plader = array();

for ($p = 0; $p < 3; $p++) {
$tal = array_slice($source, 0, 15);
$source = array_slice($source, 15);
sort($tal);
$r = 0;
$plade = array();
foreach ($tal as $number) {
$plade[$r][] = $number;
$r++;
$r %= 3;
}
$plader[] = $plade;
}
 if (isset($_GET["bp"])) {
 $i = 0;
foreach ($plader as $plade) {
$i++;
echo "<div class='plade'><b>Plade $i:</b>";
foreach ($plade as $raekke) {
echo "<div class='tr' id='td'>";
foreach ($raekke as $tal) {
echo "<div class='number'><p> $tal </p></div>\n";
}
echo "</div>";
}
echo "</div><br />";
}
}




How to split and copy files from multiple folder in train, test and validation folder

I have a dataset that is composed by 130 folders containing 32 photos each.

From each folder, I want to copy randomly that photos (26 for training, 3 for testing and 3 for validation) to the the respective subfolder (001, 002, 003...) in train, validation and test folder. So I'll have something like this:

  • Train set

    • 001 (folder contain 26 photo)
    • 002
    • 003
    • ....
  • Validation set

    • 001 (folder contain 3 photos)
    • 002
    • 003
    • ....
  • Train set

    • 001 (folder contain 3 photos)
    • 002
    • 003
    • ....

This is the code:

import random
import shutil

n_photo_train = 26
n_photo_validation = 3
n_photo_test = 3

for idx in range(130):

    source = '/Users/john/photodb_original/{d:03d}'.format(d=(idx + 1))
    dest_train = '/Users/john/photodb_sets/Train/{d:03d}'.format(d=(idx + 1))
    dest_validation = '/Users/john/photodb_sets/Validation/{d:03d}'.format(d=(idx + 1))
    dest_test = '/Users/john/photodb_sets/Test/{d:03d}'.format(d=(idx + 1))

    files = random.choice(os.listdir(source))
    photo_train = files[:n_photo_train]
    photo_test = files[26:29]
    photo_train = files[29:]

    shutil.copyfile(os.path.join(source, photo_train), dest_train)
    shutil.copyfile(os.path.join(source, photo_test), dest_validation)
    shutil.copyfile(os.path.join(source, photo_train), dest_test)

I get this error: IsADirectoryError: [Errno 21] Is a directory: '/Users/john/photodb_original/001/'




vendredi 25 janvier 2019

How random is this 50 x 50 Latin square?

I have the following 50 x 50 Latin square:

    latin_square = [[2,3,4,5,34,37,18,50,36,21,20,35,19,10,12,13,11,43,42,27,26,7,6,39,23,38,22,45,44,14,46,15,30,28,1,33,17,47,31,49,29,8,40,9,24,41,16,48,32,25],[1,33,9,37,41,49,17,25,5,2,35,3,34,21,44,19,43,11,27,18,10,39,38,7,6,22,14,46,28,30,50,42,26,12,23,4,36,15,20,13,47,40,31,45,8,24,29,16,48,32],[33,34,41,7,1,2,50,18,37,49,10,39,42,3,28,17,27,26,38,23,6,15,22,36,14,9,46,30,12,4,47,35,31,44,19,20,25,11,40,45,43,24,8,29,16,5,13,32,21,48],[34,2,3,39,18,50,35,36,19,43,42,4,20,37,1,27,12,10,11,26,33,44,28,49,8,41,17,40,6,7,9,24,25,38,48,5,21,16,13,23,32,45,29,47,22,46,14,30,15,31],[49,18,36,4,3,34,1,2,12,17,44,50,33,42,20,43,38,27,6,10,22,9,41,23,25,35,5,8,37,28,26,46,19,40,7,11,39,31,24,14,30,15,16,13,48,32,47,21,45,29],[17,35,34,23,49,1,19,33,44,27,26,37,10,9,5,11,21,29,43,45,14,2,46,4,41,3,20,16,25,12,13,47,28,7,39,36,50,40,18,8,31,48,42,32,30,6,24,38,22,15],[41,50,20,21,7,18,2,9,28,11,12,36,39,26,23,34,44,4,14,15,3,35,30,8,47,5,19,25,40,38,31,10,1,24,42,37,16,43,48,29,46,27,33,6,32,45,22,17,13,49],[9,19,40,15,10,42,3,34,35,6,8,24,41,38,16,22,1,33,2,46,18,49,26,17,48,43,30,50,32,31,14,25,5,37,21,45,13,29,4,36,7,20,47,39,11,44,23,27,12,28],[10,42,35,26,33,36,4,1,3,46,19,5,2,34,17,49,6,25,41,50,9,18,14,28,38,30,21,24,20,39,45,8,11,47,15,44,37,13,22,31,16,29,48,40,12,27,32,43,7,23],[25,10,42,47,36,9,43,41,2,38,34,26,50,5,18,6,33,22,35,40,4,17,12,1,20,27,44,14,46,15,37,49,3,21,16,28,32,8,30,24,48,13,45,31,19,29,39,11,23,7],[36,43,11,34,50,17,40,10,42,35,2,21,1,18,49,33,9,8,3,41,38,25,24,12,5,6,37,22,13,47,29,26,45,16,31,48,46,7,32,15,4,14,20,23,27,19,30,44,28,39],[37,11,32,31,2,5,27,49,43,14,3,34,21,50,13,1,36,45,19,9,46,28,29,44,30,25,33,17,4,6,41,7,35,23,10,39,18,42,15,47,38,26,24,22,20,8,48,12,16,40],[4,36,2,38,9,35,41,6,22,34,46,14,3,27,11,25,28,19,10,43,39,47,7,18,15,50,23,48,29,44,20,16,42,5,8,1,30,12,37,32,33,31,49,21,40,13,45,26,24,17],[5,27,24,43,37,21,11,42,4,3,28,2,45,41,35,14,13,36,25,29,30,12,18,31,22,46,49,38,19,20,10,50,9,48,47,7,34,26,33,17,6,23,32,15,44,40,1,8,39,16],[20,8,7,6,42,24,39,26,23,15,47,40,48,2,33,38,41,9,22,25,50,32,1,35,49,10,29,36,16,3,30,17,43,4,37,34,5,45,12,18,14,21,13,46,28,11,19,31,27,44],[12,40,27,44,17,28,6,37,11,18,4,20,36,22,32,10,8,48,50,14,5,38,13,21,9,42,7,35,45,23,25,29,46,39,3,15,41,33,49,34,2,1,30,26,43,16,31,24,47,19],[44,24,48,35,25,41,7,5,20,19,15,1,12,33,4,30,17,32,39,42,34,50,49,9,46,37,45,6,38,2,22,18,13,14,26,29,23,10,16,40,27,11,28,8,31,21,36,47,43,3],[28,48,47,50,38,33,15,22,31,44,39,45,17,6,46,26,18,40,7,16,41,20,9,19,24,13,2,49,5,36,42,1,10,32,29,43,3,14,34,30,25,37,21,35,23,12,11,4,8,27],[45,4,50,14,26,13,42,17,27,30,11,49,18,8,2,5,29,20,46,37,25,16,21,40,32,33,1,43,48,24,38,22,34,9,36,23,10,41,6,39,44,12,15,28,35,3,7,19,31,47],[50,9,18,36,20,3,34,4,10,28,1,13,25,45,27,41,22,38,33,49,42,29,2,47,17,11,6,32,30,5,19,40,44,15,35,12,31,48,7,37,24,39,23,16,21,43,8,46,14,26],[18,7,10,20,4,25,26,12,50,31,43,42,49,1,41,29,45,46,30,13,21,36,34,37,33,44,28,39,23,11,17,48,8,22,40,16,27,24,9,2,5,32,3,19,14,47,6,15,38,35],[8,39,12,3,40,45,23,29,24,16,32,33,28,14,36,42,37,13,26,38,1,48,47,20,35,18,34,5,2,19,15,21,50,49,46,30,9,25,17,6,41,22,27,44,10,31,4,7,11,43],[21,20,37,18,23,38,46,14,40,32,9,41,13,30,48,35,2,3,5,6,8,31,50,24,16,1,42,19,49,45,43,39,22,36,11,17,7,34,27,10,15,47,4,33,29,25,26,28,44,12],[13,45,26,30,12,10,8,20,18,37,50,44,4,25,42,46,19,16,29,21,7,34,15,3,40,14,39,27,36,1,28,31,24,6,32,47,48,23,38,33,11,43,2,41,5,35,49,22,17,9],[16,41,28,13,6,26,24,3,38,22,33,43,27,19,50,9,30,35,40,17,31,8,10,48,4,29,25,34,11,32,12,23,15,45,2,21,42,39,47,46,18,7,44,14,1,37,5,49,36,20],[29,16,8,22,45,20,32,19,7,47,36,17,37,44,21,3,5,24,12,34,28,4,25,13,2,39,38,23,14,35,6,33,18,30,49,31,11,9,1,27,26,10,41,43,50,48,15,40,46,42],[42,26,43,45,39,19,36,23,34,41,49,9,16,12,25,7,4,1,17,2,11,10,33,50,29,24,8,15,47,40,5,32,48,31,20,13,44,27,46,21,35,3,18,30,6,22,28,14,37,38],[40,15,16,2,5,29,31,48,26,50,21,18,14,17,34,47,46,37,32,39,13,24,44,45,36,49,41,10,8,27,1,11,6,20,43,9,33,30,25,22,12,28,19,7,3,23,38,42,35,4],[38,23,6,28,44,12,22,7,46,42,31,25,9,36,30,4,10,49,20,19,37,14,48,5,21,8,40,47,39,43,24,13,16,3,41,27,26,32,50,35,45,17,1,11,15,2,34,29,33,18],[48,31,25,19,14,6,20,30,21,39,7,32,23,46,8,40,24,47,34,1,49,41,17,16,13,15,10,44,3,26,18,2,29,35,45,38,22,50,28,12,42,5,43,27,33,36,37,9,4,11],[24,12,33,42,22,11,28,38,8,48,16,46,6,13,40,39,32,44,49,30,2,1,27,41,45,31,18,4,15,50,34,9,37,43,14,26,29,21,36,7,17,25,5,3,47,20,35,23,19,10],[6,47,31,11,35,4,38,21,14,23,27,29,15,28,9,36,49,17,1,33,12,30,20,25,34,7,13,26,43,42,2,41,40,19,24,32,45,44,5,3,8,16,37,48,39,50,46,10,18,22],[31,32,39,27,46,30,47,13,6,36,23,28,44,29,38,15,25,41,9,11,17,22,16,33,37,2,26,12,34,10,48,14,21,8,5,19,43,20,45,42,49,4,35,50,7,18,40,1,3,24],[39,1,45,17,13,23,49,35,16,8,48,27,32,47,24,37,15,31,21,5,40,19,3,29,11,34,43,33,9,46,7,30,14,41,50,10,2,18,44,26,22,42,12,4,38,28,25,36,20,6],[3,17,38,1,31,8,33,47,13,26,29,30,22,24,14,20,35,2,45,4,23,46,42,43,7,40,48,11,27,16,32,36,12,25,44,49,15,28,19,41,39,6,34,5,18,9,50,37,10,21],[43,21,44,10,8,27,16,46,48,5,24,19,11,35,29,45,20,28,18,22,15,40,31,32,42,36,47,37,1,33,3,34,17,26,38,2,14,6,39,9,23,50,7,12,13,4,41,25,49,30],[7,37,5,49,21,22,45,39,1,33,25,23,29,4,3,2,47,15,13,31,35,27,43,11,19,17,50,9,41,18,16,38,32,46,34,42,24,36,10,48,28,44,14,20,26,30,12,6,40,8],[15,38,23,41,19,39,13,28,47,4,17,12,7,20,37,16,14,30,31,32,44,26,45,10,50,48,9,2,35,49,40,6,27,34,25,18,8,5,21,11,1,33,22,24,36,42,43,3,29,46],[22,6,1,12,15,7,37,44,9,20,5,47,38,43,19,24,50,23,4,48,27,3,32,30,31,21,16,29,17,13,39,45,41,33,28,8,49,35,11,25,40,36,46,18,42,34,10,2,26,14],[35,49,19,29,30,14,48,15,32,1,40,6,46,11,22,18,16,12,24,47,43,33,23,27,10,26,31,28,7,9,21,44,2,17,13,25,38,37,8,50,3,41,36,34,4,39,42,20,5,45],[11,22,21,33,16,43,44,24,30,9,14,38,8,40,6,31,34,42,48,7,32,5,37,15,26,19,12,3,50,29,35,28,36,1,27,41,47,46,23,4,10,18,39,17,45,49,20,13,25,2],[32,28,15,46,27,16,12,45,39,7,13,48,24,49,26,44,40,14,23,36,29,37,5,2,18,4,11,31,22,21,8,20,47,10,33,35,19,1,42,43,50,30,9,25,17,38,3,34,6,41],[23,30,29,48,24,15,5,40,49,25,45,22,47,7,31,12,39,50,44,8,36,11,35,46,43,16,32,13,18,41,27,37,20,42,6,14,4,19,3,28,21,38,26,10,9,1,17,33,2,34],[26,25,49,40,32,47,9,11,45,24,41,10,31,23,15,8,7,39,16,20,48,42,4,34,27,12,3,1,21,22,36,43,33,29,18,50,28,2,14,38,19,35,6,37,46,17,44,5,30,13],[19,14,17,8,47,40,25,32,29,10,30,31,35,15,7,50,26,18,36,44,16,6,39,22,28,20,27,41,42,48,23,4,49,13,12,24,1,3,43,5,9,46,11,38,2,33,21,45,34,37],[14,5,30,9,11,48,29,8,33,40,37,16,43,32,45,23,31,34,28,12,24,21,19,6,44,47,4,42,26,17,49,3,7,27,22,46,35,38,41,20,13,2,10,36,25,15,18,39,1,50],[30,44,14,24,43,46,21,16,41,29,6,8,40,31,47,32,48,5,15,28,45,13,36,38,12,23,35,7,10,25,4,27,39,11,17,3,20,22,2,19,37,9,50,49,34,26,33,18,42,1],[46,13,22,25,28,44,14,43,15,12,38,11,30,39,10,48,42,21,47,3,20,45,8,26,1,32,24,18,31,34,33,19,23,50,9,6,40,4,29,16,36,49,17,2,37,7,27,35,41,5],[27,46,13,16,29,32,10,31,25,45,18,7,26,48,43,21,3,6,8,24,47,23,40,42,39,28,15,20,33,37,11,5,4,2,30,22,12,17,35,44,34,19,38,1,49,14,9,41,50,36],[47,29,46,32,48,31,30,27,17,13,22,15,5,16,39,28,23,7,37,35,19,43,11,14,3,45,36,21,24,8,44,12,38,18,4,40,6,49,26,1,20,34,25,42,41,10,2,50,9,33]]

I would like to know whether it is particularly random; that is, if I told you I generated it from an algorithm which generates Latin Squares of size 50 x 50 uniformly at random, how might you support or refute this claim?

Below is the result of running plt.matshow(latin_square) with plt.colorbar().

The result of running plt.matshow(latin_square) with plt.colorbar()




How to generate random unique numbers on java

I'm new to Java and im trying to randomize non-repeating numbers for a Bingo game. My code generates unique random numbers from 1 to 75 only if i do not add a break statement, (which i have to do to only get one number at the time). What do I do?

public static void bingoNumber() {
    Random random = new Random();

   int num;
    String u; 
    String letter = "";
    HashSet<Integer> used = new HashSet<>(75);
        for (int i = 1; i <= 75; i++){
            ball.add(i);
        }

   while(used.size() > 0) {

    num = 1 + random.nextInt(75);

        if (used.contains(num)){
            used.remove(new Integer(num));

          if ( num >= 1 && num <=15){
        letter = "B";
      }else if (num >= 16 && num <=30){
         letter = "I";
      }else if (num >= 31 && num <=45){
        letter = "N";
      }else if (num >= 46 && num <=60){
        letter = "G";
      }else if  (num >= 61 && num <=75){
        letter = "O";   
      }
        u = Integer.toString(num); 
        System.out.print("BINGO CALL IS: " + letter + u + "\n");
break; 

        }
        if (!used.contains(num)){
            continue;
        }
       }

Output:

BINGO CALL IS: B11
BINGO CALL IS: N34
BINGO CALL IS: B4
BINGO CALL IS: G52
BINGO CALL IS: O70
BINGO CALL IS: I28
BINGO CALL IS: O66
BINGO CALL IS: G48
BINGO CALL IS: G58
BINGO CALL IS: O62
BINGO CALL IS: G56
BINGO CALL IS: G59
BINGO CALL IS: I29
BINGO CALL IS: O71
BINGO CALL IS: I25
BINGO CALL IS: I27
BINGO CALL IS: N31
BINGO CALL IS: N43
BINGO CALL IS: I16
BINGO CALL IS: O72
BINGO CALL IS: O61
BINGO CALL IS: G57
BINGO CALL IS: B7
BINGO CALL IS: I26
BINGO CALL IS: I24
BINGO CALL IS: B8
BINGO CALL IS: O74
BINGO CALL IS: G51
BINGO CALL IS: I30
BINGO CALL IS: B14
BINGO CALL IS: B6
BINGO CALL IS: N32
BINGO CALL IS: O64
BINGO CALL IS: I19
BINGO CALL IS: G49
BINGO CALL IS: N42
BINGO CALL IS: N36
BINGO CALL IS: O69
BINGO CALL IS: I18
BINGO CALL IS: G54
BINGO CALL IS: O63
BINGO CALL IS: N44
BINGO CALL IS: G50
BINGO CALL IS: B12
BINGO CALL IS: N41
BINGO CALL IS: N40
BINGO CALL IS: B9
BINGO CALL IS: O68
BINGO CALL IS: B10
BINGO CALL IS: N38
BINGO CALL IS: I21
BINGO CALL IS: N33
BINGO CALL IS: O75
BINGO CALL IS: G55
BINGO CALL IS: N39
BINGO CALL IS: B13
BINGO CALL IS: I20
BINGO CALL IS: G46
BINGO CALL IS: O67
BINGO CALL IS: I17
BINGO CALL IS: N37
BINGO CALL IS: G53
BINGO CALL IS: G60
BINGO CALL IS: B5
BINGO CALL IS: O65
BINGO CALL IS: N45
BINGO CALL IS: O73
BINGO CALL IS: B15
BINGO CALL IS: I22
BINGO CALL IS: B1
BINGO CALL IS: I23
BINGO CALL IS: N35
BINGO CALL IS: B2

The numbers are unique and random but i only want one number at the time (without repeating) not all 75 at once.




How to generate unique random numbers or variables for a request in jmeter for load test?

I have 2 thread group and 1 request . I am trying to execute the same request 5 times with 5 different values. I am using the function ${__time()}. But this generates random value but its the same for all 5 request.Can someone help with this?

Solutions tried:  ${__time()}., ${__Random(0000,9999)}




Choose more words in a token

I am trying to make a random event that chooses from a list of words and sentences. Whenever the event happens it only displays the first word in every line. How do I make it so that it will display the entire line?

Here is the batch file.

set /a groceryrandom=%random%%%16
for /f "tokens=1,2" %%a in (groceryevents.txt) do if %groceryrandom%==%%a echo %%b

Here is the text file its referencing

1 Nothing
2 Nothing
3 "You have gained 1 survivor!"
4 Nothing
5 Nothing
6 "You have lost 1 survivor!"
7 Nothing
8 Nothing
9 "You have gained 1 survivor!"
10 Nothing
11 Nothing
12 "You have found 1 weapon!"
13 Nothing
14 Nothing
15 "You have found 5 ammo!"




How to assign random values from a list to a column in a pandas dataframe?

I am working with Python in Bigquery and have a large dataframe df (circa 7m rows). I also have a list lst that holds some dates (say all days in a given month).

I am trying to create an additional column "random_day" in df with a random value from lst in each row.

I tried running a loop and apply function but being quite a large dataset it is proving challenging.

My attempts passed by the loop solution:

df["rand_day"] = ""

for i in a["row_nr"]:
  rand_day = sample(day_list,1)[0]
  df.loc[i,"rand_day"] = rand_day

And the apply solution, defining first my function and then calling it:

def random_day():
  rand_day = sample(day_list,1)[0]
  return day

df["rand_day"] = df.apply(lambda row: random_day())

Any tips on this? Thank you




using random in python's list and print it but the output is empty

here my code

import random
def check_for_greeting(sentence):
    for word in sentence :
        if word in GREETING_KEYWORDS:
            print (random.choice(GREETING_RESPONSES))

print("start talking : ")
sentence=input().strip()
GREETING_KEYWORDS = ["hello", "hi", "greetings", "sup", "what's up"]
GREETING_RESPONSES = ["'sup bro", "hey", "hey you get my snap?"]
while True :
    check_for_greeting(sentence)
    sentence=input().strip()
    if sentence =="end" : break

like a chatbot. I want it to reply 1 word from random GREETING_RESPONSES if There is keyword ps. I'm a beginner for coding. correct me if my code has something wrong




jeudi 24 janvier 2019

Creating a function: replacing random index values

I am trying to write a function that would be able to look at all the indexes of a vector which have no values stored in them and then replace one of them randomly with the number 2.

How it works(or at least how it should):

Find number of indices with zero ---> used this to find a random number between 1 and number of zero founs ---> finds that index and changes it to 2.

int random_num(std::vector<int>&v){

    int length = std::sqrt(v.size());
    int count = 0;

    for(int i = 0; i < v.size(); i++){
        if(v[i] = 0){
            count++;
        }
    }

    srand(time(0));
    int tmp = (rand()%(count+1));

    for(int i = 0; i < length; i++){
        if(v[i] = 0 && i == (tmp-1)){
            v[i] = 2;
        }
    }
}

The only issue here is that when I compile this, the values of the vector all come out as 0 when I print them out. What is wrong with this?




How to create randomized user ids with no repeats in MySQL?

I am looking for some insight into efficiency and ease of implementation with a certain goal I have. I have a MySQL table storing user information. When an account is created, they need to get their own unique random 5 digit code from 00000-99999.

Here are the strategies I am considering. Some of them seem difficult (for a beginner like me), so I just want to consult Stack Overflow for any advice.

  • Populate the company_id column with all 5 digit codes from 00000-99999 in random order. This is what I have done thus far. My issue is that when someone creates an account, I would need to query the database to find the first open row and grab the 5 digit code associated with it. I haven't been able to figure that part out thus far.
  • Populate the company_id column with all 5 digits codes from 00000-99999 in numerical order. When someone creates an account, I would choose a random open row and grab the 5 digit code associated with it. The issue here is choosing a random row that is open. Again, I do not know how I would accomplish this.
  • Create the 5 digit code when the user creates a new account and create a new row in my user_data with that 5 digit code as the company_id column. The issue here is that the program in which a new account is created must be able to access a list of 5 digit codes that are not yet used. I am thinking this may be the best option, by creating an array of 5 digit codes 00000-99999, filling an array with all currently used 5 digit codes from the company_id column, removing all elements in the first array that match elements in the second, and then selecting a random 5 digit code from the altered first array.

What I am asking is which (of these or your own strategy) would be best first and foremost in terms of efficiency when creating a new account (don't want to keep users waiting), and secondly, in terms of ease of implementation. Thanks in advance!




Sample from pdf for discrete r.v

I have a random variable that can take 4 different values (4,8,16,32)and I would like to update it via sampling from its pdf, which is proportional to:

\begin{equation}
    \pi(\nu)\prod_{i=1}^N(\Gamma(\nu/2)(\nu/2)^{(\nu/2)})^{-1} \lambda_i^{(\nu/2 -1)} e^{-\nu\lambda_i/2}
\end{equation}




return integer value of random string key

This is my BlackJack project and it currently only returns 1 card. I am struggling to get the randomKey to be equal to its value in the HashMap

public static void main(String[] args) {

    Random ran = new Random();
    Scanner in = new Scanner(System.in);

    HashMap<String, Integer> hash = new HashMap<String, Integer>();
    hash.put("2", 2);
    hash.put("3", 3);
    hash.put("4", 4);
    hash.put("5", 5);
    hash.put("6", 6);
    hash.put("7", 7);
    hash.put("8", 8);
    hash.put("9", 9);
    hash.put("10", 10);
    hash.put("Jack", 10);
    hash.put("Queen", 10);
    hash.put("King", 10);
    hash.put("Ace", 11);

    List<String> keyList = new ArrayList<>(hash.keySet());
    List<Integer> valueList = new ArrayList<>(hash.values());


    String[] colors = {"Spades", "Hearts", "Diamonds", "Clubs"};

    for (int i = 0; i < 1; i++) {
        int col = ran.nextInt(colors.length); // random color
        String randomKey = keyList.get(ran.nextInt(hash.size())); // random type
        int keyValue = valueList.get(ran.nextInt(hash.size())); 

        System.out.println(randomKey+ " of "+colors[col]);
        if (keyValue < 21) {System.out.println(keyValue);}
    } // returns a cards

I used the if (keyValue < 21) {System.out.println(keyValue);} to test if the keyValue would be equal to the unique value of the random key. Obviously it isnt, but I need it to be so I can then calculate the sum of multiple cards, while printing out only the keys.




How can i randomly sample from a distribution already fitted with allfitdist in MATLAB?

I 've found the best fitting of a variable distribution (D(:,2)) using the function "allfitdist". Now i want to save this result in a structure and then i want to randomly sample 10000 times from this result. I'm using this code:

[Ddg2 PDdg2] = allfitdist(D(:,2),'cdf')
My(2).result = PDdg2{1,1} %generalized pareto
output = random(My(2).result,10000)

Something is weard because in the output i get a really big matrix. Maybe i'm wrong in the third raw of the code, when i randomly sample from this distribution. Someone can help me?