mercredi 30 septembre 2015

WordPress - Display Random Number Between 190-250

Does anyone know of a way to display a random number between 190-250 inside a specific page?

For example: Today I had Display Random Number Coffees.




On-the-fly pseudo-random permutation of very large set without repeating and with inverse operation

I have a very large set of values (0-300000^700) and I would like to find an algorithm which would bijectively assign a unique value within the same set.

It is the equivalent of a permutation, but because of obvious memory problems, that would have to be done "on the fly". And the algorithm would need to be inverted at some point.

This problem is similar to this one in the "library of babel": http://ift.tt/1MEcEfR

A LCG is used, with parameters set using the Hull-Dobell Theorem in order to assure no repetitions. The seed is used as the initial value. What I do not get is how the inverse is possible (i.e. getting the seed from the output), as I thought that would require bruteforce.




Microsoft SQL Server 2012: Algorithm to do a summation over a column with random selection of data from other column

I have a table like this:

CREATE TABLE Table1
    ([IdeaNr] int, [SubmitterName] varchar(4), [SubmitterDepartment] varchar(4))
;

INSERT INTO Table1
    ([IdeaNr], [SubmitterName], [SubmitterDepartment])
VALUES
    (1, 'Joe', 'Org1'),
    (1, 'Bill', 'Org2'),
    (1, 'Kate', 'Org1'),
    (1, 'Tom', 'Org3'),
    (2, 'Sue', 'Org2'),
    (3, 'Bill', 'Org2'),
    (3, 'Fred', 'Org1'),
    (4, 'Ted', 'Org3'),
    (4, 'Kate', 'Org1'),
    (4, 'Hank', 'Org3')
;

I want get the following result from a query:

IdeaNr  SubmitterCount   SubmitterRndName   SubmitterRndDepartment
1       4                Joe or ...         Org1 (if Joe)
2       1                Sue                Org2
3       2                Bill or ...        Org1 (if Bill)
4       3                Ted or ...         Org3 (if Ted)

I have tried a lot of thinks with all kind of JOINs of Table1 with itself, derived tables and GROUP BY, e.g.:

SELECT COUNT(IdeaNr) AS SubmitterCount,IdeaNr,SubmitterName,SubmitterDepartment
FROM Table1
GROUP BY IdeaNr,SubmitterName,SubmitterDepartment

I think the problem is to create an algorithm that takes just the first (or a random) name and department appearing in a group of IdeaNr. It is absolutely clear that you can get to misleading interpretations of that kind of data, e. g.:

  • Org1 has 2 Ideas
  • Org2 has 1 Idea
  • Org3 has 1 Idea

But this kind of "wrong averaging" is OK for the task. Can you help?




R: Generate data from a probability density distribution

Say I have a simple array, with a corresponding probability distribution.

library(stats)    
data <- c(0,0.08,0.15,0.28,0.90)
pdf_of_data <- density(data, from= 0, to=1, bw=0.1)

Is there a way I could generate another set of data using the same distribution. As the operation is probabilistic, it need not exactly match the initial distribution anymore, but will be just generated from it.

I did have success finding a simple solution on my own. Thanks!




Raspberry Pi - How to generate random long txt

I've followed this tutorial for generating random data with my raspberry pi model b:

http://ift.tt/1qwcZse

The creation of a 1 mb bin file works great, but for my needs I want to create a random txt file with one long value in each line. How can I accomplish this?




Variance using Gaussian distribution Python

I have a code which calculates the square of a number using Gaussian distribution in python. Now my task is to calculate the variance for the same. But when I try, i keep getting error. The code is as follows:

import random
def generate_data(size):
    n = 5
    m =0.5
    mu, sigma = n ** 2, m/3
    return [random.gauss(mu, sigma) for _ in range(size)]


def average(ls):
    avg =  sum(ls) / len(ls)
    variance = (sum(ls) - sum(avg)) ** 2 / len(ls)

    return variance

I am not good in statistics, so I might be wrong with the formula too. and I am also a beginner in python.The error I get is

'float' object is not iterable 




Simple 2D Random walk

I'm having a problem with average distance in this exercise. It should be close to the sqrt of N steps, but it's lower. Can you help me to find out where is my mistake?

2D random walk. A two dimensional random walk simulates the behavior of a particle moving in a grid of points. At each step, the random walker moves north, south, east, or west with probability 1/4, independently of previous moves. Determine how far away (on average) the random walker is from the starting point after N steps. (Theoretical answer: on the order of sqrt(N).)

public class RandomWalk{
    public static void main(String[] args){

    int N = Integer.parseInt(args[0]);

    double nextStep = 0;
    double averageDistance = 0;
    int COUNT = 1000;

    for (int j = 0; j < COUNT; j++){
        int moveWest = 0;
        int moveEast = 0;
        int moveSouth = 0;
        int moveNorth = 0;
        double distance = 0;

        for (int i = 0; i < N; i++){
        nextStep = Math.random()*4;
        if (nextStep <= 1) ++moveWest;
          else if (nextStep <= 2) ++moveEast;
            else if (nextStep <= 3) ++moveSouth;
              else if (nextStep <= 4)++moveNorth;       
        }

        moveEast = moveEast - moveWest;
        moveNorth = moveNorth - moveSouth;
        distance = Math.sqrt((moveEast * moveEast) + (moveNorth * moveNorth));
        averageDistance += distance; 

        System.out.println("Walker is " + distance + "\t steps away of from the starting point");
        //System.out.println("Sqrt of N is " + Math.sqrt(N));

    }
    System.out.println("Average distance is " + averageDistance/COUNT + " steps away of from the starting point");
    }
}




square of a number using gaussian distribution

Is there a way to calculate the square of a number, say 4, using Gaussian distribution where mu is the square of the number and sigma is 0.16. and for 1000 random points?

I searched the internet a lot, but couldn't find a solution to this. Any piece of code would be very much helpful as i am new to python.




Taking random point from list of points per grid square

Below I have a set of points with locations and attributes. I have one problem here:

The Attr is not passed into final point_grid_loc

Secondly, what I want do do next is take 1 random point from each grid and return it as a data.frame or SpatialPointDataFrame of points.

Struggling with how to approach it:

# Install libraries
library(sp)
library(gstat)

# Set seed for reproducible results
set.seed = 34
x <- c(5.9,6.5,7.1,3.1,5.6,8.1,6.3,5.8,2.1,8.8,5.3,6.8,9.9,2.5,5.8,9.1,2.4,2.5,9.2)
y <- c(3.6,6.5,5.4,5.2,1.1,5.1,2.7,3.8,6.07,4.4,7.3,1.8,9.2,8.5,6.8,9.3,2.5,9.2,2.5)
attr <- c(23,56,2,34,7,89,45,34,2,34,5,67,8,99,6,65,3,32,12)
initialdata <- data.frame(x,y,attr)
colnames(initialdata) <- c("x","y","attr")

# Creating SpatialPointDataFrame:
coords <- data.frame(initialdata$x,initialdata$y)
coords <- SpatialPoints(coords, proj4string=CRS(as.character(NA)), bbox = NULL)
initialdata_DF <- data.frame(coords,initialdata$attr)
initialdata_SPDF <- SpatialPointsDataFrame(coords,initialdata_DF)

#==============#
cellsize <- 3
#==============#

# Creating a grid which will constitute a mesh for stratified sampling
# Info how to include CSR p. 50 yellow book
bb<- bbox(coords)
cs <- c(cellsize,cellsize)
cc <- bb[,1] + (cs/2)
cd <- ceiling(diff(t(bb))/cs)
initialdata_grd <- GridTopology(cellcentre.offset = cc, cellsize = cs,
                                cells.dim = cd)
initialdata_SG <- SpatialGrid(initialdata_grd) # Final grid created here

# Plot the results:
plot(initialdata_SG)
plot(initialdata_SPDF, add=T,col="blue", pch="+")

# Create a polygon:
poly  <- as.SpatialPolygons.GridTopology(initialdata_grd)

# Identifies which point is in which grid/polygon location:
point_grid_loc <- data.frame(initialdata_SG,grid=over(initialdata_SPDF,poly))




How to compare random numbers in Swift

I’m a beginner in programming and playing around with the arc4random_uniform() function in Swift. The program I’m making so far generates a random number from 1-10 regenerated by a UIButton. However, I want the variable ’highest' that gets initialised to the random number to update if the next generated number is larger than the one currently held in it. For example the random number is 6 which is stored in highest and if the next number is 8 highest becomes 8. I don't know how to go about this. I have connected the UIButton to an IBAction function and have the following code:

    var randomValue = arc4random_uniform(11) + 1
    highest = Int(randomValue)

    if (Int(randomValue) < highest) {
        // Don’t know what to do
    }




Use case of Sequential IO and Random IO

I'm working with IOPS, then understand that any disk/drive always has sequential access and random access. I have a question that those accesses depend on the application we used. So, if I'm watching movie what kind of access is being used or I'm typing some piece of text what kind of access is being used there. Thank you so much!




C++ random numbers: What are the advantages of using uniform_int_distribution vs a modulus operation?

According to following results, generating uniform random integers between 2 numbers using % operation is almost 3 times faster then using uniform_int_distribution.

Is there any good reason to use uniform_int_distribution?

Code:

#include <iostream>
#include <functional>
#include <vector>
#include <algorithm>
#include <random>

#include <cstdio>
#include <cstdlib>

using namespace std;

#define N 100000000

int main()
{

clock_t tic,toc;

for(int trials=0; trials<3; trials++)
{
    cout<<"trial: "<<trials<<endl;

    // uniform_int_distribution
    {
        int res = 0;
        mt19937 gen(1);
        uniform_int_distribution<int> dist(0,999);

        tic = clock();
        for(int i=0; i<N; i++)
        {
            int r = dist(gen);
            res += r;
            res %= 1000;
        }
        toc = clock();
        cout << "uniform_int_distribution: "<<(float)(toc-tic)/CLOCKS_PER_SEC << endl;
        cout<<res<<" "<<endl;

    }

    // simple modulus operation
    {
        int res = 0;
        mt19937 gen(1);

        tic = clock();
        for(int i=0; i<N; i++)
        {
            int r = gen()%1000;
            res += r;
            res %= 1000;
        }
        toc = clock();
        cout << "simple modulus operation: "<<(float)(toc-tic)/CLOCKS_PER_SEC << endl;
        cout<<res<<" "<<endl;

    }

    cout<<endl;
}

}

Output:

trial: 0
uniform_int_distribution: 2.90289
538 
simple modulus operation: 1.0232
575 

trial: 1
uniform_int_distribution: 2.86416
538 
simple modulus operation: 1.01866
575 

trial: 2
uniform_int_distribution: 2.94309
538 
simple modulus operation: 1.01809
575 




mardi 29 septembre 2015

Does this stackoverflow forum answer questions related to IELTS?

I am a programmer but seeking emigration in an English speaking country, which requires IELTS band of 7 in each module.Can I use this forum for IELTS? If not please suggest me other forum similar to stackoverflow.




How to only choose elements in an array with a specific length

public String[] words={"cat", "dog", "rodeo", "bird", "lookers", "skid");

.

// Picks a random word from the dictionary, given the length of the word
public String pickWord(int size)
{

}

So if a user inputs 4, it randomly chooses a word in the word array with 4 letters, and randomly. I have created a rand variable from the Random class for that. So how do I choose an element in the array with the same number of letters as the number the user inputted.




unable to generate random words from SQLite database in android

Background: Every time the user starts a new game with another player, he is given 4 words that are taken from the SQLite database, which remain in the current game activity until the game is finished. If the user has multiple games, each of those games will have a different set of words.

problem: I am able to generate a random set of words, but the problem is that my app generates the set of words only once, and this set is used in all the games of the current user, and any other user I log in as.

Here is my code:

  public class WordsListDatabaseHelper extends SQLiteOpenHelper {

protected static Set<String> mSelectedWords;
private static final String DB_NAME = "GAME_TABLE";
private static final int DB_VERSION = 1;
protected static LinkedList<String> mCopy;
public static int gameNumber = 0;


WordsListDatabaseHelper(Context context) {
    super(context, DB_NAME, null, DB_VERSION);
}

@Override
public void onCreate(SQLiteDatabase db) {
    db.execSQL("CREATE TABLE GAME ("
                    + "_id INTEGER PRIMARY KEY AUTOINCREMENT, "
                    + "SELECTED_WORDS TEXT, "
                    + "GAME_NUMBER INTEGER);"
    );



    Collection<String> wordList = new LinkedList<String>();
    mSelectedWords = new LinkedHashSet<String>();

    wordList.add("ant");
    wordList.add("almond");
      //lots more words

    mCopy = new LinkedList<String>(wordList);

    Gson gson = new Gson();
    String wordsContainer = gson.toJson(mCopy);
    insertWordList(db, wordsContainer, gameNumber);

}

private static void insertWordList(SQLiteDatabase db, String wordsContainer, int gameNumber) {
    ContentValues wordValues = new ContentValues();

    Gson gson = new Gson();
    Collections.shuffle(mCopy);
    mSelectedWords.addAll(mCopy.subList(1,7));
    wordsContainer = gson.toJson(mSelectedWords);

    wordValues.put("SELECTED_WORDS", wordsContainer);
    wordValues.put("GAME_NUMBER", gameNumber);
    db.insert("GAME", null, wordValues);
}

@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
}

}

Here is the relevant code from FindingOpponentsActivity, which randomly matches the user with an opponent. When the match is created, the user is taken to StartGameActivity.

  Intent intentRand = new Intent(FindingOpponentActivity.this, StartGameActivity. .class);
                    int gameNum = WordsListDatabaseHelper.gameNumber;
                    intentRand.putExtra(
                            StartGameActivity.EXTRA_RAND_OPPONENT,
                            mOpponent.getObjectId());

                    intentRand.putExtra(
                            StartGameActivity.EXTRA_GAME_NUMBER,
                            gameNum);

                    sendPushNotification();
                    startActivity(intentRand);
                }

