vendredi 31 janvier 2020

Coin flip method advice

I was assigned to create a method that simulates flipping a coin. I think my code here is pretty solid, only I can't get it to show a series of results after n number of flips. So instead of showing HTHHHTTTHTT, I'm only getting H or T.

public static void main(String[] args) {
    System.out.println((flipCoin(2, 10)));

}
    public static String flipCoin(int chance, int numFlips) {
        String result = "";
        Random rando = new Random();
        chance = rando.nextInt();
        for (int i = 0; i < numFlips; i++) {
            if (chance % 2 == 0) {
                result = "H";
            }
            else {
                result = "T";
            }
            numFlips++;
        }
        return result;
}



Getting negative value from Random.nextInt using XORShift seed implementation

From my understanding (and the javadoc), Random.nextInt should return a positive (or zero) value.

But when I use it with arguments that are power of 2, I often receive negative values. Here is my Random class:

import java.util.Random;
import java.util.concurrent.atomic.AtomicLong;

public class SavableRandom extends Random {

    private AtomicLong seed = new AtomicLong();

    /** {@inheritDoc} */
    @Override
    protected int next(int bits) {
        long newSeed = seed.get();

        newSeed ^= (newSeed << 21);
        newSeed ^= (newSeed >>> 35);
        newSeed ^= (newSeed << 4);
        seed.set(newSeed);

        return (int) (newSeed >>> (48 - bits));
    }

    /** @return the seed. */
    public long getSeed() {
        return seed.get();
    }

    /** @param seed the seed to set. */
    @Override
    public void setSeed(long seed) {
        if (this.seed != null) {
            this.seed.set(seed);
        }
    }

    public static void main(String... args) {
        Random random = new SavableRandom();
        random.setSeed(536662536331391686L);

        System.out.println(random.nextInt(13));
        System.out.println(random.nextInt(12));
        System.out.println(random.nextInt(16));
    }
}

I added a main method with a specific seed so that you could easily reproduce it (the last one returns -1).

What am I doing wrong ?




Generating weather scenarios following Poisson distribution

I would like to generate random values of summer rainfall in Python, for a model of grass growth. I would like to extrapolate a weather series of 42 years that seems to follow a Poisson distribution 1. I tested it in R and it seems to have a Lambda of 4. I didn't find how to generate randomly continuous values (floats) based on my mean precipitation value and assumed lambda. Someone knows how to do that ? Best




non-conformable arrays error when multiplying two matrix (*%*)

The next reproducible code generates 394 observations of 183 random normales, and tries to correlate them with Cholesky decomposition:

Generate the parameters

d <- 211

l <- 183

m <- -0.006495094

vectorsd <- rep(0.29, 183)

Generate random normals uncorrelated

rnormd <- as.data.frame(rnorm(l, mean = m, sd = vectorsd))

for (i in 1:(d+l))  {
  rnormd[,i] <- rnorm(l, mean = m, sd = vectorsd)
}

Generate a random semidefinite positive matrix of correlations

v <- runif(183,0.6,0.8)
corr <- `diag<-`(tcrossprod(v),1)

Generate cholesky matrix

cholesky <- chol(corr)

Correlate the normals and transpose the output

rnormd <- t(rnormd*cholesky)

In this last instruction I get the error

Error in rnormd * cholesky : non-conformable arrays

At first a thought that the problem was going to be solved transposing my cholesky matrix, but then I realized that chol() function already transposes it.

Can anyone help me?




generate more than one random code in laravel and save it to database

I'm a newbie in laravel. I have to generate more than one random code at one time in my laravel project and save it to database. Any example or advise that quite easy to understand? thank you




populating fragment with random changing images

I am trying to build an educational bilingual application for kids and adults. User has to answer questions that appear randomly on screen. Questions appear in English and Russian, user has an option to switch between these two by swiping left. So, it's English first, then swipe to Russian. I am very new to Fragments and coding in general.

So, first question is how to populate a single fragment with a pair of images that are swipe-able?

Next question is how do I pair images (containing question)? I can't have a random question in English and then completely different question in Russian. It should be same question in different language.

I hope it is understandable. I can't seem to find a tutorial that would suit my task. Thanks in advance!




c++ checking each element of random array [closed]

I need to create a seperate function that I can run in my main that checks each element of the array I created with the size and random number limit. I need to have the parameters in the function (assignement) Basically I have to run the array, then run that function to check if it's within the limit then modify the array if it isn't. Any help/tips appreciated :)

2.Declare an array to hold 10 integer values3.Set the 10 values to a number between 1 and 50 using the rand function4.Create a function called “Limit” that takes as parameters the array name, the array length and a limiting value (between 1 and 50). It must check all the elements, and if any of the elements are larger than Limit, change them to that Limit value.5.Print out the list of 10 numbers, then call the function “Limit” and print out the numbers again.

This is what I have so far:

#include <iostream>
#include <ctime>
using namespace std;
int main()
{
    srand(time(NULL));

    const int SIZE = 10;
    int Arr[SIZE];

    for (int i = 0; i < Arr; i++)
    {
        Arr[i] = rand() % 50;
        cout << Arr[i] << endl;

    }

    system("PAUSE");

}

int limit(int Arr, const int sizeOfArray)
{

    if (Arr)
    {

    }


}



shuffle string with javascript and keep track of the number

I have a function

function shuffle(length,string) {
   var result           = '';
   var characters       = string;
   var charactersLength = characters.length;
   for ( var i = 0; i < length; i++ ) {
       result += characters.charAt(Math.floor(Math.random() * charactersLength));
   }
   return result;
}

and I use it like to generate the array of the random string

var value = shuffle(66,'guitar'); value.split('')

Now I am using this function in a setinterval function to generate the random string every 5 seconds But I need to keep track of the characters so if the first characters was moved to fifth position I need to know.

so the output of the shuffle function should be

array('g,5','i,4','t,1')

Numbers after comma denoted the new place of the characters with respect to the index of the array.First position was moved to fifth and second position was moved to fourth position and so on.




Random values generator bug with OpenMP tasks

I'm trying to develop a micro code based on the calculation of Pi by the Monte Carlo method while using OpenMP tasks. It seems that I have some troubles in that code. Indeed, my application simply crashes and I got a segmentation fault coming from the gomp_barrier function...

I don't know if I am doing wrong things in my code or not, but I spend a little bit time on time to try to debug it and I found nothing. When I simply remove the computation of x and y with random values generator, the code is doing well... But if I add a call to rand_r or srand48_r, I have this segfault. So maybe, my use of these functions is wrong. Does anyone have an idea please ?

Here is my code :

#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <inttypes.h>
#include <time.h>
#include <unistd.h>

#include "omp.h"

#define TRIALS_PER_THREAD 10E6

int main(int argc, char** argv)
{
  uint64_t const n_test = TRIALS_PER_THREAD;
  uint64_t i;
  double pi = 0.;

  int nb_threads = 2;
  #pragma omp parallel shared(nb_threads)
  {
    #pragma omp master
      nb_threads = omp_get_num_threads();

  }
  fprintf(stdout, "Nb threads: %d\n", nb_threads);

  uint64_t* result = (uint64_t*)malloc(sizeof(uint64_t) * nb_threads);
  for(i = 0; i < nb_threads; ++i)
  {
    result[i] = 0;
  }

  int nb_test_per_thread = 20;

  #pragma omp parallel\
  shared(result)\
  firstprivate(n_test,nb_test_per_thread)
  {
    unsigned int seed;
    struct drand48_data randBuffer;

    seed = time(NULL) ^ omp_get_thread_num() ^ getpid();
    srand48_r(seed, &randBuffer);

    for(int k = 0; k < nb_test_per_thread; ++k)
    {
      #pragma omp task shared(result, seed, randBuffer)
      {
        uint64_t local_res = 0;
        double x = 0., y = 0.;
        for(i = 0; i < n_test; ++i)
        {
          drand48_r(&randBuffer, &x);// / (double)RAND_MAX;
          drand48_r(&randBuffer, &y);// / (double)RAND_MAX;

          local_res += (((x * x) + (y * y)) <= 1);
        }
        int tid = omp_get_thread_num();
        result[tid] += local_res;
      }
    }
  }

  for(i = 0; i < nb_threads; ++i)
  {
    pi += result[i];
  }

  fprintf(stdout, "%ld of %ld throws are in the circle !\n", (uint64_t)pi, n_test*nb_test_per_thread*nb_threads);
  pi *= 4;
  pi /= (double)(n_test*nb_test_per_thread*nb_threads);
  fprintf(stdout, "Pi ~= %f\n", pi);

  return 0;
}

Thank you in advance for your help !




Rigging pseudo random generator in javascript [duplicate]

I'm using Math.random to generate numbers between a range. Instead of having complete randomness I want my generator to have a slight bias towards higher numbers. Is there some way to achieve this without destroying the randomness of the generator?




R: how to make a random correlation matrix semi definite positive

I am trying to make a random matrix correlation over 183 variables to calculate a Cholesky decomposition and correlate 183 random normals. For the creation of the correlation matrix the following reproducible code is the one I am using:

First I set the seed

set.seed(2)

Then I generate random numbers between 0.6 and 0.8

corr <- matrix(runif(183*183, min = 0.6, max = 0.8), 183, 183)

The next step is turning the diagonal into ones

for (i in 1:183) {
  for (j in 1:183) {
    if (i == j) {
    corr[i,j] <- 1
    }
  }
}

Last step is making it symmetric

for (i in 1:183) {
  for (j in 1:183) {
    if (i < j) {
    corr[i,j] <- corr[j,i]
    }
  }
}

The problem I run into arise when I try to make the cholesky decomposition

cholesky <- chol(corr)

I get the following error:

Error in chol.default(corr) : the leading minor of order 14 is not positive definite

How could I make my correlation matrix semi definite positive?




jeudi 30 janvier 2020

Can we make different random sequences at each batch?

I wonder we are possible to make different random sequences at each batch with lambda layer in functional API

for example

main_input=Input(shape=(67),name='main_input')
noised_data = Lambda(noising,name='adding_noise_layer')(main_input)
def noising(x):
  noise_real = 1/(np.sqrt(2)*)*K.random_normal((67,),mean=0,stddev=1)
  noise_imag = 1/(np.sqrt(2)*)*K.random_normal((67,),mean=0,stddev=1)
  noise = tf.reshape(tf.dtypes.complex(noise_real,noise_imag), (1,67,))
  return x+noise

In this case, Does each batch add different random noise????




Replace every vowel with random vowels and every consonant with random consonants in Javascript

I need a function that takes a string and replaces every vowel in it with random vowels and every consonant in it with random consonants and returns the new string with the same capitalization as the original in Javascript. Is there a fast way to do it?

For example: If the string is “John” then it could return “Lavr” or “Xiqp”.




C# Display an XML file in a ListBox with possibility to edit the XML

