prob 1 : What is this code its a constructor or a method or else?
prob 2 : How is this return statement working (both)?
Can anyone please explain...
public class RandomIntGenerator
{
private final int min;
private final int max;
private RandomIntGenerator(int min, int max) {
this.min = min;
this.max = max;
}
public static RandomIntGenerator between(int max, int min) //Prob 1
{
return new RandomIntGenerator(min, max); //Prob 2
}
public static RandomIntGenerator biggerThan(int min) {
return new RandomIntGenerator(min, Integer.MAX_VALUE); //Prob 2
}
public static RandomIntGenerator smallerThan(int max) {
return new RandomIntGenerator(Integer.MIN_VALUE, max);
}
public int next() {...} //its just a method
}
Basically they are methods which return new instances of the RandomIntGenerator class. Once you have those you can use the next() method to get random numbers.
RandomIntGenerator generator = RandomIntGenerator.between(5, 10);
int a = generator.next(); //a is now a "random" number between 5 and 10.
If the constructor was public, you could replace the first line with the line below, as they have the same effect.
RandomIntGenerator generator = new RandomIntGenerator(5, 10);
Related
I'm trying to figure out how to randomize the object selected as a parameter in a method. So I created two Pokemon classes below (rattata and pidgey)
class WildPokemon {
private static int randomHealth(int min, int max) {
int range = (max - min) + 1;
return (int)(Math.random() * range) + min;
}
private static int randomAttack(int min, int max) {
int range = (max - min) + 1;
return (int)(Math.random() * range) + min;
}
private static int randomSpeed(int min, int max) {
int range = (max - min) + 1;
return (int)(Math.random() * range) + min;
}
static Pokemon rattata = new Pokemon("Rattata",randomHealth(15,20),randomAttack(2,5),randomSpeed(2,6));
static Pokemon pidgey = new Pokemon("Pidgey",randomHealth(10,17),randomAttack(3,4),randomSpeed(3,5));
}
Below I am able to call rattata in the method Pokemon.battle() and it functions as expected. Is there a way I could randomize my second parameter to where it could be either rattata or pidgey selected at random?
public class PokemonTester{
public static void main(String[] args){
Pokemon.battle(starter, WildPokemon.rattata);
}
}
Important remark : using static methods and static fields for model is generally not advised.
Instead you should create an instance of WildPokemon and call method on it.
Do it in the same way you have already done to calculate random values.
You should use a List of pokemon rather than doing the compute with two hard coded values.
Try this :
public class WildPokemon{
...
private Random rand = new Random();
private List<Pokemon> pokemonList;
...
public WildPokemon(){
pokemonList = new ArrayList();
Pokemon rattata = new Pokemon("Rattata",randomHealth(15,20),randomAttack(2,5),randomSpeed(2,6));
pokemonList.add(rattata);
Pokemon pidgey = new Pokemon("Pidgey",randomHealth(10,17),randomAttack(3,4),randomSpeed(3,5));
pokemonList.add(pidgey);
...
}
private Pokemon getRandomPokemon() {
int n = rand.nextInt(pokemonList.size());
return pokemonList.get(n);
}
...
}
And call it :
WildPokemon wildPokemon = new WildPokemon();
Pokemon.battle(starter, wildPokemon.getRandomPokemon());
Use an array (or list) of objects and randomly generate an index value.
public class PokemonTester{
public static void main(String[] args){
WildPokemon[] pokemons = { rattata, pidgey };
Pokemon.battle(starter, pokemons[ (int)(Math.random()*pokemons.length) ] );
}
}
I am trying to do a pvp event in my game server which uses 3 zones to do it randomly. I use the following code but always is returning me the values 1 and 2 and repeated as well. I need some sequence like this for example: 3-2-1-2-1-3 or something that never repeats the same number.
int random = Rnd.get(1, 3);
if (random == 1)
{
setstartedpvpzone1(true);
}
if (random == 2)
{
setstartedpvpzone2(true);
}
if (random == 3)
{
setstartedpvpzone3(true);
}
this is what i get in rnd:
public final class Rnd
{
/**
* This class extends {#link java.util.Random} but do not compare and store atomically.<br>
* Instead it`s using a simple volatile flag to ensure reading and storing the whole 64bit seed chunk.<br>
* This implementation is much faster on parallel access, but may generate the same seed for 2 threads.
* #author Forsaiken
* #see java.util.Random
*/
public static final class NonAtomicRandom extends Random
{
private static final long serialVersionUID = 1L;
private volatile long _seed;
public NonAtomicRandom()
{
this(++SEED_UNIQUIFIER + System.nanoTime());
}
public NonAtomicRandom(final long seed)
{
setSeed(seed);
}
#Override
public final int next(final int bits)
{
return (int) ((_seed = ((_seed * MULTIPLIER) + ADDEND) & MASK) >>> (48 - bits));
}
#Override
public final void setSeed(final long seed)
{
_seed = (seed ^ MULTIPLIER) & MASK;
}
}
and rnd.get:
/**
* Gets a random integer number from min(inclusive) to max(inclusive)
* #param min The minimum value
* #param max The maximum value
* #return A random integer number from min to max
*/
public static final int get(final int min, final int max)
{
return rnd.get(min, max);
}
If all you are looking for is a random number that doesn't equal the previous one returned then the solution is much simpler:
private Random random = new Random();
private int previousZone = 0;
public int nextZone() {
int zone;
do {
zone = random.nextInt(3) + 1;
} while (zone == previousZone);
previousZone = zone; //store last "generated" zone
return zone;
}
[not tested] It is possible that it may contain some syntax errors as I am not a Java programmer.
int a=0,b=0;
while(true)
{
int random = Rnd.get(1, 3);
if(!(a==random or b==random))
{
a=b;
b=random;
break;
}
}
if (random == 1)
{
setstartedpvpzone1(true);
}
if (random == 2)
{
setstartedpvpzone2(true);
}
if (random == 3)
{
setstartedpvpzone3(true);
}
Your problem boils down to a graph traversal in which from each current zone, you only have 2 possible next zones and those choices never change. So here is how I would implement it:
public static class EventLocator{
private int currentZone;
private Random random;
private Map<Integer, int[]> locations;
private static EventLocator instance;
private EventLocator() {
}
public static EventLocator getInstance(){
if (instance == null) {
instance = new EventLocator();
}
return instance;
}
public int getNextZone(){
if (this.currentZone == 0) {//first time called
this.random = new Random();
this.locations = new HashMap<>(3);//graph <currentZone, posibleZones>
this.locations.put(1, new int[] { 2, 3 });
this.locations.put(2, new int[] { 1, 3 });
this.locations.put(3, new int[] { 1, 2 });
this.currentZone = this.random.nextInt(3) + 1;// to 1-based Zones
return currentZone;
}
int[] possibleZones = this.locations.get(this.currentZone);
int randomIndex = this.random.nextInt(2);//0 or 1 index
this.currentZone = possibleZones[randomIndex];
return this.currentZone;
}
}
You would call it like:
EventLocator eventLocator = MyProgram.EventLocator.getInstance();
System.out.println(eventLocator.getNextZone());
System.out.println(eventLocator.getNextZone());
This code never repeats any numbers, for example if you have 1,2,3 you can get a random sequence of 4 numbers, example 2,1,3.
Create an array with all numbers you need...
int[] a = {1, 2, 3};
Then select random items
for (int i=0; i<a.length; i++){
int random = Rnd.get(0, a.length);
//remove the selected item from the array
ArrayUtils.removeElement(a, random);
if (random == 1) {
setstartedpvpzone1(true);
} else if (random == 2) {
setstartedpvpzone2(true);
} else if (random == 3) {
setstartedpvpzone3(true);
}
}
private boolean _lastevent1 = false;
public boolean lastevent1()
{
return _lastevent1;
}
public void setlastevent1(boolean val)
{
_lastevent1 = val;
}
private boolean _lastevent2 = false;
public boolean lastevent2()
{
return _lastevent2;
}
public void setlastevent2(boolean val)
{
_lastevent2 = val;
}
private boolean _lastevent3 = false;
public boolean lastevent3()
{
return _lastevent3;
}
public void setlastevent3(boolean val)
{
_lastevent3 = val;
}
if (!lastevent1())
{
setlastevent3(false);
setstartedpvpzone3(false);
setstartedpvpzone1(true);
setlastevent1(true);
}
else if (!lastevent2())
{
setstartedpvpzone1(false);
setstartedpvpzone2(true);
setlastevent2(true);
}
else if (!lastevent3())
{
setlastevent1(false);
setlastevent2(false);
setstartedpvpzone2(false);
setstartedpvpzone3(true);
setlastevent3(true);
}
hello finally i fixed using booleans and i get this secuence, 1-2-3-1-2-3-1-2-3-1-2-3 , i breaked my mind with it because is very confuse this code but it work now as a charm , thanks for all to try to help me i very appreciate it, great community.
I would like to write simple program which can offer me feature to print n even numbers starting from some firstNumber. Its number is totalNumber. I don't want to save them, just print them. This is my piece of code:
import java.util.Iterator;
public class EvenNumbers implements Iterable<Integer>{
private int firstNumber;
private int totalNumbers;
public EvenNumbers(int firstNumber, int totalNumbers) {
this.firstNumber = firstNumber;
this.totalNumbers = totalNumbers;
}
#Override
public Iterator<Integer> iterator() {
return new myNewIterator();
}
private static class myNewIterator implements Iterator<Integer>{
private int firstNumber;
private int totalNumbers;
private int tmp;
public myNewIterator() {
this.firstNumber = firstNumber;
this.totalNumbers = totalNumbers;
this.tmp = firstNumber - 2;
}
#Override
public boolean hasNext() {
if(totalNumbers > 0){
totalNumbers--;
return true;
}
return false;
}
#Override
public Integer next() {
return tmp + 2;
}
}
}
And Main:
public class Main {
public static void main(String[] args) {
EvenNumbers en = new EvenNumbers(14, 4);
for (Integer n : en) {
System.out.println(n);
}
}
}
As may you can see, I don't get any output for this program.
Can someone explain me what I doing wrong?
Many thanks!
Why do you have so much code?
public class Main {
public static void main(String[] args) {
int start = 14;
int count = 4;
for (int n = start; n < start + 2 * count; n += 2) {
System.out.println(n);
}
}
}
#fafl answer is a better and concise answer.
To point out why this code was not working:
1. The problem is with your myNewIterator constructor. You were assigning the variable with itself. Also as default value of int is zero and your iteration condition if(totalNumbers > 0) will always fail.
public myNewIterator() {
/** these two lines have to be changed**/
this.firstNumber = firstNumber;
this.totalNumbers = totalNumbers;
/** end **/
this.tmp = firstNumber - 2;
}
You have to take these two values from constructor. Following is the corrected code. I have corrected the constructor name as well.
2. you must not decrement totalNumbers in hasNext() method because say there is a only one next element if I call hasNext() 100 times without calling next() it should still return true i.e. it has next element. So decrement should happen when next() is called.
3. tmp must be updated for every next() call.
These changes also are reflected in following code.
import java.util.Iterator;
public class EvenNumbers implements Iterable<Integer>{
private int firstNumber;
private int totalNumbers;
public EvenNumbers(int firstNumber, int totalNumbers) {
this.firstNumber = firstNumber;
this.totalNumbers = totalNumbers;
}
#Override
public Iterator<Integer> iterator() {
/***** changed *****/
return new myNewIterator(this.firstNumber,this.totalNumbers);
}
private static class myNewIterator implements Iterator<Integer>{
private int firstNumber;
private int totalNumbers;
private int tmp;
/***** changed *****/
public myNewIterator(int firstNo,int totalNo) {
/***** changed *****/
/**** edited these lines *******/
this.firstNumber = firstNo;
this.totalNumbers = totalNo;
/***** ****/
this.tmp = firstNumber - 2;
}
#Override
public boolean hasNext() {
if(totalNumbers > 0){
/***** changed *****/
//totalNumbers--; //commenting this line as repeated calls of this line makes this call unsafe
return true;
}
return false;
}
#Override
public Integer next() {
/***** changed *****/
totalNumbers--;
tmp = tmp + 2
return tmp;
}
}
}
Is there a way to implement a loop using final variables?
I mean a loop that would run for a specified number of iterations when you are not allowed to change anything after initialization!
Is recursion allowed, or do you literally need a loop construct like for or while? If you can use recursion, then:
void loop(final int n) {
if (n == 0) {
return;
} else {
System.out.println("Count: " + n);
loop(n-1);
}
}
One way is to create an Iterable<Integer> class representing an arbitrary range (without actually having to store all of the values in a list):
public static class FixedIntRange implements Iterable<Integer> {
private final int min;
private final int max;
public FixedIntRange(final int min, final int max) {
this.min = min;
this.max = max;
}
#Override
public Iterator<Integer> iterator() {
return new Iterator<Integer>() {
private Integer next = FixedIntRange.this.min;
#Override
public boolean hasNext() {
return next != null;
}
#Override
public Integer next() {
final Integer ret = next;
next = ret == max ? null : next + 1;
return ret;
}
#Override
public void remove() {
throw new UnsupportedOperationException();
}
};
}
}
and then iterate over it normally:
for (final int i : new FixedIntRange(-10, 20)) {
// this will be run for each i in the range [-10, 20]
}
Create an array whose size is the required number of iterations, then use it in a for-each loop:
public class Test {
public static void main(String[] args) {
final int N = 20;
final int[] control = new int[N];
for(final int i : control){
System.out.println(i);
}
}
}
The trick here is that the iteration indexing is generated by the compiler as part of the enhanced for statement, and does not use any user-declared variable.
Something like this -
final int max = 5;
for(int i=0; i<max; i++) {}
Or another interesting one-
final boolean flag = true;
while(flag) {
// keep doing your stuff and break after certain point
}
One more-
List<String> list = ......
for(final Iterator iterator = list.iterator(); iterator.hasNext(); ) {
}
I have an enum that I would like to randomly select a value from, but not truly random. I would like some of the values to be less likely of being selected so far. Here is what I have so far...
private enum Type{
TYPE_A, TYPE_B, TYPE_C, TYPE_D, TYPE_E;
private static final List<Type> VALUES =
Collections.unmodifiableList(Arrays.asList(values()));
private static final int SIZE = VALUES.size();
private static final Random RANDOM = new Random();
public static Type randomType() {
return VALUES.get(RANDOM.nextInt(SIZE));
}
}
Is there an efficient way of assigning probabilities to each of these values?
Code found from here
several ways to do it, one of them, similar to your approach
private enum Type{
TYPE_A(10 /*10 - weight of this type*/),
TYPE_B(1),
TYPE_C(5),
TYPE_D(20),
TYPE_E(7);
private int weight;
private Type(int weight) {
this.weight = weight;
}
private int getWeight() {
return weight;
}
private static final List<Type> VALUES =
Collections.unmodifiableList(Arrays.asList(values()));
private int summWeigts() {
int summ = 0;
for(Type value: VALUES)
summ += value.getWeight();
return summ;
}
private static final int SIZE = summWeigts();
private static final Random RANDOM = new Random();
public static Type randomType() {
int randomNum = RANDOM.nextInt(SIZE);
int currentWeightSumm = 0;
for(Type currentValue: VALUES) {
if (randomNum > currentWeightSumm &&
randomNum <= (currentWeightSumm + currentValue.getWeight()) {
break;
}
currentWeightSumm += currentValue.getWeight();
}
return currentValue.get();
}
}
Here's a generic approach to choosing an enum value at random. You can adjust the probabilities as suggested here.
Assuming you have a finite number of values you could have a separate array (float[] weights;) of weights for each value. These values would be between 0 and 1. When you select a random value also generate another random number between and only select the value if the second generated number is below the weight for that value.
You can create an enum with associated data bby provding a custom constructor, and use the constructor to assign weightings for the probabilities and then
public enum WeightedEnum {
ONE(1), TWO(2), THREE(3);
private WeightedEnum(int weight) {
this.weight = weight;
}
public int getWeight() {
return this.weight;
}
private final int weight;
public static WeightedEnum randomType() {
// select one based on random value and relative weight
}
}
import java.util.*;
enum R {
a(.1),b(.2),c(.3),d(.4);
R(final double p) {
this.p=p;
}
private static void init() {
sums=new double[values().length+1];
sums[0]=0;
for(int i=0;i<values().length;i++)
sums[i+1]=values()[i].p+sums[i];
once=true;
}
static R random() {
if (!once) init();
final double x=Math.random();
for(int i=0;i<values().length;i++)
if (sums[i]<=x&&x<sums[i+1]) return values()[i];
throw new RuntimeException("should not happen!");
}
static boolean check() {
double sum=0;
for(R r:R.values())
sum+=r.p;
return(Math.abs(sum-1)<epsilon);
}
final double p;
static final double epsilon=.000001;
static double[] sums;
static boolean once=false;
}
public class Main{
public static void main(String[] args) {
if (!R.check()) throw new RuntimeException("values should sum to one!");
final Map<R,Integer> bins=new EnumMap<R,Integer>(R.class);
for(R r:R.values())
bins.put(r,0);
final int n=1000000;
for(int i=0;i<n;i++) {
final R r=R.random();
bins.put(r,bins.get(r)+1);
}
for(R r:R.values())
System.out.println(r+" "+r.p+" "+bins.get(r)/(double)n);
}
}
Here is another alternative which allows the distribution to be specified at runtime.
Includes suggestion from Alexey Sviridov. Also method random() could incorporate suggestion from Ted Dunning when there are many options.
private enum Option {
OPTION_1, OPTION_2, OPTION_3, OPTION_4;
static private final Integer OPTION_COUNT = EnumSet.allOf(Option.class).size();
static private final EnumMap<Option, Integer> buckets = new EnumMap<Option, Integer>(Option.class);
static private final Random random = new Random();
static private Integer total = 0;
static void setDistribution(Short[] distribution) {
if (distribution.length < OPTION_COUNT) {
throw new ArrayIndexOutOfBoundsException("distribution too short");
}
total = 0;
Short dist;
for (Option option : EnumSet.allOf(Option.class)) {
dist = distribution[option.ordinal()];
total += (dist < 0) ? 0 : dist;
buckets.put(option, total);
}
}
static Option random() {
Integer rnd = random.nextInt(total);
for (Option option : EnumSet.allOf(Option.class)) {
if (buckets.get(option) > rnd) {
return option;
}
}
throw new IndexOutOfBoundsException();
}
}
You can use EnumeratedDistribution from the Apache Commons Math library.
EnumeratedDistribution<Type> distribution = new EnumeratedDistribution<>(
RandomGeneratorFactory.createRandomGenerator(new Random()),
List.of(
new Pair<>(Type.TYPE_A, 0.2), // get TYPE_A with probability 0.2
new Pair<>(Type.TYPE_B, 0.5), // get TYPE_B with probability 0.5
new Pair<>(Type.TYPE_C, 0.3) // get TYPE_C with probability 0.3
)
);
Type mySample = distribution.sample();