And now, this is the code in the onCreate() method of StartGameActivity:

  Intent intent = getIntent();
    mGameNum = intent.getIntExtra(EXTRA_GAME_NUMBER, 0);


    //create a cursor

    try {
        SQLiteOpenHelper wordsListDatabaseHelper = new WordsListDatabaseHelper(this);
        SQLiteDatabase db = wordsListDatabaseHelper.getReadableDatabase();
        Cursor cursor = db.query("GAME",
                new String[] {"SELECTED_WORDS"},
                "GAME_NUMBER =? ",
                new String[]{Integer.toString(mGameNum)},
                null, null, null);

        //move to the first record in the Cursor

        if (cursor.moveToFirst()) {
            //get wordList
            String savedWordList  = cursor.getString(0);

            Gson gson = new Gson();
            Type type = new TypeToken<ArrayList<String>>() {}.getType();
            ArrayList<String> finalWordList = gson.fromJson(savedWordList, type);
            mCopy = new LinkedList<String>();
            mCopy.addAll(finalWordList);


            word1 = (TextView) findViewById(R.id.word1);
            word1.setText(mCopy.get(1));

            word2 = (TextView) findViewById(R.id.word2);
            word2.setText(mCopy.get(2));

What I want is that every time a new game begins, the table has a new entry: a new GAME_NUMBER and wordsContainer (which contains the random words). Thus, each game of the user has a unique identifier (GAME_NUMBER). I think what I am doing wrong is not creating a new entry every time a new game begins, and this is what's causing the same list to appear, but I am totally lost as to how to implement the solution.




HTML/Javascript How to put id's into an array and randomly choose from it?

So this is what I have,

<body>
<h1 style= "text-align:center">Welcome to John's Tic Tac Toe Game</h1>
<script type="text/javascript">
</script>
<div>
<table align="center" border="1" style="width:50%; height:50%; text-    align:center">
<tr>
<td id = "topLeft"></td>
<script>
    document.getElementById('topLeft').onclick = function() {
        document.getElementById('topLeft').style.cssText = "background-color:red";
    }
</script>
<td id = "topMiddle"></td>
<script>
    document.getElementById('topMiddle').onclick = function() {
        document.getElementById('topMiddle').style.cssText = "background-color:red";
    }
</script>
<td id = "topRight"></td>
<script>
    document.getElementById('topRight').onclick = function() {
        document.getElementById('topRight').style.cssText = "background-color:red";
    }
</script>
</tr>
<tr>
<td id = "middleLeft"></td>
<script>
    document.getElementById('middleLeft').onclick = function() {
        document.getElementById('middleLeft').style.cssText = "background-color:red";
    }
</script>
<td id = "middleMiddle"></td>
<script>
    document.getElementById('middleMiddle').onclick = function() {
        document.getElementById('middleMiddle').style.cssText = "background-color:red";
    }
</script>
<td id = "middleRight"></td>
<script>
    document.getElementById('middleRight').onclick = function() {
        document.getElementById('middleRight').style.cssText = "background-color:red";
    }
</script>
</tr>
<tr>
<td id = "bottomLeft"></td>
<script>
    document.getElementById('bottomLeft').onclick = function() {
        document.getElementById('bottomLeft').style.cssText = "background-color:red";
    }
</script>
<td id = "bottomMiddle"></td>
<script>
    document.getElementById('bottomMiddle').onclick = function() {
        document.getElementById('bottomMiddle').style.cssText = "background-color:red";
    }
</script>
<td id = "bottomRight"></td>
<script>
    document.getElementById('bottomRight').onclick = function() {
        document.getElementById('bottomRight').style.cssText = "background-color:red";
    }
</script>
</tr>

</table>
</div>


</body>

What ends up showing up from this is a table and when I click on a box, it turns red. I am trying to get the computer to make a random decision as to where to make a square blue. I thought of making an array of all the different id's i have for each table data and making it choose randomly which one to turn blue, but I couldn't insert the id's into an array because it just reads it as a string. I was wondering if any of you guys could help me solve this or suggest a better way of choosing a random square.

Thanks!




pop a random value from a list of cells

I have a question that is similar to this one, but a little different:

Let's say I have data like this:

CAR NAME   COLOR  LIST OF COLORS
Car1         ?        Red
Car2         ?        Blue
Car3         ?        Green
Car4         ?        Black

and I want to randomly distribute all of the colors to all of the cars without repetition, i.e.

CAR NAME   COLOR  LIST OF COLORS
Car1       Green        Red
Car2       Black        Blue
Car3       Blue         Green
Car4       Red          Black

Is there a way to have a cell randomly select from a list excluding values already input in another range?




Draw random numbers from distribution within a certain range

I want to draw a number of random variables from a series of distributions. However, the values returned have to be no higher than a certain threshold. Let’s say I want to use the gamma distribution and the threshold is 10 and I need n=100 random numbers. I now want 100 random number between 0 and 10. (Say scale and shape are 1.)

Getting 100 random variables is obviously easy...

rgamma(100, shape = 1, rate = 1)

But how can I accomplish that these values range from 0 to 100?




How to generate list of random integers, but only using specified integers? (Python)

This question could be generalized to randomly creating a list of size n, containing pre-specified integers (assuming a uniform distribution). Hopefully it would look like the following:

Perhaps the syntax would look something like

randList([list of integers], size)

which could then produce something along the lines of:

randList([1,-1], 7)
>>> [1,-1,1,-1,-1,-1,1] #(random)

or

randList([2,3,4], 10)
>>> [4,3,4,2,2,4,2,3,4,3] #(random)

I am a bit new to python and everywhere I look it is always returning a range of values between a low and a high, and not specific values. Thanks




generating correlated summated scales from random normal variables in r

I want to generate 5 random normal variables in r each with given mean and sd

x1 <- rnorm(100,20,5)
x2 <- rnorm(100,22,4)
y1 <- rnorm(100,21,3)
y2 <- rnorm(100,23,4)
y3 <- rnorm(100,22,5)

and with summated scales x and y having a predefined correlation as

x <- rowMeans(cbind(x1,x2))
y <- rowMeans(cbind(y1,y2,y3))
cor(x,y) # must be about 0.6

I believe using a loop should be an inefficient solution for this. also y=r*x+sqrt(1-r*r)*rnorm(n) was not applicable. I'm a bit confused how to start. any suggestion would be greatly appreciated.




randomly seek a small sequence of a particular length in a larger sequnce in python

I want to randomly seek a subsequence of length 4 from a larger sequence.

I tried the following code:

import system
import random

    X = 'ATGCATGCTAGCTAGTAAACGTACGTACGTACGATGCTAATATAGAGGGGCTTCGTACCCCTGA'
    Y = [random.choice(X) for i in range(4)]
    print(Y)

But it selects 4 distinct elements from X and not a sequence of length 4 in continuity.




How can I create coordinates that almost border my GameScene?

I am trying to generate circles that nearly border the edge of the screen. I tried creating my own coordinate generator, my issue is that the circles that I am randomly generating are only appearing at the top and bottom of the screen. Here is a screenshot of what it is doing: http://ift.tt/1FB77au

I have no idea why this is happening because when I print the x and y coordinate of the circle's position, it says that both points are less than the frame's width and height. In my GameScene.swift I call this function.

    private func generateRandomCoorindates() -> CGPoint {

    let randomNumber = arc4random_uniform(2)
    var xCoordinate: Double
    var yCoordinate: Double
    if randomNumber == 0 {
        var _xCoordinate: Double {
           let _randomNumber = arc4random_uniform(2)
            //x-corrdinate either 50 or width-50
            if _randomNumber == 0 {
                return 50
            } else {
                return Double(self.frame.width - 50)
            }
        }
        xCoordinate = _xCoordinate
        //random y-coordinate from 50 to height-50
        yCoordinate = Double.random(lower: 50, upper: Double(self.frame.height) - 50)
    }
    else {
        //random x-coordinate from 50 to width-50
        xCoordinate = Double.random(lower: 50, upper: Double(self.frame.width) - 50)
        var _yCoordinate: Double {
            //y-coordinate either 50 or height - 50
            let _randomNumber = arc4random_uniform(2)
            if _randomNumber == 0 {
                return 50
            } else {
                return Double(self.frame.height - 50)
            }
        }
        yCoordinate = _yCoordinate
        }
    return CGPoint(x: CGFloat(xCoordinate), y: CGFloat(yCoordinate))
    }

My extensions are:

public func arc4random <T: IntegerLiteralConvertible> (type: T.Type) -> T {
var r: T = 0
arc4random_buf(&r, Int(sizeof(T)))
return r
}

public extension Double {
    public static func random(lower lower: Double, upper: Double) -> Double {
        let r = Double(arc4random(UInt64)) / Double(UInt64.max)
        return (r * (upper - lower)) + lower
    }
 }




Range of quantizer to avoid clipping of transmitted signal in MATLAB

I have a signal ,say

s = sqrt(0.5) * (randn(1,10000) + 1i * randn(1,10000))

After quantizing it to say 512 levels, I observe that there is clipping of the original signal. I would like to know if there is a method to calculate the range of quantizer for a signal with complex normal distribution (signal s defined above) in a way that the original signal is not clipped.




How to reject randomly generated numbers in R that don't meet a criteria

Basically I'm generating random numbers in r from a uniform distribution then using Marsaglia and Bray's method to transform these to random normal deviates, a step in this process is to transform u[1]^2 + u[2]^2 to a value w, w can only be accepted if it is less than 1, in R what can I write to reject the number if it is larger than 1 and as I'm doing this inside a while loop I don't want to add a count to the index for rejected values? Thanks




Need help getting populating array with random numbers 1-10 without using 0 in Java

Need help getting populating array with random numbers 1-10 without using 0. - Create an array of 100 integers. I've tried int random = r.nextInt(High-Low) + Low; but that throws off the count of how many of each number.

What I need to do in my assignment:

  • Populate the array with random numbers ranging from 1 to 10. (not zero)
  • Determine what the average is of all the numbers in the array.
  • Count the occurrence of each of the ten numbers in the array of 100. Do by having a second array that's 10 integers in size and increment each element of the array based on the number of duplicates you find in your array of 100 integers.


package arrays;

import java.util.Arrays;
import java.util.Random;

public class Intergers {

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

        Random r = new Random();

        // Create an array of 100 integers.
        int array[] = new int[100];

        int a = 0;

        // Populate the array with random numbers ranging from 1 to 10.
        while (a < 100)
        {
            int random = r.nextInt(10);
            array[a] = random;
            a++;
        }

        //calculate sum of all array elements
        int sum = 0;

         for(int i=0; i < array.length ; i++)
             sum = sum + array[i];

        //calculate average value
         double average = (double)sum/array.length;

        System.out.println("Array: " + Arrays.toString(array));
        // System.out.println("Sum: " + sum);
         //System.out.println("Array Length: " + array.length);
         System.out.println("Average value of array is: " + average);

         // Count the occurrence of each of the ten numbers in the array of 100
         int[] occurrences = new int[10];
         for (int b : array) {
                occurrences[b]++;
            }
         // System.out.println("Array: " + Arrays.toString(occurrences));



          System.out.println(1 + " appeared " + occurrences[0] + " times");
          System.out.println(2 + " appeared " + occurrences[1] + " times");
          System.out.println(3 + " appeared " + occurrences[2] + " times");
          System.out.println(4 + " appeared " + occurrences[3] + " times");
          System.out.println(5 + " appeared " + occurrences[4] + " times");
          System.out.println(6 + " appeared " + occurrences[5] + " times");
          System.out.println(7 + " appeared " + occurrences[6] + " times");
          System.out.println(8 + " appeared " + occurrences[7] + " times");
          System.out.println(9 + " appeared " + occurrences[8] + " times");
          System.out.println(10 + " appeared " + occurrences[9] + " times");




    }
}




lundi 28 septembre 2015

C# Array within for loop produces the same random integar values

this is my first time posting. Hopefully this question isn't too confusing. I'm working on a lab for a beginners C# book and am now stuck. I'm creating a "Dog Race Simulator" program. When I click the "Start Race" button, dogs are to move to the right with every tick of the timer at a random integer between 1 and 30 until they reach the finish. I've tried switching up the code a ton of different ways, reading about arrays, the Random class, and for loops online, yet for some reason, no matter what, the dogs always move at the same rate. They need to be moving at different random rates with each tick.

A solution would be nice, but what I really want to know, why is my code not working? Shouldn't each dog be assigned a different random number as it cycles through the 'i' values of the array?

Image can be found here: http://ift.tt/1iXTTdC

Here is the Form1 code:

Greyhound[] dogs = new Greyhound[4];

    private void startRaceButton_Click(object sender, EventArgs e)
    {
        timer1.Start();
        dogs[0] = new Greyhound() { MyPictureBox = dog1PictureBox };
        dogs[1] = new Greyhound() { MyPictureBox = dog2PictureBox };
        dogs[2] = new Greyhound() { MyPictureBox = dog3PictureBox };
        dogs[3] = new Greyhound() { MyPictureBox = dog4PictureBox };
    }

    private void timer1_Tick(object sender, EventArgs e)
    {
        for (int i = 0; i < 4 ; i++)
        {
            if (dogs[i] != null)
            {
                dogs[i].Randomizer = new Random();
                dogs[i].Distance = dogs[i].Randomizer.Next(1, 30);
                dogs[i].Move(); 
            }
        }
    }

And this is the Greyhound class code:

class Greyhound
{
    public PictureBox MyPictureBox; 
    public bool GoingForward = true;
    public Random Randomizer; 
    public int Distance;

    public void Move() 
    {
        if (MyPictureBox != null)
        {
            if (GoingForward == true)
            {
                MyPictureBox.Left += Distance; 
                if (MyPictureBox.Left >= MyPictureBox.Parent.Width - MyPictureBox.Width)
                {
                    GoingForward = false; 
                }
            }
        }
    }
}




RNG in loop and printing word from string array

I'm learning C++ and trying to generate a new Random number between 0 and 49 for each pass of the for loop in this program. Which I then need it to print the corresponding word at that point in the string array. I'm having trouble getting it to make a new random number each loop, and also with how to get it to print the word at that point in the array, and not just the letter.

Thank you ahead of time for any suggestions

#include <string>
#include <iostream>
#include <algorithm>
#include <fstream>
#include <time.h>
#include <stdlib.h>
#include <random>

using namespace std;

int generateRandom() {
default_random_engine generator;
uniform_int_distribution<int> distribution(0, 49);
int random = distribution(generator);  // generates number in the range 0..49
return random;
}

int main() {
ofstream outFile;
ifstream inFile;
string words;
srand(time(NULL));

int Random2 = rand() % 7 + 1;
inFile.open("words.txt");
if (!inFile.is_open()) { //tests to see if file opened corrected
    exit(EXIT_FAILURE);
}
while (getline(inFile, words)) { //Puts file info into string
    inFile >> words;
}
for (int i = 0; i < Random2; i++) {

    cout << words[generateRandom()];
}

cin.get();
}




How to check if an array has enough empty/null "consecutive" positions to place values together randomly in Java?

I'm creating a commercial airline flight program and I'm still learning how to get around with Java. So, I was wondering if there was any way to check if an array has enough consecutive positions to place values together in those positions in the array? For example, I have an array of strings called seats, each position in this array corresponds to an available seat on the flight. Initially these seats are all empty.

String[] seats = new String[8];

In the long-run, this program is going to be inserting values into this array and I want my program to be able to check if there are any empty seats(positions) in the flight(array) to assign a passenger to a seat. I sketched this to check.

for(int i=0; i< seats.length-1;i++) {
if(seats[i] != null) {
     do something;
   } else {
       system.out.println("No seats available");
       (how do I not assign seats or accept more values to my array?)
   }
}

but advised on using an objective approach, I got to this

private static int MAX_SEATS = 8;
private String[] seats = new String[MAX_SEATS];

public boolean addPassenger(String passengerName) {
    for (int i = 0; i < seats.length; i++) {
        if (seats[i] == null) {
            seats[i] = passengerName;
            return true;
        }
    }
    return false;
}

If the program finds an empty seat after checking, It should then check again if there are empty consecutive seats. (For example, if we wanted to make 3 passengers seat together, the program should check if there are empty 3 seats and then seat them there). If the program finds 3 consecutive positions in the array, it should randomly assign the passengers to whichever 3 position. otherwise it should randomly try another seat, repeating until successful. Right now, my array of seat can take up to 8 values, so the possible 3 positions could be (1,2,3 or 2,3,4 or 3,4,5 or 4,5,6 or 5,6,7). If the program does not find a consecutive position to seat these 3 people, it should randomly place them in different positions.(pick random seat numbers till it can find an empty seat) This code is just adding passengers to the seats array .

//accepting more values to the seats array
public boolean addPassengers(String... passengerNames) {
    boolean everyoneAdded = true;
    for (String passengerName : passengerNames) {
        everyoneAdded = everyoneAdded && addPassenger(passengerName);
    }
    return everyoneAdded;
}

How is it possible to check for consecutive positions in an array in order to add groups of passengers randomly? Any correction/contribution would be helpful.




Calculating chance of adding char to string

So my objective is to create a random password generator of length n (n >= 5 && n <= 15) that adds in only two numbers at random locations.

(e.g. 7S4js 86dJxD h6Zqs9K)

I have this working... or so I want to believe. What I want to know is will my code ALWAYS work at determining whether or not a number should be inserted.

'newPassword': Returns a string of length 'len', using 'nums' numbers.

std::string newPassword(int len, int nums)
{
    std::string password = "";

    // Required numbers
    int req = nums;

    for (int i = 0; i < len; i++)
    {
        bool needNum = req > 0;

        bool chance = rand() % len > req;

        bool useNum = needNum && chance;

        if (useNum)
            req--;

        char c = nextChar(useNum);

        password += c;
    }

    return password;
}

'nextChar': Returns a random character. The character will be a number if 'isNum' is true.

char nextChar(bool isNum)
{
    char c;

    if (!isNum)
    {
        // 50% chance to decide upper or lower case
        if (rand() % 100 < 50)
        {
            c = 'a' + rand() % 26;
        }
        else
        {
            c = 'A' + rand() % 26;
        }
    }
    else
    {
        // Random number 0-9
        c = '0' + rand() % 10;
    }

    return c;
}

So specifically, will the 'chance' variable in 'newPassword' work all the time?




Faster way then mine to populate a vector with unique integers except two values ? C++

I can´t post my all program here, just snippets. Will answer any question.

What I have:

1) I have a vector with 20 ID´s, like this [0,1,2,3,4,5,6...19].

2) I pick two ID´s, for example number 3 and number 6.

What I need:

1) Generate a vector of size N-1, where the N=5. This vector should not contain number 3 and number 6, only the remaining ID´s, and do not repeat them. For example: new vector = [7,2,19,4]. Yes, only 4 items because the 5th is the number 3 or number 6, they will play with this new created groups, so 1+4 =5(N).

My problem:

1) I need to do this like 1 millions times. It is very slow. I believe that this part of code is the most heavy, because I deleted that part and the program runs really fast without it.

My question:

1) Below is my code, the do while loop, can I somehow optimize it ? maybe I need to use another structure or smarter method to generate this ?

Code:

for (int i = 0; i < _iterations; i++)
    {
        players.clear();
        int y = 0;
        do{
            // _pop_size = 20
            int rand_i = static_cast<int>(rand_double(0, _pop_size));
            if (rand_i != 3 && rand_i 6){
             // verify if the ID already exists in vector
                if (std::find(players.begin(), players.end(), rand_i) == players.end()){
                    players.push_back(rand_i);
                    ++y;
                }
            }
          } while (y < _group_size - 1);
   // ...
   // ...
   // ...
   // ...

rand_double() function:

    double rand_double(int min, int max) const
{
    std::random_device rd;
    std::mt19937 mt(rd());
    std::uniform_real_distribution<double> dist(min, max);

    return dist(mt);
}




Using arrays to find the largest number between 2 lists

Create a program that randomly generates 5 numbers from 1 to 50, have these print out and then a second array to do the same thing. Have the program determine which is the largest number between the 2???? Okay so this is a question i asked myself and this is probably completely wrong but i tried:

public class FindArray2 
{
    public static void main(String args[]) {
        int[] list = new int[5];
        for (int i = 0; i < 5; i++) {
            list[i] = (int)(Math.random() * 50) + 1;
            System.out.println(list[i]);
        }

    }
    public static double[] ListOne() {
        double[] list = new double[5];
        for (int i = 0; i < 5; i++) {
            list[i] = (int)(Math.random() * 50) + 1;
            System.out.println(list[i]);
        }
        return list;
    }
    public static double[] ListTwo() {
        double[] list = new double[5];
        for (int i = 0; i < 5; i++) {
            list[i] = (int)(Math.random() * 50) + 1;
            System.out.println(list[i]);
        }
        return list;
    }
}

I could use a lot of help




R Programming Random Stock Pick

I stuck in a problem with R Programming. My aim is to randomly select 2 stocks out of the Swiss Market Index, which contains of 30 stocks.

Until now I solved the random pick of the 2 stocks with the following code:

SMI_components <- cbind("ABB (ABBN.VX)", "ADECCO (ADEN.VX)", "ACTELION (ATLN.VX)", "JULIUS BAER GRP (BAER.VX)", "RICHEMONT (CFR.VX)", "CREDIT SUISSE (CSGN.VX)", "GEBERIT (GEBN.VX)", "GIVAUDAN (GIVN.VX)", "HOLCIM (HOLN.VX)", "NESTLE (NESN.VX)", "NOVARTIS (NOVN.VX)", "TRANSOCEAN (RIGN.VX)", "ROCHE HOLDING (ROG.VX)", "SWISSCOM (SCMN.VX)", "SGS (SGSN.VX)", "SWISS RE (SREN.VX)", "SYNGENTA (SYNN.VX)", "UBS (UBSG.VX)", "SWATCH GROUP (UHR.VX)", "ZURICH INSURANCE GROUP (ZURN.VX)")

 for(i in 1:1){
 print(sample(SMI_components, 2))
}

How do I continue my code, if I want to download the historical data from these two random picked stocks? For example, the random selection is:

"NOVARTIS (NOVN.VX)" and "ZURICH INSURANCE GROUP (ZURN.VX)"

how to continue that ...

SMI_NOVARTIS <- yahooSeries ("NOVN.VX", from = "2005-01-01", to = "2015-07-30", frequency = "daily")

SMI_ZURICH <- yahooSeries ("ZURN.VX", from = "2005-01-01", to = "2015-07-30", frequency = "daily")

I would really appreciate your help Regards




How to create random color to fill a circle? Running Python in bash terminal mac

the equation for my circle is

 circle1 = plt.Circle((0,0),0.5, color ="r", alpha=0.75)

here, the r represents red however I'm wondering if its possible to fill the circle with a random color.

I've tried (after importing random)

 COLORS = [(139, 0, 0), 
          (0, 100, 0),
          (0, 0, 139)] 
 circle1 = plt.Circle((0,0),0.5, color='random.choice(COLORS)', alpha=0.75)

and I have tried

 nums = map(lambda x : random.randint(0,7), range(50))
 cols = map(lambda i: colour[i], nums)
 circle1 = plt.Circle((0,0),0.5, color='cols', alpha=0.75)

but I havent had any luck yet. any help would be greatly appreciated! Thanks




"Randomizer" Code not working in IE

I'm trying to display a bunch of divs in a random order with 4 divs in each of them. Those have to be in a random order too. My code:

var cards = $(".qcards").get();
    cards.sort(function() {
        return Math.random()*30 > 5 ? 1 : -2;
    });
    $.each(cards,function(i,el) {
        var color = this.className,
            $el = $(el);
        $el.css({backgroundColor: color}).appendTo( $el.parent() );
    });

var answers = $(".answer").get();
    answers.sort(function() {
        return Math.random()*30 > 5 ? 1 : -2;
    });
    $.each(answers,function(i,el) {
        var color = this.className,
            $el = $(el);
        $el.css({backgroundColor: color}).appendTo( $el.parent() );
    });

There are 40 .qcards and in each of those 4 .answer

Somehow this isn't working in IE, there's no error message/code though. The only statement I get when I'm debugging is "'return'" statement outside of function. Is it possbile that .get() isn't working in IE?




Math random to find Names in an Array while not duplicating

So I want to find three names out of an array of names which I then want to write to a new array (not gotten this far yet though), but the problem I have is that it keeps randomizing the same names I already found.

Check out the jsfiddle script.

Code:

findStudentBtn.onclick = findStudent;

function findStudent() {
    var studArray = ["John","Daniel","Hans","Lars","Tom","Amanda","Jane","Sarah"] //1-8
    for (i=0; i<3; i++) {
        if (i=1) {
            var randomStud1 = studArray[Math.floor(studArray.length * Math.random())];
            msg8.innerHTML += randomStud1 + ", ";
        }
        if (i=2) {
            var randomStud2 = studArray[Math.floor(studArray.length * Math.random())];
            msg8.innerHTML += randomStud2 + ", ";
        }
        if (i=3) {
            var randomStud3 = studArray[Math.floor(studArray.length * Math.random())];
            msg8.innerHTML += randomStud3 + ", ";
        }

        if (randomStud1 == randomStud2 || randomStud2 == randomStud3 || randomStud1 == randomStud3){
            ms8.innerHTML = "";
            findStudent();
        } 
    }
}  




Generate random numbers in android for new album [duplicate]

This question already has an answer here:

Generate random numbers without duplicates in android while creating new Album and store in SQlite.




How Do I get a Random Variable Based on Time in Java

I am trying to make a program that picks random numbers between 1 and 0. However, when I run the program, I get the same output over and over again (20 times!). How might I go about fixing this? I have heard that Math.random() is more biased than random().

This is my code:

public class Startup {

    public static void main(String[] args) {
        double match = Math.random();

        for(int i = 0; i <= 20; i++){
            if(match < 0.05){
                System.out.println("a");
            }
            else if(0.05 <= match && match <= 0.1){
                System.out.println("b");
            }
            else if(0.1 < match && match <= 0.15){
                System.out.println("c");
            }
            else if(0.15 < match && match <= 0.2){
                System.out.println("d");
            }
            else if(0.2 < match && match <= 0.25){
                System.out.println("e");
            }
            else if(0.25 < match && match <= 0.3){
                System.out.println("f");
            }
            else if(0.3 < match && match <= 0.35){
                System.out.println("g");
            }
            else if(0.35 < match && match <= 0.4){
                System.out.println("h");
            }
            else if(0.35 < match && match <= 0.4){
                System.out.println("i");
            }
            else if(0.4 < match && match <= 0.45){
                System.out.println("j");
            }
            else if(0.45 < match && match <= 0.5){
                System.out.println("k");
            }
            else if(0.5 < match && match <= 0.55){
                System.out.println("l");
            }
            else if(0.55 < match && match <= 0.6){
                System.out.println("m");
            }
            else if(0.6 < match && match <= 0.65){
                System.out.println("n");
            }
            else if(0.65 < match && match <= 0.7){
                System.out.println("o");
            }
            else if(0.7 < match && match <= 0.75){
                System.out.println("p");
            }
            else if(0.75 < match && match <= 0.8){
                System.out.println("q");
            }
            else if(0.8 < match && match <= 0.85){
                System.out.println("r");
            }
            else if(0.85 < match && match <= 0.9){
                System.out.println("s");
            }
            else if(0.9 < match && match <= 0.95){
                System.out.println("t");
            }
            else if(0.95 < match && match <= 1){
                System.out.println("u");
            }
        }
    }
}




How to fill svg with a random color?

I am using this code but I'd like my fill and stroke color lo be selected randomly from an array. This is my css:

 <style>          
      #svg.clickit .logo {
          fill: #002100;
          stroke: #002100;
          transition: 1s;
      }
  </style> 




Python: Choose random line from file, then delete that line

I'm new to Python (in that I learned it through a CodeAcademy course) and could use some help with figuring this out.

I have a file, 'TestingDeleteLines.txt', that's about 300 lines of text. Right now, I'm trying to get it to print me 10 random lines from that file, then delete those lines.

So if my file has 10 lines:

Carrot

Banana

Strawberry

Canteloupe

Blueberry

Snacks

Apple

Raspberry

Papaya

Watermelon

I need it to randomly pick out from those lines, tell me it's randomly picked blueberry, carrot, watermelon, and banana, and then delete those lines.

The issue is, when Python reads a file, it reads that file and once it gets to the end, it won't go back and delete the lines. My current thinking was that I could write the lines to a list, then reopen the file, match the list to the text file, and if it finds a match, delete the lines.

My current problem is twofold:

  1. It's duplicating the random elements. If it picks a line, I need it to not pick that same line again. However, using random.sample doesn't seem to work, as I need those lines separated out when I later use each line to append to a URL.
  2. I don't feel like my logic (write to array->find matches in text file->delete) is the most ideal logic. Is there a better way to write this?

    import webbrowser
    import random
    
    """url= 'http://www.google.com'
    webbrowser.open_new_tab(url+myline)""" Eventually, I need a base URL + my 10 random lines opening in each new tab
    
    def ShowMeTheRandoms():
        x=1
        DeleteList= []
        lines=open('TestingDeleteLines.txt').read().splitlines()
    for x in range(0,10):
        myline=random.choice(lines)
        print(myline) """debugging, remove later"""
        DeleteList.append(myline)
        x=x+1
        print DeleteList """debugging, remove later"""
    ShowMeTheRandoms()
    
    



Are we allowed to OrderBy(Random)?

I sometimes shuffle lists or arrays using OrderBy (item => R.NextDouble()), where Random R is initialized elsewhere.

Now this clearly is a hack, though the one recommended everywhere on this site, and it does work very nicely in practice.

However, it was also pointed out that this makes the assumption that the sorting algorithm does not get confused by changing values of a single item and e.g. enters an infinite loop.

My question is if there is some sort of implicit or explicit guarantee that this won't happen. I could not find anything about it in MSDN.

While there are very good, specialized O(n) algorithms for this purpose, I don't always want to search and copy-paste them in little side projects (we are not talking about prod here). They would obviously be the right solution.

Also note that performance is not an issue at all.




How to make random string replace textview?

I have an activity with 3 edittexts and a button. I have a second activity with 2 textviews.

When button is clicked i want two random edittexts values from activity1 to replace the text on textviews on activity2.

I managed to do that, but not randomly. How can I make it random?

Here is the first activity.

final EditText et  = (EditText) findViewById(R.id.editText);
        final EditText et1 = (EditText) findViewById(R.id.editText2);
        final EditText et2 = (EditText) findViewById(R.id.editText3);
        Button btn = (Button) findViewById(R.id.button);

        btn.setOnClickListener(new View.OnClickListener() {

            public void onClick (View v){
                Intent i = new Intent(MainActivity.this, postavke.class);
                i.putExtra("prvi", et.getText().toString());
                i.putExtra("drugi", et1.getText().toString());
                i.putExtra("treci", et2.getText().toString());
                startActivity(i);
            }
        });
    }

Here is the second activity.

   TextView tv = (TextView) findViewById(R.id.asdf);
    tv.setText(getIntent().getExtras().getString("prvi"));

TextView dr = (TextView) findViewById(R.id.asdg);
dr.setText(getIntent().getExtras().getString("drugi"));




Php / sql Random users of Db

I get with Rand() random user out of the database. I am using php pdo so it looks like this: $db = DBWrapper::getInstance();

    /**
     * Random user 
     */
    $table = "staff";
    $columns    = array("id", "firstname", "lastname", "categorie_bit");
    $whereRand  = array('categorie_bit = :idRand');
    $valuesRand = array('idRand' => 00);
    $orderBy    = array('RAND()');

    $result_set  = $db->select($table, $columns, $whereRand, $valuesRand, $orderBy, 1);

    foreach($result_set as $result) { var_dump($result); }

This give me a Random user from the database.

Now I want to take randomly more users of the database but with the exception of not taken users I already took with Rand().

How to I accomplish that.




dimanche 27 septembre 2015

create a loop whith normrnd with given mus and sigmas

This is could be seen as an easy question but I could not figure out so far. I want to generate random number following a normal distribution, using given mus and sigmas, next round those numbers and eliminate the negatives. Finally store the created vectors in just one matrix called sim. The given mus and sigmas are the next ones: m1=22.06; s1=16.06; m2=23.84; s2=72.39; m3=3.79; s3=3.4; m4=148.306; s4=125.81; m5=36.82; s5=15.64; So far I have the next code:

for i = 1: 5 R(i) = normrnd(m(i),s(i),[m,n]);%generate random number ND R(i) = round(R(i)); [badrows,c]=find(R(i)<0);%find negatives ones newR(i) = R(setdiff(1:size(R(i),1),badrows),:);%eliminate them sim(:;i)= = newR(i); end I have tried the codes part by part and generate the random numbers, also round it and eliminates the negatives, but when I est the loop it has troubles calling the given numbers




number guessing game java

So I'm very new to programming, even newer to this site and I'm just looking for help with my program. I'm not asking for someone to do the code for me because I already have the entire program written, I just need help with one piece. I'm writing a java code that asks the user to guess the computers random number, which I have fine, however, what I would like to do is have a message that corresponds to the number of guesses it took the user. For example if the user guessed the random number in 1 try there would be in output of "Excellent!" if the user guessed the answer in 2-4 tries "Good Job" and so on.. I have looked at many other posts and haven't quite found anything to help me out, like I said I am very very new and I will post my code, once I figure out how to do so without insulting anyone here willing to help! Also, I'm writing in java! Thank you for looking!




How do i randomly display my questions so its now always the same? (JavaScript)

<script type="text/javascript">

var questions = [
    ['http://ift.tt/1GaXDgH','0'],
    ['http://ift.tt/1NVKOgH','1'],
    ['http://ift.tt/1GaXDgJ','2'],
    ['http://ift.tt/1FC1p7V','3'],
    ['http://ift.tt/1LVZLef','4'],
    ['http://ift.tt/1FC1nN6','5'],
    ['http://ift.tt/1LVZLeh','6'],
    ['http://ift.tt/1FC1p7Z','7'],
    ['http://ift.tt/1FC1pod','8'],
    ['http://ift.tt/1LVZIPE','9'],
    ['http://ift.tt/1FC1nN9','10'],
    ['http://ift.tt/1LVZLuw','11'],
    ['http://ift.tt/1FC1nNb','12'],
    ['http://ift.tt/1LVZJ5S','13'],
    ['http://ift.tt/1FC1nNd','14'],
    ['http://ift.tt/1LVZLuy','15'],
    ['http://ift.tt/1FC1pof','16']
];
var qNo = 0;
var correct = 0;
var cnt = 0;

function NextQuestion(response) {
  if ((qNo < questions.length) && (response == questions[qNo][1])) { correct++; }
  document.getElementById('score').innerHTML 
    = 'Your score is '+correct+'/'+(cnt+1);
  qNo++;
  if (qNo < questions.length) { document.getElementById('Pic').src = questions[qNo][0]; cnt++; }
                     else { alert('Quiz is done'); }
}
onload = function() {
 document.getElementById('Pic').src = questions[0][0];
}

</script>

Okay so basically I have 17 questions and 17 answers that are listed using the numbers 0-16, what I want to do is randomize the order in which the pictures are shown so that you cant just find a pattern and not answer it right, also and I cant figure this out, I want to make it so that after each question is answered a green Correct or a Red incorrect shows up depending on If you got the previous question right can anyone help?




How can I create a random math statement and have the computer solve it?

a = Math.random();
b= Math.random();

az = Math.round(a);
bz = Math.round(b);

var chooseoperator = ['+','-','*','/'];


var operator = chooseoperator[Math.floor(Math.random() *chooseoperator.length)];

var final=az+operator+bz;

alert(final);

So the computer alerts,"1-0" or something similar. How can I make the computer solve it?




Generate 100 random numbers between 0 and 1 and freeze it

How to generate 100 random numbers between 0 and 1 and freeze so it can not be changed? I want to use MATLAB. I used Excel to generate, but it changes constantly so I am fed up with those constant changes. I have 10 variables, and have to generate 100 random numbers between 0 and 1 for each variable. I also need to export these generated numbers to Excel as well. Your help will be greatly appreciated.




Function that creates an array in C

I tried to write a function that returns a random array of pixel colors, so when I call randomPalette(i), the function will create a random array of i colors.
Below are my codes. It says error at random[colors] that expression must have constant value. I don't know why. How to fix it?

pixel* randomPalette(int colors){

pixel random[colors] ;
int i, x;
srand(time(NULL)); //generate a random seed
for (i = 0; i < colors; i++){
    x = rand() % 256;
    random[i].r = x; random[i].g = x; random[i].b = x;
}
return random;
}




Generating N random points with certain predefined distance between them

I have to create highway scenario in MATLAB. I have to generate random points (i.e. vehicles) on highway. By using randn() command, random points are overlapping on each other. I want to generate random points such that a minimum distance between random points is maintained.

Could anybody help me in generating this kind of scenario..




How do I create a deterministic Random number generator with numpy seed?

As I understand the syntax is

In[88]: np.random.seed(seed=0)

In[89]: np.random.rand(5) < 0.8
Out[89]: array([ True,  True,  True,  True,  True], dtype=bool)
In[90]: np.random.rand(5) < 0.8
Out[90]: array([ True,  True, False, False,  True], dtype=bool)

However, when I run the rand(), I get different results. Is there something I am missing with the seed function?

Thanks.




Pick a random image of an album of imgur

I need a php function to pick a random image of a predetermined album of imgur.

For example, I have this album: http://ift.tt/1KMZg66

I want to get a randomd url of the image, for example: http://ift.tt/1KYi71A

This is for a Wordpress blog I have been working on, and my knowledge of PHP is low.




Same random numbers in a for loop

There's a lot of similar question, but I can't find an answer to my problem. I'm writing my own random number generator (for learning purposes). I paste here the important parts of my code:

long rng(long x0, long c, long p)
{
    long x = (c*x0) % p;
    return x;
}

In the main() function, I iterate this rng()

long x2 = 37951;                    // initialize the seed
long c = 69069; long p = pow(2,32); // initialize c and p

for (int i=1; i<=n; i++) {
    long x1 = rng(x2,c,p);
    long x2 = rng(x1,c,p);
    cout << x1 << "\t" << x2 <<endl;
}

As afterwards I want to generate polar coordinates, I need to generate 2 random numbers in each loop. As you can see, the seed is initialized just one time, but the result I become is:

2621237619  504678423
2621237619  504678423
2621237619  504678423
2621237619  504678423
2621237619  504678423

If I only generate x2 (with long x2 = rng(x1,c,p);), I become different results at each loop. Can someone tell me why?




Storing a Random state

I'm designing a program which:

  1. Includes randomness
  2. Can stop executing and save its state at certain points (in XML)
  3. Can start executing starting from a saved state
  4. Is deterministic (so the program can run from the same state twice and produces the same result)

The problem here is saving the randomness. I can initialize it at start, but from state to state I may generate anywhere from 0 to 1000 random numbers.

Therefore, I have 3 options I can see:

  1. Store the seed, and number of times a number has been randomly generated, then when loading the state, run the random number generator that many times.
  2. On state save, increment the seed by N
  3. On state save, randomly generate the next seed

The problem with option 1 is the run time, and is pretty infeasible.

However, I'm unsure whether 2 or 3 will produce good random results. If I run two random generators, one seeded with X, the other seeded with X+1, how different will their results be? What if the first is seeded with X, and the second is seeded with X.random()?

In case it makes a difference, I'm using Python 3.




Java: Generate random double from 0.1 to 1

So, I know I can use double random1 = new Random().nextDouble();

But how can i make it so it only outputs doubles from 0.1 to 1?




How is probability of skiplist node height Implement in redis when it comes to calculate the height of inserted node?

the follow is a function in t_zset.c in redis source. The purpose of zslRandomLevel is to get height for a new inserted node by stochastic algorithm. What makes me confused is the while condition. As I can understand, the probability of while condition to be true is 0.25,should the probability of this condition be 0.5? So, can someone help me understanding how much the probability of this condition and what is the theory of (random() & 0xFFFF) < (ZSKIPLIST_P * 0xFFFF), cause I can replace it simply with random()<ZSKIPLIST_P?

int zslRandomLevel(void) {
    int level = 1;

    while ((random() & 0xFFFF) < (ZSKIPLIST_P * 0xFFFF))//ZSKIPLIST_P=0.25
        level += 1;

    return (level < ZSKIPLIST_MAXLEVEL) ? level : ZSKIPLIST_MAXLEVEL;
}




Using a loop, and conditionals to change score in a game

I used a loop to generate 1 numbers onto the text file. I start to have problems on when the user starts to play the game.

I'm going to go right ahead and give my pseudo code so you can understand what I want to do...

  1. Randomly generate 10 numbers between 0 and 10
  2. Store these numbers into a file called mysteryNumbers.txt, a number per line
  3. Prompt the user to enter a number between 0 and 10
  4. Check this number against the first number in the file
  5. If the user guesses right, subtract 10 from the score (at the start, the score is 0)
  6. If the user guesses wrong, add the correct amount of score to the current score of the user (at the start, the score is 0)
  7. Prompt the user to enter a number between 0 and 10
  8. Check this number against the second number in the file
  9. If the user guesses right, subtract 10 from the score
  10. If the user guesses wrong, add the correct amount of score to the current score of the user
  11. Prompt the user to enter a number between 0 and 10
  12. Check this number against the third number in the file
  13. If the user guesses right, subtract 10 from the score
  14. If the user guesses wrong, add the correct amount of score to the current score of the user
  15. … etc. …
  16. Display the score of the user: of course, the lower the better!

-I also organized the code below following the pseudocode outline.

    /************************************************************************************
    PrintWriter mywriter = new PrintWriter("mysteryNumber.txt");
    int randomNumber;
    int i = 0;
    i=1;
    while (i<=10) {
    Random randomGen = new Random();
        randomNumber= randomGen.nextInt(11);
    // then store (write) it in the file
    mywriter.println(randomNumber);
        i = i + 1;
    }
    //numbers are now generated onto text file...   

    /************************************************************************************
     * 3.   Prompt the user to enter a number between 0 and 10                          */
    Scanner myscnr= new Scanner (System.in);

    System.out.print ("Please enter a number between 0 and 10: ");

    int userNumber= myscnr.nextInt();

    /************************************************************************************
     * 4.   Check this number against the first number in the file                      */
    // to check the user's number against the file's, you need to be able to read
    // the file. 
    FileReader fr = new FileReader("./mysteryNumber.txt");
    BufferedReader textReader = new BufferedReader(fr);
    int numberInFile;
    // the number in your file is as follows:
    numberInFile = Integer.valueOf(textReader.readLine());

    /************************************************************************************
     * 5.   If the user guesses right, subtract 10 from the score                       */
    /************************************************************************************
     * 6.   If the user guesses wrong, add the correct amount of score to the current   *
     * score of the user (at the start, the score is 0                                  */  


    /************************************************************************************
     * 7.   Prompt the user to enter a number between 0 and 10                          */
    //Sytem.out.println ("Enter a number between 0");

    /************************************************************************************
     * 8.   Check this number against the second number in the file                     */

    etc etc...

I'm confused starting on comment section 5. I know I have to create a new integer for score, but after that I'm lost! I tried working in an if else statemnent but I couldn't get it going..




samedi 26 septembre 2015

Random method gives the same number in MPI program if called multiple times

I am writing a MPI program to generate random number and call MPI_Reduce() to get the max number. The random method returns the same number for the same process for different call. Here is my code

void printArray(float *array, int size, int rank){
 int index;
 printf("Rank: %d, elements: ", rank);
 for(index=0; index<size; index++){
      printf("%f \t",array[index]);
 }

 printf("\n");
}
int main (int argc, char* argv[]) {

     int rank, root, size, index;
     int N = 2;
     float rcvBuffer; 
     float localmax;

     MPI_Status status;  
     MPI_Init (&argc, &argv);      /* starts MPI */
     MPI_Comm_rank (MPI_COMM_WORLD, &rank);        /* get current process id */
     MPI_Comm_size (MPI_COMM_WORLD, &size);




     root = 0;
     float *array = (float *)malloc(sizeof(float)*N);

     for(index=0; index<N; index++) {
          // i hv to create between 0 and 1. so need to modify
          srand(rank); // to generate different seed value
          localmax = random()/100000000;
          array[index] = localmax;
          MPI_Reduce(&localmax, &rcvBuffer, 1, MPI_FLOAT, MPI_MAX, root, MPI_COMM_WORLD);

          if(rank==root) {
          printf("Process: %d MPI_MAX result is %f \n", rank, rcvBuffer);
       }
     }
     printArray(array, N, rank);

     MPI_Finalize();

     return 0;
}

here is the output:

Rank: 3, elements: 12.000000    12.000000
Rank: 2, elements: 15.000000    15.000000
Rank: 1, elements: 18.000000    18.000000
Process: 0 MPI_MAX result is 18.000000
Process: 0 MPI_MAX result is 18.000000
Rank: 0, elements: 18.000000    18.000000

The program is returning exactly the same value for localmax for all iteration. I am not sure why it is happening. Somehow I doubt the MPI_Reduce() call in side the for loop. So basically I want to know two things 1. Why random() is not returning the random value each time? 2. is it fine to call MPI_Reduce() multiple times in the for loop?




how to sort in random a large file

I have a big txt file ( list of coupon separate by a comma) the coupon are in an order list, I need to randomise it. But my file is too big ( around 16GB), the unix command sort cannot manage it - memory issue). any idea how I can randomised it in another way?




Rand() generating different values when used in valgrind

I'm trying to randomly generate rooms in a two-dimensional array of size 100x100. If the room being generated collides with an already existing room, it generates new points for the room. The generation code makes sense conceptually, but when I try to run, the program loops endlessly, and checking the log reveals why.

Room created successfully with dimensions x=0, y=0, width=976761120, height=809120052

For some reason, at lines 65-68, inside create_room(), the width and height for the room are being randomly assigned huge numbers, when they should be between 1 and 11. Just for fun, I ran the program through Valgrind using the options --track-origins=yes -v, and I what I found surprised me. Suddenly, the program would run!

Room created successfully with dimensions x=0, y=0, width=0, height=0

While still not exactly what I wanted, this at least prevents an infinite loop of collisions being detected with an impossibly huge room.

So, my question is, why is the code generating such large numbers when executed normally, but generate smaller numbers when in Valgrind?

Here's the code for the program.

#include <time.h>
#include <stdlib.h>
#include "global.h"
#include "draw.h"
#include "log.h"
#include "generate.h"
#define NUM_ROOMS 10
#define ROOM_SIZE 10
#define MAP_HEIGHT 100
#define MAP_WIDTH 100

static struct ROOM* create_room (unsigned int);

struct ROOM {
    int x, y, width, height; 
    int feature;
};

struct ROOM* rooms[NUM_ROOMS] = {NULL};

static FILE* gen_log;

static WINDOW* gen_window;

int** generate_dungeon(unsigned int seed){
    char* log_entry = malloc (80);
    int i = 0, j, k;
    gen_window = create_window (0, 0, LINES, COLS);

    gen_log = log_open (GEN_LOG);
    if (seed == 0){
        time_t t;
        seed = time (&t);
    }
    srand (seed); 
    for (int i = 0; i < NUM_ROOMS; i++){
        rooms[i] = create_room (seed);
        sprintf (log_entry,"Room created successfully with dimensions x=%d, y=%d, width=%d, height=%d\n", rooms[i]->x, rooms[i]->y, rooms[i]->width, rooms[i]->height);
        LOG_DEBUG (gen_log,log_entry);
    }
    LOG_DEBUG(gen_log, "Beginning to draw rooms\n");
    for (i=0;i < NUM_ROOMS;i++){
        sprintf (log_entry, "Drawing room %d\n", i);
        LOG_DEBUG (gen_log, log_entry);
        for (j = rooms[i]->y; j < rooms[i]->y + rooms[i]->height; j++){
            for (k = rooms[i]->x; k < rooms[i]->x + rooms[i]->width; k++){
                sprintf (log_entry, "Clearing %d,%d]\n", j,k);
                LOG_DEBUG (gen_log, log_entry);
                map_array[j][k] = 1;
            }
        }
    }
    destroy_window (gen_window);
}

static struct ROOM* create_room (unsigned int seed){
    int i = 0, flag; 
    srand (seed);
    if (rooms[0] == NULL)
        flag = 0;
    else
        flag = 1;
    char* log_entry = malloc (80);
    struct ROOM* new_room = malloc (sizeof(struct ROOM));
    while (flag){
        draw_notify (gen_window, "Creating room\n");
        new_room->x = (rand() % MAP_WIDTH);
        new_room->y = (rand() % MAP_HEIGHT);
        new_room->width =  (rand() % ROOM_SIZE + 1);
        new_room->height = (rand() % ROOM_SIZE + 1);

        sprintf (log_entry, "New room created with points x=%d, y=%d,width=%d, height=%d\n", new_room->x, new_room->y, new_room->width, new_room->height);
        LOG_DEBUG (gen_log, log_entry);
        draw_notify (gen_window, "Log entry made\n");

        if (new_room->x + new_room->width >= MAP_WIDTH || new_room->y + new_room->height >= MAP_HEIGHT){
            LOG_DEBUG (gen_log, "Room out of bounds\n");
            continue;
        }
        i=0;
        draw_notify(gen_window, "Entering loop\n");
        while (rooms[i] != NULL && i < NUM_ROOMS){
            sprintf (log_entry, "Testing room %d\n", i);
            draw_notify (gen_window, log_entry);
            LOG_DEBUG(gen_log, log_entry);
            if (new_room->x < rooms[i]->x + rooms[i]->width && 
                new_room->x + new_room->width > rooms[i]->x && 
                new_room->y < rooms[i]->y + rooms[i]->height &&
                new_room->y + new_room->height > rooms[i]->y){
                    sprintf (log_entry, "Collision detected with room %d\n", i);
                    draw_notify (gen_window, log_entry);
                    LOG_DEBUG (gen_log, log_entry);
                    flag = 1;
                    break;
            }
            else{
                sprintf (log_entry, "Room %d passed.\n", i);
                flag = 0;
                i++;
            }
        }
        draw_notify(gen_window, "Exited loop\n");
    }
    return new_room;
}




Selecting a Random Value from dictionary in constant time in Python 3?

I know that you can select a random value from a dictionary in several ways.

In Python 2:

random.choice(d.keys())

In Python 3:

random.choice(list(d.keys()))

Nonetheless, both approaches require a transformation, i.e. linear time O(n), to a list before the random selection. For example, I know that in Python 3 d.keys() returns an iterator and I am guessing that in Python 3 the list is created internally from the dictionary.

Is it possible to select a value from a dictionary in constant time, i.e. O(1)?




undefined reference to `'srandom'`

Why am I getting this error in lines 8 and 9?:

8 undefined reference to `srandom'
9 undefined reference to `srandom'

Code:

#include <stdio.h>
#include <stdlib.h>
#define RNG_SEED 9061

int main()
{
    long num = 0;
    srandom(RNG_SEED);
    num = srandom();

    printf("%ld", num);

    return 0;
}




Will Math.random show speed?

Can I use Javascript to throw the computer a bunch of random mathematical equations, then have it tell me the time taken for the operation?

Will this give a true and accurate representation about the speed of a computer?

I created a sample Javascript code just to document.write numbers up till 50,000.

var start = new Date().getTime();

document.write("<h1>Start</h1><br><h3>Time taken:</h3>");

for (i = 0; i <= 50000; ++i) {               
document.write(i+"\n");
}

var end = new Date().getTime();
var time = end - start;

document.write("<h1>Success.</h1>");



alert("For the program to execute, it took this computer... \n\n" + time + " milliseconds.\n\nOperation was SUCCESSFUL. ✓");



Javascript-esq random floating point number 0-1 in Racket?

I've checked out the docs for this on docs.racket-lang.org, and looked all over the internet for a possible implementation of this, but all I'm looking for is a random number generating function that generates a number between 0 and 1. For instance, in Javascript:

> Math.random()
0.16275149723514915

I'm looking for this in Racket, and I'd implement it if I could, but I just don't have the chops (yet).




The scenes in the Asn2 Scenes link on the Web Page represents an island (yellow squares) surrounded by water

The scenes in the Asn2 Scenes link on the Web Page represents an island (yellow squares) surrounded by water (blue squares). There is a cat on the island (brown square) and a bridge leading to safety (black square). A drunk mouse is placed in the center of the island. The motion of the mouse is guided by the following rules: • The mouse is allowed to move one square at a time, either horizontally or vertically (no diagonal moves). • A random number between 0 and 3 inclusive is used to define the direction of the next move (0 for North, 1 for East, 2 for South and 3 for West). • The mouse drowns if it : o hits water, o dies of starvation if it makes more than 100 moves, or o gets eaten by the cat. • The mouse escapes if it hopefully crosses the bridge. Write a program to make the mouse move randomly across the island. The program should run from the start several times (random number of runs) to count the number of times the mouse drowns, escapes or dies. Your program should produce a histogram representing the statistics of the runs.




Generate a Random Number that Stays for more than one PHP Process?

I have done some research on this and discovered the rand(), srand(), and mt_srand() yet they don't work too well for me.

I want PHP to generate a random ID (number) and then have it stay that way no matter how many times you refresh the page. I suppose this could be done with incrementing operators or session variables? Cookies perhaps?




How to randomize the sql result set from a two tables?

I have two tables

Table1 person:
-person_id
-name

Table2 expertise:
-expertise_id
-person_id
-expertise_name

What I want to achieve is to return 5 random persons with a corresponding 2 random expertise of that person. So far I can return all the persons and all their expertise.

SELECT * FROM person p, expertise e WHERE e.person_id = p.person_id

Can anyone help me on this? Thank you in advance.




Simulating Random numbers [on hold]

INITIAL_SEED=21092015;
simulation.init(INITIAL_SEED);
simulation.setDuration(3600) ; // seconds
log=simulation.run();
// simulation ends and returns the log file
slices=36;
rMsgs=list();
for i = 0; i < slices; i + + do
aSlice=log.slice( i · 100, ( i + 1) · 100);
rMsgs.add(aSlice.extract(’Received messages’));
print mean(rMsgs)

Can someone explain any flow or possible issue?




Generate random numbers in android for new album

Generate random numbers without duplicates in android while creating new Album and store in SQlite.




vendredi 25 septembre 2015

How Do I get a Random Variable Based on Time in Java

I am trying to make a program that picks random numbers between 1 and 0. However, when I run the program, I get the same output over and over again (20 times!). How might I go about fixing this? I have heard that Math.random() is more biased than random().




How to draw without replacement to fill in data set

I am generating a data set where I first want to randomly draw a number for each observation from a discrete distribution, fill in var1 with these numbers. Next, I want to draw another number from the distribution for each row, but the catch is that the number in var1 for this observation is not eligible to be drawn anymore. I want to repeat this a relatively large number of times.

To hopefully make this make more sense, suppose that I start with:

id
1
2
3
...
999
1000

Suppose that the distribution I have is ["A", "B", "C", "D", "E"] that happen with probability [.2, .3, .1, .15, .25].

I would first like to randomly draw from this distribution to fill in var. Suppose that the result of this is:

id    var1
1     E
2     E
3     C
...   
999   B
1000  A

Now E is not eligible to be drawn for observations 1 and 2. C, B, and A are ineligible for observations 3, 999, and 1000, respectively.

After all the columns are filled in, we may end up with this:

id    var1  var2  var3  var4  var5
1     E     C     B     A     D
2     E     A     B     D     C
3     C     B     A     E     D
...        
999   B     D     C     A     E
1000  A     E     B     C     D

I am not sure of how to approach this in Stata. But one way to fill in var1 is to do something like:

gen random1 = runiform()
replace var1 = "A" if random1<.2
replace var1 = "B" if random1>=.2 & random1<.5
etc....




How to fill svg with a random color?

I am using this code but I'd like my fill and stroke color lo be selected randomly from an array. This is my css:

 <style>          
      #svg.clickit .logo {
          fill: #002100;
          stroke: #002100;
          transition: 1s;
      }
  </style> 




Python: Choose random line from file, then delete that line

I'm new to Python (in that I learned it through a CodeAcademy course) and could use some help with figuring this out.

I have a file, 'TestingDeleteLines.txt', that's about 300 lines of text. Right now, I'm trying to get it to hand me 10 random lines from that file, then delete those lines.

The issue is, when Python reads a file, it reads that file and once it gets to the end, it won't go back and delete the lines. My current thinking was that I could write the lines to a list, then reopen the file, match the list to the text file, and if it finds a match, delete the lines.

My current problem is twofold:

  1. It's duplicating the random elements. If it picks a line, I need it to not pick that same line again. However, using random.sample doesn't seem to work, as I need those lines separated out when I later use each line to append to a URL.
  2. I don't feel like my logic (write to array->find matches in text file->delete) is the most ideal logic. Is there a better way to write this?

    import webbrowser
    import random
    
    """url= 'http://www.google.com'
    webbrowser.open_new_tab(url+myline)""" Eventually, I need a base URL + my 10 random lines opening in each new tab
    
    def ShowMeTheRandoms():
        x=1
        DeleteList= []
        lines=open('TestingDeleteLines.txt').read().splitlines()
    for x in range(0,10):
        myline=random.choice(lines)
        print(myline) """debugging, remove later"""
        DeleteList.append(myline)
        x=x+1
        print DeleteList """debugging, remove later"""
    ShowMeTheRandoms()
    
    



TI-84 Plus Random Number Generator Algorithm

Edit: my main question is that I want to replicate the TI-84 plus RNG algorithm on my computer, so I can write it in a language like Javascript or Lua, to test it faster.

I tried using an emulator, but it turned out to be slower than the calculator.

Just for the people concerned: There is another question like this, but answer to that question just says how to transfer already-generated numbers over to the computer. I don't want this. I already tried something like it, but I had to leave the calculator running all weekend, and it still wasn't done.




Limit an intStream with a condition [duplicate]

This question already has an answer here:

I'm trying to make an array of random ints like this:

static int[] randomInts (int size, int randomNumberOrigin, int randomNumberBound)
{
    return ThreadLocalRandom.current()
            .ints(size, randomNumberOrigin, randomNumberBound)
            .toArray();
}

The array would be like this:

[1, 8, 4, 4, 9, 6, 0, 9, 0, 5, 3, 6, ... ]

The task is to limit the stream to the first found zero so that the array would be like this:

[1, 8, 4, 4, 9, 6, 0]

Is there a way?




generating unique row and column in 2 dimensional array

I am randomly filling a 2 dimensional array but i want to have the numbers generated in each row and column to be unique. Here is the code i have used

int[][] values = new int[3][3];

    Random randomGenerator = new Random();
    for (int i = 0; i < values.length; i++) {

        int[] sub = values[i];
        for (int x = 0; x < sub.length; x++) {
            sub[x]= randomGenerator.nextInt(4);;
        System.out.print(sub[x] + " ");
        }
        System.out.println();
    }

My current output is and this might change as the numbers generated are random

2 2 2 
3 2 0 
0 2 1 

But i am expecting something like this

1 2 3 
3 1 2 
2 3 1 




Variance of a complex signal

I have the following signal in MATLAB:

a = randn(1,50) + 1i*randn(1,50)

What would be the variance of this signal? I would appreciate if someone clears my doubt!




Check for all similar domain names

I have this python script :

import string
import random
import difflib

def generate_similar(domain):
# Generates similar name by substituting vowels
similar_word = []
for char in domain:
 if char.lower() in 'aeiou':
  similar_word.append(random.choice('aeiou').lower())
 else:
  similar_word.append(char)
return ''.join(similar_word)

for i in range(1,20) :
 ratio = 0
 while ratio < 0.83:
  dom = generate_similar("potatoes")
  ratio = difflib.SequenceMatcher(None,"potatoes",dom).ratio()
 i =i +1
 print dom

And When I run it on terminal I get the following output :

potutoes

patatoes

potatues

potataos

potatees

potatoos

potatoos

potatoes

potatoos

patatoes

pitatoes

pitatoes

potatoos

pitatoes

potetoes

petatoes

potateis

potatuos

potateas

However,I need to generate similar domain names which can be taped by mistake.

For example if we gave potatoes.com. it should create all the permutations of potatoes like, pottatoe, pottatoes,potatos e.t.c.




Non repetitive random number generator in c

I want to make a program that will give me 4 random numbers in the range 1 - 20 without any of them being the same. It does give me 4 different random numbers but every couple of tries 2 numbers are the same. I don't want that. Here's my code:

int main(){
int g;
srand(time(0));
start:;
scanf("%d",&g);
switch(g){
case 1:RNG_4_10();
break;
default:exit(0);
break;
}
goto start;
}

int RNG_4_10(){

int a,n,i,c;
for(c=0;c<10;c++){
printf("\n");
for(i=0;i<4;i++){
        a = (rand() % 20 + 1);      //give a random value to a;
        n = a;                      //assign n the value of a;
        while(a == n){
        a = rand() % 20 + 1;                  
        }
        printf("%d\t",a);
}
}
}




How to get AutoFixture create an integer that is >0, and not another number?

I want AutoFixture generate two integers, and for the second number, I don't want it to be 0, or the previous generated number. Is there a way to tell AutoFixture to honor that "requirement".

Looking at RandomNumericSequenceGenerator, I looks like the lower limit is 1, so I might not have to specify the first requirement. Next, I was looking at the "seeding" option, but as indicated in this answer, it won't be used for a number, by default.

Is there something I'm overlooking here?




Batch script for starting random .bat file from a certain folder

Problem is this,i have one folder named "abc" with several batch files and they are named like this: abc1.bat

abc2.bat

abc3.bat

abc4.bat

and so on...Now i need a script that will randomly run one of those batch files when i click it.That Script i need will be stored in the same folder by the name "abcRandom.bat" or something similar,name isn't of big importance. I have no experiance in batch scripting,so any help i get is highly appretiated.I asume that it wont be a big deal for you guys here to solve it at all,so thanks in advance,CHEERS.




jeudi 24 septembre 2015

Generating two ( or multiple) uniformly distributed random numbers c++

I would like to generate several uniformly distributed random numbers in the same pass. So far I have a "standard" function for generating a random number

double generateRandomNumber()
{
    srand((unsigned)time(NULL));
    double r=((double)rand()/(double)RAND_MAX);
    return r;
}

how ever when in main I call it like that:

# include <iostream>
# include <string>
# include <cmath>
# include <ctime>

int main()
{

    // generate random number
    double rr1=generateRandomNumber();
    double rr2=generateRandomNumber();
    cout << rr1 << endl;
    cout << rr2 << endl;
    return 0;
}

I get that both numbers are the same ( I guess its the time limitations of seconds), anyways, this is something I would like to generelize to multiple random numbers.

Can anyone suggest a better way? maybe using a different method or library?




Get latest "x.png" from a folder

I have a "take a screenshot" feature in my program. I am taking the screenshot and saving it with this code:

Bmp.Save(dir & "\MyApp\Screenshot" & random & ".png")

dir is Documents. and the random is this

random = CInt(Math.Ceiling(Rnd() * 99999)) + 1

But I don't want to save like this. I want to save in order. I want to check the folder, get the latest name and add +1 to it. Like If the latest one is Screenshot-17.png, save it as Screenshot-18.png.

I am thinking a substring but I don't know how can I get the latest png file from a folder.

Full code is here:

    Dim dir As String
    dir = System.Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments)
    Dim random As Integer
    random = CInt(Math.Ceiling(Rnd() * 99999)) + 1
    Dim pathh As String
    pathh = dir & "\MyApp\"
    If (Not System.IO.Directory.Exists(pathh)) Then
        System.IO.Directory.CreateDirectory(pathh)
    End If


    Dim Bmp As New Bitmap(WebControl1.ClientRectangle.Width, WebControl1.ClientRectangle.Height)
    Dim gBmp As Graphics = Graphics.FromImage(Bmp)
    gBmp.CopyFromScreen(WebControl1.PointToScreen(New Point(0, 0)), New Point(0, 0), New Size(WebControl1.Width, WebControl1.Height))
    Bmp.Save(dir & "\MyApp\Screenshot" & random & ".png")


    NotifyIcon1.ShowBalloonTip(1500, "Click here to see your screenshot!", "Saved to Documents/MyApp/Screenshot" & random & ".png!", ToolTipIcon.Info)
    baloon = pathh & "Screenshot" & random & ".png"




Random number between INT_MAX & INT_MIN

Well I feel my question is bit more complex compared to other questions. I realized this while trying to solve it.

I tried using

int number = rand() % (INT_MAX - INT_MIN + 1) + INT_MIN;
rand() % (INT_MAX + INT_MIN + 1) + rand() % INT_MIN;

However, I got floating point exception 8 error. No warnings, that's really strange!

Also, from time.h, I used srand((unsigned)time(NULL)) for new random number every time I execute my code.

But whatever I try either I get incorrect results or floating point exception.

I am really curious as to overflow & underflow, how it's happening and can such a random number be actually generated?

I basically want to generate a number in C greater than INT_MIN and lesser than INT_MAX.

I tried lots of logic but I got incorrect result.




VBA Random number generation with user defined mean & Std dev

I am attempting to generate normally distributed random variables. I have a user input for the total number of variables (M), the number of sets of random variables (N). I am using the formula =NORM.INV(RAND(),0,1) and it works fine. However when I want to have a user input mean and std dev, I declare a variable for each. The cell that is bring referenced by the variable I put say a 0 for Mean and 1 for StdDev. The code will run, however the output of the random variables is the good old #NAME?. I do not understand why referencing a cell if just entering the formula on the worksheet works, but in VBA is does not.

Any help would be appreciated. I am probably overlooking something basic. Cheers

The Code is as follows.

Sub RandomNorm()

Dim WS_W As Worksheet: Set WS_W = ActiveWorkbook.Worksheets("Working") ' Sheet for calculations
Dim WS_Rand As Worksheet: Set WS_Rand = ActiveWorkbook.Worksheets("Random Generated") ' Sheet for random variable generation

Application.ScreenUpdating = False

Dim N As Long: N = WS_W.Range("B3").Value ' Number of random variable sets
Dim M As Long: M = WS_W.Range("C3").Value ' Number of simulations

WS_W.Select

Dim Mean As Double: Mean = WS_W.Cells(3, 4).Value ' Mean of Normal distribution
Dim StdDev As Double: StdDev = WS_W.Cells(3, 5).Value ' Standard Deviation of normal distribution

Dim i As Long
Dim j As Long

WS_Rand.Select
WS_Rand.Cells.Select
Selection.ClearContents ' Prepare for generation by clearing Generation sheet

For i = 1 To N
    For j = 1 To M
        WS_Rand.Cells(j, i).Select
        ActiveCell.FormulaR1C1 = "=NORM.INV(RAND(),Mean,StdDev)"
    Next
Next
End Sub




Generate Array of Unique Random Numbers within Inclusive Range

I am trying to write a function in Apple Swift (iOS) that will generate any given amount of unique random numbers that are within a given inclusive range, say between 0 and 10. So if I say I want 5 unique random numbers between 0 and 10, it would return an array with [7, 10, 2, 3, 0] or [7, 10, 2, 8, 0], etc.

I have that part working with:

// Returns an array of unique numbers
func uniqueRandoms(numberOfRandoms: Int, minNum: Int, maxNum: UInt32) -> [Int] {

    var uniqueNumbers = [Int]()

    while uniqueNumbers.count < numberOfRandoms {

        let randomNumber = Int(arc4random_uniform(maxNum + 1)) + minNum
        var found = false

        for var index = 0; index < uniqueNumbers.count; ++index {
                if uniqueNumbers[index] == randomNumber {
                    found = true
                    break
                }
        }

        if found == false {
            uniqueNumbers.append(randomNumber)
        }

    }

    return uniqueNumbers
}

print(uniqueRandoms(5, minNum: 0, maxNum: 10))

Now I want to add the ability to blacklist a single number within that range that I don’t want. Say I still want 5 unique random numbers between 0 and 10 BUT I don’t want it to ever include 8.

That part causes an endless loop (25%+ of the time or more) and I can’t figure out why? Here’s what I have:

var blackListNum = 8

// Returns an array of unique numbers
func uniqueRandoms(numberOfRandoms: Int, minNum: Int, maxNum: UInt32, checkBlackList: Bool = false) -> [Int] {

    var uniqueNumbers = [Int]()

    while uniqueNumbers.count < numberOfRandoms {

        let randomNumber = Int(arc4random_uniform(maxNum + 1)) + minNum
        var found = false

        for var index = 0; index < uniqueNumbers.count; ++index {
            if checkBlackList == false {
                if uniqueNumbers[index] == randomNumber {
                    found = true
                    break
                }
            } else {
                if uniqueNumbers[index] == randomNumber || uniqueNumbers[index] == blackListNum  {
                    found = true
                    break
                }
            }
        }

        if found == false {
            uniqueNumbers.append(randomNumber)
        }

    }

    return uniqueNumbers
}

print(uniqueRandoms(5, minNum: 0, maxNum: 10, checkBlackList: true))

I understand that my function is far from efficient because I am just starting to learn Swift but I want to keep it similar as I want to understand how it works. I don’t want to simply copy and paste someone else’s more efficient solution and not understand it. I have just learned variables, constants, if, while, for, etc. statements and the other basics and want to keep it to that.




Randomizing a list of tuples without random.shuffle() python

I have a list of tuples looking like... deck=[(1,'clubs'),(1,'hearts')...and so on to (13,'diamonds').

How do I randomize this list into something like...

[(5,'spades'),(12,'clubs'),(3,'clubs'),... and so on?

I have tried using random.randint() and nothing seems to work. And I can not use random.shuffle()




Insert random string into field with MySQL UNI key

The task is to fill the table with N rows of random unique data.

I have the next MySQL table structure:

+----------+--------------+------+-----+---------+----------------+
| Field    | Type         | Null | Key | Default | Extra          |
+----------+--------------+------+-----+---------+----------------+
| id       | int(11)      | NO   | PRI | NULL    | auto_increment |
| username | varchar(100) | NO   | UNI | NULL    |                |
+----------+--------------+------+-----+---------+----------------+

Username field has string type but if the script will insert numbers its OK.

Theres is dirty solution with INSERT IGNORE, that can make 1000 random rows with endless cycle.

INSERT IGNORE INTO table (id,username) VALUES ('', 1 + ceil(rand() * 1000));

Also, I can use ON DUPLICATE KEY structure, but this 2 solutions are not OK.

I want to make the query, that generate unique username which will be unique and will be inserted from the first time.

So, I tell the script to add 1m of rows and it will insert 1m of unique data without any infelicities.

Any ideas? Thanks.




Is there a numpy shortcut for generating array of floats within a desired limit?

If I need an array containing 5 rows of 2 floating point numbers whose values are between 0 and 100, I would normally do this:

coordinates = 100 * np.random.rand(10, 2)

It would produce something similar to the following output:

array([[ 18.12298022,  23.06041984],
       [ 79.29855044,  25.41550915],
       [ 79.61747255,  35.09879784],
       [ 63.75090875,  95.88711405],
       [ 23.87727443,  97.02211991]])

This computation requires generating the random sequence irst and then multiplying it with the desired upper limit (100). Is there a builtin function in numpy's random library that can do this (presumably faster)? I couldn't find one from the docs.




Generate similar domain names with Python

I am looking for a function which generates similar domain names.

For example domains which are similar to "amazon" :

amazin

amazan

amazen

amaznn

amozon

...




PHP MySQL select random value from table

I am trying to get a random city from the location table but is not working, I have searched over Stack and tried many ways still not getting it work.

<?php  include "../database.php"?>
<?php

$sSQLQuery = mysql_query("SELECT city FROM location ORDER BY RAND() LIMIT 1;");

$aResult = mysql_query($sSQLQuery); 

?>

<span class="h3"><?php echo $aResult ?></span>




Getting cryptographically secure random numbers in C++ on iOS

I'm working on an iOS app that is written in Objective-C and C++. In the C++ part, I need cryptographically secure random numbers.

  1. As I understand the iOS security model, there is no way to access /dev/random directly. Is that correct?

  2. The official way to get secure random numbers is SecRandomCopyBytes. Sadly, this is an Objective-C interface. Is there a way to use this interface from C++, ideally without resorting to Objective-C++?

There's also arc4random, but I'm reluctant to use anything that's based on RC4 nowadays...




randomly display content in a div after refresh

i want to have a div that randomly displays content after refresh. i found a code that worked kinda, but it doesnt 100% work, so I'm trying to find the error here.

I was asked to post this as a new topic after using the code of this randomly display a div class using JQuery topic, but having it not work properly.

code in the header:

window.onload=function() {
  var E = document.getElementsByClassName("item");
  var m = E.length;
  var n = parseInt(Math.random()*m);
  for (var i=m-1;i>=0;i--) {
  var e = E[i];
  e.style.display='none';
  }
  E[n].style.display='';
}

in the body i have the following

<div class="item">Lorem ipsum dolor</div>
<div class="item">Lorem ipsum dolor sit amet</div>
<div class="item">Lorem ipsum </div>
<div class="item">Lorem </div>

when loading the page it displays all of the item-divs and then after the rest is loaded (the divs are at the very top) all except for one are hidden.

why is this happening? how does the code need to be changed so the other contents arent displayed at all?