How to tackle this puzzle? [closed] - java

Closed. This question is off-topic. It is not currently accepting answers.
Want to improve this question? Update the question so it's on-topic for Stack Overflow.
Closed 10 years ago.
Improve this question
Disclaimer: This is not a homework problem. I stumbled upon this puzzle here and I also have the answer. However, I am not able to figure out an approach to arrive at the solution.
The puzzle is as given below:
The product of the ages of David's children is the square of the sum of their ages. David has less than eight children. None of his children have the same age. None of his children is more than 14 years old. All of his children is at least two years old. How many children does David have, and what are their ages?
The answer happens to be 2,4,6,12.
Please suggest a way to solve this problem programmatically.

In Python (Which is not what you asked, but you're more asking for an algorithm):
import operator
import itertools
possible_ages = range(2,15)
# If the list of ages passed to this function returns true, then this solves the puzzle.
def valid(ages):
product_of_ages = reduce(operator.mul, ages, 1)
square_of_sum_of_ages = reduce(operator.add, ages, 0) ** 2
return product_of_ages == square_of_sum_of_ages
for number_of_children in range(1, 9):
for ages in itertools.combinations(possible_ages, number_of_children):
if valid(ages):
print ages
And that prints, almost immediately:
(2, 4, 6, 12)

You don't specify that the ages are all integers, but I'm going to assume that's true. If so, there are only about 1e9 possible combinations of those ages among 8 children. Simply enumerate (for(age1=2; age1<15; age1++) { for(age2=2; age2<15; age2++) { ...) them all and test. Your computer should finish that task within a few minutes even in a script interpreter.
There are optimizations to be applied, because hard-coding "8" loops is clumsy, and because the age lists are order-independent (having children of "4 and 2" is the same thing as "2 and 4"), but frankly I don't think that's worth it here. Your time taken coding the extra steps will take more time than you'll save at runtime.

I solved it in java using a recursive approach.
First the program prints all the combinations, then gives the correct combination (that matches the specified criteria) at last.
This program instantly gives the output
(2, 4, 6, 12)
just as you have specified in your question.
public class Tackle {
static int[] ages = {2,3,4,5,6,7,8,9,10,11,12,13,14}; // Since the program uses a recursive function,
static StringBuffer sb = new StringBuffer(""); // the variables are declared as static
static int x=0,occurances=0;
static int sum,pdt=1,count=0;
static String[] instances = new String[100];
static void recurse(int a[], int k, int n) throws Exception
{
if(k==n) // This program obtains various combinations using binary technique
{
for(int i=0;i<n;i++)
if(a[i] == 1){
System.out.print(ages[i]+" "); // Displays all the combinations available
sum = sum + ages[i];
pdt = pdt * ages[i];
count++;
sb.append(String.valueOf(ages[i]+" "));
}
if(Math.pow(sum, 2) == pdt && count<8){ // Checking the criteria
instances[occurances++] = sb.toString();
}
sb = new StringBuffer("");
count = 0;
sum = 0;
pdt = 1;
System.out.println("");
}
else for(int i=0;i<=1;i++)
{
a[x++] = i;
recurse(a,k+1,n);
x--;
}
}
public static void main(String[] args) throws Exception {
int[] a = new int[10000];
recurse(a,0,ages.length);
if(occurances>0)
{
System.out.println("No of combinations matching: " + occurances);
for(int i=0;i<occurances;i++)
System.out.println("The combination of ages is [ " + instances[i] + "]");
}
else
System.out.println("No combination matches the criteria. ");
}
}
The output obtained was
[All possible combinations are listed here]
No of combinations matching: 1
The combination of ages is [ 2 4 6 12 ]

Related

Understanding Recursion Function [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 1 year ago.
Improve this question
Recently in class, there was a recursion function that returned an array as either being true or false (sorted or not). However, I had trouble understanding it. The function is:
int[] array = { 3, 5, 2, 57, 8, 20 };
int start=0;
boolean sorted = sorted( array, start, array.length );
System.out.print( "array: ");
for ( int i=0 ; i<array.length ; ++i ) System.out.print( array[i] + " " );
if (sorted) System.out.println(" is sorted" );
else System.out.println( "is not sorted" );
static boolean sorted(int array[], int i, int count ) {
if (count == 1 || count == 0) return true;
if (array[count - 1] < array[count - 2]) return false;
return sorted(array, i-1, --count);
}
What is happening in the method and how is the recursion working? What does the variable count do if there is already an integer i? Why must it be equal to 0(or null) and 1? Why are the variables different for when you initialize "sorted" in the main method and for the sorted method? I believe some of the additional questions I asked may be redundant or unnecessary if I knew how the whole method worked. I would really appreciate your help!
First of all, welcome to the forum! :) Indubitably, recursion is something that's really difficult to come to grips with, but if you have learned about stack - as a part of the memory - you can understand recursion more easily. This article might appear useful in investigating what exactly happens in these types of algorithms.
The code might not be written in Java, but the syntax itself will be fairly understandable. I suggest you skip the memoization part - since it is more advanced and you can learn it later -, but the factorial code and the image are really self-explanatory.
You could also practice and write these algorithms and I agree: debugging is excessively useful if you don't understand something.
Finally, let me add some practical pieces of advice in the future for coding in Java:
Auto-format your code (the hotkeys are different in every major IDE's, but they definitely exist)
Avoid C-style coding when declaring arrays:
instead of
int array[]
, Java devs tend to do it in the following way:
int[] array
(Fun fact about multidimensional arrays: int[][] array, int array[][] and int[] array[] (!) work too.)
Last, but not least, do not miss curly braces also if there is only one statement in that particular block of code.
These are only coding conventions, though that code is syntactically alright, as you might have already seen it.
Happy coding!
The sorted method could just be:
static boolean sorted(int array[], int count) {
if (count == 1 || count == 0) {
// If the array has no elements or if it just has a single element,
// then it means that the array is sorted.
return true;
}
if (array[count - 1] < array[count - 2]) {
// If an element is less than the previous element,
// then the array is not sorted.
return false;
}
// check rest of the array.
return sorted(array, count-1);
}
I would suggest you to debug through the whole code so that you could get a better picture of what is happening.

If else loop not adding valuing to variable using +=? [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
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.
Closed 2 years ago.
Improve this question
I have a 1D matrix with data and another with scores. I'm trying to loop across all of the elements in the data and find the element in the same position in the score matrix, and keep adding these values together during each loop. For some reason, my script keeps starting from sum = zero instead of retaining and adding to the sum from the previous loop. For the below example, I expect sum = 1 in the first loop, 3 after the second loop (since 1+2=3) and 6 after the third loop (3+3=6). Instead, sum just yields the last value retrieved from scores. What am I doing wrong here?
public static int calc_score( )
{
String [] dat = {"A", "B","C"};
int [][] scores = new int [1][3];
scores[0][0] = 1;
scores[0][1] = 2;
scores[0][2] = 3;
int sum = 0;
for (int i = 0; i < dat[0].length(); i++)
{
if (dat[i].equals("A")) {
sum = sum + scores[i][0];
// scores[i][0] returns the expected value of 1 in the first loop
}
else if (dat[i].equals("B")) {
sum = sum + scores[i][1];
}
else if (dat[i].equals("C")) {
sum = sum + scores[i][2];
}
}
System.out.println(sum);
return sum;
}
I tried modifying sum = sum + scores[i][1]; to sum+=scores[i][1] but that doesn't fix this. I have to be missing something simple.
Learn to debug. Add println statements, or use a debugger, and track, on paper if you prefer, what you think the program should do. Where the computer does something different from what you thought: Voila. You found a bug; there may be more.
If you can't figure out why something is happening, go back and re-check assumptions.
Had you done that here, for example, you might have eventually noticed: Huh, that for loop really is only running exactly once, that's bizarre. Eventually you'd check what dat[0].length() returns and then realized it returns, mysteriously, 1, and perhaps then you'd have one of those slap yourself on the forehead moments: dat[0] refers to the first entry in the dat array, so, the string "A". Then you ask that string about length, which dutifully returns 1.
I assume you wanted dat.length instead.
Note that scores[1][0] is 0 too, you have more than one problem here.

Doing a Monte Carlo Analysis of the Birthday Paradox using a HashSet

DISCLAIMER : I DO NOT WANT THE ANSWER TO THIS PROBLEM. I SIMPLY NEED SOME GUIDANCE.
I want to perform Monte Carlo analysis on the infamous Birthday Paradox (determining the probability that at least 2 people in a given group share the same birthday) using a HashSet.
Now when I run this, the collisionCount is WAY lower than I expected it to be.First, I was expecting the collisionCount for a group of 10 people to be 11446 (or a probability of 0.11446). Then by the time I got to 100 people, I was expecting the collisionCount to be 100,000 (with a probability of 1.0). But instead, for every 10 people, the collisionCount only counts by 1 (10 people: 1 collision, 20 people: 2 collisions, 30 people: 3 collisions, etc).
Here is the code I have wrote so far :
import java.util.HashSet;
import java.util.Random;
import java.util.Set;
public class BirthdayParadox
{
public static void main(String [] args)
{
Random rand = new Random();
int tests = 100000;
int collisionCount = 0;
for(int people = 10; people <= 100; people += 10)
{
Set<Integer> birthdays = new HashSet<>(365);
birthdays.add(rand.nextInt(365));
for(int runs = 0; runs < tests; runs++)
{
int randomBirthday = rand.nextInt(365);
if(birthdays.contains(randomBirthday))
{
collisionCount++;
break;
}
birthdays.add(randomBirthday);
}
float prob = (float)collisionCount / tests;
System.out.println("After " + tests + " tests there were " +
collisionCount + " occurrences of shared " +
" birthdays in a set of " + people + " people.");
System.out.println("Probability : " + prob);
}
}
}
I guess my question is : Am I not doing something right with either of my for-loops in order to get the collisionCount to count correctly?
I am new to learning Java and I am new to the Stack Overflow community and am still learning the ropes. Any help/ advice/ tips are greatly appreciated.
Your problem appears to be that you are missing one of your loops.
Notice that your runs loop is broken by the first collision. This means that your value will never be more than 1.
Also, you never use your people variable inside the inner loop except when outputting results.
What you need to do is run your simulation 100_000 times. The way to do this is to place logic within your runs loop that checks if people people will have a birthday collision and then iterate your collision count.
I think that the java solution is not the best, this probably it is the problem why you have a difference between the simulation and the mathematical values. What i understand for the problem is that you have to determine for a group of 10 people (in this case) how many of them share the same birthday. To do that you have to random an array of 10 with number from 0 to 365 (days of the year) and count how many of them are the same. You have to do that severals time (100000 in your case).
I think that you have to invert the FOR order. I mean..
for(int runs = 0; runs < tests; runs++)
{
//initialize an array of 10
for(int people = 0; people <= 10; people +=1)
{
//random birthdayDay
//array [people] = rand.nextInt(365);
}
//check if there is a collision
//If there is one you have to increase you success variable in 1
}
//calculate the probability
I try to help you, doing kind of pseudocode.
Hope that this help you a little bit.
Regards
Arturo.

Polish Matura Mistake in answers?

in Polish matura from IT in task 5.1 we have to count of increasing subsequence largest than 3 in file which 310 lines with int values, series is when all piervous values in smaller than next.
In Answers we have the count of increasing subsequence largest than 3 is 14, but i always gets 11, and i dont have idea why.
Some one can tell me what's wrong?
My code:
static int Series = 0;
static int Big = 0;
public static void main(String[] args){
Scanner In = new Scanner(System.in);
String Line = "Seria 1: ";
int Last = 0;
int i = 0;
while(In.hasNext()){
int Current = In.nextInt();
if(Last<Current){
Series++;
Line +=Current+" ";
}
else{
if(Series>=3){
Big++;
System.out.println(Line+"#");
Line="Seria "+(Big+1)+": ";
}
Series = 0;
}
Last = Current;
}
System.out.println(Big);
In.close();
}
There is a file with records: http://wklej.to/phpgW
Ok, as far as I know your program works correctly and returns what you expect. The problem might be the wording. "Amount of increasing subsequences >= 3" can actually refer to two distinct ways of approaching it:
First one is your way, the end of the sequence is just before the increasingness stops. You get sequences like {3,4,5} {9,12,45,23049,2123455}.
The second one is trickier - It doesn't matter if increasingness continues, if you have three numbers in an increasing sequence it counts. In that interpretation input 3,4,5,6,7 leads to {3,4,5} {4,5,6} {5,6,7}, and possibly even {3,4,5,6} {4,5,6,7} and {3,4,5,6,7}.
This is pure speculation, but it would fit quite nicely if they asked for the second interpretation (hopefully in non-ambiguous way) with sequence length = 3. Than your input would indeed return 14.

How to create statistics from output of Java code?

Summary: I need a function based on the output. The problem is
connecting Eclipse or a Java code with another software.
I'm studying Physics. I needed a code that works the following way:
first, it declares a random number n;
then it outputs a "winner" number (based on some rules; the code
itself is irrelevant now I think), 20 times (but should be more,
first I need something to record the values, though).
I have n and 20 other numbers which are each between 1 and n (including 1 and n). I want, after compiling the code once, to see the 20 values, how they are distributed (for example, are they around one particular number, or in a region, is there a pattern (this is based on the rules, of course)).
The problem is, I'm only familiar with basic Java (I used eclipse), and have no clue on how I should register for example 2000 instead of the 20 numbers (so for an n number the code should print 2000 or more numbers, which should appear on a function: domain of the function is 1, 2, ..., n, and range is 0, 1, ..., 2000, as it might happen that all 2000 numbers are the same). I thought of Excel, but how could I connect a Java code with it? Visual interpretation is not necessary, although it would make my work easier (I hope, at least).
The code:
import java.util.Random;
public class korbeadosjo {
public static void main(String Args[]){
Random rand = new Random();
int n = (rand.nextInt(300)+2);
System.out.println("n= " + n);
int narrayban = n-1;
int jatekmester = n/2;
int jatekmesterarrayban = jatekmester-1;
System.out.println("n/2: " + jatekmester);
for(int i=0; i<400; i++){
int hanyembernelvoltmar = 1;
int voltmar[] = new int[n];
voltmar[jatekmesterarrayban]=1;
int holvan=jatekmester;
int holvanarrayban = holvan-1;
fori: for(;;){
int jobbravagybalra = rand.nextInt(2);
switch(jobbravagybalra){
case 0: //balra
if(holvanarrayban ==0){
holvanarrayban = narrayban;
}else {
--holvanarrayban;
};
if(voltmar[holvanarrayban]==0){
voltmar[holvanarrayban] =1;
++hanyembernelvoltmar;
}
break;
case 1: //jobbra
if(holvanarrayban == narrayban){
holvanarrayban = 0;
} else {++holvanarrayban;};
if(voltmar[holvanarrayban]==0){
voltmar[holvanarrayban]=1;
++hanyembernelvoltmar;
}
break;
}if(hanyembernelvoltmar==n){
System.out.println(holvanarrayban+1);
break fori;
}}}}}
basic Java (I used eclipse)
Unrelated.
I could only find two prompts in your question:
How to create statistics from output of Java code?
You are likely not wanting to get the output alone. Use those numbers in your Java program to find what you want and output it.
How did you store 2000 values? An array, list, queue...? So also iterate on that data structure and generate the statistics you need.
I thought of Excel, but how could I connect a Java code with it?
There is this site.

Categories