Sort primes from list to a list: Difference between revisions
Content deleted Content added
(14 intermediate revisions by 11 users not shown) | |||
Line 12:
{{libheader|ALGOL 68-primes}}
{{libheader|ALGOL 68-rows}}
<
PR read "primes.incl.a68" PR # include prime utilities #
PR read "rows.incl.a68" PR # include row (array) utilities #
Line 30:
print( ( newline, " are: " ) );
SHOW ( QUICKSORT prime list FROMELEMENT 1 TOELEMENT p count )[ 1 : p count ]
END</
{{out}}
<pre>
Line 36:
are: 2 7 13 43 103
</pre>
=={{header|AppleScript}}==
The strangely worded title and task description suggest to this native English speaker that the task is to sort each prime into the primes list ''as it's identified'', which is certainly a less pointless coding exercise than simply extracting all the primes and then sorting them. The implementation here allows for the primes list to be created from scratch or supplied with a few ordered numbers already in it. The sort process is part of an insertion sort.
<syntaxhighlight lang="applescript">on isPrime(n)
if (n < 4) then return (n > 1)
if ((n mod 2 is 0) or (n mod 3 is 0)) then return false
repeat with i from 5 to (n ^ 0.5) div 1 by 6
if ((n mod i is 0) or (n mod (i + 2) is 0)) then return false
end repeat
return true
end isPrime
-- primes list created from scratch.
on sortPrimesFromList:givenList
return my sortPrimesFromList:givenList toList:{}
end sortPrimesFromList:
-- primes list supplied as a parameter, its current contents assumed to be already ordered ascending.
on sortPrimesFromList:givenList toList:primes
set j to (count primes)
repeat with this in givenList
set this to this's contents
if (isPrime(this)) then
set end of primes to this
set j to j + 1
if (j > 1) then
repeat with i from (j - 1) to 1 by -1
set v to primes's item i
if (v > this) then
set primes's item (i + 1) to v
else
set i to i + 1
exit repeat
end if
end repeat
set primes's item i to this
end if
end if
end repeat
return primes
end sortPrimesFromList:toList:
on demo()
set primes to my sortPrimesFromList:{2, 43, 81, 22, 63, 13, 7, 95, 103}
log primes
my sortPrimesFromList:{8, 137, 19, 5, 44, 23} toList:primes
log primes
end demo
demo()</syntaxhighlight>
{{output}}
<pre>Log:
(*2, 7, 13, 43, 103*)
(*2, 5, 7, 13, 19, 23, 43, 103, 137*)</pre>
=={{header|Arturo}}==
<syntaxhighlight lang="arturo">lst: [2 43 81 122 63 13 7 95 103]
print sort select lst => prime?</syntaxhighlight>
{{out}}
<pre>2 7 13 43 103</pre>
=={{header|AutoHotkey}}==
<
t := [], result := []
Line 53 ⟶ 121:
v := A_Index = 1 ? n : mod(n,A_Index) ? v : v "," A_Index "," n//A_Index
Return (v = n)
}</
{{out}}
<pre>[2, 7, 13, 43, 103]</pre>
=={{header|AWK}}==
<syntaxhighlight lang="awk">
# syntax: GAWK -f SORT_PRIMES_FROM_LIST_TO_A_LIST.AWK
BEGIN {
Line 84 ⟶ 152:
return(1)
}
</syntaxhighlight>
{{out}}
<pre>
Line 94 ⟶ 162:
==={{header|BASIC256}}===
{{trans|FreeBASIC}}
<
global temp
Line 150 ⟶ 218:
call sort(temp)
call showArray(temp)
end</
{{out}}
<pre>
Line 157 ⟶ 225:
==={{header|FreeBASIC}}===
<
Function isPrime(Byval ValorEval As Integer) As Boolean
Line 198 ⟶ 266:
sort(temp())
showArray(temp())
Sleep</
{{out}}
<pre>[2,7,13,43,103]</pre>
==={{header|Yabasic}}===
<
Primes(1) = 2
Primes(2) = 43
Line 256 ⟶ 324:
txt$ = txt$ + "]"
print txt$
end sub</
{{out}}
<pre>
Igual que la entrada de FreeBASIC.
</pre>
=={{header|Delphi}}==
{{works with|Delphi|6.0}}
{{libheader|SysUtils,StdCtrls}}
Uses Delphi TList object to hold and sort the data.
<syntaxhighlight lang="Delphi">
{Raw data to process}
var NumList: array [0..8] of integer = (2,43,81,122,63,13,7,95,103);
function Compare(P1,P2: pointer): integer;
{Compare for quick sort}
begin
Result:=Integer(P1)-Integer(P2);
end;
procedure GetSortedPrimes(Nums: Array of integer; var IA: TIntegerDynArray);
{Extract data from array "Nums" and return a sorted list of primes}
var I: integer;
var List: TList;
begin
List:=TList.Create;
try
{Put the primes in the TList object}
for I:=0 to High(Nums) do
if IsPrime(Nums[I]) then List.Add(Pointer(Nums[I]));
{Sort the list}
List.Sort(Compare);
{Put the result in array}
SetLength(IA,List.Count);
for I:=0 to List.Count-1 do
IA[I]:=Integer(List[I]);
finally List.Free; end;
end;
function ArrayToStr(Nums: array of integer): string;
{Convert array of integers to a string}
var I: integer;
begin
Result:='[';
for I:=0 to High(Nums) do
begin
if I<>0 then Result:=Result+',';
Result:=Result+IntToStr(Nums[I]);
end;
Result:=Result+']';
end;
procedure ShowSortedPrimes(Memo: TMemo);
var I: integer;
var IA: TIntegerDynArray;
var S: string;
begin
GetSortedPrimes(NumList,IA);
Memo.Lines.Add('Raw data: '+ArrayToStr(NumList));
Memo.Lines.Add('Sorted Primes: '+ArrayToStr(IA));
end;
</syntaxhighlight>
{{out}}
<pre>
Raw data: [2,43,81,122,63,13,7,95,103]
Sorted Primes: [2,7,13,43,103]
Elapsed Time: 2.910 ms.
</pre>
=={{header|EasyLang}}==
<syntaxhighlight lang=text>
fastfunc isprim num .
i = 2
while i <= sqrt num
if num mod i = 0
return 0
.
i += 1
.
return 1
.
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]
.
.
.
.
inp[] = [ 2 43 81 122 63 13 7 95 103 ]
for v in inp[]
if isprim v = 1
d[] &= v
.
.
sort d[]
print d[]
</syntaxhighlight>
{{out}}
<pre>
[ 2 7 13 43 103 ]
</pre>
=={{header|F_Sharp|F#}}==
This task uses [http://www.rosettacode.org/wiki/Extensible_prime_generator#The_functions Extensible Prime Generator (F#)]
<
// Primes from a list. Nigel Galloway: Januuary 23rd., 2022
[2;43;81;122;63;13;7;95;103]|>List.filter isPrime|>List.sort|>List.iter(printf "%d "); printfn ""
</syntaxhighlight>
{{out}}
<pre>
Line 275 ⟶ 448:
=={{header|Factor}}==
{{works with|Factor|0.99 2021-06-02}}
<
{ 2 43 81 122 63 13 7 95 103 } [ prime? ] filter natural-sort . </
{{out}}
<pre>
Line 285 ⟶ 458:
=={{header|Go}}==
{{libheader|Go-rcu}}
<
import (
Line 303 ⟶ 476:
sort.Ints(primes)
fmt.Println(primes)
}</
{{out}}
<pre>
[2 7 13 43 103]
</pre>
=={{header|Haskell}}==
<syntaxhighlight lang="haskell">import Data.List ( sort )
isPrime :: Int -> Bool
isPrime n
|n == 1 = False
|n == 2 = True
|otherwise = all (\d -> mod n d /= 0 ) [2..limit]
where
limit = floor $ sqrt $ fromIntegral n
solution :: [Int]
solution = sort $ filter isPrime [2 , 43 , 122 , 63, 13 , 7 , 95 , 103]
</syntaxhighlight>
{{out}}
<pre>
[2,7,13,43,103]
</pre>
Line 314 ⟶ 506:
This is a filter (on primality) and a sort (though we could first sort then filter if we preferred):
<
2 7 13 43 103</
=={{header|jq}}==
Line 322 ⟶ 514:
See [[Erdős-primes#jq]] for a suitable definition of `is_prime` as used here.
<
lst | map( select(is_prime) ) | sort</
{{out}}
<pre>
Line 332 ⟶ 524:
=={{header|Julia}}==
<
julia> sort(filter(isprime, [2,43,81,122,63,13,7,95,103]))
Line 341 ⟶ 533:
43
103
</syntaxhighlight>
=={{header|Mathematica}}/{{header|Wolfram Language}}==
<
{{out}}
<pre>{2, 7, 13, 43, 103}</pre>
=={{header|Nim}}==
<syntaxhighlight lang="Nim">import std/[algorithm, strutils]
let primes = [2, 43, 81, 122, 63, 13, 7, 95, 103]
echo sorted(primes).join(", ")
</syntaxhighlight>
{{out}}
<pre>2, 7, 13, 43, 63, 81, 95, 103, 122
</pre>
=={{header|Perl}}==
<
use strict; # https://rosettacode.org/wiki/Sort_primes_from_list_to_a_list
Line 356 ⟶ 559:
use List::AllUtils qw( nsort_by );
print "@{[ nsort_by {$_} grep is_prime($_), 2,43,81,122,63,13,7,95,103 ]}\n";</
{{out}}
<pre>
Line 364 ⟶ 567:
=={{header|Phix}}==
You could also use unique() instead of sort(), since that (by default) performs a sort() internally anyway. It wouldn't be any slower, might even be better, also it does not really make much difference here whether you filter() before or after the sort(), though of course some more expensive filtering operations might be faster given fewer items.
<!--<
<span style="color: #008080;">with</span> <span style="color: #008080;">javascript_semantics</span>
<span style="color: #7060A8;">pp</span><span style="color: #0000FF;">(</span><span style="color: #7060A8;">sort</span><span style="color: #0000FF;">(</span><span style="color: #7060A8;">filter</span><span style="color: #0000FF;">({</span><span style="color: #000000;">2</span><span style="color: #0000FF;">,</span><span style="color: #000000;">43</span><span style="color: #0000FF;">,</span><span style="color: #000000;">81</span><span style="color: #0000FF;">,</span><span style="color: #000000;">122</span><span style="color: #0000FF;">,</span><span style="color: #000000;">63</span><span style="color: #0000FF;">,</span><span style="color: #000000;">13</span><span style="color: #0000FF;">,</span><span style="color: #000000;">7</span><span style="color: #0000FF;">,</span><span style="color: #000000;">95</span><span style="color: #0000FF;">,</span><span style="color: #000000;">103</span><span style="color: #0000FF;">},</span><span style="color: #7060A8;">is_prime</span><span style="color: #0000FF;">)))</span>
<!--</
{{out}}
<pre>
Line 375 ⟶ 578:
=={{header|Python}}==
===Python: Procedural===
<
print("Primes are:")
Line 393 ⟶ 596:
Temp.sort()
print(Temp)
print("done...")</
{{out}}
<pre>working...
Line 401 ⟶ 604:
===Python: Functional===
<
Line 444 ⟶ 647:
# MAIN ---
if __name__ == '__main__':
main()</
{{Out}}
<pre>[2, 7, 13, 43, 103]</pre>
=={{header|Quackery}}==
<code>eratosthenes</code> and <code>isprime</code> are defined at [[Sieve of Eratosthenes#Quackery]].
<syntaxhighlight lang="Quackery"> ' [ 2 43 81 122 63 13 7 95 103 ]
sort
dup -1 peek eratosthenes
[] swap witheach
[ dup isprime iff join else drop ]
echo</syntaxhighlight>
{{out}}
<pre>[ 2 7 13 43 103 ]</pre>
=={{header|Raku}}==
<syntaxhighlight lang="raku"
{{out}}
<pre>2 7 13 43 103</pre>
''Of course "ascending" is a little ambiguous. That ^^^ is numerically. This vvv is lexicographically.
<syntaxhighlight lang="raku"
{{out}}
<pre>103 13 2 43 7</pre>
=={{header|Ring}}==
<
load "stdlibcore.ring"
? "working"
Line 484 ⟶ 702:
txt = txt + "]"
? txt
</syntaxhighlight>
{{out}}
<pre>
Line 491 ⟶ 709:
[2,7,13,43,103]
done...
</pre>
=={{header|RPL}}==
{{works with|HP|49}}
'''With control flow structure'''
« SORT { }
1 PICK3 SIZE '''FOR''' j
OVER j GET
'''IF''' DUP ISPRIME? '''THEN''' + '''ELSE''' DROP '''END'''
'''NEXT''' NIP
» '<span style="color:blue">TASK</span>' STO
'''Direct computation'''
« DUP ISPRIME? SWAP IFT SORT
» '<span style="color:blue">TASK</span>' STO
{2,43,81,122,63,13,7,95,103} <span style="color:blue">TASK</span>
{{out}}
<pre>1: { 2 7 13 43 103 }
</pre>
=={{header|Ruby}}==
<syntaxhighlight lang="ruby">require 'prime'
p [2,43,81,122,63,13,7,95,103].select(&:prime?).sort</syntaxhighlight>
{{out}}
<pre>[2, 7, 13, 43, 103]
</pre>
=={{header|Rust}}==
<syntaxhighlight lang="rust>fn is_prime( number : u32 ) -> bool {
let result : bool = match number {
0 => false ,
1 => false ,
2 => true ,
_ => {
let limit : u32 = (number as f32).sqrt( ).floor( ) as u32 ;
(2..=limit).filter( | &d | number % d == 0 ).count( ) == 0
}
} ;
result
}
fn main() {
let numbers : Vec<u32> = vec![2 , 43 , 81 , 122 , 63 , 7 , 95 , 103] ;
let mut primes : Vec<u32> = numbers.into_iter( ).filter( | &d | is_prime( d ) ).
collect( ) ;
primes.sort( ) ;
println!("{:?}" , primes )
}
</syntaxhighlight>
{{out}}
<pre>
[2, 7, 43, 103]
</pre>
=={{header|Sidef}}==
<
say arr.grep{.is_prime}.sort</
{{out}}
<pre>
Line 503 ⟶ 774:
=={{header|Wren}}==
{{libheader|Wren-math}}
<
var lst = [2, 43, 81, 122, 63, 13, 7, 95, 103]
System.print(lst.where { |e| Int.isPrime(e) }.toList.sort())</
{{out}}
Line 514 ⟶ 785:
=={{header|XPL0}}==
<
int Primes, Smallest, I, SI;
def Len=9, Inf=1000;
Line 526 ⟶ 797:
[IntOut(0, Smallest); ChOut(0, ^ )];
until Smallest = Inf;
]</
{{out}}
|