mercredi 31 octobre 2018

Check if one element in array is being used, if so, use another element

How do I check if one element is being used, and if so to use another element on the Switch Case statements.

//Input
function myFunction() {
  
var myArray = ["60","50", "20", "30", "15", "10"];
  var randomJumpingJacks = myArray[Math.floor(Math.random()*myArray.length)];
  var randomCrunches = myArray[Math.floor(Math.random()*myArray.length)];
   
    var workOut = document.getElementById("myInput").value;
  
  
var text = "";
for(const char of workOut.toUpperCase()){
    switch(char) {
        case "A":
        case "I":
        case "N":
        case "X":
            text += randomJumpingJacks;
            text += " Jumping Jacks";
                  
        break;
        case "B":
        case "J":
        case "Q":
        case "Y":
            text += randomCrunches;
            text += " Crunches";       
          break;
          case " ":
            /*text += " break ";*/
        break;
       
        default:
        text += "I have never heard of that fruit...";    
    }
  text +=" "
  text +="<br>"
}
  
    document.getElementById("excercise").innerHTML = text;
}
<!DOCTYPE html>
<html>
<body>

<p>Input some characters  and click the button.</p>
<p>Your excericse routine will display based on your input.</p>

<input id="myInput" type="text">

<button onclick="myFunction()">Try it</button>
<p>
  <span id="reps"></span>
  <span id="excercise"></span>
  </p>

</body>
</html>

Example: I typed: ABBY I'm expecting it to output:

10 Jumping Jacks

15 Crunches

10 Crunches

20 Crunches

I'm unsure if I'm using the correct terminology, but I'm going to refer cases A,I,N,X as Jumping Block, and cases B,J,Q,Y as Crunches Block.

If the chars called are from the same block, there's a tendency to display the same random number.

On the second Char (B) of the Crunches block, it naturally outputs 15, but since it is being used for the first char (also B), I'd like it to use some other element,

and the third char (Y) being on the Crunches block as well, I'd like it to use a different element that are different from the first two elements, and so forth, and repeat after 4 times.

I'd love to know what you think.




Generate table with 1000 random values and average equal to 3 [on hold]

How do I generate a random int value between [1-4] with average equal to 3




C++: Generate random numbers with a given (numerical) distribution

TL&DR:

How to implement a function in C++ like numpy.random.choice(numpy.arange(1, 7), p=[0.1, 0.05, 0.05, 0.2, 0.4, 0.2]) in Python?


Related Question Generate random numbers with a given (numerical) distribution

I have a file with some probabilities for different values e.g.:

1 0.1
2 0.05
3 0.05
4 0.2
5 0.4
6 0.2

I would like to generate random numbers using this distribution in C++. Does an existing module that handles this exist?

Thx in advance.




Random Number generating in java without having any number of 0 in it

I have to generate 5 digit random number , without having any 0 in it. I have tried with below code, sometimes it works and sometimes it doesn't Is there any better way to do this?

public  Integer generateLastFiveSequenceNumbers()
        {
            Random ranndomNumber = new Random();
            Random replaceNumber = new Random();

            Integer fiveDigitRanndomNumber = 11111 + ranndomNumber.nextInt(99999);
            Integer replaceZeroNumber = 1 + replaceNumber.nextInt(9);


            String tempValidation = fiveDigitRanndomNumber.toString();
            char[] ch = tempValidation.toCharArray();

            for(int i = 0 ; i < ch.length-1 ;i++)
            {
                if(ch[i]=='0')
                {
                    ch[i] = '1'; 

                }
            }

            String newValue = new String(ch);
            Integer finalNumber = Integer.parseInt(newValue);
            return finalNumber;
        }




find average between two random numbers in java

Hello again StackOverflow,

New question needing help with some code. So far I'm making a random number generator that will choose a random number between 1-100 for rolls and then roll a "die" for a number between 1-6. It then prints out every roll and number rolled up to said random number between 1-100.

The problem I'm having is this. Let's be simple and say that the random number generated between 1-100 is 9 and the die rolls in order for each roll is

1, 6, 3 , 5, 4, 2, 1, 6, 6

That output is fine. The problem is that I need to take all these random numbers, add them together, then divide that sum by the random number between 1-100 (in the example case above, 9). I don't know how to do that. Help please?

My Current Code:

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

    int rolls = (int)(Math.random()*100);
    System.out.println("Number of Rolls: "+ rolls);

    System.out.println(" ");
    System.out.println("Rolls\t\tNumber");
    for (int i = 1; i <= rolls ; i++)
      {
        int dienumber = (int)(Math.random()*6+1);    
        System.out.println(i + "\t\t" + dienumber);
      }

    //(this space is left blank for the code I need)

  }
}




Generate Random numbers from tuple list in Python

I have a tuple list containing numbers with a certain probability assigned:

    import random
    my_randoms = [random.randrange(1, 51, 1) for _ in range(10)]

    weights = [0.1, 0.2, 0.05, 0.03, 0.15, 0.05, 0.2, 0.02, 0.09, 0.11]

    aa = list(zip(my_randoms, weights))    

    aa
        Out[40]: 
    [(7, 0.1),
 (5, 0.2),
 (47, 0.05),
 (21, 0.03),
 (13, 0.15),
 (32, 0.05),
 (41, 0.2),
 (1, 0.02),
 (47, 0.09),
 (19, 0.11)]

I would like to randomly generate 100 numbers from the list given the probability distribution that I assigned. How could I do this? Thanks!




mardi 30 octobre 2018

How to Reverse an array in a method? (java) [duplicate]

This question already has an answer here:

So I have a question that tells me I need to create an int array, initialize this array with random ints between 200 and 300, and then I need to call a function which I pass this array to, and then the function should create a new array and copy the array that it's passed, but in reverse order, and then main should display the original array and the returned one. Here's what i have:

import java.util.Random;
public class Q {


public static void main(String[] args) { 
Random r = new Random();
int[] a = new int[100];
for (int i = 0; i < a.length; i++)
{
 a[i] = r.nextInt(300)+200; 
}


System.out.println(a);
System.out.println(reverse(a));

}

public static int[] reverse(int[] x)
{

int []t = new int[x.length];

for (int i = t.length-1; i >= 0; i--)
{
  t[(x.length - i - 1)] = x[i];
}
return t;
}
}

I feel like I'm on the right track, but the console ends up displaying all these weird characters. Thanks for any help.




Java - printing all random numbers at the last line of the while loop

I have the while loop running and processing properly. When the numbers that the user entered do not match the random number, the code prints out "Sorry ...(and proceeds to explain what the right number is)" each time the user is wrong. However, I cannot get the code to print out those same exact random numbers at the very end of the last loop before it terminates. Any suggestions?

   while (counter < 6)
        {
          counter++;
          System.out.println("Enter a number between 1-60: ");
          userInput = scan.nextInt();
          if (userInput > 60 || userInput < 1)
            System.out.println("Invalid input");

          int randomNumber = (int) (Math.random() * 60) + 1;
          if (userInput == randomNumber)
            System.out.println("Congrats, you have won!");
        else
          System.out.println("Sorry, you didn't choose the winning number." + "The winning number is " + randomNumber + ".");
        }

The bottom of the code has the winning number, but I want all of those same exact random numbers (which were randomized earlier) to show up at the end of the sixth loop. Also, the order of the user input does not influence the results. If the user chooses 1-13-8-34-56-2 and the computer had come up with 1-8-56-2-14-34…there would still be 5 matching numbers




How to output a word based on the probability of it occurring in a text?

Say I have 3 words and a frequency of them occurring in a piece of text.

For example:

be (1)

not (1)

have (2)

Since the total frequency of all the words is 4, I generate a random number between 0-3 or 1-4. How would I use this random number so that the program outputs "be" 1/4 of the time, "not" 1/4 of the time, and "have" 1/2 of the time?




random.sample(my_set, 1) appears not to be deterministic over multiple runs with the same seed

When writing simulation code, I always print out the random seed and maintain provision to specify it in a future run. That way, if anything unusual occurs during a run, I can duplicate that exact run to figure out what is going on.

I have found that when my current code involves random.sample() from a set, multiple runs using the same seed do not follow the same trajectory.

A minimal code example appears here and also below. In this code, I use random.sample() on a list and on a set. The random.samples from the set fail in the described manner.

It is also of interest that for sampling from a set, the results vary considerably when printing is done to the screen vs. redirecting stdout from the shell to a file. When output is redirected to a file, sampling from the set gives less variation over multiple invocations than when output is sent to the screen.

Here is what I see in a file ('rm foo', then 'python rantest.py >> foo', repeatedly). Each pair in parenthesis is the single line printed by an invocation of the program. The first number printed is the sample from the set; the second is the sample from the list:

(6 0) (0 0) (0 0) (7 0) (6 0) (6 0) (7 0) (0 0) (0 0) (0 0)

And here are the the results from the screen ('python rantest.py', repeatedly):

(7 0) (7 0) (7 0) (7 0) (7 0) (7 0) (7 0) (8 0) (7 0) (7 0)

I am on MacOS 10.14, running Python Python 3.7.0 (Anaconda).

import random

random.seed(12345)

class Texs():
    ''' Create x objects and keep track of the collection within the class '''

    all_my_xs_set = set()
    all_my_xs_list = []
    nxs = 0

    @classmethod
    def add_x(cls):
        ''' Create a new x and add it to the collection '''
        x = cls()
        cls.all_my_xs_set.add(x)
        cls.all_my_xs_list.append(x)
        cls.nxs += 1

    def __init__(self):
        self.i = Texs.nxs

for i in range(10):
    Texs.add_x()

x = random.sample(Texs.all_my_xs_set, 1)[0]
y = random.sample(Texs.all_my_xs_list, 1)[0]

print(x.i, y.i)




Java create arrays with random integers using for loop [duplicate]

I'm new to programming and would appreciate some help. I am trying to create multiple arrays populated with random integers and got stuck.

My ideal goal is to create 3 arrays, each size of 10, 100, 1000, filled with random integers between 100 and 1000.

Random rand = new Random();
int array10[] = new int[10];
int array100[] = new int[100];
int array1000[] = new int[1000];
int array10000[] = new int[10000];

I've been searching through and I saw people using

    int arr[][] = new int[][];

Is this something that I need to use? Or should I use a nested loop that first creates arrays, and then fill it with random numbers?




Projects ideas about fractals, random walks, space, chaos

Is there any practical applications of random walks ?

Is there something else besides terrain and tree generation with fractals ?

Is there any practical applications of chaos game ?

If you have any project ideas don't hesitate !




Python - Appending array element to dictionary value

# Create an array of integers from 1–16.
random_rankings = list(range(1, 17))
# Shuffle the array.
random.shuffle(random_rankings)
for ranking in random_rankings:
    all_players = {k: ranking if not v else v for k, v in all_players.items()}
print(all_players)

