jeudi 28 février 2019

Get Random itens from a config and put it in a custom inventory (Bukkit)

Well, Hello, I'm new member here and here's my first post on a dev forum.

I'm doing a quest plugin for minecraft.

Let's go to my question, I've a config.yml file with a list of quests numbered from 0 to 5, each number is a type of quests. Example:

Quest 0 type is Mine. Quest 1 type is Farm. Quest 2 type is KillMob. Etc...

Each type have 15 different quests with a different objectives.

I wanna randomize the type and the quest itself and put 10 of them in the custom inventory I've created, how I do this? Can someone help me please? Any code you need I'll post here, Thanks!!




proxy in class room java programming

    there is voice recorder which store student voice as per roll number on which it was heard earlier. When the attendance process is 
    complete, it will provide a list which would consist of the number of distinct voices.
    teacher presents the list to you and asks for the roll numbers of students who were not present in class. 

    i am trying to find out roll number of absent students in increasing order.

i wrote this case but some test cases are failing. i am not sure what values would be in list which is provided by teacher.

    there are only two inputs :
    1. no of student
    2. result from voice recorder

So can anyone tell what is missing here

public static void main(String args[] ) throws Exception {
     BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        int n = Integer.parseInt(br.readLine());
                 List<Integer> ll = new ArrayList<>();
                 List<Integer> input = new ArrayList<>();
                 for (int i = 1; i <= n; i++) {
                        ll.add(i);
                    }

                 String  lines = br.readLine();    

                    String[] strs = lines.trim().split("\\s+");

                    for (int i = 0; i < strs.length; i++) {
                        input.add(Integer.parseInt(strs[i]));
                    }
             for(int i=0;i<ll.size();i++)
                    {

                        if(input.contains(ll.get(i)))
                        {
                            continue;
                        }
                        else {
                            System.out.print(ll.get(i));
                       if(i!=ll.size()-1)
                                    System.out.print(" ");  




Most efficient way to sample from high dimensional gaussian distribution in Python

Which is the most efficient way to sample some tens of datapoints from a high dimensional distribution in Python (e.g. from a 16K-dimensional Gaussian)? My experiments in numpy, torch and tensorflow, have led me to use tf.random.normal. Is there something faster?




C# Deleting a randomly file

So I have this very interesting program in mind that when i press a button, it deletes a random file in a specific folder (for example, let's say the folder: "C:\Users\User\Desktop\test") Let's say i have 20 files in this folder and each time I press the button it will delete 1 of those files randomly Extemsions should not matter.

I need this for further research in C# and would have no clue where to start, nor have i found ANYTHING similiar on internet like this. Feel free to help. Greetings Luna




C# Deleting a randomly file

So I have this very interesting program in mind that when i press a button, it deletes a random file in a specific folder (for example, let's say the folder: "C:\Users\User\Desktop\test") Let's say i have 20 files in this folder and each time I press the button it will delete 1 of those files randomly Extemsions should not matter.

I need this for further research in C# and would have no clue where to start, nor have i found ANYTHING similiar on internet like this. Feel free to help. Greetings Luna




Break program if file is empty

The code below picks a random word from a file and later delete the word and its working great. I want the program to BREAK when file is empty since I delete every random word picked from the file.

Here is Random part of the code:

import random
import os

g = r"C:\Users\Homer\name.txt"
lines = [line.rstrip('\n') for line in open(g)]
rand = random.choice(lines)       
print(rand)

Is it good to say Break if file is empty and print "file is empty"? Or if Random (rand) return no word, then break and print file is empty.

I have already checked this site and there are some answers on how to check if a file is empty and print file empty or file size is zero or there is not word in file. However, I could find one that say BREAK program if file is empty. I get the error below when my file is empty.

--->rand = random.choice(lines)
IndexError: Cannot choose from an empty sequence

At the moment I'm using the code below to check if file is empty or not. but i keep getting error with the break statement.

if os.path.getsize("name.txt") == 0:
    print("File is Empty")
else:
    print("File is not Empty")
    break


 ----> SyntaxError: 'break' outside loop




Use random library to get two random numbers from list do this step until it sort

Step 1: Take the elements of the list_1 as input. Step 2: randomly choose two indexes i and j within the range of the size of list_1. Step 3: Swap the elements present at the indexes i and j. After doing this, check whether the list_1 is sorted or not. Step 4: Repeat step 3 and 4 until the array is not sorted.




Unity - Get Random Color at Spawning

i have a little issue....i want to spawn Quads in my Scene and they all should have either red or green as Material. But the Random.Range function will only int´s, how could i solve it ??

void SpawningSquadsRnd()
    {
        rndColor[0] = Color.red;
        rndColor[1] = Color.green;

        for (int i = 0; i < 5; i++)
        {
            GameObject quad = Instantiate(squadPrefab, new Vector3(Random.Range(- 23, 23), 1.5f, Random.Range(-23, 23)), Quaternion.identity);
            int index = Random.Range(0, rndColor.Length);

            quad.gameObject.GetComponent<Renderer>().material.color = //Random.Range(0, rndColor.Length);
        }
    }




mercredi 27 février 2019

How to do Big data stratified random sampling (platfrom - python)?

Here I'm attaching python code, data & error, I want to split the data by stratified random sample method,but its getting error.The method I followed is mentioning here, let me know what is wrong with this program.

from sklearn.model_selection import StratifiedShuffleSplit
import pandas as pd

data = pd.read_csv('strat.csv')
data = data[data.columns[0:47]]
req_f = data[data.columns[0:3]]
feature = pd.get_dummies(req_f)
target = data[data.columns[3:]]

sss = StratifiedShuffleSplit( n_splits=5,test_size=0.5, random_state=42)
sss.get_n_splits(feature, target)

for train_index, test_index in sss.split(feature, target):

    x_train = feature.iloc[train_index]
    x_test = feature.iloc[test_index]
    y_train = target.iloc[train_index]
    y_test = feature.iloc[test_index]

print(x_test)
print(y_test)

Where 'strat.csv' looks like:

ReviewerID,ReviewText ,ProductId,C1,C2,C3,C4,C5,C6,C7,C8,C9,C10,C11,C12,C13,C14,C15,C16,C17,C18,C19,C20,C21,C22,C23,C24,C25,C26,C27,C28,C29,C30,C31,C32,C33,C34,C35,C36,C37,C38,C39,C40,C41,C42,C43,C44
1212,good product,14444425,0,0,1,0,1,0,1,0,0,1,1,1,1,1,0,0,1,0,1,0,1,0,1,0,1,1,0,0,1,1,0,0,0,1,0,1,0,1,0,0,0,0,1,1
1233,will buy again,324532,0,0,1,0,1,0,1,0,0,1,1,1,1,1,0,0,1,0,1,0,1,0,1,0,1,1,0,0,1,1,0,0,0,1,0,1,0,1,0,0,0,0,1,1
5432,not recomended,789654123,0,0,1,0,1,0,0,0,1,1,1,0,1,1,0,0,1,0,1,0,1,0,1,0,1,1,0,0,1,1,0,0,0,1,0,1,0,1,0,0,0,0,1,1
1212,good product,14444425,0,0,1,0,1,0,1,0,0,1,1,0,1,1,0,0,1,0,1,0,0,0,1,0,1,0,0,0,1,1,0,1,0,1,0,1,0,1,0,0,0,0,1,1
1233,will buy again,324532,0,0,1,0,1,0,1,0,0,1,1,1,1,1,0,0,1,0,1,0,1,0,1,0,1,1,0,0,1,1,0,0,0,1,0,1,0,1,0,0,0,0,1,1




[![Getting this error][1]][1]

Thank you




Creating a Guessing Game 4 digits

I wanted to make a guessing game. This game should guess a 4 digit number and then tells what number did i guess right and tells the place of the digit whether it is the first second third or fourth digit. Lastly, after guessing the game and checking the correct placements of the number it should also display score. Can someone kindly help me im new in using python and ive done some research but i couldnt find exact answer.




How to convert a date into a random index in a list?

I need something that generates a random item from a list, but that item is randomised every day and is consistent for all users. This is on a website, and thus using JavaScript (although really I just need the algorithm you'd follow, not necessarily the code itself.

I've got day, month, and year stored in variables, but what could I do to convert this into an integer between 0 and list length?

Thanks!




How do I make sure that multiple randomly generated colors aren't too close in hue?

We are building an app that generates several random colors and we need to make sure that no two colors are close together. Are there any good libraries or algorithms for this? (JavaScript)




C cannot get search number in array inside while loop to work and "double free or corruption" error

i'm noob in C programming and I'm sorry for this question which could be very easy, but i cannot solve this problem after searching all the afternoon. I'm trying to write a program that generates a random number, checking that this is not already present in a list contained in the file number.txt. At the end the program has to ask if you want to extract another number and, if Yes, re-run it. I tried various for and while loops but none of these worked: numbers in the list are often extracted, What's wrong?

Moreover, sometimes, after various iterations, the program stops with the error "double free or corruption (! prev)", what causes it?

#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#define rangeMAX 27 //Upper limit of range.
#define rangeMIN 1  //Lower limit of range.


int main()
{
  int get, i, n;
  int num[5];
  char r;
  FILE *filer;
    filer = fopen("numbers.txt", "r");
    printf("When you are ready press any key to continue\n");
    getchar();
    if (filer == NULL)
    {
        printf("ERROR Creating File!");
        exit(1);
    }
    do {
        num[5] = 0;
        n = 0;
        i = 0;
        free(filer);
        get = 0;
        r = 0;
            srand(time(0)); // this will ensure that every time, program will generate different set of numbers. If you remove this, same set of numbers will generated every time you run the program.
            get = ((rand() % (rangeMAX-rangeMIN+1)) + rangeMIN); // generate random number.
        for (n = 0; n < 5; n++){
        fscanf(filer, "%d\n", &num[n]);
        }
            for (n = 0; n < 5; n++){
                if (get == num[n]){
                printf("false\n");
                printf("%d\n", n);
                break;
                }
            }
                i=get;
                printf("%d\n",i);
    printf ("Do you want another number? Y/N ");
    scanf (" %c", &r);
    } while (r == 'y' || r == 'Y');
    return(0);

}




Questions when trying to simulate lottery draws (draw numbers without putting back) using Excel VBA

I was trying to simulate the 649 lottery draw using VBA subroutine. For the lottery draw, six balls will be selected by ball machine, in the beginning there are 49 balls, each with a 1/49 probability of being selected, and after the first ball was selected, the rest 48 balls will then each have a 1/48 probability of being selected, and so on.

There is no direct VBA function to generate random numbers such that the interval is not consecutive; for instance, the first number selected is 3, and for the second number selection, 3 will not be available! So computer has to choose from 1, 2, 4, ..., 49.

Below is a subroutine I wrote, basically I used Int((UBound(array) - 1 + 1) * Rnd + 1) to first generate random number between integer intervals, but I treat the random number only as index; for example, for the second number selection where I have the above 48 number left: 1, 2, 4, ..., 49, now if the random number is 3 (chosen from between 1 to 48), I actually get 4 for the second number selection because it's the 3rd in the list. And Rnd() provides draw from uniform distribution, so each number is equally likely. This is the method I use to get around.

Then I record all previous selected numbers into s1 to s6, and then make them non-repetitive in the subsequent number selection.

At last I sort using a quicksort algorithm found at VBA array sort function? with slight modification to the input array. And output results on an empty worksheet.

I also used Randomize to increase randomness. So everything seems good, I'm mimicking exactly the ball machine does: select the first number, then the second... and at last the sixth, without putting back (non-repetitive), the only difference I think would be ball machine is True random number, whereas VBA is Pseudo random number.

To my surprise, for 100,000 simulations, I used the Remove Duplicates and then 79994 duplicate values found and removed; 20006 unique values remain. Now I feel it is not reliable. How could most draws have duplicates? Tried many time but same thing, lots of duplicates. I'm not sure where has gone wrong, if something wrong with this design and logic, or it's just because Pseudo random number? Thank you all!

Here is my code:

Public k As Long

Sub RNG()

Dim NUMBER(), SELECTION(1 To 100000, 1 To 6)
Dim i As Integer, j As Integer, n As Integer
Dim s1 As Integer, s2 As Integer, s3 As Integer, s4 As Integer, s5 As Integer, s6 As Integer

For k = 1 To 100000
    Erase NUMBER
    ReDim NUMBER(1 To 49)
    For i = 1 To 49
        NUMBER(i) = i
    Next i

    For j = 1 To 6
        'generate random number as index and select number based on index
        Randomize
        random_number = Int((UBound(NUMBER) - 1 + 1) * Rnd + 1)
        SELECTION(k, j) = NUMBER(random_number)
        'record each selection
        Select Case j
            Case Is = 1
                s1 = SELECTION(k, j)
            Case Is = 2
                s2 = SELECTION(k, j)
            Case Is = 3
                s3 = SELECTION(k, j)
            Case Is = 4
                s4 = SELECTION(k, j)
            Case Is = 5
                s5 = SELECTION(k, j)
            Case Is = 6
                s6 = SELECTION(k, j)
        End Select

        'recreate number 1 to 49 by excluding already-selected numbers
        Erase NUMBER
        ReDim NUMBER(1 To 49 - j)

        n = 0
        For i = 1 To 49
            Select Case j
                Case Is = 1
                    If i <> s1 Then
                        n = n + 1
                        NUMBER(n) = i
                    End If

                Case Is = 2
                    If i <> s1 And i <> s2 Then
                        n = n + 1
                        NUMBER(n) = i
                    End If

                Case Is = 3
                    If i <> s1 And i <> s2 And i <> s3 Then
                        n = n + 1
                        NUMBER(n) = i
                    End If

                Case Is = 4
                    If i <> s1 And i <> s2 And i <> s3 And i <> s4 Then
                        n = n + 1
                        NUMBER(n) = i
                    End If

                Case Is = 5
                    If i <> s1 And i <> s2 And i <> s3 And i <> s4 And i <> s5 Then
                        n = n + 1
                        NUMBER(n) = i
                    End If

            End Select
        Next i
    Next j

    Call QuickSort(SELECTION, 1, 6)

Next k

Range("A1:F" & k - 1).Value = SELECTION

End Sub


Public Sub QuickSort(vArray As Variant, inLow As Long, inHi As Long)
'https://stackoverflow.com/questions/152319/vba-array-sort-function

  Dim pivot   As Variant
  Dim tmpSwap As Variant
  Dim tmpLow  As Long
  Dim tmpHi   As Long

  tmpLow = inLow
  tmpHi = inHi

  pivot = vArray(k, (inLow + inHi) \ 2)

  While (tmpLow <= tmpHi)
  While (vArray(k, tmpLow) < pivot And tmpLow < inHi)
    tmpLow = tmpLow + 1
  Wend

  While (pivot < vArray(k, tmpHi) And tmpHi > inLow)
    tmpHi = tmpHi - 1
  Wend

  If (tmpLow <= tmpHi) Then
    tmpSwap = vArray(k, tmpLow)
    vArray(k, tmpLow) = vArray(k, tmpHi)
    vArray(k, tmpHi) = tmpSwap
    tmpLow = tmpLow + 1
    tmpHi = tmpHi - 1
 End If
Wend

If (inLow < tmpHi) Then QuickSort vArray, inLow, tmpHi
If (tmpLow < inHi) Then QuickSort vArray, tmpLow, inHi
End Sub




How do I randomly join the users input to strings stored in an array using random.choice

I need to write a program that will automatically generate unique usernames for students. The usernames have to be six characters long. The program should generate and display a list of student usernames. The program will ask how many usernames are to be generated. For each username, the first three letters of the student’s first name will be entered and then combined with a random ending from the list below: Ing, end, axe, gex, goh For a student with the first name David, the technician would enter Dav. The program will generate the username by RANDOMLY joining Dav to one of the endings. For example – Daving.

This is all I have so far, I would really appreciate it if anyone knows how to use random.choice to randomly combine the students first 3 letters of their name to the endings that are stored in the array. Thank you!

my code so far:

#Initialising the variables
usernames=0
usernameEndings=["ing", "end", "axe", "gex", "goh"]
studentsName=""
#Getting inputs
usernames=int(input("How many ``usernames are to be generated?"))
#proccess
for counter in range(0,usernames):
    studentsName = str(input("Please enter the first three letters of students name."))
        while len(str(studentsName)) <3 or len(str(studentsName)) >3:
        studentsName= str(input("ERROR, please re-enter the first three letters of students name."))




C trying to fix infinite loop

I have a function that gets an index value, puts it in an array. Then generates a new new random index using rand + srand(key). And it checks if the newly generated index is in array already, it will will keep on generating new index and checking until a unique value is generated.

The problem is that it works fine for small keys, but at longer keys it gets stuck in an infinite loop and can never find a unique value. Here's my code:

int getNewIndex(PPM *im, int index, int *visitedPixels, int *visitedPixelsIndex) {

    int i = 0;

    visitedPixels[*visitedPixelsIndex] = index;
    (*visitedPixelsIndex)++;
    // If index is already in the list, generate a new number and check again.
    while (i < *visitedPixelsIndex) {
        (index == visitedPixels[i]) ? index = rand() % im->height, i = 0 : i++;
    }

    return index;
}

EDIT: im->height which is the image height is about 400-600 in average.




mardi 26 février 2019

Modify a random value of a list at any point regardless of depth

I have a list that can be of any depth or length. By this I mean I could have a list like so:

lst = [1,2,3]

Or:

lst = [[2,233],[[[4,5],[66.33]],[[24,88.65,103,2200.0],[-44.2,-8,5]]], [[[[[[[[5]]]]]]]]]

and what I would like to do is modify a single one of any of these numerical values in the list. I'm aware I could do something dodgy by converting the list to a string, but if there is a standard way of doing this, an answer pertaining to such would be appreciated!




Sampling on conditions within another column

How can I randomly sample 2 reports that have weights between 0.5 - 1.0

Also; How can I randomly sample 20% of reports that have weights between 0.5 - 1.0

DF <- data.frame(Report_ID=c(2,8,12,15,16, 51,67,89,88,98),
                        Weight=c(0.05,0.1,0.25,0.30,0.35,0.56,0.75,0.81,0.95,1.0))




Deleting a name from a text file in Python

Can someone check the code for me? I have three set of codes. The first part draws a random name from a file, name.txt and then displays it. The second code copies the drawn name into another file name2.txt and the third code is suppose to delete the drawn name from the first file. this is where I'm struggling to get it right. any help would be appreciated.

  import random

  #File path    
  g = r"C:\Users\Homer\name.txt"  
  lines = [line.rstrip('\n') for line in open(g)]

  #draw a random word  
  rand = random.choice(lines)

  # Display random word 
  print(rand) 

  # Append random word to name2.txt 
  with open("name2.txt",'a') as k:
        k.write(rand)
        k.write("\n")
        k.close()

  # Delete random word from orignal file (name.txt)
  g = with open("name.txt",'w')      
  lines = [line.rstrip('\n') for line in open(g)]        
  g.pop(rand)




Random in Java, repeating same number

My code:

public class SkillsDemoTwoCrapsGameClass {

public static void main(String[] args) {
    RandomNumber diceRoll = new RandomNumber(); //Create instance diceRoll of class RandomNumber
    play playGame = new play(); //Create instance playGame of class play


    //Initialise variables from play class
    playGame.diceRoll = diceRoll.randNum;
    playGame.point = playGame.diceRoll;
    playGame.newPoint = diceRoll.randNum;

        System.out.println("WELCOME TO A GAME OF CRAPS!");

        if(playGame.diceRoll == 7 || playGame.diceRoll == 11){
            //Show the users point
            System.out.println("Point: " + playGame.point);
            System.out.println("------------------------------");

            //Tell user they won
            System.out.println("Congratulations you won, with a " + playGame.diceRoll);
        }
        else if(playGame.diceRoll == 2 || playGame.diceRoll == 3|| playGame.diceRoll == 12){
            //Show the users point
            System.out.println("Point: " + playGame.point);
            System.out.println("------------------------------");

            //Tell the user they lost
            System.out.println("Sorry you lost, with a " + playGame.diceRoll);
        }
        else{
            System.out.println("Point: " + playGame.point);
            System.out.println("------------------------------");

            while(playGame.point != playGame.newPoint || playGame.point == playGame.newPoint){
                /*
                BUG: (2/2/19)
                    User will receive their original roll again, causing them to always win
                */
                //Roll dice again for the new point
                playGame.newPoint = diceRoll.randNum;

                //Checks if the user can win
                if(playGame.point == playGame.newPoint){
                    System.out.println("Your new roll: " + playGame.newPoint + "\t\t Win");
                    break;
                }
                //Checks if the user has lost
                else if(playGame.newPoint == 7){
                    System.out.println("Your new roll: " + playGame.newPoint + "\t\t Lose");
                    break;
                }
                //Check if user needs to roll again
                else{
                    System.out.println("Your new roll: " + playGame.newPoint + "\t\t No help");    
                    }
            }
        }
    }
    }

    class RandomNumber{
     Random rand = new Random();
     int randNum = rand.nextInt(12) + 1;    
    }

    class play{
    int diceRoll, point, newPoint;
    }

The above code is for a game of Craps, my problem is when the user needs to get a new point. Instead of a new random number being assigned, they receive the same number as before. Is there a way to call the RandomNumber class, and get a new random number to assign to the newPoint variable?

Thanks




c# Flawed random generator [duplicate]

This question already has an answer here:

This is simulation of the famous St. Petersburg Paradox

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Sorrow
{
    class Program
    {
        static void Main(string[] args)
        {
            Random rnd = new Random(Environment.TickCount);
            double totalSum = 0;
            int bigWins = 0;
            double iterations = 1000;
            for (int z = 0; z < 10; z++)
            {
                iterations *= 10;
                for (double i = 1; i < iterations; i++)
                {
                    int sum = 2;
                    int a = 1;
                    while (a == 1)
                    {
                        //generate a random number between 1 and 2
                        a = rnd.Next(1, 3);

                        if (a == 1)
                        {
                            sum *= 2;
                        }
                        if (sum > 8000)
                        {
                            // if the sum is over 8000 that means that it scored 1 13 times in a row (2^13) - that should happen
                            //once every 8192 times. Given that we run the simulation 100 000 000 times it should hover around 
                            // 100 000 000/8192
                            //However is much , much bigger
                            bigWins++;
                        }
                    }

                    totalSum += sum;

                }

                Console.WriteLine("Average gain over : "+iterations+" iterations is:" + totalSum / iterations);
                Console.WriteLine("Expected big wins: " + iterations / 8192 + " Actual big wins: " + bigWins);
                Console.WriteLine();
            }


        }
    }
}

As you can see we should expect 7 times smaller number. That means that c# random is very prone to choosing the same number over and over again? Is it true or there is something wrong with my code? How can we fix it to true random?




Vectorizing np.random.binomial for accepting a multidimensional array

I have an array, let us say a three-dimensional of size (3,3,3):

M = np.arange(27).reshape((3,3,3))

What I would like to achieve, is to apply the numpy.random.binomial function, like:

X[i,j,k] = (n=M[i,j,k], p=0.5 , size=1)

This should be easy with for loops, but for large arrays, not the best idea.

A possible solution would be:

def binom(x):
   fis = int(np.random.binomial(x,p=0.5,size=1))
   return fis

X = np.vectorize(binom)(M)

It works fine, but np.vectorizeis basically a well-disguised for equivalent, so not much of an improvement for larger arrays. I am sure that there are way cheaper and faster solutions.




randomly generate specific pattern 5 digit number with minimum and maximum 2 similar digits with javascript / node

I'm trying to find a way to generate 5 digit number with the specific pattern :

  • The digits can't be : 12345 or 54321
  • The digits should have at minimum and at maximum 2 occurrences exemple : 84262 is acceptable but 87249 is not.

I've been trying to use regex exec and math floor but i can't seem to find a solution.




lundi 25 février 2019

Fill a matrix without using for()

I have a long matrix which I want to fill with rnorm(1) but it takes much time (unlike this sample below). Is there an alternative way since the number of rows and columns will always be equal but dynamic.

my <- matrix(c(0), nrow= 3, ncol = 3)
for (i in 1:3){
  for (j in 1:3){
    my[i,j]<-rnorm(1)
  }
  }




how to fix: Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException" for boolean array of random numbers in java

I am making a program where I get how many random numbers they want and the highest number they want to go up to, but when I run the code it does not give me the amount of numbers they asked for. it either gives me 1 number or none. Then it says "Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 9 at practice4.practice4.main(practice4.java:38)" in red.

double randomNum;
        int highestNumber, numsInLottery, display;
        boolean[] numberUsed;

        System.out.println("Welcome to the Lottery Number Generator!");

        System.out.println("How many numbers are in your lottery?");
        numsInLottery = TextIO.getInt();

        System.out.println("What is the highest possible number?");
        highestNumber = TextIO.getInt();


        numberUsed= new boolean [numsInLottery];

        for (int index = 0; index < numsInLottery; index++)
        {
        numberUsed [index]= false;

        while(index < highestNumber)
        {
            do
            {

                randomNum = Math.random() * highestNumber + 1;
                display = (int) randomNum ;

            } while (numberUsed [display - 1 ] ); 

        System.out.print(display + " ");
        numberUsed [display + ] = true;

        }   
        }
        }   
        }

before I had numberUsed= new boolean [numsInLottery]; I accidentally put highestNumber where numsInLottery is. when I had that it would give me all the numbers. but now that I have changed it it does not work any more this is what I get now

Welcome to the Lottery Number Generator!
How many numbers are in your lottery?
6
What is the highest possible number?
? 30
1 Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 21
    at practice4.practice4.main(practice4.java:35)




How to randomly generate an abject from array of objects with no reputation in JavaScript

I have 5 objects in an array with properties. I want to randomly generate one from the objects without reputation. I want the random to loop only after all the 5 objects within the array are generated. How can I achieve that?




Sample from a 2d probability numpy array?

Say that I have an 2d array ar like this:

0.9, 0.1, 0.3
0.4, 0.5, 0.1
0.5, 0.8, 0.5

And I want to sample from [1, 0] according to this probability array.

rdchoice = lambda x: numpy.random.choice([1, 0], p=[x, 1-x])

I have tred two methods:

1) reshape it into a 1d array first and use numpy.random.choice and then reshape it back to 2d:

np.array(list(map(rdchoice, ar.reshape((-1,))))).reshape(ar.shape)

2) use the vectorize function.

func = numpy.vectorize(rdchoice)
func(ar)

But these two ways are all too slow, and I learned that the nature of the vectorize is a for-loop and in my experiments I found that map is no faster than vectorize.

I thought this can be done faster. If the 2d array is large it would be unbearably slow.




Why does the merseen_twister_engine guarantee certain results?

I note the following on cppreference's article for std::mersenne_twister_engine (e.g. std::mt19937):

The 10000th consecutive invocation of a default-constructed std::mt19937 is required to produce the value 4123659995.

The 10000th consecutive invocation of a default-constructed std::mt19937_64 is required to produce the value 9981545732273789042.

Assuming that this interpretation of the standard is accurate, what's the deal? Why do these guarantees exist? Isn't this non-random?




C++

I want to generate random numbers outside the main function but even when using the library and seeding the random number generator, the output is not random. Any help is appreciated.

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

int foo(std::mt19937 rng)
{
    std::uniform_int_distribution<int> distr(0, 9);

    return distr(rng);
}

int main()
{
    std::random_device rd;
    std::mt19937 rng(rd());

    for (int j=0; j<10; j++)
    {
        std::cout << foo(rng) << " ";
    }
    return 0;
}

With output

5 5 5 5 5 5 5 5 5 5




Generating random solution in python - Tabu Search - Graph

I want to implement Tabu Search in Python to solve a problem related to a Graph (finding trees, coloring problem and that kind of stuff). I have written basic codes in Python and that's the first time I am writing something like that. I know how the algorithm works (in theory) and I am having some trouble to implement it.

What's the best way to generate the random solution so I can start the algorithm? I have to generate a random tree. I have a .txt file with the information about the graph I already have, and from this graph I have to generate a random tree (doesn't matter the size of it)

I am reading and looking for libraries and would be nice if anyone could share some ideas, hints or useful links. Thank you!




Random boolean array with fixed number of True and False Python [duplicate]

This question already has an answer here:

I want to create an array with fixed number of True and False. Here is the code to generate random array of True and False:

np.random.choice(a=[False, True], size=(N, N), p=[p, 1-p])

This code will give me an array of N*N with probability of p for False and 1-p for True. Now I want to set fixed number of False and True. How can I do it in Python?

Here are some other related questions but are not the same as what I'm asking:

Example in C

Example in C#

Example but without specific number of True and False




Creating random, unique pairs based on values from other columns and then pasting values from pair's column in R

I'm hoping to randomly pair up study participants (in the "Rater" column) with other study participants (in the "Rater" column) and create a new column titled "Paired_Partner" with the person who the participant was paired with (the value from the Rater column).

However, these pairs are supposed to come from the same groups (Group_Subsets; Group 1, Group 2, Group 3, or Group 4). Each Group (Groups 1, 2, 3, and 4) has 10 raters, but Group 1 and Group 3 have 23 Donors and Group 2 and Group 4 have 20 Donors.

After these pairs are made, I'm hoping to take 4 numbers from 4 consecutive rows from a particular column (e.g., Snap_judgments, or perhaps something else, like predictions_SnapOnly) that correspond with an already pre-existing pair (e.g., the values housed in the rows for Rater p01a and Donor p13a). The Index column (know, nothang, friends, activity) corresponds with what these 4 values are. This new column would be titled Partners_judgments (or Partners_predictions_SnapOnly).

Here is a picture of the data I'm working with: https://i.stack.imgur.com/rSocb.png

Any help will be greatly appreciated.




C++

beginner at C++ here.

I have been generating random numbers in C++ using the following function:

double randDouble() {
    std::random_device rd;
    std::mt19937 mt(rd());
    std::uniform_real_distribution<double> dist(1.0, 10.0);
    return dist(mt);
}

I was wondering why I am unable to do this in say a single line, (using temporary objects) like so:

double randDouble2() {
    return std::uniform_real_distribution<double>{1.0, 10.0}(std::default_random_engine(std::random_device{}()));
}

I think I read somewhere it is something to do with the default constructor not being explicit for these classes, but I'm not really sure what to search to find out whether I am correct?

I have also read that this would be bad practice since creating a new random_device for every call would be quite expensive, however, I am interested in why the one-liner is not possible rather than not practical - that is to say I am interested in the general case for creating anonymous objects (unsure whether this is the right term).




JavaScript Choose your own adventure game random number function in loop problem

I'm writing a choose your own adventure program where If a specific option is chosen (example to wait) the user gets a random number between 1-10 to do push ups(the push-ups would be the user clicking on the prompt "ok" button however many times the random number is equal to) here's my code so far but I keep getting errors. I'm a complete noob so go easy on me.

 var count = Math.floor((Math.random() * 10) + 1);
var setsOf10 = false;
function pushUps() {
  alert("Nice! Lets see you crank out " + pushUps + "!");
}
if (setsOf10 == pushUp) {
    alert("Nice! Lets see you crank out " + pushUp + "!");
    setsOf10 = true;
  }
for (var i=0; i<count; i++){
  pushUps();
}
  else {
    alert("Really, thats it? Try again");
  }

while ( setsOf10 == false);
}




