Numbers triangle in Java - java

I'm trying to write a program that prints out a triangle made of numbers. It should look like that:
1
2 3 4
3 4 5 6 7
4 5 6 7 8 9 0
5 6 7 8 9 0 1 2 3
6 7 8 9 0 1 2 3 4 5 6
In my case it returns negative numbers (876543210-1-2-3...) but it should use only 0-9. I could use modulo n%10, but I don't know how to write that. Any help? Thank you.
import java.util.Scanner ;
public class Triangle {
public static void main (String [] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Number: ");
int n = sc.nextInt();
int j;
int i;
int k = n-1;
System.out.printf("n=%d\n\n", n);
for (i=1; i<=(n*2); i=i+2) {
for (j=0; j<=2*n-1; j++) {
if (j < k){
System.out.print(" ");
}
else if (j < (k+i)){
System.out.printf("%d", (n-j));
}
else {
System.out.print(" ");
}
}
k = k-1;
System.out.println();
}
}
}

This is a possible implementation, I modified your index names because it was a little confusing:
public class Triangle {
public static void main (String [] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Number: ");
int n = sc.nextInt();
int startNumber = 1; /* First number in the line */
int spaces = n - 1; /* Spaces in the current line */
int numbers = 1; /* Numbers in the current line */
System.out.printf("n=%d\n\n", n);
for (int lineCounter = 0; lineCounter < n; lineCounter++) {
/* Spaces before the numbers */
for (int spaceCounter = 0; spaceCounter < spaces; spaceCounter++) {
System.out.print(" ");
}
for (int numberCounter = 0, number = startNumber; numberCounter < numbers; numberCounter++) {
System.out.printf("%d", (number));
number = (number + 1) % 10;
}
/* Spaces after the numbers */
for (int spaceCounter = 0; spaceCounter < spaces; spaceCounter++) {
System.out.print(" ");
}
System.out.println();
startNumber = (startNumber + 1) % 10;
spaces--;
numbers += 2;
}
}
}

You could create a printTriangle() method like this (explanation follow in the comments):
static void printTriangle(int numLines) {
for (int lineNumber = 1; lineNumber <= numLines; lineNumber++) {
// Print 2 * (numLines - lineNumber) spaces before the first number in the current line
for (int spacesPerLine = 0; spacesPerLine < 2 * (numLines - lineNumber); spacesPerLine++) {
System.out.print(" ");
}
// First line has 1 number, second has 3, third has 5, etc.
int numbersPerLine = (2 * lineNumber) - 1;
// Print the numbers in the current line
// from lineNumber (inclusive) to lineNumber + numbersPerLine (exclusive)
for (int number = lineNumber; number < lineNumber + numbersPerLine; number++) {
System.out.print((number % 10) + " ");
}
System.out.println();
}
}

Related

How to determine how many times a character is repeated in a string?

I am having some trouble with writing a method that when prompted with a number returns how many times each value is repeated. For example, if the number 7846597 is entered the method would return:
0 - 0
1 - 0
2 - 0
3 - 0
4 - 1
5 - 1
6 - 1
7 - 2
8 - 1
9 - 1
I know this would be most easily done with a loop, but I am not sure how to write the actual code. I also know that I need to convert the number value I get as an input into a string so I can use char methods.
This is my attempt:
public double countOccurences(int num)
{
String str = num + "";
int goneThrough = 0;
int count0 = 0;
int count1 = 0;
int count2 = 0;
int count3 = 0;
int count4 = 0;
int count5 = 0;
int count6 = 0;
int count7 = 0;
int count8 = 0;
int count9 = 0;
while(goneThrough <= str.length())
{
int value = 0;
if(value >= 10){
value = value * 0;
}
if(str.charAt(0) == 0)
count0++;
if(str.charAt(0) = 1)
count1++;
}
return count0;
return count1;
return count2;
return count3;
return count4;
return count5;
return count6;
return count7;
return count8;
return count9;
}
countOccurences(int num) should return the number of occurrences of each digit as int[10].
static int[] countOccurences(int num) {
int[] result = new int[10];
for ( ; num > 0; num /= 10)
++result[num % 10];
return result;
}
public static void main(String[] args) {
int input = 7846597;
int[] output = countOccurences(input);
for (int i = 0; i < 10; ++i)
System.out.println(i + " - " + output[i]);
}
output:
0 - 0
1 - 0
2 - 0
3 - 0
4 - 1
5 - 1
6 - 1
7 - 2
8 - 1
9 - 1
This is my code where I used HashTable and stored number as string and count as value. This is optimized code where time complexity is O(n).
// code
import java.util.*;
class Main {
public static void main(String args[]) {
String number = "7846597";
Hashtable<String, Integer> result = new Hashtable<String, Integer>();
for(int i=0; i<number.length(); i++){
String current = "" + number.charAt(i);
if(result.contains(current)) {
int val = result.get(current);
result.put(current, ++val);
} else {
result.put(current, 1);
}
}
System.out.print(result);
}
}
Using int array of size 10 and increment value at index that maps to digit of 0-9.
public static void digitFrequencies(int number) {
int[] arr = new int[10];
for (char ch : String.valueOf(number).toCharArray()) {
int digit = Character.digit(ch, 10);
arr[digit] = arr[digit] + 1;
}
for (int i = 0; i < arr.length; i++) {
System.out.print(i + " - " + arr[i] + " ");
}
}

Java, removing duplicate output from separate lines generated by nested for loops

I am new to java, and I have this program that takes a number between 1 and 10 from a user and displays the multiplication table for that number. Here is the code:
import java.util.Scanner; //importing the scanner library
public class question3 {
public static void main(String[] args){
Scanner keyb = new Scanner(System.in);
System.out.print("Enter an integer between 1 and 10: ");
int userNumber = keyb.nextInt();
while (userNumber <= 0 || userNumber >= 10){
System.out.print("Enter an integer between 1 and 10: ");
userNumber = keyb.nextInt();
}
keyb.close();
for (int counter = 1; counter <= userNumber; counter++){
System.out.print(counter + "\t");
for (int number = 2; number <= userNumber; number++){
System.out.print((counter * number) + "\t");
}
System.out.println(" ");
}
}
}
So if the user enters 4, the output will look like:
1 2 3 4
2 4 6 8
3 6 9 12
4 8 12 16
This works. I need to take the multiplication table and remove any duplicate numbers. So if the user enters 4, the desired output will look like:
1 2 3 4
4 6 8
9 12
16
How can I remove the duplicate output when it only exists in the for loop print statements?
Thanks!
Set<Integer> generatedNumbers = new HashSet<>();
for(int counter = 1; counter <= userNumber; counter+=1)
{
System.out.print((generatedNumbers.contains(counter) ? "" : counter) + "\t");
generatedNumbers.add(counter);
for(int number = 2; number <= userNumber; number+=1)
{
int product = number * counter;
System.out.print((generatedNumbers.contains(product) ? "" : product) + "\t");
generatedNumbers.add(product);
}
System.out.println();
}
You need an extra List<Integer> to check the condition only: (Just need to align the space(DIY))
public class question3 {
public static void main(String[] args) {
Scanner keyb = new Scanner(System.in);
System.out.print("Enter an integer between 1 and 10: ");
int userNumber = keyb.nextInt();
while (userNumber <= 0 || userNumber >= 10) {
System.out.print("Enter an integer between 1 and 10: ");
userNumber = keyb.nextInt();
}
keyb.close();
List<Integer> arr = new ArrayList<Integer>();
for (int counter = 1; counter <= userNumber; counter++) {
if (!arr.contains(counter)) {
System.out.print(counter + "\t");
arr.add(counter);
} else
System.out.println("\t");
for (int number = 2; number <= userNumber; number++) {
if (!arr.contains((counter * number))) {
System.out.print((counter * number) + "\t");
arr.add((counter * number));
} else {
System.out.print("\t");
}
}
System.out.println("\t");
}
}
}
EDIT:
Also utilize do-while loop here to avoid duplicate code to ask input like
System.out.print("Enter an integer between 1 and 10: ");
int userNumber = keyb.nextInt();

