프로그래머스 - 1차 비밀지도

프로그래머스 - 1차 비밀지도

프로그래머스 17681번 문제


@DisplayName("프로그래머스 17681 - [1차] 비밀지도")
class Programmers17681Test {
  Programmers17681 solve = new Programmers17681();

  static Stream<Arguments> solution() {
    return Stream.of(
            Arguments.of(
                    5,
                    new int[]{9, 20, 28, 18, 11},
                    new int[]{30, 1, 21, 17, 28},
                    new String[]{"#####", "# # #", "### #", "#  ##", "#####"}
            ),
            Arguments.of(
                    6,
                    new int[]{46, 33, 33, 22, 31, 50},
                    new int[]{27, 56, 19, 14, 14, 10},
                    new String[]{"######", "###  #", "##  ##", " #### ", " #####", "### # "}
            )
    );
  }

  @MethodSource
  @ParameterizedTest
  void solution(int n, int[] arr1, int[] arr2, String[] expected) throws Exception {
    String[] actual = solve.solution(n, arr1, arr2);
    assertThat(actual).containsExactly(expected);
  }
}


밑바닥부터 만드는 컴퓨팅 시스템에서 배운 컴퓨터의 수의 체계가 바로 떠올랐다.

문제를 유심히 보니 이진문자열을 OR연산 해주면 쉽게 풀릴 것 같았다.

풀이는 다음과 같다.


01001 = 9를 이진수로 변환

11110 = 30을 이진수로 변환

11111 = 두 수를 OR 연산한 결과


예를 들어 OR연산 결과로 10011이 나왔다고 치자.

이때 0은 공백으로, 1은 #으로 변경해주면 답이된다.


public class Programmers17681 {
  public String[] solution(int n, int[] arr1, int[] arr2) {
    return IntStream.range(0, n)
            .mapToObj(i -> String.format("%" + n + "s", toBinaryString((arr1[i] | arr2[i])))
                    .replace('0', ' ')
                    .replace('1', '#'))
            .toArray(String[]::new);
  }
}



© 2022. All rights reserved.