jeudi 30 avril 2015

libGDX - How can I make smooth transitions between tiles

So I am recoding a game with a randomly generated map using libgdx instead of using java2D. And I currently have a map that looks like this.

enter image description here

And I need to figure out a way to make it look like this without making edge tiles for every possible transition.

enter image description here

and

enter image description here

How I used to do it was take each 16 x 16 tile split it into 8 x 8 tiles then add on the transition texture depending on where it needed to be.

I would do this again but I have 2 issues.

  1. I don't know how to generate a single 16 x 16 tile from 4 8x8 tiles.
  2. I don't have a way to correctly color a greyscale image to the correct color.

If I can do number 1 then I can just create the border tiles for each transition. Its more work but shouldn't be to much more work.

If you think im going about this all wrong then suggestions are appreciated




How to randomly fill fixed amount of columns in 2d array with a value in java?

Wordy question, let me give an example

The program that I am creating makes a 2D world using a 2D array whose sized is based on user input. In this example the world is a 4 X 10 world

----------
----------
----------
----------

How would I put 3 Xs in random positions along the bottom Row?

i.e.

----------
----------
----------
--x-x---x-

but making sure that it is random so that they don't appear in the same row if I run the method again?




How to generate n points and restrict the distance between them to be greater than a given value in MATLAB?

I would like to generate, randomly with uniform distribution, n points such that the distance between any point is greater than some fixed value.

Here is the scenario that I have in MATLAB:

  • I have M red points which I generate randomly with uniform distribution as follow: the x-abscissa of the M red points are xr = rand(1, M) and the y-ordinate of the M red points are yr = rand(1, M).
  • Also, I have M black points which I generate similarly as the red points, i.e., xb = rand(1, M) and yb = rand(1, M).
  • Then, I calculate the distances between all the points as follow:

    x = [xr, xb];
    y = [yr, yb];
    D = sqrt(bsxfun(@minus, x, x').^2 + bsxfun(@minus, y, y').^2);
    d = D(1:M, M + 1:end);
    
    
  • Now, I have to restrict the distance d to be always greater than some given value, say d0=0.5.

How to do this?




Random word out of 9 possible outcomes with Javascript [duplicate]

This question already has an answer here:

I want to write a javascript code that will randomly chose one out of nine possible words and display it on my page.

How would I go about this?

All help greatly appreciated!




Split data based on the outcome and on the predictor date

In simple two class machine learning problem we could split data using caret package, for example:

library(caret)
set.seed(3456)
trainIndex <- createDataPartition(iris$Species, p = .8,
                                  list = FALSE)
irisTrain <- iris[ trainIndex,]
irisTest  <- iris[-trainIndex,]

Using this approach we preserve the overall class distribution of the data. But, what if we want to use second factor to be used for splitting. Let's say, we have a data from four neighbouring sites for one year and two class outcome. So the split we want to make, will group sites by date and (on the same time) - try to preserve the overall class distribution of the data. For example:

Training set will be:
Class A, site a, January 25 
Class A, site b, January 25 
Class B, site c, January 25 
Class A, site d, January 25,
Class B, site c, January 27, 
Class A, site d, January 27,
....

Testing set will be:
Class B, site a, January 26 
Class A, site b, January 26 
Class B, site c, January 26 
Class A, site d, January 26,
Class A, site c, January 28, 
Class A, site d, January 28,
....   

I'm looking for solution to the problem - how to split the data based not only on the outcome, but also on the predictors (dates)?




Python using 'randint' gives error [on hold]

import random
rand = 0

while True:
    rand = rand.randint(70, 123)
    print (rand)

Gives this error...

rand = rand.randint(70, 123)
AttributeError: 'int' object has no attribute 'randint'

I really don't know why this doesn't work.




Hangman: problems with code

I recently started learning Python and am trying to make a hangman program.

The error comes up at for char in word and says that "name 'word' is not defined".

The code:

import random
import time

r = random.randint(0, 4)
name = raw_input("what is your name? ")
print "hello, " + name, "time to play hangman\n"
time.sleep(1)
print "ok take a guess:"
time.sleep(0.5)
wordList = ['apples', 'banana', 'orange', 'blueberry', 'grapefruit']
word = wordList[r]
guesses = 0
turns = 10
while turns > 0:         
failed = 0             
for char in word:      
    if char in guesses:    
        print char,    
    else:
        print "_",
        failed += 1    
if failed == 0:        
    print "\nYou won"  
break              
print
theGuess = raw_input("guess a character:")
guesses += theGuess                    
if theGuess not in word:  
    turns -= 1        
    print "Wrong\n"    
    print "You have", + turns, 'more guesses' 
    if turns == 0:           
        print "You Loose\n"




Generating 2 random numbers with specific probabilities

I have earlier written a code that generates random number - 0 or 1 - that represents the outcome of a one toss, with the assumption that probability to have head or tail is 0.5 " equal probabilities".

Now I want to modify the code so that, it will represent a Bernolli trial. H - head- represents a success, and a variable p represents probability of success. I tried to search how to generate random number with specific probability however I didn't know exactly how it's done.

My Earlier Code

n = 1; %number of trials

% Generating a random number from 1 to n trials, logical condition <0.5
% indicates that function rand should generates only two outcomes,
% either 0 or 1.

% Let 1 indicates "H" and 0 indicates "T".
x = rand(1,n) <0.5;

% count how many H and T in each tossing trial
number_of_H =0 ; number_of_T  =0;

for n=1:n
    if(x(1,n)==1)
        number_of_H=number_of_H+1;
    end
    if(x(1,n)==0) 
        number_of_T = number_of_T+1;
    end
end

probability_H = number_of_H/n; 
probability_T = number_of_T/n; 

I have seen this r = random(pd) from mathwork reference but when I tried to replace 0.7 with pd as a probability it gives an error that this is not a probability distribution.




java.util.Random NextDouble() is biased towards higher uniform number

I am using NextDouble() to generate uniform random number. I generated random number with 500 different seeds and found that the generated uniform random number is biased towards higher uniform number (mean was 0.93). Which is very absurd. I then divided the seed by 10000 and the random number generated was perfect (mean was 0.51). I found that the seed should not be more than 48 bits and so made sure that the seed I provide (seed for NextDouble() is generated randomly using nextLong() with seed = 12345) is less 48 bits. Then I re-generated the random number 500 times and found the same problem. Does anyone had similar issues with NextDouble()?




How to make a picture change randomly in a website?

I want to make a website that the user will decide something. The user will click what he or she chose.

I want to know how to make the picture change to a random other picture everytime the user clicks it.

Is there any way to do that?




VBA - create random number without duplicating

Let me start by saying I did do a search and found similar posts but I was unsure how to apply solutions to the code I have so I am hoping someone can help me.

I am trying to troubleshoot an existing Access database application that is supposed to generate a random number between 1 and the number of records in the table. This is done for 2o different tables with a varying amount of records. The tables with less records are displaying duplicate numbers of the 10 that it is supposed to display and write to a separate table. I assume the same would happen with the larger tables but with more numbers to choose from I was just unable to duplicate the issue.

Here is a sampling of the code with error handling removed:

    Dim db As DAO.Database
Dim rstRecords As DAO.Recordset
Dim rs As DAO.Recordset
Dim tdfNew As TableDef
Dim fldNew As Field
Dim i As Integer
Dim K As Integer
Dim Check As String

Set db = CurrentDb
Set rstRecords = db.OpenRecordset("customer_table")

     rstRecords.MoveLast
     FindRecordCount = rstRecords.RecordCount
     i = rstRecords.RecordCount
DoCmd.DeleteObject acTable, "Unique_numbers"

'--- create the table
Set tdfNew = db.CreateTableDef("Unique_numbers")
'--- add text field (length 20)
Set fldNew = tdfNew.CreateField("customer_table", dbLong)
'--- save the new field
tdfNew.Fields.Append fldNew

'--- save the new table design
db.TableDefs.Append tdfNew

'---Initialize your recordset
Set rs = CurrentDb.OpenRecordset("Unique_numbers", dbOpenDynaset)


'Dim i As Integer
'Dim K As Integer
'Dim Check As String

'i = TxtInput
  TxtInput = i
  K = 0
  Check = T

Do
  Do While K < 11
    'K = K + 1
        Randomize
          If K = 0 Then
            TxtOutput = Fix(i * Rnd) + 1
            rs.AddNew
            rs.Fields(0).Value = TxtOutput
            rs.Update
            K = K + 1
          ElseIf K = 1 Then
            TxtOutput2 = Fix(i * Rnd) + 1
            rs.AddNew
            rs.Fields(0).Value = TxtOutput2
            rs.Update
            K = K + 1
          ElseIf K = 2 Then
             TxtOutput3 = Fix(i * Rnd) + 1
             rs.AddNew
             rs.Fields(0).Value = TxtOutput3
             rs.Update
             K = K + 1
          ElseIf K = 3 Then
             TxtOutput4 = Fix(i * Rnd) + 1
             rs.AddNew
             rs.Fields(0).Value = TxtOutput4
             rs.Update
             K = K + 1
          ElseIf K = 4 Then
             TxtOutput5 = Fix(i * Rnd) + 1
             rs.AddNew
             rs.Fields(0).Value = TxtOutput5
             rs.Update
             K = K + 1
          ElseIf K = 5 Then
             TxtOutput6 = Fix(i * Rnd) + 1
             rs.AddNew
             rs.Fields(0).Value = TxtOutput6
             rs.Update
             K = K + 1
          ElseIf K = 6 Then
             TxtOutput7 = Fix(i * Rnd) + 1
             rs.AddNew
             rs.Fields(0).Value = TxtOutput7
             rs.Update
             K = K + 1
          ElseIf K = 7 Then
             TxtOutput8 = Fix(i * Rnd) + 1
             rs.AddNew
             rs.Fields(0).Value = TxtOutput8
             rs.Update
             K = K + 1
           ElseIf K = 8 Then
             TxtOutput9 = Fix(i * Rnd) + 1
             rs.AddNew
             rs.Fields(0).Value = TxtOutput9
             rs.Update
             K = K + 1
           ElseIf K = 9 Then
             TxtOutput10 = Fix(i * Rnd) + 1
             rs.AddNew
             rs.Fields(0).Value = TxtOutput10
             rs.Update
             K = K + 1
             Check = f
            Exit Do
          End If
    Loop
Loop Until Check = f

Thanks in advance.

Scott




segmentation fault while generating a number of random numbers using rand() in C

