청기백기 명령문 generator

highwind의 이미지

교회에서 소풍을가서 추억의 게임 청기백기를 하기로 하였습니다.
미리 올려 내려 명령을 손으로 쓰기도 그렇고 즉흥적으로 명령하기도 모하고 해서
프로그램을 짜서 명령문을 랜덤으로 만들게 해보았습니다.
Python과 ruby로 짜보았습니다.

Python 3.0:

import random
data = [["청기", "백기", "둘다"], ["올", "내"], ["려","려","리지마"]]
for i in range(50):
    print(*[random.choice(d) for d in data], sep='')

Ruby:

data = [["청기", "백기", "둘다"], ["올", "내"], ["려","려","리지마"]]
50.times {puts data.collect {|d| d[rand(d.length)]}.join}

"려"가 두번 들어간 이유는 하지마라는 명령보다 하라는 명령을 더 많이 출력하고 싶어서 입니다.

ps.
강좌에 올리긴 좀 그런가??

Forums: 
ldgood의 이미지

심플하면서도 괜찮은듯
이터레이션 엘리먼트 d 가 중복사용되어서 list generator에서 2초정도 헷갈렸다능 ㅎㅎ
------------------------------
모든것은 모든것에 잇닿아 있다.


------------------------------
모든것은 모든것에 잇닿아 있다.

highwind의 이미지

앗 오타네요.. 수정 하였습니다.

=====================================
http://timothylive.net

=====================================
http://timothylive.net

aero의 이미지

.
.
.
.
.
Perl 5

use 5.010;
my @data = ([qw/청기 백기 둘다/],[qw/올 내/],[qw/려 려 리지마/]);
say map { @$_[rand @$_] } @data for 1..50;

Perl 6

my @data = [<청기 백기 둘다>],[<올 내>],[<려 려 리지마>];
say map {$_.pick(1)}, @data for 1..50;
jg의 이미지

출력할 때 약간의 지연 현상을 줘서 긴장감을 살짝 더 유발하도록 고쳐봤습니다. :-)
여기에 올라온 다른 것들도 테스트 해보고 싶은데 제 컴퓨터에는 python2.6과 perl밖에 없네요.

#!/usr/bin/env perl
 
use Time::HiRes qw(usleep);
use strict;
 
package DelayWord;
use base qw(Class::Accessor::Fast);
__PACKAGE__->mk_accessors( qw(word) );
 
sub new {
    my $class = shift;
    return bless { 'word' => shift }, $class;
}
 
sub print {
    my ( $this, $surfix ) = @_;
    local $| = 1;
    $surfix = ' ' unless defined $surfix;
    print $this->word.$surfix;
    ::usleep( ( 30 + rand( 70 ) ) * 10e2 );
}
 
package DelayWord::Direction;
use base 'DelayWord';
sub print {
    $_[0]->SUPER::print( '' );
}
 
package DelayWord::Command;
use base 'DelayWord';
__PACKAGE__->mk_accessors( qw(continue) );
 
sub new {
    my $class = shift;
    return bless { 'word' => shift,
		   'continue' => shift,
    }, $class;
}
 
sub print {
    my $this = shift;
    $this->SUPER::print( ( $this->continue ) ? " " : "\n" );
    ::usleep( ( 21 + rand(170) ) * 10e3 );
}
 
package main;
 
use warnings;
use strict;
 
my @data;
for my $args ( ( map { [ 0, "DelayWord", $_  ] } qw(청기 백기 둘다)     ),
               ( map { [ 1, "DelayWord::Direction", $_ ] } qw(올 내)    ),
               ( map { [ 2, "DelayWord::Command", @$_ ] }
                 ( ( ["려", ] ) x 3, ( ["리지마", ] ) x 2,
                   ["리지 말고", "continue" ] )                         ) ) {
    push @{ $data[ shift @$args ] }, (shift @$args)->new( @$args );
}
 
for ( 1..50 ) {
    for my $part ( @data ) {
	@$part[ rand scalar( @$part) ]->print;
    }
}

just for fun 인 거 아시죠? ^^

$Myoungjin_JEON=@@=qw^rekcaH lreP rehtonA tsuJ^;$|++;{$i=$like=pop@@;unshift@@,$i;$~=18-length$i;print"\r[","~"x abs,(scalar reverse$i),"~"x($~-abs),"]"and select$good,$day,$mate,1/$~for 0..$~,-$~+1..-1;redo}

aero의 이미지

실행해보니 실제 게임하는 기분이네요

근데 사용하신 Class::Accessor::Fast 모듈은 따로 new 메소드를 재정의 하지 않아도 됩니다.

package DelayWord;
use base qw(Class::Accessor::Fast);
__PACKAGE__->mk_accessors( qw(word) );
...

이렇게 하셨으면 객체를 생성할 때
DelayWord->new( { word => $word } );
와 같이 mk_accessors에 정의한 파라메터들을 담은 해시를 익명해시 형태로 넘겨주면 됩니다.
이건 Class::Accessor 모듈의 다음과 같은 new 메소드 정의를 보시면 이해가 가실 듯..
sub new {
    my($proto, $fields) = @_;
    my($class) = ref $proto || $proto;
 
    $fields = {} unless defined $fields;
 
    # make a copy of $fields.
    bless {%$fields}, $class;
}

jg의 이미지

아 그렇군요. 하나 배우고 갑니다. ^^

수정한 버전입니다. 그리고 위에서 "리고" 명령어를 빼먹었네요. ^^;

#!/usr/bin/env perl
 
use strict;
use Time::HiRes qw(usleep);
 
 
package DelayWord;
use base qw(Class::Accessor::Fast);
__PACKAGE__->mk_accessors( qw(word) );
 
sub print {
    my ( $this, $surfix ) = @_;
    local $| = 1;
    $surfix = ' ' unless defined $surfix;
    print $this->word.$surfix;
    ::usleep( ( 30 + rand( 70 ) ) * 10e2 );
}
 
package DelayWord::Direction;
use base 'DelayWord';
sub print {
    $_[0]->SUPER::print( '' );
}
 
package DelayWord::Command;
use base 'DelayWord';
__PACKAGE__->mk_accessors( qw(continue) );
 
sub print {
    my $this = shift;
    $this->SUPER::print( ( $this->continue ) ? " " : "\n" );
    ::usleep( ( 21 + rand(170) ) * 10e3 );
}
 
package main;
 
use warnings;
use strict;
 
my @data;
for my $args ( ( map { [ 0, 'DelayWord',
			 'word' => $_ ] } qw(청기 백기 둘다)		),
	       ( map { [ 1, 'DelayWord::Direction',
			 'word' => $_ ] } qw(올 내)			),
	       ( map { [ 2, 'DelayWord::Command', 'word', @$_ ] }
		 ( ( ["려", ] ) x 3, ( ["리지마", ] ) x 2,
		   ["리고", "continue" => "t", ],
		   ["리지 말고", "continue" => "t" ] )			) ) {
    push @{ $data[ shift @$args ] }, (shift @$args)->new( { @$args } );
}
 
for ( 1..50 ) {
    for my $part ( @data ) {
	@$part[ rand scalar( @$part) ]->print();
    }
}

$Myoungjin_JEON=@@=qw^rekcaH lreP rehtonA tsuJ^;$|++;{$i=$like=pop@@;unshift@@,$i;$~=18-length$i;print"\r[","~"x abs,(scalar reverse$i),"~"x($~-abs),"]"and select$good,$day,$mate,1/$~for 0..$~,-$~+1..-1;redo}

jg의 이미지

xvidcap을 처음 써보는군요. youtube에 한 번 올려봤습니다.

$Myoungjin_JEON=@@=qw^rekcaH lreP rehtonA tsuJ^;$|++;{$i=$like=pop@@;unshift@@,$i;$~=18-length$i;print"\r[","~"x abs,(scalar reverse$i),"~"x($~-abs),"]"and select$good,$day,$mate,1/$~for 0..$~,-$~+1..-1;redo}

redneval의 이미지

Haskell 버전입니다.

-- `cabal install utf8-prelude' to compile this code.
import Prelude ()
import UTF8Prelude
import System.Random
command = [["청기", "백기", "둘다"], ["올", "내"], ["려","려","리지마"]]
combine (x:xs) = if xs == [] then x else [a++b | a <- x, b <- combine xs]
rand seed list = map (list !!) $ randomRs (0, (length list) - 1) seed
main = getStdGen >>= \s -> mapM putStrLn $ take 50 $ rand s $ combine command

--------------------Signature--------------------
Light a candle before cursing the darkness.

yong27의 이미지

join 메쏘드에는 대괄호를 쓰지 않아도 됩니다. generator expression.

좀더 다이나믹하게~

highwind의 이미지

이렇게 update했습니다.
.
.
.

data = [["청기", "백기", "둘다"], ["올", "내"], ["려","려","리지마"]]
 
for i in range(50):
    print(*[random.choice(d) for d in data], sep='')

=====================================
http://timothylive.net

=====================================
http://timothylive.net

neocoin의 이미지

data = [["청기", "백기", "둘다"], ["올", "내"], ["려","려","리지마"]]
50.times{puts data.map{|d| d.sort_by{rand}[0]}*''}

lateau의 이미지

data = [["청기", "백기", "둘다"], ["올", "내"], ["려","려","리지마"]]
ARGV[0].to_i.times{puts data.map{|d| d.sort_by{rand}[0]}*''}

실행시 수를 지정할 수 있도록 수정했습니다. :)

- Why don't you come in OpenSolaris? I hope you come together.

--
I think to myself...what a emerging world.

neocoin의 이미지

data = [["청기", "백기", "둘다"], ["올", "내"], ["려","려","리지마"]]
(ARGV[0]||10).to_i.times{puts data.map{|d| d.sort_by{rand}[0]}*''}
lateau의 이미지

감사합니다! :)

- Why don't you come in OpenSolaris? I hope you come together.

--
I think to myself...what a emerging world.

solbatso의 이미지

청기 올려
청기 내려
청기 올리지마
청기 내리지마
백기 올려
백기 내려
백기 올리지마
백기 내리지마
둘다 올려
둘다 내려
둘다 올리지마
둘다 내리지마

는 되는데

청기 올리고 백기 내리지마
청기 올리지말고 백기 올려

같은건 안되네요

["려","려","리지마"] -> ["려", "리고", "리지말고", "리지마"]

로 하셔야겠네요.. 주절..
acc92의 이미지

char* data1[] = { (char*)"청기",(char*)"백기",(char*)"둘다"};
	char* data2[] = { (char*)"올",(char*)"내"};
	char* data3[] = { (char*)"려",(char*)"려",(char*)"리지마"};
 
	int i,d1,d2,d3;
	srand(time(NULL)); 
	for(i=0;i<10;i++)
	{
		d1 = rand()%3;
		d2 = rand()%2;
		d3 = rand()%3;
 
		//printf("d1=%d   d2=%d  d3=%d\n",d1,d2,d3);
		printf("%s %s %s \n",data1[d1],data2[d2],data3[d3]);
		sleep(1);
	}

방가워요

lateau의 이미지

class Flags {
    public static void main(String[] args) {
        String[] data = {
            "청기", "백기", "둘다",
            "올", "내",
            "려", "려", "리지마"
        };
 
        java.util.Random rand = new java.util.Random();
        for (int i = 0; i < 50; i++) {
            int d1 = rand.nextInt(3);
            int d2 = rand.nextInt(2) + 3;
            int d3 = rand.nextInt(3) + 5;
 
            System.out.println(data[d1] + data[d2] + data[d3]);
        }
    }
}

- Why don't you come in OpenSolaris? I hope you come together. class Flags {

--
I think to myself...what a emerging world.

댓글 달기

Filtered HTML

  • 텍스트에 BBCode 태그를 사용할 수 있습니다. URL은 자동으로 링크 됩니다.
  • 사용할 수 있는 HTML 태그: <p><div><span><br><a><em><strong><del><ins><b><i><u><s><pre><code><cite><blockquote><ul><ol><li><dl><dt><dd><table><tr><td><th><thead><tbody><h1><h2><h3><h4><h5><h6><img><embed><object><param><hr>
  • 다음 태그를 이용하여 소스 코드 구문 강조를 할 수 있습니다: <code>, <blockcode>, <apache>, <applescript>, <autoconf>, <awk>, <bash>, <c>, <cpp>, <css>, <diff>, <drupal5>, <drupal6>, <gdb>, <html>, <html5>, <java>, <javascript>, <ldif>, <lua>, <make>, <mysql>, <perl>, <perl6>, <php>, <pgsql>, <proftpd>, <python>, <reg>, <spec>, <ruby>. 지원하는 태그 형식: <foo>, [foo].
  • web 주소와/이메일 주소를 클릭할 수 있는 링크로 자동으로 바꿉니다.

BBCode

  • 텍스트에 BBCode 태그를 사용할 수 있습니다. URL은 자동으로 링크 됩니다.
  • 다음 태그를 이용하여 소스 코드 구문 강조를 할 수 있습니다: <code>, <blockcode>, <apache>, <applescript>, <autoconf>, <awk>, <bash>, <c>, <cpp>, <css>, <diff>, <drupal5>, <drupal6>, <gdb>, <html>, <html5>, <java>, <javascript>, <ldif>, <lua>, <make>, <mysql>, <perl>, <perl6>, <php>, <pgsql>, <proftpd>, <python>, <reg>, <spec>, <ruby>. 지원하는 태그 형식: <foo>, [foo].
  • 사용할 수 있는 HTML 태그: <p><div><span><br><a><em><strong><del><ins><b><i><u><s><pre><code><cite><blockquote><ul><ol><li><dl><dt><dd><table><tr><td><th><thead><tbody><h1><h2><h3><h4><h5><h6><img><embed><object><param>
  • web 주소와/이메일 주소를 클릭할 수 있는 링크로 자동으로 바꿉니다.

Textile

  • 다음 태그를 이용하여 소스 코드 구문 강조를 할 수 있습니다: <code>, <blockcode>, <apache>, <applescript>, <autoconf>, <awk>, <bash>, <c>, <cpp>, <css>, <diff>, <drupal5>, <drupal6>, <gdb>, <html>, <html5>, <java>, <javascript>, <ldif>, <lua>, <make>, <mysql>, <perl>, <perl6>, <php>, <pgsql>, <proftpd>, <python>, <reg>, <spec>, <ruby>. 지원하는 태그 형식: <foo>, [foo].
  • You can use Textile markup to format text.
  • 사용할 수 있는 HTML 태그: <p><div><span><br><a><em><strong><del><ins><b><i><u><s><pre><code><cite><blockquote><ul><ol><li><dl><dt><dd><table><tr><td><th><thead><tbody><h1><h2><h3><h4><h5><h6><img><embed><object><param><hr>

Markdown

  • 다음 태그를 이용하여 소스 코드 구문 강조를 할 수 있습니다: <code>, <blockcode>, <apache>, <applescript>, <autoconf>, <awk>, <bash>, <c>, <cpp>, <css>, <diff>, <drupal5>, <drupal6>, <gdb>, <html>, <html5>, <java>, <javascript>, <ldif>, <lua>, <make>, <mysql>, <perl>, <perl6>, <php>, <pgsql>, <proftpd>, <python>, <reg>, <spec>, <ruby>. 지원하는 태그 형식: <foo>, [foo].
  • Quick Tips:
    • Two or more spaces at a line's end = Line break
    • Double returns = Paragraph
    • *Single asterisks* or _single underscores_ = Emphasis
    • **Double** or __double__ = Strong
    • This is [a link](http://the.link.example.com "The optional title text")
    For complete details on the Markdown syntax, see the Markdown documentation and Markdown Extra documentation for tables, footnotes, and more.
  • web 주소와/이메일 주소를 클릭할 수 있는 링크로 자동으로 바꿉니다.
  • 사용할 수 있는 HTML 태그: <p><div><span><br><a><em><strong><del><ins><b><i><u><s><pre><code><cite><blockquote><ul><ol><li><dl><dt><dd><table><tr><td><th><thead><tbody><h1><h2><h3><h4><h5><h6><img><embed><object><param><hr>

Plain text

  • HTML 태그를 사용할 수 없습니다.
  • web 주소와/이메일 주소를 클릭할 수 있는 링크로 자동으로 바꿉니다.
  • 줄과 단락은 자동으로 분리됩니다.
댓글 첨부 파일
이 댓글에 이미지나 파일을 업로드 합니다.
파일 크기는 8 MB보다 작아야 합니다.
허용할 파일 형식: txt pdf doc xls gif jpg jpeg mp3 png rar zip.
CAPTCHA
이것은 자동으로 스팸을 올리는 것을 막기 위해서 제공됩니다.