mardi 31 mai 2016

Why does my random number generator always give me one?

I'm working on a project that will give me a random town wealth depending on what number is randomly generated. Yet whenever I press the "establish township" button, I always get "wealthy". How can I fix my code to enable desired results?

<!DOCTYPE html>
<html>
<body>
<style>
h1 {font-size: 20pt; color: red;}
    p {font-size: 17pt; color: blue;}
    p2 {font-size: 18pt; color: orange;}
    p3 {font-size: 18pt; color: green;}
</style>
<p>This program will create a random town upon the click of a button.</p>

<button onclick="numberdescription()">Establish Township</button>
<br /><br /><br />
<p3 id="random"></p3>

<script>

function numberdescription() {
var num = Math.floor(Math.random() * 3 + 1)
    if (num = 1) {
        desc = "wealthy";
    } else if (num = 2) {
        desc = "middle wealth";
    } else {
        desc = "dirt poor";
    }
document.getElementById("random").innerHTML = desc;
}
</script>

</body>
</html>




How to scale pseudo random numbers to a specific range?

How would I scale random numbers to say 1-10 whithout loosing the randomness?

I know, just using % 10 is not a good idea.

And in addition, I need a seed value, so I can test on determinsitic numbers,

but I have not understood what value this seed should have and I how it influences the sequence.

Is there a difference if it is high or low ?

thanks in advance.




Android : how to generate unique random numbers in an array and perform bubble sort

The following is my code but it doesn't generate unique random numbers

Random rand = new Random();

            int[] array = new int[n];

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

                array[i] = rand.nextInt(n)+1;

              }




            for (int i = 0; i < ( n - 1 ); i++)
            {
                for (int j = 0; j < n - i - 1; j++) {
                    if (array[j] > array[j+1])        {
                        int temp = array[j];
                        array[j]   = array[j+1];
                        array[j+1] = temp;
                    }
                }
            }




Javascript random generator

I created a random number generator in javascript whose values are in an array. The code is that one

function GetValue()
{
    var names= new Array(1,2,3,4,5);
    var random = names[Math.floor(Math.random() * names.length)];
    //alert(random);
    document.getElementById("message").innerHTML=random;
}
<p>number generator</p>  
<form class="form">
        <div class="form-group">
      <input type="button" id="btnSearch" value="Generatore" onclick="GetValue();"   class="btn btn-default"/>
<p id="message" ></p>
            </div>
        </form>

I'd like to know if it is possible to give a different text in the p tag according to the number generated by the button. Thanks very much and sorry if there is any english error




Laravel - Paginate Random records

How we can paginate through random records in laravel? for example:

$products = Product::all()->orderBy(DB::raw('RAND()'));
$products->paginate(4);
$products->setPath('products');

Above will ends in duplicate records, because of random order. How can I persist the $products object so that, when a new page request made, it should filter though same/fixed random record set ?




How can I run the randomness test suite (NIST SP 800-22) in Visual Studio 2012

I am stuck and do not know how to run NIST SP 800-22 in Visual Studio 2012 (in MS Windows) without errors. The source code is at http://ift.tt/1PeYYg8.

I would greatly appreciate it if someone could explain it in detail and make it understandable by a dummy like me.




Calculating pi by throwing darts (python 2.7)

Can´t find the problem with this code, at the end its supossed to print pi but it print numbers close to 2 instead

import random
def kasta_pil():
    x = random.random()
    y = random.random()
    return (x, y)
def inne_i_cirkel(x, y):
    if x + y <= 1:
        return True
    else:
        return False
while True:
    try:
        z = int(raw_input("Hur många pilar vill du kasta: "))
    except ValueError:
        print "Invalid input"
        continue
    if z < 1:
        print "Måste vara åtminstone 1"
    else:
        break
pilar_i_cirkel = 0.0
for i in range(z):
    x, y = kasta_pil()
    if inne_i_cirkel(x, y):
        pilar_i_cirkel = pilar_i_cirkel + 1
print "Pi är ungefär: ", (pilar_i_cirkel / z) * 4




lundi 30 mai 2016

Shuffle elements in a string and get all the possible arrangements

This is what I want to do, when given a list, I want to shuffle the elements in the list and get all the possible combinations of elements in that list. E.g. given a list as shown below,

    Ben went to the shop

so listing and printing all the possible combinations,

    shop went to the Ben
    went to the Ben shop
    to the went shop Ben
            .
            . 
            .

How do I get all the possible combinations and print them out one string at a time?




Why are the "normal" methods for generating random integers so slow?

Not a maths major or a cs major, I just fool around with python (usually making scripts for simulations/theorycrafting on video games) and I discovered just how bad random.randint is performance wise. It's got me wondering why random.randint or random.randrange are used/made the way they are. I made a function that produces (for all intents and actual purposes) identical results to random.randint:

big_bleeping_float= (2**64 - 2)/(2**64 - 2)
def fastrandint(start, stop):
  return start + int(random.random() * (stop - start + big_bleeping_float))

There is a massive 180% speed boost using that to generate an integer in the range (inclusive) 0-65 compared to random.randrange(0, 66), the next fastest method.

>>> timeit.timeit('random.randint(0, 66)', setup='from numpy import random', number=10000)
0.03165552873121058

>>> timeit.timeit('random.randint(0, 65)', setup='import random', number=10000)
0.022374771118336412

>>> timeit.timeit('random.randrange(0, 66)', setup='import random', number=10000)
0.01937231027605435

>>> timeit.timeit('fastrandint(0, 65)', setup='import random; from fasterthanrandomrandom import fastrandint', number=10000)
0.0067909916844523755

Furthermore, the adaptation of this function as an alternative to random.choice is 75% faster, and I'm sure adding larger-than-one stepped ranges would be faster (although I didn't test that). For almost double the speed boost as using the fastrandint function you can simply write it inline:

>>> timeit.timeit('int(random.random() * (65 + big_bleeping_float))', setup='import random; big_bleeping_float= (2**64 - 2)/(2**64 - 2)', number=10000)
0.0037642723021917845

So in summary, why am I wrong that my function is a better, why is it faster if it is better, and is there a yet even faster way to do what I'm doing?




Randomizing List in Python3.3 [duplicate]

This question already has an answer here:

Hi guys I am a student trying to create a program for a nonprofit organization but need some help.

I want to randomize a list that I have

trained = ['name1,email1','name2,email2','name3,email3','name4,email4']

I need this so that everytime I run the program the values (the names and their corresponding emails) are random. This way it will print in a different order from the original list.Please note that the actual list does not have numbers like the list above, rather it has names and email addresses.

Thank you in advance!




Random Generator in Assembly

algorithm writes random numbers between 0 and 255, to the ram. I tried to write an algorithm that every chromosome consists of 4 random number. And there must be 4 bytes of data between every 4-byte data. There must be 20 chromosomes, that is 20x4=80 random numbers. Like:(photo)enter image description here

code: http://txt.do/5bm6h




Randomly select from a string array and set equal to variable

I want to randomly select a word from a string array and set it equal to a variable, doing this 10 times, each time getting a different word from the array and setting it equal to a different variable. Can anyone help?

string v1, v2, v3, v4, v5, v6, v7, v8, v9, v10;

