Enable Javascript in your browser and then refresh this page, for a much enhanced experience.
First solution in Clear category for Hexagonal Islands by Tinus_Trotyl
def hexagonal_islands(coasts):
FIRST, SECOND = 'ABCDEFGHIJKL', '123456789'
map = {f+s : 'COAST' if f+s in coasts else 'NOID' for s in SECOND for f in FIRST}
def surrounds(co): # is ok
indexes = FIRST.index(co[0]), SECOND.index(co[1]) # str to num
neighbours = []
for delta in ( (0, -1),
(-1, -1,), (1, -1),
(-1, 0,), (1, 0),
(0, 1) ):
neigh = [indexes[id] + delta[id] for id in (0, 1)]
neigh[1] += (indexes[0] % 2) * abs(delta[0]) # correct uneven columns
if 0 <= neigh[0] < 12 and 0 <= neigh[1] < 9:
neighbours.append(FIRST[neigh[0]] + SECOND[neigh[1]]) # num to str
return neighbours
def flood(co):
for neigh in surrounds(co):
if map[neigh] != 'NOID': continue
map[neigh] = 'SEA'
flood(neigh)
def polder(co, island):
for neigh in surrounds(co):
if map[neigh] == 'SEA' or map[neigh] == island: continue
map[neigh] = island
polder(neigh, island)
### main routine ###
for edge in [(FIRST, SECOND[0]), (FIRST[0], SECOND[1:-1]),
(FIRST[~0], SECOND[1:-1]), (FIRST, SECOND[~0])]:
for f in edge[0]:
for s in edge[1]:
if map[f+s] == 'NOID':
map[f+s] = 'SEA'
flood(f+s)
number = 1
island = 'ISL:' + str(number)
islands = []
for f in FIRST:
for s in SECOND:
if map[f+s] == 'COAST':
map[f+s] = island
polder(f+s, island)
number += 1
island = 'ISL:' + str(number)
for n in range(1, number):
island = 'ISL:' + str(n)
size = 0
for f in FIRST:
for s in SECOND:
if map[f+s] == island:
size += 1
islands.append(size)
return islands
Aug. 12, 2019
Comments: