mercredi 30 novembre 2016

for loop is crashing on big number

I have a problem. I have to write a program that counts the collisions of the table of randomly generated numbers(collision test). For example table [1,2,2,3,4,5,5,5,6] has 3 collisions. Here is my code: And my problem is that whenever i try to increase number n to for example int n = 5191401 my program crashes. What is happening? Why does it stop working? I need really big ammount of random numbers (like 10^14)

    #include <iostream>
    #include <gsl/gsl_rng.h>
    #include <stdlib.h>
    #include<cmath>
    using namespace std;
    int compare(const void * a, const void * b){
    return ( *(int*)a - *(int*)b );
    }
   int main (void)
   {
unsigned int seed=10540000;
gsl_rng * r=gsl_rng_alloc (gsl_rng_minstd);
gsl_rng_set(r,seed);
gsl_rng_env_setup();
int lPrzedzialow=400000000;
int n = 519140;
int z,lKolizji=0;
int lwKomorkach[n-1];
double dlPrzedzialu=1./(lPrzedzialow);
for (int i = 0; i < n; i++)
{
    lwKomorkach[i]=floor(gsl_rng_uniform (r)/dlPrzedzialu)+1;

}
qsort (lwKomorkach, n, sizeof(int), compare);
for(z=0;z<=n-1;z++)
{
        if(lwKomorkach[z+1]==lwKomorkach[z]){lKolizji++;}
}
cout<<endl<<lKolizji<<endl;
gsl_rng_free (r);
return 0;
}




Random samples but grouped by certain values in columns

I've looked everywhere but can't find someone doing this. I imagine there must be a way in R though.

I have a dataset of around 200k rows that looks like this:

Report ID | Month | Day | Year | Location ID | comments
1             4       1    2015       200          blah blah blah
2            11       3    2014       100          blah blah blah 
3             4       5    2015       203          blah blah blah
4             8      30    2012       204          blah blah blah
5            11       5    2013       204          blah blah blah
6            11       1    2015       100          blah blah blah  
7            11      10    2013       204          blah blah blah

I need to create a random sample of report IDs that has an even distribution of location IDs, year, and months. I know this wouldn't truly be a random sample, but location ID skews pretty heavily to some locations and some months have way more reports than others.

I have tried various sampling and sub setting techniques in R, but they all seem to want to sample the data set as a whole and I've been unable to locate a way where I can ask the sample to provide say 500 report ids for each location. Let alone be able to then say, within this 500, I want an even distribution of years and months. Any suggestions?




Dice Roll Histogram with Loops

I have a problem in my class that I just can't figure out.

This is the question:

The purpose of this quiz is to reinforce the understanding of using loops and counting as well as reviewing the use of random numbers.

Modify the program below to print a histogram in which the total number of times the dice rolls equals each possible value is displayed by printing a character like # that number of times. Two dices will be used in each roll.

Example:

Histogram showing total number of dice rolls for each possible value.

Dice roll statistics (result varies):

2s: ######

3s: ####

4s: ###

5s: ########

6s: ###################

7s: #############

8s: #############

9s: ##############

10s: ###########

11s: #####

12s: ####

~~~~~~~~~~~~~~~~~~~~~

I haven't been able to get the program to print the histogram in the example above.

And this is what I have so far:

    import java.util.Scanner;

    import java.util.Random;

    public class DiceStats {

       public static void main(String[] args) {

          Scanner scnr = new Scanner(System.in);

          Random randGen = new Random();

          int seedVal = 11;

          randGen.setSeed(seedVal);

          // FIXME 1 and 2: Set the seed to the Random number generator


          int i = 0;          // Loop counter iterates numRolls times
          int numRolls = 0;   // User defined number of rolls 


          // FIXME 3: Declare and initiate cariables needed

          int numOnes = 0;
          int numTwos = 0;
          int numThrees = 0;
          int numFours = 0;
          int numFives = 0;
          int numSixes = 0;   // Tracks number of 6s found
          int numSevens = 0;  // Tracks number of 7s found
          int numEights = 0;
          int numNines = 0;
          int numTens = 0;
          int numElevens = 0;
          int numTwelves = 0;
          int die1 = 0;       // Dice 1 values
          int die2 = 0;       // Dice 2 values
          int rollTotal = 0;  // Sum of dice values

          System.out.println("Enter number of rolls: ");
          numRolls = scnr.nextInt();

          if (numRolls >= 1) {
             // Roll dice numRoll times
             for (i = 0; i < numRolls; ++i) {
                die1 = randGen.nextInt(6) + 1;
                die2 = randGen.nextInt(6) + 1;
                rollTotal = die1 + die2;

                // FIXME 4: Count number of sixs and sevens; complete the same for all other possible values
                if (rollTotal == 1) {
                   numOnes = numOnes + 1;
                }
                if (rollTotal == 2) {
                   numTwos = numTwos + 1;
                }
                if (rollTotal == 3) {
                   numThrees = numThrees + 1;
                }
                if (rollTotal == 4) {
                   numFours = numFours + 1;
                }
                if (rollTotal == 5) {
                   numFives = numFives + 1;
                }
                if (rollTotal == 6) {
                   numSixes = numSixes + 1;
                }
                if (rollTotal == 7) {
                   numSevens = numSevens + 1;
                }
                if (rollTotal == 8) {
                   numEights = numEights + 1;
                }
                if (rollTotal == 9) {
                   numNines = numNines + 1;
                }
                if (rollTotal == 10) {
                   numTens = numTens + 1;
                }
                if (rollTotal == 11) {
                   numElevens = numElevens + 1;
                }
                else if (rollTotal == 12) {
                   numTwelves = numTwelves + 1;
                }
                System.out.println("Debugging: Roll " + (i+1) + " is " + rollTotal + " (" + die1 + 
              "+" + die2 + ")");
            }

             // Print statistics on dice rolls
             System.out.println("\nDice roll statistics:");

             // FIXME 5: Complete printing the histogram
             System.out.println("1s: " + numOnes);
             System.out.println("2s: " + numTwos);
             System.out.println("3s: " + numThrees);
             System.out.println("4s: " + numFours);
             System.out.println("5s: " + numFives);
             System.out.println("6s: " + numSixes);
             System.out.println("7s: " + numSevens);
             System.out.println("8s: " + numEights);
             System.out.println("9s: " + numNines);
             System.out.println("10s: " + numTens);
             System.out.println("11s: " + numElevens);
             System.out.println("12s: " + numTwelves);
          }
          else {
             System.out.println("Invalid rolls. Try again.");
          }

         return;
       }
    }

Any help would be very appreciated.




Generating limited amount of random numbers in Perl for a known range

I am a newbie in here and wanted to ask a question that I am not able to find its answer. I have a file which has couple letters as :

letters.txt :

@string1 10 letters

A H K Y M H O L H L

@string2 9 letters

H N U P W X L Y H

I am trying to create a file which will only have random numbers from 20 to 60 for each letter, for each string. My expected output should look like :

output.txt:

@string1

29 27 56 43 39 40 36 48 59 38

@sting2

26 36 39 39 26 51 38 42 42

I have tried this code below while having $minimum as 20 and $maximum as 60:

open ($fh, '>', $fileToLocate) or die;`

my $x = $minimum + int(rand($maximum - $minimum);

print $fh "$x\n";

close $fh;

And it creates only 1 random number in my $fh file, however I want to extract the number of letters in each string (written just before "letter" in identifier, 10 for string1 and 9 for string2 forex.) and create a loop which will give the expected output.

I have tried to this below to create 30 random numbers ranging between 20 and 60, however it did not work out :

my @Chars = ( 20 .. 60);my @Chars = ( 20 .. 60); emy $RandString = join("", @Chars[ map { $x } ( 1 .. 30 ) ]); print $fh "$x\n"; close $fh;

I am sorry if it is too much to ask, but I would very much appreciate if you show me a way to do it.

Thank you so much in advance..




Simple javascript for selecting random element out of array outputting "undefined" on 2 elements (jsfiddle included)

Below is my code, for some reason it outputs undefined for ['6'] & ['7'], all the other ones work. I don't understand what is going wrong.

var array = [
    ['1'],
    ['2'],
    ['3'],
    ['4'],
    ['5'],
    ['6']
    ['7'],
    ['8'],
    ['9'],
    ['10']
];

if(document.getElementById("random-element")) {
    var rand = array[Math.floor(Math.random() * array.length)];
    document.getElementById('random-element').innerHTML = rand;
}

http://ift.tt/2fDrvjB




random number to play mp3 file

First of all - BIG thanks in advance.

I need to put together a one page site for playing random mp3's/wav's from a folder. I saved the files in numbers (1.mp3, 2.mp3, etc.) so that I won't have to list each one in the script. So the idea is that on page load, the script randomise a number and a html5 audio player will play the mp3 that corresponds to that number.

I tried several variations, but so far I can't get it right. So I figured better start from scratch again.

I'm not a programmer though, just basic stuff.

thanks again for any help.




system verilog - implementation of randomize()

I have to implement randomize() function in systemVerilog because the tool I use (model sim) doesn't support this function.

I implemented a basic function in a class with the following member:

   bit [15:0]  data_xi;
   bit [15:0]  data_xq;

the basic random function:

   //function my_randomize
    function int my_randomize(int seed);
       int temp1, temp2;
      // temp = $urandom_range(1,11);
       temp1 = (($urandom(seed)) + 1);
       data_xi = temp1 - 1;
       temp2 = (($urandom(seed)) + 1);
       data_xq = temp2 - 1;
       if(temp1 != 0 || temp2 != 0 )
     return 1;
       else
     return 0;
    endfunction: my_randomize

Now I have to change it to global function which suppose to behave like randomize() with constraints.

How can I implement this?




How can I use Linux getrandom system call to generate a random number within a range?

I have the following piece of code

#include <unistd.h>
#include <sys/syscall.h>
#include <linux/random.h>

unsigned long int s;
syscall(SYS_getrandom, &s, sizeof(unsigned long int), 1);
std::cout << s << std::endl;

According to GETRANDOM(2) it returns random numbers from /dev/random or /dev/urandom with high entropy.

How can I use it to return numbers within a range? The range I'm using is [0 - 2^125]




mardi 29 novembre 2016

C++ ArraysWrite a program that creates an array of five random integer numbers and then displays the numbers

I'm in the beginning stages of learning how to program and I'm teaching myself.

Write a program that creates an array of five random integer numbers and then displays the numbers. The program should use an array declared as a global variable. Two functions voidArray and voidPrint

Initializes an array with random numbers between 1 and 1000 Print the of array

I'm really confused on how I would write code for the voidArray and main functions and the answer is not in my book.




How does one randomly pick an item from a set such that it is not a particular variable

I am trying to generate an integer from the set [1,2,3] such that it is not the variable inputted into the function. I have already imported the module random. So, if I inputted 3, it would randomly pick 1 or 2. Thank you for the help.




Generate random numbers for two different objects [duplicate]

This question already has an answer here:

How can we make a constructor generate a random number whenever we call a new object ? For example in this code :

class Box
{
public:
Box()
{ 
    number = rand() % 9;
};

int number; 
};

int main()
{
    Box b1;
    cout << b1.number;
    Box b2; 
    cout << b2.number; 
    }

I always get the same number value for b1 and b2




How to generate line of 4 letters from choice of 6 letters in c++

I need a way to generate a line string of 4 letters from the following 6 letters R,V,B,J,M,C, the same letter can be string multiple time since itsending you my current code would be useless since the rest of the code has nothing to do with this

Help would be Greatly appreciated !




Variabel gives everytime a seemingly random answer

I'm learning C++ and tried an exercise on Project Euler (Problem 2) to practise my C++ abilities. Everything compiles fine, but everytime a certain variable is defined, it starts with a seemingly random integer. Here's the code:

#include <iostream>
#include <Windows.h>

int fibonacci(int tripoloski){
    int first = 1;
    int second = 1;
    int next;
    int result;
    std::cout << first << std::endl;
    std::cout << second << std::endl;
    for(next = 1; next < tripoloski; ){
        result = result + first + second;
        next = first + second;
        first = second;
        second = next;
        std::cout << next << std::endl;
        std::cout << "WHOOP: " << result << std::endl;
    }
    return result;
}

int main(){
    int a = fibonacci(4000000);
    std::cout << "RESULT: " << a << std::endl;
    system("pause");
    return 0;
}

And here's an output log (ignore the "tripoloski" and "WHOOP" :) ):

1
1
2
WHOOP: 1075637419
3
WHOOP: 1075637422
5
WHOOP: 1075637427
8
WHOOP: 1075637435
13
WHOOP: 1075637448
21
WHOOP: 1075637469
34
WHOOP: 1075637503
55
WHOOP: 1075637558
89
WHOOP: 1075637647
144
WHOOP: 1075637791
233
WHOOP: 1075638024
377
WHOOP: 1075638401
610
WHOOP: 1075639011
987
WHOOP: 1075639998
1597
WHOOP: 1075641595
2584
WHOOP: 1075644179
4181
WHOOP: 1075648360
6765
WHOOP: 1075655125
10946
WHOOP: 1075666071
17711
WHOOP: 1075683782
28657
WHOOP: 1075712439
46368
WHOOP: 1075758807
75025
WHOOP: 1075833832
121393
WHOOP: 1075955225
196418
WHOOP: 1076151643
317811
WHOOP: 1076469454
514229
WHOOP: 1076983683
832040
WHOOP: 1077815723
1346269
WHOOP: 1079161992
2178309
WHOOP: 1081340301
3524578
WHOOP: 1084864879
5702887
WHOOP: 1090567766
RESULT: 1090567766
Press any key to continue . . .

second output log...:

1
1
2
WHOOP: 702745584
3
WHOOP: 702745587
5
WHOOP: 702745592
8
WHOOP: 702745600
13
WHOOP: 702745613
21
WHOOP: 702745634
34
WHOOP: 702745668
55
WHOOP: 702745723
89
WHOOP: 702745812
144
WHOOP: 702745956
233
WHOOP: 702746189
377
WHOOP: 702746566
610
WHOOP: 702747176
987
WHOOP: 702748163
1597
WHOOP: 702749760
2584
WHOOP: 702752344
4181
WHOOP: 702756525
6765
WHOOP: 702763290
10946
WHOOP: 702774236
17711
WHOOP: 702791947
28657
WHOOP: 702820604
46368
WHOOP: 702866972
75025
WHOOP: 702941997
121393
WHOOP: 703063390
196418
WHOOP: 703259808
317811
WHOOP: 703577619
514229
WHOOP: 704091848
832040
WHOOP: 704923888
1346269
WHOOP: 706270157
2178309
WHOOP: 708448466
3524578
WHOOP: 711973044
5702887
WHOOP: 717675931
RESULT: 717675931
Press any key to continue . . .

As I said earlier, I just started with learning C++ (about a few days ago), so the answer might be very obvious to you. I would appreciate it if you won't bash (badumm tss) me for it and give me an insightful explanation :)

-ThomThom




Random Number Generation Without Python's in-built ".random" Function

Using Gaussian distribution (Normal distribution) is it possible to generate random numbers in the range of 0,1 without Python's in-built function?

I've tried the Linear Congruential Method and Mersenne Twister Algorithms forked right from GitHub but it's too complex to understand.

I'm also avoiding Numpy or any external libraries for now.

Any Suggestions/links are welcome. Thank you!




Make choice from array semi-randomly based on string

I have this problem. I'd like to make random a choice from array [1,2,3,4] based on arbitrary 6 letter string in such way that this choice is always same if string is same.

So if i have string 'dogdog' function would return always '3' for example, but '4' for 'bigcat' etc.

I think the solution might be first hashing the string. How could one convert hash string into choice from array?




Once I've generated a random Int between a range, how could I assign that integer to each letter in the alphabet?

New to arrays here... I want to get a random integer and set that integer to each individual letter in the alphabet like integer 1 = a. So that I can print a random letter in the alphabet without using a pre-existing java method for random string. I don't want to generate a random string this is the way I need it.

{
  public static void main(String[] args)
  {
    Random Gen = new Random();

    String[] letters = new String[50];

    String alphabet = "abcdefghijklmnopqrstuvwxyz";

    int randomInt = Gene.nextInt(26);

    String second = "" + randomInt;
    System.out.println(second);

    //Not sure what next....
  }
}




Which is the more efficient way to choose a random pair of objects from a list of lists or tuples?

I have got a list of 2d coordinates with this structure:

coo = [(0, 0), (0, 1), (0, 2), (1, 0), (1, 1), (1, 2), (2, 0)]

Where coo[0] is the first coordinate stored in a tuple.

I would like to choose two random coordinates. I can of course use this method:

import numpy  as np
rndcoo1 = coo[np.random.randint(0,len(coo))]
rndcoo2 = coo[np.random.randint(0,len(coo))]

But because I have to repeat this operation 1'000'000 times I was wondering if there is a faster method to do that. np.random.choice() can't be used for 2d array is there any alternative that I can use?




Python battleships random ship placement

Hi I have a program that randomly places ships on the battlefield but I've ran into some problems namely, ships sometimes overlaps or not all of them are placed or none of them are placed. Below is the whole program without class Ship initialized with size parameter.

import random
from Ship import Ship

def make_board(board):
    for x in range(0, 10):
        board.append(["_"] * 10)

def print_board(board):
    for row in board:
        print(" ".join(row))

def random_row(board):
    return random.randint(0, len(board) - 1)

def random_col(board):
    return random.randint(0, len(board) - 1)

def place(ships, board):
    hidden_board = []
    for x in range(0, 10):
        hidden_board.append(["_"] * 10)
    print("jestem w place")
    dir_list = ["North", "South", "East", "West"]
    for x in range(0, len(ships), 1):
        placed = False
        while not placed:
            ship_row, ship_col = random_row(board), random_col(board)
            print(ship_row, ship_col)
            if hidden_board[ship_row][ship_col] == "_":
                hidden_board[ship_row][ship_col] = "C"
                if board[ship_row][ship_col] == "_":
                    direction = random.choice(dir_list)
                    if validate(ships[x], ship_row, ship_col, direction):
                        place_ship(ships[x], ship_row, ship_col, direction)
                        placed = True

def place_ship(ships, ship_row, ship_col, direction):
    size = ships.get_size()
    print(direction)
    if direction == "North":
        for x in range(ship_row, ship_row - size, -1):
            board[x][ship_col] = "S"
    elif direction == "South":
        for x in range(ship_row, ship_row + size, 1):
            board[x][ship_col] = "S"
    elif direction == "East":
        for x in range(ship_col, ship_col + size, 1):
            board[ship_row][x] = "S"
    elif direction == "West ":
        for x in range(ship_col, ship_col - size, -1):
            board[ship_row][x] = "S"

def validate(ships, ship_row, ship_col, direction):
    size = ships.get_size()
    print("Jestem w can_place")
    is_free = True
    if direction == "North":
        if ship_row - size <= 0:
            is_free = False
        else:
            for x in range(ship_row, ship_row - size and is_free, -1):
                is_free = is_free
                board[x][ship_col] = "_"
    elif direction == "South":
        if ship_row + size > 10:
            is_free = False
        else:
            for x in range(ship_row, ship_row + size and is_free, 1):
                is_free = is_free
                board[x][ship_col] = "_"
    elif direction == "East":
        if ship_col + size > 10:
            is_free = False
        else:
            for x in range(ship_col, ship_col + size and is_free, 1):
                is_free = is_free
                board[ship_row][x] = "_"
    else:
        if ship_col - size <= 0:
            is_free = False
        else:
            for x in range(ship_col, ship_col - size and is_free, 1):
                is_free = is_free
                board[ship_row][x] = "_"
    return is_free


if __name__ == "__main__":
    board = []
    make_board(board)
    ships = [Ship(3), Ship(2), Ship(1)]
    place(ships, board)
    print_board(board)
    print("\n")




Generating random positive double is returning negative double value

I have a strange issue (at least for me) with generating random double values. I am doing this:

 Random rndparam = new Random();
 double param1 = rndparam.NextDouble() * (paramUpperBound - paramLowerBound) + paramLowerBound;
 MySheetWrite.Cells[i + 1, 1] = param1;

I am trying to generate more parameters like this (with positive values), however I am getting negative values for few of them (all values for these parameters are negative) and for other parameters, there are also few negative values. There are however few parameters that are generated correctly between upper and lower bound. I am pretty sure that paramUpperBound is allways greater than paramLowerBound.

Also, to generate another parameters I am using rndparam object and these parameters are generated in one for loop.

Thank you for any advices.




lundi 28 novembre 2016

Random number generator giving inconsistent results

I am trying to work out how to add 6 randomly generated numbers to a HashSet. I am getting results but they are inconsistent. Sometimes it prints 6 numbers to the console and other times it prints 5 numbers to the console.

I'm new to this stuff only this morning so I apologize if it is blatantly obvious and thank you for your help.

 HashSet<Integer> GeneratedLotteryNumbers = new HashSet<Integer>();
Random r = new Random();

for(int i=0; i<6; i++){
  GeneratedLotteryNumbers.add(r.nextInt(49));
}

System.out.println(GeneratedLotteryNumbers);




The order of growth of the Fermat test in SICP

The fermat-test procedure presented by Structure and Interpretation of Computer Programs has a theta-of-log(n) order of growth, which has been verified by me and many other people's experiments.

What confuses me is the random primitive procedure in its definition. Does this imply that the order of growth of random is at most theta of log(n)? After some searching work, I'm still not sure whether it's possible to write a pseudorandom number generator whose order of growth is no more than theta of log(n).

Here is the code:

(define (fermat-test n)
  (define (try-it a)
    (= (expmod a n n) a))
  ; Wait a second! What's the order of growth of `random`?
  (try-it (+ 1 (random (- n 1)))))

, where expmod has a theta-of-log(n) order of growth:

(define (expmod base exp m)
  (cond ((= exp 0) 1)
        ((even? exp)
         (remainder (square (expmod base (/ exp 2) m))
                    m))
        (else
         (remainder (* base (expmod base (- exp 1) m))
                    m)))) 

Could you explain this to me?

  • If such a pseudorandom number generator does exist, please show me how it works.
  • If such a pseudorandom number generator does not exist, please tell me how can fermat-test still have a theta-of-log(n) order of growth.



firebase - random query

I am making and application that show a first screen with a bunch of randomly picked data from a node in firebase database.

To present user with different data every time is kind of important for my application

Is there anyway to achieve this in native Android, all snapshots are of same model




Sample an unevenly distributed set for training

I'm training an SGD neural net classifier on a very imbalanced training dataset. To compensate for underepresentated classes, I perform actual training on a set randomly sampled s.t. classes with fewer examples get picked more often.

What is a principled way to pick the volume of the latter set vs the number of epochs it will be run on? Advice much appreciated.




Python Battleships game random ship placement

I found a code academy lesson about battleship game and I'm trying to expand it a little. I added some code that allows to place multiple ships on the board but I've run into some issues when randomly placing ships namely, the ships sometimes overlaps. enter image description here

As you see S should be of length 3. But B overlaps that. Below is the place_ship function. I would really appreciate some advice on what to fix.

def place_ship(board, ship_name):
    global ship_count, hiddenBoard
    ship = ""
    size = 0
    if ship_name == "Destroyer":
        ship, size = "D", 2
    elif ship_name == "Submarine":
        ship, size = "S", 3
    elif ship_name == "Battleship":
        ship, size = "B", 4
    ship_row, ship_col = random_row(board), random_col(board)
    orientation = bool(random.getrandbits(1))
    if orientation:
        while hiddenBoard[ship_row][ship_col] != "D" or "S" or "B":
            if ship_col + size not in range(10):
                ship_col -= size
            if ship_row + size not in range(10):
                ship_row -= size
            for x in range(0, size):
                hiddenBoard[ship_row][ship_col + x] = ship
                ship_count += 1
            break
    else:
        while hiddenBoard[ship_row][ship_col] != "D" or "S" or "B":
            if ship_row + size not in range(10):
                ship_row -= size
            if ship_col + size not in range(10):
                ship_col -= size
            for x in range(0, size):
                hiddenBoard[ship_row + x][ship_col] = ship
                ship_count += 1
            break




How to generate random points in a square using numpy.random.uniform?

Generate 20 random points in the square −5,5 ×[−5,5] (that is, both x and y coordinates are chosen at random with equal probability from the interval [-5,5]). Plot all those points.

I do not understand how to generate those 20 random points and the asnswer to the question I was given which is :

import numpy as np

points = np.random.uniform(-5,5,(50,2))

I do not understand the second part of the numpy function, "(50,2)".

Thank you very much for your help.




Display a Shuffle of button text and backgrounds

I have a button in xml. On button press I wish to rapidly change the background and Text on that button.

I normally would use a code like this for the final result:

String rndm[]  = {"A","B","C","D"};
{rnd = rndm[(int) (Math.random() * rndm.length)];}

{Button btn = (Button) findViewById(R.id.button1);
btn.setText(String.valueOf(rnd));
btn.setTextColor(Color.parseColor("#000000"));}

Before that is called though I would like perhaps a second or two of a "shuffling" effect.

I have tried using java.util.timer like this:

@Override
            public void onClick(View v) {                           

                    new java.util.Timer().schedule(
                        new java.util.TimerTask() {
                            @Override
                            public void run() {
                                runOnUiThread(new       Runnable() 
                                        public void.   run() {}});

String rndm[] = {"A","B","C","D"}; {rnd = rndm[(int) (Math.random() * rndm.length)];}

{Button btn = (Button) findViewById(R.id.button1);
btn.setText(String.valueOf(rnd));
btn.setTextColor(Color.parseColor("#000000"));}

}}}, 100 );

Then making a few of these with different backgrounds to fire one after the other. I just can't seem to get the hang of it. From what I have read on here and in the Oracle docs, I understand you need to use EventQueue.invokeLater To refresh the GUI, but I can't seem to get a clear use.

I may need a whole new method to do what I want to do, but I am not sure what the best wat to accomplish what I need is.




Is there a non-repeating pseudo random number generator in JavaScript? [on hold]

I want to generate 6-digit numeric coupon codes in JavaScript.

Is there something like Preshing's algorithm?

http://ift.tt/16IdhVI




How to return middle bits from random number generator?

I have a random_rand() function which produces a random number between 0 and RANDOM_RAND_MAX. RANDOM_RAND_MAX is defined to be 65535.

I would like to use the middle bits from the result of random_rand() instead of lowest-order bits so that I can make the randomiztion better.

Could you please show me a quick way to do this.

Thanks




Mastermind game: program didn't calculate right perfect and imperfect match

I'm coding the Mastermind game. And the rules doesn't like any of these topics:

Simple guessing game in c

C number guessing game with isdigit() verification

MasterMind game in C

Mastermind Game Algorithm

Here are rules:

  1. You are given a random of 4 numbers, (all numbers in range between 0 and 5);

  2. You guess those numbers by inputting 4 numbers, separated by a space, (condition are the same with the random);

  3. After input, you will be told how many perfect and imperfect match you've got (perfect match means player guess any of 4 which correct both in value and position, imperfect match means correct in value but not correct in position)

  4. You have 10 chances, if you fail after 10 guess attemps, the program stop and print out the random board. Otherwise, if you guess 4 numbers correctly, the program stop and print out the number of attemps and time taken when the game run and after your guess correct.

Here are my codes:

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

void MastemindRandom(int random[]);
int * getGuess();
int isValidNumbers(int a, int b, int c, int d);
void run(int * count);

int main(int argc, char** argv) {
    time_t begin, end;
    int count;
    double timeTaken;
    time(&begin); //count the time when the program start
    run(&count);
    time(&end); 
    if (count != 10) {    //if player wins, print out the time taken 
       timeTaken = difftime(end, begin);
       printf("time taken: %f", timeTaken);
    }
    return (EXIT_SUCCESS);
}

void run(int * count) {
    int random[4], *guess = malloc(4);
    int imperfect, perfect, flag[4] = { 0, 0, 0, 0 };
    MastemindRandom(random);  //doing the random
    do {
        imperfect = perfect = 0;
        memset(flag, 0, sizeof(int) * 4);
        printf("input your guess: ");
        guess = getGuess();
        for (int i = 0; i < 4; i++) {
            if (random[i] == guess[i]) {
                perfect++; //if player guess correctly any of 4 numbers, both in position and value, increase the perfect count and set flag of that position
                flag[i] = 1;
                continue;
            }
            for (int j = 0; j < 4; j++) {
                if (flag[j] == 1) //if that position has been check before
                    continue;

                if (random[i] == guess[j]) {
                    imperfect++; //if the player guess correct in value but not correct in position, increase the imperfect and flag it
                    flag[j] = 1;
                    break;
                }
            }
        }
        printf("you have %d perfect match and %d imperfect match\n", perfect, imperfect);
        if (perfect == 4) {
            (*count)++;
            break;
        } else {
            printf("sorry you didn't win, better luck next time\n");
            (*count)++;
        }
    } while (*count != 10);
    if (*count == 10) {
        printf("sorry you don't win the game, the real numbers are: ");
        for (int i = 0; i < 4; i++) {
            printf("%d ", random[i]);
        }
    } else {
        printf("congratulation, you won after %d tries \n", *count);
    }
}

void MastemindRandom(int random[]) {
    srand(time(NULL));
    for (int i = 0; i < 4; i++) {
        random[i] = rand() % +6;
        printf("%d ", random[i]);
    }
    printf("\n");
}

int * getGuess() {
    int* numbers = malloc(4);
    int a, b, c, d;
    do {
        scanf("%d %d %d %d", &a, &b, &c, &d);
        while (getchar() != '\n'){}
    } while (!isValidNumbers(a, b, c, d) && printf("Input from 0 to 5 only, input again: "));
    numbers[0] = a;
    numbers[1] = b;
    numbers[2] = c;
    numbers[3] = d;
    return numbers;
}

int isValidNumbers(int a, int b, int c, int d) {
    if (a < 0 || b < 0 || c < 0 || d < 0 ||
        a > 5 || b > 5 || c > 5 || d > 5)
        return 0;
    else return 1;
}

My code run with no error, but the calculation of the perfect and imperfect match are wrong in some conditions

Here are the output: (the first four numbers of all outputs below are the random that I print out to check)

Condition when random has no equal numbers (still OK)

3 2 4 5 
input your guess: 4 4 4 4
you have 1 perfect match and 0 imperfect match
sorry you didn't win, better luck next time
input your guess: 4 2 3 5
you have 2 perfect match and 2 imperfect match
sorry you didn't win, better luck next time
input your guess: 4 3 2 2
you have 0 perfect match and 3 imperfect match
sorry you didn't win, better luck next time
input your guess: 5 2 3 4
you have 1 perfect match and 3 imperfect match
sorry you didn't win, better luck next time
input your guess: 5 5 5 5
you have 1 perfect match and 0 imperfect match
sorry you didn't win, better luck next time
input your guess: 1 2 3 4
you have 1 perfect match and 2 imperfect match
sorry you didn't win, better luck next time
input your guess: 3 4 3 4
you have 1 perfect match and 1 imperfect match
sorry you didn't win, better luck next time
input your guess: 3 5 2 3
you have 1 perfect match and 2 imperfect match
sorry you didn't win, better luck next time
input your guess: 4 3 5 5
you have 1 perfect match and 2 imperfect match
sorry you didn't win, better luck next time
input your guess: 1 3 2 2
you have 0 perfect match and 2 imperfect match
sorry you didn't win, better luck next time
sorry you don't win the game, the real numbers are: 3 2 4 5 
RUN SUCCESSFUL (total time: 1m 50s)

Condition when random has 2 equal numbers (has some incorrect)

3 2 3 5 
input your guess: 3 3 2 5
you have 2 perfect match and 2 imperfect match
sorry you didn't win, better luck next time
input your guess: 3 3 3 3 
you have 2 perfect match and 0 imperfect match
sorry you didn't win, better luck next time
input your guess: 3 4 3 5
you have 3 perfect match and 0 imperfect match
sorry you didn't win, better luck next time
input your guess: 3 4 4 3
you have 1 perfect match and 1 imperfect match
sorry you didn't win, better luck next time
input your guess: 3 2 4 5
you have 3 perfect match and 0 imperfect match
sorry you didn't win, better luck next time
input your guess: 4 2 3 5
you have 3 perfect match and 1 imperfect match //wrong, should be 3 and 0
sorry you didn't win, better luck next time
input your guess: 5 2 3 5
you have 3 perfect match and 1 imperfect match //wrong, should be 3 and 0
sorry you didn't win, better luck next time
input your guess: 1 2 3 5
you have 3 perfect match and 1 imperfect match //wrong, should be 3 and 0
sorry you didn't win, better luck next time

condition when random has 3 equal numbers (has some incorrect)

3 3 3 4 
input your guess:  3 4 3 4
you have 3 perfect match and 1 imperfect match  //wrong, should be 3 perfect and 0 imperfect  
sorry you didn't win, better luck next time
input your guess: 4 3 4 3
you have 1 perfect match and 3 imperfect match  //wrong, should be 1 perfect and 2 imperfect
sorry you didn't win, better luck next time
input your guess: 4 4 4 3
you have 0 perfect match and 2 imperfect match   
sorry you didn't win, better luck next time
input your guess: 3 4 3 4
you have 3 perfect match and 1 imperfect match   //wrong, should be 3 perfect and 0 imperfect
sorry you didn't win, better luck next time
input your guess: 5 3 3 4
you have 3 perfect match and 1 imperfect match   //wrong, should be 3 perfect and 0 imperfect
sorry you didn't win, better luck next time
input your guess: 2 3 3 4
you have 3 perfect match and 1 imperfect match   //wrong, should be 3 perfect and 0 imperfect 
sorry you didn't win, better luck next time
input your guess: 3 3 3 2
you have 3 perfect match and 0 imperfect match
sorry you didn't win, better luck next time
input your guess: 1 2 3 4
you have 2 perfect match and 1 imperfect match   //wrong, should be 2 perfect and 0 imperfect
sorry you didn't win, better luck next time
input your guess: 3 3 4 4
you have 3 perfect match and 0 imperfect match   
sorry you didn't win, better luck next time
input your guess: 3 3 2 4
you have 3 perfect match and 0 imperfect match
sorry you didn't win, better luck next time
sorry you don't win the game, the real numbers are: 3 3 3 4 
RUN SUCCESSFUL (total time: 4m 53s)

I don't want to print out more, because basically, my logic is totally wrong. Can you guys help me out, i would be very appreciated.




MySQL - Generate random unique code if collumn is NULL

I'm having a table col called unique_id which is set to NULL by default.

How can I "create a patch" and alter the table so when the unique_id is NULL to generate a random code (preferably as integer)

ALTER TABLE `projects`
CHANGE `unique_id` char('24') 
COLLATE 'latin1_swedish_ci' NULL 
DEFAULT 'none' 
AFTER `status`;




Conditional Randomization

Imagine there is a list of elements as follow:

1a, 2a, 3a, 4a, 5b, 6b, 7b, 8b

Now we need to randomize it such that not more than 2 "a"s or 2 "b"s get next to each other. For instance the following list is not allowed because of the 2nd, third and fourth elements:

3a, 7b, 8b, 5b, 2a, 1a, 5b, 4a

How can we write write an efficient code without generating many random sequences and many triad comparisons?

Thanks,




The plots of co-variance functions should start from 0-shift

The following was my question given by my teacher,

  1. Generate a sequence of N = 1000 independent observations of random variable with distribution: (c) Exponential with parameter λ = 1 , by inversion method.
  2. Present graphically obtained sequences(except for those generated in point e) i.e. e.g. (a) i. plot in the coordinates (no. obs., value of the obs) ii. plot in the coordinates (obs no n, obs. no n + i) for i = 1, 2, 3. iii. plot so called covariance function for some values. i.e. and averages:

enter image description here

I have written the following code,

(*****************************************************************)
(*Task 01(c) and 02(a)*)
(*****************************************************************)
n = 1000;

taskC = Table[-Log[RandomReal[]], {n}];

ListPlot[taskC, AxesLabel->{"No. obs", "value of the obs"}]

i = 1;
ListPlot[Table[
    {taskC[[k]], taskC[[k+i]]}, 
    {k, 1, n-i,1}],
AxesLabel->{"obs.no.n", "obs.no.n+1"}]

i++;
ListPlot[Table[
    {taskC[[k]], taskC[[k+i]]},
    {k, 1, n-i,1}],
AxesLabel-> {"obs.no.n", "obs.no.n+2"}]

i++;
ListPlot[Table[
    {taskC[[k]], taskC[[k+i]]},
    {k,1,n-i,1}],
AxesLabel->{"obs.no.n", "obs.no.n+3"}]

avg = (1/n)*Sum[taskC[[i]], {i,n}];

ListPlot[Table[1/(n-tau) * Sum[(taskC[[i]]-avg)*(taskC[[i+tau]] - avg), n], {tau, 1,100}], 
    Joined->True, 
    AxesLabel->"Covariance Function"]

enter image description here

He has commented,

The plots of co-variance functions should start from 0-shift. Note that for larger than 0 shifts you are estimating co-variance between independent observations which is zero, while for 0 shift you are estimating variance of observation which is large. Thus the contrast between these two cases is a clear indication that the observations are uncorrelated.

What did I do wrong?

How can I correct my code?




Random background color on anchor only gets first anchor?

i have 3 anchor blocks where i want 3 different random background-colors on when i load the page. But only the first anchor is randomly changing from background-color.

Here is the HTML & jQuery code i use:

<script type="text/javascript">
            $(document).ready ( function () {
                var color = '#'; // hexadecimal starting symbol
                var letters = ['000000','FF0000','00FF00','0000FF','FFFF00','00FFFF','FF00FF','C0C0C0']; //Set your colors here
                color += letters[Math.floor(Math.random() * letters.length)];
                document.getElementById('kleur').style.background = color; // Setting the random color on your div element.
            });
        </script>

<div class="content_block_list">
                    <?php if( have_rows('content_block_list') ): ?>
                        <ul>
                        <?php while( have_rows('content_block_list') ): the_row(); 
                        $content = get_sub_field('content');
                        $button_link = get_sub_field('button_link');
                        ?>
                            <li>
                                <div>
                                    <?php if ($content == true){ ?><?php echo $content; ?><?php } ?>
                                    <?php if ($button_link == true){ ?><a id="kleur" class="more" href="<?php echo $button_link; ?>">LEES MEER</a><?php } ?>
                                </div>
                            </li>
                        <?php endwhile; ?>
                        </ul>
                    <?php endif; ?>
            </div>

This code automatically generates 3 blocks with 'Read More' anchors, these anchors have background-color. Those background-colors need to change randomly, do i have to create a loop or something?

Here u can see that the first anchor does change from background-color:

First 'Read More' is changing background-color randomly

Thanks for your time!




How to simulate a bimodal distribution in javascript?

I need to simulate a bimodal distribution in Javascript. Could anyone point me in the right direction?




dimanche 27 novembre 2016

Prevent having more than two same attributes(srcset) when randomly changing attributes with jQuery

i made this script for grid gallery that changes images randomly one at the time every 3s, by changing its srcset attribute, theres allways 15 visible images but array is made out of 28 and since its random sometimes happens that there are 3 or more of the same image, theres chance to have all 15 be the same (crazy small chance but you get my point) and i want to prevent it somehow.

I was thinking about somehow defining that theres allways 2 same attributes possible at most, so it wont change other img to that attribute if there are 2 of those. Or if its possible, this would be perfect, to have only one of attribute visible and it wont add that to other img if there is exactly that attribute.

Im ok with having at most 2 of the same attributes since it will minimize chance of seeing them both at the same time since half is hidden and it will prevent seeig 3 or more.

Heres the jQuery:

$(function () {


    //array
    var dice = $('.attachment-lenslight_squares').map(function () {
        return $(this).attr('srcset')
    }).get();

    $('.attachment-lenslight_squares')
       .click(function () {

        var num = Math.floor(Math.random() * dice.length);
        $(this).fadeOut(200, function() {
            $(this).attr('srcset', dice[num]);
    }).fadeIn(200);
    });
    setInterval(function () {
        var rand = Math.floor(Math.random()* 15);
    $('.attachment-lenslight_squares').eq(rand).click();
}, 3000);

});

Thanks for ideas




How to generate random values with fixed sum in C++

I want to generate 3 random numbers in the range 0 to 9 that sum up to a given fixed number. For example, for the given fixed sum 15, one possible solution would be (3, 8, 4). How can I do this?




how to get randomly generated numbers to equal a set value?

Here is the question at hand

so in short, I need to randomly generate 6 numbers between 1-1000, and the 6 numbers added together must equal 1000

here's what I have so far

    public static void main(String[] args){
    Scanner keybd= new Scanner(System.in);
        System.out.println("In 1000 rolls of dice, I got: ");
        int sum = 0;        

        for(int side=1; side<= 6; side++){
        int number = (int)(Math.random() * 1000 + 1);       
        System.out.println(side + "‘s " + (number);
        sum = sum + number;
                }   
             }
    }

All it does is just print out 6 random numbers between 1-1000

I just can't figure out how to make it so that the numbers added together equal 1000

Any help will be appreciated!




Trouble translating small C# "Random String" function to Haskell

I saw the following code in my companies codebase and thought to myself "Damn that's a fine line of linq, I'd like to translate that to Haskell to see what it's like in an actual functional language"

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

However I'm having a bit of trouble getting a concise and direct translation to Haskell because of how awkward it is to generate random numbers in this language.

I've considered a couple of approaches. The most direct translation of the C# code only generates a single random index and then uses that in place of the random.Next(s.Length). But I need to generate multiple indexes, not a single one.

Then I considered doing a list of IO Int random number actions, but I can't work out how to go through and convert the list of IO actions into actual random numbers.

So the Haskell code that I end up writing ends up looking quite convoluted compared to the C# (which I wasn't expecting in this case) and I haven't even got it to work anyway.

My question, what would be a natural translation of the C# to Haskell? Or more generally, how would you go about generating a random String of a specified length in Haskell (because this C# way doesn't seem to translate well to Haskell)?




Getting a random word from a text file

I am trying to return a word from a text file (so that I can eventually make a game from the word) but right now I get the error

IndexError: string index out of range

this is what my text file looks like

yellow
awesome
barking
happy
dancing
laughing

and this is the code I currently have

import random

def generate_the_word(infile):

    for line in infile.readlines():
        random_line = random.randrange(line[0], line[len(line) + 1])

        print(random_line)



def main():
    infile = open("words.txt","r")
    generate_the_word(infile)

    infile.close


main()

Do I have the wrong idea about indexing?




Generating Arrays of Random Values Influenced by Integers in Julia

We begin with

sets=[0.306894 0.564316 0.835714; 0.962995 0.97134 0.627331; 0.739529 0.665181 0.279065; 0.598537 0.0537966 0.918484; 0.220525 0.554764 0.294359]

shown in table form:

╔══════════╦═══════════╦══════════╗
║   Set1   ║   Set2    ║   Set3   ║
╠══════════╬═══════════╬══════════╣
║ 0.306894 ║ 0.564316  ║ 0.835714 ║
║ 0.962995 ║ 0.971345  ║ 0.627331 ║
║ 0.739529 ║ 0.665181  ║ 0.279065 ║
║ 0.598537 ║ 0.0537966 ║ 0.918484 ║
║ 0.220525 ║ 0.554764  ║ 0.294359 ║
╚══════════╩═══════════╩══════════╝

and

influencers=[9,5,9,4,7]

shown in table form:

╔═════════════╗
║ Influencers ║
╠═════════════╣
║           9 ║
║           5 ║
║           9 ║
║           4 ║
║           7 ║
╚═════════════╝

where influencers specifies how many times a process will be repeated (will be explained further down).

We will then create an array of random values using rand() and Normal() from the Distributions package.

The first column of the array will be five random values partly based on the first value in Set 1 (0.306894)

rand(Normal(0,.15+0.306894),5)

The second column of the array will be five random values partly based on the second value in Set 1 (0.962995).

This should be done until the last value in Set 1 (0.220525) is used to generate 5 random values.

Before moving on to using the values from Set 2, this process must be repeated (with new random numbers being generated in each repetition) by the corresponding number in "influencers". As the first value in influencers is 9, the process would be repeated 9 times, generating an array of 5 rows by 5*9=45 columns.

This would be performed until all values in sets were used. The data impacted by set 2 would be a 5x25 as there are five values in set 5 and the second value in "influencers" is 5.

The final output would be a 5x170 array with the general appearance of:

╔══════════╦═══════════╦═════╦══════════╦══════════╦═════╗
║   out1   ║   out2    ║ ... ║   out9   ║  out10   ║ ... ║
╠══════════╬═══════════╬═════╬══════════╬══════════╬═════╣
║ 0.617515 ║ 0.840251  ║     ║ 0.433632 ║ 0.259546 ║     ║
║ 0.302227 ║ 0.972178  ║     ║ 0.683352 ║ 0.567368 ║     ║
║ 0.788301 ║ 0.607621  ║     ║ 0.562016 ║ 0.424742 ║     ║
║ 0.195857 ║ 0.0176129 ║     ║ 0.251916 ║ 0.406313 ║     ║
║ 0.695097 ║ 0.168849  ║     ║ 0.993037 ║ 0.760426 ║     ║
╚══════════╩═══════════╩═════╩══════════╩══════════╩═════╝

where out1 through out9 would be based on set 1 and out10 would be where the data generated from set 2 would begin.

Can anyone point me in the right direction for how to achieve this? If it is possible to keep the output in this format, that would be best as the coding for future calculations will be simplified significantly.

Thank you for your help!

-Alejandro Braun




Is hardware random number generation truly random?

Using techniques like thermal noise, would a hardware based randomly generated number be truly random?

How can we prove that a hardware generated random number is truly random?

I have a hard time wrapping my head around true randomness. Is it even possible to prove that a number is completely random?




Rand function that increment respectively

I want to generate random numbers

  randomnumberseed(M)=5 
    thenumberofrandomnumbersthatprogramshouldgenerate(N)=105 
    lowerbound(l)=-1
    upperbound(u)=20 and
    incrementrespectively(s)=0.01

srand(M);
for (i = 1; i <= N; i++) {
        rn = (l + (size) *(double)rand() / RAND_MAX);
        printf("%10.3f", rn);

So my random numbers must be like:

-0.460 12.930 16.550 12.490 2.600 19.300 7.270 7.490 0.720 10.400

8.140 9.210 8.330 5.760 3.260 0.070 13.630 11.070 15.500 11.310

And then i want to count the numbers which in the same interval(range will be divided 30 equal interval like (u-l)/30) and must to display.

First, i can generate random number between range but i can't provide incrementation respectively with s(0.01).

Secondly, how can i count intervals frequency? with an array or counter?

waiting for your urgent help :((((




MethodError: no method matching /(::Int64,::Array{Int64,1}) when generating random numbers based on Normal Distribution in Julia

I need to construct a multi-element array of random numbers from a normal distribution (using the "Distributions" package for this). I am using the code below.

[rand(Distributions.Normal(0,a[end]+0.5*(1-b[n])),c,length(b[1,:])*d[n]/c) for n=1:length(b)]

where (I am using random numbers for this example):

a=rand(10)
b=rand(5,32)
c=5
d=rand(32)

When I run the code I receive the following error message:

MethodError: no method matching /(::Int64,::Array{Int64,1})

Any ideas on how I can get this to work?

Thank you for your help.

-Alejandro Braun




Little mistake somewhere. Help needed

I wrote a little browser-game.

The rules are easy: you have 15 seconds to decide if you know the name written on the screen.

You have two buttons: "i know"/"give up" - depends on what you want to choose.

If you choose "give up" (or time ends) photo 1 appears. Otherwise, photo 2 will be shown.

Whole operation is looped.

Here's my question: I wanted to choose random name from array "word" every single round, so I wrote function "random_word()". I put it into "timer()", "surrender()" and "winning()" functions. But it doesn't work.

I'm just starting with programming, so I'll be grateful for possibly easiest to understand code. Thanks for all help.

Here's my code:

<!DOCTYPE html>
<html>
<head>
<style>

</style>
<script src="/scripts/snippet-javascript-console.min.js?v=1"></script>
</head>
<body> 
<button id= "btnSurrender">give up</button>

<button id= "btnWinning">i know</button>

<p id="seconds">15</p>
<div id="photo"></div>
<script type="text/javascript">


var word = new Array(3);
word[0] = "Michael";
word[1] = "Simon";
word[2] = "Peter";
word[3] = "Mark";

function random_word(){
var randomWord = word[Math.floor(Math.random()*word.length)]
}




var btn1 = document.getElementById("btnSurrender");
var btn2 = document.getElementById("btnWinning");
var pic = document.getElementById("photo");
var secondsP = document.getElementById('seconds');

var clock = null;


btn1.addEventListener("click", surrender);
btn2.addEventListener("click", winning);

function timer () {

random_word();

clearInterval(clock);

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

clock = setInterval(function() {



         pic.innerHTML='<img src="" alt="">';
         var seconds = Math.round(15 - (new Date().getTime() - start) / 1000);


         if (seconds >= 0) {
           secondsP.textContent = seconds;
         } else {
           clearInterval(clock);
         }

         if (seconds === 0) {
           pic.innerHTML='<img src="mops bops.png" alt="">';

         }
}, 1000);
}

function surrender(){

clearInterval(clock);
pic.innerHTML='<img src="mops bops.png" alt="">';
secondsP.textContent = 0;
setTimeout(timer,2000);
word[Math.floor(Math.random()*word.length)]
random_word();
}
function winning(){

clearInterval(clock);
pic.innerHTML='<img src="mopsik.jpg" alt="">';
secondsP.textContent = 0;
setTimeout(timer,2000);
word[Math.floor(Math.random()*word.length)]
random_word();
}

timer();

document.write(randomWord)
setInterval(timer, 17000)

</script>
</body>
</html>




Return statment for an array is unreachable [on hold]

import java.util.Random;

public class game {

    private static Random rand = new Random();

    private static int[] pick6(int max) {
        int [] pick6 = {1, 1, 1, 1, 1, 1};
        for (int i = 0; 1<6;i++) {
            pick6[i] = rand.nextInt(max);
        }
        return pick6; //unreachable code
    }


    public static void main(String [] args) {
        int [] pick6 = pick6(10);
        for (int i = 0; i<=6; i++) {
            System.out.println(pick6[i]);
        }
    }
}

Is my method of creating a random array off, or is there some underlying problem I am missing?




Absorption and Distribution Laws and dealing with breaks

You'll assign the password to a variable, And the user will be prompted to enter a password. Their attempt is assigned to another variable and you'll compare them. If they don't match "INVALID" is displayed and they will continue to be prompted for a password until the correct one is entered.

package arrays;
import java.util.Scanner;
public class searchingalgorithms {

public static void main(String[] args){

    Scanner sc=new Scanner(System.in);
    int password= 9320;
    int user = 0;

    System.out.print("Enter a password: :");
    user = sc.nextInt();

    if(user==password){
        System.out.println("Valid");
    }

    if(user!=password){
        System.out.println("INVALID");
        user = sc.nextInt();
    }
}

}

Hi so, my program works the first time if it is valid but, it just keeps on going on and on. Also, What I want my program to do is repeat the program if it is invalid. How do I do this?




Why does one random int become the same as another random int after I specifically prevent this? (JAVA)

In my program, two random numbers are generated. One of them (rbvalue) is between 0 and 8. The other, loadG4, is between 0 and 9. If rbvalue is ever == as loadG4, it'll be set to 9. This way, the two numbers can never be equal. For some reason, the code is flawed after the first time a button is clicked (program loops after each button click). In the code there may be excess information not relevant, I am putting it in anyway in case in clashes with the random generation and comparison that we are focusing on. Here is the code:

Random random = new Random();
int rbselector = random.nextInt(4);    //These three are declared outside of onCreate.
int loadG4 = random.nextInt(10);


for(int allrbA=0; allrbA<4; allrbA++) {
                int rbvalue = random.nextInt(9);
                if (rbvalue == loadG4) {
                    rbvalue=9;
                }
                selectrb[allrbA].setText(""+rbvalue);
            }
            selectrb[rbselector].setText(""+ loadG4);


                for (int allrbA = 0; allrbA < 4; allrbA++) {
                selectrb[allrbA].setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                            Button clicked = (Button) v;
                            String clickVal = (String) clicked.getText();
                            int finalClick = Integer.valueOf(clickVal);

                            if (finalClick == loadG4) {
                                score++;
                                for (int allrbA = 0; allrbA < 4; allrbA++) {
                                    int rbvalue = random.nextInt(9);
                                    loadG4 = random.nextInt(10);
                                    if (rbvalue == loadG4) {
                                        rbvalue=9;
                                    }
                                    selectrb[allrbA].setText("" + rbvalue);
                                }
                                number.setText("" + loadG4);
                                rbselector = random.nextInt(4);
                                selectrb[rbselector].setText("" + loadG4);
                            }
                    }
                });
                }

Many thanks in advance.




1D and 2D Arrays, random numbers in Java for a lottery game

I am trying to develop a lottery game in java, where the user enters 3 lines of 5 numbers and the application generates 5 random numbers, compares the guessed numbers and returns to the user the guessed numbers for each line.

I have tried to use a 2D array for the input from the user and 1D array for the 5 random numbers. But it is not working...I am getting a lot of errors and not sure how to make it work...

Below are the app and instantiable classes, anyone could help me?

INSTANTIABLE

import java.util.Random;
public class Lotto{


    Random myRand = new Random();

    //declare instance variables
    private int [] myArray;
    private int [][] guesses;
    private int result;


    for(int i=0; i<5; i++){
        myArray[i]= myRand.nextInt(40);
        myArray += 1;
    }

    public Lotto(){

    }
    public void setGuess(int [][]g){
        guesses=g;
    }
    public int getResult(){
        return result;
    }
    public void computeResult(){
        int score1 =0;
        int score2 = 0;
        int scoe3 =0;

        //travesse 2D array
        for (int row=0; row<rain.length; row++){
            for (int col=0; col<guesses[row].length; col++){
                if(myArray[0]==guesses[0][col]){
                    score1 += 1;
                }else if(myArray[1]==guesses[0][col]){
                    score1 += 1;
                }else if(myArray[2]==guesses[0][col]){
                    score1 += 1;
                }else if(myArray[3]==guesses[0][col]){
                    score1 += 1;
                }else(myArray[4]==guesses[0][col]){
                    score1 += 1;
                }


            }
        }
    }
}

APP CLASS

import java.util.Scanner;

public class LottoApp{
    public static void main(String args[]){
        Scanner in = new Scanner(System.in);

        //declare a 2D array
        int [][] myArray;
        //create the 2D array
        int tries=3;
        int numbers=5;

        myArray = new int[tries][numbers];

        for (int rows=0; rows<myArray.length; rows++){
            for(int col=0; col<myArray[rows].length; col++){
                int line = rows+1;
                System.out.println("Number for list "+line);
                myArray[rows][col] = in.nextInt();
            }
        }
        Lotto myObj = new Lotto();
        //give data from user
        myObj.setGuess(myArray);

        //processing
        myObj.computeResult();

        //output
        int r = myObj.getResult();
        System.out.println("result: "+r);
    }
}




Why does Java program flaw after first click? (Android Studio)

I have a program in which a random value is applied to four random buttons. One of the random values id displayed on top of the four buttons. If the user taps the button containing that number displayed (loadG4) they get a point. The problem I have with this is that once the user clicks the correct button and new numbers are generated, the rbvalue buttons may not all be different to the loadG4 value. As seen in my code, they should never be equal. Here's the code:

int score = 0;
Random random = new Random();
int rbselector = random.nextInt(4);    //These four initiations are out onCreate.
int loadG4 = random.nextInt(10);


final Button[] selectrb = new Button[4];
    selectrb[0] = rb1;
    selectrb[1] = rb2;
    selectrb[2] = rb3;
    selectrb[3] = rb4;


    final Button loseStarter4 = (Button) findViewById(R.id.Starter4);
    loseStarter4.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            infoG4.setVisibility(View.GONE);
            loseStarter4.setVisibility(View.GONE);
            rb1.setVisibility(View.VISIBLE);
            rb2.setVisibility(View.VISIBLE);
            rb3.setVisibility(View.VISIBLE);
            rb4.setVisibility(View.VISIBLE);


            rbselector = random.nextInt(4);

            final TextView number = (TextView) findViewById(R.id.number);
            number.setText(""+ loadG4);


            for(int allrbA=0; allrbA<4; allrbA++) {
                int rbvalue = random.nextInt(9);
                if (rbvalue == loadG4) {
                    rbvalue=9;
                }
                selectrb[allrbA].setText(""+rbvalue);
            }
            selectrb[rbselector].setText(""+ loadG4);


                for (int allrbA = 0; allrbA < 4; allrbA++) {
                selectrb[allrbA].setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                            Button clicked = (Button) v;
                            String clickVal = (String) clicked.getText();
                            int finalClick = Integer.valueOf(clickVal);

                            if (finalClick == loadG4) {
                                score++;
                                for (int allrbA = 0; allrbA < 4; allrbA++) {
                                    int rbvalue = random.nextInt(9);
                                    if (rbvalue == loadG4) {
                                        rbvalue=9;
                                    }
                                    selectrb[allrbA].setText("" + rbvalue);
                                }
                                int loadG4 = random.nextInt(10);
                                number.setText("" + loadG4);
                                int rbselector = random.nextInt(4);
                                selectrb[rbselector].setText("" + loadG4);
                            }
                    }
                });
                }

I have it so that if an rbvalue is equal to loadG4, it is set to = 9. For some reason, after the first correct click it is possible that an rbvalue could be equal to loadG4.

Furthermore, the value of loadG4 never changes here either. Why is this?

Would be grateful to anyone who could look through this and explain why a) rbvalue are not all always different to loadG4 after first correct click and b) why loadG4 stays the same number.

Many thanks in advance.




Party simulation and a random generator [duplicate]

This question already has an answer here:

I'm trying to create a simulation for a party. There will be 4 classes: host, engineer, artist and scientist. Each one of those will have to be placed on a 50x50 field. I have to create a random generator in order to do this and I'm really stuck on this part for many hours now since I've never done random generators before so I hope that I can get some help. (I'm a beginner, yes.) I'm currently receiving this error: "Exception in thread "main" java.lang.NullPointerException at Simulator.populate(Simulator.java:88) at Simulator.partyStatus(Simulator.java:101) at Simulator.(Simulator.java:56) at Simulator.main(Simulator.java:41) BUILD SUCCESSFUL (total time: 3 seconds)"

If there is a different, better way of doing it then I'd be more than happy to see it and if you need any more details regarding this then just ask.

Thanks in advance!

public class Simulator {

    private static double ARTIST_CREATION_PROBABILITY = 0.2;
    private static double HOST_CREATION_PROBABILITY = 0.2;
    private static double ENGINEER_CREATION_PROBABILITY = 0.2;
    private static double SCIENTIST_CREATION_PROBABILITY = 0.2;

    private static int seed;

    private ArrayList<Artist> artists;
    private ArrayList<Scientist> scientists;
    private ArrayList<Engineer> engineers;
    private ArrayList<Host> hosts;
    private ArrayList<People> people;

    private int depth;
    private int width;
    private Field field;
//    private static int step;
    private SimulatorView simView;

    Random rand = RandomGenerator.getRandom();


    public static void main(String [] args) {
//     SimulatorView simView = new SimulatorView(50,50); 
     Simulator simulator = new Simulator(50,50);


    }

    /**
     *
     * @param depth
     * @param width
     */
    public Simulator(int depth, int width) {
        this.simView = new SimulatorView(depth, width);
        this.field = new Field(depth, width);
        this.depth = depth;
        this.width = width;
        this.partyStatus(simView, field);

        RandomGenerator.initialiseWithSeed(seed);
    }   

    public void populate(Field field){
//        People host = new Host();
//        People artist = new Artist();
//        People scientist = new Scientist();
//        People engineer = new Engineer(); 
//        field.place(artist, 10, 10);
//        field.place(scientist, 20, 20);
//        field.place(engineer, 30, 30);
//        field.place(host,40,40);

               Random rand = RandomGenerator.getRandom();
        field.clear();

         for(int row = 0; row<field.getDepth(); row++){
            for(int col = 0; col<field.getWidth(); col++){
               if(rand.nextDouble() < ARTIST_CREATION_PROBABILITY){
                 Artist artist = new Artist();
                 artists.add(artist);
                 field.place(artist, row, col);
               }
               else if(rand.nextDouble() < SCIENTIST_CREATION_PROBABILITY){
                 Scientist scientist = new Scientist();
                 scientists.add(scientist);
                 field.place(scientist, row, col);
               }
               else if(rand.nextDouble() < ENGINEER_CREATION_PROBABILITY){
                 Engineer engineer = new Engineer(); 
                 engineers.add(engineer);
                 field.place(engineer, row, col);
               }
               else if(rand.nextDouble() < HOST_CREATION_PROBABILITY){
                 Host host = new Host();
                 hosts.add(host);
                 field.place(host, row, col);
               } 
            }
         }        
    }

    public void partyStatus(SimulatorView simView, Field field){
        this.populate(field);
        simView.setColor(Artist.class, Color.ORANGE);
        simView.setColor(Scientist.class, Color.BLUE);
        simView.setColor(Engineer.class, Color.MAGENTA);
        simView.setColor(Host.class, Color.GREEN);
        simView.showStatus(1, field);
    }  
    }




2 Bit Random number generator in HDL Verilog

I was attempting to write a R.N.G. in Verilog, im new.

Though I'm not sure if what I'm doing is correct.

module random(
input clk,
input rst_n,

output reg [1:0] data
);

reg [1:0] data_next;

always @* begin
data_next[1] = data[1]^data[0];
data_next[0] = data[0]^data_next[1];
end

always @(posedge clk or negedge rst_n)
if(!rst_n)
data <= 1'h1f;
else
data <= data_next;

endmodule

Any suggestions and guidance is appreciated.




Score not adding up correctly in Java program [duplicate]

In the program, I have two random values (loadG4 and rbvalue). These values are set to 4 buttons, rbvalue to 3 and loadg4 to one (loadg4 overrides on of the rbvalue buttons). They are randomly generated and assigned to a button by random. Any other details are clearly shown in the code below.

Here's my code:

final Random rbselection = new Random();
    final int rbselector = rbselection.nextInt(4);
    final Button[] selectrb = new Button[4];
    selectrb[0] = rb1;
    selectrb[1] = rb2;
    selectrb[2] = rb3;
    selectrb[3] = rb4;

int score = 0;
final Random GenerateG4 = new Random();
final int[] loadG4 = {GenerateG4.nextInt(10)};
final Random randoms1 = new Random();
final TextView number = (TextView) findViewById(R.id.number);

            number.setText(""+ loadG4[0]);
            for(int allrbA=0; allrbA<4; allrbA++) {
                int rbvalue = randoms1.nextInt(9);
                if (rbvalue== loadG4[0]) {
                    rbvalue=9;
                }
                selectrb[allrbA].setText(""+rbvalue);
            }
            selectrb[rbselector].setText(""+ loadG4[0]);

            if (score<4) {
                for (int allrbA = 0; allrbA < 4; allrbA++) {
                    final int rbselector = rbselection.nextInt(4);
                    selectrb[allrbA].setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            String getrbvalue = (String) selectrb[rbselector].getText();
                            loadG4[0] = GenerateG4.nextInt(10);
                            number.setText("" + loadG4[0]);
                            for (int allrbA = 0; allrbA < 4; allrbA++) {
                                int rbvalue = randoms1.nextInt(9);
                                if (rbvalue == loadG4[0]) {
                                    rbvalue = 9;
                                }
                                selectrb[allrbA].setText("" + rbvalue);
                            }
                            final int rbselector = rbselection.nextInt(4);
                            selectrb[rbselector].setText("" + loadG4[0]);
                        }
                    });
                }
            }

            if (score<4) {
                for (int allrbA = 0; allrbA < 4; allrbA++) {
                    final int rbselector = rbselection.nextInt(4);
                    selectrb[rbselector].setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            String getrbvalue = (String) selectrb[rbselector].getText();
                            int finalisesrbvalue = Integer.valueOf(getrbvalue);
                            if (finalisesrbvalue == loadG4[0]) {
                                score++;
                                int loadG4 = GenerateG4.nextInt(10);
                                number.setText("" + loadG4);
                                for (int allrbA = 0; allrbA < 4; allrbA++) {
                                    int rbvalue = randoms1.nextInt(9);
                                    if (rbvalue == loadG4) {
                                        rbvalue = 9;
                                    }
                                    selectrb[allrbA].setText("" + rbvalue);
                                }
                                final int rbselector = rbselection.nextInt(4);
                                selectrb[rbselector].setText("" + loadG4);
                            }

                            else {
                                loadG4[0] = GenerateG4.nextInt(10);
                                number.setText("" + loadG4[0]);
                                for (int allrbA = 0; allrbA < 4; allrbA++) {
                                    int rbvalue = randoms1.nextInt(9);
                                    if (rbvalue == loadG4[0]) {
                                        rbvalue = 9;
                                    }
                                    selectrb[allrbA].setText("" + rbvalue);
                                }
                                final int rbselector = rbselection.nextInt(4);
                                selectrb[rbselector].setText("" + loadG4[0]);
                            }
                        }
                    });
                }
            }

My issue is that the score output is disordered, despite how many times the user clicks the button storing loadG4. This button and the value of loadG4 are constantly changing, as shown above. If I count what should be 6 points, I may get 2 points or 3 points, for example. The user gets awarded a point for the wrong reason, and I'm not sure what it is. My intention is for the program to add a point each time the user clicks the button holding the current loadG4 value, as you'd expect.

I'd appreciate it if anyone could explain what the root of my issue is, and how it could be resolved. Many thanks in advance.

Additional summary (read full post first):

There are 4 buttons and 4 random numbers for 0-8 which are generated and put randomly in each button. rbvalue is put 4 times (random each time) into all 4 buttons. LoadG4 then replaces one rbvalue in a random button. If an rbvalue is equal to loadG4, it'll be set to 9 to ensure it's never the same as LOADG4. If the user clicks the button with LoadG4 in it, they get a point. They're meant to get a point whenever they click a button containing LoadG4, and that button is random each time.

Note: I uploaded a similar question already I'm aware, apologies but I had to repost as my last question was neglected. Would be grateful if someone could help me clear this up, thank you.




Using C++ file in Swift Project

I've added a C++ file to my project written in Swift. It only calculates some random numbers and also uses an vector array. It's wrapper is written in Objective-C. When I try to call functions from the cpp file the App crashes after some time. But there's a strange behavior, because it doesn't crash while executing the C++ code (it runs like I expect to), but when I load a navigation controller. This hasn't to do anything with either. The console shows this:

'pthread_mutex_lock(&mutex)' failed with error 'EINVAL'(22)

I googled this bug, but I don't really understand the problem in my case.




MersenneTwister random number generator

I have a list(with 100.000 data) and i want to choose 4000 of them using MersenneTwister. I also want to use current system time because i run 15 times the program and i need different number of times.

MersenneTwister mt = new MersenneTwister("current system function");
for(int i=0; i<4000; i++){
    list1.add(mt.nextDouble());
}

I think that i must write something like this but i dont know which current system function to use to take different numbers




Python - Sample from 'x' lists with different distribution

In the following code, I've created a list of items and users. I've seperated the items to 3 different lists of very popular, popular and regular items.

import numpy as np


N_USERS = 20000
N_ITEMS = 1000

items = range(0, N_ITEMS)
users = range(0, N_USERS)

vpop = int(len(items)*0.1)
pop = int(len(items)*0.3)

np.random.shuffle(items)
vpop_items = items[:vpop]
pop_items = items[vpop:pop]
reg_items = items [pop:]

I want to sample X samples from those lists with different distribution. For example:

list_of_items = sample(vpop_items, pop_items, reg_items, p = [0.5, 0.35, 0.15], X)

where X is the number of samples I want to make. and P is the list of distributions corespond with the lists (vpop_items, pop_items, reg_items).




uniqid with mt_rand() as prefix and more entropy... Predictable string?

I using the next code to generate a unique string name for the files who are uploaded to my webserver:

uniqid(mt_rand(), true)

This returns strings like:

774984555583a985c017ef8.28294931

I used this in conjunction with a conditional to check if there is any file with the generated name; if exist I generate another string and so on until I get a unique name.

This works well; but I have a doubt that I cannot clarify for myself:


There is any way to predict the generated names with uniqid() and mt_rand() as prefix and "more entropy" to true?


ACLARATION:

I'm thinking of a potential brute force attack trying to access the file names.


ACLARATION 2: I do not have this problem, since I store my files outside the accessible directory of the web server.




Efficiently generating a large array of biased coin flips

I am looking for a high-performance Python solution to the following problem:

Flip a biased coin n times so that the probability of heads (=1) is equal to a given probability p. n is in the millions.

I suspect there can be a very efficient numpy-based solution.




samedi 26 novembre 2016

What is the range limit for uniform real distributions?

I want to create a random number within the numeric limits of the double floating point range. I thought this would be easy:

#include <random>                                                                   
#include <cassert>                                                                  
#include <math.h>                                                                

int main()                                                                          
{                                                                                   
    double a = std::numeric_limits<double>::lowest();                               
    double b = std::numeric_limits<double>::max();                                  

    std::default_random_engine engine;                                           

    std::uniform_real_distribution<double> dist(a, b);                           
    assert(std::isfinite(dist(engine))); // this triggers!

    return 0;                                                                    
}                                                                                   

The assert fails for both clang 3.8.0 and gcc 5.4.0. I tried using nextafter(a,0) and nextafter(b,0) instead of a and b when constructing dist but got the same result.

According to std::uniform_real_distribution, the methods min and max should be the answer to this question, but apparently that's not the case:

std::cout << dist.min() << ", " << dist.max() << std::endl;

The output of this is:

-1.79769e+308, 1.79769e+308

Again, same result for both compilers. The assert shouldn't be triggering. What's going on?




Timing-based (truly) random numbers?

I need a random number generator. Not for pseudo-random numbers, but the truly random kind. It crossed my mind that maybe I could extract bits from the subtle timing differences in loop execution, so I put something together to do just that:

#ifdef _WIN32
#include <windows.h>
unsigned long long tick()
{
    unsigned __int64 
        tock;
    QueryPerformanceCounter((LARGE_INTEGER *)&tock);
    return (unsigned long long)tock;
}
#elif __linux__
#include <sys/time.h>
unsigned long long tick()
{
    timespec 
        tock;
    clock_gettime(CLOCK_REALTIME, &tock);
    return (unsigned long long)tock.tv_nsec;    
}
#else
#warning "random_bits()/random_word() may run slowly on this system"
#include <time.h>
unsigned long long tick()
{
    return (unsigned long long)clock();    
}
#endif
#include <limits.h>
unsigned long long random_bits(unsigned short bits)
{
/*
    The `threshold` setting determines the smallest sample to extract a bit 
    from. If set too low the result won't contain enough entropy to be useful. 
    We don't want to set it so high that we're just wasting CPU cycles either, 
    so we need to settle on a value somewhere in the middle. Heuristically, 
    256 seems to be a pretty good compromise.    
*/    
    const unsigned long long    
        threshold = 256;
    unsigned long long
        result = 0,
        increment,
        accumulator,    
        count,
        target;
    const unsigned short
        size = sizeof(result) * CHAR_BIT;    
    if(bits == 0 || bits > size)
        bits = size;
    while(bits-- > 0)
    {
        increment = 1;
        accumulator = 0;
    /*
        Build up the value to be extracted from. We don't know anything 
        about the clock resolution, so the increment is repeatedly doubled 
        until it's large enough to make a difference.
    */        
        while(accumulator < threshold)
        {
            count = 0;
            target = tick() + increment;
            while(tick() < target)
                ++count;            
            accumulator += count;
            increment <<= 1;                
        }
    /*
        Shift the previous bit up one position and insert the newly sample one.
    */        
        result <<= 1;
        result |= (accumulator & 1);
    }    
    return result;
}
unsigned long long random_word(unsigned short length)
{
    return random_bits(length * CHAR_BIT);
}

//    Example useage:

#include <stdio.h>
int main(void)
{
    for(;;)
    {
        printf(" %u\n", (unsigned)random_word(sizeof(unsigned)));
        getchar();
    }
}

It appears to work well (passes the TESTU01 test suite)...but I still wonder:

(1) did I implemented everything correctly

(2) do the platform #defines look okay

(3) is there is any (reasonable) likelihood that this could be vulnerable in the case where a hacker gains control of the system time or some such

(4) is there is some better way to achieve this

(5) are there any legitimate arguments that (a) the generated values are in fact not sufficiently random and (b) if so, whether adjusting the threshold parameter might remedy the situation in such a case




How to generate just one random number

I want to generate one random number when a timer runs out that everyone will see in javascript or php. But if I just use Math.random() it will generate a random number for each page that is open when the timer runs out. How can I do this so I only generate one number for the entire site.

Thanks




shuffle letters in a string c++

I'm meant to write a function that keeps the first and last letter of a string the same and ignores any non-letters after the last letter. I'm supposed to use the std::random_shuffle(). I read the documentation however I don't seem to grasp the concept of this function. This is my code:

#include <iostream>
#include <algorithm>
#include <string>

std::string mix(std::string s){
    int last_char;
    if(std::isalpha(s[s.size()-1]) == true){
        last_char = s.size()-1;
    } else {
     for(int i=s.size() ; i>0; --i){
        if((std::isalpha(s[i]) == false) && (std::isalpha(s[i-1])==true)){
            last_char = i -1;
            break;
        }
      }
    }
    std::random_shuffle(s[1],s[last_char-1]);

}

int main(){
    std::string test = "Hello";
    std::cout << mix(test) << std::endl;
}




Arrays and random numbers

generate 1,000,000 Math.random() integers from 0 to 37 and calculate the percentage that each number appears

package arrays;
import java.util.List;
import java.util.Random;

public class arraysintro {

public static void main(String[] args){

    int numValues = 37;
    int[] array = randomArray(numValues);
    printArray(array);
}

public static int[] randomArray(int n) {
    int[] a = new int[n];
    for (int i = 0; i<a.length; i++) {
        a[i] = randomInt(0, 1000000);
    }
    return a;
}

private static int randomInt(int i, int j) {
    Random random = new Random();
    int abc = random.nextInt(1000000);
    return  abc;
}

public static void printArray(int[] a) {
    for (int i = 0; i<a.length; i++) {
        System.out.println(a[i]);
    }
}

}

Hi so I did most of the code everything works. I can get the 37 randomized 1 to 1000000 numbers but, I can't get the percentage for them. I tried creating a variable in the Random Int that would create the percentage but, since I can't create a double how do I approach this?




use input from .txt file for if command shell linux

I need to write a script that plays a different sound every time it is ran. If you have an easier method then let me know. Right now the following script is what I have but I don't think the cat command is working like I want it to. Please assist.

#! /bin/sh
### BEGIN INIT INFO
# Provides:          rc.local
# Required-Start:    $all
# Required-Stop:
# Default-Start:     2 3 4 5
# Default-Stop:
# Short-Description: Run /etc/rc.local if it exist
### END INIT INFO

if [ "cat /home/lucio/Desktop/welcomevar" = "10" ];
then
echo 1 > /home/lucio/Desktop/welcomevar; mplayer         /home/lucio/Desktop/sounds/welcome1.mp3
fi

if [ "cat /home/lucio/Desktop/welcomevar" = "1" ];
then
echo 2 > /home/lucio/Desktop/welcomevar; mplayer     /home/lucio/Desktop/sounds/welcome2.mp3
fi

if [ "cat /home/lucio/Desktop/welcomevar" = "2" ];
then
echo 3 > /home/lucio/Desktop/welcomevar; mplayer /home/lucio/Desktop/sounds/welcome3.mp3
fi

if [ "cat /home/lucio/Desktop/welcomevar" = "3" ];
then
echo 4 > /home/lucio/Desktop/welcomevar; mplayer     /home/lucio/Desktop/sounds/welcome4.mp3
fi

if [ "cat /home/lucio/Desktop/welcomevar" = "4" ];
then
echo 5 > /home/lucio/Desktop/welcomevar; mplayer         /home/lucio/Desktop/sounds/welcome5.mp3
fi

if [ "cat /home/lucio/Desktop/welcomevar" = "5" ];
then
echo 6 > /home/lucio/Desktop/welcomevar; mplayer     /home/lucio/Desktop/sounds/welcome6.mp3
fi

if [ "cat /home/lucio/Desktop/welcomevar" = "6" ];
then
echo 7 > /home/lucio/Desktop/welcomevar; mplayer     /home/lucio/Desktop/sounds/welcome7.mp3
fi

if [ "cat /home/lucio/Desktop/welcomevar" = "7" ];
then
echo 8 > /home/lucio/Desktop/welcomevar; mplayer     /home/lucio/Desktop/sounds/welcome8.mp3
fi

if [ "cat /home/lucio/Desktop/welcomevar" = "8" ];
then
echo 9 > /home/lucio/Desktop/welcomevar; mplayer /home/lucio/Desktop/sounds/welcome9.mp3
fi

if [ "cat /home/lucio/Desktop/welcomevar" = "9" ];
then
echo 10 > /home/lucio/Desktop/welcomevar; mplayer            /home/lucio/Desktop/sounds/welcome10.mp3
fi

exit 0




"ValueError: list.remove(x): x not in list", due to random numbers?

I'm writing a function to take a new card from a deck of cards, given that there are already some cards out of the deck.

def trekken(getrokken = []):
    import itertools
    import random

    getrokken = list(getrokken)
    kind = 'HCDS'
    value = '123456789XJQKA'
    deck = ["".join(card) for card in itertools.product(value,kind)]
    for i in range(0, len(getrokken)-1): deck.remove(getrokken[i])
    return(deck[(random.randint(1, len(deck)))])

When I use this for some examples a few times I sometimes get the error message:

line 16, in trekken print(deck[(random.randint(1, len(deck)))]) IndexError: list index out of range

For example with the following input:

trekken(['6H', '3C', '3D', '8C', 'AD', '9D', '7D', 'QC'])

Maybe not the first time, but after a few tries (max. 20) I always get this error message.




Crunch ignoring numbers when processing word charsets with -p or -q, is there any workaround?

I have an input.txt file with the following content:

abc
cba
bca

I'm genereating every possible combinations of these words with crunch:

$ crunch 3 6 -o output.txt -q input.txt

The generated output.txt looks like this:

abcbcacba
abccbabca
bcaabccba
bcacbaabc
cbaabcbca
cbabcaabc

However what I want to achieve is to print only the combinations which is between 3-6 characters in length. Crunch ignoring the numbers when you use -p or -q which is stated in the manpage.

Is there any workaround for this?




C - Issue with random number generator

I have an issue while generating a random number and giving the value to a pointer.

What I want to do here: generate a number between 1 and 1000, and the player will receive that amount of gold. The base gold is 0 obviously. Although, for some reason, when I printf the amount of integer gold, there were cases when it was more than 3000, which is obviously a sign of error.

The goldchange part is because the player will receive gold lots of times and I want it to work every time. Although at the moment, since I am testing this part of my program, the player receives gold only once.

Since I am a beginner programmer, I guess I am doing it wrong. How should I do this correctly so integer GOLD will have the correct value?

int* gold=0;
int goldchange;
srand(time(0));
goldchange=gold;
gold=gold+rand()%1000+1;
goldchange=gold-goldchange;
printf("You have received the following amount of gold: %d", goldchange);

printf("You have this many golds: %d", gold);

So, for example, this was what happened last time: You have received the following amount of gold: 777 You have this many golds: 3108

But it should be 777 not 3108.... (obviously every run gives different numbers, but the two values are never the same...)




Deleting a random number of enemies from a linked list

I am required to create a function that does the following:

Pick at most 4 random active enemies to kill: Randomly pick two from high priority active enemies and randomly pick two from normal active enemies. High priority enemies are the ones that have type of shielded fighter or tank or chooper.

First of, I have the following structs and enums

enum Region
{
A,
B,
C,
D,
};
enum Type{
    paver,
    fighter,
    shielded_fighter,
    tank,
    chooper,
};
const char *types[] = { "Paver", "Fighter", "SF","Tank","Chooper"};
struct enemy
{
    int ID;     //Each enemy has a unique ID (sequence number)
    int time_step; //The time step of each enemey
    Region region;  //Region of this enemy
    int Health; //Enemy health
    Type type;  //Paver,Fighter,SHielded fighter
    int reload_power;
    int fire_power;};
struct node
{
    enemy enemyy;
    node* next;
};

I current have a linked list which contains enemies data and should randomly pick a number from 1-4 that represents the number of enemies that should be killed if the number is 1, 1 high priority enemy is killed, if there is no priority enemies 1 normal one is killed same goes for 2, if there is 2 high priority enemies or more 2 are killed, if only 1 exists, he is killed along with a normal one, if none exists 2 normal ones are killed. the maximum number of high priority enemies killed is 2. one thing to note tho, is the deleted nodes are chosen randomly so if the number of high priority enemies is 5, and I must kill 2, these 2 are chosen randomly, they aren't chosen from the end nor the beginning.furthermore, killed enemies are deleted from the actual list and transferred to another one made for dead enemies.

my first idea, was to create 2 lists from the actual linked list I have. one for High priority targets and one for the normal ones,then I would simply randomly delete n number of them but I got lost with all the rands and if conditions.

I made the following functions successfully:

bool merge(node*&temp,node*&temp2){
    if (isEmptyLinked(temp) && isEmptyLinked(temp2))
    {
        return false;
    }
    else if (isEmptyLinked(temp) && !isEmptyLinked(temp2))
    {
        merge(temp2,temp);
    }


        node*temp3=temp2;
        while (temp3->next!=NULL)
        {
            temp3=temp->next;
        }
        temp3->next=temp2;
        return true;
}


  void destroy(node*&head){
        node*temp=head;
        if (head->next==NULL)
        {
        delete head;
        head=NULL;
        }
        else if (head==NULL)
        {
            cout<<"Empty list"<<endl;
        }
        else
        {

        while (head->next!=NULL)
        {
            head=head->next;
            delete temp;
            temp=head;

        }
        delete head;
        head=NULL;
        }
    }
bool deletewithindex(node*&head, int index){
    if (head==NULL || index>countList(head) || index<0)
    {
        return false;
    }
    else if (head->next==NULL || index==0)
    {
        delete head;
        head= NULL;
            return true;
    }
    else
    {
        node*pre=head;
        node*post=head->next;
        int c=1;
        while (c!=index && post!=NULL)
        {
            pre=pre->next;
            post=post->next;
            c++;
        }
        pre->next=post->next;
        delete post;
        post=pre->next;
    }
}
void DivideList(node*&head){
    node* high=NULL;
    node* normal = NULL;
    int counttotal=countList(head);
    while (head!=NULL)
    {
        enemy x;
        if (head->enemyy.type==fighter)
        {
            x.fire_power=head->enemyy.fire_power;
            x.Health=head->enemyy.Health;
            x.ID=head->enemyy.ID;
            x.region=head->enemyy.region;
            x.reload_power=head->enemyy.reload_power;
            x.time_step=head->enemyy.time_step;
            x.type=head->enemyy.type;
            insertatEnd(normal,x);
        }
        else
        {
            x.fire_power=head->enemyy.fire_power;
            x.Health=head->enemyy.Health;
            x.ID=head->enemyy.ID;
            x.region=head->enemyy.region;
            x.reload_power=head->enemyy.reload_power;
            x.time_step=head->enemyy.time_step;
            x.type=head->enemyy.type;
            insertatEnd(high,x);
        }
    }
    srand(time(NULL));
    int numberofdeleted;
    if (counttotal>4){
    numberofdeleted= rand()%4+1;
    }
    else
    {
    numberofdeleted= rand()%counttotal+1;
    }

    int counthigh=countList(high);
    int countnormal=countList(normal);
    if (numberofdeleted>4 && counthigh>=2)
    {
        for (int i = 0; i < 2; i++)
        {

        }
    }
}

I couldn't complete the last function as I couldn't wrap my head around it. Thanks for your time,




R conditional random samples

How can I get a random samples based on conditional values. For example I have the following dataframe:

GROUP CLASS  AGE
A     1      10
A     2      15
B     1      10
B     2      17
C     1      12
C     2      14

I need to get a sample of 30 records for each of the GROUPS, but only from CLASS = 1 compiled all in a sample dateframe.

I Know how to get a sample of 30 records, but I don't know how to create a condition that loops throught the different GROUPS and filters the CLASS

ran.sample = sample(nrow(df_all), 30)
df = df_all[ran.sample, ]

Any ideas?

Thanks