samedi 30 novembre 2019

PHP generate array of random numbers with conditions

Is there an easy way with PHP to generate an array with 15 items, all single digit numbers between 1 and 8, in random order, but with the conditions that no digit is next to itself and no pair of digits are next to themselves.

Want to end up with something like: 3 2 7 1 3 2 5 6 7 4 5 1 8 4 8

But not: 3 8 4 4 6 7 2 6 7 3 1 1 8 5 2

Or: 2 8 6 3 7 5 7 5 4 8 1 2 4 1 6

Plan B is to generate a bigger array and then compare the current value with the previous during the foreach function and if the same skip that one and move to the next. And I am guessing could do the same by comparing the last three to check for pairs. But then I risk some digits appearing too many times, as the ideal is each digit appearing at least once, but no more than 2 times.




PHP to get random title for videos

Good day. This is a section of my code that goes and gets videos from any video site. What I'm having issues with is having it post a random title, that are all in a text file called titles.txt. What I'm wanting to accomplish is have my script go pull the video embed code, the duration, the tags, etc. Which all works fine until I get to the title part where it pulls locally from the server from the text file. I get a 500 error in the browser when I try to run the script. Here is the code I have that is responsible for putting the title in.

                    $video  = array(
                        'user_id'     => $this->user_id,
                        'status'      => $this->status,                     
                        'site'        => 'xvideos',
                        'id'          => '',
                        'embeddable'  => true,                      
                        'url'         => '',
                        'titles'       => '',
                        'title'       => '',
                        'description' => '',
                        'tags'        => '',
                        'category'    => '',
                        'thumbs'      => array(),
                        'duration'    => 0,
                        'embed'       => '' 

                    function random_title () 
                    { 
                    $titles = file ("titles.txt", FILE_IGNORE_NEW_LINES);
                    $num = rand (0, intval (count ($titles) / 3)) * 3;
                    return ucwords($titles[$num]);
                    }

                    //Title
                    if(preg_match('/title="(.*?)"/', $match, $matches_title)) {
                        $video['title'] = random_title(). ' - My site name';
                    } else {
                        $this->errors[] = 'Failed to get video title for '.$video['url'].'!';
                        if (!$this->debug) continue;
                        else $debug_e[] = 'TITLE';

Can someone help me out with this please so that it will function correctly. I'm kinda lost at the moment on how to get this code to run correctly. Thank you.




How can I write android java random number?

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        final Button roll_Button = findViewById(R.id.rollButton);
        final TextView result_TextView = findViewById(R.id.resutlsTextView);
        final SeekBar seekBar = findViewById(R.id.seekBar);

        roll_Button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Random rand = new Random();
                int nr = rand.nextInt(seekBar.getProgress() + 1);
                result_TextView.setText(Integer.toString(nr));
            }
        }

        );

    }
}

what is wrong here? Nothing is displayed on the screen when I click on ROLL. I written the code in Java. That is a problem with Android Studio?




lua : storing values in string array and printing a value by calling a random index

i have a table named t

t = {"hi","hello","hola","whats up"}

and i want to be able to index the elements so that

hi = 1
hello = 2
hola = 3
whats up = 4

so that this random number generator

math.randomseed(os.time())
ranNumber = math.random(4)

can call on the tables elements and have a 25% probability of printing one element

if you dont understand, the java equivalent of this program would work like this

import java.awt.Desktop;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import java.util.concurrent.TimeUnit;
import javax.xml.soap.SOAPElement;

public class PrintRandom{

 public static void main(String []args){

    String[] names={"hi", "hello", "hola", "whats up"};
    Random r=new Random();
    int RandomNumber=r.nextInt(4);

    System.out.println(names[RandomNumber]);
 }
}



Generate random names

Can someone please help me, i can't seem to figure it out:

exercise: "Add another function to your design, which is now to create and return names according to the specifications in the introduction. Comment out the main function from the first step (do not remove it completely!) and output 100 randomly generated names in a new main function.

The output looks like this: Hadrian Steiner-Jakobi Lucia Sommer Dr. Jo Hintz André Schultheiß Rupert Richter Dr. Anja Fobbe Barbara Pradela Julian-Adrienne Wolfram-Ossege "

i've already created a main function that generates a random male and female full name

import random
man = [a list of male names] 
woman = [list of female names]
lastname = [list of last names]

gen = random.choice(man)
gen2 = random.choice(woman)
gen3 = random.choice(lastname)
def main():
    return print(f'{gen}-{gen3}\n{gen2}-{gen3}')
main()

but i can't figure it out how to add random "dr." and "-" to these names thanks




print('') func does not display the result

I have been working on a simple dice roller. This is what I'm struggling with:

import random

print("What kind of dice would you like to roll?")
class dice:
    input("D4, D6, D8, D10, D20, D30, D100?")

print('How many dice should I roll?')
class many:
    input("1, 13, 53, etc. ?")

if dice ==('d4' or '4'):
    for x in range(many):
      print(random.randint(1,4))

print('Again?')
  1. I haven't found an answer whether a class will work with the 'range' function, however I do not get any errors in the editor or when running the program.

  2. The code itself does prompt for the class input, however the print function for random.randint appears to be ignored/skipped over, as it does not print a result, the code goes to the next line and carries on.

This is what I get as output:

What kind of dice would you like to roll?
D4, D6, D8, D10, D20, D30, D100?4
How many dice should I roll?
1, 13, 53, etc. ?1
Again?

I did read through the documentation for the random library and I could get this example script to run without issue, however when I replace the range in my own script with an integer instead of the class 'many', it still fails to print the result. Ultimately I'd like the range to be set by the user rather than a set amount.

This is the example 'Random' script that runs as it should:

import random
for x in range(10):
  print(random.randint(1,101))
81
87
35
20
89
53
13
13
20
95



vendredi 29 novembre 2019

how optimize prestashop category get product for random

this is prestashop 1.7 version category get product query. if use random, it is very slow, how optimize it?

SELECT
    cp.id_category,
    p.*,
    product_shop.*,
    stock.out_of_stock,
    IFNULL( stock.quantity, 0 ) AS quantity,
    IFNULL( product_attribute_shop.id_product_attribute, 0 ) AS id_product_attribute,
    product_attribute_shop.minimal_quantity AS product_attribute_minimal_quantity,
    pl.`description`,
    pl.`description_short`,
    pl.`available_now`,
    pl.`available_later`,
    pl.`link_rewrite`,
    pl.`meta_description`,
    pl.`meta_keywords`,
    pl.`meta_title`,
    pl.`name`,
    image_shop.`id_image` id_image,
    il.`legend` AS legend,
    m.`name` AS manufacturer_name,
    cl.`name` AS category_default,
    DATEDIFF(
        product_shop.`date_add`,
    DATE_SUB( "2019-11-30 00:00:00", INTERVAL 7 DAY )) > 0 AS new,
    product_shop.price AS orderprice 
FROM
    `ps_category_product` cp
    LEFT JOIN `ps_product` p ON p.`id_product` = cp.`id_product`
    INNER JOIN ps_product_shop product_shop ON ( product_shop.id_product = p.id_product AND product_shop.id_shop = 1 )
    LEFT JOIN `ps_product_attribute_shop` product_attribute_shop ON ( p.`id_product` = product_attribute_shop.`id_product` AND product_attribute_shop.`default_on` = 1 AND product_attribute_shop.id_shop = 1 )
    LEFT JOIN ps_stock_available stock ON ( stock.id_product = `p`.id_product AND stock.id_product_attribute = 0 AND stock.id_shop = 1 AND stock.id_shop_group = 0 )
    LEFT JOIN `ps_category_lang` cl ON ( product_shop.`id_category_default` = cl.`id_category` AND cl.`id_lang` = 11 AND cl.id_shop = 1 )
    LEFT JOIN `ps_product_lang` pl ON ( p.`id_product` = pl.`id_product` AND pl.`id_lang` = 11 AND pl.id_shop = 1 )
    LEFT JOIN `ps_image_shop` image_shop ON ( image_shop.`id_product` = p.`id_product` AND image_shop.cover = 1 AND image_shop.id_shop = 1 )
    LEFT JOIN `ps_image_lang` il ON ( image_shop.`id_image` = il.`id_image` AND il.`id_lang` = 11 )
    LEFT JOIN `ps_manufacturer` m ON m.`id_manufacturer` = p.`id_manufacturer` 
WHERE
    product_shop.`id_shop` = 1 
    AND cp.`id_category` = 12 
    AND product_shop.`active` = 1 
    AND product_shop.`visibility` IN ( "both", "catalog" ) 
ORDER BY
    RAND() 
    LIMIT 50



Trying to make the answer randomly generated after retry in C#

using System;

namespace Test
{
    class Program
    {
        static void Main(string[] args)
        {   

            int num1 = int.Parse(args[0]);
            int num2 = int.Parse(args[1]);            
            bool GameOver = false;
            int turn = 3;
            Random random = new Random();
            int answer = random.Next(num1, num2);        
            // string input = "";

            Console.WriteLine("Hello, welcome to the guess a number challenge");

            while (!GameOver)
            {
                if (turn != 0)
                {                    
                    turn--;
                    Console.WriteLine($"Please Select number between {num1} to {num2}:");                    
                    int SelectedNumber = int.Parse(Console.ReadLine());
                    if (SelectedNumber < answer && SelectedNumber >= num1)
                    {
                        System.Console.WriteLine("Almost there, just the number is too small\n");
                    } else if (SelectedNumber > answer && SelectedNumber <= num2)
                    {
                        System.Console.WriteLine("Your number is too big\n");
                    } else if(SelectedNumber == answer)
                    {
                        System.Console.WriteLine("CONGRATULATIONS!!!! You guess it right\n");
                        GameOver = true;
                        retry();
                    } else
                    {
                        System.Console.WriteLine("Your number is out of range\n");
                    }
                } else
                {
                    System.Console.WriteLine($"GAME OVER!!!! The answer is {answer}");
                    GameOver = true;
                    retry();
                }

                void retry() {
                    System.Console.WriteLine("Would you like to retry? Y/N");
                    string input = Console.ReadLine();
                    string ConsoleInput = input.ToLower();
                    if(ConsoleInput == "y")
                    {
                        GameOver = false;
                        turn = 3;
                    } else if(ConsoleInput == "n")
                    {
                        GameOver = true;
                    } else
                    {
                        Console.WriteLine("Invalid input");
                        retry();
                    }
                }
            }
        }
    }
}

Hello all, just want to ask a question. I tried to build "guess a number" game in terminal, where player has to guess a number based on the number range given. I tried to make the answer randomly generated, thus the Random class. and the answer will be randomized after retry. The problem is, after each retry, the answer is still the same. I am not sure where did I did wrong. Thanks for the help, and sorry for the noob question.




Random movement algorithm in C

I'm basically trying to write down a very basic algorithm that lets a char "move" into a preset map of chars.

What I need to do, is to get the char moving to a next position which must be empty (checked with == ' ' over the map matrix values); if there are both horizontal or vertical need to chose one randomly.

What I've done so far is VERY messy: I first check if there's an empty tile next to the char, if there is one, check if vertically both next tiles are free, if free chose one randomly, then do the same for X axis. If neither vertical\horizontal axis has both free next tiles, find one free and set it as the direction taken.

Now, I don't know if the logic is actually correct but I couldn't come to a better AND working solution. Open to any suggestion.

if(map[charPos.y-2][charPos.x-1] == ' ' || map[charPos.y][charPos.x-1] == ' '
|| map[charPos.y-1][charPos.x-2] == ' ' || map[charPos.y-1][charPos.x] == ' '){

if ((map[charPos.y-2][charPos.x-1] == ' ' && map[charPos.y][charPos.x-1] == ' ')
    || (map[charPos.y-1][charPos.x-2] == ' ' && map[charPos.y-1][charPos.x] == ' ')){
    if ( map[charPos.y-2][charPos.x-1] == ' ' && map[charPos.y][charPos.x-1] == ' '){
        chosenDir = rand() % (DIR_DW - DIR_UP + 1) + DIR_UP;
    } else if (map[charPos.y-1][charPos.x-2] == ' ' && map[charPos.y-1][charPos.x] == ' '){
        chosenDir = rand() % (DIR_RT - DIR_LT + 1) + DIR_LT;
    }
} else if(map[charPos.y-2][charPos.x-1] == ' '){
                chosenDir=DIR_UP;
} else if(map[charPos.y][charPos.x-1] == ' '){
                chosenDir=DIR_DW;
} else if(map[charPos.y-1][charPos.x-2] == ' '){
                chosenDir=DIR_LT;
} else if(map[charPos.y-1][charPos.x] == ' '){
                chosenDir=DIR_RT;
}
}

switch (chosenDir){
    case DIR_UP: {
        charPos.y-=1;
    }
    case DIR_DW: {
        charPos.y+=1;
    }
    case DIR_LT: {
        charPos.x-=1;
    }
    case DIR_RT: {
        charPos.x+=1;
    }
}



2-D regression dependent truncated normal/laplace distribution

I need your help in creating a normal or better truncated laplace distribution which linearly depends on another laplace distributed variable.

This is what I achieved so far unfortunately with NaNs in the derived y-distribution:

import numpy as np
from matplotlib import pyplot as plt
from scipy.stats import gaussian_kde, truncnorm

slope = 0.2237
intercept = 1.066
spread = 4.8719

def dependency(x):
    y_lin = slope * x + intercept
    lower = slope / spread * 3 * x
    upper = slope * spread / 3 * x + 2 * intercept

    y_lin_noise = np.random.laplace(loc=0, scale=spread, size=len(y_lin)) + y_lin

    y_lin_noise[y_lin_noise < lower] = np.nan  # This is the desperate solution where
    y_lin_noise[y_lin_noise > upper] = np.nan  # NaNs are introduced

    return y_lin_noise

max = 100
min = 1
mean = 40
sigma = 25

x = truncnorm((min-mean)/sigma, (max-mean)/sigma, loc=mean, scale=sigma).rvs(5000)
y = dependency(x)

# Plotting
xx = np.linspace(np.nanmin(x), np.nanmax(x), 100)
yy = slope * xx + intercept
lower = slope/spread*3*xx
upper = slope*spread/3*xx + 2*intercept

mask = ~np.isnan(y) & ~np.isnan(x)
x = x[mask]
y = y[mask]

xy = np.vstack([x, y])
z = gaussian_kde(xy)(xy)
idz = z.argsort()
x, y, z = x[idz], y[idz], z[idz]

fig, ax = plt.subplots(figsize=(5, 5))
plt.plot(xx, upper, 'r-.', label='upper constraint')
plt.plot(xx, lower, 'r--', label='lower constraint')

ax.scatter(x, y, c=z, s=3)
plt.xlabel(r'$\bf X_{laplace}$')
plt.ylabel(r'$\bf Y_$')
plt.plot(xx, yy, 'r', label='regression model')
plt.legend()
plt.tight_layout()
plt.show()

Result

What I want to get in the end is a y-distribution without NaNs, so that for every x there is a corresponding y within in the range of the upper/lower thresholds. So to say, a lower/upper-truncated distribution around the regression line.

I am looking forward to ideas!

Thank you and best regards.




TypeError: random() takes no arguments (2 given)

I keep getting the error TypeError: random() takes no arguments (2 given) at this line withing my code: atk = random.random(8, 12)

The out out I want from this line, is for the "atk" variable to output a random number between 8 and 12, whenever that event is called. Could someone help me with this please ?




jeudi 28 novembre 2019

Bound must be positive when add a list?

My categories list doesn't empty but when I call fake product API, it return: "message": "bound must be positive". Maybe the random made these errors? I don't know why. Help me, please!

    @GetMapping("/fake")
    public BaseAPI fakeProducts() {
        BaseAPI baseAPI = new BaseAPI();
        try {
            long totalproducts = productService.getTotalProducts();
            List<Product> productList = new ArrayList<>();
            List<Category> categoryList = new ArrayList<>();
            Random random = new Random();
            for (long i = totalproducts+1; i <= totalproducts + 10; i++)
            {
                Product product = new Product();
                product.setName("Product" +i);
                product.setPrice(prices[random.nextInt(prices.length)]);
                product.setMainImage(images[random.nextInt(images.length)]);
                product.setSize(sizes[random.nextInt(sizes.length)]);
                product.setDisplay(screens[random.nextInt(screens.length)]);
                product.setOperatorSystem(os[random.nextInt(os.length)]);
                product.setFrontCamera(frontCam[random.nextInt(frontCam.length)]);
                product.setBackCamera(backCam[random.nextInt(backCam.length)]);
                product.setCategory(categoryList.get(random.nextInt(categoryList.size())));
                product.setCreatedDate(new Date());
                productList.add(product);
            }
            productService.addListProducts(productList);
            baseAPI.setMessage("success");
        }catch (Exception e) {
            baseAPI.setMessage(e.getMessage());
        }
        return baseAPI;
    }



How to change an if statement depending of Informations

Here is my problem: I have a if statement regrouping multiple conditions eg: if(stat1 & stat2 & stat3 & stat4).

in this condition, I want to compare 4 times 2 numbers.

If the number 1 is negative and the number 2 positive, I want the if statement to be if(num1 >= num2 & ....). If the number 1 is positive and the number 2 is negative, I want the if statement to be if(num1 <= num2 & ...). If the numbers are both positive but number 1 is smaller, I want it to be if(num1 >= num2 & ...)

And I think you get it.

the problem is that i can't just make multiple if statements for every possibilities, since there are something like 8 cases per conditions and 4 conditions. Is there anyway I can adapt my if statement to fit my needs in the script ? (the values number 1 and number 2 are generated randomly)




How to make shapes not overlap in python turtle?

What technique should i use to make the numbers from the second picture not overlap as those in the first picture? The positions of the numbers should be random.

what i should have
what i have




How can I generate a new item randomly from a list every time a button is pressed?

I am learning how to use kivy, and I made an example code meant to select a new random item from a list every time a button is pressed. When I run this code, I get the error: 'line 19, in NewChoice number += 1 UnboundLocalError: local variable 'number' referenced before assignment'. How can I reference number in the NewChoice function?

Code:

from kivy.app import App
from kivy.lang import Builder
from kivy.uix.label import Label
from kivy.uix.screenmanager import Screen
import random

RandomList = ["First", "Second", "Third", "Fourth", "Fifth"]
number = 0

class GameScreen(Screen):

    def __init__(self, **args):
        Screen.__init__(self, **args)
        self.item = random.sample(RandomList, 5)
        self.label = Label(text=str(self.item[number]), color=(1,0,0,1), font_size=(45),size_hint=(0.2,0.1), pos_hint={"center_x":0.5, "center_y":0.9})
        self.add_widget(self.label)

    def NewChoice(self):
        number += 1
        self.label.text = str(self.item[number])

Builder.load_string('''
<GameScreen>:
    name: "GameScreen"
    canvas:
        Color:
            rgb: 1, 1, 1
        Rectangle:
            pos: self.pos
            size: self.size

    Button:
        size: self.texture_size
        on_release: root.NewChoice()
        text: "Press"
        font_size: 50
        color: 1,1,1,1
        background_color: (0,0,0,1)
        background_normal: ""
        background_down: ""
        size_hint: None, None
        pos_hint: {"center_x":0.5, "center_y":0.6}
        width: self.texture_size[0] + dp(10)
        height: self.texture_size[1] + dp(10)
    ''')

class TestApp(App):
    def build(self):
        return GameScreen()

if __name__ == '__main__':
    TestApp().run()



Preventing randomly generated pictureboxes from clashing (C# Form)

The pictureboxes I create in this way sometimes overlap. how can i prevent it ?. I want a distance between each picture box. for example, a distance of at least 10px between pictureboxes.

 int sayac = 0;
            Random random = new Random();
            while (sayac < 10)
            {

                PictureBox picture = new PictureBox();
                picture.BackColor = Color.Blue;
                picture.SizeMode = PictureBoxSizeMode.StretchImage;
                picture.SetBounds(random.Next(621, 967), random.Next(56, 647), 100, 50);
                this.Controls.Add(picture);
                sayac++;

            }



Private setction and classes OMP, Random C++. Problem with understanding with a result

The task is to calculate PI with MonteCarlo and OpenMP. The code is below:

#include <omp.h>
#include <chrono>
#include <iostream>
#include <random>

#define numSamples 10000000

int main() {

    double I, t1, t2, x, y;
    std::default_random_engine engine;
    auto seed = std::chrono::system_clock::now().time_since_epoch().count();
    std::uniform_real_distribution<double> distr(-1.0, 1.0);
    engine.seed(seed);


    size_t counter = 0;

    t1 = omp_get_wtime();

#pragma omp parallel for reduction(+ : counter) private(x, y) firstprivate(engine, distr)
    for (size_t i = 0; i < numSamples; ++i) {

        x = distr(engine);
        y = distr(engine);

        if (x * x + y * y <= 1) {
            counter++;
        }
    }

    t2 = omp_get_wtime();

    I = 4.0 * (double)counter / numSamples;
    std::cout << "I = " << I << ", t = " << t2 - t1 << "." << std::endl;

    return 0;
}

There is a question. I should have the engine variable private for every thread and it's understandable. But as I've noticed there is no need for making distr variable private. There is no race conditions in this case (the execution time of the program is the same if this variable private or not). Why it happens this way?




python guessing random number game not working, my names arent defined?

import sys, random
def rand():
    number = random.randint(0, 100)

def start():
    print("Entrez un nombre et essayez de faire correspondre le nombre aléatoire")
    guess= int(input())

def check():
    print (guess, number)
    if guess == number:
        print ("Les nombres sont le même!")
        print ("Recomence?")
        reawn=str(input())
        if reawn == "oui":
            rand()
            start()
            check()
    elif guess < number:
        print ("Ton nombre est plus grands que le nombre aléatoire!")
        print ("Essaye encore?")
        reawn=str(input())
        if reawn == "oui":
            start()
            check()
    elif guess > number:
        print ("Ton nombre est plus petit que le nombre aléatoire!")
        print ("Essaye encore?")
        reawn=str(input())
        if reawn == "oui":
            start()
            check()

rand()
start()
check()

Traceback (most recent call last): File "F:\Dominic\Python\rando.py", line 36, in check() File "F:\Dominic\Python\rando.py", line 10, in check print (guess, number) NameError: name 'guess' is not defined




Python function which provides a random orderings completely different from the previous one

I am looking for a function in Python which provides you different orderings each time without replacement, so for example:

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

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

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

but not

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

since number 0 has already been in the first position once.




How to reproducibly query random rows with SQLAlchemy from PostgreSQL?

I am trying to pseudo-randomly select rows from a PostgreSQL table using SQLAlchemy, but I need to use a seed to guarantee reproducibility of the query. The specific case is concerning a publication being submitted, tied to a codebase.

This answer does a great job introducing how one can leverage the following one-liner to select a single random row:

select.order_by(func.random()) # for PostgreSQL, SQLite

Further, one can select many of psuedo-random rows via:

select.order_by(func.random()).limit(n)

But how do I ensure that I select the same psuedo-random rows every time I run the above query?




Use of Diehard : How to format a suitable input for Diehard Test?

I am studying on testing PRNG and I have problem in using Diehard Test. This intruction in Diehard's document (Prof. Marsaglia) is not clear to me: _

Your random number generator should produce 32-bit integers. (If 31 bits, left justify by shift-left-one, as some of the tests in DIEHARD favor leading bits.) You should send them to your ascii file in hex form, 8 hex 'digits' per integer, 10 integers per line, no intervening spaces. The ascii file will be twice as big as the binary file it is reduced to._

In fact, I generated random number by using Marsenne Twister (MT19937) algorithm in C and also obtained the integer numbers. But I am not sure how to make a test file which is used as an input for Diehard or Dieharder. I hope to hear from you in detail about my problem.

Thank you,

#include <stdio.h>

/* Period parameters */  
#define N 624
#define M 397
#define MATRIX_A 0x9908b0dfUL   /* constant vector a */
#define UPPER_MASK 0x80000000UL /* most significant w-r bits */
#define LOWER_MASK 0x7fffffffUL /* least significant r bits */

static unsigned long mt[N]; /* the array for the state vector  */
static int mti=N+1; /* mti==N+1 means mt[N] is not initialized */

/* initializes mt[N] with a seed */
void init_genrand(unsigned long s)
{
    mt[0]= s & 0xffffffffUL;
    for (mti=1; mti<N; mti++) {
        mt[mti] = 
        (1812433253UL * (mt[mti-1] ^ (mt[mti-1] >> 30)) + mti); 
        /* See Knuth TAOCP Vol2. 3rd Ed. P.106 for multiplier. */
        /* In the previous versions, MSBs of the seed affect   */
        /* only MSBs of the array mt[].                        */
        /* 2002/01/09 modified by Makoto Matsumoto             */
        mt[mti] &= 0xffffffffUL;
        /* for >32 bit machines */
    }
}

/* initialize by an array with array-length */
/* init_key is the array for initializing keys */
/* key_length is its length */
/* slight change for C++, 2004/2/26 */
void init_by_array(unsigned long init_key[], int key_length)
{
    int i, j, k;
    init_genrand(19650218UL);
    i=1; j=0;
    k = (N>key_length ? N : key_length);
    for (; k; k--) {
        mt[i] = (mt[i] ^ ((mt[i-1] ^ (mt[i-1] >> 30)) * 1664525UL))
          + init_key[j] + j; /* non linear */
        mt[i] &= 0xffffffffUL; /* for WORDSIZE > 32 machines */
        i++; j++;
        if (i>=N) { mt[0] = mt[N-1]; i=1; }
        if (j>=key_length) j=0;
    }
    for (k=N-1; k; k--) {
        mt[i] = (mt[i] ^ ((mt[i-1] ^ (mt[i-1] >> 30)) * 1566083941UL))
          - i; /* non linear */
        mt[i] &= 0xffffffffUL; /* for WORDSIZE > 32 machines */
        i++;
        if (i>=N) { mt[0] = mt[N-1]; i=1; }
    }

    mt[0] = 0x80000000UL; /* MSB is 1; assuring non-zero initial array */ 
}

/* generates a random number on [0,0xffffffff]-interval */
unsigned long genrand_int32(void)
{
    unsigned long y;
    static unsigned long mag01[2]={0x0UL, MATRIX_A};
    /* mag01[x] = x * MATRIX_A  for x=0,1 */

    if (mti >= N) { /* generate N words at one time */
        int kk;

        if (mti == N+1)   /* if init_genrand() has not been called, */
            init_genrand(5489UL); /* a default initial seed is used */

        for (kk=0;kk<N-M;kk++) {
            y = (mt[kk]&UPPER_MASK)|(mt[kk+1]&LOWER_MASK);
            mt[kk] = mt[kk+M] ^ (y >> 1) ^ mag01[y & 0x1UL];
        }
        for (;kk<N-1;kk++) {
            y = (mt[kk]&UPPER_MASK)|(mt[kk+1]&LOWER_MASK);
            mt[kk] = mt[kk+(M-N)] ^ (y >> 1) ^ mag01[y & 0x1UL];
        }
        y = (mt[N-1]&UPPER_MASK)|(mt[0]&LOWER_MASK);
        mt[N-1] = mt[M-1] ^ (y >> 1) ^ mag01[y & 0x1UL];

        mti = 0;
    }

    y = mt[mti++];

    /* Tempering */
    y ^= (y >> 11);
    y ^= (y << 7) & 0x9d2c5680UL;
    y ^= (y << 15) & 0xefc60000UL;
    y ^= (y >> 18);

    return y;
}

/* generates a random number on [0,0x7fffffff]-interval */
long genrand_int31(void)
{
    return (long)(genrand_int32()>>1);
}

/* generates a random number on [0,1]-real-interval */
double genrand_real1(void)
{
    return genrand_int32()*(1.0/4294967295.0); 
    /* divided by 2^32-1 */ 
}

/* generates a random number on [0,1)-real-interval */
double genrand_real2(void)
{
    return genrand_int32()*(1.0/4294967296.0); 
    /* divided by 2^32 */
}

/* generates a random number on (0,1)-real-interval */
double genrand_real3(void)
{
    return (((double)genrand_int32()) + 0.5)*(1.0/4294967296.0); 
    /* divided by 2^32 */
}

/* generates a random number on [0,1) with 53-bit resolution*/
double genrand_res53(void) 
{ 
    unsigned long a=genrand_int32()>>5, b=genrand_int32()>>6; 
    return(a*67108864.0+b)*(1.0/9007199254740992.0); 
} 
/* These real versions are due to Isaku Wada, 2002/01/09 added */

int main(void)
{
    int i;
    unsigned long init[4]={0x123, 0x234, 0x345, 0x456}, length=4;
    init_by_array(init, length);
    printf("1000 outputs of genrand_int32()\n");
    for (i=0; i<1000; i++) {
      printf("%10lu ", genrand_int32());
      if (i%5==4) printf("\n");
    }
    printf("\n1000 outputs of genrand_real2()\n");
    for (i=0; i<1000; i++) {
      printf("%10.8f ", genrand_real2());
      if (i%5==4) printf("\n");
    }
    return 0;
} 




mercredi 27 novembre 2019

PHP random no repeat

I have 4 numbers to be random select from 1 to 4. How can i create that number will not repeat in 2 or 3 times in a row.

I can't use datebase or cookies and every time is a new user.

<?php

$temp = (rand(1,4));
echo $temp;
?>



Calculate number of distinct values between two numbers at a given precision

Context: I am building a random-number generating user interface where a user can enter values for the following:

  • lowerLimit: the lower limit for each randomly generated number
  • upperLimit: the upper limit for each randomly generated number
  • maxPrecision: the maximum precision each randomly generated number
  • Quantity: the maximum number of random number values to be generated

The question is: how can I ensure that at a given lowerLimit/upperLimit range and at a given precision, that the user does not request a greater quantity than is possible?

Example:

lowerLimit: 1 upperLimit: 1.01 maxPrecision: 3 Quantity: 50

At this precision level (3), there are 11 possible values between 1 and 1.01: 1.000, 1.001, 1.002, 1.003, 1.004, 1.005, 1.006, 1.007, 1.008, 1.009, 1.100, yet the user is asking for the top 50.

In one version of the function that returns only distinct values that match user criteria, I am using a dictionary object to store already-generated values and if the value already exists, try another random number until I have found X distinct random number values where X is the user-desired quantity. The problem is, my logic allows for a never-ending loop if the number of possible values is less than the user-entered quantity.

While I could probably employ logic to detect runaway condition, I thought it would be a nicer approach to somehow calculate the quantity of possible return values in advance to make sure it is possible. But that logic is eluding me. (Haven't tried anything because I can't think of how to do it).

private Random RandomSeed = new Random();
public double GetRandomDouble(double lowerBounds, double upperBounds, int maxPrecision)
{
    //Return a randomly-generated double between lowerBounds and upperBounds 
    //with maximum precision of maxPrecision
    double x = (RandomSeed.NextDouble() * ((upperBounds - lowerBounds))) + lowerBounds;
    return Math.Round(x, maxPrecision);
}
public double[] GetRandomDoublesUnique(double lowerBounds, double upperBounds, int maxPrecision, int quantity)
{
    //This method returns an array of doubles containing randomly-generated numbers
    //between user-entered lowerBounds and upperBounds with a maximum precision of
    //maxPrecision.  The array size is capped at user-entered quantity.

    //Create Dictionary to store number values already generated so we can ensure
    //we don't have duplicates
    Dictionary<double, int> myDoubles = new Dictionary<double, int>();
    double[] returnValues = new double[quantity];
    double nextValue;
    for (int i = 0; i < quantity; i++)
    {
        nextValue = GetRandomDouble(lowerBounds, upperBounds, maxPrecision);
        if (!myDoubles.ContainsKey(nextValue))
        {
            myDoubles.Add(nextValue, i);
            returnValues[i] = nextValue;
        }
        else
        {
            i -= 1;
        }
    }
    return returnValues;
}



Python; How do we copy a random line in a txt file and delete the same line?

We have 2 txt files. (file1.txt and file2.txt)

I want a random row in file1.txt to be assigned to the variable named x and I want this random line to be deleted from file1.txt and added to file2.txt in a new line.

If there is nothing in file1.txt, I want to copy all lines in file2.txt and throw them into file1.txt and delete all lines in file2.txt. And then I want a random row in file1.txt to be assigned to the variable named x. Delete this random line from file1.txt and delete it from file2.txt I want it to be added to txt in a new line.

I was only able to select random rows and assign them to x.

import random
from random import randint

file=open("file1.txt","r")
rows=file.readlines()
i=0
m={}
for row in rows:
    m[i]=row
    i=i+1
print(i)
random_row_number= random.randint(0,i)
x=m[random_row_number]
file.close()



pyspark - get random values reproducible across Spark sessions

I want to add a column of random integers to a dataframe for something I am testing. I am struggling to get reproducible results across Spark sessions. I am able to reproduce the results by using

from pyspark.sql.functions import rand

new_df = my_df.withColumn("rand_index", rand(seed = 7))

but it only works when I am running it in same Spark session. I am not getting same results once I relaunch Spark and run my script. I also tried defining a udf and using random from Python with random.seed set but to no avail.

Is there a way to ensure reproducible random number generation across Spark sessions? I would really appreciate some guidance :) Thanks for the help!




How to generate 2**40 possible binary numbers with conditions

I want to generate all possible 2**N binary numbers with conditions that every array must have 20 of ones (1) like this: 00000000001111111111111111111110000000000, i found methods of generating the binary matrix like this one:

import itertools
l = itertools.product([0, 1], repeat=N)

and i tried to generate it using Numpy but i get memory errors.

So is there any other methods ?




Multiple samplings and calculating Standard deviation and standard error of the Mean using a trend line

Assuming I have the following data:

df1<-rnorm(100,000, 20,5)

I want to get the following samples from df1 with 50 trials each:

C=( 25,50,100,200,300,400,500,600)

Next, I want to plot a trend line. In the trend line plot, the x-axis= Sample size and the y-axis is SD and SEM. Sorry, I was unable to draw the plot, but hopefully, my description is clear. Thanks for your help.




How can I use send_keys at random intervals with Python Selenium?

For example, when writing "Hello", I do this to put a random wait time between 0.03 and 0.2 seconds for each character to be typed.

