samedi 31 août 2019

Trouble calling method and Populating Random Array

I am new to coding and trying to call a method (RandomArray) which I wrote and defined in a separate class, but in my driver code I keep getting the error message "Couldn't find symbol- RandomArray()".

the code SHOULD create an array (size of which is chosen by the user) and then populate it with random numbers and output the Highest, Lowest, and Average of the numbers in said array.

All spellings match up, and the call itself works and displays no errors, but when using it in the for-loop I get the error message.

// this is the class where I created the method

import java.util.Random;
public class RandomArray
{
    //things declared at class level
    public int minimun,maximun,adverage, mn, mx, avg;
    public String range;

    //constucotr for inital numbers
    public RandomArray()
    {
        minimun = 0;
        maximun = 1000 + 1;
    }


static int RandomArray()
{
    Random ran = new Random();
    return (ran.nextInt(1000) + 1);
}

//define types
public RandomArray (int mn, int mx, String r, int a)
{
    minimun = mn;
    maximun = mx;
    range = r;
    adverage =  a;
}

//set minimun
public void setMinimun (int m)
{
    minimun = mn;
}

//get minimun
public int getMinimun()
{
    return minimun;

}

//set maximun
public void setMaximun(int x)
{
    maximun = mx;
}
//get maximun
public int getMaximun()
{
    return maximun;
}

//compute adverage
public int adverage(int...array)
{
   int adverage = 0;
   if (array.length > 0)
   {
       int sum = 0;
       for(int num : array)
            sum = sum + num; //add numbers in array 
       adverage = (int)sum / array.length; //divide numbers in array by the array lenth

    }

   return adverage;
}

//return values as a string
public String toString()
{

    return String.valueOf(getMinimun() + getMaximun() + adverage());

}

}

// and this is the driver program that should be populating the array (of users choice) with random numbers and printing the highest, lowest and average.

import java.util.Random;
import java.util.Scanner;
import java.util.Arrays;
public class DemoRandomArray
{
    // variable go here
    final int minimun = 0;


    public static void main(String[] args)
    {
        final int max = 100;

        RandomArray ra = new RandomArray(); 

        int[] anArray = new int[1000];


        for(int i=1; i < max; i++)
        {
           System.out.println(RandomArray());
        }

    }

}




how to get just one line of a text file in a string in python3.x?

