Created
September 28, 2016 04:36
-
-
Save ityonemo/3f8fa2f04021a58ac6ee0e800f4975c8 to your computer and use it in GitHub Desktop.
Iterates over upper triangular indices.
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
#upper triangular indices - iterates over upper triangular indices in a list of | |
#indices. | |
type uppertriangular; iterable; end | |
Base.start(x::uppertriangular) = (1, 1) | |
function Base.next(x::uppertriangular, state) | |
(idx1, idx2) = state | |
next1 = idx1 | |
next2 = idx2 + 1 | |
if next2 > length(x.iterable) | |
next1 += 1 | |
next2 = next1 | |
end | |
((x.iterable[idx1], x.iterable[idx2]), (next1, next2)) | |
end | |
function Base.done(x::uppertriangular, state) | |
(state[1] > length(x.iterable)) | |
end | |
function Base.length(x::uppertriangular) | |
(x.length * x.length + x.length) / 2 | |
end | |
########################################### | |
# examples | |
for (x,y) in uppertriangular(1:3) | |
print("<$x, $y> ") | |
end | |
println() | |
# output: | |
# <1, 1> <1, 2> <1, 3> <2, 2> <2, 3> <3, 3> | |
for (x,y) in uppertriangular([2, 7, 5]) | |
print("<$x, $y> ") | |
end | |
println() | |
# output: | |
# <2, 2> <2, 7> <2, 5> <7, 7> <7, 5> <5, 5> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment