As the title says i was trying to convert binary to decimal using recursive technique in java but i cannot get the desire output
here's what i did
public class deci {
public static void main(String args[]){
hexa s1=new deci();
s1.spawn(11000);
}
void spawn(int a){
int p=0;int x=0;int k=0;
if(a>0){
p=a%10;
x=x+p*(int)Math.pow(2,k);
k++;
spawn(a/10);
} else {
System.out.print(x);
}
}
}
The problem is you ar not using the result of spawn, either returning or printing it.
If you want to return it, you need the shifting or power, but it you want to print it.
I suggest you step through the code in your debugger so you can see what it is doing.
Here is a working program.
Parameters are (binary code, size of code-1) e.g. for (111, 2) this will return 7
int binaryToDecimal(int binary,int size){
if(binary==0) return 0;
return binary%10*(int)Math.pow(2,size)+binaryToDecimal((int)binary/10,size-1);
}
Related
For the past few months, I switched to programming in a functional language (Racket), and recently restarted coding in Java, so I'm a bit confused regarding a few concepts.
The following (simplified version) code is an implementation of euclid's algorithm. It works just fine. My problem with it is the return statement. Is it possible in java to store the results of a method in a variable? For example,in my code, I initialized the variable result to store the gcd of two numbers. But that returns an incorrect value. However, if I remove the variable result, I get the correct value for the gcd, which brings me to my 2nd question: return statements. I don't quite understand what the return statement is doing here. The only reason I have it in the 1st place was because I was aiming to store the result of the method Recursion in a variable. But as far as I've tried it, and seems to be only messing up my code.
Primary objective: To store the result of the gcd of two numbers in a variable, so I can re-use it elsewhere.
Is there is a way to make this possible?
Any suggestions would be appreciated!
import java.util.*;
public class StoringResults
{
public static void main(String[]args)
{
int big,small,remainder,gcd; //Variables declared.
Scanner sc=new Scanner(System.in);
/* Use enters input */
//Big is the larger number.
//Small is the smaller of the two.
remainder=big%small;
int result=recursion(big,small,remainder);
System.out.println("FINAL RESULT:"+result);
}
//recursive method.
public static int recursion(int big,int small,int remainder)
{
remainder=big%small;
if(remainder==0)
{
System.out.println(small);
}
else
{
int dummyvar=remainder;
big=small;
small=dummyvar;
recursion(big,small,remainder);
}
return remainder;
}
}
As my comment already stated your logic is faulty.
And your statement if I remove the variable result,I get the correct value for the gcd is plain wrong. You get the correct result printed but not returned. And that is caused by the fact that you return the wrong value.
remove the remainder from the method signature since your first statement is assigning something to it
return the correct value: smaller instead of remained
return in the else branch
That will result in the following code:
public static int recursion(int big,int small)
{
int remainder=big%small;
if(remainder==0)
{
System.out.println(small);
}
else
{
big=small;
small=remainder;
return recursion(big,small);
}
return small;
}
Shortening results in
public static int recursion(int big, int small) {
int remainder = big % small;
if(remainder == 0) {
return small;
} else {
return recursion(small,remainder);
}
}
Adding to TDG's answer, your code should be more like this:
//recursive method.
public static int recursion(int big, int small, int remainder) {
remainder = big%small
if (remainder==0) {
System.out.println(small);
return small;
} else {
Int dummyvar = remainder;
big = small;
small = dummyvar;
return recursion(big, small, remainder);
}
}
For Java practice I started working on a method countBinary that accepts an integer n as a parameter that prints all binary numbers that have n digits in ascending order, printing each value on a separate line. Assuming n is non-negative and greater than 0, some example outputs would look like this.
I am getting pretty much nowhere with this. I am able to write a program that finds all possible letter combinations of a String and similar things, but I have been unable to make almost any progress with this specific problem using binary and integers.
Apparently the best way to go about this issue is by defining a helper method that accepts different parameters than the original method and by building up a set of characters as a String for eventual printing.
Important Note: I am NOT supposed to use for loops at all for this exercise.
Edit - Important Note: I need to have trailing 0's so that all outputs are the same length.
So far this is what I have:
public void countBinary(int n)
{
String s = "01";
countBinary(s, "", n);
}
private static void countBinary(String s, String chosen, int length)
{
if (s.length() == 0)
{
System.out.println(chosen);
}
else
{
char c = s.charAt(0);
s = s.substring(1);
chosen += c;
countBinary(s, chosen, length);
if (chosen.length() == length)
{
chosen = chosen.substring(0, chosen.length() - 1);
}
countBinary(s, chosen, length);
s = c + s;
}
}
When I run my code my output looks like this.
Can anyone explain to me why my method is not running the way I expect it to, and if possible show me a solution to my issue so that I might get the correct output? Thank you!
There are more efficient ways to do it, but this will give you a start:
public class BinaryPrinter {
static void printAllBinary(String s, int n) {
if (n == 0) System.out.println(s);
else {
printAllBinary(s + '0', n - 1);
printAllBinary(s + '1', n - 1);
}
}
public static void main(String [] args) {
printAllBinary("", 4);
}
}
I'll let you work out the more efficient way.
Im a beginner.
Here is a binary search code.Its showing array out of bounds error for main method.
please look into the program and kindly tell me my mistake.ill be grateful for ur service.
i have to write all this crap cause i cant post it as its asking for more details.
public class BinaryS
{
int n;
public BinaryS(int z)
{
n=z;
}
static int pos;
static boolean flag=false;
public void disp()
{
int arr[]={0,1,2,3,4};
int len=arr.length;
int first=0;
int last=len;
int mid=(int)(first+last/2);
//boolean flag=false;
while(mid>=0 && mid<=len)
{
if(n<arr[mid])
{
last=mid;
}
if(n>arr[mid])
{
first=mid;
}
if(n==arr[mid])
{
flag=true;
pos=mid+1;
}
}
if(flag==true){
System.out.println("the no."+n+"is found at"+pos);
}
else{
System.out.println("the no."+n+"is not found ");
}
}
public static void main(String args[])
{
BinaryS obj=new BinaryS(2);
obj.disp();
}
}
Currently your code does compile, and runs forever - because of this loop:
while(mid>=0 && mid<=len)
{
// Code which doesn't modify mid or len
}
Assuming it gets into that loop at all (which it does), the condition is never going to become false - so unless you return or break from within the loop (you don't) or an exception is thrown (it isn't) you're just going to keep going round the loop.
This is where you should:
Use a debugger to observe what's happening
Think about what the condition should actually be and how you want it to become false
Adjust your code to either change the condition, or change the loop body so that it modifies mid or len
Hi I'm currently working on getting my Quick Sort program working but cannot figure out where I'm going wrong, i have spent hours trying to find out why it's not working but no luck,when I run my code nothing happens. I have four other sorting algorithms working in a similar fashion which is what's confusing me the most.
Below is my code for the Quick Sort program
import java.io.IOException;
public class QuickSort {
public static int[] compute(int[] array, int lower, int higher )throws IOException{
if(lower<higher){
int pivot=split(array,lower,higher);
if(pivot>1)
compute(array, lower, pivot-1);
if(pivot+1<higher)
compute(array, pivot+1, higher);
}
return array;
}
public static int split(int[] array, int lower, int higher){
while(true){
int pivot=array[lower];
while(array[lower]<pivot)
lower++;
while(array[higher]>pivot)
higher--;
if(lower<higher){
int temp=array[higher];
array[higher]=array[lower];
array[lower]=temp;
}
else{
return higher;
}
}
}
}
Here is my Test class that's running the code:
import java.io.IOException;
import java.util.Scanner;
public class Test extends ReadIn{
static BubbleSort bubble=new BubbleSort();
public static void main(String[] args) throws IOException{
System.out.println("Enter 1 for BubbleSort\nEnter 2 for Insertion Sort\nEnter 3 for Selection Sort\nEnter 4 for Merge Sort\nEnter 5 for QuickSort\nPlease input sorting algorithm to use for sorting:");
Scanner input=new Scanner(System.in);
int number=input.nextInt();
final long startTime = System.currentTimeMillis();
int[] Array=read();
if(number==1){
Array=BubbleSort.compute(Array);
for(int i=0;i<BubbleSort.compute(Array).length;i++){
System.out.println(Array[i]);
}
}
if(number==2){
Array=InsertionSort.compute(Array);
for(int i=0;i<InsertionSort.compute(Array).length;i++){
System.out.println(Array[i]);
}
}
if(number==3){
Array=SelectionSort.compute(Array);
for(int i=0;i<SelectionSort.compute(Array).length;i++){
System.out.println(Array[i]);
}
}
if(number==4){
Array=MergeSort.compute(Array);
for(int i=0;i<MergeSort.compute(Array).length;i++){
System.out.println(Array[i]);
}
}
if(number==5){
Array=QuickSort.compute(Array,0,Array.length-1);
for(int i=0;i<QuickSort.compute(Array,0,Array.length-1).length;i++){
System.out.print(Array[i]);
}
}
final long endTime = System.currentTimeMillis();
System.out.println("Total execution time: " + (endTime - startTime) );
}
}
When I press 5 nothing happens, the rest work perfectly.
I cant figure out whatsoever what the problem is so any help or input would be appreciated.
Your Quicksort code loops forever if there's duplicate numbers in the input, since the numbers can just keep swapping with each other. As mentioned in the comment, you should manually try out your code with a sample array, or check the code running with a debugger. See the example array below.
You might want to switch the while(true) loop to a recursive call to make the code a little clearer. Also, you can practice going through the different steps of Quicksort on my Quicksort online tutorial.
Say the array = {3,1,2,3} and the pivot is 3. Nothing will change and the code will loop forever.
while(true){
int pivot=array[lower];
while(array[lower]<pivot)
lower++;
while(array[higher]>pivot)
higher--;
if(lower<higher){ //this will just swap the 3's with each other.
int temp=array[higher];
array[higher]=array[lower];
array[lower]=temp;
}
else{
return higher;
}
}
While it looks like your program is doing nothing, it probably just loops infinitely inside this loop:
while(true){
int pivot=array[lower];
while(array[lower]<pivot)
lower++;
while(array[higher]>pivot)
higher--;
if(lower<higher){
int temp=array[higher];
array[higher]=array[lower];
array[lower]=temp;
// I recommend adding this line for you to see what's going on
System.out.println("lower="+lower+", higher="+higher+", pivot="+pivot);
}
else{
return higher;
}
}
for example, if you have equal values in your Array, say value 65 is there twice, that loop will run forever...
int[] Array={1,41,2,90,32,65,12,43,78,65,46,67};
Also, in your loop above I added and extra printout of higher, lower, and pivot values - it will help you see what is happening inside that devious loop.
In general writing a while(true) loop is not a good practice, because it's so easy to hang your system on it.
public int X1[]=new int[1001];
public int X2[]=new int[1001];
public int Xj;
public double R[]=new double[1001];
public double[] Generate(int seed1,int seed2)
{
X1[0]=seed1;
X2[0]=seed2;
for(int j=0;j<2;j++)
{
X1[j+1]=(40014*X1[j])%(2147483563);
X2[j+1]=(40629*X2[j])%2147483399;
System.out.println(X1[j+1]+" "+X2[j+1]);
Xj=Math.abs(X1[j+1]-X2[j+1]);
Xj=Xj%2147483562;
System.out.println(Xj+" "+j);
if(Xj>0)
{ R[j]=Xj/2147483563;}
else if(Xj==0)
{ R[j]=2147483562/2147483563;}
System.out.println(R[j]+" "+j);
}
In the above code when i try to print the elements of R[],it just prints 0.Can someone tell me whats wrong?I've put i out.println statements as a way of debugging the code.However they print the desired value.
It's because you're performing integer divisions. For example, change this:
Xj/2147483563
... to this:
Xj/2147483563.0
Do the same with all the other divisions. Notice that in Java, int/int will always return an int. To get a result with decimals, one of the two operands (or both) must be a decimal number.