Skip to content

Instantly share code, notes, and snippets.

@shiracamus
Created March 14, 2018 18:00
Show Gist options
  • Save shiracamus/271a0dbc885751ab44a0373c4d96670b to your computer and use it in GitHub Desktop.
Save shiracamus/271a0dbc885751ab44a0373c4d96670b to your computer and use it in GitHub Desktop.
def number2yx(number):
b = int((number - 1) ** 0.5)
start = b ** 2 + 1
a = min(number - start, start + b * 2 - number)
return (a, b) if (b % 2 == 1) ^ (a == number - start) else (b, a)
def yx2number(y, x):
if y < 0 or x < 0: return '-'
a, b = sorted((y, x))
start = b ** 2 + 1
return start + (a if (b % 2 == 1) ^ (a == y) else b * 2 - a)
def solve(data):
y, x = number2yx(int(data))
return ','.join(str(yx2number(y + dy, x + dx))
for dy, dx in ((-1, 0), (1, 0), (0, -1), (0, 1)))
def test(data, expect):
answer = solve(data)
print("%s %s %s %s" % (answer == expect and 'OK' or 'NG', data, expect, answer))
test( "1", "-,2,-,4" );
test( "10", "9,25,-,11" );
test( "1", "-,2,-,4" );
test( "2", "1,9,-,3" );
test( "4", "-,3,1,5" );
test( "26", "25,49,-,27" );
test( "43", "42,56,44,58" );
test( "72", "71,73,57,93" );
test( "82", "81,121,-,83" );
test( "91", "92,112,90,110" );
test( "100", "-,99,65,101" );
test( "122", "121,169,-,123" );
test( "141", "142,140,104,148" );
test( "145", "-,146,144,196" );
test( "320", "321,319,261,329" );
test( "504", "503,505,465,557" );
test( "563", "564,562,498,590" );
test( "906", "905,907,895,1019" );
test( "1047", "1046,1048,1002,1134" );
test( "1111", "1068,1204,1110,1112" );
test( "1338", "1257,1401,1339,1337" );
test( "1613", "1612,1614,1588,1752" );
test( "1845", "1686,1854,1846,1844" );
test( "1921", "1922,1920,1780,1952" );
test( "2517", "2516,2518,2484,2688" );
test( "2670", "2671,2669,2535,2739" );
test( "2798", "2613,2821,2799,2797" );
test( "2841", "2778,2994,2840,2842" );
test( "2896", "2897,2895,2725,2937" );
test( "3050", "3001,3225,3049,3051" );
test( "3354", "3355,3353,3147,3375" );
test( "3563", "3564,3562,3402,3638" );
test( "4454", "4261,4525,4455,4453" );
test( "5397", "5262,5558,5396,5398" );
test( "5592", "5363,5659,5593,5591" );
test( "6122", "6121,6123,6047,6363" );
test( "6772", "6771,6773,6677,7009" );
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment