vendredi 31 août 2018

How to create random value between two different sets of numbers

I am trying to generate a random character between the following two sets of unicode U+0020 to U+007E and U+00A0 to U+00FF. I have created the code to generate a value between U+00A0 to U+00FF but I also need my generator to include the values from U+00A0 to U+00FF, how is this possible? Any help is greatly appreciated, here is what I have so far. (P.S. I am using seed for testing). For example instead of just trying to create a integer between 1-10, I would like to know how to create a random number that could either be between 1-10 or 50-100.

  private static char random(){
        long seed = 1776;
        Random number = new Random(seed);
        int randomNumber = number.nextInt(126) + 32;
        char a = (char) randomNumber;
        return a;
    }




Picking random array element

I'm trying to grab a random value from this array. When I run the program it just prints 0 for x. Why isn't it printing the updated value that is returned from the function?

import java.util.*;
public class randomArray
{
    public static void main(String[] args)
    {
        int[] myArray = new int[]{1,2,3};
        int x = 0;
        getRandom(myArray, x);
        System.out.println(x);
    }
    public static int getRandom(int[] array, int h) 
    {
        int rnd = new Random().nextInt(array.length);
        return h;   
    }
}




Multiple random numbers in assembly x86 [DOS-TASM]

So I need a random number generator for my school project but I couldn't find one that gets multiple numbers, just a single one each time

this is the best one I found so far but unfortunately this is not quite what I need:

   MOV AH, 00h       
   INT 1AH     
   mov  ax, dx
   xor  dx, dx
   mov  cx, 10    
   div  cx
   add  dl, '0'
   mov ah, 2h
   int 21h

I understood it is something with "pseudo-random" but I didn't fully understand

Any ideas?




Loading images with javascript

By clicking on the button , the random two pictures should appear of 12 included in two boxes.But something goes wrong.Need advice to solve this this problem.

var startBtn = document.getElementById("start-button");
var imgBox1 = document.getElementById("firstBox");
var imgBox2 = document.getElementById("secondBox");


var images = [
    '/assets/img/pic1.png',
    '/assets/img/pic2.png',
    '/assets/img/pic3.png',
    '/assets/img/pic4.png',
    '/assets/img/pic5.png',
    '/assets/img/pic6.png',
    '/assets/img/pic7.png',
    '/assets/img/pic8.png',
    '/assets/img/pic9.png',
    '/assets/img/pic10.png',
    '/assets/img/pic11.png',
    '/assets/img/pic12.png',
    
];

function loadImages(imgArr){
    for(var i=0; i< imgArr.length; i++) {
        console.log(imgArr[i]);
        var img = new Image();
            img.src = imgArr[i];
        document.getElementById('output').appendChild(img);
       
    }
 
}
    


startBtn.onclick = function(){
    
imgBox1.style.backgroundImage = images[Math.floor(Math.random()*images.length)];
imgBox2.style.backgroundImage = images[Math.floor(Math.random()*images.length)];
}



Random generated images inside a table disappear

Problem

I tried to randomly generate the position of two images in a table, but sometimes they wouldn't show. One of them or both would just disappear. Try to loading more times (from 1 to 5) the pen to let the bug occur.

Pen

Here is all the code: penHere

Interested functions

How the table\map is building? it's a 2d array random generated, something like this:

map = [[1,1,1,1,0],
       [1,0,0,0,0],
       [1,0,1,1,1],
       [1,0,0,0,1],
       [1,1,1,0,1]]

After I build the map in the table with this one:

function mapGenerate(map){

        //loop the 2d array map and change the number with the appropriate img    
        for(var i = 0; i < map.length; i++) {
            var innerArrayLength = map[i].length;
            for(var j = 0; j<innerArrayLength; j++){
                if(map[i][j] === 0){
                    map[i][j]="<div class=\"tile\"><img class=\"walkable\" src=\"https://image.ibb.co/bGanFz/floor_Resized.png\"></div>";
                }else{
                    map[i][j]="<img class=\"nonWalkable\" src=\"https://image.ibb.co/m9s1az/volcanoresize.png\">";
                }    
                ;
            }
            $("#tableGame").append("<tr><td>"+ map[i].join('</td><td>') + "</td></tr>")    
        }
}

with the function below i select the coordinate ( they are corrects, i check it several times in the console)

function placeCharAndItem(char){


    let rowCoord= mapA.length;
    let cellCoord = mapA[1].length;
    //this object is to save 2 random number, the row and the cell 
    let coord={
        row: Math.floor(Math.random() * rowCoord),
        cell: Math.floor(Math.random() * cellCoord)
        };  
    //I need this 2 variables to check if the tiles is a correct one
    let toCheck = mapA[coord.row][coord.cell];     
    let check= toCheck.search('nonWalkable');

    //if it's not correct(you found the sub-string "non- 
    //walkable"), this while loop have to generate random new 
    //coordinates.

    while(check != -1){
        coord.row=Math.floor(Math.random() * rowCoord);
        coord.cell=Math.floor(Math.random() * cellCoord);
        toCheck = mapA[coord.row][coord.cell];     
        check= toCheck.search('nonWalkable');
    };   
        place(coord, char);
};

and finally, after i have 2 valid coordinates i can show the character:

function place(coord, char){
  console.log('sei entrato nella funzione place');
  var charImage = $("<img>").attr("src", char.image).addClass('char');
  var row = $($("#tableGame tr")[coord.row]);
  var cell = $($("td", row)[coord.cell]);
  var tile = $($(".tile", row)[coord.cell]);
  tile.prepend(charImage);
};

these are the css regarding the table and the image char:

#tableGame .td{
  position: relative;
}

.char{
    z-index: 1000;
}

#tableGame .char {
  position: absolute;
}

table{
    background-color: black;
    border-collapse: collapse;
    border: 2px solid white;
    box-shadow: 1px 1px 30px white;
}


tr{
    border: 0px;
    padding: 0px;
    margin:0px;
}

td{
    border: 0px;
    padding: 0px;
    margin:0px;
}

I don't understand why sometimes one or both of the images, disappear, any kind of help will be really appreciated.




Why is wrapping coordinates not making my simplex noise tile seamlessly?

I've been trying to create a fake 3D texture that repeats in shadertoy (see here, use wasd to move, arrow keys to rotate) But as you can see, it doesn't tile.

I generate the noise myself, and I've isolated the noise generation in this minimal example, however it does not generate seamlessly tileable noise seemingly no matter what I do.

Here is the code:

//Common, you probably won't have to look here. 
vec2 modv(vec2 value, float modvalue){
    return vec2(mod(value.x, modvalue), 
                mod(value.y, modvalue));
}
vec3 modv(vec3 value, float modvalue){
    return vec3(mod(value.x, modvalue), 
                mod(value.y, modvalue),
                mod(value.z, modvalue));
}
vec4 modv(vec4 value, float modvalue){
    return vec4(mod(value.x, modvalue), 
                mod(value.y, modvalue),
                mod(value.z, modvalue),
                mod(value.w, modvalue));
}

//MATH CONSTANTS
const float pi  = 3.1415926535897932384626433832795;
const float tau = 6.2831853071795864769252867665590;
const float eta = 1.5707963267948966192313216916397;
const float SQRT3 = 1.7320508075688772935274463415059;
const float SQRT2 = 1.4142135623730950488016887242096;
const float LTE1 =  0.9999999999999999999999999999999;
const float inf = uintBitsToFloat(0x7F800000u);

#define saturate(x) clamp(x,0.0,1.0)
#define norm01(x) ((x + 1.0) / 2.0)

vec2 pos3DTo2D(in vec3 pos, 
               const in int size_dim, 
               const in ivec2 z_size){
    float size_dimf = float(size_dim);
    pos = vec3(mod(pos.x, size_dimf), mod(pos.y, size_dimf),  mod(pos.z, size_dimf));
    int z_dim_x = int(pos.z) % z_size.x;
    int z_dim_y = int(pos.z) / z_size.x;
    float x = pos.x + float(z_dim_x * size_dim);
    float y = pos.y + float(z_dim_y * size_dim);
    return vec2(x,y);
}

vec4 textureAs3D(const in sampler2D iChannel, 
                 in vec3 pos, 
                 const in int size_dim, 
                 const in ivec2 z_size,
                 const in vec3 iResolution){
    //only need whole, will do another texture read to make sure interpolated?

    vec2 tex_pos = pos3DTo2D(pos, size_dim, z_size)/iResolution.xy;
    vec4 base_vec4 = texture(iChannel, tex_pos);

    vec2 tex_pos_z1 = pos3DTo2D(pos+vec3(0.0,0.0,1.0), size_dim, z_size.xy)/iResolution.xy;
    vec4 base_vec4_z1 = texture(iChannel, tex_pos_z1);
    //return base_vec4;
    return mix(base_vec4, base_vec4_z1, fract(pos.z));
}

vec4 textureZ3D(const in sampler2D iChannel, 
                 in int y,
                 in int z,
                 in int offsetX,
                 const in int size_dim, 
                 const in ivec2 z_size,
                const in vec3 iResolution){
    int tx = (z%z_size.x);
    int ty = z/z_size.x;
    int sx = offsetX + size_dim * tx;
    int sy = y  + (ty *size_dim);
    if(ty < z_size.y){
        return texelFetch(iChannel, ivec2(sx, sy),0);
    }else{
        return vec4(0.0);
    }
    //return texelFetch(iChannel, ivec2(x, y - (ty *32)),0);
}

//Buffer B this is what you are going to have to look at. 
//noise

//NOISE CONSTANTS
// captured from https://en.wikipedia.org/wiki/SHA-2#Pseudocode
const uint CONST_A = 0xcc9e2d51u;
const uint CONST_B = 0x1b873593u;
const uint CONST_C = 0x85ebca6bu;
const uint CONST_D = 0xc2b2ae35u;
const uint CONST_E = 0xe6546b64u;
const uint CONST_F = 0x510e527fu;
const uint CONST_G = 0x923f82a4u;
const uint CONST_H = 0x14292967u;

const uint CONST_0 = 4294967291u;
const uint CONST_1 = 604807628u;
const uint CONST_2 = 2146583651u;
const uint CONST_3 = 1072842857u;
const uint CONST_4 = 1396182291u;
const uint CONST_5 = 2227730452u;
const uint CONST_6 = 3329325298u;
const uint CONST_7 = 3624381080u;




uvec3 singleHash(uvec3 uval){
    uval ^= uval >> 16;
    uval.x *= CONST_A;
    uval.y *= CONST_B;
    uval.z *= CONST_C;
    return uval;
}

uint combineHash(uint seed, uvec3 uval){
    // can move this out to compile time if need be. 
    // with out multiplying by one of the randomizing constants
    // will result in not very different results from seed to seed. 
    uint un = seed * CONST_5;
    un ^= (uval.x^uval.y)* CONST_0;
    un ^= (un >> 16);
    un = (un^uval.z)*CONST_1;
    un ^= (un >> 16);
    return un;
}

/* 
//what the above hashes are based upon, seperate 
//out this mumurhash based coherent noise hash
uint fullHash(uint seed, uvec3 uval){
    uval ^= uval >> 16;
    uval.x *= CONST_A;
    uval.y *= CONST_B;
    uval.z *= CONST_D;
    uint un = seed * CONST_6;
    un ^= (uval.x ^ uval.y) * CONST_0;
    un ^= un >> 16;
    un = (un^uval.z) * CONST_2;
    un ^= un >> 16;
    return un;
}
*/

const vec3 gradArray3d[8] = vec3[8](
    vec3(1, 1, 1), vec3(1,-1, 1), vec3(-1, 1, 1), vec3(-1,-1, 1),
    vec3(1, 1,-1), vec3(1,-1,-1), vec3(-1, 1,-1), vec3(-1,-1,-1)
);


vec3 getGradient3Old(uint uval){
    vec3 grad = gradArray3d[uval & 7u];
    return grad;
}

//source of some constants
//https://github.com/Auburns/FastNoise/blob/master/FastNoise.cpp
const float SKEW3D = 1.0 / 3.0;
const float UNSKEW3D = 1.0 / 6.0;
const float FAR_CORNER_UNSKEW3D = -1.0 + 3.0*UNSKEW3D;
const float NORMALIZE_SCALE3D = 30.0;// * SQRT3;
const float DISTCONST_3D = 0.6;

float simplexNoiseV(uint seed, in vec3 pos, in uint wrap){
    pos = modv(pos, float(wrap));
    float skew_factor = (pos.x + pos.y + pos.z)*SKEW3D;
    vec3 fsimplex_corner0 = floor(pos + skew_factor);
    ivec3 simplex_corner0 = ivec3(fsimplex_corner0);

    float unskew_factor = (fsimplex_corner0.x + fsimplex_corner0.y + fsimplex_corner0.z) * UNSKEW3D;
    vec3 pos0 = fsimplex_corner0 - unskew_factor;

    //subpos's are positions with in grid cell. 
    vec3 subpos0 = pos - pos0;
    //precomputed values used in determining hash, reduces redundant hash computation
    //shows 10% -> 20% speed boost. 
    uvec3 wrapped_corner0 = uvec3(simplex_corner0);
    uvec3 wrapped_corner1 = uvec3(simplex_corner0+1);
    wrapped_corner0 = wrapped_corner0 % wrap;
    wrapped_corner1 = wrapped_corner1 % wrap;

    //uvec3 hashes_offset0 = singleHash(uvec3(simplex_corner0));
    //uvec3 hashes_offset1 = singleHash(uvec3(simplex_corner0+1));
    uvec3 hashes_offset0 = singleHash(wrapped_corner0);
    uvec3 hashes_offset1 = singleHash(wrapped_corner1);
    //near corner hash value
    uint hashval0 = combineHash(seed, hashes_offset0);
    //mid corner hash value
    uint hashval1;

    uint hashval2;
    //far corner hash value
    uint hashval3 = combineHash(seed, hashes_offset1);

    ivec3 simplex_corner1;
    ivec3 simplex_corner2;
    if (subpos0.x >= subpos0.y)
    {
        if (subpos0.y >= subpos0.z)
        {
            hashval1 = combineHash(seed, uvec3(hashes_offset1.x, hashes_offset0.yz));
            hashval2 = combineHash(seed, uvec3(hashes_offset1.xy, hashes_offset0.z));
            simplex_corner1 = ivec3(1,0,0);
            simplex_corner2 = ivec3(1,1,0);
        }
        else if (subpos0.x >= subpos0.z)
        {
            hashval1 = combineHash(seed, uvec3(hashes_offset1.x, hashes_offset0.yz));
            hashval2 = combineHash(seed, uvec3(hashes_offset1.x, hashes_offset0.y, hashes_offset1.z));
            simplex_corner1 = ivec3(1,0,0);
            simplex_corner2 = ivec3(1,0,1);
        }
        else // subpos0.x < subpos0.z
        {
            hashval1 = combineHash(seed, uvec3(hashes_offset0.xy, hashes_offset1.z));
            hashval2 = combineHash(seed, uvec3(hashes_offset1.x, hashes_offset0.y, hashes_offset1.z));
            simplex_corner1 = ivec3(0,0,1);
            simplex_corner2 = ivec3(1,0,1);
        }
    }
    else // subpos0.x < subpos0.y
    {
        if (subpos0.y < subpos0.z)
        {
            hashval1 = combineHash(seed, uvec3(hashes_offset0.xy, hashes_offset1.z));
            hashval2 = combineHash(seed, uvec3(hashes_offset0.x, hashes_offset1.yz));
            simplex_corner1 = ivec3(0,0,1);
            simplex_corner2 = ivec3(0,1,1);
        }
        else if (subpos0.x < subpos0.z)
        {
            hashval1 = combineHash(seed, uvec3(hashes_offset0.x, hashes_offset1.y, hashes_offset0.z));
            hashval2 = combineHash(seed, uvec3(hashes_offset0.x, hashes_offset1.yz));
            simplex_corner1 = ivec3(0,1,0);
            simplex_corner2 = ivec3(0,1,1);
        }
        else // subpos0.x >= subpos0.z
        {
            hashval1 = combineHash(seed, uvec3(hashes_offset0.x, hashes_offset1.y, hashes_offset0.z));
            hashval2 = combineHash(seed, uvec3(hashes_offset1.xy, hashes_offset0.z));
            simplex_corner1 = ivec3(0,1,0);
            simplex_corner2 = ivec3(1,1,0);
        }
    }

    //we would do this if we didn't want to seperate the hash values. 
    //hashval0 = fullHash(seed, uvec3(simplex_corner0));
    //hashval1 = fullHash(seed, uvec3(simplex_corner0+simplex_corner1));
    //hashval2 = fullHash(seed, uvec3(simplex_corner0+simplex_corner2));
    //hashval3 = fullHash(seed, uvec3(simplex_corner0+1));

    vec3 subpos1 = subpos0 - vec3(simplex_corner1) + UNSKEW3D;
    vec3 subpos2 = subpos0 - vec3(simplex_corner2) + 2.0*UNSKEW3D;
    vec3 subpos3 = subpos0 + FAR_CORNER_UNSKEW3D;
    float n0, n1, n2, n3;

    //http://catlikecoding.com/unity/tutorials/simplex-noise/
    //circle distance factor to make sure second derivative is continuous
    // t variables represent (1 - x^2 + y^2 + ...)^3, a distance function with 
    // continous first and second derivatives that are zero when x is one. 
    float t0 = DISTCONST_3D - subpos0.x*subpos0.x - subpos0.y*subpos0.y - subpos0.z*subpos0.z;
    //if t < 0, we get odd dips in continuity at the ends, so we just force it to zero
    // to prevent it
    if(t0 < 0.0){
        n0 = 0.0;
    }else{
        float t0_pow2 = t0 * t0;
        float t0_pow4 = t0_pow2 * t0_pow2;
        vec3 grad = getGradient3Old(hashval0);
        float product = dot(subpos0, grad);
        n0 = t0_pow4 * product;
    }
    float t1 = DISTCONST_3D - subpos1.x*subpos1.x - subpos1.y*subpos1.y - subpos1.z*subpos1.z;
    if(t1 < 0.0){
        n1 = 0.0;
    }else{
        float t1_pow2 = t1 * t1;
        float t1_pow4 = t1_pow2 * t1_pow2;
        vec3 grad = getGradient3Old(hashval1);
        float product = dot(subpos1, grad);
        n1 = t1_pow4 * product;
    }
    float t2 = DISTCONST_3D - subpos2.x*subpos2.x - subpos2.y*subpos2.y - subpos2.z*subpos2.z;
    if(t2 < 0.0){
        n2 = 0.0;
    }else{
        float t2_pow2 = t2 * t2;
        float t2_pow4 = t2_pow2*t2_pow2;
        vec3 grad = getGradient3Old(hashval2);
        float product = dot(subpos2, grad);
        n2 = t2_pow4 * product;
    }

    float t3 = DISTCONST_3D - subpos3.x*subpos3.x - subpos3.y*subpos3.y - subpos3.z*subpos3.z;
    if(t3 < 0.0){
        n3 = 0.0;
    }else{
        float t3_pow2 = t3 * t3;
        float t3_pow4 = t3_pow2*t3_pow2;
        vec3 grad = getGradient3Old(hashval3);
        float product = dot(subpos3, grad);
        n3 = t3_pow4 * product;
    }
    return (n0 + n1 + n2 + n3);
}

//settings for fractal brownian motion noise
struct BrownianFractalSettings{
    uint seed;
    int octave_count;
    float frequency;
    float lacunarity;
    float persistence;
    float amplitude;
};

float accumulateSimplexNoiseV(in BrownianFractalSettings settings, vec3 pos, float wrap){
    float accumulated_noise = 0.0;
    wrap *= settings.frequency;
    vec3 octave_pos = pos * settings.frequency;
    for (int octave = 0; octave < settings.octave_count; octave++) {
        octave_pos = modv(octave_pos, wrap);
        float noise = simplexNoiseV(settings.seed, octave_pos, uint(wrap));
        noise *= pow(settings.persistence, float(octave));
        accumulated_noise += noise;
        octave_pos *= settings.lacunarity;
        wrap *= settings.lacunarity;
    }
    float scale = 2.0 - pow(settings.persistence, float(settings.octave_count - 1));
    return (accumulated_noise/scale) * NORMALIZE_SCALE3D * settings.amplitude;
}

const float FREQUENCY = 1.0/8.0;
const float WRAP = 32.0;

void mainImage( out vec4 fragColor, in vec2 fragCoord )
{
    //set to zero in order to stop scrolling, scrolling shows the lack of tilability between
    //wrapping. 
    const float use_sin_debug = 1.0;
    vec3 origin = vec3(norm01(sin(iTime))*64.0*use_sin_debug,0.0,0.0);
    vec3 color = vec3(0.0,0.0,0.0);
    BrownianFractalSettings brn_settings = 
        BrownianFractalSettings(203u, 1, FREQUENCY, 2.0, 0.4, 1.0);
    const int size_dim = 32;
    ivec2 z_size = ivec2(8, 4);
    ivec2 iFragCoord = ivec2(fragCoord.x, fragCoord.y);
    int z_dim_x = iFragCoord.x / size_dim;
    int z_dim_y = iFragCoord.y / size_dim;

    if(z_dim_x < z_size.x && z_dim_y < z_size.y){
        int ix = iFragCoord.x % size_dim;
        int iy = iFragCoord.y % size_dim;
        int iz = (z_dim_x) + ((z_dim_y)*z_size.x);
        vec3 pos = vec3(ix,iy,iz) + origin; 
        float value = accumulateSimplexNoiseV(brn_settings, pos, WRAP);
        color = vec3(norm01(value));
    }else{
        color = vec3(1.0,0.0,0.0);
    }
    fragColor = vec4(color,1.0);
}

//Image, used to finally display
void mainImage( out vec4 fragColor, in vec2 fragCoord )
{
    const float fcm = 4.0;
    //grabs a single 32x32 tile in order to test tileability, currently generates
    //a whole array of images however. 
    vec2 fragCoordMod = vec2(mod(fragCoord.x, 32.0 * fcm), mod(fragCoord.y, 32.0 * fcm));
    vec3 color = texture(iChannel2, fragCoordMod/(fcm*iResolution.xy)).xyz;
    fragColor = vec4(color, 1.0);
}

What I've tried position % wrap value, modifying wrap value by lacunarity, and after warp % wrap value, which are currently in use (look in simplexNoiseV for the core algorithm, accumulateSimplexNoiseV for the octave summation).

According to these answers it should be that simple (mod position used for hashing), however this clearly just doesn't work. I'm not sure if it's partially because my hashing function is not Ken Perlin's, but it doesn't seem like that should make a difference. It does seem the skewing of coordinates should make this method not work at all, but apparently others have had success with this.

Here's an example of it not tiling: enter image description here

Why is wrapping coordinates not making my simplex noise tile seamlessly?




Generate random number in series

I want to generate 16 digit random number (EndToEndId) in ECMAScript in series. I have written below function but it generates any random number. For example, it generated 8031241688371482 but I want to get second random number ((EndToEndId1))as 8031241688371483. I am using Rational Integration Tester (RIT) tool. So, tags is used in RIT but you can neglect it for now.

I want to use random number to enter as a EndToEndId to send in PAIN001 file for transaction.

Thank you.

var arr_names = new Array(3)
var randomNumber
var len

function GenerateNumber(){
    randomNumber = Math.round(Math.random()*10000000000000000).toFixed(0)
    len = randomNumber.toString().length
}

for(var i = 0;i<arr_names.length;i++) { 
    randomNumber = Math.round(Math.random()*10000000000000000).toFixed(0)
    len = randomNumber.toString().length

    while(len != 16){
        GenerateNumber()
    }

   arr_names[i] = randomNumber
}

tags["EndToEndId"] = arr_names[0];
tags["EndToEndId1"] = arr_names[1];
tags["EndToEndId2"] = arr_names[2];




RNGCryptoServiceProvider random string. always returns a string that ends with '='

static public string GetRandomSalt(int saltLength)
    {
        byte[] saltByte = new byte[saltLength];

        using (var random = new RNGCryptoServiceProvider())
        {

            random.GetBytes(saltByte);
        }
        return Convert.ToBase64String(saltByte);
    }

so if the salt length is 8, it will returns some random string but ends with '=', how do I avoid it? looked at other stack overflow solution, but still cannot fix it




How to assign probabilities based on certain condition?

I have run into a wall here. So i pull random sample of, lets say 10 elements, and i want to give them probabilities, based on some condition. Lets say that i have this random sample [1, 3, 5, 7, 13, 16, 6, 9, 22, 15] so i want to give each number a probability based on the relative distance from int of 8. Further element is from 8, less the probability. In this case 7 and nine have same, biggest probabilities and 22 have the smallest?

I tried to find some numpy function, but with no success.

Thanks!




How to draw random numbers in python from a normal distribution with given mean, variance, skewness and kurtosis

I'm trying to draw random numbers from a normal distribution with given mean, variance, skewness and kurtosis.

My first attempt was to use the numpy function random.normal however to this function as far as i understand i can only pass a location (mean) and a scale (std) parameter.

Second attempt is to draw random numbers from the uniform distribution in the interval [0,1] and then pass them through the scipy.stats.norm method ppf. I see that scipy has the ability to treat skewness and kurtosis, however i cannot see how i can pass skewness and kurtosis values into the function.

If the problem should be solved in an entirely different way please let me know.

Attempt 1:

import numpy as np

def draw_normal():
    return np.random.normal(loc=0, scale=1) # how to pass skew and kurtosis (excess kurtosis) to the function 

Attempt 2

import numpy as np
from scipy.stats import norm


def draw_uniform():
    return np.random.uniform(0,1)

def draw_normal_alt():
    return norm.ppf(draw_uniform(),loc=0, scale=1) #how to pass skew and kurtosis (excess kurtosis) to func




Get a random file from a random folder

I have a folder "testfiles" in my project directory, which contains a lot of others folders. Those folders all have names like "alice-g" (firstname and then first letter from lastname). Each of those folders contains some other folders, not always the same number. And in each of those last folders, i got a bunch of files, all named with number ("1.", "2.", "3." and so on).

What i want to do is going into this "testfiles" directory, randomly select a folder, get his name, then randomly select another folder in it and finally select a random file in this folder (and get his name).

I have found this post which say we can pick a random file from a folder this way:

File[] files = dir.listFiles();
Random rand = new Random();
File file = files[rand.nextInt(files.length)];

This sound clear and easy to me. However, since all my files have "easy numbered names", i wonder if there is a way to do this without making list of all files (i can have thousand of files in a directory, dunno how efficient this will be then...). Is there any way to just get the number of files in a directory (without making this list of all files)? Then i will just have to select a random number between 1 and the amount of files and i can set the filename and select the file.

Second, this solve the problem of selecting a random file, but not of selecting a random directory (and get his name).

It may be important to say that i'm on Ubuntu 16.04? I've never worked with directories in java, so dunno if it's really relevant.




How do I filter out random sample from dataframe in which there are different sample size for each value, in python?

Hi I am newbie to python,

I have to filter out random sample from Data on which:

'a' should have 6 values,

'b' should have 4 values and

'c' should have 7 values randomly.

Data    Value

a       1

a       2

a       3

a       4

a       5

a       6

a       7

a       8

a       9

a       10

b       1

b       2

b       3

b       4

b       5

b       6

b       7

b       8

b       9

c       1

c       2

c       3

c       4

c       5

c       6

c       7

c       8

I want output as:

Data Value

a     3

a     5

a     7

a     2

a     4

a     9

b     3

b     5

b     7

b     8

c     1

c     3

c     4

c     5

c     6

c     7

c     9




jeudi 30 août 2018

Is it possible to generate a random number in python on a completely open interval or one that is closed on the high end?

I would like to generate a random number n such that n is in the range (a,b) or (a,b] where a < b. Is this possible in python? It seems the only choices are a + random.random()*(b-a) which is includes [a,b) or random.uniform(a,b) which includes the range [a,b] so neither meet my needs.




How to generate random numbers between 0.1 and 0.01

I know its possible to generate integer random number using

(rand() % (difference_between_upper_and_lower_limit)) + lower_limit

I'm wondering if theres a way to generate a number between 0.1 and 0.01. I've tried double speed = (rand() % 10)/100; But it always just gives me 0.0000000; Thanks in Advance!`




How can I generate a range of random floating point numbers in Julia?

I noticed that rand(x) where x is an integer gives me an array of random floating points. I want to know how I can generate an array of random float type variables within a certain range. I tried using a range as follows:

rand(.4:.6, 5, 5)

And I get:

 0.4  0.4  0.4  0.4  0.4
 0.4  0.4  0.4  0.4  0.4
 0.4  0.4  0.4  0.4  0.4
 0.4  0.4  0.4  0.4  0.4
 0.4  0.4  0.4  0.4  0.4

How can I get a range instead of the lowest number in the range?




Not generating the same random number multiple times in a loop

I'm new to Java so apologies in advance if any of this is unclear (or the code is really bad), but I am trying to build a program that gets the computer to guess a two digit code that the user has entered (i.e. secretCode). The following piece of code works fine and it will generate a random code that is then compared to the secret code and check if there are positions entered in the correct place.

However, how would I do it so that each time the computer guessed, it wouldn't be able to guess a number it has previously guessed (e.g. if it guesses 57 on the first guess, it can't pick 57 again for the duration of the loop). Basically I want the computer to keep track of the guesses it has made and not do them again. Any ideas how this is possible (without substantial rewriting of the program if possible)? Or am I going the wrong way about this?

        while (guesses < 10)
        int[] compCode = computer.getComputerCode(); //This line gets a random two digit array of ints
        System.out.print("Computer guess: ");
        Arrays.stream(compCode).forEach(System.out::print);
        correctPositions = getPosition(compCode, secretCode);

        System.out.println("\nYou picked " + correctPositions + " numbers in the correct position.");
        guesses++;




Is it possible to set a deterministic seed for boost::random::uniform_int_distribution<>?

I'm using boost::random::uniform_int_distribution<boost::multiprecision::uint256_t> to generate some unit tests. Notice that I'm using multiprecision, which is why I need to use boost and not the standard library. For my periodic tests, I need to generate deterministic results from a nondeterministic seed, but in such a way where I can reproduce the results later in case the tests fail.

So, I would generate a true random number and use as a seed, and inject that to uniform_int_distribution. The purpose is that if this fails, I'll be able to reproduce the problem with the same seed that made the tests fail.

Does this part of boost support generating seed-based random numbers in its interface? If not, is there any other way to do this?

The way I generate random numbers currently is:

boost::random::random_device                                              gen;
boost::random::uniform_int_distribution<boost::multiprecision::uint256_t> dist{100, 1000};
auto random_num = dist(gen);

PS: Please be aware that the primary requirement is to support multiprecision. I require numbers that range from 16 bits to 512 bits. This is for tests, so performance is not really a requirement. I'm OK with generating large random numbers in other ways and converting them to boost::multiprecision.




Is there a package for reading large data in blocks AND randomly split it into N parts in R?

everyone! I am a decent R user who already used R for several years in modeling and manipulation. Since R is an in RAM operational language, is there a package that can do both of the following:

  1. Can read the extremely large file (like 1 TB CSV) in (let's say) 256MB blocks each time.
  2. Distribute them into N (user-defined) files and save as different CSV files.

Since I am mostly working on modeling, I am really lacking of knowledge on read and split data. I knew some packages can do part of it, but not with both of it.

Again, thank you for any suggestions and help!




How to Random generate a value like this 23-4564567

I am looking for how I can random generate a value like this 23-3455673. My issue is I'm not sure how to get the - in the middle of my random numeric code. I am using a Maven java project and using the RandomStringUtils.randomnumeric(10)

So looking for a way to random generate the value as 23-5672345 basically two digits then a - then 7 digits all in a single string.

I'm not super skilled here so i really am not looking for highly technical answers just the simplest method to make this work is what I'm looking for.

Thanks in advance for any advise on how to accomplish this.




Selecting Random Row With Postgres & TypeORM

I am trying to get a random row from a table in Postgres.

After reading this and this I was able to come up with the following piece of code:

@Get("/motivations/random")
async getRandomMotivation() {

  return await getConnection()
    .createQueryBuilder()
    .select("id")
    .from(Motivation, "motivation")
    .orderBy("RANDOM()")
    .limit(1)
    .getOne()
}

The result is this:

query: SELECT id FROM "motivations" "motivation" ORDER BY RANDOM() ASC LIMIT 1

However, when sending a GET request with POSTMAN it returns a NotFoundError and that's all ...

I was looking in TypeORM's documentation plenty of times, looking for a randomizing solution of any sort but found none.

Did I miss anything in the query builder? Or did I add something extra? Or just the whole query statement is built in the wrong way?

Any tip or comment helping solve the problem is welcomed.




How to perform a quasirandom shuffle on Python? [on hold]

If I have an 2-d numpy array, how can I perform a quasirandom shuffle on it? What I would like to do is have as an input the numpy array, and then have it shuffled in the same way as random.shuffle() would do it, but instead of using pseudorandom approach, use quasirandom approach (for example sobol or halton).




Javascript Random Name Always Returning Same item

I have this javascript code that collects the name from an array of string and return a random name, But everytime I fire the function, it is returning the same name; I need to refresh the web page to generate a new random name.

var items = ["Tony","Peter","Chris","Thor","Roger","Steve"];
var  randomItem = items[Math.floor(Math.random() * items.length)];

function getRandom(){
  document.getElementById("random").innerHTML = randomItem;
}
<button id="getRandom" onclick="getRandom()">Get Random name</button>
<span id="random">Click button to generate new name</span>



Please help me verify this parallel Fisher-Yates shuffle algorithm [on hold]

I try to find a way I could make a parallel shuffling algorithm

Suppose I have 100 objects, each kept its own index 0-99. I need to shuffle the index of each one in parallel and I could not making array to shuffle it normally because it might be scaled to million. So it not practical to create million array of million object in parallel

So I just came up with this about counting the number of random to match the index of object

var random = new Random(seed); // random with seed in C#
var obj = new { index : 16 }; // the index of the 16th object
int i = 100; // number of object amount
while(i > 0)
{
    i--; // 99,98,97,... index to put object into

    int rand = random.Next(0,i); // 0-99,0-98,0-97,...
    if(rand == obj.index)
        break;

    // simulate index of array in original Fisher-Yates,
    // if the index that was randomed out was less than all the object, 
    // means that the object in that index was taken out and put to the i index,
    // so every index after that would be shifted by one
    if(rand < obj.index)
        obj.index--; 
}

obj.index = i; // simulate index that put to the last of array

Are there any problem with this code? Is it really work?

And also, I just came up with this, so I wish that there would be any better shuffle algorithm that could run in parallel like this. Are there any?




Get Possible Random Result

How to get combination result while random my table. I have a table as Question_id, Question_Ans_id Q1 A1 Q1 A2 Q1 A3 Q1 A4

I would to random the question_as_id so i can have records such as Question_id, Question_Ans_id Q1 A1 Q1 A2 Q1 A3 Q1 A4 Question_id, Question_Ans_id Q1 A1 Q1 A3 Q1 A4 Q1 A2 Question_id, Question_Ans_id Q1 A1 Q1 A4 Q1 A2 Q1 A3 Question_id, Question_Ans_id Q1 A1 Q1 A2 Q1 A4 Q1 A3

and all possible result.

Please help.




mercredi 29 août 2018

Generate two set of random numbers and multiply each elements in python

Generate 10 random number in the range 1-200.Also,Generate another 10 random numbers in the range 1-10.Multiply each random number from the first set with all the random numbers from the second set (Total 10*10 = 100 numbers will be generated after multiplication). Calculate mean, variance, median and mode of the multiplied numbers. how to do this in python.I am new in python.help!.




What are the chances of Math.random returning 0?

Like the asker of this question, I was wondering why Math.ceil(Math.random() * 10) was not preferred over Math.floor(Math.random() * 10) + 1, and found that it was because Math.random has a tiny (but relevant) chance of returning 0 exactly. But how tiny?

Further research told me that this random number is accurate to 16 decimal places... well, sort of. And it's the "sort of" that I'm curious about.

I understand that floating point numbers work differently to decimals. I struggle with the specifics though. If the number were a strict decimal value, I believe the chances would be one in ten billiard (or ten quadrillion, in the American system) - 1:1016.

Is this correct, or have I messed up, or does the floating point thing make a difference?




How to operate random node for Shortest Path?

Let n = 10; Then, how can we use random nodes (replaces X & Y values) to generate shortest path such as below code:

x= [1 1 2 2 3 4 6 4 5 5 ];    
y= [2 5 3 4 4 5 3 1 2 6 ];

% Random weight for shortestpath
weights = randi(52, size(x));    
w = randi([1 10], 13, 1); 

D = graph(x,y,weights);    
p = plot(D,'x','EdgeLabel',D.Edges.Weight );

path = shortestpath(D,1,5);    
highlight(p,path,'NodeColor','g','EdgeColor','g')

Thanks.




Python even group assigning

I am a beginner to python and was working on a random team generator. The issue I've run into is that I am not sure of how to make it generate even teams. The code is below as well as a sample output.

import random


def main():
    run = True
    while run:

        try:
            print("Welcome to this group picker, follow the instructions and your groups will be picked.")
            groupnum = int(input("How many groups do you want?"))
            peoplenum = int(input("How many people are there?"))
            print("Okay, assign everyone a number from 0 to", peoplenum - 1, ".")
            nums = []
            for i in range(0, peoplenum):
                nums.append(i)

            for i in nums:
                print("Number", i, "is in group", random.randint(1, groupnum))

            break

        except:
            print("Error, please follow instructions and enter only numbers.")
            break


main()

Sample output:

 Welcome to this group picker, follow the instructions and your groups
 will be picked.
 How many groups do you want?2 
 How many people are there?8
 Okay, assign everyone a number from 0 to 7 . 
 Number 0 is in group 1 
 Number 1 is in group 2 
 Number 2 is in group 1 
 Number 3 is in group 2 
 Number 4 is in group 1 
 Number 5 is in group 1 
 Number 6 is in group 2 
 Number 7 is in group 1




How to Find All Possible Anagrams?

So I want to make an anagram decoder, and I want to know if there's a better way to do it. My current code is this:

Random random = new Random();
char[] splitAnagram = chosenAnagram.toCharArray();
int[] presetNumbers = new int[chosenAnagram.length()];
int i = 0;
while (true) {
    TimeUnit.MILLISECONDS.sleep(10);
    int thisRandom = random.nextInt(chosenAnagram.length());
    if (Arrays.asList(presetNumbers).contains(thisRandom) == true)
        presetNumbers[i] = thisRandom;
    else
        continue;
    i++;
    if (i > chosenAnagram.length())
        break;
}
for (int l = 0; l < chosenAnagram.length(); l++) {
    System.out.println(splitAnagram[presetNumbers[l]]);
}

Basically, it generates random numbers for each letter, so that it "scrambles" the word. It's flawed as is, because it's not even supposed to loop yet, just make one scramble, but it just in-general seems really slow and prone-to-error (I sleep by 10ms because it can only make random numbers every system time change).

I'm wondering if there's some other algorithm for this, or a possible API I could use. Thank you!

P.S I'm running Eclipse Photon, in case you know of a plugin for that.




How to select a random object except one spesific one from a list?

I am designing an experiment with the Expyriment package. There is two boxes and I give them random colors but they must be different from each others. I use for loop and enumerate to loop through:

color = [(0, 76, 153), (204, 0, 0), (0, 153, 0), (255, 230, 0)]

for i, x in enumerate(color): print(color[i]) print(random.choice(color.remove(color[i])))

2 problems emerged from here, the tuple I removed gone forever and I got a TypeError: object of type 'NoneType' has no len()

I search for a way to temporarely remove an tuple for looping but cant find it.

Also, when I tried using pop [ print(random.choice(color.pop(i))) ], it didnt give me an error but it just prints int not tuple. Also, object that I pop is still gone forever.

Sorry about the mistakes, this is my first post. Thank you.




Improving scaling of sample from discrete distribution

I have recently started playing around with Julia and I am currently working on a Monte Carlo simulation of some stochastic process on a 2-dimensional lattice. Each site has some associated rate of activation (the number of times it "does something" per second on average) which we can assume to be approximately constant. The order in which lattice sites activate is relevant so we need a method for randomly picking one particular site with probability proportional to its rate of activation.

It looks like sample(sites,weights(rates)) from the StatsBase package is exactly what I am looking for BUT from testing out my code structure (no logic, just loops and RNG), it turns out that sample() scales linearly with the number of sites. This means that overall my runtimes scale like N^(2+2), where N in the side length of my 2-dimensional lattice (one factor of 2 from the increase in total rate of activity, the other from the scaling of sample()).

Now, the increase in total rate of activity is unavoidable but I think the scaling of the "random pick with weights" method can be improved. More specifically, one should be able to achieve a logarithmic scaling with the number of sites (rather than linear). Consider for example the following function (and, please, forgive the poor coding)

function randompick(indices,rates)
cumrates = [sum(rates[1:i]) for i in indices]
pick = rand()*cumrates[end]
tick = 0
lowb = 0
highb = indis[end]

while tick == 0
    mid = floor(Int,(highb+lowb)/2)
    midrate = cumrates[mid]

    if pick > midrate
        lowb = mid
    else
        highb = mid
    end

    if highb-lowb == 1
        tick = 1
    end
end
return(highb)
end

Because we half the number of "pickable" sites at each step, it would take n steps to pick one specific site out of 2^n (hence the logarithmic scaling). However, in its current state randompick() is so much slower than sample() that scaling is practically irrelevant. Is there any way of reducing this method to a form that can compete with sample() and hence take advantage of the improved scaling?




NIST statistical test suite issue

The question is about the document: NIST SP 800-22, which can be obtained, for example, here

The issue is: in the linear-complexity test it is assumed that the expected probabilities of classes are: [0.010417, 0.03125, 0.125, 0.5, 0.25, 0.0625, 0.20833]. You can easily verify that the sum of probabilities equals 1, which is OK.

But all of the implementations I have found use another vector of expected probabilities, which is: [0.01047, 0.03125, 0.125, 0.5, 0.25, 0.0625, 0.20833].

The sum of the coordinates of this vector is definitely not equal 1, which means that this is a replicated typo.

NIST provides several examples of results that are expected (for instance, for e, pi, sha-1 sequence and two others). It can be checked that if you want to obtain the same results, the vector should be with this typo. Is it possible, that there is a mistake in this standard or this is a mistake in all available implementations?




How to turn all rand_mode on effectively after partially turn them off in systermverilog

I have classes as below

class h1_c;
  rand bit[1:0] h1_a;
  rand bit[1:0] h1_b;
  h2_c h2;
  function new()
    h2 = mew();
  endfunction
endclass

class h2_c;
  rand bit[1:0] h2_a;
  rand bit[1:0] h2_b;
  h3_c h3;
  function new()
    h3 = mew();
  endfunction
endclass

class h3_c;
  rand bit[1:0] h3_a;
  rand bit[1:0] h3_b;
endclass

module p1;   
  h1_c h1;

  initial begin
    h1 = new();
    h1.h2.h2_a.rand_mode(0);
    h1.h2.h3.h3_a.rand_mode(0);
    h1.randomize();
    //How to turn all rand_mode on effectively after I turn them off seperately.
    //which like h1.*.rand_mode(1);
  end
endmodule

I turn some variables' rand mode off and want to turn them all on effectively after randomize(). Is there any efficient way to do that?




Unable to generate random numbers when passed into a function in C++

I'm still a beginner trying to learn some C++.

I'm trying to pass in a random number to a function to generate a random 2D array for a small game. Unfortunately, it always prints out the same option instead of generating a random one each time.

Could you please help? I'd appreciate it.

Could you please advise me also if there is a better way to randomize 'X' and 'O' within a 2D array than simply hard-coding it as I have tried?

Thank you very much.

#include <iostream>
#include <cstdlib>

using namespace std;

void generateBlock(int n)
{
    switch (n)
    {
    case 0:
    {
        char blocks1[4][4] = { 'X', 'X', 'O', 'O',
            'X', 'X', 'O', 'O',
            'O', 'O', 'O', 'O',
            'O', 'O', 'O', 'O' };

        for (int i = 0; i < 4; i++)
        {
            for (int j = 0; j < 4; j++)
            {
                cout << blocks1[i][j];
            }
            cout << endl;
        }
        return;
    }

    case 1:
    {
        char blocks2[4][4] = { 'X', 'X', 'O', 'O',
            'O', 'O', 'X', 'X',
            'O', 'O', 'O', 'O',
            'O', 'O', 'O', 'O' };

        for (int i = 0; i < 4; i++)
        {
            for (int j = 0; j < 4; j++)
            {
                cout << blocks2[i][j];
            }
            cout << endl;
        }
        return;
    }

    case 2:
    {
        char blocks3[4][4] = { 'X', 'X', 'O', 'O',
            'X', 'O', 'O', 'O',
            'X', 'O', 'O', 'O',
            'O', 'O', 'O', 'O' };

        for (int i = 0; i < 4; i++)
        {
            for (int j = 0; j < 4; j++)
            {
                cout << blocks3[i][j];
            }
            cout << endl;
        }
        return;
    }
    }
}

int main()
{
    int n = rand() % 3;
    generateBlock(n);
}




Segfault and uninitialized data when generating a random array in C

#include "stdafx.h"
#include <stdlib.h>
#include <time.h>
#define len 10

int *randomArray(void);

int main()
{
    srand(time(NULL));
    int *rArray = (int *)malloc(sizeof(int) * len);
    rArray = randomArray();
    for (int i = 0; i < len; i++) {
        printf("%d ", *(rArray+i));
    }
    puts("");
    free(rArray);
}

int *randomArray(void)
{
    int array[len] = { 0 };
    for (int i = 0; i < len; i++) {
        array[i] = rand() % len;
    }
    return array;
}

Task is to create an array of ints and have a function fill that array with random numbers. The function randomArray() works just fine, but for some reason the assignment rArray = randomArray() doesn't work correctly, although some elements of rArray are valid numbers not gibberish. Also, the last main line free(rArray); crashes the program which is just mind numbing for me, it doesn't make any sense. If I remove the line the program doesn't crash but we all know you need to free() a malloc()-ed array.




mardi 28 août 2018

How to make trials jitter in a certain temporal block in MATLAB

I am trying to design a fMRI experiment that trials jitter in a certain time-block. A single trial takes 3.5 seconds and I want every trial to appear in a block of 6 seconds.

For example, if this trial starts simultaneously with this time block, it will start at 0-second point, end after 3.5 seconds, and the next trial will start after 2.5 seconds. If a trial started 1.2 seconds after the block started, the trial will end at 4.7 seconds after the start of the block and will show a fixation cross for 1.3 seconds to reach the end of the 6-second block.

Basically, I want this 3.5-second smaller block to freely float inside a bigger, 6-second block in a random manner. How can I achieve this in MATLAB?

I attached a descriptive figure for better understanding.




How to pseudo-randomize trials without repeating same condition more than three times

I know there are lots of pseudo-randomization skills but this one, I couldn't search it so I put it on here.

I am using MATLAB 2018a. I've been trying to set up a behavior experiment which has 10 conditions. Each condition has 50 trials. This results in 500 trials total. I would like to pseudo-randomize the sequence of trials such that no same conditions appear more than three times consecutively.

I thought it would be not so difficult since I have many conditions but some of the methods I found by googling had minor problems. One of the methods I used was by extracting indexes using 'unique(find(diff(seq)==0))', re-randomize it and replace it with the original redundant sequence. (Link) But this method had a problem that it would randomly change the total number of a condition. If you wanted 40 stimuli for each condition, it would result in 39 for some conditions while 41 for others..

My question would be how to improve this method to have constraints of having no one condition repeated three times, while solving the problem mentioned above. Or would there be any better ways?




How to randomly create 6 groups of 5 people 4 times without any person being in a group with another person twice

In Excel I must distribute 30 people randomly in 6 groups of 5 people 4 times. Is it possible to do this so no person gets in a group with someone they have been in a group with before?

The problem is kind of like the question on the follwing link, but I need to solve it in Excel: How to create 21 random groups of 10 people 4 times, without people being in the same group

I don’t hope I am bothering you with my question.




How to get one random element from an array using mersenne twister in javascript?

I inherited a gambling project, where mersenne twister is used as a random nunmber generator.

But I am not sure about the implementation of the same.

The library that is used gives random number [0,1>

Now, for the purpose of the app, it should give back one random number from an array of [0,1,2,...,n>

I was wondering, what is the easiest way to implement this, that is statistically correct. (that it passes bigcrush for example)

I believe that current implementation is very bad

https://gist.github.com/matejthetree/5c510babe767634b6c5189d9e482aca3

It is used to shuffle an array and then take one member from that array, instead of taking random [0,length> and choosing array[random]




Moving numbers of two columns to achieve desired correlation

We have numbers in columns A1 to An and B1 to Bn. What code(VB) can be written to put together these numbers so that their correlation be within (a, b)? For example, in screenshots I've attached, there are numbers in A1 to A10 and B1 to B10 that their correlation is 0.58, But we want correlation of these numbers be in (0.3.0.80).

enter image description here




How do I randomly split a multiset into sets of predetermined sizes, without duplicates?

I'm looking for help on a problem which I don't know how to deal with. I'm guessing similar questions have already been asked, but I couldn't google it the right way.

What I'm trying to do is a randomizer for the boards in FFXII and there's a part of the problem I don't know how to solve: the randomization.

I'm simplifying a bit here: there are 12 boards containing licenses that you can unlock to equip stuff or use magic. Board spots may be empty and no single license may appear twice on one board, but licenses can occur several times if they are on different boards. Each board also has a different number of licenses. There's a total of 1626 licenses on the boards, with the number of unique licenses being around 350. I have a list of all licenses, along with the number times they occur in the original board setup. (The one you get if you play the game normally.)

I would like help with generating 12 random licence lists of predetermined size, without duplicates, from the multiset of licence occurences in the original game. The total size of the 12 lists is equal to the number of elements in the multiset, of course. (I'll place them on the board myself, that is not too difficult.)

Oh also, I'm coding in C#, but this is more of a combinatorics question, so the exact language is not as important.




How to test prng for distribution and volatily?

I have one prng implementation that gives random numbers from an array.

Now, I am searching for a script or a way to test the distribution of it, and also how fast does the distribution equalize

I tried searching online for it, but maybe I am missing some search terms, as only thing I find is other prng implementations. Thank you Thank you




change color of shape when mouse is hovered over it and spacebar pressed

If the mouse is over the shape and the user presses spacebar, i want the colour of the shape to change to a random color. Any help is greatly appreciated as im still learning, cheers.

Program.cs

if (SwinGame.KeyTyped(KeyCode.SpaceKey))
{
myShapes.SelectShapes(SwinGame.MousePosition());
}

Drawing.cs

i believe it is this part of the code that i need to change. Color is not changing the color of the shape like i hoped but im not sure what else to use, nothing i've tried seems to work.

    public void SelectShapes(Point2D pt)
    {
        foreach (Shape s in _shapes)
        {
            if (s.At(pt))
            {
                Color = SwinGame.RandomRGBColor(255);
            }
        }
    }

Shape.cs

using SwinGameSDK;

namespace ShapeGame
{
    public class Shape
    {
        public Color _color;
        private float _x, _y;
        private int _w, _h;
        private bool _selected;



        public bool At(Point2D pt)
        {
            return SwinGame.PointInRect(pt, _x, _y, _w, _h);
        }

        public Shape()
        {
            _color = Color.DarkRed;
            _x = 0;
            _y = 0;
            _w = 80;
            _h = 80;
        }



        public Color Color
        {
            get
            {
                return _color;
            }
            set
            {
                _color = value;
            }
        }

        public float X
        {
            get
            {
                return _x;
            }
            set
            {
                _x = value;
            }
        }

        public float Y
        {
            get
            {
                return _y;
            }
            set
            {
                _y = value;
            }
        }

        public int W
        {
            get
            {
                return _w;
            }
        }

        public int H
        {
            get
            {
                return _h;
            }
        }


        public void Draw()
        {
            if (_selected)
            {
                DrawOutline();
            }

            SwinGame.FillRectangle(_color, _x, _y, _w, _h);
        }




Generating random number between 2 variables

I'm struggling to find a way to generate a random number only between 20 and 30. I have this so far but its getting numbers below 20.

int num1 = 30;
int num2 = 20;
int num_random = rand()%num1;
while (num_random < num2){
    num_random = rand()%30;
}




Random points in a space time

I have a set of date compost by several years of mortality in the roads. My data are coordinates x&y. I need to create a random distribution of data as a control to be able to compare my data with the random control and see if there are hot-spots of mortality. I know it is possible to create a random set of points with R, but I don’t know how to make both comparable in terms of time. How can I crate these points for a period of several years?

Thank you again

Aurora




lundi 27 août 2018

Generating array with random integers C [duplicate]

This question already has an answer here:

so I am trying to fill an array with random integers.

for (int i = 0; i < 2; i++){
    srand(time(NULL));
    array[i]=rand()%30; }`

