Data commit
This commit is contained in:
parent
7387c8f97b
commit
cb5bb5e222
199093 changed files with 3378972 additions and 0 deletions
|
|
@ -0,0 +1,60 @@
|
|||
# This code takes a ridiculously inefficient algorithm and rather futilely
|
||||
# optimizes one part of it. Permutations are computed lazily.
|
||||
|
||||
sorted_copy = (a) ->
|
||||
# This returns a sorted copy of an array by lazily generating
|
||||
# permutations of indexes and stopping when the indexes yield
|
||||
# a sorted array.
|
||||
indexes = [0...a.length]
|
||||
ans = find_matching_permutation indexes, (permuted_indexes) ->
|
||||
new_array = (a[i] for i in permuted_indexes)
|
||||
console.log permuted_indexes, new_array
|
||||
in_order(new_array)
|
||||
(a[i] for i in ans)
|
||||
|
||||
in_order = (a) ->
|
||||
# return true iff array a is in increasing order.
|
||||
return true if a.length <= 1
|
||||
for i in [0...a.length-1]
|
||||
return false if a[i] > a[i+1]
|
||||
true
|
||||
|
||||
get_factorials = (n) ->
|
||||
# return an array of the first n+1 factorials, starting with 0!
|
||||
ans = [1]
|
||||
f = 1
|
||||
for i in [1..n]
|
||||
f *= i
|
||||
ans.push f
|
||||
ans
|
||||
|
||||
permutation = (a, i, factorials) ->
|
||||
# Return the i-th permutation of an array by
|
||||
# using remainders of factorials to determine
|
||||
# elements.
|
||||
while a.length > 0
|
||||
f = factorials[a.length-1]
|
||||
n = Math.floor(i / f)
|
||||
i = i % f
|
||||
elem = a[n]
|
||||
a = a[0...n].concat(a[n+1...])
|
||||
elem
|
||||
# The above loop gets treated like
|
||||
# an array expression, so it returns
|
||||
# all the elements.
|
||||
|
||||
find_matching_permutation = (a, f_match) ->
|
||||
factorials = get_factorials(a.length)
|
||||
for i in [0...factorials[a.length]]
|
||||
permuted_array = permutation(a, i, factorials)
|
||||
if f_match permuted_array
|
||||
return permuted_array
|
||||
null
|
||||
|
||||
|
||||
do ->
|
||||
a = ['c', 'b', 'a', 'd']
|
||||
console.log 'input:', a
|
||||
ans = sorted_copy a
|
||||
console.log 'DONE!'
|
||||
console.log 'sorted copy:', ans
|
||||
|
|
@ -0,0 +1,19 @@
|
|||
> coffee permute_sort.coffee
|
||||
input: [ 'c', 'b', 'a', 'd' ]
|
||||
[ 0, 1, 2, 3 ] [ 'c', 'b', 'a', 'd' ]
|
||||
[ 0, 1, 3, 2 ] [ 'c', 'b', 'd', 'a' ]
|
||||
[ 0, 2, 1, 3 ] [ 'c', 'a', 'b', 'd' ]
|
||||
[ 0, 2, 3, 1 ] [ 'c', 'a', 'd', 'b' ]
|
||||
[ 0, 3, 1, 2 ] [ 'c', 'd', 'b', 'a' ]
|
||||
[ 0, 3, 2, 1 ] [ 'c', 'd', 'a', 'b' ]
|
||||
[ 1, 0, 2, 3 ] [ 'b', 'c', 'a', 'd' ]
|
||||
[ 1, 0, 3, 2 ] [ 'b', 'c', 'd', 'a' ]
|
||||
[ 1, 2, 0, 3 ] [ 'b', 'a', 'c', 'd' ]
|
||||
[ 1, 2, 3, 0 ] [ 'b', 'a', 'd', 'c' ]
|
||||
[ 1, 3, 0, 2 ] [ 'b', 'd', 'c', 'a' ]
|
||||
[ 1, 3, 2, 0 ] [ 'b', 'd', 'a', 'c' ]
|
||||
[ 2, 0, 1, 3 ] [ 'a', 'c', 'b', 'd' ]
|
||||
[ 2, 0, 3, 1 ] [ 'a', 'c', 'd', 'b' ]
|
||||
[ 2, 1, 0, 3 ] [ 'a', 'b', 'c', 'd' ]
|
||||
DONE!
|
||||
sorted copy: [ 'a', 'b', 'c', 'd' ]
|
||||
Loading…
Add table
Add a link
Reference in a new issue