カード配り問題(10分プログラミング)

"Latest topics > カード配り問題 – outsider reflex" や "10分プログラミング – hogehoge" を見て、自分も "10分でコーディング|プログラミングに自信があるやつこい!!" をやってみた。

カード枚数が足りない場合を考えていたら20分かかってしまった・・・

var deal = function(numPlayers, cards) {
    var result = [];
    var len = Math.floor(cards.length / numPlayers) * numPlayers;
    for (var i=0; i<numPlayers; i++) {
        result.push('');
    }
    for (var i=0; i<len; i++) {
        result[i % numPlayers] += cards[i];
    }
    return result;
};

console.log(deal(3, "123123123"));
console.log(deal(4, "123123123"));
console.log(deal(2, "123123123"));
console.log(deal(6, "012345012345012345"));
console.log(deal(4, "111122223333"));
console.log(deal(1, "012345012345012345"));
console.log(deal(6, "01234"));
console.log(deal(2, ""));

追記:Gauche で作ってみた。

(use srfi-1)
(use gauche.sequence)

(define (deal num-players cards)
  (let* ((l-cards (string->list cards))
         (util-cards (drop-right l-cards (remainder (length l-cards) num-players))))
        (define (iter i p)
          (if (= i 0)
              p
              (iter (- i 1)
                    (cons
                      (map cadr (filter
                                  (lambda (x) (= (remainder (car x) num-players) (- i 1)))
                                  (map-with-index list util-cards)))
                      p))))
        (iter num-players '())))

(map list->string (deal 3 "123123123"))
(map list->string (deal 4 "123123123"))
(map list->string (deal 2 "123123123"))
(map list->string (deal 6 "012345012345012345"))
(map list->string (deal 4 "111122223333"))
(map list->string (deal 1 "012345012345012345"))
(map list->string (deal 6 "01234"))
(map list->string (deal 2 ""))

実行結果

gosh> ("111" "222" "333")
gosh> ("12" "23" "31" "12")
gosh> ("1321" "2132")
gosh> ("000" "111" "222" "333" "444" "555")
gosh> ("123" "123" "123" "123")
gosh> ("012345012345012345")
gosh> ("" "" "" "" "" "")
gosh> ("" "")
コメント

この記事へのコメントはまだありません。

Top