I am writing a program where I need to set a number of elements (specified by the blanks variable) of a 2D array (board) to be 0.(array size is 9x9) These locations has to be picked up in random and once I use the following code segment to do it, the program ends up in a segmentation fault in some instances and does not set the required number of positions to 0.

i = rand() % 10;
j = rand() % 10;

if (board[i][j]){
    board[i][j] = 0;
    blanks--;
}

I have been looking up on this issue bit and came to know that rand() is not thread safe. Is it the reason for the segmentation fault I am getting, or is it something else?

Further, is there a workaround for this? (For me to get a set of random numbers without this segmentation fault)




How do i set the notification to have a random message? [duplicate]

This question is an exact duplicate of:

Hi im trying to get my notification to display a random message from a list.

 mManager = (NotificationManager) this.getApplicationContext().getSystemService(this.getApplicationContext().NOTIFICATION_SERVICE);
    Intent intent1 = new Intent(this.getApplicationContext(),MainActivity.class);

    Notification notification = new Notification(R.mipmap.ic_launcher,"Hey!!!", System.currentTimeMillis());
    intent1.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP| Intent.FLAG_ACTIVITY_CLEAR_TOP);

    PendingIntent pendingNotificationIntent = PendingIntent.getActivity( this.getApplicationContext(),0, intent1,PendingIntent.FLAG_UPDATE_CURRENT);
    notification.flags |= Notification.FLAG_AUTO_CANCEL;
    notification.setLatestEventInfo(this.getApplicationContext(), "My favorite fruit is the", "", pendingNotificationIntent);

    mManager.notify(0, notification);

Where it says "my favorite fruit is", "" i want those to be random strings. When i tried to make the an array and choose a random string from in the array it force closed.




mercredi 29 avril 2015

Why does this list contain more than one distinct value?

I have code that looks like:

import qualified Data.Vector as V
import System.Random
import Control.Monad.State.Lazy
nextWeightedRandom :: State (StdGen, V.Vector Int) Int
nextWeightedRandom = do
  (g, fs) <- get
  let (i, g') = randomR (0, V.length fs - 1) g
  put (g', fs)
  return (fs V.! i)

weightedRandomList :: (StdGen, V.Vector Int) -> [Int]
weightedRandomList = evalState $ mapM (\_ -> nextWeightedRandom) [1..]

QuickCheck confirms that the values coming out of weightedRandomList are different and have roughly the distribution that I was hoping for (the Vector Int looks like [5, 5, 5, 10], so that nextWeightedRandom spits out 5 with probability 3/4 and 10 with probability 1/4).

I was able to get it working by guessing my way though the types, but I'm very confused --- isn't evalState getting run over a bunch of different copies of the same generator? Why doesn't the list produced look like [5, 5, 5, 5,...]?




Setting the text in a notification to a random string

I'm trying to get the notification to pick from my a random string from my array to display every time it appears. I made "random" a random string from my array and put it in my "notification.setLatestEventInfo." Here is what i have so far

public class MyAlarmService extends Service
{
Random r;
private NotificationManager mManager;
String[] fruits = {"Apple","Mango","Peach","Banana","Orange","Grapes","Watermelon","Tomato"};;
int idx = r.nextInt(fruits.length);
String random = (fruits[idx]);




@Override
public IBinder onBind(Intent arg0)
{
    // TODO Auto-generated method stub
    return null;
}

@Override
public void onCreate()
{
    // TODO Auto-generated method stub
    super.onCreate();
}

@SuppressWarnings("static-access")
@Override
public void onStart(Intent intent, int startId)
{
    super.onStart(intent, startId);

    mManager = (NotificationManager) this.getApplicationContext().getSystemService(this.getApplicationContext().NOTIFICATION_SERVICE);
    Intent intent1 = new Intent(this.getApplicationContext(),MainActivity.class);

    Notification notification = new Notification(R.mipmap.ic_launcher,"Hey!!!", System.currentTimeMillis());
    intent1.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP| Intent.FLAG_ACTIVITY_CLEAR_TOP);

    PendingIntent pendingNotificationIntent = PendingIntent.getActivity( this.getApplicationContext(),0, intent1,PendingIntent.FLAG_UPDATE_CURRENT);
    notification.flags |= Notification.FLAG_AUTO_CANCEL;
    notification.setLatestEventInfo(this.getApplicationContext(), "My favorite fruit is the", random, pendingNotificationIntent);

    mManager.notify(0, notification);
}

@Override
public void onDestroy()
{
    // TODO Auto-generated method stub
    super.onDestroy();
}

}

All it does with this is force close.




Random python selection within a ranged distribution

I have a normal distributed range from 10 to 100 with an average of 25. I am wanting to randomly sample this. Using:

random.gauss(25, 5)

I can obtain get a sample where the mean is 25 and the standard deviation is 6. Meaning only a 1% chance of getting outside of my lower limit. Obviously though this is not putting a high enough waiting on my upper limit and I will at most reach 40.

At present the only way I can think to hit the upper limit is to look at both the upper and lower with using a decision rule to look at the upper half 50% using

random.gauss(25, 25) 

of the time and lower the other 50% and have the first snippet. Only consider values higher than the mean for the upper and lesser than the mean for the other.

Is there any other way I can make this anymore precise. I have seen online ways of skewing a normal distribution but unsure how I can get that to work as my stats really isn't that strong.

Thanks in advance for any assistance.




Pick from array based on conditions C#

I'm developing a basic poker game (texas hold 'em) in C# right now. I have divided faces and suits in to Enums like so:

public enum Face { Ace, Two, Three, Four, Five, Six, Seven, Eight, Nine, Ten, Jack, Queen, King }

public enum Suit { Clubs, Spades, Hearts, Diamonds }

I then generate a string for debug purposes to test the generation.

string[] Faces = Enum.GetNames(typeof (Face));
string[] Suits = Enum.GetNames(typeof (Suit));

int r3 = rnd.Next(Faces.Length);
int r4 = rnd.Next(Suits.Length);

string currentCard = string.Format("{0} of {1}", Faces[r3], Suits[r4]);

This will generate a random string such as "Six of Diamonds"

For the visualization of the "generated" cards, I've loaded several images of each card in a deck into the resources and loaded those images into an image array like so (shortened for clutter purposes):

Image[] cardArray = { 
                      Resources._10_of_clubs, 
                      Resources._10_of_diamonds,
                      Resources._10_of_hearts,
                      Resources._10_of_spades,
                      Resources._2_of_clubs,
                      etc...
};

Is it possible to select a specific image from the array based on the generated circumstances created by the face and suit combinations above? So if "Six of Diamonds" were to be generated, the program will go in to the array and pick out the six of diamonds resource. Sorry if this is a bit much to ask. Even a push in the right direction would be appreciated.




Printing random data to .txt file in list form. ( python )

I am fairly new to python. I want to create a program that can generate random numbers and write them to a file, but I am curious to as whether it is possible to write the output to a .txt file, but in individual lists. (every time the program executes the script, it creates a new list)

Here is my code so far:

def main():
    import random
    data = open("Random.txt", "w" )

    for i in range(int(input('How many random numbers?: '))):
        line = str(random.randint(1, 1000))
        data.write(line + '\n')
        print(line)


    data.close()
    print('data has been written')
    main()




Python random value generator between a range with a mean

I need a random value generator between 5 and 100 where the average is 25.




What's the difference between arc4random and arc4random_uniform in Swift?

So I've seen old posts about the difference between random and arc4random in Obj. C, and I've seen answers to this online but I didn't really understand the answers so I was hoping someone here could explain it in an easier to understand manner.

What is the difference between using arc4random and arc4random_uniform to generate random numbers in Swift?

Thanks, Brennan




Standard Seed for random values from MATLAB to Python

Is there a simple way to translate this code from MATLAB to Python.

MATLAB

rand('twister',sum(100*clock));

Using the numpy module I should have something like this:

Python

import numpy as np
np.random.seed(value)

But how can I calculate value?




javascript random images script

I have an online store and I would like to make some improvements. I want to create a script which inserts me on every product page some random images of another products. But these images have to be linked with the description of that product and with the price. So far I got this :

function random_imglink(){
  var myimages=new Array()
  myimages[1]="imagepath1"
  myimages[2]="imagepath2"
  myimages[3]="imagepath3"
  ..............
  ..............

  var imagelinks=new Array()
  imagelinks[1]="link1"
  imagelinks[2]="link2"
  imagelinks[3]="link3"
  ................
  ................
  
  var Quotation=new Array()
  Quotation[1]="<h1>image 1</h1>"
  Quotation[2]="<h1>image 2</h1>"
  Quotation[3]="<h1>image 3</h1>"
  .............
  .............

  var price=new Array()
  price[1]="price1"
  price[2]="price2"
  price[3]="price3"
  ............
  .............
  
  var ry=Math.floor(Math.random()*myimages.length)  
  if (ry==0)
     ry=1
   document.write('<a href='+'"'+imagelinks[ry]+'"'+'><img src="'+myimages[ry]+'" border=0> '+Quotation[ry]+' '+price[ry]+'</a>')
     
}   

  random_imglink()

The problem is that I want more than just one image which gets randomising. I want 4 images to do that at every refresh... For example,if I create a table with one row and 4 columns and I copy the code above in every cell the script is working well. But I'm sure there is a beautiful solution.

I hope you people was able to understand me.Sorry for my english !




Random row selection using MySQL returns NULL

I am trying to get a random row from MySQL table using one of the following PHP lines:

$query = "SELECT * FROM tablename LIMIT 1 OFFSET ".rand(1,$num_rows);
$query = "SELECT * FROM tablename OFFSET RANDOM() * (SELECT COUNT(*) FROM characters) LIMIT 1";
$query = "SELECT * FROM tablename ORDER BY RAND() LIMIT 1";

but all return NULL.

Higher up my PHP code I obtain a row from the same table OK by specifying WHERE, so I don't understand why I can't retrieve a random one.




Having trouble resetting an equation in javafx

I've searched here for this answer and either I'm not using the proper words in my searches, or the question hasn't been asked.

I have a program that gives the user a randomly selected equation. The user works through 3 scenes to solve the equation, then is asked if they want to solve another. If they choose yes, I want the program to return to scene 1, and ask them to click "Load" for another problem. When they do this, the program would randomly select another equation and display it in Scene 2.

The problem I'm having is that when the user chooses yes, the program returns them to scene 1, asks them to click "Load," then takes them to the END of scene 2, displaying the end result of the equation they have already worked on.

I need help with clearing those values and displaying a new equation for the user.

I'm using Eclipse, and I've cut out A LOT of code just to give the relevant parts of the program that are giving me trouble. Thank you in advance for your help.

public class equationsapp extends Application implements EventHandler<ActionEvent> {

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

    @Override public void start(Stage primaryStage) {

        stage = primaryStage;

        Text welcome = new Text("Click the button to load an equation");

        Button begin = new Button("Load");
        begin.setOnAction(e -> begin_Click());

        HBox letsbegin = new HBox();
        letsbegin.getChildren().addAll(welcome);

        HBox letsbegin2 = new HBox();
        letsbegin2.getChildren().addAll(begin);

        GridPane startitoffgp = new GridPane();
        startitoffgp.add(letsbegin, 0, 0);
        startitoffgp.add(letsbegin2, 0, 1);

        startitoff.setCenter(startitoffgp);

        //Add BorderPane to Scene
        scene1 = new Scene(startitoff, 500, 300);       

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

        setreset();
    }

    public void begin_Click() {
        stage.setScene(scene2);
    }

    public void setreset() {
        Random eqrdmzr = new Random();
        randomNumber = eqrdmzr.nextInt(5) + 1;

            if (randomNumber == 1) {
                equation = 2n + 7 = 17
            }

            if(randomNumber == 2) {
                equation = 2n – 18 = 4
            }

            if(randomNumber == 3) {
                equation = 3n – 5 = 19
            }

            if(randomNumber == 4) {
                iCounterCoeff = 3n + 8 = 95
            }

            if(randomNumber == 5) {
                equation = 3n + 11 = 62
            }

        //Build scene1 - top BorderPane
        isoltext = new Text("Isolate the Variable Term");

        //Build scene1 - center BorderPane
        -- Equation is inserted here --

        //Build scene1 - bottom BorderPane
        -- User controls for isolating the variable term and advancing to next scene--

        //Create GridPanes and Fill Them
        gridpane1 contains isoltext
        gridpane2 contains the equation
        gridpane3 contains the user controls

        //Add GridPane to BorderPane
        gridpanes are added to borderpane

        //Add BorderPane to Scene
        scene2 = new Scene(borderpane, 500, 300);

        solve();
    }

    public void isolcontinuebtn_Click() {
        stage.setScene(scene3);
    }

    public void solve() { 
        //Build scene3 – top BorderPane
        slvtext = new Text("Solve for the Variable");

        //Build scene3 - center BorderPane
        -- Equation is inserted here --

        //Build scene3 - bottom BorderPane
        -- User controls for solving for the variable and advancing to next scene --

        //Create GridPanes and Fill Them
        Gridpane4 contains slvtext
        Gridpane5 contains the equation
        Gridpane6 contains the user controls

        //Add GridPanes to BorderPane
        gridpanes are added to borderpane2

        //Add BorderPane to Scene
        scene3 = new Scene(slvborderpane, 500, 300);

        sbmt();
    }

    private void slvsbmtbtn_Click() {
        if (iCounterSolve1b == 1 && iCounterSolve1a == iCounterSolve2a) {
            stage.setScene(scene4);
        }
    }

    public void sbmt() {
        //Build scene4
        sbmttext = new Text("Correct! Would You Like to Try Another?");

        yesbtn = new Button("Yes");
        yesbtn.setStyle("-fx-font-size: 12pt;");
        yesbtn.setOnAction(e -> yesbtn_Click());

        nobtn = new Button("No");
        nobtn.setStyle("-fx-font-size: 12pt;");
        nobtn.setOnAction(e -> nobtn_Click());

        sbmt = new HBox(30);
        sbmt.setPadding(new Insets(0, 0, 30, 0));
        sbmt.setAlignment(Pos.CENTER);
        sbmt.getChildren().addAll(yesbtn, nobtn);

        //Create GridPanes and fill them
        sbmtgridpane1 = new GridPane();
        sbmtgridpane1.setAlignment(Pos.CENTER);
        sbmtgridpane1.add(sbmttext, 0, 0);

        sbmtgridpane2 = new GridPane();
        sbmtgridpane2.setAlignment(Pos.CENTER);
        sbmtgridpane2.add(sbmt, 0, 0);

        sbmtborderpane = new BorderPane();
        sbmtborderpane.setTop(sbmtgridpane1);
        sbmtborderpane.setCenter(sbmtgridpane2);

    scene4 = new Scene(borderpane3, 500, 300);
    }

    public void yesbtn_Click() {
        stage.setScene(scene2);
    }

    public void nobtn_Click() {
        stage.close();
    }

}




Creating non reoccuring random groups of people

So this isn't really an informatics question but I'm guessing the solution lies in informatics.

We have a group of 100 students that are meant to have discussion amongst each other. For this we want to separate them into 10 groups of 10 people. We want to have three rounds of discussions, however we want the groups to be different each time. No one person should get to sit with the same person twice.

Say we assign our groups letters abcdefghij (10) Person1 gets Round1:A Round2:B Round3:C Person2 gets Round1:A but then can't have Round2:B or Round3:C because they would then meet again.

Doing this by hand sounds pretty insane and I'm sure there is a pretty simple solution for this. Maybe even a program that does exactly this, but I just can't find it or don't know what to search for...

Sadly I have no skills whatsoever in programming, but maybe this can even be done in excel or sth like that?

All help or tips apreciated. Thanks for taking the time!




Testing if random number equals a specific number

I know this might already have been answered, but all the places where i found it, it wouldn't work properly. I'm making a game in Greenfoot and I'm having an issue. So I'm generating a random number every time a counter reaches 600, and then testing if that randomly generated number is equal to 1, and if it is, it creates an object. For some reason, the object will be created every time the counter reaches 600. I'm somewhat new to Java so it's probably something simple.

if (Counter > 600)
  {
      int randomNumber = random.nextInt(10);

      if (randomNumber == 1)
      {          
          Invincible invincible = new Invincible();
          addObject(invincible, Greenfoot.getRandomNumber(getWidth()), Greenfoot.getRandomNumber(getHeight()));
          Counter = 0;
      }
      else 
      {              
      }
    }
 Counter ++;
}

I'm not getting errors as it is compiling fine, but when i run it i have issues. Any help? Thanks in advance!




How to Position an Object Separately from Randomized Objects in Unity3D?

In my 2D game I have randomized objects which are spawned as 4 to 5 clones each time I run the game. My problem is that I also have a different object that I want to spawn as 1 clone, and position it to appear after the last clone of the randomized objects I have in my game.

The objects randomization works perfectly in my game, I just need to separate that from the object that I want it to be spawned indecently and after the last clone of the randomized objects.

This is the code I am using with 1 line of attempt to spawn the independent object: (The code was taken from this tutorial)

 using UnityEngine;
    using System;
    using System.Collections.Generic;           //Allows us to use Lists.
    using Random = UnityEngine.Random;          //Tells Random to use the Unity Engine random number generator.
    
    namespace Completed
        
    {
        
        public class BoardManager : MonoBehaviour
        {
                
                // Using Serializable allows us to embed a class with sub properties in the inspector.
                [Serializable]
                public class Count
                {
                        public int minimum;                     //Minimum value for our Count class.
                        public int maximum;                     //Maximum value for our Count class.
                        
                        
                        //Assignment constructor.
                        public Count (int min, int max)
                        {
                                minimum = min;
                                maximum = max;
                        }
                }
                
                
                public int columns = 7;                                                                                 //Number of columns in our game board.
                public Count random1Count = new Count (1, 2);                                           //Lower and upper limit for our random number of objects
                public Count random2Count = new Count (1, 1);
                public Count random3Count = new Count (1, 1);
                public Count random4Count = new Count (1, 1);
                
                public GameObject[] randomObject1;                                                                      //Array of objects prefabs.
                public GameObject[] randomObject2;
                public GameObject[] randomObject3;
                public GameObject[] randomObject4;
    
                public GameObject obj; // the independent object declaration
    
                private List <Vector3> gridPositions = new List <Vector3> ();       //A list of possible locations to place objects.
                
                
                //Clears our list gridPositions and prepares it to generate a new board.
                void InitialiseList ()
                {
                        //Clear our list gridPositions.
                        gridPositions.Clear ();
    
                        //Loop through x axis (columns).
                        for(int x = 2; x < columns; x++)
                        {
                                
                                
                                //At each index add a new Vector3 to our list with the x and y coordinates of that position.
                                gridPositions.Add (new Vector3(x, 0.3f, 0f));
    
                                Instantiate(obj); // my attempt to instantiate the separate object
                                Debug.Log(obj.transform.position.x); // my attempt to track the position of the separate object
                        }
    
                }
                
                
                //RandomPosition returns a random position from our list gridPositions.
                Vector3 RandomPosition ()
                {
                        //Declare an integer randomIndex, set it's value to a random number between 0 and the count of items in our List gridPositions.
                        int randomIndex = Random.Range (0, gridPositions.Count);
                        
                        //Declare a variable of type Vector3 called randomPosition, set it's value to the entry at randomIndex from our List gridPositions.
                        Vector3 randomPosition = gridPositions[randomIndex];
                        
                        
                        //Remove the entry at randomIndex from the list so that it can't be re-used.
                        gridPositions.RemoveAt (randomIndex);
                        
                        
                        //Return the randomly selected Vector3 position.
                        return randomPosition;
                        
                }
                
                
                //LayoutObjectAtRandom accepts an array of game objects to choose from along with a minimum and maximum range for the number of objects to create.
                void LayoutObjectAtRandom (GameObject[] tileArray, int minimum, int maximum)
                {
                        //Choose a random number of objects to instantiate within the minimum and maximum limits
                        int objectCount = Random.Range (minimum, maximum+1);
                        
                        //Instantiate objects until the randomly chosen limit objectCount is reached
                        for(int i = 0; i < objectCount; i++)
                        {
                                
                                //Choose a position for randomPosition by getting a random position from our list of available Vector3s stored in gridPosition
                                Vector3 randomPosition = RandomPosition();
                                
                                
    
                                
                                //Choose a random tile from tileArray and assign it to tileChoice
                                GameObject tileChoice = tileArray[Random.Range (0, tileArray.Length)];
    
                                
                                //Instantiate tileChoice at the position returned by RandomPosition with no change in rotation
                                Instantiate(tileChoice, randomPosition, Quaternion.identity);
                                
                        }
                        
                }
                
                
                //SetupScene initializes our level and calls the previous functions to lay out the game board
                public void SetupScene (int level)
                {
    
                        //Reset our list of gridpositions.
                        InitialiseList ();
                        
                        //Instantiate a random number of objects based on minimum and maximum, at randomized positions.
                        LayoutObjectAtRandom (randomObject1, random1Count.minimum, random1Count.maximum);
                        LayoutObjectAtRandom (randomObject2, random2Count.minimum, random2Count.maximum);
                        LayoutObjectAtRandom (randomObject3, random3Count.minimum, random3Count.maximum);
                        LayoutObjectAtRandom (randomObject4, random4Count.minimum, random4Count.maximum);
                        
                        
                }
        }
    }

