vendredi 30 novembre 2018

Faster alternatives to using numpy.random.choice in Python?

My goal is to generate a large 2D array in Python where each number is either a 0 or 1. To do this, I created a nested for-loop as shown below:

    for count in range(0,300):
      block = numpy.zeros((8,300000))

      for a in range(0,8):
        for b in range(0,300000):
          block[a][b] = numpy.random.choice(2,1, p=[0.9,0.1])

The block has a 90% chance of picking a "0" and a 10% of picking a "1". But it takes over 1 minute for the outer for loop to process once. Is there a more efficient way to pick random numbers for a large number of arrays while stilling being able to use the "P" values? (This is my first post so sorry if the formatting is broken)




How to output array of numbers by setInterval Math.floor Math.random

I have multiple html elements <h2> and </b> with the classname: randomgen.

function generateRandomNumber outputs one random number between 1 and 100 to each element:

function generateRandomNumber(min_value, max_value) {

    var random_number = Math.random() * (100 - 1) + 1;
    return Math.floor(random_number);
}

document.getElementsByClassName("randomgen")[0].innerHTML = generateRandomNumber();

Would it be posible to output multiple generateRandomNumber(); in an array, instead of identifying each [x] for the class randomgen.

setInterval(function () {

    document.getElementsByClassName("randomgen")[0].innerHTML = generateRandomNumber();
    document.getElementsByClassName("randomgen")[1].innerHTML = generateRandomNumber();
    document.getElementsByClassName("randomgen")[2].innerHTML = generateRandomNumber();
    document.getElementsByClassName("randomgen")[3].innerHTML = generateRandomNumber();
    document.getElementsByClassName("randomgen")[4].innerHTML = generateRandomNumber();
    document.getElementsByClassName("randomgen")[5].innerHTML = generateRandomNumber();
    document.getElementsByClassName("randomgen")[6].innerHTML = generateRandomNumber();
    document.getElementsByClassName("randomgen")[7].innerHTML = generateRandomNumber();
    document.getElementsByClassName("randomgen")[8].innerHTML = generateRandomNumber();
    document.getElementsByClassName("randomgen")[9].innerHTML = generateRandomNumber();
    document.getElementsByClassName("randomgen")[10].innerHTML = generateRandomNumber();
    document.getElementsByClassName("randomgen")[11].innerHTML = generateRandomNumber();
    document.getElementsByClassName("randomgen")[12].innerHTML = generateRandomNumber();
    document.getElementsByClassName("randomgen")[13].innerHTML = generateRandomNumber();
    document.getElementsByClassName("randomgen")[14].innerHTML = generateRandomNumber();
    document.getElementsByClassName("randomgen")[15].innerHTML = generateRandomNumber();
    document.getElementsByClassName("randomgen")[16].innerHTML = generateRandomNumber();
    document.getElementsByClassName("randomgen")[17].innerHTML = generateRandomNumber();
    document.getElementsByClassName("randomgen")[18].innerHTML = generateRandomNumber();
    document.getElementsByClassName("randomgen")[19].innerHTML = generateRandomNumber();
    document.getElementsByClassName("randomgen")[20].innerHTML = generateRandomNumber();
    document.getElementsByClassName("randomgen")[21].innerHTML = generateRandomNumber();
    document.getElementsByClassName("randomgen")[22].innerHTML = generateRandomNumber();
    document.getElementsByClassName("randomgen")[23].innerHTML = generateRandomNumber();

}, 8000);




Change image randomly when hover

i want to change an image randomly when hovering. The Hover effect is working but when the mouse moves out the image does not change back. Any ideas?

var arr = ["020", "053", "306", "035", "930"];

function getRandomImage() {
  var index = Math.floor(Math.random() * arr.length);

  return arr[index];

}

$(function(){
$(".size-woocommerce_thumbnail").hover(function(){
    var image = getRandomImage();
    $(this).attr("srcset", function(index, attr){
        return attr.replace("070", image);
    });
    $(this).attr("src", function(index, attr){
        return attr.replace("070", image);
    });
}, function(){
    $(this).attr("srcset", function(index, attr){
        return attr.replace(image, "070");
    });
    $(this).attr("src", function(index, attr){
        return attr.replace(image, "070");
    });
});
});




r - generate multiple files from randomizing a data frame

I need to generate and save multiple files from the randomization of a data frame. The original data frames are daily weather data for several years. I need to generate files that are random reorganizations of the years but keeping the year sequence.

I have developed a simple code for randomizing years, but I am having trouble to repeat randomization and save each output randomized data frame as a separate file.

This is what I have thus far:

# Create example data frame
df <- data.frame(x=c(1,1,1,2,2,2,3,3,3,4,4,4,5,5,5,6,6,6,7,7,8,8))
df$y <- c(4,8,9,1,1,5,8,8,3,2,0,9,4,4,7,3,5,5,2,4,6,6)
df$z <- c("A","A","A","B","B","B","C","C","C","D","D","D","F","F","F","G","G","G","H","H","I","I")

set.seed(30)

# Split data frame based on info in one column (i.e. df$x) and store in a list 
dt_list <- split(df, f = df$x)

# RANDOMIZE data list -- Create a new index and change the order of dt_list
# SAVE the result to "random list" (i.e. 'rd_list')

rd_list <- dt_list[sample(1:length(dt_list), length(dt_list))]

# Put back together data in the order established in 'rd_list' 
rd_data <- do.call(rbind, rd_list)

This randomizes the data frame just as I need, but I don't know how to "save & repeat" so I get multiple files, let's say about 20, named as the original and a sequential numeration (e.g. df_1, df_2 ...).

Also, being random samples, it's possible to get repetitions. Is there any way to automatically discard repeated files?

Thanks!




How to generate random numbers with each random number having a difference of atleast x with all other elements?

I know this goes against the definition of random numbers, but still I require this for my project. For instance, I want to generate an array with 5 random elements in the range[0, 200].

Now, I want each of the elements to have a difference of atleast 15 between them. So the random array should look something like: [15, 45, 99, 132, 199]

I can generate random numbers using numpy: np.random.uniform(low=0, high=200, size=5)

Thanks in advance.

However, I am not able to keep a consistent difference of atleast 15.




Cypress how can I use the number of elements on a page in a function

I’m new to cypress and am trying to learn it by converting some of our current behat tests to cypress, one of our scenarios checks article links on multiple ‘list’ pages of a website with a step definition of ‘And I click random article.

this step definition,

  • gets the number of article links on the page
  • uses this as the upper end of a range for a random number
  • this random number is then used to target the corresponding article link

using cypress with the cucumber plugin, I have this semi-working in with

Then(/^I click on a random article$/, () => {

let num = Math.floor(Math.random() * 10)

cy.get(‘.article_link’)
    .eq(num).click()
})

The issue is that the number of the articles on the page can vary but I haven’t found a way to pass this varying number of the articles to the Math function and am instead using a ‘semi’ safe upper limit of 10.




Avoiding duplicate values using random module

Below is a "Brute Force" word guessing...thing. I'ts to prove to my sibling how long it takes to find a password even knowing the number of characters using brute force. After letting this run for a couple hours with no success I think he gets the point. Now I want to put some logic behind it and for the life of me I can't figure it out. I've found things similar to what I want online but I don't know how to adapt it to my code.

import string
import random

def make_random():
   return''.join([random.choice(string.ascii_uppercase) for n in xrange(3)])

while True:
   random2=make_random()
   if random2 != "AAA":
      print(random2)
   if random2 == "AAA":
      print("AAA")
      print("Found")
      break

I think I need to have a variable to keep track of all the choices that have been guessed and compare that to the new string and set them so they can't equal but I honestly don't know.

Any help is good help.




How to Return a Random Number in an HTTP Call in Firebase Cloud Functions?

My Code is this but it doesnt work;

const functions = require('firebase-functions');

exports.randomNumber = functions.https.onRequest((request, response) => {

return Math.floor(Math.random() * 20)

});




weight allocation matrix using python

I want to generate about 1000 random weight allocations for 4 Equities. ex: [0.2,0.5,0.1,0.2] Conditions: 1. Sum of the weights should be equal to 1 2. Each weight should have a precision factor of 1 (0.2, 0.3, 0.4 etc)

Your replies are most required and appreciated.

Thanks Amit




Weird Output When Filling Large Array with Random Numbers in C

I'm currently trying to use threads to get the max and min of a large array (only have max right now). I'm have an issue with my output though. When I run my program, I get a HUGE number, even after putting a range for the random number. I'm getting numbers like 2147483644 and 2147483606. I would like it to be a range from 0/1 to 1000, but I just don't seem to be getting the right output. Any ideas?

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

// Size of array 
#define size 100000000 

// Max number of thread 
#define Th_max 4 

// Array 
int a[size];

// Array to store max of threads 
int max_num[Th_max] = { 0 }; 
int thread_no = 0; 

// Function to find maximum 
void* maximum(void* arg) 
{ 

    int i, num = thread_no++; 
    int maxs = 0; 

    for (i = num * (size / 4); i < (num + 1) * (size / 4); i++) { 
        if (a[i] > maxs) 
            maxs = a[i]; 
    } 

    max_num[num] = maxs; 
} 

void fillArray()
{
    for (int i = 0; i < size; i++)
    {
        a[i] = rand() % 1000 + 1;
    }

}

// Driver code 
int main() 
{ 
    int maxs = 0; 
    int i; 
    pthread_t threads[Th_max];


    fillArray();

    for(int i = 0; i < 100000000; i++)
    {
    a[i] = rand();
    }

    // creating 4 threads 
    for (i = 0; i < Th_max; i++) 
        pthread_create(&threads[i], NULL, 
                       maximum, (void*)NULL); 

    // joining 4 threads i.e. waiting for 
    // all 4 threads to complete 
    for (i = 0; i < Th_max; i++) 
        pthread_join(threads[i], NULL); 

    // Finding max element in an array 
    // by individual threads 
    for (i = 0; i < Th_max; i++) { 
        if (max_num[i] > maxs) 
            maxs = max_num[i]; 
    } 

    printf("Maximun Element is : %d", maxs); 

    return 0; 
} 

Thank you.




How can I calculate min, max and average value in a while loop?

I have the following code:

<?php
echo "<p>Exercise 5:</p>";

echo "Numbers: ";

$random = 0;

while ($random < 10) {
    $rand = rand(2, 80);
    echo "$rand";

    $random = $random + 1;

    if ($random < 10) {
     echo ", ";
    };
}

echo "<br><br>Min value: <br>";
echo "Max value: <br>";
echo "Average value: <br>";

?>

How can I calculate the min, max and average value of the 10 numbers?

$min = min($rand) doesn't work...
$max = max($rand) doesn't work either...




Random Div Display on Reload

<div class='quote'>
</div>
<div class='layout_atest news'>
</div>
<div class='quote'>
</div>

Currently I have a mix of news items and some customer reviews whoch are in the 'quote' div. I need two quotes to be shown randomly, on each reload, out of the several 'quote' div. So far i have this function

$(function() {
    var random=Math.floor(Math.random() * $('.quote').length);
    $('.quote').hide().eq(random).show().css('display','inline-block');
});

But it displays just one quote div, any way that I can have two random div displayed on reload, without subsequent repetition.




How can I get randomly generated numbers between 0 to 99 with 0 and 99 included?

Use a random number function to randomly generate 10 integers between 0 and 99 with 0 and 99 included




jeudi 29 novembre 2018

Shouldn't random.gauss return values in between mean and the standard deviation?

I tried using the random.gauss function in Python to get a random value between a range. The gauss function takes mean, standard deviation as parameters. Shouldn't the return value be between [mean +- standard deviation]?

Below is the code snippet:

for y in [random.gauss(4,1) for _ in range(50)]:
    if y > 5 or y < 3: # shouldn't y be between  (3, 5) ?
        print(y)

Output of the code:

6.011096878888296
2.9192195126660403
5.020299287583643
2.9322959456674083
1.6704559841869528




How to fix while loop within function?

My code works, and asks to name the file, and how many numbers. But it just keeps asking for numbers, and if I put zero then it does what it is suppose too. any help at all is appreciated very much. I just don't know how to fix the code, and it is really bugging me.

import random
    def generateRandomNumber(myfile):
        try:
            fileToBeWrittenTo = open(myfile,"w")
            numberOfRandomNumbers = int(input("How many numbers" + \
                                          " should the random file hold?:" ))
        except Exception as potentialError:
            print("An error has occured:", potentialError )
        else:
            for randomNumberCount in range(1, numberOfRandomNumbers + 1 ):
                randomNumber = generateRandomNumber(myfile)
                fileToBeWrittenTo.write(str( randomNumber ) + '\n' )
            print( numberOfRandomNumbers, "numbers have been written" + \
                   " to the file ")
        finally:
            fileToBeWrittenTo.close()
            print("\nEnd of program")
        displayNumber(myfile)
        randomNumber = random.randint(1,500)
        return randomNumber
    def main():
        myfile = str(input("Enter file name here "))
        with open(myfile, 'w+') as f:
            generateRandomNumber(myfile)

        return f
        myfile.close





    def displayNumber(myfile):
        try:
            myfile = open(myfile,'r')
            total = 0
            NORN = 0
            Avg = 0
            line = myfile.readline()
            while line != "":
                randomNumber = int(line)
                total += randomNumber
                NORN += 1
                Avg = total / NORN
                print( randomNumber )
            line = myfile.readline()
        except IOError:
            print("Problem with file being opened")
        else:
            print("The average of the numbers is " + str(Avg))
            print("The total of all the numbers is " + str(total)+\
              "\nThere are " + str(NORN)+\
              " in the file")
            myfile.close()
        finally:
            print("End of program")

    main()




getrandbits doesn't return the exact length

I'm trying to get a key with a certain length.When i do test i don't get the length that i want for example (k=500 i get a key of length 301 or 302) with the both statements getrandbits or with randrange, my code :

def generate_prime(k,d):
temp=1
while not millerRabin(temp,d):
    temp=getrandbits(k)
    #temp= randrange(1 << k-1, 1 << k)
return temp

and when i try this i get 301 of length :

k=500
print(len(str(generate_prime(k,40))))




pulling ranom index array from a different class

Trying to make a mad lib that will pull a random Verb from an array in my other class, tried creating an object of other class and calling the getRandomVerb method inserting the array list, works normally for the main class and arrays in main but having trouble with other class. enter image description here enter image description here




How to fix TypeError?

So I have thoutghly researched how to do this, but even then I am coming accross problems. It is one error after another. For example

Traceback (most recent call last):
  File "C:/Users/Owner.OWNER-PC/AppData/Local/Programs/Python/Python37-32/lab 5 maybe.py", line 41, in <module>
    main()
  File "C:/Users/Owner.OWNER-PC/AppData/Local/Programs/Python/Python37-32/lab 5 maybe.py", line 8, in main
    rand_gen(myfile)
  File "C:/Users/Owner.OWNER-PC/AppData/Local/Programs/Python/Python37-32/lab 5 maybe.py", line 19, in rand_gen
    my_file.write(line +'\n')
TypeError: unsupported operand type(s) for +: 'int' and 'str'

I get this error with this code. And I have no clue how to fix a type error. And I have been at this for what seems hours, and every change I make seems to create more of a problem. I have read through the book, and it has offered nothing. I get some things, but it is just not working for me at all. I have scoured the forums relentlessly. In the main it needs to ask the user to name the file to write into, which works. also needs to pass the argruments when the other functions are called either to write into the file or read from it. The second function, writes a series of random numbers to a file between 1-500 and also needs to ask how many random numbers to do, which works.(meaning it lets the user ask for the number) after that it gives the error. lastly, the third function need to show the amount of numbers that were generated, the sum of the numbers, and the average of numbers! Thank you in advance.

import random
import math


def main():
    myfile = str(input("Enter file name here "))
    with open(myfile, 'w+') as f:
        rand_gen(myfile)

    return f
    myfile.close

    disp_stats()

def rand_gen(myfile):
    my_file = open(myfile, 'w')
    for count in range(int(input('How many random numbers should we use?'))):
        line = random.randint(1,500)
        my_file.write(line +'\n')
    my_file.close()

def disp_stats():
    myfile = open(f,"r")
    total = 0
    count = 0
    print('The numbers are: ')
    for line in myfile:
        number = int(line)
        total += number
        count += 1
        print(number)

    average = total / count
    data = np.loadtxt(f)
    print('The count is ',count,)
    print('The sum is',total,)
    print('The average is ',format(average, '.2f'))

    myfile.close
main()




Random Orthogonal matrices in MATLAB

I got a code to generate random orthogonal matrix in matlab.