Is it possible to do write with a single send_keys function with a random wait time between 0.03 and 0.2 seconds to write each character?

import random
import time
from selenium import webdriver
from selenium.webdriver.chrome.options import Options

chrome_options = Options()
driver = webdriver.Chrome(executable_path='C:/Users/X/chromedriver.exe',chrome_options=chrome_options)

driver.get ('https://example.com/login')

driver.find_element_by_name("session[username_or_email]").send_keys('H')
time.sleep(random.uniform(0.03,0.2))
driver.find_element_by_name("session[username_or_email]").send_keys('e')
time.sleep(random.uniform(0.03,0.2))
driver.find_element_by_name("session[username_or_email]").send_keys('l')
time.sleep(random.uniform(0.03,0.2))
driver.find_element_by_name("session[username_or_email]").send_keys('l')
time.sleep(random.uniform(0.03,0.2))
driver.find_element_by_name("session[username_or_email]").send_keys('o')
time.sleep(random.uniform(0.03,0.2))



Asynchronous data (entropy) collection in python

I'm trying to code a PRNG which adds entropy into its state. To do that, i want to use multiple entropy sources, that would collect the entropy asynchronously into buckets, and the PRNG itself would then take the data from them.

What is the best way to build such asynchronous data collection in python?

class EntropyBuckets(object):
    buckets = [[]] ## only an example, this should be a structure capable of working with asynchronously added data

    def get_entropy(self):
        pass

In essence this would be used by the PRNG. During initialization all of the entropy sources would start running asynchronously for the duration of the process. PRNG would then be able to request entropy without being blocked (due to waiting for more data).

class EntropySource(object):
    entropy_bucket = None # reference to a single EntropyBuckets bucket where it adds its entropy

This is just some random class to represent the source. It can define any methods, but the main point is it only has reference to single bucket it adds entropy into. There is no further interaction with teh parent class outside of when it gets shut down.

As for what these sources are, it can be anything from cpu temp, clocks, keyboard or mouse data, etc.

Just to reiterate, the question is only about what would be the best way to asynchronously collect data like this.




Placing randomly selected images into new folder

I have a directory that contains a large amount of sub directories.

Within each of these subdirectories are different jpegs, pngs.

I want to:

Select X amount of random images from these subdirectories

Create a new folder and copy these selected random images inside.

Thanks to help received here already I can print out a random selection of images using os.walk and random.choice.

import os
import random
import shutil


files_list = []
for root, dirs, files in os.walk("/Path/to/Directory"):
    for file in files:
        #all 
        if file.endswith(".jpg") or file.endswith(".png") or file.endswith(".jpeg"):
            files_list.append(os.path.join(root, file))


#print images
#lets me count and print the amount of jpeg,jpg,pmg 
file_count = len(files_list)
print file_count

print files_list   
print(random.sample(files_list, 2))  #prints two random files from list 

However, my issue is with actually selecting random images (not their names)

I have tried to create a variable imagePath that uses os.walk

#creates a variable imagePath that lets me access all img files in different folders
imagePath = os.walk("/Path/to/Directory") 

and a new variable to randomly select a single image from imagePath

#create a variable that lets me choose random iamge from imagePath
randomImages = random.choice(os.listdir(imagePath)) 

and then created a new directory and used shutil.copy to move radnomally selected image into this new directory

#creates a new directory 
os.mkdir('testDirectory')

#moves the randomly selected image into new directory 
shutil.copy(randomImages, testDirectory)

However, I am getting the following error:

Traceback (most recent call last):
  File "crawl.py", line 28, in <module>
    randomImages = random.choice(os.listdir(imagePath)) 
TypeError: coercing to Unicode: need string or buffer, generator found

Any suggestions would be great.




randomly record array values to data frame column with if condition

I have an array with randomly generated data (Y1age). I need to randomly assign values from this array (Y1age) to a column ('age') in data frame if a condition is met.

I tried this:

df.loc[df['year'] == "Y1", 'age'] = (np.random.choice(Y1age))

This only chooses I value and assigns to all cells if a condition is met: head of the data frame:




mardi 26 novembre 2019

c++ opencv randu function throws 'Integer division by zero'

I'm trying to fill a cv::Mat with random numbers.

cv::Mat mat(100, 100, CV_8UC4);
cv::randu(mat, cv::Scalar(0), cv::Scalar(256));

The above code works fine, as long as I keep the scalars exactly as they are. Changing 0 and 256 to any other values will cause an Integer division by zero exception on the call to randu. Can anyone explain to me why? I'm using opencv3.




Excel VBA Total 10% Random rows from a data but equally selected for each users

I want to create a macro to select 10% rows randomly from a data.

BUT there are 6 users so I want my sample to select equal rows for each user.

DATA: Staff 1 | 10 entries created in this month Staff 2 | 20 entries created in this month Staff 3 | 5 entries created in this month Staff 4 | 15 entries created in this month Staff 5 | 10 entries created in this month

Total entries created for a month = 60. I need 10% of sample - At least 12 random entries selected. This means, I need 3 random samples to be selected (and highlighted) for each Staff. (Max 15 samples)

OUTCOME: Staff 1 | Highlight 3 random entry created by Staff 1 Staff 2 | Highlight 3 random entry created by Staff 2 Staff 3 | Highlight 3 random entry created by Staff 3 Staff 4 | Highlight 3 random entry created by Staff 4 Staff 5 | Highlight 3 random entry created by Staff 5

I don't need to create another worksheet. Just want to Highlight the samples chosen on the same worksheet.

Please help!




Selecting random IDs from another table....confused about LATERAL JOIN

I'm trying to get a handle on generating random data in Postgres, and find I'm misunderstanding something about LATERAL JOIN. Building on some help I got earlier, I've got some code that's trying to:

-- Generate a series of numbers
-- Generate timestamps on the hour matching the number sequence
-- Generate a random(ish) score in a roughly normal distribution for each row
-- Pick an ID randomly from a table in the database.

This last bit is not working. When I run the script shown below, I get a random value for the facility_id, but every row has the same random value. I'd like the random ID assigned on each row, not once globally for the whole run. In procedural thinking, the facility_id is being assigned before the loop, and I want it assigned in the loop. I thought that LATERAL JOIN would help me out here, but

WITH facilities_count AS
(SELECT count(*) from facility)

 SELECT hour_number AS id, -- Get numbers in sequence.
       '2019-01-01 00:00'::timestamp + interval '1 HOUR' * hour_number AS stamp, -- Get hours in sequence
        ABS(TRUNC(normal_rand(1, 0, 1) * 100)) AS score, -- Create a random score in a ~normal distribution.
       random_facility.id

 FROM (SELECT * FROM generate_series(1,8760,1) AS hour_number) generated_numbers 

 LEFT JOIN LATERAL
      (SELECT id
          FROM facility 
        OFFSET floor(random() * (select count from facilities_count))
         LIMIT 1) random_facility
            ON true;

I thought that a subquery might work, but I also get a single value across all rows for the facility_id with this code:

WITH facilities_counter AS
(SELECT count(*) from facility)

 SELECT hour_number AS id, -- Get numbers in sequence.
       '2019-01-01 00:00'::timestamp + interval '1 HOUR' * hour_number AS stamp, -- Get hours in sequence
        ABS(TRUNC(normal_rand(1, 0, 1) * 100)) AS score, -- Create a random score in a ~normal distribution.
         (SELECT id FROM facility OFFSET floor(random() * (select count from facilities_counter)) LIMIT 1)

 FROM (SELECT * FROM generate_series(1,8760,1) AS hour_number) generated_numbers;

I haven't listed the facility table definition, but the only field that matters above is id, so any table would work the same way.

In case it makes any difference to the answer, once I can figure out the solution to this problem, I'd like to then use the random facility_id on each row as an input to select something else out of another table.

Thanks for any help. I'm working on this not just to get the solution, but to try and get a better mental model of how the various tools work. I'm (obviously) not at the point where I can read code like the above and predict in my head how it will behave. Getting to that understanding is kind of fundamental to figuring out how to solve problems on my own. Put another way, I'm not only trying to solve this problem, I'm trying to reduce my mental gaps generally.




Get multiple random different items from an array in javascript?

function question1(){
    if(sessionStorage.quizCounter == 0){
        var qa0 = qs[Math.floor(Math.random() * 19)];
        document.getElementById('questions_container').innerHTML = qa0[0]

        for (let i = 1; i <= 3; i++) {
            document.getElementById('answers_container').innerHTML += qa0[Math.floor((Math.random() * 2))+1];
        }
    }
}

Aight so that's my function it's supposed to place the first item in the array in a <div id="questions_container"> wich works but the second part, the for-loop, doesn't.

The for-loop is supposed to paste the last 3 items randomly in <div id="answers_container">. And straight up got no idea on how to do that other than

qa0[0] is always the question. qa0[1, 2, 3] is always the answeres. qa0[] qontains always 4 items.




Trying to generate an image where each pixel is a random color in python

I'm trying to make an image with a random color for each pixel then print open a window to see the image.

import PIL, random
import matplotlib.pyplot as plt # single use of plt is commented out
import os.path  
import PIL.ImageDraw            
from PIL import Image, ImageDraw, ImageFilter


im = Image.new("RGB", (300,300))

for r in range(0,300):
    for c in range(0,300):
        re = random.randint(0, 255)
        gr = random.randint(0, 255)
        bl = random.randint(0, 255)
        im[r][c]=[re,gr,bl]
im.show()

     14         bl = random.randint(0, 255)
---> 15         im[r][c]=[re,gr,bl]
     16 im.show()
TypeError: 'Image' object does not support indexing 



How can I load only Google StreetView dynamic images in react-native?

I'm trying to create a Game similar to "Geoguessr" for a Mobile Application problem. My problem is that when I'm loading random StreetView coordinates, it happens that I'm loading static images made by people and loaded in the Google database. Is there any way to exclude this kind of images? I already tried to load the images using as parameter "StreetViewSource OUTDOOR" but it doesn't seem to work. Thank you in advance.




Generate random number in increments of X in Javascript not working

I'm trying to generate random numbers in increments of X using a generic function in Javascript which returns a random number, my function is:

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

When used, e.g: getRndInteger(50, 500) a random number will be generated, e.g: 253, however, I'm trying to modify my function to generate a random number between Z and X, but in increments of A, so for instance, 250, 300, 350, 400 ... etc. I've tried:

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

// and...

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

both of these return numbers beyond my maximum number.




How can i randomly generate EOS account and Public key with flutter App

I have been using Eosdart package of flutter for connecting and calling action on EOS blockcahin but there is no method for creating EOS accocut and keys for account. Is there any way through which we can create Eos account on flutter app?




Is there a way of saying "if anything == anything"? (Python)

sample code:

import random

x = random.randint(1, 101)
y = random.randint(1, 101)
z = random.randint(1, 101)

print(x, y, z)

Now, is there an easier way of saying

while x == y or x == z or y == z:
    x = random.randint(1, 101)
    y = random.randint(1, 101)
    z = random.randint(1, 101)

Because the more variables you have, the longer that while statement goes and the uglier and more frustrating it gets if you forget something.

Something like: If any variable is equal to any other one: reroll.

Thanks!




lundi 25 novembre 2019

Is there a cmd in Stata to generate a variable with custom observations?