i am actually trying to do a sort of random menu generator for lunch or dinner, i have an XML file in my app resources with multiples nodes, i want to put every STARTER NAME as items in a combobox, then you can choose an item and the STARTER NAME, DESC and RECIPE will be shown in the ListBox. Then on another tab i can create a random menu with starter, main course and dessert. The problem is that's the first time that i need to deal with XML and i dont know how to do what i want to do, i tried a lot of things that i've seen on forums but nothing was working for me.

My XML File looks like that :

<xmlentrees>
  <entrees>
<entree>
    <Nomentree>STARTER NAME</Nomentree>
    <descentree>STARTER DESC</descentree>   
    <recetteentree>RECIPE (YES/NO)</recetteentree>
    <recette>RECIPE THERE</recette>
</entree>
<entree>
    <Nomentree>STARTER NAME</Nomentree>
    <descentree>STARTER DESC</descentree>   
    <recetteentree>RECIPE (YES/NO)</recetteentree>
    <recette>RECIPE THERE</recette>
</entree>
<entree>
    <Nomentree>STARTER NAME</Nomentree>
    <descentree>STARTER DESC</descentree>   
    <recetteentree>RECIPE (YES/NO)</recetteentree>
    <recette>RECIPE THERE</recette>
</entree>
  </entrees>

<nombreentrees>TOTAL OF STARTER LISTED</nombreentrees>

</xmlentrees>

