다이아몬드 그리기

출처: xper.org

다음과 같이 다이아몬드 모양의 그림을 출력하는 함수를 만든다.

> diamond 2
   *    
  ***   
   *    
> diamond 3
   *    
  ***   
 *****  
  ***   
   *    
> diamond 4
   *    
  ***   
 *****  
******* 
 *****  
  ***   
   *   

댓글 보기 옵션

원하시는 댓글 전시 방법을 선택한 다음 "설정 저장"을 누르셔서 적용하십시오.

하스켈 버전

diamond n = putStr $ unlines $ map (line.abs) [negate m..m] where
    m = n - 1
    line k = replicate k ' ' ++ replicate (2*n-2*k-1) '*'

자바버전

소스가 깨져서 링크겁니다.
다이아몬드

루비 풀이

얼랭 긴 버전.

-module(diamond).
-include_lib("eunit/include/eunit.hrl").
-export([draw/1, draw_on_console/1]).

odds(N) ->
    odds(N * 2 - 1, []).

odds(1, Acc) ->
    [1|Acc];
odds(I, Acc) ->
    odds(I - 2, [I|Acc]).

odds_test_() ->
    [?_assertMatch([1], odds(1)),
     ?_assertMatch([1,3], odds(2))].

plan(N) ->
    Top = odds(N),
    [Width|Bottom] = lists:reverse(Top),
    {Width, Top ++ Bottom}.

plan_test_() ->
    [?_assertMatch({3, [1,3,1]}, plan(2)),
     ?_assertMatch({5, [1,3,5,3,1]}, plan(3))].

draw_line(N, W) ->
    Space = lists:duplicate((W - N) div 2, $ ),
    Space ++ lists:duplicate(N, $*) ++ Space.

draw_line_test_() ->
    [?_assertMatch("*", draw_line(1, 1)),
     ?_assertMatch(" * ", draw_line(1, 3)),
     ?_assertMatch("  ***  ", draw_line(3, 7))].

draw(Size) ->
    {Width, Design} = plan(Size),
    lists:map(fun(N) -> draw_line(N, Width) end, Design).

draw_on_console(Size) ->
    lists:foreach(fun(Line) -> io:format("~s~n", [Line]) end, draw(Size)).

http://colus.egloos.com/3376757

생각보다 어렵네요.

c

#include <stdio.h>

void triangle(int nfields, int beg, int end, int step)
{
  int i;
  
  for (; beg != end + step; beg += step) {
    printf("%*s", (nfields - beg) / 2, "");
    for (i = 0; i < beg; i++)
      putchar('*');
    printf("\n");
  }
}

void diamond(int n)
{
  int nfields = 2 * n - 1;
  triangle(nfields, 1, nfields, 2);
  triangle(nfields, nfields -2, 1, -2);
}

int main(void)
{
  diamond(2);
  diamond(3);
  diamond(4);
  return 0;
}

루비 늅늅

class Fixnum;def diamond;(-self+1..self-1).each { |i| puts " "*i.abs+"*"*(2*(self-i.abs)-1)};end;end
2.diamond
3.diamond
4.diamond