Here is my code so far. I am currently getting the same random number twice. Would like to know if there is a way around this?




Random.Next returning same number

When I searched for a reason why this is happening I kept finding responses about creating new instances of Random() too close in time. However, I am using only 1 instance of Random and am passing it to the same method multiple times.

Thank you for any advice you can give.




Securely Use Random Number Generator for Lottery Winning

I want to design a lottery winning mechanism using random number generator. I know that for computer, there is no true randomness but only "pseudorandom". If the system gets hacked and random seed is seen, people will know the sequence of random numbers. In fact, there is news that people did this and won several lotteries. I am thinking about two ways of designing my system:

  1. Use random number generator as a global variable. There is only one random seed; the sequence is generated when the system starts.

    Con:

    a. Once the random seed is seen, hackers will know the sequence easily.

    b. Once the system crashes and restarts, the sequence will repeat itself.

  2. Create a random number generator using timestamp as random seed each time to generate a number.

    Con:

    a. Obviously timestamp cannot be directly used. There are some tricks needed to be done with the timestamp each time. For example, plus or minus some values each time on the timestamp. What algorithm can I use here to do this kind of modification on timestamp?

    b. Is this method even taking advantage of random number generator? It seems I am just creating a random number by myself...

As we can see, either of the method above is not secure enough. Which way is slightly better? Or is there a better way?




PySpark : generate Random Distributed Matrix

Does someone know how we can generate a random Distributed Matrix (RowMatrix ,IndexedRowMatrix, CoordinateMatrix or BlockMatrix)in Pyspark given the dimensions (n,m) of a matrix ? Thank you. (I know this can easy be done with Numpy package in Python)




Why this code for sorting in python falls into an infinite loop?

I want to take a list for sorting and sort it using python random library. The strategy to do this:

  • First, take any two random index in the list we take as input
  • Then swap those two elements.
  • check if the list is sorted or not.
  • if not sorted , repeat the steps again.

I am new in python. So not well acquainted with all the techniques . Please help with explanation. I cant figure out what is going wrong.

from random import randint

n=int(input())
l=[int(input()) for x in range(0,n)]

p=1

while (1):
  if(p==1):
    ransort(n)
  else:
    break

for x in l:
  print (x)


def ransort(n):
  i=randint(0,n-1)
  j=randint(0,n-1)
  l[i],l[j]=l[j],l[i]

  if l== l.sort():
    p=0
  else:
    p=1
  return p




SQLITE random value/row with criteria

So, i know that the question about getting a random row in SQL database have been posted (even more than one time), and it helped me get to this SQL query:

"SELECT column FROM table WHERE id IN (SELECT id FROM table ORDER BY RANDOM() LIMIT 1)"; 

if i understand that well, order by Random is not efficient on large table but if you use it with the id it's fast enough.

So i've tried it, it seems to work well, but then i wanted to add a criteria, so i've changed it just a little bit:

"SELECT column1 FROM table WHERE (column2 LIKE '" + value + "' AND id IN (SELECT id FROM table ORDER BY RANDOM() LIMIT 1)"; 

To be more clear, i have this table: uploaded = (id, filename, owner). I want to select a random filename from a given owner. Which gives me that:

"SELECT filename FROM uploaded WHERE (owner LIKE '" + owner + "' AND id IN (SELECT id FROM uploaded ORDER BY RANDOM() LIMIT 1))";

