Common sorted list: Difference between revisions

From Rosetta Code
Content added Content deleted
(Added solution for Action!)
 
(18 intermediate revisions by 15 users not shown)
Line 13: Line 13:


=={{header|11l}}==
=={{header|11l}}==
<lang 11l>F csl(nums)
<syntaxhighlight lang="11l">F csl(nums)
Set[Int] r
Set[Int] r
L(num) nums
L(num) nums
Line 19: Line 19:
R sorted(Array(r))
R sorted(Array(r))


print(csl([[5, 1, 3, 8, 9, 4, 8, 7], [3, 5, 9, 8, 4], [1, 3, 7, 9]]))</lang>
print(csl([[5, 1, 3, 8, 9, 4, 8, 7], [3, 5, 9, 8, 4], [1, 3, 7, 9]]))</syntaxhighlight>


{{out}}
{{out}}
Line 28: Line 28:
=={{header|Action!}}==
=={{header|Action!}}==
{{libheader|Action! Tool Kit}}
{{libheader|Action! Tool Kit}}
<lang Action!>INCLUDE "D2:SORT.ACT" ;from the Action! Tool Kit
<syntaxhighlight lang="action!">INCLUDE "D2:SORT.ACT" ;from the Action! Tool Kit

DEFINE PTR="CARD"


PROC PrintArray(BYTE ARRAY a BYTE len)
PROC PrintArray(BYTE ARRAY a BYTE len)
Line 55: Line 57:
RETURN (0)
RETURN (0)


PROC CommonListElements(CARD ARRAY arrays
PROC CommonListElements(PTR ARRAY arrays
BYTE ARRAY lengths BYTE count
BYTE ARRAY lengths BYTE count
BYTE ARRAY res BYTE POINTER resLen)
BYTE ARRAY res BYTE POINTER resLen)
Line 85: Line 87:
RETURN
RETURN


PROC Test(CARD ARRAY arrays BYTE ARRAY lengths BYTE count)
PROC Test(PTR ARRAY arrays BYTE ARRAY lengths BYTE count)
BYTE ARRAY res(100)
BYTE ARRAY res(100)
BYTE len,i
BYTE len,i
Line 100: Line 102:


PROC Main()
PROC Main()
CARD ARRAY arrays(3)
PTR ARRAY arrays(3)
BYTE ARRAY
BYTE ARRAY
lengths(3)=[8 5 4],
lengths(3)=[8 5 4],
Line 121: Line 123:
lengths(0)=0
lengths(0)=0
Test(arrays,lengths,3)
Test(arrays,lengths,3)
RETURN</lang>
RETURN</syntaxhighlight>
{{out}}
{{out}}
[https://gitlab.com/amarok8bit/action-rosetta-code/-/raw/master/images/Common_sorted_list.png Screenshot from Atari 8-bit computer]
[https://gitlab.com/amarok8bit/action-rosetta-code/-/raw/master/images/Common_sorted_list.png Screenshot from Atari 8-bit computer]
Line 148: Line 150:


=={{header|Ada}}==
=={{header|Ada}}==
<lang Ada>with Ada.Text_Io;
<syntaxhighlight lang="ada">with Ada.Text_Io;
with Ada.Containers.Vectors;
with Ada.Containers.Vectors;


Line 192: Line 194:
Unique (R);
Unique (R);
Put (R);
Put (R);
end Sorted;</lang>
end Sorted;</syntaxhighlight>
{{out}}
{{out}}
<pre>[ 1 3 4 5 7 8 9 ]</pre>
<pre>[ 1 3 4 5 7 8 9 ]</pre>
Line 198: Line 200:
=={{header|APL}}==
=={{header|APL}}==
{{works with|Dyalog APL}}
{{works with|Dyalog APL}}
<lang>csl ← (⊂∘⍋⌷⊢)∪∘∊</lang>
<syntaxhighlight lang="text">csl ← (⊂∘⍋⌷⊢)∪∘∊</syntaxhighlight>
{{out}}
{{out}}
<pre> csl (5 1 3 8 9 4 8 7)(3 5 9 8 4)(1 3 7 9)
<pre> csl (5 1 3 8 9 4 8 7)(3 5 9 8 4)(1 3 7 9)
Line 205: Line 207:
=={{header|AppleScript}}==
=={{header|AppleScript}}==


<lang applescript>use AppleScript version "2.4" -- OS X 10.10 (Yosemite) or later
<syntaxhighlight lang="applescript">use AppleScript version "2.4" -- OS X 10.10 (Yosemite) or later
use framework "Foundation"
use framework "Foundation"


Line 212: Line 214:
set nums to current application's class "NSArray"'s arrayWithArray:({{5, 1, 3, 8, 9, 4, 8, 7}, {3, 5, 9, 8, 4}, {1, 3, 7, 9}})
set nums to current application's class "NSArray"'s arrayWithArray:({{5, 1, 3, 8, 9, 4, 8, 7}, {3, 5, 9, 8, 4}, {1, 3, 7, 9}})
set output to (nums's valueForKeyPath:("@distinctUnionOfArrays.self"))'s sortedArrayUsingSelector:("compare:")
set output to (nums's valueForKeyPath:("@distinctUnionOfArrays.self"))'s sortedArrayUsingSelector:("compare:")
return output as list</lang>
return output as list</syntaxhighlight>


{{output}}
{{output}}
<lang applescript>{1, 3, 4, 5, 7, 8, 9}</lang>
<syntaxhighlight lang="applescript">{1, 3, 4, 5, 7, 8, 9}</syntaxhighlight>




Line 222: Line 224:
while ''concat/flatten'' and ''nub/distinct'' are more atomic, and more frequently reached for):
while ''concat/flatten'' and ''nub/distinct'' are more atomic, and more frequently reached for):


<lang applescript>use AppleScript version "2.4"
<syntaxhighlight lang="applescript">use AppleScript version "2.4"
use framework "Foundation"
use framework "Foundation"


Line 255: Line 257:
((current application's NSArray's arrayWithArray:xs)'s ¬
((current application's NSArray's arrayWithArray:xs)'s ¬
sortedArrayUsingSelector:"compare:") as list
sortedArrayUsingSelector:"compare:") as list
end sort</lang>
end sort</syntaxhighlight>
{{Out}}
{{Out}}
<pre>{1, 3, 4, 5, 7, 8, 9}</pre>
<pre>{1, 3, 4, 5, 7, 8, 9}</pre>

=={{header|Arturo}}==

<syntaxhighlight lang="rebol">print sort unique flatten [[5 1 3 8 9 4 8 7] [3 5 9 8 4] [1 3 7 9]]</syntaxhighlight>

{{out}}

<pre>1 3 4 5 7 8 9</pre>


=={{header|AutoHotkey}}==
=={{header|AutoHotkey}}==
<lang AutoHotkey>Common_sorted_list(nums){
<syntaxhighlight lang="autohotkey">Common_sorted_list(nums){
elements := [], output := []
elements := [], output := []
for i, num in nums
for i, num in nums
Line 268: Line 278:
output.push(val)
output.push(val)
return output
return output
}</lang>
}</syntaxhighlight>
Examples:<lang AutoHotkey>nums := [[5,1,3,8,9,4,8,7], [3,5,9,8,4], [1,3,7,9]]
Examples:<syntaxhighlight lang="autohotkey">nums := [[5,1,3,8,9,4,8,7], [3,5,9,8,4], [1,3,7,9]]
output := Common_sorted_list(nums)
output := Common_sorted_list(nums)
return</lang>
return</syntaxhighlight>
{{out}}
{{out}}
<pre>[1, 3, 4, 5, 6, 7, 9]</pre>
<pre>[1, 3, 4, 5, 6, 7, 9]</pre>


=={{header|AWK}}==
=={{header|AWK}}==
<syntaxhighlight lang="awk">
<lang AWK>
# syntax: GAWK -f COMMON_SORTED_LIST.AWK
# syntax: GAWK -f COMMON_SORTED_LIST.AWK
BEGIN {
BEGIN {
Line 296: Line 306:
exit(0)
exit(0)
}
}
</syntaxhighlight>
</lang>
{{out}}
{{out}}
<pre>
<pre>
[5,1,3,8,9,4,8,7],[3,5,9,8,4],[1,3,7,9] : 1 3 4 5 7 8 9
[5,1,3,8,9,4,8,7],[3,5,9,8,4],[1,3,7,9] : 1 3 4 5 7 8 9
</pre>
</pre>

=={{header|BQN}}==

Joins all the arrays, deduplicate, sort.

<syntaxhighlight lang="bqn"> arr ← ⟨⟨5,1,3,8,9,4,8,7⟩, ⟨3,5,9,8,4⟩, ⟨1,3,7,9⟩⟩
⟨ ⟨ 5 1 3 8 9 4 8 7 ⟩ ⟨ 3 5 9 8 4 ⟩ ⟨ 1 3 7 9 ⟩ ⟩
CSL ← ∧·⍷∾
∧(⍷∾)
CSL arr
⟨ 1 3 4 5 7 8 9 ⟩</syntaxhighlight>


=={{header|C}}==
=={{header|C}}==
<lang c>#include <stdio.h>
<syntaxhighlight lang="c">#include <stdio.h>
#include <stdlib.h>
#include <stdlib.h>
#include <string.h>
#include <string.h>
Line 373: Line 394:
free(sorted);
free(sorted);
return 0;
return 0;
}</lang>
}</syntaxhighlight>


