How to create unique random numbers from a given Random generator - java

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.

Related

Generating a list of random integers (from -1000 to 1000), the number of integers in the list are determined by user input

I have looked through other questions but nothing seems to work. The user chooses how many numbers are in the list and they should be between -1000 and 1000. I tried using two for loops, one displaying the random number and another around that loop repeating the number of time the user enters. For now I tried to just get the loop to work with positive integers up to 1000. When using system print out it finally worked but using the GUI I just get one random number. I used an ArrayList because I thought it'd let me add to it with each loop.
int a;
private void btnSortActionPerformed(java.awt.event.ActionEvent evt) {
try {
a = Integer.parseInt(txtSort.getText());
} catch (NumberFormatException numberFormatException) {
lbl1.setText("Please enter a proper integer");
}
ArrayList<Integer> list = new ArrayList<>();
for (int i=1;i<=1000; i++) {
list.add(i);
}
for (int i=0; i<a; i++) {
txtpane1.setText(String.valueOf(list.get(i)));
}
}
txtSort is the textfield the program gets the number of integers and I'm using Apache NetBeans.
If I am understanding correctly your problem!
You want to generate random numbers user input times which lie between -1000 to 1000.
Then you want to display these all numbers in a Text Pane (Your GUI).
Please look at the following code: (Modified your code)
int a;
private void btnSortActionPerformed(java.awt.event.ActionEvent evt) {
try {
a = Integer.parseInt(txtSort.getText());
}
catch (NumberFormatException numberFormatException) {
lbl1.setText("Please enter a proper integer");
}
StringBuilder stringBuilder = new StringBuilder();
for (int i=1;i<=a; i++) {
int randomNumber = getRandomNumber(-1000,1001);
stringBuilder.append(randomNumber).append(" ");
}
txtpane1.setText(stringBuilder.toString());
}
public int getRandomNumber(int min, int max) {
return (int) ((Math.random() * (max - min)) + min);
}
I have created a method that gives you a random number in range (-1000 to 1000).
I have removed the ArrayList. Instead, I have created a StringBuilder which will store all random numbers in it.
Modify the first Loop which will iterate till user input times (not till 1000 time) and in each iteration, it get the random number and append this random number to string builder.
Removed second loop, no need for it.
After then, just setting StringBuilder text in the GUI.
Random rand = new Random()
final int min = -1000;
final int max = 1000;
// Map (-1000 to 1000) to ​(0 to 2001)
// because 'Random.nextInt' returns
// positive integers only.
final int positiveIntRangeMax = max - min + 1;
final int offsetFromPositiveIntRange = min;
​//loop 'a' times as required by user input
​for (int i=1;i<=a; i++) {
​int newPositiveRandInt = rand.nextInt(positiveIntRangeMax);
​int newRandIntInRange =
​newPositiveRandInt + offsetFromPositiveIntRange;
​list.add(newRandIntInRange);
​}
​txtpane1.setText(list.toString());
My attempt to get the random numbers.
You can generate the numbers like this.
Random r = new Random();
int n = r.nextInt(2001) - 1000;
r.nextInt(2001) returns a number between 0 and 2000 inclusive.
subtract 1000 from that and you get a number between -1000 and 1000 inclusive.
So you can use a loop to generate as many of those as you want. You can also use a stream to generate the numbers and create the list.
specify the number to generate and the range via r.ints
map to an Integer and subtract 1000 as before.
collect into a list.
int count = 10;
List<Integer> numbers = r.ints(count, 0, 2001)
.mapToObj(i -> Integer.valueOf(i - 1000))
.collect(Collectors.toList());
System.out.println(numbers);
Prints something like
[586, 110, 667, 502, 129, -474, 382, -357, -906, -910]
imports required
import java.util.List;
import java.util.Random;
import java.util.stream.Collectors;

How to generate random numbers between 1 and 60 [duplicate]

This question already has answers here:
Generate n random numbers whose sum is m and all numbers should be greater than zero
(8 answers)
Closed 2 years ago.
How can I do this? I know how to generate random numbers but not in a fixed range.
why dont you just simply random the sum. then generate n random numbers with that sum
public static void random(int n, int min, int max) {
Random random = new Random();
int sum = random.nextInt(max - min) + min;
List<Integer> list = new ArrayList<>();
int currentSum = 0;
for (int i = 0; i < n - 1; i++) {
int value = random.nextInt((int) (sum - currentSum) / (n - 1 - i)) + 1;
currentSum += value;
list.add(value);
}
list.add(sum - currentSum);
}
reference: Generate n random numbers whose sum is m and all numbers should be greater than zero
Here is a possible solution:
First we can call our method that will get us our sum value.
Then we get a random number between 0 and the sum we calculated which will give our first number.
Subtract our first number from the sum get another random for the second and the final value will be the 2nd from the sum again.
//Get the random number between two values
public static int startRange(int x, int y) {
Random rand = new Random();
return rand.nextInt(Math.abs(x-y)) + Math.min(x, y);
}
public static void main(String[] args) {
Random rand = new Random();
int sum = startRange(30, 50);
int firstNum = rand.nextInt(sum);
sum -= firstNum;
int secNum = rand.nextInt(sum);
int thirdNum = sum - secNum;
System.out.println(String.format("The nums are %d, %d and %d totaling %d",
firstNum, secNum, thirdNum, firstNum + secNum + thirdNum));
}
I assume you want to generate a random combination of N integers such that—
each integer is 0 or greater,
the integers have a sum that lies in the interval [minsum, maxsum],
the integers appear in random order, and
the combination is chosen uniformly at random from among all combinations that meet the other requirements.
This can be described as—
choosing a random sum (according to the number of combinations possible for that sum), then
choosing a random combination for that sum.
Part 2 is trivial thanks to the Smith and Tromble algorithm, and I give Ruby code for this algorithm in a question for a related problem.
Part 1 is the trickier part. It involves—
counting the number of valid combinations for each sum in [minsum, maxsum] (more formally, the number of partitions of each sum into N parts, where each part can be empty and occur more than once), then
choosing a random sum with probability proportional to the number of valid combinations (partitions) for that sum.
This is only a sketch of the problem, since I don't know the exact formula that meets the first three requirements stated above in this answer. All I know is that the number of partitions of N into k non-empty parts is equal to the Sterling number of the second kind (but I don't know a similar formula for the case where the parts can be empty or the parts can occur more than once).
This is probably your best bet for a generic solution:
int[] randomNumbersWithSumBetween(int num, int min, int max, Random random) {
if (min > max) throw new IllegalArgumentException("min > max");
if (num < 1) throw new IllegalArgumentException("No random numbers to generate");
int[] result = new int[num];
result[0] = min + random.nextInt(max - min);
for (; num-- > 1; ) {
result[num] = random.nextInt(result[0]);
result[0] -= result[num];
}
return result;
}

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

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;}
}

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.

What is the best way to create a random value?

I am triying to create random value for my game to show enemies on screen. BUt it some times shows 2 together some times 3 ...I want to ask that which is the best formul for creating random value.. This is my so far random value
random = 1 * (int) (Math.random() * 100);
"BUt it some times shows 2 together some times 3"
Given perfectly random numbers... In every 100 random values from 0 to 99, you'll find an average of 1.0 doubles. A triple will occur on average once for every 10,000 values. Given 10 million random numbers, java.util.Random yeilds the following results on my machine:
Doubles: 99873
Triples: 985
Double Rate: 1 in 100
Triple Rate: 1 in 10152
Source code:
import static java.lang.System.*;
import java.util.Random;
public class Sandbox {
public static final int NUM_ITERATIONS = 10000000;
public static void main(String[] args) {
Random rand = new Random();
int cur;
int last = -1;
int secondLast = -2;
int nDoubles = 0;
int nTriples = 0;
for (int i = 0; i < NUM_ITERATIONS; i++) {
cur = rand.nextInt(100);
if (cur == last) {
nDoubles++;
if (cur == secondLast) nTriples++;
}
secondLast = last;
last = cur;
}
out.println("Doubles: " + nDoubles);
out.println("Triples: " + nTriples);
out.println();
out.println("Double Rate: 1 in " + Math.round(1.0 * NUM_ITERATIONS / nDoubles));
out.println("Triple Rate: 1 in " + Math.round(1.0 * NUM_ITERATIONS / nTriples));
exit(0);
}
}
Actually the creation of genuinely random random numbers is a complex game in its own right. The Wikipedia article on this subject will give you an insight into the complexity that lies therein. Simple approximations such as those outlined above are probably sufficient for game purposes but will, it should be noted, be inclined to be 'streaky' from time to time.
You can use java.util.Random:
Random random = new Random(); // uses System.nanoTime() as seed
int enemies = random.nextInt(100);
Anyway, your approach is also fine, as it is in fact equivalent (behind the scene) with the above.
You can print a sequence of 100 random numbers generated your way and see for yourself that there isn't a problem.
What you use if perfectly fine.
In case you want something simplier you might like to use Random class like this:
Random generator = new Random(seed);
int number = generator.nextInt(100);
...and sometimes 77, sometimes 23, etc, as expected in a uniform distribution?
If you would like a normal distribution instead for your "enemies", so that extremes are less likely, it seems to be there in Java.

Categories

Resources