Get input from user and print decreasing pattern of numbers - java

Can someone help me write a code that prints the following pattern.
987654321
98765432
9876543
987654
98765
9876
987
98
9
This is my code sample but I am getting the exact opposite of the above pattern.
height = getInPut("Enter the height of the triangle");
int h = Integer.parseInt(height);
int start = h, num=1,max=h;
for (int r= 1; r <=h; r++)
{
System.out.println();
for (int j = 1; j<= max; j++)
{
if(h>=6 && h<=10)
{
System.out.print(num);
}else{
System.out.println("height should be between 6-10");
System.exit(0);
}
num++;
}
num= r+1;
max--;
}

I would start with an initial value of 987654321 in a StringBuilder, then loop while that contains characters; in every iteration of the loop, we want to print the difference (in spaces) between the initial length (nine) and the current length of the StringBuilder, then print the contents of the StringBuilder before removing the last character. Like,
StringBuilder sb = new StringBuilder("987654321");
while (sb.length() > 0) {
for (int i = 0; i < 9 - sb.length(); i++) {
System.out.print(' ');
}
System.out.println(sb);
sb.setLength(sb.length() - 1);
}
Which outputs (as requested)
987654321
98765432
9876543
987654
98765
9876
987
98
9
I'll leave filling the initial StringBuilder and adjusting nine into a variable as an exercise for the reader.

Related

Decreasing number pyramid, nested for loop, user input, java

Write a program to produce the following output for any given integer number between
1 and 9 inclusive.
Enter an integer value [1..9]: 6
1
12
123
1234
12345
123456
666666
66666
6666
666
66
6
I have done the top half but I can not figure out the bottom with the repeating user input.
package lab7;
import java.util.Scanner;
public class problem5 {
public static void main(String[] args) {
Scanner scan = new Scanner (System.in);
System.out.println("Input an integer between 1 and 9");
int input = scan.nextInt();
while (input <= 9) {
for (int i = 1; i <= input; i++) {
for (int j = 1; j <= i; j++) {
System.out.print(j);
}
System.out.println();
}
break;
}
}
}
Expected result: included at the top; actual result so far (input of 5):
1
12
123
1234
12345
You're pretty close. You have a for loop that covers the first half of the output you want. You can add a second for loop to handle the second half of the output.
This is pretty similar to the first loop, but has a few small differences:
instead of the loop variable starting at 1 and increasing, this one starts at input and decreases each time through (i-- instead of i++)
instead of printing any of the loop variables (i or j), it prints the input value ("6" in your example)
for (int i = input; i > 0; i--) {
for (int j = 1; j <= i; j++) {
System.out.print(input);
}
System.out.println();
}
If I run that code locally – so your for loop, then this for loop, then the break statement – this is the output:
Input an integer between 1 and 9
6
1
12
123
1234
12345
123456
666666
66666
6666
666
66
6
I would prefer a more efficient algorithm, your current approach is O(n2); consider the digits '1' - '9'; if we store them in a String then we can take a simple substring of that String for each line at the top (for example, "123456789".substring(0, 3) -> "123") that can be used to generate the top through successive calls to substring. We can use a similar approach to build the bottom; use an array of all possible rows and iteratively call substring. Finally, don't forget to validate that input is between one and nine inclusive. Something like,
Scanner scan = new Scanner(System.in);
String digits = "123456789";
String[] btm = { "1", "22", "333", "4444", "55555",
"666666", "7777777", "88888888", "999999999" };
System.out.println("Input an integer between 1 and 9");
int input = scan.nextInt();
if (input < 1 || input > 9) {
System.err.printf("Invalid input: %d%n", input);
System.exit(1);
}
for (int i = 0; i < input; i++) {
System.out.println(digits.substring(0, i + 1));
}
for (int i = input - 1; i >= 0; i--) {
System.out.println(btm[input - 1].substring(0, i + 1));
}

How to make a frequency histogram in java

I am trying to create a code that reads through a file and prints out the following:
number of lines of the file
the frequency of each letter
the frequency of each non-alphabetic character
I want to create a histogram for the frequency of the letters and numbers but I can't seem to find a solution around it. If anything i would want the output to look like this:
A ***** - 5
B *** - 3
C ******* - 7
My output looks like this:
*********************
*********************
*********************
A 263
B 130
C 50
etc.
This is how you do the task. It counts the number of lower case letters and prints the stars as well in addition to the frequency, just as you wanted.
Here is the general code (paragraph is the string that contains the content of your file):
int[] lettercount = new int[26];
for(int i = 0; i < 26; i++){
//Set every single number in the array to 0.
lettercount[i] = 0;
}
for(char s : paragraph.toCharArray()){
int converted = (int) s;
converted -= 97;
if(converted >=0 && converted <=25){
lettercount[converted] += 1;
}
}
//Print out the letter with the frequencies.
for(int i = 0; i < 26; i++){
char convertback = (char) (i+97);
String stars = "";
for(int j = 0; j < lettercount[i]; j++){
stars += "*";
}
System.out.println(convertback + " " + stars + " - " + lettercount[i]);
}
This should work for lowercase letters. If you want to do uppercase letters, lettercount[] should be 52 elements long. You would also have to check if converted (in the second for loop), after subtracting 97 is negative, and if it is, you would add back 58.
I hope this helps! If you have any problems, just comment below.

Having trouble filling an array of binary numbers from an integer

This is the question we were assigned :
Nine coins are placed in a 3x3 matrix with some face up and some face down. You can represent the state of the coins using a 3x3 matrix with values 0 (heads) and 1 (tails). Here are some examples:
0 0 0 1 0 1 1 1 0
0 1 0 0 0 1 1 0 0
0 0 0 1 0 0 0 0 1
Each state can also be represented using a binary number. For example, the preceding matrices correspond to the numbers:
000010000 101001100 110100001
There are a total of 512 possibilities, so you can use decimal numbers 0, 1, 2, 3,...,511 to represent all the states of the matrix.
Write a program that prompts the user to enter a number between 0 and 511 and displays the corresponding matrix with the characters H and T.
I want the method toBinary() to fill the array binaryNumbers. I realized that this does not fill in 0s to the left. I have to think that through but is that the only thing that is the problem?
//https://www.geeksforgeeks.org/java-program-for-decimal-to-binary-conversion/
import java.util.Scanner;
public class HeadsAndTails {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int num = input.nextInt();
int[] binaryNumbers = toBinary(num);
for (int i = 0; i < 9; i++) {
printArr(binaryNumbers);
System.out.print(binaryNumbers[1]);
}
}
public static int[] toBinary(int inputtedNumber) {
int[] binaryNum = new int[9];
int i = 0;
while (inputtedNumber > 0) {
binaryNum[i] = inputtedNumber % 2;
inputtedNumber = inputtedNumber/2;
inputtedNumber++;
} return binaryNum;
}
public static void printArr(int[] arr) {
for (int i = 0; i < 9; i++) {
if (arr[i] == 0) {
System.out.print("H ");
} else {
System.out.print("T ");
}
if (arr[i+1] % 3 == 0) {
System.out.println();
} System.out.print(arr[i]);
}
}
}
Looks like you are incrementing the wrong variable in your while loop:
while (inputtedNumber > 0) {
binaryNum[i] = inputtedNumber % 2;
inputtedNumber = inputtedNumber/2;
i++; // NOT inputtedNumber
} return binaryNum;
Also note, a new int[9] is probably already initialized to 0, but if not, you could just loop 9 times, rather than until the inputtedNumber is 0:
for (int i = 0; i < 9; i++) {
binaryNum[i] = inputtedNumber % 2;
inputtedNumber = inputtedNumber/2;
}
return binaryNum;
Finally, I think your array might be backwards when you're done, so you may need to reverse it or output it in reverse order
I realize this is a homework assignment so you should stick with your current approach. However, sometimes it can be fun to see what can be achieved using the built in features of Java.
The Integer class has a method toBinaryString that's a good starting point:
int n = 23;
String s1 = Integer.toBinaryString(n);
System.out.println(s1);
Output: 10111
But as we can see, this omits leading 0s. We can get these back by making sure our number has a significant digit in the 10th place, using a little bit-twiddling:
String s2 = Integer.toBinaryString(1<<9 | n);
System.out.println(s2);
Output: 1000010111
But now we have a leading 1 that we don't want. We'll strip this off using String.substring, and while we're at it we'll use String.replace to replace 0 with H and 1 with T:
String s3 = Integer.toBinaryString(1<<9 | n).substring(1).replace('0','H').replace('1','T');
System.out.println(s3);
Output: HHHHTHTTT
Now we can print this string in matrix form, again using substring to extract each line and replaceAll to insert the desired spaces:
for(int i=0; i<9; i+=3)
System.out.println(s3.substring(i, i+3).replaceAll("", " ").trim());
Output:
H H H
H T H
T T T
If we're up for a bit of regex wizardry (found here and here) we can do even better:
for(String sl : s3.split("(?<=\\G.{3})"))
System.out.println(sl.replaceAll(".(?=.)", "$0 "));
Putting it all together we get:
int n = 23;
String s3 = Integer.toBinaryString(1<<9 | n).substring(1).replace('0','H').replace('1','T');
for(String s : s3.split("(?<=\\G.{3})"))
System.out.println(s.replaceAll(".(?=.)", "$0 "));

Counting with Java

I have two given Strings: String a = "111" and String b = "132", for these two String I want to achieve this count order:
111
112
121
122
131
132
Other example is if I have two given String like this: String a = "1111" and String b = "1223", I expect this result:
1111
1112
1113
1121
1122
1123
1211
1212
1213
1221
1222
1223
These can be also longer strings like String a = "0100110" and String b = "01101120".
I'm waiting these Strings from user in condition that every character in String a should be lower or equal than the same character position in String b (String a = "11" and String b = "00" <= not allowed)
This is a recursive method till now but it doesn't work very well because it generates number twice or more depending on the input:
public void expand(String l,String h){
for(int i=l.length()-1; i>=0; i--)
{
sb = new StringBuffer(l);
if(charToDigit(l.charAt(i)) < charToDigit(h.charAt(i))) {
sb.replace(i, i+1, inc(sb.charAt(i)));
expand(sb.toString(),h);
System.out.println(sb.toString());
}
}
}
Call the smaller number x and the larger number y. If you calculate y mod 10 (y % 10), you will find the value of the least significant digit, call this n. Similarly, calculate the least significant digit of x, call it m Then, create a temporary variable i which is equal to x initially. Loop until that number is equal to y.
In the body of the loop, first, print i. Then, if the least significant digit of i (again, calculated by i % 10), call it o, is less than n, increment i by one. Otherwise, if o == n, increase i by 10 - n + m. Naturally, if it is ever the case that o > n, something went wrong (i.e. invalid input from the user), since the guarantee was that all digits of x are less than or equal to the corresponding digits in y.
So, in pseudocode:
x = smaller number
y = larger number
n = y % 10
m = x % 10
i = x
while (i <= y):
print i
o = i % 10
if (o < n):
i += 1
else if (o == n):
i += 10 - n + m
Here is my solution
static String l="000";
static String h="232";
static ArrayList<String> combinations = new ArrayList<String>();
static int stringLength= l.length();
for(int i=0; i<rulelength; i++)
{
combinations.add((charToDigit(h.charAt(i)) - charToDigit(l.charAt(i))+1)+"");
}
int number = 1;
for(int i=0; i<combinations.size(); i++)
{
number*=Integer.parseInt(combinations.get(i));
}
int change = Integer.parseInt(combinations.get(combinations.size()-1));
expand(l, h, change, number);
public static void expand(String l, String h, int change, int comb)
{
StringBuffer sb = new StringBuffer(l);
int pos = stringLength-1;
int tmpPos = pos;
for(int i=1; i<=comb; i++)
{
System.out.println(sb.toString());
sb.replace(pos, pos+1, inc(sb.charAt(pos)));
if((i % change)==0) {
for(int j=stringLength-1; j>0; j--)
{
if(charToDigit(sb.charAt(j)) >= (Integer.parseInt(combinations.get(j))-1))
tmpPos = j-1;
else
break;
}
sb.replace(tmpPos, tmpPos+1, inc(sb.charAt(tmpPos)));
for(int j=stringLength-1; j>tmpPos; j--)
{
sb.replace(j, j+1, l.charAt(j)+"");
}
}
}
}

