Skip to content

Instantly share code, notes, and snippets.

@kkdd
Last active August 27, 2018 12:37
Show Gist options
  • Save kkdd/9991b4410133e9cb832032c150919c3e to your computer and use it in GitHub Desktop.
Save kkdd/9991b4410133e9cb832032c150919c3e to your computer and use it in GitHub Desktop.
ランダム化連鎖配列の本来の並び順を求める ref: https://qiita.com/kkdd/items/1a6968d9a45f3358d4f6
$ ./sequence_sort.py
[[2, 3], [1, 2], [0, 1]] ==>
[0, 1]
[1, 2]
[2, 3]
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import random
SKIP = -1
def find_vacancy(seq):
return list(set(range(len(seq))) - set(seq))[0]
def seq_nexts(arr):
heads = [a[0] for a in arr]
nexts = [heads.index(a[-1]) if a[-1] in heads else SKIP for a in arr]
index_top = find_vacancy(nexts)
return index_top, nexts
def sequence_sort(arr):
i, nexts = seq_nexts(arr)
indices = []
while i is not SKIP:
indices.append(i)
i = nexts[i]
return indices
N = 3
data = [[i,i+1] for i in range(N)]
random.shuffle(data)
print(data, '==>')
for i in sequence_sort(data):
print(data[i])
exit(0)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment