binary search guessing number recursively - java

I am coding a binary search algorithm and I want to get the count minimum guesses does it take to search the number that I provide.suppose that the number which I provide is 33, then it should count 7 steps.
Step no number guessed result range of possible values
0 1-100
1 50 too high 1-49
2 25 too low 26-49
3 37 too high 26-36
4 31 too low 32-36
5 34 too high 32-33
6 32 too low 33-33
7 33 correct
so this is my code for this
package binarySearch;
public class Binary {
int gussedNo;
public static int count =0;
void search(int lowerBound,int upperBound,int num){
gussedNo=upperBound+lowerBound/2;
count();
if(gussedNo==num){
System.out.println(count);}
else if(gussedNo>num){
upperBound=gussedNo-1;
search(lowerBound,upperBound,num);
}
if(gussedNo<num){
lowerBound=gussedNo+1;
search(lowerBound,upperBound,num);
}
}
int count(){
count=count+1;
return count;
}
}
I created a a separate method. here is my my main class..
package binarySearch;
public class MainClass {
public static void main (String[] args){
Binary search= new Binary();
search.search(1, 100,33 );
}
}
Here I have given lowerbound as 1 and uperbound as 100, and the number I want to count guesses for it is 33.
But when I execute the code I get the count as 68..but it should be 7 according to binary search

Take a look at the line where you create the next guess:
gussedNo=upperBound+lowerBound/2;
Due to mathematical operators precedence in Java, this line is the same as having:
gussedNo=upperBound+(lowerBound/2);
Which is clearly not performing a binary search, and thus, not what you wanted. You can solve this by explicitly adding the brackets:
gussedNo = (upperBound + lowerBound) / 2;

here is your problem
gussedNo=upperBound+lowerBound/2;
you forgot abour operatots order execution
it should be
gussedNo=(upperBound+lowerBound)/2;

Related

Java Int(Why returning 0 when number is within range)

Thank you for your time!
for value upto 2147483641 code is working fine after that it is returning 0(why)..
as per my understanding program should return 0 only when overflow occurs.. (for -2147483648 and 2147483647 ) not for value falling in the range.
Also please share any link for leading zero number reversal.. I could not find any online.
public class ReverseDigit {
public int reverse(int integer) {
boolean negflag=false;
if(integer<0){
negflag=true;
integer=integer*-1;
}
int rev=0;
int rem=0;
while(integer!=0){
rem=integer%10;
int newrev= rev*10+rem;
if((newrev-rem)/10!=rev){
return 0;
}
else{
rev=newrev;
}
integer=integer/10;
}
return rev = negflag?rev*-1:rev;
}
public static void main(String[] args) {
ReverseDigit rd = new ReverseDigit();
System.out.println(rd.reverse(**2147483642**));
}
}
This is happens because the reversed number of 2147483642 is 2463847412, and this number is greater then Intrgre.MAX_VALUE which is 2147483647, so the number became less than 0.
This is happens to 2147483623 too, because his reversed number is 3263847412, and this number is greater then Intrgre.MAX_VALUE.
To fix that, I see two possible solutions:
Use long instead of int.
Rewrite the method to work with String, because you aren't really do any calculations (You can use string.charAt(int index) to get the digits one bt one).

A random number with 3 digit and try to guess every digit one by one

I am new in Java and for the moment basic with methods, classes and constructors. For practice I am trying to write a basic game (safecracker). So my logic is get a 3 digit random number and try to guess it.
private static int takeRandomSafeCode(int min, int max) {
Random random = new Random();
int result = random.nextInt(max - min) + min;
return result;
private static void playGame() {
int safeCode = takeRandomSafeCode(100, 999);
int guess = takeGuess();
These are my random number methods. But if player guess a number and first digit is correct but on a wrong place I want to say "1 digit is correct but on a wrong position" or if one digit is correct "1 digit is correct and correct position"
I need to use here if-else statement i guess but I get my numbers int variable. What is the way of checking numbers one by one? Do I need to use a String? I am a little bit lost at this point. I would appreciate with your help.
It may be preferable - and result in simpler code - if you generate an integer array with three elements. Logically, the safe code 1-2-3 is not one hundred and twenty three but actually 1 followed by 2 followed by 3.
private static int takeRandomDigit() {
Random random = new Random();
int result = random.nextInt(10);
return result;
}
private static void playGame() {
int[] safeCode = {takeRandomDigit(), takeRandomDigit(), takeRandomDigit()};
int guess = takeGuess();
for (int safeDigit : safeCode) // for each digit in the safe code
{
// if the digit matches the guess, do something
}
}
You can use some math to take the numbers for example if your number is:
d=253
d % 10 -> gives you 3
d / 10 % 10 -> gives you 5
d / 100 -> gives you 2
Changing it to string is also an option because you can then access the different characters using the string functions like charAt etc.
But if you want to make it the Java and OOP way in order to learn you can make an object and add the 3 numbers as properties of that object and input some of the logic for checking there instead of doing some magic tricks like the above. For example:
class Combination {
private int firstPos;
private int secondPos;
private int thirdPos;
public Combination(){
firstPos=random.nextInt(10);
secondPos=random.nextInt(10);
thirdPos=random.nextInt(10);
}
public boolean checkCombination(Combination testedCombination){
.............
}
some methods, getter, setters etc
}

I am getting negative values with a quick binary counter I made

In java I was attempting to make a binary counter, that later on I could use to count in any base-n system. My results however had a mysterious outcome. At one point the values jumped from 1111111111 to -1111111111. It seemed unusual, but the fact that I don't know how different number limits work in java probably doesn't help me in this situation. Meanwhile I looked at my code and so no way that the value could become negative. My code for the binary counter is as follows:
`
package bin;
public class Counter {
public static Integer currentNumber = 0;
public static Integer upTo = 1000;
public static Integer currentCount = 0;
public static void main(String[] args) {
while(upTo>=currentCount) {
if(currentNumber.toString().endsWith("0")) {
currentNumber++;
}else if(currentNumber.toString().endsWith("1")){
currentNumber+=10;
}
if(currentNumber.toString().contains("2")|currentNumber.toString().contains("3")|currentNumber.toString().contains("4")|currentNumber.toString().contains("5")|currentNumber.toString().contains("6")|currentNumber.toString().contains("7")|currentNumber.toString().contains("8")|currentNumber.toString().contains("9")) {
}else {
currentCount++;
System.out.print(currentNumber + "\n");
}
}
System.out.print("done");
}
}
`
The results of the program can be found at https://pastebin.com/UUMRhkhv I would appreciate any answer that explains what may have happened so I may create a more efficient and accurate binary counter.
You're encountering an integer overflow. An int in Java is 32-bits, so the max value is 2,147,483,647. The number you tried to store exceeds that. You might want to use a long or just keep the representation as a string.
(BTW, your binary counter doesn't actually count properly, but presumably you already know that. Also, you really want ||, which is the logical or operator instead of |, which is the bitwise or operation.)

Getting the inverse of a function that uses summation in Java

I have a program with one class, which looks like this.
public class Functions {
public static void main(String[] args) {
System.out.println(summationFunction(1)); //Prints 13
System.out.println(summationFunction(2)); //Prints 29
System.out.println(summationFunction(3)); //Prints 48
System.out.println(summationFunction(4)); //Prints 70
}
public static int summationFunction(int input) {
int summedNumber = 0;
int i = input;
while (i > 0) {
summedNumber += i * 3;
i--;
}
return 10 * input + (summedNumber);
}
}
So, this program will take in a given number and apply this function to it:
And this all works well (I have run the class Functions and everything prints just as it's supposed to.) BUT, I need to find the inverse of this function, and I need to be able to translate it to code; I do not know how to do this.
I basically need a function that will return values like this:
public static void main(String[] args) {
System.out.println(summationFunction(13)); //Prints 1
System.out.println(summationFunction(29)); //Prints 2
System.out.println(summationFunction(48)); //Prints 3
System.out.println(summationFunction(70)); //Prints 4
}
which, (as you can tell) is the opposite of the original function.
So to sum everything up, I need a function that will return the inverse of my original function (summationFunction), and I would like to know how I would model this or if there is a quick solution, in code.
One more thing: I know that I can have the method take an input and search for the most similar output of the original method, but I would like to see if there is a simpler way to do this which does not involve searching, thus giving a quicker output speed. And if you wish you can safely assume that the input of the inversed function will always be a number which will give an integer output, like 13, 29, 48, 70, etc...
By the way, if you are going to downvote the question, will you at least give a reason somewhere? The comments perhaps? I can not see any reason that this question is eligible for being downvoted, and a reason would help.
Wolfram Alpha to the rescue !
It tells you that this function can be written as :
1/24*(6*x+23)^2-529/24
So if you want to solve f(x)=a, you have :
x = 1/6*(sqrt(24*a+529)-23)
a = 70
# => x = 4
Note : Using Wolfram shouldn't prevent you from finding the answer on your own.
sum(something*i) is equal to something*sum(i) because something (3 in this case ) doesn't depend on i.
sum(i,i=1..n) is equal to n*(n+1)/2, and it's easy to prove (see Wikipedia)
So your function becomes 10*x+3*x*(x+1)/2
Expanded, it is :
(3 x^2)/2+(23 x)/2
You need to solve (3 x^2)/2+(23 x)/2 = 70, in other words :
(3 x^2)/2+(23 x)/2 - 70 = 0
It is a quadratic equation, with a=3/2, b=23/2 and c=-70 or c=-29 or c=....
You sum can be written like this 3*x*(x+1)/2 so you have equation 10*x + 3*x*(x+1)/2 = y you need to solve it.
Wolfram alpha tells that result will be 1/6.0 * (-23.0+sqrt(529.0+24.0 * y))

Learning Java - Do not fully understand how this sequence is calculated (Fibonacci) [duplicate]

This question already has answers here:
Java recursive Fibonacci sequence
(37 answers)
Closed 8 years ago.
I am learning Java and I have this code from the internet and running it in Eclipse:
public class Fibonacci {
public static void main (String [] args) {
for (int counter = 0; counter <= 3; counter++){
System.out.printf("Fibonacci of %d is: %d\n", counter, fibonacci(counter));
}
public static long fibonacci(long number) {
if ((number == 0) || (number == 1))
return number;
else
return fibonacci(number - 1) + fibonacci(number - 2);
}
}
I've tried to understand it but cannot get it. So I run through the code and counter gets passed in through the fibonacci method. As counter starts at 0 and this is what gets passed first, then 1 and I understand the method passes back 0 and then 1.
When it reaches 2: it will return 2-1 + 2-2 = 2 and it does return this.
When it reaches 3: it will return 3-1 + 3-2 = 3 but it does not return 3 it returns 2.
Please can someone explain to me why as I cannot figure this out?
Thanks
First, I have to tell you that this recursive version has a dramatic exponential cost. Once you understand how it works, my advice for you would be to learn about tail recursivity, write a tail-recursive solution, an iterative solution, and compare them to your current method for high values of "number".
Then, your function basically uses the mathematical definition of the Fibonacci sequence :
f0 = 1, f1 = 1, fn = fn-1 + fn-2 for all n >= 2
For example if we call fibonacci(3), this will return fibonacci(2) + fibonacci(1). fibonacci(2) will be executed first and will return fibonacci(1) + fibonnacci(0). Then fibonacci(1) will return immediately 1 since it is a terminal case. It happens the same thing with fibonnacci(0), so now we have computed fibonnacci(2) = 1 + 0 = 1. Let's go back to fibonacci(3) which has been partially evaluated at this point : 1 + fibonnacci(1). We just have to compute fibonnacci(1) and we can finally return 1 + 1 = 2.
Even in this little example, you can see that we evaluated twice fibonacci(1), that is why this version is so slow, it computes many times the same values of the sequence, and it gets worth when "number" is high.

Categories

Resources