Last active
August 27, 2018 12:37
-
-
Save kkdd/9991b4410133e9cb832032c150919c3e to your computer and use it in GitHub Desktop.
ランダム化連鎖配列の本来の並び順を求める ref: https://qiita.com/kkdd/items/1a6968d9a45f3358d4f6
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
$ ./sequence_sort.py | |
[[2, 3], [1, 2], [0, 1]] ==> | |
[0, 1] | |
[1, 2] | |
[2, 3] |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/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