how to fix: boolean array for random lottery number program. "can't convert int to boolean"

I need to make a random lottery generator for class with a boolean array. at first i made it with an int array and it worked perfectly fine but when i changed the int array to a bool array i got an error that says "Type mismatch: cannot convert from int to boolean". I'm wondering how to fix my code so this will work.

    int highestNumber, numsInLottery, randomNum;
    //int[] lottery = new int[numsInLottery];

    System.out.println("Welcome to the Lottery Number Generator!");
    System.out.println("How many numbers are in your lottery?");
    numsInLottery = TextIO.getInt();
    System.out.println("What is the highest number in your lottery?");
    highestNumber = TextIO.getInt();

    boolean[] lottery = new boolean[numsInLottery];

    for(int i = 0; i < numsInLottery; i++)
    {
        randomNum = (int)(Math.random() * highestNumber);
        for(int x = 0; x < i; x++ )
        {

            /*if (lottery[x] == randomNum)
            {
            randomNum = (int)(Math.random() * highestNumber);
            x = -1;
            }*/
        }   
        lottery[i] = randomNum;
        System.out.print(lottery[i] + " ");
    }

        //System.out.print(lottery[i] + " ");
    }
}




Randomization of words in PHP

I'm trying to code a small emailing script and I am wondering how I can add text in a format like {Hello|Hi|Hey|Hola} in my text only email template and every time one word would randomly be used in the email.

Can someone give me any hint on how I can do that?

Thanks for reading




Fastest precise way to convert a vector of integers into floats between 0 and 1

Consider a randomly generated __m256i vector. Is there a faster precise way to convert them into __m256 vector of floats between 0 (inclusively) and 1 (exclusively) than division by float(1ull<<32)?




How to get Random Images from a Thumbnail Click

Morning everyone, I've got a particular issue with an assignment of mine.

The assignment is called Random Otters.

  1. Design the Ottergram base page. DONE.
  2. Apply given CSS styles. DONE.
  3. Add thumbnail-scroll menu to the side. DONE.
  4. Develop javascript functions to transition between images. DONE.
  5. Alter/Add to the code so one of the icons shows random images instead of the chosen otter. In Progress.

My teacher's instructions for this last part are as follows:

  1. Use a random number generator to pick out one of the thumbnail images.
  2. When that image is clicked, show a random image instead of the otter.
  3. Use an array to store images and math.random to select the thumbnail.

OK, so I know I'll need something along the lines of:

var pic = new 
Array("images/pic1.jpg","images/pic2.jpg","images/pic3.jpg");

function choosePic() {
var randomNum = Math.floor(Math.random() * pic.length);
document.getElementById("newPic").src = pic[randomNum];

However, I'm not certain how to implement it with the code I've already written. I know I'll need the math.random but I don't know how it applies to a series of thumbnails. I've had some practice with button clicks randomizing images and window.onload but I'm admittedly lost with this one.

Anyway here's the HTML:

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Ottergram</title>
<link rel="stylesheet" 

</head>
<body>
    <header class="main-header">
        <h1 class="logo-text">Ottergram</h1>
    </header>
    <main class="main-content">
    <ul class="thumbnail-list">
        <li class="thumbnail-item">
            <a href="img/barry.jpg"
                                    data-image-role="trigger"
                                    data-image-title="Stayin' Alive"
                                    data-image-url="img/barry.jpg">
                <img class= "thumbnail-image" src="img/barry.jpg" alt="">
            <span class="thumbnail-title">Barry</span>
            </a>
        </li>
        <li class="thumbnail-item">
            <a href="img/robin.jpg"
                                   data-image-role="trigger"
                                   data-image-title="How Deep Is Your Love"
                                   data-image-url="img/robin.jpg">
                <img class= "thumbnail-image" src="img/robin.jpg" alt="">
                <span class="thumbnail-title">Robin</span>
            </a>
        </li>
        <li class="thumbnail-item">
            <a href="img/maurice.jpg"
                                   data-image-role="trigger"
                                   data-image-title="You Should be Dancing"
                                   data-image-url="img/maurice.jpg">
                <img class= "thumbnail-image" src="img/maurice.jpg" alt="">
                <span class="thumbnail-title">Maurice</span>
            </a>
        </li>
        <li class="thumbnail-item">
            <a href="img/lesley.jpg"
                                    data-image-role="trigger"
                                    data-image-title="Night Fever"
                                    data-image-url="img/lesley.jpg">
                <img class= "thumbnail-image" src="img/lesley.jpg" alt="">
                <span class="thumbnail-title">Lesley</span>
            </a>
        </li>
        <li class="thumbnail-item">
            <a href="img/barbara.jpg"
                                    data-image-role="trigger"
                                    data-image-title="To Love Somebody"
                                    data-image-url="img/barbara.jpg">
                <img class= "thumbnail-image" src="img/barbara.jpg" alt="">
                <span class="thumbnail-title">Barbara</span>
            </a>
        </li>
    </ul>

    <div class="detail-image-container">
        <div class="detail-image-frame">
            <img class="detail-image" data-image-role="target" src="img/barry.jpg" alt="">
            <span class="detail-image-title" data-image-role="title">Stayin' Alive</span>
        </div>
    </div>
    </main>
    <script src="scripts/main.js" charset="utf-8"></script>
</body>
</html>

Here's the css, though I don't know if I'll be manipulating much in it.

@font-face{
font-family: 'lakeshore';
/*src: url('fonts/LAKESHOR-webfont.eot');*/
/*src: url('fonts/LAKESHOR-webfont.eot?#iefix') format('embedded-opentype'),*/
    /*url('fonts/LAKESHOR-webfont.woff') format('woff'),*/
    /*url('fonts/LAKESHOR-webfont.ttf') format('truetype'),*/
    /*url('fonts/LAKESHOR-webfont.svg#lakeshore')format('svg');*/



font-weight: normal;
font-style: normal;
}


@font-face{
font-family: 'airstreamregular';
/*src: url('fonts/Airstream-webfont.eot');
src: url('fonts/Airstream-webfont.eot?#iefix') format('embedded-opentype'),
url('fonts/Airstream-webfont.woff') format('woff'),
url('fonts/Airstream-webfont.ttf') format('truetype'),
url('fonts/Airstream-webfont.svg#airstreamregular')format('svg');*/

font-weight: normal;
font-style: normal;
}

html, body{
    height: 100%;
}

body{
    display: flex;
    flex-direction: column;

    font-size: 10px;
    background: rgb(149, 194, 215);
}

a {
text-decoration: none;
}

.main-header{
flex: 0 1 auto;
}

.logo-text{
background: white;

text-align: center;
text-transform: uppercase;
font-family: Algerian, serif;
font-size: 37px;
}

.main-content{
flex: 1 1 auto;
display: flex;
flex-direction: column;
}

.thumbnail-list{
flex: 0 1 auto;
order: 2;
display: flex;
justify-content: space-between;
list-style: none;

white-space: nowrap;
overflow-x: auto;
}

.thumbnail-item{
display: inline-block;
min-width:120px;
max-width: 120px;
border: 1px solid rgb(100%, 100%, 100%);
border: 1px solid rgba(100%, 100%, 100%, 0.8);

transition: transform 133ms ease-in-out;
}

.thumbnail-item:hover{
transform: scale(1.01);
}

.thumbnail-style{
list-style: none;
}

.thumbnail-image{
display: block;
width: 100%;
}

.thumbnail-title{
display: block;
margin: 0;
padding: 4px 10px;

background: rgb(96, 125, 139);
color: rgb(202, 238, 255);

font-size: 18px;
}

.detail-image-container{
flex: 1 1 auto;
display: flex;
justify-content: center;
align-items: center;
}

.detail-image-frame{
position: relative;
text-align: center;

transition: transform 333ms cubic-bezier(1,.06,.28,1);
}

.is-tiny{
transform: scale(0.001);
transition: transform 0ms;
}

.detail-image{
width: 90%;
}

.detail-image-title{
position: absolute;
bottom: -16px;
left: 4px;

font-family: "Freestyle Script", serif;
color: white;
text-shadow: rgba(0,0,0,0.9) 1px 2px 9px;
font-size: 60px;
}

.hidden-detail .detail-image-container{
display: none;
}

.hidden-detail .thumbnail-list{
flex-direction: column;
align-items: center;
}

.hidden-detail .thumbnail-item{
max-width: 80%;
}

@media all and (min-width: 768px){
.main-content{
    flex-direction: row;
    overflow: hidden;
}
.thumbnail-list{
    flex-direction: column;
    order: 0;
    margin-left: 20px;

    padding: 0 35px;
}

.thumbnail-item{
    max-width: 260px
}

.thumbnail-item + .thumbnail-item{
    margin-top: 20px;
}
}

And lastly the .js:

var DETAIL_IMAGE_SELECTOR = '[data-image-role="target"]';
var DETAIL_TITLE_SELECTOR = '[data-image-role="title"]';
var DETAIL_FRAME_SELECTOR = '[data-image-role="frame"]';
var THUMBNAIL_LINK_SELECTOR = '[data-image-role="trigger"]';
var HIDDEN_DETAIL_CLASS = 'hidden-detail';
var TINY_EFFECT_CLASS = 'is-tiny';
var ESC_KEY = 27;

function setDetails(imageUrl, titleText){
    'use strict';
    var detailImage = document.querySelector(DETAIL_IMAGE_SELECTOR);
    detailImage.setAttribute('src', imageUrl);

    var detailTitle = document.querySelector(DETAIL_TITLE_SELECTOR);
    detailTitle.textContent = titleText;
}

function imageFromThumb(thumbnail){
    'use strict';
    return thumbnail.getAttribute('data-image-url');
}

function titleFromThumb(thumbnail){
    'use strict';
    return thumbnail.getAttribute('data-image-title');
}

function setDetailsFromThumb(thumbnail){
    'use strict';
    setDetails(imageFromThumb(thumbnail), titleFromThumb(thumbnail));

}

function addThumbClickHandler(thumb){
    'use strict';
    thumb.addEventListener('click', function (event)
    {
        event.preventDefault();
        setDetailsFromThumb(thumb);
        showDetails();
    });
}

function getThumbnailsArray(){
    'use strict';
    var thumbnails = document.querySelectorAll(THUMBNAIL_LINK_SELECTOR);
    var thumbnailArray = [].slice.call(thumbnails);
    return thumbnailArray;
}

function hideDetails(){
    'use strict';
    document.body.classList.add(HIDDEN_DETAIL_CLASS);
}

function showDetails(){
    'use strict';
    var frame = document.querySelector(DETAIL_FRAME_SELECTOR);
    document.body.classList.remove(HIDDEN_DETAIL_CLASS);
    frame.classList.add(TINY_EFFECT_CLASS);
    setTimeout(function (){
    frame.classList.remove(TINY_EFFECT_CLASS);
    }, 50);
}

function addKeyPressHandler(){
    'use strict';
    document.body.addEventListener('keyup', function(event){
        event.preventDefault();
        console.log(event.keyCode);
        if (event.keyCode ===ESC_KEY){
            hideDetails();
        }
    });
}

function initializeEvents(){
    'use strict';
    var thumbnails = getThumbnailsArray();
    thumbnails.forEach(addThumbClickHandler);
    addKeyPressHandler();
}

initializeEvents();

I could really use some help here.




Randomize stylesheet.css per page visit

I have a quick question what the best practice approach is with JS or Jquery concerning the randomization of stylesheets.

I plan to 5 to 6 different stylesheet.css documents handling only color elements (background, href, color). What I try to achieve is to randomize which stylesheet file (For example red, green, black, white) is loaded per user visit.

Is there a JS library for this purpose or a common practice in use already?




JavaScript | Genetate a table with conditions

Hello everyone

I need to generate a table like this :

enter image description here

but with lot of condition :

1 index[0] must be between 0 & 9

2 index[n] depends on the sum of prev indexs

 let's define a variable sum of all prev indexs

IF ( sum == 0 ) => index [n+1] can be a number between 0 & 9

IF ( sum == 1 ) => index[n+1] can be one of this array [-1,0,1,2,3,5,6,7,8]

IF ( sum == 2 ) => index[n+1] can be one of this array [-2,-1,0,1,2,3,5,6,7]

IF ( sum == 3 ) => index[n+1] can be one of this array [-3,-2,-1,0,1,2,3,5,6]

IF ( sum == 4 ) => index[n+1] can be one of this array [-4,-3,-2,-1,0,1,2,3,5]

IF ( sum == 5 ) => index[n+1] can be one of this array [-5,0,1,2,3,4]

IF ( sum == 6 ) => index[n+1] can be one of this array [-6,-5,-1,0,1,2,3]

IF ( sum == 7 ) => index[n+1] can be one of this array [-7,-6,-1,-2,0,1,2]

IF ( sum == 8 ) => index[n+1] can be one of this array [-8,-7,-6,-5,-3,-2,-1,0,1]

IF ( sum == 9 ) => index[n+1] can be one of this array [-9,-8,-7,-6,-5,-4,-3,-2,-1,0]

i need a script that allow me to generate tables




GOlang Random number + database

I am curious to look at how I would make this work, My idea is: Whenever i run the program i want it to generate a Random number, this number should be logged in some document so it wont EVER generate this number twice.

package main

import (
"fmt"
"math/rand"
"time"
)

func random(min int, max int) int {
return rand.Intn(max-min) + min
}

// NummerGenerator between 1 & 99999
func main() {
rand.Seed(time.Now().UnixNano())
randomNum := random(1, 99999)
fmt.Printf("Random Num: %d\n", randomNum)
}

(this would be the Number generator)




How does IntRange.random() introduce entropy in Kotlin

I'm planning on using IntRange.random() (i.e. (0,9999).random()) to generate a random 5 digit code in Kotlin. It's important that malicious people cannot predict the sequence of numbers that will be generated.

Does IntRange.random() ensures that there is entropy when generating these numbers? i.e. How is the seed generated and is a new seed generated each time IntRange.random() is called?

Thanks!




dimanche 24 février 2019

Random multiple image wpf c#

How to random four product (image, name, price) from 10 product in resource when windows_load. Help me, i'm newbieenter image description here




Python create combinations of ID's based on conditions

Hi I would like to create combinations of ID's. I know how to create all possible combinations but am stuck on one final part of the operation. Any help will be greatly appreciated.

I have a dataset as follows:

import pandas as pd from itertools import combinations_with_replacement

d1 = {'Subject': ['Subject1','Subject1','Subject1','Subject2','Subject2','Subject2','Subject3','Subject3','Subject3','Subject4','Subject4','Subject4','Subject5','Subject5','Subject5'],
'Actual':['1','0','0','0','0','1','0','1','0','0','0','0','1','0','1'],
'Event':['1','2','3','1','2','3','1','2','3','1','2','3','1','2','3'],
'Category':['1','1','2','1','1','2','2','2','2','1','1','1','1','2','1'],
'Variable1':['1','2','3','4','5','6','7','8','9','10','11','12','13','14','15'],
'Variable2':['12','11','10','9','8','7','6','5','4','3','2','1','-1','-2','-3'],
'Variable3': ['-6','-5','-4','-3','-4','-3','-2','-1','0','1','2','3','4','5','6']}
d1 = pd.DataFrame(d1)

I want to create all possible combinations of the subjects within each event within each tier. This is done by (from a previous question Form groups of individuals python (pandas)):

L = [(i[0], i[1], y[0], y[1]) for i, x in d1.groupby(['Event','Category'])['Subject'] 
                          for y in list(combinations_with_replacement(x, 2))]
df = pd.DataFrame(L, columns=['Event','Category','Subject_IDcol1','Subject_IDcol2'])

Now, I want to take only those pairs for which Actual = 1 and randomly select "n" Subjects for which Actual = 0. Here for simplicity sake let's take n = 1. I want to run the function combinations_with_replacement on this new list.

The output that I want to get for example (assuming random selection) is something like this:

For event 1, category 1: Subject 1 and 5 have Actual = 1 and suppose Subject 2 is randomly drawn.

enter image description here

As compared to this, in the previous case, the result was something like this (for event =1 and category =1)

enter image description here

Any help will be appreciated. Thanks.




(Javascript) How do I get a random number in between two user inputted variables?

I am working on an assignment and I am having difficulty writing up the function to get a random number between two variables.

Basically what I want is the script to prompt you for the first number followed by the second then give me a random number in between those two.

How do I get a random whole number in between two user inputted variables? What I am doing wrong? Here's my code:

var age = prompt("How old are you?");
var videogames = prompt("How many hours of video games have you played last month?");

function getRndInteger(age, videogames) {
  return Math.floor(Math.random() * (videogames - age)) + age;
}
document.write(getRndInteger(age, videogames));



How do I only get 2 decimals when printing a double?

I have 2 questions that connect to each other.
1) I am working on a project where I need to add the gpa of 4 students to find the average. The gpa can only go to two decimal places when printed out, but I have not been able to figure out what's wrong with my code. Or find another simpler way to print out the answer. 2) Every time I click on the buttons for the student gpa it's supposed to change and be recalculated, same should happen to the average. It will do that but if I myself add the gpa's of the students and divide by four the average gpa is no where near where it should be and I don't understand why that is happening. This code is from my group.java class that calculates the average gpa

double averageGPA()
{
    double average = (sd1.GPA + sd2.GPA + sd3.GPA + sd4.GPA) / 4;
    return Double.toString("%.2f", average);// Double.format("%.2f", average) does not work either
}

This is my code from student.java class that calculates the 4 gpa's randomly.

 String getInfo()
{
   GPA = Math.random();
   myRandomNumber = (GPA *4.0);
   return "NAME = " + firstName + " " + lastName + " " + String.format("%.2f", myRandomNumber);

}

an example of when the I run the code: student 1: 2.34 student 2: 0.19 student 3: 2.66 Student 4: 2.94 Average = .5079037

when the actual average should be 2.03




On each submit to show a new random array class of random array subclass

I'm creating a lorem ipsum app and I want to click on a button to generate random quotes from a random character. And there will be no mixing of quotes between characters. However, every time I click submit it only shows random quotes from the first character I list in my array. How can I fix this?

const aQuotes = require("./public/quotes/a");
const bQuotes = require("./public/quotes/b");
const cQuotes = require("./public/quotes/c");

const loremIpsum = new GenerateNewText();
function GenerateNewText(){}

GenerateNewText.prototype.getRandomSentence = function() {
  const charQuotes =
  [
    aQuotes,
    bQuotes,
    cQuotes,
  ]
  for(var i = 0; i < charQuotes.length; i++){
    let randomSentence = charQuotes[i][Math.floor(Math.random() * charQuotes[i][Math.floor(Math.random())].length)]
    return randomSentence;
  }
}

