Java output issue? Program not getting desired result [format updated] [closed] - java

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 5 years ago.
Improve this question
This program is supposed to go through the number of 2 to 50 people and get the probability out of 100,000 trials whether 2 people will have the same birthday or not.
import java.util.Random;
public class birthday {
public static void main(String[] args) {
int N = 2;
while (N != 51) {
double probability = one_probability(N);
System.out.println(N + " " + probability);
N++;
}
}
public static boolean one_group(int N) {
int A[] = new int[N];
Random random = new Random();
boolean have_match = false;
for (int i = 0; i < N; i++) { //assigns each person a birthday
int k = random.nextInt(365);
A[i] = k;
}
for (int i = 0; i < N; i++) { //testing to see if birthdays match up
for (int j = i+1; j < N; j++) {
if (A[i] == A[j]) { have_match = true; break; }
}
}
return have_match;
}
public static double one_probability(int N) {
int x = 0;
for (int i = 0; i < 100000; i++) { //repeating 100,000 times to get average probability
boolean have_match = one_group(N);
if (have_match == true) { x++; }
}
double probability = x / 100000; //getting the average probability
return probability;
}
}
Here's the result (it goes from 2-50), it keeps giving me zeros so I know something is wrong. Please help :)
Output

Try with
int probability = x / 1000; // 1/100 of the value to get an probability in percent (integer)
or
float probably = x / 100000F; //F for a `float`
double probability = x / 100000.0; //a decimal without a F is a `double`
Without that, this can't work :
float probably = x / 100000;
First, the division of two integer will be stored in memory like an integer then store in a float/double. That storage truncate the value. This is the operator logic to return the biggest type in an operation so :
int * int -> int
int * float -> float
int * double -> double
short * short -> int //that's a trick, int is the minimal value an operation can return

int probability=x/100000; always return 0.
convert it to double probability=x/100000.0; the value of probability will always less than or equal one. because x will never be greater than 100000. And also change the return type of one_probability method to double.

Related

What is wrong of my solution for the Leetcode question Sqrt(x)?

I am trying Leetcode Question - 69. Sqrt(x)
Given a non-negative integer x, compute and return the square root of x.
Since the return type is an integer, the decimal digits are truncated, and only the integer part of the result is returned.
Note: You are not allowed to use any built-in exponent function or operator, such as pow(x, 0.5) or x ** 0.5.
class Solution {
public int mySqrt(int x) {
int ans = 0;
int i=1;
while(i*i<=x){
ans = i;
i++;
}
return ans;
}
}
This is the code I came up with. But the testcase input=2147395600 is not passing.
My Output = 289398
Expected Output = 46340
I'm confused as I have put the condition i*i<=x, then how can ans be more than the sqrt value?
Since you are comparing i * i with the input x, if the input x is too close to Integer.MAX_VALUE (2.147.483.647), like in that test case, i * i will be bigger than the maximum value allowed for an int to have and i*i<=x will be true.
Possible solutions:
Implement a binary search algorithm where max would be the floor(sqrt(Integer.MAX_VALUE)) or 46340.
Implement a algorithm where ans, i and x are declared locally as long type variables and in the return line you return the value cast to int using return (int)ans;
By running the following algorithm you can see the limit of a java int exploding and what happens afterwards.
int x = 2;
while(true) {
System.out.println(x);
x *= 2;
}
Not pretending to be fast, just the idea that (n+1)2=n2 + 2n + 1:
public static int mySqrt(int x) {
int i = 0;
while (x >= 0) {
x -= (i++ << 1) + 1;
}
return i - 1;
}
My JavaScript Solution
var mySqrt = function(x) {
var ans = 1;
if(x === 0){
ans = 0;
} else {
for (let i = 1; i< x;i++){
if(i*i === x){
ans = i;
break;
}
if(i*i >x){
ans = i - 1;
break;
}
}
}
return ans;
};

Java: Expression including binomial coefficient calculation

Task is to calculate expression for natural numbers entered.
I know I should calculate binominal coefficient here right?
Also I know that (-1)^p determines whether this array is decrementing or incrementing, but don't know how to use p in my code
I am not quite sure how to put it all together, this is what I came up with so far and it is really nothing special as I still can't grasp on the idea of how to write this in program.
public static int calculateExpression(int n, int k,int p) {
if(k<0 || n<k)
{
return 0;
}
// Find factorial of n
int n_fac = 1;
for (int j = 1; j <= n; j++) {
n_fac = n_fac * j;
}
// Find factorial of k
int k_fac = 1;
for(int i = 1; i<=k; i++) {
k_fac = k_fac * i;
}
// Find n-k fac
int n_k = n-k;
int n_k_fac = 1;
for(int l = 1; l<=n_k;l++) {
n_k_fac*=l;
}
// n/k = n!/k!(n-k)!
double resultOf_n_kDivision = n_fac/k_fac*n_k_fa;
System.out.println(resultOf_n_kDivision);
return n_k_fac;
}
The factorial function is a very fast-growing one, so calculating the numerator and denominator separately may not be a good idea, as it may lead to overflow for even relatively small values of n.
Let's look at an iterative method for calculating the coefficient:
We see that we can calculate the next coefficient of the row if we know the current one. Thus we can incrementally calculate each term in S, while being less concerned about overflow problems.
static int calculateExpression(int n, int k, int p)
{
// first term of the row is (n, 0) = 1
int binom = 1;
// Iteratively find (n, k)
for (int i = 0; i < k; i++)
binom = (binom * (n - i)) / (i + 1);
// sum the series
int S = binom;
for (int i = 0; i < p; i++) {
// "trick": multiply with a minus sign each time to flip the sign
binom = (-binom * (n - k - i)) / (k + i + 1);
S += binom;
}
return S;
}
UPDATE: Parallel numerical tests:
n k p | orig new
----------------------
5 3 2 | 6 6
10 4 1 | -42 -42
12 3 7 | 44 44
15 8 6 | 3433 8 // integer overflow occurred with the original method
As you can see the two functions were consistent until the last line with n = 15, as 15! = 1307674368000 is much bigger than the maximum positive value of int in most implementations of Java (32-bit).
Use abstraction for better tackling problems; define fac and over.
Then the problem becomes:
public static int calculateExpression(int n, int k,int p) {
int sum = 0;
int minus1toP = 1;
for (int i = 0; i <= p; i++) {
sum += minus1toP * over(n, ...);
minus1toP = -minus1toP;
}
return sum;
}
static int over(int n, int k) {
return fac(n) / fac(k) / fac(n - k);
}
static int fac(int n) {
int f = 1;
for(int i = 2; i <= n; i++) {
f *= i;
}
return f;
}
I did not give the entire solution (...), but maybe too much already.
I did not really get your question, but you can just use this.
public static double combination(int n, int k)
{
double nFactorial = getFactorialFromNToK(n, k);
double kFactorial = getFactorialFromNToK(k, 1);
return nFactorial / kFactorial;
}
public static double getFactorialFromNToK(double n, double k)
{
double factorial = 1;
for (; n - k + 1 > 0; n--)
{
factorial *= n;
}
return factorial;
}
This is the evaluation of nCk for the coef of a term in the binomial expansion.
If nCn is a term in the expansion, then it converges and if it does not exist as term in the expansion, then it will not converge. So if it is a natural number expansion, then it will always converge.
A better solution is to use the lngamma function instead of factorial. It's a more efficient way to calculate factorials. The natural log means that dividing large numbers will be less of a problem.

generating random numbers in java and finding percentage of how many are less than or equal to 50

