Java Problems: Building a Number Pyramid

Asked 2 years ago, Updated 2 years ago, 64 views

Hello, I'm asking you a question because I didn't like my code while doing my assignment.

The questions you gave me are as follows.

Develop a JAVA-program that does the following job:
    Your program shall ask the user for the input of some integer num. 
    Subsequent to the input, your program shall print a pyramid like
    described below.
    Each line consists of three parts.
    The first part comprises some spaces for formatted output; 
    the second part, some leading numbers, such as 3 2 1 on line 3; 
    and the last part, some ending numbers, such as 2 3 on line 3.
    So, the output should look as follows:

    ex) input: 5

        1
       212
      32123
     4321234
    543212345

 

This is my code that I submitted for the assignment.

package kr.co.hashcode;

import java.util.Scanner;

public class Question4 {
    public static void main(String[] args) {
        int counter;
        int i, j, k;

        Scanner scan = new Scanner(System.in);

        System.out.printf("Input integer value: ");
        counter = scan.nextInt();        
        System.out.printf("\n");
        scan.close();

        for (i = 0; i < counter; i++) {
            for (j = 0; j < counter-i-1; j++) {
                System.out.printf(" ");
            }
            k = i + 1;
            for (j = 0; j < i; j++) {
                System.out.printf("%d", k--);
            }
            k = 1;
            for (j = 0; j < i+1; j++) {
                System.out.printf("%d", k++);
            }
            System.out.printf("\n");
        }
    }
}

 

It works well, but I don't remember well because I learned it before returning to school, but I don't like it because it's a code with O(n)()(?) time complexity. I submitted the assignment today, but can I write this code more simply?

java algorithm big-o

2022-09-22 20:16

2 Answers

Java

public class Main {
    public static void main(String[] args) {
        int n = 7;
        String line = "";
        for(int i = 1; i <= n; i++) {
            line = i == 1 ? String.valueOf(i) : String.valueOf(i) + line + String.valueOf(i);
            //String.format("%3s%s", "", "12321"); //"   12321"
            String reg = i == n ? "%s%s" :"%" + String.valueOf(n - i) + "s%s";
            System.out.println(String.format(reg, "", line));
        }
    }

}

      1
     212
    32123
   4321234
  543212345
 65432123456
7654321234567


2022-09-22 20:16

It's Python.

n = 7
line = ''
for i in range(1, n + 1):
    line = str(i) if i == 1 else str(i) + line + str(i)
    print(' ' * (n - i) + line)


      1      
     212     
    32123    
   4321234   
  543212345  
 65432123456 
7654321234567


2022-09-22 20:16

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.