adding data from a string to binary tree using recursion java - java

I'm trying to basically add data to a binary tree where each node will contain a digit and number of times it has been entered. So example 1 1 2 2 lets say first node will have digit 1 and has been entered 2 times. Thats no problem. The issue I cant seem to understand is why does the count method seem to return right amount of occurences(2 times) for digit 1 but for digit 2 it gives me 4 occurences. Disregard the NullPointer handling in registerDigit, its just because if a node is not found the findNode method will return null, so it means I can add this node, once it is found then it shouldnt be added. Ofcourse in the beginning the tree is empty so the it will initially give me this error.
private void registerDigit(){
System.out.println("Register digits like this: 1 2 3 4 1 4 ");
values=input.nextLine().replaceAll("\\s","");
for(int x=0; x<values.length();x++) {
try{
if(theTree.findNode(Integer.parseInt("" + values.charAt(x)))==null )
theTree.addNode(Integer.parseInt("" + values.charAt(x)),count(values,values.charAt(x)));
else
System.out.println("Digit "+values.charAt(x)+" has been added before with "+count(values,values.charAt(x))+ "times");
}
catch(NullPointerException e){
theTree.addNode(Integer.parseInt("" + values.charAt(x)),count(values,values.charAt(x)));
}
}
System.out.println("Thank you, digits are registered");
}
public int count (String values, char c)
{
int charOccurences=0;
if(values.length()==0)
return 0;
if (values.contains(""+c))
charOccurences++;
else
return 0;
return charOccurences + count (values.substring(1), c);
}

Related

my code executes, but does not get any output

I am Jordan a high school student, i recently got a coding challenge/homework that goes like this: you have the numbers 1 to 18 and you need to find combinations of flowing numbers that are equal when you put an equal sign in between them and a plus sign between every number, for example: 1+2=3 or
4+6+7+8=9+10+11
I need to find six of these combinations but my program will not find any, please help.
public static void main(String[] args) {
int[] A = new int[]{0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17};
boolean check;
int s = A[1];
int e = A[s+1];
int eq= A[s+1];
for(e=s+1;e==A[17];e++){
for(eq=s+1;eq==e;eq++){
if(Integer.sum(s, eq-1) == e) {
check = true;
}
if(check = true) {
System.out.println("start number is ---" + s + "equal number is ---" + eq + "end number is ---" + e);
i expect to get a starting point where to put the equal and an ending point for six combinations but instead i get nothing

Empty String in an array of strings

I want to calculate the no of letters in words from 1 to 100. for example....
If the numbers 1 to 5 are written out in words: one, two, three, four, five,
then there are 3 + 3 + 5 + 4 + 4 = 19 letters used in total.
for which I have written the following code...
public static int helper(int a){
String ones[]= {"","one","two","three","four","five","six","seven","eight","nine","ten",
"eleven","twelve","thirteen","fourteen","fifteen","sixteen","seventeen"
,"eighteen","nineteen"};
String tens[]= {"","","twenty","thirty","forty","fifty","sixty","seventy","eighty","ninety"};
if(a<20){
return ones[a].length();
}
else
return tens[a/10].length();
}
public static int countLetters(int a){
if(a==100)
return 10;
else if(a<20){
return helper(a);
}
else{
return helper((a/10)*10)+ helper(a%10);
}
}
The main function looks like
public static void main(String[] args) {
// TODO Auto-generated method stub
int result=0;
for(int i=1;i<=100;i++){
result+=countLetters(i);
}
System.out.println(result);
}
The correct answer for this problem is 864. In the String ones[] array I used punctuation marks " " with space between them. The result returned was 872which is incorrect but after removing space between them answer returned was 864. I used "" without space. I wonder why this happened..?
Is there any logical aspect with respect to strings or string arrays for this problem ?
It only happens when you have the " " in the ones array.
If you have 20, you get the length of "twenty" + the length of helper(a%10) which is helper(0), which returns the length of " ". So you get the length of "twenty" + the length of " ".
This happens for 20, 30, 40, 50, 60 ,70 ,80 and 90. 8 times. That's why you see the 872.
The easiest fix is just making the first string "", like you did, but this would work too:
// return helper((a/10)*10)+ helper(a%10);
return helper((a/10)*10) + (a%10 == 0 ? 0 : helper(a%10));
A space in a String also adds to the length of a String for example:
"foo bar".length() --> 7
" foo bar ".length() -->9
"foobar".length() -->6
If you want to avoid having this problem and remove the outer space use trim.
"foo bar".trim().length() --> 7
" foo bar ".trim().length() -->7
"foobar".trim().length() -->6
Hope this helped.
What does this line of code calculate when value of a is 20?
return helper((a / 10) * 10) + helper(a % 10);
Your answer is in the calculation of this calculation. So, let's solve this out.
return helper((20 / 10) * 10) + helper(20 % 10);
which becomes:
return helper(20) + helper(0);
and in call against helper(0), your method executes this particular condition:
if(a<20){
return ones[a].length();
}
So, although you start your loop's iteration from 1 doesn't mean that index 0 for array ones is not being traversed.

Pascal's Triangle Formatting

I have a program that finally works to print pascal's triangle, kind of.
For whatever reason when it prints, it prints all the rows correctly as you would assume, but at the end of each row where it should just stop at one the last whole row is pasted. I'll give an example.
Instead of just this:
Enter the row number up to which Pascal's triangle has to be printed: 4
Rows to print: 4
1
11
121
1331
14641
It prints this:
Enter the row number up to which Pascal's triangle has to be printed: 4
Rows to print: 4
1
11
1211
1331211
14641331211
Those extra tidbits on the end are not supposed to be there. I have no idea why there are there. Any help is much appreciated.
"Yes, it is supposed to use recursion, and no, I can't change that."
Here is my code:
import java.util.Scanner;
public class pascalsTriangle {
public static int rows;
public static String list = "";
public static String line = "1";
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.print("Enter the row number up to which Pascal's triangle has to be printed: ");
rows = scan.nextInt();
System.out.println("Rows to print: " + rows);
scan.close();
if (rows == 1)
System.out.println("1");
else {
System.out.println(print(1, rows));
}
}
public static String print(int largest, int row) {
if (row < 1)
return "1";
else{
list = print(1, row - 1) + "\n" + curLine(row, 0, 1);
}
return list;
}
public static String curLine(int n, int k, int last) {
if(n > k && n != 0){
line = Integer.toString(last) + curLine(n, k + 1, last*(n - k)/(k + 1));
}
return line;
}
}
When your program moves to put together the next line of the triangle, your String variable line needs to be reset back to just "1". What's happening is that when your program moves to the next line, line is still the previous line of numbers, and it adds the triangle onto that. Notice how the "extra tidbit" on the last line: 14641'331211' matches up with the row above it: 1'331211'
Alternatively you could work-around this using a substring by changing your line:
list = print(1, row - 1) + "\n" + curLine(row, 0, 1);
To:
list = print(1, row - 1) + "\n" + curLine(row, 0, 1).substring(0,row+1);
And that will solve your problem entirely

Get the next sequence in an arithmetic or geometric progression

I want to make an application that takes a sequence of 3 numbers per line to produce and stops when it reaches a sequence of zeros and then prints if it's an arithmetic progression or geometric progression and the next number in the series.
Example input:
4 7 10
2 6 18
0 0 0
should output
AP 13
GP 54
here is my code I wanna know what's wrong with it and what are the possibilities that won't work with my code.
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class Main
{
static String s="";
public static void main (String[] args) throws IOException
{
String c;
String a[];
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
do {
c= br.readLine();
a = c.split(" ");
if(c.charAt(0)!='0'){
calc(a[1], a[2]);
}
}while((c.charAt(0))!='0');
printer(s);
}
public static void calc(String a, String b){
int x = Integer.parseInt(a);
int y = Integer.parseInt(b);
if(y%x==0){
s += "GP" +" " + (y*(y/x)) + "z";
return;
}else{
s += "AP" + " " + (y + (y-x)) + "z";
return;
}
}
public static void printer(String s){
String p= "";
for(int i =0;i<=s.length()-1;i++){
if(s.charAt(i)!='z'){
p+= s.charAt(i);
}else{
System.out.println(p);
p= "";
}
}
}
}
Your problem it that you discover progression type incorrectly. For example, 0 4 8 is obviously AP, but your algorithm will say it is GP. Another example: 8 4 2 is GP, but 2%4 will return false, saying it is AP. Also, you don't proceed cases when offered sequence is not progression at all.
It is absolutely clear that all 3 numbers should be involved. Suppose that integer numbers a, b, c form AP or GP, and you need to discover which progression it is. Simple math can be used:
If they form AP, then a + c = b + b. Next element is c + c - b
If they form GP, then a * c = b * b. Next element is c * c / b
(Please notice how + is changed to *, and - to /, when you switch from AP to GP).
Your code works on the assumption that if two consecutive numbers of a 3 number series is divisible, the series is a GP and that if it's not, it has to be an AP. This assumption is wrong. There are many cases in which it will not be true, such as a series 0,3,6. It is an AP, not a GP. So instead of sending 2 parameters to the function calc(), you should send all three numbers as parameters, and check as follows:
if((a+c)==(2*b))
{//AP
}
else if((a*c)==(b*b))
{//GP
}
These above are the proper check for Arithmetic and Geometric progressions. Also while checking if the inputs are all 0, you are only checking for the first element. Instead you have to see if all three of the elements are 0. Your code might not work in the case of 0,3,6 or 0,2,4 or 0,1,2. So instead you have to check like this:
int flag=0;
for(int i=0;i<3;i++)
if(Integer.parseInt(a[i]))
flag=1;
if(flag==1)
{//continue prog
}
else
{//Terminate prog as input is 0,0,0
}

Number guessing game keeps repeating same questions and guesses incorrectly

If you run the the game you can see that certain numbers the game cannot guess correctly. For example if your number is 13 the game will loop two times too many and will also guess your number as 12 instead of 13. I think this is an issue with the counting but I've tried tracing the loops repeatedly but cannot find the error. I think the issue mainly lies within my while loop.
//import statements
import java.util.Scanner;
public class Numbers
{
public static void binarySearch()
{
int position=0;
String answer;
int upper_BOUND=100;
int lower_BOUND=0;
Scanner input=new Scanner(System.in);
while( (lower_BOUND <= upper_BOUND))
{
position = (lower_BOUND + upper_BOUND) / 2;
System.out.println("Is your value greater than " + position + "?");
answer=input.next();
if((upper_BOUND-lower_BOUND<=1))
{
break;
}
if (answer.equals("no")) // If the number is > key, ..
{ // decrease position by one.
upper_BOUND = position --;
}
if(answer.equals("yes"))
{
lower_BOUND = position ++; // Else, increase position by one.
}
}
System.out.println("Is your number " + position + "?");
String answer2=input.next();
System.out.println(position+" is the answer.\n Thank you for playing the guessing game.");
//else
// System.out.println("Bruh pick a number from 1 to 100 ");
}
}
......
tester class
public class NumberGuesser
{
public static void main(String[] args)
{
int[ ] num = new int [100];
// Fill array
for (int i = 0; i <= 99; i++)
num[i]=i;
//The search method
Numbers.binarySearch();
}
}
Your issue should be with the increment that you do in "lower_BOUND = position ++; " here what happens is when you increment the position value, the "++" first increments and then assigns the value to position variable. The lowerbound is not actually assigned the incremented value of position but old value of positon. So please make a change to "lower_BOUND = ++ position ; "
Like below
if(answer.equals("yes"))
{
lower_BOUND = ++ position ; // Else, increase position by one.
}
And also my suggestion is to check your " if((upper_BOUND-lower_BOUND <= 1))" condition. I guess the condition should be like this " if((upper_BOUND-lower_BOUND == 0)) "
And please remove unused code in your "NumberGuesser" class, this will confuse people who are trying to answer your question.

Categories

Resources