My question is why isn't the code generating the amount of numbers that the users enters? Right now the code is only generating one number. Here is the original question given to me:
"In your main method, prompt the user for a number n. Write a method
called assessRandomness that generates a random number between 1 and
100 'n' times and return the percentage of times the number was less than
or equal to 50. Call your assessRandomness method from main and display
the result to the user from main. Do not interact with the user from
within the assessRandomness method."
output:
How many random numbers should I generate? 10
<assume the random numbers generated were 11 7 50 61 52 3 92 100 81 66>
40% of the numbers were 50 or less
my code:
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.println("how many random numbers should I generate?: ");
int number = in.nextInt();
assessRandomness(number);
}
public static double assessRandomness(int n){
int random = (int)(Math.random()*100);
int randomNumbersLessthan50 = 0;
if (random <= 50)
{
double getPercentage = random/randomNumbersLessthan50;
}
else
{
System.out.println(random);
}
return random;
}
I don't see any kind of loop within assessRandomness.
Try
for(int x = 1; x <= n; x++){ ... }
as first line in assessRandomness, it should finally look like
public static double assessRandomness(int n){
int counterLessThan50 = 0;
for ( int x = 1; x <= n; x++)
if( (int)(Math.random()*100) <= 50 ) counterLessThan50++;
return (double) counterLessThan50 / n;
}
There's no repetition in your code to do something n times.
Here's one way to do it in one line using a stream:
public static double assessRandomness(int n) {
return Stream.generate(Math::random).limit(n).map(r -> r * 100 + 1).filter(r -> r <= 50).count() / (double)n;
}
Note that converting Math.random() to a number in the range 1-100 is pointless; this will give the same result:
public static double assessRandomness(int n) {
return Stream.generate(Math::random).limit(n).filter(n -> n < .5).count() / (double)n;
}
And is easier to read.
At the moment, your assessRandomness method never uses the variable n.
At first you should initialize a variable which counts the number of created randoms that are bigger than 50 (this will be your retutn value). You should then do a loop from 0 until n. For each loop run you should create a random value between 0 and 100. Then you should check wether the value is bigger than 50. If so, count up your previously created variable. When the loop has finished, return the count variable and print it in the main method.
This should help you understand better how to do something like this.
public static void main(String[] args) {
System.out.println("how many random numbers should I generate?: ");
Scanner in = new Scanner(System.in);
int number = in.nextInt();
int[] arrayPlaceHolderInMainMethod = new int[number];
arrayPlaceHolderInMainMethod = generateRandomNumberArray(number);
assessRandomness(arrayPlaceHolderInMainMethod);
}
public static void assessRandomness(int[] inputArray) {
int randomNumbersLessthan50 = 0;
int randomNumbersGreaterthan50 = 0;
int random = 0;
for (int i = 0; i < inputArray.length; i++) {
random = inputArray[i];
}
if (random <= 50) {
randomNumbersLessthan50 += 1;
} else {
randomNumbersGreaterthan50 += 1;
}
System.out.println(">50: " + randomNumbersGreaterthan50 + " Less: " + randomNumbersLessthan50);
}
public static int[] generateRandomNumberArray(int numberPickedByUser) {
int[] arrayOfRandomNumbers = new int[numberPickedByUser];
for (int i = 0; i < numberPickedByUser; i++) {
arrayOfRandomNumbers[i] = (int) (Math.random() * 100 + 1);
}
return arrayOfRandomNumbers;
}