When I run the example above, it'll show a random list of quotes stored in aQuotes with the word "undefined" sprinkled throughout. If I were to move bQuotes to the top of the array, then it will show random bQuotes only, also with the word "undefined". Why is it only showing the results of the first element in the array and why is "undefined" showing (i.e. aQuotes)?

const aQuotes = [
    "Lalalalalalalala.",
    "Blah blah blah blah.",
    "Blank Blank Blank Blank Blank." 
]

module.exports = aQuotes;

I tried doing charQuotes[i][Math.floor(Math.random())].length * charQuotes[i][Math.floor(Math.random())].length thinking that it will first randomize the charQuotes array and then randomize the individual a/b/cQuotes array but it ended up returning a block of the number 169. Other "fixes" I've attempted resulted in paragraphs of all undefined text, paragraphs of all NaN, or showing all the quotes for all the characters with the word "undefined" interjected here and there.

How can I randomize the charQuotes array AND the content in my a/b/cQuotes array with every click? And get rid of the weird "undefined" texts that come up?

I am using Node and Express.




Generate 15 random numbers that may be the same 2 times but not 3 times

I am working on a scratch card in PHP and i need to build the backbone behind it.

My plan is as following: 1. Generate 15 random numbers ( there are 8 containers and 15 images to choose from. ). 2. Each number correspondences with a image ( 1 is image 1, 2 is image 2 etc. ). 3. Show a random image (1/15) on container 1, show random image (1/15) on container 2 etc. There are 8 containers to be filled.

What i currently can't figure out is to check if there are duplicate numbers, and if so it is fine to have 2 duplicates but not 3 since that would mean a win.

What i have now is this:

$images = array();
for ($i = 0; $i < 8; $i++) {
    $random[$i] = rand(1,15);
}

This will fill $random with 15 numbers i can use. Now i want to check if within those 15 there are duplicates. But the trick is that duplicates are no problem ( and even preferred on some degree ) but once there are 3 of the same numbers i want one of those to change again in a random number ( and re-check for duplicates).

So what should be fine ( 2x 8 is fine, 2x 1 is fine ):

Container 1: 14
Container 2: 8
Container 3: 8
Container 4: 4
Container 5: 1
Container 6: 9
Container 7: 1
Container 8: 12

What should be incorrect ( 3x 14 is not fine ):

Container 1: 14
Container 2: 8
Container 3: 4
Container 4: 14
Container 5: 14
Container 6: 9
Container 7: 1
Container 8: 12

You guys have any advice on what the right way is here? I am trying to stay away from a lot of "if's".




if consecutive duplicates generate another list

How can I make sure that this list does not have consecutive letters? I do not want to eliminate them, that I know how to do, I want to just have them pseudorandomly arrange where there are 5 letters of each but the same letter does not appear in succession.

Thank you.

my code thus far:

import random 

kounter1 = [5,5,5,5]
kounter2 = [0,0,0,0]


list = []

boo = True
while boo:
        #keep going until the profile of counts in kounter1 and and 2 match 
r = random.random()

if r <0.25 and kounter2[0] < kounter1[0]:
    c1 = 'a'
    kounter2[0]+=1      
    list.append(c1)

elif kounter2[1] < kounter1[1]:

   c1 = 'b'
   kounter2[1]+=1

   list.append(c1)

elif kounter2[2] < kounter1[2]:
   c1 = 'c'
   kounter2[2]+=1

   list.append(c1)
elif kounter2[3] < kounter1[3]:

  c1 = 'd'
  kounter2[3]+=1
  list.append(c1)

if kounter1 == kounter2:
   boo = False

print(list)




why is my python implementation of metropolis algorithm (mcmc) so slow?

I'm trying to implement the Metropolis algorithm (a simpler version of the Metropolis-Hastings algorithm) in Python.

Here is my implementation:

def Metropolis_Gaussian(p, z0, sigma, n_samples=100, burn_in=0, m=1):
"""
Metropolis Algorithm using a Gaussian proposal distribution.
p: distribution that we want to sample from (can be unnormalized)
z0: Initial sample
sigma: standard deviation of the proposal normal distribution.
n_samples: number of final samples that we want to obtain.
burn_in: number of initial samples to discard.
m: this number is used to take every mth sample at the end
"""
# List of samples, check feasibility of first sample and set z to first sample
sample_list = [z0]
_ = p(z0) 
z = z0
# set a counter of samples for burn-in
n_sampled = 0

