Non-continuous subsequences: Difference between revisions

m
m (→‎{{header|REXX}}: re-aligned DO-loops indentation. -- ~~~~)
 
(84 intermediate revisions by 42 users not shown)
Line 6:
A ''continuous'' subsequence is one in which no elements are missing between the first and last elements of the subsequence.
 
Note: Subsequences are defined ''structurally'', not by their contents. So a sequence ''a,b,c,d'' will always have the same subsequences and continuous subsequences, no matter which values are substituted; it may even be the same value.
So a sequence ''a,b,c,d'' will always have the same subsequences and continuous subsequences, no matter which values are substituted; it may even be the same value.
 
'''Task''': Find all non-continuous subsequences for a given sequence. Example: For the sequence ''1,2,3,4'', there are five non-continuous subsequences, namely ''1,3''; ''1,4''; ''2,4''; ''1,3,4'' and ''1,2,4''.
 
'''Task''': Find all non-continuous subsequences for a given sequence.
'''Goal''': There are different ways to calculate those subsequences. Demonstrate algorithm(s) that are natural for the language.
 
 
;Example:
For the sequence   ''1,2,3,4'',   there are five non-continuous subsequences, namely:
::::*   ''1,3''
::::*   ''1,4''
::::*   ''2,4''
::::*   ''1,3,4''
::::*   ''1,2,4''
 
 
;Goal:
There are different ways to calculate those subsequences.
 
Demonstrate algorithm(s) that are natural for the language.
 
{{Template:Strings}}
<br><br>
 
=={{header|11l}}==
{{trans|Python}}
 
<syntaxhighlight lang="11l">F ncsub(seq, s = 0)
I seq.empty
R I s >= 3 {[[Int]()]} E [[Int]]()
E
V x = seq[0.<1]
V xs = seq[1..]
V p2 = s % 2
V p1 = !p2
R ncsub(xs, s + p1).map(ys -> @x + ys) [+] ncsub(xs, s + p2)
 
print(ncsub(Array(1..3)))
print(ncsub(Array(1..4)))
print(ncsub(Array(1..5)))</syntaxhighlight>
 
{{out}}
<pre>
[[1, 3]]
[[1, 2, 4], [1, 3, 4], [1, 3], [1, 4], [2, 4]]
[[1, 2, 3, 5], [1, 2, 4, 5], [1, 2, 4], [1, 2, 5], [1, 3, 4, 5], [1, 3, 4], [1, 3, 5], [1, 3], [1, 4, 5], [1, 4], [1, 5], [2, 3, 5], [2, 4, 5], [2, 4], [2, 5], [3, 5]]
</pre>
 
=={{header|Ada}}==
===Recursive===
<langsyntaxhighlight lang="ada">with Ada.Text_IO; use Ada.Text_IO;
 
procedure Test_Non_Continuous is
Line 50 ⟶ 92:
Put_NCS ((1,2,3,4)); New_Line;
Put_NCS ((1,2,3,4,5)); New_Line;
end Test_Non_Continuous;</langsyntaxhighlight>
 
Sample output:
 
{{out}}
<pre style="height:30ex;overflow:scroll"> 1 3
 
Line 78 ⟶ 119:
2 5
3 5</pre>
 
=={{header|ALGOL 68}}==
===Recursive===
Line 85 ⟶ 127:
 
{{works with|ELLA ALGOL 68|Any (with appropriate job cards) - tested with release [http://sourceforge.net/projects/algol68/files/algol68toc/algol68toc-1.8.8d/algol68toc-1.8-8d.fc9.i386.rpm/download 1.8-8d]}}
<langsyntaxhighlight lang="algol68">PROC test non continuous = VOID: BEGIN
MODE SEQMODE = CHAR;
MODE SEQ = [1:0]SEQMODE;
Line 119 ⟶ 161:
print((seq, new line))
# OD # )
END; test non continuous</langsyntaxhighlight>
{{out}}
Output:
<pre>
aeiu
Line 149 ⟶ 191:
 
Note: This specimen can only handle sequences of length less than ''bits width'' of '''bits'''.
<langsyntaxhighlight lang="algol68">MODE SEQMODE = STRING;
MODE SEQ = [1:0]SEQMODE;
MODE YIELDSEQ = PROC(SEQ)VOID;
Line 195 ⟶ 237:
print((seq, new line))
# OD # )
)</langsyntaxhighlight>
{{out}}
Output:
<pre>
iu
Line 220 ⟶ 262:
ahk forum: [http://www.autohotkey.com/forum/viewtopic.php?p=277328#277328 discussion]
 
<langsyntaxhighlight AutoHotkeylang="autohotkey">MsgBox % noncontinuous("a,b,c,d,e", ",")
MsgBox % noncontinuous("1,2,3,4", ",")
 
Line 239 ⟶ 281:
ToBin(n,W=16) { ; LS W-bits of Binary representation of n
Return W=1 ? n&1 : ToBin(n>>1,W-1) . n&1
}</langsyntaxhighlight>
 
=={{header|BBC BASIC}}==
{{works with|BBC BASIC for Windows}}
<syntaxhighlight lang="bbcbasic"> DIM list1$(3)
list1$() = "1", "2", "3", "4"
PRINT "For [1, 2, 3, 4] non-continuous subsequences are:"
PROCnon_continuous_subsequences(list1$())
DIM list2$(4)
list2$() = "1", "2", "3", "4", "5"
PRINT "For [1, 2, 3, 4, 5] non-continuous subsequences are:"
PROCnon_continuous_subsequences(list2$())
END
DEF PROCnon_continuous_subsequences(l$())
LOCAL i%, j%, g%, n%, r%, s%, w%, a$, b$
n% = DIM(l$(),1)
FOR s% = 0 TO n%-2
FOR g% = s%+1 TO n%-1
a$ = "["
FOR i% = s% TO g%-1
a$ += l$(i%) + ", "
NEXT
FOR w% = 1 TO n%-g%
r% = n%+1-g%-w%
FOR i% = 1 TO 2^r%-1 STEP 2
b$ = a$
FOR j% = 0 TO r%-1
IF i% AND 2^j% b$ += l$(g%+w%+j%) + ", "
NEXT
PRINT LEFT$(LEFT$(b$)) + "]"
NEXT i%
NEXT w%
NEXT g%
NEXT s%
ENDPROC</syntaxhighlight>
{{out}}
<pre>
For [1, 2, 3, 4] non-continuous subsequences are:
[1, 3]
[1, 3, 4]
[1, 4]
[1, 2, 4]
[2, 4]
For [1, 2, 3, 4, 5] non-continuous subsequences are:
[1, 3]
[1, 3, 4]
[1, 3, 5]
[1, 3, 4, 5]
[1, 4]
[1, 4, 5]
[1, 5]
[1, 2, 4]
[1, 2, 4, 5]
[1, 2, 5]
[1, 2, 3, 5]
[2, 4]
[2, 4, 5]
[2, 5]
[2, 3, 5]
[3, 5]
</pre>
 
=={{header|Bracmat}}==
<syntaxhighlight lang="bracmat">( ( noncontinuous
This is a one-liner. The <code>%</code> flags matches only non-nil elements. Thus the middle <code>%</code> ensures that there is a hole in the sequence, while <code>?%a</code> and <code>?%b</code> match sequences of one or more elements. The elements not matched by the <code>?%a</code>, <code>%</code> and <code>?%b</code> patterns are matched by the two wildcards <code>?</code>. After the output statement the pattern matching is forced to fail (<code>~</code>) and backtracks to construct alternative distributions of the subject's elements over the five patterns.
= sub
 
. ( sub
<lang Bracmat>{?} 1 2 3 4 5:? ?%a % ?%b (?&out$(!a !b)&~)
= su a nc
1 3
. !arg:(?su.?nc)
1 3 4
& !su
1 3 4 5
: %
1 4
%?a
1 4 5
( %:[%(sub$(!sjt.!nc !a))
1 5
| ?
1 2 4
& !nc:~
1 2 4 5
& out$(!nc !a)
1 2 5
& ~
1 2 3 5
)
2 4
)
2 4 5
& sub$(dummy !arg.)
2 5
|
2 3 5
)
3 5</lang>
& noncontinuous$(e r n i t)
);
</syntaxhighlight>
{{out}}
<pre>e n t
e n
e n i
e n i t
e i
e i t
e t
e r i
e r i t
e r t
e r n t
r i
r i t
r t
r n t
n t</pre>
 
=={{header|C}}==
Loosely based on the [[Non-continuous_subsequences#J|J]] implementation.
 
Note: This specimen can only handle lists of length less than the number of bits in an '''int'''.
<langsyntaxhighlight Clang="c">#include <assert.h>
#include <stdio.h>
 
int main(int c, char **v) {
{
int i, j, k;
unsigned int n = 1 << (c - int1), i n= c-1n, j, k;
assert(n);
unsigned int lim=1<<n;
 
assert(lim); /* check int's bit width limit */
while (i--) {
int K= lim>>1;
if (!(i & (i + (i & -(int)i)))) // consecutive 1s
for (j= 1; j < lim; j++) {
continue;
int state= 0;
 
for (k= K; k; k>>=1) {
for (j = n, k = 1; j >>= 1; k++)
int b= j&k;
if (i & j) printf("%s ", v[k]);
switch (state) {
 
case 0: if (b) state++; break;
putchar('\n');
case 1: if (!b) state++; break;
}
case 2: if (!b) continue;
 
for (k= K, i= 1; k; k>>=1, i++)
return 0;
if (j&k) printf("%s ", v[i]);
}</syntaxhighlight>
printf("\n");
/* k=0, now, ending containing loop */
}
}
}
}</lang>
Example use:
<pre>
$ ./noncont 1 2 3 4
1 2 4
1 3 4
1 3
2 4
1 4
1 3
1 3 4
1 2 4
$ ./noncont 1 2 3 4 5 6 7 8 9 0 | wc -l
968
</pre>
 
Using "consecutive + gap + any subsequence" to produce disjointed sequences:
<syntaxhighlight lang="c">#include <assert.h>
#include <stdio.h>
#include <stdlib.h>
 
void binprint(unsigned int n, unsigned int m)
{
char c[sizeof(n) * 8 + 1];
int i = 0;
while (m >>= 1) c[i++] = n & m ? '#' : '-';
c[i] = 0;
puts(c);
}
 
int main(int c, char **v)
{
unsigned int n, gap, left, right;
if (c < 2 || ! (n = 1 << atoi(v[1]))) n = 16;
 
for (gap = 2; gap < n; gap <<= 1)
for (left = gap << 1; left < n; left |= left << 1)
for (right = 1; right < gap; right++)
binprint(left | right, n);
 
return 0;
}</syntaxhighlight>
===Recursive method===
Using recursion and a state transition table.
<langsyntaxhighlight lang="c">#include <stdio.h>
 
typedef unsigned char sint;
Line 354 ⟶ 496:
pick(c - 1, 0, s_blnk, v + 1, 0);
return 0;
}</langsyntaxhighlight>running it:
<pre>% ./a.out 1 2 3 4
1 3
Line 363 ⟶ 505:
% ./a.out 1 2 3 4 5 6 7 8 9 0 | wc -l
968</pre>
 
=={{header|C sharp}}==
<syntaxhighlight lang="csharp">using System;
using System.Collections.Generic;
using System.Linq;
 
class Program
{
public static void Main() {
var sequence = new[] { "A", "B", "C", "D" };
foreach (var subset in Subsets(sequence.Length).Where(s => !IsContinuous(s))) {
Console.WriteLine(string.Join(" ", subset.Select(i => sequence[i])));
}
}
static IEnumerable<List<int>> Subsets(int length) {
int[] values = Enumerable.Range(0, length).ToArray();
var stack = new Stack<int>(length);
for (int i = 0; stack.Count > 0 || i < length; ) {
if (i < length) {
stack.Push(i++);
yield return (from index in stack.Reverse() select values[index]).ToList();
} else {
i = stack.Pop() + 1;
if (stack.Count > 0) i = stack.Pop() + 1;
}
}
}
 
static bool IsContinuous(List<int> list) => list[list.Count - 1] - list[0] + 1 == list.Count;
 
}</syntaxhighlight>
{{out}}
<pre>
A B D
A C
A C D
A D
B D
</pre>
 
=={{header|C++}}==
<syntaxhighlight lang="cpp">
/*
* Nigel Galloway, July 19th., 2017 - Yes well is this any better?
*/
class N{
uint n,i,g,e,l;
public:
N(uint n): n(n-1),i{},g{},e(1),l(n-1){}
bool hasNext(){
g=(1<<n)+e;for(i=l;i<n;++i) g+=1<<i;
if (l==2) {l=--n; e=1; return true;}
if (e<((1<<(l-1))-1)) {++e; return true;}
e=1; --l; return (l>0);
}
uint next() {return g;}
};
</syntaxhighlight>
Which may be used as follows:
<syntaxhighlight lang="cpp">
int main(){
N n(4);
while (n.hasNext()) std::cout << n.next() << "\t* " << std::bitset<4>(n.next()) << std::endl;
}
</syntaxhighlight>
{{out}}
<pre>
9 * 1001
10 * 1010
11 * 1011
13 * 1101
5 * 0101
</pre>
I can count the length of the sequence:
<syntaxhighlight lang="cpp">
int main(){
N n(31);
int z{};for (;n.hasNext();++z); std::cout << z << std::endl;
}
</syntaxhighlight>
{{out}}
<pre>
2147483151
</pre>
 
=={{header|Clojure}}==
Line 368 ⟶ 595:
Here's a simple approach that uses the clojure.contrib.combinatorics library to generate subsequences, and then filters out the continuous subsequences using a naïve subseq test:
 
<langsyntaxhighlight lang="lisp">
(use '[clojure.contrib.combinatorics :only (subsets)])
 
Line 385 ⟶ 612:
 
(filter (of-min-length 2) (non-continuous-subsequences [:a :b :c :d]))
</syntaxhighlight>
</lang>
 
=={{header|CoffeeScript}}==
Use binary bitmasks to enumerate our sequences.
<langsyntaxhighlight lang="coffeescript">
is_contigous_binary = (n) ->
# return true if binary representation of n is
Line 447 ⟶ 674:
num_solutions = non_contig_subsequences(arr).length
console.log "for n=#{n} there are #{num_solutions} solutions"
</syntaxhighlight>
</lang>
 
{{out}}
output
<langpre>
> coffee non_contig_subseq.coffee
[ [ 1, 3 ],
Line 467 ⟶ 694:
for n=9 there are 466 solutions
for n=10 there are 968 solutions
</langpre>
 
=={{header|Common Lisp}}==
Line 475 ⟶ 702:
looking at the screen wondering what's wrong for about half an hour -->
 
<langsyntaxhighlight lang="lisp">(defun all-subsequences (list)
(labels ((subsequences (tail &optional (acc '()) (result '()))
"Return a list of the subsequence designators of the
Line 495 ⟶ 722:
(map-into subsequence-d 'first subsequence-d)))
(let ((nc-subsequences (delete-if #'continuous-p (subsequences list))))
(map-into nc-subsequences #'designated-sequence nc-subsequences))))</langsyntaxhighlight>
 
{{trans|Scheme}}
 
<langsyntaxhighlight lang="lisp">(defun all-subsequences2 (list)
(labels ((recurse (s list)
(if (endp list)
Line 514 ⟶ 741:
(recurse s xs))
(recurse (+ s 1) xs)))))))
(recurse 0 list)))</langsyntaxhighlight>
 
=={{header|D}}==
===Recursive Version===
{{trans|Python}}
<syntaxhighlight lang="d">T[][] ncsub(T)(in T[] seq, in uint s=0) pure nothrow @safe {
<lang d>import std.stdio;
 
T[][] ncsub(T)(in T[] seq, in int s=0) pure nothrow {
if (seq.length) {
T[][]typeof(return) aux;
foreach (ys; ncsub(seq[1 .. $], s + !(s % 2)))
aux ~= seq[0] ~ ys;
return aux ~ ncsub(seq[1 .. $], s + s % 2);
} else
return new T[][]typeof(return)(s >= 3, 0);
}
 
void main() @safe {
import std.stdio;
writeln(ncsub([1, 2, 3]));
 
writeln(ncsub([1, 2, 3, 4]));
foreach (nc; ncsub([1, 2, 3, 4, 5])).ncsub.writeln;
[1, 2, 3, 4].ncsub.writeln(nc);
foreach (const nc; [1, 2, 3, 4, 5].ncsub)
}</lang>
nc.writeln;
}</syntaxhighlight>
{{out}}
<pre>[[1, 3]]
Line 556 ⟶ 783:
[2, 5]
[3, 5]</pre>
 
===Faster Lazy Version===
This version doesn't copy the sub-arrays.
<langsyntaxhighlight lang="d">struct Ncsub(T) {
T[] seq;
 
int opApply(int delegate(ref intT[]) dg) const {
immutable int n = seq.length;
int result;
auto S = new intT[n];
 
OUTER: foreach (immutable i; 1 .. 1 << n) {
FOR_I:
foreach (i; 1 .. 1uint << seq.length) {lenS;
int len_S;
bool nc = false;
foreach (immutable j; 0 .. seq.lengthn + 1) {
immutable int k = i >> j;
if (k == 0) {
if (nc) {
auto auxS = S[0 .. len_SlenS];
result = dg(auxS);
if (result)
break FOR_IOUTER;
}
break;
} else if (k % 2) {
S[len_SlenS] = seq[j];
len_SlenS++;
} else if (len_SlenS)
nc = true;
}
Line 594 ⟶ 821:
void main() {
import std.array, std.range;
 
//assert(iota(24).array().Ncsub!int().walkLength() == 16_776_915);
//assert(24.iota.array.Ncsub!int.walkLength == 16_776_915);
auto r = array(iota(24));
intauto counterr = 24.iota.array;
uint counter = 0;
foreach (s; Ncsub!int(r))
counter++;
assert(counter == 16_776_915);
}</langsyntaxhighlight>
 
===Generator Version===
This version doesn't copy the sub-arrays, and it's a little slower than the opApply-based version.
<syntaxhighlight lang="d">import std.stdio, std.array, std.range, std.concurrency;
 
Generator!(T[]) ncsub(T)(in T[] seq) {
return new typeof(return)({
immutable n = seq.length;
auto S = new T[n];
 
foreach (immutable i; 1 .. 1 << n) {
uint lenS = 0;
bool nc = false;
foreach (immutable j; 0 .. n + 1) {
immutable k = i >> j;
if (k == 0) {
if (nc)
yield(S[0 .. lenS]);
break;
} else if (k % 2) {
S[lenS] = seq[j];
lenS++;
} else if (lenS)
nc = true;
}
}
});
}
 
void main() {
assert(24.iota.array.ncsub.walkLength == 16_776_915);
 
[1, 2, 3].ncsub.writeln;
[1, 2, 3, 4].ncsub.writeln;
foreach (const nc; [1, 2, 3, 4, 5].ncsub)
nc.writeln;
}</syntaxhighlight>
 
=={{header|EasyLang}}==
{{trans|Nim}}
<syntaxhighlight>
func[][] ncsub seq[] s .
if len seq[] = 0
if s >= 3
return [ [ ] ]
.
return [ ]
.
last = seq[$]
len seq[] -1
res[][] = ncsub seq[] (s + s mod 2)
r[][] = ncsub seq[] (s + 1 - s mod 2)
for i to len r[][]
r[i][] &= last
res[][] &= r[i][]
.
return res[][]
.
print ncsub [ 1 2 3 4 ] 0
</syntaxhighlight>
{{out}}
<pre>
[
[ 1 3 ]
[ 1 4 ]
[ 2 4 ]
[ 1 2 4 ]
[ 1 3 4 ]
]
</pre>
 
=={{header|Elixir}}==
{{trans|Erlang}}
<syntaxhighlight lang="elixir">defmodule RC do
defp masks(n) do
maxmask = trunc(:math.pow(2, n)) - 1
Enum.map(3..maxmask, &Integer.to_string(&1, 2))
|> Enum.filter_map(&contains_noncont(&1), &String.rjust(&1, n, ?0)) # padding
end
defp contains_noncont(n) do
Regex.match?(~r/10+1/, n)
end
defp apply_mask_to_list(mask, list) do
Enum.zip(to_char_list(mask), list)
|> Enum.filter_map(fn {include, _} -> include > ?0 end, fn {_, value} -> value end)
end
 
def ncs(list) do
Enum.map(masks(length(list)), fn mask -> apply_mask_to_list(mask, list) end)
end
end
 
IO.inspect RC.ncs([1,2,3])
IO.inspect RC.ncs([1,2,3,4])
IO.inspect RC.ncs('abcd')</syntaxhighlight>
 
{{out}}
<pre>
[[1, 3]]
[[2, 4], [1, 4], [1, 3], [1, 3, 4], [1, 2, 4]]
['bd', 'ad', 'ac', 'acd', 'abd']
</pre>
 
=={{header|Erlang}}==
Erlang's not optimized for strings or math, so this is pretty inefficient. Nonetheless, it works by generating the set of all possible "bitmasks" (represented as strings), filters for those with non-continuous subsequences, and maps from that set over the list. One immediate point for optimization that would complicate the code a bit would be to compile the regular expression, the problem being where you'd put it.
 
<syntaxhighlight lang="erlang">-module(rosetta).
-export([ncs/1]).
 
masks(N) ->
MaxMask = trunc(math:pow(2, N)),
Total = lists:map(fun(X) -> integer_to_list(X, 2) end,
lists:seq(3, MaxMask)),
Filtered = lists:filter(fun(X) -> contains_noncont(X) end, Total),
lists:map(fun(X) -> string:right(X, N, $0) end, Filtered). % padding
contains_noncont(N) ->
case re:run(N, "10+1") of
{match, _} -> true;
nomatch -> false
end.
 
apply_mask_to_list(Mask, List) ->
Zipped = lists:zip(Mask, List),
Filtered = lists:filter(fun({Include, _}) -> Include > 48 end, Zipped),
lists:map(fun({_, Value}) -> Value end, Filtered).
 
ncs(List) ->
lists:map(fun(Mask) -> apply_mask_to_list(Mask, List) end,
masks(length(List))).</syntaxhighlight>
 
{{out}}
<pre>
Eshell V5.10.1 (abort with ^G)
1> c(rosetta).
{ok,rosetta}
2> rosetta:ncs([1,2,3,4]).
[[2,4],[1,4],[1,3],[1,3,4],[1,2,4]]
</pre>
 
=={{header|F_Sharp|F#}}==
===Generate only the non-continuous subsequences===
<syntaxhighlight lang="fsharp">
(*
A function to generate only the non-continuous subsequences.
Nigel Galloway July 20th., 2017
*)
let N n =
let fn n = Seq.map (fun g->(2<<<n)+g)
let rec fg n = seq{if n>0 then yield! seq{1..((1<<<n)-1)}|>fn n; yield! fg (n-1)|>fn n}
Seq.collect fg ({1..(n-2)})
</syntaxhighlight>
This may be used as follows:
<syntaxhighlight lang="fsharp">
let Ng ng = N ng |> Seq.iter(fun n->printf "%2d -> " n; {0..(ng-1)}|>Seq.iter (fun g->if (n&&&(1<<<g))>0 then printf "%d " (g+1));printfn "")
Ng 4
</syntaxhighlight>
{{out}}
<pre>
5 -> 1 3
9 -> 1 4
10 -> 2 4
11 -> 1 2 4
13 -> 1 3 4
</pre>
Counting the number of non-continuous subsequences is interesting:
<pre>
> Seq.length (N 20);;
Real: 00:00:00.169, CPU: 00:00:00.169, GC gen0: 0, gen1: 0
val it : int = 1048365
> Seq.length (N 23);;
Real: 00:00:01.238, CPU: 00:00:01.239, GC gen0: 0, gen1: 0
val it : int = 8388331
> Seq.length (N 24);;
Real: 00:00:02.520, CPU: 00:00:02.523, GC gen0: 0, gen1: 0
val it : int = 16776915
> Seq.length (N 25);;
Real: 00:00:04.926, CPU: 00:00:04.930, GC gen0: 0, gen1: 0
val it : int = 33554106
</pre>
===Generate all subsequences and filter out the continuous===
<syntaxhighlight lang="fsharp">
(*
A function to filter out continuous subsequences.
Nigel Galloway July 24th., 2017
*)
let Nonseq n=
let fn = function
|((n,0),true )->(n+1,1)
|((n,_),false)->(n,0)
|(n,_) ->n
{5..(1<<<n)-1}|>Seq.choose(fun i->if fst({0..n-1}|>Seq.takeWhile(fun n->(1<<<(n-1))<i)|>Seq.fold(fun n g->fn (n,(i&&&(1<<<g)>0)))(0,0)) > 1 then Some(i) else None)
</syntaxhighlight>
Again counting the number of non-continuous subsequences
<pre>
> Seq.length (Nonseq 20);;
Real: 00:00:02.356, CPU: 00:00:02.389, GC gen0: 183, gen1: 0
val it : int = 1048365
> Seq.length (Nonseq 23);;
Real: 00:00:20.714, CPU: 00:00:20.950, GC gen0: 1571, gen1: 0
val it : int = 8388331
> Seq.length (Nonseq 24);;
Real: 00:00:43.129, CPU: 00:00:43.601, GC gen0: 3216, gen1: 0
val it : int = 16776915
> Seq.length (Nonseq 25);;
Real: 00:01:28.853, CPU: 00:01:29.869, GC gen0: 6577, gen1: 0
val it : int = 33554106
</pre>
===Conclusion===
Find a better filter or use the generator.
 
 
=={{header|FreeBASIC}}==
{{trans|BBC BASIC}}
<syntaxhighlight lang="freebasic">Sub Subsecuencias_no_continuas(l() As String)
Dim As Integer i, j, g, n, r, s, w
Dim As String a, b, c
n = Ubound(l)
For s = 0 To n-2
For g = s+1 To n-1
a = "["
For i = s To g-1
a += l(i) + ", "
Next i
For w = 1 To n-g
r = n+1-g-w
For i = 1 To 2^r-1 Step 2
b = a
For j = 0 To r-1
If i And 2^j Then b += l(g+w+j) + ", "
Next j
'Print Left(Left(b)) + "]"
c = (Left(b, Len (b)-1))
Print Left(c, Len(c)-1) + "]"
Next i
Next w
Next g
Next s
End Sub
 
Dim lista1(3) As String = {"1", "2", "3", "4"}
Print "Para [1, 2, 3, 4] las subsecuencias no continuas son:"
Subsecuencias_no_continuas(lista1())
Dim lista2(4) As String = {"e", "r", "n", "i", "t"}
Print "Para [e, r, n, i, t] las subsecuencias no continuas son:"
Subsecuencias_no_continuas(lista2())
Sleep</syntaxhighlight>
{{out}}
<pre>
Para [1, 2, 3, 4] las subsecuencias no continuas son:
[1, 3]
[1, 3, 4]
[1, 4]
[1, 2, 4]
[2, 4]
Para [e, r, n, i, t] las subsecuencias no continuas son:
[e, n]
[e, n, i]
[e, n, t]
[e, n, i, t]
[e, i]
[e, i, t]
[e, t]
[e, r, i]
[e, r, i, t]
[e, r, t]
[e, r, n, t]
[r, i]
[r, i, t]
[r, t]
[r, n, t]
[n, t]
</pre>
 
 
=={{header|Go}}==
Generate the power set (power sequence, actually) with a recursive function, but keep track of the state of the subsequence on the way down. When you get to the bottom, if state == non-continuous, then include the subsequence. It's just filtering merged in with generation.
<langsyntaxhighlight lang="go">package main
 
import "fmt"
Line 642 ⟶ 1,146:
fmt.Println(" ", s)
}
}</langsyntaxhighlight>
{{out}}
Output:
<pre>
5 non-continuous subsequences:
Line 657 ⟶ 1,161:
===Generalized monadic filter===
 
<langsyntaxhighlight lang="haskell">action p x = if p x then succ x else x
 
fenceM p q s [] = guard (q s) >> return []
Line 665 ⟶ 1,169:
return $ f x ys
 
ncsubseq = fenceM [((:), action even), (flip const, action odd)] (>= 3) 0</langsyntaxhighlight>
 
Output:
 
{{out}}
<pre>*Main> ncsubseq [1..3]
[[1,3]]
Line 680 ⟶ 1,183:
This implementation works by computing templates of all possible subsequences of the given length of sequence, discarding the continuous ones, then applying the remaining templates to the input list.
 
<langsyntaxhighlight lang="haskell">continuous = null . dropWhile not . dropWhile id . dropWhile not
ncs xs = map (map fst . filter snd . zip xs) $
filter (not . continuous) $
mapM (const [True,False]) xs</langsyntaxhighlight>
 
===Recursive===
Recursive method with powerset as helper function.
 
<langsyntaxhighlight lang="haskell">import Data.List
 
poset = foldr (\x p -> p ++ map (x:) p) [[]]
Line 697 ⟶ 1,200:
nc [_] [] = [[]]
nc (_:x:xs) [] = nc [x] xs
nc xs (y:ys) = (nc (xs++[y]) ys) ++ map (xs++) (tail $ poset ys)</langsyntaxhighlight>
 
Output:
 
{{out}}
<pre>
*Main> ncsubs "aaa"
["aa"]
Line 713 ⟶ 1,216:
[]
(0.00 secs, 0 bytes)
</pre>
 
A disjointed subsequence is a consecutive subsequence followed by a gap,
then by any nonempty subsequence to its right:
<syntaxhighlight lang="haskell">import Data.List (subsequences, tails, delete)
 
disjoint a = concatMap (cutAt a) [1..length a - 2] where
cutAt s n = [a ++ b | b <- delete [] (subsequences right),
a <- init (tails left) ] where
(left, _:right) = splitAt n s
 
main = print $ length $ disjoint [1..20]</syntaxhighlight>
 
Build a lexicographic list of consecutive subsequences,
and a list of all subsequences, then subtract one from the other:
<syntaxhighlight lang="haskell">import Data.List (inits, tails)
 
subseqs = foldr (\x s -> [x] : map (x:) s ++ s) []
 
consecs = concatMap (tail.inits) . tails
 
minus [] [] = []
minus (a:as) bb@(b:bs)
| a == b = minus as bs
| otherwise = a:minus as bb
 
disjoint s = (subseqs s) `minus` (consecs s)
 
main = mapM_ print $ disjoint [1..4]</syntaxhighlight>
 
=={{header|J}}==
We select those combinations where the end of the first continuous subsequence appears before the start of the last continuous subsequence:
 
<langsyntaxhighlight Jlang="j">allmasks=: 2 #:@i.@^ #
firstend=:1 0 i.&1@E."1 ]
laststart=: 0 1 {:@I.@E."1 ]
noncont=: <@#~ (#~ firstend < laststart)@allmasks</langsyntaxhighlight>
 
Example use:
<langsyntaxhighlight Jlang="j"> noncont 1+i.4
┌───┬───┬───┬─────┬─────┐
│2 4│1 4│1 3│1 3 4│1 2 4│
Line 732 ⟶ 1,264:
└──┴──┴──┴───┴───┴──┴──┴───┴──┴───┴───┴────┴───┴───┴────┴────┘
#noncont i.10
968</langsyntaxhighlight>
 
Alternatively, since there are relatively few continuous sequences, we could specifically exclude them:
 
<langsyntaxhighlight Jlang="j">contmasks=: a: ;@, 1 <:/~@i.&.>@i.@+ #
noncont=: <@#~ (allmasks -. contmasks)</langsyntaxhighlight>
 
(we get the same behavior from this implementation)
 
=={{header|Java}}==
<syntaxhighlight lang="java">public class NonContinuousSubsequences {
 
public static void main(String args[]) {
seqR("1234", "", 0, 0);
}
 
private static void seqR(String s, String c, int i, int added) {
if (i == s.length()) {
if (c.trim().length() > added)
System.out.println(c);
} else {
seqR(s, c + s.charAt(i), i + 1, added + 1);
seqR(s, c + ' ', i + 1, added);
}
}
}</syntaxhighlight>
 
<pre>12 4
1 34
1 3
1 4
2 4</pre>
 
=={{header|JavaScript}}==
Line 743 ⟶ 1,301:
 
{{works with|SpiderMonkey}}
<langsyntaxhighlight lang="javascript">function non_continuous_subsequences(ary) {
var non_continuous = new Array();
for (var i = 0; i < ary.length; i++) {
Line 766 ⟶ 1,324:
load('json2.js'); /* http://www.json.org/js.html */
 
print(JSON.stringify( non_continuous_subsequences( powerset([1,2,3,4]))));</langsyntaxhighlight>
 
{{out}}
Outputs:
<pre>[[1,3],[1,4],[2,4],[1,2,4],[1,3,4]]</pre>
 
=={{header|Mathematicajq}}==
{{works with|jq|1.4}}
We make all the subsets then filter out the continuous ones:
In order to handle arrays of more than a handful of elements, we define
non_continuous_subsequences/0 as a generator; that is, it produces a
stream of arrays, each of which is a non-continuous subsequence of the given sequence.
 
Since the non-continuous subsequences are dense in the set of all
<lang Mathematica>GoodBad[i_List]:=Not[MatchQ[Differences[i],{1..}|{}]]
subsets, we will use the powerset approach, and accordingly begin by
defining subsets/0 as a generator.
<syntaxhighlight lang="jq"># Generate a stream of subsets of the input array
def subsets:
if length == 0 then []
else .[0] as $first
| (.[1:] | subsets)
| ., ([$first] + .)
end ;
 
# Generate a stream of non-continuous indices in the range 0 <= i < .
def non_continuous_indices:
[range(0;.)] | subsets
| select(length > 1 and length != 1 + .[length-1] - .[0]) ;
 
def non_continuous_subsequences:
(length | non_continuous_indices) as $ix
| [.[ $ix[] ]] ;</syntaxhighlight>
'''Example''':
To show that the above approach can be used for relatively large n, let us count the number of non-continuous subsequences of [0, 1, ..., 19].
<syntaxhighlight lang="jq">def count(f): reduce f as $i (0; . + 1);
 
count( [range(0;20)] | non_continuous_subsequences)
</syntaxhighlight>
{{out}}
$ jq -n -f powerset_generator.jq
1048365
 
=={{header|Julia}}==
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.
 
<tt>NCSubSeq</tt> works by filtering indices according to whether all <tt>1</tt>s in these indices have bit pattern that are contiguous (using the <tt>iscontseq</tt> functions). This is an easy to implement approach. Greater efficiency might be achieved by exploiting the property that a sequence is contiguous if and only if its index is a difference of two powers of 2. This property is used to create the <tt>length(NCSubSeq(n))</tt> function, which gives the number of non-contiguous sub-sequences of a sequence of length <tt>n</tt>.
 
<tt>NCSubSeq</tt> works transparently for sequence lengths up to <tt>WORD_SIZE-1</tt> (typically 63). It can be extended to work for longer sequences by casting <tt>n</tt> to a larger integer, e.g. using <tt>Big(n)</tt>. A more polished implementation would handle this extension behind the scenes.
 
'''Iterator and Functions'''
<syntaxhighlight 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)
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.IteratorSize(::NCSubSeq) = Base.HasLength()
Base.length(a::NCSubSeq) = 2 ^ a.n - a.n * (a.n + 1) ÷ 2 - 1
function Base.iterate(a::NCSubSeq, as::NCSubState=NCSubState(5, makeint2seq(a.n)))
if 2 ^ a.n - 3 < as.m
return nothing
end
s = as.m2s(as.m)
as.m += 1
while iscontseq(as.m)
as.m += 1
end
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(cs))) - m
println("\nThe first and last ", m, " NC sub-sequences of \"", s, "\":")
for (i, a) in enumerate(NCSubSeq(length(s)))
i <= m || n < i || continue
println(@sprintf "%6d %s" i join(cs[a], ""))
i == m || continue
println(" .. ......")
end
 
println("\nThe first and last ", m, " NC sub-sequences of \"", s, "\"")
for x in IterTools.Iterators.flatten([1:10; 20:10:40; big.(50:50:200)])
@printf "%7d → %d\n" x length(NCSubSeq(x))
end
</syntaxhighlight>{{out}}
<pre>
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":
1 Rs
2 Re
3 oe
4 Roe
5 Rse
6 Rt
7 ot
8 Rot
9 st
10 Rst
.. ......
90 otta
91 Rotta
92 stta
93 Rstta
94 ostta
95 Rostta
96 Retta
97 oetta
98 Roetta
99 Rsetta
 
The first and last 10 NC sub-sequences of "Rosetta"
1 → 0
2 → 0
3 → 1
4 → 5
5 → 16
6 → 42
7 → 99
8 → 219
9 → 466
10 → 968
20 → 1048365
30 → 1073741358
40 → 1099511626955
50 → 1125899906841348
100 → 1267650600228229401496703200325
150 → 1427247692705959881058285969449495136382735298
200 → 1606938044258990275541962092341162602522202993782792835281275
</pre>
 
=={{header|Kotlin}}==
<syntaxhighlight lang="scala">// version 1.1.2
 
fun <T> ncs(a: Array<T>) {
fun generate(m: Int, k: Int, c: IntArray) {
if (k == m) {
if (c[m - 1] != c[0] + m - 1) {
for (i in 0 until m) print("${a[c[i]]} ")
println()
}
}
else {
for (j in 0 until a.size) {
if (k == 0 || j > c[k - 1]) {
c[k] = j
generate(m, k + 1, c)
}
}
}
}
 
for (m in 2 until a.size) {
val c = IntArray(m)
generate(m, 0, c)
}
}
 
fun main(args: Array<String>) {
val a = arrayOf(1, 2, 3, 4)
ncs(a)
println()
val ca = arrayOf('a', 'b', 'c', 'd', 'e')
ncs(ca)
}</syntaxhighlight>
 
{{out}}
<pre>
1 3
1 4
2 4
1 2 4
1 3 4
 
a c
a d
a e
b d
b e
c e
a b d
a b e
a c d
a c e
a d e
b c e
b d e
a b c e
a b d e
a c d e
</pre>
 
=={{header|M2000 Interpreter}}==
<syntaxhighlight lang="m2000 interpreter">
Module Non_continuous_subsequences (item$(), display){
Function positions(n) {
function onebit {
=lambda b=false (&c)-> {
=b :if c then b~:c=not b
}
}
dim k(n)=onebit(), p(n)
m=true
flush
for i=1 to 2^n {
for j=0 to n-1 :p(j)= k(j)(&m) :next
m1=p(0)
m2=0
for j=1 to n-1
if m2 then if m1>p(j) then m2=2:exit for
if m1 < p(j) then m2++
m1=p(j)
next
if m2=2 then data cons(p())' push a copy of p() to end of stack
m=true
}
=array([])
}
 
a=positions(len(item$()))
if display then
For i=0 to len(a)-1
b=array(a,i)
line$=format$("{0::-5})",i+1,)
for j=0 to len(b)-1
if array(b,j) then line$+=" "+item$(j)
next
print line$
doc$<=line$+{
}
next
end if
line$="Non continuous subsequences:"+str$(len(a))
Print line$
doc$<=line$+{
}
}
global doc$
document doc$ ' change string to document object
Non_continuous_subsequences ("1","2","3","4"), true
Non_continuous_subsequences ("a","e","i","o","u"), true
Non_continuous_subsequences ("R","o","s","e","t","t","a"), true
Non_continuous_subsequences ("1","2","3","4","5","6","7","8","9","0"), false
clipboard doc$
</syntaxhighlight>
 
{{out}}
<pre style="height:30ex;overflow:scroll">
1) 1 3
2) 1 4
3) 2 4
4) 1 2 4
5) 1 3 4
Non continuous subsequences: 5
1) a i
2) a o
3) e o
4) a e o
5) a i o
6) a u
7) e u
8) a e u
9) i u
10) a i u
11) e i u
12) a e i u
13) a o u
14) e o u
15) a e o u
16) a i o u
Non continuous subsequences: 16
1) R s
2) R e
3) o e
4) R o e
5) R s e
6) R t
7) o t
8) R o t
9) s t
10) R s t
11) o s t
12) R o s t
13) R e t
14) o e t
15) R o e t
16) R s e t
17) R t
18) o t
19) R o t
20) s t
21) R s t
22) o s t
23) R o s t
24) e t
25) R e t
26) o e t
27) R o e t
28) s e t
29) R s e t
30) o s e t
31) R o s e t
32) R t t
33) o t t
34) R o t t
35) s t t
36) R s t t
37) o s t t
38) R o s t t
39) R e t t
40) o e t t
41) R o e t t
42) R s e t t
43) R a
44) o a
45) R o a
46) s a
47) R s a
48) o s a
49) R o s a
50) e a
51) R e a
52) o e a
53) R o e a
54) s e a
55) R s e a
56) o s e a
57) R o s e a
58) t a
59) R t a
60) o t a
61) R o t a
62) s t a
63) R s t a
64) o s t a
65) R o s t a
66) e t a
67) R e t a
68) o e t a
69) R o e t a
70) s e t a
71) R s e t a
72) o s e t a
73) R o s e t a
74) R t a
75) o t a
76) R o t a
77) s t a
78) R s t a
79) o s t a
80) R o s t a
81) e t a
82) R e t a
83) o e t a
84) R o e t a
85) s e t a
86) R s e t a
87) o s e t a
88) R o s e t a
89) R t t a
90) o t t a
91) R o t t a
92) s t t a
93) R s t t a
94) o s t t a
95) R o s t t a
96) R e t t a
97) o e t t a
98) R o e t t a
99) R s e t t a
Non continuous subsequences: 99
Non continuous subsequences: 968
 
</pre >
 
=={{header|Mathematica}}/{{header|Wolfram Language}}==
We make all the subsets then filter out the continuous ones:
<syntaxhighlight lang="mathematica">GoodBad[i_List]:=Not[MatchQ[Differences[i],{1..}|{}]]
n=5
Select[Subsets[Range[n]],GoodBad]</langsyntaxhighlight>
{{out}}
<pre>{{1,3},{1,4},{1,5},{2,4},{2,5},{3,5},{1,2,4},{1,2,5},{1,3,4},{1,3,5},{1,4,5},{2,3,5},{2,4,5},{1,2,3,5},{1,2,4,5},{1,3,4,5}}</pre>
 
=={{header|Nim}}==
gives back:
{{trans|Python}}
<syntaxhighlight lang="nim">import sequtils
 
proc ncsub[T](se: seq[T], s = 0): seq[seq[T]] =
<lang Mathematica> {{1,3},{1,4},{1,5},{2,4},{2,5},{3,5},{1,2,4},{1,2,5},{1,3,4},{1,3,5},{1,4,5},{2,3,5},{2,4,5},{1,2,3,5},{1,2,4,5},{1,3,4,5}}</lang>
result = @[]
if se.len > 0:
let
x = se[0..0]
xs = se[1 .. ^1]
p2 = s mod 2
p1 = (s + 1) mod 2
for ys in ncsub(xs, s + p1):
result.add(x & ys)
result.add(ncsub(xs, s + p2))
elif s >= 3:
result.add(@[])
 
