Java unknown output - java

Soo this problem involves me rolling a pair of dice and estimate the probability that the first roll is a losing roll (2, 3, or 12).
output is the count of rolls that were losers (2,3, or 12) and calculated probability (count/N)
public static void main(String [] args){
int N1 = (int) (Math.random()*6 + 1);
int N2 = (int) (Math.random()*6 + 1);
int count = N1 + N2;
for (int i = 0; i<=1; i++)
if (count==2 || count = 3 || count == 12)
I just don't seem to know what to do get the output...... This is my attempt

It seems that you will want to roll the dice N times (where N is some large number) and count the number of times that it was a loser, correct?
So you will need to store in memory the total number of rolls, and the number of losing rolls. You can store those in int variables.
An int variable can be incremented using the ++ operator.
int rolls = 0;
rolls++;
is equivalent to
int rolls = 0;
rolls = rolls + 1;
You also don't want to call your main function a million times, so you can set the upper limit of your loop to the amount of rolls you want to have.
To calculate the probability, you will want to use floats rather than ints - you can cast an int to a float like this:
int a = 10;
float b = (float) a;
Finally, if you want to see your output via standard out, use System.out.println(). The argument to the println() function should be whatever you want to output.
Since this sounds like homework, I'm avoiding writing much code for now. Let me know if it isn't.

The simplest way to get output from a command-line app (like you are writing) is to use System.out.println(...). For example:
int digits = 5;
System.out.println("Hello world");
System.out.println("I have " + digits + " fingers");
This should be enough of a hint for you to make progress.

Related

Writing a method that outputs a different uniqe permutation of a number every time it's called

I got this interview question and I am still very confused about it.
The question was as the title suggest, i'll explain.
You are given a random creation function to use.
the function input is an integer n. let's say I call it with 3.
it should give me a permutation of the numbers from 1 - 3. so for example it will give me 2, 3 , 1.
after i call the function again, it won't give me the same permutation, now it will give me 1, 2, 3 for example.
Now if i will call it with n = 4. I may get 1,4,3,2.
Calling it with 3 again will not output 2,3,1 nor 1,2,3 as was outputed before, it will give me a different permutation out of the 3! possible permutations.
I was confused about this question there and I still am now. How is this possible within normal running time ? As I see it, there has to be some static variable that remembers what was called before or after the function finishes executing.
So my thought is creating a static hashtable (key,value) that gets the input as key and the value is an array of the length of the n!.
Then we use the random method to output a random instance out of these and move this instance to the back, so it will not be called again, thus keeping the output unique.
The space time complexity seems huge to me.
Am I missing something in this question ?
Jonathan Rosenne's answer was downvoted because it was link-only, but it is still the right answer in my opinion, being that this is such a well-known problem. You can also see a minimal explanation in wikipedia: https://en.wikipedia.org/wiki/Permutation#Generation_in_lexicographic_order.
To address your space-complexity concern, generating permutations in lexicographical ordering has O(1) space complexity, you don't need to store nothing other than the current permutation. The algorithm is quite simple, but most of all, its correctness is quite intuitive. Imagine you had the set of all permutations and you order them lexicographically. Advancing to the next in order and then cycling back will give you the maximum cycle without repetitions. The problem with that is again the space-complexity, since you would need to store all possible permutations; the algorithm gives you a way to get the next permutation without storing anything. It may take a while to understand, but once I got it it was quite enlightening.
You can store a static variable as a seed for the next permutation
In this case, we can change which slot each number will be put in with an int (for example this is hard coded to sets of 4 numbers)
private static int seed = 0;
public static int[] generate()
{
//s is a copy of seed, and increment seed for the next generation
int s = seed++ & 0x7FFFFFFF; //ensure s is positive
int[] out = new int[4];
//place 4-2
for(int i = out.length; i > 1; i--)
{
int pos = s % i;
s /= i;
for(int j = 0; j < out.length; j++)
if(out[j] == 0)
if(pos-- == 0)
{
out[j] = i;
break;
}
}
//place 1 in the last spot open
for(int i = 0; i < out.length; i++)
if(out[i] == 0)
{
out[i] = 1;
break;
}
return out;
}
Here's a version that takes the size as an input, and uses a HashMap to store the seeds
private static Map<Integer, Integer> seeds = new HashMap<Integer, Integer>();
public static int[] generate(int size)
{
//s is a copy of seed, and increment seed for the next generation
int s = seeds.containsKey(size) ? seeds.get(size) : 0; //can replace 0 with a Math.random() call to seed randomly
seeds.put(size, s + 1);
s &= 0x7FFFFFFF; //ensure s is positive
int[] out = new int[size];
//place numbers 2+
for(int i = out.length; i > 1; i--)
{
int pos = s % i;
s /= i;
for(int j = 0; j < out.length; j++)
if(out[j] == 0)
if(pos-- == 0)
{
out[j] = i;
break;
}
}
//place 1 in the last spot open
for(int i = 0; i < out.length; i++)
if(out[i] == 0)
{
out[i] = 1;
break;
}
return out;
}
This method works because the seed stores the locations of each element to be placed
For size 4:
Get the lowest digit in base 4, since there are 4 slots remaining
Place a 4 in that slot
Shift the number to remove the data used (divide by 4)
Get the lowest digit in base 3, since there are 3 slots remaining
Place a 3 in that slot
Shift the number to remove the data used (divide by 3)
Get the lowest digit in base 2, since there are 2 slots remaining
Place a 2 in that slot
Shift the number to remove the data used (divide by 2)
There is only one slot remaining
Place a 1 in that slot
This method is expandable up to 12! for ints, 13! overflows, or 20! for longs (21! overflows)
If you need to use bigger numbers, you may be able to replace the seeds with BigIntegers

Subtraction using while loop Java

So i'm trying to write a programme whereby the user enters two integers .
The programm is supposed to subtract 5 from the second integer entered in a loop depending on the first number entered. (so the first number should dictate how many times it will loop.
public int getScheme1() {
while (Mark >= 20) {
System.out.printf((Mark = Mark - 5) + Mark + " ");
}
for (int Day = 1; Day <= 20; Day++) {
System.out.printf("( " + Day + "):" + Mark + " ");
}
return Mark;
}
All my code does is print the user's second input integer 20 times.
Also im sorry im totally new to java
you must call this function in your main program.
public int getScheme1 (int num1, int num2){
for(int i = 1 ; i >= num1 ; i++ ){
num2 -= 5;
}
return num2;
}
to call it simply use getScheme1(num1,num2);
Based on what you described, you are looking for something like this:
Scanner input = new Scanner(System.in); //create a scanner to get user input
int a1 = input.nextInt(); //get 2 ints from the user
int a2 = input.nextInt();
for(int i = 0; i < a1; i++) { //loop as many times as a1 specifies
a2-=5; //subtract 5 from a2 each time it loops
}
System.out.println(a2);
The key part of this is the for loop, which works in the following:
for(variable; condition; increment),
basically, what the for loop I wrote is saying:
Set i = 0 at the start. If i is meeting the condition (in this case being less then a1), then loop. The increment part is called when it finishes running the code block, it now makes i bigger (in this case 1 bigger using ++) Another important thing to note is that the first time the loop runs, i = 0.
So for example, if I wanted to loop 10 times, with a starting variable of 3 and incremented 5 each time, I'd do:
for(int i = 3; i <= 53; i+=5) {}
Also, one last thing: please look at variable naming conventions, variables shouldn't start with caps like that, they should be camelCase

Explain what this code is doing

I'm a newbie in java. I was going through some tutorials and came across this code I was not able to understand the code. Please explain what it means.
class Randoms
{
public static void main(String[] args)
{
Random rand = new Random();
int freq[] = new int[7];
for(int roll = 1; roll < 10; roll++)
{
(++freq[1 + rand.nextInt(6)]);
}
...
Line by line:
Random rand = new Random(); create new instance of the Random object, this is responsible for the creation of random numbers.
int[] freq = new int[7]; create a new int array that can store 7 elements, with indices from 0...6. It is worth noting that in Java, the ints stored in the array are initialized to 0. (This is not true for all languages, an example being C, as in C the int arrays initially store memory junk data, and must be explicitly initialized to zero).
for(int roll = 1; roll < 10; roll++) this rolls 9 times (because 1...9, but it's better practice to go from 0)
(++freq[1 + rand.nextInt(6)]); this line is something that you shouldn't ever do in this sort of fashion, because it's a monstrosity as you can see.
Do something like this:
for(int roll = 0; roll < 9; roll++)
{
int randomNumber = rand.nextInt(6); //number between 0...5
int index = 1 + randomNumber; //number between 1...6
freq[index]++; //increment the number specified by the index by 1
//nearly equivalent to freq[index] += 1;
}
So basically it randomizes the number of 9 dice throws, and stores the dice throw count (or so it calls it, frequency) in the array.
Thus, it's simulating 9 dice throws (numbers from 1...6), and each time it "rolls" a particular number, it increases the number stored in the array at that specific location.
So in the end, if you say:
for(int i = 1; i <= 6; i++)
{
System.out.println("Thrown " + freq[i] + " times of number " + i);
}
Then it will be clearly visible what's happened.
(++freq[1 + rand.nextInt(6)]); // this line of code.
The above line of code is pre-incrementing the value of freq[] array at the specified position,i.e., 1+rand.nextInt(6) --- referred value is ++freq[some-position to be evaluated] which we will evaluate below.
This rand.nextInt(6) will generate an integer number lesser than 6 and greater than 0,as it is a pre-defined method of Random Class ,randomly.We can't predict it.
And,then say number generated is 4. SO, 1+rand.nextInt(6)=5.
Hence,your code would simplify to (++freq[1 + rand.nextInt(6)]) OR `(++freq[5]).
So,simplification of this code will be equivalent to a number which equals 1 more than 6th element of array freq[].
// as freq[5] is the 6th element of the array freq[].
Also,there are some other points which SIR David Wallace suggested me to include which I would like to explain a bit more.It goes below :-
++a here ++ is called pre-increment operator and it increases the value of a by 1. There also exists an altered reverse version of it.
a++ here this ++ is called post-increment operator and it also increases the value of a by 1.But,WAIT,you might have thought that there aren't differences,but there are.
For the differences potion,I'd like to suggest to have a reading of What is the difference between pre-increment and post-increment in the cycle (for/while)?, though it is questioned in sense of C++,the same is in Java too!
// Create a new Random Object, this helps you generate random numbers
Random rand = new Random();
// create a integer array with 7 integers
int freq[] = new int[7];
// loop 9 times
for(int roll = 1; roll < 10; roll++)
{
// rand.nextInt(6) generates a number between 0 and 5 (<6). add one to it
// ++ adds one to the integer in the array that is at the index of 1-6.
(++freq[1 + rand.nextInt(6)]);
}
Some strange things about this code:
Roll loop starts at 1 then goes to 10 so at first glance it would seem to loop 10 times but actually runs 9 times.
The ++ inside the loop would generally be located on the right and could lead to some confusion among newer programmers.
freq[1 + rand.nextInt(6)] causes freq[0] to never be used.
At first a new object of the Random-Class and an array with 7 elements are created. Each element of the Array has the value 0. Inside the for-loop you randomly pick element 2 to 7 of the Array and increase its current value by 1. This is done 9 times.
Your code will never pick the first element of the Array which has the index 0.
I would rewrite the code to make it more clear:
Random rand = new Random();
int freq[] = new int[6];
int randomIndex = 0;
for(int roll = 0; roll < 9; ++roll)
{
randomIndex = rand.nextInt(6);
freq[randomIndex] = freq[randomIndex] + 1;
}
This code has not been tested, but it should basicly do the same.

How to get a 50/50 chance in random generator

I am trying to get a 50/50 chance of get either 1 or 2 in a random generator.
For example:
Random random = new Random();
int num = random.nextInt(2)+1;
This code will output either a 1 or 2.
Let's say I run it in a loop:
for ( int i = 0; i < 100; i++ ) {
int num = random.nextInt(2)+1 ;
}
How can I make the generator make an equal number for 1 and 2 in this case?
So I want this loop to generate 50 times of number 1 and 50 times of number 2.
One way: fill an ArrayList<Integer> with fifty 1's and fifty 2's and then call Collection.shuffle(...) on it.
50/50 is quite easy with Random.nextBoolean()
private final Random random = new Random();
private int next() {
if (random.nextBoolean()) {
return 1;
} else {
return 2;
}
}
Test Run:
final ListMultimap<Integer, Integer> histogram = LinkedListMultimap.create(2);
for (int i = 0; i < 10000; i++) {
nal Integer result = Integer.valueOf(next());
histogram.put(result, result);
}
for (final Integer key : histogram.keySet()) {
System.out.println(key + ": " + histogram.get(key).size());
}
Result:
1: 5056
2: 4944
You can't achieve this with random. If you need exactly 50 1s and 50 2s, you should try something like this:
int[] array = new int[100];
for (int i = 0; i < 50; ++i)
array[i] = 1;
for (int i = 50; i < 100; ++i)
array[i] = 2;
shuffle(array); // implement shuffling algorithm or use an already existing one
EDIT:
I understand that if you are looking to accomplish exactly 50-50 results, then my answer was not accurate. You should use a pre-filled collection, since it is impossible to achive that using any kind of randomness. This considered, my answer is still valid for the title of the question, so, this is it:
Well, you do not need the rnd generator to do this.
Comming from javascript, I would go with a single liner:
return Math.random() > 0.5 ? 1: 2;
Explanation: Math.random() returns a number between 0(inclusive) and 1(exclusive), so, we just examine weather is larger than 0.5 (middle value). In theory there is a 50% change that does.
For a more generic use, you can just replace 1:2 to true:false
You can adjust the probability along the way so that the probability of getting a one decreases as you get more ones. This way you don't always have a 50% chance of getting a one, but you can get the result you expected (exactly 50 ones):
int onesLeft = 50;
for(int i=0;i<100;i++) {
int totalLeft = 100 - i;
// we need a probability of onesLeft out of (totalLeft)
int r = random.nextInt(totalLeft);
int num;
if(r < onesLeft) {
num = 1;
onesLeft --;
} else {
num = 2;
}
}
This has an advantage over shuffling because it generates numbers incrementally so it desn't need memory to store the numbers.
You have already successfully created a random generator that returns 1 or 2 with equal probability.
As (many) other's have mentioned, your next request, to force an exact 50/50 distributions in 100 trials, does not fall in line with random number generation. As shown in https://math.stackexchange.com/questions/12348/probability-of-getting-50-heads-from-tossing-a-coin-100-times, the realistic expectation of that occurring is only around 8%. So even while you might expect 50 of each, that exact outcome is actually rather rare.
The Law of Large Numbers states that you should close in on expected value as your number of trials increases.
So for your actual question: How can I make the generator make an equal number for 1 and 2 in this case?
The best (humorous) answer I can come up with is: "Run it in an infinite loop."

find the sum of even number not exceed four million

class fibo {
//int firstNumber = 0;
public static void main(String args[]){
//int firstNumber = 0;
int length = 4000000;
int[] series = new int[length];
//long[] sum = new long[4000000];
long sum =0;
series[0] = 0;
series[1] = 1;
for (int i = 2; i<4000000; i++){
//firstNumber = firstNumber + i;
//System.out.println("fibo" + i);
series[i] = series[i-1] + series[i-2];
if(series[i] %2 == 0) {
sum = sum + series[i];
}
}
for(int j=0;j<length; j++){
System.out.println("fibo Series" + series[j]);
}
}
}
I got the answer, but the approach was different. What's wrong with this code?. Can anyone give an insight on this.
The same code works when the length is 10. I am not getting any expection on this, but the answer seems to be different. Its something -92719184589087346 which is incorrect.
What's wrong with this code?
Well it's taking the sum of the even numbers within the first four million Fibonacci numbers, not the even numbers within the sequence of Fibonacci numbers less than four million.
It's also creating an array of all the Fibonacci numbers it's seen, for no reason: you only ever need the last two at a time, so you can do that in constant space.
I'm guessing you are trying to get the sum where the sum is less than 4million? because that isn't what you are calculating. You are calculating the sum at the 4 millionth index which is completely different.
The reason your answer is wrong (besides your logic being wrong) is that a long can't fit the number you are calculating. The 4 millionth entry in the fibonacci sequence is some number so incredibly large that it is overflowing your long. The overflow will make it wrap back into the negatives (probably multiple times).

Categories

Resources