function M=RandOrthMat(n, tol)
% M = RANDORTHMAT(n)
% generates a random n x n orthogonal real matrix.
%
% M = RANDORTHMAT(n,tol)
% explicitly specifies a thresh value that measures linear dependence
% of a newly formed column with the existing columns. Defaults to 1e-6.
%
% In this version the generated matrix distribution *is* uniform over the manifold
% O(n) w.r.t. the induced R^(n^2) Lebesgue measure, at a slight computational 
% overhead (randn + normalization, as opposed to rand ). 
% 
% (c) Ofek Shilon , 2006.


    if nargin==1
      tol=1e-6;
    end

    M = zeros(n); % prealloc

    % gram-schmidt on random column vectors

    vi = randn(n,1);  
    % the n-dimensional normal distribution has spherical symmetry, which implies
    % that after normalization the drawn vectors would be uniformly distributed on the
    % n-dimensional unit sphere.

    M(:,1) = vi ./ norm(vi);

    for i=2:n
      nrm = 0;
      while nrm<tol
        vi = randn(n,1);
        vi = vi -  M(:,1:i-1)  * ( M(:,1:i-1).' * vi )  ;
        nrm = norm(vi);
      end
      M(:,i) = vi ./ nrm;

    end %i

end  % RandOrthMat

But I am not sure how can I get say 1000 random orthogonal matrices from this code and utilize it in my code.

Below is a code of generating 1000 random matrices in MATLAB.

nmc = 1000 matrices = rand(3,3, nmc);

I need to do like this in the code of generating random orthogonal matrix.




Is there a difference in security between a random string encoded as base64 vs hex?

Just like the title says, is there a security difference in the randomness of a random string encoded as a base64 or hex string?




Generate random integer in range multiple of another integer in Java

I'm struggling to finish the utility method to generate a number in a range of 2 integers which is also a multiplier of another integer.

For example:

public static void main(String[] args) {
    getIntegerInRangeMultipleOf(100, 1000, 444);
} 

Should yield either 444 or 888. Nothing else.

I've came up with this solution:

public static int getIntegerInRangeMultipleOf(int minInclusive, int maxInclusive, int multiplier) {
    return Math.toIntExact(Math.round((Math.random() * (maxInclusive - minInclusive) + minInclusive) / multiplier) * multiplier);
}

But for the example above sometimes it yields 0 (zero) in addition to 444 and 888.

Please suggest how to fix the function.




Random mouse movements and drag times in Python

I would like to make a script that drags the mouse to a x, y in a random line every time with a random drag time everytime, when it arrives at x, y it needs to click a random location in a specified rectangle.

Ive tried reading about it but havent gotten anything to work, all help is appreciated!




Edit the content of a text block in a list C# (WPF Application)

So I have five text blocks I've added to a list, and each one is supposed to get its own random number between one and 6.

I know I can just do a new int for each text block (int randomNumberOne, randomNumberTwo, etc) but I'm trying to see if I can figure out how to make a list and a for each loop to work.

Is there some way to edit the content of a TextBox in a list as it goes through? If there is, I haven't found any way to do so.

Here's my code so far.

List<TextBlock> randomBoxList = new List<TextBlock>();

        public MainWindow()
        {
            InitializeComponent();
            randomBoxList.Add(randomBoxOne);
            randomBoxList.Add(randomBoxTwo);
            randomBoxList.Add(randomBoxThree);
            randomBoxList.Add(randomBoxFour);
            randomBoxList.Add(randomBoxFive);
        }

    Random randomGenerator = new Random();
    int randomNumber;

    private void randomButton_Click(object sender, RoutedEventArgs e)
    {
        foreach (TextBlock textBlock in randomBoxList)
        {
            randomNumber = randomGenerator.Next(1, 7);
            //Code to change randomBox content goes here. 
        }
    }




How do I randomly equalize unequal values?

Say I have multiple unequal values a, b, c, d, e. Is it possible to turn these unequal values into equal values just by using random number generation?

Example: a=100, b=140, c=200, d=2, e=1000. I want the algorithm to randomly target these sets such that the largest value is targeted most often and the smallest value is left alone for the most parts.

Areas where I've run into problems: if I just use non-unique random number generation, then value e will end up going under the other values. If I use unique number generation, then the ration between the values doesn't change even if their absolute values do. I've tried using sets where a certain range of numbers have to be hit a certain number of times before the value changes. I haven't tried using a mix of unique/non-unique random numbers yet.

I want the ratio between the values to gradually approach 1 as the algorithm runs.

Another way to think about the problem: say these values a, b, c, d, e, are all equal. If we randomly choose one, each is as likely to be chosen as any other. After we choose one, we add 1 to that value. Then we run this process again. This time, the value that was picked last time is 1-larger than any other value so it's more likely to be picked than any one other value. This creates a snowball effect where the value picked first is likely to keep getting picked and achieve runaway growth. I'm looking for the opposite of this algorithm where we start after these originally-equal values have diverged and we bring them back to the originally-equal state.

I think this process is impossible because of entropy and the inherent one-way nature of existence.




Uniform random bit from a mask

Suppose I have a 64 bit unsigned integer (u64) mask, with one or more bits set.

I want to select one of the set bits uniformly at random from m to give a new mask x such that x & mask has one bit set. Some pseudocode that does this might be:

def uniform_random_bit_from_mask(mask):
  assert mask > 0
  set_indices = get_set_indices(mask)
  random_index = uniform_random_choice(set_indices)
  new_mask = set_bit(random_index, 0)
  return new_mask

However I need to do this as fast as possible (code similar to the above in a low-level language is slowing a hot loop). Does anyone have a more efficient scheme?




Python random.shuffle does not give exact unique values to the data frame

I am making a dummy dataset of list of companies as user_id, the jobs posted by each company as job_id and c_id as candidate id. I have already achieved the first two steps and my dataset looks like below.

user_id job_id 0 HP HP2 1 Microsoft Microsoft4 2 Accenture Accenture2 3 HP HP0 4 Dell Dell4 5 FIS FIS1 6 HP HP0 7 Microsoft Microsoft4 8 Dell Dell2 9 Accenture Accenture0

Also they are shuffled. now i wish to add a random candidate id to this dataset in such a way that no c_id is repeated to a particular job_id.

My approach for this is as follows. joblist is a list of all job_ids.

for i in range(50):
    l = list(range(0,len(df[df['job_id'] == joblist[i]])))
    random.shuffle(l)
    df['c_id'][df['job_id'] == joblist[i]] = l

after which i tested it as

len(df['c_id'][df['job_id'] == joblist[0]])

output = 168

df['c_id'][df['job_id'] == joblist[0]].nunique()

output = 101

and the same is happening with all values. i have rechecked the uniqueness of l after each step and its 168 unique values. What am i doing wrong here?




Does compilation and interpretation have effect on random number generation?

(i am a beginner at this platform and at programming too. please ignore my immature mistakes if you notice any. Thank you)

this is the c code below for generating a random number :

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

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

and in python :

from random import randint
print(randint(0,100))

my question is why c is always generating the same random number after i run the program again and again while python is able to do it by giving out new random number everytime .Not asking about the algorithm for generating the number but why same number ? is it because python is interpreted while c is compiled ?




Creating a normally distributed sample where data adds to a number

I want to generate a sample of n data points (floating values), such that they are approximately normally distributed and their sum is very close to S. I am using python function random.normalvariate(sampleMean, standardDeviatnion) to generate the set, but I am not sure how to guarantee that the data points add up to S. How could I go about it?




mercredi 28 novembre 2018

undefined reference to some of my functions [duplicate]

This question already has an answer here:

forgive me for any shortcomings in my descriptionof my problem but its my first day here. so my program wont compile. it keeps kicking out "undefined reference to 'isOdd' and 'IsEven', also an ld returned 1 exit status. cant seem to figure out whats causing the error. its a random number generator trying to use bool to judge whether a set of random integers are both even or if one of them is odd.

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

bool isOdd (int num1, int num2);
bool isEven (int num1, int num2);
void valueForOdd (int num1, int num2);
void valueForBothEven (int num1, int num2);

int i;
int num1;
int num2;

int main(void)
{
  srand(time(NULL));
  for (i=1; i <= 10; ++i) {
    num1 = rand() % 10 + 1;
    num2 = rand() % 10 + 1;
    printf("The two random numbers are %u and %u\n", num1, num2);
  }

  bool valueForOdd = isOdd (num1, num2);

  if (valueForOdd) {
        printf("one of these numbers, %u and %u, isOdd.\n\n", num1, num2);
  }
  else {
        printf("\n");
  }

  bool isOdd (int num1, int num2)
  {
    if ((num1 % 2 != 0) || (num2 % 2 != 0)) {
        return true;
    }
    else {
        return false;
    }
  }

  bool valueForBothEven = isEven (num1, num2);

  if (valueForBothEven) {
        printf("Both of these numbers, %u and %u, are even.\n\n", num1, num2);
  }
  else {
        printf("\n");
  }

  bool isEven (int num1, int num2)
  {
    if ((num1 % 2 == 0) && (num2 % 2 == 0)) {
        return true;
    }
    else {
        return false;
    }
  }

}




boolean data type random integer

Im trying to create a random number generator and judging the random integers odd or even using a srand call and boolean but i cant figured out how to get it to distinguish properly between whats odd and whats even.

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

int i;
int num1;
int num2;

bool isOdd (int num1, int num2);

int main(void)
{
srand(time(NULL));


for (i=1; i <= 10; ++i) {
 num1 = rand() % 10 + 1;
 num2 = rand() % 10 + 1;
printf("The two random numbers are %u and %u\n", num1, num2);


bool valueIsOdd = isOdd(num1, num2);

if (valueIsOdd) {
    printf("one of these numbers, %u and %u, isOdd.\n\n", num1, num2);
}
else {
    printf("Both of these numbers, %u and %u, are even.\n\n", num1, num2);
    }
}
}

bool isOdd(int num1, int num2)
{
if (num1 % 2 != 0) {
    return true;
}
else {
    return false;
    }

}




Are there multiple random seeds and sequences

I want to make a game in micropython an implementation of python 3.4. I want my monsters to be controlled by a random number generator. I was considering passing the current grid reference as a seed and todays date so the monster would always appear today. Play the game tomorrow and there will be new monsters.

The problem is i need to use random.randint and random.randchoice for dice and other truely random events.

If i were doing this in c I'd use erand48 from <stdlib.h> and keep and maintain multiple seeds.

What are my solutions in python?

I probably need a chaotic function to control monsters. Years ago i were given one by a maths professor, but it was simple and due to floating point rounding it tended to 0.0




What is the general formula for calculating the probability of generating a duplicate random number?

I am generating random order tracking numbers that should be short, yet should not be duplicate.

For a tracking number consisting of 3 digits, we will generate a duplicate random number after 40 attempts on average.

If we bump it to 12 digits, it will take on average 1.3 million attempts to generate a duplicate random number.

What is a more general formula for calculating how many attempts on average it will take to generate a duplicate random number up to a predefined limit?

Empirically, I can figure it out using this code, but I am looking for a more general solution:

/**
 * Calculates the average iteration at which we will generate
 * a random integer that has been generated before.
 * This numbers is much smaller than expected due to birthday paradox.
 */

// Generate random numbers up to (exclusive) this number:
const RANGE = 1000000000000;

let foundCollisions = 0;
const foundAt = [];

while(true) {
    let i = 0;
    const exists = {}

    while(true) {
        i++;

        const random = Math.floor(Math.random() * RANGE);

        if (exists[random]) {
            // We found a duplicate number:
            break;
        } else {
            exists[random] = true;
        }
    }

    foundCollisions++;
    foundAt.push(i);

    // Calculate the average iteration at which we found a duplicate number:
    const averageFoundAt = foundAt.reduce((total, num) => total + num) / foundCollisions;
    console.log(`Found ${foundCollisions} collisions, average at ${Math.round(averageFoundAt)}th iteration.`);
}




Is this random integer function acceptable for generating passwords?

I've been goofing around with random numbers a lot recently and have usually just used Math.Random as I've had no need to use something more secure, however I figured it would be useful to learn stuff like this and I was wondering how secure / practical this function is and some improvements I could implement.

function random_number(max) {
    let buffer=new ArrayBuffer(8);
    let ints=new Int8Array(buffer);
    window.crypto.getRandomValues(ints);
    ints[7]=64-1;
    ints[6]|=0xf0;
    let float=new DataView(buffer).getFloat64(0,true)-1;
    return Math.floor(float*Math.floor(max+1));
}




Creating a large random number in Racket

I'm trying to generate a very large random number in Racket, something between 0 and 1e20.

(random) has the limitation set in the range of 1 and 4294967087.

I've created a hack-y function that tries to generate a random number, but only does so based on order-of-magnitude, not the actual number. Here's that function:

define (l-random [min 0] [max 10])
  (define length (random (number-length min) (number-length max)))
  (define string "")
  (for ([i length])
    (set! string (format "~a~a" string (random 0 10))))
  (string->number string))

And here's how I calculate order of magnitude:

(define (number-length number)
  (cond [(= 0 number) 1]
        [else (+ 1 (exact-floor (log (abs number) 10)))]))

Do you have any suggestions or solutions? Thanks!




New string every time a loop runs

Looking to prove a sibling wrong about how long it can take a computer to guess a specific string by using Brute Force even with the correct number of characters put in. I can get the code to run but I cannot figure out how to get it to print a new string every time it runs. I'm sure I'm over looking something simple. Below are a couple examples of the code I've tried.

import string
import random

random=''.join([random.choice(string.ascii_letters+string.digits) for n in xrange(5)])

while True:
   if random != "Steve":
      print(random)
   if random == "Steve":
      print("Found")

This will continually print the same string over and over. I've also tried this without the while statement just the if and it doesn't seem to work.

I know enough that once random picks those 5 randoms characters it won't change until something makes it change but like I said I'm not sure how to do that. I've tried moving random to different places but doesn't work I just get different error messages.

Can someone help me out.




C++ random yields different numbers for same Mersenne Twister seed when using float precision

I need to run reproducible Monte Carlo runs. That means I use a known seed that I store with my results, and use that seed if I need to run the same problem instance using the same random numbers. This is common practice.

While investigating the effects of numeric precision, I ran into the following issue: For the same Mersenne Twister seed, std::uniform_real_distribution<float>(-1, 1) returns different numbers than std::uniform_real_distribution<double>(-1, 1) and std::uniform_real_distribution<long double>(-1, 1), as the following example shows:

#include <iomanip>
#include <iostream>
#include <random>

template < typename T >
void numbers( int seed ) {
  std::mt19937                        gen( seed );
  std::uniform_real_distribution< T > dis( -1, 1 );
  auto p = std::numeric_limits< T >::max_digits10;
  std::cout << std::setprecision( p ) << std::scientific << std::setw( p + 7 )
            << dis( gen ) << "\n"
            << std::setw( p + 7 ) << dis( gen ) << "\n"
            << std::setw( p + 7 ) << dis( gen ) << "\n"
            << "**********\n";
}

int main() {
  int seed = 123;
  numbers< float >( seed );
  numbers< double >( seed );
  numbers< long double >( seed );
}

Result:

$ /usr/bin/clang++ -v
Apple LLVM version 10.0.0 (clang-1000.11.45.5)
Target: x86_64-apple-darwin18.2.0
Thread model: posix
InstalledDir: /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin

$ /usr/bin/clang++ bug.cpp -std=c++17
$ ./a.out 
 3.929383755e-01
 4.259105921e-01
-4.277213216e-01
**********
 4.25910643160561708e-01
-1.43058149942132062e-01
 3.81769702875451866e-01
**********
 4.259106431605616525145e-01
-1.430581499421320209545e-01
 3.817697028754518623166e-01
**********

As you can see, double and long double both start around at the same number (save precision differences) and continue yielding the same values. On the other hand, float starts off with a completely different number, and its second number is similar to the first number produced by double and long double.

Do you see the same behavior in your compiler? Is there a reason for this unexpected (to me) discrepancy?




Better pseudo random number generator

I am writing an application that requires a better quality pseudo random number generator (PRNG) than the default C# one. I have found that the ranlux generator in C++ is good enough, so I tried to find a simple implementation of the ranlux algorithm that I could reasonably expect to translate into C#. I found one, but the fact that it only generates 2^24 distinct values is a problem. I am looking for a quality PRNG (i.e., with good statistical properties) that produces at least 2^48 distinct values and that is either in C# or which is simple enough that I could reasonably expect to be able to translate it into C#.




Change value in boolean array. Choose place not value

I,m not sure this is possible. I,m building a program to choose a lotto row. I have a for loop to random pick seven numbers from 1 to 35. My plan is that i can make a boolean array and then take one of the random numbers to choose a place (not a value) in the boolean array and change it to True.

In this way i have the row number and i,m sure that the number is taken when the array place i true.

import java.util.Random; {


public static void main(String[] args) {
    int randomNr;
    boolean[] lottoRow = new boolean[35];

    Random randNr = new Random();

    for(int i=0; i<7; i++) {
        randomNr = randNr.nextInt(35)+1;

    }
}

How would i do this? Is it even a good way to approach this problem?




Random generator using stack data structure

class Stack:
     def __init__(self):
         self.container = []  

     def isEmpty(self):
         return self.size() == 0   

     def push(self, item):
         self.container.append(item)  

     def peek(self) :
         if self.size()>0 :
             return self.container[-1]
         else :
             return None

     def pop(self):
         return self.container.pop()

     def size(self):
         return len(self.container)

s = Stack()
s.isEmpty()
s.push("Cat")
s.push("Dog")
s.push("Horse")
s.push("Snake")
s.push("Lion")
s.push("Fish")
s.push("Bear")
s.push("Tiger")

These are my codes using stack. I am having problems trying to come up with a code that can randomly generate only 3 out of the 8 animals as the output using stack data structure only.

Output Example:

Dog
Snake
Tiger




shuffle random pair in array but excluding pair possibility

I wish to create a small script to generate pair of users.

Users are in array so I use shuffle to pair them randomly.

My problem is I want to avoid / exclude some pair of users in the final result.

So I have the first part to shuffle users :

<?php 

$user[] = "Miaa";
$user[] = "Xavier";
$user[] = "Antoine";
$user[] = "Marie-Ange";
$user[] = "Claire";
$user[] = "Orlando";
$user[] = "Camille";
$user[] = "Chloé";
$user[] = "Audrey";
$user[] = "*";

$users = count($user);
// Shuffle user
shuffle($user);// You get a shuffled array

// Pair the adjacent user
for ( $index = 0; $index < $users; $index +=2) {

    // Pair $user[$index ] with $user[$index +1]
    echo $user[$index ] . " <=> " . $user[$index+1] . "\n";
}

?>

Here it's a link with my code into a sandbox => http://sandbox.onlinephpfunctions.com/code/6ef04e99946849606544493e64e317206209c10c

I tried to include if statment but without success

$user[$index[0]] == "Miaa" && $user[$index[1]] == "Xavier"




mardi 27 novembre 2018

Discard method to generate uniform random points in sphere

I'm trying to use the discard method to randomly generate coordinates within a sphere in python (generate points in a cube and 'discard' those outside the sphere) but ideally I just want to replace the 'discarded' points with a point that DOES lie in the sphere.

N = 10000

position = numpy.random.uniform(-100, 100, (N,3))
for i in range(N):
    if numpy.linalg.norm(position[i]) > 100:
        position[i] = numpy.random.uniform(-100, 100)

fig = pyplot.figure()
ax = Axes3D(fig)
ax.scatter(position[:,0], position[:,1], position[:,2])
pyplot.show()

This is what I've tried, and it seems to almost work, but I get this weird line through the sphere and I can't figure out how to get rid of itplot of code




Why doesn't prolog give a correct value for variable?

I am writing a basic program in prolog but I don't get it to work. This is the code:

My prolog code.

borders(sweden,finland,586).
borders(norway,sweden,1619).

allborders(X,Y,L) :- borders(X,Y,L).
allborders(X,Y,L) :- borders(Y,X,L).
addborders(C,Lsum,Set) :- length(Set,0), write(C), write(' - '), write(Lsum), C == Lsum.
addborders(C,Lsum,[H|T]) :- Lsum2 is Lsum + H, addborders(C,Lsum2,T).
helpsetofpredicate(Country,L) :- allborders(Country,_,L).
circumference(C,Country) :- setof(L,helpsetofpredicate(Country,L),Set), addborders(C,0,Set).

(Obs: the borders are just a small sample for a gigantic file but are enough to describe the problem)

So what this program is supposed to do is to sum all the borders to a country and check if the given circumference (C) is the total of a countries circumference (Country). If I were to type

circumference(2205,sweden).

the program gives true, which is expected. But if I type

circumference(C,sweden).

the program gives false. I have put some writes within the code to see which values C and Lsum has and the output is _G962 - 2205. Why doesn't prolog assign a correct value to C instead of giving it a random value?




PHP How to Make Unique Text from array random result?

My script looks like this:

<?php 
$placeholders = 'City1 - City1 - City1 - City2 - City3 - City4 - City4';
$substitutes  = [
'City1' => ['Orlando','Dallas','Atlanta','Detroit','Houston'],
'City2' => ['Jakarta','Bandung','Surabaya','Medan','Makassar','Surabaya'],
'City3' => ['Atlanta','Tampa','Miami','Houston'],
'City4' => ['Mandalay','Caloocan','Hai Phong','Quezon City'],
];
$replacements = [];
foreach($substitutes as $key => $choices) {
    $random_key = array_rand($choices);
    $replacements[$key] = $choices[$random_key];
}
$spun = str_replace(
    array_keys($replacements),
    array_values($replacements),
    $placeholders
);
echo $spun;
?>

but the result that i get is the same...

Result: Orlando - Orlando - Orlando - Bandung - Miami - Caloocan - Caloocan

I want to make result like this:

Result: Orlando - Houston - Atlanta - Bandung - Miami - Caloocan - Mandalay




How do I create Random Number generator using Recursion

I've created code to generate a random number between 1 and 100 but my question is how would I create the same output using recursion in java

 import java.util.Random;

 public class Recursion{




 public static void main(String[] args) {

   Random r = new Random();
   int random  = r.nextInt(100) + 1;
   System.out.println("Random number between 1 and 100 is: " + random);

}
}




Random Generator - carrying over variables

Would anyone please be able to help? I am just starting out with some very basic android development. I am developing an initial app to help my daughter learn her times tables. Idea being (in its first version) randomly generate 2 numbers between 1 and 12. Then click on a calculate button which will give the answer. I have it so that it randomly generates the 2 numbers, however, when I click calculate, it does not calculate, simply shows 0. I believe it is something to do with the value of the variables (digit1 & digit2) not being seen by the next method (calculate). If I hard code 2 numbers into the calculate method, it works. I just cannot the random generated numbers to calculate. Any help would be most appreciated. MainActivity.java:

package uk.co.myrayner.sophiestimestables;

import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.TextView;

import java.util.Random;


public class MainActivity extends AppCompatActivity {

    int digit1;
    int digit2;
    int show_answer;

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

    public void randomise_digits(View view) {
        Random rand1 = new Random();
        int digit1 = rand1.nextInt(12) + 1;
        displaydigit1(digit1);
        Random rand2 = new Random();
        int digit2 = rand2.nextInt(12) + 1;
        displaydigit2(digit2);
    }

    public void calculate(View view) {
        show_answer = (digit1 * digit2);
        displayanswer(show_answer);
    }

    private void displaydigit1(int number) {
        TextView digit1TextView = (TextView) findViewById(R.id.digit1);
        digit1TextView.setText("" + number);
    }

    private void displaydigit2(int number) {
        TextView digit2TextView = (TextView) findViewById(R.id.digit2);
        digit2TextView.setText("" + number);
    }

    private void displayanswer(int number) {
        TextView answerTextView = (TextView) findViewById(R.id.show_answer);
        answerTextView.setText("" + number);

    }
}




Generating a Pseudo-random number between 0 an 1 GLSL ES

I am trying to create a pseudo random float between 0.0 (inclusive) and 1.0 (inclusive) in GLSL ES in order to process the mutations for a chromosome on the GPU rather than a CPU in a genetic algorithm. How would I go about this?




Random Numbers Generating without extending lib

Is there a way to generate numbers without using rand(std) lib? or any lib in general specified for numbers generating.




Seed to java.security.SecureRandom on Windows os

I am interested in java.util.Random and java.security.SecureRandom classes. I found that Random uses system clock to generate seed and SecureRandom uses /dev/random or /dev/urandom but these files are on Linux, while on Windows it uses some mistic CryptGenRandom. Even if that is super secure function, do we know from where does it take values? What is the basement to generate seed?




lundi 26 novembre 2018

How does Javascript’s Math.random() works behind the scenes? [on hold]

I've always wondered how on earth does Javascript picks a random number and how can it possibly be random? Don’t computers just take in some input, swirl it around with some math, and then return it?

I'm not asking how to generate a random number with Math.random(), my question is: What happens when you want to generate a ‘random’ number? How does that even work and what’s happening behind the scenes? I understand it's a big topic to discuss but any links will be appreciated!




rlnorm function in r-programming producing NA's

I am trying to generate a random values using log distribution. The reason for using log-distribution is keep the values positive.

   cv=0.2 # 20% cv for the values K used in the simulation 

calc_sd <- function(mean,cv){
  sd=mean*cv
  print(sd)
}
calc_sd((6.19*10^-3),(0.2))
mu<-6.19*10^-3
sd<- 0.001238
nsample=50000
kdist <- data.frame(id=1:nsample)
kdist$KE <- (rlnorm(nsample, meanlog=mu,sdlog=sd))

This is the warning message I keep getting

Warning messages: 1: In rlnorm(50000, mean = (6.19 * 10^-3), sd =sd) : NAs produced

My question is how do I adderss this issue. I ave tried using one of the previous suggestions which was mentioned here and it does not work.

https://msalganik.wordpress.com/2017/01/21/making-sense-of-the-rlnorm-function-in-r/

http://r.789695.n4.nabble.com/Is-my-understanding-of-rlnorm-correct-td853068.html

My second question is : is there a way to directly use CV instead of sd for the generating this ?

Thanks in advance.




Is it possible to create a two-player trivia game in Rust

So I am trying to complete a programming project using Rust. I have already written it in my native language Python. The program presents both players with 5 questions each. The question shows four possible answers and tally points for each player. The program also includes a Question class with accessors, mutators and an array that holds the 10question objects.

I am having trouble getting the random method working from the extern crate rand.

extern crate rand;

pub struct Game
{
    players        : Vec<String>,
    places         : [i32; 6],
    purses         : [i32; 6],
    in_penaltybox  : [bool; 6],
    current_player : i32,
    is_getting_out_of_penaltybox : bool,

    pop_questions     : Vec<String>,
    science_questions : Vec<String>,
    sports_questions  : Vec<String>,
    rock_questions    : Vec<String>,
}

impl Default for Game {
    fn default() -> Game {
        let mut game = Game {
            players        : vec![],
            places         : [0;6],
            purses         : [0;6],
            in_penaltybox  : [false;6],
            current_player : 0,
            is_getting_out_of_penaltybox : false,
            pop_questions     : Vec::new(),
            science_questions : Vec::new(),
            sports_questions  : Vec::new(),
            rock_questions    : Vec::new(),
        };
        for x in 0..50 {
            let pop_qu = "Pop Question ".to_string() + &x.to_string();
            game.pop_questions.push(pop_qu);
            let sci_qu = "Science Question ".to_string() + &x.to_string();
            game.science_questions.push(sci_qu);
            let spo_qu = "Sports Question ".to_string() + &x.to_string();
            game.sports_questions.push(spo_qu);
            let rock_qu = game.create_rock_question(x);
            game.rock_questions.push(rock_qu);
        }
        game
    }
}

impl Game {
    fn how_many_players(&self) -> usize {
        self.players.len()
    }

    fn is_playable(&self) -> bool {
        self.how_many_players() >= 2
    }

    fn did_player_win(&self) -> bool {
        !(self.purses[self.current_player as usize] == 6)
    }

    fn current_category(&self) -> &'static str {
        match self.places[self.current_player as usize] {
            0 | 4 | 8  => return "Pop",
            1 | 5 | 9  => return "Science",
            2 | 6 | 10 => return "Sports",
            _          => return "Rock"
        }
    }

    fn create_rock_question(&self,index: i32) -> String {
        "Rock Question ".to_string() + &index.to_string()
    }

    fn add(&mut self,player_name: String) -> bool {
        let l_player = player_name.clone();
        self.players.push(player_name);
        self.places[self.how_many_players()] = 0;
        self.purses[self.how_many_players()] = 0;
        self.in_penaltybox[self.how_many_players()] = false;
        println!("{} was added",l_player);
        println!("They are player number {}",self.players.len());
        true
    }

    fn wrong_answer(&mut self) -> bool {
        println!("Question was incorrectly answered");
        println!("{} was sent to the penalty box",self.players[self.current_player as usize]);
        self.in_penaltybox[self.current_player as usize] = true;
        self.current_player += 1;
        if self.current_player == self.players.len() as i32 {
            self.current_player = 0;
        }
        true
    }
}

impl Game {
    fn ask_question(&mut self) {
        match self.current_category() {
            "Pop" => {
                let top = self.pop_questions.pop();
                println!("{:?}",top.unwrap());

            },
            "Science" => {
                let top = self.science_questions.pop();
                println!("{:?}",top.unwrap());
            },
            "Sports" => {
                let top = self.sports_questions.pop();
                println!("{:?}",top.unwrap());
            },
            "Rock" => {
                let top = self.rock_questions.pop();
                println!("{:?}",top.unwrap());
            },
            _ => {
                println!("Unexpected case");
            }
        }
    }
}

impl Game {
    fn roll(&mut self,roll: i32) {
        println!("{} is current player",self.players[self.current_player as usize]);
        println!("They have rolled a {}",roll);
        if self.in_penaltybox[self.current_player as usize]  {
            if roll % 2 != 0  {
                self.is_getting_out_of_penaltybox = true;
                println!("{} is getting out of the penalty box",self.players[self.current_player as usize]);
                self.places[self.current_player as usize] += roll;
                if self.places[self.current_player as usize] > 11 {
                    self.places[self.current_player as usize] -= 12;
                }
                println!("{0} 's new location is {1}",self.players[self.current_player as usize],self.places[self.current_player as usize]);
                println!("The category is {}",self.current_category());
                self.ask_question();
            }
            else {
                println!("{} is not getting out of the penalty box",self.players[self.current_player as usize]);
                self.is_getting_out_of_penaltybox = false;
            }
        }
        else {
            self.places[self.current_player as usize] += roll;
            if self.places[self.current_player as usize] > 11 {
                self.places[self.current_player as usize] -= 12;
            }
            println!("{0} 's new location is {1}",self.players[self.current_player as usize],self.places[self.current_player as usize]);
            println!("The category is {}",self.current_category());
            self.ask_question();
        }
    }
}

impl Game {
    fn was_correctly_answered(&mut self) -> bool {
        if self.in_penaltybox[self.current_player as usize] {
            if self.is_getting_out_of_penaltybox {
                println!("Answer was correct!!!!");
                self.purses[self.current_player as usize] += 1;
                println!("{0} now has {1} Gold Coins.",self.players[self.current_player as usize],self.purses[self.current_player as usize]);
                let winner: bool = self.did_player_win();
                self.current_player += 1;
                if self.current_player == self.players.len() as i32 {
                    self.current_player = 0;
                }
                winner
            }
            else {
                self.current_player += 1;
                if self.current_player == self.players.len() as i32 {
                    self.current_player = 0;
                }
                true
            }
        }
        else
        {
            println!("Answer was correct!!!!");
            self.purses[self.current_player as usize] += 1;
            println!("{0} now has {1} Gold Coins.",self.players[self.current_player as usize],self.purses[self.current_player as usize]);
            let winner: bool = self.did_player_win();
            self.current_player += 1;
            if self.current_player == self.players.len() as i32 {
                self.current_player = 0;
            }
            winner
        }
    }
}

fn main()
{
    let mut not_a_winner : bool = false;
    let mut game = Game {..Default::default()}; 
    game.add("Chet".to_string());
    game.add("Pat".to_string());
    game.add("Sue".to_string());
    while {
        game.roll(rand::random::<i32>() % 5 + 1);
        if rand::random::<i32>() % 9 == 7 {
            not_a_winner = game.wrong_answer();
        }
        else {
            not_a_winner = game.was_correctly_answered();
        }
        not_a_winner != false
    } {}
}




Summary random number need to equals 200

Help! Summary random number need to equals 200!!! In C# please.




keeping track about a random choice

Is there a better way to keep track on what is the random choice (i.e. "src") and what is the other choice ("dst") than this?

x,y = "hello","kitty"
n = randint(0,1)
src,dst = (x,y)[n], (x,y)[n-1]
z = deepcopy(src)
z += dst

z
Out[51]: 'kittyhello'




Increments with random numbers

I have been trying to get this script to work for quite a while now. I usually have no problem with increments but I can't seem to get the architecture down for this one. Here is what I have so far.

package Temper;
import java.util.Random;
 import java.util.Scanner;
 public class Temp {

public static void main(String[] args) {
    // TODO Auto-generated method stub
    {
    System.out.println("I am going to store a bunch of random numbers so pick the first one ");
    Scanner in = new Scanner(System.in);
    in.nextInt();
    }
    {
        System.out.println("I know I said pick a number of your own but here are a bunch of random ones instead \n");
    {
            method1();
        }
        }
        }
    public static int method1()
        {   
            int rv = 0;
            for(int i = 0; i <= 99; i++);
            {

                Random r = new Random();
                int number = r.nextInt(100) + 1;
                System.out.println(number);
                rv = rv + number;
            }
            return rv;
        }   
 }              

When I run the script in the console it ust gives me one number instead of 100. Any help figuring this out would be much appreciated. Thank You




check unrepeated random number

I have a method that return a number:

  public String getNum()
   {
    Random random = new Random();
    return random.nextInt(1000) + "";
   }

And I have this method that stores an object

public void store(User user)
{
  String str = getNum();
  user.setIdCode(str);
  for (User users: userList)
  { 
    if(users.getId() == user.getId())
{
user.setIdCode(getNum);
}

  }

}

if Id is excited than re-set the id. This is for sure checks if the id exists the first time but how about the second time that id is set. there would be a possibility of repeating the same number. At the same time we cant go in infinite loop.




Generating true random numbers

this is my first post on StackOverflow, so just tell me if I made something wrong :)

In my cryptography lessons i learned that one should use as many parameters together as possible in order to have the entropy to generate a close to perfect random number. My question is: Let's say I would just messure the temperature of room at a given moment (e.g. 19,6573°C), would the number not be already random enough? I mean an attacker could not possibly guess my room temperature and he could also not messure it afterwards, because he would need to go back in time^^

Since cryptographic algorithms would turn my temperature from 19,6573 to a string of 512 characters or more and an attacker would not be able to reproduce the messurement, my random number should be random enough, or not?




Javascript - retrieve random image from array

I'm trying to write a program using Javascript and the p5.js library to trigger a random image from an array whenever a peak in an audio file is detected. p5's sound library can detect the audio peak for me and then trigger a function upon that audio peak. However, I don't have much experience in Javascript so I'm not sure where to go from here. I've created an array of images and am planning on creating a function using math.Random to grab one of these images. Can I then call that function within my triggerBeat function?

Also, I've set the image as the background so that it's not within p5's draw function, so I'm trying to change the bg variable. I've preloaded the background image, and I've also got code within the preload function to allow the user to upload an audio file.

Sorry if this doesn't make a ton of sense. I'm pretty new to Javascript and I've spent most of today trying to wrap my head around it.

var cnv, song, fft, peakDetect, img, bg;

var imageset = new Array;
imageset[0] = "dogs01.png";
imageset[1] = "dogs02.png";
imageset[2] = "dogs03.png";
imageset[3] = "dogs04.png";
imageset[4] = "dogs05.png";
imageset[5] = "dogs06.png";
imageset[6] = "dogs07.png";
imageset[7] = "dogs08.png";
imageset[8] = "dogs09.png";
imageset[9] = "dogs10.png";
imageset[10] = "dogs11.png";
imageset[11] = "dogs12.png";
imageset[12] = "dogs13.png";
imageset[13] = "dogs14.png";
imageset[14] = "dogs15.png";
imageset[15] = "dogs16.png";
imageset[16] = "dogs17.png";
imageset[17] = "dogs18.png";
imageset[18] = "dogs19.png";
imageset[19] = "dogs20.png";
imageset[20] = "dogs21.png";
imageset[21] = "dogs22.png";
imageset[22] = "dogs23.png";
imageset[23] = "dogs24.png";
imageset[24] = "dogs25.png";

function preload(){
  img = loadImage("dogs01.png");
  var loader = document.querySelector(".loader");
  document.getElementById("audiofile").onchange = function(event) {
      if(event.target.files[0]) {
          if(typeof song != "undefined") {
              song.disconnect();
              song.stop();
          }


          song = loadSound(URL.createObjectURL(event.target.files[0]));
          loader.classList.add("loading");
      }
  }
}


function setup() {
  bg = loadImage("dogs01");
  cnv = createCanvas(200,154);

  fft = new p5.FFT();
  peakDetect = new p5.PeakDetect();

  setupSound();
  peakDetect.onPeak(triggerBeat);
}

function draw() {
  background(bg);

  fill(0);
  text('play', width/2, height/2);

  fft.analyze();
  peakDetect.update(fft);


}

function triggerBeat() {

//this is where I want an image to be pulled from the array and randomly displayed

}