I want to create a variable with continuous observations( note : the observations should be of same length : specifically (0001 - 8000).

I want this in order to create a UID by merging this variable with other identifying variable. I have tried using (egen var = _n).But the observations are of unequal length(e.g : 1 - 8000).

Any help on the this would be really appreciated.

Thanks




C++ same random number [duplicate]

This question already has an answer here:

While creating 2 different random numbers, they are the same as each other every time.

void foo() {
        int YPos;
        int XPos;
        YPos = ranInt();
        cout << YPos << endl;
        XPos = ranInt();
        cout << XPos << endl;
}
int ranInt() {
        srand(time(NULL));
        int ranNum;
        ranNum = rand() % 4 + 1;
        return ranNum - 1;
}

This gives me an example output:

2

2

How would I go about making these numbers different from each other?




boost::random generates identical values too often from the same seed at different states

Problem description

Sometimes I get the same random number from a uniform distribution using a Mersenne Twister engine even I properly used the engine and iterated it. I know that the number of possible states of the engine is finite and number of possible generated values is also finite, but this is not the case now.

Using boost's implementation, 1e6 number of uniformly distributed random values are generated on the range [0; 1e7). That means that there way more possible values than required number of random values. However, I get quite often the same values, sometimes more than 100 times in this range. How is it possible?

Code

A simple code is provided to reproduce the situation. On both platforms I get the same problem:

  • MSVS 2019 with boost-random:x64-windows 1.71.0, and
  • g++ (Ubuntu 5.4.0-6ubuntu1~16.04.12) 5.4.0 20160609 with libboost-dev 1.58.0.1ubuntu1
#include <iostream>
#include <chrono>

#include <boost/random/mersenne_twister.hpp>          // random number generator
#include <boost/random/uniform_real_distribution.hpp> // uniform distribution generator
using namespace std;

int main()
{
    size_t seed = static_cast<int> (std::chrono::system_clock::now().time_since_epoch().count());
    cout << "seed = " << seed << endl;

    boost::random::mt19937 engine(seed);                         // the random number generator engine
    boost::random::uniform_real_distribution<double> u(0, 1e7);  // uniformly distributed double values on the range [0; 1e7)
    cout.precision(20);
    vector<double> history;                                      // stores the generated values for comparison
    for (size_t i = 0; i < 1e6; ++i)
    {
        history.push_back(u(engine));
        for (size_t j = 0; j < i; ++j)
            if (history[i] == history[j])
                cout << "Equal values ("<< history[i] <<") at ID = " << i << " and " << j << endl;
    }
}

Question

Is there a bug in the code that produces the same values? Or is it a bug in boost?

For my task it is important to generate numbers with uniform distribution. Finding identical values is one of the easiest tests but there are many more and I am sure I don't want to do quality analysis on a well-known library like Boost. I didn't want to use the standard library, because it is not guaranteed that two different compilers will give the same sequence for the same seed values, but it was a requirement for the task. What kind of a solution can you suggest?

Note

A strange behavior can be seen if one compares the generated values with the one std::random generates. Example for values from random::boost for seed 4561565448989 is

1755586.0406719148159
3354420.976247638464   <--
3630764.0071026980877
3488445.2889673411846  <--
7920481.4555123448372
8773544.1024415194988  <--

while standard library generates

3354420.9766563926823  <--
3488445.2898126943037  <--
8773544.1042856499553  <--
...

That is, every second generated value in the boost's sequence is very close to a corresponding value in the standard library's implementation. When two values in the boost-sequence are equal, the values in the standard-library-sequence are not equal, but close to each other. The similarity holds for MSVS and g++ compilers too, which have the right to have different implementation for Mersenne Twister and distributions.




How to demonstrate a mean of sample means using a single histogram

Suppose I have data as follows:

df1<-rnorm(400000, 65,10)

I want to draw 1000 samples of size 100 and plot a histogram using Means of Samples. In the histogram, the x-axis is "Mean" and the y-axis is "Frequency" and a Red Line shows the Mean of Samples in the middle of the histogram.

I am sorry that I could not develop a histogram to show it. I hope my description makes it clear. Any help would be much appreciated.




Creating a custom random variable

I want to create a custom variable or command that can be called on like $RANDOM, but for strings. I have a script that creates a random string, using /dev/urandom . The script produces a randomly generated string each time the script is run.

#!/bin/bash

rando=$(head -100 /dev/urandom | tr -dc a-zA-Z0-9 | fold -w 15 | head -1)

echo $rando

If I create an alias or environmental variable that calls on the script, it will produce only one variation of a random string until a new bash sessions is created. How can I make it so it will create a new variation of the random string in the same bash session?




python systemrandom for unique numbers

I need to generate a globally unique integer identifier.

Does the number generated using

from random import SystemRandom
SystemRandom().getrandbits(64)

Is guaranteed to be unique?




Transformation of random variables with exponential distribution

I am wondering about the distribution of 2 random variable with exponential distribution. The transformation cases are: W=X/(X+Y) and Z=(X-Y)/(X+Y) where Y and X distribute exponential distribution with lambda parameter.

Can someone help me for these transformation?

Moreover, i am also doing conditional transformation z: X|(X+Y)~Hypergeometric(m+n, n; z) where X~Bin(n,p) and Y~Bin(m, p) but i did not get the hypergeometric distribution. Seems like i did something wrong. I just simply used conditional probability theorem which is P(X|X+Y) = P(X, X+Y)/P(X+Y). Can i estimate this way? or am i wrong?




Do most pseudorandom number generators produce a cyclic sequence of unique numbers?

Saw the formula for a pseudorandom number generator in BASIC ages ago and it used each pseudorandom number as the seed for the next one. So if it hit the same number after a while, it would cycle the same sequence all over again and therefore the numbers in the sequence were all different.

  1. Would the sequence include the complete set of numbers from 0 to 2^16-1 for the 16 bit version of this generator, all appearing once?

  2. Is this what happens in most pseudorandom number generators in most languages even today?




How to do word + consecutive/ random numbers with imacros?

I need to write a name with a random number or a consecutive number house12 house15 or house18 house19.... I do it:

4l TAG POS=1 TYPE=INPUT:TEXT FORM=ID:mForm ATTR=ID:checkoutm CONTENT=house 5l TAG POS=1 TYPE=INPUT:TEXT FORM=ID:mForm ATTR=ID:checkoutm CONTENT= EVAL("var randomNumber=Math.floor(Math.random()*100 + 1); randomNumber;")

Imacros write house but when write the random number delete house

How can i do for imacros don’t delete house? And how can i do yo write consecutive number house18, house19, house20....?

Thanks




How to block randomize data according more than just 1 parameter using R

I want to do block randomize my data into 3 arms with respect to both gender and smoking status as best as possible.

Here is some simulated data similar to my actual data. Note that males & females and smokers & non-smokers are unevenly sampled.

set.seed(33)
mydata <- data.frame("gender"=rep(c("female", "male"),  times=c(40,10)),
                 "smoker"=rep(c("yes", "no"), each=50),
                 "measurement"=rnorm(n=50, mean=15, sd=3),
                 "outcome of interest"= rep(c("positive", "negative"), times=c(20,30)))
head(mydata)
#     gender smoker measurement outcome.of.interest
# 1   female    yes   12.309256            positive
# 2   female    yes   15.554548            positive
# 3   female    yes   19.763536            positive
# 4   female    yes   11.608873            positive
# 5   female    yes   14.759245            positive
# 6   female    yes    15.39726            positive

I found the randomizr package useful for randomizing according to 1 variable, but I get unbalanced distribution of the other:

set.seed(2)
library(randomizr)
Z <- block_ra(blocks = mydata[,"gender"], num_arms = 3)
table(Z, mydata$gender)
# Z    female male
#   T1     26    7
#   T2     27    6
#   T3     27    7
table(Z, mydata$smoker)
# Z    no yes
#   T1 17  16
#   T2 13  20
#   T3 20  14

Z <- block_ra(blocks = mydata[,"smoker"], num_arms = 3)
table(Z, mydata$smoker)
# Z    no yes
#   T1 17  17
#   T2 17  16
#   T3 16  17
table(Z, mydata$gender)
# Z    female male
#   T1     29    5
#   T2     24    9
#   T3     27    6

How can I block randomize according to 2 or more parameters?




Need a maven plugin to generate random string in pom.xml

Below is my requirement: Need a maven plugin to generate random string in pom.xml and I can use it for further process. Generating the random string must happen in each build time.

Or

run the below linux command in pom.xml using execute plugin and store the random string in a variable. Everything must be inside pom.xml

openssl rand hex -12



How to reproduce that array efficiently in python/numpy?

I have the following array that I want to reproduce using sp.random.seed(10):

[[ 0. 0.09174312 0.18348624 0.27522936 0.36697248 0.4587156 0.55045872 0.64220183 0.73394495 0.82568807 0.91743119 1.00917431 1.10091743 1.19266055 1.28440367 1.37614679 1.46788991 1.55963303 1.65137615 1.74311927 1.83486239 1.9266055 2.01834862 2.11009174 2.20183486 2.29357798 2.3853211 2.47706422 2.56880734 2.66055046 2.75229358 2.8440367 2.93577982 3.02752294 3.11926606 3.21100917 3.30275229 3.39449541 3.48623853 3.57798165 3.66972477 3.76146789 3.85321101 3.94495413 4.03669725 4.12844037 4.22018349 4.31192661 4.40366972 4.49541284 4.58715596 4.67889908 4.7706422 4.86238532 4.95412844 5.04587156 5.13761468 5.2293578 5.32110092 5.41284404 5.50458716 5.59633028 5.68807339 5.77981651 5.87155963 5.96330275 6.05504587 6.14678899 6.23853211 6.33027523 6.42201835 6.51376147 6.60550459 6.69724771 6.78899083 6.88073394 6.97247706 7.06422018 7.1559633 7.24770642 7.33944954 7.43119266 7.52293578 7.6146789 7.70642202 7.79816514 7.88990826 7.98165138 8.0733945 8.16513761 8.25688073 8.34862385 8.44036697 8.53211009 8.62385321 8.71559633 8.80733945 8.89908257 8.99082569 9.08256881 9.17431193 9.26605505 9.35779817 9.44954128 9.5412844 9.63302752 9.72477064 9.81651376 9.90825688 10. ]]

What is the best way to achieve that?




Save multiple shuffled csv files

is there a quick way to shuffle a list n times (in a different order) and save it as n single csv file? I already searched a lot, but couln't find anything about that. I have the following code, but I'm sure it could be shorter and with this I can't be sure that all shuffled lists have a different order. Has someone a solution?

import random

example = ['S01_a', 'S01_b', 'S02_a', 'S02_b', 'S03_a', 'S03_b', 'S04_a']

while True:
    example

    shuffle3 = []

    last = ""

    while example:
        i = example
        if last:
            i = [x for x in i if x[4] != last[4]]
        if not i:
            #no valid solution
            break 
        newEl = random.choice(i)
        last = newEl
        shuffle3.append(newEl)
        example.remove(newEl)
    if not example:
        break


fid = open("example.csv", encoding='latin1', mode="w")
fid.writelines(shuffle3)
fid.close()



Choose one array for each group of arrays in matlab?

I have N group of arrays. Each group is a group of 3 array ( for example). Now I would like to take only one array (random) from each of these groups and take a product with B array.

For example:

Group_1=[A_1 ,A_2, A_3];
...
Group_N=[A_m ,A_k, A_l];

Now I am choosing one array in each group and taking a product with B

C_1=A_2*B;  % Matlab has choosen random A_2 in group_1

...

C_N=A_k*B;  % Matlab has choosen random A_kin group_N

How to implement such computation?

I have tried A(randi(numel(A))); But it doesn't work




Very simple card drawing game (Eliminating duplicates + resetting arrays)

a programming beginner here! I was challenging myself to create a drawing game(card drawing or in this case number drawing) in order to sharpen my coding skills, but it seemed a little too challenging for me as I am just a beginner.

The program I'm making is actually very simple. You have a deck of 15 cards(or in this case numbers) and the program asks you to draw 5 cards. While I am able to do this, I noticed there would sometimes be duplicates of a card you already drew, and as for any normal deck there would only be 1 copy of each card.

As for my code it's fairly short:

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

namespace CardGame
{
    class Program
    {
        static void Main(string[] args)
        {
            string ans = " ";
            int[] Deck = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15 }; // the deck

            Console.WriteLine("Draw 5 cards? Y/N");


            while (!ans.Equals("N"))
            {

                ans = Console.ReadLine();

                if (ans.Equals("Y"))
                {
                    Draw(Deck);
                }

                else
                {
                    Console.WriteLine("Closing program");
                }
            }
        }

        static void Draw(int[] Deck) //Draw function
        {
            Random rand = new Random(); // randomizer
            int turncount = 1;

            while (turncount <= 5)
            {
                int pick = rand.Next(Deck.Count()); // random pick for each iteration
                Console.WriteLine(Deck[pick]);
                turncount++;
            }


        }


    }
}