This is the code I am using with 1 line of attempt to spawn the independent object: (The code was taken from this tutorial)

 using UnityEngine;
    using System;
    using System.Collections.Generic;           //Allows us to use Lists.
    using Random = UnityEngine.Random;          //Tells Random to use the Unity Engine random number generator.
    
    namespace Completed
        
    {
        
        public class BoardManager : MonoBehaviour
        {
                
                // Using Serializable allows us to embed a class with sub properties in the inspector.
                [Serializable]
                public class Count
                {
                        public int minimum;                     //Minimum value for our Count class.
                        public int maximum;                     //Maximum value for our Count class.
                        
                        
                        //Assignment constructor.
                        public Count (int min, int max)
                        {
                                minimum = min;
                                maximum = max;
                        }
                }
                
                
                public int columns = 7;                                                                                 //Number of columns in our game board.
                public Count random1Count = new Count (1, 2);                                           //Lower and upper limit for our random number of objects
                public Count random2Count = new Count (1, 1);
                public Count random3Count = new Count (1, 1);
                public Count random4Count = new Count (1, 1);
                
                public GameObject[] randomObject1;                                                                      //Array of objects prefabs.
                public GameObject[] randomObject2;
                public GameObject[] randomObject3;
                public GameObject[] randomObject4;
    
                public GameObject obj; // the independent object declaration
    
                private List <Vector3> gridPositions = new List <Vector3> ();       //A list of possible locations to place objects.
                
                
                //Clears our list gridPositions and prepares it to generate a new board.
                void InitialiseList ()
                {
                        //Clear our list gridPositions.
                        gridPositions.Clear ();
    
                        //Loop through x axis (columns).
                        for(int x = 2; x < columns; x++)
                        {
                                
                                
                                //At each index add a new Vector3 to our list with the x and y coordinates of that position.
                                gridPositions.Add (new Vector3(x, 0.3f, 0f));
    
                                Instantiate(obj); // my attempt to instantiate the separate object
                                Debug.Log(obj.transform.position.x); // my attempt to track the position of the separate object
                        }
    
                }
                
                
                //RandomPosition returns a random position from our list gridPositions.
                Vector3 RandomPosition ()
                {
                        //Declare an integer randomIndex, set it's value to a random number between 0 and the count of items in our List gridPositions.
                        int randomIndex = Random.Range (0, gridPositions.Count);
                        
                        //Declare a variable of type Vector3 called randomPosition, set it's value to the entry at randomIndex from our List gridPositions.
                        Vector3 randomPosition = gridPositions[randomIndex];
                        
                        
                        //Remove the entry at randomIndex from the list so that it can't be re-used.
                        gridPositions.RemoveAt (randomIndex);
                        
                        
                        //Return the randomly selected Vector3 position.
                        return randomPosition;
                        
                }
                
                
                //LayoutObjectAtRandom accepts an array of game objects to choose from along with a minimum and maximum range for the number of objects to create.
                void LayoutObjectAtRandom (GameObject[] tileArray, int minimum, int maximum)
                {
                        //Choose a random number of objects to instantiate within the minimum and maximum limits
                        int objectCount = Random.Range (minimum, maximum+1);
                        
                        //Instantiate objects until the randomly chosen limit objectCount is reached
                        for(int i = 0; i < objectCount; i++)
                        {
                                
                                //Choose a position for randomPosition by getting a random position from our list of available Vector3s stored in gridPosition
                                Vector3 randomPosition = RandomPosition();
                                
                                
    
                                
                                //Choose a random tile from tileArray and assign it to tileChoice
                                GameObject tileChoice = tileArray[Random.Range (0, tileArray.Length)];
    
                                
                                //Instantiate tileChoice at the position returned by RandomPosition with no change in rotation
                                Instantiate(tileChoice, randomPosition, Quaternion.identity);
                                
                        }
                        
                }
                
                
                //SetupScene initializes our level and calls the previous functions to lay out the game board
                public void SetupScene (int level)
                {
    
                        //Reset our list of gridpositions.
                        InitialiseList ();
                        
                        //Instantiate a random number of objects based on minimum and maximum, at randomized positions.
                        LayoutObjectAtRandom (randomObject1, random1Count.minimum, random1Count.maximum);
                        LayoutObjectAtRandom (randomObject2, random2Count.minimum, random2Count.maximum);
                        LayoutObjectAtRandom (randomObject3, random3Count.minimum, random3Count.maximum);
                        LayoutObjectAtRandom (randomObject4, random4Count.minimum, random4Count.maximum);
                        
                        
                }
        }
    }



program using the rand () function

I want to make a simple program in which the rand() function generates a random number out of 1,2,3 and the user is asked to predict the number. if the user predicts the number correctly then he wins otherwise he looses. Here's the program-

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

int main()
{
    int game;
    int i;
    int x;

    printf("enter the expected value(0,1,2)");
    scanf("%d\n",&x);
    for(i=0;i<1;i++){
        game=(rand()%2) + 1

        if(x==game){
            printf("you win!");
        }

        else{
            printf("you loose!");
        }
    } return 0;

}




Is numpy.random.RandomState() automatically called whenever rand() is called?

Languages like C++ needs the programmer to set seed otherwise the output of random number generation is always the same. However, libraries like numpy does not need to initialize seen manually.

For example, code like:

from numpy.random import rand
rand()

gives a different result every time.

Does that mean numpy.random.RandomState(seed=None) is called every time you call rand?




mardi 28 avril 2015

Generating 9 random numbers without repeating

I have an assignment that wants ne to make a magic square program where you generate random numbers 1-9 and assign them to a 2D array, I cannot figure out how to generate random numbers that don't repeat and I was wondering if someone can help me it's c++.

in advance thank you!




Generating 'random' string from a different string in python?

I'm trying to generate a random string using the elements of a different string, with the same length.

Ex) String: AGAACGC

I want a random string using only elements from the string above

Right now I have:

import random
seq = 'AGAACGC'
length = len(seq)    

for blah in range(len(seq)): #Apologies for the lame variable names
    x = random.randint(0,length - 1)
    print seq[x]

And of course this will give me something like:

A

A

G

A

C

A

A

How would I alter the program so that it prints out my random string on one line?

I'm hoping for a relatively simple answer, as I'm still a beginner in python, so I don't want to get too fancy. But any help at all would be appreciated.

And is there a way to repeat the randomization 'n' number of times?

Say instead of 1 random string, I wanted 4 random strings on different lines. Is there an easy way doing this? (My newbish mind is telling me to repeat the loop 'n' times...but it needs to be a changeable number of randomized strings)

Sorry for asking. I'd really appreciate some help. I'm stuck on a bigger problem because I don't know how to do these steps.




Consolidating Action Listeners of Buttons In Random Number Game

I'm relatively new to Java, and I had a question about a game that I wrote. It's a random number game where you try to guess a number from 1-10 in the least number of guesses.

