jeudi 31 décembre 2015

what is the purpose of variable i minus 1 within the swap method? Is - 1 really necessary for a fair randomization?

I saw this code in Oracle documentation.

The documentation states: "The shuffle method below,unlike most naive attempts at shuffling, it's fair (all permutations occur with equal likelihood, assuming an unbiased source of randomness)".

My question is what is the purpose of variable i minus 1 within the swap method? Is - 1 really necessary for a fair randomization?

public static void shuffle(List<?> list, Random rnd) {
    for (int i = list.size(); i > 1; i--)
        swap(list, i - 1, rnd.nextInt(i));
}




If statement depending on the random image shown

I have a imageview that randomly generate 1 out of 2 possibles images clicking on one button.

I want that when one image is showed (R.drawable.aa) and I press other button, a toast is shown.

My problem is that once a random image is shown and click on the other button, nothing happens.

public class buho extends Activity {

// UI components
private Button drawButton;
private Button boton2;
private ImageView cardImage;

// Random object
private final static Random random = new Random();

// The card deck
private final static int[] cardDeck = new int[] {   R.drawable.aa,
        R.drawable.a2,
         };



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

    drawButton  = (Button)findViewById(R.id.drawButton);
    boton2  = (Button)findViewById(R.id.button2);
    cardImage = (ImageView)findViewById(R.id.cardImage);


    drawButton.setOnClickListener(new View.OnClickListener() {
        public void onClick(View arg0)
        {cardImage.setImageResource(cardDeck[random.nextInt(cardDeck.length)]);
            boton2.setOnClickListener(new View.OnClickListener() {
                public void onClick(View arg0) {
                    if (cardImage.equals(R.drawable.aa)) {
                        Toast toast = Toast.makeText(buho.this, "si", Toast.LENGTH_LONG);
                        toast.show();
                    } else {

                    }


                }
            });




pandas: read a small random sample from big CSV, according to sampling policy

Very related to Read a small random sample from a big CSV file into a Python data frame .

I have a very big csv, with columns patient_id,visit_data. I want to read a small sample from it, but if I sample a patient I want to sample all of his records.




How to populate empty attributes with random values from seeds.rb

I've generated User model with attributes: first_name, last_name, city. Then, I've created 200 instances of the class using seed.rb and gem 'faker'. After all, I have added one more attribute to this model - age:string, so now in every instance of the class the age = 'nil'. Now, I want to populate every single user with randomly generated number from range 10..99. Here is my code from seed.rb:

users = User.all
users.each do |element|
    element.age = rand(10..99).to_s
end

When I type rake db:seed it seems to be successfull but when I check the database, each age:string is still 'nil'. Do you have any idea what might have gone wrong?




mercredi 30 décembre 2015

Get a random image from a database along with its caption in PHP

I need to retrieve a random image and the caption that goes along with it from a database. There is a caption column and a photo column.

Here is my (messy) code:

      $getThis = $mysqli->query("SELECT * FROM `k_pictures` ORDER BY RAND() LIMIT 1");
      $photo = "";
      while($row = $getThis->fetch_assoc()) {
        $photo .= $row['photo'];
        $photoName = $row['fileName'];
        echo "<tr>";
        echo "<td><img src='../p/$photoName' height='500px' width='500px'></td>";
        echo "</tr>\n";
        $getCaption = $mysqli->query("SELECT * FROM `k_pictures` WHERE fileName = '$photoName'");
        while($retrieve = $getCaption->fetch_array()) {
          if(isset($_POST['submit'])) {
            require "caption.php";
            insertCaption($photoName, $_POST['caption']);
            header('Location: ../success/');
            $getCapt = $mysqli->query("SELECT * FROM `k_captions` WHERE fileName = '$photoName'");
            $captionRetrieved = $getCapt->fetch_array();
            echo "Top rated caption: " . $captionRetrieved['caption'];
          }
        }
      }




generate random image over a button

I'm working on a project to generate random images from an array. I'm running into an issue. I will have one button on the screen name "generage shapes". Once the user clicks on this button the "generate shapes" button becomes hidden and 4 buttons display 4 different shapes. I'm having an issue making these 4 buttons display with the image from my array. I tried a switch statement but it doesn't go through. I'm providing my code below. Please let me know if you can help.

Thank you

import UIKit

class ShapesDetailViewController: UIViewController {

var random = arc4random_uniform(4)

@IBOutlet weak var titleBar: UINavigationItem!

@IBOutlet weak var displayMessageLabel: UILabel!

var myImages = [ "diamond.png", "decagon.png", "dodecagon.png", "hectagon.png", "heptagon.png", "octagon.png", "parallelogram.png", "pentagon.png", "rectangle.png", "rightTriangle.png", "square.png", "trapezoid.png", "triangle.png"]







//my image labels


@IBOutlet weak var buttonOne: UIButton!
@IBOutlet weak var buttonTwo: UIButton!
@IBOutlet weak var buttonThree: UIButton!
@IBOutlet weak var buttonFour: UIButton!

@IBOutlet weak var generateImage: UIButton!

override func viewDidLoad() {

    self.buttonFour.hidden = true
    self.buttonOne.hidden = true
    self.buttonThree.hidden = true
    self.buttonTwo.hidden = true
    displayMessageLabel.hidden = true



}

@IBAction func generateRandomImages(sender: AnyObject) {


    displayMessageLabel.hidden = false


    buttonOne.hidden = false


    switch(random){

    case 0: buttonOne.imageView?.image = UIImage(named: "circle.png")
        break

    case 1: buttonOne.imageView?.image = UIImage(named: "decagon.png")
        break

    case 2: buttonOne.imageView!.image = UIImage(named: "diamond.png")
        break

    case 3: buttonOne.imageView!.image = UIImage(named: "hectagon.png")
        break
    default:
        break;

    }



    generateImage.hidden = true

}


}




Execute file compiled by sbcl cannot make random or make with-open-file work.

I write a script with using random and with-open-file, it works well in slime by emacs. But it cannot work when I use sbcl compile it to a execute file.

Code:

(defun choice-file-to-open (files)
  (let ((filePath (nth (random (length files)) files)))
    (open-by-system filePath)
    (with-open-file (file "./logs" :direction :output
                          :if-exists :append
                          :external-format '(:utf-8 :replacement #\?))
      (format file "~S~%" (namestring filePath)))))

open-by-system is a function to open file.

My purpose is pick random file in the folder. But it always choice the same file to open when I use it. Only for the singer execute file, the slime work well.

Then I add the log file to record the filename every time I open. But there is no log file, as same as problem before, this problem only issues in executed file, and code works well in slime.

I found the answer (Random) in Common Lisp Not So Random? and it cannot solve the random problem.

What wrong with me? There are many differences between slime and sbcl?




How to generate a series of unique double numbers in C++?

I know how to generate a series of integer numbers between (low,high) by using the subscript as another look up map's subscript. While this might not work for the double number? Any better Solution? (Better with C++ 11)




Converting an arbitrary seed into a float between 0 and 1

I want to be able to change any string containing any utf-8 into a random number between 0 and 1.

I can convert any seed that is a number with the following:

Math.abs(Math.sin(seed));

From this I'm able to generate a pseudo seeded Math.random()-like number.

So it's converting a string into a number. I looked into using crypto and found that making a digest of the string works but is incredibly slow, and is a bit overkill.

Any ideas on how to accomplish this?




Generate pseudo random float number between 0.0 (inclusive) and 1.0 (exclusive) in C++/Qt5

I want to generate a pseudo random number between 0.0f (inclusive) and 1.0f (exclusive) in C++ using Qt5.

How can I do this in the recommended/Qt way?




Team and Fight Randomizer in C

I'm trying to make a program, which puts a given amount of players in a given amount of teams. Afterwards they should be randomly chosen (eg. you roll the "dice" and Team 3's Player 42 and shall fight against Team 4's Player 22 (All the players are randomly put in the different teams, which are limited to the choice of the Gamemaster)).

In my code I have the basic output and structure. It says something like:

Team 1 now owns Player 43 Team 2 now owns Player 12 Team 4 now owns Player 1 Team 3 now owns Player 54

But my question is, how - based on the code - I could save this information and how can I (afterwards) let the players randomly fight? Members of the same team should NOT be able to fight each other and after each fight I want the players (if they lose in what ever game this gets translated into) to be somehow on a "blacklist" where they can't be rolled anymore.

My code so far

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

int main() {
        int mitglieder, teams, teameins = 0, teamzwei = 0, teamdrei = 0, teamvier = 0;
        printf("Teamcreation\n");
        printf("\nNumber of Players: ");
        scanf("%d", &mitglieder);
        printf("\nNumber of Teams: ");
        scanf("%d", &teams);
        printf("\nThere are ");
        printf("%d", mitglieder);
        printf(" Player in ");
        printf("%d", teams);
        printf(" Teams. \n");

        int array[mitglieder];

                for (int i = 0; i < mitglieder; i++) {     // fill array
                    array[i] = i;
                    
                }
                printf("The Player are in the following Teams: \n ");
                
                for (int i = 0; i < mitglieder; i++) {    // shuffle array
                    int temp = array[i];
                    int randomIndex = rand() % mitglieder;
                
                    array[i]           = array[randomIndex];
                    array[randomIndex] = temp;
                }
                
                
                for (int i = 0; i < mitglieder; i++) {    // print array
                        int random_number = rand() % teams + 1;
                        int tp = random_number;
                        if(tp == 1) {
                                        teameins+1;
                                        }else 
                                            if(tp == 2 ) {
                                                teamzwei+1;
                                            }else 
                                            if(tp == 3 ) {
                                                teamdrei+1;
                                            }else 
                                            if(tp == 4 ) {
                                                teamvier+1;
                                            
                                            }
                    printf("Team %d - Spieler: %d\n ",random_number,array[i] + 1);              
                }
                
                        if( (teamvier == 0) && (teamdrei == 0) ) {
                        printf("\n%d Mitglieder in Team 1 und %d Mitglieder in Team2",teameins,teamzwei);
                }else
                        if( (teamvier == 0) && (teamdrei < 0) ) {
                        printf("\n%d Mitglieder in Team 1, %d Mitglieder in Team2 und %d Mitglieder in Team3.",teameins,teamzwei,teamdrei);
                }else
                        if(teamvier < 0) {
                        printf("\n%d Mitglieder in Team 1, %d Mitglieder in Team2, %d Mitglieder in Team 3 und %d Mitglieder in Team4.",teameins,teamzwei,teamdrei,teamvier);
                        }
        return 0;
}



Sorting arrays with uncertain data

I am crafting a script for a browser game that will generate a random animal for the player to battle with anywhere from 0-5 markings. The markings on that animal are randomly generated and are fed into a custom imagick function, which will add them in order as they appear in the array.

While the markings are randomly decided, there are a lot of rules to how they are supposed to appear on an animal, for instance markings in the "full body" region show above markings in the "belly" region. To better explain, I'll attach an image of the tester so far:

enter image description here

So to break down the 5 markings on this randomly generated animal, the eyeshadow marking belongs to eye region, undertail belongs to tail, streaks belongs to fullbody, appaloosa belongs to back, and okapi belongs to legs. The order right now is just added as the script looped through the database and randomly selected markings, so okapi (the stripes on the legs) is on top since it was the last on in the array, and the last one added. But following the order rules, the last one in the array should have been streaks (the horizontal streaks across the body), since fullbody markings go on top.

Here is the code the selects markings, this is done using the Laravel engine:

    // Determine number of markings
    $num = mt_rand(1,10);

    if ($num == 1) {
        $markingNum = 0;
    } elseif ($num > 1 && $num < 4) {
        $markingNum = 1;
    } elseif ($num > 4 && $num < 6) {
        $markingNum = 2;
    } elseif ($num > 6 && $num < 8) {
        $markingNum = 3;
    } elseif ($num > 8 && $num < 10) {
        $markingNum = 4;
    } else {
        $markingNum = 5;
    }

    // Calculate Marking type and color
    $markings = array();

    if ($markingNum > 0) {
        for ($m = 0 ; $m < $markingNum; $m++) {
            // Set color values (pulls from the "pallet" selected earlier in the code, which will determine the range of color that marking can be)
            if ($m == 1) {
                $pal = $pallet->marking1;
            } elseif ($m == 2) {
                $pal = $pallet->marking2;
            } elseif ($m == 3) {
                $pal = $pallet->marking3;
            } elseif ($m == 4) {
                $pal = $pallet->marking4;
            } else {
                $pal = $pallet->marking5;
            }

            // Pull previous marking info
            if (count($markings) != 0) {
                    $previous = DataMarking::whereIn('name', array_keys($markings))->get();

                    // This pulls the regions of the current markings in the array so it won't select a region that already has a marking.
                    foreach ($previous as $p) {
                        $regions[$p->region] = $p->name;
                    }

                    // Uncommon marking (10% chance)
                    $r = mt_rand(1, 10);

                    if ($r == 10) {
                        $marking = DataMarking::where('rarity', 1)
                                              ->where('public', 1)
                                              ->whereNotIn('name', array_keys($markings))
                                              ->whereNotIn('region', array_keys($regions))
                                              ->orderByRaw("RAND()")
                                              ->first();
                    // Common markings
                    } else {
                        $marking = DataMarking::where('rarity', 0)
                                              ->where('public', 1)
                                              ->whereNotIn('name', array_keys($markings))
                                              ->whereNotIn('region', array_keys($regions))
                                              ->orderByRaw("RAND()")
                                              ->first();
                    }

                    // Colors marking
                    if ($pal == 0) {
                        $markingColor = rand_color();
                    } else {
                        $range = ColorRange::where('id', $pal)->firstOrFail();
                        $markingColor = "#" . mixRange(substr($range->start_hex, 1), substr($range->end_hex, 1));
                    }

                    $markings[$marking->name] = $markingColor;
                } else {
                // Uncommon marking (10% chance)
                $r = mt_rand(1, 10);

                if ($r == 10) {
                    $marking = DataMarking::where('rarity', 1)
                                          ->where('public', 1)
                                          ->orderByRaw("RAND()")->first();
                // Common marking
                } else {
                    $marking = DataMarking::where('rarity', 0)
                                          ->where('public', 1)
                                          ->orderByRaw("RAND()")->first();
                }

                // Colors marking
                if ($pal == 0) {
                    $markingColor = rand_color();
                } else {
                    $range = ColorRange::where('id', $pal)->firstOrFail();
                    $markingColor = "#" . mixRange(substr($range->start_hex, 1), substr($range->end_hex, 1));
                }

                $markings[$marking->name] = $markingColor;
            }
        }
    }

I figure I can accomplish this with a lot of complex if statements but it just doesn't seem like an elegant solution to me. In addition, there is an exception: 'Gradient', a fullbody marking, goes underneath everything even though it is a full body marking. So far it is the only marking with this sort of exception to it, though.

I have tried using various sort functions offered by PHP but I am not having much luck. uksort seems the most promising, but since the value we are sorting by exists in the database and not in the array we are sorting (the imagick function has to be fed a marking => color array format), it's proving difficult to work with.

Tl;dr: I need to reorder an array that an uncertain amount of data based off of values that exist in the DB for the keys (the region for the markings). What's the most elegant way to accomplish this?




How can I delay onClick action

I am trying to do something in java app (android) and I need something to delay/wait for an amount of seconds for a loop. How can I do delay android function? I have tried to use Thread.sleep(), TimeUnit.sleep, but it is only going to do irresponsible program for some seconds. I want to do some onClick actionlistener which updating for some seconds. e.g: if I clicked to button -> Text is changed to random(int) and it's should be done per second.

random ... waiting for a second ... random ... waiting for a second ... random ... and so many times

for (int i = 0; i < 10; i++) {
    int random = r.nextInt(100) - 10;
    String rand = Integer.toString(random);
    textView3.setText(rand);
    TimeUnit.SECONDS.sleep(1);
}




Retrieve random image with its caption from a MySQL database

all.

I would like my script to select a random image from a database. Then, from the same database, select the caption that goes along with it (there is a separate 'caption' row).

My problem is that whenever 'caption' gets updated in the database, it isn't getting updated with the random image that is being shown on the web page.

Picture of database here

Yes, I know that uploading images into a database isn't the best practice, but right now, I'm in a 'whatever works, works' mode.

Thanks for the help!




Looping failed if same value skipped

``hello anyone can you give me tips a random from array 2d i make a small code example

public function autoRandom($simpankota) {

    $alfa = 1.0;
    $beta = 1.0;
    $semut = 3;
    $rho = 0.5;
    $tijawal = 0.01;
    //$route[] = $simpankota;
    $new = new addLat();
    //$route1 [1] = $simpankota[sizeof($simpankota) - 1];

    $route[0] = 0;

    $route1[] = reset($simpankota);
      echo "<h1> apakah kota awal" . reset($simpankota) ."</h1>";
    $d = array();
    $simpankota2 = $simpankota;
    $simpankota1 = $simpankota;
    $simpankota3 = $simpankota;

    $zx = 0;
    $hit = 1;

    foreach ($simpankota1 as $key1 => $value1)
    {
        $zx++;

        $beban = array();
        $beban1 = array();
        $beban2 = array();
        $prob = array();

        echo "<h2>" . $simpankota1[$route] ."</h2>";

        foreach ($simpankota2 as $key2 => $value2) 
        {
            $berangkat = reset($simpankota1);
            $tujuankota = $value2;
            $prob = $this->getProbabilitas($berangkat, $tujuankota) * $tijawal;
            $prob1[] = $prob;
            $ar = array_sum($prob1);
        }

        foreach ($simpankota3 as $key3 => $value3) 
        {

            $start = reset($simpankota1);
            $value2 = $value3;

            if ($start != $value2) 
            {
                $beban1[] = ($tijawal * $alfa) * ($this->getProbabilitas($start, $value2)) / $ar;
                $beban2[] = array_sum($beban1);
            }
            else 
            {
                $beban1[] = ($tijawal * $alfa) * ($this->getProbabilitas($start, $value2)) / $ar;
                $beban2[] = array_sum($beban);
            }
        }
            $tempnama1 = 'null';
            $x;
            $tempselisih = 100000000000;

            $sum = $this->randomD();

            $beban = $beban2;
            $xzz = sizeof($beban);


            for ($i = 0; $i < sizeof($beban); $i++)
            {
                if ($sum > $beban[$i]) 
                {
                    if ($tempselisih > $sum - $beban[$i]) 
                    {
                        $tempselisih = $sum - $beban[$i];
                        $x = $tempselisih;
                        $tempnama1 = $i;
                    }
                } 
                elseif ($beban[$i] > $sum) 
                {
                    if ($tempselisih > $beban[$i] - $sum)
                    {
                        $tempselisih = $beban[$i] - $sum;
                        $x = $tempselisih;
                        $tempnama1 = $i;
                    }
                } 
                $flag=true;
                if ($tempnama1 == true)
                {
                    $beban2[$tempnama1]= 999;
                    $flag=false;
                }
            }


            $route[sizeof($route)] = $tempnama1;
    }
    $route [sizeof($route)] = sizeof($simpankota) - 1;
    echo "<h1> <pre>KAMPRET" .print_r($route,true) ."</pre></h1>";
    return $route;
}

but if i try open show like Array ( [0] => 0 [1] => 2 [2] => 4 [3] => 4 [4] => 4 [5] => 4 [6] => 4 )

but i want make like a if index visited not looping again if checked not itteration looping again Array ( [0] => 0 [1] => 2 [2] => 5 [3] => 3 [4] => 1 [5] => 4 [6] => 6 )

if value checked skip itteration and not get value same again
can you give me tips ?

so do you have some tips? sorry for bad english and bad logic:(

my full code in here

http://ift.tt/1PxbcNB




How to make an array of UILabels in Swift

i'm trying to make a random text array then call it on a label but errors keep showing up

let array = ["Yes", "No", "Maybe", "perhaps"] let randomIndex = Int(arc4random_uniform(UInt32(array.count)))

label.text = (array[randomIndex])




mardi 29 décembre 2015

Issues With Ordering Array from Greatest To Least

Below you will see what I have for making a random array. I am needing to order the items from greatest to least and then be able to put them into textboxes according to the class the user has picked. This is for a DnD 4e ability generator. I need to be able to put the highest ability scores into the best suited field for that class.

    Private Sub Button1_Click(sender As System.Object, e As System.EventArgs) Handles Button1.Click
    'Dim randstr As New Random

    'Dim a As Integer
    'Dim b As Integer
    'Dim c As Integer
    'Dim d As Integer
    'Dim h As Integer
    'Dim f As Integer


    'a = randstr.Next(3, 18)
    'b = randstr.Next(3, 18)
    'c = randstr.Next(3, 18)
    'd = randstr.Next(3, 18)
    'h = randstr.Next(3, 18)
    'f = randstr.Next(3, 18)

    Static randomNumberGenerator As New System.Random


    Dim randomNumbers(6) As Integer ' Create the array

    Dim smallestNumber As Integer = 3 ' Set the lower bounds

    Dim largestNumber As Integer = 18 ' Set the upper bounds



    For i = 0 To 6 ' loop through each element in the array

        randomNumbers(i) = randomNumberGenerator.Next(smallestNumber, largestNumber)

    Next

    If CbClass.SelectedItem = "Fighter" Then

    End If
End Sub




Swift random number insert in array or array list

My question is I want to make some app. Want to show random numbers and then it should go in to array or array list. Each number show in one second. then go in to array. I don't know how to make random numbers go in to array or array list.

(random number is label, in one second only one number shows, then it should insert to array or array list)




Generate random int and use it about 5 times before it changes to a new random number

Total newb pls help..there is a similar question but i didn't understand the explanation. I have this code

public int randomindex = new Random().nextInt(whatifphrases.length);

private String[] question = new String[]{
            why[randomindex],
            but[randomindex]
};

private int[] likability = new int[]{
        like[randomindex],
        dislike[randomindex]
};

I want the likability and question arrays use the same random number. For example, i want why[10] but[10] like[10] dislike [10] but what i get is why[10] but[10] like[15] dislike [15]




Python randint returns slightly off versions of numbers? [duplicate]

This question already has an answer here:

I'm trying to write a program to generate all the possible configurations of European money to make 2 Euros, but when I try to use randint to choose a random number from my list, it returns the numbers with a few extra numbers at the end.

pence = [.01, .02, .05, .1, .2, 1, 2]
from random import randint
for i in range(200):
    add = [0]
    while sum(add) < 2:
        add.append(pence[randint(0, 6)])
    print (add)
    print (sum(add))
    print ("")

It returns this:

[0, 0.050000000000000003, 2]
2.0499999999999998

I'm not sure how to round this number. How do I get it to stop giving me strange numbers?




runif() is not uniform

I'm writing a roulette simulator and I stuck just on the beginning. I wanted to draw integer from 0 to 36, so I used runif(). I noticed that 0's are outstanding. Have a look:

n=1000000
x=floor(runif(n,0,37))
hist(x,breaks=37)

Histogram: floor(runif(n,0,37))

To remove "0's" i wrote:

n=1000000
x=floor(runif(n,0,37)*100)/100
hist(x,breaks=37)

What gave me Histogram: enter image description here

And my question is why it works?




/dev/urandom error (permission denied by webhost)

I am using function:

private function random($len) {
        if (@is_readable('/dev/urandom')) {
            $f=fopen('/dev/urandom', 'r');
            $urandom=fread($f, $len);
            fclose($f);
        }

        $return='';
        for ($i=0;$i<$len;++$i) {
            if (!isset($urandom)) {
                if ($i%2==0) mt_srand(time()%2147 * 1000000 + (double)microtime() * 1000000);
                $rand=48+mt_rand()%64;
            } else $rand=48+ord($urandom[$i])%64;

            if ($rand>57)
                $rand+=7;
            if ($rand>90)
                $rand+=6;

            if ($rand==123) $rand=52;
            if ($rand==124) $rand=53;
            $return.=chr($rand);
        }
        return $return;
    }

I have some forms which trigger this function and I get the error:

int(2) string(200) "is_readable(): open_basedir restriction in effect. File(/dev/urandom) is not within the allowed path(s):

Is there a way to replace this function and not to use /dev/urandom ? Thank you very much.




Reading and Printing random number in FORTRAN

**Dear All, I have a following program and below the program there is input data file, which is contain 10 lines of different data. I want to read these data randomly not sequentially, for example, it will may read number 3 line then may be number 5 line not like number 1 2 3 4...Then these numbers I want to print randomly...Kindly help me

Thank You **

 program rand
  implicit none
  integer::i, ok
  real(kind=8) , allocatable , dimension(:):: s
  integer, parameter:: nstep = 1, natom = 10
  integer:: seed, rand


  open(unit=2,file="fort.2",status="old",action="read")


  allocate(s(natom),stat=ok)
  if(ok/=0)then
  print*,"problem allocating position array"
  end if

  do i=1,natom
  read(2,*)s(i)
  print*,i=(rand(seed))
  end do
  end program rand



Input file 
   1.004624
   1.008447
   1.028897
   1.001287
  0.9994195
   1.036111
  0.9829285
   1.029622
   1.005867
  0.9372157




lundi 28 décembre 2015

C# - Best way to randomize two identical arrays without overlap?

Suppose we have two identical arrays {"A", "B", "C", "D", "E", "F"}. Is there a quick way to randomize the order of each that ensures when the two are lined up, the same letters are never at the same indices? (Obviously we can just generate a new index if it will cause a match but I'm wondering if there's a way that produces less repetition).




Simple random function in an interval

It doesn't give me a value r in the given range? Why?

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

var x = window.prompt("minimo");
var y = window.prompt("maximo");
var r = getRandomIntInclusive(x,y);

console.log(r);

edit: This function has been taken from a link of dev mozilla Thank you




Exactly 5 numbers every time in php

I want to add exactly 5 random numbers to an array, but each number must be different. Here is what I have so far...

$col_B = array();

for ($i=1; $i < 6; $i++) { 
    $rand = $col_ranges['B'][rand ( 0 , 14 )]; // calls to an array of numbers
    if(!in_array($rand, $col_B)){
        $col_B[] = $rand;   
    }
    else{ $i - 1;}

}
echo implode($col_B, '<br>');




random number in python with constraints dependent on random numbers, Columns and Rows have to be unique: Pic Included

I'm helping my uncle out for a project and I realized I cannot use Excel for the solution--need to find a new way to solve:

The Problem:

Random number generation with constraints that are dependent on each row. See attached image: http://ift.tt/1OhrPOl

Each cell in every row (33 rows total) has to be different number between (1 - 33 ( only 17 are used per row)) but each column has to be different each week (all 33 are used).

Inputs:

I want the input variables to be a random number between 1-33 with the constraints above. For every row there are 17 inputs, for 17 weeks. so 561 inputs.

The problem is linear and I can't see it being too hard, but I'm not that good with python, so it is very hard.

My steps so far:

I put all the constraints into Excel solver and should have received a solution, but I have too many variable cells and it cannot solve (max variable number in Excel is 200).

I'm deciding to try python to try and solve now. I have random generation down, but can't figure out how to make sure 17 weeklyColumns with 1-33 sequence for each week.

I'm sure python has a solution, but would another language be easier?

Any tips?




Execute code with random delay on Ruby

I want to execute my function with random delay I tried several solutions but nothing worked

My code look like this

for i in (1..10)
  puts "Love Stack"
end

I have tried this :

def every_n_seconds(n)
  loop do
      before = Time.now
      yield
      interval = n-(Time.now-before)
      sleep(interval) if interval > 0
  end
end

for i in (1..10)
  a = [1,2,3,4,5,6,7,8,9]
  a.shuffle!
  b = a[1]
    every_n_seconds(b) do
      for i in (1..10)
        puts "test"
      end
    end
end

Have you a solution ?




Randomly generate enemies faster and faster Javascript

Hey I am using a Spawn function I found for a javascript game I am creating to randomy generate enemies to click on. But it is very slow and I would like it to be able to generate faster and faster.. is it possible to modify this code in that way? the spawn function is at the end of the code.

function Gem(Class, Value, MaxTTL) {
            this.Class = Class;
            this.Value = Value;
            this.MaxTTL = MaxTTL;
        };

    var gems = new Array();
    gems[0] = new Gem('green', 10, 0.5);
    gems[1] = new Gem('blue', 20, 0.4);
    gems[2] = new Gem('red', 50, 0.6);

    function Click(event)
    {
        if(event.preventDefault) event.preventDefault();
        if (event.stopPropagation) event.stopPropagation();
        else event.cancelBubble = true;

        var target = event.target || event.srcElement;

        if(target.className.indexOf('gem') > -1){
            var value = parseInt(target.getAttribute('data-value'));
            var current = parseInt( score.innerHTML );
            var audio = new Audio('music/blaster.mp3');
            audio.play();
            score.innerHTML = current + value;
            target.parentNode.removeChild(target);

            if (target.className.indexOf('red') > 0){
                var audio = new Audio('music/scream.mp3');
                audio.play();
                endGame("You lose");
            }

        }

        return false;
    }

    function Remove(id) {
        var gem = game.querySelector("#" + id);

        if(typeof(gem) != 'undefined')
            gem.parentNode.removeChild(gem);
    }

    function Spawn() {
        var index = Math.floor( ( Math.random() * 3 ) );
        var gem = gems[index];

        var id = Math.floor( ( Math.random() * 1000 ) + 1 );
        var ttl = Math.floor( ( Math.random() * parseInt(gem.MaxTTL) * 1000 ) + 1000 ); //between 1s and MaxTTL
        var x = Math.floor( ( Math.random() * ( game.offsetWidth - 40 ) ) );
        var y = Math.floor( ( Math.random() * ( game.offsetHeight -  44 ) ) );

        var fragment = document.createElement('span');
        fragment.id = "gem-" + id;
        fragment.setAttribute('class', "gem " + gem.Class);
        fragment.setAttribute('data-value', gem.Value);

        game.appendChild(fragment);

        fragment.style.left = x + "px";
        fragment.style.top = y + "px";

        setTimeout( function(){
            Remove(fragment.id);
        }, ttl)
    }
        function Stop(interval) {
            clearInterval(interval);
        }

        function endGame( msg ) {
            count = 0;
            Stop(interval);
            Stop(counter);
            var left = document.querySelectorAll("section#game .gem");
            for (var i = 0; i < left.length; i++) {
                if(left[i] && left[i].parentNode) {
                    left[i].parentNode.removeChild(left[i]);
                }
            }
            time.innerHTML = msg || "Game Over!";
            start.style.display = "block";
            UpdateScore();
        }

        this.Start = function() {
            score.innerHTML = "0";
            start.style.display = "none";
            interval = setInterval(Spawn, 750);

            count = 4000;
            counter = null;

            function timer()
            {
                count = count-1;
                if (count <= 0)
                {
                    endGame();

                    return;
                } else {
                    time.innerHTML = count + "s left";
                }
            }

            counter = setInterval(timer, 1000);

            setTimeout( function(){
                Stop(interval);
            }, count * 1000)
        };
        addEvent(game, 'click', Click);
        addEvent(start, 'click', this.Start);
        HighScores();
    }




Why use Float(arc4random()) / 0xFFFFFFFF instead of drand()

I'm new to Swift and just saw this code used to generate a random angle degree in a tutorial.

func random() ->CGFloat{
    return CGFloat(Float(arc4random()) / 0xFFFFFFFF)
}
func random(#min: CGFloat, max:CGFloat) ->CGFloat{
    return random()*(max-min)+min
}

I'm wondering is the line return CGFloat(Float(arc4random()) / 0xFFFFFFFF) generates a random float number between 0 and 1.0? Then why cannot just use drand()? Any difference between the two functions? Thanks!




C++11: How to set seed using

I am exercising the random library, new to C++11. I wrote the following minimal program:

#include <iostream>
#include <random>
using namespace std;
int main() {
    default_random_engine eng;
    uniform_real_distribution<double> urd(0, 1);
    cout << "Uniform [0, 1): " << urd(eng);
}

When I run this repeatedly it gives the same output each time:

>a
Uniform [0, 1): 0.131538
>a
Uniform [0, 1): 0.131538
>a
Uniform [0, 1): 0.131538

I would like to have the program set the seed differently each time it is called, so that a different random number is generated each time. I am aware that random provides a facility called seed_seq, but I find the explanation of it (at cplusplus.com) totally obscure:

http://ift.tt/1MCJ9b3

I'd appreciate advice on how to have a program generate a new seed each time it is called: The simpler the better.




dimanche 27 décembre 2015

vb.net combine random password

I need some help. I'm creating a login system in which has five buttons, each button will have two random numbers, these numbers will change every time the application loads, just like this picture.

See image

My question is what is the best way to check if the password is true or not?

  • The password consists of four digits
  • Once the user click on four buttons I'll have 8 different numbers

Let me know if my question isn't clear enough.




How can I generate random sequences from 0 to 12000 in C#?

How can I generate random sequences in example from 0 to 12000 in C#? I don't need only one sequence. I need generate all 12000 sequences from 0 to 12000.




Be fast to create a big numpy array of random boolean

I need to create a big random boolean numpy array without going on swap. I use a laptop with 8Gb.

Create a 1200x2e6 array is less than 2s and use 2.29 Go of RAM:

>>> dd = np.ones((1200, int(2e6)), dtype=bool)
>>> dd.nbytes/1024./1024
2288.818359375

>>> dd.shape
(1200, 2000000)

For a small 1200x400e3 array using np.random.randint it's fast, 5sec the db has 458Mb:

db = np.array(np.random.randint(2, size=(int(400e3), 1200)), dtype=bool)
print db.nbytes/1024./1024., 'Mb'

But only twice bigger db 1200x800e3 array it go on swap and take 2.7 min ;(

cmd = """
import numpy as np
db = np.array(np.random.randint(2, size=(int(800e3), 1200)), dtype=bool)
print db.nbytes/1024./1024., 'Mb'"""

print timeit.Timer(cmd).timeit(1)

Using getrandbits take even longer, 8min and went on swap too:

from random import getrandbits
db = np.array([not getrandbits(1) for x in xrange(int(1200*800e3))], dtype=bool)

Using np.random.randint for a 1200 x 2e6 array we get a MemoryError

So what is the solution to create a random boolean 1200x2e6 array in a fast way ?




Generate a list of random string of fixed length in python

I need to generate a list which will have random alphanumeric string of fixed length. It will be something like: list = ['ag5','5b9','c85'] I can make the list with random numbers, but i can't work out to make strings which will have both numbers and letters.The list will have fixed length(say 100 item). I am using python 3.




PHP Array issue (beginner)

I'm receiving an integer value from my array, instead of a name. How can i correct my code to randomly select a name from the array?

$family = array();
        array_push($family, "joe");
        array_push($family, "bill");
        array_push($family, "carl");
    $sorted = sort($family);
    $select = rand(0, count($sorted) - 1);

    echo $select;




Why do I get no random number?

I try to get this code to run. The code should generate me a integer number from 1 to 99999999 but always when I run it it only responds with 0. Could someone please tell me why?

  public ActionResult Edit([Bind(Include="AccountId,Balance,AccountType,AppUserId")] 
  Account   account)
    {
        if (ModelState.IsValid)
        {
            //account.AppUserId = User.Identity.GetUserId();
            Random rand = new Random();
            int bankId = 0;
            int i = 0;
            do
            {
                bankId = rand.Next(1, 100000000);
                if ((db.Accounts.Find(bankId)) == null)
                {
                    i = 1;
                    account.AccountId = bankId;
                }
                else
                {
                    i = 0;
                }
            } while (i == 0);                
            db.Accounts.Add(account);
            db.SaveChanges();
            return RedirectToAction("Index");
        }
        ViewBag.AccountType = new SelectList(db.AccountTypes, "AccountTypeId", "AccType", account.AccountType);
        return View(account);
    }




Generate random number in interval in PostScript

I am struggling to find a way to generate a random number within a given interval in PostScript.

Basically PostScript has three functions to help you generate (pseudo-)random numbers. Those are rand, srand and rrand.

The later two are for passing a seed to the number generator to be able to reproduce specific results. At least that´s what I understood they are for. Anyway they don´t seem suitable for my case.

So rand seems to be the only function I can use to generate a random number, but...

rand returns a random integer in the range 0 to 231 − 1
(From the PostScript Language Reference, page 637 (651 in the PDF))

This is far beyond the the interval I´m looking for. I am more interested in values up to small thousands, maybe 10.000 or something like that and small float values, up to 100, all with the lower limit of 0.

I thought I could just narrow my numbers down by simple divisions and extracting the root but that tends to give me unusable small values in quite a lot cases. I am wondering if there are robust ways to either shrink a large number down to what I need or, I´d prefer that, only generate numbers in the desired interval.

Besides: while-loops are not possible in PostScript, otherwise I´d have written a function to generate numbers until they fit in my interval.

Any hints on what to look for breaking numbers down into my interval?




Cannot use !random! in batch file

@echo off
setlocal enableDelayedExpansion

set /p startIndex="Start index: "
set /p endIndex="End index: "

for /l %%a in (%startIndex% 1 %endIndex%) do (
    set /a seed = !random!
    echo %seed%
)
set /p endfile="Wait for it...."

I expect that this script will print out some random numbers. But it does not work. It just printed out some lines with same content: "Echo is off ."

How can I fix this code ?




Generate random number in delphi

i want to create a random number in delphi and assign it to file as a file name. I managed to do that but when i click button to generate number it always start with a 0. Any idea how to fix it

procedure TForm1.Button1Click(Sender: TObject);
var
test:integer;

begin
test:= random(8686868686868);

edit1.Text:= inttostr(test);
end;

end.




Generate a random number doesnt work when calling function twice

Im trying to get 2 different types of numbers/colors when im calling my function twice, but it doesnt work. I've seeded the numbers/function but its still not working.

Here's how my code looks:

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

#define DIAMONDS 0
#define CLUBS 1
#define HEARTS 2
#define SPADES 3
#define JACK 11
#define QUEEN 12
#define KING 13
#define ACE 1
#define COLOR_SIZE 13
#define NR_OF_SUITS 4
#define DECK_SIZE 52


struct Card
{
    int suit;
    int value;
};

void printCards(struct Card *cardDeck);
void swapCards(struct Card *cardA, struct Card *cardB);
void shuffleCards(struct Card *cardDeck);
void printOneCards(struct Card *cardDeck);

int main()
{
    //struct Card deck[DECK_SIZE];      //Statiskt allokerad array
    struct Card * deck; //Dynamiskt allokerad array
    int index;
    int suit_index;

    deck = (struct Card *)malloc(sizeof(struct Card) * DECK_SIZE);
    for (suit_index = 0; suit_index < NR_OF_SUITS; suit_index++)    /* Initiera kortleken */
        for (index = 0; index < COLOR_SIZE; index++)
        {
            deck[suit_index*COLOR_SIZE + index].suit = suit_index;
            deck[suit_index*COLOR_SIZE + index].value = index;
        }
    printCards(deck);
    shuffleCards(deck);
    printCards(deck);
    printf("\n");
    printOneCards(deck);
    printf("Dealers cards\n");
    srand(time(NULL));
    printOneCards(deck);

    system("pause");
    return 0;
}

void printCards(struct Card *cardDeck)
{
    for (int i = 0; i < DECK_SIZE; i++)
    {
        switch (cardDeck[i].value + 1)
        {
        case ACE: printf("Ace ");
            break;
        case JACK: printf("Jack ");
            break;
        case QUEEN: printf("Queen");
            break;
        case KING: printf("King ");
            break;
        default: printf("%d ", cardDeck[i].value + 1);
            break;
        }
        printf("of ");
        switch (cardDeck[i].suit)
        {
        case DIAMONDS: printf("Diamonds ");
            break;
        case HEARTS: printf("Hearts ");
            break;
        case CLUBS: printf("Clubs ");
            break;
        case SPADES: printf("Spades ");
            break;
        default: printf("Something went wrong!! ");
            break;
        }
        printf("\n");
    }
}

void swapCards(struct Card * cardA, struct Card *cardB)
{
    struct Card temp;
    temp = *cardA;
    *cardA = *cardB;
    *cardB = temp;
}

void shuffleCards(struct Card *cardDeck)
{
    srand(time(NULL));

    for (int i = 0; i < DECK_SIZE; i++)
        swapCards(&cardDeck[i], &cardDeck[rand() % 52]);
}
void printOneCards(struct Card *cardDeck)
{
    srand(time(NULL));
    for (int i = 0; i < 2; i++)
    {
        switch (cardDeck[i].value + 1)
        {
        case ACE: printf("Ace ");
            break;
        case JACK: printf("Jack ");
            break;
        case QUEEN: printf("Queen");
            break;
        case KING: printf("King ");
            break;
        default: printf("%d ", cardDeck[i].value + 1);
            break;
        }
        printf("of ");
        switch (cardDeck[i].suit)
        {
        case DIAMONDS: printf("Diamonds ");
            break;
        case HEARTS: printf("Hearts ");
            break;
        case CLUBS: printf("Clubs ");
            break;
        case SPADES: printf("Spades ");
            break;
        default: printf("Something went wrong!! ");
            break;
        }
        printf("\n");
    }
}

So when im calling the function printonecards(), it prints out 2 randomly cards and colors the first time, but the second time i call it, it doesnt. How do i fix this problem and how do i make it properly work?




Modifying the polar coordinates of a disk with random dots in Matlab

I am trying to create a dynamic random dots stereogram by updating the position of the dots, so that I can get an inward motion of the dots (optic flow). I first created a disk filled with dots whose position is randomised:

se = strel('disk',4);
x = linspace(-1,1,768); %generates 768 points in a vector with a [-1:1] interval
[X,Y] = meshgrid(x,x); %generates a rectangular grid in replicating the x vector.
[T,R] = cart2pol(X,Y); 

threshold = 1 - (dot_nb / 768^2); %dot_nb=5;
Rd = double(rand(768,768)>threshold);
Rd(R>0.95 | R<0.06)=0; %remove some of the dots in order to get a circle and no dots in the middle of it

I am now trying to update the location of the dots at a specific refresh rate (20Hz) but I am having troubles with it. I thought the following lines of code (which are in a bigger loop controlling the frame rate) could work but obviously something is missing and I do not know how else I could do it:

update = 0.1; 
for i = 1:size(R,1) %R is the matrix with the radius values of the dots
for j = 1:size(R,2)
 if R(i,j)<0.95 && R(i,j)>0.06
     R(i,j) = R(i,j)-update;
 else
     R(i,j)=0;
 end
end
end

Has anyone any idea how I could do to get what I'm looking for? Thank you in advance!




Math.random() v/s Random class

The Math class in Java has a method, Math.random() which returns a pseudorandom number between 0 and 1.
There is also a class java.util.Random which has various methods like nextInt(), nextFloat(), nextDouble(), nextLong()etc.

My question is that if I want to get a random number in a range (say, 30-70), then which way should I go? The factors under consideration are speed and randomness.




How to seed rand() in IBM Swift Sandbox?

I am new to StackOverflow so please correct me if there is a better way to post a question which is a specific case of an existing question.

Alberto Barrera answered How does one seed the random number generator in Swift?

with

let time = UInt32(NSDate().timeIntervalSinceReferenceDate)
srand(time)
print("Random number: \(rand()%10)")

which is perfect generally, but when I try it in The IBM Swift Sandbox it gives the same number sequence every run, at least in the space of a half hour.

import Foundation
import CoreFoundation

let time = UInt32(NSDate().timeIntervalSinceReferenceDate)
srand(time)
print("Random number: \(rand()%10)")

At the moment, every Run prints 5.

Has anyone found a way to do this in the IBM Sandbox? I have found that random() and srandom() produce a different number sequence but similarly are the same each Run. I haven't found arc4random() in Foundation, CoreFoundation, Darwin, or Glibc.

As an aside, I humbly suggest someone with reputation above 1500 creates a tag IBM-Swift-Sandbox.




samedi 26 décembre 2015

How well do Python sets randomize? [duplicate]

First of all, I know that I should never attempt what I describe in this question and this is purely hypothetical so please don't yell at me.

Python sets don't maintain order because they are hash-maps without the map part. So I was wondering how well they are at randomizing things. It obviously isn't enough for crypto, and won't work on ints (because Python hash is identity on ints), but is it good enough for games and stuff?

It makes sense that it would work decently because its modding on a hash, but I'm not really sure how good that hash is and how well it'll work for randomizing.

P.S: Sets will always return the same shuffle for the same values, but you can assume that that isn't a problem.




Questions about random number with array in swift?

I just started to learned swift I want to make random generator with array. how can I make random generator that shows between 0-9 number in iPhone. then I want to try to make match. if it shows 9 and if I put input number 9. it is correct then pass to next number automatically. Can you guys make this?




Master degree thesis(adaptive system)?

My thesis it will be about "adaptive system" until now I didn't fix my abstract so can you please recommend me good abstract and some links or books ? Thank you




How to Spawn Two Different Objects Randomly in Two Specified Positions in Unity 2D?

I am working on a 2D project and I am trying to instantiate two different objects using two different positions that are already specified in the code. Each object should pick one random value of the two positions. So each time the player runs the game, the objects can exchange their positions. My problem is that sometimes the two objects pick the same exact position, which is wrong. The followings are the only two possibilities that should work in the game:

Possibility 1: 1

Possibility 2: 2

This is the code I am using:

using UnityEngine;
using System.Collections;

public class Randomizer : MonoBehaviour
{

    public GameObject[] prefab;
    int prefab_num;
    Vector3[] positions;
    Vector3 pos1;
    Vector3 pos2;

    void Start(){ 
        prefab_num = Random.Range(0,1);
        positions = new Vector3[]{new Vector3 (-5, 0f, 0f), new Vector3 (5, 0f, 0f)};
        pos1 = positions [Random.Range (0, positions.Length)];
        pos2 = positions [Random.Range (0, positions.Length)];
        Instantiate (prefab [0], pos1, Quaternion.identity);
        Instantiate (prefab [1], pos2, Quaternion.identity);

    }

    void Update(){ // Here I am trying to prevent objects from spawning on each other but it didn't work for me
        if (pos1 == positions [0] && pos2 == positions [0]) {
            prefab [prefab_num].transform.position = positions [1];
        } else if (pos1 == positions [1] && pos2 == positions [1]) {
            prefab [prefab_num].transform.position = positions [0];
        }
    }       
}




How to generate a random key in C# with stripes? [duplicate]

This question already has an answer here:

I would like to make a function that returns a key like this " XXXX-XXXX-XXXX-XXX" but when I use this code the key always return with the same 4 digit numbers. ex: ABCD-ABCD-ABCD-ABCD. Can anyone help?

public string Get(string Secret)
{
    string key = "" + RandomString(4) + "-" + RandomString(4) + "-" + RandomString(4) + "-" + RandomString(4);
    return key;
}

private string RandomString(int length)
{
    const string chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
    var random = new Random();
    return new string(Enumerable.Repeat(chars, length)
          .Select(s => s[random.Next(s.Length)]).ToArray());
}




Filling a 2D Array with Random Letters - C Programming

So in the previous thread I wasn't clear about the issue and I posted a lot of code.

I'm totally new to C Progamming and I encountered some issues.

I'm trying to create a Word Search, however I encountered a problem.

I'm trying to fill the Word Search Grid ( a 2D array) with random single characters) (Characters like A,B,C,D,E... )

I'm trying to use the rand() function , however I can't get it to fill the whole 2D array. When I'm trying it I only can get it to fill the first slot.

This is the code where it fills the puzzle. At the moment I filled with with '.'

void createBlankPuzzle()
{
    int i , j;

    for(i = 0;i < ROWS;i++)
    {
        for(j = 0;j < COLUMNS;j++)
        {
            puzzle[i][j] = '.';
        }
    }
}

I'm trying to generate the random character with the rand() function.

char getRandomCharacter() 
{
    int rl = (rand() % 26) + 65;

    return (char)rl;
}   

I hope this is clear enough and I tried to use good formatting.




php/javascript random number

Hello i am playing around with javascript and trying to choose some random images.

What i'm actually trying to do i have $totalsixes = rand(1,6); in php and lets say that chose 4 then in javascript i want to show 4 images with the number 6 and 2 others whit random numbers from 1-5

here's what I've tried so far:

<?php
$totalsixes = rand(1,6);
?>
<script type="text/javascript">
function shuffle(o){ 
    for(var j, x, i = o.length; i; j = Math.floor(Math.random() * i), x = o[--i], o[i] =     o[j], o[j] = x);
    return o;
};

var imagePaths = shuffle([
    "http://ift.tt/1Tlc09v",
    "http://ift.tt/1J9tyEZ",
    "http://ift.tt/1Tlc09x",
    "http://ift.tt/1J9tyF1",
    "http://ift.tt/1Tlc0pN",
    "http://ift.tt/1J9tyF3"]);

for(var i = 0; i < imagePaths.length; i++) {
    document.getElementById("randterning" + i).src = imagePaths[i];
}
</script>

as you may see above the $totalsixes have no meaning at all in the code yet, as i don't know how to tell the javascript to show X of sixes ($totalsixes chose the X), and also i don't know how to make the javascript chose a random number for those others dices. total there is always 6 dices.

hope it was easy for you to understand what i meant and hopefully you can help me.

Thanks and sorry for my English.




rand% spawning all my entities in predictable pattern

I have been trying to create a "1D shooter game" with prints in c++. My problem is I am trying to spawn enemies from a list at random moments and I also want to make it random where the enemy spawns (left or right of the screen).

This does not seem to fully work, as I seem to get a stream of contiguous enemies from one side, and only after all those enemies coming from the left side are killed, enemies from the right might appear.

I never seem to get a couple coming from the left and a couple coming from the right at similar times. Its always either one or the other. In addition to this, once an enemy is spawned, the rest seem to spawn almost all at once, and suddenly there is no spawning whatsoever. The pattern seems predictable and wrong.

Here is my method that is called every time in the game loop (the game loop takes care of calling srand(time(NULL)) on every iteration, and after that calls this function.

void Enemy::spawnEnemy()
{
    if (enemList.size() < 5)
    {
        if (!(rand() % 3))
        {
            if (!(rand() % 2))
            {
                Enemy * newEnemy = new Enemy(worldWidth, 'l');
                enemList.push_front(newEnemy);
            }
            else
            {
                Enemy * newEnemy = new Enemy(0, 'r');
                enemList.push_front(newEnemy);
            }
        }
    }
}

Thank you very much in advance. I really hope someone can solve this problem, because I have been struggling to find an answer for it!




Issue with filling a grid with random letters - C Programming

I'm totally new to C Progamming and I encountered some issues.

I'm trying to create a Word Search, however I encountered a problem.

I'm looking to generate random letter inside the 2D array however I can't manage to do that with the srand function.

This is how the code looks like:

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

#define ROWS 10
#define COLUMNS 10




int getRandomWord()
{

    char *names1[]= {"DOG" , "CAT", "HORSE" , "SNAKE" };
    char *names2[]= {"RAT", "FOX", "FISH", "DRAGON" };
    char *names3[]= { "TIGER", "COW", "SHARK", "BEAR" };
    char *names4[]= { "NOSE", "TICKET", "GIRAFFE", "CAKE" };
    char *names5[]= { "HOLE", "RECORD", "DRY", "BED" };
    char *names6[]= { "LACE", "ZIP", "CAMP", "FROG" };
    char *names7[]= { "SHIP", "TOWN", "FLAG", "DRUMS" };
    char *names8[]= { "BEE", "SEA", "FIRE", "WATER" };

    int l;
    int rn = (rand() % 8) + 1;

    printf ("These are the random words:");

    switch(rn)

    {
    case 1 : 
            for (l = 0; l  <4; l++ )
    {
        printf (" %s", names1[l]);
    }
        break;

    case 2 : 
            for (l = 0; l  <4; l++ )
    {
        printf (" %s", names2[l]);
    }
        break;

    case 3 :  
            for (l = 0; l  <4; l++ )
    {
        printf (" %s", names3[l]);


    }
        break;

    case 4 :  
            for (l = 0; l  <4; l++ )
    {
        printf (" %s", names4[l]);


    }
        break;

    case 5 :  
            for (l = 0; l  <4; l++ )
    {
        printf (" %s", names5[l]);


    }
        break;

    case 6 :  
            for (l = 0; l  <4; l++ )
    {
        printf (" %s", names6[l]);


    }
        break;

    case 7 :  
            for (l = 0; l  <4; l++ )
    {
        printf (" %s", names7[l]);


    }
        break;

    case 8 :  
            for (l = 0; l  <4; l++ )
    {
        printf (" %s", names8[l]);


    }
        break;
    default : puts ("Invalid");

    }

    getchar();

    }



    char puzzle[ROWS][COLUMNS];

char getRandomCharacter() 
{
    int rl = (rand() % 26) + 65;
    return (char)rl;
}    


void createBlankPuzzle()
{
    int i , j;

    for(i = 0;i < ROWS;i++)
    {
        for(j = 0;j < COLUMNS;j++)
        {
            puzzle[i][j] = '.';
        }
    }
}

void displayPuzzle()   //gridpositions

{
    int i , j;
    char x = 'A';

    printf("\t");


    for(i = 0; i< COLUMNS; i++)
    {
        printf( "%c    " , x );
        x++;
    }
    printf ("\n\n");

    for (i=0; i < ROWS ; i ++)
    {
        printf("%d\t" , i);

        for(j = 0 ; j < COLUMNS ; j++ )
        {

            printf("%c    " , puzzle[i][j]);
        }
        printf ("\n\n");
    }
}



void createMenu()
{
    while(1)
{
    int selection = 0;
    printf("Menu\n");
    printf(" Press 1 to start the game\n");
    printf(" Press 2 to exit the game\n" );


    scanf("%d" , &selection);


    switch(selection)
    {
    case 1:
    createBlankPuzzle();
    displayPuzzle();
    getRandomWord();


    printf("\n");
    printf("\n");
    break;

    case 2:
        exit(0);
    break;


    default: puts ("Invalid Option");

    }

    }
}


    int main(void)
{   
    srand(time(NULL));
    createMenu();
    getchar();

}




vendredi 25 décembre 2015

pass random numbers generated from Rand() to other pages for verification

I am trying to get a way to get the phone number of the users on my website verified. to do that i am integrating an SMS gateway. this will work like this :-

step 1 /page 1 - User clicks on a button to get their phone number verified. Which runs the script that sends an SMS to their phone number with a random number and re-directs the user to page 2. Please see code below:-

    <?php
// Start the session
session_start();
?>
<html>
<head>
</head>
<body>
<form id="sms2" name="sms2" method="POST" action="sms3.php">
<table width= "400">

<tr>
  <td align="right" valign="top">Verification Code:</td>
  <td align="left"><textarea name="Vefificationcode" cols="80" rows="20" id="Vefificationcode"></textarea></td>
  </tr>
  <tr>
  <td colspan="2" align="right"><input type="submit" name= "submit" value="submit"/></td>
  <p>
<?php
$_SESSION['phverf'] = rand();//set the session variable
$phverf= rand();//stores the value of rand function in phverf variable
echo "$phverf" . "\n"; // echo this just to check...when users inputs the random number received on sms
?></p>
  </tr>
  </table>
  </form>


</body>
</html>

step2/ Page2 - has an input box for the user to type in the same verification code they received in SMS. and hit submit. They go to the 3rd Page. Please see code below :-

    <?php
session_start();
?>

<html>
<head>
</head>
<body>

<?php
   echo $_SESSION['phverf'];
if(isset($_POST['submit'])){

$verificationcode= $_POST['Vefificationcode'];
echo $verificationcode;

if($_SESSION['phverf']==$verificationcode){echo"you have successfully verified your Phone Number";}
else {echo "Please type in the code sent to your phone number correctly";}
}
?>


<body>
</html>

Thanks Pranay




Why does my use of pcg64_once_insecure() not produce unique random numbers?

I'm attempting to use the PCG random number generator functions that are described as producing "each number exactly once during their period", such as pcg64_once_insecure. However, in my hands they produce some duplicate numbers. My question is, why? Am I using the functions incorrectly, or do I misunderstand their documentation and their purpose?

Here is a simple test program using one of the functions; you can substitute others from the *_once_insecure list instead of pcg64_oneseq_once_insecure used here. Also, you get repeats even when the upper bound is removed (i.e., calling rng() without arguments), although I don't show that code here (but I did try it):

#include <random>       // for random_device
#include "pcg_random.hpp"

using namespace std;

int main(int argc, char** argv)
{
    // Default values.
    int upper_bound = -1;
    int how_many    = 5000000;

    // Read command line arguments.
    int c;
    while ((c = getopt(argc, argv, "n:u:")) != -1) {
        switch (c) {
        case 'n':
            how_many = atoi(optarg);
            break;
        case 'u':
            upper_bound = atoi(optarg);
            break;
        }
    }

    // Set things up.
    pcg64_oneseq_once_insecure rng(42u);
    rng.seed(pcg_extras::seed_seq_from<std::random_device>());

    // Generates a uniformly distributed 32-bit unsigned integer less than
    // bound, such that 0 <= x < bound.
    if (upper_bound > 0)
        for (int count = 0; count < how_many; ++count)
            printf("%d\n", rng(upper_bound));
    else
        for (int count = 0; count < how_many; ++count)
            printf("%d\n", rng());

    return 0;
}

I compile it with this simple Makefile on a Mac OS X 10.10 system:

CPPFLAGS += -I/usr/local/include -Wno-format
CXXFLAGS += -std=c++11
CC        = $(CXX)

all: generate-random-numbers

generate-random-numbers: generate-random-numbers.o

And here is a simple test command line that detects duplicates:

./generate-random-numbers -n 100000 | sort | uniq -c | egrep '^   2'

When I run this repeatedly, I get dozens of duplicate numbers.

Can anyone explain to me what I am doing wrong?

EDIT 2015-12-25 21:49 PST: I updated the code to provide the ability to call rng() with and without arguments. Whether called with an upper bound or not, it still generates repeats.




Randomizing position of button Obj C

Right now my code makes it so that when a user clicks Button A, Button A changes to a random position on the screen. How do I make it so that the button changes to a random position anywhere on the screen, but not go lower than the bottom portion of the screen (to allow room for a banner ad and the button not go behind the banner ad)? NOTE: the name of my button is "blackDot"

Here is what I have:

-(IBAction) mainClickButton{


int xmin = ([blackDot frame].size.width)/2;
int ymin = ([blackDot frame].size.height)/2;

int x = xmin + arc4random_uniform(self.view.frame.size.width - blackDot.frame.size.width);
int y = ymin + arc4random_uniform(self.view.frame.size.height - blackDot.frame.size.height);


    [blackDot setFrame:CGRectMake(x,y,blackDot.frame.size.width,blackDot.frame.size.height)];


}




DrawCard blackjack from CSharpforBeginners

I'm just starting c# and I'm following Bob Tabor's C# Fundamentals for Absolute Beginners and part of the course information it gives a companion guide. On the Module 6 lab I'm stuck on trying to figure out how to draw a card in a game of black jack. I'm trying to stick to the course material so I would like to try to figure this out using arrays vs list which I know would be easier.

So my problem is that I'm not sure at the end why my return drawCard[0] throws an exception

Index was outside the bounds of the array

when I am specifically calling position 0 and how would I go about fixing this?

public Card DrawCard()
    {
        // Will generate a random number between 0 and 51.
        Random getRandomNumber = new Random();
        int randomNumber = getRandomNumber.Next(0, 52);
        // Created array drawnCard so I could set array Cards = to it.
        Card[] drawnCard = new Card[0];            

        // Checks to see if the deck is empty.
        if (cardsDrawn == 52)
        {
            drawnCard[0] = null;
            Console.WriteLine("No cards left to draw.");
        }
        // Sets the drawnCard to a random card pulled from the deck.
        else if (Cards[randomNumber] != null)
        {
            Array.Copy(Cards, randomNumber, drawnCard, 0, 0);
            //drawnCard[0] = Cards[randomNumber];
            Cards[randomNumber] = null;
            cardsDrawn++;
        }
        else
        {
            // Keeps looping until cards has been drawn.
            while (Cards[randomNumber] == null)
            {
                randomNumber = RandomGenerator.Next(0, 52);
                if (Cards[randomNumber] != null)
                {
                    Array.Copy(Cards, randomNumber, drawnCard, 0, 0);
                    //drawnCard[0] = Cards[randomNumber];
                    Cards[randomNumber] = null;
                    cardsDrawn++;
                }
            }
        }
        return drawnCard[0];
    }




My Unity Script Wont work?

Hi I have a script attached to the main camera, and in this script I want to choose a number between 0 to 5 . And depending on what number I get, I want a script to run. Hers my script that is attached to the main camera. I keep getting this error

NullReferenceException: Object reference not set to an instance of an object RandomFunction.Start () (at Assets/Resources/Scripts/RandomFunction.cs:22)

using UnityEngine;
   using System.Collections;
   public class RandomFunction : MonoBehaviour {
     int n;
     void Awake()
     {
         GetComponent<RandomFunction> ().enabled = true;
     }
     void Start () 
     {
         n=Random.Range(0,5);
         if(n==0)
         {
             GetComponent<BlueGoUp> ().enabled = true;
         }
         else if(n==1)
         {
             GetComponent<RedGoUp> ().enabled = true;
         }
         else if(n==2)
         {
             GetComponent<GreenGoUp> ().enabled = true;
         }
         else if(n==3)
         {
             GetComponent<OrangeGoUp> ().enabled = true;
         }
         else if(n==4)
         {
             GetComponent<YellowGoUp> ().enabled = true;
         }
         else if(n==5)
          {
             GetComponent<PurpleGoUp> ().enabled = true;
         }
     }

 }




Why does that loop sometimes click randomly on screen?

I have made that loop my self and Iam trying to make it faster, better... but sometimes after it repeat searching for existing... it press random ( i think cuz its not similar to any img iam using in sikuli ) place on the screen. Maybe you will know why.

Part of this loop below

    while surowiec_1:        
        if exists("1451060448708.png", 1) or exists("1451061746632.png", 1):
            foo = [w_lewo, w_prawo, w_dol, w_gore]                
            randomListElement = foo[random.randint(0,len(foo)-1)]
            click(randomListElement)
            wait(3)
        else:
            if exists("1450930340868.png", 1 ):
                click(hemp)
                wait(1)
                hemp = exists("1450930340868.png", 1)
            elif exists("1451086210167.png", 1):
                click(tree)
                wait(1)
                tree = exists("1451086210167.png", 1)
            elif exists("1451022614047.png", 1 ):
                hover("1451022614047.png")
                click(flower)
                flower = exists("1451022614047.png", 1)
            elif exists("1451021823366.png", 1 ):
                click(fish)
                fish = exists("1451021823366.png")
            elif exists("1451022083851.png", 1 ):
                click(bigfish)
                bigfish = exists("1451022083851.png", 1)
            else: 
                foo = [w_lewo, w_prawo, w_dol, w_gore]                
                randomListElement = foo[random.randint(0,len(foo)-1)]
                click(randomListElement)
                wait(3)

I wonder if this is just program problem with img recognitions or I have made a mistake.




JAVA GAME loop?

I have a problem with my java game. I’m beginner, but i have to write it as a school project.
Game is called „Birthday Cake” there is 7 candles on the cake and randomly one of it is showing for let say 30s and during this time u have to click on it to get point, if u don’t click on it during this time next candle will show. Game end when 10 candle shows.
I made for loop and i tried to make it work for sooo long that I’m dying from frustration
my for loop works but it is so fast that i use Thread.sleep(1000), i tried lots of solutions it looks ok. BUT when i start my game nothing is happening and after few seconds all 7 candles shows and quickly disappear. I think I’m doing something wrong, but i have no idea what.

   if(Dane.start){

        int liczbaLosowa = 0;

        for(int i=0; i<10 ;i++){
            liczbaLosowa = (int)(Math.random()*7);

            this.wspX= wspX_p[liczbaLosowa];
            this.wspY= wspY_p[liczbaLosowa];
            g2d.drawImage(plomienImg, wspX, wspY,null);
            Toolkit.getDefaultToolkit().sync();
            try {
                Thread.sleep(1000);     
            } catch (Exception ex) { }
            //repaint();
        }
        Dane.start=false;

        }




Randomize words in a batch script from a txt

Hi :) I have this code:

del *.txt
for  %%x in (*) do type NUL > %%~nx.txt
for /f "delims=" %%A in ('dir /b *.txt') do (
echo title: bear mouse rabbit & echo description: word & echo tag_field: wolf, fish, bird & echo photography: 1 & echo design: 1 & echo painting: 0 & echo drawing: 0 & echo digital: 0 & echo hidden: false & echo safe_for_work: true) >>%%A
)

I need to randomize words like bear mouse rabbit and wolf, fish, bird from newfolder/dictionary.txt which contains 15 simmilar words. But the word count always must be 3X2 in this script. Also this script should generate different 3x2 words everytime it creates a txt file.




How do I generate two independent discretized Brownian paths in C++?

The following code generates a discretized Brownian path:

std::vector<double> brownian_path(double t, std::size_t n)
{
    std::random_device rd;
    std::mt19937 gen(rd());
    std::normal_distribution<> dis;

    std::vector<double> bm(n + 1);
    auto const sqrt_dt = std::sqrt(t / n);

    for (std::size_t i = 1; i <= n; ++i)
        bm[i] = bm[i - 1] + sqrt_dt * dis(gen);
    return bm;
}

However, it yields the same Brownian path, each time it's called. So, what do I need to do, to generate a new Brownian path at each call?




Weighted random sampling with CUDA

What is the most efficient way to implement weighted random sampling with CUDA?

I have some iterative process and I have a lot of objects with weights. I need to sample one of them at each iteration and recalculate all weights (in a way based on the selected object). And so on.

In pure C++ it will be something like this:

while(1) {
    std::partial_sum(w.begin(), w.end(), w_cumsum.begin());
    int i = std::upper_bound(w_cumsum.begin(), w_cumsum.end(), rand() * w_cumsum.back()) - w_cumsum.begin();
    recalc_weights(w, objects[i]);
}

But I'm not sure which way is faster - to copy values from GPU to host memory and make upper_bound binary search at host, or to make a binary search at GPU (which will work in one thread at one block and can be really slow), or both are bad and there is some much better way?

Also a more general question - is it fine to use a single-block single-thread call of a device-function if we need to do some non-parallel task on small amounts of data, or better way is to copy all needed data into host memory, proceed it there, and after that copy it back to the device?




jeudi 24 décembre 2015

Sikuli Random - function that randomly click one of the location

Iam looking for function in python that choosing random defined function.

I got 4 function :

w_lewo = Location(345,400)
w_prawo = Location(1570,400)
w_gore = Location(945,900)
w_dol = Location(945,870)

And I need function that randomly click one of the location above.




C++: Implementing Binary Search in RNG Guessing Game

I'm trying to write a program where the computer attempts to guess a number that the user selects ( 1 - 100 ). I have most of the program written out, and have also made a random number generator. The only thing I need now is a way to implement the binary search algorithm into my program based on the user's inputs of HIGH or LOW. I've read some about the binary search algorithm, but I'm not sure how to use it in my program. Could someone point me in the right direction?

Lines 34 and 42 have a blank where there should be a function. That's where I would like to input some sort of equation that would implement the binary search algorithm into my program.

Below is my code as of now:

#include <iostream>
#include <ctime>//A user stated that using this piece of code would make a true randomization process.
#include <cstdlib>
#include <windows.h>
using namespace std;

int main()
{
    int highLow;
    int yesNo;
    int ranNum;
    srand( time(0));


    ranNum = rand() % 100 + 1;

    cout << "Please think of a number between 1-100. I'm going to try to guess it.\n";
    _sleep(3000);

    cout << "I'm going to make a guess. Is it "<< ranNum <<" (1 for yes and 2 for no)?\n";
    cin >> yesNo;


    while (yesNo == 2)
        {
            cout << "Please tell me if my guess was higher or lower than your number\n";
            cout << "by inputting 3 for HIGHER and 4 for LOWER.\n";
            cin >> highLow;

            if (highLow == 3)
                {
                    cout << "Okay, so my guess was higher than your number. Let me try again.\n";
                    _sleep (1500);
                    cout << "Was your number " <<  <<"? If yes, input 1. If not, input 2.\n";// I would like to find a way to implement the
                //binary search algorithm in this line of code.
                    cin >> yesNo;
                }
            if (highLow == 4)
                {
                    cout << "Okay, so my guess was lower than your number. Let me try again.\n";
                    _sleep (1500);
                    cout << "Was your number " <<  <<"? If yes, input 1. If not, input 2.\n";// I would like to find a way to implement the
                //binary search algorithm in this line of code.
                    cin >> yesNo;
                }
        }
        if (yesNo == 1)
        {
            cout << "My guess was correct!\n";
        }
}




Can we reproduce the same benchmarking results for a stochastic algorithm, using the same random seed but on different machines?

I am testing a stochastic algorithm. To make the results reproducible, I plan to use the same random seed and include this seed number (an integer) together with the benchmark results when they are published.

But I have a naive question regarding the random seed. Are others with a different machine guaranteed to reproduce my results if they use the same random seed? In fact, I have little knowledge about the principle about random seeds. Admitted, many websites explain it in a more or less elaborated manner, but maybe you have some thinking on that topic to share with?

Concretely, I have a python project that is based on scipy.optimize procedures. I will use numpy.random.seed(42) for my published benchmark results, and expect others to have the same results as in my machine, as long as the same seed number is used. Does it make sense?




Generate fake answers for a math calculation

I am making a quiz like game where I generate math expression and then I generate plus two fake answers given the result of the generated math expression. So user sees the math expression and is given three answers from which he need to choose the right one.

So far I have

switch(opIndexValue)
{
    case Helper.CASE_ADD:
        answer1 = resultValue + Random.Range(1, 4);
        answer2 = resultValue - Random.Range(1, 4);
        break;
    case Helper.CASE_SUBTR:
        answer1 = resultValue + Random.Range(1, 4);
        answer2 = resultValue - Random.Range(1, 4);
        break;
    case Helper.CASE_MULTI:
        answer1 = resultValue + Random.Range(1, 4);
        answer2 = resultValue - Random.Range(1, 4);
        break;
    case Helper.CASE_DIVIS:
        answer1 = resultValue + Random.Range(1, 4);
        answer2 = resultValue - Random.Range(1, 4);
        break;
}

It looks decent and it does the job but its kind of generic. If you are and adult it would quite easy for you to distigush the right solution among the three even without calculating in your mind.

If you were a mathematician how would you generate the two fake answers? On the other hand how would you generate 4 fake answers? :)

The code is written in C# / Unity3D 5.1.4.




C++ Generating random numbers

srand(time(NULL));
    for (int o = 0; o < 8; o++){

        x = rand() % 126 + 33;      
        keysInNumbers[o] = x;
        cout << "Randomly generated number: " << keysInNumbers[o] << endl;
    };

This should be generating random numbers between 33 and 126 but for some reason there are a few numbers that are above 126 though never below 33. I cannot figure out why this is happening.




Changes needed to make this code book tickets in numerical order rather than random? [on hold]

**I would like the code to print out in numerical order rather than a random integer as it does at present due to the fact that I now want to fill up the bookings from 1 to the upper range of 32. Any help on this would be really appreciated, thanks in advance.

sorry if my English isn't the greatest it is not my first language!**

 class FirstClassCompartment
 { 
        public void FirstClassTickets()
        {
            Random rand = new Random();
            bool[] seats = new bool[32];
            List<int> seatsBooked = new List<int>();
            int completeBooking = 0;
            bool quit = false;
            string ticketAmount = "";
            {
                Console.Clear();
                Console.WriteLine("\nWelcome to the First Class booking menu");
                Console.WriteLine("");
                Console.WriteLine("Please enter the amount of tickets you would like to book");
                ticketAmount = Console.ReadLine();
            }
            do
            {
                Console.Clear();
                Console.WriteLine("\nFirst Class booking menu");
                Console.WriteLine("");
                Console.WriteLine("Please press 1 to complete your first class booking");
                completeBooking = Int32.Parse(Console.ReadLine());

                switch (completeBooking)
                {
                    case 1:
                        int firstClassSeat;
                        if (seatsBooked.Count == 0)
                        {
                            firstClassSeat = rand.Next(32);
                            seats[firstClassSeat] = true;
                            seatsBooked.Add(firstClassSeat);
                        }
                        else
                        {

                            do
                            {
                                firstClassSeat = rand.Next(32);
                                if (!seatsBooked.Contains(firstClassSeat))
                                {
                                    seats[firstClassSeat] = true;

                                }
                            }
                            while (seatsBooked.Contains(firstClassSeat) && seatsBooked.Count < 32);
                            if (seatsBooked.Count < 32)
                            {
                                seatsBooked.Add(firstClassSeat);
                            }
                        }
                        if (seatsBooked.Count >= 32)
                        {
                            Console.WriteLine("All seats for first class have been booked");
                            Console.WriteLine("Please press enter to continue...");

                        }
                        else
                        {
                            Console.WriteLine("Your seat: {0}", firstClassSeat + 1);
                            Console.WriteLine("Please press enter to continue...");

                        }
                        Console.ReadLine();
                        break;
                    default:
                        Console.WriteLine("ERROR: INVALID SELECTION");
                        quit = true;
                        break;
                }
            } while (!quit);
        }
    }
}

strong text




Random position on div creation

Currently I'm working on some layout with markers. These markers need to be placed randomly on my window and afterwards they need to be animated. I'm currently creating 50 divs and they are getting placed randomly already. Except for the fact that all 50 are getting placed on the same random spot.

So I'm hoping if someone can point out on how to place all 50 divs on different random locations so not all on the same spot. I think I'm close but not sure what to do next.

Here is my code so far: http://ift.tt/1OJknaZ

Thanks in advance.




Why does pyplot.draw() reseed rand() when called via Python's C API?

I have written a small program that produces unexpected behavior.

I am using Python's C API to plot some random data using pyplot's interactive mode (plt.ion()) from my C application. But every time I call plt.draw(), apparantly rand() is reseeded with the same value. Thus, in below example code, every call to rand() produces the same value.

Is this a bug? Is it only on my machine? How can I work around this?

I am pretty sure this worked some time back. I stumbled accross this today, when I tried to compile and run some code I created and successfully tested some years ago (for the code in this answer).

I'm running Fedora 23.

This is the code:

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

int main () {
  Py_Initialize();
  PyRun_SimpleString("import matplotlib");
  PyRun_SimpleString("print matplotlib.__version__");
  PyRun_SimpleString("from matplotlib import pyplot as plt");
  //PyRun_SimpleString("plt.ion()");
  for (int i = 0; i < 10; i++) {
    // rand() returns always the same value?!
    int x = rand();
    int y = rand();
    printf("%d %d\n", x, y);
    // comment out the following line to "fix" rand() behavior:
    PyRun_SimpleString("plt.draw()");
  }
  Py_Finalize();
  return 0;
}

The output is like this:

$ gcc test.c -I/usr/include/python2.7 -lpython2.7 && ./a.out
1.4.3
1804289383 846930886
1804289383 846930886
1804289383 846930886
1804289383 846930886
1804289383 846930886
1804289383 846930886
1804289383 846930886
1804289383 846930886
1804289383 846930886
1804289383 846930886




Verify the figure gap between 2 numbers and a random number in PHP

I have a little problem with PHP. I create a little game in PHP, in which two players must choose a number, and the one who is closest wins.

Here are the rules:

  • Player 1 chooses the minimum number (to generate the random number to find) CHECK

  • Player 2 chooses the maximum number (to generate the random number to find) CHECK

  • The two players pick their numbers (between the minimum and maximum)

  • The player who is closest to the randomly generated number (between the minimum and maxium), win the game

This is my script

<form action="" method="post">
    <input name="min" type="number" placeholder="Min" />
    <input name="max" type="number" placeholder="Max" />
    <input name="player1" type="number" placeholder="player1" />
    <input name="player2" type="number" placeholder="player2" />
    <input name="submit" type="submit" />
</form>

<?php

    // Variables

    $min = $_POST['min'];
    $max = $_POST['max'];
    $player1 = $_POST['player1'];
    $player2 = $_POST['player2'];


    // Get Random Number

    function getRandomNumber($min, $max) {

        return mt_rand($min, $max);

    }


    // Submit Form

    if (isset($_POST['submit'])) {

        echo "The random number is " . getRandomNumber($min, $max) . "<br />";
        echo "Player 1: " . $player1 . "<br />";
        echo "Player 2: " . $player2 . "<br />";

    }

?>

Thank you in advance for your response.




Given a number, produce another random number that is the same every time and distinct from all other results

Basically, I would like help designing an algorithm that takes a given number, and returns a random number that is unrelated to the first number. The stipulations being that a) the given output number will always be the same for a similar input number, and b) within a certain range (ex. 1-100), all output numbers are distinct. ie., no two different input numbers under 100 will give the same output number.

I know it's easy to do by creating an ordered list of numbers, shuffling them randomly, and then returning the input's index. But I want to know if it can be done without any caching at all. Perhaps with some kind of hashing algorithm? Mostly the reason for this is that if the range of possible outputs were much larger, say 10000000000, then it would be ludicrous to generate an entire range of numbers and then shuffle them randomly, if you were only going to get a few results out of it.

Doesn't matter what language it's done in, I just want to know if it's possible. I've been thinking about this problem for a long time and I can't think of a solution besides the one I've already come up with.

Edit: I just had another idea; it would be interesting to have another algorithm that returned the reverse of the first one. Whether or not that's possible would be an interesting challenge to explore.




Rand is still not working when im seeding the number

Note, the code below is not completely written out, I've already made a deck and shuffled the cards

I don't understand why i don't get two random numbers, I've tried to seed the numbers but it doesn't seem to work properly. What i would like is for everytime i print out face/suit it should be two different numbers/colors. Where are my mistake?

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

struct card{
    const int *face; 
    const char *suit; 
};
typedef struct card Card;

void dealing(const Card * const wDeck);
void shuffle(Card * const wDeck);

int main(){
    srand(time(NULL));
    shuffle(deck);
    dealing(deck);
    return(0);
}

void dealing(Card * const wDeck)
{
    int j;
    j = rand() % 52;
    srand(time(NULL));

    printf("%d of %s\n", wDeck[j].face, wDeck[j].suit);
    printf("%d of %s\n", wDeck[j].face, wDeck[j].suit);
} 
void shuffle(Card * const wDeck)
{
    int i;     
    int j;    
    Card temp; 

    for (i = 0; i <= 51; i++) {
        j = rand() % 52;
        temp = wDeck[i];
        wDeck[i] = wDeck[j];
        wDeck[j] = temp;
    } 
} 




Is the nonce in a HMAC useful to increase the security, to generate a random number based on the seed?

To generate a number based on a seed, I written this code:

var crypto = require('crypto'),

//generate the crypto random token
clientToken = crypto.createHash("sha256").update(crypto.randomBytes(128)).digest('hex')
serverToken = crypto.createHash("sha256").update(crypto.randomBytes(128)).digest('hex'),

//generate the seed
hmac = crypto.createHmac('sha512', serverToken);
hmac.update(clientToken);
var seed = hmac.digest('hex'),

//generate the random number with a PRNG algorithm
prng = new require("seedrandom")(seed),
random = Math.floor(prng() * (100000000 - 10000)) + 10000;

//log the results
console.log("clientToken: ", clientToken);
console.log("serverToken: ", serverToken);
console.log("Seed     :   ", seed);
console.log("Random number:", random);

As you can see, I don't HMAC a nonce value and I would to know if digesting it, will add more security.

This could be the code updated with the nonce implementation added:

//generate the nonce by using a nanosecond timestamp
var hrtime = process.hrtime(),
nonce = (hrtime[0] * 1e9 + hrtime[1]).toString();
nonce = crypto.createHash("sha1").update(nonce).digest('hex');

//generate the seed
var hmac = crypto.createHmac('sha512', serverToken);
hmac.update(clientToken);
hmac.update(nonce);
var seed = hmac.digest('hex');

Adding the nonce, will increase the security ? An user that only knows the client token, could guess the hmac seed ? (With and without the nonce implementation)




How to Find a Link's Random Image URL?

When I post a link in Reddit or Facebook, a random image appears in the subreddit, or page in case of Facebook. That random image is from the link I posted.

I want that random image to appear in a webpage, but I don't know how to capture the random pic's URL to post it there.

How can I find the URL for that random image?

The page that I want to link to is an EBAY search result page, and the listings change by time. So, I want the target webpage to have a random image from EBAY's search result webpage, but I don't know how to capture that random image's URL to post it in the target page.




Rng Kind broken?

Okay guys so bear with me, i need to add a health bar but before i add a health bar i need to get it working correctly.

The Problem: When i run it and it rolls it will land on a number and select a hit, when it determines the hit it runs through multiple types of hits instead of just the one. Try running it if you would. Hopefully the comments help.

What ive tried: I have tried fine combing through everything but after about 2 hours of tweaking and no avail of finding the solution i have turned to here....

Imports: import javax.swing.JOptionPane; import java.util.Random;

Declaring Values:

    int life = 100; //Your life
    int life2 = 100; //Enemy life
    Random chance = new Random();



 while (life >= 0 && life2 >= 0){ //loop
int hitchance = chance.nextInt(100)+1; 
System.out.println(hitchance); //Your roll
if (hitchance <= 20 ){//Miss
    JOptionPane.showMessageDialog(null, "You have missed your opponent like a fool.\nYour Opponent has "+life2+" health remaining.");

}
if (hitchance >= 21 && hitchance <= 34){//Wiff
    int Wiff = chance.nextInt(10)+1;
    life = life-Wiff;
    JOptionPane.showMessageDialog(null, "You have stubbed your toe. Idiot.\nYou have "+life+" health remaining." +Wiff);

}
if (hitchance >= 35 && hitchance <= 74){//Regular Hit
    int regHit = chance.nextInt(20)+1;
    life2 = life2-regHit;
    JOptionPane.showMessageDialog(null, "You have hit your opponent for "+regHit+" damage!\nThey have "+life2+" health remaining.");

}
if (hitchance >= 75 && hitchance <= 90){//CritHit
    int critHit = chance.nextInt(40)+1;
    life2 = life2-critHit;
    JOptionPane.showMessageDialog(null, "You have dealt critical damage! "+critHit+"\nThey have "+life2+" health reamining.");

}
if (hitchance >= 91 && hitchance <= 100) {//Fatality.      
    JOptionPane.showMessageDialog(null, "Fatality!\nYou stabbed your opponent in the foot,\ndrug your knife throught"
            + "his belly,\nand impaled his head on your knife!");
    System.exit(0);

}

int hitchance2 = chance.nextInt(100)+1;
System.out.println(hitchance2); //Enemy roll
if (hitchance2 <= 20 ){//Miss
    JOptionPane.showMessageDialog(null, "Your opponent has missed you.\nYou have "+life+" health remaining.");

}
if (hitchance2 >= 21 && hitchance <= 34){//Wiff
    int Wiff = chance.nextInt(10)+1;
    life2 = life2-Wiff;
    JOptionPane.showMessageDialog(null, "Your enemy has stubbed his toe. Idiot.\nThey have "+life2+" health remaining." +Wiff+" Damage dealt.");

}
if (hitchance2 >= 35 && hitchance <= 74){//Regular Hit
    int regHit = chance.nextInt(20)+1;
    life = life-regHit;
    JOptionPane.showMessageDialog(null, "Your opponent has hit you for "+regHit+" damage!\nYou have "+life+" health remaining.");

}
if (hitchance2 >= 75 && hitchance <= 90){//CritHit
    int critHit = chance.nextInt(40)+1;
    life = life-critHit;
    JOptionPane.showMessageDialog(null, "Your opponent has dealt critical damage! "+critHit+"\nYou have "+life+" health reamining.");

}
if (hitchance2 >= 91 && hitchance2 <= 100) {//Fatality.      
    JOptionPane.showMessageDialog(null, "Fatality!\nYour opponent stabbed you in the foot,\ndrug their knife through"
            + "your belly,\nand impaled your head on his knife!");
    System.exit(0);

}
}
}
}




How to generate a list of random numbers without duplicates in pure batch scripting?

I want to generate a list of random numbers with a predefined number of items %RND_TOTAL% in the given range from %RND_MIN% to %RND_MAX% and with a certain interval %RND_INTER%. Of course this can be accomplished with the following code snippet:

@echo off
setlocal EnableExtensions EnableDelayedExpansion
rem total number of random numbers:
set /A "RND_TOTAL=8"
rem range for random numbers (minimum, maximum, interval):
set /A "RND_MIN=1, RND_MAX=10, RND_INTER=1"
rem loop through number of random numbers:
for /L %%I in (1,1,%RND_TOTAL%) do (
    rem compute a random number:
    set /A "RND_NUM[%%I]=!RANDOM!%%((RND_MAX-RND_MIN)/RND_INTER+1)*RND_INTER+RND_MIN"
    echo !RND_NUM[%%I]!
)
endlocal
exit /B

Here is an example of the corresponding output (4 and 9 both apear twice here):

2
4
9
8
9
4
7
3

But how can I create such a list without any duplicate items?


Of course I could use the following script which checks each item whether it is already avalable in the array-like variable RND_NUM[], but this approach is quite inefficient due to nested for /L loops and, particularly when %RND_TOTAL% comes close to the available count of random numbers covered by the the range specification, due to numerous calculation repetitions:

@echo off
setlocal EnableExtensions EnableDelayedExpansion
rem total number of random numbers, duplicate flag (`0` means no duplicates):
set /A "RND_TOTAL=20, FLAG_DUP=0"
rem range for random numbers (minimum, maximum, interval):
set /A "RND_MIN=1, RND_MAX=30, RND_INTER=1"
rem loop through number of random numbers, generate them in a subroutine:
for /L %%I in (1,1,%RND_TOTAL%) do (
    call :SUB %%I
    echo !RND_NUM[%%I]!
)
endlocal
exit /B

:SUB
rem get number of already collected random numbers:
set /A "RND_COUNT=%1-1"
:LOOP
rem compute a random number:
set /A "RND_NUM[%1]=!RANDOM!%%((RND_MAX-RND_MIN)/RND_INTER+1)*RND_INTER+RND_MIN"
rem check whether random number appears in the previous collection:
if %FLAG_DUP% EQU 0 (
    for /L %%I in (1,1,%RND_COUNT%) do (
        rem re-compute random number if duplicate has been encountered:
        if !RND_NUM[%1]! EQU !RND_NUM[%%I]! (
            goto :LOOP
        )
    )
)
exit /B

This is the related sample output (no duplicates here):

4
1
2
10
6
7
3
5