So my expected output would be something like: 5,8,1,4,12 | 2,3,9,11,7 | 10,6,15,13,14

But what I did was spitting out something like: 1,5,5,3,7 | 15,12,1,15,3| 2,3,1,5,6

and I also an added challenge I wanted the deck to reset once you finish your 3 draws. So after 3 draws you can draw all of the cards again. But I have no idea on how i could do that at all.

As for the various methods that I tried, I tried implementing the Distinct function, so i could eliminate duplicates but, it was not really the result I was looking for as it would call my the elements in order like: 1,2,3,4,5,6,7,8,9,10,11,12,13,14,15.

That about sums up my question. Hope you all could help this beginner and enlighten me!




Generate/sample random probability mass function (PMF)

It feels it is very easy but I spent the last half an hour trying to find a solution.

What I need to do is to randomly generate/sample the vector (x,y,z) that is a probability mass function, i.e., 0 <= x,y,z <= 1 and x + y + z = 1. And such a vector should be uniformly distributed among all the vectors satisfying the conditions.




How to create a numpy array with a random entries that exclude one element in each index?

I have an array val of possible values (ex. val = [0, 1, 2, 3, 4, 5]) and an array A (possibly very long list) of selected values (ex. A = [2, 3, 1, 0, 2, 1, ... , 2, 3, 1, 0, 4])

Now I want to create an array B of the same length as A such that A[i] is different than B[i] for each i and entries in B are selected randomly. How to do it efficiently using numpy?




How to Generate 32 bit integers random number using marsenne twister Algorithm

How to Generate 32 bit integers random number using marsenne twister Algorithm? and save it to binary file.




Python: Random but equally distributed

I want to code a test unit in Django/Python and I need to create a table with one column filled with 'random' integer choosen (1,2,3,4) and equally distributed

this table contain 64 rows and I should have:

  • 16 rows filled with '1'
  • 16 rows filled with '2'
  • 16 rows filled with '3'
  • 16 rows filled with '4'

I try with randint but it is not equally distributed I read about uniform but it return a float

for i in (range(1,65)):
    r = uniform(1,4)



dimanche 24 novembre 2019

How to plot some terms of a lmer model

I am trying to plot only a few terms of random effects from a lmer object. I will borrow the dataset posted by oshun here.

Make up data:

tempEf <- data.frame(
  N = rep(c("Nlow", "Nhigh"), each=300),
  Myc = rep(c("AM", "ECM"), each=150, times=2),
  TRTYEAR = runif(600, 1, 15),
  site = rep(c("A","B","C","D","E"), each=10, times=12)   #5 sites
)

Make up some response data

tempEf$r <- 2*tempEf$TRTYEAR +                   
  -8*as.numeric(tempEf$Myc=="ECM") +
  4*as.numeric(tempEf$N=="Nlow") +
  0.1*tempEf$TRTYEAR * as.numeric(tempEf$N=="Nlow") +
  0.2*tempEf$TRTYEAR*as.numeric(tempEf$Myc=="ECM") +
  -11*as.numeric(tempEf$Myc=="ECM")*as.numeric(tempEf$N=="Nlow")+ 
  0.5*tempEf$TRTYEAR*as.numeric(tempEf$Myc=="ECM")*as.numeric(tempEf$N=="Nlow")+ 
  as.numeric(tempEf$site) +  #Random intercepts; intercepts will increase by 1
  tempEf$TRTYEAR/10*rnorm(600, mean=0, sd=2)    #Add some noise

library(lme4)
model <- lmer(r ~ Myc * N * TRTYEAR + (1|site), data=tempEf)

I can plot random effects by using type = "re" as follows:

plot_model(model, type = "re")

Here is the result:

enter image description here

I would like to show only A and E so I add the 'terms' argument as follows:

plot_model(model, type = "re", terms = c("A", "E"))

But this does not work. Any guidance on how I can show "A" and "B" only??




how can i make a random number/letter generator

So hello guys I am very bad at notepad, I want to make a random code generator. That Generates codes like this 3K2EU-ZGS5L-P3DNL-YM9JC I want it to work with a notepad .bat file so i can let it run on my pc




How to randomize different values in a loop? c++

I want to assign different -random- values (index) to populate a vector. Each time I run the program, it produces a different random value. But, it produces the same random value in each iteration of the loop for the same run.

this is my code :

  void hire (vector<PersonType> &salaryMan, vector<CompanyType> &company){

            double payment;
            string role;
            int i;
            int j;

            for (int x =0; x <5; x++){

                i =randomizeEmp(salaryMan);
                payment =salaryMan[i].getSalary();
                role =salaryMan[i].getTitle();      
                j =randomizeEmp(salaryMan);
                salaryMan[j].setTitle(role);
                salaryMan[j].setSalary(payment);
                company[x].employee.push_back(salaryMan[j]);
            }
        }

  int randomizeEmp(vector<PersonType> &v){
            double i;
            int minNumOfEmp =0;
            unsigned seed =time(NULL);
            srand(seed);
            i =minNumOfEmp +rand()% ((v.size()-1) - minNumOfEmp);
            cout <<i<<endl;
            return i;
        }

My output is the following: CompanyA Florida Miami 100 Linette Lefevers 529 PartnerG 600000
Linette Lefevers 529 PartnerG 600000
Linette Lefevers 529 PartnerG 600000
Linette Lefevers 529 PartnerG 600000
Linette Lefevers 529 PartnerG 600000
CompanyB NewYork NewYork 101 Linette Lefevers 529 PartnerG 600000
Linette Lefevers 529 PartnerG 600000
Linette Lefevers 529 PartnerG 600000
Linette Lefevers 529 PartnerG 600000
Linette Lefevers 529 PartnerG 600000
CompanyC California SanJose 102 Linette Lefevers 529 PartnerG 600000
Linette Lefevers 529 PartnerG 600000
Linette Lefevers 529 PartnerG 600000
Linette Lefevers 529 PartnerG 600000
Linette Lefevers 529 PartnerG 600000
CompanyD Texas Dallas 103 Linette Lefevers 529 PartnerG 600000
Linette Lefevers 529 PartnerG 600000
Linette Lefevers 529 PartnerG 600000
Linette Lefevers 529 PartnerG 600000
Linette Lefevers 529 PartnerG 600000
CompanyE Florida Talahasse 104 Linette Lefevers 529 PartnerG 600000
Linette Lefevers 529 PartnerG 600000
Linette Lefevers 529 PartnerG 600000
Linette Lefevers 529 PartnerG 600000
Linette Lefevers 529 PartnerG 600000




How do you generate a random decimal with decimals above 0 in Java?

I need to generate a random decimal from 0.85 to 1. I saw on other questions a lot of different methods, but all of them count on the beginning number to be 0. How do I do this?




Select random iamgine from list using pygame

