Binary Search won't ever finish, I have to terminate it myself - java

public static boolean binarySearch(int[] data, int value){
int start = 0;
int end = data.length-1;
int middle = (start + end) / 2;
while(end >= start){
if(data[middle] == value){
System.out.println("binarySearch found value " + value + " at position " + data[middle]);
return true;
}
if(data[middle] < value){
start = middle + 1;
}
if(data[middle] > value){
end = middle + 1;
}
}
return false;
}
I have this code for binary search, and to me it looks like everything is in check. But when i pass an array and a variable I'm looking for through it it doesn't give me anything in return and I just have to terminate it. Any thoughts?

if(data[middle] == value)
this part checks if the middle of the array equals to data all the time. If you don't modify the variable middle, no matter what you do, it will always check if the middle value is equal to data.
Since you don't modify start and end as well,
while(end >= start)
this part also prevents you to finish the loop.
This is what I tried:
int data[] = {1, 3, 4, 5, 7, 8, 12};
int value = 7;
binarySearch(data, value);
And this is the output I get when I add
System.out.println("Start: " + start +
" Middle: " + middle + " End: " + end);
at the beginning of while loop:
Start: 4 Middle: 3 End: 6
Start: 4 Middle: 3 End: 6
Start: 4 Middle: 3 End: 6
Start: 4 Middle: 3 End: 6
Start: 4 Middle: 3 End: 6
Start: 4 Middle: 3 End: 6
Start: 4 Middle: 3 End: 6
...
to infinity.

Related

Addition in field with finite int elements?

I need to write a function (in Java) which has the following input:
int amountFieldElements
int summandOne
int summandTwo
amountFieldElement describes the amount of int numbers in a range starting from 1 (e.g. 1, 2, 3, 4 or just 1). summandOne is a int from this range, summandTwo can be any non-negative int.
The function has to add summandTwo to summandOne. If the result is bigger then amountFieldElement, it has to start over from 1.
I tried to simply use modulo: (summandOne + summandTwo) % amountFieldElements
But this is often wrong, e.g. (3 + 1) % 4 = 0 but I'd need it to be 4.
Example: If amountFieldElements = 4:
2 + 2 = 4 would stay as 4
3 + 2 = 5 would become 1
4 + 2 = 6 would become 2 etc
or for amountFieldElements = 1
1 + 0 = 1 would stay as 1
1 + 1 = 2 would also be 1
-> any result would be 1 here
something like this will work:
int result = (summandOne + summandTwo) % amountFieldElements;
if (result == 0) result = amountFieldElements;
another method, shorter but harder to understand is:
int result = (summandOne + summandTwo - 1) % amountFieldElements + 1;

Understanding Return f(n-1) + 5.

I am learning recursion need a better explanation of the following code. I have most of it down, but not I am sort of confused on the last part of the function where it says return f(n-1) + 5. I got 32 for f(7) which is correct, and that prints out at the very last, but I am still a little fuzzy and was wondering if anyone would give me a better explanation.
The output.
I know that once n = 1 by f(n-1) n being 7 at first, then (7-1) = 6 and so on until it gets to 1, which returns a value of 2, but this where I get sort of lost. What about the + 5? 2 + 5 = 7, 7 + 5 = 12,... 27 + 5 = 32. How does this tie to the f(n-1) + 5
public class scratch {
public static void main(String[] args) {
System.out.println(f(7));
}
static int f(int n) {
System.out.println("f(" + n + ")");
if (n <= 1)
return 2;
else
return f(n - 1) + 5;
}
}
What is the problem? When your n becomes 1 it returns 2 to n = 2 and then this n = 2 returns 2 + 5 to n = 3 and so on.
For Example, Consider f(7):
n = 7, f(6) + 5
n = 6, f(5) + 5
n = 5, f(4) + 5
n = 4, f(3) + 5
n = 3, f(2) + 5
n = 2, f(1) + 5
n = 1, 2
As you see, f(1) will return 2 to f(2) which will return 2 + 5 to f(3) and so on.
If a program says int x = f(1);, then it calls the method f. Since the argument is 1, this just returns 2.
If a program says int x = f(2);, it calls the method f. The argument is 2, so it executes this line:
return f(n - 1) + 5;
which calls the method f again, with argument 1. As I noted in the first paragraph, when you call f with argument 1, it returns 2, so the above evaluates to
return 2 + 5;
which is 7.
If a program says int x = f(3);, it calls the method f. The argument is 3, so it executes this line:
return f(n - 1) + 5;
which calls the method f again, with argument 2. As I noted earlier, when you call f with argument 1, it returns 7, so the above evaluates to
return 7 + 5;
which is 12. And so on.
I think you basically do understand what's going on; hopefully, breaking it down like this will help eliminate whatever doubts you still have.

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);
}

How to find numbers that are dividable with 2, 3 or 5 in max 1 second

I need your help guys with this specific question.
How many numbers from an interval a <= b [1, 10^18] are dividable by 2, 3 or 5?
Result must be run in max 1 sec!
A standard program would use a for loop seen bellow.
a = 1;
b = 1000000000
results = 0;
for (int i = a; i <= b; i++){
if (i % 2 == 0 || i % 3 == 0, i % 5 == 0){
results++;
}
}
System.out.println(results);
But if I enter high numbers, my program need a lot of time to give me the results.
Example 1:
a = 11, b = 30, result = 14
Example 2:
a = 123456789012345678, b = 876543210987654321
, result = 552263376115226339
I came up with something like that
public static void main(String[] args) {
long a = 123456789012345678L, b = 876543210987654321L;
long start = System.currentTimeMillis();
long score = getCount(b) - getCount(a - 1);
System.out.println("Time: " + ((System.currentTimeMillis() - start)));
System.out.println("Divisible by 2 or 3 or 5: " + score);
}
public static long getCount(long end) {
return (end / 2) + (end / 3) + (end / 5) - ((end / 6) + (end / 10) + (end / 15)) + (end / 30);
}
The solution:
It counts how many numbers are divisible by 2 or 3 or 5 separately and sums that.
Now we need to discard numbers that where counted twice: for 2 and 3 it will be every 6th number, for 2 and 5 every 10th number, for 3 and 5 every 15th number
At the end we need to include numbers that are divisible by 2 and 3 and 5 that where discarded in step 2 so we add every 30th number.

Returns from Recursive methods

I am trying to practice understanding recursion but the following program has me stumped. How is the answer being returned as 14? Can someone show me how this is calculating? I tried to put in afew print statments to help me identify what is going on but I do not see how spot is decremented after it goes up to 4. I have the program and output to console below, please help.
from console:
The spot 1 is 0
The spot 1 is 1
The spot 1 is 2
The spot 1 is 3
The spot 1 is 4
when spot = length. the spot is 4
The value is 4
spot after return 3
the spot 2 is 3
The value is 8
spot after return 2
the spot 2 is 2
The value is 11
spot after return 1
the spot 2 is 1
The value is 13
spot after return 0
the spot 2 is 0
The answer is 14
Code:
public class Recurs1 {
public static void main (String [] arg) {
Recurs1 r = new Recurs1();
r.compute();
}
public void compute() {
int [] stuff = {1, 2, 3, 4};
int answer = go(stuff, 0);
System.out.println("The answer is " + answer);
}
private int go(int[] numbers, int spot) {
System.out.println("The spot 1 is " + spot);
//System.out.println("0 is " + numbers[0] + " 1 is " + numbers[1] + " 2 is " + numbers[2] + " 1 is " + numbers[3]);
if (numbers.length == spot) {
System.out.println("when spot = length. the spot is " + spot); return spot;
}
int value = go(numbers, spot + 1 );
System.out.println(" The value is " + value);
System.out.println("spot after return " + spot);
System.out.println(" the spot 2 is " + spot);
return value + numbers[spot];
}
}
Try returning 0 instead of spot when you've reached the end. You're tacking 4 (the current value of spot) onto the end.
If your goal is to write a method which is summing the array, then the problem is that on the line of go() where you have if(numbers.length == spot) you are returning spot, which is 4, and it is adding that to the total value (because the method that called go(numbers, 4) is setting value to that and adding it.) Instead, you should be returning 0 to stop recursion (because the result will be 1+2+3+4+0)
Try this on for size:
private int go(int[] numbers, int spot){
if(numbers.length == spot) return 0;
return go(numbers, spot+1) + numbers[spot];
}
Maybe I can help walk you through it. Your program works it's way up until it calls go(numbers, 3+1), which returns 4, because numbers has 4 elements and spot is of value 4 (3+1).
At this point you are looking at a call stack of something like this:
answer = go(stuff, 0);
value = go(numbers, 0 + 1);
value = go(numbers, 1 + 1);
value = go(numbers, 2 + 1);
value = go(numbers, 3 + 1) = 4
Now it will work it's way back up the stack.
go(numbers, 2 + 1 );
Calling this will give you value+numbers[3], which is 4 + 4, with value coming from go(numbers, 3 + 1).
Next we have
go(numbers, 1 + 1 );
This will return go(numbers, 2 + 1 ) + numbers[2], which is 8 + 3 (or 11).
And then go(numbers, 0 + 1 ) is called, which returns go(numbers, 1 + 1 ) + numbers[1], which is 11 + 2 or 13.
Lastly, go(stuff, 0) can be calculated. This returns go(numbers, 0 + 1 ) + numbers[0], which is 13+1, or 14 - the answer you are currently getting.
I'm not sure if I actually explained much, but hopefully walking through it can show where your confusion is.
Another way of visualizing it would be something like this:
answer = go(stuff, 0);
go(stuff, 0) = go(numbers, 0 + 1) + 1;
go(numbers, 0 + 1) = go(numbers, 1 + 1) + 2;
go(numbers, 1 + 1) = go(numbers, 2 + 1) + 3;
go(numbers, 2 + 1) = go(numbers, 3 + 1) + 4;
go(numbers, 3 + 1) = 4;

Categories