mardi 30 novembre 2021

how to make output line up (Ex. '12345') in python?

i have written a simple number generation function but i want the output to line up horizontally('234567') and not vertically like it currently outputs.

import random

def get_num():
    listz = [1,2,3,4,5]
    for x in listz:
        print(random.randrange(1,7))
    

get_num()



Generating a discrete random variable in Java?

Today in interview they asked me this question? How to generate a discrete random variable in Java? I couldn't do it but I wonder the solution. They gave me an array:

double[] probabilities={.2,.1,.3,.4};
double[] outcomes ={4,5,8,11.5};

And this should give the answer:

double discreteRV = problem.randPMF(probabilities,outcomes);

I couldn't understand how to solve this question.




Randomly sample points from coordinates that fall within a square

I have an array of individual ids and a separate array with their corresponding spatial coordinates on a 20x20 plane. I can easily select individuals from specific parts of the plane like so:

from numpy.random import randint
from numpy.random import default_rng

rng = default_rng()
inds = rng.choice(50, size=50, replace=False) #individual tags
locs = np.random.randint(0, 20, size=(50, 2)) #corresponding locations

groups = {
   'left' : inds[np.logical_and(locs[:, 0] < 10, locs[:, 1] < 20)],
   'right' : inds[np.logical_and(locs[:, 0] > 10, locs[:, 1] > 0)]
}

which gives me a "left" and "right" group. However, I'd like to randomly drop a square of size 4x4 onto the plane and sample only individuals that fall within that square. Any help would be greatly appreciated!




Random Walk project in Python: How can I make one of my walkers walk twice as often as any other direction?

Here is the code I have so far. But in line 104 I have one of my walkers, Mi-Ma, walking south two times compared to the other directions each time it is called, but when I coded this I misread the description of the project. Instead of always walking south two times it should instead walk twice as often as any other directions. What can I do to make her walk twice as often and not just two times each times south is called?

import turtle as ts
from math import sqrt
from random import choices, seed
from statistics import mean, stdev
from sys import argv
import tempfile
import subprocess

def save_to_image(dest='random_walk.png'):
    '''Saves the turtle canvas to dest. Do not modify this function.'''
    with tempfile.NamedTemporaryFile(prefix='random_walk',
                                     suffix='.eps') as tmp:
        ts.getcanvas().postscript(file=tmp.name)
        subprocess.run(['gs',
                        '-dSAFER',
                        '-o',
                        dest,
                        '-r200',
                        '-dEPSCrop',
                        '-sDEVICE=png16m',
                        tmp.name],
                       stdout=subprocess.DEVNULL)

def get_args() -> tuple:
    walk_lengths = list(map(int, argv[1].split(',')))
    n = int(argv[2])
    walker_name = argv[3]
    return (walk_lengths, n, walker_name)


class RandomWalker:
    '''
    Class to represent the random walker.
    '''
    directions = dict(
        North=[0, +1],
        South=[0, -1],
        East=[+1, 0],
        West=[-1, 0],
    )

    def __init__(self, name, N, S, E, W, color, shape) -> None:
        '''
        Initialisation function
            Parameters:
                name (str) : name of random walker
                N,S,E,W (int) : weights for moving in the specified direction
                color (str) : color for plot representation
                shape (str) : shape for plot representation
        '''
        self.name = name
        self.N = N
        self.S = S
        self.E = E
        self.W = W
        self.color = color
        self.shape = shape

    def take_walk(self, walk_length, n) -> list:
        '''
        Takes a random walk
            Parameters:
                walk_length (int): Length of random walk
            Returns:
                List of final destinations
        '''
        walker_weight = (self.N, self.S, self.E, self.W)
        directions = list(RandomWalker.directions.keys())
        final_postions = []

        for _ in range(n):
            position = [0, 0]
            for step in range(walk_length):
                random_direction = choices(
                    directions, weights=walker_weight, k=1)[0]
                delta_direction = RandomWalker.directions[random_direction]
                position[0] += delta_direction[0]
                position[1] += delta_direction[1]
            final_postions.append(position)

        final_distances = list(map(lambda pos: sqrt(
            pos[0]**2 + pos[1]**2), final_postions))

        Mean = mean(final_distances)
        CV = stdev(final_distances)/Mean
        Max = max(final_distances)
        Min = min(final_distances)

        print(f'{self.name} random walk of {walk_length} steps\nMean = {Mean:.1f} CV = {CV:.1f}\nMax = {Max:.1f} Min = {Min:.1f}')

        return final_postions

    @staticmethod
    def get_walkers(walker_name: str) -> list:
        '''
        Returns the instances of the RandomWalkers
            Parameters:
                walker_name: mentions the random_walker; 'all' for all walkers
            Returns:
                A list containing instance of random walkers.
        '''
        walkers = {
            'Pa': RandomWalker('Pa', 1, 1, 1, 1, 'black', 'circle'),
            'Mi-Ma': RandomWalker('Mi-Ma', 1, 2, 1, 1, 'green', 'square'),
            'Reg': RandomWalker('Reg', 0, 0, 1, 1, 'red', 'triangle'),
        }
        if walker_name in walkers:
            return [(walkers[walker_name])]
        elif walker_name == 'all':
            return list(walkers.values())
        else:
            raise Exception(f'Inavlid walker_name, "{walker_name}"')


def simulate(walk_lengths: list, n: int, walker_name: str) -> list:
    '''
    Simulating random walks
        Parameters:
            walk_lengths (list) : length of random walks to simulate
            n (int) : number of random walks to simulate
            walker_name (str) : mentions the random_walker; 'all' for all walkers
        Returns:
            Data for plotting (list) of form [shape, color, final_postions, walk_length]
    '''
    walkers = RandomWalker.get_walkers(walker_name)

    data_for_plotting = []
    for walker in walkers:
        for walk_length in walk_lengths:
            final_postion = walker.take_walk(walk_length, n)
            data_for_plotting.append(
                [walker.shape, walker.color, final_postion, walk_length])
    return data_for_plotting


def plot(data_for_plotting: list = []) -> None:
    '''
    Function to plot
        Parameters:
            data_for_plotting (list) of form [shape, color, final_postions, walk_length]
    '''

    ts.screensize(300, 400)
    turtle = ts.Turtle()
    turtle.speed(0)
    turtle.shapesize(0.5, 0.5)
    turtle.up()



    for shape, color, positions, walk_length in data_for_plotting:

        if walk_length > 100:
            continue

        turtle.shape(shape)
        turtle.color(color)

        for position in positions:
            x, y = position
            scale = 5
            turtle.goto(x*scale, y*scale)
            turtle.stamp()

    save_to_image()
def main():
    plotting_data = simulate(*get_args())
    plot(plotting_data)

if __name__ == "__main__":
    main()

Here is the part of the project description that asks for this step. It is in the last paragraph.

"Farmer John has an old grandparent (Pa) that likes to wander off randomly when working in the barn. Pa starts from the barn and every second takes one step in a random direction North, South, East or West. What is Pa’s expected distance away from the barn after 1000 steps? If Pa takes many steps, will Pa be likely to move ever further from the origin, or be more likely to wander back to the origin over and over, and end up not far from where he started? Let’s write a simulation to find out.

This particular barn is in the center of a large grassy field. One day Pa starts to wander off, and notices that the grass has been mysteriously cut (by John) to resemble graph paper. Notice that after one step Pa is always exactly one unit away from the start. Let’s assume that Pa wanders eastward from the initial location on the first step. How far away might Pa be from the initial location after the second step? John sees that with a probability of 0.25 Pa will be 0 units away, with a probability of 0.25 Pa will be 2 units away, and with a probability of 0.5 Pa will be √2 units away. So, on average Pa will be further away after two steps than after one step. What about the third step? If the second step is to the north or south, the third step will bring the farmer closer to origin half the time and further half the time. If the second step is to the west (back to the start), the third step will be away from the origin. If the second step is to the east, the third step will be closer to the origin a quarter of the time, and further away three quarters of the time.

It seems like the more steps Pa takes, the greater the expected distance from the origin. We could continue this exhaustive enumeration of possibilities and perhaps develop a pretty good intuition about how this distance grows with respect to the number of steps. However, it is getting pretty tedious, so it seems like a better idea to write a program to do it for us.

However, there are a couple more twists to the situation. Pa’s wife Mi-Ma, another grandparent of John’s, also likes to wander away randomly, but riding an old mule. The mule goes South twice as often as any other direction. Lastly, John’s favorite hog Reg has an odd habit of wandering off too, but only randomly going east or west at each step, never north or south. People think he’s a sun-follower, but nobody’s really sure. John figures your Python program ought to model these two as well, while you’re at it."




Operator `+' cannot be applied to operands of type `int' and `System.Random'

i'm a beginner to c#,so i was trying to make a program that rolls a die for you and the enemy for 10 turns,each turns adding the number of your roll to an overall count and whoever got the largest in the end won,i didn't finish it all the way but this is what i have so far:

namespace dfgs
{
   class dice
   {
       public static void Main(String[] args)
       {
           int plsc = 0;
           int aisc = 0;
           int turns = 0;
           Random plrnd = new Random();
           Random airnd = new Random();
           while (turns < 11)
            {
                Console.WriteLine("Player Roll Is" + Convert.ToInt32(plrnd.Next(6)));
                Console.WriteLine("AI Roll Is" + Convert.ToInt32(airnd.Next(6)));
                plsc = plsc + plrnd;
                aisc = aisc + airnd;
                Console.WriteLine("Type A and hit enter to go again");
                string nxt = Console.ReadLine();
                if (nxt == "A"){
                    turns++;
                }
                Console.ReadLine();
            }
            
       }   
   } 
}

and whenever i try to compile i get the error Operator +' cannot be applied to operands of type int' and System.Random',this error appears twice,i tried changing the type of the random numbers to int but then i got the error messege Type int' does not contain a definition for Next' and no extension method Next' of type int' could be found. Are you missing an assembly reference? i am kinda stuck here,any help would be appreciated.

EDIT:Thank you to everyone who answered, i have managed to make this work,here is the final code,it's not the cleanest but works as intended:

namespace dfgs
{
   class die
   {
       public static void Main(String[] args)
       {
           int plsc = 0;
           int aisc = 0;
           int turns = 0;
           Random plrnd = new Random();
           Random airnd = new Random();
           while (turns < 10)
            {
                Console.WriteLine("Player Roll Is " + Convert.ToInt32(plrnd.Next(6)));
                Console.WriteLine("AI Roll Is " + Convert.ToInt32(airnd.Next(6)));
                plsc = plsc + plrnd.Next(6);
                aisc = aisc + airnd.Next(6);
                Console.WriteLine("Type A and hit enter to go again");
                string nxt = Console.ReadLine();
                if (nxt == "A"){
                    turns++;
                }
                else{
                    break;
                }
                if (turns == 10){
                    if (plsc > aisc){
                        Console.WriteLine("The Player Has Won,Ai Score: " + aisc + " Player Score: " + plsc);
                    }

                    else if (aisc > plsc){
                        Console.WriteLine("The AI Has Won,Ai Score: " + aisc + " Player Score: " + plsc);
                    }
                    break;
                    
                }
               
            }
            Console.ReadLine();
       }   
   } 
}



