lundi 31 août 2015

Can you find previously generated random numbers generated using the java.util.Random?

Is is possible to find previously generated random numbers generated using java.util.Random?


I found information at this website, it seems to indicate it uses a LCG in the format

numberi+1 = (a * numberi + c) mod 248

where the first value of number is the seed and it is simply added to by one every time nextInt (or somthing similar) is called

Does anyone have any more information on how it is generated? or what the offset values are?




Generate Random Binary Matrix

I wish to generate 10,000 random binary matrices which have the same number of 1s per row and per column as a given binary matrix.

The matrix is ~500 x ~10,000. There are about 2,000,000 1s. There are no zero rows or columns.

My current method converts the binary matrix into a bipartite adjacency matrix, and performs 1,000,000 random edge switches to guarantee randomness. This takes 13,000 seconds for 1 matrix. I'm coding in python, using a modified version of networkx's double_edge_swap function.

Is there a more efficient way to generate such matrices?




Filling a 2D array in C twice, first with one number in randomized positions and then fill the rest with randomized numbers

I'm totally lost here, i'm a C newbie and i'm just learning about 2D arrays and i got an assignment about making an array and filling it with -1 in random positions, and then filling the rest of it with random numbers from 0 to 100.

I've been trying different functions and i've created arrays but i can only completely fill them with random numbers.

My main problem is the first step, making it fill itself with -1 in random positions, where should i start? i've been searching but i cant find something that makes this. I'm asking out of desperation.




Generate *truly* random numbers fortran 90

I am relatively new to Fortran 90 and despite having scoured a lot of manuals, forums, tutorials, university pages, and books, I have not managed to modify the F90 routine below using the system clock so that the random numbers generated (in [0,1]) are independent from one run to another.

! Simple random number generator in the range [0,1]
! ranset_(iseed) initializes with iseed
! ranf_() returns next random number




      real function ranf_()
       implicit none
       real rand_
!       ranf_ = rand_(0)
        call random_number(ranf_)
       return
      end


      subroutine ranset_(iseed)
      implicit none
      real rand_,ranf_
      integer iseed, i, m, nsteps
!      i = rand_(1) ! reinitialize (reset)
      nsteps = iseed*10000
      do i = 1,nsteps
        m = ranf_()
!       m = rand_(0)
      end do
      return
      end





      real function rand_(iseed)
      implicit none
      integer iseed
      integer ia1, ia0, ia1ma0, ic, ix1, ix0, iy0, iy1
      save ia1, ia0, ia1ma0, ic, ix1, ix0
      data ix1, ix0, ia1, ia0, ia1ma0, ic/0,0,1536,1029,507,1731/
      if (iseed.ne.0) then
        ia1 = 1536
        ia0 = 1029
        ia1ma0 = 507
        ic = 1731
        ix1 = 0
        ix0 = 0
        rand_ = 0
      else
       iy0 = ia0*ix0
       iy1 = ia1*ix1 + ia1ma0*(ix0-ix1) + iy0
       iy0 = iy0 + ic
       ix0 = mod (iy0, 2048)
       iy1 = iy1 + (iy0-ix0)/2048
       ix1 = mod (iy1, 2048)
       rand_ = ix1*2048 + ix0
       rand_ = rand_ / 4194304.
      end if
      return
      end

The code is not that easy to fully understand for a beginner like me. Any insights/suggestions/solutions on how to properly do this using the system clock?




Random Number Generator using a given seed

I have a question that asking me to use a seed in a random number generator. For example, if the seed is 13771, I need to generate 50 (x,y) co-ordinates using that seed.

How is this achieved? I haven't the slightest clue.

I have this loop:

for (int i = 0; i <= num-1; i++){

        }

Where num = 50. I don't know how to use the seed to create random numbers.




Php echo random User from DB

I trying to echo a random User from my database: I got this so far:

$randUser = "SELECT * FROM `staff` ORDER BY RAND() LIMIT 1";
echo $randUser;

But this just does output me my sql string. How to solve this issue.




App was Force close when button Clicked

actually i had button that clicked it will be random his position every second so i declare the code like this

this mainactivity class

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Point;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.widget.Button;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.WindowManager;

import java.util.Random;
import java.util.Timer;
import java.util.TimerTask;

import com.google.android.gms.ads.AdRequest;
import com.google.android.gms.ads.AdView;



public class MainActivity extends Activity {

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

         buttonblack = (Button)findViewById(R.id.button1);

         buttonblack.setOnClickListener(new View.OnClickListener() {

                     @Override
                     public void onClick(View view) {
                         startRandomButton(buttonblack);    
                         }               
                 });

         startRandomButton(buttonblack);    

    }

    public static Point getDisplaySize(@NonNull Context context) {
        Point point = new Point();
        WindowManager manager = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
        manager.getDefaultDisplay().getSize(point);
        return point;
    }

    private void setButtonRandomPosition(final Button button){
        int randomX = new Random().nextInt(getDisplaySize(this).x);
        int randomY = new Random().nextInt(getDisplaySize(this).y);

        button.setX(randomX);
        button.setY(randomY);
    }

    private void startRandomButton(Button button) {
        Timer timer = new Timer();
        timer.schedule(new TimerTask() {
            @Override
            public void run() {
                setButtonRandomPosition(buttonblack);
            }
        }, 1000, 1000);//Update button every second
    }
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }

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

and this is the xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://ift.tt/nIICcg"
    xmlns:ads="http://ift.tt/GEGVYd"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent" >

     <RelativeLayout
         android:layout_width="wrap_content"
         android:layout_height="wrap_content"
         android:layout_centerHorizontal="true"
         android:layout_centerVertical="true"
         android:layout_margin="30dp"
         android:background="@drawable/backgroundblankred" >

         <Button
             android:id="@+id/button1"
             android:layout_width="100dp"
             android:layout_height="100dp"
             android:background="@drawable/eeclevelfirstblackbuton" />

     </RelativeLayout>

</RelativeLayout>

when the app is open in a second will force close

can anyone help me to fix this?

and second, can anyone help me with explain code to that make the button stop random? because i dont know to make the button stop lol.

thanks in advance.




Weighted Random Graph Traversal in Python

Basically, I have a 300 by 250 area that I want to randomly move about. However, there are areas of interest at points 18750 and 9300 (you can figure out x,y by doing y = 0 while(num > x): num = num - x y += 1 and you'll get the coordinates). Anyway, so if the starting point is (0,0), I want to be able to randomly move about the area but kind of move in the general area of the two given points. Maybe one has a stronger pull so even if the node traversal leads to the weaker one, it will, with enough time, end up at the one with stronger pull.

So far, I have this in order to create my graph and create my vertices and edges. It gives me a 300x250 space with each node connected vertically and horizontally. `

from igraph import *
g = Graph()
x = 300
y = 250
g.add_vertices(x*y)
li = []

for i in range(x-1):
    for j in range(y):
        li.append((i+j*x, i+1+j*x))
for i in range(x):
    for j in range(y-1):
        li.append((i+j*x, i+x+j*x))

g.add_edges(li)

gravity_points = [18750, 9300]
final_point = 24900

` How can I go about this? I want to have the traveling node have to make a choice at every resting node but the probability of it traveling in any direction being completely dependent on the weights of the gravity points. So it might have a 10% chance to go left, a 10% chance to go right, a 50% chance to go down and a 30% chance to go up. Something like that. The probabilities don't have to change with proximity but rather with the direction the gravity points are in.

Any help is welcome!! Thank you in advance.




Cannot refer to the non-final local variable button defined in an enclosing scope, Random method error

I am getting an error in my project with eclipse:

Cannot refer to the non-final local variable button defined in an enclosing scope

This my class:

import android.app.Activity;
import android.content.Context;
import android.graphics.Point;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.widget.Button;
import android.view.Menu;
import android.view.MenuItem;
import android.view.WindowManager;

import java.util.Random;
import java.util.Timer;
import java.util.TimerTask;

public class MainActivity extends Activity {
Button buttonblack;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

     buttonblack = (Button)findViewById(R.id.Button01);

     startRandomButton(buttonblack);    

}

public static Point getDisplaySize(@NonNull Context context) {
    Point point = new Point();
    WindowManager manager = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
    manager.getDefaultDisplay().getSize(point);
    return point;
}

private void setButtonRandomPosition(Button button){
    int randomX = new Random().nextInt(getDisplaySize(this).x);
    int randomY = new Random().nextInt(getDisplaySize(this).y);

    button.setX(randomX);
    button.setY(randomY);
}

private void startRandomButton(Button button) {
    Timer timer = new Timer();
    timer.schedule(new TimerTask() {
        @Override
        public void run() {
            setButtonRandomPosition(button);
        }
    }, 0, 1000);//Update button every second
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.main, menu);
    return true;
}

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

The problem is in this method:

private void startRandomButton(Button button) {
        Timer timer = new Timer();
        timer.schedule(new TimerTask() {
            @Override
            public void run() {
                setButtonRandomPosition(button);// Cannot refer to the non-final local variable button defined in an enclosing scope
            }
        }, 0, 1000);//Update button every second
    }

Can someone help me fix this? Or suggest any other code that could be better than this?




dimanche 30 août 2015

Random Number Generating in Java

I am new to programming and have just started to learn about arrays and was doing just fine until I got to an array that stores random numbers inside of it. The line of code below is the one that baffles me the most.

for (int roll = 1; roll <=6000000; roll++)
     ++frequency[1 + randomNumbers.nextInt(6)];

Before this I imported the Random class and made a new object named randomNumbers as well as declared the variable frequency as an array with 7 integers. The book I am reading tells me that this line above rolls a die 6 million times and uses the die value as frequency index.

