Non-continuous subsequences: Difference between revisions

Content added Content deleted
Line 1,234:
 
=={{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,243 ⟶ 1,241:
 
'''Iterator and Functions'''
<lang Julia>using Printf, IterTools
 
import Base.IteratorSize, Base.iterate, Base.length
 
iscontseq(n::Integer) = count_zeros(n) == leading_zeros(n) + trailing_zeros(n)
iscontseq(n::BigInt) = !ismatch(r"0", rstrip(bin(n), '0'))
 
function makeint2seq(n::Integer)
const idex = collect(1:n)
function int2seq(m::Integer)
d = digits(m, base=2, pad=n)
idex[d .== 1]
end
return int2seq
end
 
struct NCSubSeq{T<:Integer}
n::T
end
 
mutable struct NCSubState{T<:Integer}
m::T
m2s::Function
end
 
Base.iteratorsizeIteratorSize(::NCSubSeq) = Base.HasLength()
Base.length(a::NCSubSeq) = 2 ^ a.n - a.n * (a.n + 1) ÷ 2 - 1
function Base.startiterate(a::NCSubSeq), as::NCSubState= NCSubState(5, makeint2seq(a.n)))
 
if 2 ^ a.n - 3 < as.m
Base.start(a::NCSubSeq) = NCSubState(5, makeint2seq(a.n))
return nothing
Base.done(a::NCSubSeq, as::NCSubState) = 2 ^ a.n - 3 < as.m
end
function Base.next(a::NCSubSeq, as::NCSubState)
s = as.m2s(as.m)
as.m += 1
Line 1,279:
return (s, as)
end
 
n = 4
println("Testing NCSubSeq for ", n, " items:\n ", join(NCSubSeq(n), " "))
 
s = "Rosetta"
cs = split(s, "")
m = 10
n = length(NCSubSeq(length(scs))) - m
println("\nThe first and last ", m, " NC sub-sequences of \"", s, "\":")
for (i, a) in enumerate(NCSubSeq(length(css)))
i <= m || n < i || continue
println(@sprintf "%6d %s" i join(cs[a], ""))
Line 1,294:
println(" .. ......")
end
 
using IterTools.chain
 
println("\nThe first and last ", m, " NC sub-sequences of \"", s, "\"")
for x in IterTools.chainIterators.flatten([1:10,; 20:10:40,; big.(50:50:200)])
@printf "%7d → %d\n" x length(NCSubSeq(x))
end</lang>
</lang>{{out}}
 
<pre>
{{out}}
<pre>Testing NCSubSeq for 4 items:
[1, 3] [1, 4] [2, 4] [1, 2, 4] [1, 3, 4]
 
Line 1,346 ⟶ 1,344:
100 → 1267650600228229401496703200325
150 → 1427247692705959881058285969449495136382735298
200 → 1606938044258990275541962092341162602522202993782792835281275</pre>
</pre>
 
=={{header|Kotlin}}==