I'm trying to randomize between these 3 variables (not range, but only between these 3 values) and store it into new variable.
int randomProductDiscount() {
int disc1 = 25;
int disc2 = 35;
int disc3 = 50;
int productDiscount = (random between disc1 or disc2 or disc3);
return productDiscount;
}
Any help would be appreciated.
Put them in an array and obtain random index:
static Random rand = new Random();
int randomProductDiscount()
{
int[] disc = {25,35,50};
return disc[rand.nextInt(disc.length)];
}
This can be used for any number of values you wish to choose randomly from.
Related
Specifically, if we create a method that will generate this integer and place it at a random spot in the array.
static void placeRandomly2D(int[][] arr, int limit) {
// generates value [0...limit) half-interval and places it into the 2D array arr
// at random position; limit must be positive
Random rand = new Random();
int value = rand.nextInt(limit);
int pos1 = rand.nextInt(arr.length);
int pos2 = rand.nextInt(arr[pos1].length);
arr[pos1][pos2] = value;
}
And, just in case, version for 1-dimensional array:
static void placeRandomly1D(int[] arr, int limit) {
// generates value [0...limit) half-interval and places it into the 1D array arr
// at random position; limit must be positive
Random rand = new Random();
int value = rand.nextInt(limit);
int pos = rand.nextInt(arr.length);
arr[pos] = value;
}
import java.util.Random;
public class Console {
public static void main(String[] args) {
while (3>2) {
Random rand1 = new Random();
Random rand2 = new Random();
Random rand3 = new Random();
Random rand4 = new Random();
Random rand5 = new Random();
Random rand6 = new Random();
Random rand7 = new Random();
Random rand8 = new Random();
int onenum = rand1.nextInt(2);
int twonum = rand2.nextInt(2);
int threenum = rand3.nextInt(2);
int fournum = rand4.nextInt(2);
int fivenum = rand5.nextInt(2);
int sixnum = rand6.nextInt(2);
int sevennum = rand7.nextInt(2);
int eightnum = rand8.nextInt(2);
int binary[] = {onenum, twonum, threenum, fournum, fivenum, sixnum, sevennum, eightnum};
System.out.println(java.util.Arrays.toString(binary));
How can I check if, say the first number of the binary array is one?
Currently if I run, i get an output of like {1, 0, 1} ect
You can do it by using an index to access to an element in a specific position of an array:
if (someArray[position] == something)
In your case, to check the first element, it would be:
if (binary[0] == 1)
Note:
Indices in most programming languages start with 0 so the first element would be in the index 0 of the array. The second in the index 1. And so on.
Gosh i can reduce your code so much!! Analyse and see that this code does same as yours.
while (3>2) {
Random rand = new Random();
int[] binary = new int[8];
for(int i=0;i<8;i++)
binary[i] = rand.nextInt(2);
if(binary[0] == 1)
//if first number is 1
}
You can simply do:
if(binary[0] == 1) {
//do something
}
0 is the first element in array, since the fact of Arrays is a 0 based.
Side note: You don't have to declare a new object from Random to get a number, you can use the same object like:
Random rand = new Random();
int onenum = rand.nextInt(2);
int twonum = rand.nextInt(2);
int threenum = rand.nextInt(2);
// and so on
Just do this to check if first element equals to 1:
if (binary[0] == 1)
{
//do whatever here..
}
Other issues about your codes
I realized you use while (3>2). You can use while(true) if you want it to be an infinite loop.
You only need to create one random object to create multiple random numbers. Do it like this..
.
Random rnd = new Random();
oneNum = rnd.nextInt(2);
twoNum = rnd.nextInt(2);
threeNum = rnd.nextInt(2);
You can even do it this way (using an array to store the random numbers):
Random rnd = new Random();
int[] num = new int[8];
for (int x=0; x<num.length; x++)
num[x] = rnd.nextInt(2);
Hi I am having some problems with using random numbers inside of loops.
private void SetMines()
{
Random randRowGen = new Random();
Random randColGen = new Random();
int mineCount = 0;
int numMines = (ROWS * COLUMNS)* (int)0.156;
while(mineCount <= numMines)
{
int randRow = randRowGen.nextInt(ROWS)+1;
int randCol = randColGen.nextInt(COLUMNS)+1;
grid[randRow][randCol] = new Character('*');
mineCount++;
}
}
Here is my method it is going through an array size 25 * 25 and picking random spots and putting "mines" there. The only problem is it only selects one location to put a "mine" in and it needs to put 97 mines in random spots.
Any help will be appreciated thanks!!
Your numMines calculation will always return 0, because when you cast a double that is less than 1 to an int, it will be set to 0, which means that the statement in your while loop will only be run a single time, hence only a single mine being placed.
The problem isn't Random, it's int numMines = (ROWS * COLUMNS)* (int)0.156;. Have you checked what that value is? It's 0, because (int) 0.156 equals 0.
Perhaps you want int numMines = (int) ((double) 0.156 * ROWS * COLUMNS);. The problem with integer maths is that you can lose a LOT of precision.
Make your computer suffer and make it drop all those mines.
Remember. The definition of "computation" is "to force a machine do a boring job that nobody else would like to do" :-)
public static void main(String[] args) {
int rows = 25;
int cols = 25;
boolean[][] mines = new boolean[rows][cols];
while(mineCount(mines) < 97){
dropMine(mines);
}
for(int i=0;i<rows;i++){
for(int j=0;j<cols;j++){
System.out.print("[");
if (mines[i][j]){
System.out.print("*");
}else{
System.out.print(" ");
}
System.out.print("] ");
}
System.out.println();
}
}
private static void dropMine(boolean[][] mines) {
int x = (int)(Math.random()*25);
int y = (int)(Math.random()*25);
mines[x][y] = true;
}
private static int mineCount(boolean[][] mines) {
int count = 0;
for(int i=0;i<25;i++){
for(int j=0;j<25;j++){
if (mines[i][j]){
count++;
}
}
}
return count;
}
In my code I use random numbers in different classes. How to define random seed? Can I define this seed for all the classes in the main code?
double rnd = Math.random();
You will probably want to use the special Random class. It gives you more control over the random numbers.
To do this you first need to create a new random object.
Random generator = new Random(seed);
Then generate a new number by
double random = generator.nextDouble();
http://docs.oracle.com/javase/6/docs/api/java/util/Random.html
public class MathRandomWithSeed {
public static void main (String args[]){
int min = 5;
int max = 100;
int seed = 5;
int random = randomNext(min, max, seed);
System.out.println("Random = " + random);
}
private static int randomNext(int min, int max, int seed){
int count = (max - min) / seed;
int random = ((int)(count * Math.random()) * seed) + min;
return random;
}
}
I need unique random ints in specified range. I use this approch:
class Main
{
static final int RANGE = 100;
static int uniqueGenerator(int range_, boolean boolArr_[], Random rand_)
{
int tmpVar = rand_.nextInt(range_);
while (boolArr_[tmpVar] == true)
{
tmpVar = rand.nextInt(range_);
}
boolArr_[tmpVar] = true;
return tmpVar;
}
public static void main(String[] args)
{
Random rand = new Random();
boolean boolArr[] = new boolean[RANGE];
Arrays.fill(boolArr, false);
int ceiling = 10;
int tmp = Main.uniqueGenerator(ceiling, boolArr, rand);
System.out.println(tmp); => 5
ceiling = 20;
tmp = Main.uniqueGenerator(ceiling, boolArr);
System.out.println(tmp); => 17
}
}
It seems to be cumbersome. Maybe someone knows better approach?
EDIT: I use it in game code, so I need most efficient solution. Answers below suggest initializing new list, shuffling it => too resource consuming/need to generate new list every time when need to change range.
List<Integer> list = new ArrayList<Integer>();
for(int i = 1; i <= 100; i++) list.add(i);
Collections.shuffle(list);
Fill an array with the range of numbers you want, shuffle it and extract an item.
Edit: Look at Eng.Fouad's example to see how this is implemented.
Generate and store random numbers in set
Set<Integer> set = new HashSet<Integer>(100);
Random rand = new Random();
while (set.size() < 1000) {
set.add(rand.nextInt(100));
}
for (Integer integer : set) {
System.out.println(integer);
}