웹사이트 검색

Java의 피라미드 패턴 프로그램


패턴 프로그램은 인터뷰 대상자의 논리적 사고 능력을 파악하기 위해 인터뷰에서 많이 사용된다. 피라미드 패턴은 매우 인기가 있으며 생성된 방식에 대한 논리를 얻으면 동일한 결과를 얻기 위한 코드를 작성하는 것이 쉬운 작업입니다.

Java의 피라미드 패턴 프로그램

숫자의 피라미드 패턴

첫 번째 패턴을 보면 모든 행에는 같은 횟수만큼 인쇄된 같은 숫자가 포함되어 있습니다. 그러나 모든 행에는 카운트가 "rows-i\인 선행 공백이 있습니다. 이 패턴을 인쇄하는 프로그램을 살펴보겠습니다.

package com.journaldev.patterns.pyramid;

import java.util.Scanner;

public class PyramidPattern {

	private static void printPattern1(int rows) {
		// for loop for the rows
		for (int i = 1; i <= rows; i++) {
			// white spaces in the front of the numbers
			int numberOfWhiteSpaces = rows - i;

			//print leading white spaces
			printString(" ", numberOfWhiteSpaces);

			//print numbers
			printString(i + " ", i);

			//move to next line
			System.out.println("");
		}
	}

	//utility function to print string given times
	private static void printString(String s, int times) {
		for (int j = 0; j < times; j++) {
			System.out.print(s);
		}
	}

	public static void main(String[] args) {

		Scanner scanner = new Scanner(System.in);
		System.out.println("Please enter the rows to print:");
		int rows = scanner.nextInt();
		// System.out.println("Rows = "+rows);
		scanner.close();

		System.out.println("Printing Pattern 1\n");
		printPattern1(rows);

	}

}

일반적인 문자열 인쇄 작업을 위한 유틸리티 함수를 만들었습니다. 프로그램을 재사용 가능한 짧은 함수로 나눌 수 있다면 프로그램을 작성하려고 할 뿐만 아니라 품질과 재사용성을 확인하고 싶어한다는 것을 보여줍니다. 위의 프로그램을 실행하면 다음과 같은 결과를 얻습니다.

Please enter the rows to print:
9
Printing Pattern 1

        1 
       2 2 
      3 3 3 
     4 4 4 4 
    5 5 5 5 5 
   6 6 6 6 6 6 
  7 7 7 7 7 7 7 
 8 8 8 8 8 8 8 8 
9 9 9 9 9 9 9 9 9 

증가하는 숫자의 피라미드 패턴

다음은 패턴 2를 인쇄하는 기능입니다. 주목해야 할 요점은 선행 공백의 수이며 숫자가 증가하는 순서로 인쇄됩니다.

/**
 * 
 * Program to print below pyramid structure
 *      1         
       1 2        
      1 2 3       
     1 2 3 4      
    1 2 3 4 5     
   1 2 3 4 5 6    
  1 2 3 4 5 6 7   
 1 2 3 4 5 6 7 8  
1 2 3 4 5 6 7 8 9 
*/
private static void printPattern2(int rows) {
	// for loop for the rows
	for (int i = 1; i <= rows; i++) {
		// white spaces in the front of the numbers
		int numberOfWhiteSpaces = rows - i;

		//print leading white spaces
		printString(" ", numberOfWhiteSpaces);

		//print numbers
		for(int x = 1; x<=i; x++) {
			System.out.print(x+" ");
		}

		//move to next line
		System.out.println("");
	}
}

문자 피라미드

이것은 정말 간단한 것입니다. 계산이나 조작 없이 문자를 인쇄하기만 하면 됩니다.

/**
 * Program to print following pyramid structure
        *         
       * *        
      * * *       
     * * * *      
    * * * * *     
   * * * * * *    
  * * * * * * *   
 * * * * * * * *  
* * * * * * * * * 

*/
private static void printPattern3(int rows) {
	// for loop for the rows
	for (int i = 1; i <= rows; i++) {
		// white spaces in the front of the numbers
		int numberOfWhiteSpaces = rows - i;

		//print leading white spaces
		printString(" ", numberOfWhiteSpaces);

		//print character
		printString("* ", i);

		//move to next line
		System.out.println("");
	}
}

피라미드 패턴 4 프로그램

/**
* 
*               1 
              1 2 1 
            1 2 3 2 1 
          1 2 3 4 3 2 1 
        1 2 3 4 5 4 3 2 1 
      1 2 3 4 5 6 5 4 3 2 1 
    1 2 3 4 5 6 7 6 5 4 3 2 1 
  1 2 3 4 5 6 7 8 7 6 5 4 3 2 1 
1 2 3 4 5 6 7 8 9 8 7 6 5 4 3 2 1 
*/

private static void printPattern4(int rows) {
	// for loop for the rows
	for (int i = 1; i <= rows; i++) {
		// white spaces in the front of the numbers
		int numberOfWhiteSpaces = (rows-i)*2;

		//print leading white spaces
		printString(" ", numberOfWhiteSpaces);

		//print numbers
		for(int x=1; x0; j--) {
			System.out.print(j+" ");
		}

		//move to next line
		System.out.println("");
	}
}

모든 행에는 2*r-1 숫자가 있습니다. 따라서 숫자를 인쇄하기 전에 (rows-i)*2 공백을 갖게 됩니다. 그런 다음 숫자는 1에서 "i\로 시작하고 다시 1로 시작합니다. 숫자를 인쇄하는 논리는 이를 달성하기 위해 두 개의 for-loop가 필요합니다.

Java의 피라미드 패턴 5 프로그램

/**
 * 
 *                9 
                8 9 8 
              7 8 9 8 7 
            6 7 8 9 8 7 6 
          5 6 7 8 9 8 7 6 5 
        4 5 6 7 8 9 8 7 6 5 4 
      3 4 5 6 7 8 9 8 7 6 5 4 3 
    2 3 4 5 6 7 8 9 8 7 6 5 4 3 2 
  1 2 3 4 5 6 7 8 9 8 7 6 5 4 3 2 1 
*/
private static void printPattern5(int rows) {
	// for loop for the rows
	for (int i = rows; i >= 1; i--) {
		// white spaces in the front of the numbers
		int numberOfWhiteSpaces = i*2;

		//print leading white spaces
		printString(" ", numberOfWhiteSpaces);

		//print numbers
		for(int x=i; x=i; j--) {
			System.out.print(j+" ");
		}

		//move to next line
		System.out.println("");
	}
}

문자의 역피라미드 패턴

다음은 역피라미드 프로그램의 코드 스니펫입니다.

/**
 * 
* * * * * * * * * 
 * * * * * * * * 
  * * * * * * * 
   * * * * * * 
    * * * * * 
     * * * * 
      * * * 
       * * 
        * 
 */
private static void printPattern6(int rows) {
	// for loop for the rows
	for (int i = rows; i >= 1; i--) {
		// white spaces in the front of the numbers
		int numberOfWhiteSpaces = rows - i;

		//print leading white spaces
		printString(" ", numberOfWhiteSpaces);

		//print character
		printString("* ", i);

		//move to next line
		System.out.println("");
	}
}

숫자의 역 피라미드 패턴

숫자로 이루어진 역피라미드 패턴의 예를 살펴보겠습니다.

	/**
	 * 
9 9 9 9 9 9 9 9 9 
 8 8 8 8 8 8 8 8 
  7 7 7 7 7 7 7 
   6 6 6 6 6 6 
    5 5 5 5 5 
     4 4 4 4 
      3 3 3 
       2 2 
        1 
	 */
private static void printPattern7(int rows) {
	// for loop for the rows
	for (int i = rows; i >= 1; i--) {
		// white spaces in the front of the numbers
		int numberOfWhiteSpaces = rows - i;

		//print leading white spaces
		printString(" ", numberOfWhiteSpaces);

		//print character
		printString(i+" ", i);

		//move to next line
		System.out.println("");
	}
}

결론

피라미드 패턴에는 여러 유형이 있습니다. 가장 중요한 점은 숫자와 공백이 구성되는 패턴을 이해하는 것입니다. 패턴에 대해 명확해지면 Java 또는 다른 프로그래밍 언어로도 코드를 쉽게 작성할 수 있습니다. 특정 패턴 프로그램을 찾고 있는 경우 알려주시면 도와드리겠습니다.

추가 자료

Java 프로그래밍 인터뷰 질문

GitHub 리포지토리에서 전체 코드와 더 많은 프로그래밍 예제를 확인할 수 있습니다.