I understand that this is going through in iteration 6 million times were it does what it says in the body each time, however I do not see in the body where it sets any variable equal to a random number. I think the biggest thing I am missing is what it means to increment the frequency[] because I understand that within the brackets there is a random number between 1 and 6 being added to 1. So therefore the six million iterations should pass by frequency[1] through frequency[7] if it chance to happen, yet even though it passes them by I do not see how it sets anything equal to those arrays.

Can someone please explain this line of code to me step by step barney style? I just can't seem to wrap my head around it.




The operator > is undefined for the argument type(s) java.util.Random, java.util.Random

I am trying to create a horse race betting game. I'm having trouble comparing the values of the horses to each other to see which one wins.

In the if statement I try to compare the value of horse1 with the value of horse2 and horse3. But I get the error of: he operator > is undefined for the argument type(s) java.util.Random, java.util.Random

    import java.util.Scanner;
 import java.util.Random;
 public class RunHorseGame 
{

public static void main(String[] args) 
{
// TODO Auto-generated method stub

//variables
    String name;
    float bal;
    float bet;
    boolean nextRace;
    int raceChoice;
    int startRace;

    Random horse1 = new Random(100);
    Random horse2 = new Random(100);
    Random horse3 = new Random(100);
    Random horse4 = new Random(100);
    Random horse5 = new Random(100);
    Random horse6 = new Random(100);
    Random horse7 = new Random(100);

    Scanner input = new Scanner(System.in);

//welcome screen
    System.out.println("Welcome to Horse Racing!");
    System.out.println("Please enter your name:");
    name = input.nextLine();
    System.out.println("welcome " + name + ", you have a balance of $200!");

//create loop to repeat races when one finishes (keep balance)
    nextRace = true;
    while (nextRace == true)
    {
        bal = 200;

//give race options
        System.out.println("Please select which race you would like to       enter:");
        System.out.println("Press 1 to enter: 3 horse race");
        System.out.println("Press 2 to enter: 5 horse race");
        System.out.println("Press 3 to enter: 7 horse race");

//create each race
//each horse has randomizer
//highest number wins race

        raceChoice = input.nextInt();
        switch(raceChoice)
        {
            case 1:
                System.out.println("You have entered the 3 horse race!");
                System.out.println("How much would you like to bet?");
                bet = input.nextFloat();
                System.out.println("You have bet " + bet + " dollars.");
                bal =- bet;
                System.out.println("Press 1 to start.");
                System.out.println("Press 2 to go back to race selection.");

                startRace = input.nextInt();
                switch(startRace)
                {
                case 1:


                    if(horse1 > horse2 && horse1 > horse3)
                    {

                    }

                    break;

                case 2:
                    nextRace = false;
                    break;
                }


                break;
            case 2:
                break;
            case 3:
                break;
            default:
                break;


        }

        nextRace = true;

    }
}
}




PHP Get random element out of array 1, show, and move to array 2

Ok i'm trying to make a page that when i press a button randomly returns an element out of array1, saves it (so i can show it on the page), and then moves it to array2 so the element doesnt get returned a second time, but i have no idea where to start.

$subject = array (
array("Title1","comment1"),
array("Title2","comment2"),
array("Title3","comment3"),
array("Title4","comment4"),
);

help would be enormously appriciated!




Working of Random number generator algorithm

How exactly is a random number generated, I mean the working of the algorithm.




Print variables in order based on pseudo-random numbers

I am creating a task where a person receives a score based on their accuracy. Then they are presented with a screen with their performance place among other players (where the other players' scores are randomly generated numbers.)

I need to generate random scores for the fake players, then somehow sort the scores in descending order based on their placement. The only real score that is presented will be [sub_score].

Below is what I have so far. I'm not sure how to sort these variables based on their values, then print the variables for [firstplace], [secondplace], [thirdplace], etc. Also, this needs to occur 4 times, where each time a different score is generated for the fake players, and their placement fluctuates across tasks. These randomly generated numbers should fall between 70-90 since these scores reflect accuracy.

import random
'jsw_score' = random.randint(70,90)
'jbp_score' = random.randint(70,90)
'bsp_score' = random.randint(70,90)
'mjk_score' = random.randint(70,90)
'phs_score' = random.randint(70,90)
'msw_score' = random.randint(70,90)
'tdl_score' = random.randint(70,90)
'aik_score' = random.randint(70,90)
'wjc_score' = random.randint(70,90)
'sub_score' = accuracy

Thank you!




Ruby generate random string from key

What's the best way to create a random string given a key. For example, I am using this

(0...50).map { ('a'..'z').to_a[rand(26)] }.join

But, I want the alphanumeric string that is generated based on a string such as "mysecretkey". I don't want to use encryption gems or Cipher, etc. I want to keep it simple like what I have, but adding a key to it.




Change mt_rand() when a certain amount of same number is reached

What I want to do is use mt_rand() to choose a random number which at the start will be 1 and 2, it would check if that number is used a certain amount of times (in my case 25), if the number was taken that many times then change the random int from 1-2 to whatever number wasnt taken and 3(removing the numbers that were used 25 times from the mt_rand() function).It would keep going up and up until it found a league that wasn't full and would then insert the random number into a table (which I've already got working). The rest I've got working(also before answering, I know about security issues and will fix it as soon as I've got all the code working)

So here's the code:

<?php    
    $servername = getenv('IP');
    $username = getenv('C9_USER');
    $passwordp = "";
    $database = "leaguescores";
    $dbport = 3306;

    // Create connection
    $db = mysql_connect($servername, $username, $passwordp, $dbport)or die("Cant Connect to server");
    mysql_select_db($database) or die("Cant connect to database");

    $name = mysql_real_escape_string($_GET['name'], $db);
    $amountinleague = "SELECT `leaguenum` FROM `leaguescores`.`silverleaguescores` WHERE leaguenum = $leaguenumber";
    $score = mysql_real_escape_string($_GET['score'], $db);
    $random = mt_rand(1, 2);
    if($score >= 100){
        $query2 = "INSERT INTO `leaguescores`.`silverleaguescores` (`id`, `name`, `score`) VALUES (NULL, '', ''), (NULL, '$name', '$score')";
        $result2 = mysql_query($query2) or die('Query Failed: ' . mysql_error());
    }else{
        $amountofpplinleague = "SELECT COUNT(*) FROM `leaguescores`.`bronzeleaguescores` WHERE leaguenum = $random";
        if($amountofpplinleague == 25){
            //Change $random
        }
        $query = "INSERT INTO `leaguescores`.`bronzeleaguescores` (`id`, `name`, `score`) VALUES (NULL, '', ''), (NULL, '$name', '$score')";
        $result = mysql_query($query) or die('Query Failed: ' . mysql_error());
    }
?>




How to make a Random Layout when button clicked

Actually i want to make it Random class but then i think to much activity can make the app slow so i just want to make Relative layout Random

so i have 5 layout in one activity class

layout1 = (RelativeLayout)findViewById(R.id.layout1);
layout2 = (RelativeLayout)findViewById(R.id.layout2);
layout3 = (RelativeLayout)findViewById(R.id.layout3);
layout4 = (RelativeLayout)findViewById(R.id.layout4);  
layout5 = (RelativeLayout)findViewById(R.id.layout5);

and in each layout there is the button in there to make layout random again

button.setOnClickListener(new View.OnClickListener() {

        public void onClick(View v){ 

        //The code to how make layout random

        }
     });
 }

and then how to make layout that already opened not open again if the button random was pressed? then if all layout was already opened it will open new activity class

can anyone help me explain with give some example code of that?




samedi 29 août 2015

How to randomly generate a narrow path?

I'm writing a sample game where a block falls down forever, and you need to steer it from side to side. If you hit the walls, you lose. I'm trying to randomly and continually generate the level so there's always a way through, and so the path gets progressively narrower.

#       #
#       #
#      ##
#     ###
#    ####
#   #####
##  #####
##  #####
##   ####
###  ####
###   ###
####  ###
####  ###
###   ###
###   ###
##   ####
##   ####
##  #####
##  #####
## ######
## ######
## ######
## ######

My current approach is to have an array of possible paths, then I randomly select a row. The problem is that the path is not smooth, and at times, it becomes impossible:

#       #
#    ####
#   #####
###   ###
##  #####
###  ####
#     ###
##  #####
####  ### <--- can't get through here
##   ####
####  ###
###   ###
#      ##
## ######
##  #####
## ######
##  #####
##  #####
##   ####
##   ####
#       #
###   ###
## ###### <--- or here
#       #
## ######
## ######

What class of algorithms would help me get started with this?




How to set probability for randomly picking character from a string in r

i have a string with repetition of 4 character "atgc"

a <- "attgctagctagtcatgctagctacgtacgcatcgtacgatgcatatgctttttaattt"

how to randomly pick a string a size 5 in which the probability of "gc" in that should be 60%




Force Close when button Clicked

In my previous question it is because the value make the activity not opened so i changed to new code but it still force close

this is my code to make random activity

public class menu extends Activity {


    int time = 5, one, two, three, four, five, number;
    RelativeLayout layout1, layout2;
    Button button1; 

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        this.requestWindowFeature(Window.FEATURE_NO_TITLE);
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
        WindowManager.LayoutParams.FLAG_FULLSCREEN);
        setContentView(R.layout.menu);

        layout1 =(RelativeLayout)findViewById(R.id.layout1);
        layout2 =(RelativeLayout)findViewById(R.id.layout2);


          new CountDownTimer(5000, 1000) {

          @Override
          public void onFinish() {        
              layout1.setVisibility(View.GONE);
              layout2.setVisibility(View.VISIBLE);
          }

          @Override
          public void onTick(long millisUntilFinished) {
          }
         }.start();  


        button1 = (Button)findViewById(R.id.introbutton1);
        button1.setOnClickListener(new View.OnClickListener() {

            public void onClick(View v){            
            SharedPreferences pref = getSharedPreferences("SavedGame", MODE_PRIVATE); 
            SharedPreferences.Editor editor = pref.edit();      
            editor.putInt("Level", 0);  
            editor.commit();


         // Here, we are generating a random number
         Random generator = new Random();
         number = generator.nextInt(5) + 1; 
         // The '5' is the number of activities

         Class activity = null;

         // Here, we are checking to see what the output of the random was
         switch(number) { 
         // E.g., if the output is 1, the activity we will open is ActivityOne.class


         case 1: 
             activity = activityone.class;

             //to check the activity already opened or not, so he will do this logic

             if(one == 1){
                Random generatorone = new Random();
                number = generatorone.nextInt(5) + 1; 
            }
             break;
         case 2: 
             activity = activitytwo.class;

             if(two== 1){
                Random generatortwo = new Random();
                number = generatortwo.nextInt(5) + 1; 
            }
             break;
         case 3:
             activity = activitythree.class;

            if(three== 1){
                Random generatorthree = new Random();
                number = generatorthree.nextInt(5) + 1; 
            }
             break;
         case 4:
             activity = activityfour.class;

             if(four == 1){
                Random generatorFour = new Random();
                number = generatorFour.nextInt(5) + 1; 
            }                                            

                 editor = pref.edit();
                 // Key,Value
                 editor.putInt("Activity", number);

                 editor.commit();      
                 }
         // We use intents to start activities
         Intent intent = new Intent(getBaseContext(), activity);
         startActivity(intent);
            }
         });
     }

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

and when each activity opened there is a code to make value of the activity == 1 (already opened)

 buttonblack = (Button)findViewById(R.id.buttonblack);
 buttonblack.setOnClickListener(new View.OnClickListener() {

 public void onClick(View v){
 level++;
 SharedPreferences pref = getSharedPreferences("SavedGame", MODE_PRIVATE); 
 SharedPreferences.Editor editor = pref.edit();      
 editor.putInt("Lifes", gamelifes);
 editor.putInt("Level", level); 
//sharedpreferences put int values to 1 (the activity already opened) 
 editor.putInt("One", 1);
 editor.commit();

// Here, we are generating a random number
Random generator = new Random();
number = generator.nextInt(5) + 1; 
// The '5' is the number of activities

Class activity = null;

// Here, we are checking to see what the output of the random was
switch(number) { 
// E.g., if the output is 1, the activity we will open is ActivityOne.class



  case 1: 
          activity = activityone.class;

          if(one == 1){
          Random generatorone = new Random();
          number = generatorone.nextInt(5) + 1; 
         }
          break;
 case 2: 
          activity = activitytwo.class;

          if(two== 1){
          Random generatortwo = new Random();
          number = generatortwo.nextInt(5) + 1; 
         }
          break;
 case 3:
          activity = activitythree.class;

          if(three== 1){
          Random generatorthree = new Random();
          number = generatorthree.nextInt(5) + 1; 
         }
          break;
 case 4:
          activity = activityfour.class;

       if(four == 1){
       Random generatorFour = new Random();
       number = generatorFour.nextInt(5) + 1; 
                                                }                                            
       break;
       default:if(level == 5){
       activity = activityfive.class;
       }
       editor = pref.edit();
       // Key,Value
       editor.putInt("Activity", number);
       editor.commit();      
       }
       // We use intents to start activities
       Intent intent = new Intent(getBaseContext(), activity);
       startActivity(intent);
                     }                
             });
    } 

There is something missing or wrong with my code that can't make the activity random properly? or anyone can help me with another alternatif code?

can anyone help me to fix this?




How do I randomly select a variable from a list, and then modify it in python?

Here's my python 3 code. I would like to randomly select one of the cell variables (c1 through c9) and change its value to the be the same as the cpuletter variable.

import random

#Cell variables
c1 = "1"
c2 = "2"
c3 = "3"
c4 = "4"
c5 = "5"
c6 = "6"
c7 = "7"
c8 = "8"
c9 = "9"
cells = [c1, c2, c3, c4, c5, c6, c7, c8, c9]

cpuletter = "X"

random.choice(cells) = cpuletter

I'm getting a "Can't assign to function call" error on the "random.choice(cells)." I assume I'm just using it incorrectly? I know you can use the random choice for changing a variable like below:

import random
options = ["option1", "option2"]
choice = random.choice(options)




C# : generate array of random number without duplicates

I want to make an array of random numbers without any duplicate.

private void SetRandomQuestions()
{
    var idS = from t in _db.QuestionsTables
              where t.Cat_Id == _catId
              select new
                     { t.Question_Id };

    // to get the questions Id from database table
    foreach (var variable in idS)
    {
        array.Add(variable.Question_Id);
    }

    // generate a random numbers depends on the array list values
    var random = new Random();

    for (var i = 0; i < _randomQuestionId.Length; i++)
    {
        _randomNumber = random.Next(array.Count);

        for (var j = 0; j < _randomQuestionId.Length; j++)
        {
            if (_randomQuestionId[j] != array[int.Parse(_randomNumber.ToString())])
            {
                _randomQuestionId[i] = array[int.Parse(_randomNumber.ToString())];
                j = 5;
            }
        }
    }
}

As you see here I have list array has values of questions id and further I have created another array to get 4 elements randomly from that array. However, my question is how I can get the elements without any duplicate Ids I have tried many times but unfortunately I didn't success with that.




Activity Random code not work and force close

In my previous question it is because the value make the activity not opened so i changed to new code but it still force close

i was using bluestack as emulator so there is no Log Cat

this is my code to make random activity

public class menu extends Activity {


    int time = 5, one, two, three, four, five, number;
    RelativeLayout layout1, layout2;
    Button button1; 

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        this.requestWindowFeature(Window.FEATURE_NO_TITLE);
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
        WindowManager.LayoutParams.FLAG_FULLSCREEN);
        setContentView(R.layout.menu);

        layout1 =(RelativeLayout)findViewById(R.id.layout1);
        layout2 =(RelativeLayout)findViewById(R.id.layout2);


          new CountDownTimer(5000, 1000) {

          @Override
          public void onFinish() {        
              layout1.setVisibility(View.GONE);
              layout2.setVisibility(View.VISIBLE);
          }

          @Override
          public void onTick(long millisUntilFinished) {
          }
         }.start();  


        button1 = (Button)findViewById(R.id.introbutton1);
        button1.setOnClickListener(new View.OnClickListener() {

            public void onClick(View v){            
            SharedPreferences pref = getSharedPreferences("SavedGame", MODE_PRIVATE); 
            SharedPreferences.Editor editor = pref.edit();      
            editor.putInt("Level", 0);  
            editor.commit();


         // Here, we are generating a random number
         Random generator = new Random();
         number = generator.nextInt(5) + 1; 
         // The '5' is the number of activities

         Class activity = null;

         // Here, we are checking to see what the output of the random was
         switch(number) { 
         // E.g., if the output is 1, the activity we will open is ActivityOne.class


         case 1: 
             activity = activityone.class;

             //to check the activity already opened or not, so he will do this logic

             if(one == 1){
                Random generatorone = new Random();
                number = generatorone.nextInt(5) + 1; 
            }
             break;
         case 2: 
             activity = activitytwo.class;

             if(two== 1){
                Random generatortwo = new Random();
                number = generatortwo.nextInt(5) + 1; 
            }
             break;
         case 3:
             activity = activitythree.class;

            if(three== 1){
                Random generatorthree = new Random();
                number = generatorthree.nextInt(5) + 1; 
            }
             break;
         case 4:
             activity = activityfour.class;

             if(four == 1){
                Random generatorFour = new Random();
                number = generatorFour.nextInt(5) + 1; 
            }                                            

                 editor = pref.edit();
                 // Key,Value
                 editor.putInt("Activity", number);

                 editor.commit();      
                 }
         // We use intents to start activities
         Intent intent = new Intent(getBaseContext(), activity);
         startActivity(intent);
            }
         });
     }

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

and when each activity opened there is a code to make value of the activity == 1 (already opened)

 buttonblack = (Button)findViewById(R.id.buttonblack);
 buttonblack.setOnClickListener(new View.OnClickListener() {

                  public void onClick(View v){
                                level++;
                                SharedPreferences pref = getSharedPreferences("SavedGame", MODE_PRIVATE); 
                                SharedPreferences.Editor editor = pref.edit();      
                                editor.putInt("Lifes", gamelifes);
                                editor.putInt("Level", level); 
                                //sharedpreferences put int values to 1 (the activity already opened) 
                                editor.putInt("One", 1);
                                editor.commit();
                                // Here, we are generating a random number
                                Random generator = new Random();
                                number = generator.nextInt(5) + 1; 
                                // The '5' is the number of activities

                                Class activity = null;

                                // Here, we are checking to see what the output of the random was
                                switch(number) { 
                                // E.g., if the output is 1, the activity we will open is ActivityOne.class



                                            case 1: 
                                                 activity = activityone.class;

                                                 if(one == 1){
                                                    Random generatorone = new Random();
                                                    number = generatorone.nextInt(5) + 1; 
                                                }
                                                 break;
                                             case 2: 
                                                 activity = activitytwo.class;

                                                 if(two== 1){
                                                    Random generatortwo = new Random();
                                                    number = generatortwo.nextInt(5) + 1; 
                                                }
                                                 break;
                                             case 3:
                                                 activity = activitythree.class;

                                                if(three== 1){
                                                    Random generatorthree = new Random();
                                                    number = generatorthree.nextInt(5) + 1; 
                                                }
                                                 break;
                                             case 4:
                                                 activity = activityfour.class;

                                                 if(four == 1){
                                                    Random generatorFour = new Random();
                                                    number = generatorFour.nextInt(5) + 1; 
                                                }                                            
                                                 break;
                                                default:if(level == 5){
                                                    activity = activityfive.class;
                                                    }
                                                    editor = pref.edit();
                                                    // Key,Value
                                                    editor.putInt("Activity", number);

                                                    editor.commit();      
                                                    }
                                           // We use intents to start activities
                                            Intent intent = new Intent(getBaseContext(), activity);
                                            startActivity(intent);
                     }                
             });
    }