string words[] = {"WORD1", "WORD2", "WORD3", "WORD4", "WORD5", "WORD6", "WORD7", "WORD8", "WORD9", "WORD10";




how does rewinding on dieharder work?

The manpage for Dieharder seems to say that if the sequence of random numbers that you give it is too short, it will "rewind" the list until it has enough numbers to test on. If I give it a 10000 number list, it rewinds 1384 times, but if I give it a 100000000 number list, it rewinds 13840006 times on the birthdays test. What am I missing?




Using a random long to generate random doubles

I'm implementing my own random number generator, and the algorithm I'm using naturally gives me a nextLong() method. However, using this core method, I need to implement the other standard methods, such as nextLong(long), nextInt(), nextDouble(), and so on, in terms of nextLong(). For example:

public long nextLong(long n) {
    long bits, val;
    do {
        bits = (nextLong() << 1) >>> 1;
        val = bits % n;
    } while (bits - val + n - 1 < 0L);
    return val;
}

public int nextInt() {
    return (int)nextLong();
}

How can I implement nextDouble?




Shuffle method results in repeating pattern?

I have an array of JButtons with String filenames set on them as text (t's a little hard to explain but the filenames specify the images, so when I want to set an icon for a specific button, I have a method to pull the filename text from the button and use it to setIcon). The String filenames are stored in a String array, and I'm trying to shuffle the Strings around but the problem is when I run my program the filenames aren't shuffled properly. They do have random positions, but I have 24 matching pairs of filenames and the matching ones are always 3 buttons apart from each other every time I run it, which is clearly not random. Does anyone know why this is happening? I doubt it's a problem with my setFace method because I'm using the shuffled array.. help would be appreciated!

public void shuffle()
{
  for(int i = 0; i < 24; i++) 
   {
        int rand = (int)(Math.random() * 24);
        temp[i] = country[rand]; //temp is a temporary array
        country[rand] = country[i];//country is the filename array
        country[i] = temp[i];
   }

  card.setBack(cards); 
  card.setFace(country, cards); //cards is the 48 button array
 }

public void setFace(String[] file, JButton[] buttons) //filename method
{
  for(int i = 0; i < 24; i++)
  {
     buttons[i].setText(file[i]);
  }
  int ct = 0;
  for(int x = 24; x < 48; x++)
  {
     buttons[x].setText(file[ct]);
     ct++;
  }
}

public void setBack(JButton[] array) //sets back icon of card
{
  icon = new ImageIcon(this.getClass().getResource("back.png"));
  img = (icon.getImage().getScaledInstance(75, 95, java.awt.Image.SCALE_SMOOTH));
  thomas = new ImageIcon(img);

  for(int x = 0; x < array.length; x++)
  {
     array[x].setIcon(thomas);
  }
}

The non-random arrangement that I'm talking about is like this:

Card A     Card R
Card D     Card H
Card F     Card Z
Card A     Card R
Card D     Card H
Card F     Card Z




Generate random number of fixed length keeping with leading zeroes in R

I would like to accomplish something very similiar to this question but in R.

In essence, I want to generate a sequence of random numbers with a fixed length (say, 4), and if the numbers are less than 4 digits in length then they will have leading zeroes.

For example, a random sequence which could include 0000, 0001.... 9999. Such numbers could be suited to be used as ID numbers for example - but they must be integers, not strings.

I know that I can use sample(0:9999, n, replace = TRUE where n is the number of repetitions, however this creates the possibility of numbers that are less than 4 digits in length.

In addition, I'm aware of a method using sprintf() that adds two leading zeroes and converts to a string, but this won't suit my needs.

I am new to R.




Elm - Random Number on init strange behaviour

Just working through the samples, and got the exercise about creating 2 random dice and rolling them with a button.

http://ift.tt/1OXsKk5

So I thought I would create the dice as a module, remove the roll action, and just have it create a D6 value on init.

So my code is now as follows (should open direct in elm-reactor)

module Components.DiceRoller exposing (Model, Msg, init, update, view)

import Html exposing (..)
import Html.App as Html
import Html.Attributes exposing (..)
import Html.Events exposing (..)
import Random
import String exposing (..)

main =
    Html.program
        { init = init
        , view = view
        , update = update
        , subscriptions = subscriptions
        }



-- MODEL


type alias Model =
    { dieFace : Int
    }


init : ( Model, Cmd Msg )
init =
    ( Model 0, (Random.generate NewFace (Random.int 1 6)) )



-- UPDATE


type Msg
    = NewFace Int


update : Msg -> Model -> ( Model, Cmd Msg )
update msg model =
    case msg of
        NewFace newFace ->
            ( Model newFace, Cmd.none )



-- SUBSCRIPTIONS


subscriptions : Model -> Sub Msg
subscriptions model =
    Sub.none



-- VIEW


dieFaceImage : Int -> String
dieFaceImage dieFace =
    concat [ "/src/img/40px-Dice-", (toString dieFace), ".svg.png" ]


view : Model -> Html Msg
view model =
    let
        imagePath =
            dieFaceImage model.dieFace
    in
        div []
            [ img [ src imagePath ] []
            , span [] [ text imagePath ]
            ]

The problem with this is that it is always producing the same value. I thought I had a problem with the seed to begin with, but if you change

init =
    ( Model 0, (Random.generate NewFace (Random.int 1 6)) )

init =
    ( Model 0, (Random.generate NewFace (Random.int 1 100)) )

it works exactly as intended. So it looks like the default generator is not working with small values, seems to work as low down as 10.

The odd thing is this, in this example (which i started with) http://ift.tt/1OXsKk5 , it works fine with 1-6 when it's not in init.

So my question is, am I doing something wrong, or is this just a wrinkle in elm? Is my usage of the command in init ok?

In the end, I put this in to get the desired effect, which feels wonky.

init =
    ( Model 0, (Random.generate NewFace (Random.int 10 70)) )

with

    NewFace newFace ->
        ( Model (newFace // 10), Cmd.none )




dimanche 29 mai 2016

C++ File Input/Output Outputting Numbers Instead of Chars

I have created a program that randomly assigns roles(jobs) to members of a certain house using file input / output.. It builds successfully, but when using cout and I actually see the results, I can see why the program is not working.

Here is the snippet of code I believe something is wrong with :

  std::string foo = std::string("Preferences/") + std::to_string(members[random]) + "-Preferences";
  cout << foo << endl;

And here is the members[random] array, it is randomly selecting members from this array and reviewing their available times and assigning them jobs based on their Preference input file.

unsigned const char members[22] = 
{   'a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v'  };

I have created a random number picker that goes through 0-21 and assigns the value it creates to variable random. So, in essence, it is members[random] and completely random.

Here is the output I get in my terminal.

Preferences/116-Preferences

But I set the output to do Preferences/ member[random] -Preferences. It is accessing a number and not my array chars.

I created a cout << members[random]; right below it, and every time I run the program, I get

  Preferences/107-Preferences   <---- A random number every time

  k                   <---- random letter every time.

So I know it must be accessing my random functions, but assigned it to numbers! How do I fix this so my proper output can be :

 Preferences/t-Preferences

Please help me, and thanks!




Should I use randint?

The randint proposal is supposed to provide an intuitive interface for getting random integral numbers. The problem however is that it uses default_random_engine and so far has no way of letting you specify the engine it uses. libstdc++ and libc++ both use minstd_rand which is a LCG, which I've read creates poor quality numbers. MSVC uses mt19937 which seems to be the most common on this site.

Is this a big negative of randint?




Variable in Parentheses C++

I am currently in the process of writing up a C++ program that randomly chooses roles for people using file input/output.

I am almost done, and I build often to make sure my code is working and not psuedocode. I received an error on my snippet of code -

randomPrefs.open ("Preferences/"members[random]"-Preferences");

I am trying to access the text file in Preferences/foo-Preferences, and the variable is made random by some code above it. I have couted the random snippet and it works perfectly, so I need not include it here. The error I get is :

Avalon - Omnipotent.cpp:61:21: error: unable to find string literal operator 'operator""members' with 'const char [13]', 'unsigned int' arguments

And so, I have searched around for this error but have found nothing. I thought of making a mini-parentheses around it, and it resulted in a different error - Avalon - Omnipotent.cpp:61:51: error: expression cannot be used as a function

Any help would be appreciated.

A little note down here, when not having the parentheses around it, I get a warning about my variable not being used -

Avalon - Omnipotent.cpp:39:21: warning: unused variable 'members' [-Wunused-variable]

However, the second error does not give a warning about the unused variable.

Hey is what my variable looks like:

 unsigned const char members[22] = 

And I assigned the value "random" which selects a random number from 0 - 21 and I assign the number generated to value random, and declare the variable as members[random]. It works perfectly, I just need help with these errors.

Help!




Randomizing nodes in linked list, C program

the following function is part of sort of a game with questions and answers. I have a problem with the randomization of the questions by their complexity-some questions appear more than once and the first also appears in every level, which should not happen. Please help!

typedef struct
{
    char question[300];
    char date[30], author[30], ansr1[80], ansr2[80], ansr3[80], ansr4[80];
    int id, correctAnsr, level;
} game;

typedef struct Node
{
    game data;
    struct Node* next;
}  node;

void printRandom1(node *head)
{
    if (isEmpty(head))
        return;

    srand(time(NULL));

    node *result = head->data.question;

    node *current = head;
    int n;
    for (n = 17; current != NULL; n++)
    {
        if (rand() % n == 0 && current->data.level == 0)
            result = current->data.question;
        current = current->next;
    }
    printf("%s\n", result);
    int i, ans;

    printf("1.-%s\n", result->data.ansr1);
    printf("2.-%s\n", result->data.ansr2);
    printf("3.-%s\n", result->data.ansr3);
    printf("4.-%s\n", result->data.ansr4);

    printf("Enter the correct answer: ");
    scanf("%d", &ans);
    if (ans == result->data.correctAnsr)
        printf("CORRECT ANSWER!\n");
    else
    {
        printf("WRONG ANSWER\n");
        printf("GAME OVER");
        printf("The correct answer is: %d\n", result->data.correctAnsr);
        return menu();
        exit(1);
    }
}




setTextColor depending on random String from array - Android

I have a String array with color names and an array with colors:

String[] words = new String[] {"yellow", "white", "green"};
int[] colors = new int[] {Color.YELLOW, Color.WHITE, Color.GREEN};

My TextView is set to one of these words randomly and now I want to set the text color to yellow if yellow was chosen, etc. I tried this with an if statement, but it keeps showing only black words.




Fast source of high quality randomnes

Evolution algorithm is highly dependant on good randomnes. Unfortunatelly, good randomness sources are slow (and hence the AI).

Question is, If I take one hight quality number and use it as a seed for poor quality (but fast) random generator, how much 'random' will be result?




Mysqli outputting 10 random rows

I would like to retrieve 10 random rows from my database, each time i refresh the page i want the random rows to change.

I have made a query and a while loop to output all 10 results however i am just getting a blank page in return, there is no errors, nothing....

Its probably something silly i have missed out, but i just cant find it.

Here is my PHP :

<?php
include '../dbconnect.php';


$res = $conn->query("SELECT id FROM messages ORDER BY RAND() LIMIT 10");
while($row=$res->fetch_array())
{

 echo $row['id'] . "<br>";

}


?>

Thankyou for any help




Obtaining Random Numbers from irregular Ranges

I want to get a random number from (0,2,6,8,4) or such ranges. Currently I loop till I get appropriate Num.

boxNum = getRandomNum(0, 8);

  while (boxNum == 1 || boxNum == 3 || boxNum == 5 || boxNum == 7))
    boxNum = getRandomNum(0, 8);

Is there any other way to do this?? The while loop crashes the page after some turns.




How to get the distribution name from a spicy.stats. frozen distribution?

Access to a Frozen Distribution's Name

When creating a frozen distribution from the scipy.stats package, how can the distribution's name be accessed once the distribution instance is frozen? Trying to access the .name attribute produces an error since it is no longer an attribute of the rv variable.

import scipy.stats as stats

# Get the name of the distribution
print 'gamma :', stats.norm.name

# Create frozen distribution
rv = stats.norm()

# Get the name of the frozen distribution
print 'rv    :', rv.name


gamma : norm
rv    :

 ---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
      9 
     10 # Get the name of the frozen distribution
---> 11 print 'rv    :', rv.name

 AttributeError: 'rv_frozen' object has no attribute 'name'




Don't understand how Math.random() works in java

Why does the following code prints just 25?

while(true) {
    int pos = (int) (Math.random() * (26 ));
    if (pos > 24)
        System.out.println(pos);
}

If Math.random() returns a number from 0 to 1 then shouldn't the code above print also 26 (1*26 = 26)?




MPI send and receive in random mode

i'm tring to make each process to send random value to two random destination ,destination1 and destination2 .each process print what send and receive.

this is code:

   #include "mpi.h"
               #include "head.h"
               #include<iostream>
               #include <random>
               #include <vector>
               #include <time.h>


               int main(int argc, char *argv[])

               {

                   int my_rank,rc,destination1,destination2,numpros,count=0,tag;

                   rc = MPI_Init(&argc,&argv);
                   if (rc != MPI_SUCCESS) 
                   {
                     printf ("Error starting MPI program. Terminating.\n");
                     MPI_Abort(MPI_COMM_WORLD, rc);
                   }

                   MPI_Comm_size(MPI_COMM_WORLD,&numpros);
                   MPI_Comm_rank(MPI_COMM_WORLD,&my_rank);
             MPI_Status status; 
            MPI_Request reqs;
                    double buffer=rand() % 6;
                     do {
                          destination1=rand() % numpros;
                          destination2=rand() % numpros;
                      } while ((destination1 == my_rank) && (destination2==my_rank)&&(destination1!=destination2)); //Prevent sending to self
             MPI_Isend(&buffer,1,MPI_INT,destination1,tag,MPI_COMM_WORLD,&reqs);

             MPI_Isend(&buffer,1,MPI_INT,destination2,tag,MPI_COMM_WORLD,&reqs);
            count++;
            vector<head*>array_data;
            for(int i ;i<count,i++){
               array_data[i]=new head;
               array_data[i]->rank=my_rank;
               array_data[i]->rank1=destination1;
               array_data[i]->rank2=destination2;
            }
            MPI_Bcast(&array_data,array_data.size(),MPI_INT,my_rank,MPI_COMM_WORLD);
            for(int j=0,j<array_data.size();j++){
              if(array_data[j].rand1==my_rank||array_data[j].rand2==my_rank)
                 source=array_data[j].rank;
               MPI_Recv(&buffer,1,MPI_INT,source,MPI_ANY_TAG,MPI_COMM_WORLD,&status);
            }

            MPI_Waitall(numprocs, reqs, status);
            printf("process :%d \t\n sent %d to  %d\t\n to %d \n",my_rank,buffer,destination1,destination2);
            printf("process %d  recived %d from %d\n",source,buffer,my_rank);
            MPI_Finalize();
               }

elements of stuct are:

    stuct head {
            int rank;
            int rand1;
            int rand2;
            };

every time i execute program show this error: anysome can help me ?




function random on matlan for quaterions numbers

i need to generate a random quaterions on matlaab between

rand(varargin{i+1}, varargin{i}+1)

but those number must be quaterionic that me the format [a b c d ] for example [1 2 3 4 ] i don't know if it possible on matlab thank u

i need to generate a random quaterions on matlaab between

rand(varargin{i+1}, varargin{i}+1)

but those number must be quaterionic that me the format [a b c d ] for example [1 2 3 4 ] i don't know if it possible on matlab thank u




Perlin Noise algorithm does not seem to produce gradient noise

I am attempting to implement Perlin Noise in c++.

Firstly, the problem (I think) is that the output is not what I expect. Currently I simply use the generated Perlin Noise values in a greyscaled image, and this is the results I get: Perlin Noise Algorithm Output

However, from my understanding, it's supposed to look more along the lines of: Expected Perlin Noise Output

That is, the noise I am producing currently seems to be more along the lines of "standard" irregular noise.

This is the Perlin Noise Algorithm I have implemented so far:

float perlinNoise2D(float x, float y)
{
    // Find grid cell coordinates
    int x0 = (x > 0.0f ? static_cast<int>(x) : (static_cast<int>(x) - 1));
    int x1 = x0 + 1;
    int y0 = (y > 0.0f ? static_cast<int>(y) : (static_cast<int>(y) - 1));
    int y1 = y0 + 1;

    float s = calculateInfluence(x0, y0, x, y);
    float t = calculateInfluence(x1, y0, x, y);
    float u = calculateInfluence(x0, y1, x, y);
    float v = calculateInfluence(x1, y1, x, y);

    // Local position in the grid cell
    float localPosX = 3 * ((x - (float)x0) * (x - (float)x0)) - 2 * ((x - (float)x0) * (x - (float)x0) * (x - (float)x0));
    float localPosY = 3 * ((y - (float)y0) * (y - (float)y0)) - 2 * ((y - (float)y0) * (y - (float)y0) * (y - (float)y0));

    float a = s + localPosX * (t - s);
    float b = u + localPosX * (v - u);

    return lerp(a, b, localPosY);
}

The function calculateInfluence has the job of generating the random gradient vector and distance vector for one of the corner points of the current grid cell and returning the dot product of these. It is implemented as:

float calculateInfluence(int xGrid, int yGrid, float x, float y)
{
    // Calculate gradient vector
    float gradientXComponent = dist(rdEngine);
    float gradientYComponent = dist(rdEngine);

    // Normalize gradient vector
    float magnitude = sqrt( pow(gradientXComponent, 2) + pow(gradientYComponent, 2) );
    gradientXComponent = gradientXComponent / magnitude;
    gradientYComponent = gradientYComponent / magnitude;
    magnitude = sqrt(pow(gradientXComponent, 2) + pow(gradientYComponent, 2));

    // Calculate distance vectors
    float dx = x - (float)xGrid;
    float dy = y - (float)yGrid;

    // Compute dot product
    return (dx * gradientXComponent + dy * gradientYComponent);
}

Here, dist is a random number generator from C++11:

std::mt19937 rdEngine(1);
std::normal_distribution<float> dist(0.0f, 1.0f);

And lerp is simply implemented as:

float lerp(float v0, float v1, float t)
{
    return ( 1.0f - t ) * v0 + t * v1;
}

To implement the algorithm, I primarily made use of the following two resources:

Perlin Noise FAQ Perlin Noise Pseudo Code

It's difficult for me to pinpoint exactly where I seem to be messing up. It could be that I am generating the gradient vectors incorrectly, as I'm not quite sure what type of distribution they should have. I have tried with a uniform distribution, however this seemed to generate repeating patterns in the texture!

Likewise, it could be that I am averaging the influence values incorrectly. It has been a bit difficult to discern exactly how it should be done from from the Perlin Noise FAQ article.

Does anyone have any hints as to what might be wrong with the code? :)




samedi 28 mai 2016

wget link from random line in file

I'm trying to download a website that uses semi-predictable urls, meaning the url will always end with a random five character alphanumeric string. I created a file with crunch with the random string by using the command:

crunch 5 5 abcdefghijklmnopqrstuvwxyz123456789 > possible_links

Then I created a bash file to call the lines and wget the links:

#!/bin/bash
FILE=possible_links
while read line; do
        wget -q --wait=20 http://ift.tt/1X4E5rb}
done

but obviously it is going to go to aaaaa, then aaaab, then aaaac, aaaad, etc etc, is there a way to make it go to random lines?




Getting a random set of words from file

I am making a "mini-game" project and I need to retrieve a random set of 10 words from a file I made. The words (around 30) are separated by the return key in the text file. The code retrieves 10 words like it's supposed to, but I need it to start at a random point within the text file.

EDIT: Sorry guys, I'm new. Here's the code.

cout << "Connecting to user...\n" << endl;
        sleep(1);
        inFile.open("Novice.txt");

        for (int x = 0; x < 10; x++)
        {
            for (int y = 0; y < 4; y++)
            {
                inFile >> letter_Match[x][y];
                passwordList[x] += letter_Match[x][y];
            }
            cout << passwordList[x] << endl;
        }
        inFile.close();




How to add a common string in every randomly generated string Javascript

I am generating random strings using the below function in node.js. I wanted to know if there is any way to create text strings appropriately with a common string within every randomly generated string.

EDIT: The common string can be in any location of the generated string

For example:

Randomly generated string - Cxqtooxyy4

Can I add 'abc' or 'ABC' within that string like this - Cxqtoabcoxyy4 or CxqtoABCoxyy4 respectively.

My Code -

var randomTextArrayGeneration = function(size)
{
    var text = "";
    var possible = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
    for(var i=0;i<size;i++)
        text += possible.charAt(Math.floor(Math.random() * possible.length));
    return text;
}

Can anyone tell me how do I do this? Any help is really helpful.




How to get parameter arguments from a frozen spicy.stats distribution?

Frozen Distribution

In scipy.stats you can create a frozen distribution that allows the parameterization (shape, location & scale) of the distribution to be permanently set for that instance.

For example, you can create an gamma distribution (scipy.stats.gamma) with a,loc and scale parameters and freeze them so they do not have to be passed around every time that distribution is needed.

import scipy.stats as stats

# Parameters for this particular gamma distribution
a, loc, scale = 3.14, 5.0, 2.0

# Do something with the general distribution parameterized
print 'gamma stats:', stats.gamma(a, loc=loc, scale=scale).stats()

# Create frozen distribution
rv = stats.gamma(a, loc=loc, scale=scale)

# Do something with the specific, already parameterized, distribution
print 'rv stats   :', rv.stats()


gamma stats: (array(11.280000000000001), array(12.56))
rv stats   : (array(11.280000000000001), array(12.56))

Accessible rv parameters?

Since the parameters will most likely not be passed around as a result of this feature, is there a way to get those values back from only the frozen distribution, rv, later on?




Plotting a Probability Density Function with rand and randn

How can I demonstrate rand function is uniformly distributed on matlab and randn is normally distributed? I want to plot a histogram to demonstrate it. Thanks for your guidance.




vendredi 27 mai 2016

Random words generate using python

I have a list of words

count=100    
list = ['apple','orange','mango']

for the count above using random function is it possible to select 40% of the time apple, 30% of the time orange and 30% of the time mango?

for ex:

for the count=100, 40 times apple, 30 times orange and 30 times mango.

this select has to happen randomly




how to make random backgorundcolor html5

First of all I want to give thanks for this social group known stackoverflow. I have been searching and I dont find nothing similar to resolve my problem. I want to change the backgraoundcolor(degrade) in the header and footer each time that I recharge the page. I have three files. index. html inside header and footer a div known = backgraound styles.css where I call the backgradound backgraound. js where i try to do the logic to work all of this.

I dont know as to do to work this I have try to do the next

HTML

<body>
<header>
<div id="background">
<div class="container " align="center">
<h1>My web</h1>
</div>
</div>
</header>
<footer>
<div class="container" align="center">
<h4>Lorem ipsun</h4> 
</div>
</footer>
<script src="js/background.js"></script>
</body>

CSS

#backgroundmorado{
background: #258dc8; /* Old browsers */
background: -moz-linear-gradient(-45deg,  #258dc8 0%, #8e2def 100%); /* FF3.6-15 */
background: -webkit-linear-gradient(-45deg,  #258dc8 0%,#8e2def 100%); /* Chrome10-25,Safari5.1-6 */
background: linear-gradient(135deg,  #258dc8 0%,#8e2def 100%); /* W3C, IE10+, FF16+, Chrome26+, Opera12+, Safari7+ */
filter: progid:DXImageTransform.Microsoft.gradient( startColorstr='#258dc8', endColorstr='#8e2def',GradientType=1 ); /* IE6-9 fallback on horizontal gradient */
height: 400px;
}
#backgroundazuloscuro{
background: #1e5799; /* Old browsers */
background: -moz-linear-gradient(45deg,  #1e5799 0%, #207cca 34%, #207cca 34%, #2989d8 50%, #d97be5 100%); /* FF3.6-15 */
background: -webkit-linear-gradient(45deg,  #1e5799 0%,#207cca 34%,#207cca 34%,#2989d8 50%,#d97be5 100%); /* Chrome10-25,Safari5.1-6 */
background: linear-gradient(45deg,  #1e5799 0%,#207cca 34%,#207cca 34%,#2989d8 50%,#d97be5 100%); /* W3C, IE10+, FF16+, Chrome26+, Opera12+, Safari7+ */
filter: progid:DXImageTransform.Microsoft.gradient( startColorstr='#1e5799', endColorstr='#d97be5',GradientType=1 ); /* IE6-9 fallback on horizontal gradient */
height: 400px;
}

Javascript

function ran_col() { //function name
    var color = document.getElementById('background').style.background = random; 
    var random = Math.floor(Math.random() * color)];
    var arraybackground = ["backgroundmorado", "backgroundazul","backgroundazuloscuro"];
    for (var i = 0; i <= arraybackground.length; i++) {
        document.getElementById(arraybackground[i]).style.background = color; 
    }
    
}

Can I help me somebody? thanks




Custom Random Data Files

I'm looking for a web site that generates random data as specified by the user. There are a number of sites that provide random words or random integers; however, I'm looking for something that will generate a combination of datatypes. For example, a file of 500 alternating random words/strings and integers (i.e, keys & values) or 2000 alternating random words, doubles, and special symbols. Downloadable as a text file, either csv or space delimited.

Purpose would be to test various sorting & searching algorithms.




Generate Random maps data in google maps like format using Python

How can I generate random data in google maps like format i.e. 29.299332, 52.892959?

Do you prefer any package for this purpose?




rand() algorithm implementation on windows

There is no secret that following code:

srand(0);
int result = rand();

will provide different result on Windows and Linux. Also this code will provide identical result for different version of Windows (at least in the range winXP-win10). So the question is: what is the exactly algorithm of RNG is used on Windows and how to implement it on C/C++ as platform-independent solution?

UPDATE. To everyone: I've asked the specific question and I want to get a specific answer. If you don't know how to/don't want to/can't help - just go away. I'dont need your advices about anything else.




Show posts from query randomly

I have this query -

<?php if( is_page_template('taxonomy-listing_area-channel.php') ) { ?>
<?php
            $posts = get_posts(array(

    'post_type'     => 'adverts',
    'numberposts'   => 1,
    'order'         => 'random',

    'meta_query'    => array(
        'relation'      => 'AND',
        array(
            'key'       => 'associate_adverts',
            'value'     => '204',
            'compare'   => 'LIKE',
        )
    ),
));

        ?>

<?php //if it's returning the object

foreach($posts as $advert){

 $img = get_field("top_advert", $advert->ID);?>

 <img src="<?php echo $img["url"]; ?>"/>

<?php }?>

But for somr reaosn the posts are just showing as the last one entered and now randomly, I've never had this problem before but I have no idea where I'm going wrong, and help would be much appreciated!




jeudi 26 mai 2016

How should I go about shuffling contents of an array?

I have an array of integers called cards[52]. Each element contains an integer that represents a card (cards[0] = 5 would represent the 6 of clubs for example).

This is how I shuffled the array. It works, but I am getting repeats.

private void shuffleCards()
    {
        for (int i = 0; i < cards.Length; i++)
        {
            int randIndex = r.Next(0, 52);
            int origCard = cards[i];
            cards[i] = cards[randIndex];
            cards[randIndex] = origCard;
        }
    }

r is the Random variable I initialized in the beginning of the program.

When testing the program, I noticed I would get the same card 2 or 3 times. Obviously I cannot get repeats, they all must be different. I can't see in any way how this method gives me repeats.

How can I shuffle this array without any repeats? Thanks.




Modify this code to estimate the probability of three heads in three flips assuming the coin has a 55% probability of heads

I am attempting to modify the code below which is a random number generator designed to estimate the percentage of times 3 coins are flipped and they are all heads. Now I must assume the coin has a 55% chance of heads, and modify the code so that it estimates the probability of three heads in three flips. I am honestly lost on how to incorporate the 55% chance of heads, and then estimating three heads in three flips. ANY help is most greatly appreciated!!

trials = 10000;

flip = rand(trials,3,1);

heads = (flip >= 0.5);

freq = sum(all(heads,2));

percent = freq/trials

percent =

0.1281

Thank you in advance!!




Python Random Number Generator numpy_rng.random_integers(1e10)) OverflowError

I am trying to generate the random numbers in python 2.7 on 64 bit windows system through the following line of code

random_state=numpy_rng.random_integers(1e10) But i am getting the following error OverflowError: Python int too large to convert to C long




Randomized selection of vector elements

In MyClass class, the constructor calls generate to set the value of another class member, which works fine. The issue occurs when I try to generate 9(3 X 3) strings from MyClass::generate() when called from another class, using:

OtherClass::OtherClass

  std::vector<MyClass> getString;
  getString.reserve(3);

  for(int j = 0; j < 3; j++){
      for(int i = 0; i < 3; i++){
          MyClass myclass;
          getString.push_back(myclass);
       }
       mapContainer[keyFromVector.at(j)] = getString;
       getString.clear();
   }

MyClass::generate()

std::vector<std::string> listOfString;

std::string MyClass::generate(){

    listOfString = { "string1", "string2",....., "string20" };

    std::random_device random;
    std::mt19937 rand_string(random());
    std::shuffle(listOfString.begin(), listOfString.end(), rand_string);
    std::string getString = listOfString.at(1);

    listOfString.erase(listOfString.begin() + 1);  

    return getString;
}

What I want as output is:

Key1

String1, String5, string7

Key2

String2, string13, string4

Key3

string10, string17, string11

Right now, I get repeated string values from




Python 3 How to move an item from list x to list y and remove it from list x?

Quick question I am trying to add .append a random card from list x (in this case is Deck = []) and move it into list y (in this case is MyHand = []). Then I want to remove the item from list that was added into list y.

import random
Deck = []
MyHand = []
CardsPicked = 0
for Cards in range(1, 101):
    Deck.append(Cards)
print(Deck)
while(CardsPicked < 8):
    MyHand.append(random.choice(Deck))
    CardsPicked = CardsPicked + 1
print(MyHand)

THINGS TO KNOW: I have the moving one card from list x into list z but i can't remove the card that was moved into list y from list x.

I tried doing:

Deck.remove(random.choice)

But it said that the choice wasn't in the deck




Exclude range within random range between negative and positive float. c# unity

Have a variable that I give a random range between -2.0f and 2.0f (Random.Range(-2.0f, 2.0f); in Unity/C#), but I don't want it to pick a number between -0.6f and 0.6f.

How do I got about doing this?

http://ift.tt/1THK551




The method nextInt(int) is undefined for the type Random

Can someone help me with this error. I m trying to generate some random numbers but this error displays:The method nextInt(int) is undefined for the type Random. Even though i have imported java.util.Random it says:The import java.util.Random conflicts with a type defined in the same file. This is my code:

import java.util.Random;
public class Random {

        public static void main(String[] args) {
                
                Random object=new Random();
                int number;
                number=1+object.nextInt(6);
        
        }

}



How to use array_rand() or shuffle() functions in php mysql

I have the following working code to output the states and output the relatd cities under each state. However, I want to shuffle or randomize the cities in each state. For example, if the State is California then I want to shuffle or randomize the relate outputted cities under it. I tried to use different methods for this such as ORDER BY RAND(), implode() and so on but didn't get the correct result.

    $get_result = "select DISTINCT state_name, city_name from country WHERE country_name='$select_country' ORDER BY state_name ASC";

    $result = array();

    $run = mysqli_query($dbconfig, $get_result);

    while ($row=mysqli_fetch_array($run)){

        $state_name = $row['state_name'];

        $city_name = $row['city_name'];

            if (!isset($result[$state_name])) {

            echo '<p>' . $state_name . '</p>';

            $result[$state_name] = true;
        }

      echo '<p style="margin-left: 10px;"><a href="http://examplesite.com/'.$city_name.'">'. $city_name .'</a></p>';
}

Any help on this matter would be greatly appreciated.




Python error 'str' object has no attribute 'choice'

So, I have this code:

import random, string, os, time
a = 0
random = ''
def calcular():
    global random
    random = ''.join([random.choice(string.ascii_letters) for n in xrange(4)])
    print random
while a<1:
    calcular()
    a=a+1
    pass
print time.strftime('%H:%M:%S')
os.system('pause')

But I'm getting an AttributeError: 'str' object has no attribute 'choice'. What's the problem?




Generating an array for random numbers

Ok so I am creating an app that allows you to set a timer to a certain length of time and set a number of beeps. when you hit start the timer will play and however many beeps you selected will play at random times. In the code I have an array that I am trying to fill with numbers between 0 and the timer length:

for (int i=0; i< arraysize; i++){
    Random random = new Random();
    beepArray[i] = random.nextInt((0 - count)+ 1);
}

The program can run but it doesnt seem to fill the array with random numbers and so the timer stops and no beeps are played. Have I done something wrong here?

Thanks in adavance Mark




Maximum capacity before workbook becomes unstable

This is a general question to ask if there is any general size restriction on files or number of formulas or something like that that would lead to my situation as follows:

I have taken one workbook I made called "Main1" (only about 6mb, 10 worksheets, alot of data and macros though) and made a copy called "Main2". In Main2 I have added a small macro (just opens a workbook and copies in data) and changed some excel formulas to add in a few IFs and VLOOKUPs.

Now, Main2 lags so much during any task, even basic moving around the workbook or running the smaller macros. Main1 still works fine. What sort of things could have caused this given I haven't changed much and certainly have only made pretty vanilla changes. (Note Main 2 is only 6.05MB, same number of sheets)




How to generate unique and increase number in C#

How can get unique number increasement DateTime.Now.Ticks function? DateTime.Now.Ticks is return long date type. I want to generate integer data type start from 0 and always increase no need to know the first number.




the stack as the source of random numbers [duplicate]

This question already has an answer here:

I need a random unsigned number [0, max), but I don't want to call a random number generator so I thought of doing:

unsigned i;

and

i % max

in the expressions. My questions is, is this a good way to obtain a random unsigned value?




Dynamic Biased Randomized Selection Algorithm

I'm looking to implement an algorithm that picks items from a list randomly, albeit in a biased way. Say I have a value priority for each element in that list. I would like an element with higher priority appear more often in the selection.

Another thing is that the priority of these elements would be changed. If someone particularly picks an element rather than letting that element come from a random selection, the priority of that element should be increased by a certain factor.

I'm afraid I'm not quite sure how to phrase my question mathematically. Also, I don't know where to begin either. I found an article here which deals with the first part but doesn't deal with dynamically increasing the priority of elements.

One approach I thought of is that more the priority of an element, the more copies we make of it. However, this is very unfeasible to implement in computer code

I've also posted this question on math.stackexchange hoping for some mathematical insight.

NOTE: Just to be clear, I'm not looking for any implementation of sort. I'm just looking for a clear direction/few insights so I can go ahead and code up my own algorithm.




How do you generate a random matrix in R with a constant colSum value?

I'm looking for a way to generate a series of matrices where all the column sums are equal to a specific value. I thought I could generate random matrices and check each one to filter out where colSums= value needed, but that doesn't seem to work. Also, how do we generate random matrices in R with both positive and negative values?




MirrorArray Project

a) The application interface should look similar to:

image

b) Write the application code so that when Display is clicked a set of random integers is generated and added to the list box in the order generated followed by the reverse order generated. The number typed by the user in the text box should be used to determine how many random integers to generate from the set. Your code should include:

  • a FillArray() procedure to generate a set of random numbers and store them in an appropriately sized array. The integers should range from 0 to 20.
  • a MirrorArray() procedure to create an array with a set of elements that mirror each other.
  • a DisplayArray() procedure that adds each element of an array to a list box.

Can you please help me with this project. Appreciate your help!




mercredi 25 mai 2016

Why Do I get: TypeError: choice() takes 2 positional arguments but 4 were given?

I have a problem with random.choice which I can't understand. I pass 3 arguments to the function which is allowed to have 4 (http://ift.tt/1OZ1jvz), but it writes I am allowed to give only 2 and 4 were given.

def load_data():
dataset = load_boston()
num_samples = size(dataset.data, 0)
test_set_sz = int(1.0 * num_samples / 10)
tst_sub_inds = random.choice(range(num_samples), test_set_sz, False)
data_test, label_test = dataset.data[tst_sub_inds, :], dataset.target[tst_sub_inds]
trn_sub_inds = list(set(range(num_samples)) - set(tst_sub_inds)) 
data_train, label_train = dataset.data[trn_sub_inds, :], dataset.target[trn_sub_inds]
return ((data_train, label_train), (data_test, label_test))

The Error:

tst_sub_inds = random.choice(range(num_samples), test_set_sz, False) TypeError: choice() takes 2 positional arguments but 4 were given Blockquote

What is the problem? Maybe it due to an old version of python?

Thanks, Eli




Generate a random string in the fastest way

I am currently using this:

(defvar my-charset
  (eval-when-compile
    (concat (number-sequence 48 57) (number-sequence 65 90) (number-sequence 97 122)))
  "Char set in terms of number list.")
(defvar my-charset-length
  (eval-when-compile
    (length (concat (number-sequence 48 57) (number-sequence 65 90) (number-sequence 97 122))))
  "Length of my-charset.")

(defun my-generate-string (&optional max-length min-length)
  "Generate a random string."
  (let (string)
    (dotimes (_i (+ (random (- (or max-length 10) (or min-length 5) -1)) (or min-length 5)))
      (push (aref my-charset (random my-charset-length)) string))
    (concat string)))

Any method to make it faster?

Or any other way to generate the string much faster?




About random numbers in C++

I am really new to C++. I am following a free online course, and one thing I had to do was to create a program which could scramble the characters of a string.

So, I created a function who received the word as parameter and returned the scrambled word. ctime and cstdlib were included and srand(time(0)); declared in the main.

Basically, the function looked like this :

std::string mixingWord(std::string baseWord)
{
std::string mixWord;
int pos(0);

for (int i = baseWord.length; i >= 0; i--)
{
  if (i != 0)
  {
    pos = rand() % i;
    mixWord += baseWord[pos];
    baseWord.erase(pos,1);
  }
  else
  {
    mixWord += baseWord[0];
  }
}

return mixWord;
}

And it worked just fine. But the correct solution was

std::string mixingWord(std::string baseWord)
{
std::string mixWord;
int pos(0);

while (baseWord.size() != 0)
{
    pos = rand() % baseWord.size();
    mixWord += baseWord[pos];
    baseWord.erase(pos, 1);
}

return mixWord;
}

And it works fine as well. My question is : Why is the solution working ? From what I understood, this :

rand() % value

gives out a value between 0 and the value given.

SO, since baseWord.size() returns, let's say 5 in the event of a word like HELLO. rand will generate a number between 0 and 5. So it COULD be 5. and baseWord[5] is out of bound, so it should crash once in a while, but I tried it over 9000 times (sorry, dbz reference), and it never crashed.

Am I just unlucky, or am I not understanding something ?




Most efficient way to find random item not present in join table and without repeating previous random item

In my Rails 4 app I have an Item model and a Flag model. Item has_many Flags. Flags belong_to Item. Flag has the attributes item_id, user_id, and reason. I am using enum for pending status. I need the most efficient way to get an item that doesn't exist in the flags table because I have a VERY large table. I also need to make sure that when a user clicks to generate another random item, it will not repeat the current random item back to back. It would be OK to repeat any time afterwards, just not back to back.

This is what I have so far:

def pending_item
  @pending_items = UserItem.joins("LEFT OUTER JOIN flags ON flags.item_id = items.id").
                   where("items.user_id != #{current_user.id} and flags.id is null")
  @pending_item = @pending_badges.offset(rand @pending_badges.count).first
end

Is there a more efficient way than this?

And how can I make sure there are no back to back repeats of the same pending_item?




How can I create a random class that includes an array of number and an array of strings

I am doing with a GUI button. When user click it, it will get number or a word randomly. I know how to do it with just numbers,but i don't know how to deal with both words and numbers.

int[] numbers = new int[5] { 100, 500, 1000, 5000, 20000};
Random rd = new Random();
int randomIndex = rd.Next(0, 5);
int randomNumber = numbers[randomIndex];
button1.Text = randomNumber.ToString(); 




How to fill an array with smaller arrays in a random way?

I've got an array with 225 elements and 15 smaller arrays which their length sum is exactly 225.

The point is that I need to fill the larger array with these smaller arrays but in a random way.

 private final short datosdeNivel[]= new short[225];
 private final short diecinueve[]= {19, 19};
 private final short veintiseis[]= {26, 26, 26};
 private final short dieciocho[]= {18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18};
 private final short veintidos[]= {22, 22};
 private final short veintiuno[]={21, 21, 21, 21, 21, 21, 21, 21, 21, 21};
 private final short cero[]= {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
 private final short diecisiete[]= {17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17};
 private final short dieciseis[]= {16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16,16, 16, 16, 16, 16, 16, 16, 16, 16, 16,16, 16, 16, 16, 16, 16, 16, 16, 16, 16,16, 16, 16, 16, 16, 16, 16, 16, 16, 16,16, 16, 16, 16, 16, 16, 16, 16, 16, 16,16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16};
 private final short veinte[]= {20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20};
 private final short veinticuatro[]= {24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24};
 private final short veinticinco[]= {25, 25, 25, 25};
 private final short veintiocho[]= {28, 28};
 private final short uno[]= {1, 1, 1, 1, 1, 1, 1};
 private final short nueve[]= {1};
 private final short ocho[]= {9, 9, 9, 9, 9, 9, 9, 9, 9};

How can I establish a random order so every time the program runs the order in which the smaller arrays are placed in the larger array is different?




Is this method of guaranteeing a fixed amount of random true values biased?

Assuming the random() function is random and returns a value in the range [0, 1]. Will the resulting true values be biased towards a direction in the array when using this method?

    int chances = 16;
    int guaranteed = 6;
    boolean[] result = new boolean[chances];
    for (int i = 0; i < result.length; i++) {
        if (random() <= (float) guaranteed / chances) {
            result[i] = true;
            guaranteed--;
        }
        chances--;
    }




mardi 24 mai 2016

GoogleDrive: How to distribute a file to a random subfolder on Google Drive with a folder action trigger

I have files coming in to a google drive folder (landing folder) from a form online. I would like to distribute that file to a randomized subfolder. I would like for the distribution to happen as soon as the file is added to the landing folder




How are command prompt random numbers generated?

In the command prompt environment, there is a variable %random% that uses some algorithm to generate pseudo-random numbers.

Does anyone know the algorithm that generates these numbers?




Reversible number generator/encrypter/compressor?

Does anyone know a good reversible number generator?

By this i mean that i would input a seed into a number generator (in my case the seed would only ever be composed of 1s and 2s, for example 121111111112111)and the output would be a much smaller number.

And, if later on i want to find the seed using the output number, i could just enter that output number into a separate function that does the opposite of the first, and the output of that would be the original seed.

to make it clearer, if i entered the seed of 1221121112, i would get a number X. Number X could include letters/symbols, not just numbers. i could then input this number X into another function, and receive 1221121112.

Sorry if this question is a bit vague, but i'm really clueless at this point since i can't find anything good on my own.




R how to create random portfolios out of a predefined range?

I want to create random portfolios made up of 10 funds each. The portfolios need to fulfill this constraint:

  • Maximum vintage year of funds in portfolio - Minimum vintage year of fund in portfolio = 5 years (5 years is the investment period). So a portfolio with the first fund with vintage 1990 can only include funds from 1990-1995.

I have a dataset of 5,000 funds from 1982 to 2010 which looks (simplified) like this:

 Fund.ID Vintage Type Region.Focus Net.Multiple  Size
[1,] 4716  2003  2    US           1.02          Small
[2,] "2237 1998  25   Europe       0.03          Medium
[3,] 1110  1992  2    Europe       1.84          Medium
[4,] 12122 1997  25   Asia         2.04          Large 
[5,] 5721  2006  25   US           0.86          Mega
[6,] 730   1998  2    Europe       0.97          Small

So far I have solved the problem by using a loop function in which I can alternate the investment period from 1-6 years or change the number of funds.

##10 funds
for(i in 1982:2005)
{
  t <- i:(i+5)
  x <- subset(dataset, Vintage == i) ##instead of dataset, you can use any other subset
  pf <- subset(dataset, Vintage %in% t) ##change dataset here as well then
  m <- 1000 %*% nrow(x) %/% nrow(dataset) ##function simulates portfolios proportional to number of funds per year, change dataset here as well then
  n <- nrow(pf)
  weight <- rlongonly(m = m, n = n, k = 10, x.t = 1, x.l = 0.01, x.u = 0.3, max.iter = 1000)
  year.fof <- paste("fof.tvpi.10", i, sep = ".")
  assign(year.fof, weight %*% pf$Net.Multiple..X.)
  colnames(weight) <- pf[, 3]
  year.weight <- paste("weight.10", i, sep =".")
  assign(year.weight, weight)
}

I am using subset to distinguish style factors. rlongonly is a function from the rportfolios package and gives out a weight matrix, which I can then multiple e.g. with the Net Multiple vector.

However, is there a simpler way of doing this? Can I use an If() function or some kind of constraint vector/matrix? I want to include other constraints as well: A portfolio can only consist of funds with one size, a portfolio can only consist of funds from one region.




Lagged Fibonacci generator using a discarding strategy

I am trying to implement the Lagged Fibonacci generator but using a discarding strategy. I have these guidelines to follow:

Step 1: Return random numbers from the next 127 numbers generated from your RNG

Step 2: Discard the next 997 numbers generated from your RNG

Step 3: Goto Step 1.

The problem is sometimes the values generated are bopping up an error with regards to array out of bounds in section 'int randomNumber = array[Next(127)];'

The initial values are:

Random rand = new Random();
int[] array = new int[6000];
int j = 83;
static int k = 258;
int m = 2;
int n = k;
double randomNumber = 0;

Here is the code for the Discarding Method:

public int NextUsingDiscarding(int maxValue)
{
    try
    {
        int[] array = new int[127];
        for (int i = 0; i < array.Length - 1; i++)
        {
            array[i] = Next(maxValue);
        }

        int randomNumber = array[Next(127)];

        for (int i = 0; i < 127 + 997; i++)
        {
            Next(maxValue);
        }

        return randomNumber;
    }
    catch
    {
        return -1;
    }
}

and the number generator:

public int Next(int maxValue)
{
    for (int i = 0; i < array.Length; i++)
    {
        array[i] = rand.Next(maxValue);
    }

    int firstElement = array[n - j];
    int secondElement = array[n - k];

    randomNumber = (firstElement + secondElement) % Math.Pow(m, 32);

    array[n] = (int)randomNumber;

    return (int)randomNumber % (maxValue + 1);
}




I cannot understand mistake lmer

I tried to solve the problem reading other answers but did not get the solution. I am performing a lmer model:

MODHET <- lmer(PERC ~ SITE + TREAT + HET + TREAT*HET + (1|PINE), data = PRESU).

Perc is the percentage of predation. Site is a categorical variable that I am using as blocking factor. It is site identity where I performed the experiement. TREAT is categorical variable of 2 levels. HET is a continuous variable. The number of observation is 56 divided in 7 sites Maybe the problem is how I expressed the random factor. In every site I selected 8 pines among 15 to perform the experiment. I included the pine identity as categorical random factor. For instance in Site 1 pines are called a1,a3,a7 ecc, while in site 2 are called b1,b4,b12 ecc... The output of the model is

Error: number of levels of each grouping factor must be < number of observations

I don´t understand where is the mistake. Could it be how I called the pines? I tried also

MODHET <- lmer(PERC ~ SITE + TREAT + HET + TREAT*HET + (1|SITE:PINE), data = PRESU)

but the output is the same. I hope that I explained well my problems. I read on this forum similar questions about it but I still do not get the solution.

Thank you for your help




Why doesn't my simple routine to avoid generating two random numbers in a row work?

I'm doing the random quote generator Free Code Camp challenge, but don't want to have the same quote twice in a row. I came to the exact same conclusion as the person here did: http://ift.tt/1syWZZH

However, he says his works but mine still does not. My pen can be found here: http://ift.tt/1sO4EEt

And the code is:

  $(document).ready(function() {

    $("#getQuote").on("click", function() {
      $.getJSON("http://ift.tt/1syXnY8", function(json) {

        var html = "";
        var lastQuote = "";
        var whichQuoteToChoose = "";

        while (whichQuoteToChoose === lastQuote) {
          whichQuoteToChoose = Math.floor(Math.random() * 12); // returns a number between 0 and 11
        }
        lastQuote = whichQuoteToChoose;

        // this converts raw data into html

        json = json.filter(function(val) {
          return (val.id == whichQuoteToChoose);
        });

        json.forEach(function(val) {

          html += "<div class = 'quote'>"

          html += "<h2>\"" + val.Quotation + "\"</h2><h2>" + val.Quotee + "</h2>"

          html += "</div>"

        });

        $(".quote").html(html);

      });
    });
  });

With the while loop and the assignment immediately after it being what should, in theory, solve the problem.

Thanks for any and all help. Sorry to ask n00b questions here but the FCC help box can be a waste of time sometimes.




Initialising random number generator in Matlab

In Matlab one can use rng('default'); to initialize the random number generator.

Does this only hold for the current function or for the whole session?

Second, I only want to initialize the random number generator in a specific function. Before and after that specific function the not initialized random number generator should be used. How can this be done?




Are postgres UUID numbers homogeneously random?

Looking at UUIDs generated as primary keys by Postgres defined by RFC 4122, ISO/IEC 9834-8:2005 (source http://ift.tt/1sO4I6V). Can we consider that these numbers are homogeneously random on all their length ?

Given this UUID :

a0eebc99-9c0b-4ef8-bb6d-6bb9bd380a11

Can we objectively assume that a0eebc99 and bd380a11 are equally as random ? If not, why ?




randint with a normal distribution

How to generate a random integer as with np.random.randint(), but with a normal distribution around 0.

np.random.randint(-10, 10) returns integers with a discrete uniform distribution np.random.normal(0, 0.1, 1) returns floats with a normal distribution

What I want is a kind of combination between the two functions.




Convert a bivariate draw in a univariate draw in Matlab

I have in mind the following experiment to run in Matlab and I am asking for an help to implement step (3). Any suggestion would be very appreciated.

(1) Consider the random variables X and Y both uniformly distributed on [0,1]

(2) Draw N realisation from the joint distribution of X and Y assuming that X and Y are independent (meaning that X and Y are uniformly jointly distributed on [0,1]x[0,1]). Each draw will be in [0,1]x[0,1].

(3) Transform each draw in [0,1]x[0,1] in a draw in [0,1]. Is there any function doing this? After some readings, I believe that a space filling curve would do what I want. I found this answer which seems perfect for my question, if it were not for the fact that the algorithm is not written in Matlab language. Is there any pre-built package in Matlab doing the same?

(4) Repeat (2) and (3) imposing some correlation between X and Y.




Select random object from list based on conditions [duplicate]

This question already has an answer here:

Hi guys i'm developing a tests generator app using asp mvc. And i need to select random questions based on some conditions randomly using some test template. Each question has a domain and a difficulty. A test template has the following structure.

NoOfQuestions
QuestionDomain
NoOfQuestionsPerDomain
QuestionDifficulty
NoOfQuestionsPerDifficulty

NoOfQuestions = NoOfQuestionsPerDomain + NoOfQuestionsPerDificulty.

My question is how can i choose a random question set based on the properties above ? thanks!




Why is the Fortran RANDOM_SEED input an array?

I use the following code to initialise me seed (I don't know where I found it, but everyone, absolutely everyone seems to have exactly this! Why? Why 37?)

SUBROUTINE init_random_seed()
IMPLICIT NONE
INTEGER :: i, n, clock
INTEGER, DIMENSION(:), ALLOCATABLE :: seed

CALL RANDOM_SEED(size = n)
ALLOCATE(seed(n))

CALL SYSTEM_CLOCK(COUNT=clock)

seed = clock + 37 * (/ (i - 1, i = 1, n) /)
CALL RANDOM_SEED(PUT = seed)

DEALLOCATE(seed)
END SUBROUTINE

Now why is the argument of PUT an array (of size .ge. n)? I can only find sources that say that that is how it should be, not why.

  1. Pg.12 of http://ift.tt/20uuass
  2. http://ift.tt/1NITr14
  3. http://ift.tt/20utJi1



How do I send the prompt backwards in my code in python?

I wrote a simple number guessing game with the randomint function.

Lets say I wrote it and it looked a little like this:

 import blah
 import blah

 print ("Hello, and welcome to the guesser")

 Answer1 = (randomint(1,5))
 Guess1 = int(input("Input a number 1-5")

 if Guess1 == Answer1:
      print ("You got lucky that time")

 elif Guess1 < 6 and != Answer1:
      #send back to guess again

 elif Guess1 > 5:
      print ("Invalid Number")
      #send back to guess again

It's probably a really stupid question and beginner stuff, but, is there a function that could fulfill my needs and wants of sending people back to guess the number again?




R "random" distributions

I have been seeing series of generated data with too much similarity between near entries from runif

Here is a short session from RStudio

1:5 * runif(1,-1,1)

This will give us five "randomly" distributed entries between (-1,1) .. well .. so I had understood.. The reality is different:

> 1:5 * runif(1,-1,1)
[1] -0.1534864 -0.3069729 -0.4604593 -0.6139458 -0.7674322
> 1:5 * runif(1,-1,1)
[1] 0.01084729 0.02169457 0.03254186 0.04338915 0.05423643
> 1:5 * runif(1,-1,1)
[1] -0.003854265 -0.007708529 -0.011562794 -0.015417058 -0.019271323
> 1:5 * runif(1,-1,1)
[1] -0.8809448 -1.7618896 -2.6428343 -3.5237791 -4.4047239
> 1:5 * runif(1,-1,1)
[1] -0.768577 -1.537154 -2.305731 -3.074308 -3.842885
> 1:5 * runif(1,-1,1)
[1] 0.03255907 0.06511815 0.09767722 0.13023629 0.16279537

Notice:

  • the first series range is (-.767,-.15)
  • the second series range is (.01,.05)
  • the third series range is (-.0038,-.019)

etc. Clearly these are not truly random series. So:

  • what are these series representing
  • how do we get more realistic randomly distributed series.



Implementing the Fisher-Yates shuffling algorithm for a 2-D array (C++)

I have a 2-D array (10 x 10) which has been populated with the numbers 1-100. I am trying to use a Fisher-Yates shuffle to randomly redistribute the values in the array without repetition.

I am able to repopulate the array with random numbers 1-100, however I still get repeating values, and even get 0s (which should not happen).

void shuffleArray(int array[][10], int count) {
    srand(time(NULL));
    for (int i = 10, k = 0; i > 0; i--) {
        for (int j = 10; j > 0; j--, k++) { 
            int newValue = rand() % (count - k);
            array[i][j] = newValue;
        }
    }
}

int main(){
//Create and populate the array with the numbers 1-100
    int array[10][10]{ { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 },
                       { 11, 12, 13, 14, 15, 16, 17, 18, 19, 20 },
                       { 21, 22, 23, 24, 25, 26, 27, 28, 29, 30 },
                       { 31, 32, 33, 34, 35, 36, 37, 38, 39, 40 },
                       { 41, 42, 43, 44, 45, 46, 47, 48, 49, 50 },
                       { 51, 52, 53, 54, 55, 56, 57, 58, 59, 60 },
                       { 61, 62, 63, 64, 65, 66, 67, 68, 69, 70 },
                       { 71, 72, 73, 74, 75, 76, 77, 78, 79, 80 },
                       { 81, 82, 83, 84, 85, 86, 87, 88, 89, 90 },
                       { 91, 92, 93, 94, 95, 96, 97, 98, 99, 100 } };

//Call the array shuffling function
shuffleArray(array, 100);


//Display the array to the screen for debug purposes
for (int i = 0; i < 10; i++) {
    for (int j = 0; j < 10; j++) {
        if (array[i][j] < 10) {
            cout << "   " << array[i][j] << "  ";
        }
        else if (array[i][j] == 100) {
            cout << " " << array[i][j] << "  ";
        }
        else {
            cout << "  " << array[i][j] << "  ";
        }
    }
    cout << "\n\n\n";

    return 0;
}




lundi 23 mai 2016

Easy way to create Random numbers in Java

I'm searching for an easy way to generate random numbers with a defined max and minimum, but for the purpose I need using the standard way to generate randoms complicates my code too much. The standard way being:

Random rand=new Random();
rand.nextInt(125)+1;

While I'm looking for a simpler way, something along the lines of:

Random(125,1);




Calling random function inside another function

I have function which genrenate me random index like this :

size_t randomIndex(vector<int>myVector) {
    srand(time(NULL));
    size_t index1 = rand() % myVector.size();
    return index1; 
}

I call it inside another funtion :

void generaTwoIndex(vector<int> myVector2) {
     size_t index1 = randomIndex(myVector2); 
     cout << "index1 = " << index1 << endl; 
     size_t index2 = randomIndex(myVector2);
     cout << "index2 = " << index2 << endl;
}

It generate me the same index. What is the issue ? Thank's in advance for your answers.




Select random index in vector which meets requirements

I have a vector X of length 1000 containing 10 randomly placed ones and 990 zeros.

I have below function which modifies vector X.

foo <- function(X){
    old <- sample(which(X==1),1)
    new <- sample(c(1:1000),1)
    X[old] <- 0
    X[new] <- 1

    return(X)
}

Above function does following:

  1. Locates the ones
  2. Selects the index of one of them at random
  3. Selects a random location in X
  4. Changes the previously located one to a zero
  5. Changes the random location from step 3 from 0 to 1.

With above code, a 1 can be added to a location which already holds a 1. This I don't want to be possible. In other words, I always want to have 10 ones in my vector.

The solution must be without loops because I am calling this function thousands of times, and speed is of the essence.




Why runif function in r doesn't really generate random numbers?

I am trying to generate a set of random numbers. It is very straight-forward:

start <- 1e-9
end <- 1e9

# centered by 1

for (i in 1:20) {
   par <- runif(10000, start, end)
   print(summary(par))
}

     Min.   1st Qu.    Median      Mean   3rd Qu.      Max. 
72230 244400000 493900000 496400000 751500000 999800000 
     Min.   1st Qu.    Median      Mean   3rd Qu.      Max. 
1.016e+05 2.505e+08 4.985e+08 5.001e+08 7.475e+08 1.000e+09 
     Min.   1st Qu.    Median      Mean   3rd Qu.      Max. 
6.333e+04 2.494e+08 5.031e+08 4.997e+08 7.495e+08 1.000e+09 
     Min.   1st Qu.    Median      Mean   3rd Qu.      Max. 
33970 242600000 489700000 491600000 738900000 999800000 
     Min.   1st Qu.    Median      Mean   3rd Qu.      Max. 
1.476e+04 2.485e+08 4.992e+08 4.980e+08 7.449e+08 1.000e+09 
     Min.   1st Qu.    Median      Mean   3rd Qu.      Max. 
64630 252600000 500500000 500600000 750400000 999800000 
     Min.   1st Qu.    Median      Mean   3rd Qu.      Max. 
2.825e+05 2.556e+08 5.010e+08 5.021e+08 7.512e+08 1.000e+09 
     Min.   1st Qu.    Median      Mean   3rd Qu.      Max. 
6.824e+04 2.498e+08 4.975e+08 5.006e+08 7.505e+08 1.000e+09 
     Min.   1st Qu.    Median      Mean   3rd Qu.      Max. 
127400 252200000 497400000 501500000 754300000 999900000 

By setting up an range centered by 1, I was expecting an roughly even numbers of samples that is below 1. However, it seems all generated samples are well above 1. Why 'runif()' didn't go below 1 as I expected?




e - greedy choose when to choose a random value?

I struggling a bit with implementing this, I think is simple, but I might be overcomplicating things. I am trying to implement an eps-greedy action selector for q-learning. The method is described in this snippet:

Snippet from: http://ift.tt/1WdycHe

How do I make the agent

"select at each time step a random action with a fixed probability 0 <= eps <= 1", instead of selecting greedily one of the learned optimal actions with respect to the Q-function"

I have implemented a AI player which uses Q-learning to determine future actions, but since i am using a greedy action selection, it doesn't explore all it's options, but quickly gets stucked to a local minima, which is why i want to try out the eps-greedy action selecter instead, and see it would help..

The way i understand it is, that if eps was 0.9. then would the output of the function 90 % of the time be the greedy output and 10% of the time would the output be random. But how do make it do so, I would preferably like to avoid having a counter that count up 100, and based on the value of the counter would either return a random action or greedy action, but how do i do that? Is there no way around this?




Generate a random value with a certain probability

I at moment trying to implement E-greedy which require me to do this:

One such method is $\epsilon$-greedy, when the agent chooses the action that it believes has the best long-term effect with probability 1-$\epsilon$, and it chooses an action uniformly at random, otherwise. : http://ift.tt/20rQKSu

Generating a random value is not a problem, but how do i choose an action randomly with a probability 1-epsilon at the time?




Independent random generator in C

I know that in C we can use rand() to generate random numbers and use srand() to set seed. However I now want an independent random generator (like a variable, or define a class). Can anyone help?




Assign random but even amount from an array to a list array in PHP?

I have to arrays. One array $People currently creates number of 44 individuals. Lets just assume currently its $People = array('1','2',...,'44');. I have another array $Test = array('A','B',...'O');, this would be length of 15. Now i want to be able to assign the test randomly to each individual. I know how to do this using random function in php.

Where it has got tricky for me and what i need help with is how can i even out the test array. What i mean by this is since there are currently 44 individuals (this array will grow in future), what I want is 14 test versions to have 3 individuals and 1 version would have 2. So i want the test array to even out. I also want it to handle as growth of $People array.

Ex: Test Version D will have individual '4', '25'. Every other version has three random individuals.

Few ideas i came up with are things like running random integer on $Test array and which ever gets highest/lowest gets 2 individuals and rest three. This would give a problem when i increase the size of $People array; to deal with that i though about using modulus to figure out what will be even number of $Test beforehand.

I can do this and other ideas but am pretty sure there has to be a better way to do this.




C and random number generation

I was just wondering if the rand (http://ift.tt/1BGCU4E) function will generate the same sequence of random numbers, while using the same seed, but when run on different libc implementations, and even different compilers and operating systems (win, linux).

I did some tests using various compilers( g++4.8, g++5.1 and clang) and it seems that the answer is yes, however I did not find any "official" mention of the PRNG algorithm used in the C's random number generation (http://ift.tt/1WKiOSV), or whether these should be mentioned in the standards ...




Dieharder dab_monobit2 test fails

i am currently testing some RNG numbers from a TRNG using the dieharder test suite. I got around 380MB binary test data from the TRNG and all tests pass except one test - the dab_monobit2 test (test 209) and I just dont know why.

As far as I understood the dab_monobit2 tests does exactly the same as the other monobit test (test 100) it counts the 1's and 0's within a specific range and checks if its more or less 50:50 . What is exactly the difference between the monobit test (test 100) and the dab_monobit2 test? And what does it say about my TRNG?

Here it the output of the monobit test and the dab_monobit2 test:

sts_monobit| 1| 100000| 100|0.74709531| PASSED
dab_monobit2| 12| 65000000| 1|1.00000000| FAILED




dimanche 22 mai 2016

switch statement in generating random numbers in java : not working

I've used a switch statement in my code that tosses a coin and generates a random result. If the coin falls on 0, it shows tails and if it falls on 1, it shows heads. But when I'm using switch statements, the outputs are always either only "heads" or both of "tails' and "heads".

My code:

import static java.lang.System.*;
import java.util.*;

class generateRandomNumbers{
    public static void main(String[] args){
        Random coin = new Random();
        int toss;
        toss = coin.nextInt(2);
        switch(toss){
            case 0 : out.println("tails");
            case 1 ; out.println("heads");
        }
    }
}

But when I used if-else statements it worked as planned:

import static java.lang.System.*;
import java.util.*;

class generateRandomNumbers{
    public static void main(String[] args){
        Random coin = new Random();
        int toss;
        toss = coin.nextInt(2);
        if(toss == 0){
            out.println("tails");
        }
        else{
            out.println("heads");
        }
    }
}

Please point out what my mistake is when I used switch statement in my code




randomly select M records from a file of N records

Need to randomly select M records (means each record in the file have the same probability to choose) from a file with N records (N > M). Wondering if any solution which read file only once?

The only method I think about is select each record with probability M/N, but this way could result in either less than M or more than M records.

Any smarter ideas are appreciated.

regards, Lin




OS X libc++ std::uniform_real_distribution bug

I'm seeing some strange behavior using the C++ 11's std::uniform_real_distribution compiling with Apple LLVM version 7.0.2 (clang-700.1.81). Calling to operator() renders results outside the distribution range. The minimal sample program below reproduces the trouble

// Example program
#include <random>
#include <iostream>
#include <string>

template< int power >
constexpr uint64_t power_of_two(){
  return 2 * power_of_two< power - 1 >();
}

template< >
constexpr uint64_t power_of_two< 0 >(){
  return 1;
}

std::linear_congruential_engine
< uint64_t, 273673163155, 13, power_of_two< 48 >() >
rng;

std::uniform_real_distribution< double > angle_cosine(-1, 1);

int main()
{
    std::cout << angle_cosine.a() << " " << angle_cosine.b() << '\n' << std::endl;

    for (int i = 0; i < 4; ++i){
        std::cout << angle_cosine(rng) << std::endl;
    }
}

Compiling and running online (presumably with g++) renders reasonable results

-1 1

-0.529254
-0.599452
0.513316
-0.604338

However, compiling and running locally renders unreasonable results.

-1 1

130349
37439.4
42270.5
45335.4

Have I overlooked something or have I encountered a bug in libc++? If the latter is the case, is anyone aware of a work around?




C: How do I use rand as input for switch statement?

I'm just trying to make a program that selects a range of numbers, then uses that to print out a statement with switch. After doing some editing, I figured this might work but so far it hasn't

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

int main() {
int i;

srand( time(NULL) );

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


  switch(( rand()%3 ) + 1 )) {
  case 1:
  printf("1 was selected.\n");
  break;

  case 2:
  printf("2 was selected.\n");
  break;

  case 3:
  printf("3 was selected.");
  break;
  }
  }



}




Randomize border color on hover

I have this script that randomize the color of my border img on hover, but it also removes my basic border when I leave the img..(from the start all my img have a grey border, and I'd like this border to alway stay there and not be removed)

script>      
$(function() {
  var colors = ["#FC3E6B","#24FF00","#0087F9","#F9F900"];

  $('.grid-item-content').hover(
    function() {
      var rand = Math.floor(Math.random()*colors.length);

      $(this).css('border-style', 'solid');
      $(this).css('border-width', '10px');
      $(this).css('border-color', colors[rand]);
    },
    function() {
      $(this).css('border-style', 'none');
    }
  );
});
</script>




measure dev/urandom efficiency

I have to measure efficiency of /dev/urandom as an assignment. I've got the following task: Check, how many bytes of data you can get from /dev/urandom in 1 minute. Don't write taken data on disk, as it could slow everything down.

I've tried

timeout 60s cat /dev/urandom | wc -c

But all I receive was just "Terminated" message.




get random char in a specific range in java

Am designing wumpus hunting program using java. Where i can include three gold, 3 pits, one wumpus, one player. and the position of the game item should be random generator.How to generate random characters in 2d array . How to specify the range for the characters in java. Thanks.




Grabbox with rarities. (Random value picker)

Hey guys I am trying to write up some code to pick a random item out of a box. Those items have rarities linked to them, for example 0.1 which should have a chance of 1/1000 ( 1 / (100/rarity) ) but for some reason it doesn't seem to work properly. This is what I tried:

        ArrayList<BoxItem> allItems = new ArrayList<>();
    int counter = 0;
    while(counter < 10000){
        ArrayList<BoxItem> possibleRewards = new ArrayList<>();
    double randomNumber = Math.random()*100;
    while(possibleRewards.isEmpty()){
        for(BoxItem item: contents){
            randomNumber = Math.random()*100;
            if(randomNumber < item.getRarity())
                possibleRewards.add(item);
        }
    }

    BoxItem boxItem = possibleRewards.get(possibleRewards.size()-1);
    allItems.add(boxItem);
    counter++;
    }
    System.out.println("Opened 10000, results:");
    int counter1 = 0;
    for(BoxItem item: contents){
        System.out.println("Item "+counter1+" received: [" + Collections.frequency(allItems, item)+"], rarity: [1/"+(100/item.getRarity()+"]"));
        counter1++;
    }

This is a simulation of 10000 boxes:

Item 0 received: [344], rarity: [1/100.0]

Item 1 received: [332], rarity: [1/100.0]

Item 2 received: [873], rarity: [1/40.0]

Item 3 received: [343], rarity: [1/100.0]

Item 4 received: [1102], rarity: [1/33.333333333333336]

Item 5 received: [380], rarity: [1/100.0]

Item 6 received: [390], rarity: [1/100.0]

Item 7 received: [366], rarity: [1/100.0]

Item 8 received: [4062], rarity: [1/10.0]

Item 9 received: [433], rarity: [1/100.0]

Item 10 received: [1336], rarity: [1/33.333333333333336]

Item 11 received: [39], rarity: [1/1000.0]

You see it's weird that an item with a rarity of 1/1000 comes 39 times when opening 10000 boxes. It should only be drawn around 8-12 times. Could anyone help me fix this? I spent a long time on this but can't seem to figure it out.

Boxitem example:

            contents.add(new BoxItem(1, 0.1));

0.1 would mean 1/1000




Swap 2 arrays in matlab

i am trying to swap 2 arrays inside an array for example

a= [1 2 3];

b=[ 5 3];

c=[ 9 3 7 6];

d=[ 7 5];

X1= [ a, b , d, c ];

now i want to swap any 2 random arrays inside X1 , knowing that each array have its own size.




samedi 21 mai 2016

Spinning content in Delphi?

I'd like to create a simple content spinner that will work like this: 1- I type a text in Memo1 with some delimiters(e.g {This is a simple text|Here We can find a simple text|Here are just some regular words} {which I want to spin|that I want to change|that I need to change}, {please|I need to know}, {what can I do?|how can I do it?} {Thank You|Thanks}).

2- The function will randomize the strings based in those delimiters and output them to Memo2. One random output for this would be "Here We can find a simple text that I need to change, please, how can I do it? Thank You".

It's important to keep the linebreaks and spaces. Another important thing is to never output results identical one another. So basically it will sort the words/sentences based on the delimiters and then create random content based on what I want. It looks simple, I could do it with numbers but can't really think in a way to do it with text. Any help?




random value assign with the class combination

Here is the case I have got a spell class

    public abstract class Spell
{

    public abstract void Castspell ();
}

public class Heal:Spell
{
    Dictionary<string, int> heals = new Dictionary<string,int> ();

    public Heal()
    {
        heals.Add ("less heal", 1);
        heals.Add ("medium heal", 2);
        heals.Add (" large heal", 3);
    }

    public override void Castspell()
    {
    }


}

ignore the Castspell(), and there is another class called student

    public class student
{
  public enum spells
    {
        lessheal,
        mediumheal,
        highheal
    }
    List<Spell> _skillist = new List<Spell>();
    public student()
    {
           //...
    }
            public void learnskills()
    {
        _skillist.Clear ();
        Spell newspell = new Spell ();
        _skillist.Add (newspell);

    }

what I am trying to do here is I wanna make learn skill method, each time I Call It will randomly add a heal spell into the _skillist.(it could be less, medium or high). how could I achieve it? please give me some advices about it.thanks




Stop previous random activity from showing

Does anyone know how to completely stop the random activity from showing? I have 5 classes with 10 questions each. Once the correct answer is given I want to move on to the next random class and not have the previous class come up again. Once all the random classes are answered the first time, then the Random method has ended. I tried finish() but that doesn't work. On button click I still get repeated classes after it has already been answered. Please see my code and advise if you could. Thx

public class HomeActivity extends AppCompatActivity {

TextView myTv;
Button nextBtn;
EditText myEt;
Button playgameBtn;

int mCounter = 0;


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

    myTv = (TextView) findViewById(R.id.myTv);
    nextBtn = (Button) findViewById(R.id.nextBtn);
    playgameBtn = (Button) findViewById(R.id.playgameBtn);
    myEt = (EditText) findViewById(R.id.myEt);


   final String[] clazzes = new String[] {"Mark.class", "John.class", "Caleb.class", "Isaiah.class", "Jacob.class"};


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

            ArrayList<Class> activityList = new ArrayList<>();
            activityList.add(Mark.class);
            activityList.add(John.class);
            activityList.add(Caleb.class);
            activityList.add(Isaiah.class);
            activityList.add(Jacob.class);


            Random generator = new Random();
            int number = generator.nextInt(5)*1;

            Class activity = null;

            switch (number){
                case 1:
                    activity = John.class;
                    break;
                case 2:
                    activity = Caleb.class;
                    break;
                case 3:
                    activity = Mark.class;
                    break;
                case 4:
                    activity = Isaiah.class;
                    break;
                default:
                    activity = Jacob.class;
                    break;


            }
            Intent intent = new Intent(getBaseContext(), activity);



             startActivity(intent);
            finish();

            }

private void finish() {
}


    });


      }



  }




Minimize the number of cuRAND states stored during a MC simulation

I am currently writing a Monte-Carlo simulation in CUDA. As such, I need to generate lots of random numbers on the fly using the cuRAND library. Each thread processes one element in a huge float array (omitted in the example) and generates 1 or 2 random numbers per kernel invocation.

The usual approach (see example below) seems to be to allocate one state per thread. The states are reused in subsequent kernel invocations. However, this does not scale well when the number of threads increases (up to 10⁸ in my application), since it becomes the dominant memory (and bandwidth) usage in the program.

I know that one possible approach would be to process multiple array elements per thread in a grid stride loop fashion. Here I want to investigate a different method.

I am aware that for the compute capability I am targeting (3.5), the maximum number of resident threads per SM is 2048, i.e. 2 blocks in the example below.
Is it possible to use only 2048 states per multiprocessor, regardless of the total number of threads ? All random numbers generated should still be statistically independent.

I think this might be done if each resident thread were associated a unique index modulo 2048, which could then be used to fetch the state from an array. Does such an index exist ?

More generally, are there other ways to reduce the memory footprint of the RNG states ?

Example code (one state per thread)

#include <cuda.h>
#include <curand.h>
#include <curand_kernel.h>
#include <assert.h>

#define gridSize 100
#define blockSize 1024
#define iter 100

__global__ void rng_init(unsigned long long seed, curandState * states) {
  const size_t Idx = blockIdx.x * blockDim.x + threadIdx.x;
  curand_init(seed, Idx, 0, &states[Idx]);
}

__global__ void kernel(curandState * states) {
  const size_t Idx = blockIdx.x * blockDim.x + threadIdx.x;
  const float x = curand_uniform(&states[Idx]);
  // Do stuff with x ...
}

int main() {
  curandState * states;
  assert(cudaMalloc(&states, gridSize*blockSize*sizeof(curandState)) == cudaSuccess);
  rng_init<<<gridSize,blockSize>>>(clock(), states);
  assert(cudaDeviceSynchronize() == cudaSuccess);

  for (size_t i = 0 ; i < iter ; ++i) {
    kernel<<<gridSize,blockSize>>>(states);
    assert(cudaDeviceSynchronize() == cudaSuccess);
  }
  return 0;
}




numpy: random select K items from total M(M>K) items?

Is there some handy implementation of Matlab function randperm in numpy that random select K items from totally M(M>K) items, and return the selected indice?

In Matlab,

randperm(100,10)

ans =

82    90    13    89    61    10    27    51    97    88




vendredi 20 mai 2016

How to keep the enemies inside the screen in pygame?

I want to keep the enemies (red rectangles in my case) inside the rectangle.What happens is that since it's a random function , the enemies keep on moving.But slowly some of my enemies moves outside , i don't want this to happen.I want them to be inside the screen only.

Here is my random movement for my enemies:

def evilMove(evilGuy):
    evilCoords = []
    #Returns either -1, 0 or 1
    randomMovex=random.randrange(-1,2)
    randomMovey=random.randrange(-1,2)
    evilMake={'x':evilGuy[0]['x']+randomMovex,'y':evilGuy[0]['y']+randomMovey}


    del evilGuy[-1] #Delete the previous spawn of enemy so there is no trail
    evilCoords.append(evilMake['x']) #Adds x coordinate
    evilCoords.append(evilMake['y']) #Adds y coordinate
    deadZones.append(evilCoords) #Adds the enemy coordinates in the list

    evilGuy.insert(0,evilMake)