I got the program to work, but the code seems very inefficient. As it currently is, I am creating a JButton for each number, then creating a separate Action Listener for each button, like this (A lot has been omitted just for simplicity's sake and because it was irrelevant to the question):

Note: int number = The random number that is chosen by the program, and int guessCounter = The number that keeps track of the number of guesses

 public class random extends JFrame{

 //Creating the Buttons

 JButton one = new JButton("1");
 JButton two = new JButton("2");
 JButton three = new JButton("3");

    public static void main(String[] args){

    //Creating Action Listeners

        OneClass uno = new OneClass();
        one.addActionListener(uno);

        TwoClass dos = new TwoClass();
        two.addActionListener(dos);

        ThreeClass tres = new ThreeClass();
        three.addActionListener(tres);

        //Action Listener For Button 1

        private class OneClass implements ActionListener{
            public void actionPerformed(ActionEvent event){
                if(number == 1){
                    guessCounter++;
                    JOptionPane.showMessageDialog(null,"Correct! You guessed the correct number in " + guessCounter + " guesses","Correct!", JOptionPane.PLAIN_MESSAGE);
                }else if(number > 1){
                    guessCounter++;
                    JOptionPane.showMessageDialog(null,"Incorrect. Guess Higher. You have guessed " + guessCounter + " time(s).","Incorrect", JOptionPane.PLAIN_MESSAGE);
                    one.setEnabled(false);
                }else if(number < 1){

                }
            }

        }

        //Action Listener For Button 2

        private class TwoClass implements ActionListener{
            public void actionPerformed(ActionEvent event){
                if(number == 2){
                    guessCounter++;
                    JOptionPane.showMessageDialog(null,"Correct! You guessed the correct number in " + guessCounter + " guesses","Correct!", JOptionPane.PLAIN_MESSAGE);
                }else if(number > 2){
                    guessCounter++;
                    JOptionPane.showMessageDialog(null,"Incorrect. Guess Higher. You have guessed " + guessCounter + " time(s).","Incorrect", JOptionPane.PLAIN_MESSAGE);
                    two.setEnabled(false);
                }else if(number < 2){
                    guessCounter++;
                    JOptionPane.showMessageDialog(null, "Incorrect. Guess Lower. You have guessed " + guessCounter + " time(s)","Incorrect", JOptionPane.PLAIN_MESSAGE);
                    two.setEnabled(false);
                }
            }
        }

        //Action Listener For Button 3

        private class ThreeClass implements ActionListener{
            public void actionPerformed(ActionEvent event){
                if(number == 3){
                    guessCounter++;
                    JOptionPane.showMessageDialog(null,"Correct! You guessed the correct number in " + guessCounter + " guesses","Correct!", JOptionPane.PLAIN_MESSAGE);
                }else if(number > 3){
                    guessCounter++;
                    JOptionPane.showMessageDialog(null,"Incorrect. Guess Higher. You have guessed " + guessCounter + " time(s).","Incorrect", JOptionPane.PLAIN_MESSAGE);
                    three.setEnabled(false);
                }else if(number < 3){
                    guessCounter++;
                    JOptionPane.showMessageDialog(null, "Incorrect. Guess Lower. You have guessed " + guessCounter + " time(s)","Incorrect", JOptionPane.PLAIN_MESSAGE);
                    three.setEnabled(false);
                }
            }

One can see where the inefficiency can be so prevalent when each Action Listener is this long. My question is, is it possible to condense this (Even if the Action Listener for each button requires that the random number be compared to a different number)? This is already very long, and will become extremely long as soon as I start adding more difficult levels with more numbers to chose from.




Random Duration in SKAction in Swift

How can I random those two objects’ duration?

  func start() {

    let ajusdtedDuration = NSTimeInterval (frame.size.width / kDefaultXToMovePerSecond)

    let moveLeft = SKAction.moveByX(-frame.size.width/2, y: 0, duration: ajusdtedDuration/2)
    let resetPosition = SKAction.moveToX(0, duration: 0)
    let moveSequence = SKAction.sequence([moveLeft, resetPosition])

    runAction(SKAction.repeatActionForever(moveSequence))
}

func stop() {
removeAllActions()


}

And this is another one. Plus, how can I make both of their duration synced?

  func startMoving() {
let moveLeft = SKAction.moveByX(-kDefaultXToMovePerSecond, y: 0, duration: 1)
    runAction(SKAction.repeatActionForever(moveLeft))
}




how to initialize a random vecor in simulations?

I made a random vector say A=random.sample([4,3,5,2],1) and am using this A as initial condition for simulation, so i did that: A=random.sample([4,3,5,2],1) A1=A for simulation A=A1 for time refine A end(time) end(simulation) but the first A for each simulation that should be the same and equal to A1 is changing. can anyone help me to figure it out. thanks




I would like to be able to generate a fill in the blank from a word missing 2 letters randomly

$word = "superman";

I would like to be able to randomly choose 2 letters from what ever word is in $word and build a fill in the blank box for me to be able to answer

example some how random picks the p and the a su_erm_n comes up so I would fill in the first box with p and the second one with a I guess with a form

$wordfinished = "su" . $fillinblank1 . "erm" . $fillinblank2 . "n";

if ($wordfinshed == $word) {
echo "congrats";
}
else{
echo "try again";
}

I am just learning php I have some things that I have done that are very complicated but was having a hard time with the random stuff any help would help me learn this




Make two random teams form dataset and get overall team score in R

Lets say I have a soccer team of 10 players (players) from which I should make two subteams of 5 players each and then compute the overall score for each team.

players <- read.table(text=
"paul    3
ringo   3
george  5
john    5
mick    1
ron     2
charlie 3
ozzy    5
keith   3
brian   3", as.is=TRUE)

I've already extracted a random set of 5 players:

t1 <- sample(players$V1, size = 5)

But one it comes to create the second team (excluding the players in the first one) and calculating the overall score for both teams I'm completed blocked.




MIPS lb command not loading anything?

I am trying to read a random word from a text file but sometimes depending on the value of $s5 an infinite loop happens and the value of $t2 never changes.

Sorry for the block of text. I've never used stack overflow before and I don't know how much of my code I should provide. Thank you very much.

.data

randomword: #word to be found inside the file
        .asciiz "\0\0\0\0\0\0\0"
fin:    
        .asciiz "dictionarysmall.txt"      # filename for input

fileContents:
        .word 0
sizeOfFile:
        .word 0

str2:       .asciiz "loop 2"
str3:       .asciiz "loop 3"
str4:       .asciiz "loop 4"
fileBuffer: 
        .asciiz
.text
###############################################################
# Open (for reading)
li   $v0, 13       # system call for open file
la   $a0, fin     # input file name
li   $a1, 0        # Open for writing (flags are 0: read, 1: write)
li   $a2, 0        # mode is ignored
syscall            # open a file (file descriptor returned in $v0)
move $s6, $v0      # save the file descriptor 

###############################################################
li $v0, 42
li $a0, 9
li $a1, 250 #if using dictionary.txt value is 171900
syscall

move $t1, $a0   #generate a random number within 0 to 171920
move $s5, $t1   #$s5 contains the random number

# Read file just opened
li   $v0, 14       # read from file
move $a0, $s6      # file descriptor 
la   $a1, fileBuffer   # address of buffer from which to write
la   $a2, ($s5)       #buffer length
syscall            # read from file
###############################################################
# Close the file 
li   $v0, 16       # system call for close file
move $a0, $s6      # file descriptor to close
syscall            # close file
###############################################################

#****HERE IS WHERE THE ERRORS BEGIN OCCURRING.
li $s5, 60 #changing this number decides whether the program works or fails


wordfindloop1:  #run through bits until random number is reached
la   $t7, fileBuffer
la   $t6, randomword
li   $t1, 13   #newline
li   $t2, 0

add  $t7, $t7, $s5
j wordfindloop2

wordfindloop2:  #go through bits until \n is found and then store word
#li $v0, 4
#la $a0, str2
#syscall

#li $v0, 11
#la $a0, ($t7) #prints out contents of $t7 which are very strange
#syscall

beq  $t2, $t1, wordfindloop3 #0 is the newline char which would mark the start of a word
lb   $t2, ($t7) #$t2 contains the next char
addi $t7, $t7, 1
j wordfindloop2

wordfindloop3:  #bad code probably but add 2 to the address

#li $v0, 4
#la $a0, str3
#syscall

addi  $t7, $t7, 1

wordfindloop4:

#li $v0, 4
#la $a0, str4
#syscall

lb   $t2, ($t7)
beq  $t2, 13, finish
sb   $t2, ($t6)
addi $t7, $t7, 1
add  $t6, $t6, 1
j wordfindloop4

finish:
li $v0, 4
la $a0, randomword
syscall




Returning a List of Integers in Swift

I am an amateur Python programmer trying my hand at Apple's new Swift programming language. I recently decided to rewrite a Python script I have in Swift as a first step towards building this out into an iOS app. I ran into a bit of a challenge that so far I have been unable to resolve. In Python I have a function that returns a list of random integers:

# Roll the Attackers dice in Python
def attacker_rolls(attack_dice):
    attacker_roll_result = []
    if attack_dice >= 3:
        attacker_roll_result += [randint(1,6), randint(1,6), randint(1,6)]
    elif attack_dice == 2:
        attacker_roll_result += [randint(1,6), randint(1,6)]
    elif attack_dice == 1:
        attacker_roll_result = [randint(1,6)]
    attacker_roll_result.sort(reverse=True)
    print "The attacker rolled: " + str(attacker_roll_result)
    return attacker_roll_result

What I have in Swift thus far:

// Roll the attackers dice in Swift
func attackerRolls(attackDice: Int) -> Array {
    if attackDice >= 3 {
        var attackerRollResult = [Int(arc4random_uniform(6)+1), Int(arc4random_uniform(6)+1), Int(arc4random_uniform(6)+1)]
        return attackerRollResult
    }
}

*That Swift function above is unfininshed but you can see where I am going with it.

So when trying to rewrite this function I get one of two erorrs. Either, as it stands now, I get:

Reference to generic type 'Array' requires arguments in <...>

Or, if I use the Int return type instead:

'[Int]' is not convertible to 'Int'

I know that the random function I am utilizing in Swift is has some complications that Pythons randint doesn't but so far I have been unable to track down the specific issue. Is my method of a random integer in error or am I returning the list incorrectly? Anyone with some Swift experience have an idea? Answers in Obj-C may also be helpful. Thanks!




Randomly generating equation and answer

I am trying to randomly generate an equation that also has a 50% chance of being wrong and displaying that incorrect answer. The incorrect answer should have an error of either -2, -1, +1, or +2.

Sometimes my code prints division equations like this(I can't post images): 2 / 10 = 13 1 / 5 = 43 etc.

I can't figure out why the equation is displaying a mix of numbers that are not checked together?

(It starts with a call to generateNumbers() in my onCreateView method

public void generateNumbers() {
    //randomly generate 2 numbers and an operator
    number1 = (int) (Math.random() * 10) + 1;
    number2 = (int) (Math.random() * 10) + 1;
    operator = (int) (Math.random() * 4) + 1;
    //50% chance whether the displayed answer will be right or wrong
    rightOrWrong = (int) (Math.random() * 2) + 1;
    //calculate the offset of displayed answer for a wrong equation (Error)
    error = (int) (Math.random() * 4) + 1;
    generateEquation();
}

public void generateEquation() {
    StringBuilder equation = new StringBuilder();
    //append the first number
    equation.append(number1);
    //generate/append the operator and calculate the real answer
    if (operator == 1) {
        equation.append(" + ");
        actualAnswer = number1 + number2;
    } else if (operator == 2) {
        equation.append(" - ");
        actualAnswer = number1 - number2;
    } else if (operator == 3) {
        equation.append(" x ");
        actualAnswer = number1 * number2;
    } else if (operator == 4) {
        if ((number1%number2==0) && (number1>number2)) {
            actualAnswer = number1 / number2;
        } else {
            generateNumbers();
        }
        equation.append(" / ");

    }
    //append the second number and the equals sign
    equation.append(number2 + " = ");

    //we will display the correct answer for the equation
    if (rightOrWrong == 1) {
        displayedAnswer = actualAnswer;
        equation.append(displayedAnswer);
    }
    //we will display an incorrect answer for the equation
    //need to calculate error (-2, -1, +1, +2)
    else {
        if (error == 1) {
            displayedAnswer = actualAnswer - 1;
        } else if (error == 2) {
            displayedAnswer = actualAnswer - 2;
        }else if (error == 3) {
            displayedAnswer = actualAnswer + 1;
        }else {
            displayedAnswer = actualAnswer + 2;
        }
        //append the displayed answer with error
        equation.append(displayedAnswer);

    }
    questionNumber.setText("You have answered " + count + " out of 20 questions");
    finalEquation.setText(equation.toString());
}




How do I display 3 randomly selected words from a list in set order in Javascript?

The idea is to generate a random reverse acronym for the acronym 'REG' using a list of words that begin with 'R', 'E' and 'G'. Every time you visit the page that the code is on it should pick a word from each list and place them in the REG order (example: Rodent Echo Ghost, Ronald Evening Garden, etc.)

Optional would be the ability to choose the font family, size and colour.

I searched around for this kind of code but to no avail. Probably also good to mention that I don't have much experience with Javascript at all, so any help is appreciated.




Weightened random number (without predefined values!)

currently I'm needing a function which gives a weightened, random number. It should chose a random number between two doubles/integers (for example 4 and 8) while the value in the middle (6) will occur on average, about twice as often than the limiter values 4 and 8. If this were only about integers, I could predefine the values with variables and custom probabilities, but I need the function to give a double with at least 2 digits (meaning thousands of different numbers)!

The environment I use, is the "Game Maker" which provides all sorts of basic random-generators, but not weightened ones.

Could anyone possibly lead my n the right direction how to achieve this?

Thanks in advance!




Why "rand()" function prints always the same random values? [duplicate]

This question already has an answer here:

I got this code:

#include <stdio.h>
#include <conio.h>
int rand();

int main()
{
        int a = 1;

        while (a<=15)
        {
                printf("%d\n", rand());
                a++;
        }

        return 0;

}

Funny thing is that it always print the same list of numbers. I thought it would print different numbers each time - and I know there's must be some argument that makes that - but what surprised me is that the program knows exactly how to print the same values always.

So how is that possible, I mean, I'm just curious, seems like a sequence of number is already predefined into the executable.




lundi 27 avril 2015

Java Configuring random number generators in multi-threaded environment

I have an application which uses pseudo-random numbers. While I'm testing the application, I want reproducibility, which I arrange by using a seed for the random number generator. Currently, the RNG is declared inside the class that uses it as a static variable: private static Random rng = new Random(seed). I have a few questions.

  1. Given that I want to seed the RNG for reproducibility, does it make sense to declare the variable static?
  2. I may need to add more different classes which need random numbers. Should I move the RNG to a separate class so I can still use one seed for the whole application? If so, should I use a static Random or a singleton object?
  3. What happens if I decide to use random numbers in multiple threads? It seems that if I use a strategy like 2., I might still lose predictability, as I can't say for sure the order in which the threads are going to access the RNG. The RNG will still generate the same, predictable sequence of random numbers, but from one run of the program to another, the thread which grabs the first (or nth) random number in the sequence may differ.
  4. What this indicates to me is that each thread needs its own RNG in order for results to be reproducible across all runs. Does that mean that each thread needs its own seed? If so, would that guarantee reproducibility, or is there something else I need to do to eliminate the randomness that may be introduced by having multiple threads?
  5. Is there a way to generate seeds from a single number which minimizes the correlation between the different RNGs?

In other words, if thread 0 has Random thread0RNG = new Random(seed) and thread 1 has Random thread1RNG = new Random(seed), I would only need one seed, but the random numbers in each thread would be highly correlated. I could have two seeds, but then I couldn't associate a run of the program with a single number, passed on the command line, say. Would it be possible and appropriate to say seed0 = someFunction(seed,0) and seed1 = someFunction(seed,1)?




angular ng-repeat, randomize orderBy

I am trying have my angular ng-repeat randomize the items when they appear. The random function I am currently using is below, however when i use this function I get a infdig, causing all sorts of problems. I dont want to do the randomize in the controller because both of these ng-repeats come from the same entry where there is a url and a name but the entry id is in both instances so it would be easier if I dont have to create separate arrays. So does anyone know of a random filter that can be used for this, that wont give me the infdig problems?

 $scope.random = function(){
    return 0.5 - Math.random();
  };  


<div ng-repeat="actor in actors | orderBy:random">
          <div class="col-md-2">
            <div class='imageDropTo'>
              <img class='imageDropTo' src={{actor.url}} data-id=   {{actor.id}}>
            </div>
          </div>
        </div>


 <div ng-repeat="actor in actors | orderBy:random">
            <div class='col-md-2'>
              <p id='{{actor.id}}' class='namesToDrag'> {{actor.name}} </p>
          </div>
        </div>




how to make random float in swift with math operations

Get an error when trying to use multiplication

var red1 : Float = ((random()%9)*30)/255;

Error says 'int' is not convertible to 'float'

I want to use this to make a float I can use to make a UIColor




Array of random integers with fixed average in java

I need to create an array of random integers which a sum of them is 1000000 and an average of these numbers is 3. The numbers in the array could be duplicated and the length of the array could be any number.

I am able to find the array of random integers which the sum of them is 1000000.

    ArrayList<Integer> array = new ArrayList<Integer>();

    int a = 1000000;
    Random rn = new Random();
    while (a >= 1)
    {
        int answer = rn.nextInt(a) + 1;
        array.add(answer);
        a -= answer;
    }

However, I don't know how to find the random numbers with average of 3.




How can I call upon a randomly generated number to determine a symbol spawn?

so what I'm trying to do is generate a random number from 1 to 3 when a symbol on the stage is clicked. Once this number is generated, i want this number to determine which of these next 3 symbols will spawn. How can I call upon this function's random number? Does the random number the generator spits out need to be declared as an integer?

//Random hitmarker generator
function randomRange(minNum:1, maxNum:3):Number 
    return (Math.floor(Math.random() * (maxNum - minNum + 1)) + minNum);
}
if (Number = 1){
    boom.x = 340;
    boom.y = 600;
    boom.visible = true;
}
if (Number = 2){
    boom.x = 370;
    boom.y = 500;
    boom.visible = true;
}
if (Number = 3){
    boom.x = 330;
    boom.y = 340;
    boom.visible = true;
}




Does anyone know why this code just won't work

To me it makes sense, then again I'm nowhere near an expert. So I'm working on a project for my first programming course and I've been stuck on this question all day, I have probebly done 5 hours of cumulative research trying to figure out how this is even possible.

Basically I need to shuffle these 'cards' for a memory game and I can't figure out why it's not working. The program runs fine but none of the images change. i put the cout in there just to make sure that the value was changing each time, I just don't know why it won't swap with those values. I tried the shuffle and random_shuffle thing but I most likely did not do it right, if someone could show me what it has to look like with my code I would be ever so grateful. I'm just so puzzled as to why it won't work. If someone could provide a working example explaining as to where i went wrong that would be amazing. Here's the full code, it's a bit long.

void shuffle(int board[][NCOLS]) {
    random_device rd;
    mt19937 gen(rd());
    uniform_int_distribution<> dis(1, 6);
    for (int i = 0; i < 20; i++) {
        int randomX = dis(gen);
        swap(board[randomX][randomX], board[randomX][randomX]);
        cout << "num = " << randomX << endl;
    }

}

I'm not quite sure how to paste code on here and the program itself is actually pretty big in full length so I've opted to just upload the full code here if you need some context: http://ift.tt/1DQNMKB

Also, I'm right in calling the function by using shuffle(board); correct? it's just wierd because there's already a built in function called shuffle correct?

Thanks for any help you can provide, I highly appreciate it.




List forward or backward

I was trying to solve some exercises I get at school and I can't get a solution.

So the main quest is to "move" in a list. Random list was generated, negatives and positives numbers, then programm was intended to choose a random value from that list and move forward if that num were positive or backward if it were negative. For example: Choosen number was "-5" and had as index "6", programm need to move 5 times backward and have as index "1". Cycle will reapeat and saving indexes into a list. That cycle, as the main programm, will stop if programm has found already "choosen" index.

P.S. If that randomly choosen were -5 and index were 3 it needs to go to the end of list and start moving there.

There starts mine "code":

#coding: UTF-8
import random
List = []                                               #List with random numbers                                                                     
NewIndex = []                                           #list with indexes that programm will save while doing cycle.                                                          
ListLong = int(raw_input("listlong "))                  #len list    
counter = ListLong
Tester1 = True
NewVal = 0                                                                  
while counter != 0:                                     #this and next lines adds random nums without 0
    valoradd = random.randrange(-10,10)
    if valoradd != 0:
        List.append(valoradd)
        counter -= 1
    elif valoradd == 0:
        valoradd = random.randrange(-10,10)
RandomVal = random.choice(List)                         #choices random num                               
ValueIndex = List.index(RandomVal)                      #Index of that num                        
AnotherIndex = ValueIndex                               
while Tester1 == True:                                  #here begins the thing i cant solve.
    if RandomVal < 0:                                   #that condition sees if num is "<0"                      
        while AnotherIndex != 0:                        
            AnotherIndex -= 1                                                   
            NewVal += 1                                                       
        NewVal = RandomVal - NewVal                                             
        Move = ListLong - NewVal
        if Move not in NewIndex:                        #if number not in list of NewIndexes it adds a new one there.                
            NewIndex.append(Move)                                      
        else:                                           #if number is already in list. Programm stops.                    
            Tester1 = False                                                     
    elif RandomVal > 0:                                 #these condition sees if num is ">0"                 
        Move = ValueIndex + RandomVal
        if Move not in NewIndex:                        #if number not in list of NewIndexes it adds a new one there.
            NewIndex.append(Move)
        else:                                           #if number is already in list. Programm stops.   
            Tester1 = False
print "Found repeated value"




Reset a random number generator with same seed (C#)

Here's my situation:

I'm making a game in C# which randomizes the positions of all the objects on the screen everytime you begin a new level. To do this I've just declared a

random r = new Random();

I then decided that even though I want to randomize whenever a new level is begun, I want each level to be the same every time.. In other words, the positions of the things on level 1 will always be the same, every time you start the game, and so on for all the other levels.

To do this, I added a seed to the generator:

random r = new Random(mySeed);

This works perfectly - when I exit the game and start it up again, the random positions in level 1 will be the same every time.

However, here's the problem: I understand that when you give the Random object a seed, it uses that seed to generate its list of numbers, which is obviously why all my r.Next()s are the same no matter how many times I re-open the program. BUT, it seems I have to COMPLETELY restart the entire program in order to reset it and get back to the first item in the list again...

In other words, If the player dies during level 1, you go back to the main menu.. But then when it calls r.Next(), it's of course not going to give me the correct level 1 positions.

I tried to solve this by simply re-constructing the object when you die, for example:

//other death code in here
r = new Random(mySeed);
//back to main menu

But that doesn't seem to make a difference - it'll still continue on with the sequence from where it was before..

So does anyone have a clue how I can point back to the beginning of the random list WITHOUT having to restart the whole program?

Thanks!




How to Make an Image Randomly Move Around Page?

This is in response to this question.

How can I add it to my web page?




display three random articles in a partial view mvc

I have a blog in which I display a partialview in that partial I am trying to display three random similar articles. However I am abit stuck with the syntax:

@{for (int i = 0; i < 3; ++i)
    {
     foreach (var item in Model)
     {
    <p class="text-left">Similar Article: <a href="@Url.Action("Details", "Post", new { urlslug = item.UrlSlug })">@Html.DisplayFor(modelItem => item.Title)</a></p>
      }
    }

}




Random access to a huge image?

I'm looking for a way to store a huge image in a way that allows random access to small regions without the need to load the whole image into memory. The focus is on speed and on a low memory footprint.

Let's say the image is 50k*50k 32-bit-pixels, amounting to ~9 GB (Currently it is stored as a single tiff file). One thing I found looks quite promising: HDF5 allows me to store and randomly access integer arrays of arbitrary size and dimension. I could put my image's pixels into such a database.

What (other) (simpler?) methods for efficient random pixel access are out there?

I would really like to store the image as a whole and avoid creating tiles for several reasons: The requested image region dimensions are not constant/predictable. I want to only load the pixels into memory that I really need. I would like to avoid the processing effort involved in tiling the image.

Thanks for any kind of input!!




distribution as global variable

In my project, I am trying to use a uniform distribution as a global variable.

In one file (global.h), I write:

#include <random>
extern std::uniform_real_distribution<> sample;

Then, in another file, I want to initialize it (set the parameters) with:

#include "global.h"
std::uniform_real_distribution<>::param_type Params(-0.3,0.3);
sample.param(Params);

But I get the following error message:
'sample' does not name a type

Any suggestions?




storing 13 random values without duplcates from a string array in java

i want distribute 13 values to a string without duplication. i have used random function and shuffle as well but it is giving me 1 value from this String array

String[] orgCards = {
                "ca", "ck", "cq", "cj", "c10", "c9", "c8", "c7", "c6", "c5", "c4", "c3", "c2",
                "sa", "sk", "sq", "sj", "s10", "s9", "s8", "s7", "s6", "s5", "s4", "s3", "s2",
                "da", "dk", "dq", "dj", "d10", "d9", "d8", "d7", "d6", "d5", "d4", "d3", "d2",
                "ha", "hk", "hq", "hj", "h10", "h9", "h8", "h7", "h6", "h5", "h4", "h3", "h2"


        };


TextView text = (TextView) findViewById(R.id.textField);
        String listString = "";
        for (String i : orgCards) {
            list.add(i);
        }
        for (int j = 1; j <= 52; j++) {
            Collections.shuffle(list);

            for (int i = 0; i < list.size(); i++) {
                orgCards[i] = list.get(i);
            }

            for (String ss : orgCards) {

                listString = ss;
            }

        }
        text.setText("my string"+" " + listString);
    }

output is :

ca




how do i compare two script files, where one file is input and another is a reference file?

i have two scripts, one is input file and another is reference file and i want to compare whether the input file is valid or not using the reference file.

I want to compare the content of the reference file with the input file and check if input is valid or no, but the input file may contain strings which are valid but if i compare whether exact string is present in the input file or no, OR if the reference string is a part of the input file, then the output will give error.

Ex:

reference file may contain the following commands:

-rpm -i *.rpm >> /tmp/logfile.log

-rpm -i *.rpm

and the input file may contain :

-rpm -rpm -ivh *.rpm -rpm -i >> /logfile.log

i am using python 2.4.

So, how can i compare them and tell if input string is valid or no?




c# how to generate random number depends on propabilities

I have a situation in which i must generate a random number, this number must be either zero or one

So, the code is something like this:

randomNumber = new Random().Next(0,1)

However, the business requirements state that there is just 10% profitability that the generated number is zero and 90% profitability that the generated number is 1

However can I include that profitability in generating the random number please?

What I thought of is:

  1. Generate array of integer that includes 10 zeros and 90 ones.
  2. Generate a random index between 1 and 100
  3. Take the value that corresponds to that index

but I don't know if this way is the correct way, plus, i think that c# should have something ready for it




dimanche 26 avril 2015

Trouble figuring out how to generate set values only twice for a set amount of times

I will start off with this is my first post on StackOverflow, so I'm sorry if i leave anything important out, i am also very new at coding and still learning.

What i am trying to is make a form of a memory game, a user will input a number, it will generate that number of tiles (even only) and give them set values. I am stuck on the giving them 2 set values each and only two for x number of tiles.

An example would be if the user choose the lowest number of tiles, 4, there would be two with A and two with B. The code i have right now is a mess but kind of a draft and it is setting text on a button, not a value. This code is also only for the 4 tiles example.

On a side note, I'm sure there is a simpler way to declare all 20 of my buttons, maybe someone could point me in the right direction.

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

    Button btn1 = (Button)findViewById(R.id.btn1);
    Button btn2 = (Button)findViewById(R.id.btn2);
    Button btn3 = (Button)findViewById(R.id.btn3);
    Button btn4 = (Button)findViewById(R.id.btn4);
    Button btn5 = (Button)findViewById(R.id.btn5);
    Button btn6 = (Button)findViewById(R.id.btn6);
    Button btn7 = (Button)findViewById(R.id.btn7);
    Button btn8 = (Button)findViewById(R.id.btn8);
    Button btn9 = (Button)findViewById(R.id.btn9);
    Button btn10 = (Button)findViewById(R.id.btn10);
    Button btn11 = (Button)findViewById(R.id.btn11);
    Button btn12 = (Button)findViewById(R.id.btn12);
    Button btn13 = (Button)findViewById(R.id.btn13);
    Button btn14 = (Button)findViewById(R.id.btn14);
    Button btn15 = (Button)findViewById(R.id.btn15);
    Button btn16 = (Button)findViewById(R.id.btn16);
    Button btn17 = (Button)findViewById(R.id.btn17);
    Button btn18 = (Button)findViewById(R.id.btn18);
    Button btn19 = (Button)findViewById(R.id.btn19);
    Button btn20 = (Button)findViewById(R.id.btn20);



int tiles = 0;        
super.onCreate(savedInstanceState);
    TextView tv = (TextView)findViewById(R.id.calling_activity_info_text_view);

    String tileNum = getIntent().getExtras().getString("tilesNumber");

    String[] tileSet = {"A","B","C","D","E","F","G","H","I","J"};
    Button[] btnA = {btn1, btn2, btn3, btn4, btn5, btn6, btn7, btn8, btn9, btn10, btn11, btn12, btn13
            , btn14, btn15, btn16, btn17, btn18, btn19, btn20};

    if(tileNum.equals("4")) {
        tiles = Integer.parseInt(tileNum);
        tv.setText("" + tiles);
        for(int i = 0; i <= 3; i++){
            btnA[i].setVisibility(View.VISIBLE);
            btnA[i].setText(tileSet[i]);
        }




Replace any 3 letters from the string with random letters

I want to replace any 3 random letters from the string with random letters from my letters variable

var str = "HELLO";
var letters = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
var arr = str.split('');
for (var i = 0; i < 3; i++) {
    var pos = Math.round(Math.random() * arr.length - 1);
    arr.splice(Math.floor(Math.random() * arr.length), 1);
    str = arr.join('');
}
alert(str);

I am able to take 3 random letters out right now but can't figure out how to get 3 random letters from letters and put them in a random position.

Here is the demo of what I have right now.

http://ift.tt/1HM36zk

Any help would be appreciated!




Python Random Selection

I have a code which generates either 0 or 9 randomly. This code is run 289 times...

  import random
    track = 0
        if track < 35:
            val = random.choice([0, 9])
            if val == 9:
                track += 1
            else:
                val = 0

According to this code, if 9 is generated 35 times, then 0 is generated. So there is a heavy bias at the start and in the end 0 is mostly output.

Is there a way to reduce this bias so that the 9's are spread out quite evenly in 289 times.

Thanks for any help in advance




How can I randomize an array?

Here's the part of the program I'm having problems with:

// precondition: board is initialized
// postcondition: board is shuffled by randomly swapping 20 values
void shuffle(int board[][NCOLS]) {
    int num = rand();
    num = num %6 + 1;
    for (int i = 0; i < 20; i++) {


    }
}

here's a link to the full program: http://ift.tt/1PIphHY

Pretty sure I have it wrong already, I think i may need the rand function but I'm not sure how the for loop would work. Basically there are 6 pictures and they're in 4 columns, it's a memory game and as of the moment they stay in the same place. I need to make it so that they are random and flipped on the side where you can't see them but I can't figure it out. I have no idea how to randomize columns especially when they're under the name of simply board and NCOLS. Please help me, I appreciate any input




Generate 0 and 1, pseudorandom, 16 char long string

I need to generate 16 characters long string (from SHA1 hash), which contains only 0 and 1, with probability 50% (statistically in most cases same amount of 1 in string as amount of 0's).

So i wrote benchmark, and i tried converting each $hash character to binary. Results are bad, i mean, if im adding leading zeros to binary converted hash, correct probability is far from correct. When im not adding leading zeros to binary conversion, probability is close to correct:

Percentage all 0 or all 1: 0.0012%
Percentage all 0 or all 1 except 1 character : 0.0146%
Percentage all 0 or all 1 except 2 characters: 0.0812%

But its still far from true correct probability that code below should produce which is:

Percentage all 0 or all 1: 0.003%
Percentage all 0 or all 1 except 1 character : 0.048%
Percentage all 0 or all 1 except 2 characters: 0.376%

How do i know its correct probability? I changed binary conversion to simple mt_rand(0,1) sixteen times (and other confirmation tests).

It must be generated from sha1 hash, to be deterministic by that hash. Anyone have idea, how to fix my code to produce correct probability results? I tried already for 10 hours straight.

    function binary($text){
            $list = '';
            $temp = '';
            $i = 0;
            while ($i < 16){
                    if (is_numeric($text[$i])){
                            $list .= decbin( $text[$i] );//sprintf( "%08d", decbin( $text[$i] ));
                    } else {
                            $temp = ord($text[$i]);
                            $list .= decbin( $temp );
    //                      $list .= sprintf( "%08d", decbin( $temp ));// substr("00000000",0,8 - strlen($temp)) . $temp;
                    }
            $i++;
            }
            return $list;
    }

    $y = 0;
    $trafien = 0;
    $trafien1= 0;
    $trafien2= 0;
    $max = 500000;
    while ($y < $max){

    $time = uniqid()  . mt_rand(1,999999999999);
    $seed = 'eqm2890rmn9ou8nr9q2';
    $hash = sha1($time . $seed);

    $last4 = substr($hash, 0, 40);
    $binary =  binary($last4);
    $final = substr($binary, 0,16);

    $ile = substr_count($final, '0');
    $ile2= substr_count($final, '1');
    if ($ile == 16 || $ile2 == 16){
        echo "\n".$last4 ." " . 'binary: '. $binary .' final: '. $final;
        $trafien += 1;
    }

    if ($ile == 15 || $ile2 == 15){
        $trafien1 += 1;
    }

    if ($ile == 14 || $ile2 == 14){
        $trafien2 += 1;
    }

$y++;
}

$procent = ($trafien * 100)  / $max;
$procent1= ($trafien1 * 100) / $max;
$procent2= ($trafien2 * 100) / $max;
echo "\nPercentage all 0 or all 1: ". $procent . "%";
echo "\nPercentage all 0 or all 1 except 1 character : ". $procent1 . "%";
echo "\nPercentage all 0 or all 1 except 2 characters: ". $procent2 . "%";




Using Solver add-in with on cells that use the rand() function

I have a monte carlo simulation model and I need to set one of my parameters (service level) to be at least 95%. The problem is that, from what I know, when Solver runs, it tries different solutions, but because of RAND() function, the target cells keeps on changing all the time. Is there any way I could deal with this? Disable RAND() from changing temporarly? I tried to switch calculations to manual but that doesnt work because then the target cell does not update at all. I appreciate any help, thanks!




print random result in php 2 dimensional array

for a simple array I can print a random item with this code:

$key = array_rand($arr);
$value = $arr[$key];

But I need do it with 2 dimensional array and one condition.

I have an array like this

$arr = array ( 'news' => 'text1',
               'news' => 'text2',
               'fun'  => 'text3',
               'news' => 'text4',
               'echo' => 'text5',
               'fun' => 'text6');

I want somthing like this algorithm in php

if($type == 'news')
   print random($arr($type));

So the results are:

text1 or text2 or text4

or another example:

 if($type == 'fun')
       print random($arr($type));

results: text3 or text6

but how can I do it?




How to generate random numbers to produce a non-standard distributionin PHP

I've searched through a number of similar questions, but unfortunately I haven't been able to find an answer to this problem. I hope someone can point me in the right direction.

I need to come up with a PHP function which will produce a random number within a set range and mean. The range, in my case, will always be 1 to 100. The mean could be anything within the range.

For example...

r = f(x)

where...

r = the resulting random number

x = the mean

...running this function in a loop should produce random values where the average of the resulting values should be very close to x. (The more times we loop the closer we get to x)

Unfortunately, I'm not well versed in statistics. Perhaps someone can help me word this problem correctly to find a solution?




How do I display a image after a amount of time with swift code?

(Im very new with swift so be kind xD) I'm wondering how to display a random image out of 4 images after a surten amount of time has passed using swift code




How to stop duplicates when picking random number in Java

public void start() throws TwitterException, IOException {

    twitter.setOAuthConsumer(CONSUMER_KEY, CONSUMER_KEY_SECRET);
    AccessToken oathAccessToken = new AccessToken(ACCESS_KEY,
            ACCESS_KEY_SECRET);
    twitter.setOAuthAccessToken(oathAccessToken);
    ColourBlender myColourBlender = new ColourBlender();
    twitter.updateStatus(TwitterActions.getCatchphrase());
}

public static String getCatchphrase() throws FileNotFoundException
{
    ColourBlender myColourBlender = new ColourBlender();
    String newColour = myColourBlender.BlendColour();
    String[] phraseArray = {"Phrase1", "Phrase2", "Phrase3"};
    Random r = new Random();
    String catchphrase = phraseArray[r.nextInt(phraseArray.length)];
    return catchphrase;
}

In this code I want to have many catchphrases in an array, which will be tweeted randomly on twitter, but I don't want them to be repeated. How can I stop r generating duplicates




Drawing random circles within a python turtle circle

I'm trying to randomly place a number of small circles within a larger circle using turtle.

The size of the larger circle depends on wether "small", "medium" or "large" are called, and I need the small circles to stay within the bounds of the radius of each circle.

    def drawCircle(myTurtle, radius):
        circumference = 2 * 3.1415 * radius
        sideLength = circumference / 360
        drawPolygon(myTurtle,sideLength,360)

How do I use random to place circles with smaller radiuses within the initial circle?




How do i make a notification appear at random times throughout the day?

Hi im trying to make a notification appear at random times throughout the day. right now all it does is make the notification appear when i press the a button. I would like the button to start making them appear every hour or so. Here is my MainActivity class.

public class MainActivity extends Activity {
Button button;


@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    button = (Button) findViewById(R.id.button1);
    button.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            NotificationCompat.Builder notification = new NotificationCompat.Builder(MainActivity.this);

            notification.setSmallIcon(R.mipmap.ic_launcher);
            notification.setTicker("Hey!!!");
            notification.setWhen(System.currentTimeMillis());
            notification.setContentTitle("You're Awesome");

            Uri sound = RingtoneManager.getDefaultUri(Notification.DEFAULT_SOUND);

            notification.setContentText("keep being awesome!!!:)");
            notification.setSound(sound);

            Bitmap picture = BitmapFactory.decodeResource(getResources(), R.mipmap.ic_launcher);

            notification.setLargeIcon(picture);

            PendingIntent mypendingintent;
            Intent myintent = new Intent();
            Context mycontext = getApplicationContext();
            myintent.setClass(mycontext, Activity2.class);
            myintent.putExtra("ID", 1);
            mypendingintent = PendingIntent.getActivity(mycontext, 0, myintent, 0);

            notification.setContentIntent(mypendingintent);
            Notification n = notification.build();

            NotificationManager nm = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
            nm.notify(1,n);




        }
    });
}

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

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

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

    return super.onOptionsItemSelected(item);
}

}




samedi 25 avril 2015

Random Hamiltonian Cycle Generation

I am trying to generate a fully random hamiltonian cycle in an undirected graph which I know to be complete with numverts vertices. I have previously initialized the arrays outgoing and incoming. outgoing[i] represents where the outgoing edge from vertex i points, and incoming[i] represents whether a vertex has an incoming edge. The following code attempts to go along each randomly created edge and create another edge, and repeat the process, and finally connect the last vertex back to 0; However, it seems to fail with probability 1/numverts, and still have at least one -2 in outgoing[]. What could be going wrong?

        for(int i = 0; i < numverts; i++) //fill outgoing and incoming with null data
       {
           outgoing[i] = -2;
           incoming[i] = false;
       }
       for(int i = 0; i < numverts; i++)
       {
           int numtotest = (int)(numverts*Math.random());
           if((!incoming[numtotest]) &&(outgoing[numtotest]==-2)) //ensure that the graph had neither incoming nor outgoing edges before generation
           {
               outgoing[currentvert] = numtotest; //create the random edge
               incoming[numtotest] = true;
               currentvert = numtotest; //recur along newly created edge
           }
           else if(i == numverts-1)
           {
               outgoing[currentvert] = 0;
               incoming[0] = true; //reconnect final vertex to 0
           }
           else
           {
               i--; //decrement counter if vertex i already had an edge outgoing or incoming
           }
        }




Python: How to track "correct" answer in randomized multiple choice

I successfully built a function to prompt the user with a question, followed by randomly ordered answer choices. However, since the answer choices are now randomized, how will python recognize the user input (a number: 1, 2, 3, or 4) for the "correct" answer?

import random

def answers():
    answerList = [answer1, answer2, answer3, correct]
    random.shuffle(answerList)
    numberList = ["1: ", "2: ", "3: ", "4: "]
    # A loop that will print numbers in consecutive order and answers in random order, side by side.
    for x,y in zip(numberList,answerList):
        print x,y 

# The question
prompt = "What is the average migrating speed of a laden swallow?"
#Incorrect answers
answer1 = "Gas or electric?"
answer2 = "Metric or English?"
answer3 = "Paper or plastic?"
# Correct answer
correct = "African or European?"

# run the stuff
print prompt
answers()

# Ask user for input; but how will the program know what number to associate with "correct"?
inp = raw_input(">>> ")




random move tic tac toe in c

alright, so I'm really new at coding in C and I have a LOT of copy and paste in my code. (it's my final project, so I really don't have time to optimize and shorten until the end if time permits). So anyway, I'm gonna avoid posting all my code for that reason. I'm only gonna post the relevant part which is what I'm trying to do.

I need the game to pick a random number from 1-9 and then use that number to select a move on the board. I added a printf in this part of the code to make sure a number is being picked, but then when i go to scanf, the game just gives a blinking prompt and does not continue.

Does anyone see what is wrong or do i need to post any other section of code? Any help will be really appreciated!! I have only included the 1 player portion of the game and then when the computer is supposed to move. I removed the win checks and the re printing of the board. Let me know if you guys need to see anything else i just didn't want to have a huge block of code.

if (player == 1)
    {
        for(k=0;k<9;k++) // 9 moves max.
        {
        printf("\n\n"); // print board again.
        printf(" %c | %c | %c\n", board[0][0], board[0][1], board[0][2]);
        printf("---+---+---\n");
        printf(" %c | %c | %c\n", board[1][0], board[1][1], board[1][2]);
        printf("---+---+---\n");
        printf(" %c | %c | %c\n", board[2][0], board[2][1], board[2][2]);

        do
        {
            printf("Player 1, where would you like to move? Enter 1-9\n");
            scanf("%d", &move);

            if (move == 1)
                board[0][0] = '1';
            if (move == 2)
                board[0][1] = '1';
            if (move == 3)
                board[0][2] = '1';
            if (move == 4)
                board[1][0] = '1';
            if (move == 5)
                board[1][1] = '1';
            if (move == 6)
                board[1][2] = '1';
            if (move == 7)
                board[2][0] = '1';
            if (move == 8)
                board[2][1] = '1';
            if (move == 9)
                board[2][2] = '1';

        }while(move>9 && move <1);


        do
        {
            printf("Computer moves...");


            move = rand() % 9 + 1;
            printf("%d", move);
            scanf("%d", &move);


            if (move == 1)
                board[0][0] = '2';
            if (move == 2)
                board[0][1] = '2';
            if (move == 3)
                board[0][2] = '2';
            if (move == 4)
                board[1][0] = '2';
            if (move == 5)
                board[1][1] = '2';
            if (move == 6)
                board[1][2] = '2';
            if (move == 7)
                board[2][0] = '2';
            if (move == 8)
                board[2][1] = '2';
            if (move == 9)
                board[2][2] = '2';


        }while(move>9 && move <1);



    }