There is something missing or wrong with my code that can't make the activity random properly?

can anyone help me to fix this?




Random activity code not Properly Worked and causes Force Close

In my previous question it is because the value make the activity not opened so i changed to new code but it still force close

i was using bluestack as emulator so there is no Log Cat

this is my code to make random activity

public class menu extends Activity {


    int time = 5, one, two, three, four, five, number;
    RelativeLayout layout1, layout2;
    Button button1; 

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        this.requestWindowFeature(Window.FEATURE_NO_TITLE);
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
        WindowManager.LayoutParams.FLAG_FULLSCREEN);
        setContentView(R.layout.menu);

        layout1 =(RelativeLayout)findViewById(R.id.layout1);
        layout2 =(RelativeLayout)findViewById(R.id.layout2);


          new CountDownTimer(5000, 1000) {

          @Override
          public void onFinish() {        
              layout1.setVisibility(View.GONE);
              layout2.setVisibility(View.VISIBLE);
          }

          @Override
          public void onTick(long millisUntilFinished) {
          }
         }.start();  


        button1 = (Button)findViewById(R.id.introbutton1);
        button1.setOnClickListener(new View.OnClickListener() {

            public void onClick(View v){            
            SharedPreferences pref = getSharedPreferences("SavedGame", MODE_PRIVATE); 
            SharedPreferences.Editor editor = pref.edit();      
            editor.putInt("Level", 0);  
            editor.commit();


         // Here, we are generating a random number
         Random generator = new Random();
         number = generator.nextInt(5) + 1; 
         // The '5' is the number of activities

         Class activity = null;

         // Here, we are checking to see what the output of the random was
         switch(number) { 
         // E.g., if the output is 1, the activity we will open is ActivityOne.class


         case 1: 
             activity = activityone.class;

             //to check the activity already opened or not, so he will do this logic

             if(one == 1){
                Random generatorone = new Random();
                number = generatorone.nextInt(5) + 1; 
            }
             break;
         case 2: 
             activity = activitytwo.class;

             if(two== 1){
                Random generatortwo = new Random();
                number = generatortwo.nextInt(5) + 1; 
            }
             break;
         case 3:
             activity = activitythree.class;

            if(three== 1){
                Random generatorthree = new Random();
                number = generatorthree.nextInt(5) + 1; 
            }
             break;
         case 4:
             activity = activityfour.class;

             if(four == 1){
                Random generatorFour = new Random();
                number = generatorFour.nextInt(5) + 1; 
            }                                            

                 editor = pref.edit();
                 // Key,Value
                 editor.putInt("Activity", number);

                 editor.commit();      
                 }
         // We use intents to start activities
         Intent intent = new Intent(getBaseContext(), activity);
         startActivity(intent);
            }
         });
     }

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

and when each activity opened there is a code to make value of the activity == 1 (already opened)

 buttonblack = (Button)findViewById(R.id.buttonblack);
 buttonblack.setOnClickListener(new View.OnClickListener() {

                  public void onClick(View v){
                                level++;
                                SharedPreferences pref = getSharedPreferences("SavedGame", MODE_PRIVATE); 
                                SharedPreferences.Editor editor = pref.edit();      
                                editor.putInt("Lifes", gamelifes);
                                editor.putInt("Level", level); 
                                //sharedpreferences put int values to 1 (the activity already opened) 
                                editor.putInt("One", 1);
                                editor.commit();
                                // Here, we are generating a random number
                                Random generator = new Random();
                                number = generator.nextInt(5) + 1; 
                                // The '5' is the number of activities

                                Class activity = null;

                                // Here, we are checking to see what the output of the random was
                                switch(number) { 
                                // E.g., if the output is 1, the activity we will open is ActivityOne.class



                                            case 1: 
                                                 activity = activityone.class;

                                                 if(one == 1){
                                                    Random generatorone = new Random();
                                                    number = generatorone.nextInt(5) + 1; 
                                                }
                                                 break;
                                             case 2: 
                                                 activity = activitytwo.class;

                                                 if(two== 1){
                                                    Random generatortwo = new Random();
                                                    number = generatortwo.nextInt(5) + 1; 
                                                }
                                                 break;
                                             case 3:
                                                 activity = activitythree.class;

                                                if(three== 1){
                                                    Random generatorthree = new Random();
                                                    number = generatorthree.nextInt(5) + 1; 
                                                }
                                                 break;
                                             case 4:
                                                 activity = activityfour.class;

                                                 if(four == 1){
                                                    Random generatorFour = new Random();
                                                    number = generatorFour.nextInt(5) + 1; 
                                                }                                            
                                                 break;
                                                default:if(level == 5){
                                                    activity = activityfive.class;
                                                    }
                                                    editor = pref.edit();
                                                    // Key,Value
                                                    editor.putInt("Activity", number);

                                                    editor.commit();      
                                                    }
                                           // We use intents to start activities
                                            Intent intent = new Intent(getBaseContext(), activity);
                                            startActivity(intent);
                     }                
             });
    }

There is something missing or wrong with my code that can't make the activity random properly?




When button clicked the app was Force Close

I had make every activity Random if a button clicked but it seemsly not working good, the game was force close.

this is the following code

public class menu extends Activity {


    int time = 5, one, two, three, four, five, number;
    RelativeLayout layout1, layout2;
    Button button1; 

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        this.requestWindowFeature(Window.FEATURE_NO_TITLE);
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
        WindowManager.LayoutParams.FLAG_FULLSCREEN);
        setContentView(R.layout.menu);

        SharedPreferences pref = getSharedPreferences("SavedGame", MODE_PRIVATE); 
        SharedPreferences.Editor editor = pref.edit();      
        editor.putInt("Lifes", 6);
        editor.putInt("Level", 0);  
        editor.putInt("One", 1);  
        editor.putInt("Two", 1);  
        editor.putInt("Three", 1);  
        editor.putInt("Four", 1); 
        editor.putInt("Five", 1);  


        editor.commit();


        layout1 =(RelativeLayout)findViewById(R.id.layout1);
        layout2 =(RelativeLayout)findViewById(R.id.layout2);


          new CountDownTimer(5000, 1000) {

          @Override
          public void onFinish() {        
              layout1.setVisibility(View.GONE);
              layout2.setVisibility(View.VISIBLE);
          }

          @Override
          public void onTick(long millisUntilFinished) {
          }
         }.start();  


        button1 = (Button)findViewById(R.id.introbutton1);
        button1.setOnClickListener(new View.OnClickListener() {

            public void onClick(View v){            
            SharedPreferences pref = getSharedPreferences("SavedGame", MODE_PRIVATE); 
            SharedPreferences.Editor editor = pref.edit();      
            editor.putInt("Level", 1);  
            editor.commit();


         // Here, we are generating a random number
         Random generator = new Random();
         number = generator.nextInt(5) + 1; 
         // The '5' is the number of activities

         Class activity = null;

         // Here, we are checking to see what the output of the random was
         switch(number) { 
         // E.g., if the output is 1, the activity we will open is ActivityOne.class


             case 1: if(one == 1){
                 activity = activityone.class;
                 }

// if the activity was aready opened he will put value == 2, so the code will random again find activity with value == 1
                else if(one == 2){
                    Random generatorone = new Random();
                    number = generatorone.nextInt(5) + 1; 
                }

                 break;
             case 2: if(two== 1){
                 activity = activitytwo.class;
                 }
                else if(two== 2){
                    Random generatortwo = new Random();
                    number = generatortwo.nextInt(5) + 1; 
                }
                 break;
             case 3:if(three== 1){
                 activity = activitythree.class;
                 }
                else if(three== 2){
                    Random generatorthree = new Random();
                    number = generatorthree.nextInt(5) + 1; 
                }
                 break;
             case 4:if(four == 1){
                 activity = activityfour.class;
                 }
                else if(four == 2){
                    Random generatorFour = new Random();
                    number = generatorFour.nextInt(5) + 1; 
                }               

                 editor = pref.edit();
                 // Key,Value
                 editor.putInt("Activity", number);

                 editor.commit();      
                 }
         // We use intents to start activities
         Intent intent = new Intent(getBaseContext(), activity);
         startActivity(intent);
            }
         });
     }

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

but when i click the button, the app was force close. Did i missing something? anyone can help?




Algorithm for shuffling recycled data

I have a program which asks the user a question. If the user doesn't know the answer, he can skip it.

But if he answers wrong, that question is allotted negative points and then that question must be asked again randomly any time during the quiz.

If the question is answered correctly, the question need not be asked again.

Is there any algorithm to shuffle the questions like that?




How to parallelise Rcpp code that generate random booleans

