Code Golf: Piano
Solution 1:
Perl, 133 (129) chars
Perl, 167 160 156 147 142 133 D'oh! 147 144 137 134 133 chars
$_=shift;die grep{5>$n?y/*/#/:y/#*/ |/;$n++-8||y/ /_/} @Q=(substr(("*# #".("*# #*# | #")x2)x9, 4*/#/+(7&ord)*5,1+/#/+5*pop).$/)x9
Here's a 129 char solution, borrowing several ideas from molf's Ruby solution:
($_,$c)=@ARGV;$j=($k=/#/)+ord; for$n(0..8){print$/,substr+(join'',map{8-$n?5>$n&&$_%7%4?"### " :" | ":"_|___"}$j..$j+$c),!$k,-3}
and with help from the Acme::AsciiArtinator:
sub init_piano{$S=$";$H='#';
( $
T ,$P,$U)=qw(
T |
_ |
/ )
; $
d =$T.$H.$S.$S;$t =
$ d . $H
. $ d . $
S .$P.$S.$S.$S.$H;$ t= $
d.$H.$t.$t;};$_=shift;-/-/;&init_piano();$Z=/#/;-/| |
| | |
| YAMAHA | /
;die grep{4>$n++?y/T/#/:y/#T/ |/;$n-8||y/ /_/;}@q=(m{
// // /// // /// // /// // /// // /// // /// // /// /
// // /// // /// // /// // /// // /// // /// // /// /
} .
substr(${t}x(9),4*${Z}+(7&ord)*5,1+$Z+5*pop).$/)x(8)
; ' \ /
| | | |
/_\ /';
Solution 2:
Ruby - 125 chars
146 144 140 137 134 126 125 chars
a,n=$*;h=a[1]?0:1;s=a[0]-h+1
9.times{|t|puts (s..s+n.to_i).map{|i|i%7%4<1||t>4?" | ":"### "
}.join[h..-4].tr t>7?" ":n,"_"}
(The second newline is not necessary and added only to avoid a scrollbar on SO. Semi-colons can be replaced by newlines if desired.)
The Ruby 1.9 version is different but of equal length (replacing a[0]
by a.ord
and "_"
by ?_
):
a,n=$*;h=a[1]?0:1;s=a.ord-h+1
9.times{|t|puts (s..s+n.to_i).map{|i|i%7%4<1||t>4?" | ":"### "
}.join[h..-4].tr t>7?" ":n,?_}
Call with
$ ruby piano.rb C 14
Solution 3:
LilyPond, 285 288 291 310 315 330 333 340 350 characters
In keeping with the music theme, here's a solution in a language designed for typesetting music scores, LilyPond:
x=#ly:string-substitute
u=#(x"*""### ""| *** | ** ")t=#(x"###"" | "u)q=#read-char
z=#(q)v=#(if(eq?(q)#\#)1 0)y=#(iota(+(*(read)5)1 v))#(format #t"~{~{~a~}
~}"(map(lambda(s)(map(lambda(i)(string-ref s(modulo(+(*(char->integer z)5)i(* v
4))35)))y))(list u u u u u t t t(x" ""_"t))))
Usage: $ lilypond thisfile.ly <input.in >output.out 2>/dev/null