So, I want to select a random image from a list. I imported all the images and made a list with all of the names(of the imported images). I am using random.choice to get a name from that list but when I run it, everything goes black. Here is the my the full code: https://pastebin.com/Eff7M573 I am posting to pastebin since i cant post the question on stack overflow because there will be too much code.

    list = [one,two,three,four,five,six,seven,eight,nine,ten]
    image = random.choice(list), (y,x))
    rect = image.get_rect()
    screen.blit(image, (y,x))```




Choose One Item from Every List, up to N combination, uniform distribution

I have 100 lists [x1..x100] , each one containing about 10 items. [x_i_1,...x_i_10] I need to generate 80 vectors. Each vector is a production of all the lists, kind of like itertools.product(*x), except 2 things:

(1) I need every item in each vector to have a uniform distribution. for example: [ np.random.choice(xi) for xi in [x1..x100]] would be good, except for my seconds condition:

(2) i can't have repetitions. itertools.product solves this, but it doesn't meet condition (1).

I need to generate 80 vectors, use them, and re-ask for another 80, and repeat this process until a certain condition is met. for EACH vector across all 80-size-batch, i need them to be uniform (condition 1) and non repeating (condition 2)

Creating all permutations and shuffling that list is a great solution for a smaller list, I'm using this batch system because of the HUGE number of possible permutations

Any ideas? thx




How can I generate a deterministic, seeded random number using the rand crate in Rust?

In a Rust project, I want to generate reproducible random numbers based on a integer seed as I'm used to in Java.

The documentation for Seed in the rand crate states:

Seed type, which is restricted to types mutably-dereferencable as u8 arrays (we recommend [u8; N] for some N).

Does this mean an integer seed is not possible? If it is possible, how can I use StdRng with an integral seed?




Generate an N-dimensional matrix using Numpy

For a certain assignment, I have to create a multivariate discrete probability mass function over N random variables. I want to do this by creating an array A filled with random numbers where each element denotes the joint probability over the random variables. In case of 2 random variables, having i and j possible values respectively, this can be done by creating an (i*j) Numpy array filled with random numbers where the total sum = 1.

It becomes more difficult however, when an additional random variable with k possible values is introduced. In this case, I need to have an i*j*k Numpy array, again filled with random numbers where the total sum equals 1.

Say I am given the structure (number of possible values for each random variable) as a list [n1,n2,...,nN], how can I from here create such an N dimensional Numpy array?




Generate unique lists of random integers within range

I am trying to write a function that will take two parameters, one that is the upper bound on the range that the random integer should be in. The other parameter is the number of lists of random numbers to be generated. Right now I am just trying to be able to generate lists of unique random numbers in a given range.

Using the following code, I can generate a random list of numbers, however, the numbers are of type randomList 5 (0,10) :: IO [Int] and not [Int]. The code also does not ensure that an integer is not repeated in a list.

import Test.QuickCheck

t :: Int -> (Int,Int) -> Gen [Int]
t n r = vectorOf n (choose r)

randomList n r = head `fmap` (sample' $ t n r)

I have looked at various StackOverflow answers although I still cannot find a solution. Many of the answers can only generate one random list with the same seed using System.Random




Poisson (npr) Size Alteration Returns ValueError (wrt arbitrary paths and array creation)

If I sample a non-central chi-square distribution using a Poisson distribution, I am unable to alter the size and can only input the mean, "nc / 2" (I must set size = 1 or it also returns the same error):

n = np.random.poisson(nc / 2, 1)  # generates a random variable from the poisson distribution with
# mean: non-centrality parameter / 2
x[t] = c * mp.nsum(lambda i: np.random.standard_normal() ** 2, [0, v + 2 * n])

If I attempt to increase the size to the number of simulations being run

n = np.random.poisson(nc / 2, simulations)

where simulations = 10000, I receive:

"ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()"

Running the code with 1 simulation produces one desired result, and every run produces another random path.

Graph created under 10,000 simulations with size = one

However, it is a necessity to have the graph composed of paths determined by each iteration of the simulation. Under a different condition, the non-central chi-square distribution is determined by the code:

x[t] = c * ((np.random.standard_normal(simulations) + nc ** 0.5) ** 2 + mp.nsum(
                lambda i: np.random.standard_normal(simulations) ** 2, [0, v - 1]))

which does produce the desired result

Graph produced by the line of code above

How can I obtain a different path for x[t] despite not being able to change the size of the Poisson distribution (i.e. not have the same path for each of the 10,000 simulations)

If required:

import numpy as np
import matplotlib.pyplot as plt
from scipy.stats import stats
import mpmath as mp

T = 1
beta = 1.5
x0 = 0.05
q = 0
mu = x0 - q
alpha = - (2 - beta) * mu
sigma0 = 0.1
sigma = (2 - beta) * sigma0
b = - (1 - beta) / (2 * mu) * sigma ** 2
simulations = 10000
M = 50
dt = T / M


def srd_sampled_nxc2():
    x = np.zeros((M + 1, simulations))
    x[0] = x0
    for t in range(1, M + 1):
        v = 4 * b * alpha / sigma ** 2
        c = (sigma ** 2 * (1 - np.exp(-alpha * dt))) / (4 * alpha)
        nc = np.exp(-alpha * dt) / c * x[t - 1]  # The non-centrality parameter lambda
        if v > 1:
            x[t] = c * ((np.random.standard_normal(simulations) + nc ** 0.5) ** 2 + mp.nsum(
                lambda i: np.random.standard_normal(simulations) ** 2, [0, v - 1]))
        else:
            n = np.random.poisson(nc / 2, 1)
            x[t] = c * mp.nsum(lambda i: np.random.standard_normal() ** 2, [0, v + 2 * n])
    return x


x1 = srd_sampled_nxc2()


plt.figure(figsize=(10, 6))
plt.plot(x1[:, :10], lw=1)
plt.xlabel('time')
plt.ylabel('index')
plt.show()



samedi 23 novembre 2019

generating correct answers in mc questions

Can i please have suggestion on how to generate correct answers for each mc questions? i cannot figure out the correct code for giving the correct answers.

Also i want to ask how to randomly assign answers to each choices and keeping one of them as the correct answers.

MC example:

Which of the following words has similar meaning to apple?
A.orange
B.pen
C.rose
D.dance

Thanks in advance.

var ques=['apple', 'pencil' ,'juice','flower','sing','beautiful'];
var ans= ['orange', 'pen','water','rose','dance','pretty'];
var QuesResp = ques.map(function(val, index){
  return [val, ans[index]]
});

var QRpointers = [];

function randOrd() { return (Math.round(Math.random())-0.5); } 

window.onload = function() 
{
  for (var i=0; i<QuesResp.length; i++) { QRpointers.push(i); }
  QRpointers.sort(randOrd);                                    

  var bdy = '<h1>MC questions</h1>';
      Q=0;
  for (var Q=0; Q<1; Q++) 
  {
    bdy += '<div class="qno">Question #'+(Q+1)+'</div> ';
    bdy += '<br/><div class="qu" id="R'+Q+'" > Which of the following words has similar meaning to '+QuesResp[QRpointers[Q]][0]+'?</div><br/>';
    bdy += ' <button class="ansbtn" id="choiceA"   onclick="scoreme()"></button>';
    bdy += ' <button class="ansbtn" id="choiceB"   onclick="scoreme()"></button>';
    bdy += ' <button class="ansbtn" id="choiceC"   onclick="scoreme()"></button>';
    bdy += ' <button class="ansbtn" id="choiceD"   onclick="scoreme()"></button><br/>';
  }
    
    bdy += '<INPUT value="next" type="button" onclick="window.onload()">';
    bdy += '<button onclick="scoreme()">Check All</button>';
    bdy += '<INPUT id="score" type="text" size="8">';
    document.getElementById('QuestionsResponses').innerHTML = bdy;
   
   var anst=Math.floor(Math.random() *ans.length);
   document.getElementById('choiceA').innerHTML= ans[anst];
}
<div id="QuestionsResponses"></div>



Adding randomly generated circles (of uniform size) in a scene to represent stars in JavaFX

Since I had such great success getting help with my hi-lo guessing game and figuring out the issues I had. I thought I would post here again to see if I could get some help on figuring out how to get the random generator to work. I am trying to add circles (dots) in the scene I have created with spaceships. They should be randomly placed on the scene but be of a uniform size. I created the random generator but every time I run the code, no stars appear. I'm not sure what I've done wrong here. I'm very new to programming and this is only my second post here on this forum. Any help in troubleshooting would be appreciated.

I only need help in figuring out the last bit of code for the random generator - everything else is working as expected - I figured including all of the code might be helpful to see if there is better placement of the random generator within the code.

public class Spaceship extends Group
{

/*
 Create the elements of the spaceship with its position in one class .
*/

    public Spaceship()
    {
        Ellipse spaceshipbottom = new Ellipse(33.0, 67.0, 59.0, 50.0);
        spaceshipbottom.setStroke(Color.GREY);
        spaceshipbottom.setStrokeWidth(1);
        spaceshipbottom.setFill (Color.YELLOW);

        Ellipse spaceshipbody = new Ellipse(31.0, 72.0, 100.0, 31.0);
        spaceshipbody.setStroke(Color.AQUA);
        spaceshipbody.setStrokeWidth(3);
        spaceshipbody.setFill (Color.DODGERBLUE);

        Ellipse spaceshiptop = new Ellipse(31.0, 44.0, 72.0, 31.0);
        spaceshiptop.setStroke(Color.BLACK);
        spaceshiptop.setStrokeWidth(2);
        spaceshiptop.setFill (Color.DODGERBLUE);

        Ellipse spaceshipcommand = new Ellipse(32.0, 15.0, 54.0, 42.0);
        spaceshipcommand.setStroke(Color.AQUA);
        spaceshipcommand.setStrokeWidth(2);
        spaceshipcommand.setFill (Color.SLATEGRAY);

        Ellipse spaceshipwindow1 = new Ellipse(40.0, 88.0, 10.0, 8.0);
        spaceshipwindow1.setStroke(Color.BLACK);
        spaceshipwindow1.setStrokeWidth(2);
        spaceshipwindow1.setFill (Color.YELLOW);

        Ellipse spaceshipwindow2 = new Ellipse(3.0, 85.0, 10.0, 8.0);
        spaceshipwindow2.setStroke(Color.BLACK);
        spaceshipwindow2.setStrokeWidth(2);
        spaceshipwindow2.setFill (Color.YELLOW);

        Ellipse spaceshipwindow3 = new Ellipse(75.0, 83.0, 10.0, 8.0);
        spaceshipwindow3.setStroke(Color.BLACK);
        spaceshipwindow3.setStrokeWidth(2);
        spaceshipwindow3.setFill (Color.YELLOW);

        Ellipse spaceshipwindow4 = new Ellipse(108.0, 77.0, 10.0, 8.0);
        spaceshipwindow4.setStroke(Color.BLACK);
        spaceshipwindow4.setStrokeWidth(2);
        spaceshipwindow4.setFill (Color.YELLOW);

        Ellipse spaceshipwindow5 = new Ellipse(-40.0, 77.0, 10.0, 8.0);
        spaceshipwindow5.setStroke(Color.BLACK);
        spaceshipwindow5.setStrokeWidth(2);
        spaceshipwindow5.setFill (Color.YELLOW);

        getChildren().addAll(spaceshipbottom,spaceshipbody,spaceshiptop,
                spaceshipcommand,spaceshipwindow1,spaceshipwindow2,
                spaceshipwindow3,spaceshipwindow4,spaceshipwindow5);
    }
}
    @Override
    public void start(Stage primaryStage) {

 /* Make four versions of the spaceship in different sizes and
    positions on the sene.   
        */

       Spaceship spaceship1 = new Spaceship();
       spaceship1.setTranslateX(100);
       spaceship1.setTranslateY(125);

       Spaceship spaceship2 = new Spaceship();
       spaceship2.setTranslateX(350);
       spaceship2.setTranslateY(350);
       spaceship2.setScaleX(1.75);
       spaceship2.setScaleY(1.75);

       Spaceship spaceship3 = new Spaceship();
       spaceship3.setTranslateX(640);
       spaceship3.setTranslateY(150);
       spaceship3.setScaleX(.75);
       spaceship3.setScaleY(.75);

       Spaceship spaceship4 = new Spaceship();
       spaceship4.setTranslateX(370);
       spaceship4.setTranslateY(70);
       spaceship4.setScaleX(.60);
       spaceship4.setScaleY(.60);

// Create background of stars
    Random rand = new Random();
    Group root = new Group();
    StackPane stack = new StackPane();
    Group stars = new Group();
    for (int i = 0; i < 100; i++) {
        int centerx = rand.nextInt();
        int centery = rand.nextInt();
        int radius = rand.nextInt(20);

        Circle circle = new Circle(centerx, centery, radius);
        circle.setStrokeType(StrokeType.OUTSIDE);
        circle.setFill(Color.WHITE);
        circle.setStroke(Color.WHITE);
        circle.setStrokeWidth(1);

    }


       root.getChildren().addAll(spaceship1,spaceship2,spaceship3,spaceship4,stars);


        Scene scene = new Scene(root, 800, 600,Color.BLACK);

        primaryStage.setTitle("Spaceships in Outerspace!");
        primaryStage.setScene(scene);
        primaryStage.show();
    }

    public static void main(String[] args) {
        launch(args);

    }
}



how to randomize double/float data type? c++

I want to randomize a value between 0.03- and 0.05. I understand there is infinite values between the two numbers and that rand takes unsigned int data type. I'm wondering how to make a function to randomize double/float data type and set the limits only to two decimals

my code is the following:

double i=0.0;
double minP = 0.03;
double maxP = 0.05;
unsigned seed =time(0);
srand(seed);r
i = rand()% (maxP -minP +0.01) +minP;



Array Random Values without repeating array in loop

How can I loop through all the entries in an array using JavaScript? I have an array and i want an another array of randoms list in arrRand variable and then execute my further code .

 list1 = ['aceClub', 'twoClub'];
 list2 = ['fourDiamond', 'aceClub', 'fourHeart', 'twoDiamond'];
 list3 = ['aceHeart', 'aceClub', 'aceHeart', 'aceDiamond'];
 list4 = ['aceDiamond', 'fourSpade', 'twoClub', 'fourHeart'];
 list5 = ['fourClub', 'twoSpade' , 'twoHeart', 'aceDiamond'];
 list6 = ['twoHeart', 'twoDiamond' , 'twoSpade' , 'aceClub'];

 var arr = [list1,list2,list3,list4, list5,list6];

i want this in array of randoms .

var arrRand = [list5,list6,list2,list4, list3,list1];
var arrRand = [list3,list2,list6,list5, list1,list4];
var arrRand = [list1,list5,list2,list4, list6,list2];

and then

if(arrRand[0] == list1){
   //mycode 
}
if(arrRand[1] == list2){
  //myCode
}
....



Concurrency & random function [pseudo code]

At uni we are studying concurrency using a very simple program which controls several robots within an area. They simulate processes/ threads. The whole thing comes bundled in a sort of mockup IDE which has a graphical console, all of this is programmed in Java, but we program in a sort of pseudocode.

(please excuse lack of knowledge about concurrency, we literally have three weeks to learn concepts and are graded in the fourth week).

We are asked to program robot types for different tasks. We may have several instances of the same type of robot running at once in order to have them doing the same thing in different places.

The robots must perform their tasks without bumping into other robots. They achieve this by:

  • sending and receiving messages. The message sending is asynchronous and the receiving is synchronous (this blocks the robot which is receiving until the message arrives).
  • blocking the part of the area which they need (the area is a 100 x 100 matrix with x,y coordinates). We can block a particular "corner" if we need to do something there, but must then unblock it after leaving so as to not lower concurrency.
  • sectoring off parts of the whole area into smaller private ones (for one robot) or semi private areas (for a few robots). Areas can be private, partly shared or completely shared, with the idea of simulating the memory in concurrency.

The tasks the robots perform are to drop or pick up objects from a corner. They can also move in a straight line and turn the corner.


We were asked to make a program to resolve the following issue.

Three collector robots positioned in their own respective corners(3,3),(4,4),(5,5) need to collect from the same corner, let's say (10,10).

One boss robot, in (1,1), uses a random function to pick which of the three robots will go to the shared corner to collect the goods.

The program needs to consider that: - the robots must all know when there may be nothing to collect from the start or when there is no longer anything to collect. It is inevitable that a lot of message sending will need to happen, but we do need to consider that the less messages we send the better because they lower concurrency. Similarily with corner blocking.

Once all of the goods have been collected the boss will inform which of the three collector robots has collected the most.

First of all the collector robots are all of the same type. So they have the same programming. One of them may go to the corner first, find nothing, communicate to the boss robot that there is nothing and that then the rest of the collector robots must stop when the boss informs them that there is nothing to collect.

Then, the same applies for once they are collecting. At some point, they will all collect, one of them will collect the last thing, and needs to communicate that to the rest, probably communicating it to the boss who will communicate that to the rest. They must all stop.

Finally, the boss must inform which one of the robots got the most elements. A maximum function.

This has so far worked allright if not efficiently and I am not sure if completely correctly.

I am including the pseudocode, In order to get some feedback. I know it can be done better, but qhenever I change anything to try and refactor the code, it just breaks and something stops working.

I really can't see the forest for the trees right now and the exams are coming up next week. Any insight is welcomed.

program threeCollectors
  functions
  function max (ES max: integer; ES maxrobot: integer; 
  E aux: integer; E id: integer)
  begin
    if (max < aux) 
      max:= aux 
      maxrobot:=id 
  end
  function sendID
  begin
    SendMsg(1, robot1)
    SendMsg(2, robot2) 
    SendMsg(3, robot3) 
  end 
  function collect (E myPosX: integer; E myPosY: integer; 
  ES boxes: integer; ES plants:integer; ES goOn: integer; ES ok: boolean)
  begin
    BlockCorner(10,10)  
    Pos(10,10)  
    if ~(ThereIsBox) & ~(ThereIsPlant)
      ok:= F
      goOn:=0
      Pos(myPosY,myPosX)
      FreeCorner(10,10)
      SendMsg(goOn, robot0)
      Print('dontGoOn',goOn)
    else
      ok:= V
      goOn:=1
      if(ThereIsBox) & (ThereIsPlant) 
        getBox 
        boxes:=boxes+1 
        getPlant  
        plants:=plants+1 
      else
        if (ThereIsBox) 
          getBox 
          boxes:=boxes+1 
        else 
          if (ThereIsPlant) 
            getPlant 
            plants:=plants+1 
      SendMsg(goOn, robot0) 
      Pos(myPosY,myPosX)
      FreeCorner(10,10)
      ReceiveMsg(goOn, robot0) 
  end
areas
  areaJ : AreaP(1,1,1,1)
  area: AreaPC(3,3,10,10)
robots 
  robot boss 
  variables
    t:integer
    id: integer
    max:integer
    maxrobot: integer
    goOn: integer
    total: integer
  begin
    max:= -1
    total:= 0
    goOn:= 1
    sendID
    while (goOn = 1)
      Random(id, 1, 3) 
      Print('envio',id)
      if(id = 3)
        SendMsg(goOn, robot3)
        ReceiveMsg(goOn, robot3)
      else
        if (id = 1)
          SendMsg(goOn, robot1)
          ReceiveMsg(goOn, robot1)
        else 
          if(id = 2)
            SendMsg(goOn, robot2)
            ReceiveMsg(goOn, robot2)
      if (goOn =0)
        SendMsg(goOn, robot1)
        SendMsg(goOn, robot2)
        SendMsg(goOn, robot3) 
    for 3
      ReceiveMsg(id, *)
      if (id = 1)
        ReceiveMsg(t, robot1)
      else
        if (id = 2)
          ReceiveMsg(t, robot2)
        else 
          if (id = 3)
            ReceiveMsg (t, robot3)
      max(max, maxrobot, t, id) 
    Print('gano',maxrobot) 
    Print('collected',t)  
  end
  robot collector
  variables
    boxes: integer
    plants: integer
    myPosY:integer
    myPosX:integer 
    whoami: integer
    goOn: integer
    total: integer
    ok: boolean
  begin
    total:=0
    boxes:= 0
    plants:= 0
    ok:=V
    myPosY:=PosY 
    myPosX:=PosX
    ReceiveMsg(whoami, robot0)
    ReceiveMsg(goOn, robot0)
    while (goOn = 1) & (ok = V)
      collect (myPosX,myPosY, boxes,plants,goOn,ok)
    total:= plants + boxes
    SendMsg(whoami, robot0)
    SendMsg(total, robot0)  
  end 
variables 
  robot0: boss
  robot1,robot2,robot3: collector 
begin 
  AsignArea(robot0, areaJ)
  AsignArea(robot1,area)
  AsignArea(robot2,area)
  AsignArea(robot3,area)
  Init(robot0, 1,1)
  Init(robot1, 3, 3)
  Init(robot2, 4, 4)
  Init(robot3, 5, 5) 



CUDA Ray-Sphere intersection random walk spooky values

Results

The above results are the |X|Y|Z|AbsDistance of each sphere intersection, random spooky values appear probably because of a newbie mistake, but I really can't get it.

To be as specific as I can:

The following snippet is supposed to calculate the intersection point between a ray and a spherical boundary with a predefined radius and the origin as the center.

To give more context:

1- The RandomWalk starts from the origin and moves with a randomly generated _step and _direction.

2- After each step, the ray is checked for hitting possibility by comparing the absolute distance to the radius of the boundary.

3- getIntersectionPoint() returns the point of intersection, but as the number of points or number of steps increases, the probability of outcasts increases, messing up the whole thing.

Here's what I've done:

main.cu

__global__ void finalPosition(unsigned int seed, curandState_t* states, Point* _gpuPoints,Boundary boundary,RNG rng) {
    int idx = blockIdx.x*blockDim.x+threadIdx.x;
    curand_init(seed, idx, 0, &states[idx]);
    Point finalPos;
    finalPos = randomWalk(states, idx, boundary, rng);
    _gpuPoints[idx] = finalPos;
.
.
.
int main(){
    int nBlocks = N/THREADS_PER_BLOCK + 1;

    curandState_t* states;
    cudaMalloc((void**) &states, N * sizeof(curandState_t));

// Allocate host memory for final positions
    Point * _cpuPoints= (Point*)malloc(sizeof(Point) * N);

// Allocate device  memory for final positions
    Point* _gpuPoints = nullptr;
    cudaMalloc((void**) &_gpuPoints, N * sizeof(Point));

// Initializing the Boundary and the Random Number Generator
    Boundary boundary = Boundary(BOUNDARY_RADIUS, Point(0.f, 0.f, 0.f));
    RNG rng;

// Call Kernel
    finalPosition<<<nBlocks,THREADS_PER_BLOCK>>>(time(0), states , _gpuPoints, boundary, rng);

// Copy device data to host memory to stream them out
    cudaMemcpy(_cpuPoints, _gpuPoints, N* sizeof( Point), cudaMemcpyDeviceToHost);


    streamOut (&_cpuPoints[0]);

    free(_cpuPoints);
    cudaFree(_gpuPoints);


    return 0;
}
}

RandomWalk.h

/**
 * @brief randomWalk
 * keeps wandering around with the photon in the 3D space
 * @return The Point where the Photon hits the Boundary
 */
__device__ Point randomWalk(curandState_t *states, int idx, Boundary boundary, RNG rng)
{
    Ray ray = Ray(Point(0.f, 0.f, 0.f), Point(0.f, 0.f, 0.f));

    while (!boundary.isCrossed(ray))
    {
        ray.move(rng.getRandomPoint(states, idx), rng.getRandomStep(states, idx));
    }
    return boundary.getIntersectionPoint(ray);
}

Boundary.cu

__device__ bool Boundary::isCrossed(Ray ray){
    float absDistance = (float) sqrtf((float) powf(ray.getCurrentPos().getX(),2)
                        + (float) powf(ray.getCurrentPos().getY(),2) 
                        + (float) powf(ray.getCurrentPos().getZ(),2));
    if(absDistance >= _radius){
        return true;
    } else {
        return false;
    }
}


__device__ Point Boundary::getIntersectionPoint(Ray ray){
        /**
            P(t) = A + tB
            P(t) is a point on the ray 
            A is the ray origin
            B is the ray direction
            t is a parameter used to move away from ray origin
            S = P - Center
            ||S||^2 = r^2
            Sphere: dot(S,S) = r^2
            Ray: P(t) = A + tB
            Combined: dot((A + tB - Center),(A + tB - Center)) = r^2
            in Quadratic form: t^2.dot(B,B) + 2t.dot(B, A - C) + dot(A - C, A - C) - r^2 = 0
            let a = dot(B,B)
                b = 2.dot(B, A - C)
                c = dot(A - C, A - C) - r^2
            t1, t2 = (-b (+/-) sqrt(b^2 - 4ac) / 2a)
        */
        Point A = ray.getPrevPos();
        Point B = ray.getDirection();
        Point S = A.add(_center);
        Point A_C = A.subtract(_center);
        float a = dot(B, B);
        float b = 2.0 * dot(B, A_C);
        float c = dot(A_C, A_C) - _radius*_radius;
        float discriminant = b*b - 4*a*c;
        float t1 = (-b + sqrtf(discriminant)) / (2.0*a);
        float t2 = (-b - sqrtf(discriminant)) / (2.0*a);
        float t;

        if(t1 < 0){
            t = t2;
        } else {
            t = t1;
        }

        return Point((A.getX()+B.getX()*t),(A.getY()+B.getY()*t),(A.getZ()+B.getZ()*t));
}

RNG.cu

__device__  float RNG::generate( curandState* globalState, int i) 
{
    curandState localState = globalState[i];
    float random = curand_uniform( &localState );
    globalState[i] = localState;
    return random;
}

__device__   float RNG::getRandomStep( curandState* globalState , int i) { 
    float step = 0.f;       // Intialize for step value
    step = generate (globalState, i);
    return step;
 } 

__device__  Point RNG::getRandomPoint( curandState* globalState , int i)
{

    float u = generate (globalState , i);
    float v = generate (globalState, i);

    float theta = 2 * M_PI * u;
    float phi = acos(1 - 2 * v);

    // Transforming into the cartesian space
    float x = sin(phi) * cos(theta);
    float y = sin(phi) * sin(theta);
    float z = cos(phi);

    return Point(x,y,z);
}