Created
August 21, 2018 09:56
-
-
Save dominusmi/9d2c3f13ac6d8d7766682e15db85f280 to your computer and use it in GitHub Desktop.
Partitioning an array in Julia 0.6
This file contains 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
# I couldn't find any simpler way of doing this, so I made my own little functions and thought | |
# I'd share them since I've used them in many different contexts. | |
# These should not be used if you're looking for performance, since they're quite hack-y | |
# I personally use them usually during initialisation for various algorithms | |
# Parition an array into partitions of a specifie size n (last partition may be shorter) | |
# e.g. partition([1,2,3,4,5,6,7],3) -> [ [1,2,3], [4,5,6], [7] ] | |
function partition(list, n) | |
l = size(list,1) | |
partitioning = collect(Iterators.partition(list, ceil(Int,l/n))) | |
end | |
# If you further want the array to be "filled" | |
# e.g. partition([1,2,3,4,5,6,7],3) -> [ [1,1,1], [2,2,2], [3] ] | |
# Then use this: | |
function fill_partitions(partitioning) | |
map( x->fill(x[1], size(x[2],1)), enumerate(partitioning) ) | |
end | |
# Finally, if you want to collect them all under one array [1,1,1,2,2,2,3] | |
function collapse_partitions(partitioning) | |
vcat( map( x->fill(x[1], size(x[2],1)), enumerate(partitioning) )...) | |
end | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment