다이아 모양 별 만들기

코테연습|2021. 5. 25. 22:37

자바 연습용으로... 최대 n칸의 다이아모양 별을 찍는 코드를 짰다.

 

//처음에 내가 짠 코드
package loopexample;

public class Boksup{
  public static void main(String[] args){
    int i;
    int j;
    int st1;
    int st2;
    int sp1;
    int sp2;

    for(i=0; i<4; i++){
      st1 = 2*i + 1;
      sp1 = 3-i;
      for(j=0; j<sp1; j++){
        System.out.print(" ");
      }
      for(j=0; j<st1; j++){
        System.out.print("*");
      }
      System.out.println();
    }
  for(i=0; i<3; i++){
    st2 = 5 - 2*i;
    sp2 = i+1;
    for(j=0; j<st2; j++){
      System.out.print(" ");
    }
    for(j=0; j<st2; j++){
      System.out.print("*");
    }
    System.out.println();
  }
  }
}

 

for문 안에서 한 번만 쓰이고 말 변수는 굳이 중괄호 밖에서 선언해줄 필요는 없다.

마찬가지로 starcount(이하 st)와 spacecount(이하 sp)도 1번 2번으로 나눠줄 필요 없음.

 

//약간 고쳐진 코드
package loopexample;

public class Boksup{
  public static void main(String[] args){
      for(i=0; i<4; i++){
      st = 2*i + 1;
      sp = 3-i;
      for(j=0; j<sp; j++){
        System.out.print(" ");
      }
      for(j=0; j<st; j++){
        System.out.print("*");
      }
      System.out.println();
    }
  for(i=0; i<3; i++){
    st = 5 - 2*i;
    sp = i+1;
    for(j=0; j<st; j++){
      System.out.print(" ");
    }
    for(j=0; j<st; j++){
      System.out.print("*");
    }
    System.out.println();
  }
  }
}

결과

내가 짠 코드는 i = 0, 1, 2, 3 내에서만 정상적으로 작동하는데, 

달라지는 i 범위에 따라 같은 규칙으로 생겨나는 코드도 한 번 만들어 보고 싶었다.

 

package loopexample;

public class Boksup{
  public static void main(String[] args){

    int lc = 8;

      for(i=0; i<lc; i++){
      st = 2*i + 1;
      sp = lc-i;
      for(j=0; j<sp; j++){
        System.out.print(" ");
      }
      for(j=0; j<st; j++){
        System.out.print("*");
      }
      System.out.println();
    }
  for(i=0; i<lc-1; i++){
    st = 2*lc - 3 - 2*i;
    sp = i+1;
    for(j=0; j<sp; j++){
      System.out.print(" ");
    }
    for(j=0; j<st; j++){
      System.out.print("*");
    }
    System.out.println();
  }
  }
}

그래서 맹금

오랜만에 점화식같은것까지 적어가면서 2번째 큰 for문에서 lc를 변수로 하는 식을 찾으려고 했는데

보니까 그냥 계차수열이었어서 약간 허무했다ㅋㅋㅋ 그래도 풀어냄~~~ 뿌듯!

'코테연습' 카테고리의 다른 글

[프로그래머스] 짝수와 홀수  (0) 2022.02.09
[프로그래머스] 직사각형 별찍기  (0) 2022.02.09
[LeetCode] Two Sum  (0) 2021.08.31

댓글()