The shortest code by character count that will output the numeric solution, given a number and a valid string pattern, using the Ghost Leg method.
Input: 3, "| | | | | | | | |-| |=| | | | | |-| | |-| |=| | | |-| |-| | |-|" Output: 2 Input: 2, "| | |=| | |-| |-| | | |-| | |" Output: 1
|
, -
, =
(and [space], [LF]). Also, two adjacent columns cannot both contain dashes (in the same line).|-|-|
and |=|=|
which create ambiguity. The given input string will never contain those.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
Minified and 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;
for (i = 0; i < lines.length; i++) {
for (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
is split into an array of lines.n
is scaled to cover the number of characters in each line, starting from 0.=
sign are attached. The middle layer is for the legs of the -
signs.n
either left or right according to the adjacent signs. There is only one possible move for every layer of each line. Therefore n
could move up to 3 times in a line.n
, normalized to start from 1 to the number of vertical lines.
Test Cases:
var ghostLegs = [];
ghostLegs[0] = "|-| |=|-|=|\n" +
"| |-| | |-|\n" +
"|=| |-| | |\n" +
"| | |-|=|-|";
ghostLegs[1] = "| | | | | | | |\n" +
"|-| |=| | | | |\n" +
"|-| | |-| |=| |\n" +
"| |-| |-| | |-|";
ghostLegs[2] = "| | |=| |\n" +
"|-| |-| |\n" +
"| |-| | |";
ghostLegs[3] = "|=|-|";
for (var m = 0; m < ghostLegs.length; m++) {
console.log('\nTest: ' + (m + 1) + '\n');
for (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