This question already has answers here:
Division of integers in Java [duplicate]
(7 answers)
Closed 2 years ago.
I've been trying to understand java operator precedence but I can't wrap my head around this equation someone has given to me. By adding parentheses myself I get (((78 / 10) * 10) + 10) - 78 but this shouldn't equate to 2. Can someone explain this to me? Thanks
78 / 10 = 7
7 * 10 = 70
70 + 10 = 80
80 - 78 = 2
remember an int /int will be an int
a float / int will be a float so you could do the following:
(float)78 / 10 * 10 + 10 - 78 or 78.0 / 10 * 10 + 10 - 78
It's because in integer math 78 / 10 is 7, not 7.8
Then:
7 * 10 = 70
+ 10 = 80
- 78 = 2
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);
}
I have a problem with multiplying numbers.
From my input I get:
number of digits of the number
how many numbers i have to multiply
Example: if I get from the input 3,2 it means I need to multiply all two digits numbers three times
For now I got some code which works only when I get two numbers with two digits.
How can I implement a method which multiplies as many numbers as user need? I made only this kind of method which prints number of digits got from the input. I can handle method which can multiply them as many times as variable multiplier says...
public static void test(int digits, int multiplier) {
int number = 0;
int result = 0;
ArrayList<String> numbers = new ArrayList<String>();
number = (int) Math.pow(10, digits);
for (int i = (int) (Math.pow(10, digits - 1)); i < number; i++) {
System.out.println(i);
for (int j = (int) (Math.pow(10, digits - 1)); j < number; j++) {
result = j * i;
}
}
System.out.println(number);
}
Sample Input And Output
If number of digits = 2, number of times = 2
We need to multiply all 2 digit numbers 10, 11, 12 .... 99 two times.
10 * 10
10 * 11
.
.
10 * 99
.
.
.
99 * 98
99 * 98
In the same way, if the no of digits is 2, and the no of times is 3
10 * 10 * 10
10 * 10 * 11
.
.
10 * 99 * 99
.
.
.
99 * 99 * 98
99 * 99 * 99
I would not use recursion, but use a for loop in combination with the Java8 streaming API.
The code example:
import java.util.stream.IntStream;
public class Multiplier {
private final int digits;
public Multiplier(int digits) {
this.digits = digits;
}
/**
* #param multiplificationSteps
* #return a stream, containing all numbers of the given digits, each multiplied several times with each other
*
* digits=1 with multiplificationSteps=1 => output [1;9]
* digits=2 with multiplificationSteps=1 => output [10;99]
* digits=1 with multiplificationSteps=2 => output [1;9] & [2;19] & ... & [9;81]
*/
public IntStream createFullStream(int multiplificationSteps) {
IntStream intStream = makeIntStream();
for (int i = 1; i < multiplificationSteps; i++)
intStream = intStream.flatMap(this::multiplyStream);
return intStream;
}
/**
* #param input a multiplier
* #return the stream, having each number multiplied by the multiplier
*
* input [1;9] and 1 => output [1;9]
* input [1;9] and 2 => output [2;18]
* input [10;99] and 3 => output [30;297]
*/
private IntStream multiplyStream(int input) {
return makeIntStream().map(k -> input * k);
}
/**
* #return a stream of all numbers with the given number of digits
*
* input 1 => output [1;9]
* input 2 => output [10;99]
* input 3 => output [100;999]
*/
private IntStream makeIntStream() {
int startNumber = (int) Math.pow(10, digits - 1);
int endNumber = (int) Math.pow(10, digits);
return IntStream.range(startNumber, endNumber);
}
public static void main(String[] args) {
new Multiplier(1).createFullStream(2).forEach(System.out::println);
}
}
sample input and outputs
For the input 1,1 it outputs:
1
2
3
4
5
6
7
8
9
For 1,2 it outputs:
1
2
3
4
5
6
7
8
9
2
4
6
8
10
12
14
16
18
3
6
9
12
15
18
21
24
27
4
8
12
16
20
24
28
32
36
5
10
15
20
25
30
35
40
45
6
12
18
24
30
36
42
48
54
7
14
21
28
35
42
49
56
63
8
16
24
32
40
48
56
64
72
9
18
27
36
45
54
63
72
81
it also will work without Java8
import java.util.*;
public class PlainOldMultiplier {
private final int digits;
public PlainOldMultiplier(int digits) {
this.digits = digits;
}
public void printAllMultipliedNumbers(int multiplicationSteps) {
// define the result
Collection<Integer> numbers = new ArrayList<>();
numbers.add(1);// multiply by 1 in first iteration
// foreach multiplicationStep once multiply all existing stuff with [start;end[
for (int multiplicationStepCount = 0; multiplicationStepCount < multiplicationSteps; multiplicationStepCount++) {
numbers = multiplyEverything(numbers);
}
// output numbers to console
for (Integer number : numbers) {
System.out.println(number);
}
}
private Collection<Integer> multiplyEverything(Collection<Integer> numbersOfPreviousIteration) {
Collection<Integer> result = new ArrayList<>();
// define start and end by taking account "digits"
int start = (int) Math.pow(10, digits-1);
int end = (int) Math.pow(10, digits);
// foreach number within [start;end[ multiply existing stuff
for (int number = start; number < end; number++) {
for (Integer numberOfPreviousIteration : numbersOfPreviousIteration) {
result.add(numberOfPreviousIteration * number);
}
}
return result;
}
public static void main(String[] args) {
new PlainOldMultiplier(1).printAllMultipliedNumbers(1); // outputs [1;9]
new PlainOldMultiplier(2).printAllMultipliedNumbers(1); // outputs [10;99]
new PlainOldMultiplier(1).printAllMultipliedNumbers(2); // outputs [1;9] & [2;18] & ... & [9;81]
}
}
I am trying to write a program that when given unfinished equations will output the lowest digit that will work or -1 if none will work. I have all my input set up but at this stage I am not sure how to continue.
Example inputs are: 1+1=?, 123*45?=5?088, -5?*-1=5, 19--45=5?, ??*??=302?
Any tips on how to tackle this would be appreciated.
import java.util.Scanner;
import java.util.regex.*;
public class Runes {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int caseNo = sc.nextInt();
for (int c = 0; c < caseNo; c++) {
String input = sc.next();
String re1="([-]?[0-9?]+)"; // -int1 or int1
String re2="([+\\-*])"; //+ or - or *
String re3="([-]?[0-9?]+)"; // -int2 or int2
String re4="(=)"; // Equals
String re5="([-]?[0-9?]+)"; // -int3 or int3
Pattern pattern = Pattern.compile(re1+re2+re3+re4+re5,Pattern.CASE_INSENSITIVE | Pattern.DOTALL);
Matcher matcher = pattern.matcher(input);
if (matcher.find()) {
String int1 = matcher.group(1);
String op1 = matcher.group(2);
String int2 = matcher.group(3);
String op2 = matcher.group(4);
String int3 = matcher.group(5);
System.out.println(int1 + " " + op1 + " " + int2 + " " + op2 + " " + int3);
}
}
}
}
Here's one way to create your Java application.
Create an Integer index array with a value for each question mark. In other words, if there are 5 question marks, your Integer index array has 5 elements.
Loop through the Integer index array. In other words, for 5 question marks, the values ought to be (see layout below).
Looping through the Integer index array, substitute the index values for the question marks.
Check to see if the string is a valid equation. If so, save it in a List.
When the looping is finished, print the List values.
Here's the layout for point 2.
0, 0, 0, 0, 0
1, 0, 0, 0, 0
...
9, 0, 0, 0, 0
0, 1, 0, 0, 0
...
9, 9, 9, 9, 9
I used your input examples to create this output. I added spaces to the equations to make them easier to read. I manually formatted this output to fit on the screen
1 + 1 = ? --> 1 + 1 = 2
123 * 45? = 5?088 --> 123 * 456 = 56088
-5? * -1 = 5 --> No equation exists
19 - -45 = 5? --> No equation exists
?? * ?? = 302? --> 57 * 53 = 3021 53 * 57 = 3021 72 * 42 = 3024
42 * 72 = 3024 48 * 63 = 3024 56 * 54 = 3024
36 * 84 = 3024 84 * 36 = 3024 54 * 56 = 3024
63 * 48 = 3024 55 * 55 = 3025 89 * 34 = 3026
34 * 89 = 3026
I need to solve this recurrence function: f(n) = 5*f(n-1) - 2*f(n-2), with f(0)=1 and f(1)=2. I wrote the below code, but it is not giving the correct answer -- it outputs 164, for example, when n = 4, although the correct answer is 26 (assuming I did my math correctly).
public static int recurFunction(int n) {
if(n == 0) {
return 1;
} else if(n == 1) {
return 2;
} else {
n = ((5 * recurFunction(n - 1)) - (2 * recurFunction(n - 2)));
return n;
}
}
Your math is wrong :)
f(n) = 5*f(n-1) - 2*f(n-2)
f(0) = 1
f(1) = 2
f(2) = 5 * f(1) - 2 * f(0) = 5 * 2 - 2 * 1 = 10 - 2 = 8
f(3) = 5 * f(2) - 2 * f(1) = 5 * 8 - 2 * 2 = 40 - 4 = 36
f(4) = 5 * f(3) - 2 * f(2) = 5 * 36 - 2 * 8 = 180 - 16 = 164
It looks like your Java code is correct, but your own math is incorrect.
f(2) = 5f(1) - 2f(0) = 5 * 2 - 2 * 1 = 10 - 2 = 8
f(3) = 5f(2) - 2f(1) = 5 * 8 - 2 * 2 = 40 - 4 = 36
f(4) = 5f(3) - 2f(2) = 5 * 36 - 2 * 8 = 180 - 16 = 164