How to make sure that I get all table rows when i choose random? pl/sql

I have two tables and i have to select randomly from the first table until the sum of a column in the other is null.

How can I make sure that all data from the first table are selected at least once?

create table child(name varchar2(20);

BEGIN
insert into child(name) values('A');
insert into child(name) values('B');
insert into child(name) values('C');
insert into child(name) values('D');
END;
create table toys(code varchar2(20), quantity number);

BEGIN
insert into toys(code, quantity) values('1',30);
insert into toys(code, quantity) values('1',30);
insert into toys(code, quantity) values('1',30);
insert into toys(code, quantity) values('1',30);
END;

<how to get all child.names at least once?>

create procedure toys_time
as
type r_name is table of varchar2;
l_name r_name;
type r_code is table of varchar2;
l_code r_code;
type r_quan is table of varchar2;
l_quan r_quan;
l_random_quan number;
i number;
begin
 select name bulk collect into l_name from child order by name;
 select code bulk collect into l_code from toys order by code;
 select quantity bulk collect into l_quan from toys order by code;
 select sum(quantity) into i from toys

while i>0 loop

**< get all child.names at least once>**

rws := FLOOR(DBMS_RANDOM.VALUE(1,l_code.count+1))
if l_quan(rws) > 0 then 
 l_random_quan:= FLOOR(DBMS_RANDOM.value(1,5));  
if l_random_quan < l_quan(rws) then
l_quan(rws):+ l_quan(rws) + l_random_quan;
i:=i-l_random_quan;

update toys
set quantity = l_quan(rws)
where code =l_code(rws);

else
i:=i-l_quan(rws);
l_quan(rqws):=0;

update toys
set quantity = l_quan(rws)
where code =l_code(rws);

end if;
end loop;
end;



Python: Getting variable from a function that generates random numbers by pressing a button

I'm working on a game where you have to roll the dice. When I press the button, a random value from 1 to 6 emarges and is printed in the window - that's fine. The problem is that I need to somehow get the same value as the one that the 'dice' showed. Here is my code:

from tkinter import *
import random
 
window=Tk()
window.geometry("400x400")
 
l1=Label(window)
 
def roll():
    dice=random.randint(1,6)
    l1.config(text=f'{dice}')
    l1.pack()
     
b1=Button(window,text="Roll the Dice!",foreground='blue',command=roll)
b1.pack()
 
window.mainloop()

Here I want to get the value dice and use this value somewhere else but the function roll is bound to the command of the button b1. I tried to create another function and even a class but then I run into other problems such as that the number on the dice won't change even after I press the button repeatedly etc. Now I've run out of ideas. Could you edit my code so that the program works just as before but it also returns the value that the dice showed so that I can use the same value somewhere else?




Fixed effects vs. random effects in plm

I have unbalanced panel data, with different observations on different companies over a 10 year period. However, when choosing whether to use Fixed effects or Random effects I did a Hausman test to decide, and the p value vas < 0.05 so fixed effect is preferable. However, R adjusted is negative when using fixed effects and positive (and good) when using random effects? Is there any way where we can use the random effects despite the test, or is there a way of improving the R adjusted in the fixed effects model?




Splicing random elements and forming a new Array out of them

I didn´t find this exact question yet, sorry if it already exists!

I´ve got some trouble with homework, Ive got an array from 1 to 50 and want to choose 6 random numbers out of it. I´m doing that with array.splice([Math.floor(Math.random()*array.length)],1)

which works fine for 1 number, but when i interchange the 1 at the end to a 6, it just chooses a random index and proceeds to splice 6 items in a row. Doing a for loop to get a random number 6 times also works but i can´t think about a proper solution to display 6 item arrays at the end

My goal is to create a new array containing exactly 6 NON REPEATING random items and on top of that, do that as many times as you input in the beginning with a prompt and display the arrays in the console, looking something like this:

[5,7,8,10,12,41] [1,10,22,23,40,42] [1,2,17,19,38,45]

I´d greatly appreciate any help, thanks in advance!




How do I keep the random generated numbers from repeating inside the array?

I´m very new at coding and I want to create a programm that generates 6 random numbers in an array, and repeat the process 20 times. So far, I can get the array to fill with random numbers and to do the 20 loops but I can´t get the random numbers from repeating inside the array. Any tips?

Code:

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

int main()
{
    printf("\n5.1 Lottoziehung 6 aus 49 \n\n");

    int Ziehung[6]; 
    int Zufallszahl; //random variable
    srand((unsigned) time(0));
    for (int i=1; i<=20; i++)//Iterationen
    {
        printf("Ziehung %i: ",i); //Ziehungen Anzahl (the 20 loops)

                    for (int j=0;j<=5;j++){ //Array

                        int Zufallszahl=(rand() % 49)+1; //random num gen

                            if (Zufallszahl>0){
                            Ziehung[j]=Zufallszahl; //Array; Zahl innerhalb Ziehung widerholt
                            printf(" %i,",Ziehung[j]);
                            }//if
                            else {
                            j-1;
                            }//else
                }//for

                 printf("\n");
 }

    return 0;
}



lundi 29 novembre 2021

How do I create a list of random strings value without duplicates?

How to generate random string of my list without duplication in python? i tried using random.sample but it keeps sending me duplicates sometimes.

import random 


column_arr = ['id', 'name', 'location', 'duration'
, 'id', 'name', 'quantity', 'unit'
, 'id', 'description', 'unit', 'quantity', 'unit_cost']


arr = []
for i in range(3):
      arr.append(random.choice(column_arr))
print(arr)



why my random maze generation program doesn't work randomly , while working well on debugging mode [duplicate]

I made a program which generates M by N maze randomly. I visit neighbor 'room' randomly by setting the parameter of srand() function as time(null) function.

But When I run the program, The maze is generated only two ways, either go straight to the end of the maze horizontally or vertically (as below).

enter image description here enter image description here

But What is more mysterious for me is, when I tried to debug to find the error, I found maze is generated randomly well on debugging mode where I run line by line by pushing f5 button. The result on debugging mode is below.

enter image description here

enter image description here

So I'm confused whether there is no logical error on my code or not.

I appreciate your help. My code is as below.

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

typedef struct coord {
    int row, col; 
}coord;
typedef enum direction{down = 0, up, right, left, none};

void errorExit(const char* msg); 
char** arrAlloc(int height, int width);
void initialize_rooms(char** rooms, int height, int width);
void initialize_maps(char** maps, int height, int width);
void DfsMazeGeneration(coord current, int dir);
void check_adjacent_rooms(coord current, coord possible_neighbors[], int possible_dir[],  int* possible_num);
bool IsVisited(int next, int visited_dir[], int possible_num);
void break_wall(coord current, int dir);
void printMap(int row_size, int col_size); 

char** rooms; 
char** maps; 
coord size; 
int unvisited; 
bool end_flag = false; 
coord offsets[4] = { {1,0}, {-1,0}, {0,1}, {0,-1} }; // down, up, right, left order from current room
int main(void) {
    int N, M; // N: width, M: height  
    coord start_point = { 0, 0 }; 
    scanf("%d %d", &N, &M); 
    
    rooms = arrAlloc(M, N); 
    maps = arrAlloc(2 * M + 1, 2 * N + 1);
    unvisited = M * N; 
    size.row = M;
    size.col = N; 
     
    initialize_rooms(rooms, M, N);
    initialize_maps(maps, 2 * M + 1, 2 * N + 1); 
    
    DfsMazeGeneration(start_point, none);

    printMap(2 * M + 1, 2 * N + 1); 

}
void printMap(int row_size, int col_size) {
    for (int i = 0; i < row_size; i++) {
        for (int j = 0; j < col_size; j++) {
            printf("%c", maps[i][j]); 
        }
        printf("\n"); 
    }
}
void DfsMazeGeneration(coord current, int dir) {
    int row = current.row;
    int col = current.col; 
    int idx_for_visited = 0; // index for visited_dir 
    coord possible_neighbors[4]; 
    int possible_dir[4]; 
    int visited_dir[4]; 
    int possible_num = 0; 
    int next; 

    if (end_flag == true) return;
    else if (rooms[row][col] == true) return; 
    else if (rooms[row][col] == false){
        // debugging part: 
        // printf("(%d, %d)\n", row, col); 
        

        break_wall(current, dir);
        
        rooms[row][col] = true;
        unvisited--;
    }
    if (unvisited == 0) {
        end_flag = true;
        return; 
    }

    /* check adjacent rooms: check neighbor rooms whether it is valid room and unvisited room and return valid neighbor rooms as list */
    
    check_adjacent_rooms(current, possible_neighbors, possible_dir,  &possible_num);
    for (int i = 0; i < possible_num; i++) {
        do {
            srand(time(NULL)); 
            next = rand() % possible_num;

        }while (IsVisited(next, visited_dir, idx_for_visited)); 

        visited_dir[idx_for_visited++] = next; 
        DfsMazeGeneration(possible_neighbors[next], possible_dir[next]); 
        
        if (end_flag == true) return; 
    }
}
void break_wall(coord current, int dir) {
    /*
    from left: assign map[2i+1][2j] as ' '
    from right: assign map[2i+1][2j+2] as ' '
    from up: assign map[2i+2[[2j+1] as ' '
    from down: assign map[2i][2j+1] as ' ' 
    
    from none(only in start position): no operation 

    */

    // row, col index of current room on maps array 
    int row = 2 * current.row + 1;
    int col = 2 * current.col + 1;
    
    switch (dir) {
    case(left): maps[row][col + 1] = ' '; break;
    case(right): maps[row][col - 1] = ' '; break;
    case(up): maps[row + 1][col] = ' '; break;
    case(down): maps[row - 1][col] = ' '; break; 
    case(none): break;
    }
    





}


bool IsVisited(int next, int visited_dir[], int visited_so_far) {
    for (int i = 0; i < visited_so_far; i++) {
        if (visited_dir[i] == next)
            return true;
    }
    return false; // next is not included in list 'visited_dir'  
}
void check_adjacent_rooms(coord current, coord possible_neighbors[], int possible_dir[],  int* possible_num) {
    int row, col, idx = 0;
    coord neighbor; 
    for (int i = 0; i < 4; i++) {
        row = current.row + offsets[i].row;
        col = current.col + offsets[i].col;
        neighbor.row = row;
        neighbor.col = col; 
        if (row < 0 || row >= size.row || col < 0 || col >= size.col)
            continue; 
        if (rooms[row][col] == true) {
            continue; 
        }

        possible_neighbors[idx] = neighbor; 
        possible_dir[idx++] = i; 
        (*possible_num)++; 
    }
}
void initialize_rooms(char **rooms, int height, int width) {
    for (int i = 0; i < height; i++) {
        for (int j = 0; j < width; j++) {
            rooms[i][j] = false; //rooms are unvisited; 
        }
    }
}
void initialize_maps(char** maps, int height, int width) {
    
    //initialize room part 
    for (int i = 1; i < height; i += 2) {
        for (int j = 1; j < width - 1; j += 2)
            maps[i][j] = ' '; 
    }

    //initialize edge part
    for (int i = 0; i < height; i += 2) {
        for (int j = 0; j < width; j += 2) {
            maps[i][j] = '+';
        }
    }

    //initialize vertical wall part 
    for (int i = 1; i < height; i += 2) {
        for (int j = 0; j < width; j += 2) {
            maps[i][j] = '|';
        }
    }

    //initialize horizontal wall part
    for (int i = 0; i < height; i += 2) {
        for (int j = 1; j < width; j += 2) {
            maps[i][j] = '-';
        }
    }
}

char** arrAlloc(int height, int width){
    char **arr = (char**)malloc(sizeof(char*) * height);
    if (arr == NULL) 
        errorExit("Memory Allocation Error.\n"); 

    for (int i = 0; i < height; i++) {
        arr[i] = (char*)malloc(sizeof(char) * width); 
        if (arr[i] == NULL)
            errorExit("Memory Allocation Error.\n"); 
    }
    return arr;
}



void errorExit(const char* msg) {
    printf("%s", msg);
    exit(1); 
}




Double Sided Flashcards [closed]

Using swift and xcode to try and create random flash cards that use a face up and face down (or double sided) rounded rectangles as a card view. One side will be text and the other side will be a corresponding image. I am trying to make it so a rounded rectangle will appear with some text, tap it to flip it over and view an image corresponding to that text, and then press an arrow or other button to generate a new random item from a vast array or dictionary containing all the text and image pairs. If anyone can help me with this it would be much appreciated.

itemArray["Hat", "Gloves", "Shoes"].shuffle

Trying to make this end up looking more like:

Dictionary{"Hat": Hat.img, "Gloves": Gloves.img, "Shoes": Shoes.img}

Where the key being the cardIsFaceUp and the value being cardIsFaceDown. Tapping the rounded rectangle on screen to flip the card over to view a corresponding image to the text. Is this possible?




How to put circles on multiple screens to move them

I'm working on a code that draws a spirograph and moves circles depending on its color towards the sides of the screen. What I mean is, for example, there are 7 colors starting from white, blue, green, etc. I want to move all the circles that are white to the sides of the screen together, every white circle moving at once. Then every blue circle to the sides of the screen together, then, etc. This is what I mean:

import turtle
import random
import math
listCircleColor = ("red", "blue", "green", "orange", "yellow", "purple", "white")
listCircleObjects = list()

intGroup = 5
angleleft = 360/(intGroup*len(listCircleColor))
# make screen object
# and set size
sc = turtle.Screen()
sc.bgcolor("black")
sc.tracer(5)
# make turlte object
turtle.hideturtle()
turtle.speed(0)

def moveanddraw(oneturtle):
   oneturtle.left(90)
   oneturtle.penup()
   oneturtle.forward(20)
   oneturtle.right(90)
   oneturtle.pendown()
   oneturtle.circle(100)

def movesamecolorcircle():
   for cls in listCircleColor:
      for tur in listCircleObjects:
         objcrlcolor = tur.color()
         if objcrlcolor == (cls, cls):
            tur.undo()
            for i in range(1, 6):
               moveanddraw(tur)
               if i < 5:
                  tur.undo()

headangle = 0
for i in range(intGroup):
   for cl in listCircleColor:
      tur = turtle.Turtle()
      tur.hideturtle()
      tur.setheading(headangle)
      tur.color(cl)
      tur.pencolor(cl)
      tur.speed(0)
      tur.pensize(2)
      tur.circle(100)
      headangle = headangle + angleleft
      listCircleObjects.append(tur)

sc.ontimer(movesamecolorcircle, 50)


 print(len(listCircleObjects))
 sc.exitonclick()

This is what I want, except that all the circles are moving together, as you can see that they don't move together in the code. So instead of using turtle, I used pygame to try to make the effect of circles moving together better. This is my current code:

import pygame
import math
import sys
import time
#setting colors
WHITE = (255, 255, 255)
BLUE = (0, 0, 255)
GREEN = (0, 255,  0)
RED = (255, 0, 0)
ORANGE = (255, 127, 0)
YELLOW = (255, 255, 0)
PURPLE = (160, 32, 240)
#setting what order the colors go in
listCircleColor = (RED, BLUE, GREEN, ORANGE, YELLOW, PURPLE, WHITE)
#how many circles per color
intGroup = 5
#the space between each circle
turnangle = 360/35
#width of screen
width = 600
#height of screen
 height = 600
#radius of circles
radius = 100
#making the screen
screen = pygame.display.set_mode((width, height))
#if the code is running, then continue
running = True
##.draw.circle(screen, BLUE, (0, 0), radius, width=2)
circles = []
circles_rect = []
#draw

#draw
alpha = turnangle
for i in range(intGroup):
    for cl in listCircleColor:
        surfacetemp = pygame.Surface((width, height))
        surfacetemp = surfacetemp.convert_alpha()
        surfacetemp.fill((0, 0, 0, 0))

        ##circlerect = pygame.rect
        if alpha > 0 and alpha < 90:
            circlerect = pygame.draw.circle(surfacetemp, cl, (300 + radius * 
math.cos(math.radians(alpha)), 300 + radius * math.sin(math.radians(alpha))), radius, width=2)
            # second quarter of circles
        if alpha > 90 and alpha < 180:
            circlerect = pygame.draw.circle(surfacetemp, cl, (300 - radius * 
math.cos(math.radians(180 - alpha)), 300 + radius * math.sin(math.radians(180 - alpha))), 
radius, width=2)
            # third quarter of circles
        if alpha > 180 and alpha < 270:
            circlerect = pygame.draw.circle(surfacetemp, cl, (300 - radius * 
math.cos(math.radians(270 - alpha)), 300 - radius * math.sin(math.radians(270 - alpha))), 
radius, width=2)
            # last quarter of circles
        if alpha > 270 and alpha < 360:
            circlerect = pygame.draw.circle(surfacetemp, cl, (300 + radius * 
math.cos(math.radians(360 - alpha)), 300 - radius * math.sin(math.radians(360 - alpha))), 
radius, width=2)

    alpha = alpha + turnangle
    ##circles.append(circlerect)
    circles.append(surfacetemp)
    circles_rect.append(surfacetemp.get_rect())

#move"

#exit only when user clicks on exit button
running = True
while running:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            pygame.quit()
            exit()
        screen.fill((0, 0, 0))
        for crect, ret in zip(circles, circles_rect):
            ret.right += 5
            ret.left += 5
            screen.blit(crect, ret)

        screen.blit(crect, ret)




##screen.blit(crect,crect)
pygame.time.Clock().tick(20)
pygame.display.update()

##for center, color in circles:
##    pygame.draw.circle(screen, color, center, radius, 2)
##pygame.display.flip()

I've been told to put each circle into multiple screens and then move them, but I have no idea how to move them simultaneously. Please help me.




Make list of random triangular functions in python [closed]

I would like to make a list of 20 random triangular functions on [0,1] in Python. My triangular function is defined as

f(x) = max{X -|Yx-Z|, 0}, where X = height of function Y = inclination of function Z = position in the coordinate system.




How to generate a collection of random numbers based on a single random seed

I'm working on a solidity contract that leverages random numbers through the use of Oracles. (ChainLink). Obviously given the price and the time it takes to get a random number I'm looking for the best ways to reuse that seed to generate more than 1 random number.

I have the following code which is supposed to generate 2 random numbers per loop 1 between 0 and 99 and the other one between 0 and 2. So a total of 20 random numbers in this example.

uint256 randomness = 78076127350936886139585537764964110448646985064549445555744769369952641998556;
for (uint256 i = 0; i < 10; i++) {
  uint8 random1 = SafeCast.toUint8((randomness % (100 + i)) % 100)
  uint8 random2 = SafeCast.toUint8((randomness % (100 + i)) % 3)
}

Seems to work okay but wanted to make sure if that made sense math wise or if there was a better way of doing this.




Is there anyway to generate random language shortcode without listing all language shortcodes?

Is there anyway to generate random language shortcode without listing all language shortcodes in C#? I was thinking about creating list with all short codes and using random to choose the random one, but i need to do it without using list or listing all languages.

Code that i am using:

     var random = new Random();
     var languages = new List<string>{ "en","ak","cz","gu" }; //Many more.., i also need to somehow grab all of them from: https://www.science.co.il/language/Codes.php
     int index = random.Next(languages.Count);
     Console.WriteLine(list[index]);



Thread separated random int generation in C++

I need to genetate three .txt files filled with random int, calling the generate function in sepatared threads.

The problem is that as a result I have the same values in every .txt files.

A function that gererates and writes values:


        void generateMoves(int limit, std::string outputPath) {
        //open fstream
        std::ofstream fout;
        fout.open(outputPath);
        if (!fout.is_open()) {
            std::cout << "Error reading " << outputPath << " file. Exiting..." << std::endl;
            exit(1);
        }
    
        static thread_local std::mt19937 generator;
        std::uniform_int_distribution<int> distribution(1, 3);
    
        //generating & writing moves
        for (int i = 0; i < limit; i++) {
            
            int value;
            value = distribution(generator);
            fout << value << std::endl;
        }
    
        fout.close();
    }

I call threads like this from main():

    int limit = 1000;
    std::thread player1(generateMoves, limit, "player1.txt");
    std::thread player2(generateMoves, limit, "player2.txt");
    std::thread player3(generateMoves, limit, "player3.txt");

    player1.join();
    player2.join();
    player3.join();

So, how do I separate int generation correctly?




dimanche 28 novembre 2021

Is there any reports/research about randomness tests on hardware wallet like Ledgr/Trezor?

randomness tests like Dieharder Test,TestU01,PractRand,FIPS 140-2.etc




How to display a YouTube Video in Jupyter Notebook by Clicking a Button Using Tkinter

I'm trying to display a random YouTube Video from a list of 2 videos in my Jupyter notebook by displaying a button and clicking it.

    import random
    from IPython.display import YouTubeVideo
    TODO =  (YouTubeVideo('-C-ic2H24OU', width=800, height=300), YouTubeVideo('NpPDgrbmAYQ', width=800, height=300))
    random_choice_from_my_list = random.choice(TODO)
    random_choice_from_my_list

^This will display a random video from the TODO list

import tkinter as tk
def TODO_ACTIVITY():
    random_choice_from_my_list   
root = tk.Tk()
frame = tk.Frame(root)
frame.pack()
button = tk.Button(frame, 
                   text="TO DO", 
                   fg="black",
                   command=TODO_ACTIVITY)
button.pack(side=tk.LEFT)
root.mainloop()

^This will display the button

Nothing happens when I click the button. Any ideas?




Generating 10 x 10 table of values from random strings

I want to create a 10 x 10 table of values. Each entry in the table row or column value should be the count of difference in the string characters. I want to also keep track of minimum character differences between strings. However, in my case, I need 0 and at least 3 mismatches between randomly generated strings. Here is an example to give an idea about the problem.

    AMUNN  NUUNN ANUNN AAANN 
AMUNN   0   2   1   2   

NUUNN   2   0   2   3

ANUNN   1   2   0   2

AAANN   2   3   2   0

Here is my code so far.

import random
import itertools
from itertools import combinations


### Random string generation function starts
def shout():

    List1 = list()
    List2 = list()

##### Generate Random Strings 
    original_list = ['P', 'U', 'B','G']

    for i in range(0, 10):
        sample_list = random.choices(original_list, k=5)
        #print("".join(sample_list))
        List1.append("".join(sample_list))
        
    List2 = random.sample(List1, len(List1))


    my_list = list()

    for original in List1:
        for shuffled in List2:
            count=0
            for i,(x,y) in enumerate(zip(original,shuffled)):
                if x != y:
                    #print(original,shuffled,f'char miss-match {x,y} in element {i}')
                    count +=1
#           print(original,shuffled,count)
            myFString = original + " " + shuffled + " " + str(count)
            my_list.append(myFString)
    return (my_list)        

### Random string generation function Ends

        
my_list = shout()
for items in my_list:
            print(items)

I am able to do things correctly. However, I need to keep at least 3 mismatches between each string in the table. This is where the problem comes. Sometimes I get only 2 or 1 mismatch between the strings. One of the solutions was to call the random string generation function again and again.

Can you guys kindly have a look at my code and suggest how I can improve my code to take care of this issue?

Thanks in advance.




How to calculate the probability of each class for test sample in a classification task?

I have used Random Forest from scikit-learn for a classification task:

rf = ensemble.RandomForestClassifier(n_estimators=1000,
                                      max_depth = 10,
                                      max_features = 2,
                                      max_samples = 0.5)
rf.fit(xtrain, ytrain)
train_output_rf = rf.predict(xtrain)
test_output_rf = rf.predict(xtest)  

In practice, the trained model labels the test sample with a single output (class). Is there any way or alternative algorithm to achieve a list of probable classes for the test sample instead of single output (class)? For instance:

1. A (80%)
2. B (15%)
3. C (4%)
4. D (1%)



Seeding based on hashing is deprecated

The below function collects random numbers but the seed parameter should be optional. Therefore, I added the * .

import random

def random_num(n, number, *seed): #n is the number of values to return and number is the range of the uniform distribution that uses later
    collect = []
    random.seed(seed)
    for i in range(n):
        collect.append(round(random.uniform(-number, number),2))    
    return collect

Running the function without using the seed parameter:

random_num(4,5)

The result is: [4.82, -3.12, -0.62, 0.27] which looks fine I guess. It also shows the warning below:

DeprecationWarning: Seeding based on hashing is deprecated since Python 3.9 and will be removed in a subsequent version. The only supported seed types are: None, int, float, str, bytes, and bytearray. random.seed(seed)

What is the proper way to simply make the seed parameter optional without issues?




How can I sample removing some groups randomly and some individuals within group randomly?

a= [1 2 3 1;5 6 7 1;1 2 3 1;1 2 4 1;1 2 3 2;1 2 3 2;1 2 4 2;1 2 4 2;1 3 4 3;1 3 4 3;1 3 4 3;1 2 3 3 ]

It gives; 1 2 3 1 5 6 7 1 1 2 3 1 1 2 4 1 1 2 3 2 1 2 3 2 1 2 4 2 1 2 4 2 1 3 4 3 1 3 4 3 1 3 4 3 1 2 3 3

a[:,4] represent group. I want randomly selected two groups each with two randomly selected individuals. Is there any easier and concise way to do it?




What cubic function can I use to get a random distribution biased towards the middle

I want a circle with more circles inside it (doesn't strictly need to be inside it). The position of inner circles are determined randomly in a way that there should be most circles at the centre and less and less and it goes out towards the edge of the circle.

From this question, I gathered that numbers can be biased using f(x) instead of just x, x being the random number, of course. Here is the code:

def distBiasedMiddle(_min, _max):
    r = lambda : random.uniform(0, 1)
    r1, r2 = r(), r()
    bias = lambda _r:  _r**3 * (1 + _max - _min) + _min
    return (bias(r1), bias(r2))

testBias = distBiasedMiddle

rps = []
for i in range(100):
    rps.append(testBias(-50, 50))

while True:

    for p in rps:
         pygame.draw.circle(window, (255, 0, 0), (p[0] + 300, p[1] + 300), 2)
    pygame.draw.circle(window, (0,255,0), (300, 300), 50, 1)

For people not familiar with pygame, green circle is of radius 50 and is drawn at (300, 300) and the red circles are drawn at (p[0] + 300, p[1] + 300)

Here I used x ** 3 but It did not work. I need help picking the correct function. Here's what I got.

enter image description here

I know that the rest of the code is correct because I used another function mentioned in that answer (f(X)=2X/(1+X)) and it gives the right distribution, biased towards the higher values:

def distBiasedUpper(_min, _max):
    r = lambda : random.uniform(0, 1)
    r1, r2 = r(), r()
    bias = lambda _r: (2 * _r / (1 + _r)) * (1 + _max - _min) + _min
    return (bias(r1), bias(r2))



samedi 27 novembre 2021

Trying to find a specific text line inside a file

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

void sorteia_palavra(char *palavra)
{
    char palavra[128];
    int n;
    int rand_number;
    open = fopen("palavras.txt", "r");
    fscanf(open, "%d", &n);
    rand_number = rand() % n;
    fclose(open);
}

// here i will try to add some context, basically, what this function is supposed to do is, i will get a number from the first line of the text, that has an integer that says the amount of words are inside the text, inside the text every line has one single word, basically, i have to use that first number that i get from the text file, and choose a random number between 0 and that number, and then use this number to choose one singular word from inside the file, what i'm trying to do, wich i'm failing, is to usee fseek to point in a place of memory, and get a word from that place, if anyone can help me find a better way on how to do what i want, i'm very thankful for that :)




Randomizing lists with set rules

ok, so i have a project where i want to make a list randomizer with a set of rules lets say i have 1 list named guests with 9 items, 1 named hosts with 4 items, and one named meals with 3 items.

now i want to randomize these guests across the hosts so every host get 3 guests, witch is fair enough. now they will all be connected to the first item in meal. problem arrives when i want to scramble them again across different hosts for meal 2, but so that none of the guests that have been together meet again for the next 2 meals. i do in the end want to have it so i can have a dynamic list of hosts and guests that will solve itself after they've been typed in

i dont want the code solved, just looking for the means to get there. Thanks alot in advance




javascript should open a random page after 7 seconds, but how?

I have this html page, with javascript code, but I can not get the code to open one of the cases 3 pages, the settimeout works, but to connect the random selected page work, I have enclosed the code cf. below, if I am some skilled javascript people who can tell what needs to be done to make it work I would be grateful.

the browser open this up http://localhost:62206/'sitelist[ran]'

my html and javascript code below here


<html lang="en" xmlns="http://www.w3.org/1999/xhtml">
<head>
    <meta charset="utf-8" />
    <title></title>
    <script language="Javascript">
        var sitelist = new array;
        sitelist[0] = "www.ford.com";
        sitelist[1] = "www.bmw.com";
        sitelist[2] = "www.mercedes.com";
 
        var ran = Math.floor(Math.random() * sitelist.length);
    </script>

   
</head>
<body onload="myFunction()">

    <h1>Hello World!</h1>

    <script>
        function myFunction() {
            setTimeout(function () { location.href = "'sitelist[ran]'" }, 7000);
        }
    </script>

</body>
</html>`




Need an algorithm to randomly generate groups on a hexagon grid

I created a hexagon grid based on information in this article https://www.redblobgames.com/grids/hexagons/

Here's how it looks so far: Grid of hexagons

I want to divide this grid into groups similar to this: Hex grid with groups

I want to have gaps in the grid but I also need all groups to be connected. Essentially I want to be able to move from any hexagon in a group to any other hexagon in a group.

My first idea is to pick a random tile for each group then add a neighboring tile to each group until a group touches another group, then maybe have a decreasing chance of adding another tile to that group. My main concern with this is that I could end up with 2 groups that touch each other but are not connected to the rest of the groups.

Any ideas are appreciated. Let me know if you need any more information.




Randomly put an image in specific places using C#

I am absolutely new with C#, so I hope my question is not completely off.

enter image description here

As you can see in the picture above, I have a form, in which there is a table (image) and a button. In the resources of the project, I have another image (black_rectangle.png), which is a black rectangle, exactly at the same size of each the table's cell. This is what I'm trying to achieve: Each time the 'Again' button is clicked, I want the six black rectangles to cover two of the tree cells in each column, in a random manner. For example, after the first try, the table could look like this: enter image description here

I'm basically stuck at the beginning:

public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();
    }

    private void button1_Click(object sender, EventArgs e)
    {
        Random random = new Random();
    }
}



How can I create a list similar to random.sample using numpy seed

I wanted to create a list(length of list 100) of unique random number from say range 0 to 100, such that no number repeats twice. I know I can do that it using random.sample()

block = random.sample(range(0,100),100)

But I wanted to use seed in this, so I wanted to use numpy random seed and generate 100 unique numbers from a given set.




Initialize Random.Seed once to keep seed

I have a function with a lot of random.choice, random.choices, random.randint, random.uniform etc functions and i have to put random.seed before them all. I use python 3.8.6, is there anyway to keep a seed initialized just in the function or atleast a way to toggle it instead of doing it every time?




How to get random keys in Firebase Database without fetching all data from a reference node?

I'm trying to get random keys from my Firebase Database which is a set of questions but all the solutions I found so far suggested fetching all the data first then getting the size and selecting random keys from that data. I want to know if it's possible to do that without having to fetch all data considering that the set could get larger.

I thought of saving the keys to another node and fetching that node only and then using those selected keys, I can get only the questions I need thus reducing unnecessary data but would that even make sense?




vendredi 26 novembre 2021

Random Turtle Walk

I want to make a program where the turtle walks off randomly in any direction with different colors, I can write the code to make the turtle move but I can't figure out how to randomly generate the different color list.




I want to generate random month, day, hour, min, sec in python but in this code generating random month is not working. How can I do this?

from datetime import datetime
from random import randrange
from datetime import date
import random
import datetime 

arr=""
def random_date(start,l):
   current = start
   while l >= 0:
      curr = current + datetime.timedelta(month=randrange(12),days=randrange(7),hours=randrange(12),minutes=randrange(60),seconds=randrange(60))
      yield curr
      l-=1

startDate = datetime.datetime(2013, 9, 20,13,00,00)

arr=[]
for x in random_date(startDate,10):
  arr.append(x.strftime("%d/%b/%y %H:%M:%S"))

for x in range(0,len(arr)):
   print(arr[x])



Difference between Numpy Randn and RandomState

My impression about the np.random.randn(n) produces different samples if executed second time. np.random.RandomState(n_clusters).randn(n) produces same samples if executed second time. Is this correct? Also, what does np.random.seed() does?

My code:

np.random.RandomState(2).randn(2)
Out[6]: array([-0.41675785, -0.05626683])

np.random.RandomState(4).randn(2)
Out[7]: array([0.05056171, 0.49995133])

np.random.RandomState(42).randn(2)
Out[8]: array([ 0.49671415, -0.1382643 ])

np.random.RandomState(42).randn(2)
Out[9]: array([ 0.49671415, -0.1382643 ])

np.random.RandomState(4).randn(2)
Out[10]: array([0.05056171, 0.49995133])

np.random.RandomState(2).randn(2)
Out[11]: array([-0.41675785, -0.05626683])

np.random.randn(2)
Out[12]: array([ 0.47143516, -1.19097569])

np.random.randn(2)
Out[13]: array([ 1.43270697, -0.3126519 ])



How to get the value from each index?

I'm extremely new to Java and we're tasked to take random values of an array and pass them through a method where it adds all of them for a running total.

For the sumMethod I'd like to take each value from all the index (given by sizeOfArray) and add them together.

Thank you!

public static void sumMethod(double[] arrayOfDoubles){
   //How to get the value from each indexes (given by sizeOfArray) and add them for the sum
   int arrayLength = arrayOfDoubles.length;
         
        System.out.println(arrayOfDoubles);
   }

  public static void main(String[] args) {   
   //1-3: Set up Scanner object to collect user's input on the size of array.
      Scanner keyboard = new Scanner(System.in);
      System.out.println("How many double numerical entries do you have?");
   //4: Declare an array of size sizeOfArray
      int sizeOfArray = keyboard.nextInt();  
   
      //Initialize array
      double[] arrayOfDoubles;
      arrayOfDoubles = new double[sizeOfArray];   
   
      
      
   
      for(int i = 0; i < sizeOfArray; i++){
      //5: Use the Random number Class and walk over the array 
         Random randomNum = new Random();       
         arrayOfDoubles[i] = randomNum.nextDouble(0.0 , 100.0);
      //6: Invoke SumMethod
         sumMethod(arrayOfDoubles); 
      }
      
     
      
      
   }
}



How to get a random image when we reload the HTML browser ? using javascript, css and html

I've checked answers on this topic and I tried a bunch of them but still doesn't work for me. I would like that a different image appears when I reload my HTML page.

For now, I have this code that is quite simple :

HTML :

<head>

<script type="text/javascript" src="../src/index.js"></script>

</head>

<body>
  <div id="container">
    <img id="image_shower_vehicule" class="vehicule" />
  </div>
</body>

</html>

CSS :

#container{
    position:relative;
    width:400px;
    height:400px;
    margin-left: auto;
    margin-right: auto;
    background-color: black;
    z-index:0;
}

.vehicule {
  position:absolute;
  z-index: 1;
}

JS :

var images_array_vehicule = ['vehicule1.png','vehicule2.png','vehicule3.png'];

function getRandomImagevehicule() {

random_index_vehicule = Math.floor(Math.random() * images_array_vehicule.length);
selected_image_vehicule = images_array_vehicule[random_index_vehicule];
document.getElementById('image_shower_vehicule').src =`../public/layers/vehicule/${selected_image_vehicule}`;

}

I have the following folders directory...: https://i.stack.imgur.com/xtnML.png

Any ideas that could help me ?

The future step is to do the same thing with different layers and overlay the chosen images with z-index but for now I just want to have a random image when I reload the page.

Thanks for your help !




How to generate random digits of String in Java? [duplicate]

The method should generate a random number of 7 digits but it should be a String, not an integer. How do I do that?




Generate random numbers within specific range and with given conditions in javascript - times table

I have generated random set of numbers (generated number) for each individual multiplier (numbers from 2 - 10).

The code itself does generates the numbers although not as expected.

Current behaviour:

  • it renders numbers (sometimes repetetive) within an array (for example 2x4 and 2x4)
  • it renders array with different length each time
  • rendered numbers multiplication value is repetetive (if there's an object with 4x7 and 7x4 it should replace one of these sets with a new value)
  • number objects are rendered on given conditions (for example number 9 multiplier will render at least once but no more than 3 times)

Expected behaviour:

  • it renders unique set of numbers for each multiplier
  • renders the array with the same length all the time (with length === 18)
  • checks if multiplication of multiplier and generated number matches the value within the array, if so then it renders another set of numbers within (still within the conditions)

This is what I got so far

const randomNumbersGenerator = () => {
  function getRandomInt(min, max) {
    min = Math.ceil(min);
    max = Math.floor(max);
    return Math.floor(Math.random() * (max - min) + min);
  }

  const number2 = getRandomInt(0, 2);
  const number3 = getRandomInt(0, 3);
  const number4 = getRandomInt(0, 3);
  const number5 = getRandomInt(0, 3);
  const number6 = getRandomInt(1, 4);
  const number7 = getRandomInt(1, 4);
  const number8 = getRandomInt(1, 4);
  const number9 = getRandomInt(1, 4);
  const number10 = getRandomInt(0, 2);
  const number11 = getRandomInt(0, 3);

  const randomNumber = () => getRandomInt(2, 12);
  let current;
  const numbersArray = [];

  for (let i = 0; i < number2; i += 1) {
    if (numbersArray.indexOf((current = randomNumber())) === -1) {
      numbersArray.push({
        multiplier: 2,
        generated: current
      });
    }
  }

  for (let i = 0; i < number3; i += 1) {
    if (numbersArray.indexOf((current = randomNumber())) === -1) {
      numbersArray.push({
        multiplier: 3,
        generated: current
      });
    }
  }

  for (let i = 0; i < number4; i += 1) {
    if (numbersArray.indexOf((current = randomNumber())) === -1) {
      numbersArray.push({
        multiplier: 4,
        generated: current
      });
    }
  }

  for (let i = 0; i < number5; i += 1) {
    if (numbersArray.indexOf((current = randomNumber())) === -1) {
      numbersArray.push({
        multiplier: 5,
        generated: current
      });
    }
  }

  for (let i = 0; i < number6; i += 1) {
    if (numbersArray.indexOf((current = randomNumber())) === -1) {
      numbersArray.push({
        multiplier: 6,
        generated: current
      });
    }
  }

  for (let i = 0; i < number7; i += 1) {
    if (numbersArray.indexOf((current = randomNumber())) === -1) {
      numbersArray.push({
        multiplier: 7,
        generated: current
      });
    }
  }

  for (let i = 0; i < number8; i += 1) {
    if (numbersArray.indexOf((current = randomNumber())) === -1) {
      numbersArray.push({
        multiplier: 8,
        generated: current
      });
    }
  }

  for (let i = 0; i < number9; i += 1) {
    if (numbersArray.indexOf((current = randomNumber())) === -1) {
      numbersArray.push({
        multiplier: 9,
        generated: current
      });
    }
  }

  for (let i = 0; i < number10; i += 1) {
    if (numbersArray.indexOf((current = randomNumber())) === -1) {
      numbersArray.push({
        multiplier: 10,
        generated: current
      });
    }
  }

  for (let i = 0; i < number11; i += 1) {
    if (numbersArray.indexOf((current = randomNumber())) === -1) {
      numbersArray.push({
        multiplier: 11,
        generated: current
      });
    }
  }

  console.log(numbersArray);
  return numbersArray;
};
randomNumbersGenerator();

You can also check it out via the codeSandbox: https://codesandbox.io/s/upbeat-jang-coqd5?file=/src/index.js:660-672




How to analyze relation between two independent scale variables and one common nominal variable?

I have three variables: Location (nominal, 4 classes); Density_settlement (scale, 5 values per class); Weight_plankton (scale, 4 values per class).

There are two datasets, one inlcuding Density_settlement and Location (4x5), the other including Weight_plankton and Location (4x4). There is no pairing between the Density and Weight of the plankton: Density is gathered through count of settlement, while Weight is defined through random sampling of ocean water. However, I do expect a relationship between both.

What is a good way to test this in R? I have tried to fit a GLM and correlation, but it does not seem to be appropriate.




how to make the Value "B" & "K" fill only certain number of cells Randomly

I have board made from class in Java with values (K, L) that will randomly fill the board. I wonder how to make the value "K" fill only certain number of cells (8 cells) randomly and the rest "L" would fill the board. My aim is to get a board where "K" appears 8 times and the rest would be "L" all randomly.

public class SimpsonsBoard {
    public static void main(String[] args) {
        String[][] board = new String[6][6];

        for(int i=0; i<board.length; i++) {
            for(int j=0; j<board.length; j++) {
                double random = Math.random();
                if (random < .8 ) {
                    board[i][j]= String.valueOf('K');
                }else {
                    board[i][j]= String.valueOf('L');
                }
                System.out.print(board[i][j]);
            }
        }


        System.out.println(" ─────────────");
        System.out.println("│" + board[0][0] + "│" + board[0][1] + "│" + board[0][2] + "│" + board[0][3] + "│" + board[0][4] + "│" + board[0][5] + "│");
        System.out.println(" ─────────────");
        System.out.println("│" + board[1][0] + "│" + board[1][1] + "│" + board[1][2] + "│" + board[1][3] + "│" + board[1][4] + "│" + board[1][5] + "│");
        System.out.println(" ─────────────");
        System.out.println("│" + board[2][0] + "│" + board[2][1] + "│" + board[2][2] + "│" + board[2][3] + "│" + board[2][4] + "│" + board[2][5] + "│");
        System.out.println(" ─────────────");
        System.out.println("│" + board[3][0] + "│" + board[3][1] + "│" + board[3][2] + "│" + board[3][3] + "│" + board[3][4] + "│" + board[3][5] + "│");
        System.out.println(" ─────────────");
        System.out.println("│" + board[4][0] + "│" + board[4][1] + "│" + board[4][2] + "│" + board[4][3] + "│" + board[4][4] + "│" + board[4][5] + "│");
        System.out.println(" ─────────────");
        System.out.println("│" + board[5][0] + "│" + board[5][1] + "│" + board[5][2] + "│" + board[5][3] + "│" + board[5][4] + "│" + board[5][5] + "│");
        System.out.println(" ─────────────");


    }
}



Robot Framework : random gives the same value everytime

I created a python file keywords.py and inside of it I have a random.randint fonction, excuted alone it works like charm.

I imported the .py file inside .robot (Library keywords.py) the problem is when I use it inside robot test it uses the same value again and again. I think robot compiles the .py file and uses the same output of the random...

So is there a way to solve it please thanks.




jeudi 25 novembre 2021

Generating random number in python using numpy

I want to generate five random numbers within the range of 0-1, 1-2, 2-3, 4-5,5-6,6-7,7-8,8-9,9-10 (five floats) and then take the average of those five floats (so I will get ten numbers in total). I'll later plot those ten numbers as the x-value of my plot. Does anyone have any recommendation as how i can do this with numpy using its methods?




How to randomize/shuffle two arrays in the same way in c#

I have two arrays one is a PictureBox array and the other is an Integer array both have the same number of elements. I want both arrays to be shuffled randomly each time but both shuffled the same way.

Here is a code that works if I use two PictureBox arrays or two Integer arrays, however I want it to shuffle one PictureBox array and one Integer array.

This is the code I want to work: (two different arrays)

PictureBox[] cards = new PictureBox[13];
// PictureBox[] numValue = new PictureBox[13];
int[] numbers = new int[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 10, 10, 10 };

 Random rnd = new Random();

         for (int i = 0; i < cards.Length - 1; i++)
         {
             int j = rnd.Next(i, cards.Length);

             PictureBox temp = cards[j];
             cards[j] = cards[i];
             cards[i] = temp;

             temp = numbers[j]; //An error occurs here because numbers is not a PictureBox variable
             numbers[j] = numbers[i];
             numbers[i] = temp; 
         }

This is the code that works: (for same arrays)

PictureBox[] numValue = new PictureBox[13];
PictureBox[] cards = new PictureBox[13];
// int[] numbers = new int[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 10, 10, 10 };

 Random rnd = new Random();

         for (int i = 0; i < cards.Length - 1; i++)
         {
             int j = rnd.Next(i, cards.Length);

             PictureBox temp = cards[j];
             cards[j] = cards[i];
             cards[i] = temp;

             temp = numValue [j]; 
             numValue [j] = numValue [i];
             numValue [i] = temp; 
         }

If you know another different code that can help me feel free to share it!




How do I find the problem in this Syntax Error? [closed]

==============simulation number = 0 ================ File "", line 1 stats.kappa3.rvsstats.a.rvs1.951349947587916, loc.rvs-0.2077336537281001, scale.rvs0.043459433428465304}} ^ SyntaxError: invalid syntax

This is the announcement I get when I run my code. I cannot indicate where the problem lays. It is not in the 1st line. Please Help!




Why Random generates different numbers in loop?

Hello there I want to generate random numbers, so I created method in my class

        private readonly Random _rand = new Random(); //Private property of class

        public void GenerateRandomNumber()
        {
            //For loop executes 10 times
            for (int i = 1; i < 11; i++)
            {
                Console.WriteLine(_rand.Next(0, 10));
            }
        }

When I call this from Main I create new instance of my class and then call it. It works properly but I want to know why does this generate different numbers each time in for loop and also each time I run the program?

That's interesting for me because I know that Random can generate same numbers but in my case it generates different ones.

How will it affect if I add static modifier to private property?




Simple method for generating a Sobol sequence

I am trying to implement a simple method of generating a Sobol seqeunce, which the author states can be done using the following syntax:

C#:

public IEnumerable<ulong> Sobol(ulong[] v)
{
    ulong s = 0;
    foreach (var r in Ruler()) yield return s ^= v[r];
}

public IEnumerable<int> Ruler()
{
    yield return 0;
    foreach (var r in Ruler())
    {
        yield return r + 1;
        yield return 0;
    }
}

VB.NET:

Public Iterator Function Sobol(ByVal v() As Double) As IEnumerable(Of ULong)
    Dim s As ULong = 0
    For Each r In Ruler()
        Yield s = s Xor v(r)
    Next
End Function

Public Iterator Function Ruler() As IEnumerable(Of Integer)
    Yield 0
    For Each r In Ruler()
        Yield r + 1
        Yield 0
    Next r
End Function

However, the author states that for example 0.100 = 1/2, which is obviously a binary to decimal conversion. Since the Sobol function returns large unsigned integers, I believe that modulo also needs to be applied, similar to x=(a*x mod c) for the linear congruential generator. Therefore, I don't think the author provided the entire solution.

I do have binary-to-decimal and decimal-to-binary, but just can't seem to be able to pick off Double values from the Sobol function which would represent the first elements in the Sobol sequence like 0, 1, 0.5, etc. I also have a Halton sequence generator, and I believe those values could be transformed into binary as the direction vectors.

Either way, if you could show a way to generate 1000 Double values from the Sobol function, it would be tremendously helpful.




Generate a random symmetric binary matrix in Python

I've looked for several question on SO but couldn't find this or figure it out how to do it. I want to generate a random symmetric binary matrix (n x n), from a given n.

Examples (n=3):

    0 0 1         0 0 1 
    1 0 1   or    0 0 0
    1 0 0         1 0 0
              

I also need the main diagonal to be zero. I know how to do it later, but in case one already want to implement it in an optimal code...




How to select a random value from an associative array in PL/SQL?

I have an associative array full of data how to select a random data from there?

declare
TYPE r_emp_id IS TABLE OF NUMBER;
    emps r_emp_id;
begin
select employes_id into emps from employes order by employes_id;

for i in <(random number of employes_id from emps)> loop

DBMS_OUTPUT.put_line(employes_id (i)); 
end loop;
end;



PHP: create a directory that always has a random numbers and letters at the end

$pathdir="./u[Numbers and letters here]"; 

Please help, I m now started php.




warning: assignment makes pointer from integer without a cast [-Wint-conversion] p = (i + 1) * 100;

i am trying to fill array with the numbers without using scanf. I encountered warning: assignment makes pointer from integer without a cast [-Wint-conversion] p = (i + 1) * 100; ^ and when i try to print the array the array output random values. How do i solve it?

#include<stdio.h>

int main() {
    int nums[8], i;
    int *p;
    p = nums;
    for (int i = 0; i < 8; ++i)
    {
        p = (i + 1) * 100;
        p++;
    }

    return 0;
}



mercredi 24 novembre 2021

Generating several random numbers in one transaction (Solidity)

Is there a way to generate several random numbers in a single transaction? Let's suppose I have this code:

function example(uint _prop) public{
    while(random(100) < _prob){
      // Do something  
    }
}

The condition of the while loop depends on the random number chosen in each iteration. Is it possible to do this with VRF (Chainlink)? Or can only one random number be generated for each transaction?

For now I'm using this solution:

function random(uint _interval) internal returns (uint) {
    nonce++;
    return uint(keccak256(abi.encodePacked(block.difficulty, block.timestamp, nonce))) % _interval;
}

but I know this is not a random number... This serves my purpose, but it is not formal. I want to improve it.




Produce Identical Random Number Sequence between C and Fortran (gcc 10.3.0)

I would like to produce the same random number sequence in both a program written in C and Fortran. I am using gcc version 10.3.0 within Windows Subsystem for Linux (Win10) running Ubuntu 20.04 LTS. I've tried using the same RNG implementation in C and using the same seeds, but thus far I can't seem to get the same output.

According to the documentation for RANDOM_NUMBER(), the runtime implements xoshiro256**

https://gcc.gnu.org/onlinedocs/gcc-10.3.0/gfortran/RANDOM_005fNUMBER.html

I grabbed xoshiro256** from here:

https://prng.di.unimi.it/xoshiro256starstar.c

This is my C test program (uses the upper 53 bits to calculate a 64-bit result):

#include <stdio.h>
#include "xoshiro256starstar.c"

int main(int argc, char** argv)
{
    size_t trials = 10u;
    int* p32state = (int*)s;

    p32state[0] = -1468754105;
    p32state[1] = -743753204;
    p32state[2] =  2022458965;
    p32state[3] = -443226243;
    p32state[4] = -23942267;
    p32state[5] = -1265286489;
    p32state[6] = -1934963269;
    p32state[7] =  1953963768;

    for( size_t i = 0u; i < trials; ++i )
    {
        uint64_t ret = next();

        if( i < 10u )
        {
            double d = ((uint64_t)(ret >> 11ull)) / (double)(1ull << 53ull);
            printf("%1.56f\n", d);
        }
    }
}

Compiled using this line:

gcc-10 -o test_rng_c test_rng.c

And here's the C output:

0.58728832572904277053993382651242427527904510498046875000
0.99628180739434757384742624708451330661773681640625000000
0.91328887972667560646300444204825907945632934570312500000
0.47383268683575230362237107328837737441062927246093750000
0.28868422781068314719732370576821267604827880859375000000
0.90562880102745912935802152787800878286361694335937500000
0.16771219329385134155785408438532613217830657958984375000
0.27161266560374741629857453517615795135498046875000000000
0.78859890296564516543043055207817815244197845458984375000
0.95109314522241128475599225566838867962360382080078125000

This is my Fortran test program:

program test_rand   

   implicit none

   real*8::v
   integer::trials,i
   integer::n
   integer, allocatable :: seed(:)
   trials = 10

   call random_seed(size=n)
   allocate(seed(n))
   if (n .eq. 8) then
     seed(1) = -1468754105
     seed(2) = -743753204
     seed(3) =  2022458965
     seed(4) = -443226243
     seed(5) = -23942267
     seed(6) = -1265286489
     seed(7) = -1934963269
     seed(8) =  1953963768
     call random_seed(put=seed)
   endif

   call random_seed(get=seed)
   do i=0,trials 
      call random_number(v)
      Print "(f58.56)", v
   enddo

stop
end

Compiled using this line:

gfortran-10 -ffree-form -o test_rng_f test_rand.f

And here's the Fortran output:

0.33898027596283408779953560951980762183666229248046875000
0.30153436367708152943123423028737306594848632812500000000
0.85599856867939150273372206356725655496120452880859375000
0.39833679489551077068654194590635597705841064453125000000
0.06316340952695409516337576860678382217884063720703125000
0.66356016219458069382852727358113043010234832763671875000
0.68412746418987169239045442736824043095111846923828125000
0.98553591281548125202505161723820492625236511230468750000
0.27351003115908101293030085798818618059158325195312500000
0.09340321315109112454422302107559517025947570800781250000
0.72886207089203813858091507427161559462547302246093750000

Output of gfortran-10 -v for good measure.

Using built-in specs.
COLLECT_GCC=gfortran-10
COLLECT_LTO_WRAPPER=/usr/lib/gcc/x86_64-linux-gnu/10/lto-wrapper
OFFLOAD_TARGET_NAMES=nvptx-none:amdgcn-amdhsa:hsa
OFFLOAD_TARGET_DEFAULT=1
Target: x86_64-linux-gnu
Configured with: ../src/configure -v --with-pkgversion='Ubuntu 10.3.0-1ubuntu1~20.04' --with-bugurl=file:///usr/share/doc/gcc-10/README.Bugs --enable-languages=c,ada,c++,go,brig,d,fortran,objc,obj-c++,m2 --prefix=/usr --with-gcc-major-version-only --program-suffix=-10 --program-prefix=x86_64-linux-gnu- --enable-shared --enable-linker-build-id --libexecdir=/usr/lib --without-included-gettext --enable-threads=posix --libdir=/usr/lib --enable-nls --enable-bootstrap --enable-clocale=gnu --enable-libstdcxx-debug --enable-libstdcxx-time=yes --with-default-libstdcxx-abi=new --enable-gnu-unique-object --disable-vtable-verify --enable-plugin --enable-default-pie --with-system-zlib --enable-libphobos-checking=release --with-target-system-zlib=auto --enable-objc-gc=auto --enable-multiarch --disable-werror --with-arch-32=i686 --with-abi=m64 --with-multilib-list=m32,m64,mx32 --enable-multilib --with-tune=generic --enable-offload-targets=nvptx-none=/build/gcc-10-S4I5Pr/gcc-10-10.3.0/debian/tmp-nvptx/usr,amdgcn-amdhsa=/build/gcc-10-S4I5Pr/gcc-10-10.3.0/debian/tmp-gcn/usr,hsa --without-cuda-driver --enable-checking=release --build=x86_64-linux-gnu --host=x86_64-linux-gnu --target=x86_64-linux-gnu --with-build-config=bootstrap-lto-lean --enable-link-mutex
Thread model: posix
Supported LTO compression algorithms: zlib zstd
gcc version 10.3.0 (Ubuntu 10.3.0-1ubuntu1~20.04)

I'm either not setting the seeds correct in the C code, or the implementations defer slightly in some key way. Any insight would be appreciated.




Is possible random number on html5?

I am create pure html5 page now. I always need clear CSS and Javascript cache from browser setting. Is possible load CSS and JavaScript with random number for files version parament ?

Like <link rel = "stylesheet" type="text/css" href = "css/desktop.css?v=*HERE_I_NEED_RANDOR_NUMBER*">




if string does not equal int: Java [closed]

I am writing a program in which you need to guess a random number 1-10. Here is my code:

package sami3;

import java.util.Scanner;
import java.util.Random;

public class Samiosman {

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        Random random = new Random();
        int r = random.nextInt(10)+1;
            System.out.println("guess a random number 1-10.");
            Scanner scanner = new Scanner(System.in);
            String how = scanner.next();
            if (String.valueOf(r).equals(how)) {
                System.out.println("right!");


            
                scanner.close();
    }

}
}

Alright so I want to find a way to say "wrong" if the number is wrong but it is not working. I tried to do

else {
 System.out.println("wrong.")
}

It did not really work. Also, I wanted there to be a way that if you get it wrong you can play again. I don't know how to make a person get it wrong so I cant start on that yet. Any suggestions are welcome! Thank you.




How do I distrubute a list of members across groups and subgroups in multiple iterations while minimizing the amount of overlap that occurs?

I was reviewing an old thread found here in trying to solve a problem: How to create 21 random groups of 10 people 4 times, without people being in the same group

The summary of the thread there was trying to distribute a list of people across groups over a number of iterations and prevent overlap of members in groups.

I like the approach posted by @pacholik (https://stackoverflow.com/a/34224863/12441567) and wanted to try and use that as a base. I am curious about the condition where completely blocked overlap is impossible or where a solution is unlikely to be found. In the problem I am considering, it is 24 people split across 2 groups and then 2 subgroups in that group. To stick with similar terms as the original question, there are five games. Summarized:

  • Group A contains Subgroup 1 and 2
  • Group B contains Subgroup 3 and 4
  • Each subgroup must contain exactly six members
  • Five iterations of the grouping

My primary objective is to minimize the amount of times a person overlaps with another person across games. A secondary objective is to minimize the amount of times the overlap in a group.

I think the problem is unlikely to have a solution where zero overlapping conditions exist, or if there is one it is unlikely to be found without extensive solve time.

I am trying to think of some sort of evaluator that scores the returned lists based on the amount of overlap and then selects the one with the lowest score. It would be ideal to have some sort of heuristic to prevent it from having to explore every possible list but that is probably beyond my scope/skillset... however I think there are so many combinations that it is hard for me to say how long it would run without that.




Working with snowflake IDs, how to generate them?

I'm trying to create a highly secure login & registration system in PHP and I want to add snowflake IDs, but I don't know how to generate them correctly.

Let's say, that I have an $epoch = 1637768288;, $currentTimestamp = new DateTime()->getTimestamp();, $workerID, $processID, and finally $sequence. (Followed by explanation in this video)

And here is the part of code, when I'm not sure what to do. How can I actually take all of these data and create a "snowflake id" from it? And how can I generate the sequence number, worker and process id, as the video explains?

Thanks,
Adalbert




On using structure literals in function and macro definitions

IMPORTANT: This question is motivated solely by my wanting to learn Common Lisp. Beyond this autodidactic goal, it has no ulterior practical purpose.


If, at my REPL1, I evaluate the following expression

CL-USER> (random-state-p
  #S(random-state
       :state #.(make-array 627
                            :element-type '(unsigned-byte 32)
                            :initial-element 7)))

...I get T. In other words, the literal

#S(random-state
     :state #.(make-array 627
                          :element-type '(unsigned-byte 32)
                          :initial-element 7))

...evaluates to a valid random-state object.


So far so good.

Now, I try to define a function, silly-random-state, so that the expression (silly-random-state 7) will produce the same random-state object as that produced by the literal above, like this:

(defun silly-random-state (some-int)
  #S(random-state
       :state #.(make-array 627
                            :element-type '(unsigned-byte 32)
                            :initial-element some-int)))

...but my REPL will have none of it! It won't even evaluate this defun! It complains that some-int is undefined2.

On further thought, I guess it makes sense that one cannot stick a variable inside a literal and expect the resulting expression to make sense... Maybe I need a macro for this?

So then I try to define a macro that, given an integer argument, will expand to such a random-state object, like this:

(defmacro silly-random-state-macro (some-int)
  `#S(random-state
        :state #.(make-array 627
                             :element-type '(unsigned-byte 32)
                             :initial-element ,some-int)))

Again, my REPL will have none of it. The evaluation of the expression above fails with

Comma inside backquoted structure (not a list or general vector.)


Each of the two failures above leads to a corresponding question:

  1. how can I define a function silly-random-state that takes an integer SOME-INT as argument, and returns the random-state equal to the one the REPL would produce if I gave it the expression below after replacing PLACEHOLDER with the integer SOME-INT?
#S(random-state
     :state #.(make-array 627
                          :element-type '(unsigned-byte 32)
                          :initial-element PLACEHOLDER))
  1. how can I define a macro silly-random-state-macro such that (silly-random-state-macro some-int) expands to a the same random-state object described in (1)?

(To repeat, my motivation here is only to better understand what can and cannot be done with Common Lisp3.)


1 SBCL + SLIME/Emacs running on Darwin.

2 BTW, my REPL had never been so picky before! For example, it will evaluate something like (defun foo () undefined-nonsense). Granted, it does grouse a bit over the undefined variable in the body, but in the end it will evaluate the defun.

3 In fact, I debated whether I should include [prng] among the tags for this question, since its topics are really literals, functions, and macros, and the role of CL's default PRNG in it is only incidental. I finally opted to keep this tag just in case the role of the PRNG in the question is less incidental than it seems to me.


EDIT: OK, I think I found a way to define the function I described in (1); it's not very elegant, but it works:

(defun silly-random-state (some-int)
  (read-from-string
   (format nil "#S(random-state :state #.(make-array 627 :element-type '(unsigned-byte 32) :initial-element ~A))" some-int)))



I draw 500 numbers from 0-10000, how to store them using Ruby and as few bits as possible, from which they can be decoded relatively quickly?

For example I can store them in an array, which can be saved as JSON. It's length is 2500 character in a particular case, and on average too.

I also can use a bitfield of 10_000 bits, in this case 10_000/8 ~ 1250 bytes is enough.

Maybe I can store them in a more space-saving way, but how?




How to create a sample of dataframe of a specific size in Pyspark?

I would like to create a sample from a dataframe of a specific size in pyspark. I am aware of proportional sampling but this doesn't always give the desired sample size. For example df.sample(0.1) gives a sample of 10%. Is there are way to define the size of a random sample? Ie code that gives a random sample of X amount?




How I do I get a second sample from a dataset in Python without getting duplication from a first sample?

I have a python dataset that I have managed to take a sample from and put in a second dataset. After that I will need to produce another sample from the original dataset but I do not want any of the first sample to come up again. Ideally this would need any flag would only be there for a year so it can then be sampled again after that time has elapsed.




mardi 23 novembre 2021

How do I create a Random number where the min value is exclusiv and the max value is inclusive? Java [duplicate]

Please consider that I need to use a final variable which is set in an interface as max_value.




Why doesn't the second random variable (Number2) change?

This program tests you on 10 questions that are 1 digit additions. When I run the code, the randomly generated Number1 value changes, however Number2 does not. Why isn't Number2 changing?

using System;

namespace Addition_test
{
    class Program
    {
        static int Test()
        {
            int AnswersCorrect = 0;

            for (int Counter = 0; Counter < 10; Counter++)
            {
                Random Num1 = new Random();
                int Number1 = Num1.Next(1, 10);

                Random Num2 = new Random(1);
                int Number2 = Num2.Next(1, 10);

                int Answer = Number1 + Number2;
                Console.WriteLine("What is " + Number1 + "+" + Number2 + "?");
                int Answer_entered = Convert.ToInt32(Console.ReadLine());

                if (Answer_entered == Answer)
                {
                    Console.WriteLine("Correct"); 
                    AnswersCorrect++;
                }
                else
                {
                    Console.WriteLine("Incorrect");
                }
            }

            return  AnswersCorrect;
        }

        static void Main(string[] args)
        {
            int Result = Test();

            Console.WriteLine("You got {0}/10 questions correct", Result);
            Console.ReadLine();
        }
    }
}



Keeping a tally of how many times a number appears using a random number generator. Java

