mardi 30 juin 2020

Reverse words without changing capitals or punctuation

Create a program with the lowest amount of characters to reverse each word in a string while keeping the order of the words, as well as punctuation and capital letters, in their initial place.

By "Order of the words," I mean that each word is split by a empty space (" "), so contractions and such will be treated as one word. The apostrophe in contractions should stay in the same place. ("Don't" => "Tno'd").

(Punctuation means any characters that are not a-z, A-Z or whitespace*).

Numbers were removed from this list due to the fact that you cannot have capital numbers. Numbers are now treated as punctuation.

For example, for the input:

Hello, I am a fish.

it should output:

Olleh, I ma a hsif.

Notice that O, which is the first letter in the first word, is now capital, since H was capital before in the same location.

The comma and the period are also in the same place.

More examples:

This; Is Some Text!

would output

Siht; Si Emos Txet!

public static String reverseWord(String input) {

        String words[]=input.split(" ");
         StringBuilder result=new StringBuilder();
       
          for (String string : words) {
              String revStr = new StringBuilder(string).reverse().toString();
              result.append(revStr).append(" ");
          }
        return result.toString().trim();
        
    } 



stackoverflowerror with recursive method that keeps on generating a series of random numbers that must meet certain set of conditions

I'm trying to write a program that implements a random number generator based on a lottery game. The game consist of 7 unrepeating numbers that has to be drawn among a range of 1-34 numbers. The interesting part is that it must meet a certain set of conditions.

The two conditions I have given is namely the odd/even numbers ratio and the distance between ball nr.1 and nr. 7. We asume that the numbers are sorted.

My problem is that I'm getting a stackoverflowerror after a few executions when I'm setting the odd/even ratio relatively low and the distance between ball nr.1 and nr.7 in a similiar way.

Here is my part of the code that regulates the two given conditions respectively:

Java

    //this method will set the maximum allowed distance 
    //between ball nr. 1 and nr.7
    public boolean diff1to7(ArrayList<Integer> ticket) {
        if (ticket.get(6) - ticket.get(0) > 19) {
            return true;
        }
        
        int diff = ticket.get(6) - ticket.get(0);
        System.out.println(diff);
        
        return false;   
    }
    
    //this method will set the ratio between odd and even numbers
    //the sum of odd and even numbers will always add up to 7 since there are
    //7 seven numbers to be drawn
    public boolean even_odd(ArrayList<Integer> ticket) {
        int countOdd = 0, countEven = 0;
        
        for (Integer nr : ticket) {
            if(nr % 2 != 0) {
                countOdd++;
            } else {
                countEven++;
            }
        }
        
        if(!(countOdd == 3 && countEven == 4)) {
            return true;
        }
        System.out.println(countOdd + " + " + countEven + " = " + (countOdd + countEven));
        
        return false;   
    }

When I'm writing

if (ticket.get(6) - ticket.get(0) > 16) {
   return true;
}

and

if(!(countOdd == 7 && countEven == 0)) {
    return true;
}

I'm expecting to get

 [1, 3, 5, 7, 9, 11, 13]
 [1, 5, 9, 11, 13, 15, 17]
 [3, 5, 9, 11, 13, 15, 17]
 ......................etc

What I get is stackoverflowerror. This seems to work fine under normal conidtions such as setting the odd/even ration to 3/4 instead of 7/0 and the range between ball nr.1 and nr.7 not too short, for instance: > 28.

Here is my whole code:

public class MainController implements Initializable {
    @FXML
    private AnchorPane anchorPane;
    
    @FXML
    private Label myMessage;
    
    @FXML
    private Button clickme;
    
    public void generateBtnClicked(ActionEvent event) {
        ArrayList<Integer> ticket = generateRandom(draw());
        String ticketString = ticket.toString();
        myMessage.setText(ticketString);
    }

    @Override
    public void initialize(URL arg0, ResourceBundle arg1) {
        
    }
    
    //this is a method for generating a random lottery ticket
    //that consist of 7 unrepeating numbers
    public ArrayList<Integer> draw() {
        ArrayList<Integer> ticket = new ArrayList<>(7); 
        Random myRandom = new Random();
        int randNR;
        
        while (ticket.size() != 7) {
            randNR = myRandom.nextInt(34) +1;
            if(ticket.isEmpty() || !ticket.contains(randNR)) {
                ticket.add(randNR);
            }
        }
        Collections.sort(ticket);
        return ticket;
    }
    
    //this is a recursive method that keeps on calling on draw method
    //until all conditions are fulfilled
    public ArrayList<Integer> generateRandom(ArrayList<Integer> ticket) {
        
        //distance/range between ball nr.1 and nr.7 condition
        if (diff1to7(ticket)) {
            return generateRandom(draw());      
        }
        
        //ratio of odd and even numbers condition
        if (even_odd(ticket)) {
            return generateRandom(draw());  
        }
        
        return ticket;
    }
    
    //this method will set the maximum allowed distance 
    //between ball nr. 1 and nr.7
    public boolean diff1to7(ArrayList<Integer> ticket) {
        if (ticket.get(6) - ticket.get(0) > 16) {
            return true;
        }
        
        int diff = ticket.get(6) - ticket.get(0);
        System.out.println(diff);
        
        return false;   
    }
    
    //this method will set the ratio between odd and even numbers
    //the sum of odd and even numbers will always add up to 7 since there are
    //7 seven numbers to be drawn
    public boolean even_odd(ArrayList<Integer> ticket) {
        int countOdd = 0, countEven = 0;
        
        for (Integer nr : ticket) {
            if(nr % 2 != 0) {
                countOdd++;
            } else {
                countEven++;
            }
        }
        
        if(!(countOdd == 7 && countEven == 0)) {
            return true;
        }
        System.out.println(countOdd + " + " + countEven + " = " + (countOdd + countEven));
        
        return false;   
    }
}

Please I need help to rewrite this code to work effectively and avoiding stackoverflowerror. I'm thinking of adding further "conditions" to this recursive method, but this needs to be fixed first.

Thanks in advance.

JT




How to generate random numbers with generalize extreme value distribution between min and max value in Matlab?

I have 16 value with distributed by generalized extreme value. I have k, sigma and mu of this data. I want to increase the data with this distribution between 20 and 21. How can I do it in Matlab, may I get your help with code sharing?




Create an Array with random numbers

How I do create an array of size 256 with sorted random numbers in the main method? I want to create an array that randomly generates numbers between 1-256, the size would be 256 as well which means it would have 256 numbers in the array and they're sorted. My code only returns me zero?

public class Array {
    public static void main(String args[]) 
    { 
        double[] randomarray = new double[256];
        for(int i = 0; i<randomarray.length;i++)
            randomarray[i] =  Math.random();
        
        for (int i = 0; i<randomarray.length;i++)
            System.out.println(randomarray[i]);
    }
}



vb6 random number no duplicates & no zeros

I am using vb6 and trying to generate a random number or String with this format
S1 = "378125649"

I have three requirements NO Duplicates Values & No Zeros & 9 charcters in length
I have approached This two very different ways the random number generator method is failing the FindAndReplace works but is too much code

The questions are
How to fix the GetNumber method code to meet the three requirement?
OR
How to simplify the FindAndReplace code to reflect a completely new sequence of numbers each time?

GetNumber code Below

Private Sub GetNumber()

Randomize
Dim MyRandomNumber As Long 'The chosen number
Dim RandomMax As Long 'top end of range to pick from
Dim RandomMin As Long 'low end of range to pick from
'Dim Kount As Long 'loop to pick ten random numbers

RandomMin = 1
RandomMax = 999999999

MyRandomNumber = Int(Rnd(1) * RandomMax) + RandomMin
lbOne.AddItem CStr(MyRandomNumber) & vbNewLine
End Sub

The FindAndReplace Code Below

Private Sub FindAndReplace()

Dim S4 As String
S4 = "183657429"
Dim T1 As String
Dim T2 As String
Dim J As Integer
Dim H As Integer

J = InStr(1, S4, 2)
H = InStr(1, S4, 8)
T1 = Replace(S4, CStr(J), "X")
T1 = Replace(T1, CStr(H), "F")


If Mid(T1, 8, 1) = "F" And Mid(T1, 2, 1) = "X" Then
T2 = Replace(T1, "F", "8")
T2 = Replace(T2, "X", "2")
End If

tbOne.Text = CStr(J) & " " & CStr(H)
lbOne.AddItem "Original Value " & S4 & vbNewLine
lbOne.AddItem "New Value      " & T2 & vbNewLine

End Sub




Sample a Pandas Df and replace a column with 'NaN' values. Not Working

I have a pd.Dataframe with 3 columns [str_name,target,sec_id]

Currently all values of the col sec_id are -1. I want to sample ~100 rows and replace the values of this column to NaN.

Following is the code

sample_rows = new_pd[new_pd['sec_id'] == -1].sample(n=130)
sample_rows.sec_id = float('NaN')
new_pd.update(sample_rows)

Consequently, I want to drop these from the new_pd. So, I did following

new_pd = new_pd[new_pd['sec_id'].notna()]

But it seems like the number of rows of the new_pd is still the same. Any idea whats happening here ?




Random/shuffle data using streambuilder? flutter

is there a way to randomise data coming from firestore? i am using a streambuilder and a staggeredview.countbuilder . i could not find any docs about it! right now the data comes in the last signup order into the stream. can someone help? best regards everybody

this is my code

StreamBuilder(
  stream: Firestore.instance.collection('users').where('myCity', isEqualTo: city).snapshots(),
  builder: (context, snapshot) {
    if (!snapshot.hasData) return Text('Loading');
    return  Container(
      child: StaggeredGridView.countBuilder(
        crossAxisCount: 2,
          crossAxisSpacing: 12,
          mainAxisSpacing: 12,
          itemCount: snapshot.data.documents.length,
          itemBuilder: (BuildContext context, int index) {
            User user = User.fromDoc(snapshot.data
                .documents[index]);
            return GestureDetector(
              child: Container(
                decoration: BoxDecoration(
                    color: Colors.transparent,
                borderRadius: BorderRadius.all(Radius.circular(12))

              ),
                child: ClipRRect(
                  borderRadius: BorderRadius.circular(21),
                  child: Image.network(user.profileImageUrl,fit: BoxFit.cover,)
                ),
            )
            );
            },
        staggeredTileBuilder: (index){
          return StaggeredTile.count(0, index.isEven? 1.2 :1.4);
      },
          ),
    );
  },
);



Random sample of N unique customer IDs while ensuring the more one transacts the higher chances of being selected

I have a table called "transaction_history", containing millions of transactions with the following columns: column 1: customer_id column 2: transaction date

In this table one customer may have x amount of transactions, where X >= 1

What I am looking to do is get a random sample of n (n is the number of prizes to allocate to n winners)unique customer IDs BUT ensure that the more frequent the transactions for a given customer the higher their chances of being selected a winner.

I have tried the following: 1- the straight forward dplyr::sample_n(transaction_history, size = ...) which leads to sample with duplicate customer_ids

2- Transactions %>% dplyr::distinct(customer_id) %>% dplyr::sample_n(transaction_history, size = ...) which does not give frequent customers a higher chance

3- Sampling from per customer_id groups before sampling again which also defeats this goal.

Any help will be greatly appreciated.

Thanks




How do I make count the number of random guesses it takes to guess a name without repetitions?

From someone else's question that got deleted, I finally understood what he wanted.

Basically he wanted to count the number of unique guesses to get the correct name.

import time
import random
chars = string.ascii_letters + string.digits + '!@#$£%^&*()[]{}.,~-_\\'
name = input("what is the name you want guessed? ")
start_time = time.time()
passwordlen = len(password)
nameguess = ''.join(random.choice(chars) for i in range(namelen))
x = 1
while nameguess != name or x != 10000000:
    x += 1
    nameguess = ''.join(random.choice(chars) for i in range(namelen))
    print("guess: " + nameguess + " attempt: " + str(x))
if nameguess == name:
    print(f"it only took {x} times")
elif x == 10000000:
    print("i give up")

my first idea was to write it into a file, but i came into a logically problem, how do i make it reset the file everytime the code runs, then append to the file for every guess in that run, and how do I make it after it checks if the current guess has already been guessed, to check the new guess, I don't know if this makes sense

How do I make it reset the file for every time I hit 'run' on the code but append to the file for every guess

And How do I make it go back in code, so I want it to go:

(clearfile)
while nameguess != name
nameguess = ''.join(random.choice(chars) for i in range(namelen))  <------      
with open("guesses.txt", 'r') as guess:                                   |
    if nameguess in guess.read():                                         |
       --------------------------------------------------------------------
    elif nameguess not in guess.read():
        (appened name to list)
       continue

How do I make it not guess the same thing twice is the bottom line, I apologise that it was unclear




Deterministic order when using an order by random with postgresql

I'm using a query like:

SELECT * FROM items ORDER BY RANDOM()

All is well if the number of rows is low. In my tests however, I would like to have something reproducible to verify. This is why I'm seeding the random number generator:

SELECT setseed(0.123);
SELECT * FROM items ORDER BY RANDOM();

It's nice and working well. It looks like the order is same time on each execution. Except that it's not completely reproducible. In some cases, the test succeeds and I get the expected order and result. In some execution of the same test, I don't. Why is that?




How to select a whole string from a list and not only a single letter? [closed]

I'm applying RandomSearchCV for a deep learning model. Therefore, I have to choose randomly parameters from a list. E.g.:

import secrets

activation = ['softmax', 'softplus', 'softsign', 'relu', 'tanh', 'sigmoid', 'hard_sigmoid', 'linear']
activation = secrets.choice(activation)

or

import random

activation = ['softmax', 'softplus', 'softsign', 'relu', 'tanh', 'sigmoid', 'hard_sigmoid', 'linear']
activation = random.choice(activation)

I've already tried also:

activation = {'d':['softmax', 'softplus', 'softsign', 'relu', 'tanh', 'sigmoid', 'hard_sigmoid', 'linear']}
activation = secrets.choice(activation['d'])

But every time I get this as a result when running the code:

    Traceback (most recent call last):
  File "/home/shiftone/miniconda3/lib/python3.7/site-packages/sklearn/model_selection/_validation.py", line 531, in _fit_and_score
    estimator.fit(X_train, y_train, **fit_params)
  File "/home/shiftone/miniconda3/lib/python3.7/site-packages/keras/wrappers/scikit_learn.py", line 142, in fit
    self.model = self.build_fn(**self.filter_sk_params(self.build_fn))
  File "/home/shiftone/vsd-shiftone/treino.py", line 244, in conv1D
    model.add(TimeDistributed(Conv1D(filters=24, kernel_size=10, activation=activation), input_shape=(1, 40, 17)))
  File "/home/shiftone/miniconda3/lib/python3.7/site-packages/keras/legacy/interfaces.py", line 91, in wrapper
    return func(*args, **kwargs)
  File "/home/shiftone/miniconda3/lib/python3.7/site-packages/keras/layers/convolutional.py", line 353, in __init__
    **kwargs)
  File "/home/shiftone/miniconda3/lib/python3.7/site-packages/keras/layers/convolutional.py", line 115, in __init__
    self.activation = activations.get(activation)
  File "/home/shiftone/miniconda3/lib/python3.7/site-packages/keras/activations.py", line 227, in get
    return deserialize(identifier)
  File "/home/shiftone/miniconda3/lib/python3.7/site-packages/keras/activations.py", line 208, in deserialize
    printable_module_name='activation function')
  File "/home/shiftone/miniconda3/lib/python3.7/site-packages/keras/utils/generic_utils.py", line 167, in deserialize_keras_object
    ':' + function_name)
ValueError: Unknown activation function:n

As long as a can see it is not selecting the whole item of the list, but a single letter.




Shuffle dictionaries of sets in Python

I am trying to shuffle dictionaries of sets. This is the set which I want to shuffle randomly

{'1': ['IMG_0001.png', 'IMG_0002.png', 'IMG_0003.png', 'IMG_0004.png'], 
 '2': ['IMG_0020.png', 'IMG_0021.png', 'IMG_0022.png', 'IMG_0023.png'], 
 '3': ['IMG_0051.png', 'IMG_0052.png', 'IMG_0053.png', 'IMG_0054.png']} 

Output should be somewhat like this below

{'1': ['IMG_0001.png', 'IMG_0002.png', 'IMG_0053.png', 'IMG_0054.png'], 
 '2': ['IMG_0020.png', 'IMG_0021.png', 'IMG_0022.png', 'IMG_0023.png'], 
 '3': ['IMG_0003.png', 'IMG_0004.png', 'IMG_0051.png', 'IMG_0052.png']}

Tried using random.shuffle() in python but not getting as expected. Can anyone help me. I am a new beginner in python. Thank you for your help.




generating two columns with randomly put 1,2 or 3 but different values for each row

I am looking to assign 3 readers to a list of entries with ~1500 rows. Each row needs to be surveyed twice but not from the same person. My idea was to create two new columns in the data set with randomly put 1,2or3 for the respective readers. But the numbers need to be different for each column.

Anyone got an easy fix for that in R?




How to make my name guesser stop guessing the same thing [closed]

import string
import random

chars = string.ascii_letters + string.digits + '!@#$£%^&*()[]{}.,~-_\\'
f = open("guesses.txt","r+")
f.truncate(0)
f.close()
name = input("what is the name you want guessed? ")
start_time = time.time()
passwordlen = len(password)
nameguess = ''.join(random.choice(chars) for i in range(namelen))
x = 1
while nameguess != name or x != 10000000:
    x += 1
    nameguess = ''.join(random.choice(chars) for i in range(namelen))
    print("guess: " + nameguess + " attempt: " + str(x))
if nameguess == name:
    print(f"it only took {x} times")
elif x == 10000000:
    print("i give up")

my first idea was to write it into a file, but i came into a logically problem, how do i make it reset the file everytime the code runs, then append to the file for every guess in that run, and how do I make it after it checks if the current guess has already been guessed, to check the new guess, I don't know if this makes sense

How do I make it reset the file for every time I hit 'run' on the code but append to the file for every guess

And How do I make it go back in code, so I want it to go:

(clearfile)
while nameguess != name
nameguess = ''.join(random.choice(chars) for i in range(namelen))  <------      
with open("guesses.txt", 'r') as guess:                                   |
    if nameguess in guess.read():                                         |
       --------------------------------------------------------------------
    elif nameguess not in guess.read():
        (appened name to list)
       continue

How do I make it not guess the same thing twice is the bottom line, I apologise that it was unclear




Random number with condition in java

How do I generate random integers within a specific range and condition in Java?? Hello all . boldI need to generate random values between 0-4 with condition. like i want to generate 100 values between 0-4 but i need the zeros to 40% of the total number and the ones to be 20% etc.bold Any ideas to do that in simple way ? '''Thanks for help.'''




lundi 29 juin 2020

Generate random numbers parallelly such that no two consecutives are same

I want to generate numbers from 0 to 5 parallelly such that no two consecutives are same. The approach below lead to many instances of numbers getting repeated consecutively. I have asked previously on how to avoid consecutive repetitions while generating numbers (Random number generation giving same numbers few times consecutively) but am still not sure of how to do this in a parallel environment .

     Random random = new Random();

        Parallel.For(0,100,(i)=>{
         int num   = random.Next(5);
            Console.WriteLine(num);
        });
           



Random number generation giving same numbers few times consecutively

I want to create random numbers multiple times. In the snippet below, i try to generate 100 numbers between 0 and 5 from the same random variable. Still , i am getting the same numbers consecutively . I just want that my next number should be different from prev one generated.

            Random random = new Random();

            for(int i=0;i<100;i++)
            {
                int num   = random.Next(5);
                Console.WriteLine(num);
            }

Picture of how the numbers were showing up .

Attached the picture of how the numbers were showing up !




Random number Array sorted out

For school i making a project for java, right now i got some problems..

I have to sort it out into a collum 10 on the X 10000(rows) on the Y Next to that i have to sort this out..

I hope someone can help me with my problem, i searched everywhere, but i can't find how to do both.

import java.util.Arrays;
import java.util.Random;
import java.io.*;

public class MijnLoop7 
{
    public static void main(String[] args) throws IOException
    {
        Random rand = new Random();
        int[] integers = new int[10];
        int min = 0;
        int max = 100000;
        int aantal = 100000;
        int random = (int) (Math.random()*((aantal-min)+1))+min;
        
        for(int x=0; x<max; x++){
            for(int y=0; y<10; y++)
                integers[y] = rand.nextInt(100000);
            System.out.println(Arrays.toString(integers));
        }
    }
}



Please explain python -> tuple(random.randrange(BOARD_SIZE[i]) for i in (0,1))

I understand that the codes below generate a random position from (0,1) to (48,48). I would like to understand the technique used. Is it a tuple comprehension? Great appreciate all your explanations.

import random
BOARD_SIZE=(48,48)

position = tuple(random.randrange(BOARD_SIZE[i]) for i in (0,1))
print(position)



Use rand() in C to get a different number every run without using time() or getpid()?

I am currently using the time() function inside srand() to generate a completely different and random number everytime the program is run.

srand(time(NULL));// chooses random seed for a different rand() every run 
  int n = 1 + rand() / (RAND_MAX / (100 - 1 + 1) + 1); // only generates numbers between 1 and 100
  printf("n = %d",n);
  int a = rand();
  printf("\na = %d",a);
  int b = rand();
  printf("\nb = %d",b);

Unfortunately, I have learned that I am not allowed to use time() or getpid(). Is there a way, using ONLY <stdio.h>, <stdlib.h> <assert.h> to generate a different random number every time the program is run?




which distirbutions can be used to produce starting times of jobs if there is no observation real state?