while len(sample_list[::m]) < n_samples:
    # Sample a candidate from Normal(mu, sigma),  draw a uniform sample, find acceptance probability
    cand = np.random.normal(loc=z, scale=sigma)
    u = np.random.rand()
    try:
        prob = min(1, p(cand) / p(z))
    except (OverflowError, ValueError) as error:
        continue
    n_sampled += 1

    if prob > u:
        z = cand  # accept and make candidate the new sample

    # do not add burn-in samples
    if n_sampled > burn_in:
        sample_list.append(z)

# Finally want to take every Mth sample in order to achieve independence
return np.array(sample_list)[::m]

When I try to apply my algorithm to an exponential function it takes very little time. However, when I try it on a t-distribution it takes ages, considering that it's not doing that many calculations. This is how you can replicate my code:

t_samples = Metropolis_Gaussian(pdf_t, 3, 1, 1000, 1000, m=100)
plt.hist(t_samples, density=True, bins=15, label='histogram of samples')
x = np.linspace(min(t_samples), max(t_samples), 100)
plt.plot(x, pdf_t(x), label='t pdf')
plt.xlim(min(t_samples), max(t_samples))
plt.title("Sampling t distribution via Metropolis")
plt.xlabel(r'$x$')
plt.ylabel(r'$y$')
plt.legend()

This code takes quite a long time to run and I'm not sure why. In my code for Metropolis_Gaussian, I am trying to improve efficiency by

  1. Not adding to the list repeated samples
  2. Not recording burn-in samples

The function pdf_t is defined as follows

from scipy.stats import t
def pdf_t(x, df=10):
    return t.pdf(x, df=df)




samedi 23 février 2019

Easy way to create a matched control set

I would like to take samples from a "control" dataset, matched by a variable called "length" (+/- 100) from a "case" dataset. I am trying to create many samples of this, and then test whether a variable "var" we observe in the "case" dataset appears more than expected.

I have two questions: 1. Is there an easier way to find the matched control set, better than going through two for loops? 2. Is there an R package to help with both setting up a matched control and even getting a pvalue for this type of analysis?

Right now this is what I am doing:

cases = data.frame(id = 1:10, length = sample(1:1000,10), var = sample(c(TRUE,FALSE), 10, TRUE)) 
control = data.frame(id = 1:100, length = sample(1:1000,100), var = sample(c(TRUE,FALSE), 100, TRUE)) 

res = data.frame()
nperm = 10
for (perm in 1:nperm) {
    control_random = control[sample(nrow(control),nrow(control),replace=FALSE),] # draw the control into a random order
    for (i in 1:nrow(cases)) { # loop through cases to find a match for each
    for (j in 1:nrow(control)) { # for each case, loop through control looking for a match
        if (abs(control_random$length[j] - cases$length[i]) < 100) { # match if length is within 100
            break
        }
    }

 res = rbind.data.frame(res, data.frame(perm, cases$id[i], control_random$id[j], control_random$var[j]))
 # and remove it so we don't use it again
 control_random = control_random[-j,]
 }
 }

# pvalue:
# count how many times var is TRUE in control set compared to cases
# ncases = length(cases$id[cases$var])

Thank you for your help!




How to randomly generate an unobserved data in Python3

I have an dataframe which contain the observed data as:

import pandas as pd
d = {'humanID': [1, 1, 2,2,2,2 ,2,2,2,2], 'dogID': 
[1,2,1,5,4,6,7,20,9,7],'month': [1,1,2,3,1,2,3,1,2,2]}
df = pd.DataFrame(data=d)

The df is follow

    humanID  dogID  month
0        1      1      1
1        1      2      1
2        2      1      2
3        2      5      3
4        2      4      1
5        2      6      2
6        2      7      3
7        2     20      1
8        2      9      2
9        2      7      2

We total have two human and twenty dog, and above df contains the observed data. For example:

The first row means: human1 adopt dog1 at January

The second row means: human1 adopt dog2 at January

The third row means: human2 adopt dog1 at Febuary

My goal is randomly generating two unobserved data for each (human, month).

like for human1 at January, he does't adopt the dog [3,4,5,6,7,..20] And I want to randomly create two unobserved sample (human, month) in triple form

humanID dogID month
   1      20    1
   1      10    1

For human1, he doesn't have any activity at Feb, so we don't need to sample the unobserved data.

For human2, he have activity for Jan, Feb and March. Therefore, for each month, we want to randomly create the unobserved data. For example, In Jan, human2 adopt dog1, dog4 and god 20. The two random unobserved samples can be

humanID dogID month
   2      2    1
   2      6    1

same process can be used for Feb and March.

I want to put all of the unobserved in one dataframe such as follow unobserved

    humanID  dogID  month
0        1      20      1
1        1      10      1
2        2      2       1
3        2      6       1
4        2      13      2
5        2      16      2
6        2      1       3
7        2      20      3

Any fast way to do this?

PS: this is an code interview for a start-up company.




Photoshop - Open random images

I have been looking for a script to open two random images from 2 separate folders (so one image per folder) into photoshop.

The idea being the cutout in one folder and overlay in the other

These are folders with 100's of pictures...

Any help would be much appreciated <3




rand() function producing same output every time C [duplicate]

I am trying to generate random numbers from 0 to 3 with the rand() function, and it works decently, but I have noticed something odd.

The function keeps producing the same pattern of numbers every time I run and rerun the project.

This is the code I am using broken down as simple as possible..

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

int main()
{
int randomNumber;

for (int i = 0; i < 15; i++)
{
    randomNumber = rand() % 4;
    printf("%d ", randomNumber);
}

getchar();
return 0;
}

And this prints 15 random numbers from 0 to 3, and for me this is what I get

1 3 2 0 1 0 2 2 2 0 1 1 1 3 1

So this is fine. But the issue is, every single time I run the program this exact same thing prints.

Any idea why this is happening?




How can I replicate specific random draws in loops of different size?

I am struggling to understand how to replicate results from earlier work. I set a seed before I ran a loop with runs X, where some randomness happens in each iteration of the loop. I am now running a smaller loop with runs Y trying to replicate results in only a couple of iterations of that bigger loop (i.e., Y < X). I can't figure out how to do this. Any help much appreciated. MWE is below.

set.seed(23) 
big_loop<-sapply(1:5,function(i) {
  saveRDS(.Random.seed,paste0("run_",i,".RDS"))
  sample(letters,1)
}) 

#I want to replicate the random letter draws on runs 2 and 3 of the big_loop

#I understand why this doesn't work
set.seed(23)
small_loop<-sapply(2:3,function(i) {
  sample(letters,1)
})

#but I'm not sure why this doesn't work.
#how can I make it match runs 2 and 3 of the big loop?
set.seed(23)
small_loop2<-sapply(2:3,function(i) {
  .Random.seed<-readRDS(paste0("run_",i,".RDS"))
  sample(letters,1)
})

#i want this to be false
identical(big_loop[1:2],small_loop) #true
identical(big_loop[1:2],small_loop2) #true

#I want these to be true
identical(big_loop[2:3],small_loop) #false
identical(big_loop[2:3],small_loop2) #false




Battleship with C++

I am going to be honest. My college professor wants us to create a battleship game using C++, but I swear she has not taught us enough code and hasn't given us enough practice to complete such a task. This is an intro to coding course and everywhere I look online to do such a project seems to require code that she hasn't even mentioned like seeding and we covered srand() for like 5 minutes in class. I am actually desperate and I need help on how to even start the code... I know this is not the place to "make connections" or ask for such broad questions and this will get disliked causing me to not be able to ask another question for another 7 days, but I really need help. I semi-planned how I think the code should be laid out, but I have no idea how to even make an array from a seperate .txt file.

// Initialize default variables
// Create game board

// Loop till all ships are placed

// Game Loop Start
// Player inputs valid attack grid
// Check to see if attack is a hit
// Remove/add damage to hit ships
// Redraw game board
// Check to see if game is over
    // If game over - exit loop/end program
// Player guesses again
// Game Loop Return

Keep in mind, this game is 100% just 1 player. The player is trying to destroy a computer generated board and nothing else. The computer does not have a turn. The player does not have a board with ships. The play just has a visual to see whether they have hit or missed the computer's board. Also the ships are 3x1 (S S S) and are only horizontal on a 100x100 grid.

ANY help would be much appreciated.




python random lottery number generator game

I have to make a game where like the lottery my program generates 5 random numbers from a list of numbers 1-50 and one additional number from a list of numbers 1-20 and combines them into a final list that reads eg: (20, 26, 49, 01, 11, + 06) where two numbers are never repeated like (22, 11, 34, 44, 01, + 22) <--- this is what I don't want

attached below is the code I have written yet how do I make it so two numbers or more are never repeated and to add the + into my list without the "" signs

input: import random

a = list(range(1,51))
b = random.randint(1, 20)

temp = []

for i in range(5):
  random.shuffle(a) 
  temp.append(random.choice(a[:5])) 
temp.append('+')
temp.append(b)

print(temp)

output:

[14, 12, 3, 16, 23, '+', 9]




Randomly number selector from a given list of numbers

I have given list of numbers,

x=[x1, x2, x3, x4, x5, x6];
non_zero=find(x);

I want Matlab to randomly select anyone among elements of 'non_zero' at a time. I searched online but there is no such function available to provide my required results.




jQuery: display several elements randomly with different timings

I'm trying to randomly display divs on different positions, but I can only display them at the same time and the goal is to have diferent, dinamic timings for each div: the first div changes position one second after the other, for example. I've researched but similar solutions didn't apply and I'm failing to use the each() function? Can someone give a help?

HTML:

<div class="container">           
        <div class="wound"></div>
        <div id="first-row">
            <div class="box"></div>
            <div class="box" id="red">                  
            </div>
            <div class="box"></div>
            <div class="box"></div>
            <div class="box" id="blue">
            ></div>
            <div class="box"></div>
        </div>
        <div id="second-row">
            <div class="box"></div>
            <div class="box"></div>
            <div class="box">                   
            </div>
            <div class="box"></div>
            <div class="box">
            </div>
            <div class="box"></div>
        </div>
    </div>

JS

    var firstRow = $('#first-row');
    var secondRow = $('#second-row');

    function randomize(target, row) {
        while (target.length) {
            row.append(target.splice(Math.floor(Math.random() * target.length), 1)[0]);
        }
    }


    function randomMove(parent, secondParent) {
        parent = firstRow;
        secondParent = secondRow;
        var secondBandit = secondParent.children();
        var bandit = parent.children();
        randomize(bandit, firstRow)
        randomize(secondBandit, secondParent);
    }

    var seconds = 4000;
    function timer(seconds) {
        seconds = seconds;
        setInterval(function () {

            randomMove();
            playerShot();
        }, seconds);
    }
    timer(seconds);

Here is the fiddle




Access file.txt from google drive

I have a code that picks a random word from a file.txt saved on my computer drive C. I would like to work on my code on my work PC or on my ipad (I am using Pythonista app on my ipad). However the file.txt where I get the random word for my code is stored on my home PC. I know I can copy the file and save it on my work PC too (that what I am doing at the moment but i cant do this for my ipad). Another problem is I keep forgetting to update my work file.txt when I add more words to the file.txt on my home PC ..... I have moved the file.txt to my Google drive.

My question is how do I write the file path in my code to look into my Google drive where the file.txt is and get the random word. This way I can work with the file.txt anywhere

I tried this but didn't work

products = r"C:\Users\colin\Google Drive\Python\file.txt"

but it didnt word on my work PC or my ipad.




generate random value form other field value in Django

I have a booking system for bank line : this is my model for the customer:

class Customer(models.Model):
customer_bank        = models.ForeignKey('Bank', on_delete=models.SET_NULL,related_name='coustmer_bank' ,null=True)
customer_branch      = models.ForeignKey('Branch', on_delete=models.SET_NULL,related_name='coustmer_branch',null=True)
booking_id           = models.CharField(max_length=120, blank= True,default=increment_booking_number)
identity_type        = models.ForeignKey('IdentityType',on_delete=models.SET_NULL,related_name='identity_type',null=True)
identity_or_passport_number   = models.CharField(max_length=20)
bank_account_no      = models.CharField(max_length=15)
Done                 = models.BooleanField(default=False)
booking_date_time    = models.DateTimeField(auto_now_add=True, auto_now=False)
Entrance_date_time   = models.DateTimeField(auto_now_add=False, auto_now=True)# Must be modified to work with Entrance Date and Time

def __str__(self):
    return self.booking_id

I need to generate a random value for booking_id field depends on bank_number and the branch_number and the Customer id so how can I do that? help please




Random String c#

This is my code. I cant understand why the n variable doesn't change when the loop loops. Right now it just writes the first random letter and do it ten times instead of making it random every loop.

            string[] alfa = new string[16]{
                "a", "b","c","d","e","f","g","h","i","j","k","l","m","n","o","p"
            };

            using (var tw = new StreamWriter(@"../../data/" + 
             NewUsername.Text + "," + NewPassword.Text + "/ReFectorPassword.txt", true))
            {

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

                    Random r = new Random();
                    int n = r.Next(16);

                    randomString = alfa[n];
                    tw.Write(randomString );
                }

            }




random select file input in ffmpeg

Please help me! I code ffmpeg add mp3 to image but i want to select random file mp3 when add to image creat video. my code:

set INPUT=E:\image
set OUTPUT=E:\video
set mp3inseart = $(shuf -n1 -e e:\music\*) 
: encode video 
for %%i in ("%INPUT%\*.jpg") DO ffmpeg -i "%%i" -i $mp3inseart -threads 0 -shortest -preset ultrafast "%output%\%%~ni.mp4"




vendredi 22 février 2019

Java: Generate Unique Random Character

I have a string of "random" characters. I assigned a numeric value to each character depending on its position in the string and then set a loop to output the character at whatever random position gets chosen. Here's my code so far:

public class Random9_4 {

  public static void main(String[] args) {

    final String chords = "ADE";
    final int N = chords.length();
    java.util.Random rand = new java.util.Random();
    for(int i = 0; i < 50; i++)
    {
        //char s = chords.charAt(rand.nextInt(N));
        //char t = chords.charAt(rand.nextInt(N));

        System.out.println(chords.charAt(rand.nextInt(N)));
        //temp variable
        //while(s == t)
        //{
        //  
        //}System.out.println(chords.charAt(rand.nextInt(N)));
    }
  }
}

As of now it works fine but the characters can repeat at times. I want it so that it is "unique" output of characters (meaning no repeats). I understand one way to do this is to use a temporary variable to check the current character with the previous one and the character that will be displayed next but I am unsure of how to get started.




C#: Generate 100 random numbers between 1-1000 and output the max value

I'm very new to coding and I just can't wrap my head around Loops/Arrays/Randoms. I understand the concept but when it comes to applying it, I'm just lost.

Here I'm trying to generate 100 random numbers between 1-1000 and it has to output the maximum value. Here's my code so far:

Random rnd = new Random();
int nums = rnd.Next(0, 1001);
for (int i = 1; i <= 100; i++)
{

}
Console.WriteLine(nums);
Console.ReadLine(); 

It's only giving me one number. :( I'd greatly appreciate any help!

Thanks!




How do u make these selections (Questions) shown at random?

Im currently in make of creating a math game that involves: addition, subtraction, multiplication and division. These parts with purple borders around them are the questions that i had created for the addition part when the user chooses to pick addition.

I dont know how to make these question be shown at random. When the user goes to select addition for addition questions everytime he does or goes back to do it again after he is done i want the questions not to be the same each time i want them to be in a different order. So its random each time. Screen shot of my questions i want to be put in random order.




Add to array in random order

Lets suppose that I have an array of arrays in C# (10x10 for example). I need to fill it with numbers from 1 to 50 (each numbers will be there twice) and these numbers must be on random position. How can I do this? I suppose that this could be ok: choose random position and then put there a number if the position is empty. If it is not empty, choose another position. But I think it is very complicated and also maximum time complexity is terrible. There must be better way, is there? I would really appreciate if your advice includes only elementary C# knowledge as this is my first week with this language.

Thanks for any advice.




C++ random numbers not random even with seed

I am trying to generate random numbers. I seeded the number generator but the following code produces numbers increasing by ~10 or so every time I run the program (if I don't wait long enough). So if I run it once I might get, say, 251. Then I run it immediately afterwards and I get 260 or so. If I wait a bit longer I might get 300, etc. What is happening?

#include <iostream>
#include <ctime>

int main()
{
    srand(time(NULL));
    int r = rand()%1000;

    std::cout << r << std::endl;
    return 0;
}




Python choose random number in specific interval

So I'm making a PyGame that baseball is falling from up, and users in the bottom have to catch the ball. The balls are falling in a random speed, but I'm having hard time getting balls falling in different speed.

For example, my current code for the ball is:

def update(self):
    if self.is_falling:
        """Move the ball down."""
        self.y += random.randint(10, 200) / 100
        self.rect.y = self.y

Here, when I run the program, the ball is falling in different speed but it's barely different. If I change the number to make it to (10, 20000) / 100 then every ball is dropping very fast. What would be the reason? Seems like random number is not so random. Am I using the function wrong?

I want to make each ball to drop in VERY different speed, such as one is very fast, and the other is very slow. And I would want it to be random number so that users can play with many different speed...

I wondered, if there is random function that I can set with a specific interval between generated random numbers? Or should I try a different approach? And if so, how should I do it?

I am very beginner at Python, so if you can explain it easy as possible, that will be much appreciated!




How to generate a random dictionary in Python

I need to create a dictionary with key and random values given a scope, i.e.

{key 1: value1, key 2: value2, key 3: value1, key 4: value 1, key 5: value 1}

or

{key 1: value2, key 2: value1, key 3: value1, key 4: value 1, key 5: value 1}

or

{key 1: value1, key 2: value1, key 3: value1, key 4: value 1, key 5: value 2}

... and so on

As you can see, the dictionary has the pattern below:

  • the key is generated from the input number of the function, if I input 5, I have 5 keys, if I input 3, I have 3 keys
  • the value has only 2 different values (value1 and value2), but value2 can only appear 1 time randomly in any key. The remaining values will be value1
def function(n):
   from random import randrange
   mydict = {}
   for i in range(5):
         key = "key " + str(i)

   value = ['value1', 'value2']






Stratified random assignment: Fix bug

library(data.table)

foo = setDT(your.data.frame) # transform your df into a data.table

dat = foo[, .SD[sample(.N, round(.N * 0.5))], by = BCS] # sample 50% of rows of each BCS

foo[subject %in% dat[, .(subject), status := "treatment"][is.na(status), status:= "control"] # assign a control treatment column

In the R code above, Please, does any one know why the last line of code is not working? That is: foo[subject %in% dat[, .(subject), status := "treatment"][is.na(status), status:= "control"] # assign a control treatment column




How can I insert a random video out of three videos in a google forms?

We want to compare the impact of three different videos. We divide the people responding in four groups, one blanco and three videos. We don't want to make four seperate forms for this, but want a random video to be shown to someone filling in the form.




How to get a random value from a string array in android without repetition?

How to get a random value from a string array in android without repetition?

I have array in String.xml file as below -

    <string-array name="msg">
    <item>Cow</item>
    <item>Pig</item>
    <item>Bird</item>
    <item>Sheep</item>
</string-array>

I am selecting random string by using following code -

String[] array = Objects.requireNonNull(context).getResources().getStringArray(R.array.msg);
String Msg = array[new Random().nextInt(array.length)];

Can anyone help me please? Thanks is advance...!




Python Random display and store dont repeat stored value

I'm struggling to get my code to work
I have a large list of fruits stored on my PC. Any time i run the program, i want the program to randomly display one fruit from the list. And then save that fruit in myfruitPicked.

My objective is, The program should always check myfruitPicked if the randomly selected fruit is already in myfruitPicked. then it should discard that fruit and randomly pick another one from the original list. when the fruits in myfruitPicked list is equal to the number of fruits in my original list. the program should break and print all fruits have been displayed.

The idea is, I dont want to see one fruit displayed twice anytime i run the program. Also because the fruit list is so large. I want to code to work well so it doesn't cause memory problem or slow that the program. Thanks for your help in advance

import random
myfruitPicked = ''
fruits = "C:\users\Homer\fruits.txt"

while True:
     randFruit = random.choice(fruits)
     myfruitPicked = myfruitPicked + randFruit

     if randFruit in myfruitPicked:
         print('All Fruits Already Displayed')
         break
     else:
         print(randFruit)




c++ random set seed failed

I am trying to set seed to the c++ std::default_random_engine:

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

using namespace std;


void print_rand();


int main() {

for (int i{0}; i < 20; ++i) {
    print_rand();
}
return 0;
}

void print_rand() {
    default_random_engine e;
    e.seed(time(0));

    cout << e() << endl;
}  

It seems that the printed numbers are same, how could I set the seed to generate the random number according to the time?




jeudi 21 février 2019

Application of conditional random field on an image

****Application of conditional random field on an image using python language after convolution****

can anybody share the code please




Swift 4.2+ seeded random number generator

I'm trying to generate seeded random numbers with Swift 4.2+, with the Int.random() function, however there is no given implementation that allows for the random number generator to be seeded. As far as I can tell, the only way to do this is to create a new random number generator that conforms to the RandomNumberGenerator protocol. Does anyone have a recommendation for a better way to do it, or an implementation of a RandomNumberGenerator conforming class that has the functionality of being seeded, and how to implement it?

Also, I have seen two functions srand and drand mentioned a couple times while I was looking for a solution to this, but judging by how rarely it was mentioned, I'm not sure if using it is bad convention, and I also can't find any documentation on them.

I'm looking for the simplest solution, not necessarily the most secure or fastest performance one (e.g. using an external library would not be ideal).




Generate data matrix using the given data matrix in R

Suppose I have a 200 x 200 matrix using the following r function.

n = 200
sim.mat = matrix(NA, nrow = n, ncol = n)
 for (i in 1:n){
   sim.mat[,i] = c(rnorm(i, 2, 1), rnorm(n-i, 3, 1))
 }

How can I generate 200 x 1000matrix using the same c(rnorm(i, 2, 1), rnorm(n-i, 3, 1)) setting?

Thank you.




R: Draw 100 random prices from each cut quality in diamonds data set?

I am using the diamonds data set:

install.packages("ggplot2")
library(ggplot2)
data("diamonds")

and I have to make a data frame that randomly takes 100 prices from each cut quality (Fair, Good, Very Good, Premium, Ideal) which would give me 500 data points. I'm having some trouble getting there and any help would be greatly appreciated! Here's a formula I tried but I can't seem to be able to figure out how to include all of the subsets that fall under 'cut'.

diamonds$price[ sample( diamonds$cut, size=100, replace=FALSE )]

I also tried using the aggregate function but that seemed to bring me even further away from where I was supposed to go. I'm sure I'm just missing something fairly obvious but I'm very new to this and I can't find anything about it online. Thank you!




Problems with GLMM models to assess nested Count data in R

=======

I want to understand what factors better explain the implementation of a directive. My data set includes Three Fixed variables and one nested. Fixed variables are Biogeographic Region with 2 Levels, Criteria (16 levels) and Groups (11 levels). Nested variable is the Marine Sub-Unit (6 levels and nested within Biog-Reg). Each Marine Sub-unit includes counts concerning Criteria and Group. All my factors are categorical. An example of the data set is the following:

Biog_Reg Marine.Sub.Unit Criteria Group Count

1 Celtic Seas FR_Celtic Seas 1.1 Benthic habitats 1

2 Celtic Seas FR_Celtic Seas 1.1 Fish 15

3 Celtic Seas FR_Celtic Seas 1.1 Marine mammals 6

4 Celtic Seas FR_Celtic Seas 1.1 Marine turtles 6

5 Celtic Seas FR_Celtic Seas 1.1 Pelagic habitats 0

6 Celtic Seas FR_Celtic Seas 1.1 Plankton 0

7 Celtic Seas FR_Celtic Seas 1.1 Rock & Biogenic Reef 0

8 Celtic Seas FR_Celtic Seas 1.1 Seabirds 14

9 Celtic Seas FR_Celtic Seas 1.1 Sedimentary habitat 1

10 Celtic Seas FR_Celtic Seas 1.2 Fish 0

... with 632 more rows

Since I am addressing nested count data and I want to access all proper interactions, I am usign GLMM to perform the analysis. I have tested several models but the most complete includes the following design:

Model3 <- glmer (Count ~ Biog_Reg + Criteria + Group + Biog_Reg: Criteria+ Biog_Reg:Group + (1|Marine.Sub.Unit/Biog_Reg), family = poisson (), data = sum)

(I understand that going instead for the following model would be easier but it simply wouldn't run: Model3 <- glmer (Count ~ Biog_Reg * Criteria * Group + (1|Marine.Sub.Unit/Biog_Reg), family = poisson (), data = sum) )

However, the model takes a very long time to resolve and when it does, provides the following errors:

*"Correlation matrix not shown by default, as p = 54 > 12. Use print(x, correlation=TRUE) or vcov(x) if you need it convergence code: 0 unable to evaluate scaled gradient Model failed to converge: degenerate Hessian with 2 negative eigenvalues failure to converge in 10000 evaluations Warning messages: 1: In vcov.merMod(object, use.hessian = use.hessian) : variance-covariance matrix computed from finite-difference Hessian is not positive definite or contains NA values: falling back to var-cov estimated from RX"

I am relatively new in GLM in general, so I have several questions: 1. Do I have the type of model and model syntaxe correct? My variable is naturally nested, i.e. each Marine Sub-unit only belong to one of the two Biogeogrpahic Region, so should a simpler anova solve this?

  1. In spite of the errors, the model provides results for each level of each factor individually. If the model is correct, how can I obtain the results for the factor?

3.Should I nest Criteria and Group within Marine Sub-Unit, evend though they are not ramdom? If so, how is the sintaxe for it?

I have already read a huge amount of information but considering

Schielzeth, H. and Nakagawa, S. (2013), Nested by design: model fitting and interpretation in a mixed model era.

I should go for mixed models and GLMM with Poisson distribution should handle count data. I have encountered many resembling questions but none specifically answered my doubts.

Help!!!




random numbers only once in an array c#

I want to generate random numbers and put them in an array, but they should only appear once in this array. It's like a mini lotto game. This is the code I have right now:

int[] arrA = new int[10];
Random random = new Random();

for (int i = 0; i <= arrA.Length -1; i++)
{           
    arrA[i] = random.Next(1, 15);
    Console.WriteLine(arrA[i]);
}

Console.ReadKey();

Random numbers are generated and put in this Array. I only need to know how it's possible to program that they only appeare once.




get a list of unique items from Random.choices function

I have a method that is using the random package to generate a list with certain probability for example:

import random

seed = 30
rand = random.Random(seed)
options_list = [1, 2, 3, 4, 5, 6]
prob_weights = [0.1, 0.2, 0.1, 0.05, 0.02, 0.06]
result = rand.choices(option_list, prob_weights, k=4) # k will be <= len(option_list)

my problem is that result can hold two of the same item, and I want it to be unique.

I could make the k param much larger and then filter out the unique items but that seems like the wrong way to do that. I looked in the docs and I dont see that the choices function gets this kind of parameter.

Any ideas how to config random to return a list of unique items?




why does rand() give relatively close numbers?

I am using the rand() function in c++ yet i am getting very close numbers every time here is my code`

int pickrandom(){
  time_t t;
  time(&t);
  srand (t);
  return rand();
}

I get numbers like : 13809 13812 13812 13817




How to generate random numbers using SDL visually?

I am using IBM Rational SDL and TTCN Suite 6.3 and programming SDL behaviour just with UI, not C/C++ code.

I am setting timers this way:

present

But I would like it to be random. Something more like:

desired

How can I do that?




mercredi 20 février 2019

Print a 4 letter word

My code below prints random 4 letters and working great. However, I want to upgrade it to print any 4 letter word. I mean a meaningful word and not just non meaningful 4 letters

CODES

      import random

      import string

      count = 0
      word = ''
      while count < 4:
        letter = random.choice(string.ascii_lowercase)
        count = count + 1
        word = word + letter
      print(word)

OUTPUTS

CURRENT OUTPUT: fxgw (non meaningful output)

EXPECTED OUTPUT: work (meaningful output)




How to make python script wait until entering specific URL

I want python script to be triggered by entering specific URLs with specific part of address.

Here is an example:

http://11.111.11.11:0000/Menu_EXAMPLE.jsp?NUMBER=1234
#1234 can be any random 4 digits Number

Basically I want python script to activate when URL has "http://11.111.11.11:0000/Menu_EXAMPLE.jsp?NUMBER=" in it.

Here is what I wrote so far:

from selenium import webdriver
from selenium.webdriver.support.ui import WebDriverWait

driver = webdriver.Chrome('./chromedriver')
wait = WebDriverWait(driver, 9999)
desired_url = http://11.111.11.11:0000/Menu_EXAMPLE.jsp?NUMBER=\d{4}
def wait_for_correct_current_url):
      wait.until(lambda driver: driver.current_url == desired_url)



driver.get("http://www.google.com")
wait_for_correct_current_url(desired_url)
**(Script that activates after entering desired_url)**

I am wondering if regex will do the trick, but I am new to python... so what do i know.

Thanks in advance!




Random.Randint() Repeating

I have this game where you need to react with the 5 random emojis sent from a list. The problem is that sometimes random.randint() spits out the same emoji twice so its impossible react twice to the same message with the same emoji. Is there a better way of doing multiple random.randints?

async def food_loop():
    await client.wait_until_ready()
    channel = client.get_channel("523262029440483329")
    while not client.is_closed:
        foodtime = random.randint(1440, 1880)
        food = ['🍇','🍈','🍉','🍊','🍋','🍌','🍍','🍎','🍏','🍐','🍑','🍒','🍓','🥝','🍅','🥑','🍆','🥔','🥕','🌽','🌶',
                '🥒','🍄','🥜','🌰','🍞','🥐','🥖','🥞','🧀','🍖','🍗','🥓','🍔','🍟','🍕','🌭','🌮','🌯',
                '🥙','🍳','🥘','🍲','🥗','🍿','🍱','🍘','🍙','🍚','🍛','🍜','🍝','🍠','🍢','🍣','🍤','🍥','🍡',
                '🍦','🍧','🍨','🍩','🍪','🎂','🍰','🍫','🍬','🍭','🍮','🥛','☕','🍵','🍶','🍾','🍷','🍸','🍹','🍺',
                '🥃']
        food1 = food[random.randint(0,79)]
        food2 = food[random.randint(0,79)]
        food3 = food[random.randint(0,79)]
        food4 = food[random.randint(0,79)]
        food5 = food[random.randint(0,79)]
        foodmonies = random.randint(350,750)
        up = 'order up'
        def orderup(m):
            return m.content.lower() == up
        foodmsg = 'Customer has ordered {}, {}, {}, {}, and {}! Fulfill their order ASAP!'.format(food1, food2, food3, food4, food5)
        foodmsgsend = await client.send_message(channel, foodmsg)
        foodpay1 = await client.wait_for_reaction(emoji=food1, message=foodmsgsend, timeout=3600,
                                             check=lambda reaction, user: user != client.user)
        foodpay2 = await client.wait_for_reaction(emoji=food2, message=foodmsgsend, timeout=3600,
                                             check=lambda reaction, user: user != client.user)
        foodpay3 = await client.wait_for_reaction(emoji=food3, message=foodmsgsend, timeout=3600,
                                             check=lambda reaction, user: user != client.user)
        foodpay4 = await client.wait_for_reaction(emoji=food4, message=foodmsgsend, timeout=3600,
                                             check=lambda reaction, user: user != client.user)
        foodpay5 = await client.wait_for_reaction(emoji=food5, message=foodmsgsend, timeout=3600,
                                             check=lambda reaction, user: user != client.user)
        foodguess = await client.wait_for_message(timeout=3600, channel=channel, check=orderup)
        if foodpay1 and foodpay2 and foodpay3 and foodpay4 and foodpay5 and foodpay3.user.id in blacklist:
            pass
        else:
            if foodpay1 and foodpay2 and foodpay3 and foodpay4 and foodpay5 and foodguess:
                await client.delete_message(foodmsgsend)
                await client.send_message(channel, "{} fulfills the order and earns ${}".format(foodpay5.user.mention, foodmonies))
                add_dollars(foodpay5.user, foodmonies)
                await asyncio.sleep(int(foodtime))