I am trying to change the empty values ('') in the dictionary to random numbers (without duplicates). So I made an array 1-16 and shuffled it. When trying to append a single integer from that to the individual values, the same number is being appended, e.g.

{'Rick Sanchez': 16, 'Morty Smith': 16, 'Beth Smith': 16, 'Jerry Smith': 16, 'Summer Smith': 16, 'Scary Terry': 16, 'Xenon Bloom': 16, 'Abradolf Lincler': 16, 'Krombopulos Michael': 16, 'Blim Blam ': 16, 'Alan Rails': 16, 'Tophat Jones': 16, 'Doofus Rick': 16, 'Million Ants': 16, 'Scroopy Noopers': 16, 'Pichael Thompson': 16}

I wanted each name to have a different number from the array. What am I doing wrong?

EDIT: I also tried...

if any(all_players.values()) == False:
        print("No rankings in csv file\nAssigning random rankings")
        # Create an array of integers from 1–16.
        random_rankings = list(range(1, 17))
        # Shuffle the array.
        random.shuffle(random_rankings)
        for value in all_players.values():
            for ranking in random_rankings:
                value = ranking
    print(all_players)

But now I get an error




assigning random values from List into List C#

I'm working on a code that assigns a random numbers from List A into a group of objects in List B

Here is the details:

I have a List of Campaigns and List of CampaignRecipients, and I need to cover three scenarios:

  1. When I have equal count on both lists, 2 campaigns and 2 recipients "I have no issue with it at all, it randomly picks a campaignID and assigns it to a randomly picked recipient from List B and so on.
  2. When I have 3 campaigns and 1000 recipients, so it will divide the List of recipients into three groups and assigns each group a randomly picked campaign ID.
  3. When having 5 campaigns and 3 recipients, then it will randomly pick 3 campaigns and assigns them to the recipients.

In point 2 where I'm having a problem with it and it takes very long time as i stated, it distributes the numbers as I want but it is very slow when dealing with 1k recipients or more.

Here is my code, maybe i'm doing something wrong, any suggestion of change needed? Note: i have no problem to change the approach if needed

private static void RandomizeScenarios(ref IList<CampaignLib> cmp, ref IList<CampaignRecipientLib> rec)
        {
            IEnumerable<int> RecipientsIds = rec.Select(x => x.ID).ToList();
            IList<int> CampaignsIds = cmp.Select(x => x.CampaignId.Value).ToList();
            int initVal = RecipientsIds.Count() / CampaignsIds.Count;
            int i = 0;

            if (CampaignsIds.Count < rec.Count())
            {
                List<CampaignRecipientLib> tmpRecipients = new List<CampaignRecipientLib>();

                foreach (var item in CampaignsIds)
                {
                    i++;
                    IEnumerable<int> tmp = null;

                    if (i < CampaignsIds.Count) tmp = RecipientsIds.Shuffle().Take(initVal);
                    else tmp = RecipientsIds.Shuffle().Take(RecipientsIds.Count());


                    RecipientsIds = from r in RecipientsIds where !tmp.Contains(r) select r;

                    var PartialRecipients = from r in rec where tmp.Contains(r.ID) select r;


                    // HERE IT TAKES A VERY LONG TIME < 35mins for 2.5K objects
                    PartialRecipients.ToList().ForEach(r => r.CampaignId = item);

                    tmpRecipients.AddRange(PartialRecipients);

                }
                rec = tmpRecipients;
            }
            else if (CampaignsIds.Count == rec.Count())
            {
                foreach (var item in CampaignsIds)
                {
                    int tmp = RecipientsIds.Shuffle().Take(1).FirstOrDefault();

                    RecipientsIds = from r in RecipientsIds where tmp != r select r;

                    rec.FirstOrDefault(x => x.ID == tmp).CampaignId = item;                  
                }
            }
            else if (CampaignsIds.Count > rec.Count())
            {
                foreach (var item in CampaignsIds.PickRandom(RecipientsIds.Count()).OrderBy(x => x))
                {
                    int tmp = RecipientsIds.Shuffle().PickRandom(1).FirstOrDefault();

                    RecipientsIds = from r in RecipientsIds where tmp != r select r;

                    rec.FirstOrDefault(x => x.ID.Equals(tmp)).CampaignId = item;
                }
            }

        }




Java - sum of prime numbers of random-generated array-values

I am a beginner in Java and I have a task to do, to calculate the sum of prime numbers from the random-generated values of an array.

So, I was told that I should have 3 classes:

1) MyArray - where I have already written this code:

    ...
    public int[] createArray(int n) {
        int[] a = new int[n];

        for (int i = 0; i < a.length; i++) {
            a[i] = rnd.nextInt(10);
        }
        return a;
    }
    ...

2) IsPrime - where I should do the checking if a number is a prime or not. The problem is I don't know how to 'connect' the array from MyArray to the IsPrime class. I started with a boolean method checkPrime, that has an object m from the MyArray class as a parameter, but I don't know how to continue, how to access the array from the IsPrime class.

I am thankful for any given opinions and advice. Thank you!

P.S. My third class Run.java has the main-method.




randomize array order Angular 4

im trying to randomize the order of my array in my Angular6 project. I have no idea how to do it and ended up tying to sort the aray with the Math.random function... (didn't work XD)

this is my code so far:

HTML

    <div style="background: darkcyan; width: 600px; height: 600px; margin: auto">
  <table>
    <tr *ngFor="let card of cards">
      <div id="" [ngStyle]="{'background-color': card.color}" style=" width: 100px; height: 125px; margin: 5px"></div>
    </tr>
  </table>
</div>
<button (click)="shuffle()">Shuffle Cards</button>

TypeScript

import { Component, OnInit } from '@angular/core';

@Component({
  selector: 'app-memory-game',
  templateUrl: './memory-game.component.html',
  styleUrls: ['./memory-game.component.css']
})
export class MemoryGameComponent implements OnInit {
  cards = [];
  constructor() { }

  ngOnInit() {
    this.cards = [
        {
          'id': 1,
          'color': 'red'
        },
        {
            'id': 2,
            'color': 'green'
        },
        {
            'id': 3,
            'color': 'blue'
        },
        {
            'id': 4,
            'color': 'yellow'
        }
    ];
      this.shuffle();
  }

  public shuffle() {
      this.cards.sort(Math.random);
  }
}

I don't know if there is an easy solution, but I really hope someone is able to help me out..

Thanks




Getting true random values for production software?

I need a service or an API for software in production to get true random numbers. For example CloudFlare has their "wall of entropy" and I have found random.org too, but I did not find any ways of getting true random values from CloudFlare, and random.org limits the number of requests.

I need a reliable and certified service. As a last option I know I could get hardware for doing the job, but it would be easier to just pay for a provider for this service based on requests or sg.

Any ideas? I googled a lot but have not found anything yet.




picking random user from online searching users and making a match using firebase - Android Studio

which uses the ideas of these apps:

1) LivU: Meet new people & Video chat with strangers

2) Live Chat - Meet new people via free video chat

These apps lets the users to search and connect to a random online user, i have a made a FirebaseDatabase ref("searchingUsers") for the algorithm,

My searching child screenshot

When userA and userB are searching userB gets connected to userA, but the problem is that at the time of connection userC often get connected with userB. please help me out with this, It will be very kind if any one explain the whole algo. thanks in advance!




Trying to get a random number with a chance to get that number

I tried to create this, but it does not really, work. Here is the table of how I want it to work.. click to see picture

But it doesnt work like that. Here is a picture of my database (in phpmyadmin) click to see picture

I want it to first look at the percentages, and find which one to use. So 75% chance to get a random number between 1 and 50. 20% chance for a random number between 51 and 200 etc.


Here is my code;

if ($_GET['method'] == "test") {
    $sql = "SELECT 1percentage, 1min, 1max, 2percentage, 2min, 2max, 3percentage, 3min, 3max, 4percentage, 4min, 4max FROM `keys`";
    $result = $conn->query($sql);
    while($row = $result->fetch_assoc()) {
            $total = $row["1percentage"] + $row["2percentage"] + $row["3percentage"] + $row["4percentage"] + 1;
            $random = rand(0, $total);
            if ($random < $row['1percentage'] || $random == $row['1percentage']) {
                $amount = rand($row['1min'], $row['1max']);
            } elseif ($random > $row['1percentage'] && $random < $row['2percentage'] || $random == $row['2percentage']) {
                $amount = rand($row['2min'], $row['2max']);
            } elseif ($random > $row['2percentage'] && $random < $row['3percentage'] || $random == $row['3percentage']) {
                $amount = rand($row['3min'], $row['3max']);
            } elseif ($random > $row['4percentage'] || $random == $row['4percentage']) {
                $amount = rand($row['4min'], $row['4max']);
            } else {
                exit("0");
            }

            echo $amount;
        }
}

But what it outputs is or 1 to 50, or 1001 to 10000. So what did I do wrong? Thanks!




C text game segmentation fault and debugging

I wanted to wrote a simple text game in C. The game generates random 2D position using 2 double variables in range from -10.000 to 10.000 (X, Y) as the "treasure" position. Player begins at position 0.000, 0.000. Then the game asks the player which directions to go in X and Y. After that the game needs to give the player a simple hint, if he's getting closer(right or wrong direction based on the treasure position). When the player is less than 0.050 away from treasure in any direction, the game ends and prints out the score(cycle steps).

I wrote this, but I'm getting 'Segmentation fault' and I'm also interested about how would you modify it to get it more effective and functional.

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