I need to produce some data which has starting times of each job (# of jobs: 30), I do not have chance to get real data so how can I generate data which let shows similarities with a data distribution. In this case, which distribution should be good to go on?




Python's random.randint() function appears to hang after a few hundred iterations in a for loop?

I have the following Python function in Jupyter Notebook:

def remove_random(df, group_counts):
    df = df.copy()
    blanks = set()
    if isinstance(group_counts, list):
        for groups, count in group_counts:
            for _, row in df.iterrows():
                current = 0
                while current < groups:
                    start = random.randint(0, len(row) - count)
                    cut = {x for x in range(start, start + count)}
                    if not cut.issubset(blanks):
                        current += 1
                        for i in range(start, start + count):
                            row[i] = np.nan
                            blanks.add(i)
    else:
        groups = group_counts[0]
        count = group_counts[1]
        
        for _, row in df.iterrows():
            i = 0
            print(_)
            while i < groups:
                start = random.randint(0, len(row) - count)
                cut = {x for x in range(start, start + count)}
                if not cut.issubset(blanks):
                    for i in range(start, start + count):
                        row[i] = np.nan
                        blanks.add(i)
                    i += 1
    return df

It is a function which removes n groups of j random points from a list; however, the indices being removed may not repeat and have to be unique each iteration. df is a pandas DataFrame, and group_counts is either a tuple or a list of tuples of the format (n, j).

When printing the row index as in the code above, the console shows that the rows of df are processed up to around 400 give or take a few, and when I kill the notebook it usually traces the point of execution to random.randint(), though I have seen it land on the issubset() as well. I have tried reseeding the random number generator but that did not fix the issue. Other than that I cannot find any bugs in my code which would be causing this problem. Moreover, as far I can tell from the output speed, the function chugs along quickly until stalling on row 400 so I don't think that using issubset() is causing a slowdown.




C#, Unity, creating unique pair of numbers[not working]

I'm trying to create some pairs of unique numbers using pretty simple algorithm. For some unknown reason after compiling Unity goes into an endless "not responding" state. Seems like it's stuck in a do..while loop, but I don't see any reason for that.

 //Creating two lists to store random numbers
    List<int> xList = new List<int>();
    List<int> yList = new List<int>();
    int rx, ry;

    for(int i = 0; i < 10; i++) 
    {
            
        // look for numbers until they are unique(while they are in lists)
        do 
        {
            rx = rand.Next(0, width);
            ry = rand.Next(0, height);
        }
        while(xList.Contains(rx) || yList.Contains(ry));
        
        //add them to lists
        xList.Add(rx);
        yList.Add(ry);
        
        Debug.Log(rx + ", " + ry);
        
        // some actions with these numbers
        gridArray[rx,ry].isBomb = true;
        gridArray[rx,ry].changeSprite(bombSprite);
            
    }



Java- "For" Loops condition to end at user input

I am a beginner, I am trying to write a code that Loops or generates a random to the amount of times user input specifies. What I currently have is a random that loops to a condition I set to a number just so I don't have infinite outputs. I would like to create a condition that stops at the user's input integer amount. Example, user input how many times they would like to play and the computer randomly outputs only that amount of times. Below is what I have so far. numberOfFlips is my scanner integer of user's input.

    for (numberOfFlips =1; numberOfFlips < 10; numberOfFlips++) {
    
    //Computer generates a pick
     compGuess= rand.nextInt(2);
     
    //Computer generates a pick
     }
        if (compGuess== 0) { 
            System.out.println("Heads");
        } else {System.out.println ("Tails");



Multiple sqeuences of random numbers without replacement

In numpy, I can use the code

from numpy.random import default_rng
rng = default_rng()
M, N, n = 10000, 1000, 3
rng.choice(np.arange(0, N), size=n, replace=False)

To get three random samples from 0 to 9 without replacement.

I would like to get thousands of such random sequences. What is the correct way to do this? I know I can do

np.array([rng.choice(np.arange(0, N), size=(n,), replace=False) for i in range(0, M)])

but I am wondering if there's a more efficient way to do this using numpy.

In this answer, the following way is recommended

np.argsort(rng.random((M,N)),axis=1)[:, :n]

which is superfast and elegant. However, the cost scales like N x M instead of n x M which I am hoping to achieve.

Are there any other methods out there?




Using SQL Query to Define min/max for Random_int

I am trying to use a SQL query to define min/max values for the radnom_int function.

private function doPreEventStart($user) {
    $MaxResult = db_fetch_item("SELECT max(resultid) FROM ResultPackage
      where ResultPackage.slotid like ‘%{$slot_id}'
      and ResultPackage.PackageID like '%{$user->packageid}%'
      ORDER BY resultid asc LIMIT 1")
    $MinResult = db_fetch_item("SELECT min(resultid) FROM ResultPackage
        where ResultPackage.slotid like ‘%{$slot_id}'
        and ResultPackage.PackageID like '%{$user->packageid}%'
        ORDER BY resultid asc LIMIT 1")
     $this->curResultId =  var_dump(random_int($MinResult,$MaxResult)
    }

So far this has not worked and I get the following errors when I try to run the file.

PHP Parse error:  syntax error, unexpected ';' in /var/www/html/VC/server-vc-RNG.php on line 761
PHP Parse error:  syntax error, unexpected '}' in /var/www/html/VC/server-vc-RNG.php on line 762
PHP Parse error:  syntax error, unexpected '}' in /var/www/html/VC/server-vc-RNG.php on line 762
PHP Parse error:  syntax error, unexpected '$MinResult' (T_VARIABLE) in /var/www/html/VC/server-vc-RNG.php on line 757

Please help me see the error.




Procedurally Generated Voronoi Roads

i'm using a noise function inspired by libnoiseforjava to try and generate roads. (See below)

public class VoronoiNoise {

private static final double SQRT_2 = 1.4142135623730950488;
private static final double SQRT_3 = 1.7320508075688772935;

private long seed;
private short distanceMethod;
private final double frequency;

public VoronoiNoise(long seed, double frequency, short distanceMethod) {
    this.seed = seed;
    this.distanceMethod = distanceMethod;
    this.frequency = frequency;
}

private double getDistance(double xDist, double zDist) {
    switch(distanceMethod) {
        case 0: //EUCLIDIAN - Length
            return Math.sqrt(xDist * xDist + zDist * zDist) / SQRT_2;
        case 1: //???
            return xDist + zDist;
        case 2: //???
            return Math.pow(Math.E, Math.sqrt(xDist * xDist + zDist * zDist) / SQRT_2)/Math.E;
        case 3: //MANHATTAN
            return Math.abs(xDist) + Math.abs(zDist);
        case 4: //CHEBYCHEV
            return Math.max(Math.abs(xDist), Math.abs(zDist));
        case 5: //MINKOVSKI
            return Math.pow(Math.pow(Math.abs(xDist), Math.PI) + Math.pow(Math.abs(zDist), Math.PI), (1 / Math.PI));
        case 6: //MINKOVSKI4
            return Math.pow(xDist*xDist*xDist*xDist+zDist*zDist*zDist*zDist,0.25);
        default:
            return 1.0;
    }
}

private double getDistance(double xDist, double yDist, double zDist) {
    switch(distanceMethod) {
        case 0:
            return Math.sqrt(xDist * xDist + yDist * yDist + zDist * zDist) / SQRT_3;
        case 1:
            return xDist + yDist + zDist;
        default:
            return 1.0;
    }
}

public short getDistanceMethod() {
    return distanceMethod;
}

public long getSeed() {
    return seed;
}

public double noise(double x, double z) {
    x *= frequency;
    z *= frequency;

    int xInt = (x > .0? (int)x: (int)x - 1);
    int zInt = (z > .0? (int)z: (int)z - 1);

    double minDist = 32000000.0;

    double xCandidate = 0;
    double zCandidate = 0;

    double xCandidate2 = 0;
    double zCandidate2 = 0;
    Random random = new Random(seed);
    long xSeed = random.nextLong();
    long zSeed = random.nextLong();

    for(int zCur = zInt - 2; zCur <= zInt + 2; zCur++) {
        for(int xCur = xInt - 2; xCur <= xInt + 2; xCur++) {

            double xPos = xCur + valueNoise2D(xCur, zCur, xSeed);
            double zPos = zCur + valueNoise2D(xCur, zCur, zSeed);
            double xDist = xPos - x;
            double zDist = zPos - z;
            double dist = xDist * xDist + zDist * zDist;

            if(dist < minDist) {
                xCandidate2 = xCandidate;
                zCandidate2 = zCandidate;
                xCandidate = xPos;
                zCandidate = zPos;
                minDist = dist;
            }
        }
    }

    double xDist = xCandidate - x;
    double zDist = zCandidate - z;

    //return getDistance(xDist, zDist);
    return getDistance(xCandidate2 - x, zCandidate2 - z) - getDistance(xCandidate - x, zCandidate - z);
}

public double noise(double x, double y, double z) {
    x *= frequency;
    y *= frequency;
    z *= frequency;

    int xInt = (x > .0? (int)x: (int)x - 1);
    int yInt = (y > .0? (int)y: (int)y - 1);
    int zInt = (z > .0? (int)z: (int)z - 1);

    double minDist = 32000000.0;

    double xCandidate = 0;
    double yCandidate = 0;
    double zCandidate = 0;

    Random rand = new Random(seed);

    for(int zCur = zInt - 2; zCur <= zInt + 2; zCur++) {
        for(int yCur = yInt - 2; yCur <= yInt + 2; yCur++) {
            for(int xCur = xInt - 2; xCur <= xInt + 2; xCur++) {

                double xPos = xCur + valueNoise3D (xCur, yCur, zCur, seed);
                double yPos = yCur + valueNoise3D (xCur, yCur, zCur, rand.nextLong());
                double zPos = zCur + valueNoise3D (xCur, yCur, zCur, rand.nextLong());
                double xDist = xPos - x;
                double yDist = yPos - y;
                double zDist = zPos - z;
                double dist = xDist * xDist + yDist * yDist + zDist * zDist;

                if(dist < minDist) {
                    minDist = dist;
                    xCandidate = xPos;
                    yCandidate = yPos;
                    zCandidate = zPos;
                }
            }
        }
    }

    double xDist = xCandidate - x;
    double yDist = yCandidate - y;
    double zDist = zCandidate - z;

    return getDistance(xDist, yDist, zDist);
}

public void setDistanceMethod(short distanceMethod) {
    this.distanceMethod = distanceMethod;
}

public void setSeed(long seed) {
    this.seed = seed;
}

public static double valueNoise2D (int x, int z, long seed) {
    long n = (1619 * x + 6971 * z + 1013 * seed) & 0x7fffffff;
    n = (n >> 13) ^ n;
    return 1.0 - ((double)((n * (n * n * 60493 + 19990303) + 1376312589) & 0x7fffffff) / 1073741824.0);
}

public static double valueNoise3D (int x, int y, int z, long seed) {
    long n = (1619 * x + 31337 * y + 6971 * z + 1013 * seed) & 0x7fffffff;
    n = (n >> 13) ^ n;
    return 1.0 - ((double)((n * (n * n * 60493 + 19990303) + 1376312589) & 0x7fffffff) / 1073741824.0);
}
}

As you can see i've been calculating the Distance21 - the distance of the 1st minus the 2nd closest point. I've been using this along with Euclidian distance calculation to generate a noise map. Here is what I get: Length-Distance21 I've then been checking whether the noise is below a certain value (black colours) and using that to place roads. One problem is that some of the cells are black, some blacker than the roads causing a mass of roads. Also, the roads are more than 1 unit in width which is unacceptable for my purposes.

Here is a chart of the different types of voronoi noise. voronoi types

I was wondering if there is an algorithm for procedurally generating noise like this

enter image description here

Except that given a seed, a frequency and a point (x,y) it would return true or false whether or not the vertices pass through that point or not. Creating lines

lines

As a last resort I will use a repeating, static, image.




What's the period of RNGCryptoServiceProvider?

I need information about RNG caracteristics. In particular I was searching the period of RNGCryptoServiceProvider for C# Net Framework 4.5 (see https://docs.microsoft.com/en-us/dotnet/api/system.security.cryptography.rngcryptoserviceprovider?view=netcore-3.1) , but I wasn't able to find anything. Could someone help me? Thank you

Just to make an example the period of a classical implementation of Mersenne Twister is 2^19937 - 1 (see https://en.wikipedia.org/wiki/Mersenne_Twister#Advantages)




Finding the correlation matrix of a large dataset in R

I have a data set that has 98 variables and nearly 1.1 million observations. I want to see the correlations between the variables however since the data is too large, R cannot proceed with the computation due to the memory allocation failure.

Then, I wanted to sample the data set with stratified sampling method so that I can compute correlations on sampled data. But again I got the same memory error which is "Error: cannot allocate vector of size ... Mb"

So, how can I find the correlation matrix of either the whole data or the sampled data?




Using Random_int instead of Rand()

I am currently using Rand() to select a random result from a table using a simple Rand() and where SQL query.

Existing code:

private function doPreEventStart($user) {
  $row = db_fetch_item("SELECT resultid FROM ResultPackage
      where ResultPackage.slotid like '{$this->curSlotId}'
      and ResultPackage.PackageID like '%{$user->packageid}%'
      ORDER BY RAND() LIMIT 1");
  $this->curResultId = $row['resultid'];

I would like to change this to use Random_int instead as this provide more genuine randomness which is needed for the application.

I have tried this but it is not working:

  private function doPreEventStart($user) {
      $row = db_fetch_item("SELECT resultid FROM ResultPackage
        where ResultPackage.slotid like ‘%{$slot_id}'
        and ResultPackage.PackageID like '%{$user->packageid}%'
        ORDER BY resultid asc LIMIT 1");
        $this->MinResult = $row['resultid'];
    var_dump(random_int($this->MinResult,$this->MaxResult) + ", SLOTID=" + $slot_id);
    }

Please can someone help to correct the above code.




dimanche 28 juin 2020

How to read csv into a list and dictionary

I want to create a game that displays a country and asks the user to enter the capital for the country displayed. After the user enters the capital, it will display another country and ask for the capital, and repeat the process until the user has answered the capital for ten countries. Then, display the users score at the end of the game. For each capital the user enters correctly, I want to award 5 points.

This is what I have done so far

import csv
import pandas
import random

african_countries = open("african_countries.csv", "r")
rd = csv.reader(african_countries)

def main():
    setupGame()
    playGame()
def setupGame():
    global countries, capitals, correct, incorrect, used
    correct = 0
    incorrect = 0
    used = [False] * 55
    countries = setupCountriesList()
    capitals = setupCapitalsDictionary()
    print("\nCOUNTRIES AND CAPITALS QUIZ!")

def playGame():
    global correct, incorrect, used
    guess = ""
    while guess.lower() != "quit":
        idx = random.randint(0, 9) 
        while used[idx]:
            idx = random.randint(0, 9) #To generate a new idx if already used
        used[idx] = True
        allTrue = True #check to see if all used is True
        for i in range(0,55):
            if used[i] == False:
                allTrue = False
        if allTrue:
            used = [False] * 55 #To reset all used to false
        country = countries[idx]
        capital = capitals[country]
        guess = input("What is the capital of " + country.upper() + "? (enter 'quit' to end)>> ")
        if guess.lower() =="quit":
            print("THANKS FOR PLAYING...You got {0} of {1} correct.\n".format(correct, (correct + incorrect)))
            break
        elif guess.lower() == capital.lower():
            print("CORRECT! {0} is the capital of {1}".format(capital, country))
            correct += 5
        else:
            print("SORRY... The capital of {0} is {1}".format(country, capital))
            incorrect += 5
        print("YOUR SCORE: You have gotten {0} of {1} correct \n".format(correct, (correct + incorrect)))

def setupCountriesList():
    countries = []
    for row in rd:
        countries.append(row[0])
    return countries

def setupCapitalsDictionary():  
    capitals = {}
    for row in rd:
        k, v = row
        capitals[k] = v
    return capitals

main()

But I got this error:

COUNTRIES AND CAPITALS QUIZ!

Traceback (most recent call last):
  File "c:/Users/Gideon Markus/Desktop/Cyhermes/Week 4/Project 3/Python/trial.py", line 61, in <module>
    main()
  File "c:/Users/Gideon Markus/Desktop/Cyhermes/Week 4/Project 3/Python/trial.py", line 10, in main
    playGame()
  File "c:/Users/Gideon Markus/Desktop/Cyhermes/Week 4/Project 3/Python/trial.py", line 35, in playGame
    capital = capitals[country]
KeyError: 'The Republic of Cabo Verde'
PS C:\Users\Gideon Markus\Desktop\Cyhermes\Week 4\Project 3\Python>



Why is rand() (and many other default random number generators) designed so badly?

It's often said that one should never use rand() in C, and similar statements are made for many of the default random number generators in other languages, but why were they designed like this?

To clarify, I do not mean what are the problems with them, but why were they designed in a way that is poor enough that many people say they should never be used?




How do you share a randomly generated integer across buttons?

Sorry, I'm quite new to Xcode, but here goes... I'm trying to make this really simple multiplication game, and I have two buttons, one to generate the next question, and one to submit your answer. The problem is that, I need both buttons to "know" the same two random integers that should be multiplied, but the two buttons generate two different sets of integers, and so the question might be something like "What is 10 * 8", while the answer the computer thinks is right might be something like 5 * 5. (I used sender tags for the two different buttons, the submit button having sender tag 2 and the next question button having sender tag 1.) Please help! Here's the full code:

@IBOutlet weak var questionLabel: UILabel!
@IBOutlet weak var answerBox: UITextField!
@IBOutlet weak var scoreLabel: UILabel!
@IBAction func button(_ sender: AnyObject) {
var thing = 1
var score = 0
if thing < 11
{
    let firstNumber = Int(arc4random_uniform(UInt32(11)))
    let secondNumber = Int(arc4random_uniform(UInt32(11)))
    let answer = Int(firstNumber * secondNumber)
    let answerString = "\(answer)"
    
    
    questionLabel.text = "What is " + "\(firstNumber)" + " x " + "\(secondNumber)"
            
    
    
    if sender.tag != 1
    {
        if answerBox.text == answerString
        {
            score += 1
            scoreLabel.text = "Score: " + "\(score)"
            questionLabel.text =  "Correct!"
            thing += 1
            self.answerBox.text = ""
        }
        else if answerBox.text !=  answerString
        {
            scoreLabel.text = "Score: " + "\(score)"
            questionLabel.text = "Incorrect..."
            thing += 1
            self.answerBox.text = ""
        }
    if sender.tag == 1
    {
        
        questionLabel.text = "What is " + "\(firstNumber)" + " x " + "\(secondNumber)"
            
    }
    if thing > 10
    {
        self.questionLabel.text = "Your score was " + "\(score)" + " out of 10!"
        thing -= 10
        score = 0
        self.scoreLabel.text = "Score: 0"
        }
    }
    
    
       
    }
    

}

}




I want to generate a number of matrices and fill it with random numbers

hi guys i want to generate a number of matrices of 5x5 with random numbers but this code i made only prints the same matrix over and over, whats the issue? (i am learning c++), this code just print the same matrix over and over instead of being different numbers in each matrix

#include <iostream>
#include <string>
#include <sstream>
#include <ctime>
#include <iomanip>
#include <cstdlib>

using namespace std;


bool verif(int carton[5][5], int f, int c, int nume){

    for(f=0;f<5;f++){
        for(c=0;c<5;c++){
            if(nume==carton[f][c]){
            return false;
            }
        }
    }
    return true;
}

int i,cant,nume;

int main()
{
ingresa: 
    int j,cant;
    cout<< "type the number of bingo cards you want: ";
    cin>>cant;
    if(cant>100){ 
    cout<<"ERROR the max number of bingo cards is 100:"<<endl;
    goto ingresa;
    }

    for(i=1;i<=cant;i++){ 
        cout<<endl;
        cout<< "BINGO #"<<i<<endl;

    int carton[5][5]; //cartón de 5x5
    int f,c,nume; 
    srand(time(NULL));

    for(f=0;f<5;f++){
        for(c=0;c<5;c++){
            nume=1+rand()%25;
            carton[f][c]=nume;
            while(verif(carton,5,5,nume)==false){
                nume=1+rand()%25;
            }
        carton[f][c]=nume;
        }
    }
    for(f=0;f<5;f++){
        for(c=0;c<5;c++){
        cout<<setw(3)<<carton[f][c]<<" ";
        }
        cout<<endl; 
    }

}
}



How to add integers to an array and get a random number?

It's a favorite panel. You can select numbers (with button click) and than I would like to add this number to an array and than get a random number from this array.

public int runs;
public int randomNumber;
public int[] favorites = new int[75];

public void RandomButton()
{
    if (DataController.Instance.group == 3)
    {
            favorites[randomNumber] = UnityEngine.Random.Range(0, favorites.Length);
            Debug.Log(favorites[randomNumber]);
    }
}

public void b0()
{
    for (runs = 0; runs < favorites.Length; runs++)
    {
        favorites[runs] = 0;
    }
}

public void b1()
{
    for (runs = 0; runs < favorites.Length; runs++)
    {
        favorites[runs] = 1;
    }
}

I'm stuck , because I get random number between 0 - 75. I would like to have a random number from the "favorites" array after I click on the buttons.




c++ random assignment producing issues

I am trying to randomly generate some assignments to a problem that I have other code processing and finding the correct solution for the problem.

The code below is a generate_assignment() function that should randomly assign a value of '0' or '1' where applicable in the "assignment" vectors. Here we are trying to create four threads of assignments. The array of integers "temp_assignment" is just for testing so I can compare between code versions.

But the issue comes when I switch from testing to real time operation using the random assignment generation. In testing, the assignments are done flawlessly and the rest of the code solves the problem as expected. I've tried many different combinations of numbers and it handles it correctly every time. However, when I switch to the random generation, the system only has the correct output about half of the time. Everywhere else in the code where the "assignment" vectors are supposed to be resized and cleared, they are done correctly.

void generate_assignment()
{
    int temp_assignment[10] = {1,1,1,1,1,0,1,0,0,0};

    for(int thread=0;thread<4;thread++){
        for(int i=0;i<literal_count;i++)
        {
            if(unit_literal_assignment[i] == -1)
            {
                //assignment[i] = temp_assignment[i]; //Direct assignment for testing
                if (thread==0){
                    assignment1[i] = temp_assignment[i];
                }else if(thread==1){
                    assignment2[i] = temp_assignment[i];
                }else if(thread==2){
                    assignment3[i] = temp_assignment[i];
                }else if(thread==3){
                    assignment4[i] = temp_assignment[i];
                }
                /*if((rand()%10) < 5) //Actual random assignment
                {
                    if (thread==0){
                        assignment1[i] = 1;
                    }else if(thread==1){
                        assignment2[i] = 1;
                    }else if(thread==2){
                        assignment3[i] = 1;
                    }else if(thread==3){
                        assignment4[i] = 1;
                    }
                }
                else
                {
                    if (thread==0){
                        assignment1[i] = 0;
                    }else if(thread==1){
                        assignment2[i] = 0;
                    }else if(thread==2){
                        assignment3[i] = 0;
                    }else if(thread==3){
                        assignment4[i] = 0;
                    }
                }*/
            }else{
                if (thread==0){
                    assignment1[i] =(int)assignment[i];
                }else if(thread==1){
                    assignment2[i] = (int)assignment[i];
                }else if(thread==2){
                    assignment3[i] = (int)assignment[i];
                }else if(thread==3){
                    assignment4[i] = (int)assignment[i];
                }
            }


        }
    }
    /*for(int i=0;i<assignment.size();i++){
        cout<<assignment1[i];
    } cout<<endl;
    for(int i=0;i<assignment.size();i++){
        cout<<assignment2[i];
    } cout<<endl;
    for(int i=0;i<assignment.size();i++){
        cout<<assignment3[i];
    } cout<<endl;
    for(int i=0;i<assignment.size();i++){
        cout<<assignment4.at(i);
    } cout<<endl;*/


}

Does anyone know what could be the cause of this? Should the random assignment be done in a different way?

I appreciate any comments or help I can get.




How togenerate a true random number from mouse movement in python

How to create a python program that lets users move the mouse anywhere on the screen and generate a random number based on those movements. I am trying to implement this feature




how to display random number in flutter

I need to display a random number in flutter using a function, but when i call it i get error.

 void generateRandomNumber() {
                        setState(() {
                          point=pointValue[new Random().nextInt(pointValue.length)];
                        });
                        }



samedi 27 juin 2020

How to select a random line from a .txt file in Kotlin

I want to create a program that randomly prints out a line from a .txt file. This is what I'm currently at, and the only other similar questions I could find were in other languages. For example, Python with the random.choice() operation, which I found in this question: How to choose a random line from a text file

Thank you all for your time!

import kotlin.system.exitProcess

fun main() {
    val file = "text.txt"
    println(file.random("text.txt")) //This code doesn't work, I'm just illustrating what I was looking to do.
}



Get random string that is not in list

I have a list of choices. Let's assume it's ['active', 'inactive', 'deleted']. I want to get a random string that isn't in that list (for example, disabled) and complication is that I don't want to look into that list myself (function must work universally for any list of string).

I know how to get random string from list with random.choice. What I want is to have inversed equivalent of it.

Actual case - I want to write a unittest with an assertNotIn assertion.

So, my code at the moment is below:

import random
import string

insiders = ['active', 'inactive', 'deleted']

while True:
    outsider = ''.join(random.choice(string.ascii_letters) for _ in range(random.choice(range(1, 10))))
    if outsider not in insiders:
        break

My question is: Is there any shorter solution? Ideally, one-liner. Something like this:

outsider = random.not_in_list(insiders)



How To Randomly Select Cells Based On Criteria In Excel?

I am looking for a help with a formula in excel. I have two tabs in my excel First tab - Updates

enter image description here

Second tab - One

enter image description here

When the input is 1, it should check if ID 1 is available in updates sheet and return a random "Code" column from "updates Sheet" which has ID 1. IF ID 1 is not available in Updates sheet, it should check in sheet "one" and return a random code from there which contains ID 1. When Input is ID 3, it should check in sheet 'updates', ID 3 is not available in updates sheet, so it should go to sheet 'one' and return a random code which has ID 3. My data here is dynamic,for example ID 1 values will keep increasing every month, so when a match is found it should return value. Please help on this.




Variable scopes in Python3

here is a piece of a very very messy code. It doesn't matter as much, since I just did it for fun. Everything works as expected until the loop ends and I am supposed to get the number of times the variables "correct" and "incorrect" were increased. The output is 0, and I don't get why. Any ideas?

import random
correct = 0
incorrect = 0

x = 100
while x >= 1:
    x = x-1

    #door with number one will the the one with the price behind it
    a = 0
    b = 0
    c = 0
    first_door_chosen = ""
    #randomly choose which door is the one with the price
    random_door = random.randint(1,3)

    if random_door == 1:
        a = 1
        print("---------FIRST DOOR IS THE RIGHT ONE")
    if random_door == 2:
        b = 1
        print("---------SECOND DOOR IS THE RIGHT ONE")
    if random_door == 3:
        c = 1
        print("---------THIRD DOOR IS THE RIGHT ONE")
    ##################END#####################

    #randomly choose which door YOU want to choose.
    random_door_selection = random.randint(1,3)

    if random_door_selection == 1:
        print("You choose door 1.")
    if random_door_selection == 2:
        print("You choose door 2.")
    if random_door_selection == 3:
        print("You choose door 3.")
    ###################END#####################

    #Stop the game if the door you chose is the one with the prize.
    if a == 1 and random_door_selection == 1:
        print("First door was the right door")
        first_door_chosen == "a"
        
    elif b == 1 and random_door_selection == 2:
        print("Second door was the right door")
        first_door_chosen == "b"
        
    elif c == 1 and random_door_selection == 3:
        print("Third door was the right door")
        first_door_chosen == "c"
        
    else:

        
    ####################END#################### 

            
        print("Your door was wrong.")
        print("For the purposes of this experiment, we will automatically discard your chosen door.")
        print("You automatically change your door with the other one that is still closed.")

        if random_door_selection == 1:
            if random_door == 2:
                print("The door with the prize was the SECOND one.")
                if random_door_selection == 2:
                    print("You LOSE")
                    incorrect += 1
                if random_door_selection == 3:
                    print("You WIN")
                    correct += 1
            if random_door == 3:
                print("The door with the prize was the THIRD one.")
                if random_door_selection == 2:
                    print("You WIN")
                    correct += 1
                if random_door_selection == 3:
                    print("You LOSE")
                    incorrect += 1
                
        if random_door_selection == 2:
            if random_door == 1:
                print("The door with the prize was the FIRST one.")
                if random_door_selection == 1:
                    print("You LOSE")
                    incorrect += 1
                if random_door_selection == 3:
                    print("You WIN")
                    correct += 1
            if random_door == 3:
                print("The door with the prize was the THIRD one.")
                if random_door_selection == 1:
                    print("You WIN")
                    correct += 1
                if random_door_selection == 3:
                    print("You LOSE")
                    incorrect += 1

        if random_door_selection == 3:
            if random_door == 1:
                print("The door with the prize was the FIRST one.")
                if random_door_selection == 1:
                    print("You LOSE")
                    incorrect += 1
                if random_door_selection == 2:
                    print("You WIN")
                    correct += 1
            if random_door == 2:
                print("The door with the prize was the SECOND one.")
                if random_door_selection == 2:
                    print("You WIN")
                    correct += 1
                if random_door_selection == 1:
                    print("You LOSE")
                    incorrect += 1

print("")
print("")


print("from %s tries, %s were incorrect" %(x, incorrect,))
print("from %s tries, %s were correct" %(x, correct,))

Thank you very much for your time !




PHP - Random string [closed]

I need a license code generator in php. It is to generate the following codes:

ABCD-EFGH-HIJK-LMNO

  • Example ^^



vendredi 26 juin 2020

Android Studio (coding with Java) extract elements code

I am trying to extract some elements randomly from several different groups and make a new group with the extracted elements.

private int[] firstgroup = {R.drawable.element_1, R.drawable.element_2, R.drawable.element_3, R.drawable.element_4};

private int[] secondgroup = {R.drawable.element_5, R.drawable.element_6, R.drawable.element_7, R.drawable.element_8};

Like this

private int[] newgroup = {R.drawable.element_1, R.drawable.element_4, R.drawable.element_6, R.drawable.element_8};

How can I code to deal with this problem?




How do I create a random number based on a seed without using random.seed()?

I know that you can do this:

random.seed(100)
r = random.randint(1, 3)

But is it possible to do something more similar to this?

r = random.randint(1, 3, seed=100)

Also I am aware that the code above would give the same output every time, that is the behavior I want.




How to (actually) correctly implement a binary symmetric channel in Python?

I'm looking to implement a binary symmetric channel in Python, preferably using Numpy. I want my results to be reproducible (i.e. depend on a seed of my choice only) and also a solution that, while it need not be state of the art in this regard, wouldn't make a cryptographer bang his head against the wall (to be slightly more precise, I'm looking for something at least as good as a Mersenne Twister in terms of statistical properties). Of course it's always nice to have a solution that's efficient.

I am aware of this topic with the same name, the answer to which uses floating point comparison together with numpy.random.random(). I'm certainly no expert but I believe our poor cryptographer will get a bad headache from this, even though such a solution might be fine for most practical applications.

There is another reason why a new answer to this question is in order: in modern Numpy, the use of numpy.random.random and similar functions is discouraged. Rather, one should use a 'numpy.random.Generator' instance to draw random numbers from, allowing one to choose a suitable PRNG. However, this introduces the difficulty of combining my (perhaps stupid) wish of being able to fix a seed for each individual use of the BSC as well as not having to instantiate a random number generator every time (which is computationally expensive). How does one do this correctly?

Just to show roughly what I'm trying to do, here are two very naive, inefficient, old-fashioined and cryptographically dubious solutions:

# (tested with python 3.7.7 and numpy 1.18.1)
import numpy as np


def worse_BSC(bits, err_rate: float, seed: int):
    """
    Binary symmetric channel
    :param bits: Numpy array of booleans 
        (obviously booleans are not the best choice, I'm not sure how terrible it is exactly)
    :param err_rate: floating point number between 0. and 1. inclusive.
    :param seed: Random seed
    :return: Numpy array. Bits subjected to Binary symmetric channel.
    """
    np.random.seed(seed)  # bad: using a legacy function and setting a global state.
    return bits ^ np.random.choice(a=[True, False], size=bits.shape, p=[err_rate, 1 - err_rate])

# -----------------------------------------------------------------
from numpy.random import MT19937, RandomState, SeedSequence


def bad_BSC(bits, err_rate: float, seed: int):
    """Everything as above. Is this ok? Does it have a huge unnecessary performance penalty?"""
    rs = RandomState(MT19937(SeedSequence(seed)))  # np.random.seed doc says this is "recommended".
    # Pycharm complains for some reason that MT19937 has an unexpected type (the code works of course)
    return bits ^ rs.choice(a=[True, False], size=bits.shape, p=[err_rate, 1 - err_rate])



How to add integers to an array / list in Unity?

I'm a little bit stuck .. I work on a favorite panel,there are numbers and next to the numbers buttons.If the button is clicked than the number should be save in a list / array. Than from this list / array I will generate a random number.

How can I solve this?




Is this "true" random? [closed]

Whether or not "true" random actually exists is somewhat of a philosophical question. I'd say it doesn't exist, but we've gotta try, right? I have a library which is performing alright, but the #1 critique I get is that it would be much cooler if it was a "true" random library, so I've been considering approaches for a while. I was thinking about how there is noise in the circuitry of our computers, and I thought that if I could measure it, I might be able to exploit that to get a random number based not off of a seeded mathematical calculation, but instead off of a real-world micro-observation. So my question is- is this a sound true random function? If not, please explain how it is vulnerable or biased. Thanks.

To be clear, I don't want compliments, insults, or philosophical debates. I want answers that will poke holes in this and give me specific ways it can be exploited. I'm asking specifically if there is a way to exploit this.

function random(){
  var randomBoolean = () => {
    var p1 = performance.now(), p1 = performance.now() - p1;
    var p2 = performance.now(), p2 = performance.now() - p2;
    return p1 == p2 ? randomBoolean() : p1 > p2;
  },
  randomDigit = () => {
    var binary = "";
    for(var i = 0; i < 4; i++) binary += +randomBoolean();
    return parseInt(binary, 2) > 9 ? randomDigit() : parseInt(binary, 2);
  },
  random = ".";
  
  for(var i = 0; i < 30; i++) random += randomDigit();
  return Number(random);
}

console.log(random());



how to make random values in one function be same for each run while random values in another function be different for each run

I searched the net and it showed the srand() method for generating new random values for each run , while i was using the simple rand() method for generating same random numbers in each run , but i want both these functionalities at different places in the program.
This is what i have tried:

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

void first()
{ 
    printf("these random values should be same for every run\n");
    for(int i = 0; i<4; i++)
        printf(" %d ", rand()%4);
    printf("\n");

} 
void second()
{ 
    srand(time(0));

    printf("these random values should be different for every run\n");
    for(int i = 0; i<4; i++)
        printf(" %d ", rand()%4);
    printf("\n");
} 

int main(void)
{


    first();
    second();
    return 0;
}

please help.




C# - Stuck on getting information from if

I've got this homework from school that I have to do this : Create a program that reads 10 numbers from the interval <-100; 100> on the input. Verify the input values. After entering, determine how many numbers are positive and calculate the diameter only from these numbers.

And I am stuck on the part after determining how many numbers are positive. Because I can't get the information from if outside so I can count them all for a diameter.

So I would be really glad if someone could help me how to move on. Or even how to simplify my code because it is probably too long when it could be like a few lines. Code:

Random number = new Random();
        int a = number.Next(-100, 100);
        int b = number.Next(-100, 100);
        int c = number.Next(-100, 100);
        int d = number.Next(-100, 100);
        int e = number.Next(-100, 100);
        int f = number.Next(-100, 100);
        int g = number.Next(-100, 100);
        int h = number.Next(-100, 100);
        int i = number.Next(-100, 100);
        int j = number.Next(-100, 100);
        Console.WriteLine("{0} {1} {2} {3} {4} {5} {6} {7} {8} {9}", a, b, c, d, e, f, g, h, i, j);



        if (a > 0)
        {
            Console.WriteLine(a + " Is a positive number");
            return a;
        }  
            if (b > 0)

                Console.WriteLine(b + " Is a positive number");
            if (c > 0)

                Console.WriteLine(c + " Is a positive number");
            if (d > 0)

                Console.WriteLine(d + " Is a positive number");
            if (e > 0)
                Console.WriteLine(e + " Is a positive number");
            if (f > 0)
                Console.WriteLine(f + " Is a positive number");
            if (g > 0)
                Console.WriteLine(g + " Is a positive number");
            if (h > 0)
                Console.WriteLine(h + " Is a positive number");
            if (i > 0)
                Console.WriteLine(i + " Is a positive number");
            if (j > 0)
                Console.WriteLine(j + " Is a positive number");

I can't recall the variables or get them out of if.




creating random numbers excluding all values in a list

I need to create random numbers in python. But it should ignore all the values stored in a 2-d list and it should be within a specified range. Is there any build in function available?




exception thrown with random numbers in c++

I'm trying to make a game which requires pseudo random numbers to set the enemies to random spots. So I tried including the stdlib header file and used srand before getting random numbers for the enemies using rand, my code until the first srand looks like this:

#include "pch.h"
#include <iostream>
#include <string>
#include <stdio.h>
#include <stdlib.h>
#include <Windows.h>
#include <time.h>

int screenWidth = 70, screenHeight = 80;

class Enemy {
public:
    int column, lives;
    Enemy() {};
    Enemy(int nColumn, int nLives) {
        column = nColumn;
        lives = nLives;
    }
};
int main()
{
    wchar_t *screen = new wchar_t[screenWidth * screenHeight];
    HANDLE hConsole = CreateConsoleScreenBuffer(GENERIC_READ | GENERIC_WRITE, 0, NULL, CONSOLE_TEXTMODE_BUFFER, NULL);
    SetConsoleActiveScreenBuffer(hConsole);
    DWORD bytesWritten = 0;
    int x = 0, y = 0, width = 10, height = 10;
    std::wstring canvas = L"";
    wchar_t *title = new wchar_t[8];
    wsprintf(title, L"retro shooter");
    SetConsoleTitle(title);
    int enemiesLength = screenWidth / width;
    Enemy* enemies = new Enemy[enemiesLength];
    for (int i = 0; i < enemiesLength; i++) {
        srand(time(NULL)); // It throws the error at this line
        if (rand() % 2) enemies[i] = Enemy(i, 1);
    }
    // the code doesn't end here that's why I didn't put out the closing curly bracket

The code above gives me the error/exception:

Exception thrown at 0x76EDE496 (ntdll.dll) in retroShooter.exe: 0xC0000005: Access violation reading location 0x183A0FA2.

I have also tried include-ing cstdlib like: #include <cstdlib> but the exception is the exact same. This exception is thrown after it has been compiled and it isn't marked as an error in visual studio




jeudi 25 juin 2020

Sphinx will not import all modules and is hanging up on random.choice()

I'm having a hard time with Sphinx where it won't import all the modules. There error it is encountering reads as follows:

  File “file path”, line 36, in Individual
    ml_params = {'C': random.choice(svr_C), 'gamma': random.choice(svr_gamma)}
  File "/usr/local/Cellar/sphinx-doc/3.1.1/libexec/lib/python3.8/random.py", line 290, in choice
    raise IndexError('Cannot choose from an empty sequence') from None
IndexError: Cannot choose from an empty sequence

I set sphinx up per the instructions in the following post: Getting Started with Sphinx...

I have followed the recommended steps in the layout and it works well for the most part, except that it gets hung up on random.choice() from random.py. The python code runs without error and does not hang up on random.choice() from random.py.

In the python code, this is how random.choice is used:

svr_C = list(np.linspace(50, 300, 10))
svr_gamma = list(np.logspace(-4, -2, 3))

ml_params = {'C': random.choice(svr_C), 'gamma': random.choice(svr_gamma)}

I need to ignore numpy in the conf.py file, otherwise Sphinx will hang up on the numpy import. I don't know why Sphinx sees this 'np.linspace(50,300,10)' as an empty sequence. Seems like I need a way to convince Sphinx that random.choice() is in fact not empty.

My conf.py is set up as follows:

import os
import sys
sys.path.insert(0, os.path.abspath(os.path.join('..', '..')))

extensions = ['sphinx.ext.autodoc']
autodoc_mock_imports = ["matplotlib", "pandas", "scipy", "statsmodels", "numpy", "xlrd", "sklearn", "fpdf", "rpy2", "joblib", "pathos", "fire", "psutil"]

The file/directory structure:

.
├── Makefile
├── build
│   ├── doctrees
│   │   ├── src_lib.doctree
│   │   ├── environment.pickle
│   │   ├── index.doctree
│   │   └── modules.doctree
│   └── html
│       ├── _sources
│       │   ├── agora_lib.rst.txt
│       │   ├── index.rst.txt
│       │   └── modules.rst.txt
│       ├── _static
│       │   ├── numerous_css_files.css
│       │   ├── numerous_js_files.js
│       │   ├── 1.js
│       │   └── underscore.js
│       ├── src_lib.html
│       ├── genindex.html
│       ├── index.html
│       ├── modules.html
│       ├── objects.inv
│       ├── py-modindex.html
│       ├── search.html
│       └── searchindex.js
├── make.bat
└── source
    ├── _static
    ├── _templates
    ├── src_lib.rst
    ├── conf.py
    ├── index.rst
    └── modules.rst



im doing a do while loop and prints the SOP statement always twice

           do
           {
              System.out.println("The word is: " + correct[randomSelection] + "\nYour Answer: ");
              answer = input.next();
           }   
           while(!(answer.equalsIgnoreCase("y") || answer.equalsIgnoreCase("n")));

in this code whenever I try to execute it, it always prints the sop statement twice.




Questions about image random

Hello I am a beginner learning Java I am trying to create a random image output The code I made stops with only one image coming out What I want is to keep showing the images at random Which code should I add? Please help me

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


        ImageView imageView_1 = findViewById(R.id.imageView_1);
      

        int[] images = {R.drawable.img_1, R.drawable.img_2, R.drawable.img_3, R.drawable.img_4, R.drawable.img_5};

            Random rand = new Random();

            imageView_1.setImageResource(images[rand.nextInt(images.length)]);
        
        }
}



postgresql query to generate 5 random DNA sequences that are each about 20 bases, and show the count of each base (A, C, G, T)

query to generate 5 random DNA sequences that are each about 20 bases, and show the count of each base (A, C, G, T). enter image description here

so far I got the query in the bottom which generated the table blow, but its missing the count for the per base as well as the rest of the rows prepare dna_length(int) as with t1 as (select chr(65) as s union select chr(67) union select chr(71) union select chr(84) ) , t2 as ( select s, row_number() over() as rn from t1) , t3 as ( select generate_series(1,$1) as i,round(random() * 4 + 0.5) as rn ) , t4 as ( select t2.s from t2 join t3 on (t2.rn=t3.rn)) select array_to_string(array(select s from t4),'') as dna ; enter image description here




Random Fortune Cookie assignemtn [closed]

I am new to Java and I have been assigned by my professor a random fortune cookie assignment which will generate one random random fortune cookie saying out of 10 sayings and will loop as long as the user doesn't enter "0".

Here is the code I have for now but for some reason I keep on getting invalid syntax on line 26 on the statement "if userInput = 0".

Any help will be appreciated, thanks. Below is my code.

import random
global fortunes
fortunes = ["Good things come to those who wait.",
            "Patience is a virtue.",
            "The early bird gets the worm.",
            "A wise man once said, everything in its own time and place.",
            "Fortune cookies rarely share fortunes.",
            "A pleasant surprise is waiting for you.",
            "A smile is your personal welcome mat.",
            "A smile is your personal welcome mat.",
            "A soft voice may be awfully persuasive.",
            "Adventure can be real happiness."]

def init():
    global fortunes
    userInput = input("Welcome to the Fortune Teller, Enter 0 to quite or anything else to get your fortune ")
    if userInput = 0
        done()

def loop():
    global fortunes
    if userInput = 0 
        done()
    else:
        print(random.choice(fortunes))
        
def done():
    print("Thanks for playing")
    
def main():
    global radius
    init()
    while userInput != 0
        loop()
    done()
main()






Randomly Assigning ID Tags to different Sections in R

I am having trouble randomly assigning ID Tags to a Section. I generated a random string of 347 made up three-letter ID Tags (i.e., sbn, hjk, cvl). I would like each individual ID Tag to be randomly assigned to a Section (i.e., w,v,g,b). There are a total of 47 Sections. After assigning the ID Tags to one Section, I would very much like to create a data frame. Below is what I have so far:

##################### Create the ID Tags

  random.tags <- function(n=347, length=3)
  {
  randomString <- c(1:n)                  
 for (i in 1:n)
  {
  randomString[i] <- paste(sample(c(letters, letters),
                                length, replace=TRUE),
                         collapse="")

} return(randomString) }

 Tags<-random.tags()

################################# Create the Sections

 Sections<-c("w","v","u","t","s","r","q","p","o","n","m","l","k","j","i","g","f","e","d","c","b","a",
             "aa","bb","cc","dd","ee","ff","gg","hh","ii","jj","kk","ll","mm",
             "nn","oo","pp","qq","rr","ss","tt","uu","vv","ww","xx","yy")

I thought using the sample function in R would allow me to randomly assign the ID Tags to one Section but I am not able to because the rows are different lengths.

  df <- data.frame(Tag=sample(Tags, replace=TRUE),
             Section=sample(Sections, replace=TRUE))  # doesn't work
                                                                               

Thank you very much in advance for your help.




How can i generate pseudorandom numbers in MATLAB of a specific range [duplicate]

How can i generate 1000 pseudorandom numbers in range [-0.7,0.7] and store them in a vector, i've tried different methods but none of them actually worked for me ?




Printing as many numbers as possible in 9 seconds then a "-1" at the 10th second

So, I'm interested in printing as many numbers as possible in 9 seconds then printing a -1 at the 10th second. I have a while loop to print -1 every 10 seconds and a while loop to print any random number between 0 and 10 every 9 seconds. 1

My problem is twofold:

  1. I'm not sure how to create a loop which can print as many possible numbers (depending on computing speed) in 9 seconds
  2. I'm not sure how to put that together with the loop to print -1 every 10 seconds.

Thanks so much everyone!




a query to generate 5 random DNA sequences that are each about 20 bases

I got this query to solve for the first 20 but I don’t know how to extend that to the 5 rows,

prepare dna_length(int) as
  with t1 as (
    select chr(65) as s 
      union select chr(67) 
      union select chr(71) 
      union select chr(84) )
, t2 as ( select s, 
            row_number() over() as rn from t1)
, t3 as ( select generate_series(1,$1) as i,
            round(random() * 4 + 0.5) as rn )
, t4 as ( select t2.s 
            from t2 join t3 on (t2.rn=t3.rn))
select 
  array_to_string(array(select s from t4),'') as dna ;

enter image description here




how do i assign a random set word value to a variable Javascript? (Discord JS v12H

(Sorry for lengthy description in advance)

Basically i'm trying to make a guessing game with my discord bot where when i type "!guessing game", it will react three emojis: 1️⃣,2️⃣,3️⃣. Then it randomly chooses one of those emojis and assigns it to the variable, "answer". And if i click the emoji that corresponds with the one that is set to the "answer" variable then it will say something like "Congratulations! you guessed the correct number!", if not, it would say "Aww! Better luck next time!" or something.

This is what my code is:

    if (msg.content === "!guessing game") {
        const filter = (reaction, user) => {
            return ['1️⃣', '2️⃣', '3️⃣'].includes(reaction.emoji.name) && user.id === msg.author.id;
        };
        msg.react('1️⃣');
        msg.react('2️⃣');
        msg.react('3️⃣');
        msg.awaitReactions(filter, { max: 1, time: 60000, errors: ['time'] })
        .then(collected => {
        const reaction = collected.first();
        var num = Math.floor(Math.random() * 3) + 1;
        if (num === "1"){
            var answer = "1️⃣"
        }
        else{
            if (num === "2"){
                var answer = "2️⃣"
            }
            else{
                if (num === "3"){
                    var answer = "3️⃣"
                }
                else{
                   console.log("Random num failed")
          
                }
            }
        }
        if (reaction.emoji.name === answer) {
            msg.reply('You did it!');
        } 
        else{
            msg.reply('Better luck next time!');
        }
        


    })

naturally, this is what my console said: "Random num failed" i have a feeling that it would be a lot more efficient to choose a random emoji rather a random number and then converting it to an emoji.

does anyone know how to fix this?




Implementing a sampler with array eltype

Hooking into rand has been easier in the old days... I think I followed the description in the docs, but it doesn't seem to like a sampler returning an array:

using Random

struct Shell{N}
    r0::Float64
    r1::Float64
end

Base.eltype(::Type{Shell{N}}) where {N} = Array{Float64, N}

function Random.rand(rng::Random.AbstractRNG, d::Random.SamplerTrivial{Shell{N}}) where {N}
    # ignore the correctness of the sampling algorithm for now :)
    shell = d[]
    Δ = shell.r1 - shell.r0
    θ = Δ .* randn(N)
    r = shell.r0 .+ θ .* .√rand(N) 
end

Test:

julia> rand(Shell{2}(0, 1))
2-element Array{Float64,1}:
 0.5165139561555491  
 0.035180151872393726

julia> rand(Shell{2}(0, 1), 2)
ERROR: MethodError: no method matching Array{Float64,2}(::Array{Float64,1})
Closest candidates are:
  Array{Float64,2}(::AbstractArray{S,N}) where {T, N, S} at array.jl:498
  Array{Float64,2}(::UndefInitializer, ::Int64, ::Int64) where T at boot.jl:406
  Array{Float64,2}(::UndefInitializer, ::Int64...) where {T, N} at boot.jl:410
  ...
Stacktrace:
 [1] convert(::Type{Array{Float64,2}}, ::Array{Float64,1}) at ./array.jl:490
 [2] setindex!(::Array{Array{Float64,2},1}, ::Array{Float64,1}, ::Int64) at ./array.jl:782
 [3] rand! at /buildworker/worker/package_linux64/build/usr/share/julia/stdlib/v1.3/Random/src/Random.jl:271 [inlined]
 [4] rand! at /buildworker/worker/package_linux64/build/usr/share/julia/stdlib/v1.3/Random/src/Random.jl:266 [inlined]
 [5] rand at /buildworker/worker/package_linux64/build/usr/share/julia/stdlib/v1.3/Random/src/Random.jl:279 [inlined]
 [6] rand at /buildworker/worker/package_linux64/build/usr/share/julia/stdlib/v1.3/Random/src/Random.jl:280 [inlined]
 [7] rand(::Shell{2}, ::Int64) at /buildworker/worker/package_linux64/build/usr/share/julia/stdlib/v1.3/Random/src/Random.jl:283
 [8] top-level scope at REPL[14]:1

What am I missing?




Powershell: generate unique semi random numeric strings

Requirement: generate 10k of unique numbers composed of a sequential number (16 digits) followed by a random numeric string (4 digits). Weapon of choice is Powershell because it's the only tool I have a very limited knowledge of.

Problems encountered:

  1. Generating 10k sequential numbers using the following method: 1400000000000000..1400000000010000 and putting into a variable. Error: Value is to large for an Int32
  2. Generating 10k of 4 digit via Get-Random -Minimum 0001 -Maximum 9999 and putting them in a variable. I manage only to obtain 1 random number.
  3. Combining the two variables using the Join-Object (or at least that's what I hope could be done)

How can I combine these 3 commands to obtain a list of semi random numbers as specified above? Or is there simpler way to achieve the same result?




Java<-->Python pseudorandom numbers consistency; is it possible?

I was wondering if I could set a seed in my Java program (for training/inference on Neural Networks) and my Python program (again for the same purpose) which would give me the same set of pseudorandom outputs everytime.

For example, this is a Java program,

import java.util.Random;

public class MyClass {
    public static void main(String args[]) {
        Random r = new Random(); 
        // setting seed 
        long s = 30; 
        r.setSeed(s); 
  
        // value after setting seed 
        System.out.println(r.nextInt(10));
        
    }
    
}

and a corresponding Python program,

import random

random.seed(30)
print (random.randint(0,10))

Of course, the outputs of both the programs were different (because probably Java and Python both use different pseudo random generators). In that case, is it possible for me to force Java and Python to use the same sequence of pseudorandom numbers or pseudorandom generators?

I would need this to have consistency in writing ML programs in Java/Python which give me the same output. Any help appreciated, thanks!




Will numpy random.randint with constant seed will stay the same over time, versions and platforms? [duplicate]

I'm using :

np.randim.seed(0); const_rand_arr = np.random.randint(LONG_INT)

In my code to perduce a constant random array.

I'm conserned that the array might change over future numpy versions or if I'll use the same code but on different machines or/ OS which will breake my software.

Is it even possible? Should I save the array to file and read it every time?

Any other recommendations for possible constant random arrays?

Thanks for the help!




Generate random integers from successively decreasing ranges in numpy

I want to generate N random integers, where the first integer is uniformly chosen from 0..N, the second is uniformly chosen from 0..(N-1), the third from 0..(N-2), and so on. Is there a way to do this quickly in numpy, without incurring the cost of performing a separate numpy call N times?




mercredi 24 juin 2020

Choosing random lines with replacement from an XY file

I have an XY file with over 40000 unique lines of floating numbers. I want to use bootstrap resampling on this file. Bootstrap resampling works as follows: it resamples N random lines with replacement from the original file. This means the new data set has the same number of lines as the first file and the new dataset can contain some lines multiple times and might not contain some of the original lines at all. I tried shuffling lines using

“shuf -n N input > output”

and

“ sort -R input | head -n N > output”

, but it seems they don’t implement the replacement.

It is deeply appreciated if somebody could introduce a way to do this using AWK and Shell.




How to change the background image of an element randomly?

I have recently created a program which creates new element when someone clicks it. The new element which is created has some specific CSS styling. Now i want it's background to randomly change when the user clicks on button. Like the first time when someone clicks the background is red another time its green and so on like this.. My code is -

function a1click(){
      var body = document.querySelector('body');
        var bubbles = document.createElement("span");
        var size = Math.random() * 100;
        bubbles.style.width = 10 + size+'px';
        bubbles.style.height = 10 + size+'px';
        body.appendChild(bubbles);
        setTimeout(function(){
            bubbles.remove();
        },1000)      
  }
*{
    margin: 0;
    padding: 0;
}
body{
    background: rgb(73, 156, 145);
}
#a1{
    position: relative;
    top: 350px;
    left: 100px;
    width: 30px;
    height: 150px;
    border: 2px solid #fff;
    background: rgb(0, 0, 0);
    float: left;
    cursor: pointer;
    perspective: 600;
}
span{
    position: absolute;
    top: 120px;
    left: 60%;
    width: 50px;
    height: 50px;
    background: #000;
    animation: tweek 1s linear infinite;
    transform-origin: top;
    background-size: cover;
    pointer-events: none;
}
@keyframes tweek {
    0% {
      transform: rotate(90deg) translate(300px);
    }
  
    100% {
      transform: rotate(0deg) translate(250px);
      opacity: 0;
    }
  }
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link rel="stylesheet" href="style.css">
    <title>Document</title>
</head>
<body onkeydown="keypress(event)">
    <div id="a1" onclick="a1click()"></div>
    <script src="script.js"></script>
</body>
</html>

I want the background color of this box to change randomly..Please help, any help is appreciated..




console application where the user has 5 tries to guess number between 1 and 100

I have created a console application where the user has 5 tries to guess number between 1 and 100. After 5 guesses the game ends, but I don’t know how to introduce at the 5th wrong intent something like “you have achieved maximum of guesses! The answer was number (X). I have tried different ways ,but is not working. This is my program

using System;

namespace Guessing_Game_4 { class Program { static void Main(string[] args) {

        var number = new Random().Next(1, 100);
        Console.WriteLine("Try and guess any number between 1-100. You have 5 guesses Max!");

        for (var i = 0; i < 5; i++)
        {

            int guess = Convert.ToInt32(Console.ReadLine());

           
            if (guess == number)
            {
                Console.WriteLine("You got it!");
                break;
            }
            else
            {
                Console.WriteLine(guess + " is not correct! Try again!");

            }
            
    }   }
}

}




JavaScript: Math.random() returning the same numbers. How do I stop this?

I have an array of JavaScript strings, and I want to pick a random string from the array. However, when it runs in Edge and Chrome, it doesn't throw any errors, but it picks the same strings from the array every time. I have looked at other answers on Stack Overflow, but none of them seemed to help. Here is my code:

var arr = ["string1, "string2", "string3", "string4", "string5", "string6", "string7"]; /* 100 quotes in the real array. */
var dis = parseInt(prompt("Enter the number of strings you would like to display."));

if(dis > arr.length) {
    alert("You have entered a number that is too great.");
} else {
    for(var n = 1; n <= dis; n++) {
        document.write(arr[(Math.random() * (arr.length - 1))] + "<br/>");      
    } 
}

Anyone have any code snippets that work for making sure it doesn't pick the same strings?




How to search a file for the last block of consecutive lines that contain a keyword in Perl

Imagine a text file like below where <some random text> could be anything or nothing, implying the KEYWORD can appear anywhere in the line, alone or along with other text:

 1 <some random text>
 2 <some random text>KEYWORD<some random text>
 3 <some random text>KEYWORD<some random text>
 4 <some random text>
 5 <some random text>
 6 <some random text>KEYWORD<some random text>
 7 <some random text>
 8 <some random text>KEYWORD<some random text>
 9 <some random text>KEYWORD<some random text>
10 <some random text>KEYWORD<some random text>
11 <some random text>
12 <some random text>KEYWORD<some random text>
13 <some random text>KEYWORD<some random text>
14 <some random text>
15 <some random text>KEYWORD<some random text>
16 <some random text>

How can I get the last occurrence of 2 or more consecutive lines that contain the keyword (lines 12 and 13 in the example)? To be clear, I am not interested in lines (8, 9, 10) because although they contain the keyword and are consecutive, they are not the last, nor in line 15 because although it contains the keyword and is the last line with keyword, it is not part of 2 or more consecutive lines.




Swift, Random Choice depending on number of users (other techs welcome) [closed]

So, here is the thing... I play Age of Empires 3 with a group of friends everyday... So each night we have to randomly choose a civilization for each player and also if they are going on team 1 or team 2. Sometimes we are 4, others 6, but mostly we are 8 players (and not always the same players) So i had the idea to develop an app where you just type the number of players, their names, and automatically get each player a Civilization and a team (can only be team 1 or 2)

I reached the point where i can do this, but only if we are 8. Any ideas on how to do this?




Creating instance of a class with random arguments in another class in python

How can an instance of a class that requires an argument be created in another class, with the argument generated randomly?

In the code below I have a 'Square' class that takes a 'height' argument. I then create a 'Cube', based on the 'Square'. The problem is with the 'add_cube' method inside the 'CubeTower' class, where I cannot figure out if I need to provide a 'cube' and 'height' or only one of these arguments. This in turn throws an error when I try to call the 'add_cube' inside a loop that creates cubes with a random side height.

(There are additional methods I have in the 'Cube' class, but they are irrelevant to this problem so I did not include them).

from random import randint

class Square:
    def __init__(self, height):
        self.height = height
    
class Cube:
    def __init__(self, height):
        self.base = Square(height)
                
class CubeTower:
    def __init__(self):
        self.tower = []
        
    def add_cube(self, cube, height): # This is where I think I am doing something wrong
        cube = Cube(height)
        if not self.tower:
            self.tower.append(cube)
        else:
            if cube.base.height < self.tower[-1].base.height:
                self.tower.append(cube)
    
    def randomize_tower(self):
        for c in range(2, 100):
            height = randint(1, 100)
            c = Cube(height)
            self.add_cube(c, height)



How to randomly choose N items from array and associate them with the right item from another array?

I have two numpy arrays of 4 items each. The i item of the first array is correlated with the i item of the second array, and so on. I need to randomly choose N items from the first array, but I'd like to keep the 'association' with the second one, so that if I pick item #2 from the first array, item #2 of the second one is chosen too.

A sample of the code I'm currently using:

data = np.array([13170.06, 12552.34,  12420.39, 12336.24])
data2 = np.array([6217.69,  12242.05,  9218.21,  5095.23])

choice = data[np.random.choice(len(data), size=1, replace=False)] #In this way I pick 1 item

Basically, if the code samples 13170.06, I need to associate something like choice2 = 6217.69, or in any case to pick the same i-item also from the second array. How can I do it?




How to generate unique pairs of numbers on python

So I’m working on a chat application right now.. let’s say we have User1, User2, User3, ...UserN. I want to generate a unique port number for each pair. Like User1 and User2 will have 5000, User1 and User3 will have 5070, User2 and User3 will have 5500, etc etc.. basically every User should have a different port number for other users.. but both of the Users should have the same one for each of them.




Stratified random sampling from data frame_follow up

I am trying to randomly sample 50% of the data for each of the group following Stratified random sampling from data frame. A reproducible example using mtcars dataset in R looks like below. What I dont understand is, the sample index clearly shows a group of gear labeled as '5', but when the index is applied to the mtcars dataset, the sampled data mtcars2 does not contain any record from gear='5'. What went wrong? Thank you very much.

> set.seed(14908141)
> index=tapply(1:nrow(mtcars),mtcars$gear,function(x){sample(length(x),length(x)*0.5)})
> index
$`3`
[1]  6  7 14  4 12  9 13

$`4`
[1] 12  7  8  4  6  5

$`5`
[1] 5 1

> mtcars2=mtcars[unlist(index),]
> table(mtcars2$gear)

 3  4 
12  3 



mardi 23 juin 2020

Oracle creating random count of rows per employee

I have the following INSERT statement, which works fine.

I also found some code on the internet that creates a random count of employee records, which works fine.

Can someone provide a solution that merges the random count code into the INSERT statement. Thanks to all who respond.

create table access_history(
   employee_id NUMBER(6), 
   card_num varchar2(10),
   location_id number(4),
   access_date date,
   processed NUMBER(1) default 0
);

INSERT into access_history
 (employee_id,
   card_num,
  location_id,
   access_date)
   with all_combos as
      ( select e.*, l.*
      from   employees e, locations l
     )
    select *
     from (
       select employee_id, card_num,
               location_id, 
             trunc(sysdate) +     dbms_random.value (0, 2) + dbms_random.value (0, .75)
        from   all_combos
        order by dbms_random.value
  );

with
 emps as
    ( select level empid, dbms_random.value(5,20) children from dual connect by level <= 20 ),
  empatt as
    ( select e.empid , x.start_date, x.start_date+dbms_random.value(0,0.75) end_date
      from emps e,
           lateral(
           select
               trunc(sysdate)+dbms_random.value(1,30) start_date
          from dual
           connect by level <= e.children
          ) x
    )

select empid, count(*) from empatt group by empid order by 1;




produce same array in matlab and python with randn

Hello I'm trying to produce the same vector in python and matlab but I'm not able to get it. Someone knows how to do that?

My python code is:

np.random.seed(1337)
A = np.random.randn(1,3)
A = array([[-0.70318731, -0.49028236, -0.32181433]])

My matlab code is:

rng(1337, 'twister');
A = randn(1,3)
A = -0.7832   -0.7012   -0.7178

I would like to both give the same vector...




std::discrete_distribution for large arrays

I need to perform weighted random sampling with replacement. I'm given the input weights as the probabilities themselves so I don't need to normalize. I believe std::discrete_distribution would help me do that.

I'm using it as:

long long int numElements = 1L << 34;
double *probabilities = {0.001, 0.0003 ....... } (Points to an array with 2^34 elements)
std::default_random_engine generator(std::random_device {}());
std::discrete_distribution<int64_t> distribution(probabilities, probabilities + numElements);

This seems to work upto 1L << 33 elements but breaks after that. It returns only 0 or 2^33. I'm running this in a compute environment where memory is not an issue. So I assume that this has to do with the discrete_distribution implementation not supporting integers greater than 33 bits, or an issue with the way I'm using it.

Could someone please help point out if I'm using it incorrectly? Or if there's a better way to accomplish what I'm doing?