Generate random number from the set {1, 3, 100} - java

I already know how to generate a random number within a range;
but my question is about possibility of generating a number from a set of 2 or more specified numbers.
for example:
the output must be randomly chosen between exactly "1" or "3" or "100"
Another way to put it is: The value obtained will be any of the three numbers: 1, 3 or 100 (without any of the numbers in between).

Put the numbers in an int[3]
Choose a random number between 0 & 2.
Use that random number as the index of the array.
..is one of many ways.

Random is your solution for it:
public static int generateRandomNumber(int[] availableCollection) {
Random rand = new Random();
return availableCollection[rand.nextInt(availableCollection.length)];
}

{1,3,100}
Store them in an array and then select a random element from there. To select random element, see this: http://answers.yahoo.com/question/index?qid=20081025124826AAR8rmY

Java Math.random() generates random numbers between 0.0 and 1.0 you can write a code for what you want.
For example:
double random = new Math.random();
random = myRandom(random);
public double myRandom(double random){
if(random < 0.33){return 1;}
else if(random < 0.66) {return 3;}
else {return 100;}
}

Related

Is it possible to change range of random numbers?

I have an array of non repeating random numbers generated in the range of 0-20 as
int[] numbers = {6,14,11,18,13};
Now, I want to convert these numbers in the range of 0-10 and I want result as non repeating as well.
Is it possible ?
Any kind of suggestion would be appreciated.
Dividing them by two is a good solution since you have the same size of input and it keeps the uniformity :
For every number every number x in [0;10[, it can come from two numers in [0;20[ : 2*x and 2*x+1.
It will give you the same result for numbers like 10 and 11 but who cares?
Here are three methods that I have come up with:
// divide by 2
Arrays.stream(numbers).map(x -> x / 2);
// subtract 10 from everything that's > 10
Arrays.stream(numbers).map(x -> x > 10 ? x - 10 : x);
// remove every number that's > 10
Arrays.stream(numbers).filter(x -> x < 10);
Now that I know that you don't want repeating numbers, you should probably remove all the duplicates by calling distinct.
You could subtract 10 if randomly generated number is greater than 10. I know it's not a proper solution but it'll definitely work for you.
If you are using Java8, you can use the below code to generate unique random numbers:
int[] rand = new Random().ints(0, 11).distinct().limit(5).toArray();
This code generates 5 unique random numbers ranging from 0 to 10.
The range 0-20 contains 21 numbers, 0-10 contains 11 numbers. So the only solution that leads to uniformly distributed numbers is to take just the numbers in the range 0-10 from the original set and discard numbers in the range 11-20.
You can iterate the array in a enhanced for loop with a if condition.You already have non repeated value since you get values from number array.You can use arraylist or any other data structure to store random numbers less than 10.
ArrayList<Integer> numberList = new ArrayList<>();
for(int number:numbers){
if(number<10){
numberList.add(number);
}
}
One possible solution is to use helper array with double values.
The algorithm is next.
Create an array with double values from origin array and values are divided by 2.
Find the maximum value in the new double array.
Scale all values in the new double array. This is should be done by multiplying all values by a coefficient. The coefficient is coefficient = 10 / max.
Convert the new double array to integer values. One of possible strategy is to round double values.
Notes
It is possible that this solution has some 'bug' and will not work for all combination of random numbers. In that case, the conversion double values to integer should be improved.
If origin array contains more than 10 values it is not possible to map the array to a new array.
And this is the code for it.
public static void main(String[] args) {
int[] numbers = { 6, 14, 11, 18, 13 };
// crate a new array with double values
double[] newNumbers = new double[numbers.length];
for (int i = 0; i < numbers.length; i++) {
newNumbers[i] = (double) numbers[i] / 2;
}
// get coefficient
double max = maxValue(newNumbers);
double coefficient = 10 / max;
// scale numbers
for (int i = 0; i < newNumbers.length; i++) {
newNumbers[i] = newNumbers[i] * coefficient;
}
int[] newIntNumbers = new int[newNumbers.length];
for (int i = 0; i < newNumbers.length; i++) {
newIntNumbers[i] = (int) Math.round(newNumbers[i]);
}
System.out.println(Arrays.toString(newNumbers));
System.out.println();
System.out.println(Arrays.toString(newIntNumbers));
}
private static double maxValue(double[] array) {
double max = Double.MIN_VALUE;
for (double num : array) {
max = Math.max(max, num);
}
return max;
}

How can we use array elements as a counters in java?

import java.util.Random;
public class DemoArrayElement {
public static void main(String arg[]) {
Random rand = new Random();
int[] freq = new int[7];
for (int roll = 1; roll < 10; roll++) {
++freq[1 + rand.nextInt(6)];
}
System.out.println("FACE\tFREQUENCY");
for (int face = 1; face < freq.length; face++) {
System.out.println(face + "\t\t" + freq[face]);
}
}
}
Can someone please explain me this ++freq[1+rand.nextInt(6)]; line of code.
This program simulates rolling a die 10 times. The array freq is used to count the frequencies each face value is rolled - the index represents the face value and the content the number of times it was rolled. So, e.g., freq[3] contains the number of times 3 was rolled.
Let's take a look at ++freq[1+rand.nextInt(6)]; and take it apart:
rand.nextInt(6) calls Java's random number generator (a java.util.Random instance) and asks it for a uniformly distributed random number between 0 and 5 (inclusive). Adding 1 to it gives you a random face value form a die - a number between 1 and 6.
Accessing this index in the freq array (freq[1+rand.nextInt(6)]), as noted above, will return the number of times this face value was randomly encountered. Since we just encountered it again, this number is incremented (the ++ operator).
frec is an array containing 7 numeric elements.
++freq[1+rand.nextInt(6)]; means pre-increment a random element from an array.
Example: if the second element from the array is 5:
++freq[1]; will make it 6.

Generate random numbers increasing by multiples of N in Java

I need to write a short randomizer which generates a random number between 1 to N where the random number is increasing by multiples of M.
For example: generate numbers between 1 and (N=30) increasing by multiples of (M=5). The only possible generated numbers can be then: 1,5,10,15,20,25 and 30. Hope you get what I mean :)
Normally if you use new Random().nextInt(30)+1, you get numbers increasing by multiples of 1 (1,2,3,4,5,6,7,etc.). That is not what I want.
Any help, links, or directions are very appreciated?
EDIT:
That the sequence of generated random numbers could include 1 not zero is one of the requirements of the method. Precisely, the sequence always starts with the lower bound (min). In the example the lower bound is 1 and therefore there can't be zero in the sequence. It's odd I know, but those are the requirements I have to follow ;)
You could multiply the random value by 5. Since you want to have 1 instead of 0 just look for that value and alter it specifically:
static final Random random = new Random(System.currentTimeMillis());
public int random(int range, int multiple) {
int value = random.nextInt(range / multiple) * multiple;
return value == 0 ? 1 : value;
}
I think that your example is a little bit flawed: the sequence should be (0, 5, 10, 15, 20, 25, 30)
If I'm correct, you can then use:
new Random().nextInt(7) * 5; // will generate a number between 0 and 7 not included then multiply by 5 which should give what you want
If you want to start by 1, then just add it to the previous statement
Try this..
public static void main(String[] args){
int N = 50;
int M = 5;
System.out.println(getRandomNumber(N, M));
}
static int getRandomNumber(int n, int m){
Random r = new Random();
int rnd = r.nextInt(n);
return rnd%m == 0?rnd:getRandomNumber(n, m);
}
int n=Random.range(1,10);
n=n*100;

How to create unique random numbers from a given Random generator

Write an efficient algorithm to print the following two outputs
You are given a pre-defined function named getrand100() which returns
an integer which is one random number from 1-100. You can call this
function as many times as you want but beware that this function is
quite resource intensive. You cannot use any other random generator.
You canNOT change the definition of getrand100().
int getrand100(){
Random rand = new Random();
return (1+rand.nextInt(100));
}
Output1: Print numbers 1-20 in random order. (Not 20 random numbers)
Output2: Print numbers 1-200 in random order. (Not 200 random numbers)
Note:
i. Every number should be printed exactly once.
ii. There should be no pattern in the numbers listing. List should be completely random
i.e., all numbers have equal probability appearing at any place.
iii. You may call getrand100() any number of time to get randomnumber
from 1 to 100.
iv. You cannot use any other random generator
function except getrand100().
The idea is to use the Random generator given to compute the required random numbers.
1) For random numbers 1-20, just divide the 100 numbers equally to represent 1 to 20.
2) To generate 1-200, find the even numbers from 1 to 200 and then add (-1 or 0) to it to get all the numbers from 1 to 200.
import java.util.*;
public class Rand20_200{
int number20[]=new int[20]; //numbers in random order
int number200[]=new int[200];
public Rand20_200(){
int n=0;
int ngen[]=new int[20]; //to store which random numbers are generated
while(n<20){
int rnd=1 + (getrand100()-1) / 5;
if (ngen[rnd-1]==0){
ngen[rnd-1]=1;
number20[n++]=rnd;
}
}
System.out.println("Random 20 numbers");
print(number20);
ngen=new int[200]; //to store which random numbers are generated
int numoff[]={-1,0}; //offset to add
n=0;
while(n<200){
int rnd=numoff[(getrand100()-1)/50]+ (getrand100()*2);
if (ngen[rnd-1]==0){
ngen[rnd-1]=1;
number200[n++]=rnd;
}
}
System.out.println("\nRandom 200 numbers");
print(number200);
}
int getrand100(){
Random rand = new Random();
return (1+rand.nextInt(100));
}
void print(int arr[]){
for(int i=0;i<arr.length;i++){
System.out.print(arr[i]+" ");
}
}
public static void main(String args[]){
new Rand20_200();
}
}
Assuming this is homework, I'll keep the answer terse. :)
Look into the modulus operator %
You could create a list with your value (1 - 20, 1 - 200) and a random number, then sort the list on the random number.
public class RandomListItem
{
int value;
int sortindex;
public RandomListItem(x,y)
{
value = x;
sortindex = y;
}
}
for(int i = 1; i <= maxvalue; i++)
{
list.add(new RandomListItem(i, getrand100());
}
This might not be so good for the 200 list, since you can only generate random numbers up to 100. Might want to use getrand100() * getrand100() or something to generate a wider range of random numbers.

a random number from an array

I have an array
(1,2,2,2,3,3,4,5,5,5,5,5,5)
I must find randomly one position taking into account the sum of elements. for example if the 5 - is six times and the 1 - is only one, so the 5 must six times be often in random
Something like this?
int array[] = {1,2,2,2,3,3,4,5,5,5,5,5,5};
int randomIndex = Random.nextInt(array.length);
int randomNumber = array[randomIndex];
You need to get a random index of the array:
int randomIndex = Random.nextInt(array.length);
int randomValue = array[randomIndex]
Like another answer said, you need an int in the range 0 : length-1.
I would advise using:
Random r = new Random();
int index = r.nextInt(array.length);
int randomValue = array[index];
Here you can see the differences between Math.random() and the nextInt() method of a Random Object:
Math.random() versus Random.nextInt(int)
try this:
1 import java.util.Random;
2
3 class Rnd {public static void main(String... args) {
4 int[] data = new int[]{1,2,2,2,3,3,4,5,5,5,5,5,5};
5 System.out.print(data[new Random().nextInt(data.length)]);
6 }
7 }
nextInt() method "Returns a pseudorandom, uniformly distributed int value between 0 (inclusive) and the specified value (exclusive), drawn from this random number generator's sequence.". Because random is uniformly distributed, you'll get your number as more often, as more often it includes in an array.

Categories

Resources