int main()
{
srand (time(NULL));
char *direction_x;
char *direction_y;
double direction_forward;
double direction_back;
double direction_left;
double direction_right;
double score_x;
double score_y;
double diff_x;
double diff_y;
double lastmove_x;
double lastmove_y;  
int i;



double random_x = (double)rand()/RAND_MAX*20.000-10.000;
double rounded_x = (int)(random_x * 1000.0)/1000.0;
printf ( "%f\n", random_x);
printf ( "%.3f\n", rounded_x);


double random_y = (double)rand()/RAND_MAX*20.000-10.000; 
double rounded_y = (int)(random_y * 1000.0)/1000.0;
printf ( "%f\n", random_y);
printf ( "%.3f\n", rounded_y);

double player_x=0.000;
double player_y=0.000;
printf("Hello freind! Let's find the hidden treasure!\n");

do{
  i++;
      printf("Where would you want to go? ('straight', 'back')\n");

  scanf("%s", &direction_x);
  if (strcmp(direction_x, "straight") == 0)
  {
    printf("How far?\n");
    scanf("%f", &direction_forward);
    player_x = player_x + direction_forward;
    printf("You've walked %.3f straight!\n", direction_forward);
    printf("Your current postion is: %.3f, %.3f.\n", player_x, player_y);
    diff_x = random_x - player_x;
    if (diff_x < random_x) 
    {
      printf("You're closer...\n");  
    }
    else
    {
      printf("Don't like this way...\n");
    }
  }

  else if (strcmp(direction_x, "back") == 0)
  {
    printf("How far?\n");
    scanf("%f", &direction_back);
    player_x = player_x - direction_back;
    printf("You've walked %.3f backwards!\n", direction_back);
    printf("Your current position is: %.3f, %.3f.\n", player_x, player_y);
    if (diff_x < random_x) 
    {
      printf("You're closer...\n");  
    }
    else
    {
      printf("Don't like this way...\n");
    }
  }
  else
  {
    printf("Don't accept this direction...\n");
  }
      printf("Where now? ('left', 'right')\n");

  scanf("%s", &direction_y);
  if (strcmp(direction_y, "left") == 0)
  {
    printf("How far?\n");
    scanf("%f", &direction_left);
    player_y = player_y + direction_left;
    printf("You've walked %.3f left!\n", direction_left);
    printf("Your current position is: %.3f, %.3f.\n", player_x, player_y);
    if (diff_y < random_y) 
    {
      printf("You're closer...\n");  
    }
    else
    {
      printf("Don't like this way...\n");
    }
  }

  else if (strcmp(direction_y, "right") == 0)
  {
    printf("How far?\n");
    scanf("%f", &direction_right);
    player_y = player_y - direction_right;
    printf("You've walked %.3f right!\n", direction_right);
    printf("Your current position is: %.3f, %.3f.\n", player_x, player_y);
    if (diff_y < random_y) 
    {
      printf("You're closer...\n");  
    }
    else
    {
      printf("Don't like this way...\n");
    }
  }
  else 
  {
    printf("Don't accept this direction...\n");     
  }

  score_x = (player_x + 0.050) - random_x; 

  score_y = (player_y + 0.050) - random_y;


}while ((-0.050 <= score_x <= 0.050) || (-0.050 <= score_y <= 0.050));

printf("Congratulations, treasure was finally founded! Treasure position is %.3f, %.3f.\n", random_x, random_y);
printf("Score (steps taken, less is better): %d\n", i);
return 0;

}




Gforth random generator has no seed

The following program in gforth prints out 10 random numbers between 0 and 2:

require random.fs
: main 10 0 do i cr . 3 random . loop ;
main

The problem is, that after each start, the numbers are the same. That means no time(0) seed was used. How can i get random numbers which are different on each start?




lundi 29 octobre 2018

generate non duplicate integers in LUA

I am very new in programming in lua

I am trying to generate 5 random non duplicate values between 0,500 and assign them to 5 variables using LUA.

So far I have used the following code which unsuccessfully attempts to generate the random numbers and assigns the values. The problem is:

1 - this code is sometime generating the duplicate numbers 2 - the name which I want to look like x-1, x-2 and so on, prints like x-1, x-12.

Can you please help me with this.

Thanks in advance.

Ed

Example:

v_Name = "x-"
for i =1, 5 do
  X = math.random (0, 500)
  v_Name = v_Name..(i)
  print (v_Name)
  print (X)
 end 




Why is random number generator tf.random_uniform in tensorflow much faster than the numpy equivalent

The following code is what I used to test the performance:

import time
import numpy as np
import tensorflow as tf

t = time.time()
for i in range(400):
    a = np.random.uniform(0,1,(1000,2000))
print("np.random.uniform: {} seconds".format(time.time() - t))

t = time.time()
for i in range(400):
    a = np.random.random((1000,2000))
print("np.random.random:  {} seconds".format(time.time() - t))

t = time.time()
for i in range(400):
    a = tf.random_uniform((1000,2000),dtype=tf.float64);
print("tf.random_uniform: {} seconds".format(time.time() - t))

All the three segments generate a uniformly random 1000*2000 matrix in double precision 400 times. The timing differences are striking. On my Mac,

np.random.uniform: 10.4318959713 seconds
np.random.random:  8.76161003113 seconds
tf.random_uniform: 1.21312117577 seconds

Why is tensorflow much faster than numpy?




Mystery Number Game (Java)

I want the computer to choose a random number between 1 and 100 and then the user will repeatedly guess until they guess correctly.

Example I'm thinking of a number between 1-100. Can you guess it? Guess # 1: 50 Sorry, you are too low. Guess # 2: 75 Sorry, you are too low. Guess # 3: 87 Sorry, that guess is too high. Guess # 4: 82 Sorry, you are too low. Guess # 5: 84 You guessed it!

My code seems to generate an extra guess for some reason, how can I make it generate the right amount of guesses?

Here is my code:

import java.util.Scanner;
import java.util.Random;
public class Main {
public static void main(String[] args) {
Scanner scnr = new Scanner(System.in);

  System.out.println("Enter a seed for the random number generator:");
  int seed = scnr.nextInt(); 
  Random random = new Random(seed);
  int compNum = (int)(Math.random()*100) + 1;
  int numGuess=1;
  int userGuess=-1;

  System.out.println();

  System.out.println("I'm thinking of a number between 1-100. Can you guess it? ");

  do {
  System.out.println("Guess " + "# " + numGuess);
  userGuess = scnr.nextInt();

  if (compNum > userGuess) {
  System.out.println("Sorry, you are too low.");


  }
  else if (compNum < userGuess) {
  System.out.println("Sorry, that guess is too high.");

  }
  else if (compNum==userGuess) {
     System.out.println("You guessed it! ");
  }

  ++numGuess;

  }while (compNum!=userGuess) ;
   }
}




How can I get random numbers between -1024 and 1024 in vhdl

I am really beginner in VHDL and I am trying to make a hot-n-cold game. My first goal is generating numbers between -1024 and 1024 so that I can use 10 switches to guess. However, there are a lot of sources about positive integers but I could not find any for negative ones. Here is a sample code of mine. Also, someone says LFSR does this job but I am new and I could not understand the behavior of LFSR.

library ieee;
use ieee.math_real.all;

entity rand_gen is
end rand_gen;

architecture behavior of rand_gen is 

signal rand_num : integer := 0;

begin

process
    variable seed1, seed2: positive;              
    variable rand: real;   
    variable range_of_rand : real := 1024.0;   
begin
    uniform(seed1, seed2, rand);   
    rand_num <= integer(rand*range_of_rand);  
    wait for 10 ns;
end process;

end behavior;




Javascript Random Quote Generator - how to have quote appear as page first loads

I am building a random quote generator as my first javascript project. I am getting the quotes to work fine, but I would love to have them displaying as someone first visits the site, and not just when someone first clicks on the button.

Here is my code so far:

<div id="quoteDisplay">
  <!-- Quotes will display here -->
</div>
<!-- Center is added for button placement -->

  <button onclick="newQuote()">New Quote</button>

<script type="text/javascript" src="ron.js"></script>

and the javascript:

var quotes = ["quote 1", "quote 2", "quote 3",]

function newQuote() {
var randomNumber = Math.floor(Math.random() * (quotes.length));
document.getElementById('quoteDisplay').innerHTML = quotes[randomNumber];

}

any suggestions on what to add to make a quote display when a user first visits page?




How do I generate a random number from 0 to 1 in c++

I'm trying to build an algorithym in c++ based in a JAVA code, ande the example i'm following uses java.lang.Math.random() which generates a random number from 0 to 0.9999.

How to I create the same in c++?




how to use php to generate random 10 digit number that begin with the same two digitsusing php

I'm working on a banking and investment website/system for my school project, please can someone help me with a PHP code that generates a random 10 digits account number when users register, but the account numbers all have to start with the same two-digit numbers like 01, thank you




Is the new random library really better than std::rand()?

So I saw a talk called rand() Considered Harmful and it advocated for using the engine-distribution paradigm of random number generation over the simple std::rand() plus modulus paradigm.

However, I wanted to see the failings of std::rand() firsthand so I did a quick experiment:

Basically, I wrote 2 functions getRandNum_Old() and getRandNum_New() that generated a random number between 0 and 5 inclusive using std::rand() and std::mt19937+std::uniform_int_distribution respectively.

Then I generated 960,000 (divisible by 6) random numbers using the "old" way and recorded the frequencies of the numbers 0-5. Then I calculated the standard deviation of these frequencies. What I'm looking for is a standard deviation as low as possible since that is what would happen if the distribution were truly uniform.

I ran that simulation 1000 times and recorded the standard deviation for each simulation. I also recorded the time it took in milliseconds.

Afterwards, I did the exact same again but this time generating random numbers the "new" way.

Afterwards, I calculated the mean and standard deviation of the list of standard deviations for both the old and new way and the mean and standard deviation for the list of times taken for both the old and new way.

Here were the results:

[OLD WAY]
Spread
       mean:  346.554406
    std dev:  110.318361
Time Taken (ms)
       mean:  6.662910
    std dev:  0.366301

[NEW WAY]
Spread
       mean:  350.346792
    std dev:  110.449190
Time Taken (ms)
       mean:  28.053907
    std dev:  0.654964

Surprisingly, the aggregate spread of rolls was the same for both methods. I.e., std::mt19937+std::uniform_int_distribution was not "more uniform" than simple std::rand()+%. Another observation I made was that the new was about 4x slower than the old way. Overall, it seemed like I was paying a huge cost in speed for almost no gain in quality.

Is my experiment flawed in some way? Or is std::rand() really not that bad, and maybe even better?

For reference, here is the code I used in its entirety:

#include <cstdio>
#include <random>
#include <algorithm>
#include <chrono>

int getRandNum_Old() {
    static bool init = false;
    if (!init) {
        std::srand(time(nullptr)); // Seed std::rand
        init = true;
    }

    return std::rand() % 6;
}

int getRandNum_New() {
    static bool init = false;
    static std::random_device rd;
    static std::mt19937 eng;
    static std::uniform_int_distribution<int> dist(0,5);
    if (!init) {
        eng.seed(rd()); // Seed random engine
        init = true;
    }

    return dist(eng);
}

template <typename T>
double mean(T* data, int n) {
    double m = 0;
    std::for_each(data, data+n, [&](T x){ m += x; });
    m /= n;
    return m;
}

template <typename T>
double stdDev(T* data, int n) {
    double m = mean(data, n);
    double sd = 0.0;
    std::for_each(data, data+n, [&](T x){ sd += ((x-m) * (x-m)); });
    sd /= n;
    sd = sqrt(sd);
    return sd;
}

