Find first missing positive: Difference between revisions
m
Added Easylang
(Added XPL0 example.) |
m (Added Easylang) |
||
(19 intermediate revisions by 12 users not shown) | |||
Line 11:
=={{header|11l}}==
<
L(l) nums
Line 17:
I n !C l
print(l‘ -> ’n)
L.break</
{{out}}
Line 27:
=={{header|Action!}}==
<
BYTE FUNC Contains(INT ARRAY a INT len,x)
Line 89:
arr(3)=a4 arr(4)=a4
Test(arr,lengths,COUNT)
RETURN</
{{out}}
[https://gitlab.com/amarok8bit/action-rosetta-code/-/raw/master/images/Find_first_missing_positive.png Screenshot from Atari 8-bit computer]
Line 98:
[-2 -6 -16] -> 1
[] -> 1
</pre>
=={{header|ALGOL 68}}==
Uses the observation in the J sample that the maximum possible minimum missing positive integer is one more than the length of the list.
<syntaxhighlight lang="algol68">BEGIN # find the lowest positive integer not present in various arrays #
# returns the lowest positive integer not present in r #
PROC min missing positive = ( []INT r )INT:
BEGIN
[]INT a = r[ AT 1 ]; # a is r wih lower bound 1 #
# as noted in the J sample, the maximum possible minimum #
# missing positive integer is one more than the length of the array #
# note the values between 1 and UPB a present in a #
[ 1 : UPB a ]BOOL present;
FOR i TO UPB a DO present[ i ] := FALSE OD;
FOR i TO UPB a DO
INT ai = a[ i ];
IF ai >= 1 AND ai <= UPB a THEN
present[ ai ] := TRUE
FI
OD;
# find the lowest value not in present #
INT result := UPB a + 1;
BOOL found := FALSE;
FOR i TO UPB a WHILE NOT found DO
IF NOT present[ i ] THEN
found := TRUE;
result := i
FI
OD;
result
END # min missing positive # ;
print( ( " ", whole( min missing positive( ( 1, 2, 0 ) ), 0 ) ) );
print( ( " ", whole( min missing positive( ( 3, 4, -1, 1 ) ), 0 ) ) );
print( ( " ", whole( min missing positive( ( 7, 8, 9, 11, 12 ) ), 0 ) ) )
END</syntaxhighlight>
{{out}}
<pre>
3 2 1
</pre>
=={{header|APL}}==
{{works with|Dyalog APL}}
<
{{out}}
<pre> fmp¨ (1 2 0) (3 4 ¯1 1) (7 8 9 11 12)
Line 109 ⟶ 147:
=={{header|AppleScript}}==
===Procedural===
<
set output to {}
repeat with aList in {{1, 2, 0}, {3, 4, -1, 1}, {7, 8, 9, 11, 12}}
Line 118 ⟶ 156:
set end of output to n
end repeat
return output</
{{output}}
<syntaxhighlight lang
Line 128 ⟶ 166:
Defining the value required in terms of pre-existing generic primitives:
<
-- firstGap :: [Int] -> Int
Line 249 ⟶ 287:
set my text item delimiters to dlm
s
end unlines</
{{Out}}
<pre>{1, 2, 0} -> 3
{3, 4, -1, 1} -> 2
{7, 8, 9, 11, 12} -> 1</pre>
=={{header|Arturo}}==
<syntaxhighlight lang="arturo">sets: @[[1 2 0] @[3 4 neg 1 1] [7 8 9 11 12]]
loop sets 's ->
print [
"Set:" s
"-> First missing positive integer:" first select.first 1..∞ 'x -> not? in? x s
]</syntaxhighlight>
{{out}}
<pre>Set: [1 2 0] -> First missing positive integer: 3
Set: [3 4 -1 1] -> First missing positive integer: 2
Set: [7 8 9 11 12] -> First missing positive integer: 1</pre>
=={{header|AutoHotkey}}==
<
Arr := [], i := 0
for k, v in obj
Line 267 ⟶ 321:
m := m ? m : Max(obj*) + 1
return m>0 ? m : 1
}</
Examples:<
for i, obj in nums{
m := First_Missing_Positive(obj)
Line 274 ⟶ 328:
}
MsgBox % Trim(output, ", ")
return</
{{out}}
<pre>3, 2, 1, 1, 1</pre>
=={{header|AWK}}==
<syntaxhighlight lang="awk">
# syntax: GAWK -f FIND_FIRST_MISSING_POSITIVE.AWK
BEGIN {
Line 311 ⟶ 365:
exit(0)
}
</syntaxhighlight>
{{out}}
<pre>
Line 317 ⟶ 371:
</pre>
=={{header|BASIC}}==
<
20 READ X
30 FOR A=1 TO X
Line 341 ⟶ 395:
230 DATA 3, 1,2,0
240 DATA 4, 3,4,-1,1
250 DATA 5, 7,8,9,11,12</
{{out}}
<pre> 1 2 0 ==> 3
Line 348 ⟶ 402:
=={{header|BCPL}}==
<
let max(v, n) = valof
Line 376 ⟶ 430:
show(4, table 3,4,-1,1)
show(5, table 7,8,9,11,12)
$)</
{{out}}
<pre>1 2 0 ==> 3
Line 383 ⟶ 437:
=={{header|BQN}}==
<
FMP¨ ⟨⟨1,2,0⟩,⟨3,4,¯1,1⟩,⟨7,8,9,11,12⟩⟩</
{{out}}
<pre>⟨ 3 2 1 ⟩</pre>
=={{header|C++}}==
<syntaxhighlight lang="cpp">#include <iostream>
#include <unordered_set>
#include <vector>
int FindFirstMissing(const std::vector<int>& r)
{
// put them into an associative container
std::unordered_set us(r.begin(), r.end());
size_t result = 0;
while (us.contains(++result)); // find the first number that isn't there
return (int)result;
}
int main()
{
std::vector<std::vector<int>> nums {{1,2,0}, {3,4,-1,1}, {7,8,9,11,12}};
std::for_each(nums.begin(), nums.end(),
[](auto z){std::cout << FindFirstMissing(z) << " "; });
}</syntaxhighlight>
{{out}}
<pre>
3 2 1 </pre>
=={{header|CLU}}==
<
where T has equal: proctype (T,T) returns (bool),
U has elements: itertype (U) yields (T)
Line 420 ⟶ 498:
stream$putl(po, "==> " || int$unparse(fmp[si](test)))
end
end start_up</
{{out}}
<pre>1 2 0 ==> 3
3 4 -1 1 ==> 2
7 8 9 11 12 ==> 1</pre>
=={{header|Delphi}}==
{{works with|Delphi|6.0}}
{{libheader|SysUtils,StdCtrls}}
Uses the Delphi "TList" object to search the list for missing integers.
<syntaxhighlight lang="Delphi">
var List1: array [0..2] of integer =(1,2,0);
var List2: array [0..3] of integer =(3,4,-1,1);
var List3: array [0..4] of integer =(7,8,9,11,12);
function FindMissingInt(IA: array of integer): integer;
var I,Inx: integer;
var List: TList;
begin
List:=TList.Create;
try
Result:=-1;
for I:=0 to High(IA) do List.Add(Pointer(IA[I]));
for Result:=1 to High(integer) do
begin
Inx:=List.IndexOf(Pointer(Result));
if Inx<0 then exit;
end;
finally List.Free; end;
end;
function GetIntStr(IA: array of integer): string;
var I: integer;
begin
Result:='[';
for I:=0 to High(IA) do
begin
if I>0 then Result:=Result+',';
Result:=Result+Format('%3.0d',[IA[I]]);
end;
Result:=Result+']';
end;
procedure ShowMissingInts(Memo: TMemo);
var S: string;
var M: integer;
begin
S:=GetIntStr(List1);
M:=FindMissingInt(List1);
Memo.Lines.Add(S+' = '+IntToStr(M));
S:=GetIntStr(List2);
M:=FindMissingInt(List2);
Memo.Lines.Add(S+' = '+IntToStr(M));
S:=GetIntStr(List3);
M:=FindMissingInt(List3);
Memo.Lines.Add(S+' = '+IntToStr(M));
end;
</syntaxhighlight>
{{out}}
<pre>
[ 1, 2, 0] = 3
[ 3, 4, -1, 1] = 2
[ 7, 8, 9, 11, 12] = 1
</pre>
=={{header|EasyLang}}==
<syntaxhighlight>
func missing a[] .
h = 1
repeat
v = 0
for v in a[]
if h = v
break 1
.
.
until v <> h
h += 1
.
return h
.
a[][] = [ [ 1 2 0 ] [ 3 4 -1 1 ] [ 7 8 9 11 12 ] ]
for i to len a[][]
write missing a[i][] & " "
.
</syntaxhighlight>
{{out}}
<pre>
3 2 1
</pre>
=={{header|F_Sharp|F#}}==
<
// Find first missing positive. Nigel Galloway: February 15., 2021
let fN g=let g=0::g|>List.filter((<) -1)|>List.sort|>List.distinct
match g|>List.pairwise|>List.tryFind(fun(n,g)->g>n+1) with Some(n,_)->n+1 |_->List.max g+1
[[1;2;0];[3;4;-1;1];[7;8;9;11;12]]|>List.iter(fN>>printf "%d "); printfn ""
</syntaxhighlight>
{{out}}
<pre>
Line 439 ⟶ 613:
=={{header|Factor}}==
<
: first-missing ( seq -- n )
Line 446 ⟶ 620:
{ { 1 2 0 } { 3 4 1 1 } { 7 8 9 11 12 } { 1 2 3 4 5 }
{ -6 -5 -2 -1 } { 5 -5 } { -2 } { 1 } { } }
[ dup first-missing "%u ==> %d\n" printf ] each</
{{out}}
<pre>
Line 461 ⟶ 635:
=={{header|FreeBASIC}}==
<
for i as uinteger = 1 to ubound(n)
if n(i) = k then return true
Line 482 ⟶ 656:
print fmp(a())
print fmp(b())
print fmp(c())</
{{out}}<pre>
3
Line 491 ⟶ 665:
=={{header|Go}}==
{{trans|Wren}}
<
import (
Line 526 ⟶ 700:
fmt.Println(a, "->", firstMissingPositive(a))
}
}</
{{out}}
Line 545 ⟶ 719:
=={{header|Haskell}}==
{{trans|Wren}}
<
task :: Integral a => [a] -> a
Line 561 ⟶ 735:
map
task
[[1, 2, 0], [3, 4, -1, 1], [7, 8, 9, 11, 12]]</
{{out}}
<pre>[3,2,1]</pre>
Line 567 ⟶ 741:
Or simply as a filter over an infinite list:
<
firstGap :: [Int] -> Int
Line 582 ⟶ 756:
[3, 4, -1, 1],
[7, 8, 9, 11, 12]
]</
and if xs were large, it could be defined as a set:
<
---------- FIRST MISSING POSITIVE NATURAL NUMBER ---------
Line 592 ⟶ 766:
firstGap xs = head $ filter (`notMember` seen) [1 ..]
where
seen = fromList xs</
{{Out}}
Same output for '''notElem''' and '''notMember''' versions above:
Line 600 ⟶ 774:
=={{header|J}}==
The first missing positive can be no larger than 1 plus the length of the list
<syntaxhighlight lang="j">fmp=: {{ {.y-.~1+i.1+#y }}S:0</syntaxhighlight>
(The <nowiki>{{ }}</nowiki> delimiters on definitions, used here, was introduced in J version 9.2)
Example use:
<
3 2 1</
Also, with this approach:
<syntaxhighlight lang=J> fmp 'abc'
1</syntaxhighlight>
=={{header|JavaScript}}==
<
"use strict";
Line 684 ⟶ 863:
// MAIN ---
return main();
})();</
{{Out}}
<pre>[1,2,0] -> 3
Line 696 ⟶ 875:
In case the target array is very long, it probably makes sense either to sort it,
or to use a hash, for quick lookup. For the sake of illustration, we'll use a hash:
<syntaxhighlight lang="jq">
# input: an array of integers
def first_missing_positive:
Line 709 ⟶ 888:
# The task:
examples
| "\(first_missing_positive) is missing from \(.)"</
{{out}}
<pre>
Line 719 ⟶ 898:
=={{header|Julia}}==
<
for array in [[1,2,0], [3,4,-1,1], [7,8,9,11,12], [-5, -2, -6, -1]]
for n in 1:typemax(Int)
Line 725 ⟶ 904:
end
end
</
<pre>
[1, 2, 0] => 3
Line 737 ⟶ 916:
In order to avoid the O(n) search in arrays, we could use an intermediate set built from the sequence. But this is useless with the chosen examples.
<
for n in 1..int.high:
if n notin a:
echo a, " → ", n
break</
{{out}}
Line 750 ⟶ 929:
=={{header|Perl}}==
<
use strict;
Line 763 ⟶ 942:
print "[ @$test ] ==> ",
first { not { map { $_ => 1 } @$test }->{$_} } 1 .. @$test + 1;
}</
{{out}}
<pre>
Line 779 ⟶ 958:
=={{header|Phix}}==
<!--<
<span style="color: #008080;">with</span> <span style="color: #008080;">javascript_semantics</span>
<span style="color: #008080;">procedure</span> <span style="color: #000000;">test</span><span style="color: #0000FF;">(</span><span style="color: #004080;">sequence</span> <span style="color: #000000;">s</span><span style="color: #0000FF;">)</span>
Line 790 ⟶ 969:
<span style="color: #008080;">end</span> <span style="color: #008080;">procedure</span>
<span style="color: #7060A8;">papply</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;">0</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: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #000000;">1</span><span style="color: #0000FF;">},{</span><span style="color: #000000;">7</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;">11</span><span style="color: #0000FF;">,</span><span style="color: #000000;">12</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: #000000;">5</span><span style="color: #0000FF;">},{-</span><span style="color: #000000;">6</span><span style="color: #0000FF;">,-</span><span style="color: #000000;">5</span><span style="color: #0000FF;">,-</span><span style="color: #000000;">2</span><span style="color: #0000FF;">,-</span><span style="color: #000000;">1</span><span style="color: #0000FF;">},{</span><span style="color: #000000;">5</span><span style="color: #0000FF;">,-</span><span style="color: #000000;">5</span><span style="color: #0000FF;">},{-</span><span style="color: #000000;">2</span><span style="color: #0000FF;">},{</span><span style="color: #000000;">1</span><span style="color: #0000FF;">},{}}</span> <span style="color: #0000FF;">,</span><span style="color: #000000;">test</span><span style="color: #0000FF;">)</span>
<!--</
{{out}}
<pre>
Line 805 ⟶ 984:
=={{header|Python}}==
<
from itertools import count
Line 831 ⟶ 1,010:
# MAIN ---
if __name__ == '__main__':
main()</
{{Out}}
<pre>[1, 2, 0] -> 3
Line 841 ⟶ 1,020:
{{works with|QBasic}}
{{works with|QuickBasic|4.5}}
<
DECLARE FUNCTION fmp (n())
Line 873 ⟶ 1,052:
IF n(i) = k THEN isin = 1
NEXT i
END FUNCTION</
{{out}}
<pre>3
Line 879 ⟶ 1,058:
1</pre>
=={{header|Quackery}}==
===Using a bitmap as a set===
Treat a number (BigInt) as a set of integers. Add the positive integers to the set, then find the first positive integer not in the set.
<syntaxhighlight lang="Quackery"> [ 0 0 rot
witheach
[ dup 0 > iff
[ bit | ]
else drop ]
[ dip 1+
1 >> dup 1 &
0 = until ]
drop ] is task ( [ --> n )
' [ [ 1 2 0 ] [ 3 4 -1 1 ] [ 7 8 9 11 12 ] ]
witheach [ task echo sp ]</syntaxhighlight>
{{out}}
<pre>3 2 1</pre>
===Using filtering and sorting===
Filter out the non-positive integers, and then non-unique elements (after adding zero).
<code>uniquewith</code> is defined at [[Remove duplicate elements#Quackery]] and conveniently sorts the nest.
Then hunt for the first item which does not have the same value as its index. If they all have the same values as their indices, the missing integer is the same as the size of the processed nest.
<syntaxhighlight lang="Quackery"> [ [] swap
witheach
[ dup 0 > iff
join
else drop ]
0 join
uniquewith >
dup size swap
witheach
[ i^ != if
[ drop i^
conclude ] ] ] is task ( [ --> n )
' [ [ 1 2 0 ] [ 3 4 -1 1 ] [ 7 8 9 11 12 ] ]
witheach [ task echo sp ]</syntaxhighlight>
{{out}}
<pre>3 2 1</pre>
===Brute force===
Search for each integer. The largest the missing integer can be is one more than the number of items in the nest.
<syntaxhighlight lang="Quackery"> [ dup size
dup 1+ unrot
times
[ i^ 1+
over find
over found not if
[ dip
[ drop i^ 1+ ]
conclude ] ]
drop ] is task ( [ --> n )
' [ [ 1 2 0 ] [ 3 4 -1 1 ] [ 7 8 9 11 12 ] ]
witheach [ task echo sp ]</syntaxhighlight>
{{out}}
<pre>3 2 1</pre>
=={{header|Raku}}==
<syntaxhighlight lang="raku"
[ 1, 2, 0], [3, 4, 1, 1], [7, 8, 9, 11, 12], [1, 2, 3, 4, 5], [-6, -5, -2, -1], [5, -5], [-2], [1], []</
{{out}}
<pre>[1 2 0] ==> 3
Line 896 ⟶ 1,149:
=={{header|REXX}}==
This REXX version doesn't need to sort the elements of the sets, it uses an associated array.
<
parse arg a /*obtain optional arguments from the CL*/
if a='' | a="," then a= '[1,2,0] [3,4,-1,1] [7,8,9,11,12] [1,2,3,4,5]' ,
Line 914 ⟶ 1,167:
if @.m=='' then m= 1 /*handle the case of a "null" set. */
say right( word(a, j), 40) ' ───► ' m /*show the set and the missing integer.*/
end /*j*/ /*stick a fork in it, we're all done. */</
{{out|output|text= when using the default inputs:}}
<pre>
Line 931 ⟶ 1,184:
=={{header|Ring}}==
<
[-6,-5,-2,-1], [5,-5], [-2], [1], []]
Line 950 ⟶ 1,203:
if n = len(ary) s = "" ok
res += "" + ary[n] + s
next return res + "]"</
{{out}}
<pre>the smallest missing positive integer for [1,2,0]: 3
Line 962 ⟶ 1,215:
the smallest missing positive integer for []: 1</pre>
=={{header|RPL}}==
≪ 1 '''WHILE''' DUP2 POS '''REPEAT''' 1 + '''END''' SWAP DROP ≫ '<span style="color:blue">FINDF</span>' STO
{ { 1 2 0 } { 3 4 -1 1 } { 7 8 9 11 12 } } 1 ≪ <span style="color:blue">FINDF</span> ≫ DOLIST
{{out}}
<pre>
1: { 3 2 1 }
</pre>
=={{header|Ruby}}==
<
puts nums.map{|ar|(1..).find{|candidate| !ar.include?(candidate) }}.join(", ")</
{{out}}
<pre>3, 2, 1</pre>
=={{header|Sidef}}==
<syntaxhighlight lang="ruby">[[1,2,0], [3,4,1,1], [7,8,9,11,12],[1,2,3,4,5],
[-6,-5,-2,-1], [5,-5], [-2], [1], []].each {|arr|
var s = Set(arr...)
say (arr, " ==> ", 1..Inf -> first {|k| !s.has(k) })
}</syntaxhighlight>
{{out}}
<pre>[1, 2, 0] ==> 3
[3, 4, 1, 1] ==> 2
[7, 8, 9, 11, 12] ==> 1
[1, 2, 3, 4, 5] ==> 6
[-6, -5, -2, -1] ==> 1
[5, -5] ==> 1
[-2] ==> 1
[1] ==> 2
[] ==> 1</pre>
=={{header|True BASIC}}==
<
FOR i = LBOUND(n) TO UBOUND(n)
IF n(i) = k THEN LET isin = 1
Line 1,004 ⟶ 1,283:
DATA 3,4,-1,1
DATA 7,8,9,11,12
END</
=={{header|V (Vlang)}}==
{{trans|go}}
<syntaxhighlight lang="v (vlang)">fn first_missing_positive(a []int) int {
mut b := []int{}
for e in a {
if e > 0 {
b << e
}
}
b.sort<int>()
le := b.len
if le == 0 || b[0] > 1 {
return 1
}
for i in 1..le {
if b[i]-b[i-1] > 1 {
return b[i-1] + 1
}
}
return b[le-1] + 1
}
fn main() {
println("The first missing positive integers for the following arrays are:\n")
aa := [
[1, 2, 0], [3, 4, -1, 1], [7, 8, 9, 11, 12], [1, 2, 3, 4, 5],
[-6, -5, -2, -1], [5, -5], [-2], [1]]
for a in aa {
println("$a -> ${first_missing_positive(a)}")
}
}</syntaxhighlight>
{{out}}
<pre>Same as go entry</pre>
=={{header|Wren}}==
{{libheader|Wren-sort}}
<
var firstMissingPositive = Fn.new { |a|
Line 1,027 ⟶ 1,340:
[-6, -5, -2, -1], [5, -5], [-2], [1], []
]
for (a in aa) System.print("%(a) -> %(firstMissingPositive.call(a))")</
{{out}}
Line 1,045 ⟶ 1,358:
=={{header|XPL0}}==
<
int Arr, Len, N, N0, I;
[N:= 1;
Line 1,060 ⟶ 1,373:
ShowMissing( Nums(I), (Nums(I+1)-Nums(I))/4 );
];
]</
{{out}}
|