Skip to content

Instantly share code, notes, and snippets.

@bayashi
Created August 4, 2012 12:29
Show Gist options
  • Save bayashi/3257175 to your computer and use it in GitHub Desktop.
Save bayashi/3257175 to your computer and use it in GitHub Desktop.
この中から最初に見つけた言葉3つがあなたが人生でほしいもの。なんだって。
#!/usr/bin/perl
use strict;
use warnings;
use utf8;
use Encode qw/encode_utf8/;
my @list = split //, 'あいうえおかきくけこさしすせそたちつてとなにぬねのはひふへほまみむめもやゆよらりるれろわをんがぎぐげござじずぜぞだぢづでどばびぶべぼぱぴぷぺぽ';
my $words = [qw/
おかね げんきん たいきん
ゆめ きぼう じゆう せいこう
あい こいびと れんあい ともだち しんゆう
じかん ちい けんこう びぼう
ちから つよさ おもいやり やさしさ
/];
my $max_x = 12;
my $max_y = 12;
my $vertical_rate = 20; # %
#----- main
my $MATRIX = [];
my $FIX_MATRIX = [];
for my $i (0..$max_x-1) {
for my $j (0..$max_y-1) {
$MATRIX->[$i][$j] = $list[int(rand(scalar @list))];
}
}
for my $word (@{$words}) {
layout($word);
}
# show result
for my $i (0..$max_x-1) {
for my $j (0..$max_y-1) {
print encode_utf8("$MATRIX->[$i][$j] ");
}
print "\n";
}
sub layout {
my $word = shift;
while (1) {
my $way = 0;
my $x = int(rand $max_x);
my $y = int(rand $max_y);
if (rand(100) < $vertical_rate) {
# vertical
next if !can_layout($word, 1, $x, $y);
layout_word($word, 1, $x, $y);
}
else {
next if !can_layout($word, 0, $x, $y);
layout_word($word, 0, $x, $y);
}
return;
}
}
sub layout_word {
my ($word, $way, $x, $y) = @_;
my $length = length $word;
if ($way == 1) {
# vertical
my $y2 = $y + $length;
my $count = 0;
for my $i ($y..$y2-1) {
$MATRIX->[$x][$i] = [split(//, $word)]->[$count];
$FIX_MATRIX->[$x][$i] = 1;
$count++;
}
}
else {
my $x2 = $x + $length;
my $count = 0;
for my $i ($x..$x2-1) {
$MATRIX->[$i][$y] = [split(//, $word)]->[$count];
$FIX_MATRIX->[$i][$y] = 1;
$count++;
}
}
}
sub can_layout {
my ($word, $way, $x, $y) = @_;
my $length = length $word;
if ($way == 1) {
# vertical
my $y2 = $y + $length;
return if $y2 >= $max_y-1;
for my $i ($y..$y2-1) {
return if $FIX_MATRIX->[$x][$i];
}
return 1;
}
else {
my $x2 = $x + $length;
return if $x2 >= $max_x-1;
for my $i ($x..$x2-1) {
return if $FIX_MATRIX->[$i][$y];
}
return 1;
}
}
# via: https://twitter.com/yucco311/status/230652288061038593/photo/1
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment