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.
Related
I am trying to make a histogram with inputting a value and rounding it. The rounded value should print out the number of asterisks.
I did the following code and inputted a value but, the output is coming out as nothing.
public class Histogram
{
public static void main(String args[])
{
histogram obj = new histogram();
obj.histogram(13.5);
}
}
class histogram
{
public void histogram(double num)
{
int roundNum = (int)(num);
if (roundNum == 14)
{
System.out.println("**************" + num);
}
if (roundNum == 3)
{
System.out.println("***" + num);
}
if (roundNum == 16)
{
System.out.println("****************" + num);
}
if (roundNum == 0)
{
System.out.println("" + num);
}
if (roundNum == 1)
{
System.out.println("*" + num);
}
}
}
In Java, typecasting to primitive type int from primitive type double can be thought of as simply removing the decimal part.
For example;
System.out.println((int) 13.1); // prints 13
System.out.println((int) 13.5); // prints 13
System.out.println((int) 13.9); // prints 13
So, when you call obj.histogram(13.5); with the function parameter num being 13.5, the operation int roundNum = (int)(num); is the same as int roundNum = (int)(13.5);, and assigns 13 to the roundNum variable.
Since no if statements handle this case (roundNum being 13), no output is generated.
On another note, hardcoding a lot of if statements for checking the same variable over and over again can usually lead to unnecessarily complex, inefficient and hard-to-read code. Can you think of a better way to print "*" characters for the histogram, by using the roundNum variable? (Hint: try experimenting with for loops)
Change your int roundNum = (int)(num); to int rounded = Math.round((float)num); it should give you the desired output.
I'm trying to return the middle 3 characters of a word using the substring method but how do I return the middle 3 letters of a word if the word can be any size (ODD only)?
My code looks like this.
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scnr = new Scanner(System.in);
String inputWord;
inputWord = scnr.next();
System.out.println("Enter word: " + inputWord + " Midfix: " + inputWord.substring(2,5));
}
}
The reason I have a 2 and 5 in the substring method is because I have tried it with the word "puzzled" and it returned the middle three letters as it was supposed to do. But if I try, for instance "xxxtoyxxx", It prints out "xto" instead of "toy".
P.S. Please don't bash me I'm new to coding :)
Consider the following code:
String str = originalString.substring(startingPoint, startingPoint + length)
To determine the startingPoint, we need to find the middle of the String and go back half the number of characters as the length we want to retrieve (in your case 3):
int startingPoint = (str.length() / 2) - (length / 2);
You could even build a helper method for this:
private String getMiddleString(String str, int length) {
if (str.length() <= length) {
return str;
}
final int startingPoint = (str.length() / 2) - (length / 2);
return "[" + str.substring(startingPoint, startingPoint + length) + "]";
}
Complete Example:
class Sample {
public static void main(String[] args) {
String text = "car";
System.out.println(getMiddleString(text, 3));
}
private static String getMiddleString(String str, int length) {
// Just return the entire string if the length is greater than or equal to the size of the String
if (str.length() <= length) {
return str;
}
// Determine the starting point of the text. We need first find the midpoint of the String and then go back
// x spaces (which is half of the length we want to get.
final int startingPoint = (str.length() / 2) - (length / 2);
return "[" + str.substring(startingPoint, startingPoint + length) + "]";
}
}
Here, I've put the output in [] brackets to reflect any spaces that may exist. The output of the above example is: [ppl]
Using this dynamic approach will allow you to run the same method on any length of String. For example, if our text String is "This is a much longer String..." our output would be: [ lo]
Considerations:
What if the input text has an even number of characters, but the length is odd? You would need to determine if you want to round the length up/down or return a slightly off-center set of characters.
I think what you can do is to calculate the string length then divided by 2. This gives you the string in the middle, then you can subtract one to the start and add 2 to the end. If you want to get the first two for an odd string, then subtract 2 to the start index and add 1 to the end.
String word_length = inputWord.length()/2;
System.out.println("Enter word: " + inputWord + " Midfix: " + inputWord.substring((word_length-1, word_length+2));
Hope this helps.
This will get the middle of the string, and return the characters at the middle, and +- 1 from the middle index.
public static String getMiddleThree(String str) {
int position, length;
if (str.length() % 2 == 0) {
position = str.length() / 2 - 1;
length = 2;
} else {
position = str.length() / 2;
length = 1;
}
int start = position >= 1 ? position - 1 : position;
return str.substring(start, position + 1);
}
The work left you have to do is make sure the end position is not greater than the length of the string, otherwise, choose the position as the final index
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);
}
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
Hey everyone I started doing recursion and I have to say its confusing me.
Currently I'm working on the Towers of Hanoi:
public static String hanoi(int n, int startPole, int endPole) {
String ret = new String();
if (n == 0){
return "";
}
int intermediatePole = 6 - startPole - endPole;
String add3 = hanoi(n-1, startPole, intermediatePole);
String add = startPole + "->" + endPole + "\n";
String add2 = hanoi(n-1, intermediatePole,endPole );
return add + add3 + add2;
}
So pretty much what's breaking my brain is - Who does one return the string of moves such that you get from a call of hanoi(2, 1, 3), you get a output like so, mine only returns one loop of the recursive call
1 - 3
1 - 2
3 - 2
1 - 3
2 - 1
2 - 3
1 - 3
Try it with return add3 + add + add2;. If your code's output is tried on a physical tower, it doesn't work.
The reason that you are only seeing "one loop of the recurisve call" is that the output show is actually for hanoi(3,1,3), not 2,1,3.