Show a number line based on the given string

I am stuck in my project where we have to show a string of line in the number line scale so later we can delete or add characters to that string. I am not sure how to print out the scale in 5s based on the length of the string.
Ex:
0 5 10 15 20
|----+----|----+----|-
This is the first line
Then, the user will choose the characters they want to delete from the string using from position and to position. It will show what position the user chose from the string and delete.
Ex:
from position: 12
to position: 18
0 5 10 15 20
|----+----|----+----|-
This is the first line
^^^^^^^ --> // this will be deleted
y/n: y
0 5 10 15
|----+----|----+
This is the ine
I was able to delete the characters but I do not know how to show the number line based on a string. Here is my code so far:
public void showNumberLine(String line)
{
int lineCount = line.length(); // getting the length of the string being passed in
String numberLine = "";
for(int i = 0; i <= lineCount; i++) //
{
numberLine = "" + i;
System.out.println("|----+----|----+----|-");
}
}
public void deleteSubString()
{
Scanner keyboard = new Scanner(System.in);
showNumberLine(textOfLine); // this will print out then number line and the line
System.out.print("from position: ");
int fromIndex = keyboard.nextInt();
System.out.print("to position: ");
int toIndex = keyboard.nextInt();
if(fromIndex < 0 || fromIndex > numOfChar || toIndex < 0 || toIndex > numOfChar)
{
System.out.println("Cannot delete at the given index: Index Out of Bounds");
}
/*
* Create a new number line where it shows what is going to be deleted
*/
String newLineOfString = textOfLine.substring(fromIndex, toIndex);
textOfLine = textOfLine.replace(newLineOfString, "");
System.out.println(newLineOfString);
}
I would recommend you to implement a method printScale or something like that which takes a String or an int as argument and prints these two lines for you.
You sad you already can remove the characters so if you have a String with the value "This is the ine" as you showed in your example you could call the method like this:
printScale(myNewString.length());
This method could look something like this (not perfect but works):
public void printLine(int amountOfCharacters) {
StringBuilder lineNumber = new StringBuilder();
StringBuilder lineScaleSymbols = new StringBuilder();
for (int i = 0; i < amountOfCharacters; i++) {
if (i % 10 == 0) {
if (i < 10) {
lineNumber.append(i);
} else {
lineNumber.insert(i -1, i);
}
lineScaleSymbols.append('|');
} else if (i % 5 == 0) {
if (i < 10) {
lineNumber.append(i);
} else {
lineNumber.insert(i -1, i);
}
lineScaleSymbols.append('+');
} else {
lineNumber.append(' ');
lineScaleSymbols.append('-');
}
}
System.out.println(lineNumber.toString());
System.out.println(lineScaleSymbols.toString());
}
Hope this helps.
You're on the right track with your showNumberLine method.
Let's outline exactly what you need to do:
determine the length of the string
generate a number line of the same length as the string
every character ending with 0 will be the special character |
every character ending in 5 will be the special character +
every other character will be -
You could make your loop like this, using the modulus operator to determine which character to write:
for(int i = 0; i < line.length(); i++) {
if(i % 10 == 0) {
// the number is divisible by 10 (ends in zero)
System.out.print("|");
} else if(i % 5 == 0 && i % 10 != 0) {
// the number is divisible by 5 and not divisible by 10 (ends in 5)
System.out.print("+");
} else {
System.out.print("-");
}
System.out.println();
}
Output:
|----+----|----+----|----+----|----+----|---
The quick brown fox jumped over the lazy dog
You'll need some more code to write out the digits (0, 5, 10, 15) above the number line, I'll leave that to you. It will be similar logic but there are subtle issues to consider as the length of the numbers is 1 character, then 2 characters, then 3 characters as they increase (0, 5, 10, 15, ... 100, 105). At some point you'll have to stop as the numbers won't fit in the space.

Categories

Resources