As a follow on from this question: Vectorised Rcpp random binomial draws - I would like to try and parallelise the Rcpp code - however it gives me errors. Example:

library(Rcpp)
library(parallel)
library(microbenchmark)

cppFunction(plugins=c("cpp11"), "NumericVector cpprbinom(int n, double size, NumericVector prob) { 
NumericVector v = no_init(n);
std::transform( prob.begin(), prob.end(), v.begin(), [=](double p){ return R::rbinom(size, p); }); 
return(v);}")


a <- runif(1e6)
b <- runif(1e6)
z <- list(a,b)


res1 <- lapply(z, function(z) rbinom(length(z), 1 , z ))
res2 <- lapply(z, function(z) cpprbinom(length(z), 1 , z ))
microbenchmark(rbinom(length(a), 1, a), cpprbinom(length(a), 1, a))

cores<-2
cl <- makeCluster(cores)
    clusterExport(cl, c("cpprbinom"))
    clusterSetRNGStream(cl=cl, 5)
    res3 <- parLapply(cl=cl, z, function(z) cpprbinom(length(z), 1 , z ))
stopCluster(cl)

The parallel version throws the error: Error in checkForRemoteErrors(val) : 2 nodes produced errors; first error: NULL value passed as symbol address

Can anyone help me to parallelise the Rcpp code ? (or is this very complicated ?)

I'm also curious as to whether I could use my GPU to generate random booleans, but I know zero about R-GPU programming and so don't really know how to frame such a question properly.




Random order for group of rows in mysql

maybe it´s easy but i have no clue how to handle this correctly. I have the following table t1 with this data:

-----------------
| id    | gr_id |
-----------------
| 1     | a     |
| 2     | a     |
| 3     | b     |
| 4     | b     |
| 5     | c     |
| 6     | c     |
| 7     | d     |
| 8     | d     |
-----------------

I would like to get randomly gr_ids like this:

-----------------
| id    | gr_id |
-----------------
| 3     | b     |
| 4     | b     |
| 5     | c     |
| 6     | c     |
| 7     | d     |
| 8     | d     |
| 1     | a     |
| 2     | a     |
-----------------

Getting ordered gr_ids ascend and descend is pretty easy, but getting randomly grouped results, is pretty more complicated than i thought it is.

I do not get it, when i use GROUP BY or sth. similar i get for sure only one row each group. How can i randomly order groups, what is the trick here???

Thank you guys for bringing light into darkness ;)




vendredi 28 août 2015

How to randomly select 2 vertices from a graph in R?

I'm new to R, and I'm trying to randomly select 2 vertices from a graph.

What I've done so far is: First, set up a graph

edgePath <- "./project1/data/smalledges.csv"

edgesMatrix <- as.matrix(read.csv(edgePath, header = TRUE, colClasses = "character"))
graph <- graph.edgelist(edgesMatrix)

The smalledges.csv is a file look like this:

from     to
4327231  2587908

Then I get all the vertices from the graph into a list:

vList <- as.list(get.data.frame(graph, what = c("vertices")))

After that, I try to use:

sample(vList, 2)

But what I've got is an error:

cannot take a sample larger than the population when 'replace = FALSE'

I guess it's because R thinks what I want is 2 random lists, so I tried this:

sample(vList, 2, replace = TRUE)

And then I've got 2 large lists... BUT THAT'S NOT WHAT I WANTED! So guys, how can I randomly select 2 vertices from my graph? Thanks!




R ergm network configuration

I am not sure how to do network configuration with ergm package in R. I now have a sample of n=10 and need to rebuild connections within the 10 samples 1000 times. May I ask what's the code for rebuilding connections?

Thankssss so much!




What is a good way to seed parallel pseudo random number generators?

The PRNG I wrote has a period of 2^64. When I use a spinlock to protect it from 4 threads, It runs twice slower than when there is a single thread. A mutex appears better at making things slower. So I decided to have separate generators per thread, but the problem here is that when the seeds are too close, The same series of random numbers will appear again and again each in a different thread. I'm not 100% sure how bad this will affect my simulation, but I'd like to avoid having very closely seeded PRNGs.

The best I can think of is like below, with 4 threads.

N = 2 ^ 64 / 4 (^ means power)
n = getSomeNiceInitialSeed()
seed1 = n
seed2 = n + N
seed3 = n + N * 2
seed4 = n + N * 3

Is there some better solution to this problem?




std::normal_distribution

Anyone came access this issue? Per 1 the implementations are not required to produce same data. What about in practice - are there many differences in STL implementations among arm, x86, free and commercial compilers?

// g++ --std=c++11 -o a minimal.cpp && ./a

#include <iostream>
#include <random>

using namespace std;

int
main()
{
  std::mt19937_64 gen;
  gen.seed(17);

  cout << "\nNormal\n";
  normal_distribution<double> distr1;
  for (int i = 0; i < 2; i++) {
    double delay = distr1(gen);
    printf("  Value = %15.15g\n", delay);
  }
  return(0);
}


/*

Results

(1) gcc-4.8.0 linux 64b version result
  Normal
    Value = 1.03167351251536
    Value = 1.21967569130525
(2) Microsoft Visual Studio Community 2015 Version 14.0.23107.0 D14REL
      or 
    Microsoft Visual Studio Professional 2012 Version 11.0.60610.01 Update 3
  Normal
    Value = 1.21967569130525
    Value = 1.03167351251536  // same values in wrong (different) order
*/

I could understand use of a different algorithm for either the generator or the distribution on some special HW platform but this difference seems more as a bug.

Here is some more code I used to diagnose where does the difference come from and workaround it: - Generator and uniform distribution match on win and linux. - The normal distribution matches numerically except for pair-wise order

//   g++ --std=c++11 -o a workaround.cpp && ./a


#include <iostream>
#include <random>
#include <stack>


using namespace std;

typedef  std::mt19937_64  RandGenLowType;

// Helper wrapper - it did confirm that the differences
// do NOT come from the generator
class RandGenType : public RandGenLowType {
  public:
    result_type operator()() {
      result_type val = RandGenLowType::operator()();
      printf("    Gen pulled %20llu\n", val);
      return(val);
    }
};


typedef normal_distribution<double> NormalDistrLowType;

// Workaround wrapper to swap the output data stream pairwise
class NormalDistrType : NormalDistrLowType {
  public:
    result_type operator()(RandGenType &pGen) {
      // Keep single flow (used variables, includes) same for all platforms
      if (win64WaStack.empty()) {
        win64WaStack.push(NormalDistrLowType::operator()(pGen));
#ifdef _MSC_VER
        win64WaStack.push(NormalDistrLowType::operator()(pGen));
#endif
      }
      result_type lResult = win64WaStack.top();
      win64WaStack.pop();
      return(lResult);
    }    
  private:
    std::stack<result_type> win64WaStack;
};


int
main()
{
  RandGenType gen;
  gen.seed(17);

  // No platform issue, no workaround used
  cout << "\nUniform\n";
  uniform_real_distribution<double> distr;
  for (int i = 0; i < 4; i++) {
    double delay = distr(gen);
    printf("  Delay = %15.15g\n", delay);
  }

  // Requires the workaround
#ifdef _MSC_VER
  cout << "Workaround code is active, swapping the output stream pairwise\n";
#endif
  cout << "\nNormal\n";
  //normal_distribution<float> distr1;
  NormalDistrType distr1;
  for (int i = 0; i < 10; i++) {
    double delay = distr1(gen);
    printf("  Value = %15.15g\n", delay);
  }
  return(0);
}




Semi-random distributed graph in python

So what I want to do is to randomize a path between any point outside of the destination and have areas of weight that may affect the probability that my random function would fall around those areas. Imagine a piece of paper with slight gravity wells but ultimately a big black hole at the destination. How would I be able to create a function that simulates this process?




Generate random xy values within two-dimensional circular radius?

I have some points that are located in the same place, with WGS84 latlngs, and I want to 'jitter' them randomly so that they don't overlap.

Right now I'm using this crude method, which jitters them within a square:

r['latitude'] = float(r['latitude']) + random.uniform(-0.0005, 0.0005)
r['longitude'] = float(r['longitude']) + random.uniform(-0.0005, 0.0005)

How could I adapt this to jitter them randomly within a circle?

I guess I want a product x*y = 0.001 where x and y are random values. But I have absolutely no idea how to generate this!

(I realise that really I should use something like this to account for the curvature of the earth's surface, but in practice a simple circle is probably fine :) )




Using Random Number Generator with Current Time vs Without

I want to understand what the difference is between using a Random number generator, setting System.currentTimeMillis() as the seed, and just using the default constructor. That is, what is the difference between this:

Random rand = new Random(System.currentTimeMillis());

and this:

Random rand = new Random();

I know that the numbers are pseudo-random, but I am yet to fully understand the details, and how they come about, between the level of 'randomness' one gets when current time is used as seed, and when the default constructor is used.




Does C always generate the same random sequence?

I ran a program that called rand() four times. I used the modulus operator to limit the range to 1–6. The integers produced were 2, 5, 4, and 2. I reran the program and got the same numbers. Then I created a brand new program that also called rand() four times, and I still got the integer sequence 2, 5, 4, 2. Then I shut the computer down, powered back up, created another new program that called rand() four times, and still got the sequence 2, 5, 4, 2.

I understand the basics that you need to “seed” the RNG using srand(), which starts the sequence at different points, but I'm just curious: forgetting about seeding for a moment, is the sequence generated by rand() installation, compiler, and/or OS dependent? For example, would any of the following result in a different sequence:

  • uninstalling and reinstalling the C compiler on my computer
  • installing and using a different C compiler on my computer
  • running the program on someone else's computer with the same compiler?
  • running the program on someone else's computer with a different compiler (and perhaps a different OS)?

Or is it just a matter of all C compilers using the same RNG algorithm and so the pseudorandom sequence (starting from the beginning) will be the same for everyone?




Random Number Generator C++ Error in CMD

I'm trying to make a random number generator, to generate a number between 0 and 999.

I did originally have it running where the seed for mt19937 was generated from time(null), but found that this would cause the number to change once per second, and was not fast enough for when I called it again from within the for loop.

I'm using code::blocks to compile my code, and it compiles with no errors, but when I run the code I an error in cmd.

Error: terminate called after throwing an instance of 'std::runtime_error'
  what():  random_device::random_device(const std::string&)

Am I doing something horribly wrong?

#include <iostream>
#include <random>

using namespace std;

//Random Number Generator
int numGen() {

    //Random Number Generator
    random_device rd;
    mt19937 mt(rd());
    uniform_int_distribution<int> dist(0, 999);

    for (int I = 0; I < 6; i++) {
        cout <<dist(mt) << " ";
    }

    cout <<endl;
}




Android game development : how to generate a map dynamically?

I'm thinking about starting to programming an Android game, and my main problem is that i don't know how to generate a random map and/or a ground like "Boom Beach" and all that stuff which foolow a logic (pattern ?).

I often read articles about this but it's always the theory (like heightmap), and i don't understand how to implement this (heightmap or not) in Android code.

I would appreciate some examples and references guys.

Thanks a lot.

[Note : I'm a beginner of game development but not in programming, i'm a web developer and also know some Java and Android programming]




Randomize 4 Colors and save C#

I'm creating a Mastermind game where the user choses 4 out of 5 colors and see if it's a match. It would then send the given color combination to the CheckClass to see if the combination is right.

My question is, how could i randomize 4 between Red, Blue, Yellow, Lime and Purple?

Would I have to randomize with the different color codes? This is what i've found so far:

private Color GetRandomColor()
{
return Color.FromArgb(random.Next(0, 255), random.Next(0, 255), random.Next(0, 255));
}

Which color codes should i use?

Thanks!




random number in every testrun | JMeter Webdriver

I have a script, which create a new user in every testrun with a random number as name. So the users are unique.

But when I start a testrun in Ultimate Thread Group with more than one user it use always the same random-number. Is it possible to create everytime a new one?

I tried to use propertys or reset a variable at the end, but it didn't worked.




jeudi 27 août 2015

Random number using Date() in Expression Builder

I want to generate random number using Date() to format it like for example: ddmmyyyyHhNnSs

How do I achieve that? Is that even possible? I was kinda hoping I can do it easy way by the expression builder but I seem to fail on each approach ;)

This number need to populate txtID field and it will be unique identifier for each database entry.




How to make a Button randomly Move

Hey Guys i have a Question about how to make a button randomly move every second

the black tiles are a button

enter image description here

so i want to make it move randomly in every second or more fast

enter image description here

this is my xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://ift.tt/nIICcg"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:background="@drawable/backgroundblank" >
                  <Button
                    android:id="@+id/Button01"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:background="@drawable/black1" />
</RelativeLayout>

this is the code

public class tested extends Activity {

Button buttonblack;



@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    this.requestWindowFeature(Window.FEATURE_NO_TITLE);
    getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
    WindowManager.LayoutParams.FLAG_FULLSCREEN);
    setContentView(R.layout.tested);


    buttonblack = (Button)findViewById(R.id.black1);
    buttonblack.setOnClickListener(new View.OnClickListener() {

              public void onClick(View v){
              //if the button clicked
              //Do some logic here
                                         }                
            });

}

anyone can help me?




How to randomly select a song I haven't heard in a while and play it

Shuffling mp3 files often results in hearing a track that recently played. So I decided to use the 'touch' command to update the 'last modified' date & time of a file. I want my script to randomly select a song from the 10 songs that I haven't heard in the longest amount of time.

I came up with this: ls -t $music_folder | tail -n 10 | sort -R | tail -n 1 | while read file; do echo $music_folder$file mplayer $music_folder$file done

I have not yet added the 'touch' line to update the song that's about to play.

This lists the files in $music_folder sorted by time last modified, looks only at the 10 that haven't been touched in the longest time, randomizes the sort order of those ten, then grabs the one at the bottom of the list...

The 'echo' line works perfectly. However, when I try to play the song with mplayer, it tries to play several files where each word of the results is a different file name. Why is it not passing $file as a single string of text? and how can I get mplayer to play the file shown in the echo line?

Thank you!




How cqn I get a Random URL on http request for Gatling?

I would like to get a Random URL on http request for Gatling

My scenario is defined like this:

    import io.gatling.core.Predef._
import io.gatling.http.Predef._
import scala.concurrent.duration._
import scala.util.Random

class testSimulation extends Simulation {

  val httpConf = http.baseURL("OURURL")


