task_url
stringlengths 30
116
| task_name
stringlengths 2
86
| task_description
stringlengths 0
14.4k
| language_url
stringlengths 2
53
| language_name
stringlengths 1
52
| code
stringlengths 0
61.9k
|
---|---|---|---|---|---|
http://rosettacode.org/wiki/FizzBuzz | FizzBuzz | Task
Write a program that prints the integers from 1 to 100 (inclusive).
But:
for multiples of three, print Fizz (instead of the number)
for multiples of five, print Buzz (instead of the number)
for multiples of both three and five, print FizzBuzz (instead of the number)
The FizzBuzz problem was presented as the lowest level of comprehension required to illustrate adequacy.
Also see
(a blog) dont-overthink-fizzbuzz
(a blog) fizzbuzz-the-programmers-stairway-to-heaven
| #Perl | Perl |
use strict;
use warnings;
use feature qw(say);
for my $i (1..100) {
say $i % 15 == 0 ? "FizzBuzz"
: $i % 3 == 0 ? "Fizz"
: $i % 5 == 0 ? "Buzz"
: $i;
} |
http://rosettacode.org/wiki/Exponentiation_with_infix_operators_in_(or_operating_on)_the_base | Exponentiation with infix operators in (or operating on) the base | (Many programming languages, especially those with extended─precision integer arithmetic, usually
support one of **, ^, ↑ or some such for exponentiation.)
Some languages treat/honor infix operators when performing exponentiation (raising
numbers to some power by the language's exponentiation operator, if the computer
programming language has one).
Other programming languages may make use of the POW or some other BIF
(Built─In Ffunction), or some other library service.
If your language's exponentiation operator is not one of the usual ones, please comment on how to recognize it.
This task will deal with the case where there is some form of an infix operator operating
in (or operating on) the base.
Example
A negative five raised to the 3rd power could be specified as:
-5 ** 3 or as
-(5) ** 3 or as
(-5) ** 3 or as something else
(Not all computer programming languages have an exponential operator and/or support these syntax expression(s).
Task
compute and display exponentiation with a possible infix operator, whether specified and/or implied/inferred.
Raise the following numbers (integer or real):
-5 and
+5
to the following powers:
2nd and
3rd
using the following expressions (if applicable in your language):
-x**p
-(x)**p
(-x)**p
-(x**p)
Show here (on this page) the four (or more) types of symbolic expressions for each number and power.
Try to present the results in the same format/manner as the other programming entries to make any differences apparent.
The variables may be of any type(s) that is/are applicable in your language.
Related tasks
Exponentiation order
Exponentiation operator
Arbitrary-precision integers (included)
Parsing/RPN to infix conversion
Operator precedence
References
Wikipedia: Order of operations in Programming languages
| #Haskell | Haskell | --https://wiki.haskell.org/Power_function
main = do
print [-5^2,-(5)^2,(-5)^2,-(5^2)] --Integer
print [-5^^2,-(5)^^2,(-5)^^2,-(5^^2)] --Fractional
print [-5**2,-(5)**2,(-5)**2,-(5**2)] --Real
print [-5^3,-(5)^3,(-5)^3,-(5^3)] --Integer
print [-5^^3,-(5)^^3,(-5)^^3,-(5^^3)] --Fractional
print [-5**3,-(5)**3,(-5)**3,-(5**3)] --Real |
http://rosettacode.org/wiki/Fibonacci_sequence | Fibonacci sequence | The Fibonacci sequence is a sequence Fn of natural numbers defined recursively:
F0 = 0
F1 = 1
Fn = Fn-1 + Fn-2, if n>1
Task
Write a function to generate the nth Fibonacci number.
Solutions can be iterative or recursive (though recursive solutions are generally considered too slow and are mostly used as an exercise in recursion).
The sequence is sometimes extended into negative numbers by using a straightforward inverse of the positive definition:
Fn = Fn+2 - Fn+1, if n<0
support for negative n in the solution is optional.
Related tasks
Fibonacci n-step number sequences
Leonardo numbers
References
Wikipedia, Fibonacci number
Wikipedia, Lucas number
MathWorld, Fibonacci Number
Some identities for r-Fibonacci numbers
OEIS Fibonacci numbers
OEIS Lucas numbers
| #FALSE | FALSE | [[$0=~][1-@@\$@@+\$44,.@]#]f:
20n: {First 20 numbers}
0 1 n;f;!%%44,. {Output: "0,1,1,2,3,5..."} |
http://rosettacode.org/wiki/Factors_of_an_integer | Factors of an integer |
Basic Data Operation
This is a basic data operation. It represents a fundamental action on a basic data type.
You may see other such operations in the Basic Data Operations category, or:
Integer Operations
Arithmetic |
Comparison
Boolean Operations
Bitwise |
Logical
String Operations
Concatenation |
Interpolation |
Comparison |
Matching
Memory Operations
Pointers & references |
Addresses
Task
Compute the factors of a positive integer.
These factors are the positive integers by which the number being factored can be divided to yield a positive integer result.
(Though the concepts function correctly for zero and negative integers, the set of factors of zero has countably infinite members, and the factors of negative integers can be obtained from the factors of related positive numbers without difficulty; this task does not require handling of either of these cases).
Note that every prime number has two factors: 1 and itself.
Related tasks
count in factors
prime decomposition
Sieve of Eratosthenes
primality by trial division
factors of a Mersenne number
trial factoring of a Mersenne number
partition an integer X into N primes
sequence of primes by Trial Division
sequence: smallest number greater than previous term with exactly n divisors
| #Oberon-2 | Oberon-2 |
MODULE Factors;
IMPORT Out,SYSTEM;
TYPE
LIPool = POINTER TO ARRAY OF LONGINT;
LIVector= POINTER TO LIVectorDesc;
LIVectorDesc = RECORD
cap: INTEGER;
len: INTEGER;
LIPool: LIPool;
END;
PROCEDURE New(cap: INTEGER): LIVector;
VAR
v: LIVector;
BEGIN
NEW(v);
v.cap := cap;
v.len := 0;
NEW(v.LIPool,cap);
RETURN v
END New;
PROCEDURE (v: LIVector) Add(x: LONGINT);
VAR
newLIPool: LIPool;
BEGIN
IF v.len = LEN(v.LIPool^) THEN
(* run out of space *)
v.cap := v.cap + (v.cap DIV 2);
NEW(newLIPool,v.cap);
SYSTEM.MOVE(SYSTEM.ADR(v.LIPool^),SYSTEM.ADR(newLIPool^),v.cap * SIZE(LONGINT));
v.LIPool := newLIPool
END;
v.LIPool[v.len] := x;
INC(v.len)
END Add;
PROCEDURE (v: LIVector) At(idx: INTEGER): LONGINT;
BEGIN
RETURN v.LIPool[idx];
END At;
PROCEDURE Factors(n:LONGINT): LIVector;
VAR
j: LONGINT;
v: LIVector;
BEGIN
v := New(16);
FOR j := 1 TO n DO
IF (n MOD j) = 0 THEN v.Add(j) END;
END;
RETURN v
END Factors;
VAR
v: LIVector;
j: INTEGER;
BEGIN
v := Factors(123);
FOR j := 0 TO v.len - 1 DO
Out.LongInt(v.At(j),4);Out.Ln
END;
Out.Int(v.len,6);Out.String(" factors");Out.Ln
END Factors.
|
http://rosettacode.org/wiki/Extreme_floating_point_values | Extreme floating point values | The IEEE floating point specification defines certain 'extreme' floating point values such as minus zero, -0.0, a value distinct from plus zero; not a number, NaN; and plus and minus infinity.
The task is to use expressions involving other 'normal' floating point values in your language to calculate these, (and maybe other), extreme floating point values in your language and assign them to variables.
Print the values of these variables if possible; and show some arithmetic with these values and variables.
If your language can directly enter these extreme floating point values then show it.
See also
What Every Computer Scientist Should Know About Floating-Point Arithmetic
Related tasks
Infinity
Detect division by zero
Literals/Floating point
| #AWK | AWK | BEGIN {
# This requires 1e400 to overflow to infinity.
nzero = -0
nan = 0 * 1e400
pinf = 1e400
ninf = -1e400
print "nzero =", nzero
print "nan =", nan
print "pinf =", pinf
print "ninf =", ninf
print
# When y == 0, sign of x decides if atan2(y, x) is 0 or pi.
print "atan2(0, 0) =", atan2(0, 0)
print "atan2(0, pinf) =", atan2(0, pinf)
print "atan2(0, nzero) =", atan2(0, nzero)
print "atan2(0, ninf) =", atan2(0, ninf)
print
# From least to most: ninf, -1e200, 1e200, pinf.
print "ninf * -1 =", ninf * -1
print "pinf * -1 =", pinf * -1
print "-1e200 > ninf?", (-1e200 > ninf) ? "yes" : "no"
print "1e200 < pinf?", (1e200 < pinf) ? "yes" : "no"
print
# NaN spreads from input to output.
print "nan test:", (1 + 2 * 3 - 4) / (-5.6e7 + nan)
# NaN never equals anything. These tests should print "no".
print "nan == nan?", (nan == nan) ? "yes" : "no"
print "nan == 42?", (nan == 42) ? "yes" : "no"
} |
http://rosettacode.org/wiki/Factorial_base_numbers_indexing_permutations_of_a_collection | Factorial base numbers indexing permutations of a collection | You need a random arrangement of a deck of cards, you are sick of lame ways of doing this. This task is a super-cool way of doing this using factorial base numbers.
The first 25 factorial base numbers in increasing order are: 0.0.0, 0.0.1, 0.1.0, 0.1.1, 0.2.0, 0.2.1, 1.0.0, 1.0.1, 1.1.0, 1.1.1,1.2.0, 1.2.1, 2.0.0, 2.0.1, 2.1.0, 2.1.1, 2.2.0, 2.2.1, 3.0.0, 3.0.1, 3.1.0, 3.1.1, 3.2.0, 3.2.1, 1.0.0.0
Observe that the least significant digit is base 2 the next base 3, in general an n-digit factorial base number has digits n..1 in base n+1..2.
I want to produce a 1 to 1 mapping between these numbers and permutations:-
0.0.0 -> 0123
0.0.1 -> 0132
0.1.0 -> 0213
0.1.1 -> 0231
0.2.0 -> 0312
0.2.1 -> 0321
1.0.0 -> 1023
1.0.1 -> 1032
1.1.0 -> 1203
1.1.1 -> 1230
1.2.0 -> 1302
1.2.1 -> 1320
2.0.0 -> 2013
2.0.1 -> 2031
2.1.0 -> 2103
2.1.1 -> 2130
2.2.0 -> 2301
2.2.1 -> 2310
3.0.0 -> 3012
3.0.1 -> 3021
3.1.0 -> 3102
3.1.1 -> 3120
3.2.0 -> 3201
3.2.1 -> 3210
The following psudo-code will do this:
Starting with m=0 and Ω, an array of elements to be permutated, for each digit g starting with the most significant digit in the factorial base number.
If g is greater than zero, rotate the elements from m to m+g in Ω (see example)
Increment m and repeat the first step using the next most significant digit until the factorial base number is exhausted.
For example: using the factorial base number 2.0.1 and Ω = 0 1 2 3 where place 0 in both is the most significant (left-most) digit/element.
Step 1: m=0 g=2; Rotate places 0 through 2. 0 1 2 3 becomes 2 0 1 3
Step 2: m=1 g=0; No action.
Step 3: m=2 g=1; Rotate places 2 through 3. 2 0 1 3 becomes 2 0 3 1
Let me work 2.0.1 and 0123
step 1 n=0 g=2 Ω=2013
step 2 n=1 g=0 so no action
step 3 n=2 g=1 Ω=2031
The task:
First use your function to recreate the above table.
Secondly use your function to generate all permutaions of 11 digits, perhaps count them don't display them, compare this method with
methods in rc's permutations task.
Thirdly here following are two ramdom 51 digit factorial base numbers I prepared earlier:
39.49.7.47.29.30.2.12.10.3.29.37.33.17.12.31.29.34.17.25.2.4.25.4.1.14.20.6.21.18.1.1.1.4.0.5.15.12.4.3.10.10.9.1.6.5.5.3.0.0.0
51.48.16.22.3.0.19.34.29.1.36.30.12.32.12.29.30.26.14.21.8.12.1.3.10.4.7.17.6.21.8.12.15.15.13.15.7.3.12.11.9.5.5.6.6.3.4.0.3.2.1
use your function to crate the corresponding permutation of the following shoe of cards:
A♠K♠Q♠J♠10♠9♠8♠7♠6♠5♠4♠3♠2♠A♥K♥Q♥J♥10♥9♥8♥7♥6♥5♥4♥3♥2♥A♦K♦Q♦J♦10♦9♦8♦7♦6♦5♦4♦3♦2♦A♣K♣Q♣J♣10♣9♣8♣7♣6♣5♣4♣3♣2♣
Finally create your own 51 digit factorial base number and produce the corresponding permutation of the above shoe
| #F.23 | F# |
// Factorial base numbers indexing permutations of a collection
// Nigel Galloway: December 7th., 2018
let lN2p (c:int[]) (Ω:'Ω[])=
let Ω=Array.copy Ω
let rec fN i g e l=match l-i with 0->Ω.[i]<-e |_->Ω.[l]<-Ω.[l-1]; fN i g e (l-1)// rotate right
[0..((Array.length Ω)-2)]|>List.iter(fun n->let i=c.[n] in if i>0 then fN n (i+n) Ω.[i+n] (i+n)); Ω
let lN n =
let Ω=(Array.length n)
let fN g=if n.[g]=Ω-g then n.[g]<-0; false else n.[g]<-n.[g]+1; true
seq{yield n; while [1..Ω]|>List.exists(fun g->fN (Ω-g)) do yield n}
|
http://rosettacode.org/wiki/Factorial_base_numbers_indexing_permutations_of_a_collection | Factorial base numbers indexing permutations of a collection | You need a random arrangement of a deck of cards, you are sick of lame ways of doing this. This task is a super-cool way of doing this using factorial base numbers.
The first 25 factorial base numbers in increasing order are: 0.0.0, 0.0.1, 0.1.0, 0.1.1, 0.2.0, 0.2.1, 1.0.0, 1.0.1, 1.1.0, 1.1.1,1.2.0, 1.2.1, 2.0.0, 2.0.1, 2.1.0, 2.1.1, 2.2.0, 2.2.1, 3.0.0, 3.0.1, 3.1.0, 3.1.1, 3.2.0, 3.2.1, 1.0.0.0
Observe that the least significant digit is base 2 the next base 3, in general an n-digit factorial base number has digits n..1 in base n+1..2.
I want to produce a 1 to 1 mapping between these numbers and permutations:-
0.0.0 -> 0123
0.0.1 -> 0132
0.1.0 -> 0213
0.1.1 -> 0231
0.2.0 -> 0312
0.2.1 -> 0321
1.0.0 -> 1023
1.0.1 -> 1032
1.1.0 -> 1203
1.1.1 -> 1230
1.2.0 -> 1302
1.2.1 -> 1320
2.0.0 -> 2013
2.0.1 -> 2031
2.1.0 -> 2103
2.1.1 -> 2130
2.2.0 -> 2301
2.2.1 -> 2310
3.0.0 -> 3012
3.0.1 -> 3021
3.1.0 -> 3102
3.1.1 -> 3120
3.2.0 -> 3201
3.2.1 -> 3210
The following psudo-code will do this:
Starting with m=0 and Ω, an array of elements to be permutated, for each digit g starting with the most significant digit in the factorial base number.
If g is greater than zero, rotate the elements from m to m+g in Ω (see example)
Increment m and repeat the first step using the next most significant digit until the factorial base number is exhausted.
For example: using the factorial base number 2.0.1 and Ω = 0 1 2 3 where place 0 in both is the most significant (left-most) digit/element.
Step 1: m=0 g=2; Rotate places 0 through 2. 0 1 2 3 becomes 2 0 1 3
Step 2: m=1 g=0; No action.
Step 3: m=2 g=1; Rotate places 2 through 3. 2 0 1 3 becomes 2 0 3 1
Let me work 2.0.1 and 0123
step 1 n=0 g=2 Ω=2013
step 2 n=1 g=0 so no action
step 3 n=2 g=1 Ω=2031
The task:
First use your function to recreate the above table.
Secondly use your function to generate all permutaions of 11 digits, perhaps count them don't display them, compare this method with
methods in rc's permutations task.
Thirdly here following are two ramdom 51 digit factorial base numbers I prepared earlier:
39.49.7.47.29.30.2.12.10.3.29.37.33.17.12.31.29.34.17.25.2.4.25.4.1.14.20.6.21.18.1.1.1.4.0.5.15.12.4.3.10.10.9.1.6.5.5.3.0.0.0
51.48.16.22.3.0.19.34.29.1.36.30.12.32.12.29.30.26.14.21.8.12.1.3.10.4.7.17.6.21.8.12.15.15.13.15.7.3.12.11.9.5.5.6.6.3.4.0.3.2.1
use your function to crate the corresponding permutation of the following shoe of cards:
A♠K♠Q♠J♠10♠9♠8♠7♠6♠5♠4♠3♠2♠A♥K♥Q♥J♥10♥9♥8♥7♥6♥5♥4♥3♥2♥A♦K♦Q♦J♦10♦9♦8♦7♦6♦5♦4♦3♦2♦A♣K♣Q♣J♣10♣9♣8♣7♣6♣5♣4♣3♣2♣
Finally create your own 51 digit factorial base number and produce the corresponding permutation of the above shoe
| #Factor | Factor | USING: assocs io kernel literals math math.factorials
math.parser math.ranges prettyprint qw random sequences
splitting ;
RENAME: factoradic math.combinatorics.private => _factoradic
RENAME: rotate sequences.extras => _rotate
IN: rosetta-code.factorial-permutations
CONSTANT: shoe $[
qw{ A K Q J 10 9 8 7 6 5 4 3 2 } qw{ ♠ ♥ ♦ ♣ }
[ append ] cartesian-map flip concat
]
! Factor can already make factoradic numbers, but they always
! have a least-significant digit of 0 to remove.
: factoradic ( n -- seq )
_factoradic dup [ drop but-last ] unless-empty ;
! Convert "3.1.2.0" to { 3 1 2 0 }, for example.
: string>factoradic ( str -- seq )
"." split [ string>number ] map ;
! Rotate a subsequence.
! E.g. 0 2 { 3 1 2 0 } (rotate) -> { 2 3 1 0 }.
: (rotate) ( from to seq -- newseq )
[ 1 + ] dip [ snip ] [ subseq ] 3bi -1 _rotate glue ;
! Only rotate a subsequence if from does not equal to.
: rotate ( from to seq -- newseq )
2over = [ 2nip ] [ (rotate) ] if ;
! The pseudocode from the task description
: fpermute ( factoradic -- permutation )
dup length 1 + <iota> swap <enumerated>
[ over + rot rotate ] assoc-each ;
! Use a factoradic number to index permutations of a collection.
: findex ( factoradic seq -- permutation )
[ fpermute ] [ nths concat ] bi* ;
: .f ( seq -- ) [ "." write ] [ pprint ] interleave ; ! Print a factoradic number
: .p ( seq -- ) [ pprint ] each nl ; ! Print a permutation
: show-table ( -- )
"Generate table" print 24
[ factoradic 3 0 pad-head dup .f fpermute " -> " write .p ]
each-integer nl ;
: show-shuffles ( -- )
"Generate given task shuffles" print
"Original deck:" print shoe concat print nl
"39.49.7.47.29.30.2.12.10.3.29.37.33.17.12.31.29.34.17.25.2.4.25.4.1.14.20.6.21.18.1.1.1.4.0.5.15.12.4.3.10.10.9.1.6.5.5.3.0.0.0"
"51.48.16.22.3.0.19.34.29.1.36.30.12.32.12.29.30.26.14.21.8.12.1.3.10.4.7.17.6.21.8.12.15.15.13.15.7.3.12.11.9.5.5.6.6.3.4.0.3.2.1"
[ [ print ] [ string>factoradic shoe findex print nl ] bi ] bi@ ;
: show-random-shuffle ( -- )
"Random shuffle:" print
51 52 [ n! ] bi@ [a,b] random factoradic shoe findex print ;
: main ( -- ) show-table show-shuffles show-random-shuffle ;
MAIN: main |
http://rosettacode.org/wiki/Factorions | Factorions |
Definition
A factorion is a natural number that equals the sum of the factorials of its digits.
Example
145 is a factorion in base 10 because:
1! + 4! + 5! = 1 + 24 + 120 = 145
It can be shown (see talk page) that no factorion in base 10 can exceed 1,499,999.
Task
Write a program in your language to demonstrate, by calculating and printing out the factorions, that:
There are 3 factorions in base 9
There are 4 factorions in base 10
There are 5 factorions in base 11
There are 2 factorions in base 12 (up to the same upper bound as for base 10)
See also
Wikipedia article
OEIS:A014080 - Factorions in base 10
OEIS:A193163 - Factorions in base n
| #360_Assembly | 360 Assembly | * Factorions 26/04/2020
FACTORIO CSECT
USING FACTORIO,R13 base register
B 72(R15) skip savearea
DC 17F'0' savearea
SAVE (14,12) save previous context
ST R13,4(R15) link backward
ST R15,8(R13) link forward
LR R13,R15 set addressability
XR R4,R4 ~
LA R5,1 f=1
LA R3,FACT+4 @fact(1)
LA R6,1 i=1
DO WHILE=(C,R6,LE,=A(NN2)) do i=1 to nn2
MR R4,R6 fact(i-1)*i
ST R5,0(R3) fact(i)=fact(i-1)*i
LA R3,4(R3) @fact(i+1)
LA R6,1(R6) i++
ENDDO , enddo i
LA R7,NN1 base=nn1
DO WHILE=(C,R7,LE,=A(NN2)) do base=nn1 to nn2
MVC PG,PGX init buffer
LA R3,PG+6 @buffer
XDECO R7,XDEC edit base
MVC PG+5(2),XDEC+10 output base
LA R3,PG+10 @buffer
LA R6,1 i=1
DO WHILE=(C,R6,LE,LIM) do i=1 to lim
LA R9,0 s=0
LR R8,R6 t=i
DO WHILE=(C,R8,NE,=F'0') while t<>0
XR R4,R4 ~
LR R5,R8 t
DR R4,R7 r5=t/base; r4=d=(t mod base)
LR R1,R4 d
SLA R1,2 ~
L R2,FACT(R1) fact(d)
AR R9,R2 s=s+fact(d)
LR R8,R5 t=t/base
ENDDO , endwhile
IF CR,R9,EQ,R6 THEN if s=i then
XDECO R6,XDEC edit i
MVC 0(6,R3),XDEC+6 output i
LA R3,7(R3) @buffer
ENDIF , endif
LA R6,1(R6) i++
ENDDO , enddo i
XPRNT PG,L'PG print buffer
LA R7,1(R7) base++
ENDDO , enddo base
L R13,4(0,R13) restore previous savearea pointer
RETURN (14,12),RC=0 restore registers from calling save
NN1 EQU 9 nn1=9
NN2 EQU 12 nn2=12
LIM DC f'1499999' lim=1499999
FACT DC (NN2+1)F'1' fact(0:12)
PG DS CL80 buffer
PGX DC CL80'Base .. : ' buffer init
XDEC DS CL12 temp fo xdeco
REGEQU
END FACTORIO |
http://rosettacode.org/wiki/Factorions | Factorions |
Definition
A factorion is a natural number that equals the sum of the factorials of its digits.
Example
145 is a factorion in base 10 because:
1! + 4! + 5! = 1 + 24 + 120 = 145
It can be shown (see talk page) that no factorion in base 10 can exceed 1,499,999.
Task
Write a program in your language to demonstrate, by calculating and printing out the factorions, that:
There are 3 factorions in base 9
There are 4 factorions in base 10
There are 5 factorions in base 11
There are 2 factorions in base 12 (up to the same upper bound as for base 10)
See also
Wikipedia article
OEIS:A014080 - Factorions in base 10
OEIS:A193163 - Factorions in base n
| #ALGOL_68 | ALGOL 68 | BEGIN
# cache factorials from 0 to 11 #
[ 0 : 11 ]INT fact;
fact[0] := 1;
FOR n TO 11 DO
fact[n] := fact[n-1] * n
OD;
FOR b FROM 9 TO 12 DO
print( ( "The factorions for base ", whole( b, 0 ), " are:", newline ) );
FOR i TO 1500000 - 1 DO
INT sum := 0;
INT j := i;
WHILE j > 0 DO
sum +:= fact[ j MOD b ];
j OVERAB b
OD;
IF sum = i THEN print( ( whole( i, 0 ), " " ) ) FI
OD;
print( ( newline ) )
OD
END |
http://rosettacode.org/wiki/Filter | Filter | Task
Select certain elements from an Array into a new Array in a generic way.
To demonstrate, select all even numbers from an Array.
As an option, give a second solution which filters destructively,
by modifying the original Array rather than creating a new Array.
| #Seed7 | Seed7 | var array integer: arr is [] (1, 2, 3, 4, 5);
var array integer: evens is 0 times 0;
var integer: number is 0;
for number range arr do
if not odd(number) then
evens &:= [] (number);
end if;
end for; |
http://rosettacode.org/wiki/Faces_from_a_mesh | Faces from a mesh | A mesh defining a surface has uniquely numbered vertices, and named,
simple-polygonal faces described usually by an ordered list of edge numbers
going around the face,
For example:
External image of two faces
Rough textual version without edges:
1
17
7 A
B
11
23
A is the triangle (1, 11, 7), or equally (7, 11, 1), going anti-clockwise, or
any of all the rotations of those ordered vertices.
1
7 A
11
B is the four-sided face (1, 17, 23, 11), or equally (23, 17, 1, 11) or any
of their rotations.
1
17
B
11
23
Let's call the above the perimeter format as it traces around the perimeter.
A second format
A separate algorithm returns polygonal faces consisting of a face name and an unordered
set of edge definitions for each face.
A single edge is described by the vertex numbers at its two ends, always in
ascending order.
All edges for the face are given, but in an undefined order.
For example face A could be described by the edges (1, 11), (7, 11), and (1, 7)
(The order of each vertex number in an edge is ascending, but the order in
which the edges are stated is arbitrary).
Similarly face B could be described by the edges (11, 23), (1, 17), (17, 23),
and (1, 11) in arbitrary order of the edges.
Let's call this second format the edge format.
Task
1. Write a routine to check if two perimeter formatted faces have the same perimeter. Use it to check if the following pairs of perimeters are the same:
Q: (8, 1, 3)
R: (1, 3, 8)
U: (18, 8, 14, 10, 12, 17, 19)
V: (8, 14, 10, 12, 17, 19, 18)
2. Write a routine and use it to transform the following faces from edge to perimeter format.
E: {(1, 11), (7, 11), (1, 7)}
F: {(11, 23), (1, 17), (17, 23), (1, 11)}
G: {(8, 14), (17, 19), (10, 12), (10, 14), (12, 17), (8, 18), (18, 19)}
H: {(1, 3), (9, 11), (3, 11), (1, 11)}
Show your output here.
| #Python | Python | def perim_equal(p1, p2):
# Cheap tests first
if len(p1) != len(p2) or set(p1) != set(p2):
return False
if any(p2 == (p1[n:] + p1[:n]) for n in range(len(p1))):
return True
p2 = p2[::-1] # not inplace
return any(p2 == (p1[n:] + p1[:n]) for n in range(len(p1)))
def edge_to_periphery(e):
edges = sorted(e)
p = list(edges.pop(0)) if edges else []
last = p[-1] if p else None
while edges:
for n, (i, j) in enumerate(edges):
if i == last:
p.append(j)
last = j
edges.pop(n)
break
elif j == last:
p.append(i)
last = i
edges.pop(n)
break
else:
#raise ValueError(f'Invalid edge format: {e}')
return ">>>Error! Invalid edge format<<<"
return p[:-1]
if __name__ == '__main__':
print('Perimeter format equality checks:')
for eq_check in [
{ 'Q': (8, 1, 3),
'R': (1, 3, 8)},
{ 'U': (18, 8, 14, 10, 12, 17, 19),
'V': (8, 14, 10, 12, 17, 19, 18)} ]:
(n1, p1), (n2, p2) = eq_check.items()
eq = '==' if perim_equal(p1, p2) else '!='
print(' ', n1, eq, n2)
print('\nEdge to perimeter format translations:')
edge_d = {
'E': {(1, 11), (7, 11), (1, 7)},
'F': {(11, 23), (1, 17), (17, 23), (1, 11)},
'G': {(8, 14), (17, 19), (10, 12), (10, 14), (12, 17), (8, 18), (18, 19)},
'H': {(1, 3), (9, 11), (3, 11), (1, 11)}
}
for name, edges in edge_d.items():
print(f" {name}: {edges}\n -> {edge_to_periphery(edges)}") |
http://rosettacode.org/wiki/FizzBuzz | FizzBuzz | Task
Write a program that prints the integers from 1 to 100 (inclusive).
But:
for multiples of three, print Fizz (instead of the number)
for multiples of five, print Buzz (instead of the number)
for multiples of both three and five, print FizzBuzz (instead of the number)
The FizzBuzz problem was presented as the lowest level of comprehension required to illustrate adequacy.
Also see
(a blog) dont-overthink-fizzbuzz
(a blog) fizzbuzz-the-programmers-stairway-to-heaven
| #Phix | Phix | constant x = {"%d\n","Fizz\n","Buzz\n","FizzBuzz\n"}
for i=1 to 100 do
printf(1,x[1+(remainder(i,3)=0)+2*(remainder(i,5)=0)],i)
end for
|
http://rosettacode.org/wiki/Exponentiation_with_infix_operators_in_(or_operating_on)_the_base | Exponentiation with infix operators in (or operating on) the base | (Many programming languages, especially those with extended─precision integer arithmetic, usually
support one of **, ^, ↑ or some such for exponentiation.)
Some languages treat/honor infix operators when performing exponentiation (raising
numbers to some power by the language's exponentiation operator, if the computer
programming language has one).
Other programming languages may make use of the POW or some other BIF
(Built─In Ffunction), or some other library service.
If your language's exponentiation operator is not one of the usual ones, please comment on how to recognize it.
This task will deal with the case where there is some form of an infix operator operating
in (or operating on) the base.
Example
A negative five raised to the 3rd power could be specified as:
-5 ** 3 or as
-(5) ** 3 or as
(-5) ** 3 or as something else
(Not all computer programming languages have an exponential operator and/or support these syntax expression(s).
Task
compute and display exponentiation with a possible infix operator, whether specified and/or implied/inferred.
Raise the following numbers (integer or real):
-5 and
+5
to the following powers:
2nd and
3rd
using the following expressions (if applicable in your language):
-x**p
-(x)**p
(-x)**p
-(x**p)
Show here (on this page) the four (or more) types of symbolic expressions for each number and power.
Try to present the results in the same format/manner as the other programming entries to make any differences apparent.
The variables may be of any type(s) that is/are applicable in your language.
Related tasks
Exponentiation order
Exponentiation operator
Arbitrary-precision integers (included)
Parsing/RPN to infix conversion
Operator precedence
References
Wikipedia: Order of operations in Programming languages
| #J | J | format=: ''&$: :([: ; (a: , [: ":&.> [) ,. '{}' ([ (E. <@}.;._1 ]) ,) ])
S=: 'x = {} p = {} -x^p {} -(x)^p {} (-x)^p {} -(x^p) {}'
explicit=: dyad def 'S format~ 2 2 4 4 4 4 ":&> x,y,(-x^y),(-(x)^y),((-x)^y),(-(x^y))'
tacit=: S format~ 2 2 4 4 4 4 ":&> [`]`([:-^)`([:-^)`((^~-)~)`([:-^)`:0
_2 explicit/\_5 2 _5 3 5 2 5 3
x = _5 p = 2 -x^p _25 -(x)^p _25 (-x)^p 25 -(x^p) _25
x = _5 p = 3 -x^p 125 -(x)^p 125 (-x)^p 125 -(x^p) 125
x = 5 p = 2 -x^p _25 -(x)^p _25 (-x)^p 25 -(x^p) _25
x = 5 p = 3 -x^p _125 -(x)^p _125 (-x)^p _125 -(x^p) _125
-:/ 1 0 2 |: _2(tacit ,: explicit)/\_5 2 _5 3 5 2 5 3 NB. the verbs produce matching results
1
|
http://rosettacode.org/wiki/Exponentiation_with_infix_operators_in_(or_operating_on)_the_base | Exponentiation with infix operators in (or operating on) the base | (Many programming languages, especially those with extended─precision integer arithmetic, usually
support one of **, ^, ↑ or some such for exponentiation.)
Some languages treat/honor infix operators when performing exponentiation (raising
numbers to some power by the language's exponentiation operator, if the computer
programming language has one).
Other programming languages may make use of the POW or some other BIF
(Built─In Ffunction), or some other library service.
If your language's exponentiation operator is not one of the usual ones, please comment on how to recognize it.
This task will deal with the case where there is some form of an infix operator operating
in (or operating on) the base.
Example
A negative five raised to the 3rd power could be specified as:
-5 ** 3 or as
-(5) ** 3 or as
(-5) ** 3 or as something else
(Not all computer programming languages have an exponential operator and/or support these syntax expression(s).
Task
compute and display exponentiation with a possible infix operator, whether specified and/or implied/inferred.
Raise the following numbers (integer or real):
-5 and
+5
to the following powers:
2nd and
3rd
using the following expressions (if applicable in your language):
-x**p
-(x)**p
(-x)**p
-(x**p)
Show here (on this page) the four (or more) types of symbolic expressions for each number and power.
Try to present the results in the same format/manner as the other programming entries to make any differences apparent.
The variables may be of any type(s) that is/are applicable in your language.
Related tasks
Exponentiation order
Exponentiation operator
Arbitrary-precision integers (included)
Parsing/RPN to infix conversion
Operator precedence
References
Wikipedia: Order of operations in Programming languages
| #Julia | Julia |
for x in [-5, 5], p in [2, 3]
println("x is", lpad(x, 3), ", p is $p, -x^p is", lpad(-x^p, 4), ", -(x)^p is",
lpad(-(x)^p, 5), ", (-x)^p is", lpad((-x)^p, 5), ", -(x^p) is", lpad(-(x^p), 5))
end
|
http://rosettacode.org/wiki/Exponentiation_with_infix_operators_in_(or_operating_on)_the_base | Exponentiation with infix operators in (or operating on) the base | (Many programming languages, especially those with extended─precision integer arithmetic, usually
support one of **, ^, ↑ or some such for exponentiation.)
Some languages treat/honor infix operators when performing exponentiation (raising
numbers to some power by the language's exponentiation operator, if the computer
programming language has one).
Other programming languages may make use of the POW or some other BIF
(Built─In Ffunction), or some other library service.
If your language's exponentiation operator is not one of the usual ones, please comment on how to recognize it.
This task will deal with the case where there is some form of an infix operator operating
in (or operating on) the base.
Example
A negative five raised to the 3rd power could be specified as:
-5 ** 3 or as
-(5) ** 3 or as
(-5) ** 3 or as something else
(Not all computer programming languages have an exponential operator and/or support these syntax expression(s).
Task
compute and display exponentiation with a possible infix operator, whether specified and/or implied/inferred.
Raise the following numbers (integer or real):
-5 and
+5
to the following powers:
2nd and
3rd
using the following expressions (if applicable in your language):
-x**p
-(x)**p
(-x)**p
-(x**p)
Show here (on this page) the four (or more) types of symbolic expressions for each number and power.
Try to present the results in the same format/manner as the other programming entries to make any differences apparent.
The variables may be of any type(s) that is/are applicable in your language.
Related tasks
Exponentiation order
Exponentiation operator
Arbitrary-precision integers (included)
Parsing/RPN to infix conversion
Operator precedence
References
Wikipedia: Order of operations in Programming languages
| #Lua | Lua | mathtype = math.type or type -- polyfill <5.3
function test(xs, ps)
for _,x in ipairs(xs) do
for _,p in ipairs(ps) do
print(string.format("%2.f %7s %2.f %7s %4.f %4.f %4.f %4.f", x, mathtype(x), p, mathtype(p), -x^p, -(x)^p, (-x)^p, -(x^p)))
end
end
end
print(" x type(x) p type(p) -x^p -(x)^p (-x)^p -(x^p)")
print("-- ------- -- ------- ------ ------ ------ ------")
test( {-5.,5.}, {2.,3.} ) -- "float" (or "number" if <5.3)
if math.type then -- if >=5.3
test( {-5,5}, {2,3} ) -- "integer"
end |
http://rosettacode.org/wiki/Fibonacci_sequence | Fibonacci sequence | The Fibonacci sequence is a sequence Fn of natural numbers defined recursively:
F0 = 0
F1 = 1
Fn = Fn-1 + Fn-2, if n>1
Task
Write a function to generate the nth Fibonacci number.
Solutions can be iterative or recursive (though recursive solutions are generally considered too slow and are mostly used as an exercise in recursion).
The sequence is sometimes extended into negative numbers by using a straightforward inverse of the positive definition:
Fn = Fn+2 - Fn+1, if n<0
support for negative n in the solution is optional.
Related tasks
Fibonacci n-step number sequences
Leonardo numbers
References
Wikipedia, Fibonacci number
Wikipedia, Lucas number
MathWorld, Fibonacci Number
Some identities for r-Fibonacci numbers
OEIS Fibonacci numbers
OEIS Lucas numbers
| #Fancy | Fancy | class Fixnum {
def fib {
match self -> {
case 0 -> 0
case 1 -> 1
case _ -> self - 1 fib + (self - 2 fib)
}
}
}
15 times: |x| {
x fib println
}
|
http://rosettacode.org/wiki/Factors_of_an_integer | Factors of an integer |
Basic Data Operation
This is a basic data operation. It represents a fundamental action on a basic data type.
You may see other such operations in the Basic Data Operations category, or:
Integer Operations
Arithmetic |
Comparison
Boolean Operations
Bitwise |
Logical
String Operations
Concatenation |
Interpolation |
Comparison |
Matching
Memory Operations
Pointers & references |
Addresses
Task
Compute the factors of a positive integer.
These factors are the positive integers by which the number being factored can be divided to yield a positive integer result.
(Though the concepts function correctly for zero and negative integers, the set of factors of zero has countably infinite members, and the factors of negative integers can be obtained from the factors of related positive numbers without difficulty; this task does not require handling of either of these cases).
Note that every prime number has two factors: 1 and itself.
Related tasks
count in factors
prime decomposition
Sieve of Eratosthenes
primality by trial division
factors of a Mersenne number
trial factoring of a Mersenne number
partition an integer X into N primes
sequence of primes by Trial Division
sequence: smallest number greater than previous term with exactly n divisors
| #Objeck | Objeck | use IO;
use Structure;
bundle Default {
class Basic {
function : native : GenerateFactors(n : Int) ~ IntVector {
factors := IntVector->New();
factors-> AddBack(1);
factors->AddBack(n);
for(i := 2; i * i <= n; i += 1;) {
if(n % i = 0) {
factors->AddBack(i);
if(i * i <> n) {
factors->AddBack(n / i);
};
};
};
factors->Sort();
return factors;
}
function : Main(args : String[]) ~ Nil {
numbers := [3135, 45, 60, 81];
for(i := 0; i < numbers->Size(); i += 1;) {
factors := GenerateFactors(numbers[i]);
Console->GetInstance()->Print("Factors of ")->Print(numbers[i])->PrintLine(" are:");
each(i : factors) {
Console->GetInstance()->Print(factors->Get(i))->Print(", ");
};
"\n\n"->Print();
};
}
}
} |
http://rosettacode.org/wiki/Extreme_floating_point_values | Extreme floating point values | The IEEE floating point specification defines certain 'extreme' floating point values such as minus zero, -0.0, a value distinct from plus zero; not a number, NaN; and plus and minus infinity.
The task is to use expressions involving other 'normal' floating point values in your language to calculate these, (and maybe other), extreme floating point values in your language and assign them to variables.
Print the values of these variables if possible; and show some arithmetic with these values and variables.
If your language can directly enter these extreme floating point values then show it.
See also
What Every Computer Scientist Should Know About Floating-Point Arithmetic
Related tasks
Infinity
Detect division by zero
Literals/Floating point
| #bc | bc | $ bc
# trying for negative zero
-0
0
# trying to underflow to negative zero
-1 / 2
0
# trying for NaN (not a number)
0 / 0
dc: divide by zero
0
sqrt(-1)
dc: square root of negative number
dc: stack empty
dc: stack empty
|
http://rosettacode.org/wiki/Extreme_floating_point_values | Extreme floating point values | The IEEE floating point specification defines certain 'extreme' floating point values such as minus zero, -0.0, a value distinct from plus zero; not a number, NaN; and plus and minus infinity.
The task is to use expressions involving other 'normal' floating point values in your language to calculate these, (and maybe other), extreme floating point values in your language and assign them to variables.
Print the values of these variables if possible; and show some arithmetic with these values and variables.
If your language can directly enter these extreme floating point values then show it.
See also
What Every Computer Scientist Should Know About Floating-Point Arithmetic
Related tasks
Infinity
Detect division by zero
Literals/Floating point
| #C | C | #include <stdio.h>
int main()
{
double inf = 1/0.0;
double minus_inf = -1/0.0;
double minus_zero = -1/ inf ;
double nan = 0.0/0.0;
printf("positive infinity: %f\n",inf);
printf("negative infinity: %f\n",minus_inf);
printf("negative zero: %f\n",minus_zero);
printf("not a number: %f\n",nan);
/* some arithmetic */
printf("+inf + 2.0 = %f\n",inf + 2.0);
printf("+inf - 10.1 = %f\n",inf - 10.1);
printf("+inf + -inf = %f\n",inf + minus_inf);
printf("0.0 * +inf = %f\n",0.0 * inf);
printf("1.0/-0.0 = %f\n",1.0/minus_zero);
printf("NaN + 1.0 = %f\n",nan + 1.0);
printf("NaN + NaN = %f\n",nan + nan);
/* some comparisons */
printf("NaN == NaN = %s\n",nan == nan ? "true" : "false");
printf("0.0 == -0.0 = %s\n",0.0 == minus_zero ? "true" : "false");
return 0;
} |
http://rosettacode.org/wiki/Factorial_base_numbers_indexing_permutations_of_a_collection | Factorial base numbers indexing permutations of a collection | You need a random arrangement of a deck of cards, you are sick of lame ways of doing this. This task is a super-cool way of doing this using factorial base numbers.
The first 25 factorial base numbers in increasing order are: 0.0.0, 0.0.1, 0.1.0, 0.1.1, 0.2.0, 0.2.1, 1.0.0, 1.0.1, 1.1.0, 1.1.1,1.2.0, 1.2.1, 2.0.0, 2.0.1, 2.1.0, 2.1.1, 2.2.0, 2.2.1, 3.0.0, 3.0.1, 3.1.0, 3.1.1, 3.2.0, 3.2.1, 1.0.0.0
Observe that the least significant digit is base 2 the next base 3, in general an n-digit factorial base number has digits n..1 in base n+1..2.
I want to produce a 1 to 1 mapping between these numbers and permutations:-
0.0.0 -> 0123
0.0.1 -> 0132
0.1.0 -> 0213
0.1.1 -> 0231
0.2.0 -> 0312
0.2.1 -> 0321
1.0.0 -> 1023
1.0.1 -> 1032
1.1.0 -> 1203
1.1.1 -> 1230
1.2.0 -> 1302
1.2.1 -> 1320
2.0.0 -> 2013
2.0.1 -> 2031
2.1.0 -> 2103
2.1.1 -> 2130
2.2.0 -> 2301
2.2.1 -> 2310
3.0.0 -> 3012
3.0.1 -> 3021
3.1.0 -> 3102
3.1.1 -> 3120
3.2.0 -> 3201
3.2.1 -> 3210
The following psudo-code will do this:
Starting with m=0 and Ω, an array of elements to be permutated, for each digit g starting with the most significant digit in the factorial base number.
If g is greater than zero, rotate the elements from m to m+g in Ω (see example)
Increment m and repeat the first step using the next most significant digit until the factorial base number is exhausted.
For example: using the factorial base number 2.0.1 and Ω = 0 1 2 3 where place 0 in both is the most significant (left-most) digit/element.
Step 1: m=0 g=2; Rotate places 0 through 2. 0 1 2 3 becomes 2 0 1 3
Step 2: m=1 g=0; No action.
Step 3: m=2 g=1; Rotate places 2 through 3. 2 0 1 3 becomes 2 0 3 1
Let me work 2.0.1 and 0123
step 1 n=0 g=2 Ω=2013
step 2 n=1 g=0 so no action
step 3 n=2 g=1 Ω=2031
The task:
First use your function to recreate the above table.
Secondly use your function to generate all permutaions of 11 digits, perhaps count them don't display them, compare this method with
methods in rc's permutations task.
Thirdly here following are two ramdom 51 digit factorial base numbers I prepared earlier:
39.49.7.47.29.30.2.12.10.3.29.37.33.17.12.31.29.34.17.25.2.4.25.4.1.14.20.6.21.18.1.1.1.4.0.5.15.12.4.3.10.10.9.1.6.5.5.3.0.0.0
51.48.16.22.3.0.19.34.29.1.36.30.12.32.12.29.30.26.14.21.8.12.1.3.10.4.7.17.6.21.8.12.15.15.13.15.7.3.12.11.9.5.5.6.6.3.4.0.3.2.1
use your function to crate the corresponding permutation of the following shoe of cards:
A♠K♠Q♠J♠10♠9♠8♠7♠6♠5♠4♠3♠2♠A♥K♥Q♥J♥10♥9♥8♥7♥6♥5♥4♥3♥2♥A♦K♦Q♦J♦10♦9♦8♦7♦6♦5♦4♦3♦2♦A♣K♣Q♣J♣10♣9♣8♣7♣6♣5♣4♣3♣2♣
Finally create your own 51 digit factorial base number and produce the corresponding permutation of the above shoe
| #Go | Go | package main
import (
"fmt"
"math/rand"
"strconv"
"strings"
"time"
)
func factorial(n int) int {
fact := 1
for i := 2; i <= n; i++ {
fact *= i
}
return fact
}
func genFactBaseNums(size int, countOnly bool) ([][]int, int) {
var results [][]int
count := 0
for n := 0; ; n++ {
radix := 2
var res []int = nil
if !countOnly {
res = make([]int, size)
}
k := n
for k > 0 {
div := k / radix
rem := k % radix
if !countOnly {
if radix <= size+1 {
res[size-radix+1] = rem
}
}
k = div
radix++
}
if radix > size+2 {
break
}
count++
if !countOnly {
results = append(results, res)
}
}
return results, count
}
func mapToPerms(factNums [][]int) [][]int {
var perms [][]int
psize := len(factNums[0]) + 1
start := make([]int, psize)
for i := 0; i < psize; i++ {
start[i] = i
}
for _, fn := range factNums {
perm := make([]int, psize)
copy(perm, start)
for m := 0; m < len(fn); m++ {
g := fn[m]
if g == 0 {
continue
}
first := m
last := m + g
for i := 1; i <= g; i++ {
temp := perm[first]
for j := first + 1; j <= last; j++ {
perm[j-1] = perm[j]
}
perm[last] = temp
}
}
perms = append(perms, perm)
}
return perms
}
func join(is []int, sep string) string {
ss := make([]string, len(is))
for i := 0; i < len(is); i++ {
ss[i] = strconv.Itoa(is[i])
}
return strings.Join(ss, sep)
}
func undot(s string) []int {
ss := strings.Split(s, ".")
is := make([]int, len(ss))
for i := 0; i < len(ss); i++ {
is[i], _ = strconv.Atoi(ss[i])
}
return is
}
func main() {
rand.Seed(time.Now().UnixNano())
// Recreate the table.
factNums, _ := genFactBaseNums(3, false)
perms := mapToPerms(factNums)
for i, fn := range factNums {
fmt.Printf("%v -> %v\n", join(fn, "."), join(perms[i], ""))
}
// Check that the number of perms generated is equal to 11! (this takes a while).
_, count := genFactBaseNums(10, true)
fmt.Println("\nPermutations generated =", count)
fmt.Println("compared to 11! which =", factorial(11))
fmt.Println()
// Generate shuffles for the 2 given 51 digit factorial base numbers.
fbn51s := []string{
"39.49.7.47.29.30.2.12.10.3.29.37.33.17.12.31.29.34.17.25.2.4.25.4.1.14.20.6.21.18.1.1.1.4.0.5.15.12.4.3.10.10.9.1.6.5.5.3.0.0.0",
"51.48.16.22.3.0.19.34.29.1.36.30.12.32.12.29.30.26.14.21.8.12.1.3.10.4.7.17.6.21.8.12.15.15.13.15.7.3.12.11.9.5.5.6.6.3.4.0.3.2.1",
}
factNums = [][]int{undot(fbn51s[0]), undot(fbn51s[1])}
perms = mapToPerms(factNums)
shoe := []rune("A♠K♠Q♠J♠T♠9♠8♠7♠6♠5♠4♠3♠2♠A♥K♥Q♥J♥T♥9♥8♥7♥6♥5♥4♥3♥2♥A♦K♦Q♦J♦T♦9♦8♦7♦6♦5♦4♦3♦2♦A♣K♣Q♣J♣T♣9♣8♣7♣6♣5♣4♣3♣2♣")
cards := make([]string, 52)
for i := 0; i < 52; i++ {
cards[i] = string(shoe[2*i : 2*i+2])
if cards[i][0] == 'T' {
cards[i] = "10" + cards[i][1:]
}
}
for i, fbn51 := range fbn51s {
fmt.Println(fbn51)
for _, d := range perms[i] {
fmt.Print(cards[d])
}
fmt.Println("\n")
}
// Create a random 51 digit factorial base number and produce a shuffle from that.
fbn51 := make([]int, 51)
for i := 0; i < 51; i++ {
fbn51[i] = rand.Intn(52 - i)
}
fmt.Println(join(fbn51, "."))
perms = mapToPerms([][]int{fbn51})
for _, d := range perms[0] {
fmt.Print(cards[d])
}
fmt.Println()
} |
http://rosettacode.org/wiki/Factorions | Factorions |
Definition
A factorion is a natural number that equals the sum of the factorials of its digits.
Example
145 is a factorion in base 10 because:
1! + 4! + 5! = 1 + 24 + 120 = 145
It can be shown (see talk page) that no factorion in base 10 can exceed 1,499,999.
Task
Write a program in your language to demonstrate, by calculating and printing out the factorions, that:
There are 3 factorions in base 9
There are 4 factorions in base 10
There are 5 factorions in base 11
There are 2 factorions in base 12 (up to the same upper bound as for base 10)
See also
Wikipedia article
OEIS:A014080 - Factorions in base 10
OEIS:A193163 - Factorions in base n
| #Applesoft_BASIC | Applesoft BASIC | 100 DIM FACT(12)
110 FACT(0) = 1
120 FOR N = 1 TO 11
130 FACT(N) = FACT(N - 1) * N
140 NEXT
200 FOR B = 9 TO 12
210 PRINT "THE FACTORIONS ";
215 PRINT "FOR BASE "B" ARE:"
220 FOR I = 1 TO 1499999
230 SUM = 0
240 FOR J = I TO 0 STEP 0
245 M = INT (J / B)
250 D = J - M * B
260 SUM = SUM + FACT(D)
270 J = M
280 NEXT J
290 IF SU = I THEN PRINT I" ";
300 NEXT I
310 PRINT : PRINT
320 NEXT B |
http://rosettacode.org/wiki/Factorions | Factorions |
Definition
A factorion is a natural number that equals the sum of the factorials of its digits.
Example
145 is a factorion in base 10 because:
1! + 4! + 5! = 1 + 24 + 120 = 145
It can be shown (see talk page) that no factorion in base 10 can exceed 1,499,999.
Task
Write a program in your language to demonstrate, by calculating and printing out the factorions, that:
There are 3 factorions in base 9
There are 4 factorions in base 10
There are 5 factorions in base 11
There are 2 factorions in base 12 (up to the same upper bound as for base 10)
See also
Wikipedia article
OEIS:A014080 - Factorions in base 10
OEIS:A193163 - Factorions in base n
| #Arturo | Arturo | factorials: [1 1 2 6 24 120 720 5040 40320 362880 3628800 39916800]
factorion?: function [n, base][
try? [
n = sum map digits.base:base n 'x -> factorials\[x]
]
else [
print ["n:" n "base:" base]
false
]
]
loop 9..12 'base ->
print ["Base" base "factorions:" select 1..45000 'z -> factorion? z base]
] |
http://rosettacode.org/wiki/Filter | Filter | Task
Select certain elements from an Array into a new Array in a generic way.
To demonstrate, select all even numbers from an Array.
As an option, give a second solution which filters destructively,
by modifying the original Array rather than creating a new Array.
| #SequenceL | SequenceL | evens(x(1))[i] := x[i] when x[i] mod 2 = 0; |
http://rosettacode.org/wiki/Faces_from_a_mesh | Faces from a mesh | A mesh defining a surface has uniquely numbered vertices, and named,
simple-polygonal faces described usually by an ordered list of edge numbers
going around the face,
For example:
External image of two faces
Rough textual version without edges:
1
17
7 A
B
11
23
A is the triangle (1, 11, 7), or equally (7, 11, 1), going anti-clockwise, or
any of all the rotations of those ordered vertices.
1
7 A
11
B is the four-sided face (1, 17, 23, 11), or equally (23, 17, 1, 11) or any
of their rotations.
1
17
B
11
23
Let's call the above the perimeter format as it traces around the perimeter.
A second format
A separate algorithm returns polygonal faces consisting of a face name and an unordered
set of edge definitions for each face.
A single edge is described by the vertex numbers at its two ends, always in
ascending order.
All edges for the face are given, but in an undefined order.
For example face A could be described by the edges (1, 11), (7, 11), and (1, 7)
(The order of each vertex number in an edge is ascending, but the order in
which the edges are stated is arbitrary).
Similarly face B could be described by the edges (11, 23), (1, 17), (17, 23),
and (1, 11) in arbitrary order of the edges.
Let's call this second format the edge format.
Task
1. Write a routine to check if two perimeter formatted faces have the same perimeter. Use it to check if the following pairs of perimeters are the same:
Q: (8, 1, 3)
R: (1, 3, 8)
U: (18, 8, 14, 10, 12, 17, 19)
V: (8, 14, 10, 12, 17, 19, 18)
2. Write a routine and use it to transform the following faces from edge to perimeter format.
E: {(1, 11), (7, 11), (1, 7)}
F: {(11, 23), (1, 17), (17, 23), (1, 11)}
G: {(8, 14), (17, 19), (10, 12), (10, 14), (12, 17), (8, 18), (18, 19)}
H: {(1, 3), (9, 11), (3, 11), (1, 11)}
Show your output here.
| #Raku | Raku | sub check-equivalence ($a, $b) { so $a.Bag eqv $b.Bag }
sub edge-to-periphery (@a is copy) {
return Nil unless @a.List.Bag.values.all == 2;
my @b = @a.shift.flat;
while @a > 1 {
for @a.kv -> $k, $v {
if $v[0] == @b.tail {
@b.push: $v[1];
@a.splice($k,1);
last
}
elsif $v[1] == @b.tail {
@b.push: $v[0];
@a.splice($k,1);
last
}
}
}
@b
}
say 'Perimeter format equality checks:';
for (8, 1, 3), (1, 3, 8),
(18, 8, 14, 10, 12, 17, 19), (8, 14, 10, 12, 17, 19, 18)
-> $a, $b {
say "({$a.join: ', '}) equivalent to ({$b.join: ', '})? ",
check-equivalence($a, $b)
}
say "\nEdge to perimeter format translations:";
for ((1, 11), (7, 11), (1, 7)),
((11, 23), (1, 17), (17, 23), (1, 11)),
((8, 14), (17, 19), (10, 12), (10, 14), (12, 17), (8, 18), (18, 19)),
((1, 3), (9, 11), (3, 11), (1, 11))
{
.gist.print;
say " ==> ({.&edge-to-periphery || 'Invalid edge format'})";
} |
http://rosettacode.org/wiki/FizzBuzz | FizzBuzz | Task
Write a program that prints the integers from 1 to 100 (inclusive).
But:
for multiples of three, print Fizz (instead of the number)
for multiples of five, print Buzz (instead of the number)
for multiples of both three and five, print FizzBuzz (instead of the number)
The FizzBuzz problem was presented as the lowest level of comprehension required to illustrate adequacy.
Also see
(a blog) dont-overthink-fizzbuzz
(a blog) fizzbuzz-the-programmers-stairway-to-heaven
| #PHL | PHL | module fizzbuzz;
extern printf;
@Integer main [
var i = 1;
while (i <= 100) {
if (i % 15 == 0)
printf("FizzBuzz");
else if (i % 3 == 0)
printf("Fizz");
else if (i % 5 == 0)
printf("Buzz");
else
printf("%d", i);
printf("\n");
i = i::inc;
}
return 0;
] |
http://rosettacode.org/wiki/Exponentiation_with_infix_operators_in_(or_operating_on)_the_base | Exponentiation with infix operators in (or operating on) the base | (Many programming languages, especially those with extended─precision integer arithmetic, usually
support one of **, ^, ↑ or some such for exponentiation.)
Some languages treat/honor infix operators when performing exponentiation (raising
numbers to some power by the language's exponentiation operator, if the computer
programming language has one).
Other programming languages may make use of the POW or some other BIF
(Built─In Ffunction), or some other library service.
If your language's exponentiation operator is not one of the usual ones, please comment on how to recognize it.
This task will deal with the case where there is some form of an infix operator operating
in (or operating on) the base.
Example
A negative five raised to the 3rd power could be specified as:
-5 ** 3 or as
-(5) ** 3 or as
(-5) ** 3 or as something else
(Not all computer programming languages have an exponential operator and/or support these syntax expression(s).
Task
compute and display exponentiation with a possible infix operator, whether specified and/or implied/inferred.
Raise the following numbers (integer or real):
-5 and
+5
to the following powers:
2nd and
3rd
using the following expressions (if applicable in your language):
-x**p
-(x)**p
(-x)**p
-(x**p)
Show here (on this page) the four (or more) types of symbolic expressions for each number and power.
Try to present the results in the same format/manner as the other programming entries to make any differences apparent.
The variables may be of any type(s) that is/are applicable in your language.
Related tasks
Exponentiation order
Exponentiation operator
Arbitrary-precision integers (included)
Parsing/RPN to infix conversion
Operator precedence
References
Wikipedia: Order of operations in Programming languages
| #Maple | Maple | [-5**2,-(5)**2,(-5)**2,-(5**2)];
[-25, -25, 25, -25]
[-5**3,-(5)**3,(-5)**3,-(5**3)];
[-125, -125, -125, -125] |
http://rosettacode.org/wiki/Exponentiation_with_infix_operators_in_(or_operating_on)_the_base | Exponentiation with infix operators in (or operating on) the base | (Many programming languages, especially those with extended─precision integer arithmetic, usually
support one of **, ^, ↑ or some such for exponentiation.)
Some languages treat/honor infix operators when performing exponentiation (raising
numbers to some power by the language's exponentiation operator, if the computer
programming language has one).
Other programming languages may make use of the POW or some other BIF
(Built─In Ffunction), or some other library service.
If your language's exponentiation operator is not one of the usual ones, please comment on how to recognize it.
This task will deal with the case where there is some form of an infix operator operating
in (or operating on) the base.
Example
A negative five raised to the 3rd power could be specified as:
-5 ** 3 or as
-(5) ** 3 or as
(-5) ** 3 or as something else
(Not all computer programming languages have an exponential operator and/or support these syntax expression(s).
Task
compute and display exponentiation with a possible infix operator, whether specified and/or implied/inferred.
Raise the following numbers (integer or real):
-5 and
+5
to the following powers:
2nd and
3rd
using the following expressions (if applicable in your language):
-x**p
-(x)**p
(-x)**p
-(x**p)
Show here (on this page) the four (or more) types of symbolic expressions for each number and power.
Try to present the results in the same format/manner as the other programming entries to make any differences apparent.
The variables may be of any type(s) that is/are applicable in your language.
Related tasks
Exponentiation order
Exponentiation operator
Arbitrary-precision integers (included)
Parsing/RPN to infix conversion
Operator precedence
References
Wikipedia: Order of operations in Programming languages
| #Mathematica_.2F_Wolfram_Language | Mathematica / Wolfram Language | {-5^2, -(5)^2, (-5)^2, -(5^2)}
{-5^3, -(5)^3, (-5)^3, -(5^3)} |
http://rosettacode.org/wiki/Exponentiation_with_infix_operators_in_(or_operating_on)_the_base | Exponentiation with infix operators in (or operating on) the base | (Many programming languages, especially those with extended─precision integer arithmetic, usually
support one of **, ^, ↑ or some such for exponentiation.)
Some languages treat/honor infix operators when performing exponentiation (raising
numbers to some power by the language's exponentiation operator, if the computer
programming language has one).
Other programming languages may make use of the POW or some other BIF
(Built─In Ffunction), or some other library service.
If your language's exponentiation operator is not one of the usual ones, please comment on how to recognize it.
This task will deal with the case where there is some form of an infix operator operating
in (or operating on) the base.
Example
A negative five raised to the 3rd power could be specified as:
-5 ** 3 or as
-(5) ** 3 or as
(-5) ** 3 or as something else
(Not all computer programming languages have an exponential operator and/or support these syntax expression(s).
Task
compute and display exponentiation with a possible infix operator, whether specified and/or implied/inferred.
Raise the following numbers (integer or real):
-5 and
+5
to the following powers:
2nd and
3rd
using the following expressions (if applicable in your language):
-x**p
-(x)**p
(-x)**p
-(x**p)
Show here (on this page) the four (or more) types of symbolic expressions for each number and power.
Try to present the results in the same format/manner as the other programming entries to make any differences apparent.
The variables may be of any type(s) that is/are applicable in your language.
Related tasks
Exponentiation order
Exponentiation operator
Arbitrary-precision integers (included)
Parsing/RPN to infix conversion
Operator precedence
References
Wikipedia: Order of operations in Programming languages
| #Nim | Nim | import math, strformat
for x in [-5, 5]:
for p in [2, 3]:
echo &"x is {x:2}, ", &"p is {p:1}, ",
&"-x^p is {-x^p:4}, ", &"-(x)^p is {-(x)^p:4}, ",
&"(-x)^p is {(-x)^p:4}, ", &"-(x^p) is {-(x^p):4}" |
http://rosettacode.org/wiki/Fibonacci_sequence | Fibonacci sequence | The Fibonacci sequence is a sequence Fn of natural numbers defined recursively:
F0 = 0
F1 = 1
Fn = Fn-1 + Fn-2, if n>1
Task
Write a function to generate the nth Fibonacci number.
Solutions can be iterative or recursive (though recursive solutions are generally considered too slow and are mostly used as an exercise in recursion).
The sequence is sometimes extended into negative numbers by using a straightforward inverse of the positive definition:
Fn = Fn+2 - Fn+1, if n<0
support for negative n in the solution is optional.
Related tasks
Fibonacci n-step number sequences
Leonardo numbers
References
Wikipedia, Fibonacci number
Wikipedia, Lucas number
MathWorld, Fibonacci Number
Some identities for r-Fibonacci numbers
OEIS Fibonacci numbers
OEIS Lucas numbers
| #Fantom | Fantom |
class Main
{
static Int fib (Int n)
{
if (n < 2) return n
fibNums := [1, 0]
while (fibNums.size <= n)
{
fibNums.insert (0, fibNums[0] + fibNums[1])
}
return fibNums.first
}
public static Void main ()
{
20.times |n|
{
echo ("Fib($n) is ${fib(n)}")
}
}
}
|
http://rosettacode.org/wiki/Factors_of_an_integer | Factors of an integer |
Basic Data Operation
This is a basic data operation. It represents a fundamental action on a basic data type.
You may see other such operations in the Basic Data Operations category, or:
Integer Operations
Arithmetic |
Comparison
Boolean Operations
Bitwise |
Logical
String Operations
Concatenation |
Interpolation |
Comparison |
Matching
Memory Operations
Pointers & references |
Addresses
Task
Compute the factors of a positive integer.
These factors are the positive integers by which the number being factored can be divided to yield a positive integer result.
(Though the concepts function correctly for zero and negative integers, the set of factors of zero has countably infinite members, and the factors of negative integers can be obtained from the factors of related positive numbers without difficulty; this task does not require handling of either of these cases).
Note that every prime number has two factors: 1 and itself.
Related tasks
count in factors
prime decomposition
Sieve of Eratosthenes
primality by trial division
factors of a Mersenne number
trial factoring of a Mersenne number
partition an integer X into N primes
sequence of primes by Trial Division
sequence: smallest number greater than previous term with exactly n divisors
| #OCaml | OCaml | let rec range = function 0 -> [] | n -> range(n-1) @ [n]
let factors n =
List.filter (fun v -> (n mod v) = 0) (range n) |
http://rosettacode.org/wiki/Extreme_floating_point_values | Extreme floating point values | The IEEE floating point specification defines certain 'extreme' floating point values such as minus zero, -0.0, a value distinct from plus zero; not a number, NaN; and plus and minus infinity.
The task is to use expressions involving other 'normal' floating point values in your language to calculate these, (and maybe other), extreme floating point values in your language and assign them to variables.
Print the values of these variables if possible; and show some arithmetic with these values and variables.
If your language can directly enter these extreme floating point values then show it.
See also
What Every Computer Scientist Should Know About Floating-Point Arithmetic
Related tasks
Infinity
Detect division by zero
Literals/Floating point
| #Clojure | Clojure |
(def neg-inf (/ -1.0 0.0)) ; Also Double/NEGATIVE_INFINITY
(def inf (/ 1.0 0.0)) ; Also Double/POSITIVE_INFINITY
(def nan (/ 0.0 0.0)) ; Also Double/NaN
(def neg-zero (/ -2.0 Double/POSITIVE_INFINITY)) ; Also -0.0
(println " Negative inf: " neg-inf)
(println " Positive inf: " inf)
(println " NaN: " nan)
(println " Negative 0: " neg-zero)
(println " inf + -inf: " (+ inf neg-inf))
(println " NaN == NaN: " (= Double/NaN Double/NaN))
(println "NaN equals NaN: " (.equals Double/NaN Double/NaN))
|
http://rosettacode.org/wiki/Extreme_floating_point_values | Extreme floating point values | The IEEE floating point specification defines certain 'extreme' floating point values such as minus zero, -0.0, a value distinct from plus zero; not a number, NaN; and plus and minus infinity.
The task is to use expressions involving other 'normal' floating point values in your language to calculate these, (and maybe other), extreme floating point values in your language and assign them to variables.
Print the values of these variables if possible; and show some arithmetic with these values and variables.
If your language can directly enter these extreme floating point values then show it.
See also
What Every Computer Scientist Should Know About Floating-Point Arithmetic
Related tasks
Infinity
Detect division by zero
Literals/Floating point
| #D | D | // Compile this module without -O
import std.stdio: writeln, writefln;
import std.string: format;
import std.math: NaN, getNaNPayload;
void show(T)() {
static string toHex(T x) {
string result;
auto ptr = cast(ubyte*)&x;
foreach_reverse (immutable i; 0 .. T.sizeof)
result ~= format("%02x", ptr[i]);
return result;
}
enum string name = T.stringof;
writeln("Computed extreme ", name, " values:");
T zero = 0.0;
T pos_inf = T(1.0) / zero;
writeln(" ", name, " +oo = ", pos_inf);
T neg_inf = -pos_inf;
writeln(" ", name, " -oo = ", neg_inf);
T pos_zero = T(1.0) / pos_inf;
writeln(" ", name, " +0 (pos_zero) = ", pos_zero);
T neg_zero = T(1.0) / neg_inf;
writeln(" ", name, " -0 = ", neg_zero);
T nan = zero / pos_zero;
writefln(" " ~ name ~ " zero / pos_zero = %f %s", nan, toHex(nan));
writeln();
writeln("Some ", T.stringof, " properties and literals:");
writeln(" ", name, " +oo = ", T.infinity);
writeln(" ", name, " -oo = ", -T.infinity);
writeln(" ", name, " +0 = ", T(0.0));
writeln(" ", name, " -0 = ", T(-0.0));
writefln(" " ~ name ~ " nan = %f %s", T.nan, toHex(T.nan));
writefln(" " ~ name ~ " init = %f %s", T.init, toHex(T.init));
writeln(" ", name, " epsilon = ", T.epsilon);
writeln(" ", name, " max = ", T.max);
writeln(" ", name, " -max = ", -T.max);
writeln(" ", name, " min_normal = ", -T.min_normal);
writeln("-----------------------------");
}
void main() {
show!float;
show!double;
show!real;
writeln("Largest possible payload for float, double and real NaNs:");
immutable float f1 = NaN(0x3F_FFFF);
writeln(getNaNPayload(f1));
immutable double f2 = NaN(0x3_FFFF_FFFF_FFFF);
writeln(getNaNPayload(f2));
immutable real f3 = NaN(0x3FFF_FFFF_FFFF_FFFF);
writeln(getNaNPayload(f3));
} |
http://rosettacode.org/wiki/Factorial_base_numbers_indexing_permutations_of_a_collection | Factorial base numbers indexing permutations of a collection | You need a random arrangement of a deck of cards, you are sick of lame ways of doing this. This task is a super-cool way of doing this using factorial base numbers.
The first 25 factorial base numbers in increasing order are: 0.0.0, 0.0.1, 0.1.0, 0.1.1, 0.2.0, 0.2.1, 1.0.0, 1.0.1, 1.1.0, 1.1.1,1.2.0, 1.2.1, 2.0.0, 2.0.1, 2.1.0, 2.1.1, 2.2.0, 2.2.1, 3.0.0, 3.0.1, 3.1.0, 3.1.1, 3.2.0, 3.2.1, 1.0.0.0
Observe that the least significant digit is base 2 the next base 3, in general an n-digit factorial base number has digits n..1 in base n+1..2.
I want to produce a 1 to 1 mapping between these numbers and permutations:-
0.0.0 -> 0123
0.0.1 -> 0132
0.1.0 -> 0213
0.1.1 -> 0231
0.2.0 -> 0312
0.2.1 -> 0321
1.0.0 -> 1023
1.0.1 -> 1032
1.1.0 -> 1203
1.1.1 -> 1230
1.2.0 -> 1302
1.2.1 -> 1320
2.0.0 -> 2013
2.0.1 -> 2031
2.1.0 -> 2103
2.1.1 -> 2130
2.2.0 -> 2301
2.2.1 -> 2310
3.0.0 -> 3012
3.0.1 -> 3021
3.1.0 -> 3102
3.1.1 -> 3120
3.2.0 -> 3201
3.2.1 -> 3210
The following psudo-code will do this:
Starting with m=0 and Ω, an array of elements to be permutated, for each digit g starting with the most significant digit in the factorial base number.
If g is greater than zero, rotate the elements from m to m+g in Ω (see example)
Increment m and repeat the first step using the next most significant digit until the factorial base number is exhausted.
For example: using the factorial base number 2.0.1 and Ω = 0 1 2 3 where place 0 in both is the most significant (left-most) digit/element.
Step 1: m=0 g=2; Rotate places 0 through 2. 0 1 2 3 becomes 2 0 1 3
Step 2: m=1 g=0; No action.
Step 3: m=2 g=1; Rotate places 2 through 3. 2 0 1 3 becomes 2 0 3 1
Let me work 2.0.1 and 0123
step 1 n=0 g=2 Ω=2013
step 2 n=1 g=0 so no action
step 3 n=2 g=1 Ω=2031
The task:
First use your function to recreate the above table.
Secondly use your function to generate all permutaions of 11 digits, perhaps count them don't display them, compare this method with
methods in rc's permutations task.
Thirdly here following are two ramdom 51 digit factorial base numbers I prepared earlier:
39.49.7.47.29.30.2.12.10.3.29.37.33.17.12.31.29.34.17.25.2.4.25.4.1.14.20.6.21.18.1.1.1.4.0.5.15.12.4.3.10.10.9.1.6.5.5.3.0.0.0
51.48.16.22.3.0.19.34.29.1.36.30.12.32.12.29.30.26.14.21.8.12.1.3.10.4.7.17.6.21.8.12.15.15.13.15.7.3.12.11.9.5.5.6.6.3.4.0.3.2.1
use your function to crate the corresponding permutation of the following shoe of cards:
A♠K♠Q♠J♠10♠9♠8♠7♠6♠5♠4♠3♠2♠A♥K♥Q♥J♥10♥9♥8♥7♥6♥5♥4♥3♥2♥A♦K♦Q♦J♦10♦9♦8♦7♦6♦5♦4♦3♦2♦A♣K♣Q♣J♣10♣9♣8♣7♣6♣5♣4♣3♣2♣
Finally create your own 51 digit factorial base number and produce the corresponding permutation of the above shoe
| #Haskell | Haskell | import Data.List (unfoldr, intercalate)
newtype Fact = Fact [Int]
-- smart constructor
fact :: [Int] -> Fact
fact = Fact . zipWith min [0..] . reverse
instance Show Fact where
show (Fact ds) = intercalate "." $ show <$> reverse ds
toFact :: Integer -> Fact
toFact 0 = Fact [0]
toFact n = Fact $ unfoldr f (1, n)
where
f (b, 0) = Nothing
f (b, n) = let (q, r) = n `divMod` b
in Just (fromIntegral r, (b+1, q))
fromFact :: Fact -> Integer
fromFact (Fact ds) = foldr f 0 $ zip [1..] ds
where
f (b, d) r = r * b + fromIntegral d |
http://rosettacode.org/wiki/Factorial_base_numbers_indexing_permutations_of_a_collection | Factorial base numbers indexing permutations of a collection | You need a random arrangement of a deck of cards, you are sick of lame ways of doing this. This task is a super-cool way of doing this using factorial base numbers.
The first 25 factorial base numbers in increasing order are: 0.0.0, 0.0.1, 0.1.0, 0.1.1, 0.2.0, 0.2.1, 1.0.0, 1.0.1, 1.1.0, 1.1.1,1.2.0, 1.2.1, 2.0.0, 2.0.1, 2.1.0, 2.1.1, 2.2.0, 2.2.1, 3.0.0, 3.0.1, 3.1.0, 3.1.1, 3.2.0, 3.2.1, 1.0.0.0
Observe that the least significant digit is base 2 the next base 3, in general an n-digit factorial base number has digits n..1 in base n+1..2.
I want to produce a 1 to 1 mapping between these numbers and permutations:-
0.0.0 -> 0123
0.0.1 -> 0132
0.1.0 -> 0213
0.1.1 -> 0231
0.2.0 -> 0312
0.2.1 -> 0321
1.0.0 -> 1023
1.0.1 -> 1032
1.1.0 -> 1203
1.1.1 -> 1230
1.2.0 -> 1302
1.2.1 -> 1320
2.0.0 -> 2013
2.0.1 -> 2031
2.1.0 -> 2103
2.1.1 -> 2130
2.2.0 -> 2301
2.2.1 -> 2310
3.0.0 -> 3012
3.0.1 -> 3021
3.1.0 -> 3102
3.1.1 -> 3120
3.2.0 -> 3201
3.2.1 -> 3210
The following psudo-code will do this:
Starting with m=0 and Ω, an array of elements to be permutated, for each digit g starting with the most significant digit in the factorial base number.
If g is greater than zero, rotate the elements from m to m+g in Ω (see example)
Increment m and repeat the first step using the next most significant digit until the factorial base number is exhausted.
For example: using the factorial base number 2.0.1 and Ω = 0 1 2 3 where place 0 in both is the most significant (left-most) digit/element.
Step 1: m=0 g=2; Rotate places 0 through 2. 0 1 2 3 becomes 2 0 1 3
Step 2: m=1 g=0; No action.
Step 3: m=2 g=1; Rotate places 2 through 3. 2 0 1 3 becomes 2 0 3 1
Let me work 2.0.1 and 0123
step 1 n=0 g=2 Ω=2013
step 2 n=1 g=0 so no action
step 3 n=2 g=1 Ω=2031
The task:
First use your function to recreate the above table.
Secondly use your function to generate all permutaions of 11 digits, perhaps count them don't display them, compare this method with
methods in rc's permutations task.
Thirdly here following are two ramdom 51 digit factorial base numbers I prepared earlier:
39.49.7.47.29.30.2.12.10.3.29.37.33.17.12.31.29.34.17.25.2.4.25.4.1.14.20.6.21.18.1.1.1.4.0.5.15.12.4.3.10.10.9.1.6.5.5.3.0.0.0
51.48.16.22.3.0.19.34.29.1.36.30.12.32.12.29.30.26.14.21.8.12.1.3.10.4.7.17.6.21.8.12.15.15.13.15.7.3.12.11.9.5.5.6.6.3.4.0.3.2.1
use your function to crate the corresponding permutation of the following shoe of cards:
A♠K♠Q♠J♠10♠9♠8♠7♠6♠5♠4♠3♠2♠A♥K♥Q♥J♥10♥9♥8♥7♥6♥5♥4♥3♥2♥A♦K♦Q♦J♦10♦9♦8♦7♦6♦5♦4♦3♦2♦A♣K♣Q♣J♣10♣9♣8♣7♣6♣5♣4♣3♣2♣
Finally create your own 51 digit factorial base number and produce the corresponding permutation of the above shoe
| #J | J | NB. A is a numerical matrix corresponding to the input and output
A =: _&".;._2[0 :0
0 0 0 0123
0 0 1 0132
0 1 0 0213
0 1 1 0231
0 2 0 0312
0 2 1 0321
1 0 0 1023
1 0 1 1032
1 1 0 1203
1 1 1 1230
1 2 0 1302
1 2 1 1320
2 0 0 2013
2 0 1 2031
2 1 0 2103
2 1 1 2130
2 2 0 2301
2 2 1 2310
3 0 0 3012
3 0 1 3021
3 1 0 3102
3 1 1 3120
3 2 0 3201
3 2 1 3210
)
NB. generalized antibase converts the factorial base representation to integers
4 3 2 #. _ 3 {. A
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
EXPECT =: 10 10 10 10#:{:"1 A
NB. the 0 through 23 anagrams of 0 1 2 3 matches our expactation
EXPECT -: (4 3 2 #. _ 3 {. A) A. 0 1 2 3
1
NB. 6 take EXPECT, for you to see what's been matched
6{.EXPECT
0 1 2 3
0 1 3 2
0 2 1 3
0 2 3 1
0 3 1 2
0 3 2 1
|
http://rosettacode.org/wiki/Factorions | Factorions |
Definition
A factorion is a natural number that equals the sum of the factorials of its digits.
Example
145 is a factorion in base 10 because:
1! + 4! + 5! = 1 + 24 + 120 = 145
It can be shown (see talk page) that no factorion in base 10 can exceed 1,499,999.
Task
Write a program in your language to demonstrate, by calculating and printing out the factorions, that:
There are 3 factorions in base 9
There are 4 factorions in base 10
There are 5 factorions in base 11
There are 2 factorions in base 12 (up to the same upper bound as for base 10)
See also
Wikipedia article
OEIS:A014080 - Factorions in base 10
OEIS:A193163 - Factorions in base n
| #AutoHotkey | AutoHotkey | fact:=[]
fact[0] := 1
while (A_Index < 12)
fact[A_Index] := fact[A_Index-1] * A_Index
b := 9
while (b <= 12) {
res .= "base " b " factorions: `t"
while (A_Index < 1500000){
sum := 0
j := A_Index
while (j > 0){
d := Mod(j, b)
sum += fact[d]
j /= b
}
if (sum = A_Index)
res .= A_Index " "
}
b++
res .= "`n"
}
MsgBox % res
return |
http://rosettacode.org/wiki/Factorions | Factorions |
Definition
A factorion is a natural number that equals the sum of the factorials of its digits.
Example
145 is a factorion in base 10 because:
1! + 4! + 5! = 1 + 24 + 120 = 145
It can be shown (see talk page) that no factorion in base 10 can exceed 1,499,999.
Task
Write a program in your language to demonstrate, by calculating and printing out the factorions, that:
There are 3 factorions in base 9
There are 4 factorions in base 10
There are 5 factorions in base 11
There are 2 factorions in base 12 (up to the same upper bound as for base 10)
See also
Wikipedia article
OEIS:A014080 - Factorions in base 10
OEIS:A193163 - Factorions in base n
| #AWK | AWK |
# syntax: GAWK -f FACTORIONS.AWK
# converted from C
BEGIN {
fact[0] = 1 # cache factorials from 0 to 11
for (n=1; n<12; ++n) {
fact[n] = fact[n-1] * n
}
for (b=9; b<=12; ++b) {
printf("base %d factorions:",b)
for (i=1; i<1500000; ++i) {
sum = 0
j = i
while (j > 0) {
d = j % b
sum += fact[d]
j = int(j/b)
}
if (sum == i) {
printf(" %d",i)
}
}
printf("\n")
}
exit(0)
}
|
http://rosettacode.org/wiki/Filter | Filter | Task
Select certain elements from an Array into a new Array in a generic way.
To demonstrate, select all even numbers from an Array.
As an option, give a second solution which filters destructively,
by modifying the original Array rather than creating a new Array.
| #Sidef | Sidef | var arr = [1,2,3,4,5];
# Creates a new array
var new = arr.grep {|i| i %% 2};
say new.dump; # => [2, 4]
# Destructive (at variable level)
arr.grep! {|i| i %% 2};
say arr.dump; # => [2, 4] |
http://rosettacode.org/wiki/Faces_from_a_mesh | Faces from a mesh | A mesh defining a surface has uniquely numbered vertices, and named,
simple-polygonal faces described usually by an ordered list of edge numbers
going around the face,
For example:
External image of two faces
Rough textual version without edges:
1
17
7 A
B
11
23
A is the triangle (1, 11, 7), or equally (7, 11, 1), going anti-clockwise, or
any of all the rotations of those ordered vertices.
1
7 A
11
B is the four-sided face (1, 17, 23, 11), or equally (23, 17, 1, 11) or any
of their rotations.
1
17
B
11
23
Let's call the above the perimeter format as it traces around the perimeter.
A second format
A separate algorithm returns polygonal faces consisting of a face name and an unordered
set of edge definitions for each face.
A single edge is described by the vertex numbers at its two ends, always in
ascending order.
All edges for the face are given, but in an undefined order.
For example face A could be described by the edges (1, 11), (7, 11), and (1, 7)
(The order of each vertex number in an edge is ascending, but the order in
which the edges are stated is arbitrary).
Similarly face B could be described by the edges (11, 23), (1, 17), (17, 23),
and (1, 11) in arbitrary order of the edges.
Let's call this second format the edge format.
Task
1. Write a routine to check if two perimeter formatted faces have the same perimeter. Use it to check if the following pairs of perimeters are the same:
Q: (8, 1, 3)
R: (1, 3, 8)
U: (18, 8, 14, 10, 12, 17, 19)
V: (8, 14, 10, 12, 17, 19, 18)
2. Write a routine and use it to transform the following faces from edge to perimeter format.
E: {(1, 11), (7, 11), (1, 7)}
F: {(11, 23), (1, 17), (17, 23), (1, 11)}
G: {(8, 14), (17, 19), (10, 12), (10, 14), (12, 17), (8, 18), (18, 19)}
H: {(1, 3), (9, 11), (3, 11), (1, 11)}
Show your output here.
| #Wren | Wren | import "./sort" for Sort
import "./seq" for Lst
import "./fmt" for Fmt
// Check two perimeters are equal.
var perimEqual = Fn.new { |p1, p2|
var le = p1.count
if (le != p2.count) return false
for (p in p1) {
if (!p2.contains(p)) return false
}
// use copy to avoid mutating 'p1'
var c = p1.toList
for (r in 0..1) {
for (i in 0...le) {
if (Lst.areEqual(c, p2)) return true
// do circular shift to right
Lst.rshift(c)
}
// now process in opposite direction
Lst.reverse(c) // reverses 'c' in place
}
return false
}
var faceToPerim = Fn.new { |face|
// use copy to avoid mutating 'face'
var le = face.count
if (le == 0) return []
var edges = List.filled(le, null)
for (i in 0...le) {
// check edge pairs are in correct order
if (face[i][1] <= face[i][0]) return []
edges[i] = [face[i][0], face[i][1]]
}
// sort edges in ascending order
var cmp = Fn.new { |e1, e2|
if (e1[0] != e2[0]) {
return (e1[0] - e2[0]).sign
}
return (e1[1] - e2[1]).sign
}
Sort.insertion(edges, cmp)
var first = edges[0][0]
var last = edges[0][1]
var perim = [first, last]
// remove first edge
edges.removeAt(0)
le = le - 1
while (le > 0) {
var i = 0
var outer = false
var cont = false
for (e in edges) {
var found = false
if (e[0] == last) {
perim.add(e[1])
last = e[1]
found = true
} else if (e[1] == last) {
perim.add(e[0])
last = e[0]
found = true
}
if (found) {
// remove i'th edge
edges.removeAt(i)
le = le - 1
if (last == first) {
if (le == 0) {
outer = true
break
} else {
return []
}
}
cont = true
break
}
i = i + 1
}
if (outer && !cont) break
}
return perim[0..-2]
}
System.print("Perimeter format equality checks:")
var areEqual = perimEqual.call([8, 1, 3], [1, 3, 8])
System.print(" Q == R is %(areEqual)")
areEqual = perimEqual.call([18, 8, 14, 10, 12, 17, 19], [8, 14, 10, 12, 17, 19, 18])
System.print(" U == V is %(areEqual)")
var e = [[7, 11], [1, 11], [1, 7]]
var f = [[11, 23], [1, 17], [17, 23], [1, 11]]
var g = [[8, 14], [17, 19], [10, 12], [10, 14], [12, 17], [8, 18], [18, 19]]
var h = [[1, 3], [9, 11], [3, 11], [1, 11]]
System.print("\nEdge to perimeter format translations:")
var i = 0
for (face in [e, f, g, h]) {
var perim = faceToPerim.call(face)
if (perim.isEmpty) {
Fmt.print(" $c => Invalid edge format", i + 69) // 'E' is ASCII 69
} else {
Fmt.print(" $c => $n", i + 69, perim)
}
} |
http://rosettacode.org/wiki/FizzBuzz | FizzBuzz | Task
Write a program that prints the integers from 1 to 100 (inclusive).
But:
for multiples of three, print Fizz (instead of the number)
for multiples of five, print Buzz (instead of the number)
for multiples of both three and five, print FizzBuzz (instead of the number)
The FizzBuzz problem was presented as the lowest level of comprehension required to illustrate adequacy.
Also see
(a blog) dont-overthink-fizzbuzz
(a blog) fizzbuzz-the-programmers-stairway-to-heaven
| #PHP | PHP | <?php
for ($i = 1; $i <= 100; $i++)
{
if (!($i % 15))
echo "FizzBuzz\n";
else if (!($i % 3))
echo "Fizz\n";
else if (!($i % 5))
echo "Buzz\n";
else
echo "$i\n";
}
?> |
http://rosettacode.org/wiki/Exponentiation_with_infix_operators_in_(or_operating_on)_the_base | Exponentiation with infix operators in (or operating on) the base | (Many programming languages, especially those with extended─precision integer arithmetic, usually
support one of **, ^, ↑ or some such for exponentiation.)
Some languages treat/honor infix operators when performing exponentiation (raising
numbers to some power by the language's exponentiation operator, if the computer
programming language has one).
Other programming languages may make use of the POW or some other BIF
(Built─In Ffunction), or some other library service.
If your language's exponentiation operator is not one of the usual ones, please comment on how to recognize it.
This task will deal with the case where there is some form of an infix operator operating
in (or operating on) the base.
Example
A negative five raised to the 3rd power could be specified as:
-5 ** 3 or as
-(5) ** 3 or as
(-5) ** 3 or as something else
(Not all computer programming languages have an exponential operator and/or support these syntax expression(s).
Task
compute and display exponentiation with a possible infix operator, whether specified and/or implied/inferred.
Raise the following numbers (integer or real):
-5 and
+5
to the following powers:
2nd and
3rd
using the following expressions (if applicable in your language):
-x**p
-(x)**p
(-x)**p
-(x**p)
Show here (on this page) the four (or more) types of symbolic expressions for each number and power.
Try to present the results in the same format/manner as the other programming entries to make any differences apparent.
The variables may be of any type(s) that is/are applicable in your language.
Related tasks
Exponentiation order
Exponentiation operator
Arbitrary-precision integers (included)
Parsing/RPN to infix conversion
Operator precedence
References
Wikipedia: Order of operations in Programming languages
| #Pascal | Pascal | program exponentiationWithInfixOperatorsInTheBase(output);
const
minimumWidth = 7;
fractionDigits = minimumWidth div 4 + 1;
procedure testIntegerPower(
{ `pow` can in fact accept `integer`, `real` and `complex`. }
protected base: integer;
{ For `pow` the `exponent` _has_ to be an `integer`. }
protected exponent: integer
);
begin
writeLn('=====> testIntegerPower <=====');
writeLn(' base = ', base:minimumWidth);
writeLn(' exponent = ', exponent:minimumWidth);
{ Note: `exponent` may not be negative if `base` is zero! }
writeLn(' -base pow exponent = ', -base pow exponent:minimumWidth);
writeLn('-(base) pow exponent = ', -(base) pow exponent:minimumWidth);
writeLn('(-base) pow exponent = ', (-base) pow exponent:minimumWidth);
writeLn('-(base pow exponent) = ', -(base pow exponent):minimumWidth)
end;
procedure testRealPower(
{ `**` actually accepts all data types (`integer`, `real`, `complex`). }
protected base: real;
{ The `exponent` in an `**` expression will be, if applicable, }
{ _promoted_ to a `real` value approximation. }
protected exponent: integer
);
begin
writeLn('======> testRealPower <======');
writeLn(' base = ', base:minimumWidth:fractionDigits);
writeLn(' exponent = ', exponent:pred(minimumWidth, succ(fractionDigits)));
if base > 0.0 then
begin
{ The result of `base ** exponent` is a `complex` value }
{ `base` is a `complex` value, `real` otherwise. }
writeLn(' -base ** exponent = ', -base ** exponent:minimumWidth:fractionDigits);
writeLn('-(base) ** exponent = ', -(base) ** exponent:minimumWidth:fractionDigits);
writeLn('(-base) ** exponent = illegal');
writeLn('-(base ** exponent) = ', -(base ** exponent):minimumWidth:fractionDigits)
end
else
begin
{ “negative” zero will not alter the sign of the value. }
writeLn(' -base ** exponent = ', -base pow exponent:minimumWidth:fractionDigits);
writeLn('-(base) ** exponent = ', -(base) pow exponent:minimumWidth:fractionDigits);
writeLn('(-base) ** exponent = ', (-base) pow exponent:minimumWidth:fractionDigits);
writeLn('-(base ** exponent) = ', -(base pow exponent):minimumWidth:fractionDigits)
end
end;
{ === MAIN =================================================================== }
begin
testIntegerPower(-5, 2);
testIntegerPower(+5, 2);
testIntegerPower(-5, 3);
testIntegerPower( 5, 3);
testRealPower(-5.0, 2);
testRealPower(+5.0, 2);
testRealPower(-5E0, 3);
testRealPower(+5E0, 3)
end. |
http://rosettacode.org/wiki/Fibonacci_sequence | Fibonacci sequence | The Fibonacci sequence is a sequence Fn of natural numbers defined recursively:
F0 = 0
F1 = 1
Fn = Fn-1 + Fn-2, if n>1
Task
Write a function to generate the nth Fibonacci number.
Solutions can be iterative or recursive (though recursive solutions are generally considered too slow and are mostly used as an exercise in recursion).
The sequence is sometimes extended into negative numbers by using a straightforward inverse of the positive definition:
Fn = Fn+2 - Fn+1, if n<0
support for negative n in the solution is optional.
Related tasks
Fibonacci n-step number sequences
Leonardo numbers
References
Wikipedia, Fibonacci number
Wikipedia, Lucas number
MathWorld, Fibonacci Number
Some identities for r-Fibonacci numbers
OEIS Fibonacci numbers
OEIS Lucas numbers
| #Fermat | Fermat | Func Fibonacci(n) = if n<0 then -(-1)^n*Fibonacci(-n) else if n<2 then n else
Array fib[n+1];
fib[1] := 0;
fib[2] := 1;
for i = 2, n do
fib[i+1]:=fib[i]+fib[i-1]
od;
Return(fib[n+1]);
fi;
fi;
. |
http://rosettacode.org/wiki/Factors_of_an_integer | Factors of an integer |
Basic Data Operation
This is a basic data operation. It represents a fundamental action on a basic data type.
You may see other such operations in the Basic Data Operations category, or:
Integer Operations
Arithmetic |
Comparison
Boolean Operations
Bitwise |
Logical
String Operations
Concatenation |
Interpolation |
Comparison |
Matching
Memory Operations
Pointers & references |
Addresses
Task
Compute the factors of a positive integer.
These factors are the positive integers by which the number being factored can be divided to yield a positive integer result.
(Though the concepts function correctly for zero and negative integers, the set of factors of zero has countably infinite members, and the factors of negative integers can be obtained from the factors of related positive numbers without difficulty; this task does not require handling of either of these cases).
Note that every prime number has two factors: 1 and itself.
Related tasks
count in factors
prime decomposition
Sieve of Eratosthenes
primality by trial division
factors of a Mersenne number
trial factoring of a Mersenne number
partition an integer X into N primes
sequence of primes by Trial Division
sequence: smallest number greater than previous term with exactly n divisors
| #Oforth | Oforth | Integer method: factors self seq filter(#[ self isMultiple ]) ;
120 factors println |
http://rosettacode.org/wiki/Extreme_floating_point_values | Extreme floating point values | The IEEE floating point specification defines certain 'extreme' floating point values such as minus zero, -0.0, a value distinct from plus zero; not a number, NaN; and plus and minus infinity.
The task is to use expressions involving other 'normal' floating point values in your language to calculate these, (and maybe other), extreme floating point values in your language and assign them to variables.
Print the values of these variables if possible; and show some arithmetic with these values and variables.
If your language can directly enter these extreme floating point values then show it.
See also
What Every Computer Scientist Should Know About Floating-Point Arithmetic
Related tasks
Infinity
Detect division by zero
Literals/Floating point
| #Delphi | Delphi | program Floats;
{$APPTYPE CONSOLE}
uses
SysUtils;
var
PlusInf, MinusInf, NegZero, NotANum: Double;
begin
PlusInf:= 1.0/0.0;
MinusInf:= -1.0/0.0;
NegZero:= -1.0/PlusInf;
NotANum:= 0.0/0.0;
Writeln('Positive Infinity: ', PlusInf); // +Inf
Writeln('Negative Infinity: ', MinusInf); // -Inf
Writeln('Negative Zero: ', NegZero); // -0.0
Writeln('Not a Number: ', NotANum); // Nan
// allowed arithmetic
Writeln('+Inf + 2.0 = ', PlusInf + 2.0); // +Inf
Writeln('+Inf - 10.1 = ', PlusInf - 10.1); // +Inf
Writeln('NaN + 1.0 = ', NotANum + 1.0); // Nan
Writeln('NaN + NaN = ', NotANum + NotANum); // Nan
// throws exception
try
Writeln('+inf + -inf = ', PlusInf + MinusInf); // EInvalidOp
Writeln('0.0 * +inf = ', 0.0 * PlusInf); // EInlalidOp
Writeln('1.0/-0.0 = ', 1.0 / NegZero); // EZeroDivide
except
on E:Exception do
Writeln(E.Classname, ': ', E.Message);
end;
Readln;
end. |
http://rosettacode.org/wiki/Factorial_base_numbers_indexing_permutations_of_a_collection | Factorial base numbers indexing permutations of a collection | You need a random arrangement of a deck of cards, you are sick of lame ways of doing this. This task is a super-cool way of doing this using factorial base numbers.
The first 25 factorial base numbers in increasing order are: 0.0.0, 0.0.1, 0.1.0, 0.1.1, 0.2.0, 0.2.1, 1.0.0, 1.0.1, 1.1.0, 1.1.1,1.2.0, 1.2.1, 2.0.0, 2.0.1, 2.1.0, 2.1.1, 2.2.0, 2.2.1, 3.0.0, 3.0.1, 3.1.0, 3.1.1, 3.2.0, 3.2.1, 1.0.0.0
Observe that the least significant digit is base 2 the next base 3, in general an n-digit factorial base number has digits n..1 in base n+1..2.
I want to produce a 1 to 1 mapping between these numbers and permutations:-
0.0.0 -> 0123
0.0.1 -> 0132
0.1.0 -> 0213
0.1.1 -> 0231
0.2.0 -> 0312
0.2.1 -> 0321
1.0.0 -> 1023
1.0.1 -> 1032
1.1.0 -> 1203
1.1.1 -> 1230
1.2.0 -> 1302
1.2.1 -> 1320
2.0.0 -> 2013
2.0.1 -> 2031
2.1.0 -> 2103
2.1.1 -> 2130
2.2.0 -> 2301
2.2.1 -> 2310
3.0.0 -> 3012
3.0.1 -> 3021
3.1.0 -> 3102
3.1.1 -> 3120
3.2.0 -> 3201
3.2.1 -> 3210
The following psudo-code will do this:
Starting with m=0 and Ω, an array of elements to be permutated, for each digit g starting with the most significant digit in the factorial base number.
If g is greater than zero, rotate the elements from m to m+g in Ω (see example)
Increment m and repeat the first step using the next most significant digit until the factorial base number is exhausted.
For example: using the factorial base number 2.0.1 and Ω = 0 1 2 3 where place 0 in both is the most significant (left-most) digit/element.
Step 1: m=0 g=2; Rotate places 0 through 2. 0 1 2 3 becomes 2 0 1 3
Step 2: m=1 g=0; No action.
Step 3: m=2 g=1; Rotate places 2 through 3. 2 0 1 3 becomes 2 0 3 1
Let me work 2.0.1 and 0123
step 1 n=0 g=2 Ω=2013
step 2 n=1 g=0 so no action
step 3 n=2 g=1 Ω=2031
The task:
First use your function to recreate the above table.
Secondly use your function to generate all permutaions of 11 digits, perhaps count them don't display them, compare this method with
methods in rc's permutations task.
Thirdly here following are two ramdom 51 digit factorial base numbers I prepared earlier:
39.49.7.47.29.30.2.12.10.3.29.37.33.17.12.31.29.34.17.25.2.4.25.4.1.14.20.6.21.18.1.1.1.4.0.5.15.12.4.3.10.10.9.1.6.5.5.3.0.0.0
51.48.16.22.3.0.19.34.29.1.36.30.12.32.12.29.30.26.14.21.8.12.1.3.10.4.7.17.6.21.8.12.15.15.13.15.7.3.12.11.9.5.5.6.6.3.4.0.3.2.1
use your function to crate the corresponding permutation of the following shoe of cards:
A♠K♠Q♠J♠10♠9♠8♠7♠6♠5♠4♠3♠2♠A♥K♥Q♥J♥10♥9♥8♥7♥6♥5♥4♥3♥2♥A♦K♦Q♦J♦10♦9♦8♦7♦6♦5♦4♦3♦2♦A♣K♣Q♣J♣10♣9♣8♣7♣6♣5♣4♣3♣2♣
Finally create your own 51 digit factorial base number and produce the corresponding permutation of the above shoe
| #Julia | Julia | function makefactorialbased(N, makelist)
listlist = Vector{Vector{Int}}()
count = 0
while true
divisor = 2
makelist && (lis = zeros(Int, N))
k = count
while k > 0
k, r = divrem(k, divisor)
makelist && (divisor <= N + 1) && (lis[N - divisor + 2] = r)
divisor += 1
end
if divisor > N + 2
break
end
count += 1
makelist && push!(listlist, lis)
end
return count, listlist
end
function facmap(factnumbase)
perm = [i for i in 0:length(factnumbase)]
for (n, g) in enumerate(factnumbase)
if g != 0
perm[n:n + g] .= circshift(perm[n:n + g], 1)
end
end
perm
end
function factbasenums()
fcount, factnums = makefactorialbased(3, true)
perms = map(facmap, factnums)
for (i, fn) = enumerate(factnums)
println("$(join(string.(fn), ".")) -> $(join(string(perms[i]), ""))")
end
fcount, _ = makefactorialbased(10, false)
println("\nPermutations generated = $fcount, and 11! = $(factorial(11))\n")
taskrandom = ["39.49.7.47.29.30.2.12.10.3.29.37.33.17.12.31.29.34.17.25.2.4.25.4.1.14.20.6.21.18.1.1.1.4.0.5.15.12.4.3.10.10.9.1.6.5.5.3.0.0.0",
"51.48.16.22.3.0.19.34.29.1.36.30.12.32.12.29.30.26.14.21.8.12.1.3.10.4.7.17.6.21.8.12.15.15.13.15.7.3.12.11.9.5.5.6.6.3.4.0.3.2.1"]
perms = map(s -> facmap([parse(Int, s) for s in split(s, ".")]), taskrandom)
cardshoe = split("A♠K♠Q♠J♠T♠9♠8♠7♠6♠5♠4♠3♠2♠A♥K♥Q♥J♥T♥9♥8♥7♥6♥5♥4♥3♥2♥A♦K♦Q♦J♦T♦9♦8♦7♦6♦5♦4♦3♦2♦A♣K♣Q♣J♣T♣9♣8♣7♣6♣5♣4♣3♣2♣", "")
cards = [cardshoe[2*i+1] * cardshoe[2*i+2] for i in 0:51]
printcardshuffle(t, c, o) = (println(t); for i in 1:length(o) print(c[o[i] + 1]) end; println())
println("\nTask shuffles:")
map(i -> printcardshuffle(taskrandom[i], cards, perms[i]), 1:2)
myran = [rand(collect(0:i)) for i in 51:-1:1]
perm = facmap(myran)
println("\nMy random shuffle:")
printcardshuffle(join(string.(myran), "."), cards, perm)
end
factbasenums()
|
http://rosettacode.org/wiki/Factorial_base_numbers_indexing_permutations_of_a_collection | Factorial base numbers indexing permutations of a collection | You need a random arrangement of a deck of cards, you are sick of lame ways of doing this. This task is a super-cool way of doing this using factorial base numbers.
The first 25 factorial base numbers in increasing order are: 0.0.0, 0.0.1, 0.1.0, 0.1.1, 0.2.0, 0.2.1, 1.0.0, 1.0.1, 1.1.0, 1.1.1,1.2.0, 1.2.1, 2.0.0, 2.0.1, 2.1.0, 2.1.1, 2.2.0, 2.2.1, 3.0.0, 3.0.1, 3.1.0, 3.1.1, 3.2.0, 3.2.1, 1.0.0.0
Observe that the least significant digit is base 2 the next base 3, in general an n-digit factorial base number has digits n..1 in base n+1..2.
I want to produce a 1 to 1 mapping between these numbers and permutations:-
0.0.0 -> 0123
0.0.1 -> 0132
0.1.0 -> 0213
0.1.1 -> 0231
0.2.0 -> 0312
0.2.1 -> 0321
1.0.0 -> 1023
1.0.1 -> 1032
1.1.0 -> 1203
1.1.1 -> 1230
1.2.0 -> 1302
1.2.1 -> 1320
2.0.0 -> 2013
2.0.1 -> 2031
2.1.0 -> 2103
2.1.1 -> 2130
2.2.0 -> 2301
2.2.1 -> 2310
3.0.0 -> 3012
3.0.1 -> 3021
3.1.0 -> 3102
3.1.1 -> 3120
3.2.0 -> 3201
3.2.1 -> 3210
The following psudo-code will do this:
Starting with m=0 and Ω, an array of elements to be permutated, for each digit g starting with the most significant digit in the factorial base number.
If g is greater than zero, rotate the elements from m to m+g in Ω (see example)
Increment m and repeat the first step using the next most significant digit until the factorial base number is exhausted.
For example: using the factorial base number 2.0.1 and Ω = 0 1 2 3 where place 0 in both is the most significant (left-most) digit/element.
Step 1: m=0 g=2; Rotate places 0 through 2. 0 1 2 3 becomes 2 0 1 3
Step 2: m=1 g=0; No action.
Step 3: m=2 g=1; Rotate places 2 through 3. 2 0 1 3 becomes 2 0 3 1
Let me work 2.0.1 and 0123
step 1 n=0 g=2 Ω=2013
step 2 n=1 g=0 so no action
step 3 n=2 g=1 Ω=2031
The task:
First use your function to recreate the above table.
Secondly use your function to generate all permutaions of 11 digits, perhaps count them don't display them, compare this method with
methods in rc's permutations task.
Thirdly here following are two ramdom 51 digit factorial base numbers I prepared earlier:
39.49.7.47.29.30.2.12.10.3.29.37.33.17.12.31.29.34.17.25.2.4.25.4.1.14.20.6.21.18.1.1.1.4.0.5.15.12.4.3.10.10.9.1.6.5.5.3.0.0.0
51.48.16.22.3.0.19.34.29.1.36.30.12.32.12.29.30.26.14.21.8.12.1.3.10.4.7.17.6.21.8.12.15.15.13.15.7.3.12.11.9.5.5.6.6.3.4.0.3.2.1
use your function to crate the corresponding permutation of the following shoe of cards:
A♠K♠Q♠J♠10♠9♠8♠7♠6♠5♠4♠3♠2♠A♥K♥Q♥J♥10♥9♥8♥7♥6♥5♥4♥3♥2♥A♦K♦Q♦J♦10♦9♦8♦7♦6♦5♦4♦3♦2♦A♣K♣Q♣J♣10♣9♣8♣7♣6♣5♣4♣3♣2♣
Finally create your own 51 digit factorial base number and produce the corresponding permutation of the above shoe
| #Nim | Nim | import algorithm, math, random, sequtils, strutils, unicode
# Representation of a factorial base number with N digits.
type FactorialBaseNumber[N: static Positive] = array[N, int]
#---------------------------------------------------------------------------------------------------
func permutation[T](elements: openArray[T]; n: FactorialBaseNumber): seq[T] =
## Return the permutation of "elements" associated to the factorial base number "n".
result = @elements
for m, g in n:
if g > 0:
result.rotateLeft(m.int..(m + g), -1)
#---------------------------------------------------------------------------------------------------
func incr(n: var FactorialBaseNumber): bool =
## Increment a factorial base number.
## Return false if an overflow occurred.
var base = 1
var k = 1
for i in countdown(n.high, 0):
inc base
inc n[i], k
if n[i] >= base:
n[i] = 0
k = 1
else:
k = 0
result = k == 0
#---------------------------------------------------------------------------------------------------
iterator fbnSeq(n: static Positive): auto =
## Yield the successive factorial base numbers of length "n".
var result: FactorialBaseNumber[n]
while true:
yield result
if not incr(result): break
#---------------------------------------------------------------------------------------------------
func `$`(n: FactorialBaseNumber): string {.inline.} =
## Return the string representation of a factorial base number.
n.join(".")
#———————————————————————————————————————————————————————————————————————————————————————————————————
# Part 1.
echo "Mapping between factorial base numbers and permutations:"
for n in fbnSeq(3):
echo n, " → ", "0123".permutation(n).join()
# Part 2.
echo ""
echo "Generating the permutations of 11 digits:"
const Target = fac(11)
var count = 0
for n in fbnSeq(10):
inc count
let perm = "0123456789A".permutation(n)
if count in 1..3 or count in (Target - 2)..Target:
echo n, " → ", perm.join()
elif count == 4:
echo "[...]"
echo "Number of permutations generated: ", count
echo "Number of permutations expected: ", Target
# Part 3.
const
FBNS = [
"39.49.7.47.29.30.2.12.10.3.29.37.33.17.12.31.29.34.17.25.2.4.25.4.1.14.20.6.21.18.1.1.1.4.0.5.15.12.4.3.10.10.9.1.6.5.5.3.0.0.0",
"51.48.16.22.3.0.19.34.29.1.36.30.12.32.12.29.30.26.14.21.8.12.1.3.10.4.7.17.6.21.8.12.15.15.13.15.7.3.12.11.9.5.5.6.6.3.4.0.3.2.1"]
Cards = ["A♠", "K♠", "Q♠", "J♠", "10♠", "9♠", "8♠", "7♠", "6♠", "5♠", "4♠", "3♠", "2♠",
"A♥", "K♥", "Q♥", "J♥", "10♥", "9♥", "8♥", "7♥", "6♥", "5♥", "4♥", "3♥", "2♥",
"A♦", "K♦", "Q♦", "J♦", "10♦", "9♦", "8♦", "7♦", "6♦", "5♦", "4♦", "3♦", "2♦",
"A♣", "K♣", "Q♣", "J♣", "10♣", "9♣", "8♣", "7♣", "6♣", "5♣", "4♣", "3♣", "2♣"]
M = Cards.len - 1
var fbns: array[3, FactorialBaseNumber[M]]
# Parse the given factorial base numbers.
for i in 0..1:
for j, n in map(FBNS[i].split('.'), parseInt):
fbns[i][j] = n
# Generate a random factorial base number.
randomize()
for j in 0..fbns[3].high:
fbns[2][j] = rand(0..(M - j))
echo ""
echo "Card permutations:"
for i in 0..2:
echo "– for ", fbns[i], ':'
echo " ", Cards.permutation(fbns[i]).join(" ") |
http://rosettacode.org/wiki/Factorions | Factorions |
Definition
A factorion is a natural number that equals the sum of the factorials of its digits.
Example
145 is a factorion in base 10 because:
1! + 4! + 5! = 1 + 24 + 120 = 145
It can be shown (see talk page) that no factorion in base 10 can exceed 1,499,999.
Task
Write a program in your language to demonstrate, by calculating and printing out the factorions, that:
There are 3 factorions in base 9
There are 4 factorions in base 10
There are 5 factorions in base 11
There are 2 factorions in base 12 (up to the same upper bound as for base 10)
See also
Wikipedia article
OEIS:A014080 - Factorions in base 10
OEIS:A193163 - Factorions in base n
| #C | C | #include <stdio.h>
int main() {
int n, b, d;
unsigned long long i, j, sum, fact[12];
// cache factorials from 0 to 11
fact[0] = 1;
for (n = 1; n < 12; ++n) {
fact[n] = fact[n-1] * n;
}
for (b = 9; b <= 12; ++b) {
printf("The factorions for base %d are:\n", b);
for (i = 1; i < 1500000; ++i) {
sum = 0;
j = i;
while (j > 0) {
d = j % b;
sum += fact[d];
j /= b;
}
if (sum == i) printf("%llu ", i);
}
printf("\n\n");
}
return 0;
} |
http://rosettacode.org/wiki/Factorions | Factorions |
Definition
A factorion is a natural number that equals the sum of the factorials of its digits.
Example
145 is a factorion in base 10 because:
1! + 4! + 5! = 1 + 24 + 120 = 145
It can be shown (see talk page) that no factorion in base 10 can exceed 1,499,999.
Task
Write a program in your language to demonstrate, by calculating and printing out the factorions, that:
There are 3 factorions in base 9
There are 4 factorions in base 10
There are 5 factorions in base 11
There are 2 factorions in base 12 (up to the same upper bound as for base 10)
See also
Wikipedia article
OEIS:A014080 - Factorions in base 10
OEIS:A193163 - Factorions in base n
| #C.2B.2B | C++ | #include <iostream>
class factorion_t {
public:
factorion_t() {
f[0] = 1u;
for (uint n = 1u; n < 12u; n++)
f[n] = f[n - 1] * n;
}
bool operator()(uint i, uint b) const {
uint sum = 0;
for (uint j = i; j > 0u; j /= b)
sum += f[j % b];
return sum == i;
}
private:
ulong f[12]; //< cache factorials from 0 to 11
};
int main() {
factorion_t factorion;
for (uint b = 9u; b <= 12u; ++b) {
std::cout << "factorions for base " << b << ':';
for (uint i = 1u; i < 1500000u; ++i)
if (factorion(i, b))
std::cout << ' ' << i;
std::cout << std::endl;
}
return 0;
} |
http://rosettacode.org/wiki/Filter | Filter | Task
Select certain elements from an Array into a new Array in a generic way.
To demonstrate, select all even numbers from an Array.
As an option, give a second solution which filters destructively,
by modifying the original Array rather than creating a new Array.
| #Slate | Slate | #(1 2 3 4 5) select: [| :number | number isEven]. |
http://rosettacode.org/wiki/Faces_from_a_mesh | Faces from a mesh | A mesh defining a surface has uniquely numbered vertices, and named,
simple-polygonal faces described usually by an ordered list of edge numbers
going around the face,
For example:
External image of two faces
Rough textual version without edges:
1
17
7 A
B
11
23
A is the triangle (1, 11, 7), or equally (7, 11, 1), going anti-clockwise, or
any of all the rotations of those ordered vertices.
1
7 A
11
B is the four-sided face (1, 17, 23, 11), or equally (23, 17, 1, 11) or any
of their rotations.
1
17
B
11
23
Let's call the above the perimeter format as it traces around the perimeter.
A second format
A separate algorithm returns polygonal faces consisting of a face name and an unordered
set of edge definitions for each face.
A single edge is described by the vertex numbers at its two ends, always in
ascending order.
All edges for the face are given, but in an undefined order.
For example face A could be described by the edges (1, 11), (7, 11), and (1, 7)
(The order of each vertex number in an edge is ascending, but the order in
which the edges are stated is arbitrary).
Similarly face B could be described by the edges (11, 23), (1, 17), (17, 23),
and (1, 11) in arbitrary order of the edges.
Let's call this second format the edge format.
Task
1. Write a routine to check if two perimeter formatted faces have the same perimeter. Use it to check if the following pairs of perimeters are the same:
Q: (8, 1, 3)
R: (1, 3, 8)
U: (18, 8, 14, 10, 12, 17, 19)
V: (8, 14, 10, 12, 17, 19, 18)
2. Write a routine and use it to transform the following faces from edge to perimeter format.
E: {(1, 11), (7, 11), (1, 7)}
F: {(11, 23), (1, 17), (17, 23), (1, 11)}
G: {(8, 14), (17, 19), (10, 12), (10, 14), (12, 17), (8, 18), (18, 19)}
H: {(1, 3), (9, 11), (3, 11), (1, 11)}
Show your output here.
| #zkl | zkl | fcn perimSame(p1, p2){
if(p1.len() != p2.len()) return(False);
False == p1.filter1('wrap(p){ (not p2.holds(p)) })
}
fcn edge_to_periphery(faces){
edges:=faces.copy().sort(fcn(a,b){ if(a[0]!=b[0]) a[0]<b[0] else a[1]<b[1] });
p,last := ( if(edges) edges.pop(0).copy() else T ), ( p and p[-1] or Void );
while(edges){
foreach i,j in (edges){
if (i==last){ p.append( last=j ); edges.del(__iWalker.idx); break; }
else if(j==last){ p.append( last=i ); edges.del(__iWalker.idx); break; }
}
fallthrough{ return(">>>Error! Invalid edge format<<<") }
}
p[0,-1] // last element not part of result
} |
http://rosettacode.org/wiki/FizzBuzz | FizzBuzz | Task
Write a program that prints the integers from 1 to 100 (inclusive).
But:
for multiples of three, print Fizz (instead of the number)
for multiples of five, print Buzz (instead of the number)
for multiples of both three and five, print FizzBuzz (instead of the number)
The FizzBuzz problem was presented as the lowest level of comprehension required to illustrate adequacy.
Also see
(a blog) dont-overthink-fizzbuzz
(a blog) fizzbuzz-the-programmers-stairway-to-heaven
| #Picat | Picat | fizzbuzz_map =>
println(fizzbuzz_map),
FB = [I : I in 1..100],
Map = [(3="Fizz"),(5="Buzz"),(15="FizzBuzz")],
foreach(I in FB, K=V in Map)
if I mod K == 0 then
FB[I] := V
end
end,
println(FB). |
http://rosettacode.org/wiki/Exponentiation_with_infix_operators_in_(or_operating_on)_the_base | Exponentiation with infix operators in (or operating on) the base | (Many programming languages, especially those with extended─precision integer arithmetic, usually
support one of **, ^, ↑ or some such for exponentiation.)
Some languages treat/honor infix operators when performing exponentiation (raising
numbers to some power by the language's exponentiation operator, if the computer
programming language has one).
Other programming languages may make use of the POW or some other BIF
(Built─In Ffunction), or some other library service.
If your language's exponentiation operator is not one of the usual ones, please comment on how to recognize it.
This task will deal with the case where there is some form of an infix operator operating
in (or operating on) the base.
Example
A negative five raised to the 3rd power could be specified as:
-5 ** 3 or as
-(5) ** 3 or as
(-5) ** 3 or as something else
(Not all computer programming languages have an exponential operator and/or support these syntax expression(s).
Task
compute and display exponentiation with a possible infix operator, whether specified and/or implied/inferred.
Raise the following numbers (integer or real):
-5 and
+5
to the following powers:
2nd and
3rd
using the following expressions (if applicable in your language):
-x**p
-(x)**p
(-x)**p
-(x**p)
Show here (on this page) the four (or more) types of symbolic expressions for each number and power.
Try to present the results in the same format/manner as the other programming entries to make any differences apparent.
The variables may be of any type(s) that is/are applicable in your language.
Related tasks
Exponentiation order
Exponentiation operator
Arbitrary-precision integers (included)
Parsing/RPN to infix conversion
Operator precedence
References
Wikipedia: Order of operations in Programming languages
| #Perl | Perl | use strict;
use warnings;
use Sub::Infix;
BEGIN { *e = infix { $_[0] ** $_[1] } }; # operator needs to be defined at compile time
my @eqns = ('1 + -$xOP$p', '1 + (-$x)OP$p', '1 + (-($x)OP$p)', '(1 + -$x)OP$p', '1 + -($xOP$p)');
for my $op ('**', '/e/', '|e|') {
for ( [-5, 2], [-5, 3], [5, 2], [5, 3] ) {
my( $x, $p, $eqn ) = @$_;
printf 'x: %2d p: %2d |', $x, $p;
$eqn = s/OP/$op/gr and printf '%17s %4d |', $eqn, eval $eqn for @eqns;
print "\n";
}
print "\n";
} |
http://rosettacode.org/wiki/Exponentiation_with_infix_operators_in_(or_operating_on)_the_base | Exponentiation with infix operators in (or operating on) the base | (Many programming languages, especially those with extended─precision integer arithmetic, usually
support one of **, ^, ↑ or some such for exponentiation.)
Some languages treat/honor infix operators when performing exponentiation (raising
numbers to some power by the language's exponentiation operator, if the computer
programming language has one).
Other programming languages may make use of the POW or some other BIF
(Built─In Ffunction), or some other library service.
If your language's exponentiation operator is not one of the usual ones, please comment on how to recognize it.
This task will deal with the case where there is some form of an infix operator operating
in (or operating on) the base.
Example
A negative five raised to the 3rd power could be specified as:
-5 ** 3 or as
-(5) ** 3 or as
(-5) ** 3 or as something else
(Not all computer programming languages have an exponential operator and/or support these syntax expression(s).
Task
compute and display exponentiation with a possible infix operator, whether specified and/or implied/inferred.
Raise the following numbers (integer or real):
-5 and
+5
to the following powers:
2nd and
3rd
using the following expressions (if applicable in your language):
-x**p
-(x)**p
(-x)**p
-(x**p)
Show here (on this page) the four (or more) types of symbolic expressions for each number and power.
Try to present the results in the same format/manner as the other programming entries to make any differences apparent.
The variables may be of any type(s) that is/are applicable in your language.
Related tasks
Exponentiation order
Exponentiation operator
Arbitrary-precision integers (included)
Parsing/RPN to infix conversion
Operator precedence
References
Wikipedia: Order of operations in Programming languages
| #Phix | Phix | for x=-5 to 5 by 10 do
for p=2 to 3 do
printf(1,"x = %2d, p = %d, power(-x,p) = %4d, -power(x,p) = %4d\n",{x,p,power(-x,p),-power(x,p)})
end for
end for
|
http://rosettacode.org/wiki/Fibonacci_sequence | Fibonacci sequence | The Fibonacci sequence is a sequence Fn of natural numbers defined recursively:
F0 = 0
F1 = 1
Fn = Fn-1 + Fn-2, if n>1
Task
Write a function to generate the nth Fibonacci number.
Solutions can be iterative or recursive (though recursive solutions are generally considered too slow and are mostly used as an exercise in recursion).
The sequence is sometimes extended into negative numbers by using a straightforward inverse of the positive definition:
Fn = Fn+2 - Fn+1, if n<0
support for negative n in the solution is optional.
Related tasks
Fibonacci n-step number sequences
Leonardo numbers
References
Wikipedia, Fibonacci number
Wikipedia, Lucas number
MathWorld, Fibonacci Number
Some identities for r-Fibonacci numbers
OEIS Fibonacci numbers
OEIS Lucas numbers
| #Fexl | Fexl |
# (fib n) = the nth Fibonacci number
\fib=
(
\loop==
(\x\y\n
le n 0 x;
\z=(+ x y)
\n=(- n 1)
loop y z n
)
loop 0 1
)
# Now test it:
for 0 20 (\n say (fib n))
|
http://rosettacode.org/wiki/Factors_of_an_integer | Factors of an integer |
Basic Data Operation
This is a basic data operation. It represents a fundamental action on a basic data type.
You may see other such operations in the Basic Data Operations category, or:
Integer Operations
Arithmetic |
Comparison
Boolean Operations
Bitwise |
Logical
String Operations
Concatenation |
Interpolation |
Comparison |
Matching
Memory Operations
Pointers & references |
Addresses
Task
Compute the factors of a positive integer.
These factors are the positive integers by which the number being factored can be divided to yield a positive integer result.
(Though the concepts function correctly for zero and negative integers, the set of factors of zero has countably infinite members, and the factors of negative integers can be obtained from the factors of related positive numbers without difficulty; this task does not require handling of either of these cases).
Note that every prime number has two factors: 1 and itself.
Related tasks
count in factors
prime decomposition
Sieve of Eratosthenes
primality by trial division
factors of a Mersenne number
trial factoring of a Mersenne number
partition an integer X into N primes
sequence of primes by Trial Division
sequence: smallest number greater than previous term with exactly n divisors
| #Oz | Oz | declare
fun {Factors N}
Sqr = {Float.toInt {Sqrt {Int.toFloat N}}}
Fs = for X in 1..Sqr append:App do
if N mod X == 0 then
CoFactor = N div X
in
if CoFactor == X then %% avoid duplicate factor
{App [X]} %% when N is a square number
else
{App [X CoFactor]}
end
end
end
in
{Sort Fs Value.'<'}
end
in
{Show {Factors 53}} |
http://rosettacode.org/wiki/Extreme_floating_point_values | Extreme floating point values | The IEEE floating point specification defines certain 'extreme' floating point values such as minus zero, -0.0, a value distinct from plus zero; not a number, NaN; and plus and minus infinity.
The task is to use expressions involving other 'normal' floating point values in your language to calculate these, (and maybe other), extreme floating point values in your language and assign them to variables.
Print the values of these variables if possible; and show some arithmetic with these values and variables.
If your language can directly enter these extreme floating point values then show it.
See also
What Every Computer Scientist Should Know About Floating-Point Arithmetic
Related tasks
Infinity
Detect division by zero
Literals/Floating point
| #Eiffel | Eiffel |
class
APPLICATION
inherit
ARGUMENTS
create
make
feature {NONE} -- Initialization
make
-- Run application.
local
negInf, posInf, negZero, nan: REAL_64
do
negInf := -1. / 0. -- also {REAL_64}.negative_infinity
posInf := 1. / 0. -- also {REAL_64}.positive_infinity
negZero := -1. / posInf
nan := 0. / 0. -- also {REAL_64}.nan
print("Negative Infinity: ") print(negInf) print("%N")
print("Positive Infinity: ") print(posInf) print("%N")
print("Negative Zero: ") print(negZero) print("%N")
print("NaN: ") print(nan) print("%N%N")
print("1.0 + Infinity = ") print((1.0 + posInf)) print("%N")
print("1.0 - Infinity = ") print((1.0 - posInf)) print("%N")
print("-Infinity + Infinity = ") print((negInf + posInf)) print("%N")
print("-0.0 * Infinity = ") print((negZero * posInf)) print("%N")
print("NaN + NaN = ") print((nan + nan)) print("%N")
print("(NaN = NaN) = ") print((nan = nan)) print("%N")
print("(0.0 = -0.0) = ") print((0.0 = negZero)) print("%N")
end
end |
http://rosettacode.org/wiki/Factorial_base_numbers_indexing_permutations_of_a_collection | Factorial base numbers indexing permutations of a collection | You need a random arrangement of a deck of cards, you are sick of lame ways of doing this. This task is a super-cool way of doing this using factorial base numbers.
The first 25 factorial base numbers in increasing order are: 0.0.0, 0.0.1, 0.1.0, 0.1.1, 0.2.0, 0.2.1, 1.0.0, 1.0.1, 1.1.0, 1.1.1,1.2.0, 1.2.1, 2.0.0, 2.0.1, 2.1.0, 2.1.1, 2.2.0, 2.2.1, 3.0.0, 3.0.1, 3.1.0, 3.1.1, 3.2.0, 3.2.1, 1.0.0.0
Observe that the least significant digit is base 2 the next base 3, in general an n-digit factorial base number has digits n..1 in base n+1..2.
I want to produce a 1 to 1 mapping between these numbers and permutations:-
0.0.0 -> 0123
0.0.1 -> 0132
0.1.0 -> 0213
0.1.1 -> 0231
0.2.0 -> 0312
0.2.1 -> 0321
1.0.0 -> 1023
1.0.1 -> 1032
1.1.0 -> 1203
1.1.1 -> 1230
1.2.0 -> 1302
1.2.1 -> 1320
2.0.0 -> 2013
2.0.1 -> 2031
2.1.0 -> 2103
2.1.1 -> 2130
2.2.0 -> 2301
2.2.1 -> 2310
3.0.0 -> 3012
3.0.1 -> 3021
3.1.0 -> 3102
3.1.1 -> 3120
3.2.0 -> 3201
3.2.1 -> 3210
The following psudo-code will do this:
Starting with m=0 and Ω, an array of elements to be permutated, for each digit g starting with the most significant digit in the factorial base number.
If g is greater than zero, rotate the elements from m to m+g in Ω (see example)
Increment m and repeat the first step using the next most significant digit until the factorial base number is exhausted.
For example: using the factorial base number 2.0.1 and Ω = 0 1 2 3 where place 0 in both is the most significant (left-most) digit/element.
Step 1: m=0 g=2; Rotate places 0 through 2. 0 1 2 3 becomes 2 0 1 3
Step 2: m=1 g=0; No action.
Step 3: m=2 g=1; Rotate places 2 through 3. 2 0 1 3 becomes 2 0 3 1
Let me work 2.0.1 and 0123
step 1 n=0 g=2 Ω=2013
step 2 n=1 g=0 so no action
step 3 n=2 g=1 Ω=2031
The task:
First use your function to recreate the above table.
Secondly use your function to generate all permutaions of 11 digits, perhaps count them don't display them, compare this method with
methods in rc's permutations task.
Thirdly here following are two ramdom 51 digit factorial base numbers I prepared earlier:
39.49.7.47.29.30.2.12.10.3.29.37.33.17.12.31.29.34.17.25.2.4.25.4.1.14.20.6.21.18.1.1.1.4.0.5.15.12.4.3.10.10.9.1.6.5.5.3.0.0.0
51.48.16.22.3.0.19.34.29.1.36.30.12.32.12.29.30.26.14.21.8.12.1.3.10.4.7.17.6.21.8.12.15.15.13.15.7.3.12.11.9.5.5.6.6.3.4.0.3.2.1
use your function to crate the corresponding permutation of the following shoe of cards:
A♠K♠Q♠J♠10♠9♠8♠7♠6♠5♠4♠3♠2♠A♥K♥Q♥J♥10♥9♥8♥7♥6♥5♥4♥3♥2♥A♦K♦Q♦J♦10♦9♦8♦7♦6♦5♦4♦3♦2♦A♣K♣Q♣J♣10♣9♣8♣7♣6♣5♣4♣3♣2♣
Finally create your own 51 digit factorial base number and produce the corresponding permutation of the above shoe
| #Perl | Perl | use strict;
use warnings;
use feature 'say';
sub fpermute {
my($f,@a) = @_;
my @f = split /\./, $f;
for (0..$#f) {
my @b = @a[$_ .. $_+$f[$_]];
unshift @b, splice @b, $#b, 1; # rotate(-1)
@a[$_ .. $_+$f[$_]] = @b;
}
join '', @a;
}
sub base {
my($n) = @_;
my @digits;
push(@digits, int $n/$_) and $n = $n % $_ for <6 2 1>; # reverse <1! 2! 3!>
join '.', @digits;
}
say 'Generate table';
for (0..23) {
my $x = base($_);
say $x . ' -> ' . fpermute($x, <0 1 2 3>)
}
say "\nGenerate the given task shuffles";
my @omega = qw<A♠ K♠ Q♠ J♠ 10♠ 9♠ 8♠ 7♠ 6♠ 5♠ 4♠ 3♠ 2♠ A♥ K♥ Q♥ J♥ 10♥ 9♥ 8♥ 7♥ 6♥ 5♥ 4♥ 3♥ 2♥ A♦ K♦ Q♦ J♦ 10♦ 9♦ 8♦ 7♦ 6♦ 5♦ 4♦ 3♦ 2♦ A♣ K♣ Q♣ J♣ 10♣ 9♣ 8♣ 7♣ 6♣ 5♣ 4♣ 3♣ 2♣>;
my @books = (
'39.49.7.47.29.30.2.12.10.3.29.37.33.17.12.31.29.34.17.25.2.4.25.4.1.14.20.6.21.18.1.1.1.4.0.5.15.12.4.3.10.10.9.1.6.5.5.3.0.0.0',
'51.48.16.22.3.0.19.34.29.1.36.30.12.32.12.29.30.26.14.21.8.12.1.3.10.4.7.17.6.21.8.12.15.15.13.15.7.3.12.11.9.5.5.6.6.3.4.0.3.2.1'
);
say "Original deck:";
say join '', @omega;
say "\n$_\n" . fpermute($_,@omega) for @books;
say "\nGenerate a random shuffle";
say my $shoe = join '.', map { int rand($_) } reverse 0..$#omega;
say fpermute($shoe,@omega); |
http://rosettacode.org/wiki/Factorions | Factorions |
Definition
A factorion is a natural number that equals the sum of the factorials of its digits.
Example
145 is a factorion in base 10 because:
1! + 4! + 5! = 1 + 24 + 120 = 145
It can be shown (see talk page) that no factorion in base 10 can exceed 1,499,999.
Task
Write a program in your language to demonstrate, by calculating and printing out the factorions, that:
There are 3 factorions in base 9
There are 4 factorions in base 10
There are 5 factorions in base 11
There are 2 factorions in base 12 (up to the same upper bound as for base 10)
See also
Wikipedia article
OEIS:A014080 - Factorions in base 10
OEIS:A193163 - Factorions in base n
| #Common_Lisp | Common Lisp | (defparameter *bases* '(9 10 11 12))
(defparameter *limit* 1500000)
(defun ! (n) (apply #'* (loop for i from 2 to n collect i)))
(defparameter *digit-factorials* (mapcar #'! (loop for i from 0 to (1- (apply #'max *bases*)) collect i)))
(defun fact (n) (nth n *digit-factorials*))
(defun digit-value (digit)
(let ((decimal (digit-char-p digit)))
(cond ((not (null decimal)) decimal)
((char>= #\Z digit #\A) (+ (char-code digit) (- (char-code #\A)) 10))
((char>= #\z digit #\a) (+ (char-code digit) (- (char-code #\a)) 10))
(t nil))))
(defun factorionp (n &optional (base 10))
(= n (apply #'+
(mapcar #'fact
(map 'list #'digit-value
(write-to-string n :base base))))))
(loop for base in *bases* do
(let ((factorions
(loop for i from 1 while (< i *limit*) if (factorionp i base) collect i)))
(format t "In base ~a there are ~a factorions:~%" base (list-length factorions))
(loop for n in factorions do
(format t "~c~a" #\Tab (write-to-string n :base base))
(if (/= base 10) (format t " (decimal ~a)" n))
(format t "~%"))
(format t "~%"))) |
http://rosettacode.org/wiki/Filter | Filter | Task
Select certain elements from an Array into a new Array in a generic way.
To demonstrate, select all even numbers from an Array.
As an option, give a second solution which filters destructively,
by modifying the original Array rather than creating a new Array.
| #Smalltalk | Smalltalk | #(1 2 3 4 5) select: [:number | number even] |
http://rosettacode.org/wiki/FizzBuzz | FizzBuzz | Task
Write a program that prints the integers from 1 to 100 (inclusive).
But:
for multiples of three, print Fizz (instead of the number)
for multiples of five, print Buzz (instead of the number)
for multiples of both three and five, print FizzBuzz (instead of the number)
The FizzBuzz problem was presented as the lowest level of comprehension required to illustrate adequacy.
Also see
(a blog) dont-overthink-fizzbuzz
(a blog) fizzbuzz-the-programmers-stairway-to-heaven
| #PicoLisp | PicoLisp | (for N 100
(prinl
(or (pack (at (0 . 3) "Fizz") (at (0 . 5) "Buzz")) N) ) )
# Above, we simply count till 100 'prin'-ting number 'at' 3rd ('Fizz'), 5th ('Buzz') and 'pack'-ing 15th number ('FizzBuzz').
# Rest of the times 'N' is printed as it loops in 'for'.
|
http://rosettacode.org/wiki/Exponentiation_with_infix_operators_in_(or_operating_on)_the_base | Exponentiation with infix operators in (or operating on) the base | (Many programming languages, especially those with extended─precision integer arithmetic, usually
support one of **, ^, ↑ or some such for exponentiation.)
Some languages treat/honor infix operators when performing exponentiation (raising
numbers to some power by the language's exponentiation operator, if the computer
programming language has one).
Other programming languages may make use of the POW or some other BIF
(Built─In Ffunction), or some other library service.
If your language's exponentiation operator is not one of the usual ones, please comment on how to recognize it.
This task will deal with the case where there is some form of an infix operator operating
in (or operating on) the base.
Example
A negative five raised to the 3rd power could be specified as:
-5 ** 3 or as
-(5) ** 3 or as
(-5) ** 3 or as something else
(Not all computer programming languages have an exponential operator and/or support these syntax expression(s).
Task
compute and display exponentiation with a possible infix operator, whether specified and/or implied/inferred.
Raise the following numbers (integer or real):
-5 and
+5
to the following powers:
2nd and
3rd
using the following expressions (if applicable in your language):
-x**p
-(x)**p
(-x)**p
-(x**p)
Show here (on this page) the four (or more) types of symbolic expressions for each number and power.
Try to present the results in the same format/manner as the other programming entries to make any differences apparent.
The variables may be of any type(s) that is/are applicable in your language.
Related tasks
Exponentiation order
Exponentiation operator
Arbitrary-precision integers (included)
Parsing/RPN to infix conversion
Operator precedence
References
Wikipedia: Order of operations in Programming languages
| #QB64 | QB64 | For x = -5 To 5 Step 10
For p = 2 To 3
Print "x = "; x; " p ="; p; " ";
Print Using "-x^p is ####"; -x ^ p;
Print Using ", -(x)^p is ####"; -(x) ^ p;
Print Using ", (-x)^p is ####"; (-x) ^ p;
Print Using ", -(x^p) is ####"; -(x ^ p)
Next
Next |
http://rosettacode.org/wiki/Exponentiation_with_infix_operators_in_(or_operating_on)_the_base | Exponentiation with infix operators in (or operating on) the base | (Many programming languages, especially those with extended─precision integer arithmetic, usually
support one of **, ^, ↑ or some such for exponentiation.)
Some languages treat/honor infix operators when performing exponentiation (raising
numbers to some power by the language's exponentiation operator, if the computer
programming language has one).
Other programming languages may make use of the POW or some other BIF
(Built─In Ffunction), or some other library service.
If your language's exponentiation operator is not one of the usual ones, please comment on how to recognize it.
This task will deal with the case where there is some form of an infix operator operating
in (or operating on) the base.
Example
A negative five raised to the 3rd power could be specified as:
-5 ** 3 or as
-(5) ** 3 or as
(-5) ** 3 or as something else
(Not all computer programming languages have an exponential operator and/or support these syntax expression(s).
Task
compute and display exponentiation with a possible infix operator, whether specified and/or implied/inferred.
Raise the following numbers (integer or real):
-5 and
+5
to the following powers:
2nd and
3rd
using the following expressions (if applicable in your language):
-x**p
-(x)**p
(-x)**p
-(x**p)
Show here (on this page) the four (or more) types of symbolic expressions for each number and power.
Try to present the results in the same format/manner as the other programming entries to make any differences apparent.
The variables may be of any type(s) that is/are applicable in your language.
Related tasks
Exponentiation order
Exponentiation operator
Arbitrary-precision integers (included)
Parsing/RPN to infix conversion
Operator precedence
References
Wikipedia: Order of operations in Programming languages
| #R | R | expressions <- alist(-x ^ p, -(x) ^ p, (-x) ^ p, -(x ^ p))
x <- c(-5, -5, 5, 5)
p <- c(2, 3, 2, 3)
output <- data.frame(x,
p,
setNames(lapply(expressions, eval), sapply(expressions, deparse)),
check.names = FALSE)
print(output, row.names = FALSE) |
http://rosettacode.org/wiki/Exponentiation_with_infix_operators_in_(or_operating_on)_the_base | Exponentiation with infix operators in (or operating on) the base | (Many programming languages, especially those with extended─precision integer arithmetic, usually
support one of **, ^, ↑ or some such for exponentiation.)
Some languages treat/honor infix operators when performing exponentiation (raising
numbers to some power by the language's exponentiation operator, if the computer
programming language has one).
Other programming languages may make use of the POW or some other BIF
(Built─In Ffunction), or some other library service.
If your language's exponentiation operator is not one of the usual ones, please comment on how to recognize it.
This task will deal with the case where there is some form of an infix operator operating
in (or operating on) the base.
Example
A negative five raised to the 3rd power could be specified as:
-5 ** 3 or as
-(5) ** 3 or as
(-5) ** 3 or as something else
(Not all computer programming languages have an exponential operator and/or support these syntax expression(s).
Task
compute and display exponentiation with a possible infix operator, whether specified and/or implied/inferred.
Raise the following numbers (integer or real):
-5 and
+5
to the following powers:
2nd and
3rd
using the following expressions (if applicable in your language):
-x**p
-(x)**p
(-x)**p
-(x**p)
Show here (on this page) the four (or more) types of symbolic expressions for each number and power.
Try to present the results in the same format/manner as the other programming entries to make any differences apparent.
The variables may be of any type(s) that is/are applicable in your language.
Related tasks
Exponentiation order
Exponentiation operator
Arbitrary-precision integers (included)
Parsing/RPN to infix conversion
Operator precedence
References
Wikipedia: Order of operations in Programming languages
| #Raku | Raku | sub infix:<↑> is looser(&prefix:<->) { $^a ** $^b }
sub infix:<^> is looser(&infix:<->) { $^a ** $^b }
use MONKEY;
for 'Default precedence: infix exponentiation is tighter (higher) precedence than unary negation.',
('1 + -$x**$p', '1 + (-$x)**$p', '1 + (-($x)**$p)', '(1 + -$x)**$p', '1 + -($x**$p)'),
"\nEasily modified: custom loose infix exponentiation is looser (lower) precedence than unary negation.",
('1 + -$x↑$p ', '1 + (-$x)↑$p ', '1 + (-($x)↑$p) ', '(1 + -$x)↑$p ', '1 + -($x↑$p) '),
"\nEven moreso: custom looser infix exponentiation is looser (lower) precedence than infix subtraction.",
('1 + -$x^$p ', '1 + (-$x)^$p ', '1 + (-($x)^$p) ', '(1 + -$x)^$p ', '1 + -($x^$p) ')
-> $message, $ops {
say $message;
for -5, 5 X 2, 3 -> ($x, $p) {
printf "x = %2d p = %d", $x, $p;
-> $op { printf " │ %s = %4d", $op, EVAL $op } for |$ops;
print "\n";
}
} |
http://rosettacode.org/wiki/Fibonacci_sequence | Fibonacci sequence | The Fibonacci sequence is a sequence Fn of natural numbers defined recursively:
F0 = 0
F1 = 1
Fn = Fn-1 + Fn-2, if n>1
Task
Write a function to generate the nth Fibonacci number.
Solutions can be iterative or recursive (though recursive solutions are generally considered too slow and are mostly used as an exercise in recursion).
The sequence is sometimes extended into negative numbers by using a straightforward inverse of the positive definition:
Fn = Fn+2 - Fn+1, if n<0
support for negative n in the solution is optional.
Related tasks
Fibonacci n-step number sequences
Leonardo numbers
References
Wikipedia, Fibonacci number
Wikipedia, Lucas number
MathWorld, Fibonacci Number
Some identities for r-Fibonacci numbers
OEIS Fibonacci numbers
OEIS Lucas numbers
| #Fish | Fish | 10::n' 'o&+&$10. |
http://rosettacode.org/wiki/Factors_of_an_integer | Factors of an integer |
Basic Data Operation
This is a basic data operation. It represents a fundamental action on a basic data type.
You may see other such operations in the Basic Data Operations category, or:
Integer Operations
Arithmetic |
Comparison
Boolean Operations
Bitwise |
Logical
String Operations
Concatenation |
Interpolation |
Comparison |
Matching
Memory Operations
Pointers & references |
Addresses
Task
Compute the factors of a positive integer.
These factors are the positive integers by which the number being factored can be divided to yield a positive integer result.
(Though the concepts function correctly for zero and negative integers, the set of factors of zero has countably infinite members, and the factors of negative integers can be obtained from the factors of related positive numbers without difficulty; this task does not require handling of either of these cases).
Note that every prime number has two factors: 1 and itself.
Related tasks
count in factors
prime decomposition
Sieve of Eratosthenes
primality by trial division
factors of a Mersenne number
trial factoring of a Mersenne number
partition an integer X into N primes
sequence of primes by Trial Division
sequence: smallest number greater than previous term with exactly n divisors
| #Panda | Panda | fun factor(n) type integer->integer
f where n.mod(1..n=>f)==0
45.factor |
http://rosettacode.org/wiki/Extreme_floating_point_values | Extreme floating point values | The IEEE floating point specification defines certain 'extreme' floating point values such as minus zero, -0.0, a value distinct from plus zero; not a number, NaN; and plus and minus infinity.
The task is to use expressions involving other 'normal' floating point values in your language to calculate these, (and maybe other), extreme floating point values in your language and assign them to variables.
Print the values of these variables if possible; and show some arithmetic with these values and variables.
If your language can directly enter these extreme floating point values then show it.
See also
What Every Computer Scientist Should Know About Floating-Point Arithmetic
Related tasks
Infinity
Detect division by zero
Literals/Floating point
| #Euphoria | Euphoria | constant inf = 1E400
constant minus_inf = -inf
constant nan = 0*inf
printf(1,"positive infinity: %f\n", inf)
printf(1,"negative infinity: %f\n", minus_inf)
printf(1,"not a number: %f\n", nan)
-- some arithmetic
printf(1,"+inf + 2.0 = %f\n", inf + 2.0)
printf(1,"+inf - 10.1 = %f\n", inf - 10.1)
printf(1,"+inf + -inf = %f\n", inf + minus_inf)
printf(1,"0.0 * +inf = %f\n", 0.0 * inf)
printf(1,"NaN + 1.0 = %f\n", nan + 1.0)
printf(1,"NaN + NaN = %f\n", nan + nan) |
http://rosettacode.org/wiki/Extreme_floating_point_values | Extreme floating point values | The IEEE floating point specification defines certain 'extreme' floating point values such as minus zero, -0.0, a value distinct from plus zero; not a number, NaN; and plus and minus infinity.
The task is to use expressions involving other 'normal' floating point values in your language to calculate these, (and maybe other), extreme floating point values in your language and assign them to variables.
Print the values of these variables if possible; and show some arithmetic with these values and variables.
If your language can directly enter these extreme floating point values then show it.
See also
What Every Computer Scientist Should Know About Floating-Point Arithmetic
Related tasks
Infinity
Detect division by zero
Literals/Floating point
| #F.23 | F# |
0.0/0.0 //->nan
0.0/(-0.0) //->nan
1.0/infinity //->0.0
1.0/(-infinity) //->0.0
1.0/0.0 //->infinity
1.0/(-0.0) //->-infinity
-infinity<infinity //->true
(-0.0)<0.0 //->false
|
http://rosettacode.org/wiki/Factorial_base_numbers_indexing_permutations_of_a_collection | Factorial base numbers indexing permutations of a collection | You need a random arrangement of a deck of cards, you are sick of lame ways of doing this. This task is a super-cool way of doing this using factorial base numbers.
The first 25 factorial base numbers in increasing order are: 0.0.0, 0.0.1, 0.1.0, 0.1.1, 0.2.0, 0.2.1, 1.0.0, 1.0.1, 1.1.0, 1.1.1,1.2.0, 1.2.1, 2.0.0, 2.0.1, 2.1.0, 2.1.1, 2.2.0, 2.2.1, 3.0.0, 3.0.1, 3.1.0, 3.1.1, 3.2.0, 3.2.1, 1.0.0.0
Observe that the least significant digit is base 2 the next base 3, in general an n-digit factorial base number has digits n..1 in base n+1..2.
I want to produce a 1 to 1 mapping between these numbers and permutations:-
0.0.0 -> 0123
0.0.1 -> 0132
0.1.0 -> 0213
0.1.1 -> 0231
0.2.0 -> 0312
0.2.1 -> 0321
1.0.0 -> 1023
1.0.1 -> 1032
1.1.0 -> 1203
1.1.1 -> 1230
1.2.0 -> 1302
1.2.1 -> 1320
2.0.0 -> 2013
2.0.1 -> 2031
2.1.0 -> 2103
2.1.1 -> 2130
2.2.0 -> 2301
2.2.1 -> 2310
3.0.0 -> 3012
3.0.1 -> 3021
3.1.0 -> 3102
3.1.1 -> 3120
3.2.0 -> 3201
3.2.1 -> 3210
The following psudo-code will do this:
Starting with m=0 and Ω, an array of elements to be permutated, for each digit g starting with the most significant digit in the factorial base number.
If g is greater than zero, rotate the elements from m to m+g in Ω (see example)
Increment m and repeat the first step using the next most significant digit until the factorial base number is exhausted.
For example: using the factorial base number 2.0.1 and Ω = 0 1 2 3 where place 0 in both is the most significant (left-most) digit/element.
Step 1: m=0 g=2; Rotate places 0 through 2. 0 1 2 3 becomes 2 0 1 3
Step 2: m=1 g=0; No action.
Step 3: m=2 g=1; Rotate places 2 through 3. 2 0 1 3 becomes 2 0 3 1
Let me work 2.0.1 and 0123
step 1 n=0 g=2 Ω=2013
step 2 n=1 g=0 so no action
step 3 n=2 g=1 Ω=2031
The task:
First use your function to recreate the above table.
Secondly use your function to generate all permutaions of 11 digits, perhaps count them don't display them, compare this method with
methods in rc's permutations task.
Thirdly here following are two ramdom 51 digit factorial base numbers I prepared earlier:
39.49.7.47.29.30.2.12.10.3.29.37.33.17.12.31.29.34.17.25.2.4.25.4.1.14.20.6.21.18.1.1.1.4.0.5.15.12.4.3.10.10.9.1.6.5.5.3.0.0.0
51.48.16.22.3.0.19.34.29.1.36.30.12.32.12.29.30.26.14.21.8.12.1.3.10.4.7.17.6.21.8.12.15.15.13.15.7.3.12.11.9.5.5.6.6.3.4.0.3.2.1
use your function to crate the corresponding permutation of the following shoe of cards:
A♠K♠Q♠J♠10♠9♠8♠7♠6♠5♠4♠3♠2♠A♥K♥Q♥J♥10♥9♥8♥7♥6♥5♥4♥3♥2♥A♦K♦Q♦J♦10♦9♦8♦7♦6♦5♦4♦3♦2♦A♣K♣Q♣J♣10♣9♣8♣7♣6♣5♣4♣3♣2♣
Finally create your own 51 digit factorial base number and produce the corresponding permutation of the above shoe
| #Phix | Phix | with javascript_semantics
function fperm(sequence fbn, omega)
integer m=0
for i=1 to length(fbn) do
integer g = fbn[i]
if g>0 then
omega[m+1..m+g+1] = omega[m+g+1]&omega[m+1..m+g]
end if
m += 1
end for
return omega
end function
function factorial_base_numbers(integer size, bool countOnly)
-- translation of Go
sequence results = {}, res = repeat(0,size)
integer count = 0, n = 0
while true do
integer radix = 2, k = n
while k>0 do
if not countOnly
and radix <= size+1 then
res[size-radix+2] = mod(k,radix)
end if
k = floor(k/radix)
radix += 1
end while
if radix > size+2 then exit end if
count += 1
if not countOnly then
results = append(results, deep_copy(res))
end if
n += 1
end while
return iff(countOnly?count:results)
end function
sequence fbns = factorial_base_numbers(3,false)
for i=1 to length(fbns) do
printf(1,"%v -> %v\n",{fbns[i],fperm(fbns[i],{0,1,2,3})})
end for
printf(1,"\n")
integer count = factorial_base_numbers(10,true)
printf(1,"Permutations generated = %d\n", count)
printf(1," versus factorial(11) = %d\n", factorial(11))
procedure show_cards(sequence s)
printf(1,"\n")
for i=1 to length(s) do
integer c = s[i]-1
string sep = iff(mod(i,13)=0 or i=length(s)?"\n":" ")
puts(1,"AKQJT98765432"[mod(c,13)+1]&"SHDC"[floor(c/13)+1]&sep)
end for
end procedure
function rand_fbn51()
sequence fbn51 = repeat(0,51)
for i=1 to 51 do
fbn51[i] = rand(52-i)
end for
return fbn51
end function
sequence fbn51s = {{39,49, 7,47,29,30, 2,12,10, 3,29,37,33,17,12,31,29,
34,17,25, 2, 4,25, 4, 1,14,20, 6,21,18, 1, 1, 1, 4,
0, 5,15,12, 4, 3,10,10, 9, 1, 6, 5, 5, 3, 0, 0, 0},
{51,48,16,22, 3, 0,19,34,29, 1,36,30,12,32,12,29,30,
26,14,21, 8,12, 1, 3,10, 4, 7,17, 6,21, 8,12,15,15,
13,15, 7, 3,12,11, 9, 5, 5, 6, 6, 3, 4, 0, 3, 2, 1},
rand_fbn51()}
for i=1 to length(fbn51s) do
show_cards(fperm(fbn51s[i],tagset(52)))
end for
|
http://rosettacode.org/wiki/Factorions | Factorions |
Definition
A factorion is a natural number that equals the sum of the factorials of its digits.
Example
145 is a factorion in base 10 because:
1! + 4! + 5! = 1 + 24 + 120 = 145
It can be shown (see talk page) that no factorion in base 10 can exceed 1,499,999.
Task
Write a program in your language to demonstrate, by calculating and printing out the factorions, that:
There are 3 factorions in base 9
There are 4 factorions in base 10
There are 5 factorions in base 11
There are 2 factorions in base 12 (up to the same upper bound as for base 10)
See also
Wikipedia article
OEIS:A014080 - Factorions in base 10
OEIS:A193163 - Factorions in base n
| #Delphi | Delphi |
program Factorions;
{$APPTYPE CONSOLE}
uses
System.SysUtils;
begin
var fact: TArray<UInt64>;
SetLength(fact, 12);
fact[0] := 0;
for var n := 1 to 11 do
fact[n] := fact[n - 1] * n;
for var b := 9 to 12 do
begin
writeln('The factorions for base ', b, ' are:');
for var i := 1 to 1499999 do
begin
var sum := 0;
var j := i;
while j > 0 do
begin
var d := j mod b;
sum := sum + fact[d];
j := j div b;
end;
if sum = i then
writeln(i, ' ');
end;
writeln(#10);
end;
readln;
end. |
http://rosettacode.org/wiki/Factorions | Factorions |
Definition
A factorion is a natural number that equals the sum of the factorials of its digits.
Example
145 is a factorion in base 10 because:
1! + 4! + 5! = 1 + 24 + 120 = 145
It can be shown (see talk page) that no factorion in base 10 can exceed 1,499,999.
Task
Write a program in your language to demonstrate, by calculating and printing out the factorions, that:
There are 3 factorions in base 9
There are 4 factorions in base 10
There are 5 factorions in base 11
There are 2 factorions in base 12 (up to the same upper bound as for base 10)
See also
Wikipedia article
OEIS:A014080 - Factorions in base 10
OEIS:A193163 - Factorions in base n
| #F.23 | F# |
// Factorians. Nigel Galloway: October 22nd., 2021
let N=[|let mutable n=1 in yield n; for g in 1..11 do n<-n*g; yield n|]
let fG n g=let rec fN g=function i when i<n->g+N.[i] |i->fN(g+N.[i%n])(i/n) in fN 0 g
{9..12}|>Seq.iter(fun n->printf $"In base %d{n} Factorians are:"; {1..1500000}|>Seq.iter(fun g->if g=fG n g then printf $" %d{g}"); printfn "")
|
http://rosettacode.org/wiki/Filter | Filter | Task
Select certain elements from an Array into a new Array in a generic way.
To demonstrate, select all even numbers from an Array.
As an option, give a second solution which filters destructively,
by modifying the original Array rather than creating a new Array.
| #SQL | SQL | --Create the original array (table #nos) with numbers from 1 to 10
CREATE TABLE #nos (v INT)
DECLARE @n INT SET @n=1
while @n<=10 BEGIN INSERT INTO #nos VALUES (@n) SET @n=@n+1 END
--Select the subset that are even into the new array (table #evens)
SELECT v INTO #evens FROM #nos WHERE v % 2 = 0
-- Show #evens
SELECT * FROM #evens
-- Clean up so you can edit and repeat:
DROP TABLE #nos
DROP TABLE #evens |
http://rosettacode.org/wiki/FizzBuzz | FizzBuzz | Task
Write a program that prints the integers from 1 to 100 (inclusive).
But:
for multiples of three, print Fizz (instead of the number)
for multiples of five, print Buzz (instead of the number)
for multiples of both three and five, print FizzBuzz (instead of the number)
The FizzBuzz problem was presented as the lowest level of comprehension required to illustrate adequacy.
Also see
(a blog) dont-overthink-fizzbuzz
(a blog) fizzbuzz-the-programmers-stairway-to-heaven
| #Pike | Pike | int main(){
for(int i = 1; i <= 100; i++) {
if(i % 15 == 0) {
write("FizzBuzz\n");
} else if(i % 3 == 0) {
write("Fizz\n");
} else if(i % 5 == 0) {
write("Buzz\n");
} else {
write(i + "\n");
}
}
} |
http://rosettacode.org/wiki/Exponentiation_with_infix_operators_in_(or_operating_on)_the_base | Exponentiation with infix operators in (or operating on) the base | (Many programming languages, especially those with extended─precision integer arithmetic, usually
support one of **, ^, ↑ or some such for exponentiation.)
Some languages treat/honor infix operators when performing exponentiation (raising
numbers to some power by the language's exponentiation operator, if the computer
programming language has one).
Other programming languages may make use of the POW or some other BIF
(Built─In Ffunction), or some other library service.
If your language's exponentiation operator is not one of the usual ones, please comment on how to recognize it.
This task will deal with the case where there is some form of an infix operator operating
in (or operating on) the base.
Example
A negative five raised to the 3rd power could be specified as:
-5 ** 3 or as
-(5) ** 3 or as
(-5) ** 3 or as something else
(Not all computer programming languages have an exponential operator and/or support these syntax expression(s).
Task
compute and display exponentiation with a possible infix operator, whether specified and/or implied/inferred.
Raise the following numbers (integer or real):
-5 and
+5
to the following powers:
2nd and
3rd
using the following expressions (if applicable in your language):
-x**p
-(x)**p
(-x)**p
-(x**p)
Show here (on this page) the four (or more) types of symbolic expressions for each number and power.
Try to present the results in the same format/manner as the other programming entries to make any differences apparent.
The variables may be of any type(s) that is/are applicable in your language.
Related tasks
Exponentiation order
Exponentiation operator
Arbitrary-precision integers (included)
Parsing/RPN to infix conversion
Operator precedence
References
Wikipedia: Order of operations in Programming languages
| #REXX | REXX | /*REXX program shows exponentition with an infix operator (implied and/or specified).*/
_= '─'; ! = '║'; mJunct= '─╫─'; bJunct= '─╨─' /*define some special glyphs. */
say @(' x ', 5) @(" p ", 5) !
say @('value', 5) @("value", 5) copies(! @('expression',10) @("result",6)" ", 4)
say @('' , 5, _) @("", 5, _)copies(mJunct || @('', 10, _) @("", 6, _) , 4)
do x=-5 to 5 by 10 /*assign -5 and 5 to X. */
do p= 2 to 3 /*assign 2 and 3 to P. */
a = -x**p ; b = -(x)**p ; c = (-x)**p ; d = -(x**p)
ae= '-x**p'; be= "-(x)**p"; ce= '(-x)**p'; de= "-(x**p)"
say @(x,5) @(p,5) ! @(ae, 10) right(a, 5)" " ,
! @(be, 10) right(b, 5)" " ,
! @(ce, 10) right(c, 5)" " ,
! @(de, 10) right(d, 5)
end /*p*/
end /*x*/
say @('' , 5, _) @('', 5, _)copies(bJunct || @('', 10, _) @('', 6, _) , 4)
exit 0 /*stick a fork in it, we're all done. */
/*──────────────────────────────────────────────────────────────────────────────────────*/
@: parse arg txt, w, fill; if fill=='' then fill= ' '; return center( txt, w, fill)
|
http://rosettacode.org/wiki/Exponentiation_with_infix_operators_in_(or_operating_on)_the_base | Exponentiation with infix operators in (or operating on) the base | (Many programming languages, especially those with extended─precision integer arithmetic, usually
support one of **, ^, ↑ or some such for exponentiation.)
Some languages treat/honor infix operators when performing exponentiation (raising
numbers to some power by the language's exponentiation operator, if the computer
programming language has one).
Other programming languages may make use of the POW or some other BIF
(Built─In Ffunction), or some other library service.
If your language's exponentiation operator is not one of the usual ones, please comment on how to recognize it.
This task will deal with the case where there is some form of an infix operator operating
in (or operating on) the base.
Example
A negative five raised to the 3rd power could be specified as:
-5 ** 3 or as
-(5) ** 3 or as
(-5) ** 3 or as something else
(Not all computer programming languages have an exponential operator and/or support these syntax expression(s).
Task
compute and display exponentiation with a possible infix operator, whether specified and/or implied/inferred.
Raise the following numbers (integer or real):
-5 and
+5
to the following powers:
2nd and
3rd
using the following expressions (if applicable in your language):
-x**p
-(x)**p
(-x)**p
-(x**p)
Show here (on this page) the four (or more) types of symbolic expressions for each number and power.
Try to present the results in the same format/manner as the other programming entries to make any differences apparent.
The variables may be of any type(s) that is/are applicable in your language.
Related tasks
Exponentiation order
Exponentiation operator
Arbitrary-precision integers (included)
Parsing/RPN to infix conversion
Operator precedence
References
Wikipedia: Order of operations in Programming languages
| #Ruby | Ruby | nums = [-5, 5]
pows = [2, 3]
nums.product(pows) do |x, p|
puts "x = #{x} p = #{p}\t-x**p #{-x**p}\t-(x)**p #{-(x)**p}\t(-x)**p #{ (-x)**p}\t-(x**p) #{-(x**p)}"
end
|
http://rosettacode.org/wiki/Fibonacci_sequence | Fibonacci sequence | The Fibonacci sequence is a sequence Fn of natural numbers defined recursively:
F0 = 0
F1 = 1
Fn = Fn-1 + Fn-2, if n>1
Task
Write a function to generate the nth Fibonacci number.
Solutions can be iterative or recursive (though recursive solutions are generally considered too slow and are mostly used as an exercise in recursion).
The sequence is sometimes extended into negative numbers by using a straightforward inverse of the positive definition:
Fn = Fn+2 - Fn+1, if n<0
support for negative n in the solution is optional.
Related tasks
Fibonacci n-step number sequences
Leonardo numbers
References
Wikipedia, Fibonacci number
Wikipedia, Lucas number
MathWorld, Fibonacci Number
Some identities for r-Fibonacci numbers
OEIS Fibonacci numbers
OEIS Lucas numbers
| #FOCAL | FOCAL | 01.10 TYPE "FIBONACCI NUMBERS" !
01.20 ASK "N =", N
01.30 SET A=0
01.40 SET B=1
01.50 FOR I=2,N; DO 2.0
01.60 TYPE "F(N) ", %8, B, !
01.70 QUIT
02.10 SET T=B
02.20 SET B=A+B
02.30 SET A=T |
http://rosettacode.org/wiki/Factors_of_an_integer | Factors of an integer |
Basic Data Operation
This is a basic data operation. It represents a fundamental action on a basic data type.
You may see other such operations in the Basic Data Operations category, or:
Integer Operations
Arithmetic |
Comparison
Boolean Operations
Bitwise |
Logical
String Operations
Concatenation |
Interpolation |
Comparison |
Matching
Memory Operations
Pointers & references |
Addresses
Task
Compute the factors of a positive integer.
These factors are the positive integers by which the number being factored can be divided to yield a positive integer result.
(Though the concepts function correctly for zero and negative integers, the set of factors of zero has countably infinite members, and the factors of negative integers can be obtained from the factors of related positive numbers without difficulty; this task does not require handling of either of these cases).
Note that every prime number has two factors: 1 and itself.
Related tasks
count in factors
prime decomposition
Sieve of Eratosthenes
primality by trial division
factors of a Mersenne number
trial factoring of a Mersenne number
partition an integer X into N primes
sequence of primes by Trial Division
sequence: smallest number greater than previous term with exactly n divisors
| #PARI.2FGP | PARI/GP | divisors(n) |
http://rosettacode.org/wiki/Extreme_floating_point_values | Extreme floating point values | The IEEE floating point specification defines certain 'extreme' floating point values such as minus zero, -0.0, a value distinct from plus zero; not a number, NaN; and plus and minus infinity.
The task is to use expressions involving other 'normal' floating point values in your language to calculate these, (and maybe other), extreme floating point values in your language and assign them to variables.
Print the values of these variables if possible; and show some arithmetic with these values and variables.
If your language can directly enter these extreme floating point values then show it.
See also
What Every Computer Scientist Should Know About Floating-Point Arithmetic
Related tasks
Infinity
Detect division by zero
Literals/Floating point
| #Factor | Factor | -0. . ! -0.0 literal negative zero
0. neg . ! -0.0 neg works with floating point zeros
0. -1. * . ! -0.0 calculating negative zero
1/0. . ! 1/0. literal positive infinity
1e3 1e3 ^ . ! 1/0. calculating positive infinity
-1/0. . ! -1/0. literal negative infinity
-1. 1e3 1e3 ^ * . ! -1/0. calculating negative infinity
-1/0. neg . ! 1/0. neg works with the inifinites
0/0. . ! NAN: 8000000000000 literal NaN, configurable with
! arbitrary 64-bit hex payload
1/0. 1/0. - . ! NAN: 8000000000000 calculating NaN by subtracting
! infinity from infinity |
http://rosettacode.org/wiki/Extreme_floating_point_values | Extreme floating point values | The IEEE floating point specification defines certain 'extreme' floating point values such as minus zero, -0.0, a value distinct from plus zero; not a number, NaN; and plus and minus infinity.
The task is to use expressions involving other 'normal' floating point values in your language to calculate these, (and maybe other), extreme floating point values in your language and assign them to variables.
Print the values of these variables if possible; and show some arithmetic with these values and variables.
If your language can directly enter these extreme floating point values then show it.
See also
What Every Computer Scientist Should Know About Floating-Point Arithmetic
Related tasks
Infinity
Detect division by zero
Literals/Floating point
| #Forth | Forth | 1e 0e f/ f. \ inf
-1e 0e f/ f. \ inf (output bug: should say "-inf")
-1e 0e f/ f0< . \ -1 (true, it is -inf)
0e 0e f/ f. \ nan
-1e 0e f/ 1/f f0< . \ 0 (false, can't represent IEEE negative zero) |
http://rosettacode.org/wiki/Extend_your_language | Extend your language | Control Structures
These are examples of control structures. You may also be interested in:
Conditional structures
Exceptions
Flow-control structures
Loops
Some programming languages allow you to extend the language. While this can be done to a certain degree in most languages (e.g. by using macros), other languages go much further. Most notably in the Forth and Lisp families, programming per se is done by extending the language without any formal distinction between built-in and user-defined elements.
If your language supports it, show how to introduce a new flow control mechanism. A practical and useful example is a four-way branch:
Occasionally, code must be written that depends on two conditions, resulting in up to four branches (depending on whether both, only the first, only the second, or none of the conditions are "true"). In a C-like language this could look like the following:
if (condition1isTrue) {
if (condition2isTrue)
bothConditionsAreTrue();
else
firstConditionIsTrue();
}
else if (condition2isTrue)
secondConditionIsTrue();
else
noConditionIsTrue();
Besides being rather cluttered, the statement(s) for 'condition2isTrue' must be written down twice. If 'condition2isTrue' were a lengthy and involved expression, it would be quite unreadable, and the code generated by the compiler might be unnecessarily large.
This can be improved by introducing a new keyword if2. It is similar to if, but takes two conditional statements instead of one, and up to three 'else' statements. One proposal (in pseudo-C syntax) might be:
if2 (condition1isTrue) (condition2isTrue)
bothConditionsAreTrue();
else1
firstConditionIsTrue();
else2
secondConditionIsTrue();
else
noConditionIsTrue();
Pick the syntax which suits your language. The keywords 'else1' and 'else2' are just examples. The new conditional expression should look, nest and behave analogously to the language's built-in 'if' statement.
| #ABAP | ABAP | DATA(result) = COND #( WHEN condition1istrue = abap_true AND condition2istrue = abap_true THEN bothconditionsaretrue
WHEN condition1istrue = abap_true THEN firstconditionistrue
WHEN condition2istrue = abap_true THEN secondconditionistrue
ELSE noconditionistrue ).
|
http://rosettacode.org/wiki/Factorial_base_numbers_indexing_permutations_of_a_collection | Factorial base numbers indexing permutations of a collection | You need a random arrangement of a deck of cards, you are sick of lame ways of doing this. This task is a super-cool way of doing this using factorial base numbers.
The first 25 factorial base numbers in increasing order are: 0.0.0, 0.0.1, 0.1.0, 0.1.1, 0.2.0, 0.2.1, 1.0.0, 1.0.1, 1.1.0, 1.1.1,1.2.0, 1.2.1, 2.0.0, 2.0.1, 2.1.0, 2.1.1, 2.2.0, 2.2.1, 3.0.0, 3.0.1, 3.1.0, 3.1.1, 3.2.0, 3.2.1, 1.0.0.0
Observe that the least significant digit is base 2 the next base 3, in general an n-digit factorial base number has digits n..1 in base n+1..2.
I want to produce a 1 to 1 mapping between these numbers and permutations:-
0.0.0 -> 0123
0.0.1 -> 0132
0.1.0 -> 0213
0.1.1 -> 0231
0.2.0 -> 0312
0.2.1 -> 0321
1.0.0 -> 1023
1.0.1 -> 1032
1.1.0 -> 1203
1.1.1 -> 1230
1.2.0 -> 1302
1.2.1 -> 1320
2.0.0 -> 2013
2.0.1 -> 2031
2.1.0 -> 2103
2.1.1 -> 2130
2.2.0 -> 2301
2.2.1 -> 2310
3.0.0 -> 3012
3.0.1 -> 3021
3.1.0 -> 3102
3.1.1 -> 3120
3.2.0 -> 3201
3.2.1 -> 3210
The following psudo-code will do this:
Starting with m=0 and Ω, an array of elements to be permutated, for each digit g starting with the most significant digit in the factorial base number.
If g is greater than zero, rotate the elements from m to m+g in Ω (see example)
Increment m and repeat the first step using the next most significant digit until the factorial base number is exhausted.
For example: using the factorial base number 2.0.1 and Ω = 0 1 2 3 where place 0 in both is the most significant (left-most) digit/element.
Step 1: m=0 g=2; Rotate places 0 through 2. 0 1 2 3 becomes 2 0 1 3
Step 2: m=1 g=0; No action.
Step 3: m=2 g=1; Rotate places 2 through 3. 2 0 1 3 becomes 2 0 3 1
Let me work 2.0.1 and 0123
step 1 n=0 g=2 Ω=2013
step 2 n=1 g=0 so no action
step 3 n=2 g=1 Ω=2031
The task:
First use your function to recreate the above table.
Secondly use your function to generate all permutaions of 11 digits, perhaps count them don't display them, compare this method with
methods in rc's permutations task.
Thirdly here following are two ramdom 51 digit factorial base numbers I prepared earlier:
39.49.7.47.29.30.2.12.10.3.29.37.33.17.12.31.29.34.17.25.2.4.25.4.1.14.20.6.21.18.1.1.1.4.0.5.15.12.4.3.10.10.9.1.6.5.5.3.0.0.0
51.48.16.22.3.0.19.34.29.1.36.30.12.32.12.29.30.26.14.21.8.12.1.3.10.4.7.17.6.21.8.12.15.15.13.15.7.3.12.11.9.5.5.6.6.3.4.0.3.2.1
use your function to crate the corresponding permutation of the following shoe of cards:
A♠K♠Q♠J♠10♠9♠8♠7♠6♠5♠4♠3♠2♠A♥K♥Q♥J♥10♥9♥8♥7♥6♥5♥4♥3♥2♥A♦K♦Q♦J♦10♦9♦8♦7♦6♦5♦4♦3♦2♦A♣K♣Q♣J♣10♣9♣8♣7♣6♣5♣4♣3♣2♣
Finally create your own 51 digit factorial base number and produce the corresponding permutation of the above shoe
| #Python | Python |
"""
http://rosettacode.org/wiki/Factorial_base_numbers_indexing_permutations_of_a_collection
https://en.wikipedia.org/wiki/Factorial_number_system
"""
import math
def apply_perm(omega,fbn):
"""
omega contains a list which will be permuted (scrambled)
based on fbm.
fbm is a list which represents a factorial base number.
This function just translates the pseudo code in the
Rosetta Code task.
"""
for m in range(len(fbn)):
g = fbn[m]
if g > 0:
# do rotation
# save last number
new_first = omega[m+g]
# move numbers right
omega[m+1:m+g+1] = omega[m:m+g]
# put last number first
omega[m] = new_first
return omega
def int_to_fbn(i):
"""
convert integer i to factorial based number
"""
current = i
divisor = 2
new_fbn = []
while current > 0:
remainder = current % divisor
current = current // divisor
new_fbn.append(remainder)
divisor += 1
return list(reversed(new_fbn))
def leading_zeros(l,n):
"""
If list l has less than n elements returns l with enough 0 elements
in front of the list to make it length n.
"""
if len(l) < n:
return(([0] * (n - len(l))) + l)
else:
return l
def get_fbn(n):
"""
Return the n! + 1 first Factorial Based Numbers starting with zero.
"""
max = math.factorial(n)
for i in range(max):
# from Wikipedia article
current = i
divisor = 1
new_fbn = int_to_fbn(i)
yield leading_zeros(new_fbn,n-1)
def print_write(f, line):
"""
prints to console and
output file f
"""
print(line)
f.write(str(line)+'\n')
def dot_format(l):
"""
Take a list l that is a factorial based number
and returns it in dot format.
i.e. [0, 2, 1] becomes 0.2.1
"""
# empty list
if len(l) < 1:
return ""
# start with just first element no dot
dot_string = str(l[0])
# add rest if any with dots
for e in l[1:]:
dot_string += "."+str(e)
return dot_string
def str_format(l):
"""
Take a list l and returns a string
of those elements converted to strings.
"""
if len(l) < 1:
return ""
new_string = ""
for e in l:
new_string += str(e)
return new_string
with open("output.html", "w", encoding="utf-8") as f:
f.write("<pre>\n")
# first print list
omega=[0,1,2,3]
four_list = get_fbn(4)
for l in four_list:
print_write(f,dot_format(l)+' -> '+str_format(apply_perm(omega[:],l)))
print_write(f," ")
# now generate this output:
#
# Permutations generated = 39916800
# compared to 11! which = 39916800
num_permutations = 0
for p in get_fbn(11):
num_permutations += 1
if num_permutations % 1000000 == 0:
print_write(f,"permutations so far = "+str(num_permutations))
print_write(f," ")
print_write(f,"Permutations generated = "+str(num_permutations))
print_write(f,"compared to 11! which = "+str(math.factorial(11)))
print_write(f," ")
"""
u"\u2660" - spade
u"\u2665" - heart
u"\u2666" - diamond
u"\u2663" - club
"""
shoe = []
for suit in [u"\u2660",u"\u2665",u"\u2666",u"\u2663"]:
for value in ['A','K','Q','J','10','9','8','7','6','5','4','3','2']:
shoe.append(value+suit)
print_write(f,str_format(shoe))
p1 = [39,49,7,47,29,30,2,12,10,3,29,37,33,17,12,31,29,34,17,25,2,4,25,4,1,14,20,6,21,18,1,1,1,4,0,5,15,12,4,3,10,10,9,1,6,5,5,3,0,0,0]
p2 = [51,48,16,22,3,0,19,34,29,1,36,30,12,32,12,29,30,26,14,21,8,12,1,3,10,4,7,17,6,21,8,12,15,15,13,15,7,3,12,11,9,5,5,6,6,3,4,0,3,2,1]
print_write(f," ")
print_write(f,dot_format(p1))
print_write(f," ")
print_write(f,str_format(apply_perm(shoe[:],p1)))
print_write(f," ")
print_write(f,dot_format(p2))
print_write(f," ")
print_write(f,str_format(apply_perm(shoe[:],p2)))
# generate random 51 digit factorial based number
import random
max = math.factorial(52)
random_int = random.randint(0, max-1)
myperm = leading_zeros(int_to_fbn(random_int),51)
print(len(myperm))
print_write(f," ")
print_write(f,dot_format(myperm))
print_write(f," ")
print_write(f,str_format(apply_perm(shoe[:],myperm)))
f.write("</pre>\n")
|
http://rosettacode.org/wiki/Factorions | Factorions |
Definition
A factorion is a natural number that equals the sum of the factorials of its digits.
Example
145 is a factorion in base 10 because:
1! + 4! + 5! = 1 + 24 + 120 = 145
It can be shown (see talk page) that no factorion in base 10 can exceed 1,499,999.
Task
Write a program in your language to demonstrate, by calculating and printing out the factorions, that:
There are 3 factorions in base 9
There are 4 factorions in base 10
There are 5 factorions in base 11
There are 2 factorions in base 12 (up to the same upper bound as for base 10)
See also
Wikipedia article
OEIS:A014080 - Factorions in base 10
OEIS:A193163 - Factorions in base n
| #Factor | Factor | USING: formatting io kernel math math.parser math.ranges memoize
prettyprint sequences ;
IN: rosetta-code.factorions
! Memoize factorial function
MEMO: factorial ( n -- n! ) [ 1 ] [ [1,b] product ] if-zero ;
: factorion? ( n base -- ? )
dupd >base string>digits [ factorial ] map-sum = ;
: show-factorions ( limit base -- )
dup "The factorions for base %d are:\n" printf
[ [1,b) ] dip [ dupd factorion? [ pprint bl ] [ drop ] if ]
curry each nl ;
1,500,000 9 12 [a,b] [ show-factorions nl ] with each |
http://rosettacode.org/wiki/Factorions | Factorions |
Definition
A factorion is a natural number that equals the sum of the factorials of its digits.
Example
145 is a factorion in base 10 because:
1! + 4! + 5! = 1 + 24 + 120 = 145
It can be shown (see talk page) that no factorion in base 10 can exceed 1,499,999.
Task
Write a program in your language to demonstrate, by calculating and printing out the factorions, that:
There are 3 factorions in base 9
There are 4 factorions in base 10
There are 5 factorions in base 11
There are 2 factorions in base 12 (up to the same upper bound as for base 10)
See also
Wikipedia article
OEIS:A014080 - Factorions in base 10
OEIS:A193163 - Factorions in base n
| #F.C5.8Drmul.C3.A6 | Fōrmulæ | Dim As Integer fact(12), suma, d, j
fact(0) = 1
For n As Integer = 1 To 11
fact(n) = fact(n-1) * n
Next n
For b As Integer = 9 To 12
Print "Los factoriones para base " & b & " son: "
For i As Integer = 1 To 1499999
suma = 0
j = i
While j > 0
d = j Mod b
suma += fact(d)
j \= b
Wend
If suma = i Then Print i & " ";
Next i
Print : Print
Next b
Sleep |
http://rosettacode.org/wiki/Filter | Filter | Task
Select certain elements from an Array into a new Array in a generic way.
To demonstrate, select all even numbers from an Array.
As an option, give a second solution which filters destructively,
by modifying the original Array rather than creating a new Array.
| #Stata | Stata | mata
a=2,9,4,7,5,3,6,1,8
// Select even elements of a
select(a,mod(a,2):==0)
// Select the indices of even elements of a
selectindex(mod(a,2):==0)
end |
http://rosettacode.org/wiki/FizzBuzz | FizzBuzz | Task
Write a program that prints the integers from 1 to 100 (inclusive).
But:
for multiples of three, print Fizz (instead of the number)
for multiples of five, print Buzz (instead of the number)
for multiples of both three and five, print FizzBuzz (instead of the number)
The FizzBuzz problem was presented as the lowest level of comprehension required to illustrate adequacy.
Also see
(a blog) dont-overthink-fizzbuzz
(a blog) fizzbuzz-the-programmers-stairway-to-heaven
| #PILOT | PILOT | C :i = 0
*loop
C :i = i + 1
J ( i > 100 ) : *finished
C :modulo = i % 15
J ( modulo = 0 ) : *fizzbuzz
C :modulo = i % 3
J ( modulo = 0 ) : *fizz
C :modulo = i % 5
J ( modulo = 0 ) : *buzz
T :#i
J : *loop
*fizzbuzz
T :FizzBuzz
J : *loop
*fizz
T :Fizz
J : *loop
*buzz
T :Buzz
J : *loop
*finished
END: |
http://rosettacode.org/wiki/Exponentiation_with_infix_operators_in_(or_operating_on)_the_base | Exponentiation with infix operators in (or operating on) the base | (Many programming languages, especially those with extended─precision integer arithmetic, usually
support one of **, ^, ↑ or some such for exponentiation.)
Some languages treat/honor infix operators when performing exponentiation (raising
numbers to some power by the language's exponentiation operator, if the computer
programming language has one).
Other programming languages may make use of the POW or some other BIF
(Built─In Ffunction), or some other library service.
If your language's exponentiation operator is not one of the usual ones, please comment on how to recognize it.
This task will deal with the case where there is some form of an infix operator operating
in (or operating on) the base.
Example
A negative five raised to the 3rd power could be specified as:
-5 ** 3 or as
-(5) ** 3 or as
(-5) ** 3 or as something else
(Not all computer programming languages have an exponential operator and/or support these syntax expression(s).
Task
compute and display exponentiation with a possible infix operator, whether specified and/or implied/inferred.
Raise the following numbers (integer or real):
-5 and
+5
to the following powers:
2nd and
3rd
using the following expressions (if applicable in your language):
-x**p
-(x)**p
(-x)**p
-(x**p)
Show here (on this page) the four (or more) types of symbolic expressions for each number and power.
Try to present the results in the same format/manner as the other programming entries to make any differences apparent.
The variables may be of any type(s) that is/are applicable in your language.
Related tasks
Exponentiation order
Exponentiation operator
Arbitrary-precision integers (included)
Parsing/RPN to infix conversion
Operator precedence
References
Wikipedia: Order of operations in Programming languages
| #Python | Python | from itertools import product
xx = '-5 +5'.split()
pp = '2 3'.split()
texts = '-x**p -(x)**p (-x)**p -(x**p)'.split()
print('Integer variable exponentiation')
for x, p in product(xx, pp):
print(f' x,p = {x:2},{p}; ', end=' ')
x, p = int(x), int(p)
print('; '.join(f"{t} =={eval(t):4}" for t in texts))
print('\nBonus integer literal exponentiation')
X, P = 'xp'
xx.insert(0, ' 5')
texts.insert(0, 'x**p')
for x, p in product(xx, pp):
texts2 = [t.replace(X, x).replace(P, p) for t in texts]
print(' ', '; '.join(f"{t2} =={eval(t2):4}" for t2 in texts2)) |
http://rosettacode.org/wiki/Exponentiation_with_infix_operators_in_(or_operating_on)_the_base | Exponentiation with infix operators in (or operating on) the base | (Many programming languages, especially those with extended─precision integer arithmetic, usually
support one of **, ^, ↑ or some such for exponentiation.)
Some languages treat/honor infix operators when performing exponentiation (raising
numbers to some power by the language's exponentiation operator, if the computer
programming language has one).
Other programming languages may make use of the POW or some other BIF
(Built─In Ffunction), or some other library service.
If your language's exponentiation operator is not one of the usual ones, please comment on how to recognize it.
This task will deal with the case where there is some form of an infix operator operating
in (or operating on) the base.
Example
A negative five raised to the 3rd power could be specified as:
-5 ** 3 or as
-(5) ** 3 or as
(-5) ** 3 or as something else
(Not all computer programming languages have an exponential operator and/or support these syntax expression(s).
Task
compute and display exponentiation with a possible infix operator, whether specified and/or implied/inferred.
Raise the following numbers (integer or real):
-5 and
+5
to the following powers:
2nd and
3rd
using the following expressions (if applicable in your language):
-x**p
-(x)**p
(-x)**p
-(x**p)
Show here (on this page) the four (or more) types of symbolic expressions for each number and power.
Try to present the results in the same format/manner as the other programming entries to make any differences apparent.
The variables may be of any type(s) that is/are applicable in your language.
Related tasks
Exponentiation order
Exponentiation operator
Arbitrary-precision integers (included)
Parsing/RPN to infix conversion
Operator precedence
References
Wikipedia: Order of operations in Programming languages
| #Smalltalk | Smalltalk | a := 2.
b := 3.
Transcript show:'-5**2 => '; showCR: -5**2.
Transcript show:'-5**a => '; showCR: -5**a.
Transcript show:'-5**b => '; showCR: -5**b.
Transcript show:'5**2 => '; showCR: 5**2.
Transcript show:'5**a => '; showCR: 5**a.
Transcript show:'5**b => '; showCR: 5**b.
" Transcript show:'-(5**b) => '; showCR: -(5**b). -- invalid: syntax error "
" Transcript show:'5**-b => '; showCR: 5**-b. -- invalid: syntax error " |
http://rosettacode.org/wiki/Fibonacci_sequence | Fibonacci sequence | The Fibonacci sequence is a sequence Fn of natural numbers defined recursively:
F0 = 0
F1 = 1
Fn = Fn-1 + Fn-2, if n>1
Task
Write a function to generate the nth Fibonacci number.
Solutions can be iterative or recursive (though recursive solutions are generally considered too slow and are mostly used as an exercise in recursion).
The sequence is sometimes extended into negative numbers by using a straightforward inverse of the positive definition:
Fn = Fn+2 - Fn+1, if n<0
support for negative n in the solution is optional.
Related tasks
Fibonacci n-step number sequences
Leonardo numbers
References
Wikipedia, Fibonacci number
Wikipedia, Lucas number
MathWorld, Fibonacci Number
Some identities for r-Fibonacci numbers
OEIS Fibonacci numbers
OEIS Lucas numbers
| #Forth | Forth | : fib ( n -- fib )
0 1 rot 0 ?do over + swap loop drop ; |
http://rosettacode.org/wiki/Factors_of_an_integer | Factors of an integer |
Basic Data Operation
This is a basic data operation. It represents a fundamental action on a basic data type.
You may see other such operations in the Basic Data Operations category, or:
Integer Operations
Arithmetic |
Comparison
Boolean Operations
Bitwise |
Logical
String Operations
Concatenation |
Interpolation |
Comparison |
Matching
Memory Operations
Pointers & references |
Addresses
Task
Compute the factors of a positive integer.
These factors are the positive integers by which the number being factored can be divided to yield a positive integer result.
(Though the concepts function correctly for zero and negative integers, the set of factors of zero has countably infinite members, and the factors of negative integers can be obtained from the factors of related positive numbers without difficulty; this task does not require handling of either of these cases).
Note that every prime number has two factors: 1 and itself.
Related tasks
count in factors
prime decomposition
Sieve of Eratosthenes
primality by trial division
factors of a Mersenne number
trial factoring of a Mersenne number
partition an integer X into N primes
sequence of primes by Trial Division
sequence: smallest number greater than previous term with exactly n divisors
| #Pascal | Pascal | program Factors;
var
i, number: integer;
begin
write('Enter a number between 1 and 2147483647: ');
readln(number);
for i := 1 to round(sqrt(number)) - 1 do
if number mod i = 0 then
write (i, ' ', number div i, ' ');
// Check to see if number is a square
i := round(sqrt(number));
if i*i = number then
write(i)
else if number mod i = 0 then
write(i, number/i);
writeln;
end. |
http://rosettacode.org/wiki/Extreme_floating_point_values | Extreme floating point values | The IEEE floating point specification defines certain 'extreme' floating point values such as minus zero, -0.0, a value distinct from plus zero; not a number, NaN; and plus and minus infinity.
The task is to use expressions involving other 'normal' floating point values in your language to calculate these, (and maybe other), extreme floating point values in your language and assign them to variables.
Print the values of these variables if possible; and show some arithmetic with these values and variables.
If your language can directly enter these extreme floating point values then show it.
See also
What Every Computer Scientist Should Know About Floating-Point Arithmetic
Related tasks
Infinity
Detect division by zero
Literals/Floating point
| #Fortran | Fortran |
REAL*8 BAD,NaN !Sometimes a number is not what is appropriate.
PARAMETER (NaN = Z'FFFFFFFFFFFFFFFF') !This value is recognised in floating-point arithmetic.
PARAMETER (BAD = Z'FFFFFFFFFFFFFFFF') !I pay special attention to BAD values.
CHARACTER*3 BADASTEXT !Speakable form.
DATA BADASTEXT/" ? "/ !Room for "NaN", short for "Not a Number", if desired.
REAL*8 PINF,NINF !Special values. No sign of an "overflow" state, damnit.
PARAMETER (PINF = Z'7FF0000000000000') !May well cause confusion
PARAMETER (NINF = Z'FFF0000000000000') !On a cpu not using this scheme.
|
http://rosettacode.org/wiki/Extreme_floating_point_values | Extreme floating point values | The IEEE floating point specification defines certain 'extreme' floating point values such as minus zero, -0.0, a value distinct from plus zero; not a number, NaN; and plus and minus infinity.
The task is to use expressions involving other 'normal' floating point values in your language to calculate these, (and maybe other), extreme floating point values in your language and assign them to variables.
Print the values of these variables if possible; and show some arithmetic with these values and variables.
If your language can directly enter these extreme floating point values then show it.
See also
What Every Computer Scientist Should Know About Floating-Point Arithmetic
Related tasks
Infinity
Detect division by zero
Literals/Floating point
| #FreeBASIC | FreeBASIC | ' FB 1.05.0 Win64
#Include "crt/math.bi"
Dim inf As Double = INFINITY
Dim negInf As Double = -INFINITY
Dim notNum As Double = NAN_
Dim negZero As Double = 1.0 / negInf
Print inf, inf / inf
Print negInf, negInf * negInf
Print notNum, notNum + inf + negInf
Print negZero, negZero - 1
Sleep |
http://rosettacode.org/wiki/Extend_your_language | Extend your language | Control Structures
These are examples of control structures. You may also be interested in:
Conditional structures
Exceptions
Flow-control structures
Loops
Some programming languages allow you to extend the language. While this can be done to a certain degree in most languages (e.g. by using macros), other languages go much further. Most notably in the Forth and Lisp families, programming per se is done by extending the language without any formal distinction between built-in and user-defined elements.
If your language supports it, show how to introduce a new flow control mechanism. A practical and useful example is a four-way branch:
Occasionally, code must be written that depends on two conditions, resulting in up to four branches (depending on whether both, only the first, only the second, or none of the conditions are "true"). In a C-like language this could look like the following:
if (condition1isTrue) {
if (condition2isTrue)
bothConditionsAreTrue();
else
firstConditionIsTrue();
}
else if (condition2isTrue)
secondConditionIsTrue();
else
noConditionIsTrue();
Besides being rather cluttered, the statement(s) for 'condition2isTrue' must be written down twice. If 'condition2isTrue' were a lengthy and involved expression, it would be quite unreadable, and the code generated by the compiler might be unnecessarily large.
This can be improved by introducing a new keyword if2. It is similar to if, but takes two conditional statements instead of one, and up to three 'else' statements. One proposal (in pseudo-C syntax) might be:
if2 (condition1isTrue) (condition2isTrue)
bothConditionsAreTrue();
else1
firstConditionIsTrue();
else2
secondConditionIsTrue();
else
noConditionIsTrue();
Pick the syntax which suits your language. The keywords 'else1' and 'else2' are just examples. The new conditional expression should look, nest and behave analogously to the language's built-in 'if' statement.
| #6502_Assembly | 6502 Assembly | CMP_Double .macro ;NESASM3 syntax
; input:
; \1 = first condition. Valid addressing modes: immediate, zero page, or absolute.
; \2 = second condition. Valid addressing modes: immediate, zero page, or absolute.
; \3 = branch here if both are true
; \4 = branch here if only first condition is true
; \5 = branch here if only second condition is true
; \6 = branch here if both are false
CMP \1
BNE .check2\@ ;\1 is not true
CMP \2
BEQ .doubletrue\@
JMP \4 ;only condition 1 is true
.doubletrue\@:
JMP \3 ;both are true
.check2\@:
CMP \2
BNE .doublefalse\@
JMP \5 ;only condition 2 is true
.doublefalse:
JMP \6 ;both are false
.endm |
http://rosettacode.org/wiki/Extend_your_language | Extend your language | Control Structures
These are examples of control structures. You may also be interested in:
Conditional structures
Exceptions
Flow-control structures
Loops
Some programming languages allow you to extend the language. While this can be done to a certain degree in most languages (e.g. by using macros), other languages go much further. Most notably in the Forth and Lisp families, programming per se is done by extending the language without any formal distinction between built-in and user-defined elements.
If your language supports it, show how to introduce a new flow control mechanism. A practical and useful example is a four-way branch:
Occasionally, code must be written that depends on two conditions, resulting in up to four branches (depending on whether both, only the first, only the second, or none of the conditions are "true"). In a C-like language this could look like the following:
if (condition1isTrue) {
if (condition2isTrue)
bothConditionsAreTrue();
else
firstConditionIsTrue();
}
else if (condition2isTrue)
secondConditionIsTrue();
else
noConditionIsTrue();
Besides being rather cluttered, the statement(s) for 'condition2isTrue' must be written down twice. If 'condition2isTrue' were a lengthy and involved expression, it would be quite unreadable, and the code generated by the compiler might be unnecessarily large.
This can be improved by introducing a new keyword if2. It is similar to if, but takes two conditional statements instead of one, and up to three 'else' statements. One proposal (in pseudo-C syntax) might be:
if2 (condition1isTrue) (condition2isTrue)
bothConditionsAreTrue();
else1
firstConditionIsTrue();
else2
secondConditionIsTrue();
else
noConditionIsTrue();
Pick the syntax which suits your language. The keywords 'else1' and 'else2' are just examples. The new conditional expression should look, nest and behave analogously to the language's built-in 'if' statement.
| #Ada | Ada | with Ada.Text_IO; use Ada.Text_IO;
procedure Test_If_2 is
type Two_Bool is range 0 .. 3;
function If_2(Cond_1, Cond_2: Boolean) return Two_Bool is
(Two_Bool(2*Boolean'Pos(Cond_1)) + Two_Bool(Boolean'Pos(Cond_2)));
begin
for N in 10 .. 20 loop
Put(Integer'Image(N) & " is ");
case If_2(N mod 2 = 0, N mod 3 = 0) is
when 2#11# => Put_Line("divisible by both two and three.");
when 2#10# => Put_Line("divisible by two, but not by three.");
when 2#01# => Put_Line("divisible by three, but not by two.");
when 2#00# => Put_Line("neither divisible by two, nor by three.");
end case;
end loop;
end Test_If_2; |
http://rosettacode.org/wiki/Factorial_base_numbers_indexing_permutations_of_a_collection | Factorial base numbers indexing permutations of a collection | You need a random arrangement of a deck of cards, you are sick of lame ways of doing this. This task is a super-cool way of doing this using factorial base numbers.
The first 25 factorial base numbers in increasing order are: 0.0.0, 0.0.1, 0.1.0, 0.1.1, 0.2.0, 0.2.1, 1.0.0, 1.0.1, 1.1.0, 1.1.1,1.2.0, 1.2.1, 2.0.0, 2.0.1, 2.1.0, 2.1.1, 2.2.0, 2.2.1, 3.0.0, 3.0.1, 3.1.0, 3.1.1, 3.2.0, 3.2.1, 1.0.0.0
Observe that the least significant digit is base 2 the next base 3, in general an n-digit factorial base number has digits n..1 in base n+1..2.
I want to produce a 1 to 1 mapping between these numbers and permutations:-
0.0.0 -> 0123
0.0.1 -> 0132
0.1.0 -> 0213
0.1.1 -> 0231
0.2.0 -> 0312
0.2.1 -> 0321
1.0.0 -> 1023
1.0.1 -> 1032
1.1.0 -> 1203
1.1.1 -> 1230
1.2.0 -> 1302
1.2.1 -> 1320
2.0.0 -> 2013
2.0.1 -> 2031
2.1.0 -> 2103
2.1.1 -> 2130
2.2.0 -> 2301
2.2.1 -> 2310
3.0.0 -> 3012
3.0.1 -> 3021
3.1.0 -> 3102
3.1.1 -> 3120
3.2.0 -> 3201
3.2.1 -> 3210
The following psudo-code will do this:
Starting with m=0 and Ω, an array of elements to be permutated, for each digit g starting with the most significant digit in the factorial base number.
If g is greater than zero, rotate the elements from m to m+g in Ω (see example)
Increment m and repeat the first step using the next most significant digit until the factorial base number is exhausted.
For example: using the factorial base number 2.0.1 and Ω = 0 1 2 3 where place 0 in both is the most significant (left-most) digit/element.
Step 1: m=0 g=2; Rotate places 0 through 2. 0 1 2 3 becomes 2 0 1 3
Step 2: m=1 g=0; No action.
Step 3: m=2 g=1; Rotate places 2 through 3. 2 0 1 3 becomes 2 0 3 1
Let me work 2.0.1 and 0123
step 1 n=0 g=2 Ω=2013
step 2 n=1 g=0 so no action
step 3 n=2 g=1 Ω=2031
The task:
First use your function to recreate the above table.
Secondly use your function to generate all permutaions of 11 digits, perhaps count them don't display them, compare this method with
methods in rc's permutations task.
Thirdly here following are two ramdom 51 digit factorial base numbers I prepared earlier:
39.49.7.47.29.30.2.12.10.3.29.37.33.17.12.31.29.34.17.25.2.4.25.4.1.14.20.6.21.18.1.1.1.4.0.5.15.12.4.3.10.10.9.1.6.5.5.3.0.0.0
51.48.16.22.3.0.19.34.29.1.36.30.12.32.12.29.30.26.14.21.8.12.1.3.10.4.7.17.6.21.8.12.15.15.13.15.7.3.12.11.9.5.5.6.6.3.4.0.3.2.1
use your function to crate the corresponding permutation of the following shoe of cards:
A♠K♠Q♠J♠10♠9♠8♠7♠6♠5♠4♠3♠2♠A♥K♥Q♥J♥10♥9♥8♥7♥6♥5♥4♥3♥2♥A♦K♦Q♦J♦10♦9♦8♦7♦6♦5♦4♦3♦2♦A♣K♣Q♣J♣10♣9♣8♣7♣6♣5♣4♣3♣2♣
Finally create your own 51 digit factorial base number and produce the corresponding permutation of the above shoe
| #Quackery | Quackery | [ 1 swap times [ i 1+ * ] ] is ! ( n --> n )
[ dup 0 = iff [ drop 2 ] done
0
[ 1+ 2dup ! / 0 = until ]
nip ] is figits ( n --> n )
[ [] unrot 1 - times
[ i 1+ ! /mod
dip join ] drop ] is factoradic ( n n --> [ )
[ 0 swap
witheach [ i 1+ ! * + ] ] is unfactoradic ( [ --> n )
[ [] unrot witheach
[ pluck
rot swap nested join
swap ]
join ] is inversion ( [ [ --> [ )
[ over size
factoradic inversion ] is nperm ( [ n --> [ )
[ 0 unrot swap witheach
[ over find
dup dip [ pluck drop ]
rot i 1+ * + swap ]
drop ] is permnum ( [ [ --> n )
say 'The 1236880662123rd permutation of' cr
say '"uncopyrightable" is "'
$ 'uncopyrightable' 1236880662123 nperm echo$
say '".' cr cr
say 'The factorial base representation of' cr
say '1236880662123 is '
1236880662123 dup figits factoradic echo
say '.' cr cr
say '"lucentbiography" is permutation' cr
say '#' $ 'lucentbiography' $ 'uncopyrightable' permnum echo
say ' of "uncopyrightable".' |
http://rosettacode.org/wiki/Factorial_base_numbers_indexing_permutations_of_a_collection | Factorial base numbers indexing permutations of a collection | You need a random arrangement of a deck of cards, you are sick of lame ways of doing this. This task is a super-cool way of doing this using factorial base numbers.
The first 25 factorial base numbers in increasing order are: 0.0.0, 0.0.1, 0.1.0, 0.1.1, 0.2.0, 0.2.1, 1.0.0, 1.0.1, 1.1.0, 1.1.1,1.2.0, 1.2.1, 2.0.0, 2.0.1, 2.1.0, 2.1.1, 2.2.0, 2.2.1, 3.0.0, 3.0.1, 3.1.0, 3.1.1, 3.2.0, 3.2.1, 1.0.0.0
Observe that the least significant digit is base 2 the next base 3, in general an n-digit factorial base number has digits n..1 in base n+1..2.
I want to produce a 1 to 1 mapping between these numbers and permutations:-
0.0.0 -> 0123
0.0.1 -> 0132
0.1.0 -> 0213
0.1.1 -> 0231
0.2.0 -> 0312
0.2.1 -> 0321
1.0.0 -> 1023
1.0.1 -> 1032
1.1.0 -> 1203
1.1.1 -> 1230
1.2.0 -> 1302
1.2.1 -> 1320
2.0.0 -> 2013
2.0.1 -> 2031
2.1.0 -> 2103
2.1.1 -> 2130
2.2.0 -> 2301
2.2.1 -> 2310
3.0.0 -> 3012
3.0.1 -> 3021
3.1.0 -> 3102
3.1.1 -> 3120
3.2.0 -> 3201
3.2.1 -> 3210
The following psudo-code will do this:
Starting with m=0 and Ω, an array of elements to be permutated, for each digit g starting with the most significant digit in the factorial base number.
If g is greater than zero, rotate the elements from m to m+g in Ω (see example)
Increment m and repeat the first step using the next most significant digit until the factorial base number is exhausted.
For example: using the factorial base number 2.0.1 and Ω = 0 1 2 3 where place 0 in both is the most significant (left-most) digit/element.
Step 1: m=0 g=2; Rotate places 0 through 2. 0 1 2 3 becomes 2 0 1 3
Step 2: m=1 g=0; No action.
Step 3: m=2 g=1; Rotate places 2 through 3. 2 0 1 3 becomes 2 0 3 1
Let me work 2.0.1 and 0123
step 1 n=0 g=2 Ω=2013
step 2 n=1 g=0 so no action
step 3 n=2 g=1 Ω=2031
The task:
First use your function to recreate the above table.
Secondly use your function to generate all permutaions of 11 digits, perhaps count them don't display them, compare this method with
methods in rc's permutations task.
Thirdly here following are two ramdom 51 digit factorial base numbers I prepared earlier:
39.49.7.47.29.30.2.12.10.3.29.37.33.17.12.31.29.34.17.25.2.4.25.4.1.14.20.6.21.18.1.1.1.4.0.5.15.12.4.3.10.10.9.1.6.5.5.3.0.0.0
51.48.16.22.3.0.19.34.29.1.36.30.12.32.12.29.30.26.14.21.8.12.1.3.10.4.7.17.6.21.8.12.15.15.13.15.7.3.12.11.9.5.5.6.6.3.4.0.3.2.1
use your function to crate the corresponding permutation of the following shoe of cards:
A♠K♠Q♠J♠10♠9♠8♠7♠6♠5♠4♠3♠2♠A♥K♥Q♥J♥10♥9♥8♥7♥6♥5♥4♥3♥2♥A♦K♦Q♦J♦10♦9♦8♦7♦6♦5♦4♦3♦2♦A♣K♣Q♣J♣10♣9♣8♣7♣6♣5♣4♣3♣2♣
Finally create your own 51 digit factorial base number and produce the corresponding permutation of the above shoe
| #Raku | Raku | sub postfix:<!> (Int $n) { (flat 1, [\*] 1..*)[$n] }
multi base (Int $n is copy, 'F', $length? is copy) {
constant @fact = [\*] 1 .. *;
my $i = $length // @fact.first: * > $n, :k;
my $f;
[ @fact[^$i].reverse.map: { ($n, $f) = $n.polymod($_); $f } ]
}
sub fpermute (@a is copy, *@f) { (^@f).map: { @a[$_ .. $_ + @f[$_]].=rotate(-1) }; @a }
put "Part 1: Generate table";
put $_.&base('F', 3).join('.') ~ ' -> ' ~ [0,1,2,3].&fpermute($_.&base('F', 3)).join for ^24;
put "\nPart 2: Compare 11! to 11! " ~ '¯\_(ツ)_/¯';
# This is kind of a weird request. Since we don't actually need to _generate_
# the permutations, only _count_ them: compare count of 11! vs count of 11!
put "11! === 11! : {11! === 11!}";
put "\nPart 3: Generate the given task shuffles";
my \Ω = <A♠ K♠ Q♠ J♠ 10♠ 9♠ 8♠ 7♠ 6♠ 5♠ 4♠ 3♠ 2♠ A♥ K♥ Q♥ J♥ 10♥ 9♥ 8♥ 7♥ 6♥ 5♥ 4♥ 3♥ 2♥
A♦ K♦ Q♦ J♦ 10♦ 9♦ 8♦ 7♦ 6♦ 5♦ 4♦ 3♦ 2♦ A♣ K♣ Q♣ J♣ 10♣ 9♣ 8♣ 7♣ 6♣ 5♣ 4♣ 3♣ 2♣
>;
my @books = <
39.49.7.47.29.30.2.12.10.3.29.37.33.17.12.31.29.34.17.25.2.4.25.4.1.14.20.6.21.18.1.1.1.4.0.5.15.12.4.3.10.10.9.1.6.5.5.3.0.0.0
51.48.16.22.3.0.19.34.29.1.36.30.12.32.12.29.30.26.14.21.8.12.1.3.10.4.7.17.6.21.8.12.15.15.13.15.7.3.12.11.9.5.5.6.6.3.4.0.3.2.1
>;
put "Original deck:";
put Ω.join;
put "\n$_\n" ~ Ω[(^Ω).&fpermute($_.split: '.')].join for @books;
put "\nPart 4: Generate a random shuffle";
my @shoe = (+Ω … 2).map: { (^$_).pick };
put @shoe.join('.');
put Ω[(^Ω).&fpermute(@shoe)].join;
put "\nSeems to me it would be easier to just say: Ω.pick(*).join";
put Ω.pick(*).join; |
http://rosettacode.org/wiki/Factorions | Factorions |
Definition
A factorion is a natural number that equals the sum of the factorials of its digits.
Example
145 is a factorion in base 10 because:
1! + 4! + 5! = 1 + 24 + 120 = 145
It can be shown (see talk page) that no factorion in base 10 can exceed 1,499,999.
Task
Write a program in your language to demonstrate, by calculating and printing out the factorions, that:
There are 3 factorions in base 9
There are 4 factorions in base 10
There are 5 factorions in base 11
There are 2 factorions in base 12 (up to the same upper bound as for base 10)
See also
Wikipedia article
OEIS:A014080 - Factorions in base 10
OEIS:A193163 - Factorions in base n
| #FreeBASIC | FreeBASIC | Dim As Integer fact(12), suma, d, j
fact(0) = 1
For n As Integer = 1 To 11
fact(n) = fact(n-1) * n
Next n
For b As Integer = 9 To 12
Print "Los factoriones para base " & b & " son: "
For i As Integer = 1 To 1499999
suma = 0
j = i
While j > 0
d = j Mod b
suma += fact(d)
j \= b
Wend
If suma = i Then Print i & " ";
Next i
Print : Print
Next b
Sleep |
http://rosettacode.org/wiki/Factorions | Factorions |
Definition
A factorion is a natural number that equals the sum of the factorials of its digits.
Example
145 is a factorion in base 10 because:
1! + 4! + 5! = 1 + 24 + 120 = 145
It can be shown (see talk page) that no factorion in base 10 can exceed 1,499,999.
Task
Write a program in your language to demonstrate, by calculating and printing out the factorions, that:
There are 3 factorions in base 9
There are 4 factorions in base 10
There are 5 factorions in base 11
There are 2 factorions in base 12 (up to the same upper bound as for base 10)
See also
Wikipedia article
OEIS:A014080 - Factorions in base 10
OEIS:A193163 - Factorions in base n
| #Frink | Frink | factorion[n, base] := sum[map["factorial", integerDigits[n, base]]]
for base = 9 to 12
{
for n = 1 to 1_499_999
if n == factorion[n, base]
println["$base\t$n"]
} |
http://rosettacode.org/wiki/Filter | Filter | Task
Select certain elements from an Array into a new Array in a generic way.
To demonstrate, select all even numbers from an Array.
As an option, give a second solution which filters destructively,
by modifying the original Array rather than creating a new Array.
| #Swift | Swift | let numbers = [1,2,3,4,5,6]
let even_numbers = numbers.filter { $0 % 2 == 0 }
println(even_numbers) |
http://rosettacode.org/wiki/FizzBuzz | FizzBuzz | Task
Write a program that prints the integers from 1 to 100 (inclusive).
But:
for multiples of three, print Fizz (instead of the number)
for multiples of five, print Buzz (instead of the number)
for multiples of both three and five, print FizzBuzz (instead of the number)
The FizzBuzz problem was presented as the lowest level of comprehension required to illustrate adequacy.
Also see
(a blog) dont-overthink-fizzbuzz
(a blog) fizzbuzz-the-programmers-stairway-to-heaven
| #PIR | PIR | .sub main :main
.local int f
.local int mf
.local int skipnum
f = 1
LOOP:
if f > 100 goto DONE
skipnum = 0
mf = f % 3
if mf == 0 goto FIZZ
FIZZRET:
mf = f % 5
if mf == 0 goto BUZZ
BUZZRET:
if skipnum > 0 goto SKIPNUM
print f
SKIPNUM:
print "\n"
inc f
goto LOOP
end
FIZZ:
print "Fizz"
inc skipnum
goto FIZZRET
end
BUZZ:
print "Buzz"
inc skipnum
goto BUZZRET
end
DONE:
end
.end |
http://rosettacode.org/wiki/Exponentiation_with_infix_operators_in_(or_operating_on)_the_base | Exponentiation with infix operators in (or operating on) the base | (Many programming languages, especially those with extended─precision integer arithmetic, usually
support one of **, ^, ↑ or some such for exponentiation.)
Some languages treat/honor infix operators when performing exponentiation (raising
numbers to some power by the language's exponentiation operator, if the computer
programming language has one).
Other programming languages may make use of the POW or some other BIF
(Built─In Ffunction), or some other library service.
If your language's exponentiation operator is not one of the usual ones, please comment on how to recognize it.
This task will deal with the case where there is some form of an infix operator operating
in (or operating on) the base.
Example
A negative five raised to the 3rd power could be specified as:
-5 ** 3 or as
-(5) ** 3 or as
(-5) ** 3 or as something else
(Not all computer programming languages have an exponential operator and/or support these syntax expression(s).
Task
compute and display exponentiation with a possible infix operator, whether specified and/or implied/inferred.
Raise the following numbers (integer or real):
-5 and
+5
to the following powers:
2nd and
3rd
using the following expressions (if applicable in your language):
-x**p
-(x)**p
(-x)**p
-(x**p)
Show here (on this page) the four (or more) types of symbolic expressions for each number and power.
Try to present the results in the same format/manner as the other programming entries to make any differences apparent.
The variables may be of any type(s) that is/are applicable in your language.
Related tasks
Exponentiation order
Exponentiation operator
Arbitrary-precision integers (included)
Parsing/RPN to infix conversion
Operator precedence
References
Wikipedia: Order of operations in Programming languages
| #Wren | Wren | import "/fmt" for Fmt
class Num2 {
construct new(n) { _n = n }
n { _n}
^(exp) {
if (exp is Num2) exp = exp.n
return Num2.new(_n.pow(exp))
}
- { Num2.new(-_n) }
toString { _n.toString }
}
var ops = ["-x^p", "-(x)^p", "(-x)^p", "-(x^p)"]
for (x in [Num2.new(-5), Num2.new(5)]) {
for (p in [Num2.new(2), Num2.new(3)]) {
Fmt.write("x = $2s p = $s | ", x, p)
Fmt.write("$s = $4s | ", ops[0], -x^p)
Fmt.write("$s = $4s | ", ops[1], -(x)^p)
Fmt.write("$s = $4s | ", ops[2], (-x)^p)
Fmt.print("$s = $4s", ops[3], -(x^p))
}
} |
http://rosettacode.org/wiki/Extensible_prime_generator | Extensible prime generator | Task
Write a generator of prime numbers, in order, that will automatically adjust to accommodate the generation of any reasonably high prime.
The routine should demonstrably rely on either:
Being based on an open-ended counter set to count without upper limit other than system or programming language limits. In this case, explain where this counter is in the code.
Being based on a limit that is extended automatically. In this case, choose a small limit that ensures the limit will be passed when generating some of the values to be asked for below.
If other methods of creating an extensible prime generator are used, the algorithm's means of extensibility/lack of limits should be stated.
The routine should be used to:
Show the first twenty primes.
Show the primes between 100 and 150.
Show the number of primes between 7,700 and 8,000.
Show the 10,000th prime.
Show output on this page.
Note: You may reference code already on this site if it is written to be imported/included, then only the code necessary for import and the performance of this task need be shown. (It is also important to leave a forward link on the referenced tasks entry so that later editors know that the code is used for multiple tasks).
Note 2: If a languages in-built prime generator is extensible or is guaranteed to generate primes up to a system limit, (231 or memory overflow for example), then this may be used as long as an explanation of the limits of the prime generator is also given. (Which may include a link to/excerpt from, language documentation).
Note 3:The task is written so it may be useful in solving the task Emirp primes as well as others (depending on its efficiency).
Reference
Prime Numbers. Website with large count of primes.
| #Ada | Ada | with Ada.Text_IO, Miller_Rabin;
procedure Prime_Gen is
type Num is range 0 .. 2**63-1; -- maximum for the gnat Ada compiler
MR_Iterations: constant Positive := 25;
-- the probability Pr[Is_Prime(N, MR_Iterations) = Probably_Prime]
-- is 1 for prime N and < 4**(-MR_Iterations) for composed N
function Next(P: Num) return Num is
N: Num := P+1;
package MR is new Miller_Rabin(Num); use MR;
begin
while not (Is_Prime(N, MR_Iterations) = Probably_Prime) loop
N := N + 1;
end loop;
return N;
end Next;
Current: Num;
Count: Num := 0;
begin
-- show the first twenty primes
Ada.Text_IO.Put("First 20 primes:");
Current := 1;
for I in 1 .. 20 loop
Current := Next(Current);
Ada.Text_IO.Put(Num'Image(Current));
end loop;
Ada.Text_IO.New_Line;
-- show the primes between 100 and 150
Ada.Text_IO.Put("Primes between 100 and 150:");
Current := 99;
loop
Current := Next(Current);
exit when Current > 150;
Ada.Text_IO.Put(Num'Image(Current));
end loop;
Ada.Text_IO.New_Line;
-- count primes between 7700 and 8000
Ada.Text_IO.Put("Number of primes between 7700 and 8000:");
Current := 7699;
loop
Current := Next(Current);
exit when Current > 8000;
Count := Count + 1;
end loop;
Ada.Text_IO.Put_Line(Num'Image(Count));
Count := 10;
Ada.Text_IO.Put_Line("Print the K_i'th prime, for $K=10**i:");
begin
loop
Current := 1;
for I in 1 .. Count loop
Current := Next(Current);
end loop;
Ada.Text_IO.Put(Num'Image(Count) & "th prime:" &
Num'Image(Current));
Count := Count * 10;
end loop;
exception
when Constraint_Error =>
Ada.Text_IO.Put_Line(" can't compute the" & Num'Image(Count) &
"th prime:");
end;
end; |
http://rosettacode.org/wiki/Fibonacci_sequence | Fibonacci sequence | The Fibonacci sequence is a sequence Fn of natural numbers defined recursively:
F0 = 0
F1 = 1
Fn = Fn-1 + Fn-2, if n>1
Task
Write a function to generate the nth Fibonacci number.
Solutions can be iterative or recursive (though recursive solutions are generally considered too slow and are mostly used as an exercise in recursion).
The sequence is sometimes extended into negative numbers by using a straightforward inverse of the positive definition:
Fn = Fn+2 - Fn+1, if n<0
support for negative n in the solution is optional.
Related tasks
Fibonacci n-step number sequences
Leonardo numbers
References
Wikipedia, Fibonacci number
Wikipedia, Lucas number
MathWorld, Fibonacci Number
Some identities for r-Fibonacci numbers
OEIS Fibonacci numbers
OEIS Lucas numbers
| #Fortran | Fortran | C FIBONACCI SEQUENCE - FORTRAN IV
NN=46
DO 1 I=0,NN
1 WRITE(*,300) I,IFIBO(I)
300 FORMAT(1X,I2,1X,I10)
END
C
FUNCTION IFIBO(N)
IF(N) 9,1,2
1 IFN=0
GOTO 9
2 IF(N-1) 9,3,4
3 IFN=1
GOTO 9
4 IFNM1=0
IFN=1
DO 5 I=2,N
IFNM2=IFNM1
IFNM1=IFN
5 IFN=IFNM1+IFNM2
9 IFIBO=IFN
END |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.