I am working on a word guessing game and i have created a text file with each line being a word(it's 1000 line). I don't want to get the whole text file into memory i just want a random line of the text put into a string.




Evenly-spaced samples from a stream of unknown length

I want to sample K items from a stream of N items that I see one at a time. I don't know how big N is until the last item turns up, and I want the space consumption to depend on K rather than N.

So far I've described a reservoir sampling problem. The last ask though is that I'd like the samples to be 'evenly spaced', or at least more evenly spaced than reservoir sampling manages. This is vague; one formalization would be that the sample indices are a low-discrepancy sequence, but I'm not particularly tied to that.

My intuition is that this is a feasible problem, and the algorithm I imagine preferentially drops samples from the 'highest density' part of the reservoir in order to make space for samples from the incoming stream. It also seems like a common enough problem that someone should have written a paper on it, but Googling combinations of 'evenly spaced', 'reservoir', 'quasirandom', 'sampling' haven't gotten me anywhere.




TLS simplified Client Random decrypt

I have got from my teacher some code, and i have to work on it. The code represents a simplified TLS implementation for Linux. The problem is that i have some blank functions, like Client Random generate or decryptRandom, and i don't really know what to do in those functions.

I tried some code, from mainstream implementation of TLS, but nothing really works, and my client session goes like "Segmentation fault."

#include <iostream>
#include <arpa/inet.h>      // for inet_ntoa
#include <string.h>         // for memset
#include <sys/socket.h>
#include <unistd.h>         // for close() on sockets
#include <netinet/in.h>
#include <time.h>

#include "sTlsHshake.h"

using namespace std;

//  ====================================================================
//  GLOBAL VARIABLES

fd_set  rset;
ClientHello cliHello;

//  ====================================================================
//  handshake (sub)functions

//  --------------------------------------------------------------------
//  decrypt the client random
int
decryptRandom(u_char * rand, u_char * key) {
    return 1;
}

//  --------------------------------------------------------------------
//  process client's hello message
int
processClientHello(char * cliMsg) {
    return 1;
}

//  --------------------------------------------------------------------
//  create random
int
createRandom(u_char * sR) {
    return 28;
}

//  --------------------------------------------------------------------
//  create premaster
int
createPremaster(u_char * cR, u_char* sR) {
    return strlen("ENCREPTED_PREMASTER");
}

//  --------------------------------------------------------------------
//  process client nessage, whatever that is
int
processClientMsg(u_char * cliMsg) {
    return 1;
}

//  --------------------------------------------------------------------
//  generate master secret
u_char * genMaster(char * preMas, u_char * cR, u_char * sR) {
    u_char master[28];
    return master;
}

//  --------------------------------------------------------------------
//  create session key
void
genSessionKey(char * preMas) {
    // return sessionKey;
}

//  --------------------------------------------------------------------
//  encrypt message using session key
int
encryptMessage(char * msg, u_char * key) {
    strcpy(msg, "FIRST_ENCRYPTED_MESSAGE");
    return strlen(msg);
}

//  --------------------------------------------------------------------
//  encrypt message using session key
int
encryptPreMaster(char * msg, u_char * key) {
    strcpy(msg, "ENCRYPTED_PREMASTER");
    return strlen(msg);
}

//  ====================================================================
//  the handshake function itself

the expected result is that i can introduce an input and, after that the client and server should send eachother the TLS information, like the cipher_suite, Server Random, CLient Random, pre-master and so on.




vendredi 30 août 2019

How to shuffle files within a directory

I am trying to shuffle all the mp3 files within a directory on a micro sd card and moving it to another directory, as it plays in order. I am using Python 3 for this. I just can't get them to randomly switch the order they are presented in. Within the directory under arranged by, "none" is checked.

I have tried to use random.shuffle to shuffle the files in the location, however I get this error:

Traceback (most recent call last): File "/Users/lewislartey/Desktop/Shuffle.py", line 8, in random.shuffle(file) File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/random.py", line 278, in shuffle x[i], x[j] = x[j], x[i] TypeError: 'str' object does not support item assignment

Here is my code:

import os
import random
import shutil
import glob
music = '/Volumes/SD/lit'
destination = '/Users/myusername/Desktop/TEST'
for file in glob.glob("/Volumes/SD/lit*/*.mp3"):
    random.shuffle(file)

.




How to let selenium make a random selection on a radion button python

Im currently working on a project. I want that it chooses a year between 1970 - 1999. The date & month should be randomly choosen. Already tried it per xpath etc. didnt worked out very well.

The website is payoneer.com / Login Form datepicker

birthselection = driver.find_elements_by_xpath("//*[@id=ui-datepicker-div]/div/div/select[1]/option[5]']").click()




Create a random, but most frequently in a certain range

I have to create a certain task that simulates the systolic pressure of a person, so i tried this:

rand = new Random();
timer = new Timer();
timer.schedule(new TimerTask() {

@Override
public void run() {
    Integer sbp = rand.nextInt((130 - 80) + 1) + 80;
        lblSBPCounter.setText(Integer.toString(sbp));           
}
}, 1000, 120000);

The problem is that the systolic pressure has a range from 90 to 120. If it goes below 90 or above 120, that person is in trouble. So in the code i tried to generate a random number every 2 minutes from 80 to 130. The problem is that the random function goes pretty often under and above the range. So my question is: Can i make the function generate more numbers from 90 to 120 and less numbers under 90 and above 120? Like 1 number every 1-2 hours?




Why using numpy.random.seed is not a good practice?

I want to do reproducible tests that use random numbers as inputs. I am used to invoke rng in Matlab and numpy.random.seed in Python. However, I noticed that the Notes section of seed's help reads:

This is a convenience, legacy function.

The best practice is to not reseed a BitGenerator, rather to recreate a new one. This method is here for legacy reasons. This example demonstrates best practice.

from numpy.random import MT19937
from numpy.random import RandomState, SeedSequence
rs = RandomState(MT19937(SeedSequence(123456789)))  
# Later, you want to restart the stream
rs = RandomState(MT19937(SeedSequence(987654321)))

Does anyone know what are the caveats of using seed compared to the docstring suggestion?




sample() keeps returning the same number

I watch movies from a bucket list with my friend containing 100 movies. I have this small script that is supposed to randomly select our next movie each time I run it.

Films <- 1:100
Gekeken <- c(2,6,30,45,86,14,22,40,13,15,16)
sample(Films[-Gekeken],1)

I append the last number to the vector Gekeken manually after running it and run the script again prior to next movie night. There is no seed set, so I would expect sample to pick a new number randomly from the vector Films[-Gekeken] each time I run the script.

However, since I've started using this script (after movie no 40) it seems to pick the 11th value in the vector each time (i.e. 13, 15, 16 and for the current script 17 comes up each time I run the script in a fresh R session).

My question, why does this script behave this way? How do I make sure the first selected number is (quasi)random in a fresh R session? I feel like I'm missing something here but can't find any information about this issue.

My session info:

R version 3.4.4 (2018-03-15)
Platform: x86_64-w64-mingw32/x64 (64-bit)
Running under: Windows >= 8 x64 (build 9200)

Matrix products: default

locale:
[1] LC_COLLATE=Dutch_Netherlands.1252  LC_CTYPE=Dutch_Netherlands.1252    LC_MONETARY=Dutch_Netherlands.1252 LC_NUMERIC=C                      
[5] LC_TIME=Dutch_Netherlands.1252    

attached base packages:
[1] stats     graphics  grDevices utils     datasets  methods   base     

loaded via a namespace (and not attached):
[1] compiler_3.4.4 tools_3.4.4    yaml_2.1.18   

I've tried running the same script in R version 3.6.1, but nothing changes. I know it would be easy to get a random order of all 100 numbers in one go, but we like the surprise.




How to generate pseudorandom numbers using power generator containing seed in C

The power generator is a method for generating pseudorandom numbers. To use the power generator, parameters 𝑝 and 𝑑 are specified, where 𝑝 is a prime, 𝑑 is a positive integer such that 𝑝∤𝑑, and a seed 𝑥0 is specified. The pseudorandom numbers 𝑥1,𝑥2,⋯ are generated using the recursive definition '''𝑥𝑛+1 = 𝑥𝑛𝑑 (𝒎𝒐𝒅 𝑝)'''. Write a program to generate pseudorandom numbers using power generator method and test your program to (a) find the sequence of pseudorandom numbers generated by the power generator with 𝑝 = 3,5,& 7 (choose the integer 𝑑 accordingly) and take the seed 𝑥0=2

I did solved this problem in java but I am having trouble in doing that in C.




jeudi 29 août 2019

Syntax for using SAMPLE() function with two or more orderBy expressions

I would like to use the SAMPLE() function in DAX to select random rows from a table. In the documentation the function appears to support multiple OrderBy_Selection parameters but I'm unable to get the syntax right.

I have a table named dCRQRisk with two columns that I would like to order by before selecting the sample rows: RSO, then RISK_LEVEL, both in Ascending order.

//This is the syntax

SAMPLE(<n_value>, <table>, <orderBy_expression>, [<order>[, <orderBy_expression>, [<order>]]…])`  

//This works

SAMPLE(31,dCRQRisk, dCRQRisk[RSO],1)

//When I try to add the second OrderBy_Expression it does not work

SAMPLE(31, dCRQRisk, dCRQRisk[RSO],[1[,dCRQRisk[RISK_LEVEL],[1]]])

//This is the error message

Query(2, 60) Unexpected value for ORDER argument in SAMPLE function. Use 0/FALSE/DESC for descending order or 1/TRUE/ASC for ascending order.




Ensuring No Random Sequence Is Repeated Indefinitely

I'm attempting to generate a random string of length X. I want to ensure that no two sequences are ever identically produced, even if this code is being run on multiple machines and at the same time.

"list" is the list of characters I'm using, "min" and "max" are the range of indexes, and "length" is the desired length of the String.

Currently, I am using System.nanoTime() as the seed for the Random object. While I realize it is likely improbable for 2 machines to run at the exact same time down to the nano second and produce the same output, I want to make this a foolproof solution.

How can I increase the randomness of this code so that no 2 strings will ever be the same without increasing the length of the string or increasing the number of characters available to be included in the string?

String seq = "";
for (int i = 0; i < length; i++)
    {
      Random rnd = new Random();
      rnd.setSeed(System.nanoTime());
      int randomNum = rnd.nextInt((max - min) + 1) + min;
      seq = seq + list[randomNum];
    }

return seq;




$RANDOM Probleem in Bash

i write'd an script with bash in while loop code:

number=0
while [ 1500 -gt $number ]
do
var="abcdefghijklmnopqrstuvxyz"
letter1="${var:$(( RANDOM % ${#var} )):1}"
letter2="${var:$(( RANDOM % ${#var} )):1}"
a=$RANDOM
b=$RANDOM
c=$(( $a * $b))
echo "$letter1$letter2 $c" >> a.txt
number=$(( 1 + $number ))
done

but now i see duplicate numbers in Result:

Result:
ab 15474
at 15474
yh 15474
gd 15474
re 18696
jg 18696

the numbers are duplicate i guess the $RANDOM changes after a invariant time and my script starts agian the the While loop faster than the $RANDOM changes can you help me an other randomization way?

please help




mercredi 28 août 2019

problem reading .txt file in C# starting from (after immediate empty whole line) to (the next empty whole line)

I am trying to randomly read a huge .txt file. It has tons of paragraphs separated by a full line of empty space prior and post each paragraph. I would like each time I randomly read that it pulls up a full intact paragraph without any characters or words missing for the sake of context. I appreciated the help in advance.

I added a for loop just to test it out and see if I can at some point include a way to recognize consecutively running empty space. That would only work post already selected the starting point obviously if applied.

public static string GetRandomLine(string filename)
{
    var lines = File.ReadAllLines(filename);

    var lineNumber = _rand.Next(0, lines.Length);

    string reply = lines[lineNumber] + lines[lineNumber + 30];

    for(int a = 0; a <= 30; a++)
    {
        reply = reply + lines[lineNumber + a];
        //The increment on the lineNumber is because I wanted to receive
        //more than one sentence for context purposes
    }

    return reply ;
}




What Collision Ratio Of Generate-Random-String Function Is Suitable for Production

In our project there is one function which is used to generate fixed-length random string. It's code is like below.

func (r RandB) Rand(length int) string {
    bucket := "0123456789abcdefghijklmnopqrstuvwxyz"

    bytes := []byte(bucket)
    size := len(bytes)

    result := make([]byte, length)
    atomic.AddInt64(&seed, 1)

    rd := rand.New(rand.NewSource(seed))
    for i := 0; i < length; i++ {
        result[i] = bytes[rd.Intn(size)]
    }

    return string(result)
}

I accidentlly found the collision ratio for this function is about 0.0026 by average, got by 1million times of generation.

I don't think this is a reasonable value for production. So I wonder what value shall be reasonable? Can we use this function in the production environment?




How to generate random list and insert into listview

I am trying to put random items from an array and insert them into a listview, at the moment the listview is just coming up blank. Ideally I would like to be able to retrieve what position from the array the list item is if it is clicked on too

String[] levelOneListList = new String[] { "Daisy", "Rock", "Tree", "Dandelion", "Grass" };

Random r=new Random(); int randomNumber=r.nextInt(levelOneListList.length);

    ArrayAdapter arrayAdapter = new ArrayAdapter(this, android.R.layout.simple_list_item_checked, randomNumber);

The listview is now empty on the emulator




How to generate random parameters in AMPL

how can I generate random parameters on AMPL. Here is my code:

set P;set R;param T>0 integer;
param k {p in P} > 0;param z {r in R} > 0;param c1 >= 0;param c2 >= 0;param c3 >= 0;param h >= 0;param f >= 0;param v >= 0;param D {t in 1..T, p in P} >= 0; param Dr{t in 1..T, r in R} >= 0;param M {t in 1..T, p in P} > 0;param O {t in 1..T, p in P} > 0;

var m {t in 1..T, p in P} >= 0;var n {t in 1..T, r in P} >= 0;var o {t in 1..T, p in P} >= 0;var a {t in 1..T, p in P} >= 0;var d {t in 1..T, p in P} >= 0;var s {t in 1..T, p in P} >= 0;

maximize profit: sum {t in 1..T} sum {p in P} k[p]* m[t,p] + sum{t in 1..T} sum {r in R}z[r]*n[t,r] - (c1*sum {t in 1..T} sum {p in P} m[t,p] + c2 *sum {t in 1..T} sum {r in R} n[t,r] + c3 * sum {t in 1..T} sum {p in P} o[t,p] + h * sum {t in 1..T} sum {p in P} a[t,p] + f * sum {t in 1..T} sum {p in P} d[t,p] + v * sum {t in 1..T} sum {p in P} s[t,p]);

subject to regular capacity {p in P, t in 1..T}: m[t,p] <= M[t,p];
subject to  overrate capacity {t in 1..T, p in P}: o[t,p] <= O[t,p];
subject to  inventory balance {t in 1..T, p in P}: s[t,p] = s[t-1,p] + m[t,p] + o[t,p] - D[t,p];
subject to  increasing limit {t in 1..T, p in P}: a[t,p] >= m[t,p] - m[t-1,p];

subject to decreasing limit {t in 1..T, p in P}: d[t,p] >= m[t-1,p] - m[t,p]; subject to refurbishing limit {t in 1..T, r in R, p in P}: n[t,r] <= 0.2 * m[t,p]; subject to demand balance {t in 1..T, p in P}: m[t,p] = D[t,p]; subject to demand balance {t in 1..T, r in R}: n[t,r] <= Dr[t,r];

here are the given sets : set P and R from 1 to 5 and T from 1 to 12 How can i randomly generate parameters other parameters based on these informations Thanks




Generate 2 random integer list of different size

I am trying to generate 2 list with different size consisting with random numbers. I can generate 2 list with random numbers, but how to achieve 2 different length of lists?

import random
list1 = random.sample(xrange(100), 10)
list2 = random.sample(xrange(100), 10)
print(list1)
print(list2)

Need to generate the lists with 2 random different sizes as well, as if both the lists are completely random.




Importance sampling over discrete probability distribution

Suppose that I know the stationary distribution of samplings via random walks and I want to calculate some expectation values. The stationary distribution is a discrete probability distribution. It is very costly to sample data from the stationary distribution to compute the expectations. So my question is that can I use importance sampling to compute the expectations with possible lower number of samples needed and lower variance?

From my knowledge, importance sampling can be used for continuous probability distribution. Can it be applied to discrete one?

If so, could you share an example with me?




mardi 27 août 2019

Alternative for UUID

I am using UUIDto generate random codes. But It's returning me 20+ digits. Is there is any other algorithm mechanism that returns 8-digit code that is unique or any other way to reduce UUID code length.

Code

const uuidv4 = require('uuid/v4');
uuidv4(); // ⇨ '1b9d6bcd-bbfd-4b2d-9b5d-ab8dfbbd4bed'




Making a BINGO game. How do I generate a random number to be displayed from one set without repeating which number is generated and displayed?

I'm making a bingo game for a course I'm taking, and the assignment is to generate a random pick/element from a pre-setup Set();, display that random value (it's going to be a letter and number e.g. G78, so not an integer), and then make sure that the number is not called again until the game is reset

So far, I'm able to generate a random number and have it displayed, but I can't figure out how to keep the generator from repeating which element from the set it picks to display

let numbers = new Set();
.add("O65")
            .add("O66")
            .add("O67")
            .add("O68")
            .add("O69")
            .add("O70")
            .add("O71")
            .add("O72")
            .add("O73")
            .add("O74")
            .add("O75");

 let guess = Array.from(numbers);

 let checks = new Array();

 function getRandomNumber()
            {
                function rando()
                {
                    for(let g = guess; g = guess.length; g++)
                    {
                        let rand = guess[Math.floor(Math.random() * 
guess.length)];
                        return rand;
                    }


                }
                let num = rando();
                document.getElementById('bingo').innerHTML = num;
                checks.push(num);
                /*if(numbers.has(num))
                {
                    numbers.delete(num);
                }*/
            }

Here, I'm able to generate a random value to be displayed, but sometimes I get one that's already been called. I don't want that to happen, each value from the set should only be generated and displayed once until the program is reset or the entire set has been called




Getting same number when using Math.random() and ThreadLocalRandom.current().nextDouble() and Random class nextDouble() method?

A BankApplication program in Java,problem in setDebitCard() function.

Here I am not able to generate a unique random number after every java run for debitCardNumber variable while it is working fine with debitCardPin

I tried working with Random class method nextDouble(),Math.random(),ThreadLocalRandom.current().nextDouble() too..

Problem 1):The debitCardNumber output is same after trying everything mentioned above.(No syntax error whatsoever)

Problem 2):Also I am getting the same 10 digit debitCardNumber instead of 12 digit.

Problem 3):debitCardPin is working fine,But Sometimes it gives me a unique 3 digit random number.

//CODE

package bankAccountApp;

import java.util.Random;

import java.util.concurrent.ThreadLocalRandom;

public class Current extends Account {

private int debitCardNumber;

private int debitCardPin;

Random rand = new Random();

//setDebitCard() code

private void setDebitCard(){

debitCardNumber = (int)(ThreadLocalRandom.current().nextDouble()*Math.pow(10,12));

/* Also tried using

debitCardNumber = (int)(rand.nextDouble()*Math.pow(10,12));

debitCardNumber = (int)(Math.random()*Math.pow(10,12));

*/

debitCardPin = (int)(Math.random()*Math.pow(10,4));
}

Expected Result:

1)debitCardNumber should return a unique random 12 digit integer after every JAVA RUN

2)debitCardPin should return only 4 digit integer.

Actual Result:

1)debitCardNumber returns same 10 digit integer after every JAVA RUN

2)debitCardPin sometimes returns a 3 digit unique random integer.




Is there a way to clearly define a random number as a variable to use it in a function?

I cant clearly use a random int as a variable to use it for a comparison in my code. It seems to only throw out the first if statement no matter the random number produced.

from random import randint
rate = randint(0, 255)
wind = rate
print(rate)
if wind > 251:
    print("The hurricane is a category 5!")
elif wind <= 251 or wind >= 209:
    print("The hurricane is a category 4!")
elif wind <= 208 or wind >= 178:
    print("The hurricane is a category 3!")

The code is suppose to use the random number in a range to determine a rating of hurricane and print the message regarding. code works to certain extent.. no error message just always prints category 4 line no matter the random number the script produces




I get a syntax error using the python random library

I have a code that should print out a random number between 1 and 6 but i get a syntax error on line 10 on print random.randint(min, max). Where did i do wrong.

import random
min = 1
max = 6

roll_again = "yes"

while roll_again == "yes" or roll_again == "y" or roll_again == "Y":
    print ("Rolling the dices...")
    print ("The values are....")
    print random.randint(min, max)
    print random.randint(min, max)

    roll_again = raw_input("Roll the dices again?")

The error message i get when trying to run is "invalid syntax".




How do I generate a random string?

How do I generate a random string in C#? I would like to generate a random string containing X amount of letters/numbers/symbols




lundi 26 août 2019

Correct way to check for a random seed while allowing seed=0 [duplicate]

I would like to do the following:

def reorder_files(files, seed=None):
    if seed:
        random.seed(seed)
    random.shuffle(files)

However, this creates a bug when I run it with seed=0 because if 0 will not enter the if statement. What is the proper way to check for a random seed and shuffle if it's found, but allow 0 to be passed as an input?




How to fix numpy.random.choice output nested inside a for loop when importing from python file?

Problem:

I am trying to generate multiple lists of random numbers, of differing length. Inside a for loop of length num_baskets, I am using np.random.choice to generate a number for the length of each successive list n. Then, again, np.random.choice generates a list of random numbers of length n.

Expected output:

List of length num_baskets, with each item in the list another list of random length n.

Current output: List of length num_baskets but with uniform sublist lengths. However, each time I run the function, sublist length is different (but still uniform) per call.

What I have tried:

When I import the function from a python file, (e.g. from python_file import create_baskets there is deviation from expected output. Despite redefining n in each loop, all the output lists have the same length.

However, when I copy and paste the function and define it inside a jupyter notebook, I get the expected output with different list lengths.

My code:

import numpy as np

def create_baskets(num_baskets, max_basket_size, unique_items):
    """
    Create list of baskets of variable length >= 3

    Parameters
    ----------
    num_baskets: 
        number of baskets (sub-lists)
    max_basket_size: maximum basket size
        Baskets will be of size range(3, max_basket_size)
    unique_items:
        number of unique items

    Returns
    -------
    ret: list of "baskets", of randomly generated length
    """
    baskets = []
    for i in range(num_baskets):
        n = np.random.choice(range(3, max_basket_size), 1)
        basket = np.random.choice(range(0, unique_items), n, replace=False)
        baskets.append(basket)
    return baskets

I am not sure if there is something that fundamentally wrong/improveable with how the function is written or if it is a problem with the import.




generate random emails by rand function and seed on mysql

I have tried the following to update my emails and create some random emails, I don't know how to pick a domain name for random for my @domain.com emails. my query is wrong. could you let me know what I am doing wrong here?

update admin_user set email=CONCAT(
    substring('ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789', rand(@seed:=round(rand(@lid)*4294967296))*36+1, 5),
    (0.5 + RAND() * 6, 'live.com', 'scosche.com', 'apple.com', 'yahoo.com', 'gmail.com','mail.com'));




make a drive from fully fake files using "fsutil file createnew" on windows

i want to make a fully fake drive with random file names and random file sizes and random file types(by size , for example size 10 KB - 10MB in JPG or GIF type and size 5Mb - 500Mb in ZIP or RAR type and size 1Byte - 50KB TXT type and etc) i have an idea generate random numbers for size (in byte) and generate 4 digt words for file name and select file's type's by THE size (told in up) and make them to a file in a folder of listed folders (i can give you the list of folders) and in the final build the files using this command in CMD(if you can do it by other way's no problem)

code: fsutil file createnew %file path%/%file name%.%file type% %file size%

i want to make fake files with fake size and .... as many files with total size 240GB

i want to use fake files to make money from ransomers and Deceiving them

I give a percentage of the income to someone who makes these

THANKS.

makeing random numbers

fsutil file createnew %file path%/%file name%.%file type% %file size%

EXAMPLE:

fsutil file createnew c:/abc.mkv 1425612012




Generate two different random numbers in dart

How can i generate two different random numbers in dart?

I have generated two random numbers using code below.

int rand1 = Random().nextInt(16); int rand2 = Random().nextInt(16);

If rand1==rand2, how do i generate new random numbers until rand1!=rand2?




dimanche 25 août 2019

Find element where 40% is less and 40% is greater in O(n)

You are given an unsorted array A of integers. Your task is to find an element e such that at least 40% of all elements are smaller than or equal to e and at least 40% of all elements are larger than or equal to e. Devise an algorithm that outputs such an element e with probability at least 1/2, and otherwise just outputs “failure”. The algorithm is supposed to have linear running time (in the worst case).

Stupid approach:

Insert: A
with probability > 1/2 do:
    m = median of median(A)    O(n)
    check if constrain holds   O(n) using simple count 
    holds? 
        return m
    holds not
        return Failure
else:
    return Failure

There must be a smarter approach!




How do you generate a random boolean in C? [duplicate]

This question already has an answer here:

I've been trying to figure out a way to generate a random integer number in C within a range of 0 to 1 (for true/false values). I'm not sure if there is a way to do that.

I've tried to manually program the random number function with for and while loops

  int randomNumber;
  for (randomNumber = 0; randomNumber<=1; randomNumber++) {
      randomNumber = rand() % 100 + 1;
      printf("%d\n", randomNumber);
  }

I expect it to print out a random number (still analyzing this so not sure what it would print out), but I need the basis to getting the 0 and 1 for the true/false values.




samedi 24 août 2019

Reading 1 text file through another text file or scan each other in opposite directions, File 1 down, File 2 up

Using Python

I have 2 text files that opens side by side on the same line in terminal, but I want the file on the left to generate/iterate down the other file while the file on the right is stationary. I want to generate/iterate text file 1 through all of text file 2.

from itertools import izip

with open("textfile1") as textfile1, open("textfile2") as textfile2: 
for x, y in izip(textfile1, textfile2):
    x = x.strip()
    y = y.strip()
    print("{0}{1}".format(x, y))



example: What my script does now 

text file1 text file2         
  asdf9s     3kf44e
  wfb4rs     c4vb1b
  vl7rcs     orbds0
  cv96rv     medyt2
  cvrb5r     p5f4sd
  7dfxgd     

What I desire it to do:

textfile1 
 asdf9s
 wfb4rs
 vl7rcs
 cv96rv
 cvrb5r
 7dfxgd   
   ↓          ↑
          textfile2
           3kf44e  
           c4vb1b  
           orbds0  
           medyt2  
           p5f4sd  

textfile1 textfile2 
 asdf9s    3kf44e
 wfb4rs    c4vb1b
 vl7rcs    orbds0
 cv96rv    medyt2
 cvrb5r    p5f4sd
 7dfxgd      

textfile1        
 asdf9s
 wfb4rs
 vl7rcs
 cv96rv
 cvrb5r
 7dfxgd




C++ - writing code to pick up random lotto number exclude the past winning number

I would like to run a program that auto pick up 5 numbers from 45 (1 to 45), no duplicate number. The odd number must have higher drawn percentage. (mean the odd must be 3 numbers, even 2 numbers). And the result exclude all the past winning numbers (exclude arrays). Examples for past winning numbers: 09-17-36-44-49, 24-25-36-39-41, 06-20-37-43-44, 04-07-24-31-35, 01-03-22-32-40, Thank you

I can write a program to pick up random numbers only, don't known how to combine other conditions.




Use Mongodb query to find random document in nested field

I'm trying to get a random document from a nested field of addresses. I've read the post here already:

Random record from MongoDB

The addresses are a subfield of the properties field like so:

{"properties" : {"Address" : "1234 MAIN ST"}}

I'm looking forward to the answer.




How can I build a code to make BustaBit in python? Do I need to download another?

I am a highschool student in South Korea, and I am studying about gemble, expecinally BustaBit. As I have low knowledege of programing, I can't catch the way how to build program. PLZ help me....

I learned random number in Python

print(random.choice())

I don't need to hold a gemble website, so I wnat to build BustaBit in program.




Decode /dev/urandom bytes in Python + basic on encoding

I'm having fun in python with generating random bytes like this:

with open('/dev/urandom', 'rb') as f:
    randbytes = f.read(10)

but, to decoding, I don't know if i need to use utf-8, utf-16, base64 or others encoding. I already tried the listed above and no one work, except utf-16 but sometimes fail raising UnicodeDecodeError.

Moreover, I don't know precisely what's an encoding is, so can anyone explain the basic of encoding strings and decoding bytes in python? Thanks.




How to remove certain int from list within a list?

I'm trying to make a blackjack game as a beginners project. When I try to remove the card that's being dealt from the deck I get this: ValueError: list.remove(x): x not in the list. How can I fix this?

This is my code:

import random

deck = [[2, 2, 2, 2],
        [3, 3, 3, 3],
        [4, 4, 4, 4],
        [5, 5, 5, 5],
        [6, 6, 6, 6],
        [7, 7, 7, 7],
        [8, 8, 8, 8],
        [9, 9, 9, 9],
        [10, 10, 10, 10],
        [10, 10, 10, 10],
        [10, 10, 10, 10],
        [10, 10, 10, 10],
        [11, 11, 11, 11]
        ]

def deal_cards():
    number = random.choice(deck[0:][0:]) # selecting the number of the card
    card = random.choice(number) # selecting wich suit from the number sould be the card
    new_deck = deck.remove(card) # Here is the problem
    print(new_deck)
    print(card)

deal_cards()




How can I get a new random item from an array excluding the ones that were already picked? [duplicate]

I've seen other posts about the issue but the difference here is that I will need the new value stored in a different variable and use it as an index for another array to change some buttons text content.

 //The 'value' in this case is an array that contains 4 strings.

 const randomNumber0 =  Math.floor(Math.random()*value.length)
 const randomNumber1 =  Math.floor(Math.random()*value.length)
 const randomNumber2 =  Math.floor(Math.random()*value.length)
 const randomNumber3 =  Math.floor(Math.random()*value.length)


 //Here the value is used to change all of the button's text content based 
 on the randomly generated numbers from the above snippet 

 document.querySelector('#btn1').textContent = value[randomNumber0]
 document.querySelector('#btn2').textContent = value[randomNumber1]
 document.querySelector('#btn3').textContent = value[randomNumber2]
 document.querySelector('#btn4').textContent = value[randomNumber3]



 The problem here is that the buttons will get repetitive text content 
 as the numbers above will repeat most of the times.

 I would like to be able to pass the 'btn2''s index value another value 
 that gets randomized from the other numbers that were not already 
 selected for the 'btn1'. 

 For example. I will let document.querySelector('#btn1').textContent = 
 value[randomNumber0] unchanged and let's say randomNumber0 generates the 
 number 1. 

 For the 'btn2' I would like to have value[randomNumber1] where 
 randomNumber1 to generate a number that excludes the number 1, which was 
 picked by randomNumber0. So, the result should be a new random number 
 from this array[0, 2, 3].

 I would like as well to be able to repeat the process for 'btn3', and 
 'btn4'. 

 Many thanks in advance for clarifying this issue.




IndexError when using secrets.choice from dictionary

I have a dictionary of providers, which will contain elements like the one below:

{ 'p_4_0_0': {'technicians': ['683707d2-be18-49b7-bf67-a32048103ca1', '23d06b03-41f4-48cc-b83f-347ebfcb3084']}, 'p_4_0_1': {'technicians': ['d226a9b6-58f3-4f94-bf81-abd4dc825dca']}, ... }

The format used for the keys is string_id_level_pid, and I use secrets.choice to get a random element where the level part of the string is equal to the current level in my loop. However, I get the following error:

Traceback (most recent call last): File "path/to/file/graph.py", line 122, in generate_graph(100) File "path/to/file/graph.py", line 112, in generate_graph provider = providers[secrets.choice(list({k:v for (k,v) in providers.items() if (k.split('_'))[2] == str(level)}))] File "C:\Users\\AppData\Local\Programs\Python\Python37\lib\random.py", line 261, in choice raise IndexError('Cannot choose from an empty sequence') from None IndexError: Cannot choose from an empty sequence [Finished in 1.564s]

The full working code is here:

import networkx as nx
import matplotlib.pyplot as plt
from random import randrange,choices,randint
from pathlib import Path
import random
import secrets
import uuid
import math
import json
import os

# ============================================================================ #

# create a technician with id and provider id
def create_technician():
    return str(uuid.uuid4())

# create a provider with n technicians
def create_provider(region_id, level, number, n):
    id = 'p_'+str(region_id)+'_'+str(level)+'_'+str(number)

    # Create n technicians
    technicians = []
    for i in range(n):
        technicians.append(create_technician())

    return {id:{'technicians': technicians}}

def create_nmi_technicians(n):
    technicians = []
    for i in range(n):
        technicians.append(create_technician())
    return technicians

# Create report with parents + technician
def create_report(device_id, level, technician, parents):
    return {'id': device_id, 'level': level, 'technician': technician, 'parents': parents}

# n = number of field devices
def generate_graph(num_field_devices):
    max_chain_length = int(2*math.log(num_field_devices, 10))

    ## Info ##
    # ====== #
    # Field level = 0
    # NMI = max_chain_length-1

    nmi_level = str(max_chain_length-1)
    regions = {
        'USA': {'id': '1', 'NMI': {'level': nmi_level, 'acronym': 'NIST', 'technicians': create_nmi_technicians(5)}},
        'UK': {'id': '2', 'NMI': {'level': nmi_level, 'acronym': 'NPL', 'technicians': create_nmi_technicians(4)}},
        'China': {'id': '3', 'NMI': {'level': nmi_level, 'acronym': 'NIM', 'technicians': create_nmi_technicians(3)}},
        'France': {'id': '4', 'NMI': {'level': nmi_level, 'acronym': 'LNE', 'technicians': create_nmi_technicians(3)}}
    }

    # For each region, create a set of
    # 1 to m calibration service
    # providers for each level up to
    # the field level
    for region, data in regions.items():
        # Create providers dict
        providers = {}

        # For range between field (0) and
        # max_chain_length-2, create providers
        for i in range(0, max_chain_length-1):
            # Choose between 2 and 5 providers
            m = randint(2, 5)
            x = 0
            for j in range(m):
                # create provider with 1-3 technicians
                providers.update(create_provider(data['id'], i, x, randint(1,3)))
                x = x + 1

        # Add providers to region
        data.update({'providers': providers})

    #print(json.dumps(regions, indent=4))

    # Cool, now this is done, create the calibration
    # reports for the chain!
    devices = {}
    for level in range(max_chain_length):
        devices.update({level: []})
        # Field level
        if level == 0:
            for i in range(num_field_devices):
                devices[level].append(str(uuid.uuid4()))
        else:
            k = int(math.pow((2/3), level) * num_field_devices)
            for i in range(k):
                devices[level].append(str(uuid.uuid4()))

    # Create reports for these devices with parents + technician
    reports = {}
    for level,devs in devices.items():
        for device in devs:
            if level == 0:
                # Choose 2-3 parents from upper level
                parents = choices(devices[level+1], k=randrange(2,4))
            elif level == max_chain_length-1:
                # NMI level has no parents
                parents = []
            else:
                # Choose 1-2 parents from upper level
                parents = choices(devices[level+1], k=randrange(1,3))

            # Choose random region
            region = regions[secrets.choice(list(regions))]
            # Choose random provider at same level
            providers = region['providers']
            provider = providers[secrets.choice(list({k:v for (k,v) in providers.items() if (k.split('_'))[2] == str(level)}))]
            # Choose technician at the same level
            technician = secrets.choice(provider['technicians'])
            reports.update({'id': create_report(device, level, technician, parents)})

    print(reports)

## Run ##
# ===== #

generate_graph(100)




vendredi 23 août 2019

Generate/Iterate text file through another text file

Using Python

I have 2 text files that opens side by side on the same line in terminal, but I want the file on the left to generate/iterate down the other file while the file on the right is stationary. I want to generate/iterate text file 1 through all of text file 2.

from itertools import izip

with open("textfile1") as textfile1, open("textfile2") as textfile2: 
for x, y in izip(textfile1, textfile2):
    x = x.strip()
    y = y.strip()
    print("{0}\t{1}".format(x, y))

example: What my script does now

textfile1     textfile2          
 asdf9s        3kf44e             
 wfb4rs        c4vb1b             
 vl7rcs        orbds0             
 cv96rv        medyt2             
 cvrb5r        p5f4sd             
 7dfxgd        652fg9             

What I want it to do:

 textfile1 
  asdf9s
  wfb4rs
  vl7rcs
  cv96rv
  cvrb5r
  7dfxgd   
     ↓          textfile2 
                 3kf44e
                 c4vb1b
                 orbds0
                 medyt2
                 p5f4sd
                 652fg9  
 textfile1        
  asdf9s
  wfb4rs
  vl7rcs
  cv96rv
  cvrb5r
  7dfxgd




Get a random Struct object from a vector of Struct objects

i am currently working on a school program. I have 3 structs, student, subject and teacher.

What i want to happen is if a student is taking a subject then a teacher who can teach that subject is randomly allocated to it (The subject has a Teacher data member)

But what i am having the most trouble with is getting a random teacher from the vector of teachers who can teacher the subject. I would like to use the default_random_engine if possible ?

vector<Teacher>canTeachArchery;
vector<Teacher>canTeachBasicBouncing;
vector<Teacher>canTeachCountingForAnimals;

default_random_engine randTeacher;

//read from list of students
for(auto &s : studentList)
    {
//loop nested vector of subjects they have to take(int)
        for(int sb : s.subjectList)
        {
            if(sb == 1)
            {
                //assign random teacher here
            }
        }
    }






OverflowErro cannot fit 'int' into an index-sized integer

I am trying to convert an int of size n bits to bytes. This returns an overflow error

Trying to convert the int to bytes to be used later with TCP

def diffie_hellman():
    global a,g,n
    a = random.randint(1,5000)
    g = random.getrandbits(4000)
    n = sympy.randprime(1, 100)
    #print(a,g,n)

def diffie_send(a,g,n):
    clientsocket.send(bytes(a))
    clientsocket.send(bytes(g))
    clientsocket.send(bytes(n))


I expect it to just convert to bytes but again all i get is an overflow error.




how to shuffle a binary array a specific amount

I have a binary array. I want to shuffle it such that n percent of random elements stay in the same place and the rest get shuffled. Another way of putting it is, I have a binary array and I want to create a second array that is of same length and n percent similar when compared to the first using difflib

I'm using random.shuffle to shuffle the array but can't find info on the percent part of my question.

import random

array = [1,1,1,1,1,1,1,1,1,1,0,0,0,0,0,0,0,0,0,0]
random.shuffle(array)
print(array)




generate random numbers n times [on hold]

The task is to generate a list of random numbers within a range n times. I wrote the code and read it many times but cant figure out where it can possibly go wrong

import random

def generate_random_list(c,b,n):
    list = []
    for i in range(0,n):
        t = random.randint(c, b)
        list1 = list.append(t)
    return list1

heh = generate_random_list(1,100,20)




generate two random number with specific rules

I writing a code that generate two random integer and display the result of dividing the first number by the second. I want the first integer to be more than the second integer and the result of the division without remainder (an integer number)

I tried using do while loop and continue to change the integers until it generate the numbers as I wanted.

std::random_device device;
std::mt19937 rd(device());
std::uniform_int_distribution<int> random(1, 100);

int firstNumber;
int secondNumber;

do
{
    firstNumber = random(rd);
    secondNumber = random(rd);
}
while ((firstNumber < secondNumber) && (firstNumber % secondNumber != 0));

int result = firstNumber / secondNumber;

//print the integer to check it
std::cout << firstNumber << std::endl; 
std::cout << secondNumber << std::endl;

each time I run this code it always give me the first integer more than the second. but the division result will be with remainder




Find number of machines on at any given time, 1000 machines and 1/15 probability

My problem is this:

I have 1000 machines which turn on after a delay upon receiving the 'on' signal. The delay is set to be a random number of minutes between 0 and 15. So for any single machine, upon receiving the 'on' signal, the delay is any number of minutes drawn at random between 0 and 15.

I have to find out how many machines could be 'on' at any given time after they all receive the on signal at once.

For example, I model a simulation of these machines from time t=0 to t=10. At t=1 the 'on' signal is sent to every machine. I have to approximately model the number of machines on at each time step from t=1 to t=10.

My thinking was that since the delay is a uniform distribution from 0-15, I would just model the number of machines on directly proportional to the cdf of p=15. Which should just be a linear relationship? (aka a straight, diagonal line with minutes 0-15 on x axis and # of machines on in the y axis).

Thank you for your time!




Radomize order of elements but group them by classes

I'm looking for a way to randomize the order of a list of <li> with jQuery but keeping them grouped by their class. So if I have like 3 levels of <li> I want them to appear in random order inside my <ul> but also keep the <li> with the highest level (defined by its class) grouped together at the top, then having the second highest group also in random order next, etc.

I have managed to use a function to reorder the items randomly but am not capable to group them by level. My knowledge of jQuery is quite basic.

Sample code before randomized order

<ul id="myList">
    <li class="level3"><a href="">Link #1</a></li>
    <li class="level3"><a href="">Link #2</a></li>
    <li class="level3"><a href="">Link #3</a></li>

    <li class="level2"><a href="">Link #4</a></li>
    <li class="level2"><a href="">Link #5</a></li>
    <li class="level2"><a href="">Link #6</a></li>
    <li class="level2"><a href="">Link #7</a></li>

    <li class="level1"><a href="">Link #8</a></li>
    <li class="level1"><a href="">Link #9</a></li>
    <li class="level1"><a href="">Link #10</a></li>
    <li class="level1"><a href="">Link #11</a></li>
    <li class="level1"><a href="">Link #12</a></li>
</ul>

and I'm looking to have something like this order randomly generated.

<ul id="myList">
    <li class="level3"><a href="">Link #3</a></li>
    <li class="level3"><a href="">Link #1</a></li>
    <li class="level3"><a href="">Link #2</a></li>

    <li class="level2"><a href="">Link #6</a></li>
    <li class="level2"><a href="">Link #4</a></li>
    <li class="level2"><a href="">Link #7</a></li>
    <li class="level2"><a href="">Link #5</a></li>

    <li class="level1"><a href="">Link #10</a></li>
    <li class="level1"><a href="">Link #12</a></li>
    <li class="level1"><a href="">Link #9</a></li>
    <li class="level1"><a href="">Link #8</a></li>
    <li class="level1"><a href="">Link #11</a></li>
</ul>




The Randomized algorithm Parody

I was reading CLRS and I was stuck at question 5.1-2.

Describe an implementation of the procedure RANDOM(a,b) that only makes calls to RANDOM(0,1).What is the expected running time of your procedure, as a function of a and b?

The solution written here provides a complexity of O(lg(b-a)).

http://sites.math.rutgers.edu/~ajl213/CLRS/Ch5.pdf

I have too written an algorithm and I want some advice regarding it.

Random[a,b]
arr[]={a,....,b}
if(high-low <= 1)
 if(Random[0,1])
  new_arr[high]
  return
 else
  new_arr[low]
  return

if(Random[0,1])
 new_arr[a+b/2,.......,b]
else
 new_arr[a,...........,a+b/2-1]

My solution is Divide and Conquer based and that too with complexity O((b-a+1)).

Is my solution correct please tell?




jeudi 22 août 2019

Batch file set to pick a random file from preset categories is not picking a random file (keeps picking the last file!)

Good evening. I enjoy modding a game in my free time, it's one those games where individual mods are packed into zip files and loaded in by simply placing said zips into a certain folder. I have hundreds of these zips and was hoping to make a batch that would pick out a random mod for me each time I use it instead of having to pick through them all myself, while placing all the unused ones into a disabled folder that I made to keep everything not being used all in one place. Every mod was prefixed with a name referring to what category it'd belong to, for example 'weapon_shotgun_GiantAngryGun9000.zip' or 'character_huck_Clown.zip'

How this batch script would work is that first it'd take every file with the specified prefixes currently in the mod folder and put them all into the disabled folder. It would then go through every single file in the disabled folder that has all the specified prefixes, pick a random file from each category, and move them into the mod folder. Currently I've gotten my batch to do all that is explained, except rather than pick a random of each, it keeps picking the alphabetically last one from each prefix list. I believe it's because the Num var being used to designate the index for the entries in the File array is not being modified or read, and in-spite my best efforts I cannot get it to work the way I'm hoping.

Any advice or solutions is appreciated, thank you for reading.

setlocal EnableDelayedExpansion

SET modFolder="C:\Game\Mods\"
SET disabledFolder="C:\Game\Mods\Disabled\"
SET itemListIndex=0

::Prefix names
SET Prefix1=Weapon_Shotgun_
set itemList[%itemListIndex%]=%Prefix1%
set /A itemListIndex+=1

SET Prefix2=Character_ThisPerson_
set itemList[%itemListIndex%]=%Prefix2%
set /A itemListIndex+=1

SET Prefix3=Weapon_Rifle_
set itemList[%itemListIndex%]=%Prefix3%
set /A itemListIndex+=1


for /l %%G in (0 1 %itemListIndex%) do (
    if not "!itemList[%%G]!" == "" (
        set num=0
        for %%f in (!itemList[%%G]!*.zip) do (
           set /A num+=1
           set file[%num%]=%%f
        )
        set /A pick = !random! * %num% / 32768 + 1
        echo Moving "!file[%pick%]!" to the mod folder
        move "%disabledFolder%!file[%pick%]!" %modFolder%
    )
)

set file[%num%]=%%f is echoed as set file[]='[name of file]' instead of the expected set file['(index number)']='[name of file]'

the written echo says Moving !file[]! to the mod folder instead of the expected Moving (name of file) to the mod folder

The pick variable echos as blank, implying num or random are not valid




How to create a random sequence excepting a set of given values

I am using numpy and i want to generate an array of size n with random integers from a to b [upper bound exclusive] that are not in the array arr (if it helps, all values in arr are unique). I want the probability to be distributed uniformly among the other possible values. I am aware I can do it in this way:

randlist = np.random.randint(a, b, n)
while np.intersect1d(randlist, arr).size > 0:
    randlist = np.random.randint(a, b, n)

But this seems really inefficent. What would be the fastest way to do this?




Cant take string values from array

Dim animals() As String = {"Dog", "Cat", "Goat", "Cow"} Dim randomAnimal As Single = Int((UBound(Animals)+1)*Rnd())

Above code gives me a index value of an array instead of string

Tried the below one but it doesnt work

Dim intIndex As Integer= Int(randomAnimal)

Dim animals() As String = {"Dog", "Cat", "Goat", "Cow"}
 Dim randomAnimal As Single = Int((UBound(Animals)+1)*Rnd())  

Expected Result: Need to get any animal names in randomanimal from an array




While loop spaming output instead of printing output once?

I'm making a regular guess the number game. I'm having problems when I enter the guess and the program spams lower or higher instead of just typing it once, since I'm using a while True loop.

Here I'm just opening the CSV file and picking a random number.

import random

numbers = open('numbers_1-200.csv').read().splitlines()
number = int(random.choice(numbers))

Here I'm importing numbers 1-50 and picking two random numbers which will be whats added and subtracted from the original number. So the computer can write two numbers where the original number is between.

I know I could have just made the program pick two numbers from the first fifty lines in the same CSV that includes numbers from 1-200 but I choose to make another CSV wich only had the numbers 1-50.

differences = open('numbers_1-50').read().splitlines()
difference = int(random.choice(differences))
difference2 = int(random.choice(differences))
clue = number + difference
clue2 = number - difference2

This is my welcome screen wich also includes the main program on the last row¨

def welcome_screen():
    print('The number is between ' + str(clue) + ' and ' + str(clue2))
    print('Guess the number: ')
    guess_the_number()

This is my loop where you guess the number

def guess_the_number():
    guess = int(input())
    while True:
        if guess == number:
            print('Correct! The number was' + str(number))
            break
        elif guess > number:
            print('Lower')
        elif guess < number:
            print('Higher')

I'm getting outputs like theese:

The number is between 45 and 97
Guess the number: 72
lower
lower
lower
lower
lower
lower
lower
lower

How can I get a output where it just sais "lower" (or "higher") one time and then I can guess again?




Choose variable based on weighted probability

I have a list of variables with their weighted probability, as below:

Cloudy: 0.25
Sunny and warm: 0.25
Dry and cold: 0.125
Wet and cold: 0.25
Wet and warm: 0.375
Stormy/rainy: 0

In google sheets I am using the following function to select a variable based on these probabilities

=INDEX('WeatherChoices'!A2:A7,COUNTIF('WeatherChoices'!D2:D7,"<="&RAND())+1)

Where A2:A7 is the list of weather types and D2:D7 is the cumulative probabilities.

I am now trying to replicate this as a google script function but can't figure out an alternative to nested IF statements. I.e. generate a random number and if between two of the cumulative values choose the variable.

Is there are more elegant way of doing this in one step?

I have looked through the documentation but couldn't find anything other than the .random() function.




mercredi 21 août 2019

Maximum number of triplets two sequences have in common

I have two questions related to the same topic. I ran a simulation of 16000 sequences of 100 elements without repetitions with numbers between 1-4, for example: 124232143214223142314... These simulations were done to see what was the longest sequence in common between the sequences randomly generated and the pre-defined sequence. Participants were also asked to do this, to generate the sequence that they had previously learned without awareness.

I want now to do two things:

1) Determine what would constitute chance level. I was thinking about 
finding the 95th percentile as these scores would be 
highly unlikely. Hence if participant's scores were equal or above that, 
we could assume that they had knowledge. However, the random distribution 
is non-normal (rightly skewed). What would be the best approach?


2) Also, I want to find all the triplets in common between both sequences. 
So if we have sequence A: 12342134213421313242... and sequence B: 
21342134123214. It would have to count all the triplets in common 
including repetitions: 213, 134, 342, 213, etc.

I have looked at Chebyshev’s Theorem, but I am not sure if my data is adequate for it as mean = 5.42, SD = 1.05, kurtosis = 1.76 and skewness = 0.97.




C++ random non-repeated integers with weights

I want to efficiently generate a random sample of unique (non-repeated) integers in a (closed) range [0, rnd_max], with each number in the range being possible to choose, and each being associated with a sample weight (the more weight, the more likely it should be that the number is chosen, with probability exactly weight[i] / sum(weight[]) to be chosen next if it's not already taken in the sample).

I see C++ has std::discrete_distribution which can generate random weighted integers, but if I use it to generate random integers and discard repeated ones, when the sample to take is large relative to the length of the possible range, there will be a lot of failed samples which are already taken, resulting in a highly inefficient procedure. It's not clear to me if Floyd's algorithm has some extension to the case with sample weights (https://math.stackexchange.com/questions/178690/whats-the-proof-of-correctness-for-robert-floyds-algorithm-for-selecting-a-sin) - I personally cannot think of one.

It's also possible to e.g. use std::discrete_distribution dropping the weight to zero, or performing a partial weighted shuffle like in this answer: C++. Weighted std::shuffle - but in that answer, std::discrete_distribution is re-generated at each iteration and thus the running time becomes quadratic (it needs to cycle through the weights that are passed to it every time).

In wondering what could be an efficient weighted random sample for unique integers in C++, that would work well for varying sample sizes (e.g. from 1% to 90% of sampled numbers in the available range).

#include <vector>
#include <random>
#include <algorithm>

int main()
{
    size_t rnd_max = 1e5;
    size_t ntake = 1e3;

    unsigned int seed = 12345;
    std::mt19937 rng(seed);
    std::gamma_distribution<double> rgamma(1.0, 1.0);
    std::vector<double> weights(rnd_max);
    for (double &w : weights) w = rgamma(rng);

    std::vector<int> chosen_sample(ntake);
    // sampler goes here...

    return 0;
}




How can I increase the period of this PRNG?

I found this pseudo random number generator on Wikipedia and gave it a try, it's fast and works great for what I intend to use, but I would like it to have a bigger period, is there a way of improving it without making it slower?

#include <stdio.h>

long seed = 134515345;

long xorshift_rand(){
    seed ^= seed >> 13;
    seed ^= seed << 17;
    seed ^= seed >> 5;
    return seed;
}


int main()
{
    long start = xorshift_rand();
    long n = 0;
    while (start != xorshift_rand()){
        n++;
        if (n == 0){
            printf("overflow, good.");
        }
    }
    printf("xorshift_rand has a period of %ld", n);

    return 0;
}





What is the standard way to generate random numbers from different distributions in C#?

Basically the title.

I'm looking for a safe, standard-ish way that supports some basic distributions (uniform, normal, binomial, 'choice' (as in NumPy)) in C# without my having to play with converting the output from the provided uniform engine into the target distribution, if even possible.




How to see if player answers the value that corresponds to the key of that value

Write a simple quiz game that has a list of ten questions and a list of answers to those questions. The game should give the player four randomly selected questions to answer. It should ask the questions one-by-one, and tell the player whether they got the question right or wrong. At the end it should print out how many out of four they got right.

I've created one function that chooses one random key from my dictionary. My dictionary consists of 10 keys ('What is the capital of 'a' country) and each key has one answer (the capital of that country 'a'). Imagine i have (for now the 3 following functions).

import random

questions = {'What is the capital of Portugal':'Lisbon','What is the capital of France':'Paris','What is the capital of Germany':'Berlin','What is the capital of Netherlands':'Amsterdam','What is the capital of Belgium':'Brussels','What is the capital of Nepal':'Kathmandu','What is the capital of Spain':'Madrid','What is the capital of England':'London','What is the capital of Ireland':'Dublin','What is the capital of United_States':'Washington'} #dictionary with all questions and answers

#function that returns random question from dict
def questions_sorting():

  return random.sample(list(questions.keys()),1)

print(questions_sorting())


#function that asks player for capital input
def player_answer():

  return input('Digit your final answer - \n')

def countries_game():

  right_ans = 0 #counts the number of right answers 
  wrong_ans = 0 #counts the number of wrong answers
  num_questions = 0 #counts the number of questions displayed so far

  while num_questions < 4: #there will be four questions to be displayed
    cpu_question = questions_sorting()
    player_choice = player_answer()
    num_questions += 1

How can i see if a player enters the correct value for the the asked key?. Also in my question sort function i am sorting one question . How can i ask another question without the possibility of asking the same question?




Create random uniform vector

Given gunction float frand(), that generates uniformly-distributed random floating point value, in range [0.0, 1.0)

How can I create uniformly-distributed random 3D unit vector, and 4D unit quaternion? (so that a 3D vector lies on a unit sphere, and 4D - on a unit hypersphere, and vectors are uniformly-distributed among correspoiding surface)




How do I stop the same 'random' rows being selected across different computers?

I have some code which requires several simulations and I am hoping to run across separate computers. Each simulation requires identifying a random subset of the data to then run the analyses on. When I try to run this on separate computers at the same time, I get notice that the same rows are selected for each simulation. So if I am running 3 simulations, each simulation will identify the same 'random' samples across separatae computers. I am not sure why this is, can anyone suggest any code to get around this?

I show the sample_n function in dplyr below, but the same thing happened using the 'sample' function in Base R. Thanks in advance.

library(dplyr)
explanatory <- c(1,2,3,4,3,2,4,5,6,7,8,5,4,3)
response <- c(3,4,5,4,5,6,4,6,7,8,6,10,11,9)

A <- data.frame(explanatory,response)
B <- data.frame(explanatory,response)
C <- data.frame(explanatory,response)

for(i in 1:3)
{
 Rand_A = sample_n(A,8)
 Rand_B = sample_n(B,8)
 Rand_C = sample_n(C,8)
 Rand_All = rbind(Rand_A, Rand_B,Rand_C)
}




mardi 20 août 2019

Python: How to fix random seed inside process?

Here is example code:

import random
from multiprocessing import Process

random.seed(2019)

def f2():
    print('from f2:')
    v = random.randint(0, 10)
    a = random.randint(0, 10)
    print('v:', v)
    return v, a


def python_process_test():
    n_workers = 2
    workers = []
    for i in range(n_workers):
        p = Process(target=f2, args=())
        p.start()
        workers.append(p)

    for p in workers:
        p.join()


if __name__ == '__main__':
    python_process_test()

Output:

run 1:

from f2:
v: 6
from f2:
v: 4

run 2:

from f2:
v: 0
from f2:
v: 5




Is it appropriate to iterate over ints for random seed?

I want to make three random samples of a pandas dataframe, while seeding random so that I can retrieve the data again at a later time. Is it appropriate to iterate over a range of integers to do this, or could there be any side-effects from doing this? Does it take away from any of the pseudo-randomness? Here's the code I'm using:

for x in range(1,4): # int for the random seed
    randsamp = df.sample(frac=0.1, random_state=x)
    randsamp.to_csv("./sample"+str(x)+".csv",sep=';')




How to generate a good seed

I'm looking for a method to generate a good seed for generating different series of random numbers in processes that starts at the same time. I would like to avoid using one of the math or crypto libraries because I'm picking random numbers very frequently and my cpu resources are very limited.

I found few example for setting seeds. I tested them using the following method:

  1. short program that picks 100 random numbers out of 5000 options. So each value has 2% chance to be selected.
  2. run this program 100 times, so in theory, in a truly random environment, all possible values should be picked at least once.
  3. count the number of values that were not selected at all.

This is the perl code I used. In each test I opt in only one method for generating seed:

#!/usr/bin/perl
#$seed=5432;
#$seed=(time ^ $$);
#$seed=($$ ^ unpack "%L*", `ps axww | gzip -f`);
$seed=(time ^ $$ ^ unpack "%L*", `ps axww | gzip -f`);

srand ($seed);

for ($i=0 ; $i< 100; $i++) {
        printf ("%03d \n", rand (5000)+1000);
}


I ran the program 100 time and counted the values NOT selected using:

# run the program 100 times
for i in `seq 0 99`; do /tmp/rand_test.pl ; done  > /tmp/list.txt
# test 1000 values (out of 5000). It should be good-enough representation.
for i in `seq 1000 1999`; do echo -n "$i  "; grep -c $i /tmp/list.txt; done   | grep " 0" | wc -l


The table shows the result of the tests (Lower value is better):

count      Seed generation method
114    default - the line: "srand ($seed);" is commented ou
986    constant seed (5432)
122    time ^ $$
125    $$ ^ unpack "%L*", `ps axww | gzip -f`
163    time ^ $$ ^ unpack "%L*", `ps axww | gzip -f`

The constant seed method showed 986 or 1000 values not selected. In other words, only 1.4% of the possible values were selected. This is close enough to the 2% that was expected.

However, I expected that the last option that was recommended in few places, would be significantly better than the default.

Is there any better method to generate a seed for each of the processes?




add random number to multi fillenames

i have a folder: "songs" inside i have filles "song1singer1.txt", "song2singer2.txt"... -i want put a random number with 3 digits before fillename like: "145_song1singer1.txt","008_song2singer2.txt","049_song3singer3.txt"... and the next time i can use the same or other program and change the random number with another random number like: "872_song1singer1.txt","263_song2singer2.txt","492_song3singer3.txt"

thank you for your attention!

i am new in programming and start from Python3 (i use linux)

import os

def renamer(folder):
    dirname = folder
    files = os.listdir(folder)
    os.chdir(folder)
    for i in files:
        os.rename(i, dirname + '_' + i)

#import random
#print(random.randint(0,9))

renamer('testrename')




How to get random points from a circle?

I am trying to develop a project with a measurement sensor(simulated) with two motors one for horizontal movement and one for the vertical movement of the sensor. Following figure illustrates the example measurement in a 3D space, for horizontal angle (HA) of 0 degrees and vertical angle (VA) of zero degrees.

enter image description here

Since beam divergence is not considered in the software, I would like to form a footprint circle of diameter D at distance R from the sensor and shoot lasers 10 more times randomly within this circle from software(Cpp). How can I randomly select 10 points within this circle?(i.e how can I have ten random values for HA and VA so that :

HA - D/2 < HA_temp[10] < HA + D/2 
VA - D/2 < VA_temp[10] < VA + D/2

I would also like to know if there are any perticular libraries available to make it easy in Cpp or specifically in unreal engine 4.




lundi 19 août 2019

Is it possible to make a randomly generated variable in batch?

I'm currently setting up a game in batch that will be able to randomly generate a world with events and structures, however I can only come up with setting each coordinate up.

This would be fine if I had a very small world, and this is what I have generated for the first 9 chunks for biome data, however I plan on making the game's world virtually infinite. What I want to do is have it so that if a player gets 11 tiles away from an ungenerated chunk, it will generate it.

The code I have currently manually generates the first 9 chunks without generating the variables themselves. The generation take in account the tiles around it so the biome data makes sense (There aren't any glaciers in the Sahara), and this tends to make the biomes similar in temperature. For reference, each chunk is 50x50 tiles.

This is the code that I have now:

rem 0x 0y
set /A biomenum0x0y = %RANDOM% * 16 / 32768 + 1
rem 0x 1y
set /A nextbiomenum = %RANDOM% * 4 / 32768 + 1
if /I "%nextbiomenum%" EQU "1" set /A biomenum0x1y =  biomenum0x0y + 1
if /I "%nextbiomenum%" EQU "2" set /A biomenum0x1y =  biomenum0x0y + 0
if /I "%nextbiomenum%" EQU "3" set /A biomenum0x1y =  biomenum0x0y + 0
if /I "%nextbiomenum%" EQU "4" set /A biomenum0x1y =  biomenum0x0y - 1
rem 1x 1y
set /A nextbiomenum = %RANDOM% * 4 / 32768 + 1
if /I "%nextbiomenum%" EQU "1" set /A biomenum1x1y =  biomenum0x0y + 1
if /I "%nextbiomenum%" EQU "2" set /A biomenum1x1y =  biomenum0x0y + 0
if /I "%nextbiomenum%" EQU "3" set /A biomenum1x1y =  biomenum0x0y + 0
if /I "%nextbiomenum%" EQU "4" set /A biomenum1x1y =  biomenum0x0y - 1
rem 1x 0y
set /A nextbiomenum = %RANDOM% * 4 / 32768 + 1
if /I "%nextbiomenum%" EQU "1" set /A biomenum1x0y =  biomenum0x0y + 1
if /I "%nextbiomenum%" EQU "2" set /A biomenum1x0y =  biomenum0x0y + 0
if /I "%nextbiomenum%" EQU "3" set /A biomenum1x0y =  biomenum0x0y + 0
if /I "%nextbiomenum%" EQU "4" set /A biomenum1x0y =  biomenum0x0y - 1
rem 1x -1y
set /A nextbiomenum = %RANDOM% * 4 / 32768 + 1
if /I "%nextbiomenum%" EQU "1" set /A biomenum1xneg1y =  biomenum0x0y + 1
if /I "%nextbiomenum%" EQU "2" set /A biomenum1xneg1y =  biomenum0x0y + 0
if /I "%nextbiomenum%" EQU "3" set /A biomenum1xneg1y =  biomenum0x0y + 0
if /I "%nextbiomenum%" EQU "4" set /A biomenum1xneg1y =  biomenum0x0y - 1
rem 0x -1y
set /A nextbiomenum = %RANDOM% * 4 / 32768 + 1
if /I "%nextbiomenum%" EQU "1" set /A biomenum0xneg1y =  biomenum0x0y + 1
if /I "%nextbiomenum%" EQU "2" set /A biomenum0xneg1y =  biomenum0x0y + 0
if /I "%nextbiomenum%" EQU "3" set /A biomenum0xneg1y =  biomenum0x0y + 0
if /I "%nextbiomenum%" EQU "4" set /A biomenum0xneg1y =  biomenum0x0y - 1
rem -1x -1y
set /A nextbiomenum = %RANDOM% * 4 / 32768 + 1
if /I "%nextbiomenum%" EQU "1" set /A biomenumneg1xneg1y =  biomenum0x0y + 1
if /I "%nextbiomenum%" EQU "2" set /A biomenumneg1xneg1y =  biomenum0x0y + 0
if /I "%nextbiomenum%" EQU "3" set /A biomenumneg1xneg1y =  biomenum0x0y + 0
if /I "%nextbiomenum%" EQU "4" set /A biomenumneg1xneg1y =  biomenum0x0y - 1
rem -1x 0y
set /A nextbiomenum = %RANDOM% * 4 / 32768 + 1
if /I "%nextbiomenum%" EQU "1" set /A biomenumneg1x0y =  biomenum0x0y + 1
if /I "%nextbiomenum%" EQU "2" set /A biomenumneg1x0y =  biomenum0x0y + 0
if /I "%nextbiomenum%" EQU "3" set /A biomenumneg1x0y =  biomenum0x0y + 0
if /I "%nextbiomenum%" EQU "4" set /A biomenumneg1x0y =  biomenum0x0y - 1
rem -1x 1y
set /A nextbiomenum = %RANDOM% * 4 / 32768 + 1
if /I "%nextbiomenum%" EQU "1" set /A biomenumneg1x1y =  biomenum0x0y + 1
if /I "%nextbiomenum%" EQU "2" set /A biomenumneg1x1y =  biomenum0x0y + 0
if /I "%nextbiomenum%" EQU "3" set /A biomenumneg1x1y =  biomenum0x0y + 0
if /I "%nextbiomenum%" EQU "4" set /A biomenumneg1x1y =  biomenum0x0y - 1
echo %biomenumneg1xneg1y% is the biome for -1,-1
echo %biomenumneg1x0y% is the biome for -1, 0
echo %biomenumneg1x1y% is the biome for -1, 1
echo %biomenum0xneg1y% is the biome for 0, -1
echo %biomenum0x0y% is the biome for 0, 0 -the starting chunk-
echo %biomenum0x1y% is the biome for 0, 1
echo %biomenum1xneg1y% is the biome for 1, -1
echo %biomenum1x0y% is the biome for 1, 0
echo %biomenum1x1y% is the biome for 1, 1

The echo %biomenumneg1xneg1y% is the biome for -1,-1 part isn't going to be in the final game, it's just a debug thing I put there so I could make sure the numbers are working fine.

I want to be able to randomly generate variables, however as far as I'm aware you cannot put a variable inside of the variable name itself. I then plan on automatically assigning coordinates to chunks based on more variables inside variable names, maybe something like dividing the coordinates by 50 and rounding to the nearest 1 to make each variable assigned to a chunk.




Inserting 2 random bits of error in data using Systemverilog

I have achieved flipping of 1 bit in data (to insert 1 bit of error). Now I wish to flip 2 random bits in the data and make sure these two bits are not the same. How can this be done in SystemVerilog?




In C, how can I generate a random string from a seed?

I want to make a way to generate a seemingly random string from a random number in the form of a seed. But if I use the same seed I get the same result. I need a function that will generate large random strings from a number. A string with a thousand letters, from a number. Any number, no matter how simple. But if I use the same number, I will get the same string. For example, one would give me a 1000 long string of random looking numbers. 2 would give a whole different 1000 character long string. But if I give 1 again, I would get the same one.

I am not allowed to have a switch statement like:

switch(n) {
    case 1:
        return "943hfj9a0fw9ubhi0rq746gyheuipoyferewoirt ...";
        break;
    case 2:
        return "984h29uu384gu2hj34982h4m234uh2349238u9uh ...";
        break;
    ...
}

Does anyone know how to do this?




How do you make a random number gen between 1 and 20 in turtle

I have a code for a random colour chooser but not a random NUMBER. I need it to choose a random number 15 times each between 5 and 20, but the twist is that the total of all 15 numbers has to be equal to 227

I have a code for a random colour generator, but I can't figure out how to generate numbers and how to get a total of 227

import turtle
import random
turtle.bgcolor("black")
t = turtle.Pen()

t.width(4)
colours = ["yellow", "orange", "red"]
for i in range(60):
    t.pencolor(colours[random.randint(0,2)])
    t.forward(100)
    t.back(100)
    t.left(6)




Randomly select hour from dataframe

I have a hard time to randomly select rows from a dataframe. In general, choosing one row is not a problem using np.random.choice(data,size=1000). I assume that replacement=True. However, I need to randomly select an hour and as output, recieve the 4 rows of each quarter.

The dataframe to choose from is the following (1132 rows):

data=
                     Price  Consume    Feed
StartTime                                  
2018-07-04 02:00:00  45.80    67.91   67.91
2018-07-04 02:15:00  45.80    51.05   51.05
2018-07-04 02:30:00  45.80    46.12   46.12
2018-07-04 02:45:00  45.80    46.86   46.86
2018-07-11 05:00:00  43.80    43.49   43.49
2018-07-11 05:15:00  43.80    50.71   50.71
2018-07-11 05:30:00  43.80    48.19   48.19
2018-07-11 05:45:00  43.80    40.02   40.02

My desired output is something like this:

Assuming the random generator has "selected" 2018-07-11 05:00:00, the output would be

2018-07-11 05:00:00  43.80    43.49   43.49
2018-07-11 05:15:00  43.80    50.71   50.71
2018-07-11 05:30:00  43.80    48.19   48.19
2018-07-11 05:45:00  43.80    40.02   40.02

Is it possible to randomly select an dayhour directly from the dataframe and repeat this 1000 times? I am afraid that using an extra dataframe to select an hour and then looking the corresponding values up in the original dataframe will be too time consuming. I am confident that this should be doable in Python, but I couldn`t find any tips on this.

Thanks for any help!




dimanche 18 août 2019

How make filters in java lotofacil

I saw this code on the net right here but I would like to create some filters, for example, that show the sum of the listing line numbers, prime number, and many more ... And this code below is possible to decrease this size?

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

        int idCombinacaoLotofacil = 0;
        /* deixando p1<=11 serao todas as combinações; cada comentario serao os filtros*/
        for (int p1 = 1; p1 <= 2; p1++) {
            for (int p2 = p1 + 1; p2 <= 12; p2++) {
                for (int p3 = p2 + 1; p3 <= 13; p3++) {
                    for (int p4 = p3 + 1; p4 <= 14; p4++) {
                        for (int p5 = p4 + 1; p5 <= 15; p5++) {
                            for (int p6 = p5 + 1; p6 <= 16; p6++) {
                                for (int p7 = p6 + 1; p7 <= 17; p7++) {
                                    for (int p8 = p7 + 1; p8 <= 18; p8++) {
                                        for (int p9 = p8 + 1; p9 <= 19; p9++) {
                                            for (int p10 = p9 + 1; p10 <= 20; p10++) {
                                                for (int p11 = p10 + 1; p11 <= 21; p11++) {
                                                    for (int p12 = p11 + 1; p12 <= 22; p12++) {
                                                        for (int p13 = p12 + 1; p13 <= 23; p13++) {
                                                            for (int p14 = p13 + 1; p14 <= 24; p14++) {
                                                                for (int p15 = p14 + 1; p15 <= 25; p15++) {

                                                                    idCombinacaoLotofacil++;

                                                                   String pesquisa= String.format("%02d ", p1) +
                                                                                    String.format("%02d ", p2) +
                                                                                    String.format("%02d ", p3) +
                                                                                    String.format("%02d ", p4) +
                                                                                    String.format("%02d ", p5) +
                                                                                    String.format("%02d ", p6) +
                                                                                    String.format("%02d ", p7) +
                                                                                    String.format("%02d ", p8) +
                                                                                    String.format("%02d ", p9) +
                                                                                    p10 + " " +
                                                                                    p11 + " " +
                                                                                    p12 + " " +
                                                                                    p13 + " " +
                                                                                    p14 + " " +
                                                                                    p15;

                                                                    // Para acompanhar processo                                                                     
                                System.out.println(idCombinacaoLotofacil + " > " + pesquisa);

                                                                }
                                                            }
                                                        }
                                                    }
                                                }
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }
}

}




C program - How do I use the -r option within Xcode?

In this project for my C program I am requested to invoke it with -r (see below), but I am not sure how to do this in Xcode. Where is this done?

“ ...because the program uses a fixed seed — invoke it with -r if you want different output each time"

I presume the requirement is to use the -r as a command line argument. Am I right? This is my assumption.

This is what I have done.... Product > Scheme > Edit Scheme

Step 1 - Info tab Select Arguments Passed on Launch For Executable, navigate to the Terminal app Uncheck Debug executable

Step 2 - Arguments tab Add the following into the Arguments Passed On Launch field: ${BUILT_PRODUCTS_DIR}/${FULL_PRODUCT_NAME} --> ${BUILT_PRODUCTS_DIR}/${CoinToss1}

-r

But doing the above has not made any difference.

The -r option has not had any effect doing it this way, because it is still using the same seed and producing identical output for the coin tosses.

Project guidelines here: http://www.pcg-random.org/using-pcg-c-basic.html

Thanks




How to add random white noise to data

Suppose I've a column of data whose value ranges from -1.23 to +2.56. What I want is to add 10% random white noise to my data. I'm not sure how to do it in python, please help me with the code?




How to add exceptions in arraylist in java

I need to add exception so the numbers that already been generated cant be generated again.

So to generate a random number i try this. I make two arraylist with 14 numbers from 1 to 14 in each:

    ArrayList<Integer> Numbers1 = new ArrayList<Integer>();
    ArrayList<Integer> Numbers2 = new ArrayList<Integer>();
    Numbers1.add(0);
    Numbers1.add(1);
    Numbers1.add(2);
    Numbers1.add(3);
    Numbers1.add(4);
    Numbers1.add(5);
    Numbers1.add(6);
    Numbers1.add(7);
    Numbers1.add(8);
    Numbers1.add(9);
    Numbers1.add(10);
    Numbers1.add(11);
    Numbers1.add(12);
    Numbers1.add(13);
    Numbers1.add(14);
    Numbers2.add(0);
    Numbers2.add(1);
    Numbers2.add(2);
    Numbers2.add(3);
    Numbers2.add(4);
    Numbers2.add(5);
    Numbers2.add(6);
    Numbers2.add(7);
    Numbers2.add(8);
    Numbers2.add(9);
    Numbers2.add(10);
    Numbers2.add(11);
    Numbers2.add(12);
    Numbers2.add(13);
    Numbers2.add(14);

then i make a Random that takes 1 number from each arraylist

   Random Calc = new Random();
    Num1 = Numbers1.get(Calc.nextInt(Numbers1.size()));
    Num2 = Numbers2.get(Calc.nextInt(Numbers2.size()));

then i make an integer that multiply the two random numbers that been choosen randomly

    FinalInt = Num1 * Num2;

then i have an HashMap with 200 Strings:

 HashMap<Integer, String> points = new HashMap<Integer, String>();
    points.put(1, "String1");
    points.put(2, "String2");
    points.put(3, "String3");
    points.put(4, "String4");
    points.put(5, "String5");
    //And so on until 200 
    TextView textview1.setText(points.get(FinalInt))

If the FinalInt generate number 1 it will set textview1 to "String1". So i need if FinalInt is 1 again to redo num1 * num2 so its not 1.




Xcode for C Implementation - Random Generator - Environment Problems

When you have a few files (see below), how do you get them all working inside Xcode for a C implementation?

These are the files that I’ve been given for this project: 
pcg_basic.c 
pcg_basic.h 
pcg32-demo.c

Project guidelines: http://www.pcg-random.org/using-pcg-c-basic.html

I am also unclear what should be copied to the main.c file. Can't get a grasp on this.

Apparently you also need to link the code with the pcg_basic.o. (not sure how to do that, either)

I know the code does work because it was developed by an expert in this space. But everything I try in Xcode ("fails to build"), so I presume it must be the way I've set things up.

What am I doing wrong?

[*Student here. I am totally new to programming. Thanks]

error snippet 1

error snippet 2




samedi 17 août 2019

Hangman game, my code picks a word then generates a hidden word length then picks another word after that for some reason?

so my script should run on page load √ then generate a word √ then hide the word with a string of dashes equal to its length √ but then it picks another word to replace the first one?

Ive tried to move the hiddenword generator around in my document but without it being in the start function it wont make the string i need.

function start() {
    usedletters = [];
    word = words[Math.floor(Math.random() * words.length)];
    life = 9;
    console.log(word)
    for (var i = 0; i < word.length; i++) {
        hiddenword[i] = ("-");
        console.log(word)
        console.log(hiddenword)
    }
    // all of this gets the id from main document then pushes what javascript generates
    document.getElementById("win").innerHTML = (wincount);
    document.getElementById("hidden").innerHTML = (hiddenword);
    document.getElementById("used").innerHTML = ("");
    document.getElementById("life").innerHTML = ("9");
    document.getElementById("victory").hidden
}


start();

I really just need it to pick the first word and not select a new one.




Why doesn't the if statement print 'well done' and why does the loop repeat out questions()

I wanted to make a game where in which you get three turns to guess the selected number, from the computer. However it will never say well done even if you get the number right (already tested using printf statements) and the loop will also mess up by either continuing or running twice.

I've tried removing the break. I've put in printf statements to check if randomise and questions actually store the correct values and they do.

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

int questions(){

int num;

printf("Chose a number between one - ten: ");
scanf("%d",&num);

return num;

}

int randomise() {

int roll;

srand(time(NULL));

roll = rand()%10 + 1;
return roll;

}

int main(){

int chosenNum, enteredNum, i;

chosenNum = randomise();
enteredNum = questions();

for(i = 0; i < 10; i++){
 if(chosenNum != enteredNum){

    questions();
    break;

   }
   else if(chosenNum == enteredNum){

      printf("WELL DONE !!!");

   }
}

return 0;

}

Zero errors and Zero warnings. and the outcome should be that you get greeted with well done.




Can't get stable result with copying random values from array to an object

So I've been in process of creating a bot for a tournament and I got stuck on the part where I want to split players in pair for play-off-style tournament. I just want to take 2 random players, write them into and array and write it as a value to a key as a round id for an object.
Here's the code:

var users = inc.funcs.getDatabase() //Getting a raw array of users (using my func that's basically a simplified fs.readFileSync func)
var tournamentPairs = new Object() //Object initialization

var id = 1
for (var i = 0; i < 16; i = i + 2) {
   var first = Math.floor(Math.random() * (users.length + 1)) //Randomizing 2 indexes
   var second = Math.floor(Math.random() * (users.length + 1))

   var player1 = client.users.get(users[first]) //Getting the players by id 
   var player2 = client.users.get(users[second])

   tournamentPairs[id++] = [player1.id, player2.id] //Writing to the object

   users.splice(first, 1)
   users.splice(second, 1)
}
console.log(tournamentPairs)

It works perfectly on the outside, but has a bad habit of duplicating users and I once could have a gamergod98 vs gamergod98 for example. I tried console.log this crap but it often get an error when trying to console.log player2 because it's undefined for some reason. If I try to print users[second] I get undefined thought it never happened for the fist player. So I try different ways to prevent situations like this: first == second. Long story short it didn't help much.
I have 9 days 'till tournament starts, any ideas on how to improve this code?




Karger Algorithm with weights

Assume that we are given an undirected, unweighted graph G= (V, E) and some cost function c:E→R>0 assigning a positive cost c(e) to each edge e∈E. The goal is to compute a minimum cut of G of minimum cost (i.e., a minimum cost cut among the cuts consisting of the smallest number of edges). Give an algorithm which with high probability finds such a minimum cost minimum cut in polynomial time. What is the running time of your algorithm? Hint: Karger Algorithm

Approach I: Do Karger n^c times (still polynomial, raises exponent on n of c) and compare resulting min cuts. with c >=1

Approach II: When Karger is taken its edges for Contraction, raise probabilty of High weights. Doesnt affect Runtime

or even a combination of both?




RecyclerView Adapter return limited randomly sorted items

I need to check if the items in the adapter is greater than the limit number, then display the items according to that limit number else return the item count, I do this like below:

public int getItemCount() {
    int ITEMS_LIMIT = 6;
    if(this.articles.size()  >= ITEMS_LIMIT){
        return ITEMS_LIMIT;
    } else {
        return this.articles.size();
    }
}

However, I need the item from the list be randomly displayed: Example if the limit is 6 and the items in the list is 10, then only display 6 items radomly sorted from the list. I tried with the code below, but the app hangs then crashes with IndexOutOfBoundException.

 public int getItemCount() {
        Random random = new Random();
        int ITEMS_LIMIT = 6;
        if(this.articles.size()  > ITEMS_LIMIT){
            return random.nextInt(ITEMS_LIMIT);
        } else {
            return this.articles.size();
        }
    }

Could somebody help me solve this?




Generating random Bootstrap patterns

For my research project, I need templates of webpages with Bootstrap and their screenshot, templates are in HTML format and are composed of different Bootstrap elements (navbar, cards, ...) in a random way.

I am looking for some Python library that will generate different possibilities of combinations of Bootstrap pages, so I can get the largest number of them

I expect to get a number of pages where each one contains a random set of Bootstrap elements in an organized way.




How do we assign the URL to the respective image which is randomly appearing?

The aim is to assign the respective URL to the respective image which is randomly appearing every 1 second on a web page in J Query.

so was wondering how do i combine both random items together? I probably did the wrong way of combining them by concatenation. hope to get some help here!


<script>
var img_arr = ["adidas_logo.jpg", "apple_logo.jpg","Changi_airport.jpg","starbucks.jpg"]

var links_arr =["https://www.adidas.com.sg/" , "https://www.apple.com/sg/" , "https://www.changiairport.com/","https://www.starbucks.com.sg/"]

var current = 0;
var current1 = 0;

setInterval(function()
{   
    var pic = Math.floor(Math.random()*img_arr.length);
    var links = Math.floor(Math.random()*links_arr.length);

    $("#image_slider").attr("src",img_arr[pic] +" "+ links_arr[links]);

    current = (img_arr[pic]< img_arr.length -1)? img_arr[pic] + 1 : 0;
    current1 = (img_arr[pic]< img_arr.length -1)? links_arr[links] + 1 : 0;

},1000);

the expected output is the random images displayed when clicked , it will go to the correct URL. currently my error is it is random but the img src and URL are combined so the image doesn't appear.




vendredi 16 août 2019

Python no longer generating random numbers from function

I have written a program that generates a random integer from a large range and puts that number into another part of the function. It worked very well before but suddenly stopped. The program itself finally works the way it should be instead of generating random data it just repeats the same one over and over.

Since randomness is my goal I played with random.random and random.choice but I had the same result.

@app.route('/button', methods=['POST', 'GET'])
def roulette():
    f = open("GutProject.txt", "w")
    for x in range(1):
        y = (random.choice(0, 59000))
        text = strip_headers(load_etext(y)).strip()
        f.write(text)
    return send_file('GutProject.txt',
    mimetype='text/plain',
    attachment_filename='GutProject.txt',
    as_attachment=True)

I would like to generate a randomly created txt file based on the integer chosen. It has worked in the past with the same python function so I can't figure out why it's not working now.




Effective algorithm to random 4 integers less than a max such as 100_000

Here is my try:

public static void main(String[] args) {
    // Max 100_000
    System.out.println(Arrays.toString(randomFour(100_000)));
}

public static int[] randomFour(int max) {
    Random r = new Random();
    int[] four = new int[4];

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

        // 1-max
        while (true) {
            four[i] = 1 + (int) (r.nextFloat() * max);

            boolean dup = false; // check j: 0 -> i-1
            for (int j = 0; j < i; j++) {
                if (four[j] == four[i]) {
                    dup = true;
                    break;
                }
            }
            if (dup == false) {
                break;
            }
        }
    }
    return four;
}

The algorithm is working fine. I guest there is a better algorithm for this problem, especially to a very big max number. Thank you!