(I am really sorry if my english is not correct, i'm french and still learning english)




The same number is generated everytime (VB.net)

Every time I run this I keep getting 71, I've tried making it public, sharing it and several other things, but it won't work, I am trying to make a program that has the use guess a randomly generated number, but for some reason, it won't work properly in window app forms, and I can't put it under the button as that results in it changing every time. Plz help.

Public Shared Randomize()
Dim value As Integer = CInt(Int((100 * Rnd()) + 1))

Public Sub EnterBtn_Click(sender As Object, e As EventArgs) Handles EnterBtn.Click
    Dim entervalue As String = EnterTxt.Text
    Dim chances As Integer
    Select Case entervalue
        Case > value
            ResTxt.Text = "Too big"
            chances += 1
        Case < value
            ResTxt.Text = "Too small"
            chances += 1
        Case = value
            ResTxt.Text = "Well done, you got it in " & chances & " tries"
    End Select
End Sub

Private Sub ResTxt_TextChanged(sender As Object, e As EventArgs) Handles ResTxt.TextChanged

End Sub

Private Sub EnterTxt_TextChanged(sender As Object, e As EventArgs) Handles EnterTxt.TextChanged

End Sub



Champernowne distribution generation

I am trying to generate random for Champernowne distribution in R. The pdf I am using is -

C_(µ,σ,λ)/(cosh⁡[σ(x-µ)]+λ)

I am having trouble with the finding the algorithm to generate from this distribution. Any help would be appreciated.




Random sampling from dictionary list values based on an integar value from another dictionary, with matching keys

I have two dictionaries, one has items with lists to random sample from:

candidates_to_sample_from = {'PCP3': ['member3', 'member12', 'member17'],
 'PCP4': ['member14', 'member15', 'member16']}

The other has matching keys and the number of samples to draw from and ultimately remove from the pool of members:

sample_counts = Counter({'PCP3': 2, 'PCP4': 1})

I tried doing it two ways without the results I expected. One way is this:

for prov, lst in candidates_to_sample_from.items():
    for i, j in sample_counts.items():
        candidates_out = random.sample(lst, j)

print(candidates_out)
['member16']

This produces only the 1 chosen person from the second item in candidate_to_sample_from but not the two who should be chose from the first item.

Then I also tried creating an empty list and appending to it:

candidates_out = []

for prov, lst in candidates_to_sample_from_dict.items():
    for i, j in sample_counts.items():
        candidates_out.append(random.sample(lst, j))

print(candidates_out)
[['member3', 'member12'], ['members17'], ['member16', 'member14'], ['member16']]

I'm trying to just get a simple list like:

candidates_out = ['member3', 'member17', 'member15']

This has two from item one of candidates_to_sample_from and one from the second. This is a smaller model, it should work the same no matter what the size and scope of the dictionaries




Pandas Replace NaN values based on random sample of values conditional on another column

Say I have a dataframe like so:

import pandas as pd
import numpy as np

np.random.seed(0)

df = {}
df['x'] = np.concatenate([np.random.uniform(0, 5, 4), np.random.uniform(5, 10, 4)])
df['y'] = np.concatenate([[0] * 4, [1] * 4])
df = pd.DataFrame(df)

df.loc[len(df) + 1] = [np.NaN, 0]
df.loc[len(df) + 1] = [np.NaN, 1]
df
Out[232]: 
           x    y
0   2.744068  0.0
1   3.575947  0.0
2   3.013817  0.0
3   2.724416  0.0
4   7.118274  1.0
5   8.229471  1.0
6   7.187936  1.0
7   9.458865  1.0
9        NaN  0.0
10       NaN  1.0

What I want to do is fill in the NaN values based on a random sample of x values based on the y value.

For example, in row 9 where y is 0, I want to replace the NaN with a number randomly sampled only from x values where the value of y is 0. Effectively, I'd be sampling from this list:

df[df['y'] == 0]['x'].dropna().values.tolist()
Out[233]: [2.7440675196366238, 3.5759468318620975, 3.0138168803582195, 2.724415914984484]

And similarly for row 10, I'd sample only based on 'x' values where y is 1, rather than 0. I can't figure out a way to do it programmatically (at least, in a way that isn't bad practice, such as iterating through dataframe rows).

I've consulted Pandas: Replace NaN Using Random Sampling of Column Values, which shows me how I would randomly sample from all values in a column, but I need the random sample to be conditional on another column's distinct values. I've also seen answers for replacing NaNs with a conditional mean (such as this), but I'm looking to randomly sample, rather than use the mean.




How to Generate an Array of Random Number Sets in PHP? [duplicate]

I'm trying to figure out the best way to create an array of sets of randomly selected numbers from a range.

So, for instance:

I have a range of numbers from which to select: 1-100. I want to generate X number of sets of 5 of those numbers WITHOUT DUPLICATES.

So, I want to generate something like:

[3, 24, 32, 49, 68]

[2, 18, 43, 76, 98]

[10, 12, 23, 45, 67]

[5, 56, 64, 72, 90]

...

I know how to generate random numbers from a range once, I just am stuck on doing it X number of times without the possibility of duplicate sets.




mercredi 29 janvier 2020

Why is there sometimes undefined in my tab? [duplicate]

I did random password generator and it works fine but sometimes when I roll for new pass there is undefined inside var text in console. How to fix it?

function generate()
{
    var tab = ['A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z','a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z','0','1','2','3','4','5','6','7','8','9'];
    var text = [];


    for (var i = 0; i < 10; i++) {
        x = Math.random()*tab.length;
        z = Math.round(x)
        text.push(tab[z]);
    }
    console.log(text);
    document.getElementById('input1').value = text.join('');
}
<!DOCTYPE html>
<html>
    <script src="script.js"></script>
    <link rel="stylesheet" href="style.css">
<head></head>
</head>
<body>
    <div class="randompass">
    <input id="input1"></input>
    <button onclick="generate()">Create random</button>
    </div>
</body>
</html>



Randomize letters in pairs (R)

I have a task in my statistics class that reads: Write an R function that randomly configures the plugboard. This function will take no input but will randomly select a set of 13 pairs of letters. The output object should be a 2 x 13 matrix for which each column represents a pair of letters. You may use the built-in R object letters, which contains the 26 letters of the alphabet as a character vector. Name the function plugboard.

I have tried to use: matrix(sample(letters),2,13), which creates the 2 x 13 matrix, and randomizes the 13 pairs of letters every time I run it. But when I create:

plugboard <- matrix(sample(letters),2,13),

and then try to type plugboard a few times, it shows the letters in the same order every time. Can anyone please explain to me how to do this correctly?

Thanks :)




Random number generation Function explanation

Can anyone explain these two lines of function??

 int getRandomNumber(int min, int max)
 {
    static const double fraction = 1.0 / (RAND_MAX + 1.0);
    return min + static_cast<int>((max - min + 1) * (rand() * fraction));
 }



Generate random numbers from a list of numbers

I have a list of numbers:

data = [15, 30, 45]

how to generate a list of N numbers taken randomly from this data list? To get result as:

new_data = [15,15, 30, 45, 15,45, 30, 15, 45, 30, 45, 45, 45, 15, ...]

np.random.randint(15, high=45, size=N) # does not help here

What numpy functions to use for this?




Implement PRNG both on arduino and python

I want to evaluate a big random bytes array both in python and Arduino. I want both of the programs to evaluate the same array. And I want to sync them by a seed.

Therefore the best option to implement that is with a PRNG.

The problem is that I want it to be as random as possible and I don't want to do it myself = which means that I don't care uses a library both in Arduino and python.

The problem is that python and Arduino library implement their random function differently.

Can someone help with a quick solution ? Something that already built up ?




Numpy Gaussian from /dev/urandom

I have an application where I need numpy.random.normal but from a crypgoraphic PRNG source. Numpy doesn't seem to provide this option.

The best I could find was numpy.random.entropy.random_entropy but this is only uint32 and it's buggy, with large arrays you get "RuntimeError: Unable to read from system cryptographic provider" even though urandom is non-blocking...

You can however do this: np.frombuffer(bytearray(os.urandom(1000*1000*4)), dtype=np.uint32).astype(np.double).reshape(1000, 1000)

But I'm still left with the problem of somehow converting it to a Guassian and not screwing anything up.

Is there a solution someone knows? Google is poisoned by numpy seeding from /dev/urandom, I don't need seeding, I need urandom being the only source of all randomness.




mardi 28 janvier 2020

pseudo random number generator for bit commitment

On the Wikipedia page for commitment scheme there is an example that refers to a pseudo random number generator G that takes n bits to 3n bits. What is an example of an algorithm that fits this description that could be used in a real world implementation of this protocol. Bonus points if there is an existing Rust implementation/library or if it is easy to write an implementation for.




If you select 60 numbers randomly from 1 to 100. Whats the overlap probability for different percentage of numbers?

In general for X selections from range 1 to Y?




Deck shuffling algorithm isnt "human" enough

For fun I made this deck shuffling function to mimic how people imperfectly shuffle a deck. They cut it nearly in half and use the "ruffle" method to interweave the left and right decks together and then they repeat the process any number of times. The deck is never perfectly weaved together. You might shuffle them like L1, L2, R1, L3, R2, L4, R3, etc. or R1, L1, R2, R3, L2, etc. . The problem in my code is that successive reshuffles never switch the first and last cards of the deck. If in the first shuffle the bias says put L1 at the top of the deck, then every reshuffle will also have L1 at the top. I moved bias = random.random() into the while loop so it should reset every time and therefore sometimes change the order. Is this some weird instance of pseudo random and recursive code not playing well together?

def shuffle_human(cards,reshuffle):
    split = random.randint(-1*int(len(cards)/20),int(len(cards)/20)) #creates a bias to imperfectly split deck +- 5% of the deck size
    L = cards[:int(len(cards)/2)+split] # creates left deck
    R = cards[int(len(cards)/2)+split:] # creates right deck
    D =[]                               # empty new deck
    while len(D)< len(cards):           
        bias = random.random()          # creates a bias to "incorrectly" choose 
          if L and bias <=.5:           #     which deck the next card will come from**strong text**
            l = L.pop(0)                # pops the card from the deck and appends it in. 
            print(l)                    # formatted this way so i can see whats going on 
            D.append(l)     
        if R and bias >.5:           # same thing for right deck
            r = R.pop(0)
            print(r)
            D.append(r)
    print(D)
    if reshuffle>0:                     # see if there are any reshuffles attempts needed 
        shuffle_perfect(D,reshuffle-1)  # recursive call to reshuffle the deck. 

shuffle_human(deck,3)

Problematic output

 [0, 5, 6, 7, 8, 1, 9, 10, 2, 3, 4]   # initial shuffle
 [0, 1, 5, 9, 6, 10, 7, 2, 8, 3, 4]   # reshuffle 1
 [0, 10, 1, 7, 5, 2, 9, 8, 6, 3, 4]   # 2
 [0, 2, 10, 9, 1, 8, 7, 6, 5, 3, 4]   # 3

As you can see it always has L1 and Ln-1 or R1 and Rn-1 as the first and last digits of the output deck, depending on the result of the first shuffle. No matter how many reshuffles I do. What am I doing wrong?




Generate random points on 10-dimensional unit sphere

I need to generate a vector sampled uniformly with 10 directions (a collection of 10 random numbers) which lies over a unit sphere. So, the sum of the squares of the 10 values should be 1.

This is the exact question for which I need to generate those points:

Implement the Perceptron algorithm and run it on the following synthetic data sets in ℝ10: pick 𝑤∗ = [1,0,0,…,0]; generate 1000 points 𝑥 by sampling uniformly at random over the unit sphere and then removing those that have margin 𝛾 smaller than 0.1; generate label 𝑦 = sign((𝑤∗)T𝑥).




Using an array in PHP to echo numbers in a random order

I have written a very simple couple of .php pages where a user chooses a times table to be tested on, and then answers questions.

At the moment they are just asked 12 random questions for that table, so could be asked the same question several times, and not be asked other questions. I am just using random number generation between 1 and 12 to achieve this.

I believe that I can enter the values 1-12 into an array, and call on them in a random order.

Does this sound like the correct way forward? If so, would someone be able to push me in the right direction? I am looking to learn from this as much as I am looking for a solution.

I have used arrays before from mysqli queries, but wouldn't say that I am 100% confident with them.

The $rand variable is used to determine which way round the question will be asked.

$question = 1;
$random = 0;
while ($question < 13)
{
      $random = rand(0,1);
      if ($random == 0)
      {
         $_SESSION['multiplier'.$question] = $_SESSION['table'];
         $_SESSION['multiplicand'.$question] = rand(1,12);
      }
      else
      {
         $_SESSION['multiplier'.$question] = rand(1,12);
         $_SESSION['multiplicand'.$question] = $_SESSION['table'];
      }
      $answer[$question] = $_SESSION['multiplier'.$question] * $_SESSION['multiplicand'.$question]; 
      $question++;
}



All the values in aray are zero

I am trying to find the time taken by a linear search program to find the time taken by a function to find a random key to from a random array, the problem is that the array comes out to be entirely 0

#include <chrono>
#include <cstdlib>
#include <iostream>
#include <random>

using namespace std;
using namespace std::chrono;

int linearsearch(int a[], int key, int i) {
  int count = 0;
  for (int j = 1; j <= i; j++) {
    if (key == a[i]) {
      count++;
    }
  }
  cout << "\nelement occured exactly " << count << " times";
  return 0;
}

int main() {
  int i, j, l;
  srand(time(0));
  for (i = 5000; i < 50000;) {
    int a[i];
    for (j = 0; j < 100; j++) {  // loop for test case, 100
      a[i] = rand() % i;
      int key = rand() % i;
      auto start = high_resolution_clock::now();
      linearsearch(a, key, i);
      auto stop = high_resolution_clock::now();
      auto duration = duration_cast<microseconds>(stop - start);
      cout << "\narray is ";
      for (l = 0; l < a[i]; l++) cout << a[l] << " ";
      cout << "\nand key is " << key;
      cout << "\nTime taken by function: " << duration.count()
           << " microseconds" << endl;
    }
    i = i + 5000;
  }
  return 0;
}



Random number generation in C++ [duplicate]

I've written this code using the library in C++.

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

double srand(){
   std::uniform_real_distribution<double> distribution(0.0, 1.0);
   std::random_device rd;
   std::default_random_engine generator(rd());
   return distribution(generator);
}

using namespace std;

int main(){
   for(int i=0; i < 10; i++){
   cout << srand() << endl;
   }
}

But every time I run the code, I get this result:

0.687363 0.687363 0.687363 0.687363 0.687363 0.687363 0.687363 0.687363 0.687363 0.687363




How to use different Random.org API keys

My site is distributing things from the Dota 2 game. The winner is randomly selected using the Random.org service. They give out 1,000 keys for free per day, but I get about 1,500 randoms. I'm trying to make sure that if 1000 keys are used, when creating a new distribution, my second API key is selected.

My Controller

<?php namespace App\Http\Controllers;
use App\Http\Controllers\RandomOrgClient;

    public function newgame()
    {
        if ($this->game->status == 2) {

            $random = new RandomOrgClient();
            $arrRandomInt = $random->generateIntegers(1, 0, 14, false, 10, true);
            $game = Game_double::create(['random' => json_encode($random->last_response['result']['random']), 'signature' => $random->last_response['result']['signature'],
                'number' => $arrRandomInt[0],
            ]);

            return $game;
        }

    }

My RandomOrgClient:

<?php namespace App\Http\Controllers;

use App\Http\Controllers\Games;
use App\Http\Controllers\SteamController;
use Exception;


/**
 * RANDOM.ORG
 * JSON-RPC API – Release 1
 * https://api.random.org/json-rpc/1/
 *
 * @author odan
 * @copyright 2014-2016 odan
 * @license http://opensource.org/licenses/MIT The MIT License (MIT)
 * @link https://github.com/odan/random-org
 */
class RandomOrgClient
{

    // The URL for invoking the API
    // https://api.random.org/json-rpc/1/
    protected $url = 'https://api.random.org/json-rpc/2/invoke';
    // Random.org API-KEY
    // https://api.random.org/api-keys
    protected $apiKey = 'MY KEY';
    // Http time limit
    protected $timeLimit = 300;

    /**
     * Constructor
     */
    function __construct()
    {
        $this->setTimelimit($this->timeLimit);
    }

    /**
     * Set API key
     *
     * @param string $apiKey
     */
    public function setApiKey($apiKey)
    {
        $this->apiKey = $apiKey;
    }

    /**
     * This method generates true random integers within a user-defined range.
     *
     * @param int $numbers How many random integers you need.
     * Must be within the [1,1000000000] range.
     * @param int $min The lower boundary for the range from which the
     * random numbers will be picked.
     * Must be within the [-1000000000,1000000000] range.
     * @param int $max The upper boundary for the range from which the
     * random numbers will be picked.
     * Must be within the [-1000000000,1000000000] range.
     * @param type $replacement Specifies whether the random numbers
     * should be picked with replacement. The default (true) will cause the
     * numbers to be picked with replacement, i.e., the resulting numbers
     * may contain duplicate values (like a series of dice rolls).
     * If you want the numbers picked to be unique (like raffle tickets
     * drawn from a container), set this value to false.
     * @param type $base Specifies the base that will be used to display
     * the numbers. Values allowed are 2, 8, 10 and 16.
     * @return array
     */
    public function generateIntegers($numbers, $min, $max, $requestID)
    {
        $replacement = true;
        $base = 10;
        $params = array();
        $params['apiKey'] = $this->apiKey;
        $params['n'] = $numbers;
        $params['min'] = $min;
        $params['max'] = $max;
        $params['replacement'] = $replacement;
        $params['base'] = $base;
        $response = $this->call('generateSignedIntegers', $params, $requestID);

        if (isset($response['error']['message'])) {
            throw new Exception($response['error']['message']);
        }
        $result = array();
        if (isset($response['result']['random']['data'])) {
            $this->last_response = $response;
            $result = $response['result']['random']['data'];
        }
        return $result;
    }

    /**
     * This method generates true random decimal fractions from a uniform
     * distribution across the [0,1] interval with a user-defined number of
     * decimal places.
     *
     * @param int $numbers How many random decimal fractions you need.
     * Must be within the [1,10000] range.
     * @param int $decimalPlaces The number of decimal places to use.
     * Must be within the [1,20] range.
     * @param bool $replacement Specifies whether the random numbers should
     * be picked with replacement. The default (true) will cause the numbers to
     * be picked with replacement, i.e., the resulting numbers may contain
     * duplicate values (like a series of dice rolls).
     * If you want the numbers picked to be unique (like raffle tickets
     * drawn from a container), set this value to false.
     * @return array
     * @throws Exception
     */
    public function generateDecimalFractions($numbers, $decimalPlaces, $replacement = true)
    {
        $params = array();
        $params['apiKey'] = $this->apiKey;
        $params['n'] = $numbers;
        $params['decimalPlaces'] = $decimalPlaces;
        $params['replacement'] = $replacement;
        $response = $this->call('generateDecimalFractions', $params);

        if (isset($response['error']['message'])) {
            throw new Exception($response['error']['message']);
        }
        $result = array();
        if (isset($response['result']['random']['data'])) {
            $result = $response['result']['random']['data'];
        }
        return $result;
    }

    /**
     * This method generates true random numbers from a Gaussian distribution 7
     * (also known as a normal distribution). The form uses a Box-Muller
     * Transform to generate the Gaussian distribution from uniformly
     * distributed numbers.
     *
     * @param int $numbers How many random numbers you need.
     * Must be within the [1,10000] range.
     * @param int $mean The distribution's mean.
     * Must be within the [-1000000,1000000] range.
     * @param int $standardDeviation The distribution's standard deviation.
     * Must be within the [-1000000,1000000] range.
     * @param int $significantDigits The number of significant digits to use.
     * Must be within the [2,20] range.
     * @return array
     * @throws Exception
     */
    public function generateGaussians($numbers, $mean, $standardDeviation, $significantDigits)
    {
        $params = array();
        $params['apiKey'] = $this->apiKey;
        $params['n'] = $numbers;
        $params['mean'] = $mean;
        $params['standardDeviation'] = $standardDeviation;
        $params['significantDigits'] = $significantDigits;

        $response = $this->call('generateGaussians', $params);

        if (isset($response['error']['message'])) {
            throw new Exception($response['error']['message']);
        }
        $result = array();
        if (isset($response['result']['random']['data'])) {
            $result = $response['result']['random']['data'];
        }
        return $result;
    }

    /**
     * This method generates true random strings.
     *
     * @param int $numbers How many random strings you need.
     * Must be within the [1,10000] range.
     * @param int $length The length of each string. Must be within
     * the [1,20] range. All strings will be of the same length
     * @param int $characters A string that contains the set of characters
     * that are allowed to occur in the random strings.
     * The maximum number of characters is 80.
     * @param bool $replacement (true = with duplicates, false = unique)
     * @return array
     * @throws Exception
     */
    public function generateStrings($numbers, $length, $characters = null, $replacement = true)
    {

        if ($characters === null) {
            // default
            $characters = 'abcdefghijklmnopqrstuvwxyz';
            $characters .= 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
            $characters .= '0123456789';
        }

        $params = array();
        $params['apiKey'] = $this->apiKey;
        $params['n'] = $numbers;
        $params['length'] = $length;
        $params['characters'] = $characters;
        $params['replacement'] = $replacement;

        $response = $this->call('generateStrings', $params);

        if (isset($response['error']['message'])) {
            throw new Exception($response['error']['message']);
        }
        $result = array();
        if (isset($response['result']['random']['data'])) {
            $result = $response['result']['random']['data'];
        }
        return $result;
    }

    /**
     * This method generates version 4 true random Universally Unique
     * IDentifiers (UUIDs) in accordance with section 4.4 of RFC 4122.
     *
     * @param int $numbers
     * @return array
     * @throws Exception
     */
    public function generateUUIDs($numbers)
    {
        $params = array();
        $params['apiKey'] = $this->apiKey;
        $params['n'] = $numbers;

        $response = $this->call('generateUUIDs', $params);

        if (isset($response['error']['message'])) {
            throw new Exception($response['error']['message']);
        }
        $result = array();
        if (isset($response['result']['random']['data'])) {
            $result = $response['result']['random']['data'];
        }
        return $result;
    }

    /**
     * This method generates Binary Large Objects (BLOBs)
     * containing true random data.
     *
     * @param int $numbers How many random blobs you need.
     * Must be within the [1,100] range.
     * @param int $size The size of each blob, measured in bits.
     * Must be within the [1,1048576] range and must be divisible by 8.
     * @param string $format Specifies the format in which the blobs will
     * be returned. Values allowed are base64 and hex.
     * @return array
     * @throws Exception
     */
    public function generateBlobs($numbers, $size, $format = 'base64')
    {
        $params = array();
        $params['apiKey'] = $this->apiKey;
        $params['n'] = $numbers;
        $params['size'] = $size;
        $params['format'] = $format;

        $response = $this->call('generateBlobs', $params);

        if (isset($response['error']['message'])) {
            throw new Exception($response['error']['message']);
        }

        $result = array();
        if (isset($response['result']['random']['data'])) {
            $result = $response['result']['random']['data'];
        }
        return $result;
    }

    /**
     * This method returns information related to the the
     * usage of a given API key.
     *
     * @param type $apiKey (optional) Your API key,
     * which is used to track the true random bit usage for your client.
     *
     * @return array
     * @throws Exception
     */
    public function getUsage($apiKey = null)
    {
        $params = array();

        if ($apiKey === null) {
            $apiKey = $this->apiKey;
        }
        $params['apiKey'] = $apiKey;

        $response = $this->call('getUsage', $params);

        if (isset($response['error']['message'])) {
            throw new Exception($response['error']['message']);
        }

        $result = array();
        if (isset($response['result'])) {
            $result = $response['result'];
        }

        return $result;
    }

    /**
     * Set endpoint URL
     *
     * @param string $url url
     */
    protected function setUrl($url)
    {
        $this->url = $url;
    }

    /**
     * Set time limit
     *
     * @param int $timeLimit
     */
    protected function setTimelimit($timeLimit)
    {
        $this->timeLimit = $timeLimit;
        set_time_limit($this->timeLimit);
    }

    /**
     * Http Json-RPC Request ausfuehren
     *
     * @param string $method
     * @param array $params
     * @return array
     */
    protected function call($method, $params = null, $randomID = null)
    {
        if(empty($randomID))
            $randomID = mt_rand(1, 999999);
        $request = array();
        $request['jsonrpc'] = '2.0';
        $request['id'] = $randomID;
        $request['method'] = $method;
        if (isset($params)) {
            $request['params'] = $params;
        }

        $json = $this->encodeJson($request);
        $responseData = $this->post($json);
        $response = $this->decodeJson($responseData);
        return $response;
    }

    /**
     * HTTP POST-Request
     *
     * @param string $content content data
     * @return string
     */
    protected function post($content = '')
    {
        $defaults = array(
            CURLOPT_POST => 1,
            CURLOPT_HEADER => 0,
            CURLOPT_URL => $this->url,
            CURLOPT_FRESH_CONNECT => 1,
            CURLOPT_RETURNTRANSFER => 1,
            CURLOPT_FORBID_REUSE => 1,
            CURLOPT_TIMEOUT => $this->timeLimit,
            CURLOPT_HTTPHEADER => array('Content-Type: application/json'),
            CURLOPT_POSTFIELDS => $content,
            CURLOPT_SSL_VERIFYHOST => 0,
            CURLOPT_SSL_VERIFYPEER => false
        );

        $ch = curl_init();
        curl_setopt_array($ch, $defaults);

        $result = curl_exec($ch);
        $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);

        if ($httpCode < 200 || $httpCode >= 300) {
            $errorCode = curl_errno($ch);
            $errorMsg = curl_error($ch);
            $text = trim(strip_tags($result));
            curl_close($ch);
            throw new Exception(trim("HTTP Error [$httpCode] $errorMsg. $text"), $errorCode);
        }

        curl_close($ch);
        return $result;
    }

    /**
     * Json encoder
     *
     * @param array $array
     * @param int $options
     * @return string
     */
    protected function encodeJson($array, $options = 0)
    {
        return json_encode($this->encodeUtf8($array), $options);
    }

    /**
     * Json decoder
     *
     * @param string $strJson
     * @return array
     */
    protected function decodeJson($strJson)
    {
        return json_decode($strJson, true);
    }

    /**
     * Encodes an ISO string to UTF-8
     *
     * @param mixed $str
     * @return mixed
     */
    protected function encodeUtf8($str)
    {
        if ($str === null || $str === '') {
            return $str;
        }

        if (is_array($str)) {
            foreach ($str as $key => $value) {
                $str[$key] = $this->encodeUtf8($value);
            }
            return $str;
        } else {
            if (!mb_check_encoding($str, 'UTF-8')) {
                return mb_convert_encoding($str, 'UTF-8');
            } else {
                return $str;
            }
        }
    }
}

