Anonymous user
Non-continuous subsequences: Difference between revisions
→{{header|Julia}}
No edit summary |
|||
Line 1,194:
=={{header|Julia}}==
{{works with|Julia|0.6}}
This solution uses an iterator over non-contiguous sub-sequences, <tt>NCSubSeq</tt>. In the spirit of Julia's <tt>permutations</tt> and <tt>combinations</tt> built-ins, <tt>NCSubSeq</tt> provides an array of indices that can be used to create each subsequence from the full sequence. Sub-sequences are indexed by integers whose bit patterns indicate which members are included.
Line 1,201 ⟶ 1,203:
'''Iterator and Functions'''
<lang Julia>iscontseq(n::Integer) = count_zeros(n) == leading_zeros(n) + trailing_zeros(n)
iscontseq(n::
function makeint2seq(n::Integer)
Line 1,214 ⟶ 1,215:
end
n::T
end
m::T
m2s::Function
end
Base.
Base.
Base.done(a::NCSubSeq, as::NCSubState) = 2^a.n-3 < as.m▼
Base.start(a::NCSubSeq) = NCSubState(5, makeint2seq(a.n))
▲Base.done(a::NCSubSeq, as::NCSubState) = 2 ^ a.n - 3 < as.m
function Base.next(a::NCSubSeq, as::NCSubState)
s = as.m2s(as.m)
Line 1,235 ⟶ 1,237:
return (s, as)
end
</lang>▼
n = 4
for a in NCSubSeq(n)▼
s = "Rosetta"
Line 1,250 ⟶ 1,245:
m = 10
n = length(NCSubSeq(length(s))) - m
▲println("The first and last ", m, " NC sub-sequences of \"", s, "\":")
i <= m || n < i || continue
println(@sprintf "%6d %s" i join(cs[a], ""))
Line 1,259 ⟶ 1,253:
end
using IterTools.chain
▲end</lang>
▲println("Numbers of NC sub-sequences of a given length:")
▲ println(@sprintf("%7d => ", i), length(NCSubSeq(i)))
{{out}}
<pre>Testing NCSubSeq for 4 items:▼
▲Testing NCSubSeq for 4 items:
▲ [1,3] [1,4] [2,4] [1,2,4] [1,3,4]
The first and last 10 NC sub-sequences of "Rosetta":
Line 1,298 ⟶ 1,287:
99 Rsetta
1
2
3
4
5
6
7
8
9
10
20
30
40
50
100
150
200
=={{header|Kotlin}}==
|