{{out}}
{{out}}
Line 381: Line 402:


=={{header|C++}}==
=={{header|C++}}==
<lang cpp>#include <iostream>
<syntaxhighlight lang="cpp">#include <iostream>
#include <vector>
#include <vector>
#include <set>
#include <set>
Line 411: Line 432:
return 0;
return 0;
}</lang>
}</syntaxhighlight>


{{out}}
{{out}}


<pre>1 3 4 5 7 8 9</pre>
<pre>1 3 4 5 7 8 9</pre>

=={{header|Clojure}}==
===Efficient transducer & sorted-set version===
<syntaxhighlight lang="lisp">(defn common-sorted [& colls]
(into (sorted-set) cat colls))

(common-sorted [5 1 3 8 9 4 8 7] [3 5 9 8 4] [1 3 7 9])
;; => #{1 3 4 5 7 8 9}
</syntaxhighlight>

===Point-free, list-based version===
<syntaxhighlight lang="lisp">(def common-sorted (comp sort distinct concat))

(common-sorted [5 1 3 8 9 4 8 7] [3 5 9 8 4] [1 3 7 9])
;; => (1 3 4 5 7 8 9)
</syntaxhighlight>

=={{header|EasyLang}}==
<syntaxhighlight>
nums[][] = [ [ 2 5 1 3 8 9 4 6 ] [ 3 5 6 2 9 8 4 ] [ 1 3 7 6 9 ] ]
#
proc sort . d[] .
for i = 1 to len d[] - 1
for j = i + 1 to len d[]
if d[j] < d[i]
swap d[j] d[i]
.
.
.
.
#
for l to len nums[][]
for e in nums[l][]
h[] &= e
.
.
sort h[]
for e in h[]
if e <> last or len r[] = 0
r[] &= e
last = e
.
.
print r[]
</syntaxhighlight>



=={{header|Excel}}==
=={{header|Excel}}==
Line 425: Line 492:


{{Works with|Office 365 betas 2021}}
{{Works with|Office 365 betas 2021}}
<lang lisp>COMMONSORTED
<syntaxhighlight lang="lisp">COMMONSORTED
=LAMBDA(grid,
=LAMBDA(grid,
SORT(
SORT(
Line 432: Line 499:
)
)
)
)
)</lang>
)</syntaxhighlight>


and also assuming the following generic bindings in the Name Manager for the WorkBook:
and also assuming the following generic bindings in the Name Manager for the WorkBook:


<lang lisp>CONCATCOLS
<syntaxhighlight lang="lisp">CONCATCOLS
=LAMBDA(cols,
=LAMBDA(cols,
LET(
LET(
Line 466: Line 533:
FILTER(xs, p(xs))
FILTER(xs, p(xs))
)
)
)</lang>
)</syntaxhighlight>


The formula in cell B2 defines a dynamic array of values, additionally populating further cells in column B.
The formula in cell B2 defines a dynamic array of values, additionally populating further cells in column B.
Line 547: Line 614:


=={{header|F_Sharp|F#}}==
=={{header|F_Sharp|F#}}==
<lang fsharp>
<syntaxhighlight lang="fsharp">
// Common sorted list. Nigel Galloway: February 25th., 2021
// Common sorted list. Nigel Galloway: February 25th., 2021
let nums=[|[5;1;3;8;9;4;8;7];[3;5;9;8;4];[1;3;7;9]|]
let nums=[|[5;1;3;8;9;4;8;7];[3;5;9;8;4];[1;3;7;9]|]
printfn "%A" (nums|>Array.reduce(fun n g->n@g)|>List.distinct|>List.sort)
printfn "%A" (nums|>Array.reduce(fun n g->n@g)|>List.distinct|>List.sort)
</syntaxhighlight>
</lang>
{{out}}
{{out}}
<pre>
<pre>
Line 560: Line 627:
Note: in older versions of Factor, <code>union-all</code> is called <code>combine</code>.
Note: in older versions of Factor, <code>union-all</code> is called <code>combine</code>.
{{works with|Factor|0.99 2021-02-05}}
{{works with|Factor|0.99 2021-02-05}}
<lang factor>USING: formatting kernel sets sorting ;
<syntaxhighlight lang="factor">USING: formatting kernel sets sorting ;


{ { 5 1 3 8 9 4 8 7 } { 3 5 9 8 4 } { 1 3 7 9 } }
{ { 5 1 3 8 9 4 8 7 } { 3 5 9 8 4 } { 1 3 7 9 } }
dup union-all natural-sort
dup union-all natural-sort
"Sorted union of %u is:\n%u\n" printf</lang>
"Sorted union of %u is:\n%u\n" printf</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>
Line 570: Line 637:
{ 1 3 4 5 7 8 9 }
{ 1 3 4 5 7 8 9 }
</pre>
</pre>

=={{header|FreeBASIC}}==
<syntaxhighlight lang="vbnet">Dim As Integer nums(2, 7) = {{5,1,3,8,9,4,8,7},{3,5,9,8,4},{1,3,7,9}}
Dim Shared As Integer sumNums()

Sub Sum(arr() As Integer, vals As Integer)
Redim Preserve arr(Ubound(arr) + 1)
arr(Ubound(arr)) = vals
End Sub

Sub Del(arr() As Integer, index As Integer)
For i As Integer = index To Ubound(arr) - 1
arr(i) = arr(i + 1)
Next i
Redim Preserve arr(Ubound(arr) - 1)
End Sub

Sub showArray(arr() As Integer)
Dim As String txt = ""
Print "[";
For n As Integer = 1 To Ubound(arr)
txt &= Str(arr(n)) & ","
Next n
txt = Left(txt, Len(txt) - 1)
txt &= "]"
Print txt
End Sub

Sub Sort(arr() As Integer)
Dim As Integer i, j
For i = 0 To Ubound(arr) - 1
For j = i + 1 To Ubound(arr)
If arr(i) > arr(j) Then Swap arr(i), arr(j)
Next j
Next i
End Sub

For n As Integer = 0 To Ubound(nums, 1)
For m As Integer = 0 To Ubound(nums, 2)
Sum(sumNums(), nums(n, m))
Next m
Next n

Sort(sumNums())
For n As Integer = Ubound(sumNums) To 1 Step -1
If sumNums(n) = sumNums(n - 1) Then
Del(sumNums(), n)
End If
Next n

Sort(sumNums())

Print "common sorted list elements are: ";
showArray(sumNums())

Sleep</syntaxhighlight>
{{out}}
<pre>common sorted list elements are: [1,3,4,5,7,8,9]</pre>


=={{header|Go}}==
=={{header|Go}}==
{{trans|Wren}}
{{trans|Wren}}
<lang go>package main
<syntaxhighlight lang="go">package main


import (
import (
Line 601: Line 726:
fmt.Println("Distinct sorted union of", ll, "is:")
fmt.Println("Distinct sorted union of", ll, "is:")
fmt.Println(distinctSortedUnion(ll))
fmt.Println(distinctSortedUnion(ll))
}</lang>
}</syntaxhighlight>


{{out}}
{{out}}
Line 610: Line 735:


=={{header|Haskell}}==
=={{header|Haskell}}==
<lang haskell>import Data.List (nub, sort)
<syntaxhighlight lang="haskell">import Data.List (nub, sort)


-------------------- COMMON SORTED LIST ------------------
-------------------- COMMON SORTED LIST ------------------
Line 625: Line 750:
[3, 5, 9, 8, 4],
[3, 5, 9, 8, 4],
[1, 3, 7, 9]
[1, 3, 7, 9]
]</lang>
]</syntaxhighlight>
{{Out}}
{{Out}}
<pre>[1,3,4,5,7,8,9]</pre>
<pre>[1,3,4,5,7,8,9]</pre>


=={{header|J}}==
=={{header|J}}==
<lang j>csl =: /:~@~.@;</lang>
<syntaxhighlight lang="j">csl =: /:~@~.@;</syntaxhighlight>
{{out}}
{{out}}
<pre> nums =: 5 1 3 8 9 4 8 7;3 5 9 8 4;1 3 7 9
<pre> nums =: 5 1 3 8 9 4 8 7;3 5 9 8 4;1 3 7 9
Line 637: Line 762:


=={{header|JavaScript}}==
=={{header|JavaScript}}==
<lang javascript>(() => {
<syntaxhighlight lang="javascript">(() => {
"use strict";
"use strict";


Line 659: Line 784:


// concat :: [[a]] -> [a]
// concat :: [[a]] -> [a]
const concat = xs => [].concat(...xs);
const concat = xs =>
xs.flat(1);




// nub :: [a] -> [a]
// nub :: Eq a => [a] -> [a]
const nub = xs => [...new Set(xs)];
const nub = xs => [...new Set(xs)];


Line 672: Line 798:


return main();
return main();
})();</lang>
})();</syntaxhighlight>
{{Out}}
{{Out}}
<pre>[1, 3, 4, 5, 7, 8, 9]</pre>
<pre>[1, 3, 4, 5, 7, 8, 9]</pre>
Line 681: Line 807:


Assuming the input is a single array of arrays, we can simply chain the `add` and `unique` filters:
Assuming the input is a single array of arrays, we can simply chain the `add` and `unique` filters:
<lang jq>jq -nc '[[5,1,3,8,9,4,8,7], [3,5,9,8,4], [1,3,7,9]] | add | unique'</lang>
<syntaxhighlight lang="jq">jq -nc '[[5,1,3,8,9,4,8,7], [3,5,9,8,4], [1,3,7,9]] | add | unique'</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>
Line 689: Line 815:


Alternatively, here's a stream-oriented version of `add` that could be used:
Alternatively, here's a stream-oriented version of `add` that could be used:
<lang jq>def add(s): reduce s as $x (null; . + $x);</lang>
<syntaxhighlight lang="jq">def add(s): reduce s as $x (null; . + $x);</syntaxhighlight>
For example:
For example:
<lang jq>jq -nc '
<syntaxhighlight lang="jq">jq -nc '
def add(s): reduce s as $x (null; . + $x);
def add(s): reduce s as $x (null; . + $x);
add(inputs) | unique' <<< '[5,1,3,8,9,4,8,7] [3,5,9,8,4] [1,3,7,9]'</lang>
add(inputs) | unique' <<< '[5,1,3,8,9,4,8,7] [3,5,9,8,4] [1,3,7,9]'</syntaxhighlight>
=={{header|Julia}}==
=={{header|Julia}}==
<lang julia>
<syntaxhighlight lang="julia">
julia> sort(union([5,1,3,8,9,4,8,7], [3,5,9,8,4], [1,3,7,9]))
julia> sort(union([5,1,3,8,9,4,8,7], [3,5,9,8,4], [1,3,7,9]))
7-element Array{Int64,1}:
7-element Array{Int64,1}:
Line 717: Line 843:
"not"
"not"


</syntaxhighlight>
</lang>


=={{header|Mathematica}}/{{header|Wolfram Language}}==
=={{header|Mathematica}}/{{header|Wolfram Language}}==
<lang Mathematica>Union[{5, 1, 3, 8, 9, 4, 8, 7}, {3, 5, 9, 8, 4}, {1, 3, 7, 9}]</lang>
<syntaxhighlight lang="mathematica">Union[{5, 1, 3, 8, 9, 4, 8, 7}, {3, 5, 9, 8, 4}, {1, 3, 7, 9}]</syntaxhighlight>
{{out}}
{{out}}
<pre>{1, 3, 4, 5, 7, 8, 9}</pre>
<pre>{1, 3, 4, 5, 7, 8, 9}</pre>

=={{header|Maxima}}==
<syntaxhighlight lang="maxima">
common_sorted(lst):=unique(flatten(lst))$
nums:[[5,1,3,8,9,4,8,7],[3,5,9,8,4],[1,3,7,9]]$
common_sorted(nums);
</syntaxhighlight>
{{out}}
<pre>
[1,3,4,5,7,8,9]
</pre>


=={{header|Nim}}==
=={{header|Nim}}==
We could use a <code>HashSet</code> or an <code>IntSet</code> to deduplicate. We have rather chosen to use the procedure <code>deduplicate</code> from module <code>sequtils</code> applied to the sorted list.
We could use a <code>HashSet</code> or an <code>IntSet</code> to deduplicate. We have rather chosen to use the procedure <code>deduplicate</code> from module <code>sequtils</code> applied to the sorted list.


<lang Nim>import algorithm, sequtils
<syntaxhighlight lang="nim">import algorithm, sequtils


proc commonSortedList(list: openArray[seq[int]]): seq[int] =
proc commonSortedList(list: openArray[seq[int]]): seq[int] =
sorted(concat(list)).deduplicate(true)
sorted(concat(list)).deduplicate(true)


echo commonSortedList([@[5,1,3,8,9,4,8,7], @[3,5,9,8,4], @[1,3,7,9]])</lang>
echo commonSortedList([@[5,1,3,8,9,4,8,7], @[3,5,9,8,4], @[1,3,7,9]])</syntaxhighlight>


{{out}}
{{out}}
<pre>@[1, 3, 4, 5, 7, 8, 9]</pre>
<pre>@[1, 3, 4, 5, 7, 8, 9]</pre>

=={{header|Pascal}}==
==={{header|Free Pascal}}===
<syntaxhighlight lang="pascal">
Program CommonSortedList;
{$mode ObjFPC}{$H+}

Uses sysutils,fgl;

Type
tarr = array Of array Of integer;

Const List1: tarr = ((5,1,3,8,9,4,8,7), (3,5,9,8,4), (1,3,7,9));

Var list : specialize TFPGList<integer>;

Procedure addtolist(arr : tarr);
Var i : integer;
arr2 : array Of integer;
Begin
For arr2 In arr Do
For i In arr2 Do
If (list.indexof(i) = -1) {make sure number isn't in list already}
Then list.add(i);
End;

Function CompareInt(Const Item1,Item2: Integer): Integer;
Begin
result := item1 - item2;
End;

Var i : integer;
Begin
list := specialize TFPGList<integer>.create;
addtolist(list1);
List.Sort(@CompareInt); {quick sort the list}
For i In list Do
write(i:4);
list.destroy;
End.
</syntaxhighlight>
{{out}}
<pre>
1 3 4 5 7 8 9
</pre>


=={{header|Perl}}==
=={{header|Perl}}==
<lang perl>@c{@$_}++ for [5,1,3,8,9,4,8,7], [3,5,9,8,4], [1,3,7,9];
<syntaxhighlight lang="perl">@c{@$_}++ for [5,1,3,8,9,4,8,7], [3,5,9,8,4], [1,3,7,9];
print join ' ', sort keys %c;
print join ' ', sort keys %c;
@c{@$_}++ for [qw<not all is integer ? is not ! 4.2>];
@c{@$_}++ for [qw<not all is integer ? is not ! 4.2>];
print join ' ', sort keys %c;</lang>
print join ' ', sort keys %c;</syntaxhighlight>
{{out}}
{{out}}
<pre>1 3 4 5 7 8 9
<pre>1 3 4 5 7 8 9
Line 748: Line 930:
=={{header|Phix}}==
=={{header|Phix}}==
{{libheader|Phix/basics}}
{{libheader|Phix/basics}}
<!--<lang Phix>(phixonline)-->
<!--<syntaxhighlight lang="phix">(phixonline)-->
<span style="color: #0000FF;">?</span><span style="color: #7060A8;">unique</span><span style="color: #0000FF;">(</span><span style="color: #7060A8;">join</span><span style="color: #0000FF;">({{</span><span style="color: #000000;">5</span><span style="color: #0000FF;">,</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #000000;">3</span><span style="color: #0000FF;">,</span><span style="color: #000000;">8</span><span style="color: #0000FF;">,</span><span style="color: #000000;">9</span><span style="color: #0000FF;">,</span><span style="color: #000000;">4</span><span style="color: #0000FF;">,</span><span style="color: #000000;">8</span><span style="color: #0000FF;">,</span><span style="color: #000000;">7</span><span style="color: #0000FF;">},</span> <span style="color: #0000FF;">{</span><span style="color: #000000;">3</span><span style="color: #0000FF;">,</span><span style="color: #000000;">5</span><span style="color: #0000FF;">,</span><span style="color: #000000;">9</span><span style="color: #0000FF;">,</span><span style="color: #000000;">8</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: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #000000;">3</span><span style="color: #0000FF;">,</span><span style="color: #000000;">7</span><span style="color: #0000FF;">,</span><span style="color: #000000;">9</span><span style="color: #0000FF;">},</span> <span style="color: #7060A8;">split</span><span style="color: #0000FF;">(</span><span style="color: #008000;">"not everything is an integer"</span><span style="color: #0000FF;">)},{}))</span>
<span style="color: #0000FF;">?</span><span style="color: #7060A8;">unique</span><span style="color: #0000FF;">(</span><span style="color: #7060A8;">join</span><span style="color: #0000FF;">({{</span><span style="color: #000000;">5</span><span style="color: #0000FF;">,</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #000000;">3</span><span style="color: #0000FF;">,</span><span style="color: #000000;">8</span><span style="color: #0000FF;">,</span><span style="color: #000000;">9</span><span style="color: #0000FF;">,</span><span style="color: #000000;">4</span><span style="color: #0000FF;">,</span><span style="color: #000000;">8</span><span style="color: #0000FF;">,</span><span style="color: #000000;">7</span><span style="color: #0000FF;">},</span> <span style="color: #0000FF;">{</span><span style="color: #000000;">3</span><span style="color: #0000FF;">,</span><span style="color: #000000;">5</span><span style="color: #0000FF;">,</span><span style="color: #000000;">9</span><span style="color: #0000FF;">,</span><span style="color: #000000;">8</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: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #000000;">3</span><span style="color: #0000FF;">,</span><span style="color: #000000;">7</span><span style="color: #0000FF;">,</span><span style="color: #000000;">9</span><span style="color: #0000FF;">},</span> <span style="color: #7060A8;">split</span><span style="color: #0000FF;">(</span><span style="color: #008000;">"not everything is an integer"</span><span style="color: #0000FF;">)},{}))</span>
<!--</lang>-->
<!--</syntaxhighlight>-->
Note the join(x,{}): the 2nd param is needed to prevent it putting 32 (ie the acsii code for a space) in the output.
Note the join(x,{}): the 2nd param is needed to prevent it putting 32 (ie the acsii code for a space) in the output.
{{out}}
{{out}}
Line 759: Line 941:


=={{header|Python}}==
=={{header|Python}}==
<lang python>'''Common sorted list'''
<syntaxhighlight lang="python">'''Common sorted list'''


from itertools import chain
from itertools import chain
Line 799: Line 981:
# MAIN ---
# MAIN ---
if __name__ == '__main__':
if __name__ == '__main__':
main()</lang>
main()</syntaxhighlight>
{{Out}}
{{Out}}
<pre>[1, 3, 4, 5, 7, 8, 9]</pre>
<pre>[1, 3, 4, 5, 7, 8, 9]</pre>
Line 807: Line 989:
<code>uniquewith</code> is defined at [[Remove duplicate elements#Quackery]].
<code>uniquewith</code> is defined at [[Remove duplicate elements#Quackery]].


<lang Quackery> ' [ [ 5 1 3 8 9 4 8 7 ]
<syntaxhighlight lang="quackery"> ' [ [ 5 1 3 8 9 4 8 7 ]
[ 3 5 9 8 4 ]
[ 3 5 9 8 4 ]
[ 1 3 7 9 ] ]
[ 1 3 7 9 ] ]
[] swap witheach [ witheach join ]
[] swap witheach [ witheach join ]
uniquewith > echo</lang>
uniquewith > echo</syntaxhighlight>


{{out}}
{{out}}
Line 820: Line 1,002:


=={{header|Raku}}==
=={{header|Raku}}==
<lang perl6>put sort keys [∪] [5,1,3,8,9,4,8,7], [3,5,9,8,4], [1,3,7,9];
<syntaxhighlight lang="raku" line>put sort keys [∪] [5,1,3,8,9,4,8,7], [3,5,9,8,4], [1,3,7,9];
put sort keys [∪] [5,1,3,8,9,4,8,7], [3,5,9,8,4], [1,3,7,9], [<not everything is an integer so why not avoid special cases # ~ 23 4.2>];</lang>
put sort keys [∪] [5,1,3,8,9,4,8,7], [3,5,9,8,4], [1,3,7,9], [<not everything is an integer so why not avoid special cases # ~ 23 4.2>];</syntaxhighlight>
{{out}}
{{out}}
<pre>1 3 4 5 7 8 9
<pre>1 3 4 5 7 8 9
Line 827: Line 1,009:


=={{header|REXX}}==
=={{header|REXX}}==
<lang rexx>/*REXX pgm creates and displays a common sorted list of a specified collection of sets*/
<syntaxhighlight lang="rexx">/*REXX pgm creates and displays a common sorted list of a specified collection of sets*/
parse arg a /*obtain optional arguments from the CL*/
parse arg a /*obtain optional arguments from the CL*/
if a='' | a="," then a= '[5,1,3,8,9,4,8,7] [3,5,9,8,4] [1,3,7,9]' /*default sets.*/
if a='' | a="," then a= '[5,1,3,8,9,4,8,7] [3,5,9,8,4] [1,3,7,9]' /*default sets.*/
Line 848: Line 1,030:
eSort: procedure expose @.; arg h 1 z; do while h>1; h= h%2; do i=1 for z-h; j= i; k= h+i
eSort: procedure expose @.; arg h 1 z; do while h>1; h= h%2; do i=1 for z-h; j= i; k= h+i
do while @.k<@.j; t=@.j; @.j=@.k; @.k=t; if h>=j then leave; j=j-h; k=k-h; end;end
do while @.k<@.j; t=@.j; @.j=@.k; @.k=t; if h>=j then leave; j=j-h; k=k-h; end;end
end; return /*this sort was used 'cause of brevity.*/</lang>
end; return /*this sort was used 'cause of brevity.*/</syntaxhighlight>
{{out|output|text=&nbsp; when using the default inputs:}}
{{out|output|text=&nbsp; when using the default inputs:}}
<pre>
<pre>
Line 855: Line 1,037:


=={{header|Ring}}==
=={{header|Ring}}==
<lang ring>
<syntaxhighlight lang="ring">
nums = [[5,1,3,8,9,4,8,7],[3,5,9,8,4],[1,3,7,9]]
nums = [[5,1,3,8,9,4,8,7],[3,5,9,8,4],[1,3,7,9]]
sumNums = []
sumNums = []
Line 886: Line 1,068:
txt = txt + "]"
txt = txt + "]"
see txt
see txt
</syntaxhighlight>
</lang>
{{out}}
{{out}}
<pre>
<pre>
common sorted list elements are: [1,3,4,5,7,8,9]
common sorted list elements are: [1,3,4,5,7,8,9]
</pre>

=={{header|RPL}}==
{{works with|HP|48G}}
≪ ∑LIST SORT → nums
≪ <span style="color:red">{ }</span>
<span style="color:red">1</span> nums SIZE '''FOR''' j
nums j GET
'''IF''' DUP2 POS '''THEN''' DROP '''ELSE''' + '''END'''
'''NEXT'''
≫ ≫ '<span style="color:blue">COMMON</span>' STO

<span style="color:red">{ { 5 1 3 8 9 4 8 7 } { 3 5 9 8 4 } { 1 3 7 9 } }</span> <span style="color:blue">COMMON</span>
{{out}}
<pre>
1: { 1 3 4 5 7 8 9 }
</pre>
</pre>


=={{header|Ruby}}==
=={{header|Ruby}}==
<lang ruby>nums = [5,1,3,8,9,4,8,7], [3,5,9,8,4], [1,3,7,9]
<syntaxhighlight lang="ruby">nums = [5,1,3,8,9,4,8,7], [3,5,9,8,4], [1,3,7,9]
p nums.inject(:+).sort.uniq
p nums.inject(:+).sort.uniq
</syntaxhighlight>
</lang>
{{out}}
{{out}}
<pre>[1, 3, 4, 5, 7, 8, 9]
<pre>[1, 3, 4, 5, 7, 8, 9]
</pre>
</pre>

=={{header|Uiua}}==
<syntaxhighlight lang="Uiua">
F ← ⊏⍏.◴/◇⊂
</syntaxhighlight>
{{out}}
<pre>
F {[5 1 3 8 9 4 8 7] [3 5 9 8 4] [1 3 7 9]}
[1 3 4 5 7 8 9]
</pre>

=={{header|V (Vlang)}}==
<syntaxhighlight lang="v (vlang)">
fn main() {
nums := [[5,1,3,8,9,4,8,7], [3,5,9,8,4], [1,3,7,9]]
println("Distinct sorted union of $nums is:")
println(common_sorted_list(nums))
}

fn common_sorted_list(nums [][]int) []int {
mut elements, mut output := map[int]bool{}, []int{}
for num in nums {
for value in num {
elements[value] = true
}
}

for key, _ in elements {
output << key
}
output.sort()
return output
}
</syntaxhighlight>
{{out}}
<pre>
Distinct sorted union of [[5 1 3 8 9 4 8 7] [3 5 9 8 4] [1 3 7 9]] is:
[1 3 4 5 7 8 9]
</pre>

=={{header|Wren}}==
=={{header|Wren}}==
{{libheader|Wren-seq}}
{{libheader|Wren-seq}}
{{libheader|Wren-sort}}
{{libheader|Wren-sort}}
<lang ecmascript>import "/seq" for Lst
<syntaxhighlight lang="wren">import "./seq" for Lst
import "/sort" for Sort
import "./sort" for Sort


var distinctSortedUnion = Fn.new { |ll|
var distinctSortedUnion = Fn.new { |ll|
Line 914: Line 1,153:
var ll = [[5, 1, 3, 8, 9, 4, 8, 7], [3, 5, 9, 8, 4], [1, 3, 7, 9]]
var ll = [[5, 1, 3, 8, 9, 4, 8, 7], [3, 5, 9, 8, 4], [1, 3, 7, 9]]
System.print("Distinct sorted union of %(ll) is:")
System.print("Distinct sorted union of %(ll) is:")
System.print(distinctSortedUnion.call(ll))</lang>
System.print(distinctSortedUnion.call(ll))</syntaxhighlight>


{{out}}
{{out}}

Latest revision as of 16:40, 3 April 2024

Common sorted list is a draft programming task. It is not yet considered ready to be promoted as a complete task, for reasons that should be found in its talk page.

Given an integer array nums, the goal is create common sorted list with unique elements.


Example

nums = [5,1,3,8,9,4,8,7], [3,5,9,8,4], [1,3,7,9]

output = [1,3,4,5,7,8,9]

11l

F csl(nums)
   Set[Int] r
   L(num) nums
      r.update(num)
   R sorted(Array(r))

print(csl([[5, 1, 3, 8, 9, 4, 8, 7], [3, 5, 9, 8, 4], [1, 3, 7, 9]]))
Output:
[1, 3, 4, 5, 7, 8, 9]

Action!

INCLUDE "D2:SORT.ACT" ;from the Action! Tool Kit

DEFINE PTR="CARD"

PROC PrintArray(BYTE ARRAY a BYTE len)
  BYTE i

  Print("  [")
  IF len>0 THEN
    FOR i=0 TO len-1
    DO
      PrintB(a(i))
      IF i<len-1 THEN Put(' ) FI
    OD
  FI
  PrintE("]")
RETURN

BYTE FUNC Contains(BYTE ARRAY a BYTE len,value)
  BYTE i

  IF len>0 THEN
    FOR i=0 TO len-1
    DO
      IF a(i)=value THEN RETURN(1) FI
    OD
  FI
RETURN (0)

PROC CommonListElements(PTR ARRAY arrays
  BYTE ARRAY lengths BYTE count
  BYTE ARRAY res BYTE POINTER resLen)
  
  BYTE ARRAY a
  BYTE i,j,len,value,cnt,maxcnt

  resLen^=0
  IF count=0 THEN
    RETURN
  ELSEIF count=1 THEN
    MoveBlock(res,a,len) RETURN
  FI

  FOR i=0 TO count-1
  DO
    a=arrays(i) len=lengths(i)
    IF len>0 THEN
      FOR j=0 TO len-1
      DO
        value=a(j)
        IF Contains(res,resLen^,value)=0 THEN
          res(resLen^)=value resLen^==+1
        FI
      OD
    FI
  OD
  SortB(res,resLen^,0)
RETURN

PROC Test(PTR ARRAY arrays BYTE ARRAY lengths BYTE count)
  BYTE ARRAY res(100)
  BYTE len,i

  CommonListElements(arrays,lengths,count,res,@len)
  PrintE("Input:")
  FOR i=0 TO count-1
  DO
    PrintArray(arrays(i),lengths(i))
  OD
  PrintE("Output:")
  PrintArray(res,len) PutE()
RETURN

PROC Main()
  PTR ARRAY arrays(3)
  BYTE ARRAY
    lengths(3)=[8 5 4],
    a1(8)=[5 1 3 8 9 4 8 7],
    a2(5)=[3 5 9 8 4],
    a3(4)=[1 3 7 9],
    a4(8)=[5 1 1 1 9 9 8 7],
    a5(5)=[5 5 9 9 9],
    a6(4)=[1 7 7 9]
  BYTE len

  Put(125) PutE() ;clear the screen
  
  arrays(0)=a1 arrays(1)=a2 arrays(2)=a3
  Test(arrays,lengths,3)

  arrays(0)=a4 arrays(1)=a5 arrays(2)=a6
  Test(arrays,lengths,3)

  lengths(0)=0
  Test(arrays,lengths,3)
RETURN
Output:

Screenshot from Atari 8-bit computer

Input:
  [5 1 3 8 9 4 8 7]
  [3 5 9 8 4]
  [1 3 7 9]
Output:
  [1 3 4 5 7 8 9]

Input:
  [5 1 1 1 9 9 8 7]
  [5 5 9 9 9]
  [1 7 7 9]
Output:
  [1 5 7 8 9]

Input:
  []
  [5 5 9 9 9]
  [1 7 7 9]
Output:
  [1 5 7 9]

Ada

with Ada.Text_Io;
with Ada.Containers.Vectors;

procedure Sorted is

   package Integer_Vectors is
     new Ada.Containers.Vectors (Index_Type   => Positive,
                                 Element_Type => Integer);
   use Integer_Vectors;

   package Vector_Sorting is
     new Integer_Vectors.Generic_Sorting;
   use Vector_Sorting;

   procedure Unique (Vec : in out Vector) is
      Res : Vector;
   begin
      for E of Vec loop
         if Res.Is_Empty or else Res.Last_Element /= E then
            Res.Append (E);
         end if;
      end loop;
      Vec := Res;
   end Unique;

   procedure Put (Vec : Vector) is
      use Ada.Text_Io;
   begin
      Put ("[");
      for E of Vec loop
         Put (E'Image);  Put (" ");
      end loop;
      Put ("]");
      New_Line;
   end Put;

   A : constant Vector := 5 & 1 & 3 & 8 & 9 & 4 & 8 & 7;
   B : constant Vector := 3 & 5 & 9 & 8 & 4;
   C : constant Vector := 1 & 3 & 7 & 9;
   R : Vector          := A & B & C;
begin
   Sort (R);
   Unique (R);
   Put (R);
end Sorted;
Output:
[ 1  3  4  5  7  8  9 ]

APL

Works with: Dyalog APL
csl ← (⊂∘⍋⌷⊢)∪∘∊
Output:
      csl (5 1 3 8 9 4 8 7)(3 5 9 8 4)(1 3 7 9)
1 3 4 5 7 8 9

AppleScript

use AppleScript version "2.4" -- OS X 10.10 (Yosemite) or later
use framework "Foundation"

local nums, output

set nums to current application's class "NSArray"'s arrayWithArray:({{5, 1, 3, 8, 9, 4, 8, 7}, {3, 5, 9, 8, 4}, {1, 3, 7, 9}})
set output to (nums's valueForKeyPath:("@distinctUnionOfArrays.self"))'s sortedArrayUsingSelector:("compare:")
return output as list
Output:
{1, 3, 4, 5, 7, 8, 9}


Or, as a composition of slightly more commonly-used generic functions (given that distinctUnionOfArrays is a relatively specialised function, while concat/flatten and nub/distinct are more atomic, and more frequently reached for):

use AppleScript version "2.4"
use framework "Foundation"


------------------- COMMON SORTED ARRAY ------------------
on run
    sort(nub(concat({¬
        {5, 1, 3, 8, 9, 4, 8, 7}, ¬
        {3, 5, 9, 8, 4}, ¬
        {1, 3, 7, 9}})))
end run


-------------------- GENERIC FUNCTIONS -------------------

-- concat :: [[a]] -> [a]
on concat(xs)
    ((current application's NSArray's arrayWithArray:xs)'s ¬
        valueForKeyPath:"@unionOfArrays.self") as list
end concat


-- nub :: [a] -> [a]
on nub(xs)
    ((current application's NSArray's arrayWithArray:xs)'s ¬
        valueForKeyPath:"@distinctUnionOfObjects.self") as list
end nub


-- sort :: Ord a => [a] -> [a]
on sort(xs)
    ((current application's NSArray's arrayWithArray:xs)'s ¬
        sortedArrayUsingSelector:"compare:") as list
end sort
Output:
{1, 3, 4, 5, 7, 8, 9}

Arturo

print sort unique flatten [[5 1 3 8 9 4 8 7]  [3 5 9 8 4]  [1 3 7 9]]
Output:
1 3 4 5 7 8 9

AutoHotkey

Common_sorted_list(nums){
    elements := [], output := []
    for i, num in nums
        for j, d in num
            elements[d] := true
    for val, bool in elements
        output.push(val)
    return output
}

Examples:

nums := [[5,1,3,8,9,4,8,7], [3,5,9,8,4], [1,3,7,9]]
output := Common_sorted_list(nums)
return
Output:
[1, 3, 4, 5, 6, 7, 9]

AWK

# syntax: GAWK -f COMMON_SORTED_LIST.AWK
BEGIN {
    PROCINFO["sorted_in"] = "@ind_num_asc"
    nums = "[5,1,3,8,9,4,8,7],[3,5,9,8,4],[1,3,7,9]"
    printf("%s : ",nums)
    n = split(nums,arr1,"],?") - 1
    for (i=1; i<=n; i++) {
      gsub(/[\[\]]/,"",arr1[i])
      split(arr1[i],arr2,",")
      for (j in arr2) {
        arr3[arr2[j]]++
      }
    }
    for (j in arr3) {
      printf("%s ",j)
    }
    printf("\n")
    exit(0)
}
Output:
[5,1,3,8,9,4,8,7],[3,5,9,8,4],[1,3,7,9] : 1 3 4 5 7 8 9

BQN

Joins all the arrays, deduplicate, sort.

  arr  ⟨⟨5,1,3,8,9,4,8,7⟩, 3,5,9,8,4⟩, 1,3,7,9⟩⟩
  5 1 3 8 9 4 8 7   3 5 9 8 4   1 3 7 9  
  CSL  ·⍷∾
(⍷∾)
  CSL arr
 1 3 4 5 7 8 9 

C

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#define COUNTOF(a) (sizeof(a)/sizeof(a[0]))

void fatal(const char* message) {
    fprintf(stderr, "%s\n", message);
    exit(1);
}

void* xmalloc(size_t n) {
    void* ptr = malloc(n);
    if (ptr == NULL)
        fatal("Out of memory");
    return ptr;
}

int icompare(const void* p1, const void* p2) {
    const int* ip1 = p1;
    const int* ip2 = p2;
    return (*ip1 < *ip2) ? -1 : ((*ip1 > *ip2) ? 1 : 0);
}

size_t unique(int* array, size_t len) {
    size_t out_index = 0;
    int prev;
    for (size_t i = 0; i < len; ++i) {
        if (i == 0 || prev != array[i])
            array[out_index++] = array[i];
        prev = array[i];
    }
    return out_index;
}

int* common_sorted_list(const int** arrays, const size_t* lengths, size_t count, size_t* size) {
    size_t len = 0;
    for (size_t i = 0; i < count; ++i)
        len += lengths[i];
    int* array = xmalloc(len * sizeof(int));
    for (size_t i = 0, offset = 0; i < count; ++i) {
        memcpy(array + offset, arrays[i], lengths[i] * sizeof(int));
        offset += lengths[i];
    }
    qsort(array, len, sizeof(int), icompare);
    *size = unique(array, len);
    return array;
}

void print(const int* array, size_t len) {
    printf("[");
    for (size_t i = 0; i < len; ++i) {
        if (i > 0)
            printf(", ");
        printf("%d", array[i]);
    }
    printf("]\n");
}

int main() {
    const int a[] = {5, 1, 3, 8, 9, 4, 8, 7};
    const int b[] = {3, 5, 9, 8, 4};
    const int c[] = {1, 3, 7, 9};
    size_t len = 0;
    const int* arrays[] = {a, b, c};
    size_t lengths[] = {COUNTOF(a), COUNTOF(b), COUNTOF(c)};
    int* sorted = common_sorted_list(arrays, lengths, COUNTOF(arrays), &len);
    print(sorted, len);
    free(sorted);
    return 0;
}
Output:
[1, 3, 4, 5, 7, 8, 9]

C++

#include <iostream>
#include <vector>
#include <set>
#include <algorithm>

template<typename T>
std::vector<T> common_sorted_list(const std::vector<std::vector<T>>& ll) {
    std::set<T> resultset;
    std::vector<T> result;
    for (auto& list : ll)
        for (auto& item : list)
            resultset.insert(item);
    for (auto& item : resultset)
        result.push_back(item);
    
    std::sort(result.begin(), result.end());
    return result;
}

int main() {
    std::vector<int> a = {5,1,3,8,9,4,8,7};
    std::vector<int> b = {3,5,9,8,4};
    std::vector<int> c = {1,3,7,9};
    std::vector<std::vector<int>> nums = {a, b, c};
    
    auto csl = common_sorted_list(nums);
    for (auto n : csl) std::cout << n << " ";
    std::cout << std::endl;
    
    return 0;
}
Output:
1 3 4 5 7 8 9

Clojure

Efficient transducer & sorted-set version

(defn common-sorted [& colls]
  (into (sorted-set) cat colls))

(common-sorted [5 1 3 8 9 4 8 7] [3 5 9 8 4] [1 3 7 9])
;; => #{1 3 4 5 7 8 9}

Point-free, list-based version

(def common-sorted (comp sort distinct concat))

(common-sorted [5 1 3 8 9 4 8 7] [3 5 9 8 4] [1 3 7 9])
;; => (1 3 4 5 7 8 9)

EasyLang

nums[][] = [ [ 2 5 1 3 8 9 4 6 ] [ 3 5 6 2 9 8 4 ] [ 1 3 7 6 9 ] ]
# 
proc sort . d[] .
   for i = 1 to len d[] - 1
      for j = i + 1 to len d[]
         if d[j] < d[i]
            swap d[j] d[i]
         .
      .
   .
.
# 
for l to len nums[][]
   for e in nums[l][]
      h[] &= e
   .
.
sort h[]
for e in h[]
   if e <> last or len r[] = 0
      r[] &= e
      last = e
   .
.
print r[]


Excel

LAMBDA

Binding the name COMMONSORTED to the following lambda expression in the Name Manager of the Excel WorkBook:

(See LAMBDA: The ultimate Excel worksheet function)

COMMONSORTED
=LAMBDA(grid,
    SORT(
        UNIQUE(
            CONCATCOLS(grid)
        )
    )
)

and also assuming the following generic bindings in the Name Manager for the WorkBook:

CONCATCOLS
=LAMBDA(cols,
    LET(
        nRows, ROWS(cols),
        ixs, SEQUENCE(
            COLUMNS(cols) * nRows, 1,
            1, 1
        ),

        FILTERP(
            LAMBDA(x, 0 < LEN("" & x))
        )(
            INDEX(cols,
                LET(
                    r, MOD(ixs, nRows),

                    IF(0 = r, nRows, r)
                ),
                1 + QUOTIENT(ixs - 1, nRows)
            )
        )
    )
)


FILTERP
=LAMBDA(p,
    LAMBDA(xs,
        FILTER(xs, p(xs))
    )
)

The formula in cell B2 defines a dynamic array of values, additionally populating further cells in column B.

Output:
fx =COMMONSORTED(C2:E9)
A B C D E
1 Common sorted
2 1 5 3 1
3 3 1 5 3
4 4 3 9 7
5 5 8 8 9
6 7 9 4
7 8 4
8 9 8
9 7

F#

// Common sorted list. Nigel Galloway: February 25th., 2021
let nums=[|[5;1;3;8;9;4;8;7];[3;5;9;8;4];[1;3;7;9]|]
printfn "%A" (nums|>Array.reduce(fun n g->n@g)|>List.distinct|>List.sort)
Output:
[1; 3; 4; 5; 7; 8; 9]

Factor

Note: in older versions of Factor, union-all is called combine.

Works with: Factor version 0.99 2021-02-05
USING: formatting kernel sets sorting ;

{ { 5 1 3 8 9 4 8 7 } { 3 5 9 8 4 } { 1 3 7 9 } }
dup union-all natural-sort
"Sorted union of %u is:\n%u\n" printf
Output:
Sorted union of { { 5 1 3 8 9 4 8 7 } { 3 5 9 8 4 } { 1 3 7 9 } } is:
{ 1 3 4 5 7 8 9 }

FreeBASIC

Dim As Integer nums(2, 7) = {{5,1,3,8,9,4,8,7},{3,5,9,8,4},{1,3,7,9}}
Dim Shared As Integer sumNums()

Sub Sum(arr() As Integer, vals As Integer)
    Redim Preserve arr(Ubound(arr) + 1)
    arr(Ubound(arr)) = vals
End Sub

Sub Del(arr() As Integer, index As Integer)
    For i As Integer = index To Ubound(arr) - 1
        arr(i) = arr(i + 1)
    Next i
    Redim Preserve arr(Ubound(arr) - 1)
End Sub

Sub showArray(arr() As Integer)
    Dim As String txt = ""
    Print "[";
    For n As Integer = 1 To Ubound(arr)
        txt &= Str(arr(n)) & ","
    Next n
    txt = Left(txt, Len(txt) - 1)
    txt &= "]"
    Print txt
End Sub

Sub Sort(arr() As Integer)
    Dim As Integer i, j
    For i = 0 To Ubound(arr) - 1
        For j = i + 1 To Ubound(arr)
            If arr(i) > arr(j) Then Swap arr(i), arr(j)
        Next j
    Next i
End Sub

For n As Integer = 0 To Ubound(nums, 1)
    For m As Integer = 0 To Ubound(nums, 2)
        Sum(sumNums(), nums(n, m))
    Next m
Next n

Sort(sumNums())
For n As Integer = Ubound(sumNums) To 1 Step -1
    If sumNums(n) = sumNums(n - 1) Then
        Del(sumNums(), n)
    End If
Next n

Sort(sumNums())

Print "common sorted list elements are: "; 
showArray(sumNums())

Sleep
Output:
common sorted list elements are: [1,3,4,5,7,8,9]

Go

Translation of: Wren
package main

import (
    "fmt"
    "sort"
)

func distinctSortedUnion(ll [][]int) []int {
    var res []int
    for _, l := range ll {
        res = append(res, l...)
    }
    set := make(map[int]bool)
    for _, e := range res {
        set[e] = true
    }
    res = res[:0]
    for key := range set {
        res = append(res, key)
    }
    sort.Ints(res)
    return res
}

func main() {
    ll := [][]int{{5, 1, 3, 8, 9, 4, 8, 7}, {3, 5, 9, 8, 4}, {1, 3, 7, 9}}
    fmt.Println("Distinct sorted union of", ll, "is:")
    fmt.Println(distinctSortedUnion(ll))
}
Output:
Distinct sorted union of [[5 1 3 8 9 4 8 7] [3 5 9 8 4] [1 3 7 9]] is:
[1 3 4 5 7 8 9]

Haskell

import Data.List (nub, sort)

-------------------- COMMON SORTED LIST ------------------

commonSorted :: Ord a => [[a]] -> [a]
commonSorted = sort . nub . concat

--------------------------- TEST -------------------------
main :: IO ()
main =
  print $
    commonSorted
      [ [5, 1, 3, 8, 9, 4, 8, 7],
        [3, 5, 9, 8, 4],
        [1, 3, 7, 9]
      ]
Output:
[1,3,4,5,7,8,9]

J

csl =: /:~@~.@;
Output:
   nums =: 5 1 3 8 9 4 8 7;3 5 9 8 4;1 3 7 9
   csl nums
1 3 4 5 7 8 9

JavaScript

(() => {
    "use strict";

    // --------------- COMMON SORTED LIST ----------------

    // commonSorted :: Ord a => [[a]] -> [a]
    const commonSorted = xs =>
        sort(nub(concat(xs)));


    // ---------------------- TEST -----------------------
    const main = () =>
        commonSorted([
            [5, 1, 3, 8, 9, 4, 8, 7],
            [3, 5, 9, 8, 4],
            [1, 3, 7, 9]
        ]);


    // --------------------- GENERIC ---------------------

    // concat :: [[a]] -> [a]
    const concat = xs =>
        xs.flat(1);


    // nub :: Eq a => [a] -> [a]
    const nub = xs => [...new Set(xs)];


    // sort :: Ord a => [a] -> [a]
    const sort = xs =>
        // An (ascending) sorted copy of xs.
        xs.slice().sort();

    return main();
})();
Output:
[1, 3, 4, 5, 7, 8, 9]

jq

Works with: jq

Works with gojq, the Go implementation of jq

Assuming the input is a single array of arrays, we can simply chain the `add` and `unique` filters:

jq -nc '[[5,1,3,8,9,4,8,7], [3,5,9,8,4], [1,3,7,9]] | add | unique'
Output:
[1,3,4,5,7,8,9]

If the arrays are presented individually in an external stream, we could use the `-s` command-line option.

Alternatively, here's a stream-oriented version of `add` that could be used:

def add(s): reduce s as $x (null; . + $x);

For example:

jq -nc '
    def add(s): reduce s as $x (null; . + $x);
    add(inputs) | unique' <<< '[5,1,3,8,9,4,8,7] [3,5,9,8,4] [1,3,7,9]'

Julia

julia> sort(union([5,1,3,8,9,4,8,7], [3,5,9,8,4], [1,3,7,9]))
7-element Array{Int64,1}:
 1
 3
 4
 5
 7
 8
 9

julia> sort(union([2, 3, 4], split("3.14 is not an integer", r"\s+")), lt=(x, y) -> "$x" < "$y")
8-element Array{Any,1}:
 2
 3
  "3.14"
 4
  "an"
  "integer"
  "is"
  "not"

Mathematica/Wolfram Language

Union[{5, 1, 3, 8, 9, 4, 8, 7}, {3, 5, 9, 8, 4}, {1, 3, 7, 9}]
Output:
{1, 3, 4, 5, 7, 8, 9}

Maxima

common_sorted(lst):=unique(flatten(lst))$
nums:[[5,1,3,8,9,4,8,7],[3,5,9,8,4],[1,3,7,9]]$
common_sorted(nums);
Output:
[1,3,4,5,7,8,9]

Nim

We could use a HashSet or an IntSet to deduplicate. We have rather chosen to use the procedure deduplicate from module sequtils applied to the sorted list.

import algorithm, sequtils

proc commonSortedList(list: openArray[seq[int]]): seq[int] =
  sorted(concat(list)).deduplicate(true)

echo commonSortedList([@[5,1,3,8,9,4,8,7], @[3,5,9,8,4], @[1,3,7,9]])
Output:
@[1, 3, 4, 5, 7, 8, 9]

Pascal

Free Pascal

Program CommonSortedList;
{$mode ObjFPC}{$H+}

Uses sysutils,fgl;

Type 
  tarr = array Of array Of integer;

Const List1: tarr = ((5,1,3,8,9,4,8,7), (3,5,9,8,4), (1,3,7,9));

Var list : specialize TFPGList<integer>;

Procedure addtolist(arr : tarr);
Var i : integer;
  arr2 : array Of integer;
Begin
  For arr2 In arr Do
    For i In arr2 Do
      If (list.indexof(i) = -1) {make sure number isn't in list already}
        Then list.add(i);
End;

Function CompareInt(Const Item1,Item2: Integer): Integer;
Begin
  result := item1 - item2;
End;

Var i : integer;
Begin
  list := specialize TFPGList<integer>.create;
  addtolist(list1);
  List.Sort(@CompareInt); {quick sort the list}
  For i In list Do
    write(i:4);
  list.destroy;
End.
Output:
   1   3   4   5   7   8   9

Perl

@c{@$_}++ for [5,1,3,8,9,4,8,7], [3,5,9,8,4], [1,3,7,9];
print join ' ', sort keys %c;
@c{@$_}++ for [qw<not all is integer ? is not ! 4.2>];
print join ' ', sort keys %c;
Output:
1 3 4 5 7 8 9
! 1 3 4 4.2 5 7 8 9 ? all integer is not

Phix

Library: Phix/basics
?unique(join({{5,1,3,8,9,4,8,7}, {3,5,9,8,4}, {1,3,7,9}, split("not everything is an integer")},{}))

Note the join(x,{}): the 2nd param is needed to prevent it putting 32 (ie the acsii code for a space) in the output.

Output:

(Unexpectedly rather Yoda-esque)

{1,3,4,5,7,8,9,"an","everything","integer","is","not"}

Python

'''Common sorted list'''

from itertools import chain


# ------------------------- TEST -------------------------
# main :: IO ()
def main():
    '''Sorted union of lists'''

    print(
        sorted(nub(concat([
            [5, 1, 3, 8, 9, 4, 8, 7],
            [3, 5, 9, 8, 4],
            [1, 3, 7, 9]
        ])))
    )


# ----------------------- GENERIC ------------------------

# concat :: [[a]] -> [a]
# concat :: [String] -> String
def concat(xs):
    '''The concatenation of all the elements in a list.
    '''
    return list(chain(*xs))


# nub :: [a] -> [a]
def nub(xs):
    '''A list containing the same elements as xs,
       without duplicates, in the order of their
       first occurrence.
    '''
    return list(dict.fromkeys(xs))


# MAIN ---
if __name__ == '__main__':
    main()
Output:
[1, 3, 4, 5, 7, 8, 9]

Quackery

uniquewith is defined at Remove duplicate elements#Quackery.

  ' [ [ 5 1 3 8 9 4 8 7 ]
      [ 3 5 9 8 4 ]
      [ 1 3 7 9 ] ]
 
  [] swap witheach [ witheach join ]
  uniquewith > echo
Output:
[ 1 3 4 5 7 8 9 ]


Raku

put sort keys [∪] [5,1,3,8,9,4,8,7], [3,5,9,8,4], [1,3,7,9];
put sort keys [∪] [5,1,3,8,9,4,8,7], [3,5,9,8,4], [1,3,7,9], [<not everything is an integer so why not avoid special cases # ~ 23 4.2>];
Output:
1 3 4 5 7 8 9
# 1 3 4 4.2 5 7 8 9 23 an avoid cases everything integer is not so special why ~

REXX

/*REXX pgm creates and displays a  common sorted list  of a specified collection of sets*/
parse arg a                                      /*obtain optional arguments from the CL*/
if a='' | a=","  then a= '[5,1,3,8,9,4,8,7]  [3,5,9,8,4]  [1,3,7,9]'     /*default sets.*/
x= translate(a, ,'],[')                          /*extract elements from collection sets*/
se= words(x)
#= 0;            $=                              /*#: number of unique elements; $: list*/
$=                                               /*the list of common elements (so far).*/
    do j=1  for se;  _= word(x, j)               /*traipse through all elements in sets.*/
    if wordpos(_, $)>0  then iterate             /*Is element in the new list? Yes, skip*/
    $= $ _;   #= # + 1;    @.#= _                /*add to list; bump counter; assign──►@*/
    end   /*j*/
$=
call eSort #                                     /*use any short (small)  exchange sort.*/
                 do k=1  for #;   $= $  @.k      /*rebuild the $ list, it's been sorted.*/
                 end   /*k*/

say 'the list of sorted common elements in all sets: ' "["translate(space($), ',', " ")']'
exit 0                                           /*stick a fork in it,  we're all done. */
/*──────────────────────────────────────────────────────────────────────────────────────*/
eSort: procedure expose @.; arg h 1 z; do while h>1; h= h%2; do i=1  for z-h; j= i; k= h+i
        do while @.k<@.j; t=@.j; @.j=@.k; @.k=t; if h>=j then leave; j=j-h; k=k-h; end;end
        end;     return                          /*this sort was used 'cause of brevity.*/
output   when using the default inputs:
the list of sorted common elements in all sets:  [1,3,4,5,7,8,9]

Ring

nums = [[5,1,3,8,9,4,8,7],[3,5,9,8,4],[1,3,7,9]]
sumNums = []

for n = 1 to len(nums)
    for m = 1 to len(nums[n])
        add(sumNums,nums[n][m])
    next
next

sumNums = sort(sumNums)
for n = len(sumNums) to 2 step -1
    if sumNums[n] = sumNums[n-1]
       del(sumNums,n)
    ok
next

sumNums = sort(sumNums)

see "common sorted list elements are: "
showArray(sumNums)

func showArray(array)
     txt = ""
     see "["
     for n = 1 to len(array)
         txt = txt + array[n] + ","
     next
     txt = left(txt,len(txt)-1)
     txt = txt + "]"
     see txt
Output:
common sorted list elements are: [1,3,4,5,7,8,9]

RPL

Works with: HP version 48G
≪ ∑LIST SORT → nums
  ≪ { }
     1 nums SIZE FOR j
        nums j GET
        IF DUP2 POS THEN DROP ELSE + END 
     NEXT
≫ ≫ 'COMMON' STO
{ { 5 1 3 8 9 4 8 7 } { 3 5 9 8 4 } { 1 3 7 9 } } COMMON
Output:
1: { 1 3 4 5 7 8 9 } 

Ruby

nums = [5,1,3,8,9,4,8,7], [3,5,9,8,4], [1,3,7,9]
p nums.inject(:+).sort.uniq
Output:
[1, 3, 4, 5, 7, 8, 9]

Uiua

F ← ⊏⍏.◴/◇⊂
Output:
F {[5 1 3 8 9 4 8 7] [3 5 9 8 4] [1 3 7 9]}
[1 3 4 5 7 8 9]

V (Vlang)

fn main() {
    nums := [[5,1,3,8,9,4,8,7], [3,5,9,8,4], [1,3,7,9]]
    println("Distinct sorted union of $nums is:")
    println(common_sorted_list(nums))
}

fn common_sorted_list(nums [][]int) []int {
    mut elements, mut output := map[int]bool{}, []int{}
	
    for num in nums {
        for value in num {
            elements[value] = true
        }
    }

    for key, _ in elements {
        output << key
    }
    output.sort()
    return output
}
Output:
Distinct sorted union of [[5 1 3 8 9 4 8 7] [3 5 9 8 4] [1 3 7 9]] is:
[1 3 4 5 7 8 9]

Wren

Library: Wren-seq
Library: Wren-sort
import "./seq" for Lst
import "./sort" for Sort

var distinctSortedUnion = Fn.new { |ll| 
    var res = ll.reduce([]) { |acc, l| acc + l }
    res = Lst.distinct(res)
    Sort.insertion(res)
    return res
}

var ll = [[5, 1, 3, 8, 9, 4, 8, 7], [3, 5, 9, 8, 4], [1, 3, 7, 9]]
System.print("Distinct sorted union of %(ll) is:")
System.print(distinctSortedUnion.call(ll))
Output:
Distinct sorted union of [[5, 1, 3, 8, 9, 4, 8, 7], [3, 5, 9, 8, 4], [1, 3, 7, 9]] is:
[1, 3, 4, 5, 7, 8, 9]