Problem is: sometimes, rs.next is false (which mean i don't have a result). However, i print the DB before searching for the filename, so i am SURE that the owner does have a related filename in this DB. Maybe only one, but still one.

This bring me to the question: what's wrong with my query?




Uniform_real does not accept numeric_limits::lowest()

I've got a line:

std::uniform_real_distribution<T> distribution(std::numeric_limits<T>::lowest(), std::numeric_limits<T>::max()); It compiles but crashes on Debug(VS 2017CE). My guess is that, according to documentation of uniform_real:

Requires that a ≤ b and b-a ≤ std::numeric_limits::max()

when my b is ::max() and a is ::lowest(), condition :

b-a ≤ std::numeric_limits::max()

is not fulfilled as b-a it basically doubles value of max. Is there any work around for this so that I will keep such a wide numbers range? ::min() works perfectly but omits negative values. Problem occurs for floating numbers only.




Confusion in Multithreading in C++

I am trying to simulate a probability problem, in which there are n clients and n servers. Each client randomly sends a request to any server, so each server can receive any number of requests, I have to calculate the expected number of maximum requests that any server can receive.

I am trying to simulate this by running 10,000 iterations, where in each iteration each client chooses a random server and a request is sent to it, servers are represented as an integer array of size N.

Client chooses a random number and then the value at that index in server array is incremented. As, for better results the question says N should be about 106.

So to make it a little faster , I used multithreading in which each thread runs 100 iterations and in total there are 10 threads.

But the multithreaded code produces very different results as that from normal code. Below are the code snippets with output for both of them

Normal Version

 #include <iostream>
 #include <random>
 #include <chrono>

 #define N 1000000
 #define iterations 1000

int servers[N];

// This array's i'th index will contain count of in how many
// iterations was i the maximum number of requests received by any  server
int distr[N+1]={0};

int main(int argc, char const *argv[])
{   
   // Initialising
   auto start = std::chrono::high_resolution_clock::now();

   std::srand(time(NULL));

   // Performing iterations
   for(int itr=1; itr<=iterations; itr++)
   {
       for(int i=0;i<N;i++)
       {
           servers[i]=0;
       }

       for(int i=1;i<=N;i++)
       {
           int index = std::rand()%N;
           servers[index]++;
       }

       int maxRes = -1;
       for(int i=0;i<N;i++)
       {
           maxRes = std::max(maxRes, servers[i]);
       }
       distr[maxRes]+=1;
   }

   for(int i=0;i<=15;i++)
   {
      std::cout<<(double)distr[i]<<std::endl;
   }

   auto stop = std::chrono::high_resolution_clock::now();
   auto duration = std::chrono::duration_cast<std::chrono::milliseconds>(stop - start);
   std::cout<<duration.count()<<" milliseconds"<<std::endl;

   return 0;
}

Output

0
0
0
0
0
0
0
359
552
79
10
0
0
0
0
0
1730 milliseconds

Multithreaded Version

#include <iostream>
#include <random>
#include <chrono>
#include <thread>
#include <fstream>

#define N 100000
#define iterations 1000
#define threads 10

// This array's i'th index will contain count of in how many
// iterations was i the maximum number of requests received by any server
std::atomic<int> distr[N] = {};

void execute(int number)
{
    // Performing iterations
    int servers[N]={0};
    for(int itr=1; itr<=number; itr++)
    {

        for(int i=1;i<=N;i++)
        {
            int index = std::rand()%N;
            servers[index]++;
        }

        int maxRes = -1;
        for(int i=0;i<N;i++)
        {
            maxRes = std::max(maxRes, servers[i]);
            servers[i]=0;
        }

        distr[maxRes] += 1;
    }
}

int main(int argc, char const *argv[])
{   
    // Initialising
    auto start = std::chrono::high_resolution_clock::now();

    std::srand(time(NULL));

    std::thread t[threads];
    for(int i=0;i<threads;i++)
    {
        t[i] = std::thread(execute, iterations/threads);
    }   

    for(int i=0;i<threads;i++)
    {
        t[i].join();
    }

    for(int i=0;i<=15;i++)
    {
        double temp = (double)distr[i];
        std::cout<<i<<"\t"<<distr[i]<<std::endl;
    }

    auto stop = std::chrono::high_resolution_clock::now();

    auto duration = std::chrono::duration_cast<std::chrono::milliseconds>(stop - start);
    std::cout<<duration.count()<<" milliseconds"<<std::endl;

    return 0;
}

Output

0   0
1   0
2   0
3   0
4   0
5   0
6   0
7   7
8   201
9   421
10  267
11  68
12  2
13  2
14  4
15  0

1385 milliseconds

Whereas I have run the normal code many times and each times the count for maximum = 9 > 500, and there is not so much scattering of data, I mean only maximum = 8,9,10,11 have significant values rest all are zeroes.

Can anyone please explain what am I doing wrong ?

Thanks in advance!




Is it possible to generate a unique random alphanumeric code consisting of 5 characters using Informix or standard sql?

I'm using informix IDS server, and I have this table table1 :

Column name          Type                                    Nulls

ad_code              char(5)                                 yes
ad_value             smallint                                yes

I would like to generate a random, unique code for field ad_code (and then store it in the ad_code field) of table table1 using sql. Is it possible ?




Attach element to a random place in HTML DOM tree

The idea is to create and insert div (whatever) to DOM. However, it needs to be done following 3 main rules:

  • Each time div is created, it is placed randomly in document, scope may be - inside of body tag.
  • Div should be accessible by JS for further usage.
  • Div is hidden(by style or html 5 attribute). Ideally, not visible even from Elements tab in developer tools.

Additional info: front-end is built via React JS.

What are the basic mechanism of implementation of this task. Maybe we could benefit from using React Portals or even Shadow Dom (for encapsulation).




PHP : play cards, generate just 1 winning card

I have to making playing cards for a website. Is it possible in php to limit the number of playing cards and generate randomly just one time a winning card ?

For exemple :

I limit to 150 playing cards, so I have 150 players, 149 losers, 1 winner ?

Thank you for anwser ! :)




dimanche 26 août 2018

use RNG library in stm32f4xx

I want to write simple code to generate random number with built-in hardware in stm32f4xx discovery board. I wrote the code below but it does not work. It sticks in inner while loop and the flag never set to jump out of loop.

#include <stm32f4xx.h>
#include <stm32f4xx_rng.h>
#include <stm32f4xx_rcc.h>

void RNG_Config(void)
{
    /* Enable RNG clock source */
    RCC_AHB2PeriphClockCmd(RCC_AHB2Periph_RNG, ENABLE);

    /* RNG Peripheral enable */
    RNG_Cmd(ENABLE);
}

int main(void)
{

    uint32_t temp = 0;
    RNG_Config();

    while(1)
    {
        while (RNG_GetFlagStatus(RNG_FLAG_DRDY) == RESET);

        temp = RNG_GetRandomNumber();
    }
}




Fastest way of randomising result with large dataset in mysql

I want to return rows order by random from a table with large number of rows to be scanned

Tried:

1) select * from table order by rand() limit 1

2) select * from table where id in (select id from table order by rand() limit 1)

2 is faster than 1 but still too slow on table with large rowsmys




How to generate mxn matrix with randomly generated 0 and 1 with probability in C

I wrote C program that defined a 2D matrix with m rows and n columns with random numbers (Either 0 or 1). The code is as following:

int i,j;
    int original_matrix[m][n];
    for (i=0; i<=m-1; i++){
        for (j=0; j<=n-1; j++){
            original_matrix[i][j] = rand() % 2;
        }
    }

It worked. For the next step, I want to create the matrix with a probability. For example, 1 is written into a cell with probability p and 0 is written with probability 1-p. Could you please share any ideas on this if you have?




Trying to get a random number between two numbers in C++

Ok, so i am trying to make a program to guess what the user is thinking of, the problem is with the random thingy, BUT! it just prints a number bigger than the max int by one. i.e: if max is 20, output is 21.

{
string hl;
string right;
bool found=false;
int max;
int min;
cin>>min;
cin>>max;
srand(time(NULL));
int x = rand() % max +  min;
while(found==false)
{
    cout<<x;
    cout<<"True?";
    cin>>right;
    if(right=="y"){
        found=true;
    }
    else{
        cout<<"h or l";
        cin>>hl;
    }
    if(hl=="h"){
        min=min+rand() % 3 + 6;
    }
    else if(hl=="l"){
        max=max-rand() % 3 + 6;
    }
    srand(time(NULL));
    x = rand() % min +  max;
}}

I just want to know what i am doing wrong in the random int generator (Btw i just started learning c++ so cut me some slack in this language :P)

Thanks in advance.




Produced Numbers are must different each other with arc4random

i want to use arc4random but produced Numbers are must different each other.

How do i do this example?




Create possion distribution wiith N random numbers whose sum is a constant (C)

I want to generate a random possion number distribution where the sum of the generate number is 1000 and the lower-upper bound of the distribution is (3-30).

I can use numpy to generate random number:

 
In [2]: np.random.poisson(5, 150)
array([ 4,  4,  6,  4,  8,  6,  4,  2,  6,  8,  8,  8,  1,  4,  3,  4,  1,
        3,  7,  6,  7,  4,  5,  5,  7,  6,  5,  3,  3,  5,  4,  6,  2,  0,
        3,  5,  6,  2,  5,  2,  4,  7,  4,  7,  8,  5,  6,  1,  4,  4,  7,
        4,  7,  2,  7,  4,  3,  8, 10,  2,  5,  7,  6,  3,  5,  7,  8,  5,
        4,  7,  8,  8,  2,  2, 10,  6,  3,  5,  2,  5,  5,  6,  4,  6,  4,
        0,  4,  3,  5,  8,  6,  7,  4,  4,  4,  3,  3,  4,  4,  6,  7,  6,
        3,  9,  7,  7,  4,  5,  2,  4,  3,  6,  5,  6,  3,  6,  8,  9,  6,
        3,  4,  4,  7,  3,  9, 12,  4,  5,  5,  7,  6,  5,  2, 10,  1,  3,
        4,  4,  6,  5,  4,  4,  7,  5,  6,  5,  7,  2,  5,  5])


But, I want to add something more to it :

- The random number should be minimal of 3 and max of 30 
- The sum of the generated random number should be 1000.

I know, I may not be creating an exact possion distribution if I manipulate. But, I want something like possion but with suggested controls.




Python | 26 lists called a-z, string with every letter, random letter is choosen, how to select the list

I have 26 lists called a,b,c,..,z and a string called letters.

letters = "abcdefghijklmnopqrstuvwxyz"

Now I randomly choose a letter out of that string.

start_letter = random.choice(letters)

The value of start_letter should now be one letter, which is a list in my script. Now, how do I select that list and randomly choose a "slot" in that list?




How to make array choose four DIFFERENT options

Does anyone know how I can make my array, choose four different options?

var colors = ['#4286f4', '#e2f442', '#f48c41', '#41f4f4', '#dd3b3b', '#7a6f6f']
window.colorOne = '';
window.colorTwo = '';
window.colorThree = '';
window.colorFour = '';


function beginAndGetCombo(){

window.colorOne = colors[Math.floor(Math.random() * colors.length)];
window.colorTwo = colors[Math.floor(Math.random() * colors.length)];
window.colorThree = colors[Math.floor(Math.random() * colors.length)];
window.colorFour = colors[Math.floor(Math.random() * colors.length)];

}


<input type=button value='Get Colors' onclick='beginAndGetCombo()'>




Generate "n" random numbers between a and b to reach desired average in m rows

Hi

Suppose in column" Z" with" 200" rows, are my optimal averages
Now I want  a macro that generate " n" integers in  (a,b) randomly (n<=20)so that difference between average of numbers  generated with

optimal average is in (-0.15,+0.15). Example: Z1:optimal average1=5.5 Z2:optimal average2=5.3

Z200:optimal average200=6.3
n=8
a=1; b=10
numbers of generated:
A1:H1)5-9-4-3-7-4-9-3
A2:H2)10-7-3-2-5-4-3-9
.
.
.
A200:H200)4-8-9-6-6-6-10-2




