# random

## C/C++: Get a random number that is in a specific range1

Assuming you need to generate a random number that is in a specified range, you can do the following:

```//int rand(void) creates a pseudo-random number in the range of 0 to RAND_MAX
//RAND_MAX is defined in stdlib.h and is the largest number rand will return (same as INT_MAX).
const int new_number = (rand() % (maximum_number + 1 - minimum_number)) + minimum_number;

```

The above code first creates a pseudo-random number that is in the range of `[0, RAND_MAX]`.
Then it will divide it with the width (+1) of the range we want to use (`maximum_number + 1 - minimum_number`) and get the remainder (modulo).
The modulo will be in the range of `[0, maximum_number - minimum_number]`, so we add to it the value of `minimum_number` to shift the result to the proper range.
This solution, as demonstrated in the example below, works for negative ranges as well.

### Full example of generating `100000` random numbers that are all in the range `[-31, 32]`.

```const int maximum_number = 31;
const int minimum_number = -32;
unsigned int i;
for (i = 0; i <= 100000; i++) {
const int new_number = (rand() % (maximum_number + 1 - minimum_number)) + minimum_number;
printf("%d\n", new_number);
}
```

## Get execution time in seconds

The following methods demonstrate different methods on how to compute the time a potion of code or script take to complete their execution.

## Method 1 – Using date

The following example will calculate the execution time in seconds by subtracting the system date and time in seconds since `1970-01-01 00:00:00 UTC` once right before the script goes to the computation part and once right after.

In order to get the system date and time in seconds since `1970-01-01 00:00:00 UTC` we use the command `date +%s`.

```#!/bin/bash

#Print the system date and time in seconds since 1970-01-01 00:00:00 UTC
startTime=\$(date +%s);

#We pick a random number between 1 and 10.
#Then we delay the execution for that amount of seconds.
sleep \$(( (RANDOM % 10) + 1 ));

endTime=\$(date +%s);

#Subtract endTime from startTime to get the total execution time
totalTime=\$((\$endTime-\$startTime));

echo "Process finished after \$totalTime seconds";

exit 0;

```

## Method 2 – Using bash internal SECONDS variable

The following example will calculate the execution time in seconds by reseting the bash internal variable `SECONDS` to 0, forcing the shell to continue counting from there.

```#!/bin/bash

#This variable expands to the number of seconds since the shell was started.
#We set it to 0, forcing the shell to continue counting from there.
SECONDS=0;

#We pick a random number between 1 and 10.
#Then we delay the execution for that amount of seconds.
sleep \$(( (RANDOM % 10) + 1 ));

echo "Process finished after \$SECONDS seconds";

exit 0;
```

## Method 3 – Using bash time

The following example uses the bash time command, which reports the time consumed by a pipeline’s execution.
When time command is executed without its complete path, then the bash built-in time command is executed, instead of the GNU time command. We will use the bash time command in this example and we will use it to run a whole block of commands.
Please note that time command will return the time in seconds as a float (i.e. there will be decimal places. e.g. 1 will be printed as 1.00).

```#!/bin/bash

#The bash time command reports the time consumed by pipeline's execution
#When time command is executed without its complete path, then the bash built-in time command is executed, instead of the GNU time command.
#We will use the bash time command in this example and we will use it to run a whole block of commands.

#We change the output format of time to print elapsed real time in seconds.
TIMEFORMAT="%E";
#We pick a random number between 1 and 10.
#Then we delay the execution for that amount of seconds.
totalTime=`time ( sleep \$(( (RANDOM % 10) + 1 )) ) 2>&1`;

#Please note that time command will return the time in seconds as a float (i.e. there will be decimal places. e.g. 1 will be printed as 1.00).
#This will happen as time has build-in more precision than the first two methods presented here.
echo "Process finished after \$totalTime seconds";

totalTimeBlock=`time (
sleep \$(( (RANDOM % 10) + 1 ));
sleep \$(( (RANDOM % 10) + 1 ));
) 2>&1`;
echo "Block finished after \$totalTimeBlock seconds";

exit 0;
```

## Method 4 – Using GNU time

The GNU time command runs the specified program command with the given arguments.
When time command is executed without its complete path (in our case it was /usr/bin/time), then the bash built-in time command is executed, instead of the GNU time command. To make sure we use the GNU time command, we use which to get the full path of the time command.
Please note that time command will return the time in seconds as a float (i.e. there will be decimal places. e.g. 1 will be printed as 1.00).

```#!/bin/bash
#The time command runs the specified program command with the given arguments.
#When time command is executed without its complete path (in our case it was /usr/bin/time), then the bash built-in time command is executed, instead of the GNU time command.
#To make sure we use the GNU time command, we use which to get the full path of the time command.
time=`which time`;

#We pick a random number between 1 and 10.
#Then we delay the execution for that amount of seconds.
#We change the output format of time to print elapsed real time in seconds.
totalTime="\$( \$time -f '%e' sleep \$(( (RANDOM % 10) + 1 )) 2>&1 1>/dev/null )";

#Please note that time command will return the time in seconds as a float (i.e. there will be decimal places. e.g. 1 will be printed as 1.00).
#This will happen as time has build-in more precision than the first two methods presented here.
echo "Process finished after \$totalTime seconds";

exit 0;
```

## Notes

### RANDOM internal variable

Each time `RANDOM` internal variable is referenced, a random integer between `0` and `32767` is generated.

By using the `RANDOM` variable in this command `\$(( (RANDOM % 10) + 1 ));` we perform a modulo on the random value with the static value 10. This way we force the range of valid values to be between `0` and `9`.
Later, we add 1 to that value to shift the range to be between `1` and `10`.

## How to randomize order of rows in Excel

In the following video we demonstrate how to randomize the rows of an Excel sheet.

## Methodology:

• We created a new column next to the data we want to randomize their order, then we typed in the first cell the following formula `=rand()`.
`=rand()` will generate a random value between 0 and 1.
• After that we applied the same formula to the entire column.
• To apply the formula to the whole column we used a very simple method: we double-clicked on the bottom right hand corner of the cell . • Later, we sorted our date using the column of random values.
• Finally, we deleted the new column.

Alternative way to copy the formula to the entire column:

• Including the cell with the formula, select the cells in the new column that you want the new formula applied to (all the rows you want to be randomized) and the press `Ctrl+D`.

## C/C++: Pass random value from parent to child after fork() via a pipe()

The following code will create a pipe for each child, fork the process as many times as it is needed and send from the parent to each child a random int value, finally the children will read the value and terminate.

```#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <time.h>
int main(int argc, char *argv[]) {
int count = 3;
int fd[count];
int pid[count];
srand(time(NULL));

// create pipe descriptors
for (int i = 0; i < count; i++) {
pipe(fd[i]);
// fork() returns 0 for child process, child-pid for parent process.
pid[i] = fork();
if (pid[i] != 0) {
// parent: writing only, so close read-descriptor.
close(fd[i]);

// send the value on the write-descriptor.
int r = rand();
write(fd[i], &r, sizeof(r));
printf("Parent(%d) send value: %d\n", getpid(), r);

// close the write descriptor
close(fd[i]);
} else {
// child: reading only, so close the write-descriptor
close(fd[i]);

// now read the data (will block)
int id;
printf("%d Child(%d) received value: %d\n", i, getpid(), id);

close(fd[i]);
//TODO cleanup fd that are not needed
break;
}
}
return 0;
}```

`date +%s | sha256sum | base64 | head -c 32 ; echo`