How do I print out factors of an input using loops?

Here is my mess of a code. I have to write a program that inputs a positive integer greater than 3. Validate that the integer is in fact greater than 3. Then print all possible pairs of positive integers great than whose product is less than or equal to the number entered.
ex. If 24 is the input.
It would print:
4 = 2 x 2
6 = 2 x 3
8 = 2 x 4
10 = 2 x 5
12 = 2 x 6
14 = 2 x 7
16 = 2 x 8....
9 = 3 x 3
12 = 3 x 4..
24 = 3 x 8...
all the way to
24 = 4 x 6
import java.util.Scanner;
public class Factors {
public static void main(String[] args) {
// Define Variables
Scanner input = new Scanner(System.in);
int i = 0;
int j = 0;
int k = 2;
int product = 0;
// Ask for input/loop
while (i < 3) {
System.out.println("Please enter an integer greater than 3");
i = input.nextInt();
}
while (product < i) {
if (product == i) { j++; k = 2;
for (j = 2; product < i; k++) {
product = j * k;
System.out.println(product + " = " + j + " x " + k);
if (product == i) { j++; k = 2;
}
}
}
}
}
}
public class Factors {
public static void main(String[] args) {
// Define Variables
Scanner input = new Scanner(System.in);
int i = 0;
int product = 0;
// Ask for input/loop
while (i < 3) {
System.out.println("Please enter an integer greater than 3");
i = input.nextInt();
}
for (int j = 2; j < i / 2; j++) {
for (int k = 2; k < i / 2; k++) {
if (j <= k && j * k <= i)
System.out.println(j * k + " = " + j + "*" + k);
}
}
// while (product < i) {
// if (product == i) {
// j++;
// k = 2;
// for (j = 2; product < i; k++) {
// product = j * k;
// System.out.println(product + " = " + j + " x " + k);
// if (product == i) {
// j++;
// k = 2;
// }
// }
// }
// }
}
}

Java - vertical integers and palindrome

