Hello I have the following tasks:
First, I am given this code that uses a method to generate random numbers 100 times:
public class Q3 {
public static void printDiceRolls(Random randGenerator) {
for (int i = 0; i < 100; i++) {
System.out.println(randGenerator.nextInt(6) + 1);
}
}
public static void main(String[] args) {
Random man = new Random();
printDiceRolls(man);
}
}
Second, I am asked to make a class LoadedDice that extends the Random class:
public class LoadedDice extends Random {
// instance variables - replace the example below with your own
public int nextInt(int num) {
// code right here
return 3;
}
}
Then I am asked to override the public int nextInt ( int num ) and do the following
Override the public int nextInt(int num) method such that with a 50%
chance, the new method always returns the largest number possible
(i.e., num-1), and with a 50% chance, it returns what the Random's
nextInt method would return
I do not quite understand what my overridden method should do in this case.
Suggestions?
Use another Random instance to give you a 50% chance (e.g. nextInt(100) >= 50) then based on that return a constant or a real random.
I guess one way to do this is to use (another?) random number generator with a uniform distribution and set it to return 0 or 1. The 0/1 would be the 50% for you to make your decision upon.... either returning super.nextInt or the max number.
To me, it looks like the nextInt(int) function comes up with a number between 1 and the input. In the root Random class, this function finds a random number within that range. What they want you to do is change that so that half the time it will return a random number in the range, but the other half the time it will give the maximum number.
In the example they gave, you're rolling a dice, so the range is 1-6. Normally, nextInt will find a random number between 1 and 6. But your new function will only do that half the time. The other half the time, it will return 6.
I have an idea on how you can implement that, but it seems like it would be cheating to go that far. ^^;
if(super.nextBoolean())
return num-1;
return super.nextInt(num);
if num<Integer.MAX/2, we can
int x = super.nextInt(num*2);
return Math.min(x, num-1);
Related
I want to create a random int value ranging from 1-3. I researched and wrote this:
#Override
Random rand = new Random();
n = rand.nextInt(3) + 1;
public int quantityDropped(Random par1Random) {
return n;
}
So it said my code had errors and it didn't specify. I can't find the error myself, can anyone help me?
As per the documentation, it says that the Random.nextInt method call returns "a pseudorandom, uniformly distributed int value between 0 (inclusive) and the specified value (exclusive)".
To get a random number between min (inclusive) and max (inclusive) in Java, you do this:
Random r = new Random():
int randomNum = random.nextInt(max - min + 1) + min;
As such, to get a random number from 1-3 (both inclusive), do this:
Random r = new Random():
int randomNum = random.nextInt(3) + 1;
In javascript you can use:
parseInt(Math.random() * 4)
Your method declaration syntax is incorrect.
At the simplest, the method could look like this:
public int quantityDropped() {
return ThreadLocalRandom.current().nextInt(1, 4);
}
ThreadLocalRandom extends Random with some helpful methods, like generating an int in a (half-open) range.
If quantityDropped() is intended to override a method of a parent class, or implement an abstract method declaration in a parent type, you should add the #Override annotation.
If you intended to pass a random number generator to the method for some reason (for example, you want to explicitly seed the generator to produce a consistent sequence for testing), the method could look like this:
public int quantityDropped(Random random) {
return random.nextInt(2) + 1;
}
Again, add the #Override annotation if appropriate.
However, I doubt that's a good design for a class. If you are trying to create a mock implementation of some type that uses random numbers to imitate a real component, consider storing the Random instance in a field of that object:
class MockQuantityDropper implements QuantityDropper {
private final Random random;
MockQuantityDropper(Random random) { this.random = Objects.requireNonNull(random); }
#Override
public int quantityDropped() {
return random.nextInt(3) + 1;
}
}
I am selecting certain digits out of a large number. I'm saving the number in a string, and then saving each character as a subarray. This is what I have so far (I'm not finished). But when this code runs, System.out.print(v[0]) returns "55". I can't understand why. Printing anything else returns a similiarly (seemingly) random two numbers.
Thanks!
public class P432 { public static void main(String[] args) {
String x = "73167176531330624919225119674426574742355349194934"+
"96983520312774506326239578318016984801869478851843"+
"85861560789112949495459501737958331952853208805511"+
"12540698747158523863050715693290963295227443043557"+
"66896648950445244523161731856403098711121722383113"+
"62229893423380308135336276614282806444486645238749"+
"30358907296290491560440772390713810515859307960866"+
"70172427121883998797908792274921901699720888093776"+
"65727333001053367881220235421809751254540594752243"+
"52584907711670556013604839586446706324415722155397"+
"53697817977846174064955149290862569321978468622482"+
"83972241375657056057490261407972968652414535100474"+
"82166370484403199890008895243450658541227588666881"+
"16427171479924442928230863465674813919123162824586"+
"17866458359124566529476545682848912883142607690042"+
"24219022671055626321111109370544217506941658960408"+
"07198403850962455444362981230987879927244284909188"+
"84580156166097919133875499200524063689912560717606"+
"05886116467109405077541002256983155200055935729725"+
"71636269561882670428252483600823257530420752963450";
int[] v = new int[1000];
for (int g=0; g<1000; g++)
{
v[g] = x.charAt(g);
}
System.out.print(v[0]);
}}
As Jim said, you need to change the array to be char instead of int.
By the way, you can use v.length instead of the number 1000 in the for loop.
.length returns the length (size) of the array (1000 in this case), so if you'll want to change the array size in the future - you won't need to change the for loop condition.
I need to create a coin tossing java application.
Ok it must have an instance variable boolean.
and when it's true, the side of the coin will heads.
if false, then tails.
how do I go about it?
then after that, head will be = 1 while tails will be 0.
the purpose is to be able to count the number of times each side has.
Thanks!
import java.lang.Math;
class Coin {
boolean coinSide;
Coin() {
coinSide = true;
}
getCoinside() {
if(num = 1) {
}
}
public static void main(String [] args) {
int num = (int)(Math.random() *2); //returns an integer
System.out.println(num);
}
}
Ok I think i better put the requirements document over here so everyone can understand. cheers
(a) Design, write and test class that will represent a coin, with a method to toss the coin.
A coin has an instance variable that indicates whether a result was heads or tails. What type should this instance variable be?
The constructor for a coin should initialise the face of the coin to heads. The constructor has no parameters.
The coin has two methods:
• A method to return the result of the toss (i.e. returns the instance variable indicating heads or tails).
• A method to toss the coin
The method to toss the coin requires a random number, either 0 or 1.
We can get a random number using a method of the Math class. Math.random() returns a double value between 0 and 1. To convert this value to an integer, either 0 or 1, the following code is used
int num = (int)(Math.random() *2); //returns an integer
(b) When you have written your coin class, write a test class, with a main method, which will create a Coin object, and toss it. Each time it is tossed, print out the result (heads or tails).
(c) Now alter the main method to toss the coin 100 times, and count the number of times the coin toss results in heads and the number of time it result in tails. You will need a loop for this, iterating 100 times. Display the heads count and tails count.
You could write a simple app such as
import java.util.Random;
//This is for flipping the "coin"
public class coins{
private static Random random=new Random();
//This is the coin
private int amountOfHead=0;
//This is the int for amount of heads flipped
private int amountOfTails=0;
//This is the int for the amount of tails flipped
private static int a1;
//This is also the coin
public void flip(){
a1=random.nextInt(1);
//This "flips the coin" making it a 1 or 0
if(a1==0){
amountOfTails+=1;
//If the "coin" is 0 tails increases by 1
}else{
amountOfHeads+=1;
//If anything else happens(such as a 1) heads increases by 1
}
System.out.println(amountOfHeads+", "+amountOfTails)
//This prints the results out
}
}
To run this program you just call flip().
Okay
I have The problem that i want to generate 64 numbers between 0 and 1 (that means 0 or 1)
the function i have currently is:
public static int randNr(int max) {
Random r = new Random();
int o = r.nextInt(max);
return o;
}
But it always returns 0.
Is there any way to make that it generates also a 1 ?
EDIT:
the function is located in a different java file than when i calling it!
Two issues:
1) nextInt(max); generates a number from 0 and up to but not including max. My guess is that you're passing 1 as max. Pass 2 and all will be well.
2) Creating a new generator object each time ruins the statistical properties of the generator. You should create one Random instance and (i) either pass into the function or (ii) have the instance stored as a member variable.
This function works fine. You are probably calling it with the wrong arguments. It should be:
randNr(2)
Why? Because it's using the Random#nextInt(max) method, which will return a random integer in the range [0, max-1] (including 0 and max-1).
Note: It's not recommended to create a new Random object each time you call the function. One solution would be to declare the Random object as an static member of the class:
public class Test
{
private static Random r = new Random();
// ...
}
Another solution would be to use the static method Math.random()1:
int o = (int) Math.round(Math.random());
1: Could someone confirm if this method is faster than the OP's one?
static int n = -1;
private static int repeatBuffer[] = new int[10];
static {
repeatBuffer[0] = 0;
//and more
repeatBuffer[9] = 9;
}
static public void randomize() {
do {
Random r = new Random();
randomNumber = r.nextInt(20);
} while (!uniqueInt(randomNumber));
Log.e(TAG, "" + randomNumber); //here I need have a unique int
}
private static Boolean uniqueInt(int random) {
for (int i = 0; i < 9; i++) {
if (random == repeatBuffer[i]) {
return false;
}
}
if (++n > 9)
n = 0;
repeatBuffer[n] = random;
return true;
}
Sometimes I'm getting same int twice, I'm wondering where is the problem? And is it even work? I spend quite a lot of time on this, and I give up. I think I need some minor tweaks in code :)
An easier way to get a random int is to create a List of integers List<Integer>, adding it with numbers that you would like to have. Then shuffling the List using Collections.shuffle(list);. Now start reading from the beginning of the list and you will get a unique random int each time.
Just make sure that each time you "read" a number from the list, either remove it from the list or increase the index for where you read.
That's the normal behavior of a random number generator, it's correct to generate repeated numbers as long as the number distribution remains uniform.
If you need a set of unique random numbers, you can generate them inside a loop and ask at every iteration if the newly generated number is present in the set of generated numbers. If not, add it, if yes, keep iterating - until the set has the desired size.
Er, a unique random between 1 and 20? What happens when it runs the 21st time?
Try making a List of the Integers between 1 and 20. Use Collections.shuffle() to shuffle the list. Then pop the first item off the front of the list and use that.