Suppose there is an array :
int arr[] = {0,1,2}
Is there a way I can generate a random number out of 0,1,2 (i.e from the array) ?
try this
import java.util.Random;
Random random = new Random();
System.out.println(arr[random.nextInt(arr.length)]);
Sure. You should generate a number between 0 and arr.length-1, round it to a int number and then take the arr[your_random_number] element.
int random_index = (int) round(Math.random() * (arr.length - 1));
then your element would be arr[random_index]
If you want unique element each time from the array then try this:
Integer arr[] = {0,1,2}
Collections.shuffle(Arrays.asList(arr));
for(int unique: ar)
System.out.println(unique);
Shuffle method of Collections will randomly shuffle the given array .
This will pick a number randomly out of the array.
public static void main(String[] args)
{
int arr[] = {0,1,2};
System.out.println(arr[(int)(Math.random()*arr.length)]);
}
Related
Sample with input and outputsI'm trying to apply the divide and conquer theorem on an array of integers in which I am to find the worst case index. On the initial array I have to split it into two on both sides of the midpoint. This is repeatedly done and at each instance the midpoint is deleted. I am to check for the peak on each sub array but in the end I am to print out only the indexes of all the worst cases. In as the input will be the initial length of the array at any given instance. So far I have been able to request and input and print out an array of indices of a given length n. Given that I'm not too familiar with Java yet I don't know how to go about it.
class Peak {
public static void main(String a[]){
List<Integer> al = new ArrayList<Integer>();
Scanner s = new Scanner(System.in);
System.out.println("enter the length of the array: ");
int n = s.nextInt();
for (int i = 0; i < n ; i++)
al.add(i);
System.out.println(al);
int size = al.size();
if (al.size()%2==0) {
//Sublist to ArrayList
ArrayList<Integer> lhs = new ArrayList<Integer>(al.subList(0, (size - 1)/2));
ArrayList<Integer> rhs = new ArrayList<>(al.subList((size + 1)/2, n));
}
if (al.size()%2==1) {
//Sublist to ArrayList
ArrayList<Integer> lhs = new ArrayList<Integer>(al.subList(0, (size - 1)/2));
ArrayList<Integer> rhs = new ArrayList<>(al.subList((size + 1)/2, n));
}
}
I want to make a 2d array that has for example {{2,5,5,2,4,7,6},{5,2,6,7,4,5,2}}
First half of array is random integers, second half of array is random members of first half of the array. This way I have pairs of every random number. This is my code so far, it gives me an array with random numbers. The part that I don't know how to do is the second half of array. Please help!
private int[][] board;
private int[] arr = {1,2,3,4,5,6,7,8};
public Board() {
board = new int[DEFAULT_SIZE][DEFAULT_SIZE];
for (int i=0;i<board.length;i++) {
for (int j=0;j<board.length;j++) {
board[i][j] = (int) (Math.random()*10);
}
}
You could use Random.nextInt() to get a random index and then use it to get the random number from the first array:
int randomIndex = Random.nextInt(arr.length);
int randomVal = arr[randomIndex];
I want to copy a larger array that some elements randomly removed by remove() method into the a small array.
I have used System.arraycopy() but this method copies elements respectively. Therefore some elements in the larger array don't be copied.
I want to copy the larger array's all non-removed elements into small array which has the length is equal to number of non-removed elements in larger array.
In case you are allowed to use other "system libraries", the solution is super-simple:
Shuffle the large array (or a copy of it; if you have to preserve the large array as is)
use arraycopy() and copy smaller.length elements from larger to smaller
The point is: when you shuffle the large array, you put it into random order!
But in case you are not allowed to use "system" libraries; you "shuffle" yourself:
iterate larger; and for each iteration, compute a random int within larger.length
swap the element of the current iteration with that randomly selected index
Afterwards, you can again use arraycopy.
import java.util.concurrent.ThreadLocalRandom; //for shuffling array
import java.util.Random; //for shuffling solution
public class BigToSmallArray {
public static void main(String[] args) {
int[] bigArray = new int[]{0,1,2,3,4,5,6,7,8,9};
int[] smallArray = new int[5];
int[] shuffledBigArray = shuffleArray(bigArray);
for(int i = 0; i < smallArray.length; i++) {
smallArray[i] = shuffledBigArray[i];
}
}
public static int[] shuffleArray(int arr[]) {
Random rnd = ThreadLocalRandom.current();
for (int i = arr.length - 1; i > 0; i--) {
int index = rnd.nextInt(i + 1);
// Simple swap
int a = arr[index];
arr[index] = arr[i];
arr[i] = a;
}
return arr;
}
}
I need to initialize an array of characters with 1000 random characters between [a,..z] and [A,..,Z].
I don’t want do this by first generating only characters between [a,..z] and then only characters in [A...Z] but treat all 52 characters equally.
I know one way to do this is to generate a random number between 0 and 51 and assign it one of the character values.
How would I approach this problem or assign values to the random numbers between 0 and 51?
You have got the interesting code idea.
Here might be the thought.
Take all the a-z and A-Z and store them in an array[].
Randomly generate a number between 1-52 (use API classes for that).
You will get a number in step 2, take it as an array index and pick this index from array[] of chars.
Place that picked char to your desired location/format............
Process it.
Best Regards.
Let me give you some general guidelines. The "one way to do this" you mentioned works. I recommend using a HashMap<E>. You can read more about hashmaps in the docs:
http://docs.oracle.com/javase/7/docs/api/java/util/HashMap.html
Alternatively, you can use another array that contains a - z and A - Z and you can use the index number to refer to them. But in this case I think it makes more sense to use a HashMap<E>.
I think you know how to create a Random object. But if you don't, check out the docs:
http://docs.oracle.com/javase/7/docs/api/java/util/Random.html
So you basically use the nextInt method of the Random class to generate a random number. And you can put that random number into your HashMap or array. And then you just put that character you get into an array that stores the result of the program.
This is the sample work, hope this will work for you
import java.util.ArrayList;
import java.util.Random;
public class RandomNumber {
public static void main(String args[]) {
char c;
ArrayList<Character> character = new ArrayList<Character>();
Random rn = new Random();
for (int i = 0; i < 500; ++i) {
character.add((char) (rn.nextInt(26) + 66));
character.add((char) (rn.nextInt(26) + 97));
}
System.out.println(character);
}
}
The simplest approach would be:
// constant declared in the class
static final int LETTERS_COUNT = 'z'-'a'+1;
char[] randomChars = new char[500];
Random r = new Random();
for(int i=0; i<randomChars.length; i++) {
randomChars[i] = (char)(r.nextInt(LETTERS_COUNT) + (r.nextBoolean() ? 'a' : 'A'));
}
If you don't like accessing random number generator two times, you can generate numbers from 0 to 51:
for(int i=0; i<randomChars.length; i++) {
int num = r.nextInt(LETTERS_COUNT*2);
randomChars[i] = (char)(num >= LETTERS_COUNT ? 'a'+(num-LETTERS_COUNT) : 'A'+num);
}
However I don't see any advantages of this approach. Internally r.nextInt may also change its internal state several times. The distribution should be similar in both cases.
You can this with a function using either arrays or arithemtic.
Note that you can calculate with characters like with numbers, because they are stored as numbers (http://www.asciitable.com/), you will also note that digits, small letters and big letters are stored in sequence so that accessing ranges is pretty easy with a simple for-loop.
private Random r = new Random();
public char randomLetter() {
int randomNumber = this.r.nextInt(52);
if(randomNumber >= 26) {
return (char)(('A'+randomNumber)-26);
} else {
return (char)('a'+randomNumber);
}
}
The version using an array will be faster, but can only be used if the set of possible outcomes is small enough to be stored.
private Random r = new Random();
private static char[] set = new char[52]; //static because we only need 1 overall
static { //this is a static "constructor"
for(int i = 0; i < 26; i++) {
set[i] = (char)('a'+i);
set[i+26] = (char)('A'+i);
}
}
public char fastRandomLetter() {
final int randomNumber = this.r.nextInt(52);
return set[randomNumber];
}
public class ShuffleArray {
public static void main(String[] args) {
int[] array = { 1, 2, 3, 4, 5, 6, 7 };
Random rand = new Random();
for (int i = 0; i < array.length; i++) {
int randomIndexToSwap = rand.nextInt(array.length);
int temp = array[randomIndexToSwap];
array[randomIndexToSwap] = array[i];
array[i] = temp;
}
System.out.println(Arrays.toString(array));
}
}
The following code shows 4 int variables:
int xy1 = 724329;
int xy2 = 714385;
int xy3 = 715440;
int xy4 = 696492;
I'm pretending to code an app that, by opening it, shows one of those numbers (NOT numbers between them) on java console, randomly. I know that Math.Random class can be used to solve these kind of issues, but I don't know what is the proper way to do so.
So, thanks.
Well it sounds like you just want a collection of possible values, and an index between 0 and 3 inclusive:
int[] values = { 724329, 714385, 715440, 696492 };
Random random = new Random(); // Ideally initialize once for the entire app
int index = random.nextInt(4);
int value = values[index];
Place them into an array and use Random to select a number between 0-3 and use it as a key to select the value from the array.
Try this one.
This line
r.nextInt(nums.length)
selects an integer from 0 to nums.length-1.
Then I print out the randomly selected number from the nums array.
I repeat this 20 times just for demonstration purposes.
import java.util.Random;
public class Test015 {
public static void main(String[] args) {
int[] nums = {724329, 714385, 715440, 696492};
Random r = new Random();
for (int i=0; i<20; i++){
int index = r.nextInt(nums.length);
System.out.println("Number randomly chosen: " + nums[index]);
}
}
}