echo "ncsub(", toSeq 1.. 3, ") = ", ncsub(toSeq 1..3)
echo "ncsub(", toSeq 1.. 4, ") = ", ncsub(toSeq 1..4)
echo "ncsub(", toSeq 1.. 5, ") = ", ncsub(toSeq 1..5)</syntaxhighlight>
{{out}}
<pre>ncsub(@[1, 2, 3]) = @[@[1, 3]]
ncsub(@[1, 2, 3, 4]) = @[@[1, 2, 4], @[1, 3, 4], @[1, 3], @[1, 4], @[2, 4]]
ncsub(@[1, 2, 3, 4, 5]) = @[@[1, 2, 3, 5], @[1, 2, 4, 5], @[1, 2, 4], @[1, 2, 5], @[1, 3, 4, 5], @[1, 3, 4], @[1, 3, 5], @[1, 3], @[1, 4, 5], @[1, 4], @[1, 5], @[2, 3, 5], @[2, 4, 5], @[2, 4], @[2, 5], @[3, 5]]</pre>
 
=={{header|OCaml}}==
Line 786 ⟶ 1,760:
{{trans|Generalized monadic filter}}
 
<langsyntaxhighlight lang="ocaml">let rec fence s = function
[] ->
if s >= 3 then
Line 807 ⟶ 1,781:
fence (s + 1) xs
 
let ncsubseq = fence 0</langsyntaxhighlight>
 
Output:
 