Remove digits from a number in Java [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
How do I remove the first digit of an integer?
My input is an integer (for example i = 123456789).
I then want to remove the first digit, so that i equals 23456789.
try this
n = n % (int) Math.pow(10, (int) Math.log10(n));
Here is one way to do it:
Convert it to String
Take the substring without the first "digit"
Convert it to int
Code:
public static void main(String[] args)
{
int x = 123456789;
String x_str = Integer.toString(x);
int new_x = Integer.parseInt(x_str.substring(1));
System.out.println(new_x);
}
Output:
23456789
Note: This can be done in one line with
int x = 123456789;
int new_x = Integer.parseInt(Integer.toString(x).substring(1));
Edit:
To handle negative-case, check if number is positive or integer:
int new_x = Integer.parseInt(x > 0 ?
Integer.toString(x).substring(1) : Integer.toString(x).substring(2));
If you want to avoid the string conversion, you can find the high digit and subtract it.
public static void main(String[] args) {
int x = 123456789;
System.out.println("x = " + x);
int hi = x, n = 0;
while (hi > 9) {
hi /= 10;
++n;
}
for (int i = 0; i < n; i++) hi *= 10;
x -= hi;
System.out.println("x with high digit removed = " + x);
}
Here's the one-line, purely numeric solution:
i %= (int) Math.pow(10, (int) Math.log10(i));
Alternate approach:
int stripLeading(int i) {
if(i > 0) {
return i - (int)Math.pow(10, (int)Math.log10(i));
} else if(i > 0) {
return i + (int)Math.pow(10, (int)Math.log(-i+1));
} else {
return 0;
}
}
I think I remember the string-free version of this … although I totally agree with #Christian as how I would do it…
NOTE: as #Darren Gilroy pointed out, one must consider negatives and zero spocially, and my function fails to do so.
Of course % is a better solution also.
public static void main (String [] argv)
{
final int x = 123456789;
int newX = x;
/* How many digits are there? */
final double originalLog = Math.floor (Math.log10 (x));
/* Let's subtract 10 to that power until the number is smaller */
final int getRidOf = (int)Math.pow (10, originalLog);
while (originalLog == Math.floor (Math.log10 (newX)))
{ newX -= getRidOf; }
System.out.println (newX);
}
Poor profiling attempt:
Looping the above function without the println for 20,000,000,000 repeats in a for loop:
real 0m9.943s
user 0m9.890s
sys 0m0.028s
The same with Christian's far-easier-to-understand and perfectly functionable version, but for only 200,000,000 repeats (because I'm lazy and got tired of waiting):
real 0m18.581s
user 0m17.972s
sys 0m0.574s
So one might argue that constructing the String objects is probably slowing it down by roughly 200×, but that isn't a really finely-tuned profiling set-up.
If you want to go for simpler methods and without using String, then here's my simple take:
Count number of digits int the integer.
Divide the int by 10^n. n is the number of digits.
Obtain absolute value of the result. //In case of (-)ve numbers.
For example
int i = 123456789;
int n = getDigitCount(i);
int r = Math.abs(i / (int)Math.pow(10,n)); //r stores result.
And you'd require this method:
int getDigitCount(int num)
{
int c = 0;
while(num > 0){
num/=10;
c++;
}
return c;
}

Java calculation run-time error (using factorial to calculate Euler's number) [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Closed 8 years ago.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Improve this question
I'm trying to calculate the Euler's number.
As the Euler's number e = 1 + (1/1!) + (1/2!) + (1/3!) + ..... = 2.718281828....
where n! equals to the factorial of n.
First I wrote a class Factorial.class to calculate to factorial:
File Factorial.java
public class Factorial
{
//Methods
//If statement to abolish negative integer parameter have to be filled
public static int factorial(int number)
{
if (number == 0 || number == 1)
{
return 1;
} else
{
int m = number;
for (int i = number - 1; i > 1; i--)
{
m = m * i;
}
return m;
}
}
}
This class works fine with a testing class FactorialTest.class
File FactorialTest.java
public class FactorialTest
{
public static void main(String[] args)
{
System.out.println(Factorial.factorial(10));
}
}
This class prints 3628800
Later I create a EulersNumber.class to print the value of e:
File EulersNumber.java
public class EulersNumber
{
public static void main(String[] args)
{
double e = 1;
for (int i = 1; i > 10000; i++)
{
double j = (double)(Factorial.factorial(i));
double k = 1 / j;
e = e + k;
}
System.out.println("e = " + e); //e = 1.0
}
}
The value of e should be 2.718281828.... but this class prints e = 1.0
Where did I make a mistake?
for (int i = 1; i > 10000; i++)
There is a problem in the above line. The loop only executes if i > 10000. But i starts at 1. So it never executes.
BTW, you won't be able to use int to represent the factorial of 10000, which is an incredibly large number, well beyond of the limit of int (which is 2^32 - 1). Use BigInteger instead.
The loop only executes when i > 10000.
replace
for (int i = 1; i > 10000; i++)
with
for (int i = 1; i< 10000; i++)
In the for loop, the condition is > and must be <
Code:
for(int i = 0;i < 10000 ; i++)
Why didn´t make the factorial method recursive?
public static int factorial(int number)
{
if (number < 2)
{
return 1;
} else
{
return number * factorial(number-1);
}
}

Categories

Resources