Trying to get triangle numbers - java

The question is "Write a program that duplicates the sample run shown at the bottom , which displays the sum of the first n integers for each value of n from 1 to 10. As the output suggests, these numbers can be arranged to form a triangle and are therefore called triangle numbers
1 = 1
1 + 2 = 3
1 + 2 + 3 = 6
1 + 2 + 3 + 4 = 10
1 + 2 + 3 + 4 + 5 = 15
1 + 2 + 3 + 4 + 5 + 6 = 21
1 + 2 + 3 + 4 + 5 + 6 + 7 = 28
1 + 2 + 3 + 4 + 5 + 6 + 7 + 8 = 36
1 + 2 + 3 + 4 + 5 + 6 + 7 + 8 + 9 = 45
1 + 2 + 3 + 4 + 5 + 6 + 7 + 8 + 9 + 10 = 55"
I am able to output 1 2 3 4 5... to 10, but I just can't figure out how to get it to look like the triangle above and make it add the next consecutive number. I'm assuming that I am missing something very obvious.
import java.util.Scanner;
public class prob3
{
public static void main(String[] args){
Scanner in = new Scanner(System.in);
for (int n = 1; n <= 10; n++) {
for (int i = n; i <= n; i++){
System.out.println(n);
}
}
}
}

Your problem is that you print whole lines just with those numbers.
You print:
1
2
3
But you need something like
1=1
1+2=3
Instead, you need to accumulate the content to be printed, like:
StringBuilder builder = new StringBuilder();
for (int i = n; i <= n; i++) {
builder.append(n);
builder.append("+");...
System.out.println(builder.toString() + "=" + sum);
}
The above is just meant to to get you going; as there are still some things missing that you will have to work with:
A) figuring how to use the StringBuilder to "remember" that part of the previous line that you can reuse!
B) computation of overall sum is missing (as it is in your code, too!)

Split the handling of each row into a helper method.
public static void main(String[] args) {
for (int i = 1; i <= 10; i++) {
printRow(i);
}
}
/**
* Print one row.
* 1 + 2 + 3 + ... + n = sum
* #param n the max for this row
*/
private static void printRow(int n) {
int sum = 0;
StringBuilder sb = new StringBuilder();
// 1 through n-1
for (int i = 1; i < n; i++) {
// TODO - update the sum
// TODO - update sb with the number and plus
}
// final number n
// TODO - update the sum
// TODO - update the sb with the final number, equals, and sum
// display
System.out.println(sb.toString());
}

Related

Get a collection of positive integers adding up to n

Consider the “sums to n problem:” given a positive integer n, list all the different ways to get a collection of positive integers adding up ton. Assume that we don’t care about order, so 1 + 2 and 2 + 1 are the same possibility.For n= 3, the possibilities are1 + 1 + 1, 1 + 2, 3
import java.util.Scanner;
public class SumsToN {
static void listNumber(int arr[], int n, int i)
{
int MAX_POINT = 3;
if (n == 0)
{
printArray(arr, i);
}
else if(n > 0)
{
for (int k = 1; k <= MAX_POINT; k++)
{
arr[i]= k;
listNumber(arr, n-k, i+1);
}
}
}
static void printArray(int arr[], int m)
{
for (int i = 0; i < m; i++)
System.out.print(arr[i] + " ");
System.out.println();
}
public static void main (String[] args)
{
System.out.print("enter n number: " );
Scanner input = new Scanner(System. in);
int n = input.nextInt();
int size = 100;
int[] arr = new int[size];
System.out.println("list of all the possibilities of "+ n + " are");
listNumber(arr, n, 0);
}
}
My work is slightly incorrect as when i enter n = 5, it does not include for example 1 4
and also it orders are wrong like 1+1+2, not 1+2+1---i.e., "order doesn't matter
Can someone help me with this please?
$ java SumsToN
enter n number: 5
list of all the possibilities of 5 are
1 1 1 1 1
1 1 1 2
1 1 2 1
1 1 3
1 2 1 1
1 2 2
1 3 1
2 1 1 1
2 1 2
2 2 1
2 3
3 1 1
3 2
$ java SumsToN
enter n number: 3
list of all the possibilities of 3 are
1 1 1
1 2
2 1
3

Get the consecutive numbers whose sum matches with given number

I was going through a simple program that takes a number and finds the number of occurrences of consecutive numbers that matches with given number.
For example:
if input is 15, then the consecutive numbers that sum upto 15 are:
1,2,3,4,5
4,5,6
7,8
So the answer is 3 as we have 3 possibilities here.
When I was looking for a solution I found out below answer:
static long process(long input) {
long count = 0;
for (long j = 2; j < input/ 2; j++) {
long temp = (j * (j + 1)) / 2;
if (temp > input) {
break;
}
if ((input- temp) % j == 0) {
count++;
}
}
return count;
}
I am not able to understand how this solves the requirement because this program is using some formula which I am not able to understand properly, below are my doubts:
The for loop starts from 2, what is the reason for this?
long temp = (j * (j + 1)) / 2; What does this logic indicates? How is this helpful to solving the problem?
if ((num - temp) % j == 0) Also what does this indicate?
Please help me in understanding this solution.
I will try to explain this as simple as possible.
If input is 15, then the consecutive numbers that sum upto 15 are:
{1,2,3,4,5} -> 5 numbers
{4,5,6} -> 3 numbers
{7,8} -> 2 numbers
At worst case, this must be less than the Sum of 1st n natural numbers = (n*(n+1) /2.
So for a number 15, there can never be a combination of 6 consecutive numbers summing up to 15 as the sum of 1st 6 numbers =21 which is greater than 15.
Calculate temp: This is (j*(j+1))/2.
Take an example. Let input = 15. Let j =2.
temp = 2*3/2 = 3; #Meaning 1+2 =3
For a 2-number pair, let the 2 terms be 'a+1' and 'a+2'.(Because we know that the numbers are consecutive.)
Now, according to the question, the sum must add up to the number.
This means 2a+3 =15;
And if (15-3) is divisible by 2, 'a' can be found. a=6 -> a+1=7 and a+2=8
Similarly, let a+1 ,a+2 and a+3
a + 1 + a + 2 + a + 3 = 15
3a + 6 = 15
(15-6) must be divisible by 3.
Finally, for 5 consecutive numbers a+1,a+2,a+3,a+4,a+5 , we have
5a + 15 = 15;
(15-15) must be divisible by 5.
So, the count will be changed for j =2,3 and 5 when the input is 15
If the loop were to start from 1, then we would be counting 1 number set too -> {15} which is not needed
To summarize:
1) The for loop starts from 2, what is the reason for this?
We are not worried about 1-number set here.
2) long temp = (j * (j + 1)) / 2; What does this logic indicates? How is this helpful to solving the problem?
This is because of the sum of 1st n natural numbers property as I have
explained the above by taking a+1 and a+2 as 2 consecutive
numbers.
3) if ((num - temp) % j == 0) Also what does this indicate?
This indicates the logic that the input subtracted from the sum of 1st
j natural numbers must be divisible by j.
We need to find all as and ns, that for given b the following is true:
a + (a + 1) + (a + 2) + ... (a + (n - 1)) = b
The left side is an arithmetic progression and can be written as:
(a + (n - 1) / 2) * n = b (*)
To find the limit value of n, we know, that a > 0, so:
(1 + (n - 1) / 2) * n = n(n + 1) / 2 <= b
n(n + 1) <= 2b
n^2 + n + 1/4 <= 2b + 1/4
(n + 1/2)^2 <= 2b + 1/4
n <= sqrt(2b + 1/4) - 1/2
Now we can rewrite (*) to get formula for a:
a = b / n - (n - 1) / 2
Example for b = 15 and n = 3:
15 / 3 - (3 - 1) / 2 = 4 => 4 + 5 + 6 = 15
And now the code:
double b = 15;
for (double n = 2; n <= Math.ceil(Math.sqrt(2 * b + .25) - .5); n++) {
double candidate = b / n - (n - 1) / 2;
if (candidate == (int) candidate) {
System.out.println("" + candidate + IntStream.range(1, (int) n).mapToObj(i -> " + " + (candidate + i)).reduce((s1, s2) -> s1 + s2).get() + " = " + b);
}
}
The result is:
7.0 + 8.0 = 15.0
4.0 + 5.0 + 6.0 = 15.0
1.0 + 2.0 + 3.0 + 4.0 + 5.0 = 15.0
We are looking for consecutive numbers that sum up to the given number.
It's quite obvious that there could be at most one series with a given length, so basically we are looking for those values witch could be the length of such a series.
variable 'j' is the tested length. It starts from 2 because the series must be at least 2 long.
variable 'temp' is the sum of a arithmetic progression from 1 to 'j'.
If there is a proper series then let X the first element. In this case 'input' = j*(X-1) + temp.
(So if temp> input then we finished)
At the last line it checks if there is an integer solution of the equation. If there is, then increase the counter, because there is a series with j element which is a solution.
Actually the solution is wrong, because it won't find solution if input = 3. (It will terminate immediately.) the cycle should be:
for(long j=2;;j++)
The other condition terminates the cycle faster anyway.
NB: loop is starting from 2 because=> (1*(1+1))/2 == 1, which doesn't make sense, i.e, it doesn't effect on the progress;
let, k = 21;
so loop will iterate upto (k/2) => 10 times;
temp = (j*(j+1))/2 => which is, 3 when j =2, 6 when j = 3, and so on (it calculates sum of N natural numbers)
temp > k => will break the loop because, we don't need to iterate the loop when we got 'sum' which is more than 'K'
((k-temp)%j) == 0 => it is basically true when the input subtracted from the sum of first j natural numbers are be divisible by j, if so then increment the count to get total numbers of such equation!
public static long process(long input) {
long count = 0, rest_of_sum;
for (long length = 2; length < input / 2; length++) {
long partial_sum = (length * (length + 1)) / 2;
if (partial_sum > input) {
break;
}
rest_of_sum = input - partial_sum
if (rest_of_sum % length == 0)
count++;
}
return count;
}
input - given input number here it is 15
length - consecutive numbers length this is at-least 2 at max input/2
partial_sum = sum of numbers from 1 to length (which is a*(a+1)/2 for 1 to a numbers) assume this is a partial sequence
rest_of_sum = indicates the balance left in input
if rest of sum is multiple of length meaning is that we can add (rest_of_sum/length) to our partial sequence
lets call (rest_of_sum/length) as k
this only means we can build a sequence here that sums up to our input number
starting with (k+1) , (k+2), ... (k+length)
this can validated now
(k+1) + (k+2) + ... (k+length)
we can reduce this as k+k+k+.. length times + (1+2+3..length)
can be reduced as => k* length + partial_sum
can be reduced as => input (since we verified this now)
So idea here is to increment count every-time we find a length which satisfies this case here
If you put this tweak in it may fix code. I have not extensively tested it. It's an odd one but it puts the code through an extra iteration to fix the early miscalculations. Even 1/20000 would work! Had this been done with floats that got rounded down and 1 added to them I think that would have worked too:
for (long j = 2; j < input+ (1/2); j++) {
In essence you need to only know one formula:
The sum of the numbers m..n (or m to n) (and where n>m in code)
This is ((n-m+1)*(n+m))/2
As I have commented already the code in the original question was bugged.
See here.
Trying feeding it 3. That has 1 occurrence of the consecutive numbers 1,2. It yields 0.
Or 5. That has 2,3 - should yield 1 too - gives 0.
Or 6. This has 1,2,3 - should yield 1 too - gives 0.
In your original code, temp or (j * (j + 1)) / 2 represented the sum of the numbers 1 to j.
1 2 3 4 5
5 4 3 2 1
=======
6 6 6 6 6 => (5 x 6) /2 => 30/2 => 15
As I have shown in the code below - use System.out.println(); to spew out debugging info.
If you want to perfect it make sure m and n's upper limits are half i, and i+1 respectively, rounding down if odd. e.g: (i=15 -> m=7 & n=8)
The code:
class Playground {
private static class CountRes {
String ranges;
long count;
CountRes(String ranges, long count) {
this.ranges = ranges;
this.count = count;
}
String getRanges() {
return this.ranges;
}
long getCount() {
return this.count;
}
}
static long sumMtoN(long m, long n) {
return ((n-m+1)* (n+m))/2;
}
static Playground.CountRes countConsecutiveSums(long i, boolean d) {
long count = 0;
StringBuilder res = new StringBuilder("[");
for (long m = 1; m< 10; m++) {
for (long n = m+1; n<=10; n++) {
long r = Playground.sumMtoN(m,n);
if (d) {
System.out.println(String.format("%d..%d %d",m,n, r));
}
if (i == r) {
count++;
StringBuilder s = new StringBuilder(String.format("[%d..%d], ",m,n));
res.append(s);
}
}
}
if (res.length() > 2) {
res = new StringBuilder(res.substring(0,res.length()-2));
}
res.append("]");
return new CountRes(res.toString(), count);
}
public static void main(String[ ] args) {
Playground.CountRes o = countConsecutiveSums(3, true);
for (long i=3; i<=15; i++) {
o = Playground.countConsecutiveSums(i,false);
System.out.println(String.format("i: %d Count: %d Instances: %s", i, o.getCount(), o.getRanges()));
}
}
}
You can try running it here
The output:
1..2 3
1..3 6
1..4 10
1..5 15
1..6 21
1..7 28
1..8 36
1..9 45
1..10 55
2..3 5
2..4 9
2..5 14
2..6 20
2..7 27
2..8 35
2..9 44
2..10 54
3..4 7
3..5 12
3..6 18
3..7 25
3..8 33
3..9 42
3..10 52
4..5 9
4..6 15
4..7 22
4..8 30
4..9 39
4..10 49
5..6 11
5..7 18
5..8 26
5..9 35
5..10 45
6..7 13
6..8 21
6..9 30
6..10 40
7..8 15
7..9 24
7..10 34
8..9 17
8..10 27
9..10 19
i: 3 Count: 1 Instances: [[1..2]]
i: 4 Count: 0 Instances: []
i: 5 Count: 1 Instances: [[2..3]]
i: 6 Count: 1 Instances: [[1..3]]
i: 7 Count: 1 Instances: [[3..4]]
i: 8 Count: 0 Instances: []
i: 9 Count: 2 Instances: [[2..4], [4..5]]
i: 10 Count: 1 Instances: [[1..4]]
i: 11 Count: 1 Instances: [[5..6]]
i: 12 Count: 1 Instances: [[3..5]]
i: 13 Count: 1 Instances: [[6..7]]
i: 14 Count: 1 Instances: [[2..5]]
i: 15 Count: 3 Instances: [[1..5], [4..6], [7..8]]

java print other side of pyramid nested loop

I'm currently stuck on creating the other side of my pyramid. I would like for my program to ask the user for a number between 5 and 15. Use that number to print out a square and a triangle. I have been able to do everything up until I get to the pyramid. I can create one side of the pyramid but I noticed i'm overlooking something when it comes to creating the other side. Any guidance on putting me in the right direction would be greatly appreciated.
import java.util.Scanner;
public class doLoop {
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner input = new Scanner(System.in);
int number;
final int minimum = 5;
final int maximum = 15;
do {
System.out.print("Enter a number between" + " " + minimum + " " + "and" + " " + maximum + ":" );
number = input.nextInt();
for(int i = 1; i <= number; i++) {
for(int j = 1; j <= number; j++) {
System.out.print(j + " ");
}
System.out.println();
}
for(int column = 1; column <= number; column++) {
for(int row = 1; row <= number ; row++) {
if(column >= row) {
System.out.print(row);
} else {
System.out.print(" ");
}
}
System.out.println(" ");
}
if (number <= minimum || number >= 15)
System.out.println("Sorry, invalid");
} while (number <= minimum || number >= maximum);
}
}
**Here is my current output:**
Enter a number between 5 and 15:5
1 2 3 4 5
1 2 3 4 5
1 2 3 4 5
1 2 3 4 5
1 2 3 4 5
1
12
123
1234
12345
Sorry, invalid
Enter a number between 5 and 15:
**This is what i'm working towards:**
Enter a number between 5 and 15: 2
Sorry, 2 is invalid. Please try again.
Enter a number between 5 and 15: 20
Sorry, 20 is invalid. Please try again.
Enter a number between 5 and 15: 10
1 2 3 4 5 6 7 8 9 10
1 2 3 4 5 6 7 8 9 10
1 2 3 4 5 6 7 8 9 10
1 2 3 4 5 6 7 8 9 10
1 2 3 4 5 6 7 8 9 10
1 2 3 4 5 6 7 8 9 10
1 2 3 4 5 6 7 8 9 10
1 2 3 4 5 6 7 8 9 10
1 2 3 4 5 6 7 8 9 10
1 2 3 4 5 6 7 8 9 10
1
2 1 2
3 2 1 2 3
4 3 2 1 2 3 4
5 4 3 2 1 2 3 4 5
6 5 4 3 2 1 2 3 4 5 6
7 6 5 4 3 2 1 2 3 4 5 6 7
8 7 6 5 4 3 2 1 2 3 4 5 6 7 8
9 8 7 6 5 4 3 2 1 2 3 4 5 6 7 8 9
10 9 8 7 6 5 4 3 2 1 2 3 4 5 6 7 8 9 10
You code has multiple errors!!!
your code will loop forever
you don't need a do loop
If I understand correrctly your problem is that you want the left side of the pyramid. You can achieve it by looping from negative user input to the values inserted by the user
Here's a snipped code, you need some tweaking based on your needs!!!
import java.util.Scanner;
public class doLoop {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int number;
final int minimum = 5;
final int maximum = 15;
System.out.print("Enter a number between" + " " +
minimum + " " + "and" + " " + maximum + ":");
number = input.nextInt();
if (number <= minimum || number >= 15) {
System.out.println("Sorry, invalid");
return;
}
for (int i = 1; i <= number; i++) {
for (int j = 1; j <= number; j++) {
System.out.print(j + " ");
}
System.out.println();
}
for (int row = 1; row < number; row++) {
for (int column = -(number - 1); column <= number; column++) {
int absValue = Math.abs(column);
// you need to use the absolute value
// to print the positive value and to perform column checks
if (absValue <= row)
System.out.print(absValue);
else {
// if the absolute value is greater the the current print 1 or 2 spaces
// based on the value of the column
//(2 spaces if lower then 10 otherwise 1 space only)
System.out.print(absValue < 10 ? " " : " ");
}
// If the absolute value of column is -1 or 1 you need to change
// the value to "1" to bypass the printing of 101
if (absValue == 1)
{
column = 1;
}
}
System.out.println();
}
}
}
I would rather edit what I have worked on as opposed to just copying what you did. Plus, I don't understand all of your code. I was able to complete the triangle I was looking for. But for some reason I can't get my loop to follow the conditions I set. It worked initially before I added the for loops for the shapes but now i'm stuck on how to get it to follow them again. Any advice?
import java.util.Scanner;
public class doLoop {
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner input = new Scanner(System.in);
int number;
final int minimum = 5;
final int maximum = 15;
do {
System.out.print("Enter a number between" + " " + minimum + " " + "and" + " " + maximum + ":" );
number = input.nextInt();
if (number <= minimum || number >= maximum) {
System.out.println("Sorry, invalid");
break;
}
for(int i = 1; i <= number; i++) {
for(int j = 1; j <= number; j++) {
System.out.print(j + " ");
}
System.out.println();
}
int columns = 1;
for (int i = number; i >= 1; i--)
{
for (int j = 1; j <= i*2; j++)
{
System.out.print(" ");
}
for (int j = i; j <= number; j++)
{
System.out.print(j + " ");
}
for (int j = number - 1; j >= i; j--)
{
System.out.printf(j + " ");
}
System.out.println();
columns++;
}
} while (number <= minimum || number >= maximum);
}
}

