My code works fine in my compiler and I even tried another few online compilers but still not able to find the issue, can someone help!
Question
https://www.codechef.com/JUNE18B/problems/NAICHEF
Once, after a stressful day, Chef decided to relax and visit a casino near his house to gamble. He feels lucky and he's going to bet almost all of his money.
The game Chef is going to play in the casino consists of tossing a die with N
faces twice. There is a number written on each face of the die (these numbers are not necessarily distinct). In order to win, Chef must get the number A
on the first toss and the number B
on the second toss of the die.
The excited viewers want to know the probability that Chef will win the game. Can you help them find that number? Assume that Chef gets each face of the die with the same probability on each toss and that tosses are mutually independent.
My submission
import static java.lang.System.exit;
import java.util.*;
import java.lang.*;
/**
*
* #author williamscott
*/
public class Main {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
boolean status = true;
int T = Integer.parseInt(in.nextLine());
//Original Constraint
if (T < 1 || T > 10) {
// System.out.println("Please follow original constraint for T");
// exit(0);
status = false;
}
int N[] = new int[T], A[] = new int[T], B[] = new int[T];
float Probability[] = new float[T];
for (int t = 0; t < T; t++) {
String[] input = in.nextLine().split(" ");
N[t] = Integer.parseInt(input[0]);
A[t] = Integer.parseInt(input[1]);
B[t] = Integer.parseInt(input[2]);
if (N[t] < 1 || N[t] > 100) {
// System.out.println("Please follow original constraint for N");
// exit(0);
status = false;
}
if (A[t] < 1 || A[t] > N[t]) {
// System.out.println("Please follow original constraint for A");
// exit(0);
status = false;
}
if (B[t] < 1 || B[t] > N[t]) {
// System.out.println("Please follow original constraint for B");
// exit(0);
status = false;
}
float pn, pa = 0, pb = 0;
String[] f = in.nextLine().split(" ");
pn = f.length;
if (pn != N[t]) {
// System.out.println("Inputs Invalid");
// exit(0);
status = false;
}
for (String f1 : f) {
if (Integer.parseInt(f1) < 1 || Integer.parseInt(f1) > N[t]) {
// System.out.println("Please follow original constraint for x (input)");
// exit(0);
status = false;
}
if (Integer.parseInt(f1) == A[0]) {
pa++;
}
if (Integer.parseInt(f1) == B[0]) {
pb++;
}
}
Probability[t] = (pa / pn) * (pb / pn);
}
if (status) {
for (float d : Probability) {
System.out.println(String.format("%.10f", d));
}
}
}
}
Error:
First of all, you should use double rather then float (precision matters)!
Secondly, you should update your conditions for status because you take in consideration only the first sub-task with (T less than 10, and N less than 100) which will give you only 20 points! the second sub-task (that rewards 80 points) takes a T less than 70 and a N less than 1000.
Finally, the issue with the code comes from the condition of updating pa & pb, you use :
Integer.parseInt(f1) == A[0] // same for B[0]
instead of
Integer.parseInt(f1) == A[t] // same for B[t]
Here is the complete code and submission results
import java.util.*;
import java.lang.*;
/**
*
* #author aoubidar
*/
public class Main {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
// number of test cases
int T = Integer.parseInt(in.nextLine());
int[] N = new int[T];
int[] A = new int[T];
int[] B = new int[T];
double[] Probability = new double[T];
for (int t = 0; t < T; t++) {
String[] input = in.nextLine().split(" ");
N[t] = Integer.parseInt(input[0]);
A[t] = Integer.parseInt(input[1]);
B[t] = Integer.parseInt(input[2]);
int total, pa = 0, pb = 0 ;
String[] faces = in.nextLine().split(" ");
total = faces.length;
for (String f : faces) {
if (Integer.parseInt(f) == A[t]) {
pa++;
}
if (Integer.parseInt(f) == B[t]) {
pb++;
}
}
double pn = (double) (total * total);
Probability[t] = (pa * pb) / pn ;
}
for (double d : Probability) {
System.out.println(d);
}
}
}
submission success:
Never compare floating point numbers using == or !=. Digital computers cannot represent floating point numbers with absolute precision, and so these tests will often fail.
Never use float when double will work. You gain little by using float and lose a much precision.
Leave your integer input as ints, and convert to double only when needed, here cast to double when doing probability calculations
Don't over-complicate your code as you're doing, and use testable methods to help simplify as well. No need to use arrays for example. The constraints mentioned above likely do not need to be tested in your program but rather assumed to be true.
Use variable names that comply with Java naming standards, and that make sense.
For example:
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
// get number of trys
String line = scanner.nextLine();
int trys = Integer.parseInt(line.trim());
for (int i = 0; i < trys; i++) {
// for each try, calc probability
double probability = processTry(scanner);
System.out.println(probability);
}
scanner.close();
}
private static double processTry(Scanner scanner) {
String line;
// get first line
line = scanner.nextLine();
// use Scanner to get ints from line
Scanner lineScan = new Scanner(line);
//number of faces
int numberOfFaces = lineScan.nextInt();
int a = lineScan.nextInt();
int b = lineScan.nextInt();
lineScan.close();
// scanner to get face values
line = scanner.nextLine();
lineScan = new Scanner(line);
// count of how many faces match a and b values
int aMatch = 0;
int bMatch = 0;
for (int i = 0; i < numberOfFaces; i++) {
int face = lineScan.nextInt();
if (a == face) {
aMatch++;
}
if (b == face) {
bMatch++;
}
}
lineScan.close();
// only cast to double when need for calc
double probability = ((double) (aMatch * bMatch) / (numberOfFaces * numberOfFaces));
return probability;
}
}
Let's suppose there is n(A) is the number of occurrence of A on the dice and n(B) is the number of occurrence of B on the dice. In this, the probability that A will be thrown at a given time is
P(A) = n(A) / N
and the probability that B will be thrown at a given time is
P(B) = n(B) / N
The probability that A will be thrown first and B will be thrown second is
P(A) ^ P(B) = P(A) * P(B)
since the experiments are independent.
P(A) * P(B) = n(A) * n(B) / N^2
since this is precisely in your code, you have implemented a correct algorithm for the calculation, so the problem must consist in something else than the algorithm.
Usage of float
The usage of float might be causing slight differences between your result and the expected result. Change it to double.
Related
I want the user to be able to input the amount of numbers they specified BEFORE the code keeps running. Currently, the user is only able to input one number before the code continues. How do i keep the code from running until a certain amount of numbers are inputted?
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
int n;
Scanner sc = new Scanner(System.in);
System.out.print("\nEnter the amount of numbers you want the array to store: ");
// reads # of # user wants to enter
n = sc.nextInt();
// creates an array in the memory of length 10
int[] array = new int[10];
System.out.println("Enter "+n+" numbers ");
for (int i = 0; i < n; i++) {
// reading array elements from the user
array[i] = sc.nextInt();
double sum = 0;
double mode = 0;
double variance = 0;
double deviation = 0;
for (i = 0; i < 2; i++)
sum = sum + array[i];
//MEAN
mode = sum / 5;
sum = 0;
for (i = 0; i < 2; i++) {
sum = sum + Math.pow((array[i] - mode), 2);
}
//VARIANCE
variance = sum / 5;
//DEVIATION
deviation = Math.sqrt(variance);
//Standard
System.out.println("Standard Deviation is: " + deviation);
//mode
System.out.println("Mode is:" + mode);
//Variance
System.out.println("Variance is: " + variance);
}
}
}
I tried to let the user decide how many numbers should be in the array, then input that many numbers.
However, when i run the code, it doesn't give them enough time to type in the numbers.
I need a way to stop this from happening.
The first thing I discovered is that at no time are you using the variable "n" to create a constant value array, so it will always be an array of 10 elements.
One recommendation that I give you is that you do not use the "Scanner" class because it can give you problems if you ask the user for different types of data. Instead it uses BufferedReader because it is more direct. Here is an example of your exercise but fixed:
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Arrays;
public class Main {
private static Number getNumber(BufferedReader reader) throws IOException {
// Get input content
String line = reader.readLine();
return Double.parseDouble(line);
}
public static void main(String[] args) throws IOException {
// Auto closeable elements
try (InputStreamReader reader = new InputStreamReader(System.in);
BufferedReader buffered = new BufferedReader(reader)) {
// Print message
System.out.print("The amount of numbers you want: ");
// Program variables here
final int totalSize = getNumber(buffered).intValue();
int[] arrayStore = new int[totalSize];
// Iterate all elementos of the array
for (int i = 0; i < totalSize; ++i) {
// Another message
System.out.print("Insert one number: ");
// Ask for numbers
int nextNumber = getNumber(buffered).intValue();
arrayStore[i] = nextNumber;
}
// TODO: Your logic program here
System.out.println(Arrays.toString(arrayStore));
}
}
}
If you were able to notice, the method that asks for the numbers does not check if the content is really a number, for that change the behavior of the getNumber method to the following:
private static Number getNumber(BufferedReader reader) throws IOException {
Number result = null;
do {
try {
result = Double.parseDouble(reader.readLine());
} catch (NumberFormatException e) {
System.err.println("The inserted content is not a valid number");
}
} while (result == null);
return result;
}
I hope it helps you in some way
I’m a newbie at programming. I was ask to do a code where it prints a number in descending and in vertical position. Below is my code:
import java.util.Scanner;
class Main{
public static void main (String args []){
Scanner input = new Scanner (System.in);
int r=0,ascend=0;
int number=input.nextInt();
while(number>0) {
r= number%10;
number= number/10;
ascend= (ascend*10)+r;
}
System.out.println(ascend + "\n");
ascend++;
}
}
However, when I put an input of: 214
The output would be:
412
What can I do to turn the output like below?
4
1
2
You could try this.
It's basically the same as yours, with the print moved into the loop and printing each digit:
import java.util.Scanner;
class Main {
public static void main (String args []) {
Scanner input = new Scanner(System.in);
int r = 0;
int number = input.nextInt();
while(number > 0) {
r = number % 10;
number /= 10; // assignment operator shorthand for number = number / 10;
System.out.println(r);
}
}
}
You need to place your println within the loop. With this, you can remove the ascend variable. With println, you also get the new line character for free
Scanner input = new Scanner(System.in);
int r = 0;
int number = input.nextInt();
while (number > 0) {
r = number % 10;
number = number / 10;
System.out.println(r);
}
Just for fun, i wanted to see whether i could employ a code to display twin primes as practice for learning Constructors. I though i had used a good logic but for some reason i couldnt make it work.
This program is to print all twin primes(primes with 1 gap between them) till a given number as input by the user.
package X;
import java.io.*;
import java.util.*;
class TwinPrimeWithConstructor {
int limit;
public void Twin() {
limit = 0;
}
public static void input() {
Scanner input = new Scanner(System.in);
System.out.println("Enter Limit");
int limit = input.nextInt();
}
public void display() {
for (int k = 1; k <= (limit - 2); k++) {
int a = prime(k);
int b = prime(k + 2);
if (a == 1 && b == 1) {
System.out.println(k + "," + k + 2);
}
}
}
public int prime(int n) {
int c = 0;
int d = 0;
for (int i = 1; i <= n; i++) {
if (n % i == 0) {
c = c + 1;
}
}
if (c == 2) {
d = 1;
return d;
} else {
return d;
}
}
void main() {
TwinPrimeWithConstructor ob = new TwinPrimeWithConstructor();
ob.input();
ob.display();
}
}
This program manages to correctly detect primes and asks for input,but does not give any output. Can someone make it clear to me? I'm still learning java so any help would be appreciated.
Also since im new, if you find any bad habits in my code, please feel free to tell me so i can become a better programmer.
You are not getting any output because this.limit is always 0:
int limit = Input.nextInt();
You should assign the input to your instance field rather than to a new local variable. To do this, the input method must not be static:
public void input() {
Scanner input = new Scanner(System.in);
System.out.println("Enter Limit");
limit = input.nextInt();
}
I wrote this program to show the Newtonian method of finding the square root and then to run the math function to find that square root and print both of them out. The math part is working well but the loop I created isn't coming up with the right square root for the newtonian method. Any ideas? Thanks in advance.
package newton_sqrt;
import java.util.Scanner;
public class Newton_sqrt {
public static void main(String[] args) {
double guess, new_guess, last_guess, accuracy, n, x, absolutex;
Scanner keyboard = new Scanner(System.in);
System.out.println("Enter in N for Newton: ");
n = keyboard.nextDouble();
last_guess = n / 2;
do {
new_guess = ((n/last_guess) + last_guess)/2;
x = new_guess - last_guess;
if(x>=0)
absolutex=x;
else
absolutex=-x;
} while(absolutex < .000001);
System.out.println("Newton = " +new_guess);
double mth = Math.sqrt(n);
System.out.println("Math.sqrt = " +mth);
}
}
Invert the loop condition. You want to loop while absolutex is bigger than epsilon, not while it's smaller. You want to stop when it is small enough.
do {
} while(absolutex > .000001);
looks like math part need little tweaks, so does with loop condition. here try it, it works
package newton_sqrt;
import java.util.Scanner;
public class Newton_sqrt {
public static void main(String[] args) {
// TODO code application logic here
double guess, new_guess = 0, last_guess, accuracy, n, x, absolutex;
Scanner keyboard = new Scanner(System.in);
System.out.println("Enter in N for Newton: ");
n = keyboard.nextDouble();
last_guess = n / 2;
do {
new_guess = last_guess - (last_guess*last_guess-n) / (2*last_guess);
x = Math.abs(last_guess - new_guess);
if (x < .000001) {
break ;
} else {
last_guess = new_guess;
}
} while (n >= .00);
System.out.println("Newton = " + new_guess);
double mth = Math.sqrt(n);
System.out.println("Math.sqrt = " + mth);
}
}
I'm writing a short program to prompt the user for numeric inputs, which I will then test to see if they are negative and report back which ones pass this test. I'm looking for a method that avoids duplicating logic for each expected input.
Here's what I have so far:
import java.util.Scanner;
public class Negative
{
public static void main(String[] arg)
{
Scanner scan = new Scanner(System.in);
System.out.println("Insert three integers, USER.");
int x = scan.nextInt();
int y = scan.nextInt();
int z = scan.nextInt();
if (x < 0 || y < 0 || z < 0)
{
System.out.println("A number is negative.");
}
}
}
I know I can do each of these individually but I'd like to condense the code somehow.
You could always create a method that takes the variable name and value and then print it. Something like,
private static void display(String name, int val) {
if (val >= 0) {
System.out.printf("%s (%d) is NOT negative%n", name, val);
} else {
System.out.printf("%s (%d) is negative%n", name, val);
}
}
Then you can call display(),
public static void main(String[] arg) {
Scanner scan = new Scanner(System.in);
System.out.println("Insert three integers, USER.");
display("x", scan.nextInt());
display("y", scan.nextInt());
display("z", scan.nextInt());
}
Now it doesn't actually store x, y or z. If you need them later, then you really do need
public static void main(String[] arg) {
Scanner scan = new Scanner(System.in);
System.out.println("Insert three integers, USER.");
int x = scan.nextInt();
int y = scan.nextInt();
int z = scan.nextInt();
display("x", x);
display("y", y);
display("z", z);
// do something else with x,y or z
}
You can do it by simply applying loop until user inputs positive number :-
int x = scan.nextInt();
int y = scan.nextInt();
int z = scan.nextInt();
while(x<0||y<0||z<0)
{
x = scan.nextInt();
y = scan.nextInt();
z = scan.nextInt();
}
You could also use Google guava preconditions statements to make it cleaner.
For example the above code can be changed..
import com.google.common.base.Preconditions.*;
public class Negative
{
public static void main(String[] arg)
{
Scanner scan = new Scanner(System.in);
System.out.println("Insert three integers, USER.");
int x = scan.nextInt();
int y = scan.nextInt();
int z = scan.nextInt();
Preconditions.checkArgument(x < 0 || y < 0 || z < 0 ,"Negative number entered");
}
}
If the argument fails, an IllegalArgumentExceptionwould be thrown.
More documentation here
Hope this helps..