In this code I am writing here the user inputs whether or not they would like to choose heads or tails in a coinflip game. I would like to keep a tally of how many times heads appears or tails appears and output it each time it changes. After hours of trying and searching I cannot figure it our perfectly so if someone could let me know what I could utilize let me know.

import java.util.Random; import java.util.Scanner;

public class CoinToss {

private enum Coin {
    Head, Tail
}

public static void main(String[] args) {
    CoinToss game = new CoinToss();
    game.startGame();


}


private void startGame() {
    Scanner scanner = new Scanner(System.in);
    Coin guess;

    while (true) {
        System.out.print("Enter your guess whether the coin will be heads or tails. Type 1 for heads, 2 for tails, or 3 to quit: ");
        String choice = scanner.nextLine();

        if (choice.equalsIgnoreCase("3")) {
            break;
        } else if (choice.equalsIgnoreCase("1")) {
            guess = Coin.Head;
        } else if (choice.equalsIgnoreCase("2")) {
            guess = Coin.Tail;
        } else {
            System.out.println("Please select either heads tails or quit.");
            continue;
        }

        Coin toss = tosscoin();

        if (guess == toss) {
            System.out.println("You guessed correctly!");
        } else {
            System.out.println("You guessed incorrectly");
        }
    }
    scanner.close();
}


private Coin tosscoin() {
    
    Random r = new Random();
    int sideup = r.nextInt(2);
    if (sideup == 1) {
        
        return Coin.Head;
    } else {
        return Coin.Tail;
    }


}

}




get non duplicate items from arraylist [closed]

Need help! I have a Json file with string values. By clicking on the button, I put a random string from this file into the arraylist. But I shouldn't put duplicate elements in the arraylist. How can i do this? Thank you in advance.




Exception has occurred: TypeError 'str' object does not support item assignment error in python [duplicate]

This is my code:

import random
number = ("1","2,","3","4,","5","6,","7","8,","9")
number = (random.choice(number))

import random
letter = ("a","b,","c","d,","e","f,","g","h,","i","j","k,","l","m","n","o","p","q","r","s","t","u","v","w")
letter = (random.choice(letter))

import random
cletter = ("A","B,","C","D,","E","F,","G","H,","I","J","K,","L","M","N","O","P","Q","R","S","T","U","V","W")
cletter = (random.choice(cletter))

import random
mletter = ("á","é","í","ó","ő","ö","ú","ü","ű")
mletter = (random.choice(mletter))

import random
cmletter = ("Á","É","Í","Ó","Ő","Ö","Ú","Ü","Ű")
cmletter = (random.choice(cmletter))

import random
sc = (".","?","!",":")
sc = (random.choice(sc))

import random
vsc = ("+","-","/","*","+",",","%","=","$","@","#","€")
vsc = (random.choice(vsc))

import random
lista = number + letter + cletter + mletter + cmletter + sc + vsc
**lista = random.shuffle(number + letter + cletter + mletter + cmletter + sc + vsc)**  <-- this is where it fails

print(lista)

So i have variables and each of them is a character. I want to shuffle them so that they make up a phrase. You can see what i've tried but it displays the error message seen in the title. Thanks for your help.




Getting non-duplicate random numbers in discord.py

I've been working on a command that returns a random string using a dictionary and the random library:

import random
randnum = random.randint(0,5)

words = {1:"random text" 2:"random text2" 3:"random text3" 4:"random text4" 5:"randomtext5"}

def getrandom():
    randomtext = words[randnum]
    return randomtext

But whenever I use the command it returns the same text since I'm getting the same number over and over again, I also tried using the random.sample method, but I'm getting the same results, I don't have much experience with this library, Is there any way for me to get a random non-duplicate number? any help would be appreciated!




The output is endless in an endless loop, what should i do? [closed]

what is wrong with my code, the output is always in an endless loop and my application keeps on closing due to this.

import java.util.Random;
public class Whilewhile{
    public static void main(String []args){
        Random number = new Random();
        float  x = 1;
        float largest = x, smallest = x;
        while ((x > 0)&&(x < 10)){
            x = number.nextFloat(10);
            System.out.println(x);
        if (x > largest) {
        largest = x;
        }
        if (x < smallest) {
        smallest = x;
        }
        }
        System.out.println("Largest number: " + largest);
        System.out.println("Smallest number: " + smallest);
    }
    
}



Generate 16 bytes of random numbers in C/C++ [duplicate]

I need to write a program to generate a key containing 16 bytes of random numbers. I wrote the code using the rand() function to get a 4 bytes random number and got the resulting value by concatenating the rand() 4 times in a loop. But I didn't get the result I wanted. Also I read somewhere that the rand() function does not necessarily creates a 4-bytes number. So I wanted to know if there is any other way I can generate the key.

#include <stdio.h>
#include <string.h>

int main(void) {
   unsigned char data[16];
   unsigned long VAL = 0;

   for(i = 0; i < 4; i++) {
      unsigned int num = rand();
      VAL = VAL + num;
   }
  printf("%x\n", VAL);
  memset(&data, VAL, 16);
}



64 bytes random number [closed]

I know this might be a stupid question but I will ask anyway since I was getting confused.

Is there a difference between a key having "64 bytes of random numbers" and a "random number of length 64 bytes"?




How to use a WHILE loop until all values in a column to be zero? pl/sql

For example, let's say that we have kids table and candy table .

create table kids( kid_name varchar2(20), money number);
create table candy( candy_name varchar(20), price number);

And I want to create a procedure(sales) that will make a sale for a random kid_name buys a random candy_name. In every sale kids money are dicreasing until all kids money := 0. How can i express it with while loop?




How do you fix a randrange error showing no range but your input is correct?

I have a Machine Learning pipeline and in the Cross-validation function, randrange is being used. When I execute it though, it gives an error saying that the input's empty. However, when I test the same line of input code above, it does give me a range of 13. Does anybody know what's going wrong?

My code

# Split a dataset into k folds
def cross_validation_split(dataset, n_folds):
    dataset_split = list()
    dataset_copy = list(dataset)
    print(len(dataset_copy))
    fold_size = int(len(dataset) / n_folds)
    for i in range(n_folds):
      fold = list()
      while len(fold) < fold_size:
        index = randrange(len(dataset_copy))
        fold.append(dataset_copy.pop(index))
      dataset_split.append(fold)
    return dataset_split

The output

13
---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-33-5932ea250f4a> in <module>()
    190 n_epoch = 100
    191 n_hidden = 5
--> 192 scores = evaluate_algorithm(dataset, back_propagation, n_folds, l_rate, n_epoch, n_hidden)
    193 print('Scores: %s' % scores)
    194 print('Mean Accuracy: %.3f%%' % (sum(scores)/float(len(scores))))

2 frames
/usr/lib/python3.7/random.py in randrange(self, start, stop, step, _int)
    188             if istart > 0:
    189                 return self._randbelow(istart)
--> 190             raise ValueError("empty range for randrange()")
    191 
    192         # stop argument supplied.

ValueError: empty range for randrange()



can we use sets for more randomness?

python random module uses time as the seed (right?), which is predictable, and sets are displayed in random order so if we use sets and random module and time module together, will it result in more randomness? and is it less predictable?
a code like this:

import random
from typing import Union
import time


def get_random_item(iterator: Union[set, list, tuple], seed=None):
    iterator = set(iterator)
    if seed is None:
        seed = time.time() / 10 ** (len(str(int(time.time()))) - 1)
    seed = int(((seed ** seed ** random.random() ** random.random()) * (10 ** random.randrange(9, 16))) % len(iterator))
    return list(iterator)[seed]



lundi 22 novembre 2021

Why [1,2,3,4,5,6].sort( () => .5 - Math.random() ); is not a good algorithm for shuffling array? [duplicate]

I found this here: How to randomize (shuffle) a JavaScript array?

And there is a comment:

Downvoting as this isn't really that random. I don't know why it has so many upvotes. Do not use this method. It looks pretty, but isn't completely correct. Here are results after 10,000 iterations on how many times each number in your array hits index [0] (I can give the other results too): 1 = 29.19%, 2 = 29.53%, 3 = 20.06%, 4 = 11.91%, 5 = 5.99%, 6 = 3.32%

Can someone explain the reason?

I really like this method because it's quite easy and simple but why the results are not that well randomized and the probability for each number on index 0 is so "fixed"?




How to random sample from a global PDF weighted by local count distribution?

The global Probability Density Distribution of a feature is given and look like this figure -- global PDF and the local feature distribution of 10,000 sample points is -- local feature count. What technique can be used to randomly sample based on the global PDF weighted by the local feature count?




Generating random points within sub geometries using st_sample from the sf package

Basically I'm trying to create 5 random spatial points within polgons of a shapefile. I am trying to use st_sample() from the sf package, but am having trouble with my for loop.

Example:

library(terra)
library(sf)

#10 polygons
v <- vect(system.file("ex/lux.shp", package="terra"))
v <- v[c(1:10)] 

#Empty list to store values
empty_list <- list()

#for loop
for(i in 1:length(v$ID_1)){
  
  empty_list[i] <- st_sample(x = v[i,], size = 5, 
                             type = "random", exact =T, by_polygon = T)
}

The loop seems fairly simple and straightforward. I think the issue is that st_sample() is only storing 1 value with each iteration. Should I use something other than a list to store output values, or is a for loop not the correct option here?




check if the numbers already given in a array

This is a program from a book that I'm studying. I don't get how this program keeps track of the numbers that have already been taken. The book is terse and I don't understand their explanation. Could someone please help me to understand the details of this code better? Specifically the part indicated in the code comment.

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

const int maxrange = 49;
const int maxballs = 6;

int rnd(int range);
void seedrnd(void);

int main()
{
    int numbers[maxrange];
    int i, b;

    printf("L O T T O  Z I E H U N G E N\n");
    seedrnd();

    for (i = 0; i < maxrange; i++)
    {
        numbers[i] = 0;
    }
    printf("Drueken sie eingabe fuer die Zahlen dieser Woche: ");
    getchar();

    printf("Es geht los\n");

    //This is the part I am stuck at: where the numbers in the array
    //are checked to see if the number has been used

    for (i = 0; i < maxballs; i++);
    {
        do
        {
            b = rnd(maxrange);
        } while (numbers[b - 1]);
        numbers[b - 1] = 1;
        printf("%i ", b);
    }

    printf("\n\nViel Glueck\n");
    return 0;
}

int rnd(int range)
{
    int r;
    r = rand() % range + 1;
    return (r);
}

void seedrnd(void)
{
    srand((unsigned)time(NULL));
}



Scratch Card Game setting percentage chances

I have an assignment where I have a bonus game where I have to display four prizes and if the same number appears more than one, they user wins that amount. Problem I'm having is user wins every time! Very long winded code below. I have four prizes, with 5 chances of winning all with different percentages. 50%, 27%, 15%, 6% and 2%.

    int[] bonus;  
        bonus = new int[5];
        bonus[0] = 10;
        bonus[0] = 20;
        bonus[0] = 50;
        bonus[0] = 200;
        bonus[0] = 1000;
        int [] bonusSum = new int[4];       
        int bonusAmount1=0;
        int bonusAmount2=0;
        
        
        numCount=0;
        
        //Select 4 bonus numbers
        while (numCount<4) {
            Random ran = new Random();
            int bonusNumber = rand.nextInt(99)+1;
                if (bonusNumber<49) {
                    System.out.print("€10 ");
                    bonusSum[numCount]=10;
                    numCount++;
                }else if(bonusNumber<27) {
                    System.out.print("€20 ");
                    bonusSum[numCount]=20;
                    numCount++;
                }else if (bonusNumber<15) {
                    System.out.print("€50 ");
                    bonusSum[numCount]=50;
                    numCount++;
                }else if (bonusNumber<06) {
                    System.out.print("€200 ");
                    bonusSum[numCount]=200;
                    numCount++;
                }else if (bonusNumber<02) {
                    System.out.print("€1,000 ");
                    bonusSum[numCount]=1000;
                    numCount++;
                    
                }
        }
          
        
            if (bonusSum[0]==bonusSum[1] || bonusSum[0]==bonusSum[2] || bonusSum[0]==bonusSum[3]) 
    {
                bonusAmount1=bonusSum[0];}
                
            if (bonusSum[1]== bonusSum[0] || bonusSum[1]==bonusSum[2] || bonusSum[1]==bonusSum[3]) 
   {
                if (bonusAmount1==0) {
                    bonusAmount1=bonusSum[1];
                }else if (bonusAmount1 == bonusSum[1]) {
            }else if (bonusAmount2==0) {                    bonusAmount2=bonusSum[1];
                }else if (bonusAmount2 == bonusSum[1]) {
                }
            }
                
            if(bonusSum[2]==bonusSum[0] || bonusSum[2]==bonusSum[1] || bonusSum[2]==bonusSum[3]){
                if (bonusAmount1==0) {
                    bonusAmount1=bonusSum[2];
                }else if (bonusAmount1 == bonusSum[2]) {
                }else if (bonusAmount2==0) {
                    bonusAmount2=bonusSum[2];
                }else if (bonusAmount2 == bonusSum[2]) {
                    }
            }
                
            if(bonusSum[3]==bonusSum[0]|| bonusSum[3]==bonusSum[1] || bonusSum[3]==bonusSum[2]) {
                if (bonusAmount1==0) {
                    bonusAmount1=bonusSum[3];
                }else if (bonusAmount1 == bonusSum[3]) {
                }else if (bonusAmount2==0) {
                    bonusAmount2=bonusSum[3];
                }else if (bonusAmount2 == bonusSum[3]) {
                }
            }
            
           if (bonusAmount1<=0 && bonusAmount2<=0) {
               System.out.println("Sorry no Luck this time ");
           }else {
               System.out.println("Congratulations you have won €"+(Math.addExact(bonusAmount1, 
    bonusAmount2))+"!");
           }

        
        
           }
        
        

    }