Largest Amount of Consecutive Odd Integers to Equal a Target

I am currently looking to find the largest amount of consecutive odd integers added together to equal a target number.
My current code to find 3 consecutive integers looks like
public class consecutiveOdd {
public static void main(String[] args){
int target = 160701;
boolean found = false;
for(int i = 1; i < target; i++){
if(i + (i+2) + (i+4) == target){
System.out.print(i + " + " + (i+2) + " + " + (i+4));
found = true;
}
}
if(!found){
System.out.println("Sorry none");
}
}
}
I am thinking there will need to be a while loop building iterations of (i+2) increments but am having trouble with developing a correct algorithm. Any help or tips will be much appreciated!
Best,
Otterman
Let's say that the answer is equal to k (k > 0). Then for some odd i we can write: i + (i + 2) + (i + 4) + ... + (i + 2k - 2) = target. You can see that this is a sum of arithmetic progression, therefore you can use a well known formula to compute it. Applying the formula we can get:
i = target/k - k + 1.
Basing on this formula I would suggest the following algorithm:
Iterate over the value of k.
If target/k - k + 1 is a positive odd integer, update the answer.
Simple implementation.
int answer = -1;
for (int k = 1;; k++) {
int i = target / k - k + 1;
if (i <= 0) {
break;
}
// Check if calculated i, can be the start of 'odd' sequence.
if (target % k == 0 && i % 2 == 1) {
answer = k;
}
}
The running time of this algorithm is O(sqrt(target)).
Looking at the pattern:
For 1 summand, i = target
For 2 summands, the equation is 2*i + 2 = target, so i = (target - 2) / 2
For 3 summands, the equation is 3*i + 6 = target, so i = (target - 6) / 3
For 4 summands, the equation is 4*i + 12 = target, so i = (target - 12) / 4
etc. Clearly i must be an odd integer in all cases.
You could work out the general expression for n summands, and simplify it to show you an algorithm, but you might be able to see an algorithm already...
Applying #rossum's suggestion:
For 1 summand, 2m + 1 = target
For 2 summands, 2m + 1 = (target - 2) / 2, so m = (target - 4) / 4
For 3 summands, 2m + 1 = (target - 6) / 3, so m = (target - 9) / 6
For 4 summands, 2m + 1 = (target - 12) / 4, so m = (target - 16) / 8
The sum of a sequence of n odd integers, can be calculated as the average value (midpoint m) multiplied by the number of values (n), so:
sum = 5 + 7 + 9 = m * n = 7 * 3 = 21
sum = 5 + 7 + 9 + 11 = m * n = 8 * 4 = 32
If n is odd then m will be odd, and if n is even then m will be even.
The first and last numbers of the sequence can be calculated as:
first = m - n + 1 = 8 - 4 + 1 = 5
last = m + n - 1 = 8 + 4 - 1 = 11
Other interesting formulas:
m = sum / n
m = (first + last) / 2
last = first + (n - 1) * 2 = first + 2 * n - 2
m = (first + first + 2 * n - 2) / 2 = first + n - 1
The longest sequence would have to start with the lowest possible first value, meaning 1, so we get:
sum = m * n = (first + n - 1) * n = n * n
Which means that the longest sequence of any given sum can at most be sqrt(sum) long.
So starting at sqrt(sum), and searching down until we find a valid n:
/**
* Returns length of sequence, or 0 if no sequence can be found
*/
private static int findLongestConsecutiveOddIntegers(int sum) {
for (int n = (int)Math.sqrt(sum); n > 1; n--) {
if (sum % n == 0) { // m must be an integer
int m = sum / n;
if ((n & 1) == (m & 1)) // If n is odd, mid must be odd. If n is even, m must be even.
return n;
}
}
return 0;
}
Result:
n = findLongestConsecutiveOddIntegers(160701) = 391
m = sum / n = 160701 / 391 = 411
first = m - n + 1 = 411 - 391 + 1 = 21
last = m + n - 1 = 411 + 391 - 1 = 801
Since sqrt(160701) = 400.875..., the result was found in 10 iterations (400 to 391, inclusive).
Conclusion:
Largest Amount of Consecutive Odd Integers to Equal 160701: 391
21 + 23 + 25 + ... + 799 + 801 = 160701

Generate all combinations of mathematical expressions that add to target (Java homework/interview)

I've tried to solve the problem below for a coding challenge but could not finish it in 1 hour. I have an idea on how the algorithm works but I'm not quite sure how to best implement it. I have my code and problem below.
The first 12 digits of pi are 314159265358.
We can make these digits into an expression evaluating to 27182 (first 5 digits of e)
as follows:
3141 * 5 / 9 * 26 / 5 * 3 - 5 * 8 = 27182
or
3 + 1 - 415 * 92 + 65358 = 27182
Notice that the order of the input digits is not changed. Operators (+,-,/, or *) are simply inserted to create the expression.
Write a function to take a list of numbers and a target, and return all the ways that those numbers can be formed into expressions evaluating to the target
For example:
f("314159265358", 27182) should print:
3 + 1 - 415 * 92 + 65358 = 27182
3 * 1 + 4 * 159 + 26535 + 8 = 27182
3 / 1 + 4 * 159 + 26535 + 8 = 27182
3 * 14 * 15 + 9 + 26535 + 8 = 27182
3141 * 5 / 9 * 26 / 5 * 3 - 5 * 8 = 27182
This problem is difficult since you can have any combination of numbers and you don't consider one number at a time. I wasn't sure how to do the combinations and recursion for that step. Notice that parentheses are not provided in the solution, however order of operations is preserved.
My goal is to start off with say
{"3"}
then
{"31", "3+1", "3-1", "3*1" "3/1"}
then
{"314", "31+4", "3+1+4", "3-1-4", "31/4", "31*4", "31-4"} etc.
then look at the every value in the list each time and see if it is target value. If it is, add that string to result list.
Here is my code
public static List<String> combinations(String nums, int target)
{
List<String> tempResultList = new ArrayList<String>();
List<String> realResultList = new ArrayList<String>();
String originalNum = Character.toString(nums.charAt(0));
for (int i = 0; i < nums.length(); i++)
{
if (i > 0)
{
originalNum += nums.charAt(i); //start off with a new number to decompose
}
tempResultList.add(originalNum);
char[] originalNumCharArray = originalNum.toCharArray();
for (int j = 0; j < originalNumCharArray.length; j++)
{
//go through every character to find the combinations?
// maybe recursion here instead of iterative would be easier...
}
for (String s : tempResultList)
{
//try to evaluate
int temp = 0;
if (s.contains("*") || s.contains("/") || s.contains("+") || s.contains("-"))
{
//evaluate expression
} else {
//just a number
}
if (temp == target)
{
realResultList.add(s);
}
}
tempResultList.clear();
}
return realResultList;
}
Could someone help with this problem? Looking for an answer with coding in it, since I need help with the generation of possibilities
I don't think it's necessary to build a tree, you should be able to calculate as you go -- you just need to delay additions and subtractions slightly in order to be able take the precedence into account correctly:
static void check(double sum, double previous, String digits, double target, String expr) {
if (digits.length() == 0) {
if (sum + previous == target) {
System.out.println(expr + " = " + target);
}
} else {
for (int i = 1; i <= digits.length(); i++) {
double current = Double.parseDouble(digits.substring(0, i));
String remaining = digits.substring(i);
check(sum + previous, current, remaining, target, expr + " + " + current);
check(sum, previous * current, remaining, target, expr + " * " + current);
check(sum, previous / current, remaining, target, expr + " / " + current);
check(sum + previous, -current, remaining, target, expr + " - " + current);
}
}
}
static void f(String digits, double target) {
for (int i = 1; i <= digits.length(); i++) {
String current = digits.substring(0, i);
check(0, Double.parseDouble(current), digits.substring(i), target, current);
}
}
First, you need a method where you can input the expression
3141 * 5 / 9 * 26 / 5 * 3 - 5 * 8
and get the answer:
27182
Next, you need to create a tree structure. Your first and second levels are complete.
3
31, 3 + 1, 3 - 1, 3 * 1, 3 / 1
Your third level lacks a few expressions.
31 -> 314, 31 + 4, 31 - 4, 31 * 4, 31 / 4
3 + 1 -> 3 + 14, 3 + 1 + 4, 3 + 1 - 4, 3 + 1 * 4, 3 + 1 / 4
3 - 1 -> 3 - 14, 3 - 1 + 4, 3 - 1 - 4, 3 - 1 * 4, 3 - 1 / 4
3 * 1 -> 3 * 14, 3 * 1 + 4, 3 * 1 - 4, 3 * 1 * 4, 3 * 1 / 4
3 / 1 -> 3 / 14, 3 / 1 + 4, 3 / 1 - 4, 3 / 1 * 4, 3 / 1 / 4
You can stop adding leaves to a branch of the tree when a division yields a non integer.
As you can see, the number of leaves at each level of your tree is going to increase at a rapid rate.
For each leaf, you have to append the next value, the next value added, subtracted, multiplied, and divided. As a final example, here are 5 of the fourth level leaves:
3 * 1 + 4 -> 3 * 1 + 41, 3 * 1 + 4 + 1, 3 * 1 + 4 - 1, 3 * 1 + 4 * 1,
3 * 1 + 4 / 1
Your code has to generate 5 expression leaves for each leaf until you've used all of the input digits.
When you've used all of the input digits, check each leaf equation to see if it equals the value.
My Javascript implementation:
Will improve the code using web worker later on
// was not allowed to use eval , so this is my replacement for the eval function.
function evaluate(expr) {
return new Function('return '+expr)();
}
function calc(expr,input,target) {
if (input.length==1) {
// I'm not allowed to use eval, so I will use my function evaluate
//if (eval(expr+input)==target) console.log(expr+input+"="+target);
if (evaluate(expr+input)==target) document.body.innerHTML+=expr+input+"="+target+"<br>";
}
else {
for(var i=1;i<=input.length;i++) {
var left=input.substring(0,i);
var right=input.substring(i);
['+','-','*','/'].forEach(function(oper) {
calc(expr+left+oper,right,target);
},this);
}
}
};
function f(input,total) {
calc("",input,total);
}

Categories