dimanche 31 décembre 2023

How does Javascript convert the result of xorshift128+ to a float value between 0 and 1 for Math.random()?

I need to write a program exploiting cryptographic insecurity of javascript's Math.random() for a CTF thing. However I do not know how javascript converts an int to a float between 0 and 1. The pseudo-randomization algorithm of javascript, as far as I understand is xorshift128+, which in python would look something like this:

def cast_to_int32(x):
    return x & 0xffffffff


def xorshift128plus():
    global state0
    global state1
    state0 = cast_to_int32(cast_to_int32(18030 * (state0 & 0xffff)) + cast_to_int32(state0 >> 16))
    state1 = cast_to_int32(cast_to_int32(30903 * (state1 & 0xffff)) + cast_to_int32(state1 >> 16))
    return cast_to_int32(cast_to_int32(state0 << 16) + (state1 & 0xffff))

However bitwise operations in this scenario are performed on integers, not floats. But the result of javascript's Math.random() is a float between 0 and 1. How does javascript convert that? I know the most intuitive thing to suggest would be a simple division by 2^32 or 2^31 but I've tried that and couldn't reproduce the results.

I tried dividing the int result by (2^31-1),(2^31),(2^32-1),(2^32) but none of these reproduced the results of Math.random() from the same state.




samedi 30 décembre 2023

How can i pass a random number generator as argument to a function that will produce several different numbers inside the function? [duplicate]

So, I have created several different random number generator functions (rng) that produce values of a random variable X which follow different distribution functions. Now, I want to experiment with the central limit theorem, and have a function (x_n) that produces n different values of X for a given distribution function, so, given the distribution function, I want to produce several different values of X, and then find their mean value.

I tried to just define a function that takes as arguments the number of values I want to generate and the function f (the rng) that I want the variable X to follow. I tried to call the RNG inside the function several times, but, of course, when I put the predefined distribution function as an argument into the x_n(n,rng), it generates only one random number, into the argument section, and then this random number is used throughout the entire run of x_n.

How can I call the rng many times inside the function x_n(n,rng) and produce many different numbers inside of it?

import random as r

#def uniform():
    #return r.random()

def x2():
    u=r.random()
    return u**(1/3)

def x_n(n,f):
    x_n=0
    for i in range(n):
        rand=f
        x_n+=rand
        #print(rand)
    return x_n/n

x_n(5,x2())
x_n(7,r.random())
x_n(20,uniform())

P.S.: One idea I had was to create random number generators that take an argument and just change the argument inside x_n()'s loop, but I was hoping there was another way, so that I can pass just r.random() as the distribution function.




lundi 18 décembre 2023

Restricted C Struct Randomizer

I am attempting to randomize members of a C struct with a few difficulties:

  1. The randomized struct may not be larger than the original one
  2. Each member has an alignment which has to be respected
  3. Members are of different sizes obviously
  4. Some members are fixed in place
  5. Members may not overlap with respect to their sizes
  6. Each member has a range in which it has to end up [min offset, max offset]

I freestyled a randomizer that respects properties 1 to 5. Also taking into account property 6 greatly complicates things. Is there an algorithm that does this kind of thing or could be abused to do it?

For context:

I have this struct representing the properties of a member of a C struct:

struct Member {
    uint32_t size;
    uint32_t offset;
    uint32_t alignment;
    uint32_t maxadd; // Max increase of offset
    uint32_t maxsub; // Max decrease of offset
};

My randomizer gets a list of objects of this struct, one object per member. It is supposed to find new, randomized offsets for each member, while not having any members overlap in the end and not translating a member by more than maxadd/maxsub.

I am not trying to randomize the strings in a struct definition. I am trying to randomize the memory layout itself. Because it is supposed to work on fully compiled binaries, the resulting layout may not consume more memory than the original struct (e.g. by translating a member by a million bytes). My randomizer also knows the size of the original struct.




Distributing random numbers with multiple conditions

My students handed in group projects. Now they are supposed to give feedback to other student's works. Each student should give feedback to two other student projects. I want to assign these projects randomly. Two conditions have to be met:

  1. A student should not give feedback to their own project.
  2. A student should not give feedback to the same project twice.
#Example Data
group <- c(1,1,1,2,2,3,3,3,4,4)
name <- c("a", "b", "c", "d", "e", "f", "g", "h", "i", "j")
feedback1 <- c(1,1,1,2,2,3,3,3,4,4)
feedback2 <- c(1,1,1,2,2,3,3,3,4,4)
df <- data.frame(group, name, feedback1, feedback2)

As you can see, the groups are not the same size (some groups have 2 members, some have 3). I created a loop that checks if someone is about to give feedback to himself. If so, a random number is chosen from all the group numbers, until a fitting number is chosen. One occurrence of the chosen number is then removed from the group numbers and the next student is checked.

# Fill feedback1
for (i in 1:nrow(df)) {
  while (df$feedback1[i] == df$group[i]) {
    df$feedback1[i] <- sample(group, 1)
  }
  group <- group[-match(df$feedback1[i], group)]
}

This works so far:


   group name feedback1 feedback2
1      1    a         2         1
2      1    b         3         1
3      1    c         3         1
4      2    d         1         2
5      2    e         1         2
6      3    f         4         3
7      3    g         4         3
8      3    h         2         3
9      4    i         1         4
10     4    j         3         4

If I add the second condition ("students should not give feedback to the same groups") the loop fails to work:

# Fill feedback2
group <- c(1,1,1,2,2,3,3,3,4,4)

for (i in 1:nrow(df)) {
  while (df$feedback2[i] == df$group[i] & df$feedback1[i] == df$feedback2[i] ) {
    df$feedback2[i] <- sample(group, 1)
  }
  group <- group[-match(df$feedback2[i], group)]
}

I do not get an error message, but df$feedback2 just stays the same for all students:

 group name feedback1 feedback2
1      1    a         2         1
2      1    b         3         1
3      1    c         3         1
4      2    d         1         2
5      2    e         1         2
6      3    f         4         3
7      3    g         4         3
8      3    h         2         3
9      4    i         1         4
10     4    j         3         4
  1. What is the mistake in my second loop for feedback2?
  2. What would be (in general) a better way to do approach the problem?

Best regards




Issue of random background in firefox browser

I've got script of random background which is working of every browser except firefox (only mobile version). In this browser the images not covering all screen but some part.

Here is a code:

<script>function pic() {

var bgm = ['image1.webp', 'image2.webp'];

$('body').css({ 'background': 'url(' + bgm[Math.floor(Math.random() * bgm.length)] + ') no-repeat', 'background-attachment': 'fixed', 'background-position': '50% 50%', 'background-size': 'cover' }); }

pic();

Why on firefox browser (only mobile version) the image not cover all screen?




dimanche 17 décembre 2023

How to predict Random numbers

If I have some code like this:

import random
for i in range(10):
    print(randint(0,1))

Now I know the previous 10 outputs how can I predict the 11th one? I know it's possible, how can I find it?




lundi 11 décembre 2023

Excel VBA Code for lottery and duplicates

I want to make a lottery in Excel where I can draw aprox 30 random numbers between 1-1000 and where the 30 numbers aren't duplicates.

I can't figure out how to check if the Array have duplicates and run the code again if so.

I currently use below VBA code to generate random numbers/winners. I do not think this is the most efficient way but this is what i got... :)

Public Sub CommandButton1_Click()
    Dim MIN, MAX, OUT, i
    Static a, n, z
    MIN = Array(1, 1, 1, 1): MAX = Array(10, 10, 10, 10): OUT = Array("Q1", "Q2", "Q3", "Q4")
    z = UBound(MIN)
    If Not IsArray(n) Then ReDim a(z): ReDim n(z)
    For i = 0 To z
        If n(i) = 0 Then Reset a(i), n(i), MIN(i), MAX(i)
        Range(OUT(i)) = a(i)(n(i)): n(i) = n(i) - 1
    Next
End Sub

Private Sub Reset(a, n, MIN, MAX)
    Dim i, j
    Randomize: n = MAX - MIN + 1: ReDim a(1 To n)
    For i = 1 To n
        j = Rnd * (i - 1) + 1: a(i) = a(j): a(j) = i - 1 + MIN
    Next
End Sub

If you can help me or know of a better way to code this please hmu! :)

Thanks! Oskar




mercredi 6 décembre 2023

Difficulty generating unique random numbers using Python's random module [closed]

I am working on a project where I need to generate a list of unique random numbers in Python using the random module. I've tried using random.sample to achieve this, but I'm running into issues with [describe the specific problem or error].

Here's a simplified version of my code:

import random

# Some code here to initialize a list of numbers
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

# Attempt to generate a random subset of unique numbers
try:
    random_subset = random.sample(numbers, k=5)
    print(random_subset)
except ValueError as e:
    print(f"Error: {e}")

Can someone please guide me on how to properly generate a subset of unique random numbers using the random module in Python?




mardi 5 décembre 2023

Equal group randomization in groups already assigned treatment

I have a list of 80 subjects already randomized into 4 groups (1-4). Now, I want to introduce a crossover design so each subject will eventually be in all 4 groups. Tried to do this with the sample function, but I need an equal distribution of each possibility of the 3 remaining groups to be randomized.

For example: Subject A was already randomized to group 1. Now I need to randomize the remaining 3 groups (2, 3, 4) There are 6 options to randomize the 3 remaining groups: 234 243 324 342 423 432

So I need to ensure that every subject who was initially assigned to group 1 (20 subjects) gets an even distribution of one of those 6 permutations above. The same for every subject initially assigned to group 2, 3 and 4

I tried

#for loop going through each row of the dataframe
for(x in 1:nrow(crossover)) {
  #TRIAL 2
  #randomly selects an integer between 1 and 4

 y<- sample(1:4, 1, replace = TRUE)
  
  #if it equals Assigned.Arm.Index, then randomly select again
 while (y == crossover$Assigned.Arm.Index[x]){

    y <- sample(1:4, 1, replace = FALSE)
  }
  
  #set New.Arm.Index column to y
  crossover$Trial_2[x] <- y

crossover is the name of my dataframe, assigned.arm.index is the premade initial randomization. I created 3 new columns for the remaining randomization I'm trying to fill.

When i asked for help regarding equal randomization across all subjects, I was told to use the rep function, something like:

sample(rep(1:6, 4) , rep= FALSE) 

but it's not fully making sense to me. Im new to R and appreciate any help!




Finding a sum of random numbers in Excel

I have a column of 57 purchases and a column of 18 payments. Is there a way to look up which purchases total a certain amount? Example would be if I had purchases of $10, $15, and $1 in column A, and one of the payments was $26 in column B, it would be identified?

I've tried pivot tables and a variety of formulas and nothing has worked.




Running simulations on high performing computing cluster generates the same results

I am performing Gillespie simulations a thousand times which take a very long time. I decided to run 10 scripts each with 100 simulations on high performing computing clusters of my school. However, once I did this and checked the results, the list of the results from the first script are the same as the second script. Meaning if I run the same scripts twice I get the exact same list of results back. Why is this happening given the fact that Gillespie simulations generate random results?




lundi 4 décembre 2023

Dummy data: generating random text and numerical data into one csv/excel file?

So I'm trying to generate dummy data that contains 3 columns: sq. feet, price and Borough. For the first two, which are purely numerical this is fine. I have 50,000 rows of data for both on a spreadsheet. However, when I add Borough and specify random values from a list I receive the following output:

       Sq. feet    Price  Borough
0           112   345382        5
1           310   901500        5
2           215   661033        5
3           147  1038431        5
4           212   296497        5

I have not used a package associated with numerical generation like np.random.randint

Instead I used "Borough" : random.randrange(len(word))

Where have I gone wrong?

My code below

import random

import pandas as pd
import numpy as np

WORDS = ["Chelsea", "Kensington", "Westminster", "Pimlico", "Bank", "Holborn", "Camden", "Islington", "Angel", "Battersea", "Knightsbridge", "Bermondsey", "Newham"]
word = random.choice(WORDS)
np.random.seed(1)
data3 = pd.DataFrame({"Sq. feet" : np.random.randint(low=75, high=325, size=50000),
                     "Price" : np.random.randint(low=200000, high=1250000, size=50000),
                      "Borough" : random.randrange(len(word))
                     })

df = pd.DataFrame(data3)
df.to_csv("/Users/thomasmcnally/PycharmProjects/real_estate_dummy_date/realestate.csv", index=False)

print(df)

I'm expecting a random line of word values from the WORDS [], instead the return value is just the number 5. It's obviously meaningless making another module just for the text-based data and printing them in different files.




dimanche 3 décembre 2023

What are the possibilities this code can produce an output which is dangerous for my computer? [closed]

enter image description here . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 😂😂😂😂😂Seriously asking...Any idea??? never tried it though...




samedi 2 décembre 2023

Program c that generate a random number to use it in guessing_number programme [duplicate]

I need a new function on C langue ( not the one that's existe in the library) tha generate a random number , then i will use it to tell the user if the number that he entered is lower.or.higher "I'm a beginner " Thank you

New function to generate number




Random walk algorithm

I'm trying to create a program which plots the different paths and points which you can take on the Cartesian plane using the following algorithm: Starting from the origin (0, 0), in step 1, you do one of the following:

*jump 1/2 to the right or 1/2 to left or terminate where you are.

If the movement hasn't ended yet, then in step 2:

*jump 1/4 upwards or 1/4 downwards or terminate where you are.

If the movement hasn't ended yet, then in step 3:

*jump 1/8 to the right or 1/8 to the left or terminate where you are,etc.

You would essentially do this indefinitely, where in step k, if k is even and the movement has not end yet, you would jump (1/2)^k upwards or downwards. Similarly, in step k if k is odd you jump (1/2)^k to the right or left or terminate where you are.

I want to plot the set of endpoints you can reach in this way in finitely many steps. Is the following code correct? By the way,the coloured circles at the end of each path is an endpoint. Are these plotted correctly?

import numpy
import pylab
import random
import matplotlib.pyplot as plt
axes = plt.axes()
k = 50

x = numpy.zeros(k)
y = numpy.zeros(k)
lst = []
for j in range(1,30):
  for i in range(1,k):
    dir = [-1,1][random.randint(0,1)]
    if i%2!=0:
        x[i] = x[i - 1] + 1/(2**(i)) * dir
        y[i] = y[i - 1]
    else:
      x[i] = x[i - 1]
      y[i] = y[i - 1] + 1/(2**(i)) * dir
  plt.plot(x, y,marker = 'o')
plt.title("Different paths the random walk movement sequences could take")
pylab.show()

Graph of possible paths plotted




vendredi 1 décembre 2023

How can I ask a user with the scanner to insert the ammount of random numbers he/she would like to be created and sort it f. e. with bubblesort?

I am currently studying computer science in my first semester and I have an assignment I need some kind help with. I am supposed to create an array which fills in the amount of random numbers the user specifies using the java.util.Scanner. Currently my code looks like this:

package lia.prog1.exercises.set09;

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

public class SortingTool
{

    private void bubblesort(int[] arr)
    {
        int sortArray;
        int i;
        int j;
        int tempArray;

        Scanner scanner = new Scanner(System.in);
        sortArray = scanner.nextInt();
        System.out.println("How many numbers do you want to sort?");



        for (i = 0; i < (arr.length - 1); i++)
        {
            for (j = 0; j < arr.length - i - 1; j++)
            {
                if (arr[j] > arr[j + 1])
                {
                    tempArray = arr[j];
                    arr[j] = arr[j + 1];
                    arr[j + 1] = tempArray;
                }
            }
        }
    }

    private void insertionsort(int [] data)
    {
        int [] sorted = new int[data.length];

        for (int i = 0; i < data.length; i++)
        {
            int min = Integer.MAX_VALUE;
            for (int j = 0; j < data.length; j++)
            {
                if (min > data[j])
                {
                    int temp = min;
                    min = data[j];
                    data[j] = temp;
                }
            }
            sorted[i] = min;
        }
    }

}



Difficulty with Rock Paper Scissors game

I'm making a code in Java that is a rock-paper-scissors game. In particular, I am trying to make it so that the randomized outputs, aka if a user loses, wins, or ties, it is counted into the score.

For example, the user inputs either rock, paper, or scissors. If they choose rock, they will get a random output that determines whether or not they win, lose, or tie. If they got the output, let's say, "You chose rock. I chose paper. You lose!" I want to add that score result as "1 loss." in my while loop. However, I don't know how to make the program count the random outputs like that.

My code is below and I put comments in it to try and better explain what I want to do.

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

public class rockpaperscissors {

public static void main(String[] args) {

Scanner input = new Scanner(System.in);

while(true){

    System.out.println("Please choose (r)ock, (p)aper or (s)cissors:");
    String answer = input.nextLine();
    int win = 0;
    int lose = 0;
    int tie = 0;
    
    if(answer.equals("r")) {
        String[] str = { "You chose rock. I chose paper. You lose!", /* lose++; */ "You chose rock. I chose scissors. You win!",  /* win++; */ "You chose rock. I chose rock. We tie!"  /* tie++; */ };
        Random r = new Random();
        System.out.println(str[r.nextInt(3)]);
        
        
     
    }
    if(answer.equals("p")) {
        String[] str = { "You chose paper. I chose scissors. You lose!",  /* lose++; */ "You chose paper. I chose rock. You win!",  /* win++; */ "You chose paper. I chose paper. We tie!"  /* tie++; */ };
        Random r = new Random();
        System.out.println(str[r.nextInt(3)]);
   
  }
    if(answer.equals("s")) {
        String[] str = { "You chose scissors. I chose rock. You lose!",  /* lose++; */ "You chose scissors. I chose paper. You win!",  /* win++; */ "You chose scissors. I chose scissors. We tie!"  /* tie++; */ };
        Random r = new Random();
        System.out.println(str[r.nextInt(3)]);
   
  }
  
    
    System.out.println("Score: " + win + " win(s), " + lose + " loss(es), " + tie + " tie(s)");
  System.out.println("Play again (y/n)?"); 
   String c = input.nextLine();

   if(c.equalsIgnoreCase("n")){ 
      break;
     }

}

}
}

I've tried using switch statements, but they haven't been working out. I've also been trying to use if statements but my code never works. Please note that I'm still fairly new to java so there are functions that I am quite unfamiliar with.