  val scn = scenario("View HomePages")
                .exec(
                        http("Home page")
                                .get("/" + new Random().nextInt())
                              .resources(
                                      http("genericons.css").get("/wp-content/themes/twentyfifteen/genericons/generi$
                                      http("style.css").get("/wp-content/themes/twentyfifteen/style.css?ver=4.2.3"),
                                      http("jquery.js").get("/wp-includes/js/jquery/jquery.js?ver=1.11.2"),
                                      http("jquery-migrate.min.js").get("/wp-includes/js/jquery/jquery-migrate.min.j$
                                      http("skip-link-focus-fix.js").get("/wp-content/themes/twentyfifteen/js/skip-l$
                                      http("functions.js").get("/wp-content/themes/twentyfifteen/js/functions.js?ver$
                                      http("wp-emoji-release.min.js").get("/wp-includes/js/wp-emoji-release.min.js?v$
                                      http("wp-emoji-release.min.js").get("/wp-includes/js/wp-emoji-release.min.js?v$
                                      http("skip-link-focus-fix.js").get("/wp-content/themes/twentyfifteen/js/skip-l$
                                      http("functions.js").get("/wp-content/themes/twentyfifteen/js/functions.js?ver$
                              )
                )

  setUp(
      scn.inject
      (
      rampUsersPerSec(1) to(300) during(60 seconds),
      constantUsersPerSec(300) during(600 seconds)
      )
      .protocols(httpConf)
      )
}

I have only one random number generated instead of one per request. Do you know how to solve it ? Thanks !




Random() always picks the same number using a seed

I have a very strange bug that I am trying to fix. I will try my best to explain it.

I have a class, and in that class I have a method that picks a random number. The random number generation has to generate the exact same sequence of numbers every time I run the application (different numbers, but appear in the same order no matter when I run the app).

Therefore I need to use seeds.

My code looks something like this:

    public class Tree{
    Random rand = new Random(12345);

///...code...///

         public Tree randomNode() {

              //HERE IS THE ERROR
              int r = rand.nextInt(this.size);

              if (r == 0) {
                 return this;

              } 
              else if (left != null && 1 <= r && r <= left.size) {
                 return left.randomNode();
              } 
              else {
                 return right.randomNode();
              }
           }
        }

I have a helper class that uses this, it looks a bit like this:

   public Crossover(Tree p1, Tree p2)
   {
      Tree subtreeP1 = p1.randomNode();
      Tree subtreeP2 = p2.randomNode();
   }

My main method looks a bit like this:

for(i=0;i<cross;i++)
{
Crossover c = new Crossover(p1,p2);
}

During the first loop in the main method, the numbers for r generate randomly and are fine. However, on the 2nd loop (and all that follow) is where I encounter the problem. The problem is on the line int r = rand.nextInt(this.size); - After the 2nd loop I ALWAYS get 0 no matter what.

If I remove the seed, all works well. If I include the seed, I start getting 0 ALWAYS after the first loop.

How can I continue using a seed, but get random numbers? And what am I doing wrong?

**EDIT: **

this.size refers to the size of my tree. I have ensured it is NOT zero when I get r to be 0. ALSO I would like to point out, that when I simply remove the number seed, it works fine, and random number generation works fine. When I add the seed, I have the problem.




Has it always been stackoverflo,ooo,ooow?

Has the logo for Stackoverflow always been "stackoverflo,ooo,ooow"?

enter image description here

They did change that right? I'm not going crazy i hope.




Simple rock, paper, scissors game [Python]

I'm trying to write a simple RPS game but I'm having trouble getting the program to display the result of the game. Mind you, I'm a total beginner in programming and I've written all this from what I've learned previously so it probably isn't the most efficent way to write a game like this.

import random
rps = ['rock', 'paper', 'scissors']
rps2 = (random.choice(rps))

print 'Welcome to RPS'
print 'Press 1 to pick Rock'
print 'Press 2 to pick Paper'
print 'Press 3 to pick Scissors'
print 'Press 4 to quit.'


while True:
    game = int(raw_input('What do you pick? '))
    if game == 1:
        print 'You picked rock.'
        print 'The computer picked...' + (random.choice(rps))
        if rps2 == [0]:
            print 'It\'s a tie!'
        elif rps2 == [1]:
            print 'You lose!'
        elif rps2 == [2]:
            print 'You win!'
    elif game == 2:
        print 'You picked paper.'
        print 'The computer picked...' + (random.choice(rps))
        if rps2 == [0]:
            print 'You win!'
        elif rps2 == [1]:
            print 'It\'s a tie!'
        elif rps2 == [2]:
            print 'You lose!'
    elif game == 3:
        print 'You picked scissors.'
        print 'The computer picked...' + (random.choice(rps))
    if rps2 == [0]:
        print 'You lose!'
    elif rps2 == [1]:
        print 'You win!'
    elif rps2 == [2]:
        print 'It\'s a tie!'
    elif game == 4:
        print 'Thank you for playing!'
        break
    else:
        continue




Java Finding Average with Loop and Arrays

This is a Java problem I am having, I am somewhat new to Java.

I have to:

  1. generate a random fraction

  2. keep generating until the sum is greater than 1

  3. then I have to display how many numbers I generated and which ones

Here is what I have so far in my function:

public static double calcAvg(int numOfTimes){
        double sumOfRand = 0 ;
        int numOffractions = 0;
        double avg = 0;

        double numOfAvg[] = new double[numOfTimes]; // number of rows
        double randNums[] = new double[] {.1,.2,.3,.4,.5,.6,.7,.8,.9};
        Random rand = new Random();


        for(int i = 0; sumOfRand <= 1; i++){
            int randNum = rand.nextInt(randNums.length); //gets a number from array randomly
                //System.out.println(randNums[randNum]);


            sumOfRand += randNums[randNum]; //adds it to the sum
              numOffractions++; //counts # of avgnums needed for > 1

              numOfAvg[i] = numOffractions; 

        }

        avg = (numOfAvg[0] + numOfAvg[1] + numOfAvg[2]) /(numOfTimes); 

    return avg;
}

I keep getting an error on: numOfAvg[i] = numOffractions; and I can't seem to add the fractions to the sum until they pass 1.




How to retrieve a given number of random hits?

I have a database from which I would like to retrieve 100 documents, randomly distributed, which match two should constraints.

If I just query using a "size": 100, I get 100 hits corresponding to only one of the constraints. Fair enough, this is probably how elasticsearch indexed the data and the result is correct (100 documents which matched either of the constraints).

To ensure that I have the right matching body, I set size to 100000 (more than the total amount of documents) and I got about 40k documents, 20k for each constraint. This is consistent with the data.

As for the random part, I know about random scoring, a good example was given as an answer to another question.

Now combining both, i.e. "size": 100 and random_score I get, like in the first case, 100 documents matching only one of the two constraints. So no randomness.

It looks therefore that the randomizing is done internally in ES after size has been applied. Is that a correct conclusion?

If so, the "random" part would only be applied to the order of the returned results, and not the query - which is not what I understood from the documentation


If the above conclusion is correct, the solution would mean first getting all the 20+20=40k hits, randomize and slice them locally. This is feasible for such a small amount of documents, but not efficient (nor scalable), taken into account the availability of random_score.




Block choice of same data pool when random.shuffle

I am working on a code that looks at choices in a mutliple trial game. There are four choice (A,B,C,D) options and four payoff pools (pool_1, pool_2, pool_3 and pool_4). Each choice is asssigned to one pool (A - pool_1 etc). I want to randomly shuffle the pools once 5 in 6 choices have been the same (e.g. AAABAA -> change pool_1 to any other BUT pool_1).

For now I have coded it the way that after 5 streaks (5 choices in a row) the pools change. I just do not manage to have the pools change after 5 in 6 choices have been the same and also sometimes the same pool gets randomly selected again, which I do not want.

if (streak % 5) == 0 : pools = [pool_1, pool_2, pool_3, pool_4] random.shuffle(pools)

work1 = pools[0]
work2 = pools[1]
work3 = pools[2]
work4 = pools[3]

Any help is appreaciated -thank you!




How do you return a random label? (Swift)

I want to return random text from one of two Labels. I can only find answers for returning random numbers. See image below for what I'm trying to do.enter image description here

Any ideas? Thanks!




Efficient way of generating random integers within a range in Julia

I'm doing MC simulations and I need to generate random integers within a range between 1 and a variable upper limit n_mol

The specific Julia function for doing this is rand(1:n_mol) where n_mol is an integer that changes with every MC iteration. The problem is that doing it this is slow... (possibly an issue to open for Julia developers). So, instead of using that particular function call, I thought about generating a random float in [0,1) multiply it by n_mol and then get the integer part of the result: int(rand()*n_mol) the problem now is that int() rounds up so I could end up with numbers between 0 and n_mol, and I can't get 0... so the solution I'm using for the moment is using ifloor and add a 1, ifloor(rand()*n_mol)+1, which considerably faster that the first, but slower than the second.

function t1(N,n_mol)
    for i = 1:N
        rand(1:n_mol)
    end
end

function t2(N,n_mol)
    for i = 1:N
        int(rand()*n_mol)
    end
end

function t3(N,n_mol)
    for i = 1:N
        ifloor(rand()*n_mol)+1
    end
end


@time t1(1e8,123456789)
@time t2(1e8,123456789)
@time t3(1e8,123456789)


elapsed time: 3.256220849 seconds (176 bytes allocated)
elapsed time: 0.482307467 seconds (176 bytes allocated)
elapsed time: 0.975422095 seconds (176 bytes allocated)

So, is there any way of doing this faster with speeds near the second test? It's important because the MC simulation goes for more than 1e10 iterations. The result has to be an integer because it will be used as an index of an array.




mercredi 26 août 2015

Finite State Machine for Generating Names One Letter at a Time

I recall taking a class several years ago where I was given an interesting example of a finite state machine in which each state contained a letter and had multiple paths that led to other letters that generally followed them in a word. Some of the letters also had paths that led to a termination as well, and by starting at any point in the finite state machine and following valid paths to a termination, you could chain the letters together and (almost) always end up with a valid word. Of course this was only a subset of the words in the language (which unfortunately I forgot what language the FSM was meant for). My question involves multiple related questions:

  • Is this a viable way to randomly generate a "pseudo" word? By that I mean a word that isn't necessarily valid, but one that's spelled in a way that looks valid.
  • Is this technique used in, or as part of, any well-known random word generators, and if so, which ones?
  • Are there other common alternatives to this that generate a random word one letter at a time, or possibly to take a random string that was generated in this manner and coerce it into a "pseudo" word?

You don't have to answer all of these, just at least one. However, I'll be more likely to accept an answer that addresses all of these in some way.




Is there a similar function like mt_rand for MYSQL

Is there a similar function like mt_rand for MYSQL? I've searched everywhere but can't seem to find one.




math.random always give 0 result

I am using Ubuntu 14.04.3 LTS and I am studying Java from the book. I tried to follow one example on the book with Ubuntu Terminal and I'm using Sublime Text. Here is the code

import java.util.Scanner;

public class RepeatAdditionQuiz{
    public static void main(String[] args){
        int number1 = (int)(Math.random()%10);
        int number2 = (int)(Math.random()%10);

        Scanner input = new Scanner(System.in);

        System.out.print(
            "What is "+number1+" + "+number2+"?");
        int answer = input.nextInt();

        while(number1+number2 != answer){
            System.out.print("Wrong answer. Try again. What is "
                 +number1+" + "+number2+"? ");
            answer = input.nextInt();
        }
        System.out.println("You got it!");
    }
}

But the problem is, when I compiled it and executed it. It gives me result

what is 0 + 0?_

every time. It suppose to give me random number, and yes, it can be 0. But I tried to run it more than 10 times, it keeps giving me 0 + 0, when it's suppose to random from 0-9.

The result of 0 + 0 is fine when I typed 0 as a result, it gets me out of the loop

Did I miss something to make the math library works? How can I fix the randomize issue?




How to create a random data API

I want to create a server side API that returns random data from a text file list. And when user call that api, random data from each set of list is displayed (but data from each set should match each other) . Something like the random user generator API. So basically I have 2 lists:

Names (Names.txt)

John
Andy
James

Family Name (Family.txt)

Doe
Candy
Mill

and the basic random return json file when calling the API (http://ift.tt/1Lx3IrX) is :

{
  "name":"John",
  "family":"Doe"
}

I can't find any good tutorials on how to do this on my own server. I have found many websites which offer similar services but I want to create my own.

Update: I want every name to match exactly a specific family name. For example json output is first name and first last name, an other call outputs second name and second last name and etc.

Can someone points me to the right direction on how to do this?




java SecureRandom nextInt() vs nextGaussian()

Problem statement: Reward a customer with lucky draw coupon of X% discount in between 1% to 100%

Assume that slabs are pre-defined ( all are theoretical)

1% discount : 90% customers

10% discount : 5% customers

20% discount : 3% customers

100% discount : 2% customers

Solution 1:

Find the total number of customers. call nextInt(customer count). For example, assume that there are 100 customers.

if nextInt() is in between

99-100 : 100% discount

96-98 : 20%

90 -95: 10%

1-89 : 1%

Solution 2:

Use nextGaussian() of SecureRandom since it is a distributed randomness algorithm. How to configure above range using Gaussian?

Which one is more accurate?

Thanks in advance.




How to pick assign something to something out of 2 in C?

so i have got a struct that goes:

enum input_result get_human_player(struct player* human)
{
    char playerName[NAMELEN];
    printf("What is your name? ");
    fgets(playerName, NAMELEN, stdin);
    strcpy((*human).name, playerName);

    (*human).type = HUMAN;
    (*human).thiscolor = C_WHITE;
    (*human).counters = 0;

    return FAILURE;
}

how do i make it so it randomly assigns it to either C_WHITE or C_RED with a 50/50 chance?




Printing function results into an array

Seems simple but I can't figure it out.

let getRandom = randomSequenceGenerator(min: 1, max: 20)
for _ in 1...20 {
    println(getRandom())
}

getRandom prints out 20 non-repeating numbers into the console... PERFECT.

I want to get those 20 non-repeating numbers into an array so I can use them. I can't seem to figure it out.

Or anyway I can access those 20 numbers other than in the console.




random character in file name while reading - java

I am trying to read a text file from a specific location. but at the end the character is not decided. Ex. it can be

Custom Summary Report -- UAT --d.txt
Custom Summary Report -- UAT --f.txt
Custom Summary Report -- UAT --.txt
Custom Summary Report -- UAT --c.txt

So, the last character can be any alphabet or no alphabet.

I am using scanner to read that text file. and in filepath I don't know what to pass as a string.

DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
Date date = new Date();

String filepath = "C:/Custom Summary Report -- UAT -- "+dateFormat.format(date)+X+".txt";


// creating File instance to reference text file in Java
File text = new File(filepath);

// Creating Scanner instance to read File in Java
Scanner scnr = new Scanner(text);

In the String filepath the character X is the character which can be anything. (ie-any alpahbet or nothing.)

So, the X which I have mentioned in String filepath can be anything which I don't know on a specific location. So I want to read that file. Since I don't know that character scanner is throwing an error.

I want a code which can take any character at that perticular place and can read a file.




Return to Last Opened Activity if the App Re-open with Some Condition

I have a few interesting question here about how to return to latest activity if the game was restart/re-open because I have a new game button and continue button.So when continue button clicked it will return to last activity that opened before and the condition is activity is random from activityone to activityfive

I will explain with my code

this is menu.class

public class menu extends Activity {

int level;

Button newgame, continues, continuelocked;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    this.requestWindowFeature(Window.FEATURE_NO_TITLE);
    getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
    WindowManager.LayoutParams.FLAG_FULLSCREEN);
    setContentView(R.layout.menu);

    continuelocked=(Button)findViewById(R.id.buttoncontinuelocked);

    continues=(Button)findViewById(R.id.buttoncontinue);

    newgame=(Button)findViewById(R.id.buttonnewgame);
    newgame.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v){

            Intent i =new Intent(menu.this, intro.class);
            startActivity(i);          
            }             
      });
}           

public void onResume() {
    super.onResume();

       SharedPreferences pref = getSharedPreferences("SavedGame", MODE_PRIVATE); 
       level = pref.getInt("Level", 0); 

       if(level == 0)

        {   
           continuelocked.setVisibility(View.VISIBLE);
           continues.setVisibility(View.GONE);
        }   

       if(level == 1)

        {   
           continuelocked.setVisibility(View.GONE);
           continues.setVisibility(View.VISIBLE);
        }          

           SharedPreferences.Editor editor = pref.edit();
           editor.putInt("Level", level);
           editor.commit();

           continues=(Button)findViewById(R.id.buttoncontinue);
           continues.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v){

         //How to set this method to return to latest activity that i play before
         //if i use random levelactivity?

              });
    }

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

and in intro.class I do this method to make activity random, check my code below here -

@Override
public void onClick(View v) {
  // TODO Auto-generated method stub            

    button5 = (Button)findViewById(R.id.button5);
    if(v==button5) {

        SharedPreferences pref = getSharedPreferences("SavedGame", MODE_PRIVATE); 
        SharedPreferences.Editor editor = pref.edit();      
        editor.putInt("Level", 1);  
        editor.commit();                     

     // Here, we are generating a random number
     Random generator = new Random();
     int number = generator.nextInt(5) + 1; 
     // The '5' is the number of activities

     Class activity = null;

     // Here, we are checking to see what the output of the random was
     switch(number) { 
         case 1:
             // E.g., if the output is 1, the activity we will open is ActivityOne.class
             activity = ActivityOne.class;
             break;
         case 2:
             activity = ActivityTwo.class;
             break;
         case 3:
             activity = ActivityThree.class;
             break;
         case 4:
             activity = ActivityFour.class;
             break;
         default:
             activity = ActivityFive.class;
             break;
     }
     // We use intents to start activities
     Intent intent = new Intent(getBaseContext(), activity);
     startActivity(intent);
   }

and in every Activity "One to Five" I put the same random activity code

@Override
    public void onClick(View v) {
        // Here, we are generating a random number
        Random generator = new Random();
        int number = generator.nextInt(5) + 1; 
        // The '5' is the number of activities

    Class activity = null;

    // Here, we are checking to see what the output of the random was
    switch(number) { 
        case 1:
            // E.g., if the output is 1, the activity we will open is ActivityOne.class
            activity = ActivityOne.class;
            break;
        case 2:
            activity = ActivityTwo.class;
            break;
        case 3:
            activity = ActivityThree.class;
            break;
        case 4:
            activity = ActivityFour.class;
            break;
        default:
            activity = ActivityFive.class;
            break;
    }
    // We use intents to start activities
    Intent intent = new Intent(getBaseContext(), activity);
    startActivity(intent);
}
}

So My question is

First. How to open the last Activity with a Continue button if Activity was Random?

Second. if in every Activity had a same Random code to One until Five, How to set Disabled to Activity that already Opened before?

Anyone can explain about this?

UPDATED

I have found a solution with my second answer, but i dont try it yet so i dont know it work or not

so i changed the code like this

@Override
public void onClick(View v) {
  // TODO Auto-generated method stub            

    button5 = (Button)findViewById(R.id.button5);
    if(v==button5) {

        SharedPreferences pref = getSharedPreferences("SavedGame", MODE_PRIVATE); 
        SharedPreferences.Editor editor = pref.edit();      
        editor.putInt("Level", 1);  
        editor.commit();

     layout7.setVisibility(View.GONE);
     layout7.setVisibility(View.VISIBLE);

     // Here, we are generating a random number
     Random generator = new Random();
     number = generator.nextInt(5) + 1; 
     // The '5' is the number of activities

     Class activity = null;

     // Here, we are checking to see what the output of the random was
     switch(number) { 
     // E.g., if the output is 1, the activity we will open is ActivityOne.class

         case 1: if(one == 1){
             activity = ActivityOne.class;
             }
            else if(one == 2){
                Random generatorone = new Random();
                number = generatorone.nextInt(5) + 1; 
            }
             break;
         case 2: if(two== 1){
             activity = ActivityTwo.class;
             }
            else if(two== 2){
                Random generatortwo = new Random();
                number = generatortwo.nextInt(5) + 1; 
            }
             break;
         case 3:if(three== 1){
             activity = ActivityThree.class;
             }
            else if(three== 2){
                Random generatorthree = new Random();
                number = generatorthree.nextInt(5) + 1; 
            }
             break;
         case 4:if(four == 1){
             activity = ActivityFour.class;
             }
            else if(four == 2){
                Random generatorFour = new Random();
                number = generatorFour.nextInt(5) + 1; 
            }
             break;
         default:if(five== 1){
             activity = ActivityFive.class;
             }
            else if(five== 2){
                Random generatorfive = new Random();
                number = generatorfive.nextInt(5) + 1; 
            }
             break;
     }
     // We use intents to start activities
     Intent intent = new Intent(getBaseContext(), activity);
     startActivity(intent);
   }
 };

i think, if the int was show ==2 its mean the Activity was already opened before. so it will random again till found activity with ==1

can anyone correct my code above? it is right or not?

and my first question still dont have an answer

First. How to open the last Activity with a Continue button if Activity was Random and the app was re-open/restart?

Thank you in advance, have a good day




Play a random video once a day at a random time (VLC / Python / Telnet)

I am working on a project that deals with a specific way to exhibit video art.

For an exhibition, I want a random video to be played once a day at a random time. The random video is picked out of 10 chosen videos. So basically one video is randomly picked at a random moment within every 24 hours.

What would be the best way for me to go about this, and which programs / scripts should I use?

One suggestion I found was connecting VLC through telnet to Python, but before I commit to this I would like to consider various options.

Thank you very much for your help in advance! Luuk




Why doesnt this while loop stop after roll1 and roll2?

I've created a simple dice roll program. But the while loop will not stop when roll1 and roll2 are equal. And the total is not adding up. The programs runs infinite times, I have to stop it. Please help.

Output:

Roll #1: 1
Roll #2: 2
Total is : 3
Roll #1: 4
Roll #2: 1
Total is : 3
Roll #1: 4
Roll #2: 4
Total is : 3
Roll #1: 2
Roll #2: 5
Total is : 3
Roll #1: 4
Roll #2: 4
Total is : 3
Roll #1: 0
Roll #2: 2
Total is : 3
Roll #1: 4
Roll #2: 3
Total is : 3

Source Code:

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

public class App1
{
    public static void main( String[] args )
    {
        Random r = new Random();

        int roll1 = 1+ r.nextInt(6);
        int roll2 = 1+ r.nextInt(6);
        int total = roll1 + roll2;

        System.out.println("Heres comes the dice!");
        System.out.println();


        while ( roll1 != roll2 )
        {
            System.out.println("Roll #1: "  + roll1);
            System.out.println("Roll #2: "  + roll2);
            System.out.println("Total is : " + total );

        }
        System.out.println("Roll #1: "  + roll1);
        System.out.println("Roll #2: "  + roll2);
        System.out.println("Total is : " + total );


    }
 }




mardi 25 août 2015

How does this code generate 100 random number

will this work just as well for(a=0;a<100;a++)?? Why would someone write code like the code below? I think I know how this code is read. Does it take for loop a * b? What other ways could you write this code? I have not seen any code similar on this site so I thought I would create a question for it. Please help me if you can, also I am new to this site.

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

int main() {
    int r,a,b;

    printf("100 Random Numbers: ");

    for (a=0; a<20; a++) {
        for (b=0; b<5; b++) {
            r=rand();
            printf("%d\t", r);
        }
    }
}