language agnostic - Code Golf: Ghost Leg -
the challenge
the shortest code character count output numeric solution, given number , valid string pattern, using ghost leg method.
examples
input: 3, "| | | | | | | | |-| |=| | | | | |-| | |-| |=| | | |-| |-| | |-|" output: 2 input: 2, "| | |=| | |-| |-| | | |-| | |" output: 1
clarifications
- do not bother input. consider values given somewhere else.
- both input values valid: column number corresponds existing column , pattern contains symbols
|
,-
,=
(and [space], [lf]). also, 2 adjacent columns cannot both contain dashes (in same line). - the dimensions of pattern unknown (min 1x1).
clarifications #2
- there 2 invalid patterns:
|-|-|
,|=|=|
create ambiguity. given input string never contain those. - the input variables same all; numeric value , string representing pattern.
- entrants must produce function.
test case
given pattern: "|-| |=|-|=|lf| |-| | |-|lf|=| |-| | |lf| | |-|=|-|" |-| |=|-|=| | |-| | |-| |=| |-| | | | | |-|=|-| given value : expected result 1 : 6 2 : 1 3 : 3 4 : 5 5 : 4 6 : 2
edit: corrected expected results
javascript: 169 158 148 141 127 125 123 122 characters
minified , golfed:
function g(n,s){for(l=s.split('\n'),n*=2;k=l.shift();)for(j=3;j;)n+=k[n-3]==(c=--j-1?'=':'-')?-2:k[n-1]==c?2:0;return n/2}
readable version:
function g(n, str) { var c, i, j; var lines = str.split('\n'); n = (n * 2) - 2; (i = 0; < lines.length; i++) { (j = 0; j < 3; j++) { c = (j == 1) ? '-' : '='; if (lines[i].charat(n-1) == c) n-=2; // move left else if (lines[i].charat(n+1) == c) n+=2; // move right } } return 1+n/2; }
explanation:
str
split array of lines.n
scaled cover number of characters in each line, starting 0.- iterate 3 times on each line: 1 time each layer. imagine each line divided 3 layers: top , bottom layers legs of of
=
sign attached. middle layer legs of-
signs. - move
n
either left or right according adjacent signs. there 1 possible move every layer of each line. thereforen
move 3 times in line. - return
n
, normalized start 1 number of vertical lines.
test cases:
var ghostlegs = []; ghostlegs[0] = "|-| |=|-|=|\n" + "| |-| | |-|\n" + "|=| |-| | |\n" + "| | |-|=|-|"; ghostlegs[1] = "| | | | | | | |\n" + "|-| |=| | | | |\n" + "|-| | |-| |=| |\n" + "| |-| |-| | |-|"; ghostlegs[2] = "| | |=| |\n" + "|-| |-| |\n" + "| |-| | |"; ghostlegs[3] = "|=|-|"; (var m = 0; m < ghostlegs.length; m++) { console.log('\ntest: ' + (m + 1) + '\n'); (var n = 1; n <= (ghostlegs[m].split('\n')[0].length / 2) + 1; n++) { console.log(n + ':' + g(n, ghostlegs[m])); } }
results:
test: 1 1:6 2:1 3:3 4:5 5:4 6:2 test: 2 1:1 2:3 3:2 4:4 5:5 6:6 7:8 8:7 test: 3 1:3 2:1 3:4 4:2 5:5 test: 4 1:3 2:2 3:1
Comments
Post a Comment