function setupSound() {
  cnv.mouseClicked( function() {
    if (song.isPlaying() ) {
      song.stop();
    } else {
      song.play();
    }
  });
}




How to randomly order two synchronized lists?

Aparently suffling an array is not so complicated: How to randomize (shuffle) a JavaScript array?

But what if I have to (Html DOM) lists that are synchronized and I need to suffle the order of the elements, but they should have the same final order?

Example, Initial state:

A)

<ul> <li>First title</li> <li>Second Title</li> <li>Thrid title</li> </ul>

B)

<ul> <li>First text</li> <li>Second text</li> <li>Thhird text</li> </ul>

After suffle

A)

<ul> <li>Second title</li> <li>First Title</li> <li>Thrid text</li> </ul>

B)

<ul> <li>Second text</li> <li>First text</li> <li>Third text</li> </ul>

How can this be achieved?




dimanche 25 novembre 2018

find xargs to cat random to files in a directory

Was trying to cat /dev/random to all the files in a directory. Tried the usual find exec way as given below, but went futile,

find -maxdepth 1 -type f -iname *.bin -exec cat /dev/random | head -n1024 > {} \;

Tried xargs way, find -maxdepth 1 -type f -print0 | xargs -0 -n1 -i{} cat /dev/random | head -n 1024 > {}, but that too went south, any idea??




Why does my loop produce the same random number unless I pause at the end of every iteration?

Why does this work and produce different random numbers per the SIZE?

for (int index = 0; index < SIZE; index++)
{
    Random rand = new Random();
    numbersArray [index] = rand.Next(0, 100);
    MessageBox.Show(index.ToString());
}

And yet this produces the same number per the SIZE?

for (int index = 0; index < SIZE; index++)
{
    Random rand = new Random();
    numbersArray [index] = rand.Next(0, 100);
}

The only guess i have is that the Random object gets refreshed when the program pauses?




Python: Randomly mix two lists

I'm having some trouble mixing two lists together to make a new list of the same length.

So far I ave randomly selected two lists from a bunch of lists called parent 1 and parent 2. This is what I have so far but the output_list line doesn't work.

parent1 = listname[random.randint(1,popsize)]
parent2 = listname[random.randint(1,popsize)]
output_list = random.choice(concatenate([parent1,parent2]), length, replace=False)
print(output_list)

The outcome I want it if parent 1 = [1,2,3,4,5] and parent 2 = [6,7,8,9,10] then a possible outcome could be [1,2,3,9,10] or [1,7,2,5,6] or [1,2,7,4,5].

Anybody have any ideas?

(the context is two sets of genes which breed to form a child with a mix of the parents genes)




Check if multiple elements in an array contain the same value

For instance I have an array that gets filled with random numbers and am going to call this one dice.

Random rnd = new Random()
int[] dice=new dice [5]
for (int i=0;i<dice.length;i++)
{
dice[i]= rnd.next(1,7)
}

Now for the sake of simplicity I wanna ask how can I find out if got a three of a kind of instance.




How to get a random float value between two floats?

The desired output is a random float between two floats. This is the way I did it but this method doesn't work for negative floats like: random float between -1f and -30f since the bound has to be positive and I get IllegalArgumentException. It also looks pretty complicated...if you have an easier approach that would be lovely. Cheers!

unitsConsumed = rnd.nextInt(Math.round(maxUnitsConsumed-minUnitsConsumed))+minUnitsConsumed;

Where rnd is an instance of Random.




Can't use randint() directly in the .format() string?

Complete beginner here.

I'm making a short game where one of the two players is randomly chosen to start the game:

from random import randint
player1 = input("First player, enter your name: ")
player2 = input("Second player, enter your name: ")

print("{randint(0,1)} will go first".format(name1, name2))

I want randint() to choose either player1 or player2, but I'm getting a TypeError. If I were to put either 0 or 1 into the {} instead of randint(0, 1) it works fine. Why doesn't this work? What other options are there besides an if/elif statement?




empty a rectangle in C

This is my code:

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


int main(){

    FILE *f = fopen("result.txt","w");

    int i, j, run=0 ,counter=0, random_i, random_j;
    double matrix[20][40];
    srand(time(NULL));

    for(i=0; i<20; i++){
        for(j=0; j<40; j++){
            matrix[0][j] = 2;
            matrix[19][j] = 2;
        }
        matrix[i][0] = 2;
        matrix[i][39] = 2;
    }

   for(i=1; i<19; i++){
        for(j=1; j<39; j++){
            matrix[i][j] = 1;
            counter++;
        }
    }

    for(i=8; i<12; i++){
        for(j=0; j<1; j++){
            matrix[i][j] = 3;
        }
        for(j=39; j<40; j++){
            matrix[i][j] = 3;
        }
    }
    fprintf(f,"\n\ncounter: %d\n run: %d\n",counter,run);

    do{

    run++;
    }while(counter != 0)


    for(i=0; i<20; i++){
        for(j=0; j<40; j++){
            fprintf(f,"%.f;\t",matrix[i][j]);
        }
        fprintf(f,"\n");
    }
    fprintf(f,"\n\ncounter: %d\n run: %d\n",counter,run);

    fclose(f);
 return 0;
}

Where '2' means a wall, '3' means a door and '1' means a human ('0' would be a plance where no human is standing).

The task is to pick a human randomly and in case this human is standing nexto a door, the place can be '0' and this means -1 human from the rectangle. In case a human is not standing nexto a door, but there is a '0' around him, he can move.

The main object is to empty this rectangle and to calculate how many times ran the program.

Could you please help me with that? Unfortunately I'm not able to write the part where I can get the rectangle empty.

Thank you very much!




How to Generate large dataset and randomizeusing python DataFrame

I have written a program that will Generate large data set and randomize it according to conditions Please Go through my whole program and conditions which i will write here if any thing which is not clear for you please ping me...

Input data:

Asset_Id  Asset Family  Asset Name  Location    Asset Component          Keywords                       
 1     Haptic Analy     HAL1        Zenoa       Tetris Measuring Unit    Measurement Inaccuracy,    
 1     Haptic Analy     HAL2        Zenoa       Micro Pressure Platform  Low air pressure,                      
 1     Haptic Analy     HAL3        Technopolis Rotation Chamber         Rotation Chamber Intermittent Slowdown
 1     Haptic Analy     HAL4        Technopolis Mirror Lens Combinator   Mirror Angle Skewed,           
 2     Hyperdome Insp   HISP1       Technopolis Laser Column             Column Alignment Issues,       
 2     Hyperdome Insp   HISP2       Zenoa       Turbo Quantifier         Quantifier output Drops Intermittently 
 2     Hyperdome Insp   HISP3       Technopolis Generator                Generator          
 2     Hyperdome Insp   HISP4       Zenoa       High Frequency Emulator  Emulator Frequency Drop            

 3     Nano Dial Assem  NDA11       Zenoa       Fusion Tank              Fall in Diffusion Ratio            
 3     Nano Dial Assem  NDA12       Zenoa       Dial Loading Unit        Faulty Scanner Unit            
 3     Nano Dial Assem  NDA13       Zenoa       Vaccum Line Control      Above Normal 
 3     Nano Dial Assem  NDA14       Zenoa       Wave Generator           Generator Power Failure
 4     Geometric Synth  GeoSyn22    La Puente   Scanning Electronic      Faulty Scanner Unit            
 4     Geometric Synth  GeoSyn23    La Puente   Draft Synthesis Chamber  Beam offset beyond Tolerance       
 4     Geometric Synth  GeoSyn24    La Puente   Progeometric Plane       Progeometric Plane Fault Detected  
 4     Geometric Synth  GeoSyn25    La Puente   Ion Gas Diffuser         Column Alignment Issues    

CONDITIONS: 1) Data should be read csv file and randomize whole data. 2) It should also randomize "Location" column separately and print along with all randomize data. 3) Data should be generate more than 30k rows from given data. 4) Important- It should also read a "Asset Component" separately and randomize it as the value of the "Haptic Analyser" column- "Asset Family" will not mix with the value "Hyperdome Inspector" and "Nano Dial Assembler" and so on.. its means that It should be randomize column in a way that values of the "Asset Family" column should not match with the other values... If any doubt related with 4th condition please let me know..

For this i have written a program which will satisfy all the three conditions

import pandas as pd
import numpy as np
import random
import csv

def main():

    df=pd.read_csv("C:\\Users\\rahul\\Desktop\\Data Manufacturing - Seed Data.csv")
    ds = (df.sample(frac=1))
#     print(ds)

    loc=df.Location
    # Here we are deleting location column and store it in loc variable
    df=df.drop("Location",1)

    # This way we can randomise location column
    randValue = (loc.sample(frac=1))

    randValue = randValue.to_frame()

    #Now we will join the column randValue with whole data
    result=ds.join(randValue, how='left', lsuffix='_left', rsuffix='')

#     cols = list(result.columns.values)
#     print("cols-",cols)

    result = result[['Asset_Id ', 'Asset Family', 'Asset Name', 'Location', 'Asset Component','Keywords','Conditions','Parts','No. of Parts','SR_Id','SR_Date','SR_Month','SR_Year']]

    #Now randomise the whole data again
    ds1 = (result.sample(frac=1))
#     print(ds1)

    # Generating Large dataSet and randomize it
    dd=ds1.append([ds1]*500)
    ds2 = (dd.sample(frac=1))
    print(ds2)
    ds1.to_csv('C:\\Users\\rahul\\Desktop\\people1.csv')


if __name__ == '__main__':
    main()

This program will generate large dataSet and randomize it and also randomize the Column "Location" But only thing i'm not able to do the 4th condition which will be randomize but according to the data which is in other column "Asset Family" values of "Haptic Analyser" and "Hyperdome Inspector" of "Asset Component " should not mix each other and print separately.

The output data:

Asset_Id   Asset Family     Asset Name  Location    Asset Component     Keywords
3         Nano Dial Assem   NDA11       Zenoa       Fusion Tank     Fall in Diffusion Ratio         
1         Haptic Analy      HAL3        Technopolis Rotation Chamber    Rotation Chamber Intermittent Slowdown      
2         Hyperdome Insp    HISP2       Zenoa       Turbo Quantifier    Quantifier output Drops Intermittently  
4         Geometric Synth   GeoSyn25    La Puente   Ion Gas Diffuser    Column Alignment Issues         
1         Haptic Analy      HAL1        Zenoa       Tetris Measuring Unit   Measurement Inaccuracy,         
2         Hyperdome Insp    HISP1       Technopolis Laser Column        Column Alignment Issues,        
3         Nano Dial Assem   NDA14       Zenoa       Wave Generator      Generator Power Failure         
4         Geometric Synth   GeoSyn24    La Puente   Progeometric Plane  Progeometric Plane Fault Detected   

In this output all three conditions is given only 4th condition i'm able to do please help me to get it.. thanks in advance

Note : please go through my all conditions before coming to my coding part please if you are not able to understand any thing or any point please text in a comment box..thanks




array errors whit imported java.util.arrays

i still having this errors also if i've imported java.util.Arrays :

Hangman.java:43: error: cannot find symbol
                 char[] randomWordToGuess = randomWordToGuessC.toCharArray() ;
                                            ^
  symbol:   variable randomWordToGuessC
  location: class Hangman
Hangman.java:94: error: cannot find symbol
                for (int i = 0; i <  array.length; i++  ) {
                                     ^
  symbol:   variable array
  location: class Hangman
Hangman.java:95: error: cannot find symbol
                        System.out.println(array[i] + "");
                                           ^
  symbol:   variable array
  location: class Hangman
Hangman.java:100: error: cannot find symbol
        for (int i = 0; i <  array.length; i++  ) {
                             ^
  symbol:   variable array
  location: class Hangman
Hangman.java:101: error: cannot find symbol
                if (array[i] == '_') return false;
                    ^
  symbol:   variable array
  location: class Hangman
5 errors

my code is:

import java.util.Random ;
import java.util.Scanner ;
import java.util.ArrayList;
import java.util.concurrent.ThreadLocalRandom;
import java.util.Arrays;

public class Hangman {

        public static void main(String[] args) {
                Scanner scanner = new Scanner (System.in);
                Random random = new Random();
                String ciao = "ciao";
                String programmazione = "programmazione";
                String frutto = "frutto";
                String cianbella = "cianbella";
                String[] guesses= {"ciao", "ciambella","frutto"};
                //char[] guessesChar = guesses.toCharArray() ;
//              String randomGuesses= (guesses.[random().nextInt(guesses.length)]);
                boolean weArePlaying = true;
                while (weArePlaying) {
                        System.out.println("Benvenuto all' impiccato di MatStar15");
                for (int i = 1; i <= 1; i++) {
                        //*                                  INIZIO RANDOM
 
                ArrayList<String> companyName = new ArrayList<String>();
 
                companyName.add("Ciao");
                companyName.add("frutta");
                companyName.add("Twitter");
                companyName.add("Paypal");
                companyName.add("Uber");
                companyName.add("Yahoo");
 
                //Get Random Company Name from Arraylist using Random().nextInt();
                String randomWordToGuessC = companyName.get(new Random().nextInt(companyName.size()));

 
        }
// *                       FINE RANDOM

                        char[] randomWordToGuess = randomWordToGuessC.toCharArray() ;
//                      char randomWordToGuess = guesses[random.nextInt(guesses.length)].toCharArray();



                        int amountOfGuesses = randomWordToGuess.length; //100
                        char[] playerGuess = new char[amountOfGuesses];//_ _ _ _ _
                        for (int i = 0; i < playerGuess.length; i++  ) {
                                playerGuess[i] = '_' ;
                                
                        }

                        boolean wordIsGuessed = false;
                        int tries = 0;
                        
                        while (!wordIsGuessed && tries != amountOfGuesses) {
                                System.out.println("numero di tentativi: \n");
                                printArray(playerGuess);
                                System.out.printf("hai altri ");
                                System.out.printf("tries ", amountOfGuesses - tries + "\n");
                                System.out.printf ( " tentativi.\n") ;
                                System.out.println("digita un solo carattere");
                                char input = scanner.nextLine().charAt (0); //shadgsv --> solo "s" 
                                tries++;
                                
                                if (input=='_') {
                                        weArePlaying = false ;
                                        wordIsGuessed = true ;
                                } else {
                                        for (int i = 0; i < randomWordToGuess.length; i++  ) {
                                                if (randomWordToGuess[i] == input) {
                                                        playerGuess[i] = input;
                                                }
                                        }
                                        
                                        if (isTheWordGuessed(playerGuess)) {
                                                wordIsGuessed = true ;
                                                System.out.println ("congratuliazioni hai vinto!");
                                        }
                                }
                        }       
                        
                        if (!wordIsGuessed) System.out.println("hai finito i tentativi :/");
                        System.out.println("vuoi fare un'altra partita? (si/no)");
                        String anotherGame = scanner.nextLine ();
                        if (anotherGame.equals("no")) weArePlaying = false;
                        
                }
                System.out.println("GameOver");
        }
        public static void printArray(char[] Array) {
                for (int i = 0; i <  array.length; i++  ) {
                        System.out.println(array[i] + "");
        }
                System.out.println() ;
        }
        public static boolean isTheWordGuessed(char[] Array) {
        for (int i = 0; i <  array.length; i++  ) {
                if (array[i] == '_') return false;
        }
        return true;
        }
}

what can i do for fixing everything and maybe also compact everything ?




samedi 24 novembre 2018

Cache is empty after the Activity is returned

I am having this issue on an app that I made. It's a simple game that I loads data from Room database in my onCreate method, saves the loaded data in List<GameData> gameData and then starts the game.

gameDao.getAll()
    .subscribe(gameDatas -> {
        gameData.addAll(gameData);
        startGame();
    });

inside my startGame, I randomly select a number in the range [0, gameData.size()] and do some game related work with the corresponding gameData.

public void startGame(){
    Random random = new Random();
    int randomNumber = random.nextInt(gameData.size());

    // do something with gameData[ramdomNumber]
}

So, then user keeps playing and then when the user loses I send him to GameOverActivity with startActivityForResult(gameOver,1123)

Inside GameOverActivity user can

  • restart the game
  • watch an ad to continue playing
  • other social related staff

So when the user presses restart button, I just finish the GameOverActivity which will redirect me to onActivityResult of GameActivity. Here I just call startGame method again, and it should supposedly start a new game.

Now the problem is sometimes for certain devices, gameData is getting empty and hence I am getting exception inside startGame when I call random.nextInt(gameData.size())

java.lang.RuntimeException: 

  at android.app.ActivityThread.performResumeActivity (ActivityThread.java:3790)

  at android.app.ActivityThread.handleResumeActivity (ActivityThread.java:3830)

  at android.app.ActivityThread.handleLaunchActivity (ActivityThread.java:3038)

  at android.app.ActivityThread.-wrap11 (Unknown Source)

  at android.app.ActivityThread$H.handleMessage (ActivityThread.java:1696)

  at android.os.Handler.dispatchMessage (Handler.java:105)

  at android.os.Looper.loop (Looper.java:164)

  at android.app.ActivityThread.main (ActivityThread.java:6944)

  at java.lang.reflect.Method.invoke (Native Method)

  at com.android.internal.os.Zygote$MethodAndArgsCaller.run (Zygote.java:327)

  at com.android.internal.os.ZygoteInit.main (ZygoteInit.java:1374)
Caused by: java.lang.RuntimeException: 

  at android.app.ActivityThread.deliverResults (ActivityThread.java:4491)

  at android.app.ActivityThread.performResumeActivity (ActivityThread.java:3762)
Caused by: java.lang.IllegalArgumentException: 

  at java.util.Random.nextInt (Random.java:388)

  at com.company.game.GameActivity.startGame (GameActivity.java:149)

  at com.company.game.GameActivity.onActivityResult (GameActivity.java:477)

  at android.app.Activity.dispatchActivityResult (Activity.java:7556)

  at android.app.ActivityThread.deliverResults (ActivityThread.java:4487)

I am not understating why would gameData is getting cleared, and I am not able to check because I have never encountered while testing and I got the crash report from PlayConsole. Any idea what might be causing this?




Random Elements from two Lists - Python

So I have two lists in Python:

import random
list_1 = ['1','2','3']
list_2 = ['4','5','6']
num = random.choice(list_1 or list_2)

This doesn't seem to work. How can I get a random number from either list 1 or list 2?




Generate Random elements without duplicate

I am trying to make a Random Number Generator.

I made a code and it does work well.

document.querySelector('#btn').addEventListener('click',()=>{
  generate(1,45,6)
});

function generate(min, max, count){
  const arr = [];

  if(min >= max) return;
  if(max - min + 1 < count) return;

  while (arr.length < count) {
    let num = Math.floor(Math.random() * max) + min;
    let flag = arr.every((i) => {
      return i === num ? false : true;
    });
    if (flag) {
      arr.push(num);
    }
  }
  console.log(arr);
}
<button id="btn">Gen</button>

But my algorithm's time complexity is O(n).

I hope to reduce the time complexity if I can.

And, I guess my above code can be compacted, but I can't.

Summary What I Want

  1. To reduce the time complexity if it can be

  2. To make it compacted




Android / String resources for options

I making a random textview and I have a problem. How can I put strings resources from xml to String options[]:

String options[] = {"abc","def","ghi",}

    Random rand = new Random();
    final int random = rand.nextInt(3);

    textfacts.setText(options[random]);

I want to use these strings in Strings options:

<string name="1">abc</string>
<string name="2">abc</string>
<string name="3">abc</string>




Seeding a random number generator with a random integer from another random number generator

In a Java project, I use the same unique Random object all over my code. I usually create it without a seed, but when debugging it is useful to initialize it with a seed so I get reproducible runs.

I am using Apache Commons Math 3.6 and its NormalDistribution class takes a RandomGenerator object. RandomGenerator is of course a different interface from Random, so I cannot just pass my unique Random object to NormalDistribution.

To keep the ability to introduce a single seed to a single random number generator and obtain reproducible runs, I create the RandomGenerator (specifically, its implementation JDKRandomGenerator) for NormalDistribution with a seed that comes from my unique Random object (using Random.nextInt()):

NormalDistribution(new JDKRandomGenerator(myUniqueRandom.nextInt()), mean, standardDeviation);

The reasoning is that, when I introduce a seed to the Random object, it will pass the same seed every time to the RandomGenerator and things will be reproducible.

Things seemed to be working but after a while I realized that the variance I was getting in my results was far from what it should have been. After some debugging I realized that if I don't pass a seed to JDKRandomGenerator from my unique Random (or use the NormalDistribution constructor that doesn't take a random number generator at all), then things work fine and the variance is what it should be. However, now I don't have the ability to obtain reproducible runs anymore.

Any idea why passing a RandomGenerator a seed coming from Random.nextInt() didn't work? It sounds like it should.




How to grow flowers using JavaScript?

I would like to console-output randomly generated flowers, which look similar to the one below. The flowers must have 8 leaves, and must have a width of 50 characters.

MMMMMMMMMMMMMMMMMMMWWKOxxxxOKWMMMMMMMMMMMMMMMMMMMM
MMMMMMMMMMMMMMMMMMWKdc;;;;;;cdKWMMMMMMMMMMMMMMMMMM
MMMMMMMMWWWNNWWMMWKl;;;;;;;;;;lKWMMWWNNWWWMMMMMMMM
MMMMMMWXkdollodkKXx;;;;;;;;;;;;xXKOdollodkXWMMMMMM
MMMMMW0l;;;;;;;;coc;;;;;;;;;;;;coc;;;;;;;;l0WMMMMM
MMMMMNd;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;dNMMMMM
MMMMMNx;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;dNMMMMM
MMMMMWKl;;;;;;;;;;;;cc:;;;;:cc;;;;;;;;;;;;lKWMMMMM
MMMMMWN0o:;;;;;;;;;:dkxl:clxkd:;;;;;;;;;:o0NWMMMMM
MMWKkdolc:;;;;;;;:cdocll::locooc:;;;;;;;:clodkKWMM
WKdc;;;;;;;;;;;cxxoll:::::cc:cloxdc;;;;;;;;;;;cdKW
Xo;;;;;;;;;;;;;:oxoc:clxOOkl::clxo;;;;;;;;;;;;;;oK
0c;;;;;;;;;;;;;;colc::d0NN0d::ccoc;;;;;;;;;;;;;;l0
Nk:;;;;;;;;;;;;cxkoc::cloolc:ccokxc;;;;;;;;;;;;ckN
MN0xl:;;;;;;;;;clllol:cc::cc:lolllc;;;;;;;;;:lxKWM
MMMWNKOko:;;;;;;;;;codxo:coxdol;;;;;;;;;:lk0KNWMMM
MMMMMMNkc;;;;;;;;;;;odlc::cldo:;;;;;;;;;;:kNWMMMMM
MMMMMWk:;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;:kWMMMMM
MMMMMXd;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;dXMMMMM
MMMMMNk:;;;;;;;;;::;;;;;;;;;;;;::;;;;;;;;;:kNMMMMM
MMMMMWNkl:;;;;:lxko;;;;;;;;;;;;oOxl:;;;;:lkNWMMMMM
MMMMMMMWN0OkO0KNWWk:;;;;;;;;;;:kWWNKOOOOKNWMMMMMMM
MMMMMMMMMMMMMMMMMMNkc;;;;;;;;:kNMMMMMMWMMMMMMMMMMM
MMMMMMMMMMMMMMMMMMMW0xlc::clx0WMMMMMMMMMMMMMMMMMMM
MMMMMMMMMMMMMMMMMMMMMWXK00KXWWMMMMMMMMMMMMMMMMMMMM

How could I randomly generate those flowers? I literally have no clue what to search for, or how to approach this task.




vendredi 23 novembre 2018

return random values from a stack python

I am trying to return 5 values from a stack and displaying it out. May I ask how I can go about doing it?

Attached is my code on how to solve the problem.

import random
Class Stack:
def __init__(self):
    self.stack = []

def isEmpty(self):
     return self.size() == 0   

def push(self, item):
     self.stack.append(item)  

def peek(self) :
     if self.size()>0 :
         return self.stack[-1]
     else :
         return None

def pop(self):
     return self.stack.pop()  

def size(self):
     return len(self.stack)

def randomFive(self):
    return self[random.randint(0,len(self)-1)]

list=Stack()
list.push("Tom")
list.push("John")
list.push("Peter")
list.push("Harry")
list.push("Jerry")

for i in range(0,list.size()):
    five = list.randomFive()

The error shown is:
return self[random.randint(0,len(self)-1)]
TypeError: object of type 'Stack' has no len()




Download link over random php image

I am displaying a number of random images from a folder, however I'm not very good with PHP (Code sourced from the internet), how would I go about having a "download" link on top of the image?

Display random image from folder using PHP:

function random_image($directory)
{
$leading = substr($directory, 0, 1);
$trailing = substr($directory, -1, 1);

if($leading == '/')
{
    $directory = substr($directory, 1);
}
if($trailing != '/')
{
    $directory = $directory . '/';
}

if(empty($directory) or !is_dir($directory))
{
    die('Directory: ' . $directory . ' not found.');
}

$files = scandir($directory, 1);

$make_array = array();

foreach($files AS $id => $file)
{
    $info = pathinfo($dir . $file);

    $image_extensions = array('jpg', 'jpeg', 'gif', 'png', 'ico');
    if(!in_array($info['extension'], $image_extensions))
    {
        unset($file);
    }
    else
    {
        $file = str_replace(' ', '%20', $file);
        $temp = array($id => $file);
        array_push($make_array, $temp);
    }
}

if(sizeof($make_array) == 0)
{
    die('No images in ' . $directory . ' Directory');
}

$total = count($make_array) - 1;

$random_image = rand(0, $total);
return $directory . $make_array[$random_image][$random_image];

}

Markup:

echo "<img src=" . random_image('css/images/avatars') . " />";

I've tried looking around google for an answer but I can't find anything, any help would be appreciated




Randomized word not showing up. C#

I'm making a hangman game. But there is one problem i'm facing. I made a function that chooses the word. But when I check if the word is chosen with a textbox. The word doesn't show up. This is the function that picks a random word to be guessed.

            private void woordLaad()
            {
                var regels = File.ReadAllLines("woorden.csv"); 
                var rnd = new Random();
                var RandomRegelNummer = rnd.Next(0, regels.Length - 1); // 
    takes a random line
                RRwoord = regels[RandomRegelNummer];

                textBox1.Text = RRwoord;

Could you people help me with it?




understanding seed of a ByteTensor in PyTorch

I understand that a seed is a number used to initialize pseudo-random number generator. in pytorch, torch.get_rng_state documentation states as follows "Returns the random number generator state as a torch.ByteTensor.". and when i print it i get a 1-d tensor of size 5048 whose values are as shown below

tensor([ 80, 78, 248, ..., 0, 0, 0], dtype=torch.uint8)

why does a seed have 5048 values and how is this different from usual seed which we can get using torch.initial_seed




setting the random number generator seed in arena-simulation

I am using Arena to simulate queues on different days. I use different schedules for some parameters on each weekday, and since days are independent, I have chosen to implement each weekday as a separate simulation. However, this means that for attributes that do not differ by weekday, I get the same random numbers on different weekdays.

So I would like to set the RNG seed to differ on each weekday (for sampling from a gamma distribution).

The Arena documentation states that one needs to use the SEEDS module from the elements panel. But I do not see any elements panel, and cannot find any guidance as to how to access this panel. I am fairly new to Arena, so any guidance as to how to set the RNG seed in Arena would be appreciated.

Thanks




jeudi 22 novembre 2018

Python - How to print multiple random element/item in a stack?

does anyone know how to print multiple element/item in stack? As from what i know, to use choose range numbers from a list is using range but how do i use with a stack? I have already tried doing like a for loop in range (the first element, last element) but had some errors in trying the code out.

Heres my current working code:

import random

class Stack:
 def __init__(self):
     self.container = []  

 def isEmpty(self):
     return self.size() == 0   

 def push(self, item):
     self.container.append(item)  

 def peek(self) :
     if self.size()>0 :
         return self.container[-1]
     else :
         return None

 def pop(self):
     return self.container.pop()  

 def size(self):
     return len(self.container)

Gift = Stack()
GiftTemp = Stack()
GiftWin = Stack()
GiftResult = Stack()
Gift.push ("Smart Watch")
Gift.push ("Gadget Key Chain")
Gift.push ("Happy Birthday Photo Frame")
Gift.push ("Silver Heart Pendant")
Gift.push ("Nike Cap")
Gift.push ("Stuffed Bunny Toy")
Gift.push ("Wireless Headphones")
Gift.push ("iPhone XS")

print("~ Mystery Gift Vending Machine ~")

size = Gift.size()+1
sizeOfGiftTemp = GiftTemp.size()+1

#prints very element in the stack and put the elements in GiftTemp
for i in range(1, size):
GiftTemp.push(Gift.pop())
print(str(i) + " - " + GiftTemp.peek())

#transfer elements from giftTemp to gift
for i in range(1, sizeOfGiftTemp):
Gift.push(GiftTemp.pop())

print("")
print("You will get one of these gifts below.")




Randomly assign array value with another array's value

I'm emulating a Deal or No Deal game where the user chooses a case from a specified list. Now, on each run of the console app I want there to be a random assignment for each cash prize to each case (for fairness sakes). My code is of the following:

    int[] cashPrizeArray = new int[] { 0, 1, 2, 5, 10, 20, 50, 100, 150, 200, 250, 500, 750, 1000, 2000, 3000, 4000, 5000, 10000, 15000, 20000, 25000, 50000, 75000, 100000, 200000 };
    string[] caseArray = new string[] { "1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12", "13", "14", "15", "16", "17", "18", "19", "20", "21", "22", "23", "24", "25", "26" };

    Console.WriteLine("Deal or Not!");
    Console.Write("Choose a case: 1-26: ");
    string userCase = Console.ReadLine();



    if (!caseArray.Contains(userCase))
    {
        Console.WriteLine("\nUnexpected input text.\nThis application will now be terminated.\nPress ENTER to continue...");
        Console.ReadLine();
        Environment.Exit(0);
    }

    else
    {
        Console.WriteLine("You chose case " + userCase);
        Console.ReadLine();
    }

I will need to reference these cases one by one when a user chooses them, and then remove them from being called in the array once initially opened.




Populate and print array with random numbers using C

I'm trying to write a program that will populate an array of 100 elements with numbers between 1 and 22, and then print the array in a 20 x 5 table. I was able to populate the array and print it, but can only get it to work with numbers 1-100, how can I change it to only do numbers 1-22?

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

#define ARY_SIZE 100

void random (int randNos[]);
void printArray (int data[], int size, int lineSize);

int main(void)
{
    int randNos [ARY_SIZE];

    random(randNos);
    printArray(randNos, ARY_SIZE, 20);

    return 0;
} 

void random (int randNos[])
{

   int oneRandNo;
   int haveRand[ARY_SIZE] = {0};

   for (int i = 0; i < ARY_SIZE; i++)
   {
      do
      {
        oneRandNo = rand() % ARY_SIZE;
      } while (haveRand[oneRandNo] == 1);
      haveRand[oneRandNo] = 1;
      randNos[i] = oneRandNo;
   }
   return;
}

void printArray (int data[], int size, int lineSize)
{

    int numPrinted = 0;

    printf("\n");

    for (int i = 0; i < size; i++)
    {
        numPrinted++;
        printf("%2d ", data[i]);
        if (numPrinted >= lineSize)
        {
         printf("\n");
         numPrinted = 0;
        }
   }
   printf("\n");
   return;

}




Arrays.stream() vs. .stream(), when to use which one [duplicate]

This question already has an answer here:

So I am trying to understand how to use streams, but I can't figure out how you're supposed to create a stream.

For Example:

public void printMultiRandom(int howMany)
{
    int[] nums = rand.ints(howMany).toArray();
    Arrays.stream(nums)
        .forEach(number -> System.out.println(number));

}

This code is correct and working, but I don't know why I have to use Arrays.stream(nums) as opposed to this:

public void printMultiRandom(int howMany)
{
    int[] nums = rand.ints(howMany).toArray();
    nums.stream()
        .forEach(number -> System.out.println(number));

}

I know that there are even more ways to create streams, like stream.of(), but I don't know what situations you're supposed to use them in.

Edit:

Okay so I think I now somewhat understand why nums.stream() doesn't work in this case. Because the .stream() method is only a method of collections, and int[] = nums is an array and not a collection. If this is the case, is there an easier way for me to code this. The Random method ints() says that it returns an IntStream already, can I use this without converting it to an array, and how would I go about doint that?