samedi 25 août 2018

(Python) Get tuple with largest numeric element, and if a tie occurs, randomly pick one of the tied tuples

I have a list of tuples:

a = [([4, 7, 9], [3], 5.5), ([2, 5, 8], [3], 5.5), ([2, 5, 8], [9], 4.5)]

and I will like to get the tuple with the largest numeric element (non-list, for e.g. 5.5 in the case of ([4, 7, 9], [3], 5.5), and if there is a tie, say for this example ([4, 7, 9], [3], 5.5) and ([2, 5, 8], [3], 5.5), one of these tied tuples will be randomly selected as the output.

My progress so far:

>>> import operator
>>> max(a, key = operator.itemgetter(1))
([3], [4, 7, 9], 5.5)

I am unsure as to how I can randomly pick one of the tied tuples at this point in time.. Some insight will be great!




np.random.randn refuses to take negative arguments

import numpy as np
a=[2,4,6,-1,4]
#b=[np.random.randn(0,2) for i in a[1:]]
#print(b)
b=[np.random.randn(x,y) for x, y in zip(a[1:], a[1:])]
print(b)

OUTPUT:

ValueError                                Traceback (most recent call 
last)
<ipython-input-34-b2077da31d55> in <module>()
      3 #b=[np.random.randn(0,2) for i in a[1:]]
      4 #print(b)
----> 5 b=[np.random.randn(x,y) for x, y in zip(a[1:], a[1:])]
      6 b

<ipython-input-34-b2077da31d55> in <listcomp>(.0)
      3 #b=[np.random.randn(0,2) for i in a[1:]]
      4 #print(b)
----> 5 b=[np.random.randn(x,y) for x, y in zip(a[1:], a[1:])]
      6 b

mtrand.pyx in mtrand.RandomState.randn()

mtrand.pyx in mtrand.RandomState.standard_normal()

mtrand.pyx in mtrand.cont0_array()

ValueError: negative dimensions are not allowed


the error keeps throwing no matter whatever a[x1:x2] i give .

What is the obvious thing i am missing ?

I am fairly new to numpy , so please dont mind if this is very basic .




What is a practical, manual (pen & paper) method to generate a cryptographically-secure key for a one-time pad using natural text as a seed?

I thought I had found an answer to my question when I read this:

link

There, one of the posters effectively claims that your seed word's gematria mod 10 is a random number. In other words, sum the letters of a word, treating each letter as the number of its place in the alphabet. Then divide it by 10 and the remainder is your random number.

Another poster even "proves" this digit is random by showing a graph representing a flat distribution of digits after inputting thousands of common English words as seeds.

But when I tried this, I got a very UNFLAT distribution. 9 and 1 are TWICE as common as any other number except 3.

So, is there a practical way to manually (with pen and paper) generate a cryptographically-secure pseudo-random number using natural text as a seed?




Labels in a loop and random numbers, please help, I tried every things [on hold]

I'm studying java and i have a trouble...

I'm trying to do a loop with labels and random numbers. I want that the loop make the labels and choose 2 types of random number for each label. and the label should to be show on my GUI panel.

I'm stuck guys, please help-me

My main class:

public class randomNumbers {
    int labels[] = new int [30];
    int numbersType1[] = {0, 0};
    int numbersType2[] = {0, 0};   




public void randomNumbers(){

    Random rand = new Random();
    int s;
    int g = 1;    
    int c = 1;          
    for( c = 1; c <= labels.length; c++){

     for (g = 1; g <= 5 ; g++){
     numbers[0] = 1 + rand.nextInt(99);
     numbers[1] = 1 + rand.nextInt(99);
    }
     for (s = 0; s <= 2; s++){
     stars[0] = 1 + rand.nextInt(99);
     stars[1] = 1 + rand.nextInt(99);

           }   

    }}}

And now my Layout code:

private class generateNumberActionListener implements ActionListener {
    @Override
    public void actionPerformed(ActionEvent e) {
        randomNumbers rand = new randomNumbers();   
        String label = rand.numbers[0]+" "+rand.numbers[1]+ " "+rand.numbers[2]+" "+rand.numbers[3]+" "+rand.numbers[4]+" | *"+rand.stars[0]+" *"+rand.stars[1]+"\n";     
        int choise = Integer.parseInt(JOptionPane.showInputDialog("Put here"));
        int c;

        for (c =1; c <= choise; c++){
          labelShow1.setText(""I'M STUCK!!!")
        }
        }
        }




Is there any way to split a character stream generated from /dev/urandom to different substreams?

I need to take a high-speed stream of random numbers generated by a hardware device and split it to different sub-streams. For the testing purposes I considering /dev/urandom as a data source. Any help? The sum of sub-stream speeds should add up to initial stream speed ( or to be close ). The sub-streams are later sent to end user by creating a socket between netcat and /dev/tcp with usage of file descriptor 3 (or another).




Setting a random interval for Apple Script

I have just began my journey in learning Apple Script and I was wondering instead of having Apple Script type out with a delay of 3 seconds . I would like it to type out in a random interval of 1-10 seconds. Thank you for your assistance in advance

tell application "System Events" set textToType to "text here" delay 3

repeat
    delay 1
    keystroke textToType

    keystroke return
end repeat

end tell




Basic Java Array and For Loop

I am taking a Java class and have read the same explanation over and over and I just want to make sure I am understanding it correctly.

The example in the class they provide is a dice rolling game and they want to see the frequency of rolls per number.

The code snippet that I am uncertain on is this:

for(int roll = 1; roll < 1000; roll++){
    ++freq[1+rand.nextInt(6)];
}

I understand this part: 1+rand.nextInt(6)

But I don't understand this part: ++freq and how it tallys the results

I am understanding this as (with the example I rolled a 4):

for(int roll = 1; roll < 1000; roll++){
    ++freq[4];
    //all indexes in freq are == 0 to start
    //freq[4] is index 4 in the array. It was 0 but is now == to 1
    //freq[0], freq[1], freq[2], freq[3], freq[5], and freq[6] are all still == to 0
}

for(int roll = 1; roll < 1000; roll++){
    ++freq[6];
    //freq[6] is index 6 in the array. It was 0 but is now == to 1
    //freq[0], freq[1], freq[2], freq[3], and freq[5] are all still == to 0
    //freq[4] and freq[6] are both == to 1
}

Is this correct?




how the seed is chosen if not set by the user

For the purpose of reproductibility, one has to choose a seed. In r, we can use set.seed(). My question is, when the seed is not set, explicitely, how the computer chooose the seed? Why is there no default seed?




Retrieve random value from local storage

is possible to retrieve. print and then delete one random value from localstorage?

      var data = jQuery.parseJSON(data);

      data.forEach(function(dataItem){

          var id = dataItem.id;
          var orario = dataItem.orario;
          var casa = dataItem.casa;
          var trasferta = dataItem.trasferta;
          var matches = "<span id='matches_text'>"+orario+"</span> "+casa+" <br> "+trasferta+"";

          localStorage.setItem("matches_"+id+"", ""+matches+"");

          var matches = localStorage.getItem("matches_"+id+"");

      });

thanks




Powershell executionspeed Improvment

i`ve played around with some sorting algorithms written in powershell last night. Beforehand i hade to generate a Array of random ints so i have something i can sort. However, the time to generate the Array took me too long and so i improved my code to run as fast as possible. My final code looks like this:

$max = 1000000
$RndNumberArr = New-Object System.Collections.ArrayList
$ran = New-Object Random
for ($i = 0; $i -lt $max; $i++)
{ 
    [void]$RndNumberArr.Add($ran.Next(0,$max))    
}

I`ve noticed that using an ArrayList, is faster then using an Array with fixed Size (which dosent make much sense to me, is there something faster?) Also, using the .NET method random.Next(), instead of the CMDLet Get-Random improves the speed a good amount aswell. Are there any downsides of using the .NET methods? ALso i think that, using

[void]$RndNumberArr.Add($ran.Next(0,$max)) 

to prevent the Array.Add output ist slightly faster then using

$RndNumberArr.Add($ran.Next(0,$max)) > $null

am i right? The CMDLet is with a clear timedifference the slowest.

$RndNumberArr.Add($ran.Next(0,$max)) | Out-Null

Does my Computerhardware (CPU especially) effect the powershell execution speed or is the speed capped at some point? If so, is there a way to enhance the assigned system ressources for a speed improvment? Thanks a lot.




vendredi 24 août 2018

Function to get random double between [0,1]?

I tried to find a function to do so, only that I find is [0,1) math.random(). Need to be able to include 1 also. Any suggestions?




How to graph random points on ti-nspire cx

I am trying to plot random points on a 2d circle with a ti-nspire cx is there any on way I can do this?




Obtain values from multiple distributions with a single generator roll

I am trying to implement the Alias method, also described here. This is an algorithm which allows to sample from a weighted N-sided dice in O(1).

The algorithm calls for the generation of two values:

  • An uniformly distributed integer i in [0, N]
  • An uniformly distributed real y in [0, 1)

The paper specifies that these two numbers can be obtained by a single real number x between [0, N). From x one can then derive two values as:

  • i = floor(x)
  • y = x - i

Now, the other implementations that I have seen call for the random number generator two times, one to generate i and one to generate y. Given that I am using a fairly expensive generator (std::mt19937) and that I need to sample many times, I was wondering if there was a better approach in terms of performance, while preserving the quality of the result.

I'm not sure whether using an uniform_real_distribution to generate x makes sense as if N is large then y's distribution is going to get sparser as doubles are not uniformly distributed. Is there maybe a way to call the engine, get the random bits out, and then generate i and y from them directly?




replace in a text file the string "NNNNN" by a different random string in each line

I have a text file like this:

.....
GGCCAAGGTCTGACAACCCTAGGGCTTCAGCTTCCCGATATCCGACGGTAGTGTNNNNNAAAGCCTCAGAAAAAACG
GTGGGGCTCTCAAAGTGACTTTGTTAAAACTTCAGCTTCCCGATATCCGACGGTAGTGTNNNNNTGTTTTTGTTCCTCCT
GGGAGCAATACAACAGGTTCAATGGGTGCTTCAGCTTCCCGATATCCGACGGTAGTGTNNNNNAACACATGACACACTCA
CAGCCTCTGAGGAACCGCACCAGTCTTCAGCTTCCCGATATCCGACGGTAGTGTNNNNNGTGGCTTTTTGGTGTTTG
GTTTGTAGAGTGGGGTGGGCTTCAGTCGCTTCAGCTTCCCGATATCCGACGGTAGTGTNNNNNTCTTTATTTCTCTCCC
GCTGAGCTCAGTGGCTCACACCTGTAATCTTCAGCTTCCCGATATCCGACGGTAGTGTNNNNNAATCACATGCCACACA
GCCGTGCTGGAAGCCTTTGTCTATGACCTTCAGCTTCCCGATATCCGACGGTAGTGTNNNNNCTTTGGGTGGAGAGTT
.....

I need to replace every NNNNN by a different random string of five characters (using only A, C, T or G letters)

Thank you!




C# Random number keeps changing its numbers

Hello so I was trying to create this "game" where the computer guesses a number between 1 to 100, and you have to input the number you guess, and it will say its guessed number is lower than what the user said or higher, now the problem here is that each time the user inputs a number, the random number changes, i have tried many things, but i never got a result. Take a look at my code.

Random rnd = new Random();
        int cmptr = rnd.Next(1, 101);       
        Console.WriteLine("Computer: I chosen a number between 1 to 100, guess it.");
        Console.WriteLine("Chosen number is displayed just for testing purposes: " + cmptr + ")"); // for test purposes only
        int usr = (Convert.ToInt32(Console.ReadLine()));
        while (usr != cmptr)
        {
            if (usr < cmptr)
            {
                Console.WriteLine("Computer: Mine is Greater!");
            }
            else if (usr > cmptr)
            {
                Console.WriteLine("Computer: Mine is Lower!");
            }

            usr = Convert.ToInt32(Console.ReadLine());
        }

        Console.WriteLine("Computer: Congrats you beat me!");




Array with random integers

I need and array that generates 10 random numbers between 1 and 5, inclusive. I then need to display the number of times 1-5 shows up in the array. This is what I have so far, it runs fine, it's just that the number of occurrences for the numberes 1-5 totals different everytime, which it should total exactly 10 everytime since the array can only hold 10 integers.

public static void main(String[] args){
    //create an array that will produce 10 numbers
    int[] randArray = new int[10];

    //initialize randArray to the values 1-5
    for(int i = 0; i < 6; i++){
        randArray[i] = (int)(Math.random() * (6 - 1)) + 1;
    }

    System.out.println("Number\t" + "Appears");

    for(int x = 1; x < 6; x++){
        System.out.println(x + "\t" + randArray[x]);
    }
}




Golang generate randon string produces same string after compile and run

I'm not sure if the title is adequate or not but I'm experiencing some strangeness in trying to generate a random string of fixed length.

I have set up a code playground as an example of what I'm talking about. You can hit "Run" as much as you like and the same "random" string will be printed. What am I doing wrong or how to generate random string at each call?

Also, here's the code I used (for history):

package main

import "fmt"
import "time"
import "math/rand"
import "encoding/base64"

// GenerateRandomBytes returns securely generated random bytes.
// It will return an error if the system's secure random
// number generator fails to function correctly, in which
// case the caller should not continue.
func GenerateRandomBytes(n int) ([]byte, error) {
    b := make([]byte, n)
    _, err := rand.Read(b)
    // Note that err == nil only if we read len(b) bytes.
    if err != nil {
        return nil, err
    }

    return b, nil
}

// GenerateRandomString returns a URL-safe, base64 encoded
// securely generated random string.
// It will return an error if the system's secure random
// number generator fails to function correctly, in which
// case the caller should not continue.
func GenerateRandomString(s int) string {
    b, _ := GenerateRandomBytes(s)
    return base64.URLEncoding.EncodeToString(b)
}

func main() {
    rand.Seed(time.Now().UnixNano())
    fmt.Print(GenerateRandomString(12))
}




How can I make my array choose different choices each time it runs?

Right now, I have an array with three options. I have a function set up so it chooses one option each time, but sometimes it repeats outputs. Is there a way to make it not repeat?

<!DOCTYPEhtml>
<html>
<head>
    <meta charset="utf-8"/>
    <title>Tester</title>
    <script type="text/javascript">

        var colors = ['#ce0e0e', '#079b0c', '#3e3fd6'];

        function changeColor(){
            var randomColor = colors[Math.floor(Math.random() * colors.length)];
            while (myDiv.style.backgroundColor == randomColor)
                randomColor = colors[Math.floor(Math.random() * colors.length)];

            myDiv.style.backgroundColor = randomColor;
        }
    </script>
    <style>
        .divClass {
            width:300px;
            height:300px;
            border: 1px solid black;
            border-radius:1000px;
            background-color:transparent;
        }
    </style>
</head>
<body>

    <div class=divClass id="myDiv" style="border:6px solid black;">
    </div>

    <input id=button type=button value="chagne color" onclick='changeColor()'>

</body>
</html>




thread is not a member of std c++

I'm having this problem where i can't use threads because i keep getting the error "'thread' is not a member of 'std'".

I am using MinGW with c++11 as a compiler flag.. On the little program i made yesterday it worked fine. Basically i want to play a "beep"-song while playing a little guessing game with pseudo random numbers.

int rnumber, guess, maxrand;

std::thread t1(pinkpanther);
t1.detach();

cout << "What do you want the maximum Number to be? ";
cin >> maxrand;

rnumber = randy(maxrand);

//Start
cout << endl << "This is a game!" << endl << "You have 5 tries to guess the random number generated by this program, have fun" << endl;

for (int i = 0; i < 5; i = i + 1)
{
    cout << "Your guess: ";
    cin >> guess;

    if (guess < rnumber)
    {
        cout << "Your guessed number is smaller than the answer! Try again!" << endl << endl;
    }
    else if (guess > rnumber)
    {
        cout << "Your guessed number is bigger than the answer! Try again!" << endl << endl;
    }
    else
    {
        cout << "you guessed the right number!";
        break;
    }
}





return 0;

it always gives me the same error ||In function 'int main()':| 'thread' is not a member of 'std'| 't1' was not declared in this scope| ||=== Build failed: 2 error(s), 0 warning(s) (0 minute(s), 0 second(s)) ===| and i really dont know why anymore

Edit: pinkpanther() just plays the pinkpanther song i found in "beeps"




Equivalent C++ implementation of MATLAB's rng(seed, 'twister') function

I'm trying to come up with equivalent ways to generate uniform random variables in MATLAB and C++. In MATLAB, it's straightforward to use the generator rng(0, 'twister') to use seed 0 and the Marsenne Twister engine. And then, for example, 5 uniform random numbers can be produced using rand(5,1). According to MATLAB's rand documentation, it uses the mt19937 engine.

I'm struggling to replicate this in C++. I've used the following code:

#include <iostream>
#include <cmath>
#include <random>

static std::random_device rd;
static std::tr1::mt19937 rand_mt(rd());

int main(void)
{
    rand_mt.seed(0);
    for (int i = 0;i < 5;i++)
    {
        std::cout << (double)rand_mt() / ((double)rand_mt.max() - 
        (double)rand_mt.min()) << std::endl;
    }
    return 0;
}

It's a very long shot, but I'm not getting the same outputs from MATLAB and C++. Any problems with the above code that I need to address? Or is there an alternative equivalent implementation in C++?




How to add a random number to a specific column in matlab function block?

I want to create a array 3X2 in Matlab function block that will contains static numbers. As an input on this block i will connect a random number generator and this values i would like to add only in the second column. Please tell my someone how I can do this.

With best regards!




Combining PRNG and 'true' random, fast and (perhaps) dumb way

Take fast PRNG like xoroshiro or xorshift and 'true' entropy based generator like /dev/random.

Seed PRNG with 'true' random, but also get a single number from 'true' random and use it to XOR all results from PRNG to produce final output.

Then, replace this number once a while (e.g. after 10000 random numbers are generated).

Perhaps this is naive, but I would hope this should improve some aspects of PRNG like period size and predictability with negligible impact on speed. What am I getting wrong?




jeudi 23 août 2018

How to have different seeds for random generation in Simulink?

I have a model in Simulink that uses the Random Number block. This Random Number block uses a Seed value for the generation of random values. Now if I have multiple copies of my model:

main.slx
    |
    |-----> child_1.slx (Random Number block inside)
    |
    |
    |-----> child_2.slx (Random Number block inside)
    |
    |
    |-----> child_3.slx (Random Number block inside)

How can I set the Seed of Random Number to be different in each copy?




Restricting numpy.random.lognormal to a given range, Python

I'm trying to sample a random number using a log normal distribution fitted to a data set of ages.

Age_abscess = numpy.random.lognormal(mean=numpy.log(29.9090909),
              sigma=numpy.log(11.6574484),size=None)

I sometimes get answers to the tune of something ^23 and smaller than 1. Given that I want these to be ages, is there a way to restrict the draw to be between 0 and 100?




Random alphanumeric string in JavaScript

I have to generate random alphanumeric sting in JavaScript like A123B456 or B001A556 (upper case letter, three numbers from 0-9, upper case letter, three numbers from 0-9). This code should be randomly generated and should be unique. Any idea is appreciated.




Random numbers in Racket

I'm trying to generate random numbers from 0 to 1, including the borders 0 and 1 in Racket. Until now I didn't find a solution. Is there a nice way ?




mercredi 22 août 2018

How to select a random number from two vectors with matching indices

I am trying to select a random number from two vectors, but they need to have matching indices. For example, if a random number in vs vector is 2, then the number selected from vd vector needs to be 7. Thanks!

extern crate rand;

use rand::Rng;

fn main() {
    let vs = vec![0, 1, 2, 3, 4];
    let vd = vec![5, 6, 7, 8, 9];
    let mut ww = Vec::with_capacity(2);
    let mut qq = Vec::with_capacity(2);
    let sample_num = 2;
    let mut num_sam = 0;
    while sample_num > num_sam {
        let mut ff = rand::thread_rng().choose(&vs);
        let mut cc = rand::thread_rng().choose(&vd);
        let mut index = vs.iter().position(|&r| r == ff).unwrap();
        let mut index1 = vd.iter().position(|&r| r == cc).unwrap();
        if index == index1 {
            ww.push(ff);
            qq.push(cc);

        }
        num_sam += 1;
    }

    println!("{:?}, {:?}", ww, qq)
}




How Can I Set the lenght, max value and random value in a array?

I need to do an array in C# and sets it's length and max and min value before giving it a random value. For example:

The First time it runs it can give this value, as you can see, the array lenght is of 10 numbers, and this numbers aren't bigger than 10.

1234567890

The second time, it can give something like this:

7892563048

It respect the rules before mentioned, but, with random numbers, do you know how can I do this?




generate uniformly distributed 3D coordinates between 0 and 1 using python

I would like to write a python script to generate a uniformly distributed 3D coordinates (e.g., x, y, z) where x, y, and z are float numbers between 0 and 1. For the moment, z can be fixed, thus what I need is a uniform distributed points in a 2D (x-y) plane. I have written a script to do this job and checked both x, and y are uniform numbers. However, I am not sure if these points are uniformly distributed in (x-y) plane.

My code is

1 import matplotlib.pyplot as plt
2 import random
3 import numpy as np
4 import csv
5 nk1=300
6 nk2=300
7 nk3=10
8 kx=[]
9 ky=[]
10 kz=[]
11 for i in range(nk1):
12     for j in range(nk2):
13         for k in range(nk3):
14             xkg1=random.random()
15             xkg2=random.random()
16             xkg3 = float(k)/nk3
17             kx.append(xkg1)
18             ky.append(xkg2)
19             kz.append(xkg3)
20 kx=np.array(kx)
21 count, bins, ignored = plt.hist(kx, normed=True)
22 plt.plot(bins, np.ones_like(bins), linewidth=2, color='r')
23 plt.show()

The plot shows both "kx", and "ky" are uniformly distributed numbers, however, how can I make sure that x-y are uniformly distributed in the 2D plane?




Split given rectangle into N given rectangles

I am trying to develop a python program that solves the following problem:

I have two given rectangles of width and height given, let's say: W1*H1 and W2*H2; I want to "cut-out" N given rectangles, which widths and heights are given as well, let's say: w_i and h_i for i in range(1, N). The orientation of the rectangles is interchangeable: w_i and h_i can be switched for every i.

I'm sure that my set of smaller rectangles all fit in the two bigger rectangles (the sum of the areas of the two big ones is bigger than the sum of the N small ones). The result should be a graph which shows me the (random) disposition of all the cut-outs... the best solution would be to maximize the "left-over" area, although it is fine if it comes out randomly (I figured I could just do it many-many times at pick the more suitable result).

I know it's not an easy question and I really hope someone can help, thanks in advance!