I stumbled upon an exercise that asked me to reproduce this (that's the expected output):
11111
3456789012109876543
This is a palindrome (at the bottom) where numbers higher that 9 (double digits) have to be written vertical. This sounds complicated to me, and I needed some help.
This is what I did so far, the palindrome:
class Print {
public static void main(String[] args) {
System.out.println("Insert a number from 1 to 100: ");
int input = Read.anInt();
System.out.println("Insert another number from 1 to 100: ");
int output = Read.anInt();
int a = input;
for (int i = a; i < output; i++){
System.out.print(a);
a++;
}
a = input -1;
for (int j = output; j > a; j--){
System.out.print(output);
output--;
}
}
}
Could you help me by explaining how to make sure numbers higher than 9 will be written vertically?
AdamRice: i mean this:
3456789111119876543
01210
But what I've managed to do so far is this mess:
456789101
0
111
1
121110987654
This is all probably because I'm completely ignoring arrays.
Apologies for being a bit slow. After finally understanding the problem, I think I have a solution.
import java.util.Scanner;
public class VerticalText {
public static void main(String[] args) {
Scanner Read = new Scanner(System.in);
System.out.println("Insert a number from 1 to 100: ");
int start = Read.nextInt();
System.out.println("Insert another number from 1 to 100: ");
int end = Read.nextInt();
String numbers = "";
for(int i = start; i <= end; i++)
{
if(i < 10)
{
numbers += String.format("%02d", i);
}
else
{
numbers += i;
}
}
for(int i = (end-1); i >= start; i--)
{
if(i < 10)
{
numbers += String.format("%02d", i);
}
else
{
numbers += i;
}
}
String row1 = "";
String row2 = "";
char[] chars = numbers.toCharArray();
for(int i = 0; i < chars.length; i++)
{
if(chars[i] == '0')
{
chars[i] = ' ';
}
row1 += chars[i];
i++;
row2 += chars[i];
}
System.out.println(row1);
System.out.println(row2);
}
}
With inputs 5 and 15, it produced the following output:
11111111111
567890123454321098765
Explanation
I build a string of the numbers and if it's less than 10 format it with a leading 0. This extra 0 is just a placeholder. When it comes to printing, we can print a space instead of a zero.

Pascal's triangle positioning

I made a Java program that prints out a pascal triangle, however I can't figure out how to correctly position it.
Program 1
public class Triangle {
public static void main() {
System.out.println("\nTriangle: ");
int row = 11;
long[][] triangle = new long[row][row];
triangle[1][1] = 1;
System.out.print(triangle[1][1] + "\n");
for (int i = 2; i < row; i++) {
for (int n = 1; n < row; n++) {
triangle[i][n] = triangle[i-1][n-1] + triangle[i-1][n];
if (triangle[i][n] > 0) {
System.out.print(triangle[i][n] + " ");
}
}
System.out.println();
}
}
}
Output:
1
1 1
1 2 1
1 3 3 1
Program 2
public class Triangle {
public static void main() {
System.out.println("\nTriangle: ");
int row = 11;
long[][] triangle = new long[row][row];
int x = 1;
while (x < row - 1) {
System.out.print(" ");
x++;
}
triangle[1][1] = 1;
System.out.print(triangle[1][1] + "\n");
for (int i = 2; i < row; i++) {
x = i;
while (x < row - 1) {
System.out.print(" ");
x++;
}
for (int n = 1; n < row; n++) {
triangle[i][n] = triangle[i-1][n-1] + triangle[i-1][n];
if (triangle[i][n] > 0) {
System.out.print(triangle[i][n] + " ");
}
}
System.out.println();
}
}
}
Output:
1
1 1
1 2 1
1 3 3 1
1 4 6 4 1
1 5 10 10 5 1 //(Notice this line is incorrectly positioned)
When the triangle approaches multiple digit numbers, it starts to break down and makes it ugly. Can someone explain how I can display a normal triangle instead of this ugly one?
Dynamic Pascal Triangle generator is here:
import java.io.IOException;
import java.util.Scanner;
public class Main {
static double fact(int n) {
double result = 1;
for (double i = 1; i <= n; i++)
result *= i;
return result;
}
static double combine(int n, int r) {
return ((fact(n)) / (fact(n - r) * fact(r)));
}
static void pascalTriangle(int n) {
int n2 = n;
for (int i = 0; i < n; i++) {
for (int space = 8 * (n2 - 1); space >= 0; space--) {
System.out.printf(" ");
}
for (int j = 0; j <= i; j++) {
System.out.printf("%14.0f", combine(i, j));
System.out.printf(" ");
}
System.out.println();
n2--;
}
}
public static void main(String[] args)
throws IOException, InterruptedException {
#SuppressWarnings("resource")
Scanner sc = new Scanner(System.in);
System.out.print("Enter Number of Lines(n): ");
int n = sc.nextInt();
pascalTriangle(n);
System.out.println("Press any key to exit! ");
sc.nextByte();
}
}
Try this ...
Results:
1
1 1
1 2 1
1 3 3 1
1 4 6 4 1
1 5 10 10 5 1
1 6 15 20 15 6 1
1 7 21 35 35 21 7 1
import java.util.*;
public class HelloWorld {
static int binCoeff(int n, int k) {
int res = 1;
if (k > n - k)
k = n - k;
for (int i = 0; i < k; ++i) {
res *= (n - i);
res /= (i + 1);
}
return res;
}
static void pascalTriangle(int lines) {
for (int i = 0; i < lines; i++) {
for (int j = 0; j <= i; j++)
System.out.print(HelloWorld.binCoeff(i, j) + " ");
System.out.println();
}
}
public static void main(String[] args) {
System.out.println("Results: ");
HelloWorld.pascalTriangle(8);
}
}
/**
* #author Ranjith
*/
public class JavaApplication2 {
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
int i;
int x;
int n = 15; //number of rows
String newLine = System.getProperty("line.separator");
for (i = 0; i < n; i++) { //loop to adjust spacing
x = i;
while (x < n - 1) {
System.out.print(" ");
x++;
}
fib(i); //fibonacci function is called
System.out.print(newLine);
}
}
public static void fib(int num) { //fibonacci function
int[] febo = new int[100];
febo[0] = 0;
febo[1] = 1;
for (int i = 2; i < num; i++) {
febo[i] = febo[i - 1] + febo[i - 2];
}
for (int i = 0; i < num; i++) {
System.out.print(febo[i] + " ");
}
}
}
Output:
0
0 1
0 1 1
0 1 1 2
0 1 1 2 3
0 1 1 2 3 5
0 1 1 2 3 5 8
0 1 1 2 3 5 8 13
0 1 1 2 3 5 8 13 21
0 1 1 2 3 5 8 13 21 34
0 1 1 2 3 5 8 13 21 34 55
0 1 1 2 3 5 8 13 21 34 55 89
0 1 1 2 3 5 8 13 21 34 55 89 144
0 1 1 2 3 5 8 13 21 34 55 89 144 233
You can represent such a triangle as a 2d array, where the elements of the first row and column are equal to one, and all other elements are the sum of the previous element in the row and column.
arr[i][j] = arr[i][j-1] + arr[i-1][j];
Then you can position it in the upper left corner as follows:
1 1 1 1 1 1 1 1 1
1 2 3 4 5 6 7 8
1 3 6 10 15 21 28
1 4 10 20 35 56
1 5 15 35 70
1 6 21 56
1 7 28
1 8
1
Try it online!
public static void main(String[] args) {
int n = 9;
// an array of 'n' rows
int[][] arr = new int[n][];
// iterate over the rows of the array
for (int i = 0; i < n; i++) {
// a row of 'n-i' elements
arr[i] = new int[n - i];
// iterate over the elements of the row
for (int j = 0; j < n - i; j++) {
if (i == 0 || j == 0) {
// elements of the first row
// and column are equal to one
arr[i][j] = 1;
} else {
// all other elements are the sum of the
// previous element in the row and column
arr[i][j] = arr[i][j - 1] + arr[i - 1][j];
}
}
}
// formatted output
for (int[] row : arr) {
for (int el : row) {
// formatting as a number with a trailing space
System.out.printf("%2d ", el); // two-digit number
// System.out.printf("%3d ", el); // three-digit number
// System.out.printf("%4d ", el); // four-digit number
}
System.out.println();
}
}
See also:
• Pascal's triangle 2d array - formatting printed output
• Print Pascal's Triangle
class pascal {
static void main(int n) {
int a[][] = new int[n][n + 1];
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
a[i][j] = 0;
}
}
a[0][1] = 1;
int k = 5;
int p = 0;
for (int i = 1; i < n; i++) {
for (int j = 1; j < n + 1; j++) {
a[i][j] = a[i - 1][j] + a[i - 1][j - 1];
}
}
for (int i = 0; i < a.length; i++) {
for (p = n + -i; p > 0; p--) {
System.out.print(" ");
}
for (int j = 0; j < a[i].length; j++) {
if (a[i][j] != 0) {
System.out.print(a[i][j] + " ");
} else {
System.out.print(" ");
}
}
System.out.println();
}
}
}

Categories