{{out}}
<pre># ncsubseq [1;2;3];;
- : int list list = [[1; 3]]
Line 823 ⟶ 1,796:
=={{header|Oz}}==
A nice application of finite set constraints. We just describe what we want and the constraint system will deliver it:
<langsyntaxhighlight lang="oz">declare
fun {NCSubseq SeqList}
Seq = {FS.value.make SeqList}
Line 847 ⟶ 1,820:
end
in
{Inspect {NCSubseq [1 2 3 4]}}</langsyntaxhighlight>
 
=={{header|PARI/GP}}==
Just a simple script, but it's I/O bound so efficiency isn't a concern. (Almost all subsequences are non-contiguous so looping over all possibilities isn't that bad. For length 20 about 99.98% of subsequences are non-contiguous.)
<syntaxhighlight lang="parigp">noncontig(n)=n>>=valuation(n,2);n++;n>>=valuation(n,2);n>1;
nonContigSubseq(v)={
for(i=5,2^#v-1,
if(noncontig(i),
print(vecextract(v,i))
)
)
};
nonContigSubseq([1,2,3])
nonContigSubseq(["a","b","c","d","e"])</syntaxhighlight>
{{out}}
<pre>[1, 3]
 
["a", "c"]
["a", "d"]
["b", "d"]
["a", "b", "d"]
["a", "c", "d"]
["a", "e"]
["b", "e"]
["a", "b", "e"]
["c", "e"]
["a", "c", "e"]
["b", "c", "e"]
["a", "b", "c", "e"]
["a", "d", "e"]
["b", "d", "e"]
["a", "b", "d", "e"]
["a", "c", "d", "e"]</pre>
 
=={{header|Perl}}==
<langsyntaxhighlight lang="perl">my ($max, @current);
sub non_continuous {
my ($idx, $has_gap, $found) = @_;
my $found;
 
for ($idx .. $max) {
Line 865 ⟶ 1,871:
}
 
$max = 20;
$max = 20; # 1048365 sequences, 10 seconds-ish
print "found ", non_continuous(1), " sequences\n";</langsyntaxhighlight>
{{out}}
<pre>found 1048365 sequences</pre>
 
=={{header|Perl 6Phix}}==
Straightforward recursive implementation, the only minor trick is that a gap does not
Uses powerset() function from [[Power Set#Perl_6|here]].
mean non-contiguous until you actually take something later.<br>
<lang perl6>sub non_continuous_subsequences ( *@list ) {
Counts non-contiguous subsequences of sequences of length 1..20 in under half a second
powerset(@list).grep: { 1 != all( .[ 0 ^.. .end] Z- .[0 ..^ .end] ) }
<!--<syntaxhighlight lang="phix">(phixonline)-->
}
<span style="color: #008080;">with</span> <span style="color: #008080;">javascript_semantics</span>
<span style="color: #004080;">integer</span> <span style="color: #000000;">count</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">0</span>
<span style="color: #008080;">procedure</span> <span style="color: #000000;">ncs</span><span style="color: #0000FF;">(</span><span style="color: #004080;">sequence</span> <span style="color: #000000;">rest</span><span style="color: #0000FF;">,</span> <span style="color: #004080;">object</span> <span style="color: #000000;">taken</span><span style="color: #0000FF;">,</span> <span style="color: #004080;">integer</span> <span style="color: #000000;">ri</span><span style="color: #0000FF;">=</span><span style="color: #000000;">0</span><span style="color: #0000FF;">,</span> <span style="color: #004080;">bool</span> <span style="color: #000000;">contig</span><span style="color: #0000FF;">=</span><span style="color: #004600;">false</span><span style="color: #0000FF;">,</span> <span style="color: #004080;">bool</span> <span style="color: #000000;">gap</span><span style="color: #0000FF;">=</span><span style="color: #004600;">false</span><span style="color: #0000FF;">)</span>
<span style="color: #008080;">if</span> <span style="color: #000000;">ri</span><span style="color: #0000FF;">>=</span><span style="color: #7060A8;">length</span><span style="color: #0000FF;">(</span><span style="color: #000000;">rest</span><span style="color: #0000FF;">)</span> <span style="color: #008080;">then</span>
<span style="color: #008080;">if</span> <span style="color: #000000;">contig</span> <span style="color: #008080;">then</span>
<span style="color: #008080;">if</span> <span style="color: #004080;">integer</span><span style="color: #0000FF;">(</span><span style="color: #000000;">taken</span><span style="color: #0000FF;">)</span> <span style="color: #008080;">then</span>
<span style="color: #000000;">count</span> <span style="color: #0000FF;">+=</span> <span style="color: #000000;">1</span>
<span style="color: #008080;">else</span>
<span style="color: #0000FF;">?</span><span style="color: #000000;">taken</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
<span style="color: #008080;">else</span>
<span style="color: #000000;">ri</span> <span style="color: #0000FF;">+=</span> <span style="color: #000000;">1</span>
<span style="color: #000000;">ncs</span><span style="color: #0000FF;">(</span><span style="color: #000000;">rest</span><span style="color: #0000FF;">,</span><span style="color: #008080;">iff</span><span style="color: #0000FF;">(</span><span style="color: #004080;">integer</span><span style="color: #0000FF;">(</span><span style="color: #000000;">taken</span><span style="color: #0000FF;">)?</span><span style="color: #000000;">taken</span><span style="color: #0000FF;">+</span><span style="color: #000000;">1</span><span style="color: #0000FF;">:</span><span style="color: #7060A8;">deep_copy</span><span style="color: #0000FF;">(</span><span style="color: #000000;">taken</span><span style="color: #0000FF;">)&</span><span style="color: #000000;">rest</span><span style="color: #0000FF;">[</span><span style="color: #000000;">ri</span><span style="color: #0000FF;">]),</span><span style="color: #000000;">ri</span><span style="color: #0000FF;">,</span><span style="color: #000000;">gap</span><span style="color: #0000FF;">,</span><span style="color: #000000;">gap</span><span style="color: #0000FF;">)</span>
<span style="color: #000000;">ncs</span><span style="color: #0000FF;">(</span><span style="color: #000000;">rest</span><span style="color: #0000FF;">,</span><span style="color: #000000;">taken</span><span style="color: #0000FF;">,</span><span style="color: #000000;">ri</span><span style="color: #0000FF;">,</span><span style="color: #000000;">contig</span><span style="color: #0000FF;">,</span><span style="color: #008080;">iff</span><span style="color: #0000FF;">(</span><span style="color: #004080;">integer</span><span style="color: #0000FF;">(</span><span style="color: #000000;">taken</span><span style="color: #0000FF;">)?</span><span style="color: #000000;">taken</span><span style="color: #0000FF;">!=</span><span style="color: #000000;">0</span><span style="color: #0000FF;">:</span><span style="color: #7060A8;">length</span><span style="color: #0000FF;">(</span><span style="color: #000000;">taken</span><span style="color: #0000FF;">)!=</span><span style="color: #000000;">0</span><span style="color: #0000FF;">))</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">procedure</span>
<span style="color: #000000;">ncs</span><span style="color: #0000FF;">({</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #000000;">2</span><span style="color: #0000FF;">,</span><span style="color: #000000;">3</span><span style="color: #0000FF;">},{})</span>
<span style="color: #0000FF;">?</span><span style="color: #008000;">"==="</span>
<span style="color: #000000;">ncs</span><span style="color: #0000FF;">({</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #000000;">2</span><span style="color: #0000FF;">,</span><span style="color: #000000;">3</span><span style="color: #0000FF;">,</span><span style="color: #000000;">4</span><span style="color: #0000FF;">},{})</span>
<span style="color: #0000FF;">?</span><span style="color: #008000;">"==="</span>
<span style="color: #004080;">atom</span> <span style="color: #000000;">t0</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">time</span><span style="color: #0000FF;">()</span>
<span style="color: #004080;">sequence</span> <span style="color: #000000;">s</span> <span style="color: #0000FF;">=</span> <span style="color: #0000FF;">{}</span>
<span style="color: #008080;">for</span> <span style="color: #000000;">i</span><span style="color: #0000FF;">=</span><span style="color: #000000;">1</span> <span style="color: #008080;">to</span> <span style="color: #000000;">20</span> <span style="color: #008080;">do</span>
<span style="color: #000000;">count</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">0</span>
<span style="color: #000000;">ncs</span><span style="color: #0000FF;">(</span><span style="color: #7060A8;">tagset</span><span style="color: #0000FF;">(</span><span style="color: #000000;">i</span><span style="color: #0000FF;">),</span><span style="color: #000000;">0</span><span style="color: #0000FF;">)</span>
<span style="color: #000000;">s</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">append</span><span style="color: #0000FF;">(</span><span style="color: #000000;">s</span><span style="color: #0000FF;">,</span><span style="color: #000000;">count</span><span style="color: #0000FF;">)</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">for</span>
<span style="color: #0000FF;">?</span><span style="color: #7060A8;">elapsed</span><span style="color: #0000FF;">(</span><span style="color: #7060A8;">time</span><span style="color: #0000FF;">()-</span><span style="color: #000000;">t0</span><span style="color: #0000FF;">)</span>
<span style="color: #7060A8;">pp</span><span style="color: #0000FF;">(</span><span style="color: #000000;">s</span><span style="color: #0000FF;">)</span>
<!--</syntaxhighlight>-->
{{out}}
<pre>
{1,3}
"==="
{1,2,4}
{1,3,4}
{1,3}
{1,4}
{2,4}
"==="
"0.3s"
{0,0,1,5,16,42,99,219,466,968,1981,4017,8100,16278,32647,65399,130918,261972,524097,1048365}
</pre>
 
=={{header|Picat}}==
sub powerset ( *@list ) {
This approach uses <code>power_set/1</code> (from the <code>util</code> module) to get the proper indices.
reduce( -> @L, $n { [ @L, @L.map: {[ .list, $n ]} ] }, [[]], @list );
 
}
<syntaxhighlight lang="picat">import util.
 
go =>
println(1..4=non_cont(1..4)),
L = "abcde".reverse(),
println(L=non_cont(L)),
println(ernit=non_cont("ernit")),
println(aaa=non_cont("aaa")),
println(aeiou=non_cont("aeiou")),
nl,
 
println("Printing just the lengths for 1..N for N = 1..20:"),
foreach(N in 1..20)
println(1..N=non_cont(1..N).length) % just the length
end,
nl.
 
% get all the non-continuous subsequences
non_cont(L) = [ [L[I] : I in S] : S in non_cont_ixs(L.length)].
 
% get all the index positions that are non-continuous
non_cont_ixs(N) = [ P: P in power_set(1..N), length(P) > 1, P.last() - P.first() != P.length-1].</syntaxhighlight>
 
{{out}}
<pre>[1,2,3,4] = [[2,4],[1,4],[1,3],[1,3,4],[1,2,4]]
edcba = [ca,da,db,dba,dca,ea,eb,eba,ec,eca,ecb,ecba,eda,edb,edba,edca]
ernit = [nt,rt,ri,rit,rnt,et,ei,eit,en,ent,eni,enit,ert,eri,erit,ernt]
aaa = [aa]
aeiou = [iu,eu,eo,eou,eiu,au,ao,aou,ai,aiu,aio,aiou,aeu,aeo,aeou,aeiu]
 
Printing just the lengths for 1..N for N = 1..20:
say ~ non_continuous_subsequences( 1..3 )».perl;
[1] = 0
say ~ non_continuous_subsequences( 1..4 )».perl;
[1,2] = 0
say ~ non_continuous_subsequences( ^4 ).map: {[<a b c d>[.list]].perl};</lang>
Output:<pre>[1, 2,3] = 1
[1, 3] [1, 4] [2, 4] [13, 2, 4] [1,= 3, 4]5
[1,2,3,4,5] = 16
["a", "c"] ["a", "d"] ["b", "d"] ["a", "b", "d"] ["a", "c", "d"]</pre>
[1,2,3,4,5,6] = 42
[1,2,3,4,5,6,7] = 99
[1,2,3,4,5,6,7,8] = 219
[1,2,3,4,5,6,7,8,9] = 466
[1,2,3,4,5,6,7,8,9,10] = 968
[1,2,3,4,5,6,7,8,9,10,11] = 1981
[1,2,3,4,5,6,7,8,9,10,11,12] = 4017
[1,2,3,4,5,6,7,8,9,10,11,12,13] = 8100
[1,2,3,4,5,6,7,8,9,10,11,12,13,14] = 16278
[1,2,3,4,5,6,7,8,9,10,11,12,13,14,15] = 32647
[1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16] = 65399
[1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17] = 130918
[1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18] = 261972
[1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19] = 524097
[1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20] = 1048365</pre>
 
=={{header|PicoLisp}}==
{{trans|Scheme}}
<langsyntaxhighlight PicoLisplang="picolisp">(de ncsubseq (Lst)
(let S 0
(recur (S Lst)
Line 901 ⟶ 1,999:
(mapcar '((YS) (cons X YS))
(recurse S XS) )
(recurse (inc S) XS) ) ) ) ) ) ) )</langsyntaxhighlight>
 
=={{header|Pop11}}==
Line 908 ⟶ 2,006:
variables to keep track if subsequence is continuous.
 
<langsyntaxhighlight lang="pop11">define ncsubseq(l);
lvars acc = [], gap_started = false, is_continuous = true;
define do_it(l1, l2);
Line 931 ⟶ 2,029:
enddefine;
 
ncsubseq([1 2 3 4 5]) =></langsyntaxhighlight>
 
{{out}}
Output:
<lang pop11pre>[[1 3] [1 4] [2 4] [1 2 4] [1 3 4] [1 5] [2 5] [1 2 5] [3 5] [1 3 5]
[2 3 5] [1 2 3 5] [1 4 5] [2 4 5] [1 2 4 5] [1 3 4 5]]</langpre>
 
=={{header|PowerShell}}==
<langsyntaxhighlight PowerShelllang="powershell">Function SubSequence ( [Array] $S, [Boolean] $all=$false )
{
$sc = $S.count
Line 1,006 ⟶ 2,104:
}
 
( NonContinuous-SubSequence 'a','b','c','d','e' ) | Select-Object length, @{Name='value';Expression={ $_ } } | Sort-Object length, value | ForEach-Object { $_.value }</langsyntaxhighlight>
 
=={{header|Prolog}}==
Line 1,012 ⟶ 2,110:
We explain to Prolog how to build a non continuous subsequence of a list L, then we ask Prolog to fetch all the subsequences.
 
<syntaxhighlight lang="prolog">
<lang Prolog>
% fetch all the subsequences
ncsubs(L, LNCSL) :-
Line 1,038 ⟶ 2,136:
reverse(L, [_|SL1]),
reverse(SL1, SL)).
</syntaxhighlight>
</lang>
Example :
<langsyntaxhighlight Prologlang="prolog">?- ncsubs([a,e,i,o,u], L).
L = [[a,e,i,u],[a,e,o],[a,e,o,u],[a,e,u],[a,i],[a,i,o],[a,i,o,u],[a,i,u],[a,o],[a,o,u],[a,u],[e,i,u],[e,o],[e,o,u],[e,u],[i,u]]</langsyntaxhighlight>
 
=={{header|Python}}==
{{trans|Scheme}}
 
<langsyntaxhighlight lang="python">def ncsub(seq, s=0):
if seq:
x = seq[:1]
Line 1,054 ⟶ 2,152:
return [x + ys for ys in ncsub(xs, s + p1)] + ncsub(xs, s + p2)
else:
return [[]] if s >= 3 else []</langsyntaxhighlight>
 
Output:
 
{{out}}
<pre>>>> ncsub(range(1, 4))
[[1, 3]]
Line 1,069 ⟶ 2,166:
A faster Python + Psyco JIT version:
 
<langsyntaxhighlight lang="python">from sys import argv
import psyco
 
Line 1,108 ⟶ 2,205:
psyco.full()
n = 10 if len(argv) < 2 else int(argv[1])
print len( ncsub(range(1, n)) )</langsyntaxhighlight>
 
=={{header|Quackery}}==
 
A sequence of n items has 2^n possible subsequences, including the empty sequence. These correspond to the numbers 0 to 2^n-1, where a one in the binary expansion of the number indicates inclusion in the subsequence of the corresponding item in the sequence. Non-continuous subsequences correspond to numbers where the binary expansion of the number has a one, followed by one or more zeroes, followed by a one.
 
<syntaxhighlight lang="quackery"> [ dup 1 & dip [ 1 >> ] ] is 2/mod ( n --> n n )
 
[ 0 swap
[ dup 0 != while
2/mod iff
[ dip 1+ ] done
again ]
[ dup 0 != while
2/mod not iff
[ dip 1+ ] done
again ]
[ dup 0 != while
2/mod iff
[ dip 1+ ] done
again ]
drop 3 = ] is noncontinuous ( n --> b )
 
[ [] unrot
[ dup 0 != while
dip behead tuck
1 & iff
[ nested dip rot
join unrot ]
else drop
1 >> again ]
2drop ] is bitems ( [ n --> [ )
 
[ [] swap
dup size bit times
[ i^ noncontinuous if
[ dup i^ bitems
nested rot
join swap ] ]
drop ] is ncsubs ( [ --> [ )
 
' [ 1 2 3 4 ] ncsubs echo cr
$ "quackery" ncsubs 72 wrap$</syntaxhighlight>
 
{{out}}
 
<pre>[ [ 1 3 4 ] [ 1 2 4 ] [ 2 4 ] [ 1 4 ] [ 1 3 ] ]
 
qackery quckery uckery qckery quakery uakery qakery akery qukery ukery
qkery quacery uacery qacery acery qucery ucery qcery cery quaery uaery
qaery aery query uery qery quackry uackry qackry ackry quckry uckry
qckry ckry quakry uakry qakry akry qukry ukry qkry kry quacry uacry
qacry acry qucry ucry qcry cry quary uary qary ary qury ury qry quackey
uackey qackey ackey quckey uckey qckey ckey quakey uakey qakey akey
qukey ukey qkey key quacey uacey qacey acey qucey ucey qcey cey quaey
uaey qaey aey quey uey qey ey quacky uacky qacky acky qucky ucky qcky
cky quaky uaky qaky aky quky uky qky ky quacy uacy qacy acy qucy ucy qcy
cy quay uay qay ay quy uy qy qacker qucker ucker qcker quaker uaker
qaker aker quker uker qker quacer uacer qacer acer qucer ucer qcer cer
quaer uaer qaer aer quer uer qer quackr uackr qackr ackr quckr uckr qckr
ckr quakr uakr qakr akr qukr ukr qkr kr quacr uacr qacr acr qucr ucr qcr
cr quar uar qar ar qur ur qr qacke qucke ucke qcke quake uake qake ake
quke uke qke quace uace qace ace quce uce qce ce quae uae qae ae que ue
qe qack quck uck qck quak uak qak ak quk uk qk qac quc uc qc qa
</pre>
 
=={{header|R}}==
The idea behind this is to loop over the possible lengths of subsequence, finding all subsequences then discarding those which are continuous.
 
<langsyntaxhighlight lang="r">ncsub <- function(x)
{
n <- length(x)
Line 1,129 ⟶ 2,291:
# Example usage
ncsub(1:4)
ncsub(letters[1:5])</langsyntaxhighlight>
 
=={{header|Racket}}==
 
Take a simple <tt>subsets</tt> definition:
<syntaxhighlight lang="racket">
(define (subsets l)
(if (null? l) '(())
(append (for/list ([l2 (subsets (cdr l))]) (cons (car l) l2))
(subsets (cdr l)))))
</syntaxhighlight>
since the subsets are returned in their original order, it is also a sub-sequences function.
 
Now add to it a "state" counter which count one for each chunk of items included or excluded. It's always even when we're in an excluded chunk (including the beginning) and odd when we're including items -- increment it whenever we switch from one kind of chunk to the other. This means that we should only include subsequences where the state is 3 (included->excluded->included) or more. Note that this results in code that is similar to the "Generalized monadic filter" entry, except a little simpler.
 
<syntaxhighlight lang="racket">
#lang racket
(define (non-continuous-subseqs l)
(let loop ([l l] [x 0])
(if (null? l) (if (>= x 3) '(()) '())
(append (for/list ([l2 (loop (cdr l) (if (even? x) (add1 x) x))])
(cons (car l) l2))
(loop (cdr l) (if (odd? x) (add1 x) x))))))
(non-continuous-subseqs '(1 2 3 4))
;; => '((1 2 4) (1 3 4) (1 3) (1 4) (2 4))
</syntaxhighlight>
 
=={{header|Raku}}==
(formerly Perl 6)
{{works with|rakudo|2015-09-24}}
<syntaxhighlight lang="raku" line>sub non_continuous_subsequences ( *@list ) {
@list.combinations.grep: { 1 != all( .[ 0 ^.. .end] Z- .[0 ..^ .end] ) }
}
 
say non_continuous_subsequences( 1..3 )».gist;
say non_continuous_subsequences( 1..4 )».gist;
say non_continuous_subsequences( ^4 ).map: {[<a b c d>[.list]].gist};</syntaxhighlight>
{{out}}
<pre>((1 3))
((1 3) (1 4) (2 4) (1 2 4) (1 3 4))
([a c] [a d] [b d] [a b d] [a c d])</pre>
 
=={{header|REXX}}==
This REXX version also works with non-numeric (alphabetic) items &nbsp; (as well as numbers).
<lang rexx>/*REXX program to list non-continuous subsequences.---------------------*/
<syntaxhighlight lang="rexx">/*REXX program lists all the non─continuous subsequences (NCS), given a sequence. */
parse arg list /*the the list from arg. */
ifparse arg list=='' then list=1 2 3 4 /*ifobtain optional null,argument thenfrom usethe defaultCL.*/
if list=space(list)'' | list=="," then list= 1 2 3 4 5 /*Not specified? Then use the /*remove extraneous blanksdefault.*/
say 'list=' space(list); say say /*echodisplay the list to consolethe terminal. */
w= words(list) /*W: is the number of wordsitems in list. */
seqsnums=0 strip( left(123456789, w) ) /*build a string of decimal digits. /*number of NCS's so far. */
tail= right(nums, max(0, w-2) ) /*construct a fast tail for comparisons*/
#= 0 /*#: number of non─continuous subseq. */
do j=13 to left(nums,1) || tail /*step through list (using smart start)*/
if verify(j, nums) \== 0 then iterate /*Not one of the chosen (sequences) ? */
f= left(j, 1) /*use the fist decimal digit of J. */
NCS= 0 /*so far, no non─continuous subsequence*/
do k=2 for length(j)-1 /*search for " " " */
x= substr(j, k, 1) /*extract a single decimal digit of J.*/
if x <= f then iterate j /*if next digit ≤, then skip this digit*/
if x \== f+1 then NCS= 1 /*it's OK as of now (that is, so far).*/
f= x /*now have a new next decimal digit. */
end /*k*/
$=
if \NCS then iterate /*not OK? Then skip this number (item)*/
#= # + 1 /*Eureka! We found a number (or item).*/
do m=1 for length(j) /*build a sequence string to display. */
$= $ word(list, substr(j, m, 1) ) /*obtain a number (or item) to display.*/
end /*m*/
 
do j=1 for w say 'a non─continuous subsequence: ' $ /*step thoughtshow the listnon─continuous subsequence. */
do k=2 to w end /*insure non-continuity. j*/
say _=word(list,j) /*assumehelp theensure startvisual offidelity NCS.in output*/
if #==0 then #= 'no' do m=j+k to w /*non-continuitymake skipit islook Kmore gooder Angleshy. */
say # "non─continuous subsequence"s(#) 'were found.' /*handle plurals.*/
_=_ word(list,m)
exit 0 if words(_)\==1 then do /*havestick wea foundfork ain it, we're NCSall yet?done. */
/*──────────────────────────────────────────────────────────────────────────────────────*/
seqs=seqs+1 /*bump the NCS counter. */
s: if arg(1)==1 then return ''; return word( arg(2) 's', 1) /*simple pluralizer.*/</syntaxhighlight>
say _ /*display the NCS. */
{{out|output|text=&nbsp; when using the input of: &nbsp; &nbsp; <tt> 1 &nbsp; 2 &nbsp; 3 &nbsp; 4 </tt>}}
end
<pre>
end /*m*/
list= 1 2 3 4
end /*k*/
end /*j*/
 
a non-continuous subsequence: 1 3
say; say 'The list has' seqs "non-continuous subsequences."</lang>
a non-continuous subsequence: 1 4
'''output''' when using the default input
a non-continuous subsequence: 2 4
<pre style="overflow:scroll">
a non-continuous subsequence: 1 2 4
list=1 2 3 4
a non-continuous subsequence: 1 3 4
 
5 non-continuous subsequences were found.
1 3
</pre>
1 3 4
{{out|output|text=&nbsp; when using the input of: &nbsp; &nbsp; <tt> a &nbsp; e &nbsp; I &nbsp; o &nbsp; u </tt>}}
1 4
<pre>
2 4
list= a e I o u
 
The list has 4a non-continuous subsequences.subsequence: a I
a non-continuous subsequence: a o
a non-continuous subsequence: a u
a non-continuous subsequence: e o
a non-continuous subsequence: e u
a non-continuous subsequence: I u
a non-continuous subsequence: a e o
a non-continuous subsequence: a e u
a non-continuous subsequence: a I o
a non-continuous subsequence: a I u
a non-continuous subsequence: a o u
a non-continuous subsequence: e I u
a non-continuous subsequence: e o u
a non-continuous subsequence: a e I u
a non-continuous subsequence: a e o u
a non-continuous subsequence: a I o u
 
16 non-continuous subsequences were found.
</pre>
'''{{out|output'''|text=&nbsp; when using the following [five channel Islands (Great Britain)] as input: &nbsp; &nbsp; <tt> aAlderney &nbsp; Guernsey &nbsp; Herm e&nbsp; IJersey o&nbsp; uSark </tt>}}
<pre>
<pre style="overflow:scroll">
list=a eAlderney IGuernsey oHerm uJersey Sark
 
a non-continuous subsequence: Alderney Herm
a I
a non-continuous subsequence: Alderney Jersey
a I o
a non-continuous subsequence: Alderney Sark
a I o u
a non-continuous subsequence: Guernsey Jersey
a o
a non-continuous subsequence: Guernsey Sark
a o u
a non-continuous subsequence: Herm Sark
a u
a non-continuous subsequence: Alderney Guernsey Jersey
e o
a non-continuous subsequence: Alderney Guernsey Sark
e o u
a non-continuous subsequence: Alderney Herm Jersey
e u
a non-continuous subsequence: Alderney Herm Sark
I u
a non-continuous subsequence: Alderney Jersey Sark
a non-continuous subsequence: Guernsey Herm Sark
a non-continuous subsequence: Guernsey Jersey Sark
a non-continuous subsequence: Alderney Guernsey Herm Sark
a non-continuous subsequence: Alderney Guernsey Jersey Sark
a non-continuous subsequence: Alderney Herm Jersey Sark
 
The list has 1016 non-continuous subsequences were found.
</pre>
'''{{out|output'''|text=&nbsp; when using the following [channelsix Islandsnoble (Great Britain)gases] as input: &nbsp; &nbsp; <tt> Alderneyhelium &nbsp; neon &nbsp; argon &nbsp; krypton Guernsey&nbsp; Hermxenon Jersey&nbsp; Sarkradon </tt>}}
<pre>
<pre style="overflow:scroll">
list= helium neon argon krypton xenon radon
list=Alderney Guernsey Herm Jersey Sark
 
a non-continuous subsequence: helium argon
Alderney Herm
a non-continuous subsequence: helium krypton
Alderney Herm Jersey
a non-continuous subsequence: helium xenon
Alderney Herm Jersey Sark
a non-continuous subsequence: helium radon
Alderney Jersey
a non-continuous subsequence: neon krypton
Alderney Jersey Sark
a non-continuous subsequence: neon xenon
Alderney Sark
a non-continuous subsequence: neon radon
Guernsey Jersey
a non-continuous subsequence: argon xenon
Guernsey Jersey Sark
a non-continuous subsequence: argon radon
Guernsey Sark
a non-continuous subsequence: krypton radon
Herm Sark
a non-continuous subsequence: helium neon krypton
a non-continuous subsequence: helium neon xenon
a non-continuous subsequence: helium neon radon
a non-continuous subsequence: helium argon krypton
a non-continuous subsequence: helium argon xenon
a non-continuous subsequence: helium argon radon
a non-continuous subsequence: helium krypton xenon
a non-continuous subsequence: helium krypton radon
a non-continuous subsequence: helium xenon radon
a non-continuous subsequence: neon argon xenon
a non-continuous subsequence: neon argon radon
a non-continuous subsequence: neon krypton xenon
a non-continuous subsequence: neon krypton radon
a non-continuous subsequence: neon xenon radon
a non-continuous subsequence: argon krypton radon
a non-continuous subsequence: argon xenon radon
a non-continuous subsequence: helium neon argon xenon
a non-continuous subsequence: helium neon argon radon
a non-continuous subsequence: helium neon krypton xenon
a non-continuous subsequence: helium neon krypton radon
a non-continuous subsequence: helium neon xenon radon
a non-continuous subsequence: helium argon krypton xenon
a non-continuous subsequence: helium argon krypton radon
a non-continuous subsequence: helium argon xenon radon
a non-continuous subsequence: helium krypton xenon radon
a non-continuous subsequence: neon argon krypton radon
a non-continuous subsequence: neon argon xenon radon
a non-continuous subsequence: neon krypton xenon radon
a non-continuous subsequence: helium neon argon krypton radon
a non-continuous subsequence: helium neon argon xenon radon
a non-continuous subsequence: helium neon krypton xenon radon
a non-continuous subsequence: helium argon krypton xenon radon
 
The list has 1042 non-continuous subsequences were found.
</pre>
'''output''' when using the following [six nobel gases] as input: <tt> helium neon argon krypton xenon radon </tt>
<pre style="overflow:scroll">
list=helium neon argon kyptron xenon radon
 
=={{header|Ring}}==
helium argon
<syntaxhighlight lang="ring">
helium argon kyptron
# Project : Non-continuous subsequences
helium argon kyptron xenon
 
helium argon kyptron xenon radon
load "stdlib.ring"
helium kyptron
list = [1,2,3,4]
helium kyptron xenon
items = newlist(pow(2,len(list))-1,len(list))
helium kyptron xenon radon
see "For [1, 2, 3, 4] non-continuous subsequences are:" + nl
helium xenon
powerset(list,4)
helium xenon radon
showarray(items,4)
helium radon
see nl
neon kyptron
 
neon kyptron xenon
list = [1,2,3,4,5]
neon kyptron xenon radon
items = newlist(pow(2,len(list))-1,len(list))
neon xenon
see "For [1, 2, 3, 4, 5] non-continuous subsequences are:" + nl
neon xenon radon
powerset(list,5)
neon radon
showarray(items,5)
argon xenon
 
argon xenon radon
func showarray(items,ind)
argon radon
for n = 1 to len(items)
kyptron radon
flag = 0
for m = 1 to ind - 1
if items[n][m] = 0 or items[n][m+1] = 0
exit
ok
if (items[n][m] + 1) != items[n][m+1]
flag = 1
exit
ok
next
if flag = 1
see "["
str = ""
for x = 1 to len(items[n])
if items[n][x] != 0
str = str + items[n][x] + " "
ok
next
str = left(str, len(str) - 1)
see str + "]" + nl
ok
next
 
func powerset(list,ind)
num = 0
num2 = 0
items = newlist(pow(2,len(list))-1,ind)
for i = 2 to (2 << len(list)) - 1 step 2
num2 = 0
num = num + 1
for j = 1 to len(list)
if i & (1 << j)
num2 = num2 + 1
if list[j] != 0
items[num][num2] = list[j]
ok
ok
next
next
return items
</syntaxhighlight>
Output:
<pre>
For [1, 2, 3, 4] non-continuous subsequences are:
[1 3]
[1 4]
[2 4]
[1 2 4]
[1 3 4]
 
TheFor list[1, has2, 203, 4, 5] non-continuous subsequences. are:
[1 3]
[1 4]
[2 4]
[1 2 4]
[1 3 4]
[1 5]
[2 5]
[1 2 5]
[3 5]
[1 3 5]
[2 3 5]
[1 2 3 5]
[1 4 5]
[2 4 5]
[1 2 4 5]
[1 3 4 5]
</pre>
 
Line 1,232 ⟶ 2,570:
Uses code from [[Power Set]].
 
<langsyntaxhighlight lang="ruby">class Array
def func_power_set
inject([[]]) { |ps,item| # for each item in the Array
Line 1,239 ⟶ 2,577:
}
end
 
def non_continuous_subsequences
func_power_set.find_allreject {|seq| not continuous?(seq.continuous)}
end
 
def continuous?(seq)
seq.each_cons(2) {|a, b| return false if a+1.succ != b}
true
end
Line 1,252 ⟶ 2,590:
p (1..3).to_a.non_continuous_subsequences
p (1..4).to_a.non_continuous_subsequences
p (1..5).to_a.non_continuous_subsequences</lang>
p ("a".."d").to_a.non_continuous_subsequences</syntaxhighlight>
 
{{out}}
<pre>[[1, 3]]
[[1, 3], [1, 4], [2, 4], [1, 2, 4], [1, 3, 4]]
[[1, 3], [1, 4], [2, 4], [1, 2, 4], [1, 3, 4], [1, 5], [2, 5], [1, 2, 5], [3, 5], [1, 3, 5],
[2, 3, 5], [1, 2, 3, 5], [1, 4, 5], [2, 4, 5], [1, 2, 4, 5], [1, 3, 4, 5]]</pre>
[["a", "c"], ["a", "d"], ["b", "d"], ["a", "b", "d"], ["a", "c", "d"]]
</pre>
It is not the value of the array element and when judging continuation in the position, it changes as follows.
<syntaxhighlight lang="ruby">class Array
def continuous?(seq)
seq.each_cons(2) {|a, b| return false if index(a)+1 != index(b)}
true
end
end
 
p %w(a e i o u).non_continuous_subsequences</syntaxhighlight>
=={{header|Scheme}}==
 
{{out}}
{{trans|Generalized monadic filter}}
<pre>[["a", "i"], ["a", "o"], ["e", "o"], ["a", "e", "o"], ["a", "i", "o"], ["a", "u"], ["e", "u"], ["a", "e", "u"], ["i", "u"], ["a", "i", "u"], ["e", "i", "u"], ["a", "e", "i", "u"], ["a", "o", "u"], ["e", "o", "u"], ["a", "e", "o", "u"], ["a", "i", "o", "u"]]</pre>
 
=={{header|Scala}}==
<lang scheme>(define (ncsubseq lst)
<syntaxhighlight lang="scala">object NonContinuousSubSequences extends App {
 
private def seqR(s: String, c: String, i: Int, added: Int): Unit = {
if (i == s.length) {
if (c.trim.length > added) println(c)
} else {
seqR(s, c + s(i), i + 1, added + 1)
seqR(s, c + " ", i + 1, added)
}
}
 
seqR("1234", "", 0, 0)
}</syntaxhighlight>
 
=={{header|Scheme}}==
{{trans|Generalized monadic filter}}
<syntaxhighlight lang="scheme">(define (ncsubseq lst)
(let recurse ((s 0)
(lst lst))
Line 1,280 ⟶ 2,647:
(map (lambda (ys) (cons x ys))
(recurse s xs))
(recurse (+ s 1) xs)))))))</langsyntaxhighlight>
 
Output:
 
{{out}}
<pre>> (ncsubseq '(1 2 3))
((1 3))
Line 1,290 ⟶ 2,656:
> (ncsubseq '(1 2 3 4 5))
((1 2 3 5) (1 2 4 5) (1 2 4) (1 2 5) (1 3 4 5) (1 3 4) (1 3 5) (1 3) (1 4 5) (1 4) (1 5) (2 3 5) (2 4 5) (2 4) (2 5) (3 5))</pre>
 
=={{header|Seed7}}==
<syntaxhighlight lang="seed7">$ include "seed7_05.s7i";
 
const func array bitset: ncsub (in bitset: seq, in integer: s) is func
result
var array bitset: subseq is 0 times {};
local
var bitset: x is {};
var bitset: xs is {};
var bitset: ys is {};
begin
if seq <> {} then
x := {min(seq)};
xs := seq - x;
for ys range ncsub(xs, s + 1 - s rem 2) do
subseq &:= x | ys;
end for;
subseq &:= ncsub(xs, s + s rem 2);
elsif s >= 3 then
subseq &:= {};
end if;
end func;
 
const proc: main is func
local
var bitset: seq is {};
begin
for seq range ncsub({1, 2, 3, 4}, 0) do
writeln(seq);
end for;
end func;</syntaxhighlight>
 
{{out}}
<pre>
{1, 2, 4}
{1, 3, 4}
{1, 3}
{1, 4}
{2, 4}
</pre>
 
=={{header|Sidef}}==
{{trans|Perl}}
<syntaxhighlight lang="ruby">func non_continuous(min, max, subseq=[], has_gap=false) {
 
static current = [];
 
range(min, max).each { |i|
current.push(i);
has_gap && subseq.append([current...]);
i < max && non_continuous(i.inc, max, subseq, has_gap);
current.pop;
has_gap = current.len;
}
 
subseq;
}
 
say non_continuous(1, 3);
say non_continuous(1, 4);
say non_continuous("a", "d");</syntaxhighlight>
{{out}}
<pre>
[[1, 3]]
[[1, 2, 4], [1, 3], [1, 3, 4], [1, 4], [2, 4]]
[["a", "b", "d"], ["a", "c"], ["a", "c", "d"], ["a", "d"], ["b", "d"]]
</pre>
 
=={{header|Standard ML}}==
Line 1,295 ⟶ 2,729:
{{trans|Generalized monadic filter}}
 
<langsyntaxhighlight lang="sml">fun fence s [] =
if s >= 3 then
[[]]
Line 1,315 ⟶ 2,749:
fence (s + 1) xs
 
fun ncsubseq xs = fence 0 xs</langsyntaxhighlight>
 
Output:
 
{{out}}
<pre>- ncsubseq [1,2,3];
val it = [[1,3]] : int list list
Line 1,331 ⟶ 2,764:
This Tcl implementation uses the ''subsets'' function from [[Power Set]], which is acceptable as that conserves the ordering, as well as a problem-specific test function ''is_not_continuous'' and a generic list filter ''lfilter'':
 
<langsyntaxhighlight Tcllang="tcl"> proc subsets l {
set res [list [list]]
foreach e $l {
Line 1,353 ⟶ 2,786:
 
% lfilter is_not_continuous [subsets {1 2 3 4}]
{1 3} {1 4} {2 4} {1 2 4} {1 3 4}</langsyntaxhighlight>
 
=={{header|Ursala}}==
Line 1,359 ⟶ 2,792:
To do it the lazy programmer way, apply the powerset library function to the list, which will generate all continuous and non-continuous subsequences of it, and then delete the subsequences that are also substrings (hence continuous) using a judicious combination of the built in substring predicate (K3), negation (Z), and distributing filter (K17) operator suffixes. This function will work on lists of any type. To meet the requirement for structural equivalence, the list items are first uniquely numbered (num), and the numbers are removed afterwards (rSS).
 
<langsyntaxhighlight Ursalalang="ursala">#import std
 
noncontinuous = num; ^rlK3ZK17rSS/~& powerset
Line 1,365 ⟶ 2,798:
#show+
 
examples = noncontinuous 'abcde'</langsyntaxhighlight>
 
Output:
 
{{out}}
<pre>abce
abd
Line 1,385 ⟶ 2,817:
be
ce</pre>
 
=={{header|VBScript}}==
{{trans|BBC BASIC}}
<syntaxhighlight lang="vb">'Non-continuous subsequences - VBScript - 03/02/2021
 
Function noncontsubseq(l)
Dim i, j, g, n, r, s, w, m
Dim a, b, c
n = Ubound(l)
For s = 0 To n-2
For g = s+1 To n-1
a = "["
For i = s To g-1
a = a & l(i) & ", "
Next 'i
For w = 1 To n-g
r = n+1-g-w
For i = 1 To 2^r-1 Step 2
b = a
For j = 0 To r-1
If i And 2^j Then b=b & l(g+w+j) & ", "
Next 'j
c = (Left(b, Len(b)-1))
WScript.Echo Left(c, Len(c)-1) & "]"
m = m+1
Next 'i
Next 'w
Next 'g
Next 's
noncontsubseq = m
End Function 'noncontsubseq
 
list = Array("1", "2", "3", "4")
WScript.Echo "List: [" & Join(list, ", ") & "]"
nn = noncontsubseq(list)
WScript.Echo nn & " non-continuous subsequences" </syntaxhighlight>
{{out}}
<pre>
List: [1, 2, 3, 4]
[1, 3]
[1, 3, 4]
[1, 4]
[1, 2, 4]
[2, 4]
5 non-continuous subsequences
</pre>
 
=={{header|Wren}}==
{{trans|Kotlin}}
{{libheader|Wren-fmt}}
Needed a bit of doctoring to do the character example as Wren only has strings.
<syntaxhighlight lang="wren">import "./fmt" for Fmt
 
var ncs = Fn.new { |a|
var f = "$d "
if (a[0] is String) {
for (i in 0...a.count) a[i] = a[i].bytes[0]
f = "$c "
}
var generate // recursive
generate = Fn.new { |m, k, c|
if (k == m) {
if (c[m - 1] != c[0] + m - 1) {
for (i in 0...m) Fmt.write(f, a[c[i]])
System.print()
}
} else {
for (j in 0...a.count) {
if (k == 0 || j > c[k - 1]) {
c[k] = j
generate.call(m, k + 1, c)
}
}
}
}
 
for (m in 2...a.count) {
var c = List.filled(m, 0)
generate.call(m, 0, c)
}
}
 
var a = [1, 2, 3, 4]
ncs.call(a)
System.print()
var ca = ["a", "b", "c", "d", "e"]
ncs.call(ca)</syntaxhighlight>
 
{{out}}
<pre>
1 3
1 4
2 4
1 2 4
1 3 4
 
a c
a d
a e
b d
b e
c e
a b d
a b e
a c d
a c e
a d e
b c e
b d e
a b c e
a b d e
a c d e
</pre>
 
=={{header|XPL0}}==
{{trans|Wren}}
<syntaxhighlight lang "XPL0">proc NCS(A, Size, Char);
int A, Size, Char;
int C, M;
 
proc Generate(M, K, C); \recursive
int M, K, C;
int I, J;
[if K = M then
[if C(M-1) # C(0)+M-1 then
[for I:= 0 to M-1 do
[if Char then ChOut(0, A(C(I)))
else IntOut(0, A(C(I)));
ChOut(0, ^ );
];
CrLf(0);
];
]
else
[for J:= 0 to Size-1 do
[if K = 0 or J > C(K-1) then
[C(K):= J;
Generate(M, K+1, C);
];
];
];
];
 
[C:= Reserve(Size*4);
for M:= 2 to Size-1 do Generate(M, 0, C);
];
 
int A, CA;
[A:= [1, 2, 3, 4];
NCS(A, 4, false);
CrLf(0);
CA:= [^a, ^b, ^c, ^d, ^e];
NCS(CA, 5, true);
]</syntaxhighlight>
{{out}}
<pre>
1 3
1 4
2 4
1 2 4
1 3 4
 
a c
a d
a e
b d
b e
c e
a b d
a b e
a c d
a c e
a d e
b c e
b d e
a b c e
a b d e
a c d e
</pre>
 
=={{header|zkl}}==
{{trans|JavaScript}}
<syntaxhighlight lang="zkl">fcn non_continuous_subsequences(ary){
pwerSet(ary).filter(fcn(list){(not isContinuous(list)) })
}
fcn isContinuous(ary){
if(ary.len()<2) return(True);
foreach n in (ary.len()-1){ if(1+ary[n]!=ary[n+1]) return(False); }
return(True);
}
non_continuous_subsequences(T(1,2,3,4)).println();</syntaxhighlight>
<syntaxhighlight lang="zkl">fcn pwerSet(list){
(0).pump(list.len(),List,List,Utils.Helpers.pickNFrom.fp1(list),
T(T,Void.Write,Void.Write) ) .append(list)
}</syntaxhighlight>
<syntaxhighlight lang="zkl">fcn brokenSubsequences(str){
pwerSet(str.split("")).apply("concat")
.filter('wrap(substr){ (not str.holds(substr)) })
}
brokenSubsequences("1234").println();</syntaxhighlight>
{{out}}
<pre>
L(L(1,3),L(1,4),L(2,4),L(1,2,4),L(1,3,4))
L("13","14","24","124","134")
</pre>
2,054

edits