a random number from an array - java

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.

Related

How to get the amount of the specified random number in Java FOR LOOP

I would like to ask how to get the amount of the specified number.
For example, I want to see the amount of the number 1234 which has been generated in the random generator. I would like it to print out the amount of the specified number which has been generated.
Merry Christmas.
Thanks for your reply.
Assuming you want to count the number of times a given random number was generated, and given an int value MAX with the maximum random number possible and an int COUNT for the number of random values to generate, you might create an array of counts and then print it. Something like
int COUNT = 1000;
int MAX = 100;
Random rand = new Random();
int[] counts = new int[MAX]; // <-- 0, MAX all initialized at 0.
for (int i = 0; i < COUNT; i++) {
counts[rand.nextInt(MAX)]++; // <-- add one at a random index between
// 0 (inclusive) and MAX (exclusive).
}
System.out.println(Arrays.toString(counts));

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;

Java Random number but not zero

int num = 10;
Random rand = new Random();
int ran = rand.nextInt(num);
if (ran==0){
ran= ran+1;
}
System.out.println("random : "+ran);
This is what i have coded so far, is there a better way to do this? I feel that this is hard coding when random is 0, I added 1.
The problem with that code is that 1 is twice as likely as other numbers (as your effective result is 1 when nextInt() returns 0 or 1).
The best solution is to just always add 1 and request random numbers from a smaller range:
int rnd = rand.nextInt(num - 1) + 1;
I guess you are trying to get a random number between 1 and 'num'.
a more generic way can be :
int Low = 1;
int High = 10;
int R = r.nextInt(High-Low) + Low;
This gives you a random number in between 1 (inclusive) and 10 (exclusive). ( or use High=11 for 10 inclusive)
Random random = new Random();
int ran = random.nextInt(9) + 1; //10 is maxRandom value for this code. 1-10
you also could do the following:
int randomNumber = 0;
do {
randomNumber = rand.nextInt(maxValue);
} while(randomNumber == 0);
Try this:
int num,max=10,min=1;
Random r=new Random();
num=r.nextInt(max-min)+1;
You'll need this import at the beginning of your file:
import java.util.Random;
Just lower the bound (num variable) by 1 and add 1 to the ran variable
int num = 10;
Random rand = new Random();
int ran = rand.nextInt(num - 1) + 1;
// or decrease num first n-- and then int ran = rand.nextInt(num) + 1
now the bound(limit) is 8 (inclusive for example, the final number is always exclusive) and if it comes 0, it will increase to 1 and if it comes 8, it will increase to 9, which was originally supposed to be the bound.
Don't expect this functionality from Random and do it yourself as you should. One can do pretty much anything with the result - multiply, add (e.g. 2*nextInt(n)+1 for random odd number), use logarithmic scale for musical note frequencies, use a map or enum to obtain random objects ...
Method nextInt(n) is here only to give you n different values (from 0 to n-1). Don't ask more of it, implement the rest by yourself. If I understand your question well, you require numbers 1..9, so you should ask for nextInt(9)+1 to get 0..8 and then add 1.
I hope this explanation helps, I saw many answers, but I didn't like the explanation in any of them.
Try:
int num = 10;
Random rand = new Random();
int ran = rand.nextInt(num) + 1;

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.

Categories

Resources