I need that if 1000 keys are used for the first API, the second API with new keys should be used. I duplicated file RandomOrgClient at App\Http\Controllers\, and try to change $random = new RandomOrgClient();, but nothing happens, a new game is not created due to the fact that 1000 keys are used.

How i can make it?




Random.org API use [closed]

My site is distributing things from the Dota 2 game. The winner is randomly selected using the Random.org service. They give out 1,000 keys for free per day, but I get about 1,500 keys. I'm trying to make sure that if 1000 keys are used, when creating a new distribution, my second API key is selected.

My Controller

<?php namespace App\Http\Controllers;
use App\Http\Controllers\RandomOrgClient;

    public function newgame()
    {
        if ($this->game->status == 2) {

            $random = new RandomOrgClient();
            $arrRandomInt = $random->generateIntegers(1, 0, 14, false, 10, true);
            $game = Game_double::create(['random' => json_encode($random->last_response['result']['random']), 'signature' => $random->last_response['result']['signature'],
                'number' => $arrRandomInt[0],
            ]);

            return $game;
        }

    }

I need that if 1000 keys are used for the first API, the second API with new keys should be used. I duplicated file RandomOrgClient at App\Http\Controllers\, and try to change $random = new RandomOrgClient();, but nothing happens, a new game is not created due to the fact that 1000 keys are used.




Randomly Generated Graphs to output Euler path or Euler cycle for it

I have this code in Java. It can print an Euler path or a cycle for a given graphs using Fleury’s algorithm. My goal is to modify this code to print Euler paths or circuits using only randomly generated graphs. In addition I would like to make it print only minimal Euler cycles, but the main goal is random generation fo graphs.

import java.util.ArrayList; 

public class Graph { 

    private int vertices; 
    private ArrayList<Integer>[] adj; 

    Graph(int numOfVertices) 
    { 
        this.vertices = numOfVertices; 

        initGraph(); 
    } 

    @SuppressWarnings("unchecked") 
    private void initGraph() 
    { 
        adj = new ArrayList[vertices]; 
        for (int i = 0; i < vertices; i++)  
        { 
            adj[i] = new ArrayList<>(); 
        } 
    } 

    private void addEdge(Integer u, Integer v) 
    { 
        adj[u].add(v); 
        adj[v].add(u); 
    } 

    private void removeEdge(Integer u, Integer v) 
    { 
        adj[u].remove(v); 
        adj[v].remove(u); 
    } 

    private void printEulerTour() 
    { 
        Integer u = 0; 
        for (int i = 0; i < vertices; i++) 
        { 
            if (adj[i].size() % 2 == 1) 
            { 
                u = i; 
                break; 
            } 
        } 

        printEulerUtil(u); 
        System.out.println(); 
    } 

    private void printEulerUtil(Integer u) 
    { 
        for (int i = 0; i < adj[u].size(); i++) 
        { 
            Integer v = adj[u].get(i); 
            if (isValidNextEdge(u, v))  
            { 
                System.out.print(u + "-" + v + " "); 

                removeEdge(u, v);  
                printEulerUtil(v); 
            } 
        } 
    } 

    private boolean isValidNextEdge(Integer u, Integer v) 
    { 
        if (adj[u].size() == 1) { 
            return true; 
        } 

        boolean[] isVisited = new boolean[this.vertices]; 
        int count1 = dfsCount(u, isVisited); 

        removeEdge(u, v); 
        isVisited = new boolean[this.vertices]; 
        int count2 = dfsCount(u, isVisited); 

        addEdge(u, v); 
        return (count1 > count2) ? false : true; 
    } 

    private int dfsCount(Integer v, boolean[] isVisited) 
    { 
        isVisited[v] = true; 
        int count = 1; 
        for (int adj : adj[v]) 
        { 
            if (!isVisited[adj]) 
            { 
                count = count + dfsCount(adj, isVisited); 
            } 
        } 
        return count; 
    } 

    public static void main(String a[]) 
    {  
        //My graphs

        Graph g1 = new Graph(5); 
        g1.addEdge(1, 0); 
        g1.addEdge(0, 2); 
        g1.addEdge(2, 1); 
        g1.addEdge(0, 3); 
        g1.addEdge(3, 4); 
        g1.addEdge(3, 2); 
        g1.addEdge(3, 1); 
        g1.addEdge(2, 4);
        g1.printEulerTour(); 
    } 
}

Any ideas how can I implement random generation for graphs here?




How to randomly choose coefficients of a linear combination in Python? [closed]

I have a linear combination like

formula

I want to randomly select the coefficients c_i with the constraint

formula

As a minimal example in Python:

import numpy as np

x = 0.1
func_list = [np.sin(x), np.cos(x), x**2]

def linear_comb(a, b, c):
    return a*func_list[0] + b*func_list[1] + c*func_list[2]

How should I sample a , b and c from uniform distributions with the constraint a^2+b^2+c^2=1?




Is there a way to run functions in the order of a randomly generated list in Arduino IDE?

I have a list of functions like this for instance:

void cube () {...}
void diamond () {...}
void cylinder () {...}
void sphere () {...}
void cone () {...}

and I make a random function where it generates a list of non-repeating numbers (let's say between 0 and 4) so that it creates a list like this:

random_List = {1,0,4,2,3}

I already know how to make the list, but after that, what would I have to do in order to make the functions run according to the sequence of the list? I will assign a number to the functions like void cube () {}would be assigned 1 and void diamond () {} would be 2 and so forth.




lundi 27 janvier 2020

Random string picker (string names are exactly the same, except the number)

Dim rnd As New Random
Dim quote1, quote2, quote3 As String
Dim int As Integer

int = rnd.Next(1, 3)
quote1 = "never give up"
quote2 = "always believe in yourself"
quote3 = "always follow your dreams"

MessageBox.Show("quote" & int)

Hey, can somebody please tell me, how I can assign the int to the word quote, so every time it would pick a different quote?




Generating random numbers from custom continuous probability density function

as the title states I am trying to generate random numbers from a custom continuous probability density function, which is:

0.001257 *x^4 * e^(-0.285714 *x)

to do so, I use (on python 3) scipy.stats.rv_continuous and then rvs() to generate them

from decimal import Decimal
from scipy import stats

class my_distribution(stats.rv_continuous):
    def _pdf(self, x):
        return (Decimal(0.001257) *Decimal(x)**(4)*Decimal(np.exp(-0.285714 *x)))

distribution = my_distribution()
distribution.rvs()

note that I used Decimal to get rid of an OverflowError: (34, 'Result too large').

Still, I get an error RuntimeError: Failed to converge after 100 iterations.

What's going on there? What's the proper way to achieve what I need to do?




Why am I getting a "Run-Time Check Failure #2 - Stack around the variable 'pr' was corrupted" Error?

It happens in void numgeneratorinator(int ar[]) whenever I try to run run the program. The program itself is supposed to generate as many magic squares as the user needs, then checks how many of those are magic squares. I have that down however this number generator is not working with me and I keep getting the "Run-Time Check Failure #2 - Stack around the variable 'pr' was corrupted" Error. It seems to "work" when I change pr[9] to pr[10] but then when I print the matrix as a test it has a zero in it and after 1 run it results in the matrix having a really low number in it (like -83289).

#include <ctime>
#include <cstdlib>
#include <iostream>
#include <iomanip> //Used for printinator

void printinator(int a[][3]) //prints a matrix
{
    using namespace std;
    for (int i = 0; i < 3; i++)
    {
        for (int j = 0; j < 3; j++)
            cout << fixed << setprecision(2) << setw(12) << a[i][j] << "  ";
        cout << endl;
    }
    cout << endl;
}

int Checkinator(int m[][3]) //https://www.codespeedy.com/how-to-check-the-given-matrix-is-magic-square-or-not-cpp/ This function checks to see if the created matrix is M A G I C A L
{
    int s1 = 0, s2 = 0;

    for (int i = 0; i < 3; i++)
        s1 += m[i][i];

    for (int i = 0; i < 3; i++)
        s2 += m[i][3 - 1 - i];

    if (s1 != s2)
        return 0;

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

        int rs = 0;
        for (int j = 0; j < 3; j++)
            rs += m[i][j];

        if (rs != s1)
            return 0;
    }

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

        int cs = 0;
        for (int j = 0; j < 3; j++)
            cs += m[j][i];

        if (cs != s1)
            return 1;
    }

    return true;
}

void numgeneratorinator(int ar[])
{
    int pr[9] = { 1,2,3,4,5,6,7,8,9 };

    for (int i = 9; i > 1; --i)
    {
        int j = rand() % i;
        int temp = pr[i];
        pr[i] = pr[j];
        pr[j] = temp;
    }
    for (int i = 1; i < 9; ++i)
        ar[i] = pr[i];
}

int main()
{
    int tr;
    srand(time(0));
    char more = 'y';

    using namespace std;
    while (more == 'y' || more == 'Y')
    {
        cout << "\n\t\tHow many randomly generated matrix would you like to test? : ";
        cin >> tr;
        int res = 0;
        int ra = 0;
        int ar[9] = {1,2,3,4,5,6,7,8,9};
        int m[3][3] = { {0,0,0}, {0,0,0}, {0,0,0} };
        numgeneratorinator(ar);

            for (int p = 0; p < tr; p++)
            {
                for (int i = 0; i < 3; i++)
                {
                    for (int k = 0; k < 3; k++)
                    {
                        m[i][k] = ar[ra++];
                        if (ra >= 10)
                            ra = 0;
                    }
                }
                if (Checkinator(m) == true)
                    res++;
            }
            cout << "\n\t\t\tThere are " << res << " magic squares after running " << tr << " times.\n";
            printinator(m); //This was used for testing purposes to ensure the random number generator was working
            cout << "\n\t\tWould you like to do another run? : ";
            cin >> more;
    }
}





Improving random selection: Python subnet mask generator

I created this code to generate random a random subnet mask (so I could practice converting them to their associated prefix, on paper). I am randomly creating a subnet mask one octet at a time, but if any octet is NOT 255, the rest are automatically "0":

from random import randint

# choose subnet bytes at random
def pick_num():
    # list of valid subnet bytes
    list = [0, 128, 192, 224, 240, 248, 252, 254, 255]

    random = randint(0,8)
    num = list[random]
    return num

def generate_netmask():
    current_byte = 0
    submask_mask = ""
    count = 1
    while count <= 4:
        current_byte = pick_num()
        if current_byte == 255:
            submask_mask += str(current_byte) + "."
            count += 1
        else:
            submask_mask += str(current_byte) + "."
            count += 1
            break

    while count != 5:
        if count != 4:
            submask_mask += "0."
            count += 1
        elif count == 4:
            submask_mask += "0"
            count += 1

    return submask_mask

print(generate_netmask())

As a result, a majority of my output doesn't make it past the 1st or 2nd octet. For example: 128.0.0.0, 192.0.0.0, 254.0.0.0, etc. Every now and then I'll get something like: 255.255.192.0

I'm seeing this as a fun opportunity to learn about using randomness in code.

Can anyone recommend a way/ways of making this code more fair to the other subnet masks possibilities? I realize I could also make a list of all the subnet masks and randomly choose elements in the list.

Thank you in advance, Sebastian




How to create sample CSV data to test with including date, string and numeric formats using Linux shell

I am looking to generate CSV data to test with in third party products.

I would like to create different types of data numeric / string.

My aim is to generate this data using Linux shell scripting.

I would be using random functions like echo cat /dev/urandom | tr -dc 'a-zA-Z0-9' | fold -w ${1:-32} which have been used to generate characters.

The outcome is like this: zMHqyni4P1ovqJtXK2HKhe19efgbxy1t

Is there any way of generating strings with words concatenated with meaning instead of random string chains?

That would be used for First/Last Names & Email addresses.

Is it possible to do it with native Linux?

Thanks




JTextField Update Text

I am using Java8 Swing. I have 2 JTextfields, one of which has a user input and the other that I want to display random numbers (btwn 1-100) until it matches the user input. I know the new random numbers are being generated becuase I see them when they are being printed out. However, my textfield is not showing any of the updated numbers and just shows the final random number that eventually matches the user input number. What am i doing wrong?

setButton.addActionListener(new ActionListener() {
     @Override
     public void actionPerformed(ActionEvent e) {
        double setCrystalTemp = Double.parseDouble(crystalSetTF.getText());
        Random random = new Random();
        int crystalTempRandom = 0;
        while (crystalTempRandom != setCrystalTemp) {
           random = new Random();
           crystalTempRandom = random.nextInt(100);
           crystalTempTF.setText(String.valueOf(crystalTempRandom));
           System.out.println(crystalTempRandom);
         }
     }
});



AxisError: axis 1 is out of bounds for array of dimension 0

I have the following code for one of NIST randomness tests. it is a python version on git hub at: https://github.com/stevenang/randomness_testsuite. the code is as follows:

def longest_one_block_test(binary_data:str, verbose=False):

        length_of_binary_data = len(binary_data)

        # print('Length of binary string: ', length_of_binary_data)

        # Initialized k, m. n, pi and v_values

        if length_of_binary_data < 128:

            # Not enough data to run this test

            return (0.00000, False, 'Error: Not enough data to run this test')

        elif length_of_binary_data < 6272:

            k = 3
            m = 8
            v_values = [1, 2, 3, 4]
            pi_values = [0.2148, 0.3672, 0.2305, 0.1875]

        elif length_of_binary_data < 750000:

            k = 5

            m = 128

            v_values = [4, 5, 6, 7, 8, 9]

            pi_values = [0.1174, 0.2430, 0.2493, 0.1752, 0.1027, 0.1124]

        else:

            # If length_of_bit_string > 750000

            k = 6

            m = 10000

            v_values = [10, 11, 12, 13, 14, 15, 16]

            pi_values = [0.0882, 0.2092, 0.2483, 0.1933, 0.1208, 0.0675, 0.0727]

        number_of_blocks = floor(length_of_binary_data / m)

        block_start = 0

        block_end = m

        xObs = 0

        # This will intialized an array with a number of 0 you specified.

        frequencies = zeros(k + 1)

        # print('Number of Blocks: ', number_of_blocks)

        for count in range(number_of_blocks):

            block_data = binary_data[block_start:block_end]

            max_run_count = 0

            run_count = 0

            # This will count the number of ones in the block

            for bit in block_data:

                if bit == '1':

                    run_count += 1

                    max_run_count = max(max_run_count, run_count)

                else:

                    max_run_count = max(max_run_count, run_count)

                    run_count = 0

            max(max_run_count, run_count)

            #print('Block Data: ', block_data, '. Run Count: ', max_run_count)

            if max_run_count < v_values[0]:

                frequencies[0] += 1

            for j in range(k):

                if max_run_count == v_values[j]:

                    frequencies[j] += 1

            if max_run_count > v_values[k - 1]:

                frequencies[k] += 1

            block_start += m

            block_end += m

        # print("Frequencies: ", frequencies)

        # Compute xObs

        for count in range(len(frequencies)):

            xObs += pow((frequencies[count] - (number_of_blocks * pi_values[count])), 2.0) / (

                    number_of_blocks * pi_values[count])

        p_value = gammaincc(float(k / 2), float(xObs / 2))


        return (p_value, (p_value > 0.01))

when i run it for some binary string, i am getting the message AxisError: axis 1 is out of bounds for array of dimension 0.
this test is one of many other ones. all run correctly, except for this one. not sure what is wrong with it.




Sceneform ARCore load and build a random 3D asset

I have a method that builds and spawns a 3D asset in an AR environment. The 3D asset is .sfb file stored in the metadata folder. I have multiple 3D assets in the metadata folder, and I wish to have an asset selected at random when this function is called. This is the code I have for spawning a specific asset:

private void addCreatureToScene() {

    ModelRenderable
            .builder()
            **.setSource(this, Uri.parse("20170219_Dragon_small.sfb"))**
            .build()
            .thenAccept(renderable -> {

                    Node node = new Node();
                    node.setRenderable(renderable);
                    scene.addChild(node);

                    Random random = new Random();
                    int x = random.nextInt(6);
                    int z = random.nextInt(6);
                    int y = random.nextInt(5);

                    z = -z;

                    node.setWorldPosition(new Vector3(
                            (float) x,
                            y / 10f,
                            (float) z
                    )); 
            });
} 

The .setSource code in bold is where a specific 3D asset is referenced. Is there a way to randomly select a 3D asset from the metadata folder? Thank you for your help.




Control output location of random from array button in javascript / HTML

I'm trying to control the output of multiple elements from an array. I have an image and 4 separate pieces of text that need to output into specific locations. Right now, the output is right next to the button. I have tried the document.getElementById function in those spots, but it didn't work, so right now it's just plain text.

I'm an educator trying to make better tools for my students so any help really helps them.

<!DOCTYPE html>
<html>

<body>

<div class="row">
  <div class="column" style="background-color:#aaa;
  height:600px;">
        <center><div id="card">
                <div id="front">This is front of the card</div>
                <div id="back"> This is the back of the card
      <img src="quote.img"> </div>
        </div>
    </div>
    <div class="column" style="
    background-color:#ccc;
     height:600px;">
   <!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
<style>
* {
  box-sizing: border-box;
}

body {
  margin: 0;
  font-family: Arial, Helvetica, sans-serif;
}

/* The grid: Three equal columns that floats next to each other */
.column {
  float: left;
  width: 50%;
  padding: 10px;
  text-align: center;
  font-size: 25px;
  cursor: pointer;
  color: white;
}

.containerTab {
  padding: 20px;
  color: white;
}

/* Clear floats after the columns */
.row:after {
  content: "";
  display: table;
  clear: both;
}

/* Closable button inside the container tab */
.closebtn {
  float: right;
  color: white;
  font-size: 35px;
  cursor: pointer;
}
</style>
</head>


<div style="text-align:center">
 
  <p>Click on the clues below:</p>
</div>


<div class="row">
  <div class="column" onclick="openTab('b1');" style="background:green;">
    Box 1
  </div>
  <div class="column" onclick="openTab('b2');" style="background:blue;">
    Box 2
  </div>
  <div class="column" onclick="openTab('b3');" style="background:red;">
    Box 3
  </div>
  <div class="column" onclick="openTab('b4');" style="background:purple;">
    Box 4
  </div>
</div>

<!--  Clue Output -->
<div id="b1" class="containerTab" style="display:none;background:green">
  <span onclick="this.parentElement.style.display='none'" class="closebtn">&times;</span>
  <h2>Clue 1</h2>
  <p><script type="text/javascript">document.getElementById("quote").innerHTML =
        '<p>' + quote.clue1 + '</p>' </script></p>
</div>

<div id="b2" class="containerTab" style="display:none;background:blue">
  <span onclick="this.parentElement.style.display='none'" class="closebtn">&times;</span>
  <h2>Clue 2</h2>
  <p>quote.clue2</p>
</div>

<div id="b3" class="containerTab" style="display:none;background:red">
  <span onclick="this.parentElement.style.display='none'" class="closebtn">&times;</span>
  <h2>Clue 3</h2>
  <p>quote.clue3</p> </div>

<div id="b4" class="containerTab" style="display:none;background:purple">
  <span onclick="this.parentElement.style.display='none'" class="closebtn">&times;</span>
  <h2>Clue 4</h2>
  <p>quote.clue4</p>
</div>


<script>
function openTab(tabName) {
  var i, x;
  x = document.getElementsByClassName("containerTab");
  for (i = 0; i < x.length; i++) {
    x[i].style.display = "none";
  }
  document.getElementById(tabName).style.display = "block";
}
</script>


      <p>
<div id="quote"></div>


    <input class="Randombutton" type="button" 
    value="Randomize" onclick="randomImg()">
     </p>
    
    <script>
    function randomImg() {
      var quotes = [
        {
          clue1: "pizza clue 1",
          clue2: "pizza clue 2",
          clue3: "pizza clue 3",
          clue4: "pizza clue 4",
          img:  "https://i.imgur.com/wauvv4p.png"
        },
        {
          clue1: "pancake clue 1",
          clue2: "pancake clue 2",
          clue3: "pancake clue 3",
          clue4: "pancake clue 4",
          img:  "https://i.imgur.com/MfFE5mT.png",
        },
    {
          clue1: "apple clue 1",
          clue2: "apple clue 2",
          clue3: "apple clue 3",
          clue4: "apple clue 4",
          img:  "https://i.imgur.com/1CdyJdS.png",
        },
 
      ];
      var quote = quotes[Math.floor(Math.random() * quotes.length)];
      document.getElementById("quote").innerHTML =
        '<p>' + quote.clue1 + '</p>' +
       '<p>' + quote.clue2 + '</p>' +
        '<p>' + quote.clue3 + '</p>' +
        '<p>' + quote.clue4 + '</p>' +
        '<img src="' + quote.img + '">';
    }
    </script>

</body>
</html> 


<style type="text/css">

        #card{
                padding:10px;
                margin: 30px;
                text-align: center;
                width: 400px;
                height: 500px;
                background:#fa0;
                border-radius: 20px;
                perspective: 700;
        
                
        }
        #front{
                backface-visibility: hidden;
        }
        #back{
                backface-visibility: hidden;
                transform: rotateY(180deg);
        }
        #card:active{
                transform-style: preserve-3d;
                transform: rotatey(180deg);
                transition: 1.3s ease;
        }


                

        }
</style>

</html>



Attempted to write a public instance method which takes no argument and returns no value however should include the information below

Write a public instance method called runExperiments() which takes no argument and returns no value.(done)

• The method should attempt to decrement powerLevel by a random number between 1 and 3 inclusive for each experiment up to numberOfExperiments. You should make use of the supplied helper method randomInteger() for this... I have attempted this below but I don't think it is correct.

• If the powerLevel can be reduced, a message indicating the experiment number (starting at 1) should be displayed. If not, a suitable message should be displayed and remaining experiments should not be attempted.

• When all experiments have finished it should display "Experiment run stopped".

Write this method, choosing a suitable kind of loop to control the number of iterations required.

Hints:

  1. Don't forget to make use of the return value from decrementPower().

  2. Experiments should not yet run as the default value of powerLevel is 0.

Can someone please help me with my code below is where I am stuck. I am not sure how to get random number by using the info above.

and here is the full code:

 public class SpaceRocket extends FlyingObject implements Launchable
  {
 private int maxPowerLevel;    
 private int numberOfExperiments;
 private int powerLevel;

public int getMaxPowerLevel()
{
return this.maxPowerLevel;
}

 public int getNumberOfExperiments()
 {
return this.numberOfExperiments;
}   

 public int getPowerLevel()
{
return this.powerLevel;
}

 public SpaceRocket(String aName, int aNumberOfExperiments)
 {
this.name = aName;  
this.numberOfExperiments = aNumberOfExperiments;
this.powerLevel = 0;
this.maxPowerLevel = 15;
}

public boolean decrementPower(int powerReduction)
{
if (powerReduction > this.getPowerLevel()){
    this.powerLevel = 0;  
return false;
} 
else
{
this.powerLevel = powerReduction;
return true;
}
}

question above: This is what I have attempted so far but not sure if it is correct and how I would do the rest of it:

public void runExperiments()
{
{
  for (int i = 0; i < this.numberOfExperiments; i++ ) {
      this.powerLevel -= randomInteger();
    }

and this is what has been privided:

/** * provided * return a random integer between 1 and 3 inclusive

 public int randomInteger() 
  {
  java.util.Random r = new java.util.Random();
  return r.nextInt(3) + 1;
  }  



Write a public instance method called which takes no argument and returns no value using supplied helper method

The method should attempt to decrement powerLevel by a random number between 1 and 3 inclusive for each experiment up to numberOfExperiments. You should make use of the supplied helper method randomInteger() for this.

Can someone please help me with my code below is where I am stuck. I am not sure how to get random number by using the info above.

and here is the full code:

 public class SpaceRocket extends FlyingObject implements Launchable
 {
private int maxPowerLevel;    
private int numberOfExperiments;
private int powerLevel;

public int getMaxPowerLevel()
{
    return this.maxPowerLevel;
}

public int getNumberOfExperiments()
{
    return this.numberOfExperiments;
}

public int getPowerLevel()
{
    return this.powerLevel;
}

public SpaceRocket(String aName, int aNumberOfExperiments)
{
    this.name = aName;  
    this.numberOfExperiments = aNumberOfExperiments;
    this.powerLevel = 0;
    this.maxPowerLevel = 15;
}

public boolean decrementPower(int powerReduction)
{
    if (powerReduction > this.getPowerLevel()){
        this.powerLevel = 0;  
    return false;
} 
else
{
    this.powerLevel = powerReduction;
    return true;
}
}

This is what I have done so far:

public void runExperiments()
{
this.powerLevel -= randomInteger(1,3);
}

and this is what has been privided:

/** * provided * return a random integer between 1 and 3 inclusive

  public int randomInteger() 
   {
   java.util.Random r = new java.util.Random();
   return r.nextInt(3) + 1;
   }  



How to get random letters in a multidimensional array in Python? [closed]

I'm new to Python and I'm trying to translate some code from c++ to python, but I can't make letters be random in both dimensions of a list. This is my function

def chooseLetter():
    lower_alphabet=['a', 'b', 'c', 'd']
    element=''
    if (random.randint(0,2)==1):
        element = element + random.choice(lower_alphabet)
        return element
    else:
        return ' '


for i in range(9):
for j in range(9):
    board[i][j]=chooseLetter()

I get something like this

[[' ', 'b', 'b', 'c', ' ', ' ', ' ', ' ', ' '], [' ', 'b', 'b', 'c', ' ', ' ', ' ', ' ', ' '], ...

I tried system random and some datetime modules, but I am not that familiar with all that and it doesn't really work. ' ' are supposed to be there, I don't want letters to be everywhere.




How to convert JavaScript array values into array stings values

I have got an array var array = [31,2,32,39,15,12:R,33:H,22:E,X,X];

And what I'm trying to do is to transform above array to: var array = ['31','2','32','39','15','12:R','33:H','22:E','X','X'];




What to include in random structure? lmer

Should we still have trial number in the linear mixed effects model even if the item order is randomized not only for each participant but each session? I included participants as a random effect but not sure about whether item should also be included.

Session 1

Participant A                  Participant B

Item A                          Item C
Item B                          Item A
Item C                          Item B
Item D                          Item D

Session 2

Participant A                  Participant B

Item E                          Item H
Item G                          Item G
Item F                          Item F
Item H                          Item E



using array_rand rather than shuffle in PHP

I am using the code from this grade.php. I would like to use array_Rand than using shuffle. Can anyone please help?

<?php 

$Questions = array(
    1 => array(
        'Question' => '1. CSS stands for',
        'Answers' => array(
            'A' => 'Computer Styled Sections',
            'B' => 'Cascading Style Sheets',
            'C' => 'Crazy Solid Shapes'
        ),
        'CorrectAnswer' => 'B'
    ),
    2 => array(
        'Question' => '2. What is the Capital of the Philippines',
        'Answers' => array(
            'A' => 'Cebu City',
            'B' => 'Davao City',
            'C' => 'Manila City'
        ),
        'CorrectAnswer' => 'C'
    )
);

if (isset($_POST['answers'])){
    $Answers = $_POST['answers']; // Get submitted answers.

    // Now this is fun, automated question checking! ;)

    foreach ($Questions as $QuestionNo => $Value){
        // Echo the question
        echo $Value['Question'].'<br />';

        if ($Answers[$QuestionNo] != $Value['CorrectAnswer']){
             echo 'You answered: <span style="color: red;">'.$Value['Answers'][$Answers[$QuestionNo]].'</span><br>'; // Replace style with a class
             echo 'Correct answer: <span style="color: green;">'.$Value['Answers'][$Value['CorrectAnswer']].'</span>';
        } else {
            echo 'Correct answer: <span style="color: green;">'.$Value['Answers'][$Answers[$QuestionNo]].'</span><br>'; // Replace style with a class
            echo 'You are correct: <span style="color: green;">'.$Value['Answers'][$Answers[$QuestionNo]].'</span>'; $counter++;

        }

        echo '<br /><hr>'; 
                                if ($counter=="") 
                                { 
                                $counter='0';
                                $results = "Your score: $counter/2"; 
                                }
                                else 
                                { 
                                $results = "Your score: $counter/2"; 
                                }
            }                           echo $results;
} else {  
?>
    <form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post" id="quiz">
    <?php 
    $totalQuestionCount = count($Questions);
    $randQuestions = rand(0, ($totalQuestionCount - 1));
    shuffle($Questions);
    foreach ($Questions as $QuestionNo => $Value) {

        ?>

        <h3><?php echo $Value['Question']; ?></h3>
        <?php 
            foreach ($Value['Answers'] as $Letter => $Answer){ 
            $Label = 'question-'.$QuestionNo.'-answers-'.$Letter;
        ?>
        <div>
            <input type="radio" name="answers[<?php echo $QuestionNo; ?>]" id="<?php echo $Label; ?>" value="<?php echo $Letter; ?>" />
            <label for="<?php echo $Label; ?>"><?php echo $Letter; ?>) <?php echo $Answer; ?> </label>
        </div>
        <?php } 

        if ($QuestionNo == $randQuestions) {
            break;
        }
        ?>
    <?php } ?>
    <input type="submit" value="Submit Quiz" />
    </form>
<?php 
}
?>

The code works fine but I would like to show maybe like 10 out of 20 questions instead hence using shuffle() isn't really what i wanted. Would appreciate any help I could get, thank you in advance!




dimanche 26 janvier 2020

How to use Array_Rand to randomised the question from txt file in PHP?

I have existing code to take in Question and Answers from a text file(can't use DB in this assignment) to display. But i need to display in random for example 10 out of 30 questions from the question.txt file.

Current code

<html>
<head>
</head>

<body>


<?php


// Read answerkey.txt file for the answers to each of the questions.
function readAnswerKey($filename) {
    $answerKey = array();

    // If the answer key exists and is readable, read it into an array.
    if (file_exists($filename) && is_readable($filename)) {
        $answerKey = file($filename);
    }

    return $answerKey;
}


// Read the questions file and return an array of arrays (questions and choices)
// Each element of $displayQuestions is an array where first element is the question 
// and second element is the choices.

function readQuestions($filename) {
    $displayQuestions = array();
    $num = 3;  //i added


    if (file_exists($filename) && is_readable($filename)) {
        $questions = file($filename);

        // Loop through each line and explode it into question and choices
        foreach ($questions as $key => $value) {
            $displayQuestions[] = explode(":",$value);



        }   

    }
    else { echo "Error finding or reading questions file."; }
    return  $displayQuestions;
}


// Take our array of exploded questions and choices, show the question and loop through the choices.
function displayTheQuestions($questions) {
    if (count($questions) > 0) {
        foreach ($questions as $key => $value) {
            //$keys = array_rand( $questions, $num ); I Tried using array rand here but it doesnt work.
            echo "<b>$value[0]</b><br/><br/>";

            // Break the choices appart into a choice array
            $choices = explode(",",$value[1]);

            // For each choice, create a radio button as part of that questions radio button group
            // Each radio will be the same group name (in this case the question number) and have
            // a value that is the first letter of the choice.

            foreach($choices as $value) {
                $letter = substr(trim($value),0,1);
                echo "<input type=\"radio\" name=\"$key\" value=\"$letter\">$value<br/>";
            }

            echo "<br/>";
        }
    }
    else { echo "No questions to display."; }
}


// Translates a precentage grade into a letter grade based on our customized scale.
function translateToGrade($percentage) {

    if ($percentage >= 90.0) { return "A"; }
    else if ($percentage >= 80.0) { return "B"; }
    else if ($percentage >= 70.0) { return "C"; }
    else if ($percentage >= 60.0) { return "D"; }
    else { return "F"; }
}

?>

<h2>Welcome to the Dream In Code Example Online Quiz!</h2>
<h4>Please complete the following questions as accurately as possible.</h4>

<form method="POST" action="<?php echo $_SERVER["PHP_SELF"]; ?>">

<?php
    // Load the questions from the questions file
    $loadedQuestions = readQuestions("questions.txt");

    // Display the questions
    displayTheQuestions($loadedQuestions);
?>

<input type="submit" name="submitquiz" value="Submit Quiz"/>


<?php

// This grades the quiz once they have clicked the submit button
if (isset($_POST['submitquiz'])) {

    // Read in the answers from the answer key and get the count of all answers.
    $answerKey = readAnswerKey("answerkey.txt");
    $answerCount = count($answerKey);
    $correctCount = 0;


    // For each answer in the answer key, see if the user has a matching question submitted
    foreach ($answerKey as $key => $keyanswer) {
        if (isset($_POST[$key])) {
            // If the answerkey and the user submitted answer are the same, increment the 
            // correct answer counter for the user
            if (strtoupper(rtrim($keyanswer)) == strtoupper($_POST[$key])) {
                $correctCount++;
            }
        }
    }


    // Now we know the total number of questions and the number they got right. So lets spit out the totals.
    echo "<br/><br/>Total Questions: $answerCount<br/>";
    echo "Number Correct: $correctCount<br/><br/>";

    if ($answerCount > 0) {

        // If we had answers in the answer key, translate their score to percentage
        // then pass that percentage to our translateGrade function to return a letter grade.
        $percentage = round((($correctCount / $answerCount) * 100),1);
        echo "Total Score: $percentage% (Grade: " . translateToGrade($percentage) . ")<br/>";
    }
    else {
        // If something went wrong or they failed to answer any questions, we have a score of 0 and an "F"
        echo "Total Score: 0 (Grade: F)";
    }
}

?>

</form>

</body>
</html>

Have tried looking at w3 example but i dont know how to manipulate it due to i am new to coding. Appreciate any help i can get to randomised the question and still able to get the answer.txt.

Format of txt file. Question.txt 1. What is your name? : A) George, B) Tom, C) Martyr, D) None of the Above 2. How old are you? : A) 15, B) 21, C) 30, D) None of the Above

Answer.txt A D




How to generate a bunch of lists of random numbers which have no repeats but in a certain range with Python?

I actually need to generate a bunch of lists of random numbers in the range of 1 to 5. I know how to generate a single list of random numbers in the range of 1 to 5 with shuffle module, but what if I want a bunch of such stuffs? I have no idea to use loop ,is there anyone can help? Many appreciates~




How to randomize variables from arrays in a rock, paper, scissors game in C#? [duplicate]

I am making a rock, paper, scissors game. I am using an array to the three variables and am trying to randomize the outcome and compare the random string to the user input. I have tried many methods with the random function and the one in the code makes the most sense to me, but it doesn't work. I am trying to make this code as concise as possible. I have seen other ways of creating this game, but they seem inefficient to me. I believe sticking with an array will allow my code to shorten and run faster. Please help me out and guide me on the right direction, thank you.

 using System;

namespace ConsoleApp1
{


    class MyArray
    {




        static void Main(string[] args)
        {

            var array = new string[] { "rock", "paper", "scissors" };
            var array = new Random();


            Console.WriteLine("Rock, paper, or scissors?");
            string rps = Console.ReadLine();

            switch (rps)
            {
                case "Rock":
                //??
                    break;
                case "Paper":
                //??
                    break;
                case "Scissors":
                //??
                    break;
            }

        }
        }
}



Generating random String out of a few user input options using java math.random?

Using Java, how do I select a random option (out of two user input items) using math.random where I assign different values to represent the different input items?

I need to create user input for 2 items, then use math.random to randomly choose one of the items.




How to implement a spell checker in random number generator in a Bash script

Just finished scripting a number generator game that requires a user to guess a number between 1 and 100, I was curious if there is a way to make the script only accept numbers in between the 1-100 number range and reject any letter characters? I tried using

typeset -i

But i'm not sure if I am fully utilizing it or missing something, here is the rest of the code

#!/bin/bash
num=$((RANDOM%100))
typeset -i attempts=0
until [[ $guess == $num ]]
do
    echo -n "Enter your guessing number: "
    read -r guess
    if (( guess < num ));
    then echo "Guess Higher..."
    elif (( guess > num ));
    then echo "Guess Lower..."
    fi
(( attempts++ )) 
done
printf "Congradulations! it took $attempts guesses!\n"



How can I pick a random variable, and then pick a random variable from the variable's list?

I have two buttons. One for a random movie flavor, ex. ['love', 'war', 'true']. I have this working. The problem, the second button is supposed to pick a random movie from the movie flavor that was picked. Ex. If "Love" is picked, the a new random would come from the Love List ['Noel', 'Titanic', 'Pearl Harbor']. Appreciate any help, thank you all ... ^ _ ^ ...




I want to write a public instance method called runExperiments() which takes no argument and returns no value

The method should attempt to decrement powerLevel by a random number between 1 and 3 inclusive for each experiment up to numberOfExperiments. You should make use of the supplied helper method randomInteger() for this.

Can someone please help me with my code. below is where I am stuck. I am not sure how to get random number by using the info abpve. Here is the complete code. Many thanks

 public void runExperiments()

and here is the full code:

public class SpaceRocket extends FlyingObject implements Launchable
{
 private int maxPowerLevel;    
 private int numberOfExperiments;
 private int powerLevel;

 public int getMaxPowerLevel()
{
 return this.maxPowerLevel;
}

 public int getNumberOfExperiments()
{
  return this.numberOfExperiments;
}
  public int getPowerLevel()
{
  return this.powerLevel;
 }
 public SpaceRocket(String aName, int aNumberOfExperiments)
{
 this.name = aName;  
 this.numberOfExperiments = aNumberOfExperiments;
 this.powerLevel = 0;
 this.maxPowerLevel = 15;
 }

public boolean decrementPower(int powerReduction)
  {
if (powerReduction > this.getPowerLevel()){
 this.powerLevel = 0;  
 return false;
 } 
 else
 {
 this.powerLevel = powerReduction;
return true;
   }
  }

This is what I have done so far:

    public void runExperiments()
    {
     this.powerLevel -= randomInteger(1,3);

     }



samedi 25 janvier 2020

Why is random.choice giving me answers from other lists? [closed]

I want to create a generator for me and my cousin to play a game with random equipment in the game. However when i would use the while loop and the if's and elif's and the random.choice it would give me random things all the time. I would get guns when i ask for armor instead.

For example if i had:

names_invited = ["Kreg, George"]

names_at_party = ["Blue", "Connor"]

names_not_at_party = ["Dixon","Donnor"]

names_not_invited = ["Sindy, Grinch"]

name__from_bothlists = [names_invited, names_not_invited]

print(random.choice(names_invited))

x = 1

while x == 1:

  ask = input("What name?: ")
  if ask == "notinvited":
    **name_selector = random.selector(name_bothlists)**
    print(random.choice(names_from_bothlists))
  elif ask == "atparty":
    print(random.choice(names_at_party))

Then I would get:

What name?: "atparty"

It gives me:

Grinch (which is from the not_invited list)

My problem is i have different lists and its getting a random one from the wrong list. Ive figured out where the problem is.... its the name_selector == random.choice. if i removed that it was fine because i had other elifs and if statements however, when i do remove that i still would get the list and not the specific random item. in this case.

['Sindy', 'Grinch']

Though it all works. i just want to be able to select that specific one... without the issue of trying to use another list and getting one from the both list group.

Simple breakdown: Im trying to have a list of lists that select a random item. However when i have the "selector = random.choice()" it uses only that list of lists. So when i have my armor list in my project, i ask for a random choice from there and get an item from my guns list.




Reverse random in java (seed finder) [duplicate]

For a project I'm working on I need to find the seed of a random number with the given information: The last integer output from the seed how many times random.next has been called before (with the implementation java.util.random)

for example, given the integer -1355028732 being the 4th call, the seed would be 1273. I've been looking online for a solution but can't find one, Is this even possible?




NUMPY: What does np.empty(()) do in 2D arrays?

What does np.empty(()) actually do?

For instance, if I want to make an empty array of 5 rows and 5 cols, I would use np.empty((5,5)). This gives a random output like:

[[0.57061489 0.57883359 0.5746548  0.57756612 0.57587218]
 [0.62539185 0.62139618 0.62313292 0.62097162 0.62221129]
 [0.70896235 0.57620393 0.73345734 0.53891594 0.75331689]
 [0.72820808 0.56994986 0.78769608 0.47609684 0.8334235 ]
 [0.62921645 0.70930812 0.6068869  0.74827839 0.55498477]]

1. Why does it give a random output between 0-1 instead of generating values from the memory -like 7.6662e-301, 5.3767e-301..... etc?

If I run the code np.empty((5,5)) again in a new file, I get the same output as above. Why is that?




How to draw a canvas bitmap image at one of two locations randomly?

How to draw a bitmap at either one of two random positions? I wanna draw a bitmap image at either

  1. at a point which is in center from one side of screen and from center of the screen
  2. or at center from other side

like as show by the dots below

 ______________________
|     .     |     .    |             
|           |          |
|           |          |
|           |          |
|           |          |
|           |          |
|           |          |
|           |          |
|           |          |
|Typical android screen|
|           |          |
________________________

Here's how tried to attain it but failed

//package and import
public class items extends View {
   //here declared to some variables
    private int RandomSing;
    Point center;
    public items(int color, Context c) {
        super(c);

        // create a bitmap from the supplied image (the image is the icon that is part of the app)
      items= Bitmap.createScaledBitmap(BitmapFactory.decodeResource(c.getResources(),
                R.drawable.rocket),dst,dst, false);


    }
    public void setBounds(int lx, int ly, int ux, int uy) {
        lowerX = lx;
        lowerY = ly;
        upperX = ux;
        upperY = uy;
        x = y = 0;
        center=new Point(0,0);
        RandomSing=0;
    }
    public boolean move() {
    // use to move the bitmap in vertical direction downwards 
        y += stepY;

        if(stepY<8){stepY+=0.0025;}

        if (y + dst > upperY) {
            x = y = 0 ;
            return true;
        }
        else
            return true;
    }

    public void reset() {
        x=0;
        RandomSing +=7;
        y=0;
    }

    public void draw(Canvas canvas)
    {
        super.draw(canvas);
        X=getWidth();
        Y=getHeight();
        center=new Point((int)(X/4),0 );
        if(RandomSing%2!=0) x = (dst +center.x );
        else x = (dst+center.x+(X/2));
        canvas.drawBitmap(items,x,y, null);
    }
}

actually I will use it in another class to use it as alien ships coming to attack but it only come at on the first dot..

Please give me as many details as you can




Random word from a string [duplicate]

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

        String color[]={"White", "Yellow", "Blue", "Red", "Green"};
        String pastTenseVerb[]={"accepted", "added", "admired", "admitted", "advised"};
        String adjective[]={"aboard", "boorish", "cooing", "enchanted", "public"};
        String noun[]={"proposal", "uncle", "ladder", "pie", "county"};

        System.out.print("The " + color + " dragon " + pastTenseVerb + " at the " + adjective);
        System.out.println(" knight, who rode in a sturdy, giant " + noun + ".");
    }
}

Hello.I have the code like above and I wonder,is there a way to print a random word from every string.If yes can you give me a solution?




How can I get a seed for srand() that takes the nanoseconds instead of seconds?

im coding a password generator, but i have to use a delay if i want the output to be diferent, i have the code (a bit messy tho).

//Variables
int menu = 0, prec = 0, digit = 0;
char password;

//Menú
cout << "##############################" << endl;
cout << "#  Generador de Contraseñas  #" << endl;
cout << "#----------------------------#" << endl;
cout << "#            MENÚ            #" << endl;
cout << "#   (1) Generador   -        #" << endl;
cout << "#   (2) Historial   -        #" << endl;
cout << "#   (3) Contraseñas -        #" << endl;
cout << "#       guardadas   -        #" << endl;
cout << "#                            #" << endl;
cout << "##############################" << endl;
cin >> menu;

while (menu == 1)
{
    cout << "¡Bienvenido al generador de contraseñas! Introduce la longitud de la contraseña (entre 8 y 32)" << endl;
    cin >> prec;
    if (prec <= 8 || prec <= 32)
    {
        cout << "Estamos calculando tu contraseña" << endl;
        while (digit++ < prec)
        {
            srand(time(NULL));
            password = (rand() % 74) + 48;
            cout << password;
            Sleep(1000);

        }
        cout << " es la contraseña generada."<< endl;
        digit = 0;
    }
    else
    {
        cout << "Has puesto un numero que no esta entre 8 y 32, introduce otro" << endl;
        cin >> prec;
    }
}

while (menu == 2)
{

}

while (menu == 3)
{

}
system("pause");

}

Im a bit new in c++, so if there is any way to do it better, im open to suggestions. im using windows by the way




vendredi 24 janvier 2020

How to rotate tensor image randomly

I want to rotate my images in parallel, using 'map', in the preprocessing stage.

The problem is that every image is rotated for the same direction (after one random number generated). But I want that each image will have different degree of rotation.

This is my code:

import tensorflow_addons as tfa
import math
import random
def rotate_tensor(image, label):
    degree = random.random()*360
    image = tfa.image.rotate(image, degree * math.pi / 180, interpolation='BILINEAR')
    return image, label

rotated_test_set = rps_test_raw.map(rotate_tensor).batch(batch_size).prefetch(1)

I tried to change the seed every call for the function:

import tensorflow_addons as tfa
import math
import random
seed_num = 0
def rotate_tensor(image, label):
    seed_num += 1
    random.seed(seed_num)
    degree = random.random()*360
    image = tfa.image.rotate(image, degree * math.pi / 180, interpolation='BILINEAR')
    return image, label

rotated_test_set = rps_test_raw.map(rotate_tensor).batch(batch_size).prefetch(1)

But I get:

UnboundLocalError: local variable 'seed_num' referenced before assignment

I use tf2, but I don't think it matter much (beside the code to rotate the image).




How to return random strings of random lenght in Python

I am working on a Python Function that has to generate random strings of random lenght. The function has 3 parameters:

a=The minimum lenght that the generated string can have

b=The maximum lenght that the generated string can have

n=The number of strings that the program has to create

Here some examples:

random(2,6,3) --> 'asdf','rtgyh','as'

random(1,5,2) --> 'd', 'olkp'

random(2,9,4) --> 'ed','tgyhujik','edsrfb','esd'

This are the steps that i have to follow:

**generate a random number C between a and b

**generate a random string of lenght C

**add c to the list

(please try to be as basic as possible)

this is what i tired:

import random,string
def casualis(w,k,n):
    l=[]
    l2=[]
    s=''
    a='abcdefghijklmnopqrstuvwxyz'
    while len(l)<(n+1):
        for i in range (w,k+1):
            l.append(random.randint(w,k))
            for j in range(l[0]):
                x=a[random.randint(1,25)]
                s+=x
    return l2



c# Which is the better way to give random number to function

Which is better and is there a difference in the random results ?

 void Func1(Random rand)
{
var num=rand.Next();
}

 void Func2(ref Random rand)
{
var num=rand.Next();
}