The code is to run simulations to find out the probability of n people sharing the same birthday.
I compared randomly assigned birthdates to an array of dates. For any dates that has more than 1 equal value, I added one to the numerator.
However, the answer comes out wrong for the code. I am not sure why.
import java.util.Scanner;
public class birthday {
public static void main (String[] args) {
Scanner inp = new Scanner(System.in);
System.out.println("How many trials");
int n = inp.nextInt();
//variable declaration
double[] birthdate = new double[n];
int num = 0;
int numerator = 0;
double bday = 0;
int trials = 0;
//assign birthdays to n people
for (int i = 0; i < n; i++)
{
birthdate[i] = Math.floor(Math.random() * 365) + 1;
System.out.println(birthdate[i]);
}
for (int i = 1; i <= 365; i++)
{
for (int j = 0; j < n; j++)
{
bday = birthdate[j];
//compare birthdates to dates
if (bday == i)
{
num++;
if (num > 1)
{
numerator++;
}
}
}
num = 0;
}
double ans = (double) numerator / n;
System.out.println("The answer is " + ans);
}
}
For any dates that has more than 1 equal value, I added one to the numerator.
That's not what your code does. For any date with at least 2 persons having birthday at that date you add the number of those people minus 1 to the numerator.
If you want your code to work according to the above statement, you have to change the following code
for (int j = 0; j < n; j++)
{
bday = birthdate[j];
//compare birthdates to dates
if (bday == i)
{
num++;
if (num > 1)
{
numerator++;
}
}
}
num = 0;
to this code:
for (int j = 0; j < n; j++)
{
bday = birthdate[j];
//compare birthdates to dates
if (bday == i)
{
num++;
}
}
if (num > 1)
{
numerator++;
}
num = 0;
This way the code if (num > 1) numerator++ isn't repeated for every person (starting from the second one), but done just once per date.
Anyway, I doubt that either version of the code calculates you the "probability of n people sharing the same birthday". If that's what you want to approximate, you should repeat the whole experiment a lot of times, count, in how many of those cases n people were sharing their birthday, and divide it by the number of experiments:
import java.util.Scanner;
public class birthday {
public static void main(String[] args) {
Scanner inp = new Scanner(System.in);
System.out.println("How many trials?");
int numExperiments = inp.nextInt();
System.out.println("How many persons?");
int n = inp.nextInt();
// variable declaration
int dups = 0;
for (int k = 0; k < numExperiments; k++) {
boolean foundDup = false;
int[] birthdate = new int[n];
// assign birthdays to n people
for (int i = 0; i < n; i++) {
birthdate[i] = (int) (Math.random() * 365) + 1;
}
// check, if there is a duplicate
for (int i = 1; i <= 365; i++) {
int num = 0;
for (int j = 0; j < n; j++) {
// compare birthdates to dates
if (birthdate[j] == i) {
num++;
}
}
if (num > 1) {
foundDup = true;
}
num = 0;
}
// count cases with duplicates
if (foundDup) {
dups++;
}
}
double ans = (double) dups / numExperiments;
System.out.println("The answer is " + ans);
}
}
Related
I have a java code to read the length of an integer array, output the range, length of the gap, and any distinct elements inside. Additionally, it will output the numbers again with none repeated.
I would like to shorten the length of my main method.
My code produces the correct output, it is just very lengthy. Additionally, is there a way I can edit this main method to where it won't require a drastic change to my other methods? Thank you so much!
package ArrayPrograms;
import java.util.Scanner;
public class WIP{
static int LargestGap(int [] a, int n)
{
int diff = Math.abs(a[1] - a[0]);
for(int i = 1; i < a.length-1; i++)
if(Math.abs(a[i+1]-a[i]) > diff)
diff = Math.abs(a[i+1] - a[i]);
return diff;
}
int range(int a[], int n)
{
int max1 = Integer.MIN_VALUE;
for (int i = 0; i < n; i++)
{
for (int j = 0; j < n; j++)
{
if (Math.abs(a[i] - a[j]) > max1)
{
max1 = Math.abs(a[i] - a[j]);
}
}
}
return max1;
}
int numberOfDistinctElement(int a[], int n)
{
int num = 1;
for (int i = 1; i < n; i++)
{
int j = 0;
for (j = 0; j < i; j++)
if (a[i] == a[j])
break;
if (i == j)
num++;
}
return num;
}
int[] distinctElements(int a[], int n,int numberofDistinct)
{
int index = 0;
int[] distinct= new int[numberofDistinct];
for (int i = 0; i < n; i++)
{
int flag = 0;
for (int j = 0; j < i; j++){
if (a[i] == a[j]){
flag = 1;
break;
}
}
if (flag == 0){
distinct[index] = a[i];
index++;
}
}
return distinct;
}
***public static void main(String[] args)
{
Scanner in = new Scanner(System.in);
int num;
WIP obj=new WIP();
System.out.print("Enter the length of the array:");
num = in.nextInt();
int array[] = new int[num];
System.out.print("Enter the elements of the array: ");
for(int i = 0; i < num; i++)
{
array[i] = in.nextInt();
}
System.out.println("The largest gap in the array is "+WIP.LargestGap(array,num)+".");
System.out.println("The range of the array is "+obj.range(array,num)+".");
int numberofDistinct=obj.numberOfDistinctElement(array,num);
System.out.println("The number of distinct elements is "+numberofDistinct+".");
int[] distinctArray=obj.distinctElements(array,num,numberofDistinct);
System.out.print("The array of distinct elements is [");
for (int i = 0; i < distinctArray.length; i++)
if(i== distinctArray.length-1)
{
System.out.print(distinctArray[i]+"]");
}
else {
System.out.print( distinctArray[i]+ ",");
}
in.close();
}
}***
Sure thing. Here you go:
package arrayprograms;
import java.util.Scanner;
public class WIP{
static int LargestGap(int [] a, int n)
{
int diff = Math.abs(a[1] - a[0]);
for(int i = 1; i < a.length-1; i++)
if(Math.abs(a[i+1]-a[i]) > diff)
diff = Math.abs(a[i+1] - a[i]);
return diff;
}
int range(int a[], int n)
{
int max1 = Integer.MIN_VALUE;
for (int i = 0; i < n; i++)
{
for (int j = 0; j < n; j++)
{
if (Math.abs(a[i] - a[j]) > max1)
{
max1 = Math.abs(a[i] - a[j]);
}
}
}
return max1;
}
int numberOfDistinctElement(int a[], int n)
{
int num = 1;
for (int i = 1; i < n; i++)
{
int j = 0;
for (j = 0; j < i; j++)
if (a[i] == a[j])
break;
if (i == j)
num++;
}
return num;
}
int[] distinctElements(int a[], int n,int numberofDistinct)
{
int index = 0;
int[] distinct= new int[numberofDistinct];
for (int i = 0; i < n; i++)
{
int flag = 0;
for (int j = 0; j < i; j++){
if (a[i] == a[j]){
flag = 1;
break;
}
}
if (flag == 0){
distinct[index] = a[i];
index++;
}
}
return distinct;
}
static void showResults(int[] array, int num, WIP obj){
System.out.println("The largest gap in the array is "+WIP.LargestGap(array,num)+".");
System.out.println("The range of the array is "+obj.range(array,num)+".");
int numberofDistinct=obj.numberOfDistinctElement(array,num);
System.out.println("The number of distinct elements is "+numberofDistinct+".");
int[] distinctArray=obj.distinctElements(array,num,numberofDistinct);
System.out.print("The array of distinct elements is [");
for (int i = 0; i < distinctArray.length; i++)
if(i== distinctArray.length-1)
{
System.out.print(distinctArray[i]+"]");
}
else {
System.out.print( distinctArray[i]+ ",");
}
}
public static void main(String[] args)
{
Scanner in = new Scanner(System.in);
int num;
WIP obj=new WIP();
System.out.print("Enter the length of the array:");
num = in.nextInt();
int array[] = new int[num];
System.out.print("Enter the elements of the array: ");
for(int i = 0; i < num; i++)
{
array[i] = in.nextInt();
}
in.close();
showResults(array, num, obj );
}
}
There's not a whole lot you can do, like most of the comments say, but you can remove and edit some of the braces around that aren't necessary for the bodies. Here is a rough draft of it. The only things you could change besides that is to store all of the WIP.tests in variables in one code block and then print them all out in another code block; which would improve readability.
public static void main(String[] args)
{
Scanner in = new Scanner(System.in);
WIP obj = new WIP();
System.out.print("Enter the length of the array:");
int num = in.nextInt();
int array[] = new int[num] ;
System.out.print("Enter the elements of the array: ");
for(int i = 0; i < num; i++)
array[i] = in.nextInt();
System.out.println("The largest gap in the array is " + WIP.LargestGap(array,num) + ".");
System.out.println("The range of the array is " + obj.range(array,num) + ".");
int numberofDistinct = obj.numberOfDistinctElement( array, num );
System.out.println("The number of distinct elements is "+numberofDistinct+".");
int[] distinctArray = obj.distinctElements(array,num,numberofDistinct);
System.out.print("The array of distinct elements is [");
for (int i = 0; i < distinctArray.length; i++)
if(i== distinctArray.length-1)
System.out.print(distinctArray[i]+"]");
else
System.out.print( distinctArray[i]+ ",");
in.close();
}
import java.util.*;
public class Combination {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter a number : ");
String input = sc.next();
System.out.printf("You entered: %d\n", Integer.parseInt(input));
sc.close();
int[] arr = new int[100];
for (int i = 0; i < arr.length; i++) {
arr[i] = i + 1;
}
for (int i = 0; i <= 97; i++) {
int num_i = arr[i];
for (int j = i + 1; j <= 98; j++) {
int num_j = arr[j];
for (int k = j + 1; k <= 99; k++) {
int num_k = arr[k];
if (num_i + num_j + num_k == Integer.parseInt(input))
System.out.printf("(%d, %d, %d)", num_i, num_j, num_k);
}
}
}
}
}
When I get a number input, I want to make a code that represents this number as the sum of three numbers.
The code is complete, but there are several combinations. I want to print out only one combination. How can I edit it?
First, some important suggestions:
Do not parse input inside the nested loop as it will hit the performance. Do it once outside the nested loops.
Do not close Sacnner for System.in as it also closes System.in and there is no way to open it again without restarting JVM. It means that if it is being used in some other part of your application, your application will crash.
Always follow Java naming conventions e.g. you could name numJ instead of num_j.
Coming back to your problem, there are many ways to solve it and I have listed below just a couple of them:
Use break <<label>> to exit the nested loops:
import java.util.Scanner;
public class Combination {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter a number : ");
String input = sc.next();
System.out.printf("You entered: %d\n", Integer.parseInt(input));
int num = Integer.parseInt(input);
int[] arr = new int[100];
for (int i = 0; i < arr.length; i++) {
arr[i] = i + 1;
}
start: for (int i = 0; i <= 97; i++) {
int numI = arr[i];
for (int j = i + 1; j <= 98; j++) {
int numJ = arr[j];
for (int k = j + 1; k <= 99; k++) {
int numK = arr[k];
if (numI + numJ + numK == num) {
System.out.printf("(%d, %d, %d)", numI, numJ, numK);
break start;
}
}
}
}
}
}
A sample run:
Enter a number : 123
You entered: 123
(1, 22, 100)
Put the logic in a method and return:
import java.util.Scanner;
public class Combination {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter a number : ");
String input = sc.next();
System.out.printf("You entered: %d\n", Integer.parseInt(input));
int num = Integer.parseInt(input);
printFirstCombination(num);
}
static void printFirstCombination(int num) {
int[] arr = new int[100];
for (int i = 0; i < arr.length; i++) {
arr[i] = i + 1;
}
for (int i = 0; i <= 97; i++) {
int numI = arr[i];
for (int j = i + 1; j <= 98; j++) {
int numJ = arr[j];
for (int k = j + 1; k <= 99; k++) {
int numK = arr[k];
if (numI + numJ + numK == num) {
System.out.printf("(%d, %d, %d)", numI, numJ, numK);
return;
}
}
}
}
}
}
You can create a seperate function for that and after you find a combination, print it and return there and then to the main function. In case you didn't find a combination you return 1 which can be handled in the main function,
public class Combination {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter a number : ");
String input = sc.next();
System.out.printf("You entered: %d\n", Integer.parseInt(input));
int res = printCombination(input);
if(res == 1) {
// Do something
}
sc.close();
}
private static int printCombination(String input) {
int[] arr = new int[100];
for (int i = 0; i < arr.length; i++) {
arr[i] = i + 1;
}
for (int i = 0; i <= 97; i++) {
int num_i = arr[i];
for (int j = i + 1; j <= 98; j++) {
int num_j = arr[j];
for (int k = j + 1; k <= 99; k++) {
int num_k = arr[k];
if (num_i + num_j + num_k == Integer.parseInt(input)) {
System.out.printf("(%d, %d, %d)", num_i, num_j, num_k);
return 0;
}
}
}
}
return 1;
}
}
I want to get a number from user and calculate how many different triangles can be formed with the given length for example :
5 (2-2-1)
Answer: 1
12 (5,5,2)(3,4,5)(4,4,4)
Answer: 3
I've wrote some codes but I want a faster way to do that.
Here is my codes:
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int t = input.nextInt();
int value = 0;
for (int i = 1; i < t; i++) {
for (int j = i; j < t; j++) {
for (int h = j; h < t; h++) {
if (i+h+j == t & i+j > h & i+h > j & h+j > i) value++;
}
}
}
System.out.println(value);
}
You can do it in O(1):
int n = input.nextInt();
long value = Math.round(((long)n*n)/12d) - ((long)n/4)*(((long)n + 2)/4);
using Alcuin's Sequence.
You can make it O(n^2) easily.
for (int i = 1; i < t; i++) {
for (int j = i; j < t; j++) {
int h=t-i-j;
//check in O(1)
}
}
For my problem I had to write a method that would take user input and create an array of objects. However any number of objects can be created. So the array size is 100 but only 2 elements of the array are filled. Now when I use my getAverage method I get a null point exception after it goes past the stored objects.
public class Item{
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("Enter the number of objects to input in the array");
int numOfEntries = input.nextInt();
Item[] itemArray = new Item[100];
Item.input(itemArray, numOfEntries);
System.out.println(Item.getAverage(itemArray));
//Item.input(itemArray);
}
public static void input(Item[] arr) {
Scanner input = new Scanner(System.in);
double pricesAdded = 0;
double average = 0;
double numofEntries = 0;
for ( int i = 0; i < arr.length; i++)
{
System.out.println("Enter item");
String item = input.next();
System.out.println("price");
double price = input.nextDouble();
if (price == -1) break;
arr[i] = new Item(item, price);
numOfItems++;
}
for( int j = 0; j < numofEntries; j++) {
if(arr[j].getName().equals("peas") || arr[j].getName().equals("Peas")) {
for( int k = 0; k < numOfItems; k++) {
pricesAdded = pricesAdded + arr[k].getPrice();
}
average = pricesAdded / numofEntries;
break;
}
}
if(average == 0) System.out.println("No average output " + average);
else System.out.println("The average is " + average);
for ( int i = 0; i < numofEntries; i++)
System.out.println(arr[i].toString());
}
public static double getAverage(Item[] itemArr) {
double pricesAdded = 0;
double average = 0;
for( int i = 0; i < itemArr.length; i++) {
if(itemArr[i].getName().equals("peas") || itemArr[i].getName().equals("Peas")) {
for( int k = 0; k < itemArr.length; k++) {
if ( itemArr[k].getPrice() == 0.0) break;
pricesAdded = pricesAdded + itemArr[k].getPrice();
}
average = pricesAdded / itemArr.length;
break;
}
}
return average;
}
Just add a null check:
if (arr[j] != null) {
// your logic
}
A better approach is to use a data structure like ArrayList, since they can grow as you add elements.
I'm not sure why others did not notice, but this code has serious issues.
public static void input(Item[] arr) {
Scanner input = new Scanner(System.in);
double pricesAdded = 0;
double average = 0;
double numofEntries = 0;//initialized to 0 and never changes
for ( int i = 0; i < arr.length; i++)
{
System.out.println("Enter item");
String item = input.next();
System.out.println("price");
double price = input.nextDouble();
if (price == -1) break;
arr[i] = new Item(item, price);
numOfItems++;//no declaration found
}
for( int j = 0; j < numofEntries; j++) {
if(arr[j].getName().equals("peas") || arr[j].getName().equals("Peas")) {
for( int k = 0; k < numOfItems; k++) {
pricesAdded = pricesAdded + arr[k].getPrice();
}
average = pricesAdded / numofEntries;//price added divided by 0
break;
}
}
You can fix these and use a global variable to keep the count.
public class Item{
static int numOfEntries;//global variable
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("Enter the number of objects to input in the array");
numOfEntries = input.nextInt();//initialize the global variable
Item[] itemArray = new Item[100];
Item.input(itemArray, numOfEntries);
System.out.println(Item.getAverage(itemArray));
//Item.input(itemArray);
}
and when you loop, use
for( int j = 0; j < numOfEntries; j++)
and this will fix your problem because user specifically enters the number of items.
Simple, just check for null before using the value:
for( int j = 0; j < numofEntries; j++) {
if(arr[j] == null){
continue; //break? if you hit one null, can you gurantee everything after is null?
}
}
package test1;
import java.util.Scanner;
public class Question2 {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int traincars;
int maxweight;
int count = 0;
int total = 0;
maxweight = input.nextInt();
traincars = input.nextInt();
int[] trains = new int[traincars];
for(int i = 0; i < traincars; i++)
{
trains[i] = input.nextInt();
}
if (total < maxweight)
{
for(int i = 0; i < traincars; i++)
{
total = trains[i] + trains[i+1] + trains[i+2] + trains[i+3];
count++;
}
}else
{
count = count + 3;
}
System.out.println("count");
}
}
this is a really simple program but for some reason, the array for the traincars goes out of bounds..
Why is this happening?
The problem is here:
for(int i = 0; i < traincars; i++)
{
total = trains[i] + trains[i+1] + trains[i+2] + trains[i+3];
count++;
}
When i equals traincars-1 you will be accessing elements i+1, i+2. and i+3 which are out of bounds of your trains array.
If your logic is calling for calculating totals of 4 consecutive elements of the array then your for loop should stop earlier:
for(int i = 0; i < traincars - 3; i++) {...}
In the last iteration of
for(int i = 0; i < traincars; i++)
{
total = trains[i] + trains[i+1] + trains[i+2] + trains[i+3];
count++;
}
You try to access trains[i+1] and this is bigger than the length of your trains array.
To make this for loop matter you should just do the following:
for(int i = 0; i < traincars; i++)
{
total += trains[i]; //unless of course you need something else...
count++;
}