Skip to content

Instantly share code, notes, and snippets.

@ityonemo
Created September 28, 2016 04:36
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save ityonemo/3f8fa2f04021a58ac6ee0e800f4975c8 to your computer and use it in GitHub Desktop.
Save ityonemo/3f8fa2f04021a58ac6ee0e800f4975c8 to your computer and use it in GitHub Desktop.
Iterates over upper triangular indices.
#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