int main() {
    const int N = 960000; // Number of trials
    const int M = 1000;   // Number of simulations
    const int D = 6;      // Num sides on die

    /* Do the things the "old" way (blech) */

    int freqList_Old[D];
    double stdDevList_Old[M];
    double timeTakenList_Old[M];

    for (int j = 0; j < M; j++) {
        auto start = std::chrono::high_resolution_clock::now();
        std::fill_n(freqList_Old, D, 0);
        for (int i = 0; i < N; i++) {
            int roll = getRandNum_Old();
            freqList_Old[roll] += 1;
        }
        stdDevList_Old[j] = stdDev(freqList_Old, D);
        auto end = std::chrono::high_resolution_clock::now();
        auto dur = std::chrono::duration_cast<std::chrono::microseconds>(end-start);
        double timeTaken = dur.count() / 1000.0;
        timeTakenList_Old[j] = timeTaken;
    }

    /* Do the things the cool new way! */

    int freqList_New[D];
    double stdDevList_New[M];
    double timeTakenList_New[M];

    for (int j = 0; j < M; j++) {
        auto start = std::chrono::high_resolution_clock::now();
        std::fill_n(freqList_New, D, 0);
        for (int i = 0; i < N; i++) {
            int roll = getRandNum_New();
            freqList_New[roll] += 1;
        }
        stdDevList_New[j] = stdDev(freqList_New, D);
        auto end = std::chrono::high_resolution_clock::now();
        auto dur = std::chrono::duration_cast<std::chrono::microseconds>(end-start);
        double timeTaken = dur.count() / 1000.0;
        timeTakenList_New[j] = timeTaken;
    }

    /* Display Results */

    printf("[OLD WAY]\n");
    printf("Spread\n");
    printf("       mean:  %.6f\n", mean(stdDevList_Old, M));
    printf("    std dev:  %.6f\n", stdDev(stdDevList_Old, M));
    printf("Time Taken (ms)\n");
    printf("       mean:  %.6f\n", mean(timeTakenList_Old, M));
    printf("    std dev:  %.6f\n", stdDev(timeTakenList_Old, M));
    printf("\n");
    printf("[NEW WAY]\n");
    printf("Spread\n");
    printf("       mean:  %.6f\n", mean(stdDevList_New, M));
    printf("    std dev:  %.6f\n", stdDev(stdDevList_New, M));
    printf("Time Taken (ms)\n");
    printf("       mean:  %.6f\n", mean(timeTakenList_New, M));
    printf("    std dev:  %.6f\n", stdDev(timeTakenList_New, M));
}




dimanche 28 octobre 2018

Function wont switch out images when trying to use a random number

im working on a slot machine game where i take 3 random numbers and assign them to different images. However i can not get my images to diplay when you click the button to play the game. I have the stock images there but when you click SPIN it should put up some new images based on the random number it gave. If you could help me figure out how to get the new images to display that would be great. (sorry if its a silly mistake, im new to coding)

these are the image boxes:

< div class="SlotDiv" id="div_1">< image id="slot_1" src="images/lemon.jpg">< /image>< /div> < div class="SlotDiv" id="div_2">< image id="slot_2" src="images/cherry.jpg">< /image>< /div> < div class="SlotDiv" id="div_3">< image id="slot_3" src="images/bar.jpg">< /image>< /div>

(there arnt spaces in the front of these in the real code, they wont appear in the thread if i dont put the spaces for some reason)

<html>

Slots

    <link href="../style.css" type="text/css" rel="stylesheet">

<script type="text/javascript" src="random.js">

    function spinslots()
        {
            var lemon = document.getElementById('lemon.jpg');
            var donut = document.getElementById('donut.jpg');
            var cherry = document.getElementById('cherry.jpg');
            var bar = document.getElementById('bar.jpg');

            var random_1;
                random_1= Math.floor((Math.random()*4 )+ 1);
            var random_2;
                random_2 = Math.floor((Math.random()*4 )+ 1);
            var random_3;
                random_3 = Math.floor((Math.random()*4 )+ 1);

            if (random_1 == 1)
                {
                    document.getElementById("slot_1").src = "lemon.jpg";
                }
            if (random_1 == 2)
                {
                    document.getElementById("slot_1").src = "donut.jpg";
                }
            if (random_1 == 3)
                {
                    document.getElementById("slot_1").src = "cherry.jpg";
                }
            if (random_1 == 4)
                {
                    document.getElementById("slot_1").src = "bar.jpg";
                }


            if (random_2 == 1)
                {
                    document.getElementById("slot_2").src = "lemon.jpg";
                }
            if (random_2 == 2)
                {
                    document.getElementById("slot_2").src = "donut.jpg";
                }
            if (random_2 == 3)
                {
                    document.getElementById("slot_2").src = "cherry.jpg";
                }
            if (random_2 == 4)
                {
                    document.getElementById("slot_2").src = "bar.jpg";
                }


            if (random_3 == 1)
                {
                    document.getElementById("slot_3").src = "lemon.jpg";
                }
            if (random_3 == 2)
                {
                    document.getElementById("slot_3").src = "donut.jpg";
                }
            if (random_3 == 3)
                {
                    document.getElementById("slot_3").src = "cherry.jpg";
                }
            if (random_3 == 4)
                {
                    document.getElementById("slot_3").src = "bar.jpg";
                }

                if (random_1 == random_2 == random_3)
                    {
                        alert("Congradulations, you won!");

                    }


        }

</script>

Test your luck! Click the SPIN button

<p><button value="Spin" onclick="spinslots();"> SPIN </button></p>

<p>Credits: <div class="OutputBox" type="numeric" id="Credits" size="10">20</div></p>




Method that generates two random numbers within a changeable range

So for part of my assignment I need to create a method of a random math generator in which you can practice addition, subtraction, multiplication, and division on.

I need to create a method in which the range is different based on what operation you are doing.. For example

1. Addition problems

  • Both operands should be random numbers in the range, 1 to 500, inclusive

2. Subtraction problems

  • Both operands should be random numbers in the range, 1 to 999, inclusive
  • But the second operand, (the number being subtracted from the top number) should be less than or equal to the first operand

3. Multiplication problems

  • The first operand (top number) must be in the range of 1 to 100, inclusive.
  • The second operand (bottom number) must be in the range of 1 to 9, inclusive.

4. Division problems

  • The range for the divisor (operand 2) must be from 1 to 9, inclusive
  • The dividend (operand 1) must have a value such that the resulting quotient is always in the range of 1 to 50, inclusive

Then after that, I would do an if else statement that looks similar to this:

correctAnswer = firstRandomNumber + secondRandomNumber
if (userInput = correctAnswer) 
{
system.out.println ("Correct!");
}
else 
{
system.out.println ("Wrong!");
}

How would I go on about doing this?




How std::random_device is implemented

I tested the following mini example with MSVC 2017 on Win7:

#include <iostream>
#include <random>

int main()
{
    std::random_device rd;
    std::cout << "entropy: " << rd.entropy() << std::endl;
    return 0;
}

To my surprise, it outputs "entropy: 32". This means that rd produces real-random numbers instead of pseudo-random numbers. I was expecting "entropy: 0". As far as I understand it, no finite-length code is capable of producing real-random numbers, it takes a real specially-designed physical device to do so. No such device is attached to my testing PC.

My question is: how std::random_device is implemented that it produces real-random number without special hardware support?




Is it possible to find an index of a randomly-chosen JavaScript Object property (if said property is an array/object)? [duplicate]

This question already has an answer here:

var geartable = {
  shittyboots: {
    name: "Shitty Boots",
    cost: "500"
  },
  shittyarmor: {
    name: "Shitty Armor",
    cost: "1000"
  },
  shittyhelmet: {
    name: "Shitty Helmet",
    cost: "750"
  }
};

var shops = {
  positions: [
    [2, 3],
    [0, 1],
    [2, 4]
  ],
  inventory: [
    [geartable.shittyboots.name, geartable.shittyboots.cost, "Available"],
    [geartable.shittyarmor.name, geartable.shittyarmor.cost, "Available"],
    [geartable.shittyhelmet.name, geartable.shittyhelmet.cost, "Available"]
  ]
};

function pickRandomItem(gearlist) {
  var result;
  var count = 0;
  for (var item in gearlist) {
    if (Math.random() < 1 / ++count) {
      result = item;
    }
  }
  console.log(geartable.result.cost);
  return result;
}

Hi there. So, my problem, put simply, is that I'm trying to access an index/a property of a parent object property, but when I run the random selector function (pickRandomItem) on geartable and try to access a property of the result, it tells me that geartable.result.cost is undefined. I assume this is because, for some god forsaken reason, JavaScript is trying to find a property 'result' inside of geartable instead of looking for a property with the value of result inside of geartable.

Is there any way around this? I'm at the end of my rope and I can't imagine there is, due to the fact that object nesting is already pretty shifty as-is. I've tried this with arrays in the place of nested objects, but geartable.result[0]... etc still returns undefined.

This is the error in the JavaScript console, if you're curious:

pickRandomItem(geartable);
TypeError: geartable.result is undefined; can't access its "cost" property[Learn More]




Call a list of functions with random parameters

How can I call a set of functions using random arguments.

import random

def sum_3 (a):
    return (sum(a) + 3)
def sum_2 (b):
    return (sum(b) + 2)

# Call the functions 
functions = [sum_3, sum_2]
# Using random arguments
random.sample(range(1, 100000), 5)




how to get random quiz question from and add listener on end of questions in quiz

I am teacher and creating a quiz for my students rest is complete I have 500 questions on my firebase real time database all I want to do is randomize questions each time 50 questions and set a listener after 50 questions here my quiz activity

public class grandtest extends AppCompatActivity {

TextView mQuestionTextView;
ProgressBar mProgressBar;
Button bchoice1,bchoice2,bchoice3,bchoice4;
Random Rand;
String mAnswer;
Timer mTimer;
TextView mScoreTextView;
public static int mScore;
int mQuestionNo = 0;

private Firebase mQuestionRef;
private Firebase mChoice1Ref;
private Firebase mChoice2Ref;
private Firebase mChoice3Ref;
private Firebase mChoice4Ref;
private Firebase mAnswerRef;

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

    mQuestionTextView = findViewById(R.id.mquestiontextview);
    mProgressBar = findViewById(R.id.progressBar);
    bchoice1 = findViewById(R.id.choice1);
    bchoice2 = findViewById(R.id.choice2);
    bchoice3 = findViewById(R.id.choice3);
    bchoice4 = findViewById(R.id.choice4);
    mScoreTextView = findViewById(R.id.mScore);
}


public void updateQuestion (){

    mQuestionRef = new Firebase("https://class9notes-2808b.firebaseio.com/"+mQuestionNo +"/question");
    mQuestionRef.addValueEventListener(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {
        String question = dataSnapshot.getValue(String.class);
        mQuestionTextView.setText(question);
        }

        @Override
        public void onCancelled(FirebaseError firebaseError) {
            Toast.makeText(grandtest.this,"Please enable data",Toast.LENGTH_SHORT).show();
        }
    });
    mChoice1Ref = new Firebase("https://class9notes-2808b.firebaseio.com/"+mQuestionNo+"/choice1");
    mChoice1Ref.addValueEventListener(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {
            String choice1 = dataSnapshot.getValue(String.class);
            bchoice1.setText(choice1);
        }

        @Override
        public void onCancelled(FirebaseError firebaseError) {

        }
    });
    mChoice2Ref = new Firebase("https://class9notes-2808b.firebaseio.com/"+mQuestionNo+"/choice2");
    mChoice2Ref.addValueEventListener(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {
            String choice2 = dataSnapshot.getValue(String.class);
            bchoice2.setText(choice2);
        }

        @Override
        public void onCancelled(FirebaseError firebaseError) {

        }
    });
    mChoice3Ref = new Firebase("https://class9notes-2808b.firebaseio.com/"+mQuestionNo+"/choice3");
    mChoice3Ref.addValueEventListener(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {
            String choice3 = dataSnapshot.getValue(String.class);
            bchoice3.setText(choice3);
        }

        @Override
        public void onCancelled(FirebaseError firebaseError) {

        }
    });
    mChoice4Ref = new Firebase("https://class9notes-2808b.firebaseio.com/"+mQuestionNo+"/choice4");
    mChoice4Ref.addValueEventListener(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {
            String choice4 = dataSnapshot.getValue(String.class);
            bchoice4.setText(choice4);
        }

        @Override
        public void onCancelled(FirebaseError firebaseError) {

        }
    });
    mAnswerRef = new Firebase("https://class9notes-2808b.firebaseio.com/"+mQuestionNo+"/answer");
    mAnswerRef.addValueEventListener(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {
            mAnswer = (String) dataSnapshot.getValue(String.class);
        }

        @Override
        public void onCancelled(FirebaseError firebaseError) {

        }
    });
    mQuestionNo ++;

I want to randomize mQuestionNo object to retrieve random questions each time. Here is structure of my firebfarebase dataase data




Instantiate A Prefab With A Random Color

Hi I've been trying to find a way to instantiate a prefab with a random color. I have looked at many questions with similar titles I'm sure they are good answers but they are not what I need. I am making a replica of a game, for practice and I want to have to random colors to be used when instantiating an object here is my code:

private Vector3 spawnPos = new Vector3(0, 0.75f, 0);
[SerializeField]
private GameObject hitCube;
private Color color1;
private Color color2;
private string lastColor;

// Use this for initialization
void Start () {
    color1 = Random.ColorHSV(0f, 1f, 0f, 0f);
    color2 = Random.ColorHSV(0f, 1f, 0f, 0f);
    for (int i = 0; i < 21; i++)
    {
        if (lastColor == "color1")
        {
            hitCube.GetComponent<Renderer>().sharedMaterial.color = color2;
            lastColor = "color2";
        }
        else
        {
            hitCube.GetComponent<Renderer>().sharedMaterial.color = color1;
            lastColor = "color1";
        }
        Instantiate(hitCube, spawnPos, Quaternion.identity);
        spawnPos.y += 0.50f;
    }

}

So does anyone know how I can make this work? When I use this the ground becomes one color and so do all of the cubes.

enter image description here

Another question I have is why does the ground change color but the launcher doesn't (it looks like it does but actually it is already set to be a darker shade of grey), and why does the ground change color in the first place? I understand that

sharedMaterial

is not the way to go because it is for all of the prefabs. All help is appreciated.




How to get random row from "list.txt" by Python [duplicate]

This question already has an answer here:

list.txt is like this:

aa
bbb
cccc

It's not so big file.

so... what should I do next?

with open('list.txt', 'r') as f:

I tried random.shuffle(f), but unfortunately it didn't work out.




Picking a random article with Javascript

I made a homepage with about 100 small previews of articles. I would like to add a "surprise me" button that picks out a random story and goes to the url of the full article. How could I make something like this with Javascript?

Im a beginner so I wouldn't really know where to exactly start.




how to change Textview text with button

I have one textview and one button ,i coud change textview text with below code :

final Textview c_tv_matn;
Button c_btn_dokme;


c_btn_dokme = (button) findviewbyid(R.id.btn1);
c_tv_matn = (Textview) findviewbyid(R.id.txt1);

c_btn_dokme.setonclickListener(new OnclickListener() {
@Override
public void onClick(View v) {
c_tv_matn.SetText("this is second text");
});

But i wanna change text from String.xml and make Next Button Like this ; "matn_1","matn_2"matn_3"matn_4...

STRING.XML

<string name="matn_0">Hello world!</string>
 <string name="matn_1">You are hero john</string>
<string name="matn_2">you can change this world</string>
<string name="matn_3">You are so clever</string>

cAN YOU HELP ME TO GET RES FROM STRING AND CHANG TEXTVIEW TEXT WITH NUMBERS?




get object.properties and place it random in dom element.Vanila Js

I'm creating quiz game. I have separate .js file with array of objects for questions,like this:

var questions = [
  {
    ask: "question",
    choice1: "answer",
    choice2: "answer",
    choice3: "answer",
    correct: "correct answer"
  },
];

then i get random object from array:

let random = questions[Math.floor(Math.random() * questions.length)];

then i can send these object.properties to dom like this:

question.innerHTML = random.ask
answer1.innerHTML = random.choice1;
answer2.innerHTML = random.choice2;
answer3.innerHTML = random.choice3;
answer4.innerHTML = random.correct;

And everything works fine but i need to randomize these answers.In ways like this every time the correct answer is on same place but i need answers and correct answer to take random place in dom.

I'm stuck in this problem,trying every solution i can find on google but no success.




(JavaScript) Can't make my script to print random numbers until I reach 5

My task is to print out random numbers until I get 5 and then stop the loop. I tried searching around the net but couldn't really find a solution. I'm still learning the basics so sorry if this was answered, can't seem to find an answer. Here's what I tried:

function myFunction(){
let x=Math.floor(Math.random()*6)+1;
    if(x!==5){
        document.getElementById('output').innerHTML=x;
            }
        else{
        document.getElementById('output').innerHTML="5";
    }
}




How to generate onsets in python

I am making a psychology experiment and I need to generate onsets (time at which a stimulus starts its presentation)

I know how to do it in excel but not in python

So I want something which can resume all the steps made in this picture in order to output in 2 different csv files the columns sentence onset and image onset enter image description here

Thank you all for your help !




samedi 27 octobre 2018

Is it possible to predict a outcome of a PRNG rand (1,49)

I've been working on a site now, trying to see if I can't predict the actual next numbers to be generated. In every 3m45s, it generates a random figures from 1-49.

https://49ja.bet9ja.com/tv Any help please?




Linux script using a Hardware (True) Random number generator

I'd like to use the built in hardware random number generator in my RPI3 for a project. Currently I'm only able to use /dev/hwrng to save binary dumps with

dd if=/dev/hwrng of=data.bin bs=25 count=1

What I need for my project is to generate sums of 200 bits of data chunks (with an expected mean of 100) from /dev/hwrng with a frequency of 1 reading/second and write the result into a text file with a timestamp, like this:

datetime, value 11/20/2018 12:48:09, 105 11/20/2018 12:48:10, 103 11/20/2018 12:48:11, 97

Any help is appreciated....




How to add random values into an empty vector repeatedly without knowing when it would stop? How to count average number of steps?

Imagine the process of forming a vector v by starting with the empty vector and then repeatedly putting a randomly chosen number from 1 to 20 on the end of v. How could you use Matlab to investigate on average how many steps it takes before v contains all numbers from 1 to 20? You can define/use as many functions or scripts as you want in your answer.

v=[];
v=zeros(1,20);

for a = 1:length(v)
  v(a)=randi(20);
end

since v is now only a 1x20 vector, if there are two numbers equal, it definitely does not have all 20 numbers from 1 to 20

for i = 1:length(v)
  for j = i+1:length(v)
    if v(i)==v(j) 
      v=[v randi(20)];
      i=i+1;
      break;
    end
  end
end



for k = 1:length(v)
  for n = 1:20
    if v(k)==n
      v=v;
    elseif v(k)~=n
      a=randi(20);
      v=[v a];
    end
    if a~=n
      v=[v randi(20)];
      k=k+1;
      break;
    end
  end
end

disp('number of steps: ')
i*k




Grab 2 randomElements that are not the same?

I am trying to grab 2 random values that are not the same in a string like this

    var players = ["Jack, John, Michael, Peter"]
    var playersArray = ["\(players.randomElement) and \(players.randomElement) has to battle")

How am i to do this, so it grabs 2 different values?




ImportError: cannot import name 'Random' in pycharm

I write a simple python in pycharm:

import requests

req = requests.get("http://phika.ir/")
print(req)

req = requests.get("https://phika.ir/python")
print(req)

but in result I came up with:

random
from random import Random as _Random
ImportError: cannot import name 'Random'

as you see, I didn't use random function!




R random number generator faulty?

I was looking into the RNG of base R and was curious if the 32-bit implementation of Mersenne-Twister might be limiting it when scaled to large numbers of random numbers needed so I did a simple test:

set.seed(8)
length(unique(runif(1e8)))
# [1] 98845641
1e8 - 98845641
# 1154359

So it turns out that there are indeed numerous duplicates in the 100 million draw.

When I switch to the 64-bit version of the MT RNG implemented by dqrng package, the problem does not appear.

Question 1:

The 64 bit referenced refers to the type of floating point numbers used?

Question 2:

Am I right to conclude that because of the large span of possible numbers (64bit FP vs 32bit FP), duplicates are less likely when using the 64-bit MT?




generate random number in range of 50 of a variable number

How can I generate random number in range of 50 of a variable number (changing number)? I tried this:

Math.random() * variableNumber + 100 - 50

but doesn't work as I wanted to




vendredi 26 octobre 2018

Question about java and nextvytes: nextbytes keeps returning the samle value

So I am trying to fill a byte array with a set of random values. However, I keep getting the same data every time I run the program. Here is my code:

byte [] result = new byte[1024*1024];

new Random().nextBytes(result);

System.out.println(Arrays.toString(result));

or just

System.out.println(result);

I am not getting random numbers and I'm not sure why. I would appreciate some help with this.

Thanks




Generate a Connected Graph java

I want to write a function, which is given a set of vertices and then develops an edge between 2 vertices and repeats this until the graph becomes a connected graph). How can I tell when the graph has become connected?




How to select randomly a pairs of adjacent elements from a python list

What is the best way to select randomly two adjacent elements from a list?

As for example, for a given list M=[2,0,8,6,4,0,1,2,4,6,5,6,5,89,12,23] Suppose I would like to select elements like (2,0),(6,5),(89,12),(5,89),(0,8) etc. Here is the code I have tried :

import random
D=[]
M=[2,0,8,6,4,0,1,2,4,6,5,6,5,89,12,23]
  for r in range(10):
  M.append((random.sample(M,2)))

But it does not give the right pairs




Python- Pulling from a normal distribution with asymmetric error bars

I'm trying to write code to pull a value randomly from a normal distribution with asymmetric error bars. Basically I'm trying to use the equivalent of np.random.normal but be able to define an upper and lower sigma that are not equal. I don't want to use scipy.stats.skewnorm because I don't know how skewed my distribution is in terms of one parameter, I only know the + and - error bars. How would I do this?

Thanks for the help good people of stackoverflow!




Creating 1000 arrays and sorting them using the bubble and selection sort (C#)

I am new to programming. C# is my first programming language.

I have an assignment where I have to create and test out a bubble sort algorithm and a selection sort algorithm using arrays. I think I understand those now.

The next part of the assignment I am having some trouble on.

I have to write a program that will ask the user for a number (n) and create 1000 arrays of n size.

So if the user enters 5 for the number, my program has to create and sort 1000 arrays that are of length 5.

I have to use the bubble sort and the selection sort methods I created.

After I do that, I have to initiate a variable called running_time to 0. I have to create a for loop that iterates 1000 times and in the body of the loop i have to create an array of n random integers.

Then I have to get the time and set this to the start time. My professor said to notice that the sort is started after each array is built, so I should time the sort process only.

Then I have to get the time and set it to end time. I have to subtract the start time from end time and add the result to the total time.

Once the program has run, note 1. the number of items sorted 2. the average running time for each array (total time/1000)

Then I have to repeat the process using 500, 2500, and 5000 as the size of the array.

This is my code for creating one array with n number of spaces and filled with random integers.

//Asks the user for number
        Console.WriteLine("Enter a number: ");
        n = Convert.ToInt32(Console.ReadLine());

        //Creates an array of the length of the user entered number
        int[] randArray = new int[n];

        //Brings in the random class so we can use it.
        Random r = new Random();

        Console.WriteLine("This is the array: ");

//For loop that will put in a random number for each spot in the array. 
        for (int i = 0; i < randArray.Length; i++) {
            randArray[i] = r.Next(n);
            Console.Write(randArray[i] + " ");
        }
        Console.WriteLine();

THIS IS MY CODE FOR THE BUBBLE SORT ALGORITHM:

//Now performing bubble sort algorithm:
        for (int j = 0; j <= randArray.Length - 2; j++) {
            for (int x = 0; x <= randArray.Length - 2; x++) {
                if (randArray[x] > randArray[x + 1]) {
                    temp = randArray[x + 1];
                    randArray[x + 1] = randArray[x];
                    randArray[x] = temp;
                }
            }
        }

//For each loop that will print out the sorted array
        foreach (int array in randArray) {
            Console.Write(array + " ");
        }
        Console.WriteLine();

THIS IS MY CODE FOR THE SELECTION SORT ALGORITHM:

//Now performing selection sort algorithm
        for (int a = 0; a < randArray1.Length - 1; a++) {
            minkey = a;
            for (int b = a + 1; b < randArray1.Length; b++) {
                if (randArray1[b] < randArray1[minkey]) {
                    minkey = b;
                }
            }
            tempSS = randArray1[minkey];
            randArray1[minkey] = randArray1[a];
            randArray1[a] = tempSS;
        }

//For loop that will print the array after it is sorted.
        Console.WriteLine("This is the array after the selection sort algorithm.");
        for (int c = 0; c < randArray1.Length; c++) {
            Console.Write(randArray1[c] + " ");
        }
        Console.WriteLine();

This is very overwhelming as I am new to this and I am still learning this language.

Can someone guide me on the beginning on how to create 1000 different arrays filled with random numbers and then the rest. I would appreciate it greatly. Thank you.




Python3: Returning random.randint with string in one line

import random
for x in range(5):
a = (random.randint(1,71))
b = "your numbers are"
c = str(a)
    print(b + c)

How do I get the output "your numbers are x1, x2, x3, x4, x5"?




Creating a daily roster that takes a name list and randomly assigns names to the the employee positions

Sorry if this seems simple, but I have searched for what I'm looking for and not finding the exact results. What I'm looking to do is create a daily roster for employees in my department. I want to take and create a list of names that will be working on that day, and hit a button which will randomly take those names and fill in the employee work positions that are listed on the left, without duplicates. So far I have created the positions to be filled, created a list of names, and used rand() and index to randomly put the names into those fields. What I would like to do is create a macro button that will allow the names to be randomized when I click the button instead of every time the spreadsheet has a new entry. I have created a Macro button, but I cannot figure out the coding inside the button to do what I would like to happen.

What I have previously tried was using the following formulas to create what I want...with no success.

   Range("k5") = WorksheetFunction.RandBetween(0, 13)

but that only gave a random number to cell k5, so I tried this instead:

  Range("$k$5:$k$17") = WorksheetFunction.RandBetween(0, 13)

but that gave the same number for all cells instead of different numbers. Is there a way to use RAND with the macro button?

any help would greatly be appreciated. I feel like I'm close to my goal but have hit a road block.




Neural Network Random Seed Affecting Results

I was playing around with the code from the interesting article on time-series regression by James McCaffrey (download).

This essentially uses machine learning to generate a prediction and forecast of the given airline data.

This is my graph generated using the code and data from his article. As you can see, everything appears to be working as normal.

The problem occurs when I attempt to mess with the random variable. He specifically seeds the System.Random object with 0 as seen here: this.rnd = new System.Random(0); (in the NeuralNetwork constructor). The program only uses the rnd variable when it is assigning the initial weights of the network and when it randomizes the order of data to process. The seed should be independent of the data (i.e. the order processed and random weights assigned should not affect the results).

However, observe what happens when I change only the line this.rnd = new System.Random(0); to this.rnd = new System.Random(1);. Here I've done nothing else except seed the System.Random object with 1 instead of 0. Now look at the results:

enter image description here

It is still able to learn and predict the data, however, the forecast is completely wrong! Why does changing the seed have such a significant effect on the results? In theory it shouldn't matter which order data is processed or what the starting weights are, as that's the point of the network, to change the bias until it reaches the solution. Is there something I'm missing?




Python Randomly Select Rows Until Criteria is Met

I have a dataframe that has a few ID's and then a column for money like this,

Id1     Id2     Id3     Money
1       10      13      10000
2       15      12      12500
3       20      11      60000

I need a pythonic method to randomly select rows until I hit $80M in money. I'm assuming a while loop such as...

while sum(money) < 80000000:
    df.sample()




Make matrix of random integers [duplicate]

This question already has an answer here:

I need to write a function that takes the number of rows and columns and returns a matrix of a size rows × columns filled with random values between -10,10.

**need to be done without NumPy, Pandas and etc.

I write:

Mat = []

def mf(r,c):
    for i in range (0,c):
        Mat.append([])
    for i in range (0,r):
        for j in range (0,c):
            Mat[i].append(j)
            Mat[i][j]=0

    print(Mat)
mf(3,4)

How to insert random values in the range -10,10?

Any help, tips or solutions are greatly appreciated, I am a python beginner with a very basic knowledge.

Many thanks in advance!




I have a input to get number 1 to 3 and a correct chance 40 percent

I have a input to get number 1 to 3 and a correct chance 40 percent

mt_rand(1,3);




SQL Random Sample With Case When Statement

I need to write a query that will return a random sample of records. But I must able to specify the sample size based on the value of one field.

This is a simplified version of the query I'm working on. In this example I need to return a total of 300 records, 100 where tier = 1 and 200 where tier =2.

I'm not sure if this is possible with the Sample feature.

 SELECT 
 ID,
 TIER

 FROM TIERTABLE a

 SAMPLE CASE WHEN TIER = 1 
 THEN 100
 WHEN TIER = 2
 THEN 200 END 




Dice thrower with methods

I'm currently doing some exercises from my study book, and one of the tasks was to: Write a dice class "Dice" which has got a value between 1-6. There should also be a constructor that picks a random value, and a method roll() that also picks a random value. The method getValue() should also be created, which is going to be used to retrieve the value being shown. Write a test class for this program.

This is my code so far:

public class Dice {
    int value;
    int currentRoll;

    //Constructor
    public Dice() {
        this.value = 1;
        this.currentRoll = 0;
}

    public int roll() {
        Random rand = new Random();
        this.currentRoll = rand.nextInt(6) + 1;
        return this.currentRoll;
}

    public int getValue() {
        return currentRoll;

}

}

What I do not understand is:Why should you random the value both in the constructor, and in the roll () method? Also, what am I missing out on?




multiple assembly instruction using asm volatile in c code

I need to modified an random number generator using rdrand(only), It implemented in c code as follows.

uint64_t _rdrand(void)
{
        uint64_t r;
            __asm__ volatile("rdrand %0\n\t" : "=r"(r));
                return r;
}

Now i need to modify such that it returns only if carry flag is set. (According to rdrand documentation).I think it can be implimented by jc instruction,but don't know how to use inside __asm__ volatile.please help me.




jeudi 25 octobre 2018

When does Math.random() start repeating?

So I have this simple test in nodejs, I left it running overnight and could not get Math.random() to repeat. I realize that sooner or later the values (or even the whole sequence) will repeat, but is any reasonable expectancy as to when it is going to happen?

let v = {};
for (let i = 0; ; i++)
{
   let r = Math.random();
   if (r in v) break;
   v[r] = r;
}
console.log(i);




Java math quiz. Keeps tally and scores but doesn't work and keep getting true as an answer

\ simple math quiz for school. needs a tally and how many questions to ask


import java.util.Scanner; import javax.swing.JOptionPane;

public class MathQuiz {
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
// limits amnt of qs
int limit = 10;
int randomNumber1 =  (int)(20 * Math.random()) + 1;
int randomNumber2 =  (int)(20 * Math.random()) + 1;
int randomNumberAdd = randomNumber1 + randomNumber2;
int randomNumberMul = randomNumber1 * randomNumber2;
int randomNumberDiv = randomNumber1 / randomNumber2;
int randomNumberRem = randomNumber1 % randomNumber2;
double correct = 0;
String input = JOptionPane.showInputDialog(null, "Enter amount of 
questions: limit " + limit);

System.out.print( limit <=10);
  \\ gives answer but with true in front of the answer 

if (limit > 10) {
     System.out.println(" Too many questions. Try again");
 } else {
if (limit < 10) 
     System.out.println (" 888888");
} else {
     System.out.print(randomNumber1 + " + " + randomNumber2 + " = ");
int GuessRandomNumberAdd = keyboard.nextInt();

if (GuessRandomNumberAdd == randomNumber1 + randomNumber2) {
    System.out.println("Correct!");
correct++
}else {
 System.out.println("Try again!");
 System.out.println("The correct answer is " + randomNumberAdd);

}
System.out.print(randomNumber1 + " * " + randomNumber2 + " = ");    
int GuessRandomNumberMul = keyboard.nextInt();

if (GuessRandomNumberMul == randomNumber1 * randomNumber2) {
  System.out.println("Correct!");
  correct++;
}else{
    System.out.println("Try again!");
    System.out.println("The correct answer is " + randomNumberMul);


//math portion here the answer shows correctly but with the word true in front of it } System.out.print(randomNumber1 + " / " + randomNumber2 + " = "); int RandomNumberDiv = keyboard.nextInt();

if (RandomNumberDiv == randomNumber1 / randomNumber2) {
    System.out.println("Correct!");
    correct++;

    }else{
        System.out.println("Try again!");
        System.out.println("The correct answer is " + randomNumberMul);


}
    System.out.print(randomNumber1 + " % " + randomNumber2 + " = ");
    int GuessRandomNumberRem = keyboard.nextInt();
        if (GuessRandomNumberRem == randomNumber1 % randomNumber2) {
        System.out.println("Correct!");
        correct++;

        }else{
            System.out.println("Try again!!");
            System.out.println("The correct answer is " + randomNumberRem);
        }

\\ question tally 


System.out.println("You got " + correct + " correct answers.");
}
}

}




How to form an equation for probability based on the following graph?

enter image description here

The y-axis is the probability density function of x.

Here's the solution I tried: formula

Is this correct?




Randomly sort character vector same way each time

I want to randomize the order of the vector the same way each time. However, the following does not order it the same way each time.

set.seed(1)
data <- ('a', 'b', 'c', 'd', 'e', 'f')  
sample(data)




C# - Duplicate Random Numbers are Getting Displayed

I have written this very crude way of generating random numbers and displaying in a labelText inside a Windows Form. What is happening is that for the second label text it is showing exactly the same of the first label text. Hoping for your feedback on how to correct this so that each label text displays unique random numbers.

    private void btnGenerateNumbers_Click(object sender, EventArgs e)
    {
        List<string> numberStringT = new List<string>();


        for (int i = 0; i < 2; i++)
        {
            string result = "";
            Random rnd = new Random();
            int one = rnd.Next(1, 49);
            int two = rnd.Next(1, 49);
            int three = rnd.Next(1, 49);
            int four = rnd.Next(1, 49);
            int five = rnd.Next(1, 49);
            int six = rnd.Next(1, 49);
            int seven = rnd.Next(1, 49);

            if ((one == two) | (one == three) | (one == four) | (one == five) | (one == six) | (one == seven))
            {
                one = rnd.Next(1, 49);
            }

            if ((two == one) | (two == three) | (two == four) | (two == five) | (two == six) | (two == seven))
            {
                two = rnd.Next(1, 49);
            }

            if ((three == one) | (three == two) | (three == four) | (three == five) | (three == six) | (three == seven))
            {
                three = rnd.Next(1, 49);
            }

            if ((four == one) | (four == two) | (four == three) | (four == five) | (four == six) | (four == seven))
            {
                four = rnd.Next(1, 49);
            }

            if ((five == one) | (five == two) | (five == three) | (five == four) | (five == six) | (five == seven))
            {
                five = rnd.Next(1, 49);
            }

            if ((six == one) | (six == two) | (six == three) | (six == four) | (six == five) | (six == seven))
            {
                six = rnd.Next(1, 49);
            }

            if ((seven == one) | (seven == two) | (seven == three) | (seven == four) | (seven == five) | (seven == six))
            {
                seven = rnd.Next(1, 49);
            }


            List<int> numberList = new List<int>();

            List<int> numberListNoDuplicates = new List<int>();


            numberList.Add(one);
            numberList.Add(two);
            numberList.Add(three);
            numberList.Add(four);
            numberList.Add(five);
            numberList.Add(six);
            numberList.Add(seven);

            numberList.Sort();


            result = numberList[0].ToString() + "  " + numberList[1].ToString() + "  " + numberList[2].ToString() + "  " + numberList[3].ToString() + "  " + numberList[4].ToString() + "  " + numberList[5].ToString() + "  " + numberList[6].ToString();
            numberStringT.Add(result);
            numberList.Clear();
            result = "";
            rnd.Next();
        }


        //lblRandomNumber.Text = result;
        lblRandomNumber.Text = numberStringT[0];
        lblRandomNumber2.Text = numberStringT[1];
    }




Semi-Random Number Generation C++

I am running a Monte Carlo simulation where I generate 100,000 random paths. My problem is that I want to find a way to keep these same 100,000 random paths in loops of other variables. Essentially, I want my random number generator to reset each time I run my 100,000 iterations. Currently, I have code that looks something like this:

 vector<double>Rand_Var(double time)
 {
static mt19937 generator;

normal_distribution<>ND(0., 1.);
ND(generator);
double phi;
vector<double> rand(time + 1);
for (int i = 1; i <= time; i++)
{
    phi = ND(generator);
    rand[i] = phi;

}

return rand;
}

Then in int main(), for testing I have:

for (int l = 0; l < 5; l++)
{

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

        vector<double>rand_val = Rand_Var(time_opt);

        cout << rand_val[4] << endl;
    }
}

I get the following output:

-0.214253
 1.25608
-1.82735
 0.919376
 1.45366
-0.791957
 0.530696
 0.0751259
-0.559636
-0.709074

What I would like to get however is something like:

-0.214253
 1.25608
-0.214253
 1.25608
-0.214253
 1.25608
-0.214253
 1.25608
-0.214253
 1.25608

Is this possible?




PHP MySQL - How to select items randomly on weekly basis?

in PHP MySQL if i want select items randomly on Daily Basis i use following code.

ORDER BY rand(" . date("Ymd") . ")

But How i can select items randomly on Weekly Basis ?




How to Generate Random Number of Barcode in Jquery

I need a code generator in jQuery that when clicking on the button it appears in the input text a number of 13 digits, start in number 7.

This is the code in my view:

<div class="form-group <?php echo !empty(form_error('barcode')) ? 'has-error':'';?>">
    <label for="barcode">Barcode:</label>
    <div class="input-group barcode">
        <div class="input-group-addon">
            <button class="fa fa-barcode" title="Generate Random Barcode"></button>
        </div>
        <input type="text" class="form-control" id="barcode" name="barcode" required value="<?php echo set_value('barcode');?>">
    </div>
    <?php echo form_error("barcode","<span class='help-block'>","</span>");?>
 </div>

This is the input text + button:

enter image description here

The generated number like this:

enter image description here




Random array or list size at scene start

I have an array of blocks. I want it to be with a random size/length when the scene starts.

 public GameObject[] blocks;

However if I try random range with an array I get all kinds of errors. Same with List<>.

I want my scene to start with a random number of items (within a range).

Any suggestions?




uniform_int_distribution return a number form outside the range

I am trying to implement a simple quicksort algorithm. It starts with f.e. two randomly selected numbers, p and r. I do get them like this:

std::random_device rd;
std::mt19937 rng(rd());
std::uniform_int_distribution<> urd(0, 10);
int p = urd(rng);
int r = urd(rng);
std::cout << p << ' ' << r << '/n';

The problem is, I get the result:

3 11214210

And its not constant. It varies. The first number is always in range of (0,10). And the second number is, well, kinda too big

And then the array (for now of fixed size of 10), printed out, looks like this:

[31129611129621129671129641129661129651129681129691129610]

Do you guys know what am I doing wrong?




Return a specific word in a string of multiple words in java

public class test{

     //my words
        private static String[] words = {"apple", "banana", "cat", "dog", "elf", "frog" };

    public static void main(String[] args) {
       int randomWord = (int) (Random() * words.length);

        System.out.println(randomWord);

    }//end string   
}//end class

I just start a project and all i want to know is how to return a specific word while still having it be random. At the moment it just prints/returns the number of the position in the string. For example i want it to return "cat" and if it does the print "" for every letter in cat. I already have the code to print the "" for every letter i just need to get the word back instead of an int.




Unable to iterate random values in subsequent lines in Python

There are probably many more straightforward ways of achieving my aim here, but as a Python newbie, I'd appreciate it if we could just concentrate on the code I'm using. I'm attempting to write out a list of commands for a graphics program (G'MIC) and output those to a command prompt (although not directly) using Python 3.6.4 (OS: Windows 10 Pro), I need to write many lines of code but each line has to have different sets of numbers (integers and floats).. for example in the code I'm attempting to use right now the syntax is like this:

gmic v -99 input_.png fx_pastell 
0.5,1,0,10,40,633,11,95,1,1,0.291651967558584,0,0,8,150,1,81,1,0,0,0 -o 
out_001.png

^ all the variables denote parameters within the particular script (in this case Pastell effect).

The code I wrote relies on the Random module to get certain numbers within a range for each parameter that I want to change. My stumbling block is to get the script to output DIFFERENT random numbers each time it prints a line. Here is my code (it's awful, I know..):

import random

a = random.randint (3,13)
b = random.randint (1,68)
c = random.randint (1,682)
d = random.randint (2,12)
e = random.randint (1,109)
g = random.randint (1,8)
h = random.uniform (0, 1)
k = random.randint (1,11)
l = random.randint (1,201)
n = random.randint (1,300)
o = random.randint (1,4)

dataFile = open("gmic1.txt", "w")
for line in range(120):
    dataFile.write("gmic v -99 input_.png fx_pastell 0.5,1,0" + "," + str(a) 
+ "," + str(b) + "," + str(c) + "," +str(d) + "," + str(e) + ",1," + str(g) 
+ "," + str(h) + ",0,0," + str(k) + "," + str(l) + ",1,"  + str(n) + "," + 
str(o) +"," + "0,0,0 -o out_%04d.png \n" % line)

dataFile.close()

The output is like this:

gmic v -99 input_.png fx_pastell 
0.5,1,0,12,2,521,12,85,1,7,0.04003331068764937,0,0,8,17,1,297,2,0,0,0 -o 
out_0000.png 
gmic v -99 input_.png fx_pastell 
0.5,1,0,12,2,521,12,85,1,7,0.04003331068764937,0,0,8,17,1,297,2,0,0,0 -o 
out_0001.png 

.. etc...

no errors as such, but not outputting a different set of numbers each time as I'd hoped.

The first input image name variable I can change with Notepad++'s Column Editor, so that takes care of that, I only need to know how to make each line of code differ.

Any help greatly appreciated!




How to specify a random seed while using Python's numpy random choice?

I have a list of four strings. Then in a Pandas dataframe I want to create a variable randomly selecting a value from this list and assign into each row. I am using numpy's random choice, but reading their documentation, there is no seed option. How can I specify the random seed to the random assignment so every time the random assignment will be the same?

service_code_options = ['899.59O', '12.42R', '13.59P', '204.68L']
df['SERVICE_CODE'] = [np.random.choice(service_code_options ) for i in df.index]




BER of QPSK for AWGN channel in MATLAB

I want to simulate the BER of QPSK for AWGN channel. Get the BER and compare it with the theoretical one but i am stuck with some parts of the code. Can you please help me with the code?

//////////////////////QPSK BER//////////////////////////
%Initial Condition
Ndata = 10000;
SNRdB = 6;

% Data generation
dataSeq = MYrandData(Ndata);

% QPSK modulation
spcOutput = reshape(dataSeq,2,Ndata/2); %reshape 2 row 5000 column
qpskSymbolIndex = [1,2]*spcOutput; % get random data from 0~3. 
qpskSymbol = ones(1,Ndata/2) * exp(j*pi/4); %0~3, 1 row 5000 column
qpskSymbol(find(qpskSymbolIndex==1)) =____; %<- try to put qpskSymbol = ones(1,Ndata/2) * exp(j*3*pi/4) but false
qpskSymbol(find(qpskSymbolIndex==3)) =____; %<- try to put qpskSymbol = ones(1,Ndata/2) * exp(j*5*pi/4) but false
qpskSymbol(find(qpskSymbolIndex==2)) =____; %<- try to put qpskSymbol = ones(1,Ndata/2) * exp(j*7*pi/4) but false

% AWGN channel
Pn = 10^(-SNRdB/10);
r = qpskSymbol + MYcompNoise([1,___],Pn); % noise of AWGN

% Demodulation
demodData = zeros(2,Ndata/2);
demodData(2,find(imag(r)<=0)) = 1;
demodData(1,find(real(r)<=0)) = 1;
qpskDemod = demodData(:);

%BER calculation
BER = sum(abs(dataSeq - qpskDemod))/Ndata;

SNR = 10^(SNRdB/10);
BER_theory = qfunc(___);

disp(['QPSKsBER=',num2str(BER),'   QPSKs BERs theory=',num2str(BER_theory)])

/////////////////My Random Data////////////////////////////
function[data] = MYrandData(Ndata)

dataSeq = randn(Ndata,1); % generate data
data = zeros(Ndata,1); 
data(find(dataSeq>0)) = 1;
return

//////////////////MyRandomNoise/////////////////
function[noise] = MYcompnoise(noiseSize,Pn) %generate noise
noise = (randn(noiseSize) + j * randn(noiseSize)) * sqrt(Pn/2);
return




Getting n random elements from array and creating duplicates when there's not enough elements

I have arrays of objects, ex:

let array1 = [
{name: '1', image: '1.jpg'},
{name: '2', image: '2.jpg'},
{name: '3', image: '4.jpg'},
{name: '4', image: '5.jpg'},
];

I want to get n random element of it and found function that serves this purpose:

function getRandom(arr, n) {
    var result = new Array(n),
        len = arr.length,
        taken = new Array(len);

        var x = Math.floor(Math.random() * len);
        result[n] = arr[x in taken ? taken[x] : x];
        taken[x] = --len in taken ? taken[len] : len;
    }
return result
}

The only problem is that when I want to have n > arr.length this does not work. I'd like to figure out how to increase number of elements in this case. For example repeating elements that are already in it.

I tried adding conditional:

if(n > len) {
    arr.push(arr);
    console.log(arr);
}

But it does me no good since, the elements are pushed as an another object, and not separately, check the console.log:

0: {name: "1", image: "1.jpg"}
1: {name: "2", image: "2.jpg"}
2: {name: "3", image: "4.jpg"}
3: {name: "4", image: "5.jpg"}
4: Array(5)
0: {name: "1", image: "1.jpg"}
1: {name: "2", image: "2.jpg"}
2: {name: "3", image: "4.jpg"}
3: {name: "4", image: "5.jpg"}
4: (5) [{…}, {…}, {…}, {…}, Array(5)]
length: 5

None of other things I tried doesn't work. If someone could figure out the way around it I would really appreciate it.




mercredi 24 octobre 2018

100,000 Random string generation just upper case letters and compare with two Algorithms in Python

How can Generate 100,000 Random string upper case letters and compare with two Algorithms of exhange sort and merge sort in Python




How do Generate a random number between 1 and 2 in PHP [duplicate]

This question already has an answer here:

How do Generate a random number between 1 and 2 with a possible result of both integer or float in PHP

I try to use rand(1,2) or mt_rand(1,2) but i keep getting between 1 and 2. I want my result so be either 1.3 , 1.1, 1.3 ,2




High Low Card Game

Basically, i'm currently coding a game which gives a random card and asks if the next card will be higher, lower or equal. The problem is I'm struggling to find a way to list for example when I get a 13 to list it as a King I tried doing below as like an 'either or' statement but it says || is undefined for this kind of statement

 System.out.print("The card is " + ((cardToGuess == 8)||(cardToGuess == ACE) ? "an ":"a ") + ((cardToGuess == ACE) ? "Ace " : cardToGuess)||
                  ((cardToGuess == JACK) ? "Jack " : cardToGuess)||((cardToGuess == QUEEN) ? "Queen " : cardToGuess)||
                  ((cardToGuess == KING) ? "King " : cardToGuess)  
                  + "\nDo you think the next card will be higher, lower, or equal? ");

I know this || can't be used here but i want to know if there is a way around this Also a way to make a random number generator to 13 that doesn't include 0 would be nice aswell I'm new to coding so any help I'd appreciate it being as simplified as possible




Java method to return random element of array of different types

I would like to pass different arrays of changing parameter types at different times into a method/function of which randomly returns one element, however am extremely struggling to do so using Java.

I have attempted to do so using the following code:

public int rndInx(Array theArray) {
    theArray = theArray[(int)(Math.random() * theArray.length)];
    return theArray;

}

However, Eclipse draws attention to errors; length not being resolved and the type of expression must be an array type. I assume one cause of the issue is the returnType, however I'm unsure what type would accept a range of returnTypes. I am aware that the syntax is probably extremely wrong too since I've only recently began to learn Java :(

For example, if I was to pass an array containing integers, then one random integer element would be returned - and if I was to pass an array containing strings etc. than one random element from the array in question would be returned.

Thanks in advance.




Generating a unique number for every submission using java or html

I have a signup form that I created using the plugin wpforms in wordpress. It was created for an event where people will physically come to the location, so instead of verifying them by names, I want everyone to have a unique id that can use to enter the event.

The question is: wpforms accepts html fields so.. How can I create a unique generated number, that will change every time someone refresh or open the page, so when someone enters his details, and submit it, his submission and data will be associated with that unique number(id) and sent to us.




How do I get random objects from a dictionary, weighted by value

I have a large dictionary. The keys are objects and the values are how often the given object appears in my data.

I would like to randomly choose an object from the dictionary but have the choice be weighted towards objects with higher corresponding values.

So far, I have been able to achieve this by adding x number of objects to a list where x is the corresponding value in the dictionary. Then I call random.choice() on this list. Like so:

import random

myDict = { 'foo' : 10,
           'boo' : 5,
           'moo' : 3,
           'roo' : 2,
           'goo' : 1,
           'oo' : 0}

selection = []
for obj in myDict.keys():
    for n in range(myDict[obj]):
        selection.append(obj)

To make sure that this is working I've run random.choice() on the list 10000 times and saved the results. Here are 4 of the results I've gotten.

{'foo': 4841, 'boo': 2397, 'moo': 1391, 'roo': 907, 'goo': 464, 'oo': 0}
{'foo': 4771, 'boo': 2410, 'moo': 1435, 'roo': 917, 'goo': 467, 'oo': 0}
{'foo': 4815, 'boo': 2340, 'moo': 1431, 'roo': 953, 'goo': 461, 'oo': 0}
{'foo': 4718, 'boo': 2443, 'moo': 1404, 'roo': 947, 'goo': 488, 'oo': 0}

As you can see, the distribution fits the frequency described in the dictionary.

My problem is that in my production code I have thousands of dictionaries each containing thousands of objects. The dictionaries are of variable length. My current method is very inefficient and slow. Is there a better way? I don't mind using a different structure to store the data as it comes in.




Javascript Popup with multiple random images loaded in the popup

I am unable to get a javascript popup (initiated by an onclick event) to load multiple "random" images when the popup loads. My code is below:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0
Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta charset="ISO-8859-1">
<title>Popup w/ Multiple Images - Test</title>
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
</head>
<html>
<body>
<head>
<script language="JavaScript">
var w = 480, h = 340;
function openWindow() {
if (document.getElementById) {
w = screen.availWidth;
h = screen.availHeight;
}
var popwidth = 800, popheight = 700;
var leftPos = (w-popwidth)/2;
var topPos = (h-popheight)/2;
msgWindow = window.open('','popup','width=' + popwidth + ',height=' + 
popheight + 
',top=' + topPos + ',left=' + leftPos + ', scrollbars=yes');
msgWindow.document.write
('<html><head>' +
'<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">' +
'<meta http-equiv="Content-Style-Type" content="text/css">' +
'<meta http-equiv="Content-Script-Type" content="text/javascript">' +
'<title>Popup w/ Multiple Images - Test</title>' +
'<style type="text/css">' +
'img {' +
'border:0;' +
'}' +
'</style>' +
'<script type="text/javascript">' +
'var linksNumber = 6;' +
'var myimages = [' +
'["docURL"]' +
'["docURL"]' +
'["docURL"]' +
'["docURL"]' +
'["docURL"]' +
'["docURL"]' +
'["docURL"],' +
'["docURL"],' +
'["docURL"],' +
'["docURL"],' +
'["docURL"]];' +
'var imagelinks = [' +
'["imgURL"],' +
'["imgURL "],' +
'["imgURL "],' +
'["imgURL "],' +
'["imgURL "],' +
'["imgURL "],' +
'["imgURL "],' +
'["imgURL "],' +
'["imgURL "],' +
'["imgURL "],' +
'["imgURL "],' +
'["imgURL "]];' +
'var ary0 = [];' +
'var ary1 = [];' +
'var k = 0' +
'var c, n;' +
'function randomImgDisplay() {' +
'for(c = 0; c < myimages.length; c++) {' +
'ary0[c] = c;' +
'}' +
'while(ary0.length > 0) {' +
'n = Math.floor(Math.random()*ary0.length);' +
'ary1[k] = ary0[n];' +
'k++;' +
'ary0.splice(n,1);' +
'}' +
'for(c = 0; c < linksNumber; c++) {' +
'document.getElementById("pic"+ c).src=myimages[ary1[c]];' +
'document.getElementById("lnk"+ c).href=imagelinks[ary1[c]];' +
'}' +
'}' +
'if (window.addEventListener) {' +
'window.addEventListener("load",randomImgDisplay,false);' +
'}' +
'else {' +
'if (window.attachEvent) {' +
'window.attachEvent("onload",randomImgDisplay);' +
'}' +
'}' +
'<\/script>' +
'</head><body>' +
'<div>' +
'<a id="lnk0" href="lnk0"><img id="pic0" src="img0" alt=""></a>' +
'<a id="lnk1" href="lnk1"><img id="pic1" src="img1" alt=""></a>' +
'<a id="lnk2" href="lnk2"><img id="pic2" src="img2" alt=""></a>' +
'<a id="lnk3" href="lnk3"><img id="pic3" src="img3" alt=""></a>' +
'<a id="lnk4" href="lnk4"><img id="pic4" src="img4" alt=""></a>' +
'<a id="lnk5" href="lnk5"><img id="pic5" src="img5" alt=""></a>' +
'</div>' +
'<form name="OnClickPopup">' +
'<br/>' +
'<input type="button" value="Close" onClick="window.close
();"></form></body></html>');
</script>
<form>
<input type="button" onClick="openWindow()" value="Click Me">
</form>
</body>
</html>

When I separate the code into two javascript files, one to create the popup & one to display multiple random images, they each work fine. I am grasping at straws and thinking it may be my use of "msgWindow.document.write" that is causing my issue, please help if you are able.