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/Loops/Wrong_ranges | Loops/Wrong ranges | Loops/Wrong ranges
You are encouraged to solve this task according to the task description, using any language you may know.
Some languages have syntax or function(s) to generate a range of numeric values from a start value, a stop value, and an increment.
The purpose of this task is to select the range syntax/function that would generate at least two increasing numbers when given a stop value more than the start value and a positive increment of less than half the difference. You are then to use that same syntax/function but with different parameters; and show, here, what would happen.
Use these values if possible:
start
stop
increment
Comment
-2
2
1
Normal
-2
2
0
Zero increment
-2
2
-1
Increments away from stop value
-2
2
10
First increment is beyond stop value
2
-2
1
Start more than stop: positive increment
2
2
1
Start equal stop: positive increment
2
2
-1
Start equal stop: negative increment
2
2
0
Start equal stop: zero increment
0
0
0
Start equal stop equal zero: zero increment
Related tasks
Loop over multiple arrays simultaneously
Loops/Break
Loops/Continue
Loops/Do-while
Loops/Downward for
Loops/For
Loops/For with a specified step
Loops/Foreach
Loops/Increment loop index within loop body
Loops/Infinite
Loops/N plus one half
Loops/Nested
Loops/While
Loops/with multiple ranges
Loops/Wrong ranges
| #Ada | Ada | with Ada.Text_IO; use Ada.Text_IO;
with Ada.Strings.Unbounded; use Ada.Strings.Unbounded;
with Ada.Text_IO.Unbounded_IO; use Ada.Text_IO.Unbounded_IO;
procedure Main is
procedure print_range(start : integer; stop : integer; step : integer) is
Num : Integer := start;
begin
Put("Range(" & start'Image & ", " & stop'image &
", " & step'image & ") => ");
if stop < start then
Put_Line("Error: stop must be no less than start!");
elsif step not in positive then
Put_Line("Error: increment must be greater than 0!");
elsif start = stop then
Put_Line(start'image);
else
while num <= stop loop
Put(num'Image);
num := num + step;
end loop;
New_Line;
end if;
end print_range;
type test_record is record
start : integer;
stop : integer;
step : integer;
comment : unbounded_string := null_unbounded_string;
end record;
tests : array(1..9) of test_record :=
( 1 => (-2, 2, 1, To_Unbounded_String("Normal")),
2 => (-2, 2, 0, To_Unbounded_String("Zero increment")),
3 => (-2, 2, -1, To_Unbounded_String("Increments away from stop value")),
4 => (-2, 2, 10, To_Unbounded_String("First increment is beyond stop value")),
5 => (2, -1, 1, To_Unbounded_String("Start more than stop: positive increment")),
6 => (2, 2, 1, To_Unbounded_String("Start equal stop: positive increment")),
7 => (2, 2, -1, To_Unbounded_String("Start equal stop: negative increment")),
8 => (2, 2, 0, To_Unbounded_String("Start equal stop: zero increment")),
9 => (0, 0, 0, To_Unbounded_String("Start equal stop equal zero: zero increment")));
begin
for test of tests loop
Put(Test.Comment); Put(" : ");
print_range(test.start, test.stop, test.step);
New_line;
end loop;
end Main; |
http://rosettacode.org/wiki/Luhn_test_of_credit_card_numbers | Luhn test of credit card numbers | The Luhn test is used by some credit card companies to distinguish valid credit card numbers from what could be a random selection of digits.
Those companies using credit card numbers that can be validated by the Luhn test have numbers that pass the following test:
Reverse the order of the digits in the number.
Take the first, third, ... and every other odd digit in the reversed digits and sum them to form the partial sum s1
Taking the second, fourth ... and every other even digit in the reversed digits:
Multiply each digit by two and sum the digits if the answer is greater than nine to form partial sums for the even digits
Sum the partial sums of the even digits to form s2
If s1 + s2 ends in zero then the original number is in the form of a valid credit card number as verified by the Luhn test.
For example, if the trial number is 49927398716:
Reverse the digits:
61789372994
Sum the odd digits:
6 + 7 + 9 + 7 + 9 + 4 = 42 = s1
The even digits:
1, 8, 3, 2, 9
Two times each even digit:
2, 16, 6, 4, 18
Sum the digits of each multiplication:
2, 7, 6, 4, 9
Sum the last:
2 + 7 + 6 + 4 + 9 = 28 = s2
s1 + s2 = 70 which ends in zero which means that 49927398716 passes the Luhn test
Task
Write a function/method/procedure/subroutine that will validate a number with the Luhn test, and
use it to validate the following numbers:
49927398716
49927398717
1234567812345678
1234567812345670
Related tasks
SEDOL
ISIN
| #8086_Assembly | 8086 Assembly | bits 16
cpu 8086
org 100h
section .text
jmp demo
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;; Check whether the 0-terminated string at DS:SI passes the Luhn
;;; test. Returns with carry clear if the string passes, carry
;;; set if the string fails.
luhn: push es ; Keep original ES, and set ES=DS so SCASB can be used.
push ds ; "REP DS:SCASB" is a bad idea, because the 286 has a
pop es ; bug where it "forgets" the 2nd prefix if interrupted!
mov di,si ; DI = pointer
xor ax,ax ; Zero to test against
xor bl,bl ; BL = S1+S2
mov dx,0A30h ; DH = 10 (divisor), DL = '0' (ASCII zero)
xor cx,cx ; Set counter to 65535
dec cx
cld ; Seek forwards
repnz scasb ; Find zero
dec di ; SCASB goes one byte too far
xchg si,di ; SI = pointer, DI = end (or rather, beginning)
mov cx,si ; CX = counter
sub cx,di
jcxz .done ; Empty string = stop
dec si ; We don't need the zero itself
std ; Seek backwards
.loop: lodsb ; Get number in odd position
sub al,dl ; Subtract ASCII zero
add bl,al ; Add to total
dec cx ; One fewer character
jz .done ; No more characters = stop
lodsb ; Get number in even position
sub al,dl ; Subtract ASCII zero
add al,al ; Multiply by two
xor ah,ah ; AX = AL
div dh ; Divide by 10; AL=quotient, AH=remainder
add al,ah ; Add the two "digits" together
add bl,al ; Add to total
loop .loop ; Decrement CX and loop
.done: xor ah,ah ; Divide total by 10
mov al,bl
div dh
and ah,ah ; If remainder 0, then return with carry clear
jz .out
stc ; Set carry (remainder wasn't 0, the test failed)
.out: cld ; Clean up: clear direction flag,
pop es ; and restore ES.
ret
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;; Run the 'luhn' routine on the argument given on the MS-DOS
;;; command line.
demo: mov si,80h ; Zero-terminate the argument
xor bh,bh
mov bl,[si]
mov [si+bx+1],bh
inc si
inc si
call luhn ; Call the routine
mov ah,9
mov dx,pass ; If carry is clear, print 'Pass'
jnc print
mov dx,fail ; Otherwise, print 'fail'
print: int 21h
ret
section .data
pass: db 'Pass$'
fail: db 'Fail$' |
http://rosettacode.org/wiki/Lucas-Lehmer_test | Lucas-Lehmer test | Lucas-Lehmer Test:
for
p
{\displaystyle p}
an odd prime, the Mersenne number
2
p
−
1
{\displaystyle 2^{p}-1}
is prime if and only if
2
p
−
1
{\displaystyle 2^{p}-1}
divides
S
(
p
−
1
)
{\displaystyle S(p-1)}
where
S
(
n
+
1
)
=
(
S
(
n
)
)
2
−
2
{\displaystyle S(n+1)=(S(n))^{2}-2}
, and
S
(
1
)
=
4
{\displaystyle S(1)=4}
.
Task
Calculate all Mersenne primes up to the implementation's
maximum precision, or the 47th Mersenne prime (whichever comes first).
| #ARM_Assembly | ARM Assembly |
/* ARM assembly Raspberry PI */
/* program lucaslehmer.s */
/* use library gmp */
/* link with gcc option -lgmp */
/* Constantes */
.equ STDOUT, 1 @ Linux output console
.equ EXIT, 1 @ Linux syscall
.equ WRITE, 4 @ Linux syscall
.equ NBRECH, 30
/* Initialized data */
.data
szMessResult: .ascii "Prime : M"
sMessValeur: .fill 11, 1, ' ' @ size => 11
.asciz "\n"
szCarriageReturn: .asciz "\n"
szformat: .asciz "nombre= %Zd\n"
/* UnInitialized data */
.bss
.align 4
spT: .skip 100
mpT: .skip 100
Deux: .skip 100
snT: .skip 100
/* code section */
.text
.global main
main:
ldr r0,iAdrDeux @ create big number = 2
mov r1,#2
bl __gmpz_init_set_ui
ldr r0,iAdrspT @ init big number
bl __gmpz_init
ldr r0,iAdrmpT @ init big number
bl __gmpz_init
mov r5,#3 @ start number
mov r6,#0 @ result counter
1:
ldr r0,iAdrspT @ conversion integer in big number gmp
mov r1,r5
bl __gmpz_set_ui
ldr r0,iAdrspT @ control if exposant is prime !
ldr r0,iAdrspT
mov r1,#25
bl __gmpz_probab_prime_p
cmp r0,#0
beq 5f
2:
//ldr r1,iAdrspT @ example number display
//ldr r0,iAdrszformat
//bl __gmp_printf
/******** Compute (2 pow p) - 1 ******/
ldr r0,iAdrmpT @ compute 2 pow p
ldr r1,iAdrDeux
mov r2,r5
bl __gmpz_pow_ui
ldr r0,iAdrmpT
ldr r1,iAdrmpT
mov r2,#1
bl __gmpz_sub_ui @ then (2 pow p) - 1
ldr r0,iAdrsnT
mov r1,#4
bl __gmpz_init_set_ui @ init big number with 4
/********** Test lucas_lehner *******/
mov r4,#2 @ loop counter
3: @ begin loop
ldr r0,iAdrsnT
ldr r1,iAdrsnT
mov r2,#2
bl __gmpz_pow_ui @ compute square big number
ldr r0,iAdrsnT
ldr r1,iAdrsnT
mov r2,#2
bl __gmpz_sub_ui @ = (sn *sn) - 2
ldr r0,iAdrsnT @ compute remainder -> sn
ldr r1,iAdrsnT @ sn
ldr r2,iAdrmpT @ p
bl __gmpz_tdiv_r
//ldr r1,iAdrsnT @ display number for control
//ldr r0,iAdrszformat
//bl __gmp_printf
add r4,#1 @ increment counter
cmp r4,r5 @ end ?
blt 3b @ no -> loop
@ compare result with zero
ldr r0,iAdrsnT
mov r1,#0
bl __gmpz_cmp_d
cmp r0,#0
bne 5f
/********* is prime display result *********/
mov r0,r5
ldr r1,iAdrsMessValeur @ display value
bl conversion10 @ call conversion decimal
ldr r0,iAdrszMessResult @ display message
bl affichageMess
add r6,#1 @ increment counter result
cmp r6,#NBRECH
bge 10f
5:
add r5,#2 @ increment number by two
b 1b @ and loop
10:
ldr r0,iAdrDeux @ clear memory big number
bl __gmpz_clear
ldr r0,iAdrsnT
bl __gmpz_clear
ldr r0,iAdrmpT
bl __gmpz_clear
ldr r0,iAdrspT
bl __gmpz_clear
100: @ standard end of the program
mov r0, #0 @ return code
mov r7, #EXIT @ request to exit program
svc 0 @ perform system call
iAdrszMessResult: .int szMessResult
iAdrsMessValeur: .int sMessValeur
iAdrszCarriageReturn: .int szCarriageReturn
iAdrszformat: .int szformat
iAdrspT: .int spT
iAdrmpT: .int mpT
iAdrDeux: .int Deux
iAdrsnT: .int snT
/******************************************************************/
/* display text with size calculation */
/******************************************************************/
/* r0 contains the address of the message */
affichageMess:
push {r0,r1,r2,r7,lr} @ save registers
mov r2,#0 @ counter length */
1: @ loop length calculation
ldrb r1,[r0,r2] @ read octet start position + index
cmp r1,#0 @ if 0 its over
addne r2,r2,#1 @ else add 1 in the length
bne 1b @ and loop
@ so here r2 contains the length of the message
mov r1,r0 @ address message in r1
mov r0,#STDOUT @ code to write to the standard output Linux
mov r7, #WRITE @ code call system "write"
svc #0 @ call system
pop {r0,r1,r2,r7,lr} @ restaur registers
bx lr @ return
/******************************************************************/
/* Converting a register to a decimal unsigned */
/******************************************************************/
/* r0 contains value and r1 address area */
/* r0 return size of result (no zero final in area) */
/* area size => 11 bytes */
.equ LGZONECAL, 10
conversion10:
push {r1-r4,lr} @ save registers
mov r3,r1
mov r2,#LGZONECAL
1: @ start loop
bl divisionpar10U @ unsigned r0 <- dividende. quotient ->r0 reste -> r1
add r1,#48 @ digit
strb r1,[r3,r2] @ store digit on area
cmp r0,#0 @ stop if quotient = 0
subne r2,#1 @ else previous position
bne 1b @ and loop
@ and move digit from left of area
mov r4,#0
2:
ldrb r1,[r3,r2]
strb r1,[r3,r4]
add r2,#1
add r4,#1
cmp r2,#LGZONECAL
ble 2b
@ and move spaces in end on area
mov r0,r4 @ result length
mov r1,#' ' @ space
3:
strb r1,[r3,r4] @ store space in area
add r4,#1 @ next position
cmp r4,#LGZONECAL
ble 3b @ loop if r4 <= area size
100:
pop {r1-r4,lr} @ restaur registres
bx lr @return
/***************************************************/
/* division par 10 unsigned */
/***************************************************/
/* r0 dividende */
/* r0 quotient */
/* r1 remainder */
divisionpar10U:
push {r2,r3,r4, lr}
mov r4,r0 @ save value
//mov r3,#0xCCCD @ r3 <- magic_number lower raspberry 3
//movt r3,#0xCCCC @ r3 <- magic_number higter raspberry 3
ldr r3,iMagicNumber @ r3 <- magic_number raspberry 1 2
umull r1, r2, r3, r0 @ r1<- Lower32Bits(r1*r0) r2<- Upper32Bits(r1*r0)
mov r0, r2, LSR #3 @ r2 <- r2 >> shift 3
add r2,r0,r0, lsl #2 @ r2 <- r0 * 5
sub r1,r4,r2, lsl #1 @ r1 <- r4 - (r2 * 2) = r4 - (r0 * 10)
pop {r2,r3,r4,lr}
bx lr @ leave function
iMagicNumber: .int 0xCCCCCCCD
|
http://rosettacode.org/wiki/Lucky_and_even_lucky_numbers | Lucky and even lucky numbers | Note that in the following explanation list indices are assumed to start at one.
Definition of lucky numbers
Lucky numbers are positive integers that are formed by:
Form a list of all the positive odd integers > 0
1
,
3
,
5
,
7
,
9
,
11
,
13
,
15
,
17
,
19
,
21
,
23
,
25
,
27
,
29
,
31
,
33
,
35
,
37
,
39...
{\displaystyle 1,3,5,7,9,11,13,15,17,19,21,23,25,27,29,31,33,35,37,39...}
Return the first number from the list (which is 1).
(Loop begins here)
Note then return the second number from the list (which is 3).
Discard every third, (as noted), number from the list to form the new list
1
,
3
,
7
,
9
,
13
,
15
,
19
,
21
,
25
,
27
,
31
,
33
,
37
,
39
,
43
,
45
,
49
,
51
,
55
,
57...
{\displaystyle 1,3,7,9,13,15,19,21,25,27,31,33,37,39,43,45,49,51,55,57...}
(Expanding the loop a few more times...)
Note then return the third number from the list (which is 7).
Discard every 7th, (as noted), number from the list to form the new list
1
,
3
,
7
,
9
,
13
,
15
,
21
,
25
,
27
,
31
,
33
,
37
,
43
,
45
,
49
,
51
,
55
,
57
,
63
,
67...
{\displaystyle 1,3,7,9,13,15,21,25,27,31,33,37,43,45,49,51,55,57,63,67...}
Note then return the 4th number from the list (which is 9).
Discard every 9th, (as noted), number from the list to form the new list
1
,
3
,
7
,
9
,
13
,
15
,
21
,
25
,
31
,
33
,
37
,
43
,
45
,
49
,
51
,
55
,
63
,
67
,
69
,
73...
{\displaystyle 1,3,7,9,13,15,21,25,31,33,37,43,45,49,51,55,63,67,69,73...}
Take the 5th, i.e. 13. Remove every 13th.
Take the 6th, i.e. 15. Remove every 15th.
Take the 7th, i.e. 21. Remove every 21th.
Take the 8th, i.e. 25. Remove every 25th.
(Rule for the loop)
Note the
n
{\displaystyle n}
th, which is
m
{\displaystyle m}
.
Remove every
m
{\displaystyle m}
th.
Increment
n
{\displaystyle n}
.
Definition of even lucky numbers
This follows the same rules as the definition of lucky numbers above except for the very first step:
Form a list of all the positive even integers > 0
2
,
4
,
6
,
8
,
10
,
12
,
14
,
16
,
18
,
20
,
22
,
24
,
26
,
28
,
30
,
32
,
34
,
36
,
38
,
40...
{\displaystyle 2,4,6,8,10,12,14,16,18,20,22,24,26,28,30,32,34,36,38,40...}
Return the first number from the list (which is 2).
(Loop begins here)
Note then return the second number from the list (which is 4).
Discard every 4th, (as noted), number from the list to form the new list
2
,
4
,
6
,
10
,
12
,
14
,
18
,
20
,
22
,
26
,
28
,
30
,
34
,
36
,
38
,
42
,
44
,
46
,
50
,
52...
{\displaystyle 2,4,6,10,12,14,18,20,22,26,28,30,34,36,38,42,44,46,50,52...}
(Expanding the loop a few more times...)
Note then return the third number from the list (which is 6).
Discard every 6th, (as noted), number from the list to form the new list
2
,
4
,
6
,
10
,
12
,
18
,
20
,
22
,
26
,
28
,
34
,
36
,
38
,
42
,
44
,
50
,
52
,
54
,
58
,
60...
{\displaystyle 2,4,6,10,12,18,20,22,26,28,34,36,38,42,44,50,52,54,58,60...}
Take the 4th, i.e. 10. Remove every 10th.
Take the 5th, i.e. 12. Remove every 12th.
(Rule for the loop)
Note the
n
{\displaystyle n}
th, which is
m
{\displaystyle m}
.
Remove every
m
{\displaystyle m}
th.
Increment
n
{\displaystyle n}
.
Task requirements
Write one or two subroutines (functions) to generate lucky numbers and even lucky numbers
Write a command-line interface to allow selection of which kind of numbers and which number(s). Since input is from the command line, tests should be made for the common errors:
missing arguments
too many arguments
number (or numbers) aren't legal
misspelled argument (lucky or evenLucky)
The command line handling should:
support mixed case handling of the (non-numeric) arguments
support printing a particular number
support printing a range of numbers by their index
support printing a range of numbers by their values
The resulting list of numbers should be printed on a single line.
The program should support the arguments:
what is displayed (on a single line)
argument(s) (optional verbiage is encouraged)
╔═══════════════════╦════════════════════════════════════════════════════╗
║ j ║ Jth lucky number ║
║ j , lucky ║ Jth lucky number ║
║ j , evenLucky ║ Jth even lucky number ║
║ ║ ║
║ j k ║ Jth through Kth (inclusive) lucky numbers ║
║ j k lucky ║ Jth through Kth (inclusive) lucky numbers ║
║ j k evenLucky ║ Jth through Kth (inclusive) even lucky numbers ║
║ ║ ║
║ j -k ║ all lucky numbers in the range j ──► |k| ║
║ j -k lucky ║ all lucky numbers in the range j ──► |k| ║
║ j -k evenLucky ║ all even lucky numbers in the range j ──► |k| ║
╚═══════════════════╩════════════════════════════════════════════════════╝
where |k| is the absolute value of k
Demonstrate the program by:
showing the first twenty lucky numbers
showing the first twenty even lucky numbers
showing all lucky numbers between 6,000 and 6,100 (inclusive)
showing all even lucky numbers in the same range as above
showing the 10,000th lucky number (extra credit)
showing the 10,000th even lucky number (extra credit)
See also
This task is related to the Sieve of Eratosthenes task.
OEIS Wiki Lucky numbers.
Sequence A000959 lucky numbers on The On-Line Encyclopedia of Integer Sequences.
Sequence A045954 even lucky numbers or ELN on The On-Line Encyclopedia of Integer Sequences.
Entry lucky numbers on The Eric Weisstein's World of Mathematics.
| #F.23 | F# |
// Odd and Even Lucky Numbers. Nigel Galloway: October 3rd., 2020
let rec fN i g e l=seq{yield! i|>Seq.skip g|>Seq.take(e-g-1)
let n=Seq.chunkBySize e i|>Seq.collect(Seq.take(e-1)) in yield! fN n (e-1) (Seq.item l n) (l+1)}
let oLuck,eLuck=let rec fG g=seq{yield g; yield! fG(g+2)} in (fN(fG 1) 0 3 2,fN(fG 2) 0 4 2)
|
http://rosettacode.org/wiki/LZW_compression | LZW compression | The Lempel-Ziv-Welch (LZW) algorithm provides loss-less data compression.
You can read a complete description of it in the Wikipedia article on the subject. It was patented, but it entered the public domain in 2004.
| #BBC_BASIC | BBC BASIC | plaintext$ = "TOBEORNOTTOBEORTOBEORNOT"
encodeLZW$ = FNencodeLZW(plaintext$)
FOR i% = 1 TO LEN(encodeLZW$) STEP 2
PRINT ; ASCMID$(encodeLZW$,i%) + 256*ASCMID$(encodeLZW$,i%+1) " " ;
NEXT
PRINT ' FNdecodeLZW(encodeLZW$)
END
DEF FNencodeLZW(i$)
LOCAL c%, d%, i%, l%, o$, w$, dict$()
DIM dict$(4095)
FOR i% = 0 TO 255 : dict$(i%) = CHR$(i%) : NEXT
l% = i%
i% = 1
w$ = LEFT$(i$,1)
REPEAT
d% = 0
REPEAT
c% = d%
IF i% > LEN(i$) EXIT REPEAT
FOR d% = 1 TO l%-1
IF w$ = dict$(d%) EXIT FOR
NEXT d%
IF d% < l% i% += 1 : w$ += MID$(i$, i%, 1)
UNTIL d% >= l%
dict$(l%) = w$ : l% += 1 : w$ = RIGHT$(w$)
o$ += CHR$(c% MOD 256) + CHR$(c% DIV 256)
UNTIL i% >= LEN(i$)
= o$
DEF FNdecodeLZW(i$)
LOCAL c%, i%, l%, o$, t$, w$, dict$()
DIM dict$(4095)
FOR i% = 0 TO 255 : dict$(i%) = CHR$(i%) : NEXT
l% = i%
c% = ASC(i$) + 256*ASCMID$(i$,2)
w$ = dict$(c%)
o$ = w$
IF LEN(i$) < 4 THEN = o$
FOR i% = 3 TO LEN(i$) STEP 2
c% = ASCMID$(i$,i%) + 256*ASCMID$(i$,i%+1)
IF c% < l% t$ = dict$(c%) ELSE t$ = w$ + LEFT$(w$,1)
o$ += t$
dict$(l%) = w$ + LEFT$(t$,1)
l% += 1
w$ = t$
NEXT
= o$ |
http://rosettacode.org/wiki/LU_decomposition | LU decomposition | Every square matrix
A
{\displaystyle A}
can be decomposed into a product of a lower triangular matrix
L
{\displaystyle L}
and a upper triangular matrix
U
{\displaystyle U}
,
as described in LU decomposition.
A
=
L
U
{\displaystyle A=LU}
It is a modified form of Gaussian elimination.
While the Cholesky decomposition only works for symmetric,
positive definite matrices, the more general LU decomposition
works for any square matrix.
There are several algorithms for calculating L and U.
To derive Crout's algorithm for a 3x3 example,
we have to solve the following system:
A
=
(
a
11
a
12
a
13
a
21
a
22
a
23
a
31
a
32
a
33
)
=
(
l
11
0
0
l
21
l
22
0
l
31
l
32
l
33
)
(
u
11
u
12
u
13
0
u
22
u
23
0
0
u
33
)
=
L
U
{\displaystyle A={\begin{pmatrix}a_{11}&a_{12}&a_{13}\\a_{21}&a_{22}&a_{23}\\a_{31}&a_{32}&a_{33}\\\end{pmatrix}}={\begin{pmatrix}l_{11}&0&0\\l_{21}&l_{22}&0\\l_{31}&l_{32}&l_{33}\\\end{pmatrix}}{\begin{pmatrix}u_{11}&u_{12}&u_{13}\\0&u_{22}&u_{23}\\0&0&u_{33}\end{pmatrix}}=LU}
We now would have to solve 9 equations with 12 unknowns. To make the system uniquely solvable, usually the diagonal elements of
L
{\displaystyle L}
are set to 1
l
11
=
1
{\displaystyle l_{11}=1}
l
22
=
1
{\displaystyle l_{22}=1}
l
33
=
1
{\displaystyle l_{33}=1}
so we get a solvable system of 9 unknowns and 9 equations.
A
=
(
a
11
a
12
a
13
a
21
a
22
a
23
a
31
a
32
a
33
)
=
(
1
0
0
l
21
1
0
l
31
l
32
1
)
(
u
11
u
12
u
13
0
u
22
u
23
0
0
u
33
)
=
(
u
11
u
12
u
13
u
11
l
21
u
12
l
21
+
u
22
u
13
l
21
+
u
23
u
11
l
31
u
12
l
31
+
u
22
l
32
u
13
l
31
+
u
23
l
32
+
u
33
)
=
L
U
{\displaystyle A={\begin{pmatrix}a_{11}&a_{12}&a_{13}\\a_{21}&a_{22}&a_{23}\\a_{31}&a_{32}&a_{33}\\\end{pmatrix}}={\begin{pmatrix}1&0&0\\l_{21}&1&0\\l_{31}&l_{32}&1\\\end{pmatrix}}{\begin{pmatrix}u_{11}&u_{12}&u_{13}\\0&u_{22}&u_{23}\\0&0&u_{33}\end{pmatrix}}={\begin{pmatrix}u_{11}&u_{12}&u_{13}\\u_{11}l_{21}&u_{12}l_{21}+u_{22}&u_{13}l_{21}+u_{23}\\u_{11}l_{31}&u_{12}l_{31}+u_{22}l_{32}&u_{13}l_{31}+u_{23}l_{32}+u_{33}\end{pmatrix}}=LU}
Solving for the other
l
{\displaystyle l}
and
u
{\displaystyle u}
, we get the following equations:
u
11
=
a
11
{\displaystyle u_{11}=a_{11}}
u
12
=
a
12
{\displaystyle u_{12}=a_{12}}
u
13
=
a
13
{\displaystyle u_{13}=a_{13}}
u
22
=
a
22
−
u
12
l
21
{\displaystyle u_{22}=a_{22}-u_{12}l_{21}}
u
23
=
a
23
−
u
13
l
21
{\displaystyle u_{23}=a_{23}-u_{13}l_{21}}
u
33
=
a
33
−
(
u
13
l
31
+
u
23
l
32
)
{\displaystyle u_{33}=a_{33}-(u_{13}l_{31}+u_{23}l_{32})}
and for
l
{\displaystyle l}
:
l
21
=
1
u
11
a
21
{\displaystyle l_{21}={\frac {1}{u_{11}}}a_{21}}
l
31
=
1
u
11
a
31
{\displaystyle l_{31}={\frac {1}{u_{11}}}a_{31}}
l
32
=
1
u
22
(
a
32
−
u
12
l
31
)
{\displaystyle l_{32}={\frac {1}{u_{22}}}(a_{32}-u_{12}l_{31})}
We see that there is a calculation pattern, which can be expressed as the following formulas, first for
U
{\displaystyle U}
u
i
j
=
a
i
j
−
∑
k
=
1
i
−
1
u
k
j
l
i
k
{\displaystyle u_{ij}=a_{ij}-\sum _{k=1}^{i-1}u_{kj}l_{ik}}
and then for
L
{\displaystyle L}
l
i
j
=
1
u
j
j
(
a
i
j
−
∑
k
=
1
j
−
1
u
k
j
l
i
k
)
{\displaystyle l_{ij}={\frac {1}{u_{jj}}}(a_{ij}-\sum _{k=1}^{j-1}u_{kj}l_{ik})}
We see in the second formula that to get the
l
i
j
{\displaystyle l_{ij}}
below the diagonal, we have to divide by the diagonal element (pivot)
u
j
j
{\displaystyle u_{jj}}
, so we get problems when
u
j
j
{\displaystyle u_{jj}}
is either 0 or very small, which leads to numerical instability.
The solution to this problem is pivoting
A
{\displaystyle A}
, which means rearranging the rows of
A
{\displaystyle A}
, prior to the
L
U
{\displaystyle LU}
decomposition, in a way that the largest element of each column gets onto the diagonal of
A
{\displaystyle A}
. Rearranging the rows means to multiply
A
{\displaystyle A}
by a permutation matrix
P
{\displaystyle P}
:
P
A
⇒
A
′
{\displaystyle PA\Rightarrow A'}
Example:
(
0
1
1
0
)
(
1
4
2
3
)
⇒
(
2
3
1
4
)
{\displaystyle {\begin{pmatrix}0&1\\1&0\end{pmatrix}}{\begin{pmatrix}1&4\\2&3\end{pmatrix}}\Rightarrow {\begin{pmatrix}2&3\\1&4\end{pmatrix}}}
The decomposition algorithm is then applied on the rearranged matrix so that
P
A
=
L
U
{\displaystyle PA=LU}
Task description
The task is to implement a routine which will take a square nxn matrix
A
{\displaystyle A}
and return a lower triangular matrix
L
{\displaystyle L}
, a upper triangular matrix
U
{\displaystyle U}
and a permutation matrix
P
{\displaystyle P}
,
so that the above equation is fulfilled.
You should then test it on the following two examples and include your output.
Example 1
A
1 3 5
2 4 7
1 1 0
L
1.00000 0.00000 0.00000
0.50000 1.00000 0.00000
0.50000 -1.00000 1.00000
U
2.00000 4.00000 7.00000
0.00000 1.00000 1.50000
0.00000 0.00000 -2.00000
P
0 1 0
1 0 0
0 0 1
Example 2
A
11 9 24 2
1 5 2 6
3 17 18 1
2 5 7 1
L
1.00000 0.00000 0.00000 0.00000
0.27273 1.00000 0.00000 0.00000
0.09091 0.28750 1.00000 0.00000
0.18182 0.23125 0.00360 1.00000
U
11.00000 9.00000 24.00000 2.00000
0.00000 14.54545 11.45455 0.45455
0.00000 0.00000 -3.47500 5.68750
0.00000 0.00000 0.00000 0.51079
P
1 0 0 0
0 0 1 0
0 1 0 0
0 0 0 1
| #C | C | #include <stdio.h>
#include <stdlib.h>
#include <math.h>
#define foreach(a, b, c) for (int a = b; a < c; a++)
#define for_i foreach(i, 0, n)
#define for_j foreach(j, 0, n)
#define for_k foreach(k, 0, n)
#define for_ij for_i for_j
#define for_ijk for_ij for_k
#define _dim int n
#define _swap(x, y) { typeof(x) tmp = x; x = y; y = tmp; }
#define _sum_k(a, b, c, s) { s = 0; foreach(k, a, b) s+= c; }
typedef double **mat;
#define _zero(a) mat_zero(a, n)
void mat_zero(mat x, int n) { for_ij x[i][j] = 0; }
#define _new(a) a = mat_new(n)
mat mat_new(_dim)
{
mat x = malloc(sizeof(double*) * n);
x[0] = malloc(sizeof(double) * n * n);
for_i x[i] = x[0] + n * i;
_zero(x);
return x;
}
#define _copy(a) mat_copy(a, n)
mat mat_copy(void *s, _dim)
{
mat x = mat_new(n);
for_ij x[i][j] = ((double (*)[n])s)[i][j];
return x;
}
#define _del(x) mat_del(x)
void mat_del(mat x) { free(x[0]); free(x); }
#define _QUOT(x) #x
#define QUOTE(x) _QUOT(x)
#define _show(a) printf(QUOTE(a)" =");mat_show(a, 0, n)
void mat_show(mat x, char *fmt, _dim)
{
if (!fmt) fmt = "%8.4g";
for_i {
printf(i ? " " : " [ ");
for_j {
printf(fmt, x[i][j]);
printf(j < n - 1 ? " " : i == n - 1 ? " ]\n" : "\n");
}
}
}
#define _mul(a, b) mat_mul(a, b, n)
mat mat_mul(mat a, mat b, _dim)
{
mat c = _new(c);
for_ijk c[i][j] += a[i][k] * b[k][j];
return c;
}
#define _pivot(a, b) mat_pivot(a, b, n)
void mat_pivot(mat a, mat p, _dim)
{
for_ij { p[i][j] = (i == j); }
for_i {
int max_j = i;
foreach(j, i, n)
if (fabs(a[j][i]) > fabs(a[max_j][i])) max_j = j;
if (max_j != i)
for_k { _swap(p[i][k], p[max_j][k]); }
}
}
#define _LU(a, l, u, p) mat_LU(a, l, u, p, n)
void mat_LU(mat A, mat L, mat U, mat P, _dim)
{
_zero(L); _zero(U);
_pivot(A, P);
mat Aprime = _mul(P, A);
for_i { L[i][i] = 1; }
for_ij {
double s;
if (j <= i) {
_sum_k(0, j, L[j][k] * U[k][i], s)
U[j][i] = Aprime[j][i] - s;
}
if (j >= i) {
_sum_k(0, i, L[j][k] * U[k][i], s);
L[j][i] = (Aprime[j][i] - s) / U[i][i];
}
}
_del(Aprime);
}
double A3[][3] = {{ 1, 3, 5 }, { 2, 4, 7 }, { 1, 1, 0 }};
double A4[][4] = {{11, 9, 24, 2}, {1, 5, 2, 6}, {3, 17, 18, 1}, {2, 5, 7, 1}};
int main()
{
int n = 3;
mat A, L, P, U;
_new(L); _new(P); _new(U);
A = _copy(A3);
_LU(A, L, U, P);
_show(A); _show(L); _show(U); _show(P);
_del(A); _del(L); _del(U); _del(P);
printf("\n");
n = 4;
_new(L); _new(P); _new(U);
A = _copy(A4);
_LU(A, L, U, P);
_show(A); _show(L); _show(U); _show(P);
_del(A); _del(L); _del(U); _del(P);
return 0;
} |
http://rosettacode.org/wiki/Lychrel_numbers | Lychrel numbers | Take an integer n, greater than zero.
Form the next n of its series by reversing the digits of the current n and adding the result to the current n.
Stop when n becomes palindromic - i.e. the digits of n in reverse order == n.
The above recurrence relation when applied to most starting numbers n = 1, 2, ... terminates in a palindrome quite quickly.
Example
If n0 = 12 we get
12
12 + 21 = 33, a palindrome!
And if n0 = 55 we get
55
55 + 55 = 110
110 + 011 = 121, a palindrome!
Notice that the check for a palindrome happens after an addition.
Some starting numbers seem to go on forever; the recurrence relation for 196 has been calculated for millions of repetitions forming numbers with millions of digits, without forming a palindrome.
These numbers that do not end in a palindrome are called Lychrel numbers.
For the purposes of this task a Lychrel number is any starting number that does not form a palindrome within 500 (or more) iterations.
Seed and related Lychrel numbers
Any integer produced in the sequence of a Lychrel number is also a Lychrel number.
In general, any sequence from one Lychrel number might converge to join the sequence from a prior Lychrel number candidate; for example the sequences for the numbers 196 and then 689 begin:
196
196 + 691 = 887
887 + 788 = 1675
1675 + 5761 = 7436
7436 + 6347 = 13783
13783 + 38731 = 52514
52514 + 41525 = 94039
...
689
689 + 986 = 1675
1675 + 5761 = 7436
...
So we see that the sequence starting with 689 converges to, and continues with the same numbers as that for 196.
Because of this we can further split the Lychrel numbers into true Seed Lychrel number candidates, and Related numbers that produce no palindromes but have integers in their sequence seen as part of the sequence generated from a lower Lychrel number.
Task
Find the number of seed Lychrel number candidates and related numbers for n in the range 1..10000 inclusive. (With that iteration limit of 500).
Print the number of seed Lychrels found; the actual seed Lychrels; and just the number of relateds found.
Print any seed Lychrel or related number that is itself a palindrome.
Show all output here.
References
What's special about 196? Numberphile video.
A023108 Positive integers which apparently never result in a palindrome under repeated applications of the function f(x) = x + (x with digits reversed).
Status of the 196 conjecture? Mathoverflow.
| #Go | Go | package main
import (
"flag"
"fmt"
"math"
"math/big"
"os"
)
var maxRev = big.NewInt(math.MaxUint64 / 10) // approximate
var ten = big.NewInt(10)
// Reverse sets `result` to the value of the base ten digits of `v` in
// reverse order and returns `result`.
// Only handles positive integers.
func reverseInt(v *big.Int, result *big.Int) *big.Int {
if v.Cmp(maxRev) <= 0 {
// optimize small values that fit within uint64
result.SetUint64(reverseUint64(v.Uint64()))
} else {
if true {
// Reverse the string representation
s := reverseString(v.String())
result.SetString(s, 10)
} else {
// This has fewer allocations but is slower:
// Use a copy of `v` since we mutate it.
v := new(big.Int).Set(v)
digit := new(big.Int)
result.SetUint64(0)
for v.BitLen() > 0 {
v.QuoRem(v, ten, digit)
result.Mul(result, ten)
result.Add(result, digit)
}
}
}
return result
}
func reverseUint64(v uint64) uint64 {
var r uint64
for v > 0 {
r *= 10
r += v % 10
v /= 10
}
return r
}
func reverseString(s string) string {
b := make([]byte, len(s))
for i, j := 0, len(s)-1; j >= 0; i, j = i+1, j-1 {
b[i] = s[j]
}
return string(b)
}
var known = make(map[string]bool)
func Lychrel(n uint64, iter uint) (isLychrel, isSeed bool) {
v, r := new(big.Int).SetUint64(n), new(big.Int)
reverseInt(v, r)
seen := make(map[string]bool)
isLychrel = true
isSeed = true
for i := iter; i > 0; i-- {
str := v.String()
if seen[str] {
//log.Println("found a loop with", n, "at", str)
isLychrel = true
break
}
if ans, ok := known[str]; ok {
//log.Println("already know:", str, ans)
isLychrel = ans
isSeed = false
break
}
seen[str] = true
v = v.Add(v, r)
//log.Printf("%v + %v = %v\n", str, r, v)
reverseInt(v, r)
if v.Cmp(r) == 0 {
//log.Println(v, "is a palindrome,", n, "is not a Lychrel number")
isLychrel = false
isSeed = false
break
}
}
for k := range seen {
known[k] = isLychrel
}
//if isLychrel { log.Printf("%v may be a Lychrel number\n", n) }
return isLychrel, isSeed
}
func main() {
max := flag.Uint64("max", 10000, "search in the range 1..`N` inclusive")
iter := flag.Uint("iter", 500, "limit palindrome search to `N` iterations")
flag.Parse()
if flag.NArg() != 0 {
flag.Usage()
os.Exit(2)
}
fmt.Printf("Calculating using n = 1..%v and %v iterations:\n", *max, *iter)
var seeds []uint64
var related int
var pals []uint64
for i := uint64(1); i <= *max; i++ {
if l, s := Lychrel(i, *iter); l {
if s {
seeds = append(seeds, i)
} else {
related++
}
if i == reverseUint64(i) {
pals = append(pals, i)
}
}
}
fmt.Println(" Number of Lychrel seeds:", len(seeds))
fmt.Println(" Lychrel seeds:", seeds)
fmt.Println(" Number of related:", related)
fmt.Println("Number of Lychrel palindromes:", len(pals))
fmt.Println(" Lychrel palindromes:", pals)
} |
http://rosettacode.org/wiki/Magic_8-ball | Magic 8-ball | Task
Create Magic 8-Ball.
See details at: Magic 8-Ball.
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
| #Raku | Raku | put 'Please enter your question or a blank line to quit.';
["It is certain", "It is decidedly so", "Without a doubt", "Yes, definitely",
"You may rely on it", "As I see it, yes", "Most likely", "Outlook good",
"Signs point to yes", "Yes", "Reply hazy, try again", "Ask again later",
"Better not tell you now", "Cannot predict now", "Concentrate and ask again",
"Don't bet on it", "My reply is no", "My sources say no", "Outlook not so good",
"Very doubtful"].roll.put while prompt('? : ').chars; |
http://rosettacode.org/wiki/Mandelbrot_set | Mandelbrot set | Mandelbrot set
You are encouraged to solve this task according to the task description, using any language you may know.
Task
Generate and draw the Mandelbrot set.
Note that there are many algorithms to draw Mandelbrot set and there are many functions which generate it .
| #Vedit_macro_language | Vedit macro language | #1 =-21000 // left edge = -2.1
#2 = 15000 // right edge = 1.5
#3 = 15000 // top edge = 1.5
#4 =-15000 // bottom edge = -1.5
#5 = 200 // max iteration depth
#6 = 350 // x step size
#7 = 750 // y step size
Buf_Switch(Buf_Free)
for (#12 = #3; #12 > #4; #12 -= #7) { // y0
for (#11 = #1; #11 < #2; #11 += #6) { // x0
#22 = 0 // y
#21 = 0 // x
#9 = ' ' // char to be displayed
for (#15 = 0; #15 < #5; #15++) { // iteration
#31 = (#21/10 * #21) / 1000 // x*x
#32 = (#22/10 * #22) / 1000 // y*y
if (#31 + #32 > 40000) {
#9 = '0' + #15 // print digit 0...9
if (#15 > 9) { // if iteration count > 9,
#9 = '@' // print '@'
}
break
}
#33 = #31 - #32 + #11 // temp = x*x - y*y + x0
#22 = (#21/10 * #22) / 500 + #12 // y = 2*x*y + y0
#21 = #33 // x = temp
}
Ins_Char(#9)
}
Ins_Newline
}
BOF
|
http://rosettacode.org/wiki/Mad_Libs | Mad Libs |
This page uses content from Wikipedia. The original article was at Mad Libs. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance)
Mad Libs is a phrasal template word game where one player prompts another for a list of words to substitute for blanks in a story, usually with funny results.
Task;
Write a program to create a Mad Libs like story.
The program should read an arbitrary multiline story from input.
The story will be terminated with a blank line.
Then, find each replacement to be made within the story, ask the user for a word to replace it with, and make all the replacements.
Stop when there are none left and print the final story.
The input should be an arbitrary story in the form:
<name> went for a walk in the park. <he or she>
found a <noun>. <name> decided to take it home.
Given this example, it should then ask for a name, a he or she and a noun (<name> gets replaced both times with the same value).
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
| #Erlang | Erlang | -module(madlib).
-compile(export_all).
main() ->
main([]).
main([]) ->
madlib(standard_io);
main([File]) ->
{ok, F} = file:open(File,read),
madlib(F).
madlib(Device) ->
{Dict, Lines} = parse(Device),
Substitutions = prompt(Dict),
print(Substitutions, Lines).
prompt(Dict) ->
Keys = dict:fetch_keys(Dict),
lists:foldl(fun (K,D) ->
S = io:get_line(io_lib:format("Please name a ~s: ",[K])),
dict:store(K, lists:reverse(tl(lists:reverse(S))), D)
end, Dict, Keys).
print(Dict,Lines) ->
lists:foreach(fun (Line) ->
io:format("~s",[substitute(Dict,Line)])
end, Lines).
substitute(Dict,Line) ->
Keys = dict:fetch_keys(Dict),
lists:foldl(fun (K,L) ->
re:replace(L,K,dict:fetch(K,Dict),[global,{return,list}])
end, Line, Keys).
parse(Device) ->
parse(Device, dict:new(),[]).
parse(Device, Dict,Lines) ->
case io:get_line(Device,"") of
eof ->
{Dict, lists:reverse(Lines)};
"\n" ->
{Dict, lists:reverse(Lines)};
Line ->
parse(Device, parse_line(Dict, Line), [Line|Lines])
end.
parse_line(Dict, Line) ->
{match,Matches} = re:run(Line,"<.*?>",[global,{capture,[0],list}]),
lists:foldl(fun ([M],D) ->
dict:store(M,"",D)
end, Dict, Matches). |
http://rosettacode.org/wiki/Loops/With_multiple_ranges | Loops/With multiple ranges | Loops/With multiple ranges
You are encouraged to solve this task according to the task description, using any language you may know.
Some languages allow multiple loop ranges, such as the PL/I example (snippet) below.
/* all variables are DECLARED as integers. */
prod= 1; /*start with a product of unity. */
sum= 0; /* " " " sum " zero. */
x= +5;
y= -5;
z= -2;
one= 1;
three= 3;
seven= 7;
/*(below) ** is exponentiation: 4**3=64 */
do j= -three to 3**3 by three ,
-seven to +seven by x ,
555 to 550 - y ,
22 to -28 by -three ,
1927 to 1939 ,
x to y by z ,
11**x to 11**x + one;
/* ABS(n) = absolute value*/
sum= sum + abs(j); /*add absolute value of J.*/
if abs(prod)<2**27 & j¬=0 then prod=prod*j; /*PROD is small enough & J*/
end; /*not 0, then multiply it.*/
/*SUM and PROD are used for verification of J incrementation.*/
display (' sum= ' || sum); /*display strings to term.*/
display ('prod= ' || prod); /* " " " " */
Task
Simulate/translate the above PL/I program snippet as best as possible in your
language, with particular emphasis on the do loop construct.
The do index must be incremented/decremented in the same order shown.
If feasible, add commas to the two output numbers (being displayed).
Show all output here.
A simple PL/I DO loop (incrementing or decrementing) has the construct of:
DO variable = start_expression {TO ending_expression] {BY increment_expression} ;
---or---
DO variable = start_expression {BY increment_expression} {TO ending_expression] ;
where it is understood that all expressions will have a value. The variable is normally a
scaler variable, but need not be (but for this task, all variables and expressions are declared
to be scaler integers). If the BY expression is omitted, a BY value of unity is used.
All expressions are evaluated before the DO loop is executed, and those values are used
throughout the DO loop execution (even though, for instance, the value of Z may be
changed within the DO loop. This isn't the case here for this task.
A multiple-range DO loop can be constructed by using a comma (,) to separate additional ranges
(the use of multiple TO and/or BY keywords). This is the construct used in this task.
There are other forms of DO loops in PL/I involving the WHILE clause, but those won't be
needed here. DO loops without a TO clause might need a WHILE clause or some other
means of exiting the loop (such as LEAVE, RETURN, SIGNAL, GOTO, or STOP), or some other
(possible error) condition that causes transfer of control outside the DO loop.
Also, in PL/I, the check if the DO loop index value is outside the range is made at the
"head" (start) of the DO loop, so it's possible that the DO loop isn't executed, but
that isn't the case for any of the ranges used in this task.
In the example above, the clause: x to y by z
will cause the variable J to have to following values (in this order): 5 3 1 -1 -3 -5
In the example above, the clause: -seven to +seven by x
will cause the variable J to have to following values (in this order): -7 -2 3
Related tasks
Loop over multiple arrays simultaneously
Loops/Break
Loops/Continue
Loops/Do-while
Loops/Downward for
Loops/For
Loops/For with a specified step
Loops/Foreach
Loops/Increment loop index within loop body
Loops/Infinite
Loops/N plus one half
Loops/Nested
Loops/While
Loops/with multiple ranges
Loops/Wrong ranges
| #11l | 11l | V prod = 1
V s = 0
-V
x = +5
y = -5
z = -2
one = 1
three = 3
seven = 7
F body(j)
:s += abs(j)
I abs(:prod) < 2 ^ 27 & j != 0
:prod *= j
L(j) (-three .. 3 ^ 3).step(three) {body(j)}
L(j) (-seven .. seven).step(x) {body(j)}
L(j) 555 .. 550 - y {body(j)}
L(j) (22 .. -28).step(-three) {body(j)}
L(j) 1927 .. 1939 {body(j)}
L(j) (x .. y).step(z) {body(j)}
L(j) 11 ^ x .. 11 ^ x + one {body(j)}
V ss = String(s)
V ps = String(prod)
V m = max(ss.len, ps.len)
print(‘ sum = ’ss.rjust(m))
print(‘prod = ’ps.rjust(m)) |
http://rosettacode.org/wiki/Ludic_numbers | Ludic numbers | Ludic numbers are related to prime numbers as they are generated by a sieve quite like the Sieve of Eratosthenes is used to generate prime numbers.
The first ludic number is 1.
To generate succeeding ludic numbers create an array of increasing integers starting from 2.
2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 ...
(Loop)
Take the first member of the resultant array as the next ludic number 2.
Remove every 2nd indexed item from the array (including the first).
2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 ...
(Unrolling a few loops...)
Take the first member of the resultant array as the next ludic number 3.
Remove every 3rd indexed item from the array (including the first).
3 5 7 9 11 13 15 17 19 21 23 25 27 29 31 33 35 37 39 41 43 45 47 49 51 ...
Take the first member of the resultant array as the next ludic number 5.
Remove every 5th indexed item from the array (including the first).
5 7 11 13 17 19 23 25 29 31 35 37 41 43 47 49 53 55 59 61 65 67 71 73 77 ...
Take the first member of the resultant array as the next ludic number 7.
Remove every 7th indexed item from the array (including the first).
7 11 13 17 23 25 29 31 37 41 43 47 53 55 59 61 67 71 73 77 83 85 89 91 97 ...
...
Take the first member of the current array as the next ludic number L.
Remove every Lth indexed item from the array (including the first).
...
Task
Generate and show here the first 25 ludic numbers.
How many ludic numbers are there less than or equal to 1000?
Show the 2000..2005th ludic numbers.
Stretch goal
Show all triplets of ludic numbers < 250.
A triplet is any three numbers
x
,
{\displaystyle x,}
x
+
2
,
{\displaystyle x+2,}
x
+
6
{\displaystyle x+6}
where all three numbers are also ludic numbers.
| #FreeBASIC | FreeBASIC | ' FB 1.05.0 Win64
' As it would be too expensive to actually remove elements from the array
' we instead set an element to 0 if it has been removed.
Sub ludic(n As Integer, lu() As Integer)
If n < 1 Then Return
Redim lu(1 To n)
lu(1) = 1
If n = 1 Then Return
Dim As Integer count = 1, count2
Dim As Integer i, j, k = 1
Dim As Integer ub = 22000 '' big enough to deal with up to 2005 ludic numbers
Dim a(2 To ub) As Integer
For i = 2 To ub : a(i) = i : Next
Do
k += 1
For i = k to ub
If a(i) > 0 Then
count += 1
lu(count) = a(i)
If n = count Then Return
a(i) = 0
k = i
Exit For
End If
Next
count2 = 0
j = k + 1
While j <= ub
If a(j) > 0 Then
count2 +=1
If count2 = k Then
a(j) = 0
count2 = 0
End If
End If
j += 1
Wend
Loop
End Sub
Dim i As Integer
Dim lu() As Integer
ludic(2005, lu())
Print "The first 25 Ludic numbers are :"
For i = 1 To 25
Print Using "###"; lu(i);
Print " ";
Next
Print
Dim As Integer Count = 0
For i = 1 To 1000
If lu(i) <= 1000 Then
count += 1
Else
Exit For
End If
Next
Print
Print "There are"; count; " Ludic numbers <= 1000"
Print
Print "The 2000th to 2005th Ludics are :"
For i = 2000 To 2005
Print lu(i); " ";
Next
Print : Print
Print "The Ludic triplets below 250 are : "
Dim As Integer j, k, ldc
Dim b As Boolean
For i = 1 To 248
ldc = lu(i)
If ldc >= 244 Then Exit For
b = False
For j = i + 1 To 249
If lu(j) = ldc + 2 Then
b = True
k = j
Exit For
ElseIf lu(j) > ldc + 2 Then
Exit For
End If
Next j
If b = False Then Continue For
For j = k + 1 To 250
If lu(j) = ldc + 6 Then
Print "("; Str(ldc); ","; ldc + 2; ","; ldc + 6; ")"
Exit For
ElseIf lu(j) > ldc + 6 Then
Exit For
End If
Next j
Next i
Erase lu
Print
Print "Press any key to quit"
Sleep |
http://rosettacode.org/wiki/Loops/Wrong_ranges | Loops/Wrong ranges | Loops/Wrong ranges
You are encouraged to solve this task according to the task description, using any language you may know.
Some languages have syntax or function(s) to generate a range of numeric values from a start value, a stop value, and an increment.
The purpose of this task is to select the range syntax/function that would generate at least two increasing numbers when given a stop value more than the start value and a positive increment of less than half the difference. You are then to use that same syntax/function but with different parameters; and show, here, what would happen.
Use these values if possible:
start
stop
increment
Comment
-2
2
1
Normal
-2
2
0
Zero increment
-2
2
-1
Increments away from stop value
-2
2
10
First increment is beyond stop value
2
-2
1
Start more than stop: positive increment
2
2
1
Start equal stop: positive increment
2
2
-1
Start equal stop: negative increment
2
2
0
Start equal stop: zero increment
0
0
0
Start equal stop equal zero: zero increment
Related tasks
Loop over multiple arrays simultaneously
Loops/Break
Loops/Continue
Loops/Do-while
Loops/Downward for
Loops/For
Loops/For with a specified step
Loops/Foreach
Loops/Increment loop index within loop body
Loops/Infinite
Loops/N plus one half
Loops/Nested
Loops/While
Loops/with multiple ranges
Loops/Wrong ranges
| #ALGOL_W | ALGOL W | begin
% sets the first n elements of s to the sequences of values specified by start, stop and increment %
% s( 0 ) is set to the number of elements of s that have been set, in case the sequence ends before n %
procedure sequence ( integer array s ( * )
; integer value n, start, stop, increment
) ;
begin
integer sPos;
for j := 0 until n do s( j ) := 0;
sPos := 1;
for j := start step increment until stop do begin
if sPos > n then goto done;
s( sPos ) := j;
s( 0 ) := s( 0 ) + 1;
sPos := sPos + 1;
end for_j ;
done:
end sequence ;
% tests the sequence procedure %
procedure testSequence( integer value start, stop, increment
; string(48) value legend
) ;
begin
integer array s ( 0 :: 10 );
sequence( s, 10, start, stop, increment );
s_w := 0; % set output formating %
i_w := 4;
write( legend, ": " );
for i := 1 until s( 0 ) do writeon( s( i ) )
end testSequence ;
% task trest cases %
testSequence( -2, 2, 1, "Normal" );
testSequence( -2, 2, 0, "Zero increment" );
testSequence( -2, 2, -1, "Increments away from stop value" );
testSequence( -2, 2, 10, "First increment is beyond stop value" );
testSequence( 2, -2, 1, "Start more than stop: positive increment" );
testSequence( 2, 2, 1, "Start equal stop: positive increment" );
testSequence( 2, 2, -1, "Start equal stop: negative increment" );
testSequence( 2, 2, 0, "Start equal stop: zero increment" );
testSequence( 0, 0, 0, "Start equal stop equal zero: zero increment" )
end. |
http://rosettacode.org/wiki/Loops/Wrong_ranges | Loops/Wrong ranges | Loops/Wrong ranges
You are encouraged to solve this task according to the task description, using any language you may know.
Some languages have syntax or function(s) to generate a range of numeric values from a start value, a stop value, and an increment.
The purpose of this task is to select the range syntax/function that would generate at least two increasing numbers when given a stop value more than the start value and a positive increment of less than half the difference. You are then to use that same syntax/function but with different parameters; and show, here, what would happen.
Use these values if possible:
start
stop
increment
Comment
-2
2
1
Normal
-2
2
0
Zero increment
-2
2
-1
Increments away from stop value
-2
2
10
First increment is beyond stop value
2
-2
1
Start more than stop: positive increment
2
2
1
Start equal stop: positive increment
2
2
-1
Start equal stop: negative increment
2
2
0
Start equal stop: zero increment
0
0
0
Start equal stop equal zero: zero increment
Related tasks
Loop over multiple arrays simultaneously
Loops/Break
Loops/Continue
Loops/Do-while
Loops/Downward for
Loops/For
Loops/For with a specified step
Loops/Foreach
Loops/Increment loop index within loop body
Loops/Infinite
Loops/N plus one half
Loops/Nested
Loops/While
Loops/with multiple ranges
Loops/Wrong ranges
| #Applesoft_BASIC | Applesoft BASIC | 0 LIMIT = 10 :MAX=1E37
10 DATA-2,2,1,NORMAL
20 DATA-2,2,0,ZERO INCREMENT
30 DATA-2,2,-1,INCREMENTS AWAY FROM STOP VALUE
40 DATA-2,2,10,FIRST INCREMENT IS BEYOND STOP VALUE
50 DATA2,-2,1,"START MORE THAN STOP: POSITIVE INCREMENT
60 DATA2,2,1,"START EQUAL STOP: POSITIVE INCREMENT
70 DATA2,2,-1,"START EQUAL STOP: NEGATIVE INCREMENT
80 DATA2,2,0,"START EQUAL STOP: ZERO INCREMENT
90 DATA0,0,0,"START EQUAL STOP EQUAL ZERO: ZERO INCREMENT
100 FOR I = 1 TO 9
110 READ START,FINISH,INCR,COMMENT$
120 PRINT CHR$(13)COMMENT$
130 LAST = FINISH
140 REM D = SGN(FINISH - START)
150 REM IF D AND NOT (D = SGN(INCR)) THEN LAST = SGN(INCR)*MAX
160 PRINT TAB(5)CHR$(91)" "MID$(" ",(START<0)+1)START" TO "MID$(" ",(FINISH<0)+1)FINISH" STEP "MID$(" ",(INCR<0)+1)INCR" ] ";
170 COUNT = 0
180 PRINT MID$(" ",(START<0)+1);
190 FOR J = START TO LAST STEP INCR
200 PRINT MID$(" ",(COUNT=0)+1)J;
210 IF COUNT < LIMIT THEN COUNT = COUNT + 1 : NEXT J
220 IF COUNT = LIMIT THEN PRINT " ... ";:if ABS(LAST) = MAX THEN PRINT MID$("-",SGN(LAST)+2,1)"INFINITY";
230 NEXT I |
http://rosettacode.org/wiki/Loops/Wrong_ranges | Loops/Wrong ranges | Loops/Wrong ranges
You are encouraged to solve this task according to the task description, using any language you may know.
Some languages have syntax or function(s) to generate a range of numeric values from a start value, a stop value, and an increment.
The purpose of this task is to select the range syntax/function that would generate at least two increasing numbers when given a stop value more than the start value and a positive increment of less than half the difference. You are then to use that same syntax/function but with different parameters; and show, here, what would happen.
Use these values if possible:
start
stop
increment
Comment
-2
2
1
Normal
-2
2
0
Zero increment
-2
2
-1
Increments away from stop value
-2
2
10
First increment is beyond stop value
2
-2
1
Start more than stop: positive increment
2
2
1
Start equal stop: positive increment
2
2
-1
Start equal stop: negative increment
2
2
0
Start equal stop: zero increment
0
0
0
Start equal stop equal zero: zero increment
Related tasks
Loop over multiple arrays simultaneously
Loops/Break
Loops/Continue
Loops/Do-while
Loops/Downward for
Loops/For
Loops/For with a specified step
Loops/Foreach
Loops/Increment loop index within loop body
Loops/Infinite
Loops/N plus one half
Loops/Nested
Loops/While
Loops/with multiple ranges
Loops/Wrong ranges
| #AWK | AWK |
# syntax: GAWK -f LOOPS_WRONG_RANGES.AWK
BEGIN {
arr[++n] = "-2, 2, 1,Normal"
arr[++n] = "-2, 2, 0,Zero increment"
arr[++n] = "-2, 2,-1,Increments away from stop value"
arr[++n] = "-2, 2,10,First increment is beyond stop value"
arr[++n] = " 2,-2, 1,Start more than stop: positive increment"
arr[++n] = " 2, 2, 1,Start equal stop: positive increment"
arr[++n] = " 2, 2,-1,Start equal stop: negative increment"
arr[++n] = " 2, 2, 0,Start equal stop: zero increment"
arr[++n] = " 0, 0, 0,Start equal stop equal zero: zero increment"
print("start,stop,increment,comment")
for (i=1; i<=n; i++) {
split(arr[i],A,",")
printf("%-52s : ",arr[i])
count = 0
for (j=A[1]; j<=A[2] && count<10; j+=A[3]) {
printf("%d ",j)
count++
}
printf("\n")
}
exit(0)
}
|
http://rosettacode.org/wiki/Luhn_test_of_credit_card_numbers | Luhn test of credit card numbers | The Luhn test is used by some credit card companies to distinguish valid credit card numbers from what could be a random selection of digits.
Those companies using credit card numbers that can be validated by the Luhn test have numbers that pass the following test:
Reverse the order of the digits in the number.
Take the first, third, ... and every other odd digit in the reversed digits and sum them to form the partial sum s1
Taking the second, fourth ... and every other even digit in the reversed digits:
Multiply each digit by two and sum the digits if the answer is greater than nine to form partial sums for the even digits
Sum the partial sums of the even digits to form s2
If s1 + s2 ends in zero then the original number is in the form of a valid credit card number as verified by the Luhn test.
For example, if the trial number is 49927398716:
Reverse the digits:
61789372994
Sum the odd digits:
6 + 7 + 9 + 7 + 9 + 4 = 42 = s1
The even digits:
1, 8, 3, 2, 9
Two times each even digit:
2, 16, 6, 4, 18
Sum the digits of each multiplication:
2, 7, 6, 4, 9
Sum the last:
2 + 7 + 6 + 4 + 9 = 28 = s2
s1 + s2 = 70 which ends in zero which means that 49927398716 passes the Luhn test
Task
Write a function/method/procedure/subroutine that will validate a number with the Luhn test, and
use it to validate the following numbers:
49927398716
49927398717
1234567812345678
1234567812345670
Related tasks
SEDOL
ISIN
| #8th | 8th |
\ Adapted from the C version:
: remap \ n1 -- n2
[0,2,4,6,8,1,3,5,7,9]
swap caseof ;
: luhn \ s -- f
0 swap
s:rev
(
'0 n:-
swap 2 n:mod if remap then
n:+
) s:each
10 n:mod not ;
: test-luhn \ s --
dup . space
luhn if "OK" else "FAIL" then . cr ;
"49927398716" test-luhn
"49927398717" test-luhn
"1234567812345678" test-luhn
"1234567812345670" test-luhn
bye |
http://rosettacode.org/wiki/Lucas-Lehmer_test | Lucas-Lehmer test | Lucas-Lehmer Test:
for
p
{\displaystyle p}
an odd prime, the Mersenne number
2
p
−
1
{\displaystyle 2^{p}-1}
is prime if and only if
2
p
−
1
{\displaystyle 2^{p}-1}
divides
S
(
p
−
1
)
{\displaystyle S(p-1)}
where
S
(
n
+
1
)
=
(
S
(
n
)
)
2
−
2
{\displaystyle S(n+1)=(S(n))^{2}-2}
, and
S
(
1
)
=
4
{\displaystyle S(1)=4}
.
Task
Calculate all Mersenne primes up to the implementation's
maximum precision, or the 47th Mersenne prime (whichever comes first).
| #Arturo | Arturo | mersenne?: function [p][
if p=2 -> return true
mp: dec shl 1 p
s: 4
loop 3..p 'i ->
s: (sub s*s 2) % mp
return s=0
]
print "Mersenne primes:"
mersennes: select 2..32 'x -> and? prime? x mersenne? x
print join.with:", " map mersennes 'm -> ~"M|m|" |
http://rosettacode.org/wiki/Lucky_and_even_lucky_numbers | Lucky and even lucky numbers | Note that in the following explanation list indices are assumed to start at one.
Definition of lucky numbers
Lucky numbers are positive integers that are formed by:
Form a list of all the positive odd integers > 0
1
,
3
,
5
,
7
,
9
,
11
,
13
,
15
,
17
,
19
,
21
,
23
,
25
,
27
,
29
,
31
,
33
,
35
,
37
,
39...
{\displaystyle 1,3,5,7,9,11,13,15,17,19,21,23,25,27,29,31,33,35,37,39...}
Return the first number from the list (which is 1).
(Loop begins here)
Note then return the second number from the list (which is 3).
Discard every third, (as noted), number from the list to form the new list
1
,
3
,
7
,
9
,
13
,
15
,
19
,
21
,
25
,
27
,
31
,
33
,
37
,
39
,
43
,
45
,
49
,
51
,
55
,
57...
{\displaystyle 1,3,7,9,13,15,19,21,25,27,31,33,37,39,43,45,49,51,55,57...}
(Expanding the loop a few more times...)
Note then return the third number from the list (which is 7).
Discard every 7th, (as noted), number from the list to form the new list
1
,
3
,
7
,
9
,
13
,
15
,
21
,
25
,
27
,
31
,
33
,
37
,
43
,
45
,
49
,
51
,
55
,
57
,
63
,
67...
{\displaystyle 1,3,7,9,13,15,21,25,27,31,33,37,43,45,49,51,55,57,63,67...}
Note then return the 4th number from the list (which is 9).
Discard every 9th, (as noted), number from the list to form the new list
1
,
3
,
7
,
9
,
13
,
15
,
21
,
25
,
31
,
33
,
37
,
43
,
45
,
49
,
51
,
55
,
63
,
67
,
69
,
73...
{\displaystyle 1,3,7,9,13,15,21,25,31,33,37,43,45,49,51,55,63,67,69,73...}
Take the 5th, i.e. 13. Remove every 13th.
Take the 6th, i.e. 15. Remove every 15th.
Take the 7th, i.e. 21. Remove every 21th.
Take the 8th, i.e. 25. Remove every 25th.
(Rule for the loop)
Note the
n
{\displaystyle n}
th, which is
m
{\displaystyle m}
.
Remove every
m
{\displaystyle m}
th.
Increment
n
{\displaystyle n}
.
Definition of even lucky numbers
This follows the same rules as the definition of lucky numbers above except for the very first step:
Form a list of all the positive even integers > 0
2
,
4
,
6
,
8
,
10
,
12
,
14
,
16
,
18
,
20
,
22
,
24
,
26
,
28
,
30
,
32
,
34
,
36
,
38
,
40...
{\displaystyle 2,4,6,8,10,12,14,16,18,20,22,24,26,28,30,32,34,36,38,40...}
Return the first number from the list (which is 2).
(Loop begins here)
Note then return the second number from the list (which is 4).
Discard every 4th, (as noted), number from the list to form the new list
2
,
4
,
6
,
10
,
12
,
14
,
18
,
20
,
22
,
26
,
28
,
30
,
34
,
36
,
38
,
42
,
44
,
46
,
50
,
52...
{\displaystyle 2,4,6,10,12,14,18,20,22,26,28,30,34,36,38,42,44,46,50,52...}
(Expanding the loop a few more times...)
Note then return the third number from the list (which is 6).
Discard every 6th, (as noted), number from the list to form the new list
2
,
4
,
6
,
10
,
12
,
18
,
20
,
22
,
26
,
28
,
34
,
36
,
38
,
42
,
44
,
50
,
52
,
54
,
58
,
60...
{\displaystyle 2,4,6,10,12,18,20,22,26,28,34,36,38,42,44,50,52,54,58,60...}
Take the 4th, i.e. 10. Remove every 10th.
Take the 5th, i.e. 12. Remove every 12th.
(Rule for the loop)
Note the
n
{\displaystyle n}
th, which is
m
{\displaystyle m}
.
Remove every
m
{\displaystyle m}
th.
Increment
n
{\displaystyle n}
.
Task requirements
Write one or two subroutines (functions) to generate lucky numbers and even lucky numbers
Write a command-line interface to allow selection of which kind of numbers and which number(s). Since input is from the command line, tests should be made for the common errors:
missing arguments
too many arguments
number (or numbers) aren't legal
misspelled argument (lucky or evenLucky)
The command line handling should:
support mixed case handling of the (non-numeric) arguments
support printing a particular number
support printing a range of numbers by their index
support printing a range of numbers by their values
The resulting list of numbers should be printed on a single line.
The program should support the arguments:
what is displayed (on a single line)
argument(s) (optional verbiage is encouraged)
╔═══════════════════╦════════════════════════════════════════════════════╗
║ j ║ Jth lucky number ║
║ j , lucky ║ Jth lucky number ║
║ j , evenLucky ║ Jth even lucky number ║
║ ║ ║
║ j k ║ Jth through Kth (inclusive) lucky numbers ║
║ j k lucky ║ Jth through Kth (inclusive) lucky numbers ║
║ j k evenLucky ║ Jth through Kth (inclusive) even lucky numbers ║
║ ║ ║
║ j -k ║ all lucky numbers in the range j ──► |k| ║
║ j -k lucky ║ all lucky numbers in the range j ──► |k| ║
║ j -k evenLucky ║ all even lucky numbers in the range j ──► |k| ║
╚═══════════════════╩════════════════════════════════════════════════════╝
where |k| is the absolute value of k
Demonstrate the program by:
showing the first twenty lucky numbers
showing the first twenty even lucky numbers
showing all lucky numbers between 6,000 and 6,100 (inclusive)
showing all even lucky numbers in the same range as above
showing the 10,000th lucky number (extra credit)
showing the 10,000th even lucky number (extra credit)
See also
This task is related to the Sieve of Eratosthenes task.
OEIS Wiki Lucky numbers.
Sequence A000959 lucky numbers on The On-Line Encyclopedia of Integer Sequences.
Sequence A045954 even lucky numbers or ELN on The On-Line Encyclopedia of Integer Sequences.
Entry lucky numbers on The Eric Weisstein's World of Mathematics.
| #Go | Go | package main
import (
"fmt"
"log"
"os"
"strconv"
"strings"
)
const luckySize = 60000
var luckyOdd = make([]int, luckySize)
var luckyEven = make([]int, luckySize)
func init() {
for i := 0; i < luckySize; i++ {
luckyOdd[i] = i*2 + 1
luckyEven[i] = i*2 + 2
}
}
func filterLuckyOdd() {
for n := 2; n < len(luckyOdd); n++ {
m := luckyOdd[n-1]
end := (len(luckyOdd)/m)*m - 1
for j := end; j >= m-1; j -= m {
copy(luckyOdd[j:], luckyOdd[j+1:])
luckyOdd = luckyOdd[:len(luckyOdd)-1]
}
}
}
func filterLuckyEven() {
for n := 2; n < len(luckyEven); n++ {
m := luckyEven[n-1]
end := (len(luckyEven)/m)*m - 1
for j := end; j >= m-1; j -= m {
copy(luckyEven[j:], luckyEven[j+1:])
luckyEven = luckyEven[:len(luckyEven)-1]
}
}
}
func printSingle(j int, odd bool) error {
if odd {
if j >= len(luckyOdd) {
return fmt.Errorf("the argument, %d, is too big", j)
}
fmt.Println("Lucky number", j, "=", luckyOdd[j-1])
} else {
if j >= len(luckyEven) {
return fmt.Errorf("the argument, %d, is too big", j)
}
fmt.Println("Lucky even number", j, "=", luckyEven[j-1])
}
return nil
}
func printRange(j, k int, odd bool) error {
if odd {
if k >= len(luckyOdd) {
return fmt.Errorf("the argument, %d, is too big", k)
}
fmt.Println("Lucky numbers", j, "to", k, "are:")
fmt.Println(luckyOdd[j-1 : k])
} else {
if k >= len(luckyEven) {
return fmt.Errorf("the argument, %d, is too big", k)
}
fmt.Println("Lucky even numbers", j, "to", k, "are:")
fmt.Println(luckyEven[j-1 : k])
}
return nil
}
func printBetween(j, k int, odd bool) error {
var r []int
if odd {
max := luckyOdd[len(luckyOdd)-1]
if j > max || k > max {
return fmt.Errorf("at least one argument, %d or %d, is too big", j, k)
}
for _, num := range luckyOdd {
if num < j {
continue
}
if num > k {
break
}
r = append(r, num)
}
fmt.Println("Lucky numbers between", j, "and", k, "are:")
fmt.Println(r)
} else {
max := luckyEven[len(luckyEven)-1]
if j > max || k > max {
return fmt.Errorf("at least one argument, %d or %d, is too big", j, k)
}
for _, num := range luckyEven {
if num < j {
continue
}
if num > k {
break
}
r = append(r, num)
}
fmt.Println("Lucky even numbers between", j, "and", k, "are:")
fmt.Println(r)
}
return nil
}
func main() {
nargs := len(os.Args)
if nargs < 2 || nargs > 4 {
log.Fatal("there must be between 1 and 3 command line arguments")
}
filterLuckyOdd()
filterLuckyEven()
j, err := strconv.Atoi(os.Args[1])
if err != nil || j < 1 {
log.Fatalf("first argument, %s, must be a positive integer", os.Args[1])
}
if nargs == 2 {
if err := printSingle(j, true); err != nil {
log.Fatal(err)
}
return
}
if nargs == 3 {
k, err := strconv.Atoi(os.Args[2])
if err != nil {
log.Fatalf("second argument, %s, must be an integer", os.Args[2])
}
if k >= 0 {
if j > k {
log.Fatalf("second argument, %d, can't be less than first, %d", k, j)
}
if err := printRange(j, k, true); err != nil {
log.Fatal(err)
}
} else {
l := -k
if j > l {
log.Fatalf("second argument, %d, can't be less in absolute value than first, %d", k, j)
}
if err := printBetween(j, l, true); err != nil {
log.Fatal(err)
}
}
return
}
var odd bool
switch lucky := strings.ToLower(os.Args[3]); lucky {
case "lucky":
odd = true
case "evenlucky":
odd = false
default:
log.Fatalf("third argument, %s, is invalid", os.Args[3])
}
if os.Args[2] == "," {
if err := printSingle(j, odd); err != nil {
log.Fatal(err)
}
return
}
k, err := strconv.Atoi(os.Args[2])
if err != nil {
log.Fatal("second argument must be an integer or a comma")
}
if k >= 0 {
if j > k {
log.Fatalf("second argument, %d, can't be less than first, %d", k, j)
}
if err := printRange(j, k, odd); err != nil {
log.Fatal(err)
}
} else {
l := -k
if j > l {
log.Fatalf("second argument, %d, can't be less in absolute value than first, %d", k, j)
}
if err := printBetween(j, l, odd); err != nil {
log.Fatal(err)
}
}
} |
http://rosettacode.org/wiki/LZW_compression | LZW compression | The Lempel-Ziv-Welch (LZW) algorithm provides loss-less data compression.
You can read a complete description of it in the Wikipedia article on the subject. It was patented, but it entered the public domain in 2004.
| #C | C | #include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdint.h>
#include <unistd.h>
#include <fcntl.h>
#include <sys/types.h>
#include <sys/stat.h>
/* -------- aux stuff ---------- */
void* mem_alloc(size_t item_size, size_t n_item)
{
size_t *x = calloc(1, sizeof(size_t)*2 + n_item * item_size);
x[0] = item_size;
x[1] = n_item;
return x + 2;
}
void* mem_extend(void *m, size_t new_n)
{
size_t *x = (size_t*)m - 2;
x = realloc(x, sizeof(size_t) * 2 + *x * new_n);
if (new_n > x[1])
memset((char*)(x + 2) + x[0] * x[1], 0, x[0] * (new_n - x[1]));
x[1] = new_n;
return x + 2;
}
inline void _clear(void *m)
{
size_t *x = (size_t*)m - 2;
memset(m, 0, x[0] * x[1]);
}
#define _new(type, n) mem_alloc(sizeof(type), n)
#define _del(m) { free((size_t*)(m) - 2); m = 0; }
#define _len(m) *((size_t*)m - 1)
#define _setsize(m, n) m = mem_extend(m, n)
#define _extend(m) m = mem_extend(m, _len(m) * 2)
/* ----------- LZW stuff -------------- */
typedef uint8_t byte;
typedef uint16_t ushort;
#define M_CLR 256 /* clear table marker */
#define M_EOD 257 /* end-of-data marker */
#define M_NEW 258 /* new code index */
/* encode and decode dictionary structures.
for encoding, entry at code index is a list of indices that follow current one,
i.e. if code 97 is 'a', code 387 is 'ab', and code 1022 is 'abc',
then dict[97].next['b'] = 387, dict[387].next['c'] = 1022, etc. */
typedef struct {
ushort next[256];
} lzw_enc_t;
/* for decoding, dictionary contains index of whatever prefix index plus trailing
byte. i.e. like previous example,
dict[1022] = { c: 'c', prev: 387 },
dict[387] = { c: 'b', prev: 97 },
dict[97] = { c: 'a', prev: 0 }
the "back" element is used for temporarily chaining indices when resolving
a code to bytes
*/
typedef struct {
ushort prev, back;
byte c;
} lzw_dec_t;
byte* lzw_encode(byte *in, int max_bits)
{
int len = _len(in), bits = 9, next_shift = 512;
ushort code, c, nc, next_code = M_NEW;
lzw_enc_t *d = _new(lzw_enc_t, 512);
if (max_bits > 15) max_bits = 15;
if (max_bits < 9 ) max_bits = 12;
byte *out = _new(ushort, 4);
int out_len = 0, o_bits = 0;
uint32_t tmp = 0;
inline void write_bits(ushort x) {
tmp = (tmp << bits) | x;
o_bits += bits;
if (_len(out) <= out_len) _extend(out);
while (o_bits >= 8) {
o_bits -= 8;
out[out_len++] = tmp >> o_bits;
tmp &= (1 << o_bits) - 1;
}
}
//write_bits(M_CLR);
for (code = *(in++); --len; ) {
c = *(in++);
if ((nc = d[code].next[c]))
code = nc;
else {
write_bits(code);
nc = d[code].next[c] = next_code++;
code = c;
}
/* next new code would be too long for current table */
if (next_code == next_shift) {
/* either reset table back to 9 bits */
if (++bits > max_bits) {
/* table clear marker must occur before bit reset */
write_bits(M_CLR);
bits = 9;
next_shift = 512;
next_code = M_NEW;
_clear(d);
} else /* or extend table */
_setsize(d, next_shift *= 2);
}
}
write_bits(code);
write_bits(M_EOD);
if (tmp) write_bits(tmp);
_del(d);
_setsize(out, out_len);
return out;
}
byte* lzw_decode(byte *in)
{
byte *out = _new(byte, 4);
int out_len = 0;
inline void write_out(byte c)
{
while (out_len >= _len(out)) _extend(out);
out[out_len++] = c;
}
lzw_dec_t *d = _new(lzw_dec_t, 512);
int len, j, next_shift = 512, bits = 9, n_bits = 0;
ushort code, c, t, next_code = M_NEW;
uint32_t tmp = 0;
inline void get_code() {
while(n_bits < bits) {
if (len > 0) {
len --;
tmp = (tmp << 8) | *(in++);
n_bits += 8;
} else {
tmp = tmp << (bits - n_bits);
n_bits = bits;
}
}
n_bits -= bits;
code = tmp >> n_bits;
tmp &= (1 << n_bits) - 1;
}
inline void clear_table() {
_clear(d);
for (j = 0; j < 256; j++) d[j].c = j;
next_code = M_NEW;
next_shift = 512;
bits = 9;
};
clear_table(); /* in case encoded bits didn't start with M_CLR */
for (len = _len(in); len;) {
get_code();
if (code == M_EOD) break;
if (code == M_CLR) {
clear_table();
continue;
}
if (code >= next_code) {
fprintf(stderr, "Bad sequence\n");
_del(out);
goto bail;
}
d[next_code].prev = c = code;
while (c > 255) {
t = d[c].prev; d[t].back = c; c = t;
}
d[next_code - 1].c = c;
while (d[c].back) {
write_out(d[c].c);
t = d[c].back; d[c].back = 0; c = t;
}
write_out(d[c].c);
if (++next_code >= next_shift) {
if (++bits > 16) {
/* if input was correct, we'd have hit M_CLR before this */
fprintf(stderr, "Too many bits\n");
_del(out);
goto bail;
}
_setsize(d, next_shift *= 2);
}
}
/* might be ok, so just whine, don't be drastic */
if (code != M_EOD) fputs("Bits did not end in EOD\n", stderr);
_setsize(out, out_len);
bail: _del(d);
return out;
}
int main()
{
int i, fd = open("unixdict.txt", O_RDONLY);
if (fd == -1) {
fprintf(stderr, "Can't read file\n");
return 1;
};
struct stat st;
fstat(fd, &st);
byte *in = _new(char, st.st_size);
read(fd, in, st.st_size);
_setsize(in, st.st_size);
close(fd);
printf("input size: %d\n", _len(in));
byte *enc = lzw_encode(in, 9);
printf("encoded size: %d\n", _len(enc));
byte *dec = lzw_decode(enc);
printf("decoded size: %d\n", _len(dec));
for (i = 0; i < _len(dec); i++)
if (dec[i] != in[i]) {
printf("bad decode at %d\n", i);
break;
}
if (i == _len(dec)) printf("Decoded ok\n");
_del(in);
_del(enc);
_del(dec);
return 0;
} |
http://rosettacode.org/wiki/LU_decomposition | LU decomposition | Every square matrix
A
{\displaystyle A}
can be decomposed into a product of a lower triangular matrix
L
{\displaystyle L}
and a upper triangular matrix
U
{\displaystyle U}
,
as described in LU decomposition.
A
=
L
U
{\displaystyle A=LU}
It is a modified form of Gaussian elimination.
While the Cholesky decomposition only works for symmetric,
positive definite matrices, the more general LU decomposition
works for any square matrix.
There are several algorithms for calculating L and U.
To derive Crout's algorithm for a 3x3 example,
we have to solve the following system:
A
=
(
a
11
a
12
a
13
a
21
a
22
a
23
a
31
a
32
a
33
)
=
(
l
11
0
0
l
21
l
22
0
l
31
l
32
l
33
)
(
u
11
u
12
u
13
0
u
22
u
23
0
0
u
33
)
=
L
U
{\displaystyle A={\begin{pmatrix}a_{11}&a_{12}&a_{13}\\a_{21}&a_{22}&a_{23}\\a_{31}&a_{32}&a_{33}\\\end{pmatrix}}={\begin{pmatrix}l_{11}&0&0\\l_{21}&l_{22}&0\\l_{31}&l_{32}&l_{33}\\\end{pmatrix}}{\begin{pmatrix}u_{11}&u_{12}&u_{13}\\0&u_{22}&u_{23}\\0&0&u_{33}\end{pmatrix}}=LU}
We now would have to solve 9 equations with 12 unknowns. To make the system uniquely solvable, usually the diagonal elements of
L
{\displaystyle L}
are set to 1
l
11
=
1
{\displaystyle l_{11}=1}
l
22
=
1
{\displaystyle l_{22}=1}
l
33
=
1
{\displaystyle l_{33}=1}
so we get a solvable system of 9 unknowns and 9 equations.
A
=
(
a
11
a
12
a
13
a
21
a
22
a
23
a
31
a
32
a
33
)
=
(
1
0
0
l
21
1
0
l
31
l
32
1
)
(
u
11
u
12
u
13
0
u
22
u
23
0
0
u
33
)
=
(
u
11
u
12
u
13
u
11
l
21
u
12
l
21
+
u
22
u
13
l
21
+
u
23
u
11
l
31
u
12
l
31
+
u
22
l
32
u
13
l
31
+
u
23
l
32
+
u
33
)
=
L
U
{\displaystyle A={\begin{pmatrix}a_{11}&a_{12}&a_{13}\\a_{21}&a_{22}&a_{23}\\a_{31}&a_{32}&a_{33}\\\end{pmatrix}}={\begin{pmatrix}1&0&0\\l_{21}&1&0\\l_{31}&l_{32}&1\\\end{pmatrix}}{\begin{pmatrix}u_{11}&u_{12}&u_{13}\\0&u_{22}&u_{23}\\0&0&u_{33}\end{pmatrix}}={\begin{pmatrix}u_{11}&u_{12}&u_{13}\\u_{11}l_{21}&u_{12}l_{21}+u_{22}&u_{13}l_{21}+u_{23}\\u_{11}l_{31}&u_{12}l_{31}+u_{22}l_{32}&u_{13}l_{31}+u_{23}l_{32}+u_{33}\end{pmatrix}}=LU}
Solving for the other
l
{\displaystyle l}
and
u
{\displaystyle u}
, we get the following equations:
u
11
=
a
11
{\displaystyle u_{11}=a_{11}}
u
12
=
a
12
{\displaystyle u_{12}=a_{12}}
u
13
=
a
13
{\displaystyle u_{13}=a_{13}}
u
22
=
a
22
−
u
12
l
21
{\displaystyle u_{22}=a_{22}-u_{12}l_{21}}
u
23
=
a
23
−
u
13
l
21
{\displaystyle u_{23}=a_{23}-u_{13}l_{21}}
u
33
=
a
33
−
(
u
13
l
31
+
u
23
l
32
)
{\displaystyle u_{33}=a_{33}-(u_{13}l_{31}+u_{23}l_{32})}
and for
l
{\displaystyle l}
:
l
21
=
1
u
11
a
21
{\displaystyle l_{21}={\frac {1}{u_{11}}}a_{21}}
l
31
=
1
u
11
a
31
{\displaystyle l_{31}={\frac {1}{u_{11}}}a_{31}}
l
32
=
1
u
22
(
a
32
−
u
12
l
31
)
{\displaystyle l_{32}={\frac {1}{u_{22}}}(a_{32}-u_{12}l_{31})}
We see that there is a calculation pattern, which can be expressed as the following formulas, first for
U
{\displaystyle U}
u
i
j
=
a
i
j
−
∑
k
=
1
i
−
1
u
k
j
l
i
k
{\displaystyle u_{ij}=a_{ij}-\sum _{k=1}^{i-1}u_{kj}l_{ik}}
and then for
L
{\displaystyle L}
l
i
j
=
1
u
j
j
(
a
i
j
−
∑
k
=
1
j
−
1
u
k
j
l
i
k
)
{\displaystyle l_{ij}={\frac {1}{u_{jj}}}(a_{ij}-\sum _{k=1}^{j-1}u_{kj}l_{ik})}
We see in the second formula that to get the
l
i
j
{\displaystyle l_{ij}}
below the diagonal, we have to divide by the diagonal element (pivot)
u
j
j
{\displaystyle u_{jj}}
, so we get problems when
u
j
j
{\displaystyle u_{jj}}
is either 0 or very small, which leads to numerical instability.
The solution to this problem is pivoting
A
{\displaystyle A}
, which means rearranging the rows of
A
{\displaystyle A}
, prior to the
L
U
{\displaystyle LU}
decomposition, in a way that the largest element of each column gets onto the diagonal of
A
{\displaystyle A}
. Rearranging the rows means to multiply
A
{\displaystyle A}
by a permutation matrix
P
{\displaystyle P}
:
P
A
⇒
A
′
{\displaystyle PA\Rightarrow A'}
Example:
(
0
1
1
0
)
(
1
4
2
3
)
⇒
(
2
3
1
4
)
{\displaystyle {\begin{pmatrix}0&1\\1&0\end{pmatrix}}{\begin{pmatrix}1&4\\2&3\end{pmatrix}}\Rightarrow {\begin{pmatrix}2&3\\1&4\end{pmatrix}}}
The decomposition algorithm is then applied on the rearranged matrix so that
P
A
=
L
U
{\displaystyle PA=LU}
Task description
The task is to implement a routine which will take a square nxn matrix
A
{\displaystyle A}
and return a lower triangular matrix
L
{\displaystyle L}
, a upper triangular matrix
U
{\displaystyle U}
and a permutation matrix
P
{\displaystyle P}
,
so that the above equation is fulfilled.
You should then test it on the following two examples and include your output.
Example 1
A
1 3 5
2 4 7
1 1 0
L
1.00000 0.00000 0.00000
0.50000 1.00000 0.00000
0.50000 -1.00000 1.00000
U
2.00000 4.00000 7.00000
0.00000 1.00000 1.50000
0.00000 0.00000 -2.00000
P
0 1 0
1 0 0
0 0 1
Example 2
A
11 9 24 2
1 5 2 6
3 17 18 1
2 5 7 1
L
1.00000 0.00000 0.00000 0.00000
0.27273 1.00000 0.00000 0.00000
0.09091 0.28750 1.00000 0.00000
0.18182 0.23125 0.00360 1.00000
U
11.00000 9.00000 24.00000 2.00000
0.00000 14.54545 11.45455 0.45455
0.00000 0.00000 -3.47500 5.68750
0.00000 0.00000 0.00000 0.51079
P
1 0 0 0
0 0 1 0
0 1 0 0
0 0 0 1
| #C.2B.2B | C++ | #include <cassert>
#include <cmath>
#include <iomanip>
#include <iostream>
#include <limits>
#include <numeric>
#include <sstream>
#include <vector>
template <typename scalar_type> class matrix {
public:
matrix(size_t rows, size_t columns)
: rows_(rows), columns_(columns), elements_(rows * columns) {}
matrix(size_t rows, size_t columns, scalar_type value)
: rows_(rows), columns_(columns), elements_(rows * columns, value) {}
matrix(size_t rows, size_t columns,
const std::initializer_list<std::initializer_list<scalar_type>>& values)
: rows_(rows), columns_(columns), elements_(rows * columns) {
assert(values.size() <= rows_);
size_t i = 0;
for (const auto& row : values) {
assert(row.size() <= columns_);
std::copy(begin(row), end(row), &elements_[i]);
i += columns_;
}
}
size_t rows() const { return rows_; }
size_t columns() const { return columns_; }
const scalar_type& operator()(size_t row, size_t column) const {
assert(row < rows_);
assert(column < columns_);
return elements_[row * columns_ + column];
}
scalar_type& operator()(size_t row, size_t column) {
assert(row < rows_);
assert(column < columns_);
return elements_[row * columns_ + column];
}
private:
size_t rows_;
size_t columns_;
std::vector<scalar_type> elements_;
};
template <typename scalar_type>
void print(std::wostream& out, const matrix<scalar_type>& a) {
const wchar_t* box_top_left = L"\x23a1";
const wchar_t* box_top_right = L"\x23a4";
const wchar_t* box_left = L"\x23a2";
const wchar_t* box_right = L"\x23a5";
const wchar_t* box_bottom_left = L"\x23a3";
const wchar_t* box_bottom_right = L"\x23a6";
const int precision = 5;
size_t rows = a.rows(), columns = a.columns();
std::vector<size_t> width(columns);
for (size_t column = 0; column < columns; ++column) {
size_t max_width = 0;
for (size_t row = 0; row < rows; ++row) {
std::ostringstream str;
str << std::fixed << std::setprecision(precision) << a(row, column);
max_width = std::max(max_width, str.str().length());
}
width[column] = max_width;
}
out << std::fixed << std::setprecision(precision);
for (size_t row = 0; row < rows; ++row) {
const bool top(row == 0), bottom(row + 1 == rows);
out << (top ? box_top_left : (bottom ? box_bottom_left : box_left));
for (size_t column = 0; column < columns; ++column) {
if (column > 0)
out << L' ';
out << std::setw(width[column]) << a(row, column);
}
out << (top ? box_top_right : (bottom ? box_bottom_right : box_right));
out << L'\n';
}
}
// Return value is a tuple with elements (lower, upper, pivot)
template <typename scalar_type>
auto lu_decompose(const matrix<scalar_type>& input) {
assert(input.rows() == input.columns());
size_t n = input.rows();
std::vector<size_t> perm(n);
std::iota(perm.begin(), perm.end(), 0);
matrix<scalar_type> lower(n, n);
matrix<scalar_type> upper(n, n);
matrix<scalar_type> input1(input);
for (size_t j = 0; j < n; ++j) {
size_t max_index = j;
scalar_type max_value = 0;
for (size_t i = j; i < n; ++i) {
scalar_type value = std::abs(input1(perm[i], j));
if (value > max_value) {
max_index = i;
max_value = value;
}
}
if (max_value <= std::numeric_limits<scalar_type>::epsilon())
throw std::runtime_error("matrix is singular");
if (j != max_index)
std::swap(perm[j], perm[max_index]);
size_t jj = perm[j];
for (size_t i = j + 1; i < n; ++i) {
size_t ii = perm[i];
input1(ii, j) /= input1(jj, j);
for (size_t k = j + 1; k < n; ++k)
input1(ii, k) -= input1(ii, j) * input1(jj, k);
}
}
for (size_t j = 0; j < n; ++j) {
lower(j, j) = 1;
for (size_t i = j + 1; i < n; ++i)
lower(i, j) = input1(perm[i], j);
for (size_t i = 0; i <= j; ++i)
upper(i, j) = input1(perm[i], j);
}
matrix<scalar_type> pivot(n, n);
for (size_t i = 0; i < n; ++i)
pivot(i, perm[i]) = 1;
return std::make_tuple(lower, upper, pivot);
}
template <typename scalar_type>
void show_lu_decomposition(const matrix<scalar_type>& input) {
try {
std::wcout << L"A\n";
print(std::wcout, input);
auto result(lu_decompose(input));
std::wcout << L"\nL\n";
print(std::wcout, std::get<0>(result));
std::wcout << L"\nU\n";
print(std::wcout, std::get<1>(result));
std::wcout << L"\nP\n";
print(std::wcout, std::get<2>(result));
} catch (const std::exception& ex) {
std::cerr << ex.what() << '\n';
}
}
int main() {
std::wcout.imbue(std::locale(""));
std::wcout << L"Example 1:\n";
matrix<double> matrix1(3, 3,
{{1, 3, 5},
{2, 4, 7},
{1, 1, 0}});
show_lu_decomposition(matrix1);
std::wcout << '\n';
std::wcout << L"Example 2:\n";
matrix<double> matrix2(4, 4,
{{11, 9, 24, 2},
{1, 5, 2, 6},
{3, 17, 18, 1},
{2, 5, 7, 1}});
show_lu_decomposition(matrix2);
std::wcout << '\n';
std::wcout << L"Example 3:\n";
matrix<double> matrix3(3, 3,
{{-5, -6, -3},
{-1, 0, -2},
{-3, -4, -7}});
show_lu_decomposition(matrix3);
std::wcout << '\n';
std::wcout << L"Example 4:\n";
matrix<double> matrix4(3, 3,
{{1, 2, 3},
{4, 5, 6},
{7, 8, 9}});
show_lu_decomposition(matrix4);
return 0;
} |
http://rosettacode.org/wiki/Lychrel_numbers | Lychrel numbers | Take an integer n, greater than zero.
Form the next n of its series by reversing the digits of the current n and adding the result to the current n.
Stop when n becomes palindromic - i.e. the digits of n in reverse order == n.
The above recurrence relation when applied to most starting numbers n = 1, 2, ... terminates in a palindrome quite quickly.
Example
If n0 = 12 we get
12
12 + 21 = 33, a palindrome!
And if n0 = 55 we get
55
55 + 55 = 110
110 + 011 = 121, a palindrome!
Notice that the check for a palindrome happens after an addition.
Some starting numbers seem to go on forever; the recurrence relation for 196 has been calculated for millions of repetitions forming numbers with millions of digits, without forming a palindrome.
These numbers that do not end in a palindrome are called Lychrel numbers.
For the purposes of this task a Lychrel number is any starting number that does not form a palindrome within 500 (or more) iterations.
Seed and related Lychrel numbers
Any integer produced in the sequence of a Lychrel number is also a Lychrel number.
In general, any sequence from one Lychrel number might converge to join the sequence from a prior Lychrel number candidate; for example the sequences for the numbers 196 and then 689 begin:
196
196 + 691 = 887
887 + 788 = 1675
1675 + 5761 = 7436
7436 + 6347 = 13783
13783 + 38731 = 52514
52514 + 41525 = 94039
...
689
689 + 986 = 1675
1675 + 5761 = 7436
...
So we see that the sequence starting with 689 converges to, and continues with the same numbers as that for 196.
Because of this we can further split the Lychrel numbers into true Seed Lychrel number candidates, and Related numbers that produce no palindromes but have integers in their sequence seen as part of the sequence generated from a lower Lychrel number.
Task
Find the number of seed Lychrel number candidates and related numbers for n in the range 1..10000 inclusive. (With that iteration limit of 500).
Print the number of seed Lychrels found; the actual seed Lychrels; and just the number of relateds found.
Print any seed Lychrel or related number that is itself a palindrome.
Show all output here.
References
What's special about 196? Numberphile video.
A023108 Positive integers which apparently never result in a palindrome under repeated applications of the function f(x) = x + (x with digits reversed).
Status of the 196 conjecture? Mathoverflow.
| #Haskell | Haskell | module Main where
import Data.List
procLychrel :: Integer -> [Integer]
procLychrel a = a : pl a
where
pl n =
let s = n + reverseInteger n
in if isPalindrome s
then [s]
else s : pl s
isPalindrome :: Integer -> Bool
isPalindrome n =
let s = show n
in (s == reverse s)
isLychrel :: Integer -> Bool
isLychrel = not . null . drop 500 . procLychrel
reverseInteger :: Integer -> Integer
reverseInteger = read . reverse . show
seedAndRelated :: (Int, [Integer], [Integer], Int)
seedAndRelated =
let (seed, related, _) = foldl sar ([], [], []) [1 .. 10000]
lseed = length seed
lrelated = length related
totalCount = lseed + lrelated
pal = filter isPalindrome $ seed ++ related
in (totalCount, pal, seed, lrelated)
where
sar (seed, related, lych) x =
let s = procLychrel x
sIsLychrel = not . null . drop 500 $ s
(isIn, isOut) = partition (`elem` lych) . take 501 $ s
newLych = lych ++ isOut
in if sIsLychrel
then if null isIn -- seed lychrel number
then (x : seed, related, newLych)
else (seed, x : related, newLych) -- related lychrel number
else (seed, related, lych)
main = do
let (totalCount, palindromicLychrel, lychrelSeeds, relatedCount) = seedAndRelated
putStrLn $ "[1..10,000] contains " ++ show totalCount ++ " Lychrel numbers."
putStrLn $ show palindromicLychrel ++ " are palindromic Lychrel numbers."
putStrLn $ show lychrelSeeds ++ " are Lychrel seeds."
putStrLn $ "There are " ++ show relatedCount ++ " related Lychrel numbers." |
http://rosettacode.org/wiki/Magic_8-ball | Magic 8-ball | Task
Create Magic 8-Ball.
See details at: Magic 8-Ball.
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
| #REXX | REXX |
/* REXX */
Call mk_a "It is certain", "It is decidedly so", "Without a doubt",,
"Yes, definitely", "You may rely on it", "As I see it, yes",,
"Most likely", "Outlook good", "Signs point to yes", "Yes",,
"Reply hazy, try again", "Ask again later",,
"Better not tell you now", "Cannot predict now",,
"Concentrate and ask again", "Don't bet on it",,
"My reply is no", "My sources say no", "Outlook not so good",,
"Very doubtful"
Do Forever
Say 'your question:'
Parse Pull q
If q='' Then Leave
z=random(1,a.0)
Say a.z
Say ''
End
Exit
mk_a:
a.0=arg()
Do i=1 To a.0
a.i=arg(i)
End
Return
|
http://rosettacode.org/wiki/Magic_8-ball | Magic 8-ball | Task
Create Magic 8-Ball.
See details at: Magic 8-Ball.
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
| #Ring | Ring |
# Project : Magic 8-Ball
answers = ["It is certain", "It is decidedly so", "Without a doubt",
"Yes, definitely", "You may rely on it", "As I see it, yes",
"Most likely", "Outlook good", "Signs point to yes", "Yes",
"Reply hazy, try again", "Ask again later",
"Better not tell you now", "Cannot predict now",
"Concentrate and ask again", "Don't bet on it",
"My reply is no", "My sources say no", "Outlook not so good",
"Very doubtful"]
index = random(len(answers)-1)+1
see answers[index] + nl
|
http://rosettacode.org/wiki/Mandelbrot_set | Mandelbrot set | Mandelbrot set
You are encouraged to solve this task according to the task description, using any language you may know.
Task
Generate and draw the Mandelbrot set.
Note that there are many algorithms to draw Mandelbrot set and there are many functions which generate it .
| #Wren | Wren | import "graphics" for Canvas, Color
import "dome" for Window
var MaxIters = 570
var Zoom = 150
class MandelbrotSet {
construct new(width, height) {
Window.title = "Mandelbrot Set"
Window.resize(width, height)
Canvas.resize(width, height)
_w = width
_h = height
}
init() {
createMandelbrot()
}
createMandelbrot() {
for (x in 0..._w) {
for (y in 0..._h) {
var zx = 0
var zy = 0
var cX = (x - 400) / Zoom
var cY = (y - 300) / Zoom
var i = MaxIters
while (zx * zx + zy * zy < 4 && i > 0) {
var tmp = zx * zx - zy * zy + cX
zy = 2 * zx * zy + cY
zx = tmp
i = i - 1
}
var r = i * 255 / MaxIters
Canvas.pset(x, y, Color.rgb(r, r, r))
}
}
}
update() {}
draw(alpha) {}
}
var Game = MandelbrotSet.new(800, 600) |
http://rosettacode.org/wiki/Mad_Libs | Mad Libs |
This page uses content from Wikipedia. The original article was at Mad Libs. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance)
Mad Libs is a phrasal template word game where one player prompts another for a list of words to substitute for blanks in a story, usually with funny results.
Task;
Write a program to create a Mad Libs like story.
The program should read an arbitrary multiline story from input.
The story will be terminated with a blank line.
Then, find each replacement to be made within the story, ask the user for a word to replace it with, and make all the replacements.
Stop when there are none left and print the final story.
The input should be an arbitrary story in the form:
<name> went for a walk in the park. <he or she>
found a <noun>. <name> decided to take it home.
Given this example, it should then ask for a name, a he or she and a noun (<name> gets replaced both times with the same value).
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
| #Factor | Factor | USING: formatting io kernel make regexp sequences sets splitting ;
IN: rosetta-code.mad-libs
: get-mad-lib ( -- str )
"Enter a mad lib. A blank line signals end of input." print
[
[ "> " write flush readln dup , empty? f t ? ] loop
] { } make harvest "\n" join ;
: find-replacements ( str -- seq )
R/ <[\w\s]+>/ all-matching-subseqs members ;
: query ( str -- str )
rest but-last "Enter a(n) %s: " printf flush readln ;
: replacements ( str seq -- str )
dup [ query ] map [ replace ] 2each ;
: mad-libs ( -- )
get-mad-lib dup find-replacements replacements nl print ;
MAIN: mad-libs |
http://rosettacode.org/wiki/Loops/With_multiple_ranges | Loops/With multiple ranges | Loops/With multiple ranges
You are encouraged to solve this task according to the task description, using any language you may know.
Some languages allow multiple loop ranges, such as the PL/I example (snippet) below.
/* all variables are DECLARED as integers. */
prod= 1; /*start with a product of unity. */
sum= 0; /* " " " sum " zero. */
x= +5;
y= -5;
z= -2;
one= 1;
three= 3;
seven= 7;
/*(below) ** is exponentiation: 4**3=64 */
do j= -three to 3**3 by three ,
-seven to +seven by x ,
555 to 550 - y ,
22 to -28 by -three ,
1927 to 1939 ,
x to y by z ,
11**x to 11**x + one;
/* ABS(n) = absolute value*/
sum= sum + abs(j); /*add absolute value of J.*/
if abs(prod)<2**27 & j¬=0 then prod=prod*j; /*PROD is small enough & J*/
end; /*not 0, then multiply it.*/
/*SUM and PROD are used for verification of J incrementation.*/
display (' sum= ' || sum); /*display strings to term.*/
display ('prod= ' || prod); /* " " " " */
Task
Simulate/translate the above PL/I program snippet as best as possible in your
language, with particular emphasis on the do loop construct.
The do index must be incremented/decremented in the same order shown.
If feasible, add commas to the two output numbers (being displayed).
Show all output here.
A simple PL/I DO loop (incrementing or decrementing) has the construct of:
DO variable = start_expression {TO ending_expression] {BY increment_expression} ;
---or---
DO variable = start_expression {BY increment_expression} {TO ending_expression] ;
where it is understood that all expressions will have a value. The variable is normally a
scaler variable, but need not be (but for this task, all variables and expressions are declared
to be scaler integers). If the BY expression is omitted, a BY value of unity is used.
All expressions are evaluated before the DO loop is executed, and those values are used
throughout the DO loop execution (even though, for instance, the value of Z may be
changed within the DO loop. This isn't the case here for this task.
A multiple-range DO loop can be constructed by using a comma (,) to separate additional ranges
(the use of multiple TO and/or BY keywords). This is the construct used in this task.
There are other forms of DO loops in PL/I involving the WHILE clause, but those won't be
needed here. DO loops without a TO clause might need a WHILE clause or some other
means of exiting the loop (such as LEAVE, RETURN, SIGNAL, GOTO, or STOP), or some other
(possible error) condition that causes transfer of control outside the DO loop.
Also, in PL/I, the check if the DO loop index value is outside the range is made at the
"head" (start) of the DO loop, so it's possible that the DO loop isn't executed, but
that isn't the case for any of the ranges used in this task.
In the example above, the clause: x to y by z
will cause the variable J to have to following values (in this order): 5 3 1 -1 -3 -5
In the example above, the clause: -seven to +seven by x
will cause the variable J to have to following values (in this order): -7 -2 3
Related tasks
Loop over multiple arrays simultaneously
Loops/Break
Loops/Continue
Loops/Do-while
Loops/Downward for
Loops/For
Loops/For with a specified step
Loops/Foreach
Loops/Increment loop index within loop body
Loops/Infinite
Loops/N plus one half
Loops/Nested
Loops/While
Loops/with multiple ranges
Loops/Wrong ranges
| #AArch64_Assembly | AArch64 Assembly |
/* ARM assembly AARCH64 Raspberry PI 3B */
/* program loopnrange64.s */
/*******************************************/
/* Constantes file */
/*******************************************/
/* for this file see task include a file in language AArch64 assembly*/
.include "../includeConstantesARM64.inc"
/*********************************/
/* Initialized data */
/*********************************/
.data
szMessResult: .asciz "@ \n" // message result
szCarriageReturn: .asciz "\n"
/*********************************/
/* UnInitialized data */
/*********************************/
.bss
qSum: .skip 8 // this program store sum and product in memory
qProd: .skip 8 // it is possible to use registers x22 and x28
sZoneConv: .skip 24
/*********************************/
/* code section */
/*********************************/
.text
.global main
main: // entry of program
ldr x0,qAdrqProd
mov x1,1
str x1,[x0] // init product
ldr x0,qAdrqSum
mov x1,0
str x1,[x0] // init sum
mov x25,5 // x
mov x24,-5 // y
mov x26,-2 // z
mov x21,1 // one
mov x23,3 // three
mov x27,7 // seven
// loop one
mov x0,3
mov x1,3
bl computePow // compute 3 pow 3
mov x20,x0 // save result
mvn x9,x23 // x9 = - three
add x9,x9,1
1:
mov x0,x9
bl computeSumProd
add x9,x9,x23 // increment with three
cmp x9,x20
ble 1b
// loop two
mvn x9,x27 // x9 = - seven
add x9,x9,1
2:
mov x0,x9
bl computeSumProd
add x9,x9,x25 // increment with x
cmp x9,x27 // compare to seven
ble 2b
// loop three
mov x9,#550
sub x20,x9,x24 // x20 = 550 - y
mov x9,#555
3:
mov x0,x9
bl computeSumProd
add x9,x9,#1
cmp x9,x20
ble 3b
// loop four
mov x9,#22
4:
mov x0,x9
bl computeSumProd
sub x9,x9,x23 // decrement with three
cmp x9,#-28
bge 4b
// loop five
mov x9,1927
mov x20,1939
5:
mov x0,x9
bl computeSumProd
add x9,x9,1
cmp x9,x20
ble 5b
// loop six
mov x9,x25 // x9 = x
mvn x20,x26 // x20 = - z
add x20,x20,1
6:
mov x0,x9
bl computeSumProd
sub x9,x9,x20
cmp x9,x24
bge 6b
// loop seven
mov x0,x25
mov x1,11
bl computePow // compute 11 pow x
add x20,x0,x21 // + one
mov x9,x0
7:
mov x0,x9
bl computeSumProd
add x9,x9,1
cmp x9,x20
ble 7b
// display result
ldr x0,qAdrqSum
ldr x0,[x0]
ldr x1,qAdrsZoneConv // signed conversion value
bl conversion10S // decimal conversion
ldr x0,qAdrszMessResult
ldr x1,qAdrsZoneConv
bl strInsertAtCharInc // insert result at @ character
bl affichageMess // display message
ldr x0,qAdrszCarriageReturn
bl affichageMess // display return line
ldr x0,qAdrqProd
ldr x0,[x0]
ldr x1,qAdrsZoneConv // conversion value
bl conversion10S // signed decimal conversion
ldr x0,qAdrszMessResult
ldr x1,qAdrsZoneConv
bl strInsertAtCharInc // insert result at @ character
bl affichageMess // display message
ldr x0,qAdrszCarriageReturn
bl affichageMess // display return line
100: // standard end of the program
mov x0,0 // return code
mov x8,EXIT // request to exit program
svc 0 // perform the system call
qAdrsZoneConv: .quad sZoneConv
qAdrszMessResult: .quad szMessResult
qAdrszCarriageReturn: .quad szCarriageReturn
/******************************************************************/
/* compute the sum and prod */
/******************************************************************/
/* x0 contains the number */
computeSumProd:
stp x1,lr,[sp,-16]! // save registers
asr x10,x0,#63
eor x12,x10,x0
sub x12,x12,x10 // compute absolue value
ldr x13,qAdrqSum // load sum
ldr x11,[x13]
add x11,x11,x12 // add sum
str x11,[x13] // store sum
cmp x0,#0 // j = 0 ?
beq 100f // yes
ldr x13,qAdrqProd
ldr x11,[x13]
asr x12,x11,#63 // compute absolute value of prod
eor x14,x11,x12
sub x12,x14,x12
ldr x10,qVal2P27
cmp x12,x10 // compare 2 puissance 27
bgt 100f
mul x11,x0,x11
str x11,[x13] // store prod
100:
ldp x1,lr,[sp],16 // restaur 2 registers
ret // return to address lr x230
qAdrqSum: .quad qSum
qAdrqProd: .quad qProd
qVal2P27: .quad 1<<27
/******************************************************************/
/* compute pow */
/******************************************************************/
/* x0 contains pow */
/* x1 contains number */
computePow:
stp x1,lr,[sp,-16]! // save registers
mov x12,x0
mov x0,#1
1:
cmp x12,#0
ble 100f
mul x0,x1,x0
sub x12,x12,#1
b 1b
100:
ldp x1,lr,[sp],16 // restaur 2 registers
ret // return to address lr x230
/********************************************************/
/* File Include fonctions */
/********************************************************/
/* for this file see task include a file in language AArch64 assembly */
.include "../includeARM64.inc"
|
http://rosettacode.org/wiki/Loops/With_multiple_ranges | Loops/With multiple ranges | Loops/With multiple ranges
You are encouraged to solve this task according to the task description, using any language you may know.
Some languages allow multiple loop ranges, such as the PL/I example (snippet) below.
/* all variables are DECLARED as integers. */
prod= 1; /*start with a product of unity. */
sum= 0; /* " " " sum " zero. */
x= +5;
y= -5;
z= -2;
one= 1;
three= 3;
seven= 7;
/*(below) ** is exponentiation: 4**3=64 */
do j= -three to 3**3 by three ,
-seven to +seven by x ,
555 to 550 - y ,
22 to -28 by -three ,
1927 to 1939 ,
x to y by z ,
11**x to 11**x + one;
/* ABS(n) = absolute value*/
sum= sum + abs(j); /*add absolute value of J.*/
if abs(prod)<2**27 & j¬=0 then prod=prod*j; /*PROD is small enough & J*/
end; /*not 0, then multiply it.*/
/*SUM and PROD are used for verification of J incrementation.*/
display (' sum= ' || sum); /*display strings to term.*/
display ('prod= ' || prod); /* " " " " */
Task
Simulate/translate the above PL/I program snippet as best as possible in your
language, with particular emphasis on the do loop construct.
The do index must be incremented/decremented in the same order shown.
If feasible, add commas to the two output numbers (being displayed).
Show all output here.
A simple PL/I DO loop (incrementing or decrementing) has the construct of:
DO variable = start_expression {TO ending_expression] {BY increment_expression} ;
---or---
DO variable = start_expression {BY increment_expression} {TO ending_expression] ;
where it is understood that all expressions will have a value. The variable is normally a
scaler variable, but need not be (but for this task, all variables and expressions are declared
to be scaler integers). If the BY expression is omitted, a BY value of unity is used.
All expressions are evaluated before the DO loop is executed, and those values are used
throughout the DO loop execution (even though, for instance, the value of Z may be
changed within the DO loop. This isn't the case here for this task.
A multiple-range DO loop can be constructed by using a comma (,) to separate additional ranges
(the use of multiple TO and/or BY keywords). This is the construct used in this task.
There are other forms of DO loops in PL/I involving the WHILE clause, but those won't be
needed here. DO loops without a TO clause might need a WHILE clause or some other
means of exiting the loop (such as LEAVE, RETURN, SIGNAL, GOTO, or STOP), or some other
(possible error) condition that causes transfer of control outside the DO loop.
Also, in PL/I, the check if the DO loop index value is outside the range is made at the
"head" (start) of the DO loop, so it's possible that the DO loop isn't executed, but
that isn't the case for any of the ranges used in this task.
In the example above, the clause: x to y by z
will cause the variable J to have to following values (in this order): 5 3 1 -1 -3 -5
In the example above, the clause: -seven to +seven by x
will cause the variable J to have to following values (in this order): -7 -2 3
Related tasks
Loop over multiple arrays simultaneously
Loops/Break
Loops/Continue
Loops/Do-while
Loops/Downward for
Loops/For
Loops/For with a specified step
Loops/Foreach
Loops/Increment loop index within loop body
Loops/Infinite
Loops/N plus one half
Loops/Nested
Loops/While
Loops/with multiple ranges
Loops/Wrong ranges
| #Ada | Ada |
with Ada.Text_IO; use Ada.Text_IO;
with Ada.Containers.Vectors;
procedure Main is
package int_vector is new Ada.Containers.Vectors
(Index_Type => Natural, Element_Type => Integer);
use int_vector;
summing_values : Vector := Empty_Vector;
prod : Integer := 1;
sum : Integer := 0;
x : Integer := 5;
y : Integer := -5;
z : Integer := -2;
N : Integer;
begin
N := -3;
while N <= 3**3 loop
summing_values.Append (N);
N := N + 3;
end loop;
N := -7;
while N <= 7 loop
summing_values.Append (N);
N := N + x;
end loop;
for I in 555 .. 550 - y loop
summing_values.Append (I);
end loop;
N := 22;
while N >= -28 loop
summing_values.Append (N);
N := N - 3;
end loop;
for I in 1_927 .. 1_939 loop
summing_values.Append (I);
end loop;
N := x;
while N >= y loop
summing_values.Append (N);
N := N + z;
end loop;
for I in 11**x .. 11**x + 1 loop
summing_values.Append (I);
end loop;
for value of summing_values loop
sum := sum + abs (value);
if abs (prod) < 2**27 and then value /= 0 then
prod := prod * value;
end if;
end loop;
Put_Line ("sum = " & sum'Image);
Put_Line ("prod = " & prod'Image);
end Main;
|
http://rosettacode.org/wiki/Ludic_numbers | Ludic numbers | Ludic numbers are related to prime numbers as they are generated by a sieve quite like the Sieve of Eratosthenes is used to generate prime numbers.
The first ludic number is 1.
To generate succeeding ludic numbers create an array of increasing integers starting from 2.
2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 ...
(Loop)
Take the first member of the resultant array as the next ludic number 2.
Remove every 2nd indexed item from the array (including the first).
2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 ...
(Unrolling a few loops...)
Take the first member of the resultant array as the next ludic number 3.
Remove every 3rd indexed item from the array (including the first).
3 5 7 9 11 13 15 17 19 21 23 25 27 29 31 33 35 37 39 41 43 45 47 49 51 ...
Take the first member of the resultant array as the next ludic number 5.
Remove every 5th indexed item from the array (including the first).
5 7 11 13 17 19 23 25 29 31 35 37 41 43 47 49 53 55 59 61 65 67 71 73 77 ...
Take the first member of the resultant array as the next ludic number 7.
Remove every 7th indexed item from the array (including the first).
7 11 13 17 23 25 29 31 37 41 43 47 53 55 59 61 67 71 73 77 83 85 89 91 97 ...
...
Take the first member of the current array as the next ludic number L.
Remove every Lth indexed item from the array (including the first).
...
Task
Generate and show here the first 25 ludic numbers.
How many ludic numbers are there less than or equal to 1000?
Show the 2000..2005th ludic numbers.
Stretch goal
Show all triplets of ludic numbers < 250.
A triplet is any three numbers
x
,
{\displaystyle x,}
x
+
2
,
{\displaystyle x+2,}
x
+
6
{\displaystyle x+6}
where all three numbers are also ludic numbers.
| #Go | Go | package main
import "fmt"
// Ludic returns a slice of Ludic numbers stopping after
// either n entries or when max is exceeded.
// Either argument may be <=0 to disable that limit.
func Ludic(n int, max int) []uint32 {
const maxInt32 = 1<<31 - 1 // i.e. math.MaxInt32
if max > 0 && n < 0 {
n = maxInt32
}
if n < 1 {
return nil
}
if max < 0 {
max = maxInt32
}
sieve := make([]uint32, 10760) // XXX big enough for 2005 Ludics
sieve[0] = 1
sieve[1] = 2
if n > 2 {
// We start with even numbers already removed
for i, j := 2, uint32(3); i < len(sieve); i, j = i+1, j+2 {
sieve[i] = j
}
// We leave the Ludic numbers in place,
// k is the index of the next Ludic
for k := 2; k < n; k++ {
l := int(sieve[k])
if l >= max {
n = k
break
}
i := l
l--
// last is the last valid index
last := k + i - 1
for j := k + i + 1; j < len(sieve); i, j = i+1, j+1 {
last = k + i
sieve[last] = sieve[j]
if i%l == 0 {
j++
}
}
// Truncate down to only the valid entries
if last < len(sieve)-1 {
sieve = sieve[:last+1]
}
}
}
if n > len(sieve) {
panic("program error") // should never happen
}
return sieve[:n]
}
func has(x []uint32, v uint32) bool {
for i := 0; i < len(x) && x[i] <= v; i++ {
if x[i] == v {
return true
}
}
return false
}
func main() {
// Ludic() is so quick we just call it repeatedly
fmt.Println("First 25:", Ludic(25, -1))
fmt.Println("Numner of Ludics below 1000:", len(Ludic(-1, 1000)))
fmt.Println("Ludic 2000 to 2005:", Ludic(2005, -1)[1999:])
fmt.Print("Tripples below 250:")
x := Ludic(-1, 250)
for i, v := range x[:len(x)-2] {
if has(x[i+1:], v+2) && has(x[i+2:], v+6) {
fmt.Printf(", (%d %d %d)", v, v+2, v+6)
}
}
fmt.Println()
} |
http://rosettacode.org/wiki/Loops/Wrong_ranges | Loops/Wrong ranges | Loops/Wrong ranges
You are encouraged to solve this task according to the task description, using any language you may know.
Some languages have syntax or function(s) to generate a range of numeric values from a start value, a stop value, and an increment.
The purpose of this task is to select the range syntax/function that would generate at least two increasing numbers when given a stop value more than the start value and a positive increment of less than half the difference. You are then to use that same syntax/function but with different parameters; and show, here, what would happen.
Use these values if possible:
start
stop
increment
Comment
-2
2
1
Normal
-2
2
0
Zero increment
-2
2
-1
Increments away from stop value
-2
2
10
First increment is beyond stop value
2
-2
1
Start more than stop: positive increment
2
2
1
Start equal stop: positive increment
2
2
-1
Start equal stop: negative increment
2
2
0
Start equal stop: zero increment
0
0
0
Start equal stop equal zero: zero increment
Related tasks
Loop over multiple arrays simultaneously
Loops/Break
Loops/Continue
Loops/Do-while
Loops/Downward for
Loops/For
Loops/For with a specified step
Loops/Foreach
Loops/Increment loop index within loop body
Loops/Infinite
Loops/N plus one half
Loops/Nested
Loops/While
Loops/with multiple ranges
Loops/Wrong ranges
| #BASIC256 | BASIC256 | arraybase 1
dim start(9) : dim fin(9) : dim inc(9) : dim cmt$(9)
start[1] = -2 : fin[1] = 2 : inc[1] = 1 : cmt$[1] = "Normal"
start[2] = -2 : fin[2] = 2 : inc[2] = 0 : cmt$[2] = "Zero increment"
start[3] = -2 : fin[3] = 2 : inc[3] = -1 : cmt$[3] = "Increments away from stop value"
start[4] = -2 : fin[4] = 2 : inc[4] = 10 : cmt$[4] = "First increment is beyond stop value"
start[5] = 2 : fin[5] = -2 : inc[5] = 1 : cmt$[5] = "Start more than stop: positive increment"
start[6] = 2 : fin[6] = 2 : inc[6] = 1 : cmt$[6] = "Start equal stop: positive increment"
start[7] = 2 : fin[7] = 2 : inc[7] = -1 : cmt$[7] = "Start equal stop: negative increment"
start[8] = 2 : fin[8] = 2 : inc[8] = 0 : cmt$[8] = "Start equal stop: zero increment"
start[9] = 0 : fin[9] = 0 : inc[9] = 0 : cmt$[9] = "Start equal stop equal zero: zero increment"
for i = 1 to 9
contar = 0
print cmt$[i]
print " Bucle de "; start[i]; " a "; fin[i]; " en incrementos de "; inc[i]
for vr = start[i] to fin[i] step inc[i]
print " Índice del bucle = "; vr
contar = contar + 1
if contar = 10 then
print " Saliendo de un bucle infinito"
exit for
endif
next vr
print " Bucle terminado" & chr(10) & chr(10)
next i
end |
http://rosettacode.org/wiki/Luhn_test_of_credit_card_numbers | Luhn test of credit card numbers | The Luhn test is used by some credit card companies to distinguish valid credit card numbers from what could be a random selection of digits.
Those companies using credit card numbers that can be validated by the Luhn test have numbers that pass the following test:
Reverse the order of the digits in the number.
Take the first, third, ... and every other odd digit in the reversed digits and sum them to form the partial sum s1
Taking the second, fourth ... and every other even digit in the reversed digits:
Multiply each digit by two and sum the digits if the answer is greater than nine to form partial sums for the even digits
Sum the partial sums of the even digits to form s2
If s1 + s2 ends in zero then the original number is in the form of a valid credit card number as verified by the Luhn test.
For example, if the trial number is 49927398716:
Reverse the digits:
61789372994
Sum the odd digits:
6 + 7 + 9 + 7 + 9 + 4 = 42 = s1
The even digits:
1, 8, 3, 2, 9
Two times each even digit:
2, 16, 6, 4, 18
Sum the digits of each multiplication:
2, 7, 6, 4, 9
Sum the last:
2 + 7 + 6 + 4 + 9 = 28 = s2
s1 + s2 = 70 which ends in zero which means that 49927398716 passes the Luhn test
Task
Write a function/method/procedure/subroutine that will validate a number with the Luhn test, and
use it to validate the following numbers:
49927398716
49927398717
1234567812345678
1234567812345670
Related tasks
SEDOL
ISIN
| #ABAP | ABAP | METHOD luhn_check.
DATA: sum(1) TYPE n VALUE 0. " Sum of checksum.
DATA: current TYPE i. " Current digit.
DATA: odd TYPE i VALUE 1. " Multiplier.
DATA: len TYPE i. " String crowler.
" Luhn algorithm.
len = NUMOFCHAR( pi_string ) - 1.
WHILE ( len >= 0 ).
current = pi_string+len(1) * odd.
IF ( current > 9 ).
current = current - 9. " Digits sum.
ENDIF.
sum = sum + current.
odd = 3 - odd. " 1 <--> 2 Swich
len = len - 1. " Move to next charcter.
ENDWHILE.
" Validation check.
IF ( sum = 0 ).
pr_valid = abap_true.
ELSE.
pr_valid = abap_false.
ENDIF.
ENDMETHOD. |
http://rosettacode.org/wiki/Lucas-Lehmer_test | Lucas-Lehmer test | Lucas-Lehmer Test:
for
p
{\displaystyle p}
an odd prime, the Mersenne number
2
p
−
1
{\displaystyle 2^{p}-1}
is prime if and only if
2
p
−
1
{\displaystyle 2^{p}-1}
divides
S
(
p
−
1
)
{\displaystyle S(p-1)}
where
S
(
n
+
1
)
=
(
S
(
n
)
)
2
−
2
{\displaystyle S(n+1)=(S(n))^{2}-2}
, and
S
(
1
)
=
4
{\displaystyle S(1)=4}
.
Task
Calculate all Mersenne primes up to the implementation's
maximum precision, or the 47th Mersenne prime (whichever comes first).
| #AWK | AWK |
# syntax: GAWK -f LUCAS-LEHMER_TEST.AWK
# converted from Pascal
BEGIN {
printf("Mersenne primes:")
n = 1
for (exponent=2; exponent<=32; exponent++) {
s = (exponent == 2) ? 0 : 4
n = (n+1)*2-1
for (i=1; i<=exponent-2; i++) {
s = (s*s-2)%n
}
if (s == 0) {
printf(" M%s",exponent)
}
}
printf("\n")
exit(0)
}
|
http://rosettacode.org/wiki/Lucky_and_even_lucky_numbers | Lucky and even lucky numbers | Note that in the following explanation list indices are assumed to start at one.
Definition of lucky numbers
Lucky numbers are positive integers that are formed by:
Form a list of all the positive odd integers > 0
1
,
3
,
5
,
7
,
9
,
11
,
13
,
15
,
17
,
19
,
21
,
23
,
25
,
27
,
29
,
31
,
33
,
35
,
37
,
39...
{\displaystyle 1,3,5,7,9,11,13,15,17,19,21,23,25,27,29,31,33,35,37,39...}
Return the first number from the list (which is 1).
(Loop begins here)
Note then return the second number from the list (which is 3).
Discard every third, (as noted), number from the list to form the new list
1
,
3
,
7
,
9
,
13
,
15
,
19
,
21
,
25
,
27
,
31
,
33
,
37
,
39
,
43
,
45
,
49
,
51
,
55
,
57...
{\displaystyle 1,3,7,9,13,15,19,21,25,27,31,33,37,39,43,45,49,51,55,57...}
(Expanding the loop a few more times...)
Note then return the third number from the list (which is 7).
Discard every 7th, (as noted), number from the list to form the new list
1
,
3
,
7
,
9
,
13
,
15
,
21
,
25
,
27
,
31
,
33
,
37
,
43
,
45
,
49
,
51
,
55
,
57
,
63
,
67...
{\displaystyle 1,3,7,9,13,15,21,25,27,31,33,37,43,45,49,51,55,57,63,67...}
Note then return the 4th number from the list (which is 9).
Discard every 9th, (as noted), number from the list to form the new list
1
,
3
,
7
,
9
,
13
,
15
,
21
,
25
,
31
,
33
,
37
,
43
,
45
,
49
,
51
,
55
,
63
,
67
,
69
,
73...
{\displaystyle 1,3,7,9,13,15,21,25,31,33,37,43,45,49,51,55,63,67,69,73...}
Take the 5th, i.e. 13. Remove every 13th.
Take the 6th, i.e. 15. Remove every 15th.
Take the 7th, i.e. 21. Remove every 21th.
Take the 8th, i.e. 25. Remove every 25th.
(Rule for the loop)
Note the
n
{\displaystyle n}
th, which is
m
{\displaystyle m}
.
Remove every
m
{\displaystyle m}
th.
Increment
n
{\displaystyle n}
.
Definition of even lucky numbers
This follows the same rules as the definition of lucky numbers above except for the very first step:
Form a list of all the positive even integers > 0
2
,
4
,
6
,
8
,
10
,
12
,
14
,
16
,
18
,
20
,
22
,
24
,
26
,
28
,
30
,
32
,
34
,
36
,
38
,
40...
{\displaystyle 2,4,6,8,10,12,14,16,18,20,22,24,26,28,30,32,34,36,38,40...}
Return the first number from the list (which is 2).
(Loop begins here)
Note then return the second number from the list (which is 4).
Discard every 4th, (as noted), number from the list to form the new list
2
,
4
,
6
,
10
,
12
,
14
,
18
,
20
,
22
,
26
,
28
,
30
,
34
,
36
,
38
,
42
,
44
,
46
,
50
,
52...
{\displaystyle 2,4,6,10,12,14,18,20,22,26,28,30,34,36,38,42,44,46,50,52...}
(Expanding the loop a few more times...)
Note then return the third number from the list (which is 6).
Discard every 6th, (as noted), number from the list to form the new list
2
,
4
,
6
,
10
,
12
,
18
,
20
,
22
,
26
,
28
,
34
,
36
,
38
,
42
,
44
,
50
,
52
,
54
,
58
,
60...
{\displaystyle 2,4,6,10,12,18,20,22,26,28,34,36,38,42,44,50,52,54,58,60...}
Take the 4th, i.e. 10. Remove every 10th.
Take the 5th, i.e. 12. Remove every 12th.
(Rule for the loop)
Note the
n
{\displaystyle n}
th, which is
m
{\displaystyle m}
.
Remove every
m
{\displaystyle m}
th.
Increment
n
{\displaystyle n}
.
Task requirements
Write one or two subroutines (functions) to generate lucky numbers and even lucky numbers
Write a command-line interface to allow selection of which kind of numbers and which number(s). Since input is from the command line, tests should be made for the common errors:
missing arguments
too many arguments
number (or numbers) aren't legal
misspelled argument (lucky or evenLucky)
The command line handling should:
support mixed case handling of the (non-numeric) arguments
support printing a particular number
support printing a range of numbers by their index
support printing a range of numbers by their values
The resulting list of numbers should be printed on a single line.
The program should support the arguments:
what is displayed (on a single line)
argument(s) (optional verbiage is encouraged)
╔═══════════════════╦════════════════════════════════════════════════════╗
║ j ║ Jth lucky number ║
║ j , lucky ║ Jth lucky number ║
║ j , evenLucky ║ Jth even lucky number ║
║ ║ ║
║ j k ║ Jth through Kth (inclusive) lucky numbers ║
║ j k lucky ║ Jth through Kth (inclusive) lucky numbers ║
║ j k evenLucky ║ Jth through Kth (inclusive) even lucky numbers ║
║ ║ ║
║ j -k ║ all lucky numbers in the range j ──► |k| ║
║ j -k lucky ║ all lucky numbers in the range j ──► |k| ║
║ j -k evenLucky ║ all even lucky numbers in the range j ──► |k| ║
╚═══════════════════╩════════════════════════════════════════════════════╝
where |k| is the absolute value of k
Demonstrate the program by:
showing the first twenty lucky numbers
showing the first twenty even lucky numbers
showing all lucky numbers between 6,000 and 6,100 (inclusive)
showing all even lucky numbers in the same range as above
showing the 10,000th lucky number (extra credit)
showing the 10,000th even lucky number (extra credit)
See also
This task is related to the Sieve of Eratosthenes task.
OEIS Wiki Lucky numbers.
Sequence A000959 lucky numbers on The On-Line Encyclopedia of Integer Sequences.
Sequence A045954 even lucky numbers or ELN on The On-Line Encyclopedia of Integer Sequences.
Entry lucky numbers on The Eric Weisstein's World of Mathematics.
| #Haskell | Haskell |
import System.Environment
import Text.Regex.Posix
data Lucky = Lucky | EvenLucky
helpMessage :: IO ()
helpMessage = do
putStrLn " what is displayed (on a single line)"
putStrLn " argument(s) (optional verbiage is encouraged)"
putStrLn "======================|==================================================="
putStrLn " j | Jth lucky number "
putStrLn " j , lucky | Jth lucky number "
putStrLn " j , evenLucky | Jth even lucky number "
putStrLn " "
putStrLn " j k | Jth through Kth (inclusive) lucky numbers "
putStrLn " j k lucky | Jth through Kth (inclusive) lucky numbers "
putStrLn " j k evenlucky | Jth through Kth (inclusive) even lucky numbers "
putStrLn " "
putStrLn " j -k | all lucky numbers in the range j -> |k| "
putStrLn " j -k lucky | all lucky numbers in the range j -> |k| "
putStrLn " j -k evenlucky | all even lucky numbers in the range j -> |k| "
putStrLn "======================|==================================================="
oddNumbers :: [Int]
oddNumbers = filter odd [1..]
evenNumbers :: [Int]
evenNumbers = filter even [1..]
luckyNumbers :: [Int] -> [Int]
luckyNumbers xs =
let i = 3 in
sieve i xs
where
sieve i (ln:s:xs) =
ln : sieve (i + 1) (s : [x | (n, x) <- zip [i..] xs, rem n s /= 0])
nth :: Int -> Lucky -> Int
nth j Lucky = luckyNumbers oddNumbers !! (j-1)
nth j EvenLucky = luckyNumbers evenNumbers !! (j-1)
range :: Int -> Int -> Lucky -> [Int]
range x x2 Lucky = drop (x-1) (take x2 (luckyNumbers oddNumbers))
range x x2 EvenLucky = drop (x-1) (take x2 (luckyNumbers evenNumbers))
interval :: Int -> Int -> Lucky -> [Int]
interval x x2 Lucky = dropWhile (<x) (takeWhile (<=x2) (luckyNumbers oddNumbers))
interval x x2 EvenLucky = dropWhile (<x) (takeWhile (<=x2) (luckyNumbers evenNumbers))
lucky :: [String] -> Lucky
lucky xs =
if "evenLucky" `elem` xs
then EvenLucky
else Lucky
readn :: String -> Int
readn s = read s :: Int
isInt :: String -> Bool
isInt s = not (null (s =~ "-?[0-9]{0,10}" :: String))
main :: IO ()
main = do
args <- getArgs
if head args == "--help" || null args
then
helpMessage
else
let l = lucky args in
case map readn (filter isInt args) of
[] -> do
putStrLn "Invalid input, missing arguments"
putStrLn "Type --help"
[x] -> print (nth x l)
[x, x2] -> if x2 > 0
then print (range x x2 l)
else print (interval x (-x2) l)
_ -> do
putStrLn "Invalid input, wrong number of arguments"
putStrLn "Type --help" |
http://rosettacode.org/wiki/LZW_compression | LZW compression | The Lempel-Ziv-Welch (LZW) algorithm provides loss-less data compression.
You can read a complete description of it in the Wikipedia article on the subject. It was patented, but it entered the public domain in 2004.
| #C.23 | C# | using System;
using System.Collections.Generic;
using System.Text;
namespace LZW
{
public class Program
{
public static void Main(string[] args)
{
List<int> compressed = Compress("TOBEORNOTTOBEORTOBEORNOT");
Console.WriteLine(string.Join(", ", compressed));
string decompressed = Decompress(compressed);
Console.WriteLine(decompressed);
}
public static List<int> Compress(string uncompressed)
{
// build the dictionary
Dictionary<string, int> dictionary = new Dictionary<string, int>();
for (int i = 0; i < 256; i++)
dictionary.Add(((char)i).ToString(), i);
string w = string.Empty;
List<int> compressed = new List<int>();
foreach (char c in uncompressed)
{
string wc = w + c;
if (dictionary.ContainsKey(wc))
{
w = wc;
}
else
{
// write w to output
compressed.Add(dictionary[w]);
// wc is a new sequence; add it to the dictionary
dictionary.Add(wc, dictionary.Count);
w = c.ToString();
}
}
// write remaining output if necessary
if (!string.IsNullOrEmpty(w))
compressed.Add(dictionary[w]);
return compressed;
}
public static string Decompress(List<int> compressed)
{
// build the dictionary
Dictionary<int, string> dictionary = new Dictionary<int, string>();
for (int i = 0; i < 256; i++)
dictionary.Add(i, ((char)i).ToString());
string w = dictionary[compressed[0]];
compressed.RemoveAt(0);
StringBuilder decompressed = new StringBuilder(w);
foreach (int k in compressed)
{
string entry = null;
if (dictionary.ContainsKey(k))
entry = dictionary[k];
else if (k == dictionary.Count)
entry = w + w[0];
decompressed.Append(entry);
// new sequence; add it to the dictionary
dictionary.Add(dictionary.Count, w + entry[0]);
w = entry;
}
return decompressed.ToString();
}
}
} |
http://rosettacode.org/wiki/LU_decomposition | LU decomposition | Every square matrix
A
{\displaystyle A}
can be decomposed into a product of a lower triangular matrix
L
{\displaystyle L}
and a upper triangular matrix
U
{\displaystyle U}
,
as described in LU decomposition.
A
=
L
U
{\displaystyle A=LU}
It is a modified form of Gaussian elimination.
While the Cholesky decomposition only works for symmetric,
positive definite matrices, the more general LU decomposition
works for any square matrix.
There are several algorithms for calculating L and U.
To derive Crout's algorithm for a 3x3 example,
we have to solve the following system:
A
=
(
a
11
a
12
a
13
a
21
a
22
a
23
a
31
a
32
a
33
)
=
(
l
11
0
0
l
21
l
22
0
l
31
l
32
l
33
)
(
u
11
u
12
u
13
0
u
22
u
23
0
0
u
33
)
=
L
U
{\displaystyle A={\begin{pmatrix}a_{11}&a_{12}&a_{13}\\a_{21}&a_{22}&a_{23}\\a_{31}&a_{32}&a_{33}\\\end{pmatrix}}={\begin{pmatrix}l_{11}&0&0\\l_{21}&l_{22}&0\\l_{31}&l_{32}&l_{33}\\\end{pmatrix}}{\begin{pmatrix}u_{11}&u_{12}&u_{13}\\0&u_{22}&u_{23}\\0&0&u_{33}\end{pmatrix}}=LU}
We now would have to solve 9 equations with 12 unknowns. To make the system uniquely solvable, usually the diagonal elements of
L
{\displaystyle L}
are set to 1
l
11
=
1
{\displaystyle l_{11}=1}
l
22
=
1
{\displaystyle l_{22}=1}
l
33
=
1
{\displaystyle l_{33}=1}
so we get a solvable system of 9 unknowns and 9 equations.
A
=
(
a
11
a
12
a
13
a
21
a
22
a
23
a
31
a
32
a
33
)
=
(
1
0
0
l
21
1
0
l
31
l
32
1
)
(
u
11
u
12
u
13
0
u
22
u
23
0
0
u
33
)
=
(
u
11
u
12
u
13
u
11
l
21
u
12
l
21
+
u
22
u
13
l
21
+
u
23
u
11
l
31
u
12
l
31
+
u
22
l
32
u
13
l
31
+
u
23
l
32
+
u
33
)
=
L
U
{\displaystyle A={\begin{pmatrix}a_{11}&a_{12}&a_{13}\\a_{21}&a_{22}&a_{23}\\a_{31}&a_{32}&a_{33}\\\end{pmatrix}}={\begin{pmatrix}1&0&0\\l_{21}&1&0\\l_{31}&l_{32}&1\\\end{pmatrix}}{\begin{pmatrix}u_{11}&u_{12}&u_{13}\\0&u_{22}&u_{23}\\0&0&u_{33}\end{pmatrix}}={\begin{pmatrix}u_{11}&u_{12}&u_{13}\\u_{11}l_{21}&u_{12}l_{21}+u_{22}&u_{13}l_{21}+u_{23}\\u_{11}l_{31}&u_{12}l_{31}+u_{22}l_{32}&u_{13}l_{31}+u_{23}l_{32}+u_{33}\end{pmatrix}}=LU}
Solving for the other
l
{\displaystyle l}
and
u
{\displaystyle u}
, we get the following equations:
u
11
=
a
11
{\displaystyle u_{11}=a_{11}}
u
12
=
a
12
{\displaystyle u_{12}=a_{12}}
u
13
=
a
13
{\displaystyle u_{13}=a_{13}}
u
22
=
a
22
−
u
12
l
21
{\displaystyle u_{22}=a_{22}-u_{12}l_{21}}
u
23
=
a
23
−
u
13
l
21
{\displaystyle u_{23}=a_{23}-u_{13}l_{21}}
u
33
=
a
33
−
(
u
13
l
31
+
u
23
l
32
)
{\displaystyle u_{33}=a_{33}-(u_{13}l_{31}+u_{23}l_{32})}
and for
l
{\displaystyle l}
:
l
21
=
1
u
11
a
21
{\displaystyle l_{21}={\frac {1}{u_{11}}}a_{21}}
l
31
=
1
u
11
a
31
{\displaystyle l_{31}={\frac {1}{u_{11}}}a_{31}}
l
32
=
1
u
22
(
a
32
−
u
12
l
31
)
{\displaystyle l_{32}={\frac {1}{u_{22}}}(a_{32}-u_{12}l_{31})}
We see that there is a calculation pattern, which can be expressed as the following formulas, first for
U
{\displaystyle U}
u
i
j
=
a
i
j
−
∑
k
=
1
i
−
1
u
k
j
l
i
k
{\displaystyle u_{ij}=a_{ij}-\sum _{k=1}^{i-1}u_{kj}l_{ik}}
and then for
L
{\displaystyle L}
l
i
j
=
1
u
j
j
(
a
i
j
−
∑
k
=
1
j
−
1
u
k
j
l
i
k
)
{\displaystyle l_{ij}={\frac {1}{u_{jj}}}(a_{ij}-\sum _{k=1}^{j-1}u_{kj}l_{ik})}
We see in the second formula that to get the
l
i
j
{\displaystyle l_{ij}}
below the diagonal, we have to divide by the diagonal element (pivot)
u
j
j
{\displaystyle u_{jj}}
, so we get problems when
u
j
j
{\displaystyle u_{jj}}
is either 0 or very small, which leads to numerical instability.
The solution to this problem is pivoting
A
{\displaystyle A}
, which means rearranging the rows of
A
{\displaystyle A}
, prior to the
L
U
{\displaystyle LU}
decomposition, in a way that the largest element of each column gets onto the diagonal of
A
{\displaystyle A}
. Rearranging the rows means to multiply
A
{\displaystyle A}
by a permutation matrix
P
{\displaystyle P}
:
P
A
⇒
A
′
{\displaystyle PA\Rightarrow A'}
Example:
(
0
1
1
0
)
(
1
4
2
3
)
⇒
(
2
3
1
4
)
{\displaystyle {\begin{pmatrix}0&1\\1&0\end{pmatrix}}{\begin{pmatrix}1&4\\2&3\end{pmatrix}}\Rightarrow {\begin{pmatrix}2&3\\1&4\end{pmatrix}}}
The decomposition algorithm is then applied on the rearranged matrix so that
P
A
=
L
U
{\displaystyle PA=LU}
Task description
The task is to implement a routine which will take a square nxn matrix
A
{\displaystyle A}
and return a lower triangular matrix
L
{\displaystyle L}
, a upper triangular matrix
U
{\displaystyle U}
and a permutation matrix
P
{\displaystyle P}
,
so that the above equation is fulfilled.
You should then test it on the following two examples and include your output.
Example 1
A
1 3 5
2 4 7
1 1 0
L
1.00000 0.00000 0.00000
0.50000 1.00000 0.00000
0.50000 -1.00000 1.00000
U
2.00000 4.00000 7.00000
0.00000 1.00000 1.50000
0.00000 0.00000 -2.00000
P
0 1 0
1 0 0
0 0 1
Example 2
A
11 9 24 2
1 5 2 6
3 17 18 1
2 5 7 1
L
1.00000 0.00000 0.00000 0.00000
0.27273 1.00000 0.00000 0.00000
0.09091 0.28750 1.00000 0.00000
0.18182 0.23125 0.00360 1.00000
U
11.00000 9.00000 24.00000 2.00000
0.00000 14.54545 11.45455 0.45455
0.00000 0.00000 -3.47500 5.68750
0.00000 0.00000 0.00000 0.51079
P
1 0 0 0
0 0 1 0
0 1 0 0
0 0 0 1
| #Common_Lisp | Common Lisp | ;; Creates a nxn identity matrix.
(defun eye (n)
(let ((I (make-array `(,n ,n) :initial-element 0)))
(loop for j from 0 to (- n 1) do
(setf (aref I j j) 1))
I))
;; Swap two rows l and k of a mxn matrix A, which is a 2D array.
(defun swap-rows (A l k)
(let* ((n (cadr (array-dimensions A)))
(row (make-array n :initial-element 0)))
(loop for j from 0 to (- n 1) do
(setf (aref row j) (aref A l j))
(setf (aref A l j) (aref A k j))
(setf (aref A k j) (aref row j)))))
;; Creates the pivoting matrix for A.
(defun pivotize (A)
(let* ((n (car (array-dimensions A)))
(P (eye n)))
(loop for j from 0 to (- n 1) do
(let ((max (aref A j j))
(row j))
(loop for i from j to (- n 1) do
(if (> (aref A i j) max)
(setq max (aref A i j)
row i)))
(if (not (= j row))
(swap-rows P j row))))
;; Return P.
P))
;; Decomposes a square matrix A by PA=LU and returns L, U and P.
(defun lu (A)
(let* ((n (car (array-dimensions A)))
(L (make-array `(,n ,n) :initial-element 0))
(U (make-array `(,n ,n) :initial-element 0))
(P (pivotize A))
(A (mmul P A)))
(loop for j from 0 to (- n 1) do
(setf (aref L j j) 1)
(loop for i from 0 to j do
(setf (aref U i j)
(- (aref A i j)
(loop for k from 0 to (- i 1)
sum (* (aref U k j)
(aref L i k))))))
(loop for i from j to (- n 1) do
(setf (aref L i j)
(/ (- (aref A i j)
(loop for k from 0 to (- j 1)
sum (* (aref U k j)
(aref L i k))))
(aref U j j)))))
;; Return L, U and P.
(values L U P))) |
http://rosettacode.org/wiki/Lychrel_numbers | Lychrel numbers | Take an integer n, greater than zero.
Form the next n of its series by reversing the digits of the current n and adding the result to the current n.
Stop when n becomes palindromic - i.e. the digits of n in reverse order == n.
The above recurrence relation when applied to most starting numbers n = 1, 2, ... terminates in a palindrome quite quickly.
Example
If n0 = 12 we get
12
12 + 21 = 33, a palindrome!
And if n0 = 55 we get
55
55 + 55 = 110
110 + 011 = 121, a palindrome!
Notice that the check for a palindrome happens after an addition.
Some starting numbers seem to go on forever; the recurrence relation for 196 has been calculated for millions of repetitions forming numbers with millions of digits, without forming a palindrome.
These numbers that do not end in a palindrome are called Lychrel numbers.
For the purposes of this task a Lychrel number is any starting number that does not form a palindrome within 500 (or more) iterations.
Seed and related Lychrel numbers
Any integer produced in the sequence of a Lychrel number is also a Lychrel number.
In general, any sequence from one Lychrel number might converge to join the sequence from a prior Lychrel number candidate; for example the sequences for the numbers 196 and then 689 begin:
196
196 + 691 = 887
887 + 788 = 1675
1675 + 5761 = 7436
7436 + 6347 = 13783
13783 + 38731 = 52514
52514 + 41525 = 94039
...
689
689 + 986 = 1675
1675 + 5761 = 7436
...
So we see that the sequence starting with 689 converges to, and continues with the same numbers as that for 196.
Because of this we can further split the Lychrel numbers into true Seed Lychrel number candidates, and Related numbers that produce no palindromes but have integers in their sequence seen as part of the sequence generated from a lower Lychrel number.
Task
Find the number of seed Lychrel number candidates and related numbers for n in the range 1..10000 inclusive. (With that iteration limit of 500).
Print the number of seed Lychrels found; the actual seed Lychrels; and just the number of relateds found.
Print any seed Lychrel or related number that is itself a palindrome.
Show all output here.
References
What's special about 196? Numberphile video.
A023108 Positive integers which apparently never result in a palindrome under repeated applications of the function f(x) = x + (x with digits reversed).
Status of the 196 conjecture? Mathoverflow.
| #J | J | revdig=:('x',~|.)&.":"0 |
http://rosettacode.org/wiki/Magic_8-ball | Magic 8-ball | Task
Create Magic 8-Ball.
See details at: Magic 8-Ball.
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
| #Ruby | Ruby | #!/usr/bin/ruby
class EightBall
def initialize
print "Welcome to 8 ball! Ask your question below. "
puts "Type 'quit' to exit the program.\n\n"
@responses = ["It is certain", "It is decidedly so",
"Without a doubt", "Yes, definitely",
"You may rely on it", "As I see it, yes",
"Most likely", "Outlook good",
"Signs point to yes", "Yes",
"Reply hazy, try again", "Ask again later",
"Better not tell you now",
"Cannot predict now",
"Concentrate and ask again", "Don't bet on it",
"My reply is no", "My sources say no",
"Outlook not so good", "Very doubtful"]
end
def ask_question
print "Question: "
question = gets
if question.chomp.eql? "quit"
exit(0)
end
puts "Response: #{@responses.sample} \n\n"
end
def run
loop do
ask_question
end
end
end
eight_ball = EightBall.new
eight_ball.run
|
http://rosettacode.org/wiki/Magic_8-ball | Magic 8-ball | Task
Create Magic 8-Ball.
See details at: Magic 8-Ball.
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
| #Rust | Rust | extern crate rand;
use rand::prelude::*;
use std::io;
fn main() {
let answers = [
"It is certain",
"It is decidedly so",
"Without a doubt",
"Yes, definitely",
"You may rely on it",
"As I see it, yes",
"Most likely",
"Outlook good",
"Signs point to yes",
"Yes",
"Reply hazy, try again",
"Ask again later",
"Better not tell you now",
"Cannot predict now",
"Concentrate and ask again",
"Don't bet on it",
"My reply is no",
"My sources say no",
"Outlook not so good",
"Very doubtful",
];
let mut rng = rand::thread_rng();
let mut input_line = String::new();
println!("Please enter your question or a blank line to quit.\n");
loop {
io::stdin()
.read_line(&mut input_line)
.expect("The read line failed.");
if input_line.trim() == "" {
break;
}
println!("{}\n", answers.choose(&mut rng).unwrap());
input_line.clear();
}
} |
http://rosettacode.org/wiki/Mandelbrot_set | Mandelbrot set | Mandelbrot set
You are encouraged to solve this task according to the task description, using any language you may know.
Task
Generate and draw the Mandelbrot set.
Note that there are many algorithms to draw Mandelbrot set and there are many functions which generate it .
| #XPL0 | XPL0 | include c:\cxpl\codes; \intrinsic 'code' declarations
int X, Y, \screen coordinates of current point
Cnt; \iteration counter
real Cx, Cy, \coordinates scaled to +/-2 range
Zx, Zy, \complex accumulator
Temp; \temporary scratch
[SetVid($112); \set 640x480x24 graphics mode
for Y:= 0 to 480-1 do \for all points on the screen...
for X:= 0 to 640-1 do
[Cx:= (float(X)/640.0 - 0.5) * 4.0; \range: -2.0 to +2.0
Cy:= (float(Y-240)/240.0) * 1.5; \range: -1.5 to +1.5
Cnt:= 0; Zx:= 0.0; Zy:= 0.0; \initialize
loop [if Zx*Zx + Zy*Zy > 2.0 then \Z heads toward infinity
[Point(X, Y, Cnt<<21+Cnt<<10+Cnt<<3); \set color of pixel to
quit; \ rate it approached infinity
]; \move on to next point
Temp:= Zx*Zy;
Zx:= Zx*Zx - Zy*Zy + Cx; \calculate next iteration of Z
Zy:= 2.0*Temp + Cy;
Cnt:= Cnt+1; \count number of iterations
if Cnt >= 1000 then quit; \assume point is in Mandelbrot
]; \ set and leave it colored black
];
X:= ChIn(1); \wait for keystroke
SetVid($03); \restore normal text display
] |
http://rosettacode.org/wiki/Mad_Libs | Mad Libs |
This page uses content from Wikipedia. The original article was at Mad Libs. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance)
Mad Libs is a phrasal template word game where one player prompts another for a list of words to substitute for blanks in a story, usually with funny results.
Task;
Write a program to create a Mad Libs like story.
The program should read an arbitrary multiline story from input.
The story will be terminated with a blank line.
Then, find each replacement to be made within the story, ask the user for a word to replace it with, and make all the replacements.
Stop when there are none left and print the final story.
The input should be an arbitrary story in the form:
<name> went for a walk in the park. <he or she>
found a <noun>. <name> decided to take it home.
Given this example, it should then ask for a name, a he or she and a noun (<name> gets replaced both times with the same value).
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
| #Fortran | Fortran | Reads a story in template form, containing special entries such as <dog's name> amongst the text.
You will be invited to supply a replacement text for each such entry, as encountered,
after which the story will be presented with your substitutions made.
|
http://rosettacode.org/wiki/Loops/With_multiple_ranges | Loops/With multiple ranges | Loops/With multiple ranges
You are encouraged to solve this task according to the task description, using any language you may know.
Some languages allow multiple loop ranges, such as the PL/I example (snippet) below.
/* all variables are DECLARED as integers. */
prod= 1; /*start with a product of unity. */
sum= 0; /* " " " sum " zero. */
x= +5;
y= -5;
z= -2;
one= 1;
three= 3;
seven= 7;
/*(below) ** is exponentiation: 4**3=64 */
do j= -three to 3**3 by three ,
-seven to +seven by x ,
555 to 550 - y ,
22 to -28 by -three ,
1927 to 1939 ,
x to y by z ,
11**x to 11**x + one;
/* ABS(n) = absolute value*/
sum= sum + abs(j); /*add absolute value of J.*/
if abs(prod)<2**27 & j¬=0 then prod=prod*j; /*PROD is small enough & J*/
end; /*not 0, then multiply it.*/
/*SUM and PROD are used for verification of J incrementation.*/
display (' sum= ' || sum); /*display strings to term.*/
display ('prod= ' || prod); /* " " " " */
Task
Simulate/translate the above PL/I program snippet as best as possible in your
language, with particular emphasis on the do loop construct.
The do index must be incremented/decremented in the same order shown.
If feasible, add commas to the two output numbers (being displayed).
Show all output here.
A simple PL/I DO loop (incrementing or decrementing) has the construct of:
DO variable = start_expression {TO ending_expression] {BY increment_expression} ;
---or---
DO variable = start_expression {BY increment_expression} {TO ending_expression] ;
where it is understood that all expressions will have a value. The variable is normally a
scaler variable, but need not be (but for this task, all variables and expressions are declared
to be scaler integers). If the BY expression is omitted, a BY value of unity is used.
All expressions are evaluated before the DO loop is executed, and those values are used
throughout the DO loop execution (even though, for instance, the value of Z may be
changed within the DO loop. This isn't the case here for this task.
A multiple-range DO loop can be constructed by using a comma (,) to separate additional ranges
(the use of multiple TO and/or BY keywords). This is the construct used in this task.
There are other forms of DO loops in PL/I involving the WHILE clause, but those won't be
needed here. DO loops without a TO clause might need a WHILE clause or some other
means of exiting the loop (such as LEAVE, RETURN, SIGNAL, GOTO, or STOP), or some other
(possible error) condition that causes transfer of control outside the DO loop.
Also, in PL/I, the check if the DO loop index value is outside the range is made at the
"head" (start) of the DO loop, so it's possible that the DO loop isn't executed, but
that isn't the case for any of the ranges used in this task.
In the example above, the clause: x to y by z
will cause the variable J to have to following values (in this order): 5 3 1 -1 -3 -5
In the example above, the clause: -seven to +seven by x
will cause the variable J to have to following values (in this order): -7 -2 3
Related tasks
Loop over multiple arrays simultaneously
Loops/Break
Loops/Continue
Loops/Do-while
Loops/Downward for
Loops/For
Loops/For with a specified step
Loops/Foreach
Loops/Increment loop index within loop body
Loops/Infinite
Loops/N plus one half
Loops/Nested
Loops/While
Loops/with multiple ranges
Loops/Wrong ranges
| #ALGOL_60 | ALGOL 60 | begin
integer prod, sum, x, y, z, one, three, seven;
integer j;
prod := 1;
sum := 0;
x := 5; y := -5; z := -2;
one := 1;
three := 3;
seven := 7;
for j := -three step three until 3^3 ,
-seven step x until seven ,
555 step 1 until 550 - y,
22 step -three until -28 ,
1927 step 1 until 1939 ,
x step z until y ,
11^x step 1 until 11^x + one
do begin
sum := sum + iabs(j);
if iabs(prod) < 2^27 & j != 0 then prod := prod*j
end;
outstring(1, " sum= "); outinteger(1, sum); outstring(1, "\n");
outstring(1, "prod= "); outinteger(1, prod); outstring(1, "\n")
end
|
http://rosettacode.org/wiki/Loops/With_multiple_ranges | Loops/With multiple ranges | Loops/With multiple ranges
You are encouraged to solve this task according to the task description, using any language you may know.
Some languages allow multiple loop ranges, such as the PL/I example (snippet) below.
/* all variables are DECLARED as integers. */
prod= 1; /*start with a product of unity. */
sum= 0; /* " " " sum " zero. */
x= +5;
y= -5;
z= -2;
one= 1;
three= 3;
seven= 7;
/*(below) ** is exponentiation: 4**3=64 */
do j= -three to 3**3 by three ,
-seven to +seven by x ,
555 to 550 - y ,
22 to -28 by -three ,
1927 to 1939 ,
x to y by z ,
11**x to 11**x + one;
/* ABS(n) = absolute value*/
sum= sum + abs(j); /*add absolute value of J.*/
if abs(prod)<2**27 & j¬=0 then prod=prod*j; /*PROD is small enough & J*/
end; /*not 0, then multiply it.*/
/*SUM and PROD are used for verification of J incrementation.*/
display (' sum= ' || sum); /*display strings to term.*/
display ('prod= ' || prod); /* " " " " */
Task
Simulate/translate the above PL/I program snippet as best as possible in your
language, with particular emphasis on the do loop construct.
The do index must be incremented/decremented in the same order shown.
If feasible, add commas to the two output numbers (being displayed).
Show all output here.
A simple PL/I DO loop (incrementing or decrementing) has the construct of:
DO variable = start_expression {TO ending_expression] {BY increment_expression} ;
---or---
DO variable = start_expression {BY increment_expression} {TO ending_expression] ;
where it is understood that all expressions will have a value. The variable is normally a
scaler variable, but need not be (but for this task, all variables and expressions are declared
to be scaler integers). If the BY expression is omitted, a BY value of unity is used.
All expressions are evaluated before the DO loop is executed, and those values are used
throughout the DO loop execution (even though, for instance, the value of Z may be
changed within the DO loop. This isn't the case here for this task.
A multiple-range DO loop can be constructed by using a comma (,) to separate additional ranges
(the use of multiple TO and/or BY keywords). This is the construct used in this task.
There are other forms of DO loops in PL/I involving the WHILE clause, but those won't be
needed here. DO loops without a TO clause might need a WHILE clause or some other
means of exiting the loop (such as LEAVE, RETURN, SIGNAL, GOTO, or STOP), or some other
(possible error) condition that causes transfer of control outside the DO loop.
Also, in PL/I, the check if the DO loop index value is outside the range is made at the
"head" (start) of the DO loop, so it's possible that the DO loop isn't executed, but
that isn't the case for any of the ranges used in this task.
In the example above, the clause: x to y by z
will cause the variable J to have to following values (in this order): 5 3 1 -1 -3 -5
In the example above, the clause: -seven to +seven by x
will cause the variable J to have to following values (in this order): -7 -2 3
Related tasks
Loop over multiple arrays simultaneously
Loops/Break
Loops/Continue
Loops/Do-while
Loops/Downward for
Loops/For
Loops/For with a specified step
Loops/Foreach
Loops/Increment loop index within loop body
Loops/Infinite
Loops/N plus one half
Loops/Nested
Loops/While
Loops/with multiple ranges
Loops/Wrong ranges
| #ALGOL_68 | ALGOL 68 | BEGIN
# translation of task PL/1 code, with minimal changes, semicolons required by #
# PL/1 but not allowed in Algol 68 removed, unecessary rounding removed #
# Note that in Algol 68, the loop counter is a local variable to the loop and #
# the value of j is not available outside the loops #
PROC loop body = ( INT j )VOID: #(below) ** is exponentiation: 4**3=64 #
BEGIN sum +:= ABS j; #add absolute value of J.#
IF ABS prod<2**27 AND j /= 0 THEN prod *:= j FI #PROD is small enough & J#
# ABS(n) = absolute value#
END; #not 0, then multiply it.#
#SUM and PROD are used for verification of J incrementation.#
INT prod := 1; #start with a product of unity. #
INT sum := 0; # " " " sum " zero. #
INT x := +5;
INT y := -5;
INT z := -2;
INT one := 1;
INT three := 3;
INT seven := 7;
FOR j FROM -three BY three TO ( 3**3 ) DO loop body( j ) OD;
FOR j FROM -seven BY x TO +seven DO loop body( j ) OD;
FOR j FROM 555 TO 550 - y DO loop body( j ) OD;
FOR j FROM 22 BY -three TO -28 DO loop body( j ) OD;
FOR j FROM 1927 TO 1939 DO loop body( j ) OD;
FOR j FROM x BY z TO y DO loop body( j ) OD;
FOR j FROM ( 11**x ) TO ( 11**x ) + one DO loop body( j ) OD;
print((" sum= ", whole( sum,0), newline)); #display strings to term.#
print(("prod= ", whole(prod,0), newline)) # " " " " #
END
|
http://rosettacode.org/wiki/Ludic_numbers | Ludic numbers | Ludic numbers are related to prime numbers as they are generated by a sieve quite like the Sieve of Eratosthenes is used to generate prime numbers.
The first ludic number is 1.
To generate succeeding ludic numbers create an array of increasing integers starting from 2.
2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 ...
(Loop)
Take the first member of the resultant array as the next ludic number 2.
Remove every 2nd indexed item from the array (including the first).
2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 ...
(Unrolling a few loops...)
Take the first member of the resultant array as the next ludic number 3.
Remove every 3rd indexed item from the array (including the first).
3 5 7 9 11 13 15 17 19 21 23 25 27 29 31 33 35 37 39 41 43 45 47 49 51 ...
Take the first member of the resultant array as the next ludic number 5.
Remove every 5th indexed item from the array (including the first).
5 7 11 13 17 19 23 25 29 31 35 37 41 43 47 49 53 55 59 61 65 67 71 73 77 ...
Take the first member of the resultant array as the next ludic number 7.
Remove every 7th indexed item from the array (including the first).
7 11 13 17 23 25 29 31 37 41 43 47 53 55 59 61 67 71 73 77 83 85 89 91 97 ...
...
Take the first member of the current array as the next ludic number L.
Remove every Lth indexed item from the array (including the first).
...
Task
Generate and show here the first 25 ludic numbers.
How many ludic numbers are there less than or equal to 1000?
Show the 2000..2005th ludic numbers.
Stretch goal
Show all triplets of ludic numbers < 250.
A triplet is any three numbers
x
,
{\displaystyle x,}
x
+
2
,
{\displaystyle x+2,}
x
+
6
{\displaystyle x+6}
where all three numbers are also ludic numbers.
| #Haskell | Haskell | import Data.List (unfoldr, genericSplitAt)
ludic :: [Integer]
ludic = 1 : unfoldr (\xs@(x:_) -> Just (x, dropEvery x xs)) [2 ..]
where
dropEvery n = concatMap tail . unfoldr (Just . genericSplitAt n)
main :: IO ()
main = do
print $ take 25 ludic
(print . length) $ takeWhile (<= 1000) ludic
print $ take 6 $ drop 1999 ludic
-- haven't done triplets task yet |
http://rosettacode.org/wiki/Loops/Wrong_ranges | Loops/Wrong ranges | Loops/Wrong ranges
You are encouraged to solve this task according to the task description, using any language you may know.
Some languages have syntax or function(s) to generate a range of numeric values from a start value, a stop value, and an increment.
The purpose of this task is to select the range syntax/function that would generate at least two increasing numbers when given a stop value more than the start value and a positive increment of less than half the difference. You are then to use that same syntax/function but with different parameters; and show, here, what would happen.
Use these values if possible:
start
stop
increment
Comment
-2
2
1
Normal
-2
2
0
Zero increment
-2
2
-1
Increments away from stop value
-2
2
10
First increment is beyond stop value
2
-2
1
Start more than stop: positive increment
2
2
1
Start equal stop: positive increment
2
2
-1
Start equal stop: negative increment
2
2
0
Start equal stop: zero increment
0
0
0
Start equal stop equal zero: zero increment
Related tasks
Loop over multiple arrays simultaneously
Loops/Break
Loops/Continue
Loops/Do-while
Loops/Downward for
Loops/For
Loops/For with a specified step
Loops/Foreach
Loops/Increment loop index within loop body
Loops/Infinite
Loops/N plus one half
Loops/Nested
Loops/While
Loops/with multiple ranges
Loops/Wrong ranges
| #C | C | #include <stdio.h>
#define TRUE 1
#define FALSE 0
typedef int bool;
typedef struct {
int start, stop, incr;
const char *comment;
} S;
S examples[9] = {
{-2, 2, 1, "Normal"},
{-2, 2, 0, "Zero increment"},
{-2, 2, -1, "Increments away from stop value"},
{-2, 2, 10, "First increment is beyond stop value"},
{2, -2, 1, "Start more than stop: positive increment"},
{2, 2, 1, "Start equal stop: positive increment"},
{2, 2, -1, "Start equal stop: negative increment"},
{2, 2, 0, "Start equal stop: zero increment"},
{0, 0, 0, "Start equal stop equal zero: zero increment"}
};
int main() {
int i, j, c;
bool empty;
S s;
const int limit = 10;
for (i = 0; i < 9; ++i) {
s = examples[i];
printf("%s\n", s.comment);
printf("Range(%d, %d, %d) -> [", s.start, s.stop, s.incr);
empty = TRUE;
for (j = s.start, c = 0; j <= s.stop && c < limit; j += s.incr, ++c) {
printf("%d ", j);
empty = FALSE;
}
if (!empty) printf("\b");
printf("]\n\n");
}
return 0;
} |
http://rosettacode.org/wiki/Luhn_test_of_credit_card_numbers | Luhn test of credit card numbers | The Luhn test is used by some credit card companies to distinguish valid credit card numbers from what could be a random selection of digits.
Those companies using credit card numbers that can be validated by the Luhn test have numbers that pass the following test:
Reverse the order of the digits in the number.
Take the first, third, ... and every other odd digit in the reversed digits and sum them to form the partial sum s1
Taking the second, fourth ... and every other even digit in the reversed digits:
Multiply each digit by two and sum the digits if the answer is greater than nine to form partial sums for the even digits
Sum the partial sums of the even digits to form s2
If s1 + s2 ends in zero then the original number is in the form of a valid credit card number as verified by the Luhn test.
For example, if the trial number is 49927398716:
Reverse the digits:
61789372994
Sum the odd digits:
6 + 7 + 9 + 7 + 9 + 4 = 42 = s1
The even digits:
1, 8, 3, 2, 9
Two times each even digit:
2, 16, 6, 4, 18
Sum the digits of each multiplication:
2, 7, 6, 4, 9
Sum the last:
2 + 7 + 6 + 4 + 9 = 28 = s2
s1 + s2 = 70 which ends in zero which means that 49927398716 passes the Luhn test
Task
Write a function/method/procedure/subroutine that will validate a number with the Luhn test, and
use it to validate the following numbers:
49927398716
49927398717
1234567812345678
1234567812345670
Related tasks
SEDOL
ISIN
| #ACL2 | ACL2 | (include-book "arithmetic-3/top" :dir :system)
(defun digits (n)
(if (zp n)
nil
(cons (mod n 10)
(digits (floor n 10)))))
(defun sum (xs)
(if (endp xs)
0
(+ (first xs)
(sum (rest xs)))))
(defun double-and-sum-digits (xs)
(if (endp xs)
nil
(cons (sum (digits (* 2 (first xs))))
(double-and-sum-digits (rest xs)))))
(defun dmx (xs)
(if (endp (rest xs))
(mv xs nil)
(mv-let (odds evens)
(dmx (rest (rest xs)))
(mv (cons (first xs) odds)
(cons (second xs) evens)))))
(defun luhn (n)
(mv-let (odds evens)
(dmx (digits n))
(= (mod (+ (sum odds)
(sum (double-and-sum-digits evens)))
10)
0))) |
http://rosettacode.org/wiki/Lucas-Lehmer_test | Lucas-Lehmer test | Lucas-Lehmer Test:
for
p
{\displaystyle p}
an odd prime, the Mersenne number
2
p
−
1
{\displaystyle 2^{p}-1}
is prime if and only if
2
p
−
1
{\displaystyle 2^{p}-1}
divides
S
(
p
−
1
)
{\displaystyle S(p-1)}
where
S
(
n
+
1
)
=
(
S
(
n
)
)
2
−
2
{\displaystyle S(n+1)=(S(n))^{2}-2}
, and
S
(
1
)
=
4
{\displaystyle S(1)=4}
.
Task
Calculate all Mersenne primes up to the implementation's
maximum precision, or the 47th Mersenne prime (whichever comes first).
| #BBC_BASIC | BBC BASIC | *FLOAT 64
PRINT "Mersenne Primes:"
FOR p% = 2 TO 23
IF FNlucas_lehmer(p%) PRINT "M" ; p%
NEXT
END
DEF FNlucas_lehmer(p%)
LOCAL i%, mp, sn
IF p% = 2 THEN = TRUE
IF (p% AND 1) = 0 THEN = FALSE
mp = 2^p% - 1
sn = 4
FOR i% = 3 TO p%
sn = sn^2 - 2
sn -= (mp * INT(sn / mp))
NEXT
= (sn = 0) |
http://rosettacode.org/wiki/Lucky_and_even_lucky_numbers | Lucky and even lucky numbers | Note that in the following explanation list indices are assumed to start at one.
Definition of lucky numbers
Lucky numbers are positive integers that are formed by:
Form a list of all the positive odd integers > 0
1
,
3
,
5
,
7
,
9
,
11
,
13
,
15
,
17
,
19
,
21
,
23
,
25
,
27
,
29
,
31
,
33
,
35
,
37
,
39...
{\displaystyle 1,3,5,7,9,11,13,15,17,19,21,23,25,27,29,31,33,35,37,39...}
Return the first number from the list (which is 1).
(Loop begins here)
Note then return the second number from the list (which is 3).
Discard every third, (as noted), number from the list to form the new list
1
,
3
,
7
,
9
,
13
,
15
,
19
,
21
,
25
,
27
,
31
,
33
,
37
,
39
,
43
,
45
,
49
,
51
,
55
,
57...
{\displaystyle 1,3,7,9,13,15,19,21,25,27,31,33,37,39,43,45,49,51,55,57...}
(Expanding the loop a few more times...)
Note then return the third number from the list (which is 7).
Discard every 7th, (as noted), number from the list to form the new list
1
,
3
,
7
,
9
,
13
,
15
,
21
,
25
,
27
,
31
,
33
,
37
,
43
,
45
,
49
,
51
,
55
,
57
,
63
,
67...
{\displaystyle 1,3,7,9,13,15,21,25,27,31,33,37,43,45,49,51,55,57,63,67...}
Note then return the 4th number from the list (which is 9).
Discard every 9th, (as noted), number from the list to form the new list
1
,
3
,
7
,
9
,
13
,
15
,
21
,
25
,
31
,
33
,
37
,
43
,
45
,
49
,
51
,
55
,
63
,
67
,
69
,
73...
{\displaystyle 1,3,7,9,13,15,21,25,31,33,37,43,45,49,51,55,63,67,69,73...}
Take the 5th, i.e. 13. Remove every 13th.
Take the 6th, i.e. 15. Remove every 15th.
Take the 7th, i.e. 21. Remove every 21th.
Take the 8th, i.e. 25. Remove every 25th.
(Rule for the loop)
Note the
n
{\displaystyle n}
th, which is
m
{\displaystyle m}
.
Remove every
m
{\displaystyle m}
th.
Increment
n
{\displaystyle n}
.
Definition of even lucky numbers
This follows the same rules as the definition of lucky numbers above except for the very first step:
Form a list of all the positive even integers > 0
2
,
4
,
6
,
8
,
10
,
12
,
14
,
16
,
18
,
20
,
22
,
24
,
26
,
28
,
30
,
32
,
34
,
36
,
38
,
40...
{\displaystyle 2,4,6,8,10,12,14,16,18,20,22,24,26,28,30,32,34,36,38,40...}
Return the first number from the list (which is 2).
(Loop begins here)
Note then return the second number from the list (which is 4).
Discard every 4th, (as noted), number from the list to form the new list
2
,
4
,
6
,
10
,
12
,
14
,
18
,
20
,
22
,
26
,
28
,
30
,
34
,
36
,
38
,
42
,
44
,
46
,
50
,
52...
{\displaystyle 2,4,6,10,12,14,18,20,22,26,28,30,34,36,38,42,44,46,50,52...}
(Expanding the loop a few more times...)
Note then return the third number from the list (which is 6).
Discard every 6th, (as noted), number from the list to form the new list
2
,
4
,
6
,
10
,
12
,
18
,
20
,
22
,
26
,
28
,
34
,
36
,
38
,
42
,
44
,
50
,
52
,
54
,
58
,
60...
{\displaystyle 2,4,6,10,12,18,20,22,26,28,34,36,38,42,44,50,52,54,58,60...}
Take the 4th, i.e. 10. Remove every 10th.
Take the 5th, i.e. 12. Remove every 12th.
(Rule for the loop)
Note the
n
{\displaystyle n}
th, which is
m
{\displaystyle m}
.
Remove every
m
{\displaystyle m}
th.
Increment
n
{\displaystyle n}
.
Task requirements
Write one or two subroutines (functions) to generate lucky numbers and even lucky numbers
Write a command-line interface to allow selection of which kind of numbers and which number(s). Since input is from the command line, tests should be made for the common errors:
missing arguments
too many arguments
number (or numbers) aren't legal
misspelled argument (lucky or evenLucky)
The command line handling should:
support mixed case handling of the (non-numeric) arguments
support printing a particular number
support printing a range of numbers by their index
support printing a range of numbers by their values
The resulting list of numbers should be printed on a single line.
The program should support the arguments:
what is displayed (on a single line)
argument(s) (optional verbiage is encouraged)
╔═══════════════════╦════════════════════════════════════════════════════╗
║ j ║ Jth lucky number ║
║ j , lucky ║ Jth lucky number ║
║ j , evenLucky ║ Jth even lucky number ║
║ ║ ║
║ j k ║ Jth through Kth (inclusive) lucky numbers ║
║ j k lucky ║ Jth through Kth (inclusive) lucky numbers ║
║ j k evenLucky ║ Jth through Kth (inclusive) even lucky numbers ║
║ ║ ║
║ j -k ║ all lucky numbers in the range j ──► |k| ║
║ j -k lucky ║ all lucky numbers in the range j ──► |k| ║
║ j -k evenLucky ║ all even lucky numbers in the range j ──► |k| ║
╚═══════════════════╩════════════════════════════════════════════════════╝
where |k| is the absolute value of k
Demonstrate the program by:
showing the first twenty lucky numbers
showing the first twenty even lucky numbers
showing all lucky numbers between 6,000 and 6,100 (inclusive)
showing all even lucky numbers in the same range as above
showing the 10,000th lucky number (extra credit)
showing the 10,000th even lucky number (extra credit)
See also
This task is related to the Sieve of Eratosthenes task.
OEIS Wiki Lucky numbers.
Sequence A000959 lucky numbers on The On-Line Encyclopedia of Integer Sequences.
Sequence A045954 even lucky numbers or ELN on The On-Line Encyclopedia of Integer Sequences.
Entry lucky numbers on The Eric Weisstein's World of Mathematics.
| #J | J | luckySeq=:3 :0
1 luckySeq y
:
len=.0
nth=.0
seq=.x+2*i.4*y
while. len~:#seq do.
len=. #seq
nth=. nth+1
seq=. nth exclude seq
end.
)
exclude=: ] #~ 1 - #@] $ -@{ {. 1:
lucky=:''
evenLucky=:0
program=:3 :0
range=: |y-.0
seq=. (1+0 e.y) luckySeq >./range
if. 0><./y do.
(#~ e.&(thru/range)) seq
else.
(<:thru/range) { seq
end.
)
thru=: <./ + i.@(+*)@-~ |
http://rosettacode.org/wiki/LZW_compression | LZW compression | The Lempel-Ziv-Welch (LZW) algorithm provides loss-less data compression.
You can read a complete description of it in the Wikipedia article on the subject. It was patented, but it entered the public domain in 2004.
| #C.2B.2B | C++ | #include <string>
#include <map>
// Compress a string to a list of output symbols.
// The result will be written to the output iterator
// starting at "result"; the final iterator is returned.
template <typename Iterator>
Iterator compress(const std::string &uncompressed, Iterator result) {
// Build the dictionary.
int dictSize = 256;
std::map<std::string,int> dictionary;
for (int i = 0; i < 256; i++)
dictionary[std::string(1, i)] = i;
std::string w;
for (std::string::const_iterator it = uncompressed.begin();
it != uncompressed.end(); ++it) {
char c = *it;
std::string wc = w + c;
if (dictionary.count(wc))
w = wc;
else {
*result++ = dictionary[w];
// Add wc to the dictionary.
dictionary[wc] = dictSize++;
w = std::string(1, c);
}
}
// Output the code for w.
if (!w.empty())
*result++ = dictionary[w];
return result;
}
// Decompress a list of output ks to a string.
// "begin" and "end" must form a valid range of ints
template <typename Iterator>
std::string decompress(Iterator begin, Iterator end) {
// Build the dictionary.
int dictSize = 256;
std::map<int,std::string> dictionary;
for (int i = 0; i < 256; i++)
dictionary[i] = std::string(1, i);
std::string w(1, *begin++);
std::string result = w;
std::string entry;
for ( ; begin != end; begin++) {
int k = *begin;
if (dictionary.count(k))
entry = dictionary[k];
else if (k == dictSize)
entry = w + w[0];
else
throw "Bad compressed k";
result += entry;
// Add w+entry[0] to the dictionary.
dictionary[dictSize++] = w + entry[0];
w = entry;
}
return result;
}
#include <iostream>
#include <iterator>
#include <vector>
int main() {
std::vector<int> compressed;
compress("TOBEORNOTTOBEORTOBEORNOT", std::back_inserter(compressed));
copy(compressed.begin(), compressed.end(), std::ostream_iterator<int>(std::cout, ", "));
std::cout << std::endl;
std::string decompressed = decompress(compressed.begin(), compressed.end());
std::cout << decompressed << std::endl;
return 0;
} |
http://rosettacode.org/wiki/LU_decomposition | LU decomposition | Every square matrix
A
{\displaystyle A}
can be decomposed into a product of a lower triangular matrix
L
{\displaystyle L}
and a upper triangular matrix
U
{\displaystyle U}
,
as described in LU decomposition.
A
=
L
U
{\displaystyle A=LU}
It is a modified form of Gaussian elimination.
While the Cholesky decomposition only works for symmetric,
positive definite matrices, the more general LU decomposition
works for any square matrix.
There are several algorithms for calculating L and U.
To derive Crout's algorithm for a 3x3 example,
we have to solve the following system:
A
=
(
a
11
a
12
a
13
a
21
a
22
a
23
a
31
a
32
a
33
)
=
(
l
11
0
0
l
21
l
22
0
l
31
l
32
l
33
)
(
u
11
u
12
u
13
0
u
22
u
23
0
0
u
33
)
=
L
U
{\displaystyle A={\begin{pmatrix}a_{11}&a_{12}&a_{13}\\a_{21}&a_{22}&a_{23}\\a_{31}&a_{32}&a_{33}\\\end{pmatrix}}={\begin{pmatrix}l_{11}&0&0\\l_{21}&l_{22}&0\\l_{31}&l_{32}&l_{33}\\\end{pmatrix}}{\begin{pmatrix}u_{11}&u_{12}&u_{13}\\0&u_{22}&u_{23}\\0&0&u_{33}\end{pmatrix}}=LU}
We now would have to solve 9 equations with 12 unknowns. To make the system uniquely solvable, usually the diagonal elements of
L
{\displaystyle L}
are set to 1
l
11
=
1
{\displaystyle l_{11}=1}
l
22
=
1
{\displaystyle l_{22}=1}
l
33
=
1
{\displaystyle l_{33}=1}
so we get a solvable system of 9 unknowns and 9 equations.
A
=
(
a
11
a
12
a
13
a
21
a
22
a
23
a
31
a
32
a
33
)
=
(
1
0
0
l
21
1
0
l
31
l
32
1
)
(
u
11
u
12
u
13
0
u
22
u
23
0
0
u
33
)
=
(
u
11
u
12
u
13
u
11
l
21
u
12
l
21
+
u
22
u
13
l
21
+
u
23
u
11
l
31
u
12
l
31
+
u
22
l
32
u
13
l
31
+
u
23
l
32
+
u
33
)
=
L
U
{\displaystyle A={\begin{pmatrix}a_{11}&a_{12}&a_{13}\\a_{21}&a_{22}&a_{23}\\a_{31}&a_{32}&a_{33}\\\end{pmatrix}}={\begin{pmatrix}1&0&0\\l_{21}&1&0\\l_{31}&l_{32}&1\\\end{pmatrix}}{\begin{pmatrix}u_{11}&u_{12}&u_{13}\\0&u_{22}&u_{23}\\0&0&u_{33}\end{pmatrix}}={\begin{pmatrix}u_{11}&u_{12}&u_{13}\\u_{11}l_{21}&u_{12}l_{21}+u_{22}&u_{13}l_{21}+u_{23}\\u_{11}l_{31}&u_{12}l_{31}+u_{22}l_{32}&u_{13}l_{31}+u_{23}l_{32}+u_{33}\end{pmatrix}}=LU}
Solving for the other
l
{\displaystyle l}
and
u
{\displaystyle u}
, we get the following equations:
u
11
=
a
11
{\displaystyle u_{11}=a_{11}}
u
12
=
a
12
{\displaystyle u_{12}=a_{12}}
u
13
=
a
13
{\displaystyle u_{13}=a_{13}}
u
22
=
a
22
−
u
12
l
21
{\displaystyle u_{22}=a_{22}-u_{12}l_{21}}
u
23
=
a
23
−
u
13
l
21
{\displaystyle u_{23}=a_{23}-u_{13}l_{21}}
u
33
=
a
33
−
(
u
13
l
31
+
u
23
l
32
)
{\displaystyle u_{33}=a_{33}-(u_{13}l_{31}+u_{23}l_{32})}
and for
l
{\displaystyle l}
:
l
21
=
1
u
11
a
21
{\displaystyle l_{21}={\frac {1}{u_{11}}}a_{21}}
l
31
=
1
u
11
a
31
{\displaystyle l_{31}={\frac {1}{u_{11}}}a_{31}}
l
32
=
1
u
22
(
a
32
−
u
12
l
31
)
{\displaystyle l_{32}={\frac {1}{u_{22}}}(a_{32}-u_{12}l_{31})}
We see that there is a calculation pattern, which can be expressed as the following formulas, first for
U
{\displaystyle U}
u
i
j
=
a
i
j
−
∑
k
=
1
i
−
1
u
k
j
l
i
k
{\displaystyle u_{ij}=a_{ij}-\sum _{k=1}^{i-1}u_{kj}l_{ik}}
and then for
L
{\displaystyle L}
l
i
j
=
1
u
j
j
(
a
i
j
−
∑
k
=
1
j
−
1
u
k
j
l
i
k
)
{\displaystyle l_{ij}={\frac {1}{u_{jj}}}(a_{ij}-\sum _{k=1}^{j-1}u_{kj}l_{ik})}
We see in the second formula that to get the
l
i
j
{\displaystyle l_{ij}}
below the diagonal, we have to divide by the diagonal element (pivot)
u
j
j
{\displaystyle u_{jj}}
, so we get problems when
u
j
j
{\displaystyle u_{jj}}
is either 0 or very small, which leads to numerical instability.
The solution to this problem is pivoting
A
{\displaystyle A}
, which means rearranging the rows of
A
{\displaystyle A}
, prior to the
L
U
{\displaystyle LU}
decomposition, in a way that the largest element of each column gets onto the diagonal of
A
{\displaystyle A}
. Rearranging the rows means to multiply
A
{\displaystyle A}
by a permutation matrix
P
{\displaystyle P}
:
P
A
⇒
A
′
{\displaystyle PA\Rightarrow A'}
Example:
(
0
1
1
0
)
(
1
4
2
3
)
⇒
(
2
3
1
4
)
{\displaystyle {\begin{pmatrix}0&1\\1&0\end{pmatrix}}{\begin{pmatrix}1&4\\2&3\end{pmatrix}}\Rightarrow {\begin{pmatrix}2&3\\1&4\end{pmatrix}}}
The decomposition algorithm is then applied on the rearranged matrix so that
P
A
=
L
U
{\displaystyle PA=LU}
Task description
The task is to implement a routine which will take a square nxn matrix
A
{\displaystyle A}
and return a lower triangular matrix
L
{\displaystyle L}
, a upper triangular matrix
U
{\displaystyle U}
and a permutation matrix
P
{\displaystyle P}
,
so that the above equation is fulfilled.
You should then test it on the following two examples and include your output.
Example 1
A
1 3 5
2 4 7
1 1 0
L
1.00000 0.00000 0.00000
0.50000 1.00000 0.00000
0.50000 -1.00000 1.00000
U
2.00000 4.00000 7.00000
0.00000 1.00000 1.50000
0.00000 0.00000 -2.00000
P
0 1 0
1 0 0
0 0 1
Example 2
A
11 9 24 2
1 5 2 6
3 17 18 1
2 5 7 1
L
1.00000 0.00000 0.00000 0.00000
0.27273 1.00000 0.00000 0.00000
0.09091 0.28750 1.00000 0.00000
0.18182 0.23125 0.00360 1.00000
U
11.00000 9.00000 24.00000 2.00000
0.00000 14.54545 11.45455 0.45455
0.00000 0.00000 -3.47500 5.68750
0.00000 0.00000 0.00000 0.51079
P
1 0 0 0
0 0 1 0
0 1 0 0
0 0 0 1
| #D | D | import std.stdio, std.algorithm, std.typecons, std.numeric,
std.array, std.conv, std.string, std.range;
bool isRectangular(T)(in T[][] m) pure nothrow @nogc {
return m.all!(r => r.length == m[0].length);
}
bool isSquare(T)(in T[][] m) pure nothrow @nogc {
return m.isRectangular && m[0].length == m.length;
}
T[][] matrixMul(T)(in T[][] A, in T[][] B) pure nothrow
in {
assert(A.isRectangular && B.isRectangular &&
!A.empty && !B.empty && A[0].length == B.length);
} body {
auto result = new T[][](A.length, B[0].length);
auto aux = new T[B.length];
foreach (immutable j; 0 .. B[0].length) {
foreach (immutable k, const row; B)
aux[k] = row[j];
foreach (immutable i, const ai; A)
result[i][j] = dotProduct(ai, aux);
}
return result;
}
/// Creates the pivoting matrix for m.
T[][] pivotize(T)(immutable T[][] m) pure nothrow
in {
assert(m.isSquare);
} body {
immutable n = m.length;
auto id = iota(n)
.map!((in j) => n.iota.map!(i => T(i == j)).array)
.array;
foreach (immutable i; 0 .. n) {
// immutable row = iota(i, n).reduce!(max!(j => m[j][i]));
T maxm = m[i][i];
size_t row = i;
foreach (immutable j; i .. n)
if (m[j][i] > maxm) {
maxm = m[j][i];
row = j;
}
if (i != row)
swap(id[i], id[row]);
}
return id;
}
/// Decomposes a square matrix A by PA=LU and returns L, U and P.
Tuple!(T[][],"L", T[][],"U", const T[][],"P")
lu(T)(immutable T[][] A) pure nothrow
in {
assert(A.isSquare);
} body {
immutable n = A.length;
auto L = new T[][](n, n);
auto U = new T[][](n, n);
foreach (immutable i; 0 .. n) {
L[i][i .. $] = 0;
U[i][0 .. i] = 0;
}
immutable P = A.pivotize!T;
immutable A2 = matrixMul!T(P, A);
foreach (immutable j; 0 .. n) {
L[j][j] = 1;
foreach (immutable i; 0 .. j+1) {
T s1 = 0;
foreach (immutable k; 0 .. i)
s1 += U[k][j] * L[i][k];
U[i][j] = A2[i][j] - s1;
}
foreach (immutable i; j .. n) {
T s2 = 0;
foreach (immutable k; 0 .. j)
s2 += U[k][j] * L[i][k];
L[i][j] = (A2[i][j] - s2) / U[j][j];
}
}
return typeof(return)(L, U, P);
}
void main() {
immutable a = [[1.0, 3, 5],
[2.0, 4, 7],
[1.0, 1, 0]];
immutable b = [[11.0, 9, 24, 2],
[1.0, 5, 2, 6],
[3.0, 17, 18, 1],
[2.0, 5, 7, 1]];
auto f = "[%([%(%.1f, %)],\n %)]]\n\n".replicate(3);
foreach (immutable m; [a, b])
writefln(f, lu(m).tupleof);
} |
http://rosettacode.org/wiki/Lychrel_numbers | Lychrel numbers | Take an integer n, greater than zero.
Form the next n of its series by reversing the digits of the current n and adding the result to the current n.
Stop when n becomes palindromic - i.e. the digits of n in reverse order == n.
The above recurrence relation when applied to most starting numbers n = 1, 2, ... terminates in a palindrome quite quickly.
Example
If n0 = 12 we get
12
12 + 21 = 33, a palindrome!
And if n0 = 55 we get
55
55 + 55 = 110
110 + 011 = 121, a palindrome!
Notice that the check for a palindrome happens after an addition.
Some starting numbers seem to go on forever; the recurrence relation for 196 has been calculated for millions of repetitions forming numbers with millions of digits, without forming a palindrome.
These numbers that do not end in a palindrome are called Lychrel numbers.
For the purposes of this task a Lychrel number is any starting number that does not form a palindrome within 500 (or more) iterations.
Seed and related Lychrel numbers
Any integer produced in the sequence of a Lychrel number is also a Lychrel number.
In general, any sequence from one Lychrel number might converge to join the sequence from a prior Lychrel number candidate; for example the sequences for the numbers 196 and then 689 begin:
196
196 + 691 = 887
887 + 788 = 1675
1675 + 5761 = 7436
7436 + 6347 = 13783
13783 + 38731 = 52514
52514 + 41525 = 94039
...
689
689 + 986 = 1675
1675 + 5761 = 7436
...
So we see that the sequence starting with 689 converges to, and continues with the same numbers as that for 196.
Because of this we can further split the Lychrel numbers into true Seed Lychrel number candidates, and Related numbers that produce no palindromes but have integers in their sequence seen as part of the sequence generated from a lower Lychrel number.
Task
Find the number of seed Lychrel number candidates and related numbers for n in the range 1..10000 inclusive. (With that iteration limit of 500).
Print the number of seed Lychrels found; the actual seed Lychrels; and just the number of relateds found.
Print any seed Lychrel or related number that is itself a palindrome.
Show all output here.
References
What's special about 196? Numberphile video.
A023108 Positive integers which apparently never result in a palindrome under repeated applications of the function f(x) = x + (x with digits reversed).
Status of the 196 conjecture? Mathoverflow.
| #Java | Java | import java.math.BigInteger;
import java.util.*;
public class Lychrel {
static Map<BigInteger, Tuple> cache = new HashMap<>();
static class Tuple {
final Boolean flag;
final BigInteger bi;
Tuple(boolean f, BigInteger b) {
flag = f;
bi = b;
}
}
static BigInteger rev(BigInteger bi) {
String s = new StringBuilder(bi.toString()).reverse().toString();
return new BigInteger(s);
}
static Tuple lychrel(BigInteger n) {
Tuple res;
if ((res = cache.get(n)) != null)
return res;
BigInteger r = rev(n);
res = new Tuple(true, n);
List<BigInteger> seen = new ArrayList<>();
for (int i = 0; i < 500; i++) {
n = n.add(r);
r = rev(n);
if (n.equals(r)) {
res = new Tuple(false, BigInteger.ZERO);
break;
}
if (cache.containsKey(n)) {
res = cache.get(n);
break;
}
seen.add(n);
}
for (BigInteger bi : seen)
cache.put(bi, res);
return res;
}
public static void main(String[] args) {
List<BigInteger> seeds = new ArrayList<>();
List<BigInteger> related = new ArrayList<>();
List<BigInteger> palin = new ArrayList<>();
for (int i = 1; i <= 10_000; i++) {
BigInteger n = BigInteger.valueOf(i);
Tuple t = lychrel(n);
if (!t.flag)
continue;
if (n.equals(t.bi))
seeds.add(t.bi);
else
related.add(t.bi);
if (n.equals(t.bi))
palin.add(t.bi);
}
System.out.printf("%d Lychrel seeds: %s%n", seeds.size(), seeds);
System.out.printf("%d Lychrel related%n", related.size());
System.out.printf("%d Lychrel palindromes: %s%n", palin.size(), palin);
}
} |
http://rosettacode.org/wiki/Magic_8-ball | Magic 8-ball | Task
Create Magic 8-Ball.
See details at: Magic 8-Ball.
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
| #Sather | Sather | class MAIN is
const answers: ARRAY{STR} :=
|
"It is certain.", "It is decidedly so.",
"Without a doubt.", "Yes - definitely.", "You may rely on it.",
"As I see it, yes.", "Most likely.", "Outlook good.",
"Yes.", "Signs point to yes.", "Reply hazy, try again.",
"Ask again later.", "Better not tell you now.", "Cannot predict now.",
"Concentrate and ask again.", "Don't count on it.", "My reply is no.",
"My sources say no.", "Outlook not so good.", "Very doubtful."
|;
main is
RND::seed := #TIMES.wall_time;
loop
#OUT+"Your question: "; #OUT.flush;
question ::= #IN.get_str;
#OUT+answers[RND::int(0, answers.size-1)] + "\n";
end;
end;
end; |
http://rosettacode.org/wiki/Magic_8-ball | Magic 8-ball | Task
Create Magic 8-Ball.
See details at: Magic 8-Ball.
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
| #Scala | Scala | import scala.util.Random
object Magic8Ball extends App {
val shake: () => String = {
val answers = List(
"It is certain.", "It is decidedly so.", "Without a doubt.",
"Yes – definitely.", "You may rely on it.", "As I see it, yes.",
"Most likely.", "Outlook good.", "Yes.", "Signs point to yes.",
"Reply hazy, try again.", "Ask again later", "Better not tell you now.",
"Cannot predict now.", "Concentrate and ask again.", "Don't count on it.",
"My reply is no.", "My sources say no.", "Outlook not so good.",
"Very doubtful."
)
val r = new Random
() => answers(r.nextInt(answers.length))
}
println("Ask the Magic 8-Ball your questions. ('q' or 'quit' to quit)\n")
while (true) {
io.StdIn.readLine("Question: ").toLowerCase match {
case "q" | "quit" =>
println("Goodbye.")
sys.exit()
case _ =>
println(s"Response: ${shake()}\n")
}
}
} |
http://rosettacode.org/wiki/Mandelbrot_set | Mandelbrot set | Mandelbrot set
You are encouraged to solve this task according to the task description, using any language you may know.
Task
Generate and draw the Mandelbrot set.
Note that there are many algorithms to draw Mandelbrot set and there are many functions which generate it .
| #XSLT | XSLT |
<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<!-- XSLT Mandelbrot - written by Joel Yliluoma 2007, http://iki.fi/bisqwit/ -->
<xsl:output method="html" indent="no"
doctype-public="-//W3C//DTD HTML 4.01//EN"
doctype-system="http://www.w3.org/TR/REC-html40/strict.dtd"
/>
<xsl:template match="/fractal">
<html>
<head>
<title>XSLT fractal</title>
<style type="text/css">
body { color:#55F; background:#000 }
pre { font-family:monospace; font-size:7px }
pre span { background:<xsl:value-of select="background" /> }
</style>
</head>
<body>
<div style="position:absolute;top:20px;left:20em">
Copyright © 1992,2007 Joel Yliluoma
(<a href="http://iki.fi/bisqwit/">http://iki.fi/bisqwit/</a>)
</div>
<h1 style="margin:0px">XSLT fractal</h1>
<pre><xsl:call-template name="bisqwit-mandelbrot" /></pre>
</body>
</html>
</xsl:template>
<xsl:template name="bisqwit-mandelbrot"
><xsl:call-template name="bisqwit-mandelbrot-line">
<xsl:with-param name="y" select="y/min"/>
</xsl:call-template
></xsl:template>
<xsl:template name="bisqwit-mandelbrot-line"
><xsl:param name="y"
/><xsl:call-template name="bisqwit-mandelbrot-column">
<xsl:with-param name="x" select="x/min"/>
<xsl:with-param name="y" select="$y"/>
</xsl:call-template
><xsl:if test="$y < y/max"
><br
/><xsl:call-template name="bisqwit-mandelbrot-line">
<xsl:with-param name="y" select="$y + y/step"/>
</xsl:call-template
></xsl:if
></xsl:template>
<xsl:template name="bisqwit-mandelbrot-column"
><xsl:param name="x"
/><xsl:param name="y"
/><xsl:call-template name="bisqwit-mandelbrot-slot">
<xsl:with-param name="x" select="$x" />
<xsl:with-param name="y" select="$y" />
<xsl:with-param name="zr" select="$x" />
<xsl:with-param name="zi" select="$y" />
</xsl:call-template
><xsl:if test="$x < x/max"
><xsl:call-template name="bisqwit-mandelbrot-column">
<xsl:with-param name="x" select="$x + x/step"/>
<xsl:with-param name="y" select="$y" />
</xsl:call-template
></xsl:if
></xsl:template>
<xsl:template name="bisqwit-mandelbrot-slot"
><xsl:param name="x"
/><xsl:param name="y"
/><xsl:param name="zr"
/><xsl:param name="zi"
/><xsl:param name="iter" select="0"
/><xsl:variable name="zrsqr" select="($zr * $zr)"
/><xsl:variable name="zisqr" select="($zi * $zi)"
/><xsl:choose>
<xsl:when test="(4*scale*scale >= $zrsqr + $zisqr) and (maxiter > $iter+1)"
><xsl:call-template name="bisqwit-mandelbrot-slot">
<xsl:with-param name="x" select="$x" />
<xsl:with-param name="y" select="$y" />
<xsl:with-param name="zi" select="(2 * $zr * $zi) div scale + $y" />
<xsl:with-param name="zr" select="($zrsqr - $zisqr) div scale + $x" />
<xsl:with-param name="iter" select="$iter + 1" />
</xsl:call-template
></xsl:when>
<xsl:otherwise
><xsl:variable name="magnitude" select="magnitude[@value=$iter]"
/><span style="color:{$magnitude/color}"
><xsl:value-of select="$magnitude/symbol"
/></span></xsl:otherwise>
</xsl:choose
></xsl:template>
</xsl:stylesheet>
|
http://rosettacode.org/wiki/Mad_Libs | Mad Libs |
This page uses content from Wikipedia. The original article was at Mad Libs. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance)
Mad Libs is a phrasal template word game where one player prompts another for a list of words to substitute for blanks in a story, usually with funny results.
Task;
Write a program to create a Mad Libs like story.
The program should read an arbitrary multiline story from input.
The story will be terminated with a blank line.
Then, find each replacement to be made within the story, ask the user for a word to replace it with, and make all the replacements.
Stop when there are none left and print the final story.
The input should be an arbitrary story in the form:
<name> went for a walk in the park. <he or she>
found a <noun>. <name> decided to take it home.
Given this example, it should then ask for a name, a he or she and a noun (<name> gets replaced both times with the same value).
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
| #FreeBASIC | FreeBASIC |
Dim As String con, cadena
cadena = "<name> went for a walk in the park. <he or she> found a <noun>. <name> decided to take it home."
Dim As Integer k = Instr(cadena, "<")
Print "La historia: "
Print cadena & Chr(10)
While k
Dim As String reemplaza = Mid(cadena, k, Instr(cadena, ">") - k + 1)
Print "What should replace "; reemplaza; : Input con
While k
cadena = Left(cadena, k-1) & con & Mid(cadena, k + Len(reemplaza))
k = Instr(k, cadena, reemplaza)
Wend
k = Instr(cadena, "<")
Wend
Print Chr(10) & "La historia final: "
Print cadena & Chr(10)
|
http://rosettacode.org/wiki/Loops/With_multiple_ranges | Loops/With multiple ranges | Loops/With multiple ranges
You are encouraged to solve this task according to the task description, using any language you may know.
Some languages allow multiple loop ranges, such as the PL/I example (snippet) below.
/* all variables are DECLARED as integers. */
prod= 1; /*start with a product of unity. */
sum= 0; /* " " " sum " zero. */
x= +5;
y= -5;
z= -2;
one= 1;
three= 3;
seven= 7;
/*(below) ** is exponentiation: 4**3=64 */
do j= -three to 3**3 by three ,
-seven to +seven by x ,
555 to 550 - y ,
22 to -28 by -three ,
1927 to 1939 ,
x to y by z ,
11**x to 11**x + one;
/* ABS(n) = absolute value*/
sum= sum + abs(j); /*add absolute value of J.*/
if abs(prod)<2**27 & j¬=0 then prod=prod*j; /*PROD is small enough & J*/
end; /*not 0, then multiply it.*/
/*SUM and PROD are used for verification of J incrementation.*/
display (' sum= ' || sum); /*display strings to term.*/
display ('prod= ' || prod); /* " " " " */
Task
Simulate/translate the above PL/I program snippet as best as possible in your
language, with particular emphasis on the do loop construct.
The do index must be incremented/decremented in the same order shown.
If feasible, add commas to the two output numbers (being displayed).
Show all output here.
A simple PL/I DO loop (incrementing or decrementing) has the construct of:
DO variable = start_expression {TO ending_expression] {BY increment_expression} ;
---or---
DO variable = start_expression {BY increment_expression} {TO ending_expression] ;
where it is understood that all expressions will have a value. The variable is normally a
scaler variable, but need not be (but for this task, all variables and expressions are declared
to be scaler integers). If the BY expression is omitted, a BY value of unity is used.
All expressions are evaluated before the DO loop is executed, and those values are used
throughout the DO loop execution (even though, for instance, the value of Z may be
changed within the DO loop. This isn't the case here for this task.
A multiple-range DO loop can be constructed by using a comma (,) to separate additional ranges
(the use of multiple TO and/or BY keywords). This is the construct used in this task.
There are other forms of DO loops in PL/I involving the WHILE clause, but those won't be
needed here. DO loops without a TO clause might need a WHILE clause or some other
means of exiting the loop (such as LEAVE, RETURN, SIGNAL, GOTO, or STOP), or some other
(possible error) condition that causes transfer of control outside the DO loop.
Also, in PL/I, the check if the DO loop index value is outside the range is made at the
"head" (start) of the DO loop, so it's possible that the DO loop isn't executed, but
that isn't the case for any of the ranges used in this task.
In the example above, the clause: x to y by z
will cause the variable J to have to following values (in this order): 5 3 1 -1 -3 -5
In the example above, the clause: -seven to +seven by x
will cause the variable J to have to following values (in this order): -7 -2 3
Related tasks
Loop over multiple arrays simultaneously
Loops/Break
Loops/Continue
Loops/Do-while
Loops/Downward for
Loops/For
Loops/For with a specified step
Loops/Foreach
Loops/Increment loop index within loop body
Loops/Infinite
Loops/N plus one half
Loops/Nested
Loops/While
Loops/with multiple ranges
Loops/Wrong ranges
| #ALGOL_W | ALGOL W | begin
% translation of task PL/1 code, with minimal changes, semicolons required by %
% PL/1 but redundant in Algol W retained ( technically they introduce empty %
% statements after the "if" in the loop body and before the final "end" ) %
% Note that in Algol W, the loop counter is a local variable to the loop and %
% the value of j is not available outside the loops %
procedure loopBody ( integer value j ); %(below) ** is exponentiation: 4**3=64 %
begin sum := sum + abs(j); %add absolute value of J.%
if abs(prod)<2**27 and j not = 0 then prod := prod*j; %PROD is small enough & J%
% ABS(n) = absolute value%
end; %not 0, then multiply it.%
%SUM and PROD are used for verification of J incrementation.%
integer prod, sum, x, y, z, one, three, seven;
prod := 1; %start with a product of unity. %
sum := 0; % " " " sum " zero. %
x := +5;
y := -5;
z := -2;
one := 1;
three := 3;
seven := 7;
for j := -three step three until round( 3**3 ) do loopBody( j );
for j := -seven step x until +seven do loopBody( j );
for j := 555 until 550 - y do loopBody( j );
for j := 22 step -three until -28 do loopBody( j );
for j := 1927 until 1939 do loopBody( j );
for j := x step z until y do loopBody( j );
for j := round( 11**x ) until round( 11**x ) + one do loopBody( j );
write(s_w := 0, " sum= ", sum); %display strings to term.%
write(s_w := 0, "prod= ", prod); % " " " " %
end. |
http://rosettacode.org/wiki/Ludic_numbers | Ludic numbers | Ludic numbers are related to prime numbers as they are generated by a sieve quite like the Sieve of Eratosthenes is used to generate prime numbers.
The first ludic number is 1.
To generate succeeding ludic numbers create an array of increasing integers starting from 2.
2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 ...
(Loop)
Take the first member of the resultant array as the next ludic number 2.
Remove every 2nd indexed item from the array (including the first).
2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 ...
(Unrolling a few loops...)
Take the first member of the resultant array as the next ludic number 3.
Remove every 3rd indexed item from the array (including the first).
3 5 7 9 11 13 15 17 19 21 23 25 27 29 31 33 35 37 39 41 43 45 47 49 51 ...
Take the first member of the resultant array as the next ludic number 5.
Remove every 5th indexed item from the array (including the first).
5 7 11 13 17 19 23 25 29 31 35 37 41 43 47 49 53 55 59 61 65 67 71 73 77 ...
Take the first member of the resultant array as the next ludic number 7.
Remove every 7th indexed item from the array (including the first).
7 11 13 17 23 25 29 31 37 41 43 47 53 55 59 61 67 71 73 77 83 85 89 91 97 ...
...
Take the first member of the current array as the next ludic number L.
Remove every Lth indexed item from the array (including the first).
...
Task
Generate and show here the first 25 ludic numbers.
How many ludic numbers are there less than or equal to 1000?
Show the 2000..2005th ludic numbers.
Stretch goal
Show all triplets of ludic numbers < 250.
A triplet is any three numbers
x
,
{\displaystyle x,}
x
+
2
,
{\displaystyle x+2,}
x
+
6
{\displaystyle x+6}
where all three numbers are also ludic numbers.
| #Icon_and_Unicon | Icon and Unicon | global num, cascade, sieve, nfilter
procedure main(A)
lds := ludic(2005) # All we need for the four tasks.
every writes("First 25:" | (" "||!lds)\25 | "\n")
every (n := 0) +:= (!lds < 1000, 1)
write("There are ",n," Ludic numbers < 1000.")
every writes("2000th through 2005th: " | (lds[2000 to 20005]||" ") | "\n")
writes("Triplets:")
every (250 > (x := !lds)) & (250 > (x+2 = !lds)) & (250 > (x+6 = !lds)) do
writes(" [",x,",",x+2,",",x+6,"]")
write()
end
procedure ludic(limit)
candidates := create seq(2)
put(cascade := [], create {
repeat {
report(l := num, limit)
put(cascade, create (cnt:=0, repeat ((cnt+:=1)%l=0, @sieve) | @@nfilter))
cascade[-2] :=: cascade[-1] # keep this sink as the last filter
@sieve
}
})
sieve := create while num := @candidates do @@(nfilter := create !cascade)
report(1, limit)
return @sieve
end
procedure report(ludic, limit)
static count, lds
initial {count := 0; lds := []}
if (count +:= 1) > limit then lds@&main
put(lds, ludic)
end |
http://rosettacode.org/wiki/Loops/Wrong_ranges | Loops/Wrong ranges | Loops/Wrong ranges
You are encouraged to solve this task according to the task description, using any language you may know.
Some languages have syntax or function(s) to generate a range of numeric values from a start value, a stop value, and an increment.
The purpose of this task is to select the range syntax/function that would generate at least two increasing numbers when given a stop value more than the start value and a positive increment of less than half the difference. You are then to use that same syntax/function but with different parameters; and show, here, what would happen.
Use these values if possible:
start
stop
increment
Comment
-2
2
1
Normal
-2
2
0
Zero increment
-2
2
-1
Increments away from stop value
-2
2
10
First increment is beyond stop value
2
-2
1
Start more than stop: positive increment
2
2
1
Start equal stop: positive increment
2
2
-1
Start equal stop: negative increment
2
2
0
Start equal stop: zero increment
0
0
0
Start equal stop equal zero: zero increment
Related tasks
Loop over multiple arrays simultaneously
Loops/Break
Loops/Continue
Loops/Do-while
Loops/Downward for
Loops/For
Loops/For with a specified step
Loops/Foreach
Loops/Increment loop index within loop body
Loops/Infinite
Loops/N plus one half
Loops/Nested
Loops/While
Loops/with multiple ranges
Loops/Wrong ranges
| #C.23 | C# | using System;
using System.Collections.Generic;
static class Program
{
static void Main()
{
Example(-2, 2, 1, "Normal");
Example(-2, 2, 0, "Zero increment");
Example(-2, 2, -1, "Increments away from stop value");
Example(-2, 2, 10, "First increment is beyond stop value");
Example(2, -2, 1, "Start more than stop: positive increment");
Example(2, 2, 1, "Start equal stop: positive increment");
Example(2, 2, -1, "Start equal stop: negative increment");
Example(2, 2, 0, "Start equal stop: zero increment");
Example(0, 0, 0, "Start equal stop equal zero: zero increment");
}
static IEnumerable<int> Range(int start, int stop, int increment)
{
// To replicate the (arguably more correct) behavior of VB.NET:
//for (int i = start; increment >= 0 ? i <= stop : stop <= i; i += increment)
// Decompiling the IL emitted by the VB compiler (uses shifting right by 31 as the signum function and bitwise xor in place of the conditional expression):
//for (int i = start; ((increment >> 31) ^ i) <= ((increment >> 31) ^ stop); i += increment)
// "Naïve" translation.
for (int i = start; i <= stop; i += increment)
yield return i;
}
static void Example(int start, int stop, int increment, string comment)
{
// Add a space, pad to length 50 with hyphens, and add another space.
Console.Write((comment + " ").PadRight(50, '-') + " ");
const int MAX_ITER = 9;
int iteration = 0;
foreach (int i in Range(start, stop, increment))
{
Console.Write("{0,2} ", i);
if (++iteration > MAX_ITER) break;
}
Console.WriteLine();
}
} |
http://rosettacode.org/wiki/Luhn_test_of_credit_card_numbers | Luhn test of credit card numbers | The Luhn test is used by some credit card companies to distinguish valid credit card numbers from what could be a random selection of digits.
Those companies using credit card numbers that can be validated by the Luhn test have numbers that pass the following test:
Reverse the order of the digits in the number.
Take the first, third, ... and every other odd digit in the reversed digits and sum them to form the partial sum s1
Taking the second, fourth ... and every other even digit in the reversed digits:
Multiply each digit by two and sum the digits if the answer is greater than nine to form partial sums for the even digits
Sum the partial sums of the even digits to form s2
If s1 + s2 ends in zero then the original number is in the form of a valid credit card number as verified by the Luhn test.
For example, if the trial number is 49927398716:
Reverse the digits:
61789372994
Sum the odd digits:
6 + 7 + 9 + 7 + 9 + 4 = 42 = s1
The even digits:
1, 8, 3, 2, 9
Two times each even digit:
2, 16, 6, 4, 18
Sum the digits of each multiplication:
2, 7, 6, 4, 9
Sum the last:
2 + 7 + 6 + 4 + 9 = 28 = s2
s1 + s2 = 70 which ends in zero which means that 49927398716 passes the Luhn test
Task
Write a function/method/procedure/subroutine that will validate a number with the Luhn test, and
use it to validate the following numbers:
49927398716
49927398717
1234567812345678
1234567812345670
Related tasks
SEDOL
ISIN
| #Action.21 | Action! | PROC ReverseDigits(CHAR ARRAY n,rev)
BYTE i,j
i=n(0)
WHILE i>0 AND n(i)='0
DO
i==-1
OD
j=1
WHILE i>0
DO
rev(j)=n(i)
j==+1 i==-1
OD
rev(0)=j-1
RETURN
BYTE FUNC SumOddDigits(CHAR ARRAY n)
BYTE sum,i
sum=0
FOR i=1 TO n(0) STEP 2
DO
sum==+ValB(n(i))
OD
RETURN(sum)
BYTE FUNC SumEvenDigitsMultiplied(CHAR ARRAY n)
BYTE sum,i,v
sum=0
FOR i=2 TO n(0) STEP 2
DO
v=ValB(n(i))*2
IF v>9 THEN v==-9 FI
sum==+v
OD
RETURN(sum)
BYTE FUNC Luhn(CHAR ARRAY n)
CHAR ARRAY rev(20)
BYTE s1,s2
ReverseDigits(n,rev)
s1=SumOddDigits(rev)
s2=SumEvenDigitsMultiplied(rev)
IF (s1+s2) MOD 10=0 THEN
RETURN(1)
FI
RETURN(0)
PROC Test(CHAR ARRAY n)
PrintF("%S is ",n)
IF Luhn(n) THEN
PrintE("valid")
ELSE
PrintE("invalid")
FI
RETURN
PROC Main()
Test("49927398716")
Test("49927398717")
Test("1234567812345678")
Test("1234567812345670")
RETURN |
http://rosettacode.org/wiki/Lucas-Lehmer_test | Lucas-Lehmer test | Lucas-Lehmer Test:
for
p
{\displaystyle p}
an odd prime, the Mersenne number
2
p
−
1
{\displaystyle 2^{p}-1}
is prime if and only if
2
p
−
1
{\displaystyle 2^{p}-1}
divides
S
(
p
−
1
)
{\displaystyle S(p-1)}
where
S
(
n
+
1
)
=
(
S
(
n
)
)
2
−
2
{\displaystyle S(n+1)=(S(n))^{2}-2}
, and
S
(
1
)
=
4
{\displaystyle S(1)=4}
.
Task
Calculate all Mersenne primes up to the implementation's
maximum precision, or the 47th Mersenne prime (whichever comes first).
| #BCPL | BCPL |
GET "libhdr"
LET M(n) = (1 << n) - 1
LET isMersennePrime(p) =
p < 3 -> p = 2,
VALOF {
LET n = M(p)
LET s = 4
FOR i = 1 TO p-2 DO {
muldiv(s, s, n) // ignore quotient; remainder is in result2
s := result2 - 2
s := s + (n & s < 0)
}
RESULTIS s = 0
}
LET start() = VALOF {
LET primes = #x28208A20A08A28AC // bitmask of primes upto 63
writes("These Mersenne numbers are prime: ")
FOR k = 0 TO 63 DO
IF (primes & 1 << k) ~= 0 & isMersennePrime(k) THEN
writef("M%d ", k)
wrch('*n')
RESULTIS 0
}
|
http://rosettacode.org/wiki/Lucky_and_even_lucky_numbers | Lucky and even lucky numbers | Note that in the following explanation list indices are assumed to start at one.
Definition of lucky numbers
Lucky numbers are positive integers that are formed by:
Form a list of all the positive odd integers > 0
1
,
3
,
5
,
7
,
9
,
11
,
13
,
15
,
17
,
19
,
21
,
23
,
25
,
27
,
29
,
31
,
33
,
35
,
37
,
39...
{\displaystyle 1,3,5,7,9,11,13,15,17,19,21,23,25,27,29,31,33,35,37,39...}
Return the first number from the list (which is 1).
(Loop begins here)
Note then return the second number from the list (which is 3).
Discard every third, (as noted), number from the list to form the new list
1
,
3
,
7
,
9
,
13
,
15
,
19
,
21
,
25
,
27
,
31
,
33
,
37
,
39
,
43
,
45
,
49
,
51
,
55
,
57...
{\displaystyle 1,3,7,9,13,15,19,21,25,27,31,33,37,39,43,45,49,51,55,57...}
(Expanding the loop a few more times...)
Note then return the third number from the list (which is 7).
Discard every 7th, (as noted), number from the list to form the new list
1
,
3
,
7
,
9
,
13
,
15
,
21
,
25
,
27
,
31
,
33
,
37
,
43
,
45
,
49
,
51
,
55
,
57
,
63
,
67...
{\displaystyle 1,3,7,9,13,15,21,25,27,31,33,37,43,45,49,51,55,57,63,67...}
Note then return the 4th number from the list (which is 9).
Discard every 9th, (as noted), number from the list to form the new list
1
,
3
,
7
,
9
,
13
,
15
,
21
,
25
,
31
,
33
,
37
,
43
,
45
,
49
,
51
,
55
,
63
,
67
,
69
,
73...
{\displaystyle 1,3,7,9,13,15,21,25,31,33,37,43,45,49,51,55,63,67,69,73...}
Take the 5th, i.e. 13. Remove every 13th.
Take the 6th, i.e. 15. Remove every 15th.
Take the 7th, i.e. 21. Remove every 21th.
Take the 8th, i.e. 25. Remove every 25th.
(Rule for the loop)
Note the
n
{\displaystyle n}
th, which is
m
{\displaystyle m}
.
Remove every
m
{\displaystyle m}
th.
Increment
n
{\displaystyle n}
.
Definition of even lucky numbers
This follows the same rules as the definition of lucky numbers above except for the very first step:
Form a list of all the positive even integers > 0
2
,
4
,
6
,
8
,
10
,
12
,
14
,
16
,
18
,
20
,
22
,
24
,
26
,
28
,
30
,
32
,
34
,
36
,
38
,
40...
{\displaystyle 2,4,6,8,10,12,14,16,18,20,22,24,26,28,30,32,34,36,38,40...}
Return the first number from the list (which is 2).
(Loop begins here)
Note then return the second number from the list (which is 4).
Discard every 4th, (as noted), number from the list to form the new list
2
,
4
,
6
,
10
,
12
,
14
,
18
,
20
,
22
,
26
,
28
,
30
,
34
,
36
,
38
,
42
,
44
,
46
,
50
,
52...
{\displaystyle 2,4,6,10,12,14,18,20,22,26,28,30,34,36,38,42,44,46,50,52...}
(Expanding the loop a few more times...)
Note then return the third number from the list (which is 6).
Discard every 6th, (as noted), number from the list to form the new list
2
,
4
,
6
,
10
,
12
,
18
,
20
,
22
,
26
,
28
,
34
,
36
,
38
,
42
,
44
,
50
,
52
,
54
,
58
,
60...
{\displaystyle 2,4,6,10,12,18,20,22,26,28,34,36,38,42,44,50,52,54,58,60...}
Take the 4th, i.e. 10. Remove every 10th.
Take the 5th, i.e. 12. Remove every 12th.
(Rule for the loop)
Note the
n
{\displaystyle n}
th, which is
m
{\displaystyle m}
.
Remove every
m
{\displaystyle m}
th.
Increment
n
{\displaystyle n}
.
Task requirements
Write one or two subroutines (functions) to generate lucky numbers and even lucky numbers
Write a command-line interface to allow selection of which kind of numbers and which number(s). Since input is from the command line, tests should be made for the common errors:
missing arguments
too many arguments
number (or numbers) aren't legal
misspelled argument (lucky or evenLucky)
The command line handling should:
support mixed case handling of the (non-numeric) arguments
support printing a particular number
support printing a range of numbers by their index
support printing a range of numbers by their values
The resulting list of numbers should be printed on a single line.
The program should support the arguments:
what is displayed (on a single line)
argument(s) (optional verbiage is encouraged)
╔═══════════════════╦════════════════════════════════════════════════════╗
║ j ║ Jth lucky number ║
║ j , lucky ║ Jth lucky number ║
║ j , evenLucky ║ Jth even lucky number ║
║ ║ ║
║ j k ║ Jth through Kth (inclusive) lucky numbers ║
║ j k lucky ║ Jth through Kth (inclusive) lucky numbers ║
║ j k evenLucky ║ Jth through Kth (inclusive) even lucky numbers ║
║ ║ ║
║ j -k ║ all lucky numbers in the range j ──► |k| ║
║ j -k lucky ║ all lucky numbers in the range j ──► |k| ║
║ j -k evenLucky ║ all even lucky numbers in the range j ──► |k| ║
╚═══════════════════╩════════════════════════════════════════════════════╝
where |k| is the absolute value of k
Demonstrate the program by:
showing the first twenty lucky numbers
showing the first twenty even lucky numbers
showing all lucky numbers between 6,000 and 6,100 (inclusive)
showing all even lucky numbers in the same range as above
showing the 10,000th lucky number (extra credit)
showing the 10,000th even lucky number (extra credit)
See also
This task is related to the Sieve of Eratosthenes task.
OEIS Wiki Lucky numbers.
Sequence A000959 lucky numbers on The On-Line Encyclopedia of Integer Sequences.
Sequence A045954 even lucky numbers or ELN on The On-Line Encyclopedia of Integer Sequences.
Entry lucky numbers on The Eric Weisstein's World of Mathematics.
| #Java | Java |
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
public class LuckyNumbers {
private static int MAX = 200000;
private static List<Integer> luckyEven = luckyNumbers(MAX, true);
private static List<Integer> luckyOdd = luckyNumbers(MAX, false);
public static void main(String[] args) {
// Case 1 and 2
if ( args.length == 1 || ( args.length == 2 && args[1].compareTo("lucky") == 0 ) ) {
int n = Integer.parseInt(args[0]);
System.out.printf("LuckyNumber(%d) = %d%n", n, luckyOdd.get(n-1));
}
// Case 3
else if ( args.length == 2 && args[1].compareTo("evenLucky") == 0 ) {
int n = Integer.parseInt(args[0]);
System.out.printf("EvenLuckyNumber(%d) = %d%n", n, luckyEven.get(n-1));
}
// Case 4 through 9
else if ( args.length == 2 || args.length == 3 ) {
int j = Integer.parseInt(args[0]);
int k = Integer.parseInt(args[1]);
// Case 4 and 5
if ( ( args.length == 2 && k > 0 ) || (args.length == 3 && k > 0 && args[2].compareTo("lucky") == 0 ) ) {
System.out.printf("LuckyNumber(%d) through LuckyNumber(%d) = %s%n", j, k, luckyOdd.subList(j-1, k));
}
// Case 6
else if ( args.length == 3 && k > 0 && args[2].compareTo("evenLucky") == 0 ) {
System.out.printf("EvenLuckyNumber(%d) through EvenLuckyNumber(%d) = %s%n", j, k, luckyEven.subList(j-1, k));
}
// Case 7 and 8
else if ( ( args.length == 2 && k < 0 ) || (args.length == 3 && k < 0 && args[2].compareTo("lucky") == 0 ) ) {
int n = Collections.binarySearch(luckyOdd, j);
int m = Collections.binarySearch(luckyOdd, -k);
System.out.printf("Lucky Numbers in the range %d to %d inclusive = %s%n", j, -k, luckyOdd.subList(n < 0 ? -n-1 : n, m < 0 ? -m-1 : m+1));
}
// Case 9
else if ( args.length == 3 && k < 0 && args[2].compareTo("evenLucky") == 0 ) {
int n = Collections.binarySearch(luckyEven, j);
int m = Collections.binarySearch(luckyEven, -k);
System.out.printf("Even Lucky Numbers in the range %d to %d inclusive = %s%n", j, -k, luckyEven.subList(n < 0 ? -n-1 : n, m < 0 ? -m-1 : m+1));
}
}
}
private static List<Integer> luckyNumbers(int max, boolean even) {
List<Integer> luckyList = new ArrayList<>();
for ( int i = even ? 2 : 1 ; i <= max ; i += 2 ) {
luckyList.add(i);
}
int start = 1;
boolean removed = true;
while ( removed ) {
removed = false;
int increment = luckyList.get(start);
List<Integer> remove = new ArrayList<>();
for ( int i = increment-1 ; i < luckyList.size() ; i += increment ) {
remove.add(0, i);
removed = true;
}
for ( int i : remove ) {
luckyList.remove(i);
}
start++;
}
return luckyList;
}
}
|
http://rosettacode.org/wiki/LZW_compression | LZW compression | The Lempel-Ziv-Welch (LZW) algorithm provides loss-less data compression.
You can read a complete description of it in the Wikipedia article on the subject. It was patented, but it entered the public domain in 2004.
| #Clojure | Clojure | (defn make-dict []
(let [vals (range 0 256)]
(zipmap (map (comp #'list #'char) vals) vals)))
(defn compress [#^String text]
(loop [t (seq text)
r '()
w '()
dict (make-dict)
s 256]
(let [c (first t)]
(if c
(let [wc (cons c w)]
(if (get dict wc)
(recur (rest t) r wc dict s)
(recur (rest t) (cons (get dict w) r) (list c) (assoc dict wc s) (inc s))))
(reverse (if w (cons (get dict w) r) r))))))
(compress "TOBEORNOTTOBEORTOBEORNOT") |
http://rosettacode.org/wiki/LU_decomposition | LU decomposition | Every square matrix
A
{\displaystyle A}
can be decomposed into a product of a lower triangular matrix
L
{\displaystyle L}
and a upper triangular matrix
U
{\displaystyle U}
,
as described in LU decomposition.
A
=
L
U
{\displaystyle A=LU}
It is a modified form of Gaussian elimination.
While the Cholesky decomposition only works for symmetric,
positive definite matrices, the more general LU decomposition
works for any square matrix.
There are several algorithms for calculating L and U.
To derive Crout's algorithm for a 3x3 example,
we have to solve the following system:
A
=
(
a
11
a
12
a
13
a
21
a
22
a
23
a
31
a
32
a
33
)
=
(
l
11
0
0
l
21
l
22
0
l
31
l
32
l
33
)
(
u
11
u
12
u
13
0
u
22
u
23
0
0
u
33
)
=
L
U
{\displaystyle A={\begin{pmatrix}a_{11}&a_{12}&a_{13}\\a_{21}&a_{22}&a_{23}\\a_{31}&a_{32}&a_{33}\\\end{pmatrix}}={\begin{pmatrix}l_{11}&0&0\\l_{21}&l_{22}&0\\l_{31}&l_{32}&l_{33}\\\end{pmatrix}}{\begin{pmatrix}u_{11}&u_{12}&u_{13}\\0&u_{22}&u_{23}\\0&0&u_{33}\end{pmatrix}}=LU}
We now would have to solve 9 equations with 12 unknowns. To make the system uniquely solvable, usually the diagonal elements of
L
{\displaystyle L}
are set to 1
l
11
=
1
{\displaystyle l_{11}=1}
l
22
=
1
{\displaystyle l_{22}=1}
l
33
=
1
{\displaystyle l_{33}=1}
so we get a solvable system of 9 unknowns and 9 equations.
A
=
(
a
11
a
12
a
13
a
21
a
22
a
23
a
31
a
32
a
33
)
=
(
1
0
0
l
21
1
0
l
31
l
32
1
)
(
u
11
u
12
u
13
0
u
22
u
23
0
0
u
33
)
=
(
u
11
u
12
u
13
u
11
l
21
u
12
l
21
+
u
22
u
13
l
21
+
u
23
u
11
l
31
u
12
l
31
+
u
22
l
32
u
13
l
31
+
u
23
l
32
+
u
33
)
=
L
U
{\displaystyle A={\begin{pmatrix}a_{11}&a_{12}&a_{13}\\a_{21}&a_{22}&a_{23}\\a_{31}&a_{32}&a_{33}\\\end{pmatrix}}={\begin{pmatrix}1&0&0\\l_{21}&1&0\\l_{31}&l_{32}&1\\\end{pmatrix}}{\begin{pmatrix}u_{11}&u_{12}&u_{13}\\0&u_{22}&u_{23}\\0&0&u_{33}\end{pmatrix}}={\begin{pmatrix}u_{11}&u_{12}&u_{13}\\u_{11}l_{21}&u_{12}l_{21}+u_{22}&u_{13}l_{21}+u_{23}\\u_{11}l_{31}&u_{12}l_{31}+u_{22}l_{32}&u_{13}l_{31}+u_{23}l_{32}+u_{33}\end{pmatrix}}=LU}
Solving for the other
l
{\displaystyle l}
and
u
{\displaystyle u}
, we get the following equations:
u
11
=
a
11
{\displaystyle u_{11}=a_{11}}
u
12
=
a
12
{\displaystyle u_{12}=a_{12}}
u
13
=
a
13
{\displaystyle u_{13}=a_{13}}
u
22
=
a
22
−
u
12
l
21
{\displaystyle u_{22}=a_{22}-u_{12}l_{21}}
u
23
=
a
23
−
u
13
l
21
{\displaystyle u_{23}=a_{23}-u_{13}l_{21}}
u
33
=
a
33
−
(
u
13
l
31
+
u
23
l
32
)
{\displaystyle u_{33}=a_{33}-(u_{13}l_{31}+u_{23}l_{32})}
and for
l
{\displaystyle l}
:
l
21
=
1
u
11
a
21
{\displaystyle l_{21}={\frac {1}{u_{11}}}a_{21}}
l
31
=
1
u
11
a
31
{\displaystyle l_{31}={\frac {1}{u_{11}}}a_{31}}
l
32
=
1
u
22
(
a
32
−
u
12
l
31
)
{\displaystyle l_{32}={\frac {1}{u_{22}}}(a_{32}-u_{12}l_{31})}
We see that there is a calculation pattern, which can be expressed as the following formulas, first for
U
{\displaystyle U}
u
i
j
=
a
i
j
−
∑
k
=
1
i
−
1
u
k
j
l
i
k
{\displaystyle u_{ij}=a_{ij}-\sum _{k=1}^{i-1}u_{kj}l_{ik}}
and then for
L
{\displaystyle L}
l
i
j
=
1
u
j
j
(
a
i
j
−
∑
k
=
1
j
−
1
u
k
j
l
i
k
)
{\displaystyle l_{ij}={\frac {1}{u_{jj}}}(a_{ij}-\sum _{k=1}^{j-1}u_{kj}l_{ik})}
We see in the second formula that to get the
l
i
j
{\displaystyle l_{ij}}
below the diagonal, we have to divide by the diagonal element (pivot)
u
j
j
{\displaystyle u_{jj}}
, so we get problems when
u
j
j
{\displaystyle u_{jj}}
is either 0 or very small, which leads to numerical instability.
The solution to this problem is pivoting
A
{\displaystyle A}
, which means rearranging the rows of
A
{\displaystyle A}
, prior to the
L
U
{\displaystyle LU}
decomposition, in a way that the largest element of each column gets onto the diagonal of
A
{\displaystyle A}
. Rearranging the rows means to multiply
A
{\displaystyle A}
by a permutation matrix
P
{\displaystyle P}
:
P
A
⇒
A
′
{\displaystyle PA\Rightarrow A'}
Example:
(
0
1
1
0
)
(
1
4
2
3
)
⇒
(
2
3
1
4
)
{\displaystyle {\begin{pmatrix}0&1\\1&0\end{pmatrix}}{\begin{pmatrix}1&4\\2&3\end{pmatrix}}\Rightarrow {\begin{pmatrix}2&3\\1&4\end{pmatrix}}}
The decomposition algorithm is then applied on the rearranged matrix so that
P
A
=
L
U
{\displaystyle PA=LU}
Task description
The task is to implement a routine which will take a square nxn matrix
A
{\displaystyle A}
and return a lower triangular matrix
L
{\displaystyle L}
, a upper triangular matrix
U
{\displaystyle U}
and a permutation matrix
P
{\displaystyle P}
,
so that the above equation is fulfilled.
You should then test it on the following two examples and include your output.
Example 1
A
1 3 5
2 4 7
1 1 0
L
1.00000 0.00000 0.00000
0.50000 1.00000 0.00000
0.50000 -1.00000 1.00000
U
2.00000 4.00000 7.00000
0.00000 1.00000 1.50000
0.00000 0.00000 -2.00000
P
0 1 0
1 0 0
0 0 1
Example 2
A
11 9 24 2
1 5 2 6
3 17 18 1
2 5 7 1
L
1.00000 0.00000 0.00000 0.00000
0.27273 1.00000 0.00000 0.00000
0.09091 0.28750 1.00000 0.00000
0.18182 0.23125 0.00360 1.00000
U
11.00000 9.00000 24.00000 2.00000
0.00000 14.54545 11.45455 0.45455
0.00000 0.00000 -3.47500 5.68750
0.00000 0.00000 0.00000 0.51079
P
1 0 0 0
0 0 1 0
0 1 0 0
0 0 0 1
| #EchoLisp | EchoLisp |
(lib 'matrix) ;; the matrix library provides LU-decomposition
(decimals 5)
(define A (list->array' (1 3 5 2 4 7 1 1 0 ) 3 3))
(define PLU (matrix-lu-decompose A)) ;; -> list of three matrices, P, Lower, Upper
(array-print (first PLU))
0 1 0
1 0 0
0 0 1
(array-print (second PLU))
1 0 0
0.5 1 0
0.5 -1 1
(array-print (caddr PLU))
2 4 7
0 1 1.5
0 0 -2
(define A (list->array '(11 9 24 2 1 5 2 6 3 17 18 1 2 5 7 1 ) 4 4))
(define PLU (matrix-lu-decompose A)) ;; -> list of three matrices, P, Lower, Upper
(array-print (first PLU))
1 0 0 0
0 0 1 0
0 1 0 0
0 0 0 1
(array-print (second PLU))
1 0 0 0
0.27273 1 0 0
0.09091 0.2875 1 0
0.18182 0.23125 0.0036 1
(array-print (caddr PLU))
11 9 24 2
0 14.54545 11.45455 0.45455
0 0 -3.475 5.6875
0 0 0 0.51079
|
http://rosettacode.org/wiki/Lychrel_numbers | Lychrel numbers | Take an integer n, greater than zero.
Form the next n of its series by reversing the digits of the current n and adding the result to the current n.
Stop when n becomes palindromic - i.e. the digits of n in reverse order == n.
The above recurrence relation when applied to most starting numbers n = 1, 2, ... terminates in a palindrome quite quickly.
Example
If n0 = 12 we get
12
12 + 21 = 33, a palindrome!
And if n0 = 55 we get
55
55 + 55 = 110
110 + 011 = 121, a palindrome!
Notice that the check for a palindrome happens after an addition.
Some starting numbers seem to go on forever; the recurrence relation for 196 has been calculated for millions of repetitions forming numbers with millions of digits, without forming a palindrome.
These numbers that do not end in a palindrome are called Lychrel numbers.
For the purposes of this task a Lychrel number is any starting number that does not form a palindrome within 500 (or more) iterations.
Seed and related Lychrel numbers
Any integer produced in the sequence of a Lychrel number is also a Lychrel number.
In general, any sequence from one Lychrel number might converge to join the sequence from a prior Lychrel number candidate; for example the sequences for the numbers 196 and then 689 begin:
196
196 + 691 = 887
887 + 788 = 1675
1675 + 5761 = 7436
7436 + 6347 = 13783
13783 + 38731 = 52514
52514 + 41525 = 94039
...
689
689 + 986 = 1675
1675 + 5761 = 7436
...
So we see that the sequence starting with 689 converges to, and continues with the same numbers as that for 196.
Because of this we can further split the Lychrel numbers into true Seed Lychrel number candidates, and Related numbers that produce no palindromes but have integers in their sequence seen as part of the sequence generated from a lower Lychrel number.
Task
Find the number of seed Lychrel number candidates and related numbers for n in the range 1..10000 inclusive. (With that iteration limit of 500).
Print the number of seed Lychrels found; the actual seed Lychrels; and just the number of relateds found.
Print any seed Lychrel or related number that is itself a palindrome.
Show all output here.
References
What's special about 196? Numberphile video.
A023108 Positive integers which apparently never result in a palindrome under repeated applications of the function f(x) = x + (x with digits reversed).
Status of the 196 conjecture? Mathoverflow.
| #jq | jq | # This workhorse function assumes its arguments are
# non-negative integers represented as decimal strings:
def add(num1;num2):
if (num1|length) < (num2|length) then add(num2;num1)
else (num1 | explode | map(.-48) | reverse) as $a1
| (num2 | explode | map(.-48) | reverse) as $a2
| reduce range(0; num1|length) as $ix
($a2; # result
( $a1[$ix] + .[$ix] ) as $r
| if $r > 9 # carrying
then
.[$ix + 1] = ($r / 10 | floor) + (if $ix + 1 >= length then 0 else .[$ix + 1] end )
| .[$ix] = $r - ( $r / 10 | floor ) * 10
else
.[$ix] = $r
end )
| reverse | map(.+48) | implode
end ;
# Input: an array
def is_palindrome:
. as $in
| (length -1) as $n
| all( range(0; length/2); $in[.] == $in[$n - .]);
# Input: a string representing a decimal number.
# Output: a stream of such strings generated in accordance with the Lychrel rule,
# subject to the limitation imposed by "limit", and ending in true if the previous item in the stream is a palindrome
def next_palindromes(limit):
def toa: explode | map(.-48);
def tos: map(.+48) | implode;
def myadd(x;y): add(x|tos; y|tos) | toa;
# input: [limit, n]
def next:
.[0] as $limit
| .[1] as $n
| if $limit <= 0 then empty
else myadd($n ; $n|reverse) as $sum
| ($sum,
if ($sum | is_palindrome) then true else [$limit - 1, $sum] | next end)
end;
[limit, toa] | next | if type == "boolean" then . else tos end;
# Consider integers in range(0;n) using maxiter as the maximum number
# of iterations in the search for palindromes.
# Emit a dictionary:
# { seed: _, palindromic_seed: _, related: _} + {($n): $n} for all related $n
# where .seed is an array of integers holding the potential Lychrel seeds, etc
def lychrel_dictionary(n; maxiter):
reduce range(0; n) as $i ({};
($i | tostring) as $is
| if .[$is] then .related += [$i]
else [$is | next_palindromes(maxiter)] as $seq
| . as $dict
# | ([$i, $seq] | debug) as $debug
| if $seq[-1] == true then .
else if ($is | explode | is_palindrome) then .palindromic_seed += [$i] else . end
| if any($seq[]; $dict[.]) then .related += [$i]
else .seed += [$i]
end
| reduce $seq[] as $n (.; if .[$n] then . else .[$n] = $n end)
end
end ) ;
|
http://rosettacode.org/wiki/Magic_8-ball | Magic 8-ball | Task
Create Magic 8-Ball.
See details at: Magic 8-Ball.
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
| #Tcl | Tcl | namespace path {::tcl::mathop ::tcl::mathfunc}
set answers {
"As I see it, yes"
"Ask again later"
"Better not tell you now"
"Cannot predict now"
"Concentrate and ask again"
"Don't bet on it"
"It is certain"
"It is decidedly so"
"Most likely"
"My reply is no"
"My sources say maybe"
"My sources say no"
"Outlook good"
"Outlook not so good"
"Reply hazy, try again"
"Signs point to yes"
"Very doubtful"
"Without a doubt"
"Yes"
"Yes, definitely"
"Yes, probably not"
"You may rely on it"
"Your question has already been answered"
}
puts -nonewline "Question: "; flush stdout
while {[gets stdin line] > 0} {
set answer [lindex $answers [int [* [rand] [llength $answers]]]]
puts "⑧ says “$answer”"
puts -nonewline "Question: "; flush stdout
} |
http://rosettacode.org/wiki/Mandelbrot_set | Mandelbrot set | Mandelbrot set
You are encouraged to solve this task according to the task description, using any language you may know.
Task
Generate and draw the Mandelbrot set.
Note that there are many algorithms to draw Mandelbrot set and there are many functions which generate it .
| #Z80_Assembly | Z80 Assembly |
;
; Compute a Mandelbrot set on a simple Z80 computer.
;
; Porting this program to another Z80 platform should be easy and straight-
; forward: The only dependencies on my homebrew machine are the system-calls
; used to print strings and characters. These calls are performed by loading
; IX with the number of the system-call and performing an RST 08. To port this
; program to another operating system just replace these system-calls with
; the appropriate versions. Only three system-calls are used in the following:
; _crlf: Prints a CR/LF, _puts: Prints a 0-terminated string (the adress of
; which is expected in HL), and _putc: Print a single character which is
; expected in A. RST 0 give control back to the monitor.
;
#include "mondef.asm"
org ram_start
scale equ 256 ; Do NOT change this - the
; arithmetic routines rely on
; this scaling factor! :-)
divergent equ scale * 4
ld hl, welcome ; Print a welcome message
ld ix, _puts
rst 08
; for (y = <initial_value> ; y <= y_end; y += y_step)
; {
outer_loop ld hl, (y_end) ; Is y <= y_end?
ld de, (y)
and a ; Clear carry
sbc hl, de ; Perform the comparison
jp m, mandel_end ; End of outer loop reached
; for (x = x_start; x <= x_end; x += x_step)
; {
ld hl, (x_start) ; x = x_start
ld (x), hl
inner_loop ld hl, (x_end) ; Is x <= x_end?
ld de, (x)
and a
sbc hl, de
jp m, inner_loop_end ; End of inner loop reached
; z_0 = z_1 = 0;
ld hl, 0
ld (z_0), hl
ld (z_1), hl
; for (iteration = iteration_max; iteration; iteration--)
; {
ld a, (iteration_max)
ld b, a
iteration_loop push bc ; iteration -> stack
; z2 = (z_0 * z_0 - z_1 * z_1) / SCALE;
ld de, (z_1) ; Compute DE HL = z_1 * z_1
ld bc, de
call mul_16
ld (z_0_square_low), hl ; z_0 ** 2 is needed later again
ld (z_0_square_high), de
ld de, (z_0) ; Compute DE HL = z_0 * z_0
ld bc, de
call mul_16
ld (z_1_square_low), hl ; z_1 ** 2 will be also needed
ld (z_1_square_high), de
and a ; Compute subtraction
ld bc, (z_0_square_low)
sbc hl, bc
ld (scratch_0), hl ; Save lower 16 bit of result
ld hl, de
ld bc, (z_0_square_high)
sbc hl, bc
ld bc, (scratch_0) ; HL BC = z_0 ** 2 - z_1 ** 2
ld c, b ; Divide by scale = 256
ld b, l ; Discard the rest
push bc ; We need BC later
; z3 = 2 * z0 * z1 / SCALE;
ld hl, (z_0) ; Compute DE HL = 2 * z_0 * z_1
add hl, hl
ld de, hl
ld bc, (z_1)
call mul_16
ld b, e ; Divide by scale (= 256)
ld c, h ; BC contains now z_3
; z1 = z3 + y;
ld hl, (y)
add hl, bc
ld (z_1), hl
; z_0 = z_2 + x;
pop bc ; Here BC is needed again :-)
ld hl, (x)
add hl, bc
ld (z_0), hl
; if (z0 * z0 / SCALE + z1 * z1 / SCALE > 4 * SCALE)
ld hl, (z_0_square_low) ; Use the squares computed
ld de, (z_1_square_low) ; above
add hl, de
ld bc, hl ; BC contains lower word of sum
ld hl, (z_0_square_high)
ld de, (z_1_square_high)
adc hl, de
ld h, l ; HL now contains (z_0 ** 2 +
ld l, b ; z_1 ** 2) / scale
ld bc, divergent
and a
sbc hl, bc
; break;
jp c, iteration_dec ; No break
pop bc ; Get latest iteration counter
jr iteration_end ; Exit loop
; iteration++;
iteration_dec pop bc ; Get iteration counter
djnz iteration_loop ; We might fall through!
; }
iteration_end
; printf("%c", display[iteration % 7]);
ld a, b
and $7 ; lower three bits only (c = 0)
sbc hl, hl
ld l, a
ld de, display ; Get start of character array
add hl, de ; address and load the
ld a, (hl) ; character to be printed
ld ix, _putc ; Print the character
rst 08
ld de, (x_step) ; x += x_step
ld hl, (x)
add hl, de
ld (x), hl
jp inner_loop
; }
; printf("\n");
inner_loop_end ld ix, _crlf ; Print a CR/LF pair
rst 08
ld de, (y_step) ; y += y_step
ld hl, (y)
add hl, de
ld (y), hl ; Store new y-value
jp outer_loop
; }
mandel_end ld hl, finished ; Print finished-message
ld ix, _puts
rst 08
rst 0 ; Return to the monitor
welcome defb "Generating a Mandelbrot set"
defb cr, lf, eos
finished defb "Computation finished.", cr, lf, eos
iteration_max defb 10 ; How many iterations
x defw 0 ; x-coordinate
x_start defw -2 * scale ; Minimum x-coordinate
x_end defw 5 * scale / 10 ; Maximum x-coordinate
x_step defw 4 * scale / 100 ; x-coordinate step-width
y defw -1 * scale ; Minimum y-coordinate
y_end defw 1 * scale ; Maximum y-coordinate
y_step defw 1 * scale / 10 ; y-coordinate step-width
z_0 defw 0
z_1 defw 0
scratch_0 defw 0
z_0_square_high defw 0
z_0_square_low defw 0
z_1_square_high defw 0
z_1_square_low defw 0
display defb " .-+*=#@" ; 8 characters for the display
;
; Compute DEHL = BC * DE (signed): This routine is not too clever but it
; works. It is based on a standard 16-by-16 multiplication routine for unsigned
; integers. At the beginning the sign of the result is determined based on the
; signs of the operands which are negated if necessary. Then the unsigned
; multiplication takes place, followed by negating the result if necessary.
;
mul_16 xor a ; Clear carry and A (-> +)
bit 7, b ; Is BC negative?
jr z, bc_positive ; No
sub c ; A is still zero, complement
ld c, a
ld a, 0
sbc a, b
ld b, a
scf ; Set carry (-> -)
bc_positive bit 7, D ; Is DE negative?
jr z, de_positive ; No
push af ; Remember carry for later!
xor a
sub e
ld e, a
ld a, 0
sbc a, d
ld d, a
pop af ; Restore carry for complement
ccf ; Complement Carry (-> +/-?)
de_positive push af ; Remember state of carry
and a ; Start multiplication
sbc hl, hl
ld a, 16 ; 16 rounds
mul_16_loop add hl, hl
rl e
rl d
jr nc, mul_16_exit
add hl, bc
jr nc, mul_16_exit
inc de
mul_16_exit dec a
jr nz, mul_16_loop
pop af ; Restore carry from beginning
ret nc ; No sign inversion necessary
xor a ; Complement DE HL
sub l
ld l, a
ld a, 0
sbc a, h
ld h, a
ld a, 0
sbc a, e
ld e, a
ld a, 0
sbc a, d
ld d, a
ret
|
http://rosettacode.org/wiki/Mad_Libs | Mad Libs |
This page uses content from Wikipedia. The original article was at Mad Libs. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance)
Mad Libs is a phrasal template word game where one player prompts another for a list of words to substitute for blanks in a story, usually with funny results.
Task;
Write a program to create a Mad Libs like story.
The program should read an arbitrary multiline story from input.
The story will be terminated with a blank line.
Then, find each replacement to be made within the story, ask the user for a word to replace it with, and make all the replacements.
Stop when there are none left and print the final story.
The input should be an arbitrary story in the form:
<name> went for a walk in the park. <he or she>
found a <noun>. <name> decided to take it home.
Given this example, it should then ask for a name, a he or she and a noun (<name> gets replaced both times with the same value).
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
| #Go | Go | package main
import (
"bufio"
"fmt"
"io/ioutil"
"log"
"os"
"regexp"
"strings"
)
func main() {
pat := regexp.MustCompile("<.+?>")
if len(os.Args) != 2 {
fmt.Println("usage: madlib <story template file>")
return
}
b, err := ioutil.ReadFile(os.Args[1])
if err != nil {
log.Fatal(err)
}
tmpl := string(b)
s := []string{} // patterns in order of appearance
m := map[string]string{} // mapping from patterns to replacements
for _, p := range pat.FindAllString(tmpl, -1) {
if _, ok := m[p]; !ok {
m[p] = ""
s = append(s, p)
}
}
fmt.Println("Enter replacements:")
br := bufio.NewReader(os.Stdin)
for _, p := range s {
for {
fmt.Printf("%s: ", p[1:len(p)-1])
r, isPre, err := br.ReadLine()
if err != nil {
log.Fatal(err)
}
if isPre {
log.Fatal("you're not playing right. :P")
}
s := strings.TrimSpace(string(r))
if s == "" {
fmt.Println(" hmm?")
continue
}
m[p] = s
break
}
}
fmt.Println("\nYour story:\n")
fmt.Println(pat.ReplaceAllStringFunc(tmpl, func(p string) string {
return m[p]
}))
} |
http://rosettacode.org/wiki/Loops/With_multiple_ranges | Loops/With multiple ranges | Loops/With multiple ranges
You are encouraged to solve this task according to the task description, using any language you may know.
Some languages allow multiple loop ranges, such as the PL/I example (snippet) below.
/* all variables are DECLARED as integers. */
prod= 1; /*start with a product of unity. */
sum= 0; /* " " " sum " zero. */
x= +5;
y= -5;
z= -2;
one= 1;
three= 3;
seven= 7;
/*(below) ** is exponentiation: 4**3=64 */
do j= -three to 3**3 by three ,
-seven to +seven by x ,
555 to 550 - y ,
22 to -28 by -three ,
1927 to 1939 ,
x to y by z ,
11**x to 11**x + one;
/* ABS(n) = absolute value*/
sum= sum + abs(j); /*add absolute value of J.*/
if abs(prod)<2**27 & j¬=0 then prod=prod*j; /*PROD is small enough & J*/
end; /*not 0, then multiply it.*/
/*SUM and PROD are used for verification of J incrementation.*/
display (' sum= ' || sum); /*display strings to term.*/
display ('prod= ' || prod); /* " " " " */
Task
Simulate/translate the above PL/I program snippet as best as possible in your
language, with particular emphasis on the do loop construct.
The do index must be incremented/decremented in the same order shown.
If feasible, add commas to the two output numbers (being displayed).
Show all output here.
A simple PL/I DO loop (incrementing or decrementing) has the construct of:
DO variable = start_expression {TO ending_expression] {BY increment_expression} ;
---or---
DO variable = start_expression {BY increment_expression} {TO ending_expression] ;
where it is understood that all expressions will have a value. The variable is normally a
scaler variable, but need not be (but for this task, all variables and expressions are declared
to be scaler integers). If the BY expression is omitted, a BY value of unity is used.
All expressions are evaluated before the DO loop is executed, and those values are used
throughout the DO loop execution (even though, for instance, the value of Z may be
changed within the DO loop. This isn't the case here for this task.
A multiple-range DO loop can be constructed by using a comma (,) to separate additional ranges
(the use of multiple TO and/or BY keywords). This is the construct used in this task.
There are other forms of DO loops in PL/I involving the WHILE clause, but those won't be
needed here. DO loops without a TO clause might need a WHILE clause or some other
means of exiting the loop (such as LEAVE, RETURN, SIGNAL, GOTO, or STOP), or some other
(possible error) condition that causes transfer of control outside the DO loop.
Also, in PL/I, the check if the DO loop index value is outside the range is made at the
"head" (start) of the DO loop, so it's possible that the DO loop isn't executed, but
that isn't the case for any of the ranges used in this task.
In the example above, the clause: x to y by z
will cause the variable J to have to following values (in this order): 5 3 1 -1 -3 -5
In the example above, the clause: -seven to +seven by x
will cause the variable J to have to following values (in this order): -7 -2 3
Related tasks
Loop over multiple arrays simultaneously
Loops/Break
Loops/Continue
Loops/Do-while
Loops/Downward for
Loops/For
Loops/For with a specified step
Loops/Foreach
Loops/Increment loop index within loop body
Loops/Infinite
Loops/N plus one half
Loops/Nested
Loops/While
Loops/with multiple ranges
Loops/Wrong ranges
| #Applesoft_BASIC | Applesoft BASIC | 100 ::::::::: REMALL VARIABLES ARE DECLARED AS INTEGERS.
110 PROD= 1 : REMSTART WITH A PRODUCT OF UNITY.
120 SUM= 0:: REM " " " SUM " ZERO.
130 X= +5
140 Y= -5
150 Z= -2
160 UNO= 1
170 THREE= 3
180 SEVEN= 7
190 REM(BELOW) ^ IS EXPONENTIATION: 4^3=64
200 DO(0) = -THREE : T0(0) = 3^3 : BY(0) = THREE
210 DO(1) = -SEVEN : T0(1) = +SEVEN : BY(1) = X
220 DO(2) = 555 : T0(2) = 550 - Y
230 DO(3) = 22 : T0(3) = -28 : BY(3) = -THREE
240 DO(4) = 1927 : T0(4) = 1939
250 DO(5) = X : T0(5) = Y : BY(5) = Z
260 DO(6) = 11^X : T0(6) = 11^X + UNO
270 FOR I = 0 TO 6 : FINISH= T0(I) : BY = BY(I)
280 START = DO(I) : IF NOT BY THEN BY = 1
290 FOR J = START TO FINISH STEP BY
300 REM ABS(N) = ABSOLUTE VALUE
310 SUM= SUM + ABS(J) : REMADD ABSOLUTE VALUE OF J.
320 IF ABS(PROD)<2^27 AND J<>0 THEN PROD=PROD*J:REMPROD IS SMALL ENOUGH AND J NOT 0, THEN MULTIPLY IT.
330 NEXT J, I
340 REMSUM AND PROD ARE USED FOR VERIFICATION OF J INCREMENTATION.
350 PRINT " SUM= ";:N=SUM :GOSUB400:REMDISPLAY STRINGS TO TERM.
360 PRINT "PROD= ";:N=PROD:GOSUB400:REM " " " "
370 END
400 N$ = STR$ ( ABS ( INT (N))):O$ = "":D = -1: FOR I = LEN (N$) TO 1 STEP - 1:C$ = MID$ (N$,I,1) : O$ = MID$ (",",1 + (D < 2)) + O$ : D = (D + 1) * (D < 2) : O$ = C$ + O$: NEXT I: PRINT MID$ ("-",1 + (N > = 0))O$: RETURN |
http://rosettacode.org/wiki/Ludic_numbers | Ludic numbers | Ludic numbers are related to prime numbers as they are generated by a sieve quite like the Sieve of Eratosthenes is used to generate prime numbers.
The first ludic number is 1.
To generate succeeding ludic numbers create an array of increasing integers starting from 2.
2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 ...
(Loop)
Take the first member of the resultant array as the next ludic number 2.
Remove every 2nd indexed item from the array (including the first).
2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 ...
(Unrolling a few loops...)
Take the first member of the resultant array as the next ludic number 3.
Remove every 3rd indexed item from the array (including the first).
3 5 7 9 11 13 15 17 19 21 23 25 27 29 31 33 35 37 39 41 43 45 47 49 51 ...
Take the first member of the resultant array as the next ludic number 5.
Remove every 5th indexed item from the array (including the first).
5 7 11 13 17 19 23 25 29 31 35 37 41 43 47 49 53 55 59 61 65 67 71 73 77 ...
Take the first member of the resultant array as the next ludic number 7.
Remove every 7th indexed item from the array (including the first).
7 11 13 17 23 25 29 31 37 41 43 47 53 55 59 61 67 71 73 77 83 85 89 91 97 ...
...
Take the first member of the current array as the next ludic number L.
Remove every Lth indexed item from the array (including the first).
...
Task
Generate and show here the first 25 ludic numbers.
How many ludic numbers are there less than or equal to 1000?
Show the 2000..2005th ludic numbers.
Stretch goal
Show all triplets of ludic numbers < 250.
A triplet is any three numbers
x
,
{\displaystyle x,}
x
+
2
,
{\displaystyle x+2,}
x
+
6
{\displaystyle x+6}
where all three numbers are also ludic numbers.
| #J | J | ludic =: _1 |.!.1 [: {."1 [: (#~ 0 ~: {. | i.@#)^:a: 2 + i. |
http://rosettacode.org/wiki/Loops/Wrong_ranges | Loops/Wrong ranges | Loops/Wrong ranges
You are encouraged to solve this task according to the task description, using any language you may know.
Some languages have syntax or function(s) to generate a range of numeric values from a start value, a stop value, and an increment.
The purpose of this task is to select the range syntax/function that would generate at least two increasing numbers when given a stop value more than the start value and a positive increment of less than half the difference. You are then to use that same syntax/function but with different parameters; and show, here, what would happen.
Use these values if possible:
start
stop
increment
Comment
-2
2
1
Normal
-2
2
0
Zero increment
-2
2
-1
Increments away from stop value
-2
2
10
First increment is beyond stop value
2
-2
1
Start more than stop: positive increment
2
2
1
Start equal stop: positive increment
2
2
-1
Start equal stop: negative increment
2
2
0
Start equal stop: zero increment
0
0
0
Start equal stop equal zero: zero increment
Related tasks
Loop over multiple arrays simultaneously
Loops/Break
Loops/Continue
Loops/Do-while
Loops/Downward for
Loops/For
Loops/For with a specified step
Loops/Foreach
Loops/Increment loop index within loop body
Loops/Infinite
Loops/N plus one half
Loops/Nested
Loops/While
Loops/with multiple ranges
Loops/Wrong ranges
| #Common_Lisp | Common Lisp |
(dolist (lst '((-2 2 1 "Normal") ; Iterate the parameters list `start' `stop' `increment' and `comment'
(-2 2 0 "Zero increment")
(-2 2 -1 "Increments away from stop value")
(-2 2 10 "First increment is beyond stop value")
( 2 -2 1 "Start more than stop: positive increment")
( 2 2 1 "Start equal stop: positive increment")
( 2 2 -1 "Start equal stop: negative increment")
( 2 2 0 "Start equal stop: zero increment")
( 0 0 0 "Start equal stop equal zero: zero increment")))
(do ((i (car lst) (incf i (caddr lst))) ; Initialize `start' and set `increment'
(result ()) ; Initialize the result list
(loop-max 0 (incf loop-max))) ; Initialize a loop limit
((or (> i (cadr lst)) ; Break condition to `stop'
(> loop-max 10)) ; Break condition to loop limit
(format t "~&~44a: ~{~3d ~}" ; Finally print
(cadddr lst) ; The `comment'
(reverse result))) ; The in(de)creased numbers into result
(push i result))) ; Add the number to result
|
http://rosettacode.org/wiki/Luhn_test_of_credit_card_numbers | Luhn test of credit card numbers | The Luhn test is used by some credit card companies to distinguish valid credit card numbers from what could be a random selection of digits.
Those companies using credit card numbers that can be validated by the Luhn test have numbers that pass the following test:
Reverse the order of the digits in the number.
Take the first, third, ... and every other odd digit in the reversed digits and sum them to form the partial sum s1
Taking the second, fourth ... and every other even digit in the reversed digits:
Multiply each digit by two and sum the digits if the answer is greater than nine to form partial sums for the even digits
Sum the partial sums of the even digits to form s2
If s1 + s2 ends in zero then the original number is in the form of a valid credit card number as verified by the Luhn test.
For example, if the trial number is 49927398716:
Reverse the digits:
61789372994
Sum the odd digits:
6 + 7 + 9 + 7 + 9 + 4 = 42 = s1
The even digits:
1, 8, 3, 2, 9
Two times each even digit:
2, 16, 6, 4, 18
Sum the digits of each multiplication:
2, 7, 6, 4, 9
Sum the last:
2 + 7 + 6 + 4 + 9 = 28 = s2
s1 + s2 = 70 which ends in zero which means that 49927398716 passes the Luhn test
Task
Write a function/method/procedure/subroutine that will validate a number with the Luhn test, and
use it to validate the following numbers:
49927398716
49927398717
1234567812345678
1234567812345670
Related tasks
SEDOL
ISIN
| #ActionScript | ActionScript | function isValid(numString:String):Boolean
{
var isOdd:Boolean = true;
var oddSum:uint = 0;
var evenSum:uint = 0;
for(var i:int = numString.length - 1; i >= 0; i--)
{
var digit:uint = uint(numString.charAt(i))
if(isOdd) oddSum += digit;
else evenSum += digit/5 + (2*digit) % 10;
isOdd = !isOdd;
}
if((oddSum + evenSum) % 10 == 0) return true;
return false;
}
trace(isValid("49927398716"));
trace(isValid("49927398717"));
trace(isValid("1234567812345678"));
trace(isValid("1234567812345670")); |
http://rosettacode.org/wiki/Lucas-Lehmer_test | Lucas-Lehmer test | Lucas-Lehmer Test:
for
p
{\displaystyle p}
an odd prime, the Mersenne number
2
p
−
1
{\displaystyle 2^{p}-1}
is prime if and only if
2
p
−
1
{\displaystyle 2^{p}-1}
divides
S
(
p
−
1
)
{\displaystyle S(p-1)}
where
S
(
n
+
1
)
=
(
S
(
n
)
)
2
−
2
{\displaystyle S(n+1)=(S(n))^{2}-2}
, and
S
(
1
)
=
4
{\displaystyle S(1)=4}
.
Task
Calculate all Mersenne primes up to the implementation's
maximum precision, or the 47th Mersenne prime (whichever comes first).
| #Bracmat | Bracmat | ( clk$:?t0:?now
& ( time
= ( print
=
. put
$ ( str
$ ( div$(!arg,1)
","
( div$(mod$(!arg*100,100),1):?arg
& !arg:<10
& 0
|
)
!arg
" "
)
)
)
& -1*!now+(clk$:?now):?SEC
& print$!SEC
& print$(!now+-1*!t0)
& put$"s: "
)
& 3:?exponent
& whl
' ( !exponent:~>12000
& ( !exponent^(!exponent^-1):!exponent^%
& 4:?s
& 2^!exponent+-1:?n
& 0:?i
& whl
' ( 1+!i:?i
& !exponent+-2:~<!i
& mod$(!s^2+-2.!n):?s
)
& ( !s:0
& !time
& out$(str$(M !exponent " is PRIME!"))
|
)
|
)
& 1+!exponent:?exponent
)
& done
); |
http://rosettacode.org/wiki/Lucky_and_even_lucky_numbers | Lucky and even lucky numbers | Note that in the following explanation list indices are assumed to start at one.
Definition of lucky numbers
Lucky numbers are positive integers that are formed by:
Form a list of all the positive odd integers > 0
1
,
3
,
5
,
7
,
9
,
11
,
13
,
15
,
17
,
19
,
21
,
23
,
25
,
27
,
29
,
31
,
33
,
35
,
37
,
39...
{\displaystyle 1,3,5,7,9,11,13,15,17,19,21,23,25,27,29,31,33,35,37,39...}
Return the first number from the list (which is 1).
(Loop begins here)
Note then return the second number from the list (which is 3).
Discard every third, (as noted), number from the list to form the new list
1
,
3
,
7
,
9
,
13
,
15
,
19
,
21
,
25
,
27
,
31
,
33
,
37
,
39
,
43
,
45
,
49
,
51
,
55
,
57...
{\displaystyle 1,3,7,9,13,15,19,21,25,27,31,33,37,39,43,45,49,51,55,57...}
(Expanding the loop a few more times...)
Note then return the third number from the list (which is 7).
Discard every 7th, (as noted), number from the list to form the new list
1
,
3
,
7
,
9
,
13
,
15
,
21
,
25
,
27
,
31
,
33
,
37
,
43
,
45
,
49
,
51
,
55
,
57
,
63
,
67...
{\displaystyle 1,3,7,9,13,15,21,25,27,31,33,37,43,45,49,51,55,57,63,67...}
Note then return the 4th number from the list (which is 9).
Discard every 9th, (as noted), number from the list to form the new list
1
,
3
,
7
,
9
,
13
,
15
,
21
,
25
,
31
,
33
,
37
,
43
,
45
,
49
,
51
,
55
,
63
,
67
,
69
,
73...
{\displaystyle 1,3,7,9,13,15,21,25,31,33,37,43,45,49,51,55,63,67,69,73...}
Take the 5th, i.e. 13. Remove every 13th.
Take the 6th, i.e. 15. Remove every 15th.
Take the 7th, i.e. 21. Remove every 21th.
Take the 8th, i.e. 25. Remove every 25th.
(Rule for the loop)
Note the
n
{\displaystyle n}
th, which is
m
{\displaystyle m}
.
Remove every
m
{\displaystyle m}
th.
Increment
n
{\displaystyle n}
.
Definition of even lucky numbers
This follows the same rules as the definition of lucky numbers above except for the very first step:
Form a list of all the positive even integers > 0
2
,
4
,
6
,
8
,
10
,
12
,
14
,
16
,
18
,
20
,
22
,
24
,
26
,
28
,
30
,
32
,
34
,
36
,
38
,
40...
{\displaystyle 2,4,6,8,10,12,14,16,18,20,22,24,26,28,30,32,34,36,38,40...}
Return the first number from the list (which is 2).
(Loop begins here)
Note then return the second number from the list (which is 4).
Discard every 4th, (as noted), number from the list to form the new list
2
,
4
,
6
,
10
,
12
,
14
,
18
,
20
,
22
,
26
,
28
,
30
,
34
,
36
,
38
,
42
,
44
,
46
,
50
,
52...
{\displaystyle 2,4,6,10,12,14,18,20,22,26,28,30,34,36,38,42,44,46,50,52...}
(Expanding the loop a few more times...)
Note then return the third number from the list (which is 6).
Discard every 6th, (as noted), number from the list to form the new list
2
,
4
,
6
,
10
,
12
,
18
,
20
,
22
,
26
,
28
,
34
,
36
,
38
,
42
,
44
,
50
,
52
,
54
,
58
,
60...
{\displaystyle 2,4,6,10,12,18,20,22,26,28,34,36,38,42,44,50,52,54,58,60...}
Take the 4th, i.e. 10. Remove every 10th.
Take the 5th, i.e. 12. Remove every 12th.
(Rule for the loop)
Note the
n
{\displaystyle n}
th, which is
m
{\displaystyle m}
.
Remove every
m
{\displaystyle m}
th.
Increment
n
{\displaystyle n}
.
Task requirements
Write one or two subroutines (functions) to generate lucky numbers and even lucky numbers
Write a command-line interface to allow selection of which kind of numbers and which number(s). Since input is from the command line, tests should be made for the common errors:
missing arguments
too many arguments
number (or numbers) aren't legal
misspelled argument (lucky or evenLucky)
The command line handling should:
support mixed case handling of the (non-numeric) arguments
support printing a particular number
support printing a range of numbers by their index
support printing a range of numbers by their values
The resulting list of numbers should be printed on a single line.
The program should support the arguments:
what is displayed (on a single line)
argument(s) (optional verbiage is encouraged)
╔═══════════════════╦════════════════════════════════════════════════════╗
║ j ║ Jth lucky number ║
║ j , lucky ║ Jth lucky number ║
║ j , evenLucky ║ Jth even lucky number ║
║ ║ ║
║ j k ║ Jth through Kth (inclusive) lucky numbers ║
║ j k lucky ║ Jth through Kth (inclusive) lucky numbers ║
║ j k evenLucky ║ Jth through Kth (inclusive) even lucky numbers ║
║ ║ ║
║ j -k ║ all lucky numbers in the range j ──► |k| ║
║ j -k lucky ║ all lucky numbers in the range j ──► |k| ║
║ j -k evenLucky ║ all even lucky numbers in the range j ──► |k| ║
╚═══════════════════╩════════════════════════════════════════════════════╝
where |k| is the absolute value of k
Demonstrate the program by:
showing the first twenty lucky numbers
showing the first twenty even lucky numbers
showing all lucky numbers between 6,000 and 6,100 (inclusive)
showing all even lucky numbers in the same range as above
showing the 10,000th lucky number (extra credit)
showing the 10,000th even lucky number (extra credit)
See also
This task is related to the Sieve of Eratosthenes task.
OEIS Wiki Lucky numbers.
Sequence A000959 lucky numbers on The On-Line Encyclopedia of Integer Sequences.
Sequence A045954 even lucky numbers or ELN on The On-Line Encyclopedia of Integer Sequences.
Entry lucky numbers on The Eric Weisstein's World of Mathematics.
| #JavaScript | JavaScript |
function luckyNumbers(opts={}) {
/**************************************************************************\
| OPTIONS |
|**************************************************************************|
| even ...... boolean ............. return even/uneven numbers |
| (default: false) |
| |
| nth ....... number ............... return nth number |
| |
| through ... number ............... return numbers from #1 to number |
| OR array[from, to] ... return numbers on index |
| from array[from] to array[to] |
| |
| range ..... array[from, to] ...... return numbers between from and to |
\**************************************************************************/
opts.even = opts.even || false;
if (typeof opts.through == 'number') opts.through = [0, opts.through];
let out = [],
x = opts.even ? 2 : 1,
max = opts.range ? opts.range[1] * 3
: opts.through ? opts.through[1] * 12
: opts.nth ? opts.nth * 15
: 2000;
for (x; x <= max; x = x+2) out.push(x); // fill
for (x = 1; x < Math.floor(out.length / 2); x++) { // sieve
let i = out.length;
while (i--)
(i+1) % out[x] == 0 && out.splice(i, 1);
}
if (opts.nth) return out[opts.nth-1];
if (opts.through) return out.slice(opts.through[0], opts.through[1]);
if (opts.range) return out.filter(function(val) {
return val >= opts.range[0] && val <= opts.range[1];
});
return out;
}
/* TESTING */
// blank
console.log( luckyNumbers() );
// showing the first twenty lucky numbers
console.log( luckyNumbers({through: 20}) );
// showing the first twenty even lucky numbers
console.log( luckyNumbers({even: true, through: 20}) );
// showing all lucky numbers between 6,000 and 6,100 (inclusive)
console.log( luckyNumbers({range: [6000, 6100]}) );
// showing all even lucky numbers in the same range as above
console.log( luckyNumbers({even: true, range: [6000, 6100]}) );
// showing the 10,000th lucky number (extra credit)
console.log( luckyNumbers({nth: 10000}) );
// showing the 10,000th even lucky number (extra credit)
console.log( luckyNumbers({even: true, nth: 10000}) );
|
http://rosettacode.org/wiki/LZW_compression | LZW compression | The Lempel-Ziv-Welch (LZW) algorithm provides loss-less data compression.
You can read a complete description of it in the Wikipedia article on the subject. It was patented, but it entered the public domain in 2004.
| #CoffeeScript | CoffeeScript |
lzw = (s) ->
dct = {} # map substrings to codes between 256 and 4096
stream = [] # array of compression results
# initialize basic ASCII characters
for code_num in [0..255]
c = String.fromCharCode(code_num)
dct[c] = code_num
code_num = 256
i = 0
while i < s.length
# Find word and new_word
# word = longest substr already encountered, or next character
# new_word = word plus next character, a new substr to encode
word = ''
j = i
while j < s.length
new_word = word + s[j]
break if !dct[new_word]
word = new_word
j += 1
# stream out the code for the substring
stream.push dct[word]
# build up our encoding dictionary
if code_num < 4096
dct[new_word] = code_num
code_num += 1
# advance thru the string
i += word.length
stream
console.log lzw "TOBEORNOTTOBEORTOBEORNOT"
|
http://rosettacode.org/wiki/LU_decomposition | LU decomposition | Every square matrix
A
{\displaystyle A}
can be decomposed into a product of a lower triangular matrix
L
{\displaystyle L}
and a upper triangular matrix
U
{\displaystyle U}
,
as described in LU decomposition.
A
=
L
U
{\displaystyle A=LU}
It is a modified form of Gaussian elimination.
While the Cholesky decomposition only works for symmetric,
positive definite matrices, the more general LU decomposition
works for any square matrix.
There are several algorithms for calculating L and U.
To derive Crout's algorithm for a 3x3 example,
we have to solve the following system:
A
=
(
a
11
a
12
a
13
a
21
a
22
a
23
a
31
a
32
a
33
)
=
(
l
11
0
0
l
21
l
22
0
l
31
l
32
l
33
)
(
u
11
u
12
u
13
0
u
22
u
23
0
0
u
33
)
=
L
U
{\displaystyle A={\begin{pmatrix}a_{11}&a_{12}&a_{13}\\a_{21}&a_{22}&a_{23}\\a_{31}&a_{32}&a_{33}\\\end{pmatrix}}={\begin{pmatrix}l_{11}&0&0\\l_{21}&l_{22}&0\\l_{31}&l_{32}&l_{33}\\\end{pmatrix}}{\begin{pmatrix}u_{11}&u_{12}&u_{13}\\0&u_{22}&u_{23}\\0&0&u_{33}\end{pmatrix}}=LU}
We now would have to solve 9 equations with 12 unknowns. To make the system uniquely solvable, usually the diagonal elements of
L
{\displaystyle L}
are set to 1
l
11
=
1
{\displaystyle l_{11}=1}
l
22
=
1
{\displaystyle l_{22}=1}
l
33
=
1
{\displaystyle l_{33}=1}
so we get a solvable system of 9 unknowns and 9 equations.
A
=
(
a
11
a
12
a
13
a
21
a
22
a
23
a
31
a
32
a
33
)
=
(
1
0
0
l
21
1
0
l
31
l
32
1
)
(
u
11
u
12
u
13
0
u
22
u
23
0
0
u
33
)
=
(
u
11
u
12
u
13
u
11
l
21
u
12
l
21
+
u
22
u
13
l
21
+
u
23
u
11
l
31
u
12
l
31
+
u
22
l
32
u
13
l
31
+
u
23
l
32
+
u
33
)
=
L
U
{\displaystyle A={\begin{pmatrix}a_{11}&a_{12}&a_{13}\\a_{21}&a_{22}&a_{23}\\a_{31}&a_{32}&a_{33}\\\end{pmatrix}}={\begin{pmatrix}1&0&0\\l_{21}&1&0\\l_{31}&l_{32}&1\\\end{pmatrix}}{\begin{pmatrix}u_{11}&u_{12}&u_{13}\\0&u_{22}&u_{23}\\0&0&u_{33}\end{pmatrix}}={\begin{pmatrix}u_{11}&u_{12}&u_{13}\\u_{11}l_{21}&u_{12}l_{21}+u_{22}&u_{13}l_{21}+u_{23}\\u_{11}l_{31}&u_{12}l_{31}+u_{22}l_{32}&u_{13}l_{31}+u_{23}l_{32}+u_{33}\end{pmatrix}}=LU}
Solving for the other
l
{\displaystyle l}
and
u
{\displaystyle u}
, we get the following equations:
u
11
=
a
11
{\displaystyle u_{11}=a_{11}}
u
12
=
a
12
{\displaystyle u_{12}=a_{12}}
u
13
=
a
13
{\displaystyle u_{13}=a_{13}}
u
22
=
a
22
−
u
12
l
21
{\displaystyle u_{22}=a_{22}-u_{12}l_{21}}
u
23
=
a
23
−
u
13
l
21
{\displaystyle u_{23}=a_{23}-u_{13}l_{21}}
u
33
=
a
33
−
(
u
13
l
31
+
u
23
l
32
)
{\displaystyle u_{33}=a_{33}-(u_{13}l_{31}+u_{23}l_{32})}
and for
l
{\displaystyle l}
:
l
21
=
1
u
11
a
21
{\displaystyle l_{21}={\frac {1}{u_{11}}}a_{21}}
l
31
=
1
u
11
a
31
{\displaystyle l_{31}={\frac {1}{u_{11}}}a_{31}}
l
32
=
1
u
22
(
a
32
−
u
12
l
31
)
{\displaystyle l_{32}={\frac {1}{u_{22}}}(a_{32}-u_{12}l_{31})}
We see that there is a calculation pattern, which can be expressed as the following formulas, first for
U
{\displaystyle U}
u
i
j
=
a
i
j
−
∑
k
=
1
i
−
1
u
k
j
l
i
k
{\displaystyle u_{ij}=a_{ij}-\sum _{k=1}^{i-1}u_{kj}l_{ik}}
and then for
L
{\displaystyle L}
l
i
j
=
1
u
j
j
(
a
i
j
−
∑
k
=
1
j
−
1
u
k
j
l
i
k
)
{\displaystyle l_{ij}={\frac {1}{u_{jj}}}(a_{ij}-\sum _{k=1}^{j-1}u_{kj}l_{ik})}
We see in the second formula that to get the
l
i
j
{\displaystyle l_{ij}}
below the diagonal, we have to divide by the diagonal element (pivot)
u
j
j
{\displaystyle u_{jj}}
, so we get problems when
u
j
j
{\displaystyle u_{jj}}
is either 0 or very small, which leads to numerical instability.
The solution to this problem is pivoting
A
{\displaystyle A}
, which means rearranging the rows of
A
{\displaystyle A}
, prior to the
L
U
{\displaystyle LU}
decomposition, in a way that the largest element of each column gets onto the diagonal of
A
{\displaystyle A}
. Rearranging the rows means to multiply
A
{\displaystyle A}
by a permutation matrix
P
{\displaystyle P}
:
P
A
⇒
A
′
{\displaystyle PA\Rightarrow A'}
Example:
(
0
1
1
0
)
(
1
4
2
3
)
⇒
(
2
3
1
4
)
{\displaystyle {\begin{pmatrix}0&1\\1&0\end{pmatrix}}{\begin{pmatrix}1&4\\2&3\end{pmatrix}}\Rightarrow {\begin{pmatrix}2&3\\1&4\end{pmatrix}}}
The decomposition algorithm is then applied on the rearranged matrix so that
P
A
=
L
U
{\displaystyle PA=LU}
Task description
The task is to implement a routine which will take a square nxn matrix
A
{\displaystyle A}
and return a lower triangular matrix
L
{\displaystyle L}
, a upper triangular matrix
U
{\displaystyle U}
and a permutation matrix
P
{\displaystyle P}
,
so that the above equation is fulfilled.
You should then test it on the following two examples and include your output.
Example 1
A
1 3 5
2 4 7
1 1 0
L
1.00000 0.00000 0.00000
0.50000 1.00000 0.00000
0.50000 -1.00000 1.00000
U
2.00000 4.00000 7.00000
0.00000 1.00000 1.50000
0.00000 0.00000 -2.00000
P
0 1 0
1 0 0
0 0 1
Example 2
A
11 9 24 2
1 5 2 6
3 17 18 1
2 5 7 1
L
1.00000 0.00000 0.00000 0.00000
0.27273 1.00000 0.00000 0.00000
0.09091 0.28750 1.00000 0.00000
0.18182 0.23125 0.00360 1.00000
U
11.00000 9.00000 24.00000 2.00000
0.00000 14.54545 11.45455 0.45455
0.00000 0.00000 -3.47500 5.68750
0.00000 0.00000 0.00000 0.51079
P
1 0 0 0
0 0 1 0
0 1 0 0
0 0 0 1
| #Fortran | Fortran | program lu1
implicit none
call check( reshape([real(8)::1,2,1,3,4,1,5,7,0 ],[3,3]) )
call check( reshape([real(8)::11,1,3,2,9,5,17,5,24,2,18,7,2,6,1,1],[4,4]) )
contains
subroutine check(a)
real(8), intent(in) :: a(:,:)
integer :: i,j,n
real(8), allocatable :: aa(:,:),l(:,:),u(:,:)
integer, allocatable :: p(:,:)
integer, allocatable :: ipiv(:)
n = size(a,1)
allocate(aa(n,n),l(n,n),u(n,n),p(n,n),ipiv(n))
forall (j=1:n,i=1:n)
aa(i,j) = a(i,j)
u (i,j) = 0d0
p (i,j) = merge(1 ,0 ,i.eq.j)
l (i,j) = merge(1d0,0d0,i.eq.j)
end forall
call lu(aa, ipiv)
do i = 1,n
l(i, :i-1) = aa(i, :i-1)
u(i,i: ) = aa(i,i: )
end do
p(ipiv,:) = p
call mat_print('a',a)
call mat_print('p',p)
call mat_print('l',l)
call mat_print('u',u)
print *, "residual"
print *, "|| P.A - L.U || = ", maxval(abs(matmul(p,a)-matmul(l,u)))
end subroutine
subroutine lu(a,p)
! in situ decomposition, corresponds to LAPACK's dgebtrf
real(8), intent(inout) :: a(:,:)
integer, intent(out ) :: p(:)
integer :: n, i,j,k,kmax
n = size(a,1)
p = [ ( i, i=1,n ) ]
do k = 1,n-1
kmax = maxloc(abs(a(p(k:),k)),1) + k-1
if (kmax /= k ) then
p([k, kmax]) = p([kmax, k])
a([k, kmax],:) = a([kmax, k],:)
end if
a(k+1:,k) = a(k+1:,k) / a(k,k)
forall (j=k+1:n) a(k+1:,j) = a(k+1:,j) - a(k,j)*a(k+1:,k)
end do
end subroutine
subroutine mat_print(amsg,a)
character(*), intent(in) :: amsg
class (*), intent(in) :: a(:,:)
integer :: i
print*,' '
print*,amsg
do i=1,size(a,1)
select type (a)
type is (real(8)) ; print'(100f8.2)',a(i,:)
type is (integer) ; print'(100i8 )',a(i,:)
end select
end do
print*,' '
end subroutine
end program |
http://rosettacode.org/wiki/Lychrel_numbers | Lychrel numbers | Take an integer n, greater than zero.
Form the next n of its series by reversing the digits of the current n and adding the result to the current n.
Stop when n becomes palindromic - i.e. the digits of n in reverse order == n.
The above recurrence relation when applied to most starting numbers n = 1, 2, ... terminates in a palindrome quite quickly.
Example
If n0 = 12 we get
12
12 + 21 = 33, a palindrome!
And if n0 = 55 we get
55
55 + 55 = 110
110 + 011 = 121, a palindrome!
Notice that the check for a palindrome happens after an addition.
Some starting numbers seem to go on forever; the recurrence relation for 196 has been calculated for millions of repetitions forming numbers with millions of digits, without forming a palindrome.
These numbers that do not end in a palindrome are called Lychrel numbers.
For the purposes of this task a Lychrel number is any starting number that does not form a palindrome within 500 (or more) iterations.
Seed and related Lychrel numbers
Any integer produced in the sequence of a Lychrel number is also a Lychrel number.
In general, any sequence from one Lychrel number might converge to join the sequence from a prior Lychrel number candidate; for example the sequences for the numbers 196 and then 689 begin:
196
196 + 691 = 887
887 + 788 = 1675
1675 + 5761 = 7436
7436 + 6347 = 13783
13783 + 38731 = 52514
52514 + 41525 = 94039
...
689
689 + 986 = 1675
1675 + 5761 = 7436
...
So we see that the sequence starting with 689 converges to, and continues with the same numbers as that for 196.
Because of this we can further split the Lychrel numbers into true Seed Lychrel number candidates, and Related numbers that produce no palindromes but have integers in their sequence seen as part of the sequence generated from a lower Lychrel number.
Task
Find the number of seed Lychrel number candidates and related numbers for n in the range 1..10000 inclusive. (With that iteration limit of 500).
Print the number of seed Lychrels found; the actual seed Lychrels; and just the number of relateds found.
Print any seed Lychrel or related number that is itself a palindrome.
Show all output here.
References
What's special about 196? Numberphile video.
A023108 Positive integers which apparently never result in a palindrome under repeated applications of the function f(x) = x + (x with digits reversed).
Status of the 196 conjecture? Mathoverflow.
| #Julia | Julia | const cache = Dict{BigInt, Tuple{Bool, BigInt}}()
Base.reverse(n::Integer) = parse(BigInt, string(n) |> reverse)
function lychrel(n::BigInt)::Tuple{Bool, BigInt}
if haskey(cache, n)
return cache[n]
end
r = reverse(n)
rst = (true, n)
seen = Set{BigInt}()
for i in 0:500
n += r
r = reverse(n)
if n == r
rst = (false, big(0))
break
end
if haskey(cache, n)
rst = cache[n]
break
end
push!(seen, n)
end
for bi in seen
cache[bi] = rst
end
return rst
end
seeds = BigInt[]
related = BigInt[]
palin = BigInt[]
for n in big.(1:10000)
t = lychrel(n)
if ! t[1]
continue
end
if n == t[2]
push!(seeds, n)
else
push!(related, n)
end
if n == t[2]
push!(palin, t[2])
end
end
println(length(seeds), " lychrel seeds: ", join(seeds, ", "))
println(length(related), " lychrel related")
println(length(palin), " lychrel palindromes: ", join(palin, ", ")) |
http://rosettacode.org/wiki/Magic_8-ball | Magic 8-ball | Task
Create Magic 8-Ball.
See details at: Magic 8-Ball.
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
| #Tiny_BASIC | Tiny BASIC | 10 PRINT "Concentrate hard on your question, then tell me your favorite number."
20 INPUT N
30 REM in lieu of a random number generator
40 IF N<0 THEN LET N=-N
50 IF N<20 THEN GOTO 1000+N*10
60 LET N=N-20
70 GOTO 50
1000 PRINT "It is certain."
1005 END
1010 PRINT "It is decidedly so."
1015 END
1020 PRINT "Without a doubt."
1025 END
1030 PRINT "Yes - definitely."
1035 END
1040 PRINT "You may rely on it."
1045 END
1050 PRINT "As I see it, yes."
1055 END
1060 PRINT "Most likely."
1065 END
1070 PRINT "Outlook good."
1075 END
1080 PRINT "Yes."
1085 END
1090 PRINT "Signs point to yes."
1095 END
1100 PRINT "Reply hazy, try again."
1105 END
1110 PRINT "Ask again later."
1115 END
1120 PRINT "Better not tell you now."
1125 END
1130 PRINT "Cannot predict now."
1135 END
1140 PRINT "Concentrate and ask again."
1145 END
1150 PRINT "Don't count on it."
1155 END
1160 PRINT "My reply is no."
1165 END
1170 PRINT "My sources say no."
1175 END
1180 PRINT "Outlook not so good."
1185 END
1190 PRINT "Very doubtful." |
http://rosettacode.org/wiki/Mandelbrot_set | Mandelbrot set | Mandelbrot set
You are encouraged to solve this task according to the task description, using any language you may know.
Task
Generate and draw the Mandelbrot set.
Note that there are many algorithms to draw Mandelbrot set and there are many functions which generate it .
| #zkl | zkl | fcn mandelbrot{ // lord this is slooooow
bitmap:=PPM(640,480);
foreach y,x in ([0..479],[0..639]){
cx:=(x.toFloat()/640 - 0.5)*4.0; //range: -2.0 to +2.0
cy:=((y-240).toFloat()/240.0)*1.5; //range: -1.5 to +1.5
cnt:=0; zx:=0.0; zy:=0.0;
do(1000){
if(zx*zx + zy*zy > 2.0){ //z heads toward infinity
//set color of pixel to rate it approaches infinity
bitmap[x,y]=cnt.shiftLeft(21) + cnt.shiftLeft(10) + cnt*8;
break;
}
temp:=zx*zy;
zx=zx*zx - zy*zy + cx; //calculate next iteration of z
zy=2.0*temp + cy;
cnt+=1;
}
}
bitmap.write(File("foo.ppm","wb"));
}(); |
http://rosettacode.org/wiki/Mad_Libs | Mad Libs |
This page uses content from Wikipedia. The original article was at Mad Libs. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance)
Mad Libs is a phrasal template word game where one player prompts another for a list of words to substitute for blanks in a story, usually with funny results.
Task;
Write a program to create a Mad Libs like story.
The program should read an arbitrary multiline story from input.
The story will be terminated with a blank line.
Then, find each replacement to be made within the story, ask the user for a word to replace it with, and make all the replacements.
Stop when there are none left and print the final story.
The input should be an arbitrary story in the form:
<name> went for a walk in the park. <he or she>
found a <noun>. <name> decided to take it home.
Given this example, it should then ask for a name, a he or she and a noun (<name> gets replaced both times with the same value).
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
| #Haskell | Haskell | import System.IO (stdout, hFlush)
import System.Environment (getArgs)
import qualified Data.Map as M (Map, lookup, insert, empty)
getLines :: IO [String]
getLines = reverse <$> getLines_ []
where
getLines_ xs = do
line <- getLine
case line of
[] -> return xs
_ -> getLines_ $ line : xs
prompt :: String -> IO String
prompt p = putStr p >> hFlush stdout >> getLine
getKeyword :: String -> Maybe String
getKeyword ('<':xs) = getKeyword_ xs []
where
getKeyword_ [] _ = Nothing
getKeyword_ (x:'>':_) acc = Just $ '<' : reverse ('>' : x : acc)
getKeyword_ (x:xs) acc = getKeyword_ xs $ x : acc
getKeyword _ = Nothing
parseText :: String -> M.Map String String -> IO String
parseText [] _ = return []
parseText line@(l:lx) keywords =
case getKeyword line of
Nothing -> (l :) <$> parseText lx keywords
Just keyword -> do
let rest = drop (length keyword) line
case M.lookup keyword keywords of
Nothing -> do
newword <- prompt $ "Enter a word for " ++ keyword ++ ": "
rest_ <- parseText rest $ M.insert keyword newword keywords
return $ newword ++ rest_
Just knownword -> do
rest_ <- parseText rest keywords
return $ knownword ++ rest_
main :: IO ()
main = do
args <- getArgs
nlines <-
case args of
[] -> unlines <$> getLines
arg:_ -> readFile arg
nlines_ <- parseText nlines M.empty
putStrLn ""
putStrLn nlines_ |
http://rosettacode.org/wiki/Loops/With_multiple_ranges | Loops/With multiple ranges | Loops/With multiple ranges
You are encouraged to solve this task according to the task description, using any language you may know.
Some languages allow multiple loop ranges, such as the PL/I example (snippet) below.
/* all variables are DECLARED as integers. */
prod= 1; /*start with a product of unity. */
sum= 0; /* " " " sum " zero. */
x= +5;
y= -5;
z= -2;
one= 1;
three= 3;
seven= 7;
/*(below) ** is exponentiation: 4**3=64 */
do j= -three to 3**3 by three ,
-seven to +seven by x ,
555 to 550 - y ,
22 to -28 by -three ,
1927 to 1939 ,
x to y by z ,
11**x to 11**x + one;
/* ABS(n) = absolute value*/
sum= sum + abs(j); /*add absolute value of J.*/
if abs(prod)<2**27 & j¬=0 then prod=prod*j; /*PROD is small enough & J*/
end; /*not 0, then multiply it.*/
/*SUM and PROD are used for verification of J incrementation.*/
display (' sum= ' || sum); /*display strings to term.*/
display ('prod= ' || prod); /* " " " " */
Task
Simulate/translate the above PL/I program snippet as best as possible in your
language, with particular emphasis on the do loop construct.
The do index must be incremented/decremented in the same order shown.
If feasible, add commas to the two output numbers (being displayed).
Show all output here.
A simple PL/I DO loop (incrementing or decrementing) has the construct of:
DO variable = start_expression {TO ending_expression] {BY increment_expression} ;
---or---
DO variable = start_expression {BY increment_expression} {TO ending_expression] ;
where it is understood that all expressions will have a value. The variable is normally a
scaler variable, but need not be (but for this task, all variables and expressions are declared
to be scaler integers). If the BY expression is omitted, a BY value of unity is used.
All expressions are evaluated before the DO loop is executed, and those values are used
throughout the DO loop execution (even though, for instance, the value of Z may be
changed within the DO loop. This isn't the case here for this task.
A multiple-range DO loop can be constructed by using a comma (,) to separate additional ranges
(the use of multiple TO and/or BY keywords). This is the construct used in this task.
There are other forms of DO loops in PL/I involving the WHILE clause, but those won't be
needed here. DO loops without a TO clause might need a WHILE clause or some other
means of exiting the loop (such as LEAVE, RETURN, SIGNAL, GOTO, or STOP), or some other
(possible error) condition that causes transfer of control outside the DO loop.
Also, in PL/I, the check if the DO loop index value is outside the range is made at the
"head" (start) of the DO loop, so it's possible that the DO loop isn't executed, but
that isn't the case for any of the ranges used in this task.
In the example above, the clause: x to y by z
will cause the variable J to have to following values (in this order): 5 3 1 -1 -3 -5
In the example above, the clause: -seven to +seven by x
will cause the variable J to have to following values (in this order): -7 -2 3
Related tasks
Loop over multiple arrays simultaneously
Loops/Break
Loops/Continue
Loops/Do-while
Loops/Downward for
Loops/For
Loops/For with a specified step
Loops/Foreach
Loops/Increment loop index within loop body
Loops/Infinite
Loops/N plus one half
Loops/Nested
Loops/While
Loops/with multiple ranges
Loops/Wrong ranges
| #ARM_Assembly | ARM Assembly |
/* ARM assembly Raspberry PI */
/* program loopnrange.s */
/* REMARK 1 : this program use routines in a include file
see task Include a file language arm assembly
for the routine affichageMess conversion10
see at end of this program the instruction include */
/*********************************/
/* Constantes */
/*********************************/
.equ STDOUT, 1 @ Linux output console
.equ EXIT, 1 @ Linux syscall
.equ WRITE, 4 @ Linux syscall
/*********************************/
/* Initialized data */
/*********************************/
.data
szMessResult: .ascii "" @ message result
sMessValeur: .fill 11, 1, ' '
szCarriageReturn: .asciz "\n"
/*********************************/
/* UnInitialized data */
/*********************************/
.bss
iSum: .skip 4 @ this program store sum and product in memory
iProd: .skip 4 @ it is possible to use registers r2 and r11
/*********************************/
/* code section */
/*********************************/
.text
.global main
main: @ entry of program
ldr r0,iAdriProd
mov r1,#1
str r1,[r0] @ init product
ldr r0,iAdriSum
mov r1,#0
str r1,[r0] @ init sum
mov r5,#5 @ x
mov r4,#-5 @ y
mov r6,#-2 @ z
mov r8,#1 @ one
mov r3,#3 @ three
mov r7,#7 @ seven
@ loop one
mov r0,#3
mov r1,#3
bl computePow @ compute 3 pow 3
mov r10,r0 @ save result
mvn r9,r3 @ r9 = - three
add r9,#1
1:
mov r0,r9
bl computeSumProd
add r9,r3 @ increment with three
cmp r9,r10
ble 1b
@ loop two
mvn r9,r7 @ r9 = - seven
add r9,#1
2:
mov r0,r9
bl computeSumProd
add r9,r5 @ increment with x
cmp r9,r7 @ compare to seven
ble 2b
@ loop three
mov r9,#550
sub r10,r9,r4 @ r10 = 550 - y
mov r9,#555
3:
mov r0,r9
bl computeSumProd
add r9,#1
cmp r9,r10
ble 3b
@ loop four
mov r9,#22
4:
mov r0,r9
bl computeSumProd
sub r9,r3 @ decrement with three
cmp r9,#-28
bge 4b
@ loop five
mov r9,#1927
ldr r10,iVal1939
5:
mov r0,r9
bl computeSumProd
add r9,#1
cmp r9,r10
ble 5b
@ loop six
mov r9,r5 @ r9 = x
mvn r10,r6 @ r10 = - z
add r10,#1
6:
mov r0,r9
bl computeSumProd
sub r9,r10
cmp r9,r4
bge 6b
@ loop seven
mov r0,r5
mov r1,#11
bl computePow @ compute 11 pow x
add r10,r0,r8 @ + one
mov r9,r0
7:
mov r0,r9
bl computeSumProd
add r9,#1
cmp r9,r10
ble 7b
@ display result
ldr r0,iAdriSum
ldr r0,[r0]
ldr r1,iAdrsMessValeur @ signed conversion value
bl conversion10S @ decimal conversion
ldr r0,iAdrszMessResult
bl affichageMess @ display message
ldr r0,iAdrszCarriageReturn
bl affichageMess @ display return line
ldr r0,iAdriProd
ldr r0,[r0]
ldr r1,iAdrsMessValeur @ conversion value
bl conversion10S @ signed decimal conversion
ldr r0,iAdrszMessResult
bl affichageMess @ display message
ldr r0,iAdrszCarriageReturn
bl affichageMess @ display return line
100: @ standard end of the program
mov r0, #0 @ return code
mov r7, #EXIT @ request to exit program
svc #0 @ perform the system call
iAdrsMessValeur: .int sMessValeur
iAdrszMessResult: .int szMessResult
iAdrszCarriageReturn: .int szCarriageReturn
iVal1939: .int 1939
/******************************************************************/
/* compute the sum and prod */
/******************************************************************/
/* r0 contains the number */
computeSumProd:
push {r1-r4,lr} @ save registers
asr r1,r0,#31
eor r2,r0,r1
sub r2,r2,r1 @ compute absolue value
//vidregtit somme
ldr r3,iAdriSum @ load sum
ldr r1,[r3]
add r1,r2 @ add sum
str r1,[r3] @ store sum
cmp r0,#0 @ j = 0 ?
beq 100f @ yes
ldr r3,iAdriProd
ldr r1,[r3]
asr r2,r1,#31 @ compute absolute value of prod
eor r4,r1,r2
sub r2,r4,r2
cmp r2,#1<<27 @ compare 2 puissance 27
bgt 100f
mul r1,r0,r1
str r1,[r3] @ store prod
100:
pop {r1-r4,lr} @ restaur registers
bx lr @ return
iAdriSum: .int iSum
iAdriProd: .int iProd
/******************************************************************/
/* compute pow */
/******************************************************************/
/* r0 contains pow */
/* r1 contains number */
computePow:
push {r1-r2,lr} @ save registers
mov r2,r0
mov r0,#1
1:
cmp r2,#0
ble 100f
mul r0,r1,r0
sub r2,#1
b 1b
100:
pop {r1-r2,lr} @ restaur registers
bx lr @ return
/***************************************************/
/* ROUTINES INCLUDE */
/***************************************************/
.include "../affichage.inc"
|
http://rosettacode.org/wiki/Loops/While | Loops/While | Task
Start an integer value at 1024.
Loop while it is greater than zero.
Print the value (with a newline) and divide it by two each time through the loop.
Related tasks
Loop over multiple arrays simultaneously
Loops/Break
Loops/Continue
Loops/Do-while
Loops/Downward for
Loops/For
Loops/For with a specified step
Loops/Foreachbas
Loops/Increment loop index within loop body
Loops/Infinite
Loops/N plus one half
Loops/Nested
Loops/While
Loops/with multiple ranges
Loops/Wrong ranges
| #0815 | 0815 | <:400:~}:_:%<:a:~$=<:2:=/^:_: |
http://rosettacode.org/wiki/Ludic_numbers | Ludic numbers | Ludic numbers are related to prime numbers as they are generated by a sieve quite like the Sieve of Eratosthenes is used to generate prime numbers.
The first ludic number is 1.
To generate succeeding ludic numbers create an array of increasing integers starting from 2.
2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 ...
(Loop)
Take the first member of the resultant array as the next ludic number 2.
Remove every 2nd indexed item from the array (including the first).
2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 ...
(Unrolling a few loops...)
Take the first member of the resultant array as the next ludic number 3.
Remove every 3rd indexed item from the array (including the first).
3 5 7 9 11 13 15 17 19 21 23 25 27 29 31 33 35 37 39 41 43 45 47 49 51 ...
Take the first member of the resultant array as the next ludic number 5.
Remove every 5th indexed item from the array (including the first).
5 7 11 13 17 19 23 25 29 31 35 37 41 43 47 49 53 55 59 61 65 67 71 73 77 ...
Take the first member of the resultant array as the next ludic number 7.
Remove every 7th indexed item from the array (including the first).
7 11 13 17 23 25 29 31 37 41 43 47 53 55 59 61 67 71 73 77 83 85 89 91 97 ...
...
Take the first member of the current array as the next ludic number L.
Remove every Lth indexed item from the array (including the first).
...
Task
Generate and show here the first 25 ludic numbers.
How many ludic numbers are there less than or equal to 1000?
Show the 2000..2005th ludic numbers.
Stretch goal
Show all triplets of ludic numbers < 250.
A triplet is any three numbers
x
,
{\displaystyle x,}
x
+
2
,
{\displaystyle x+2,}
x
+
6
{\displaystyle x+6}
where all three numbers are also ludic numbers.
| #Java | Java | import java.util.ArrayList;
import java.util.List;
public class Ludic{
public static List<Integer> ludicUpTo(int n){
List<Integer> ludics = new ArrayList<Integer>(n);
for(int i = 1; i <= n; i++){ //fill the initial list
ludics.add(i);
}
//start at index 1 because the first ludic number is 1 and we don't remove anything for it
for(int cursor = 1; cursor < ludics.size(); cursor++){
int thisLudic = ludics.get(cursor); //the first item in the list is a ludic number
int removeCursor = cursor + thisLudic; //start removing that many items later
while(removeCursor < ludics.size()){
ludics.remove(removeCursor); //remove the next item
removeCursor = removeCursor + thisLudic - 1; //move the removal cursor up as many spaces as we need to
//then back one to make up for the item we just removed
}
}
return ludics;
}
public static List<List<Integer>> getTriplets(List<Integer> ludics){
List<List<Integer>> triplets = new ArrayList<List<Integer>>();
for(int i = 0; i < ludics.size() - 2; i++){ //only need to check up to the third to last item
int thisLudic = ludics.get(i);
if(ludics.contains(thisLudic + 2) && ludics.contains(thisLudic + 6)){
List<Integer> triplet = new ArrayList<Integer>(3);
triplet.add(thisLudic);
triplet.add(thisLudic + 2);
triplet.add(thisLudic + 6);
triplets.add(triplet);
}
}
return triplets;
}
public static void main(String[] srgs){
System.out.println("First 25 Ludics: " + ludicUpTo(110)); //110 will get us 25 numbers
System.out.println("Ludics up to 1000: " + ludicUpTo(1000).size());
System.out.println("2000th - 2005th Ludics: " + ludicUpTo(22000).subList(1999, 2005)); //22000 will get us 2005 numbers
System.out.println("Triplets up to 250: " + getTriplets(ludicUpTo(250)));
}
} |
http://rosettacode.org/wiki/Loops/Wrong_ranges | Loops/Wrong ranges | Loops/Wrong ranges
You are encouraged to solve this task according to the task description, using any language you may know.
Some languages have syntax or function(s) to generate a range of numeric values from a start value, a stop value, and an increment.
The purpose of this task is to select the range syntax/function that would generate at least two increasing numbers when given a stop value more than the start value and a positive increment of less than half the difference. You are then to use that same syntax/function but with different parameters; and show, here, what would happen.
Use these values if possible:
start
stop
increment
Comment
-2
2
1
Normal
-2
2
0
Zero increment
-2
2
-1
Increments away from stop value
-2
2
10
First increment is beyond stop value
2
-2
1
Start more than stop: positive increment
2
2
1
Start equal stop: positive increment
2
2
-1
Start equal stop: negative increment
2
2
0
Start equal stop: zero increment
0
0
0
Start equal stop equal zero: zero increment
Related tasks
Loop over multiple arrays simultaneously
Loops/Break
Loops/Continue
Loops/Do-while
Loops/Downward for
Loops/For
Loops/For with a specified step
Loops/Foreach
Loops/Increment loop index within loop body
Loops/Infinite
Loops/N plus one half
Loops/Nested
Loops/While
Loops/with multiple ranges
Loops/Wrong ranges
| #Delphi | Delphi |
program Wrong_ranges;
{$APPTYPE CONSOLE}
uses
System.SysUtils;
procedure Example(start, stop, Increment: Integer; comment: string);
var
MAX_ITER, iteration, i: Integer;
begin
Write((comment + ' ').PadRight(50, '-') + ' ');
MAX_ITER := 9;
iteration := 0;
if Increment = 1 then
begin
for i := start to stop do
begin
Write(i: 2, ' ');
inc(iteration);
if iteration >= MAX_ITER then
Break;
end;
Writeln;
exit;
end;
if Increment = -1 then
begin
for i := start downto stop do
begin
Write(i: 2, ' ');
inc(iteration);
if iteration >= MAX_ITER then
Break;
end;
Writeln;
exit;
end;
Writeln('Not supported');
end;
begin
Example(-2, 2, 1, 'Normal');
Example(-2, 2, 0, 'Zero increment');
Example(-2, 2, -1, 'Increments away from stop value');
Example(-2, 2, 10, 'First increment is beyond stop value');
Example(2, -2, 1, 'Start more than stop: positive increment');
Example(2, 2, 1, 'Start equal stop: positive increment');
Example(2, 2, -1, 'Start equal stop: negative increment');
Example(2, 2, 0, 'Start equal stop: zero increment');
Example(0, 0, 0, 'Start equal stop equal zero: zero increment');
Readln;
end. |
http://rosettacode.org/wiki/Luhn_test_of_credit_card_numbers | Luhn test of credit card numbers | The Luhn test is used by some credit card companies to distinguish valid credit card numbers from what could be a random selection of digits.
Those companies using credit card numbers that can be validated by the Luhn test have numbers that pass the following test:
Reverse the order of the digits in the number.
Take the first, third, ... and every other odd digit in the reversed digits and sum them to form the partial sum s1
Taking the second, fourth ... and every other even digit in the reversed digits:
Multiply each digit by two and sum the digits if the answer is greater than nine to form partial sums for the even digits
Sum the partial sums of the even digits to form s2
If s1 + s2 ends in zero then the original number is in the form of a valid credit card number as verified by the Luhn test.
For example, if the trial number is 49927398716:
Reverse the digits:
61789372994
Sum the odd digits:
6 + 7 + 9 + 7 + 9 + 4 = 42 = s1
The even digits:
1, 8, 3, 2, 9
Two times each even digit:
2, 16, 6, 4, 18
Sum the digits of each multiplication:
2, 7, 6, 4, 9
Sum the last:
2 + 7 + 6 + 4 + 9 = 28 = s2
s1 + s2 = 70 which ends in zero which means that 49927398716 passes the Luhn test
Task
Write a function/method/procedure/subroutine that will validate a number with the Luhn test, and
use it to validate the following numbers:
49927398716
49927398717
1234567812345678
1234567812345670
Related tasks
SEDOL
ISIN
| #Ada | Ada | with Ada.Text_IO;
use Ada.Text_IO;
procedure Luhn is
function Luhn_Test (Number: String) return Boolean is
Sum : Natural := 0;
Odd : Boolean := True;
Digit: Natural range 0 .. 9;
begin
for p in reverse Number'Range loop
Digit := Integer'Value (Number (p..p));
if Odd then
Sum := Sum + Digit;
else
Sum := Sum + (Digit*2 mod 10) + (Digit / 5);
end if;
Odd := not Odd;
end loop;
return (Sum mod 10) = 0;
end Luhn_Test;
begin
Put_Line (Boolean'Image (Luhn_Test ("49927398716")));
Put_Line (Boolean'Image (Luhn_Test ("49927398717")));
Put_Line (Boolean'Image (Luhn_Test ("1234567812345678")));
Put_Line (Boolean'Image (Luhn_Test ("1234567812345670")));
end Luhn; |
http://rosettacode.org/wiki/Lucas-Lehmer_test | Lucas-Lehmer test | Lucas-Lehmer Test:
for
p
{\displaystyle p}
an odd prime, the Mersenne number
2
p
−
1
{\displaystyle 2^{p}-1}
is prime if and only if
2
p
−
1
{\displaystyle 2^{p}-1}
divides
S
(
p
−
1
)
{\displaystyle S(p-1)}
where
S
(
n
+
1
)
=
(
S
(
n
)
)
2
−
2
{\displaystyle S(n+1)=(S(n))^{2}-2}
, and
S
(
1
)
=
4
{\displaystyle S(1)=4}
.
Task
Calculate all Mersenne primes up to the implementation's
maximum precision, or the 47th Mersenne prime (whichever comes first).
| #Burlesque | Burlesque | 607rz2en{J4{J.*2.-2{th}c!**-..%}#R2.-E!n!it}f[2+]{2\/**-.}m[p^ |
http://rosettacode.org/wiki/Lucky_and_even_lucky_numbers | Lucky and even lucky numbers | Note that in the following explanation list indices are assumed to start at one.
Definition of lucky numbers
Lucky numbers are positive integers that are formed by:
Form a list of all the positive odd integers > 0
1
,
3
,
5
,
7
,
9
,
11
,
13
,
15
,
17
,
19
,
21
,
23
,
25
,
27
,
29
,
31
,
33
,
35
,
37
,
39...
{\displaystyle 1,3,5,7,9,11,13,15,17,19,21,23,25,27,29,31,33,35,37,39...}
Return the first number from the list (which is 1).
(Loop begins here)
Note then return the second number from the list (which is 3).
Discard every third, (as noted), number from the list to form the new list
1
,
3
,
7
,
9
,
13
,
15
,
19
,
21
,
25
,
27
,
31
,
33
,
37
,
39
,
43
,
45
,
49
,
51
,
55
,
57...
{\displaystyle 1,3,7,9,13,15,19,21,25,27,31,33,37,39,43,45,49,51,55,57...}
(Expanding the loop a few more times...)
Note then return the third number from the list (which is 7).
Discard every 7th, (as noted), number from the list to form the new list
1
,
3
,
7
,
9
,
13
,
15
,
21
,
25
,
27
,
31
,
33
,
37
,
43
,
45
,
49
,
51
,
55
,
57
,
63
,
67...
{\displaystyle 1,3,7,9,13,15,21,25,27,31,33,37,43,45,49,51,55,57,63,67...}
Note then return the 4th number from the list (which is 9).
Discard every 9th, (as noted), number from the list to form the new list
1
,
3
,
7
,
9
,
13
,
15
,
21
,
25
,
31
,
33
,
37
,
43
,
45
,
49
,
51
,
55
,
63
,
67
,
69
,
73...
{\displaystyle 1,3,7,9,13,15,21,25,31,33,37,43,45,49,51,55,63,67,69,73...}
Take the 5th, i.e. 13. Remove every 13th.
Take the 6th, i.e. 15. Remove every 15th.
Take the 7th, i.e. 21. Remove every 21th.
Take the 8th, i.e. 25. Remove every 25th.
(Rule for the loop)
Note the
n
{\displaystyle n}
th, which is
m
{\displaystyle m}
.
Remove every
m
{\displaystyle m}
th.
Increment
n
{\displaystyle n}
.
Definition of even lucky numbers
This follows the same rules as the definition of lucky numbers above except for the very first step:
Form a list of all the positive even integers > 0
2
,
4
,
6
,
8
,
10
,
12
,
14
,
16
,
18
,
20
,
22
,
24
,
26
,
28
,
30
,
32
,
34
,
36
,
38
,
40...
{\displaystyle 2,4,6,8,10,12,14,16,18,20,22,24,26,28,30,32,34,36,38,40...}
Return the first number from the list (which is 2).
(Loop begins here)
Note then return the second number from the list (which is 4).
Discard every 4th, (as noted), number from the list to form the new list
2
,
4
,
6
,
10
,
12
,
14
,
18
,
20
,
22
,
26
,
28
,
30
,
34
,
36
,
38
,
42
,
44
,
46
,
50
,
52...
{\displaystyle 2,4,6,10,12,14,18,20,22,26,28,30,34,36,38,42,44,46,50,52...}
(Expanding the loop a few more times...)
Note then return the third number from the list (which is 6).
Discard every 6th, (as noted), number from the list to form the new list
2
,
4
,
6
,
10
,
12
,
18
,
20
,
22
,
26
,
28
,
34
,
36
,
38
,
42
,
44
,
50
,
52
,
54
,
58
,
60...
{\displaystyle 2,4,6,10,12,18,20,22,26,28,34,36,38,42,44,50,52,54,58,60...}
Take the 4th, i.e. 10. Remove every 10th.
Take the 5th, i.e. 12. Remove every 12th.
(Rule for the loop)
Note the
n
{\displaystyle n}
th, which is
m
{\displaystyle m}
.
Remove every
m
{\displaystyle m}
th.
Increment
n
{\displaystyle n}
.
Task requirements
Write one or two subroutines (functions) to generate lucky numbers and even lucky numbers
Write a command-line interface to allow selection of which kind of numbers and which number(s). Since input is from the command line, tests should be made for the common errors:
missing arguments
too many arguments
number (or numbers) aren't legal
misspelled argument (lucky or evenLucky)
The command line handling should:
support mixed case handling of the (non-numeric) arguments
support printing a particular number
support printing a range of numbers by their index
support printing a range of numbers by their values
The resulting list of numbers should be printed on a single line.
The program should support the arguments:
what is displayed (on a single line)
argument(s) (optional verbiage is encouraged)
╔═══════════════════╦════════════════════════════════════════════════════╗
║ j ║ Jth lucky number ║
║ j , lucky ║ Jth lucky number ║
║ j , evenLucky ║ Jth even lucky number ║
║ ║ ║
║ j k ║ Jth through Kth (inclusive) lucky numbers ║
║ j k lucky ║ Jth through Kth (inclusive) lucky numbers ║
║ j k evenLucky ║ Jth through Kth (inclusive) even lucky numbers ║
║ ║ ║
║ j -k ║ all lucky numbers in the range j ──► |k| ║
║ j -k lucky ║ all lucky numbers in the range j ──► |k| ║
║ j -k evenLucky ║ all even lucky numbers in the range j ──► |k| ║
╚═══════════════════╩════════════════════════════════════════════════════╝
where |k| is the absolute value of k
Demonstrate the program by:
showing the first twenty lucky numbers
showing the first twenty even lucky numbers
showing all lucky numbers between 6,000 and 6,100 (inclusive)
showing all even lucky numbers in the same range as above
showing the 10,000th lucky number (extra credit)
showing the 10,000th even lucky number (extra credit)
See also
This task is related to the Sieve of Eratosthenes task.
OEIS Wiki Lucky numbers.
Sequence A000959 lucky numbers on The On-Line Encyclopedia of Integer Sequences.
Sequence A045954 even lucky numbers or ELN on The On-Line Encyclopedia of Integer Sequences.
Entry lucky numbers on The Eric Weisstein's World of Mathematics.
| #Julia | Julia | using Base, StringDistances
struct Lucky
start::Int
nmax::Int
Lucky(iseven, nmax) = new(iseven ? 2 : 1, nmax)
end
struct LuckyState
nextindex::Int
sequence::Vector{Int}
end
Base.eltype(iter::Lucky) = Int
function Base.iterate(iter::Lucky, state = LuckyState(1, collect(iter.start:2:iter.nmax)))
if length(state.sequence) < state.nextindex
return nothing
elseif state.nextindex == 1
return (iter.start, LuckyState(2, state.sequence))
end
result = state.sequence[state.nextindex]
newsequence = Vector{Int}()
for (i, el) in enumerate(state.sequence)
if i % result != 0
push!(newsequence, el)
end
end
(result, LuckyState(state.nextindex + 1, newsequence))
end
function luckyindex(j, wanteven, k=0)
topindex = max(j, k) + 4
luck = Lucky(wanteven, topindex * 20)
iter_result = iterate(luck)
while iter_result != nothing
(elem, state) = iter_result
iter_result = iterate(luck, state)
if iter_result != nothing && iter_result[2].nextindex > topindex
return iter_result[2].sequence[k > j ? (j:k) : j]
end
end
throw("Index $j out of range for nmax of $(luck.nmax).")
end
function luckyrange(j, k, wanteven)
topvalue = max(j, k)
luck = Lucky(wanteven, topvalue + 1)
iter_result = iterate(luck)
(elem, state) = iter_result # save next to last result
while iter_result != nothing
(elem, state) = iter_result
iter_result = iterate(luck, state)
end
filter(x -> (j <= x <= k), state.sequence)
end
function helpdisplay(exitlevel=1)
println("\n", PROGRAM_FILE, " j [-][k] [lucky|evenLucky]")
println("\tj: index wanted or a starting point (index or value)",
"\n\tk: optional ending point (index), \n\t-k: optional ending point (value)\n")
helpstring =
""" | Argument(s) | What is printed |
|--------------------------------------------------------------------------|
| j | jth lucky number (required argument) |
| j , lucky | jth lucky number |
| j , evenLucky | jth even lucky number |
| j k | jth through kth (inclusive) lucky numbers |
| j k lucky | jth through kth (inclusive) lucky numbers |
| j k evenLucky | jth through kth (inclusive) even lucky numbers |
| j -k | all lucky numbers in the value range [m, |k|] |
| j -k lucky | all lucky numbers in the value range [m, |k|] |
| j -k evenLucky | all even lucky numbers in the value range [m, |k|] |
|--------------------------------------------------------------------------|\n\n"""
println(helpstring)
exit(exitlevel)
end
function parsecommandline()
comma = false
evenLucky = false
range = false
j = k = 0
if length(ARGS) < 1
helpdisplay()
end
for (pos, arg) in enumerate(ARGS)
if pos == 1
j = tryparse(Int, arg)
if j == nothing
println("The first argument must be a positive integer.\n")
helpdisplay()
end
elseif pos == 2 || (pos == 3 && comma)
k = tryparse(Int, arg)
if k == nothing
k = 0
if arg == ","
comma = true
continue
elseif arg == "lucky"
continue
elseif arg == "evenLucky"
evenLucky = true
elseif compare(Hamming(), arg, "lucky") > 0.4 || compare(Hamming(), arg, "evenLucky") > 0.4
println("Did you misspell \"lucky\" or \"evenLucky\"? Check capitalization.\n")
helpdisplay()
else
helpdisplay()
end
elseif k < 0
k = -k
range = true
end
elseif pos == 3 || pos == 4 && comma
if arg == ","
comma = true
continue
elseif arg == "lucky"
continue
elseif arg == "evenLucky"
evenLucky = true
elseif compare(Hamming(), arg, "lucky") > 0.1 || compare(Hamming(), arg, "evenLucky") > 0.1
println("Did you misspell "\lucky\" or "\evenLucky\"?\n\n")
helpdisplay()
else
helpdisplay()
end
elseif arg == "lucky"
continue
elseif arg == "evenLucky"
evenLucky = true
else
println("Too many arguments.\n")
helpdisplay()
end
end
(j, k, evenLucky, range)
end
function runopts()
(j, k, evenLucky, range) = parsecommandline()
if j < 1 || (k != 0 && j >= k)
throw("Lucky number integer parameters out of range: $(typeof(j)), $j, $(typeof(k)), $k")
end
if range
println(luckyrange(j, k, evenLucky))
else
println(luckyindex(j, evenLucky, k))
end
end
runopts() |
http://rosettacode.org/wiki/Lucky_and_even_lucky_numbers | Lucky and even lucky numbers | Note that in the following explanation list indices are assumed to start at one.
Definition of lucky numbers
Lucky numbers are positive integers that are formed by:
Form a list of all the positive odd integers > 0
1
,
3
,
5
,
7
,
9
,
11
,
13
,
15
,
17
,
19
,
21
,
23
,
25
,
27
,
29
,
31
,
33
,
35
,
37
,
39...
{\displaystyle 1,3,5,7,9,11,13,15,17,19,21,23,25,27,29,31,33,35,37,39...}
Return the first number from the list (which is 1).
(Loop begins here)
Note then return the second number from the list (which is 3).
Discard every third, (as noted), number from the list to form the new list
1
,
3
,
7
,
9
,
13
,
15
,
19
,
21
,
25
,
27
,
31
,
33
,
37
,
39
,
43
,
45
,
49
,
51
,
55
,
57...
{\displaystyle 1,3,7,9,13,15,19,21,25,27,31,33,37,39,43,45,49,51,55,57...}
(Expanding the loop a few more times...)
Note then return the third number from the list (which is 7).
Discard every 7th, (as noted), number from the list to form the new list
1
,
3
,
7
,
9
,
13
,
15
,
21
,
25
,
27
,
31
,
33
,
37
,
43
,
45
,
49
,
51
,
55
,
57
,
63
,
67...
{\displaystyle 1,3,7,9,13,15,21,25,27,31,33,37,43,45,49,51,55,57,63,67...}
Note then return the 4th number from the list (which is 9).
Discard every 9th, (as noted), number from the list to form the new list
1
,
3
,
7
,
9
,
13
,
15
,
21
,
25
,
31
,
33
,
37
,
43
,
45
,
49
,
51
,
55
,
63
,
67
,
69
,
73...
{\displaystyle 1,3,7,9,13,15,21,25,31,33,37,43,45,49,51,55,63,67,69,73...}
Take the 5th, i.e. 13. Remove every 13th.
Take the 6th, i.e. 15. Remove every 15th.
Take the 7th, i.e. 21. Remove every 21th.
Take the 8th, i.e. 25. Remove every 25th.
(Rule for the loop)
Note the
n
{\displaystyle n}
th, which is
m
{\displaystyle m}
.
Remove every
m
{\displaystyle m}
th.
Increment
n
{\displaystyle n}
.
Definition of even lucky numbers
This follows the same rules as the definition of lucky numbers above except for the very first step:
Form a list of all the positive even integers > 0
2
,
4
,
6
,
8
,
10
,
12
,
14
,
16
,
18
,
20
,
22
,
24
,
26
,
28
,
30
,
32
,
34
,
36
,
38
,
40...
{\displaystyle 2,4,6,8,10,12,14,16,18,20,22,24,26,28,30,32,34,36,38,40...}
Return the first number from the list (which is 2).
(Loop begins here)
Note then return the second number from the list (which is 4).
Discard every 4th, (as noted), number from the list to form the new list
2
,
4
,
6
,
10
,
12
,
14
,
18
,
20
,
22
,
26
,
28
,
30
,
34
,
36
,
38
,
42
,
44
,
46
,
50
,
52...
{\displaystyle 2,4,6,10,12,14,18,20,22,26,28,30,34,36,38,42,44,46,50,52...}
(Expanding the loop a few more times...)
Note then return the third number from the list (which is 6).
Discard every 6th, (as noted), number from the list to form the new list
2
,
4
,
6
,
10
,
12
,
18
,
20
,
22
,
26
,
28
,
34
,
36
,
38
,
42
,
44
,
50
,
52
,
54
,
58
,
60...
{\displaystyle 2,4,6,10,12,18,20,22,26,28,34,36,38,42,44,50,52,54,58,60...}
Take the 4th, i.e. 10. Remove every 10th.
Take the 5th, i.e. 12. Remove every 12th.
(Rule for the loop)
Note the
n
{\displaystyle n}
th, which is
m
{\displaystyle m}
.
Remove every
m
{\displaystyle m}
th.
Increment
n
{\displaystyle n}
.
Task requirements
Write one or two subroutines (functions) to generate lucky numbers and even lucky numbers
Write a command-line interface to allow selection of which kind of numbers and which number(s). Since input is from the command line, tests should be made for the common errors:
missing arguments
too many arguments
number (or numbers) aren't legal
misspelled argument (lucky or evenLucky)
The command line handling should:
support mixed case handling of the (non-numeric) arguments
support printing a particular number
support printing a range of numbers by their index
support printing a range of numbers by their values
The resulting list of numbers should be printed on a single line.
The program should support the arguments:
what is displayed (on a single line)
argument(s) (optional verbiage is encouraged)
╔═══════════════════╦════════════════════════════════════════════════════╗
║ j ║ Jth lucky number ║
║ j , lucky ║ Jth lucky number ║
║ j , evenLucky ║ Jth even lucky number ║
║ ║ ║
║ j k ║ Jth through Kth (inclusive) lucky numbers ║
║ j k lucky ║ Jth through Kth (inclusive) lucky numbers ║
║ j k evenLucky ║ Jth through Kth (inclusive) even lucky numbers ║
║ ║ ║
║ j -k ║ all lucky numbers in the range j ──► |k| ║
║ j -k lucky ║ all lucky numbers in the range j ──► |k| ║
║ j -k evenLucky ║ all even lucky numbers in the range j ──► |k| ║
╚═══════════════════╩════════════════════════════════════════════════════╝
where |k| is the absolute value of k
Demonstrate the program by:
showing the first twenty lucky numbers
showing the first twenty even lucky numbers
showing all lucky numbers between 6,000 and 6,100 (inclusive)
showing all even lucky numbers in the same range as above
showing the 10,000th lucky number (extra credit)
showing the 10,000th even lucky number (extra credit)
See also
This task is related to the Sieve of Eratosthenes task.
OEIS Wiki Lucky numbers.
Sequence A000959 lucky numbers on The On-Line Encyclopedia of Integer Sequences.
Sequence A045954 even lucky numbers or ELN on The On-Line Encyclopedia of Integer Sequences.
Entry lucky numbers on The Eric Weisstein's World of Mathematics.
| #Kotlin | Kotlin | // version 1.1.51
typealias IAE = IllegalArgumentException
val luckyOdd = MutableList(100000) { it * 2 + 1 }
val luckyEven = MutableList(100000) { it * 2 + 2 }
fun filterLuckyOdd() {
var n = 2
while (n < luckyOdd.size) {
val m = luckyOdd[n - 1]
val end = (luckyOdd.size / m) * m - 1
for (j in end downTo m - 1 step m) luckyOdd.removeAt(j)
n++
}
}
fun filterLuckyEven() {
var n = 2
while (n < luckyEven.size) {
val m = luckyEven[n - 1]
val end = (luckyEven.size / m) * m - 1
for (j in end downTo m - 1 step m) luckyEven.removeAt(j)
n++
}
}
fun printSingle(j: Int, odd: Boolean) {
if (odd) {
if (j >= luckyOdd.size) throw IAE("Argument is too big")
println("Lucky number $j = ${luckyOdd[j - 1]}")
}
else {
if (j >= luckyEven.size) throw IAE("Argument is too big")
println("Lucky even number $j = ${luckyEven[j - 1]}")
}
}
fun printRange(j: Int, k: Int, odd: Boolean) {
if (odd) {
if (k >= luckyOdd.size) throw IAE("Argument is too big")
println("Lucky numbers $j to $k are:\n${luckyOdd.drop(j - 1).take(k - j + 1)}")
}
else {
if (k >= luckyEven.size) throw IAE("Argument is too big")
println("Lucky even numbers $j to $k are:\n${luckyEven.drop(j - 1).take(k - j + 1)}")
}
}
fun printBetween(j: Int, k: Int, odd: Boolean) {
val range = mutableListOf<Int>()
if (odd) {
val max = luckyOdd[luckyOdd.lastIndex]
if (j > max || k > max) {
throw IAE("At least one argument is too big")
}
for (num in luckyOdd) {
if (num < j) continue
if (num > k) break
range.add(num)
}
println("Lucky numbers between $j and $k are:\n$range")
}
else {
val max = luckyEven[luckyEven.lastIndex]
if (j > max || k > max) {
throw IAE("At least one argument is too big")
}
for (num in luckyEven) {
if (num < j) continue
if (num > k) break
range.add(num)
}
println("Lucky even numbers between $j and $k are:\n$range")
}
}
fun main(args: Array<String>) {
if (args.size !in 1..3) throw IAE("There must be between 1 and 3 command line arguments")
filterLuckyOdd()
filterLuckyEven()
val j = args[0].toIntOrNull()
if (j == null || j < 1) throw IAE("First argument must be a positive integer")
if (args.size == 1) { printSingle(j, true); return }
if (args.size == 2) {
val k = args[1].toIntOrNull()
if (k == null) throw IAE("Second argument must be an integer")
if (k >= 0) {
if (j > k) throw IAE("Second argument can't be less than first")
printRange(j, k, true)
}
else {
val l = -k
if (j > l) throw IAE("The second argument can't be less in absolute value than first")
printBetween(j, l, true)
}
return
}
var odd =
if (args[2].toLowerCase() == "lucky") true
else if (args[2].toLowerCase() == "evenlucky") false
else throw IAE("Third argument is invalid")
if (args[1] == ",") {
printSingle(j, odd)
return
}
val k = args[1].toIntOrNull()
if (k == null) throw IAE("Second argument must be an integer or a comma")
if (k >= 0) {
if (j > k) throw IAE("Second argument can't be less than first")
printRange(j, k, odd)
}
else {
val l = -k
if (j > l) throw IAE("The second argument can't be less in absolute value than first")
printBetween(j, l, odd)
}
} |
http://rosettacode.org/wiki/LZW_compression | LZW compression | The Lempel-Ziv-Welch (LZW) algorithm provides loss-less data compression.
You can read a complete description of it in the Wikipedia article on the subject. It was patented, but it entered the public domain in 2004.
| #Common_Lisp | Common Lisp | (declaim (ftype (function (vector vector &optional fixnum fixnum) vector)
vector-append))
(defun vector-append (old new &optional (start2 0) end2)
(declare (optimize (speed 3) (safety 0) (debug 0)))
(prog1 old
(let* ((old-fill (fill-pointer old))
(new-fill (+ old-fill (length new))))
(when (> new-fill (array-dimension old 0))
(adjust-array old (* 4 new-fill)))
(setf (fill-pointer old) new-fill)
(replace old new :start1 old-fill :start2 start2 :end2 end2))))
(declaim (ftype (function (vector t) vector) vector-append1))
(defun vector-append1 (old new)
(prog1 old
(let* ((old-fill (fill-pointer old))
(new-fill (1+ old-fill)))
(when (> new-fill (array-dimension old 0))
(adjust-array old (* 4 new-fill)))
(setf (fill-pointer old) new-fill)
(setf (aref old old-fill) new))))
(declaim (ftype (function (&optional t) vector) make-empty-vector))
(defun make-empty-vector (&optional (element-type t))
(make-array 0 :element-type element-type :fill-pointer 0 :adjustable t))
(declaim (ftype (function (t &optional t) vector) make-vector-with-elt))
(defun make-vector-with-elt (elt &optional (element-type t))
(make-array 1 :element-type element-type
:fill-pointer 1
:adjustable t
:initial-element elt))
(declaim (ftype (function (vector t) vector) vector-append1-new))
(defun vector-append1-new (old new)
(vector-append1 (vector-append (make-empty-vector 'octet) old)
new))
(declaim (ftype (function (vector vector) vector) vector-append-new))
(defun vector-append-new (old new)
(vector-append (vector-append (make-empty-vector 'octet) old)
new))
(deftype octet () '(unsigned-byte 8))
(declaim (ftype (function () hash-table) build-dictionary))
(defun build-dictionary ()
(let ((dictionary (make-hash-table :test #'equalp)))
(loop for i below 256
do (let ((vec (make-vector-with-elt i 'octet)))
(setf (gethash vec dictionary) vec)))
dictionary))
(declaim (ftype (function ((vector octet)) (vector octet))
lzw-compress-octets))
(defun lzw-compress-octets (octets)
(declare (optimize (speed 3) (safety 0) (debug 0)))
(loop with dictionary-size of-type fixnum = 256
with w = (make-empty-vector 'octet)
with result = (make-empty-vector 't)
with dictionary = (build-dictionary)
for c across octets
for wc = (vector-append1-new w c)
if (gethash wc dictionary) do (setq w wc)
else do
(vector-append result (gethash w dictionary))
(setf (gethash wc dictionary)
(make-vector-with-elt dictionary-size))
(incf dictionary-size)
(setq w (make-vector-with-elt c 'octet))
finally (unless (zerop (length (the (vector octet) w)))
(vector-append result (gethash w dictionary)))
(return result)))
(declaim (ftype (function (vector) (vector octet)) lzw-decompress))
(defun #1=lzw-decompress (octets)
(declare (optimize (speed 3) (safety 0) (debug 0)))
(when (zerop (length octets))
(return-from #1# (make-empty-vector 'octet)))
(loop with dictionary-size = 256
with dictionary = (build-dictionary)
with result = (make-vector-with-elt (aref octets 0) 'octet)
with w = (copy-seq result)
for i from 1 below (length octets)
for k = (make-vector-with-elt (aref octets i) 't)
for entry = (or (gethash k dictionary)
(if (equalp k dictionary-size)
(vector-append1-new w (aref w 0))
(error "bad compresed entry at pos ~S" i)))
do (vector-append result entry)
(setf (gethash (make-vector-with-elt dictionary-size) dictionary)
(vector-append1-new w (aref entry 0)))
(incf dictionary-size)
(setq w entry)
finally (return result)))
(defgeneric lzw-compress (datum)
(:method ((string string))
(lzw-compress (babel:string-to-octets string)))
(:method ((octets vector))
(lzw-compress-octets octets)))
(defun lzw-decompress-to-string (octets)
(babel:octets-to-string (lzw-decompress octets)))
(defun test (string)
(assert (equal #2=(lzw-decompress-to-string (lzw-compress string)) string) ()
"Can't compress ~S properly, got ~S instead" string #2#)
t) |
http://rosettacode.org/wiki/LU_decomposition | LU decomposition | Every square matrix
A
{\displaystyle A}
can be decomposed into a product of a lower triangular matrix
L
{\displaystyle L}
and a upper triangular matrix
U
{\displaystyle U}
,
as described in LU decomposition.
A
=
L
U
{\displaystyle A=LU}
It is a modified form of Gaussian elimination.
While the Cholesky decomposition only works for symmetric,
positive definite matrices, the more general LU decomposition
works for any square matrix.
There are several algorithms for calculating L and U.
To derive Crout's algorithm for a 3x3 example,
we have to solve the following system:
A
=
(
a
11
a
12
a
13
a
21
a
22
a
23
a
31
a
32
a
33
)
=
(
l
11
0
0
l
21
l
22
0
l
31
l
32
l
33
)
(
u
11
u
12
u
13
0
u
22
u
23
0
0
u
33
)
=
L
U
{\displaystyle A={\begin{pmatrix}a_{11}&a_{12}&a_{13}\\a_{21}&a_{22}&a_{23}\\a_{31}&a_{32}&a_{33}\\\end{pmatrix}}={\begin{pmatrix}l_{11}&0&0\\l_{21}&l_{22}&0\\l_{31}&l_{32}&l_{33}\\\end{pmatrix}}{\begin{pmatrix}u_{11}&u_{12}&u_{13}\\0&u_{22}&u_{23}\\0&0&u_{33}\end{pmatrix}}=LU}
We now would have to solve 9 equations with 12 unknowns. To make the system uniquely solvable, usually the diagonal elements of
L
{\displaystyle L}
are set to 1
l
11
=
1
{\displaystyle l_{11}=1}
l
22
=
1
{\displaystyle l_{22}=1}
l
33
=
1
{\displaystyle l_{33}=1}
so we get a solvable system of 9 unknowns and 9 equations.
A
=
(
a
11
a
12
a
13
a
21
a
22
a
23
a
31
a
32
a
33
)
=
(
1
0
0
l
21
1
0
l
31
l
32
1
)
(
u
11
u
12
u
13
0
u
22
u
23
0
0
u
33
)
=
(
u
11
u
12
u
13
u
11
l
21
u
12
l
21
+
u
22
u
13
l
21
+
u
23
u
11
l
31
u
12
l
31
+
u
22
l
32
u
13
l
31
+
u
23
l
32
+
u
33
)
=
L
U
{\displaystyle A={\begin{pmatrix}a_{11}&a_{12}&a_{13}\\a_{21}&a_{22}&a_{23}\\a_{31}&a_{32}&a_{33}\\\end{pmatrix}}={\begin{pmatrix}1&0&0\\l_{21}&1&0\\l_{31}&l_{32}&1\\\end{pmatrix}}{\begin{pmatrix}u_{11}&u_{12}&u_{13}\\0&u_{22}&u_{23}\\0&0&u_{33}\end{pmatrix}}={\begin{pmatrix}u_{11}&u_{12}&u_{13}\\u_{11}l_{21}&u_{12}l_{21}+u_{22}&u_{13}l_{21}+u_{23}\\u_{11}l_{31}&u_{12}l_{31}+u_{22}l_{32}&u_{13}l_{31}+u_{23}l_{32}+u_{33}\end{pmatrix}}=LU}
Solving for the other
l
{\displaystyle l}
and
u
{\displaystyle u}
, we get the following equations:
u
11
=
a
11
{\displaystyle u_{11}=a_{11}}
u
12
=
a
12
{\displaystyle u_{12}=a_{12}}
u
13
=
a
13
{\displaystyle u_{13}=a_{13}}
u
22
=
a
22
−
u
12
l
21
{\displaystyle u_{22}=a_{22}-u_{12}l_{21}}
u
23
=
a
23
−
u
13
l
21
{\displaystyle u_{23}=a_{23}-u_{13}l_{21}}
u
33
=
a
33
−
(
u
13
l
31
+
u
23
l
32
)
{\displaystyle u_{33}=a_{33}-(u_{13}l_{31}+u_{23}l_{32})}
and for
l
{\displaystyle l}
:
l
21
=
1
u
11
a
21
{\displaystyle l_{21}={\frac {1}{u_{11}}}a_{21}}
l
31
=
1
u
11
a
31
{\displaystyle l_{31}={\frac {1}{u_{11}}}a_{31}}
l
32
=
1
u
22
(
a
32
−
u
12
l
31
)
{\displaystyle l_{32}={\frac {1}{u_{22}}}(a_{32}-u_{12}l_{31})}
We see that there is a calculation pattern, which can be expressed as the following formulas, first for
U
{\displaystyle U}
u
i
j
=
a
i
j
−
∑
k
=
1
i
−
1
u
k
j
l
i
k
{\displaystyle u_{ij}=a_{ij}-\sum _{k=1}^{i-1}u_{kj}l_{ik}}
and then for
L
{\displaystyle L}
l
i
j
=
1
u
j
j
(
a
i
j
−
∑
k
=
1
j
−
1
u
k
j
l
i
k
)
{\displaystyle l_{ij}={\frac {1}{u_{jj}}}(a_{ij}-\sum _{k=1}^{j-1}u_{kj}l_{ik})}
We see in the second formula that to get the
l
i
j
{\displaystyle l_{ij}}
below the diagonal, we have to divide by the diagonal element (pivot)
u
j
j
{\displaystyle u_{jj}}
, so we get problems when
u
j
j
{\displaystyle u_{jj}}
is either 0 or very small, which leads to numerical instability.
The solution to this problem is pivoting
A
{\displaystyle A}
, which means rearranging the rows of
A
{\displaystyle A}
, prior to the
L
U
{\displaystyle LU}
decomposition, in a way that the largest element of each column gets onto the diagonal of
A
{\displaystyle A}
. Rearranging the rows means to multiply
A
{\displaystyle A}
by a permutation matrix
P
{\displaystyle P}
:
P
A
⇒
A
′
{\displaystyle PA\Rightarrow A'}
Example:
(
0
1
1
0
)
(
1
4
2
3
)
⇒
(
2
3
1
4
)
{\displaystyle {\begin{pmatrix}0&1\\1&0\end{pmatrix}}{\begin{pmatrix}1&4\\2&3\end{pmatrix}}\Rightarrow {\begin{pmatrix}2&3\\1&4\end{pmatrix}}}
The decomposition algorithm is then applied on the rearranged matrix so that
P
A
=
L
U
{\displaystyle PA=LU}
Task description
The task is to implement a routine which will take a square nxn matrix
A
{\displaystyle A}
and return a lower triangular matrix
L
{\displaystyle L}
, a upper triangular matrix
U
{\displaystyle U}
and a permutation matrix
P
{\displaystyle P}
,
so that the above equation is fulfilled.
You should then test it on the following two examples and include your output.
Example 1
A
1 3 5
2 4 7
1 1 0
L
1.00000 0.00000 0.00000
0.50000 1.00000 0.00000
0.50000 -1.00000 1.00000
U
2.00000 4.00000 7.00000
0.00000 1.00000 1.50000
0.00000 0.00000 -2.00000
P
0 1 0
1 0 0
0 0 1
Example 2
A
11 9 24 2
1 5 2 6
3 17 18 1
2 5 7 1
L
1.00000 0.00000 0.00000 0.00000
0.27273 1.00000 0.00000 0.00000
0.09091 0.28750 1.00000 0.00000
0.18182 0.23125 0.00360 1.00000
U
11.00000 9.00000 24.00000 2.00000
0.00000 14.54545 11.45455 0.45455
0.00000 0.00000 -3.47500 5.68750
0.00000 0.00000 0.00000 0.51079
P
1 0 0 0
0 0 1 0
0 1 0 0
0 0 0 1
| #Go | Go | package main
import "fmt"
type matrix [][]float64
func zero(n int) matrix {
r := make([][]float64, n)
a := make([]float64, n*n)
for i := range r {
r[i] = a[n*i : n*(i+1)]
}
return r
}
func eye(n int) matrix {
r := zero(n)
for i := range r {
r[i][i] = 1
}
return r
}
func (m matrix) print(label string) {
if label > "" {
fmt.Printf("%s:\n", label)
}
for _, r := range m {
for _, e := range r {
fmt.Printf(" %9.5f", e)
}
fmt.Println()
}
}
func (a matrix) pivotize() matrix {
p := eye(len(a))
for j, r := range a {
max := r[j]
row := j
for i := j; i < len(a); i++ {
if a[i][j] > max {
max = a[i][j]
row = i
}
}
if j != row {
// swap rows
p[j], p[row] = p[row], p[j]
}
}
return p
}
func (m1 matrix) mul(m2 matrix) matrix {
r := zero(len(m1))
for i, r1 := range m1 {
for j := range m2 {
for k := range m1 {
r[i][j] += r1[k] * m2[k][j]
}
}
}
return r
}
func (a matrix) lu() (l, u, p matrix) {
l = zero(len(a))
u = zero(len(a))
p = a.pivotize()
a = p.mul(a)
for j := range a {
l[j][j] = 1
for i := 0; i <= j; i++ {
sum := 0.
for k := 0; k < i; k++ {
sum += u[k][j] * l[i][k]
}
u[i][j] = a[i][j] - sum
}
for i := j; i < len(a); i++ {
sum := 0.
for k := 0; k < j; k++ {
sum += u[k][j] * l[i][k]
}
l[i][j] = (a[i][j] - sum) / u[j][j]
}
}
return
}
func main() {
showLU(matrix{
{1, 3, 5},
{2, 4, 7},
{1, 1, 0}})
showLU(matrix{
{11, 9, 24, 2},
{1, 5, 2, 6},
{3, 17, 18, 1},
{2, 5, 7, 1}})
}
func showLU(a matrix) {
a.print("\na")
l, u, p := a.lu()
l.print("l")
u.print("u")
p.print("p")
} |
http://rosettacode.org/wiki/Lychrel_numbers | Lychrel numbers | Take an integer n, greater than zero.
Form the next n of its series by reversing the digits of the current n and adding the result to the current n.
Stop when n becomes palindromic - i.e. the digits of n in reverse order == n.
The above recurrence relation when applied to most starting numbers n = 1, 2, ... terminates in a palindrome quite quickly.
Example
If n0 = 12 we get
12
12 + 21 = 33, a palindrome!
And if n0 = 55 we get
55
55 + 55 = 110
110 + 011 = 121, a palindrome!
Notice that the check for a palindrome happens after an addition.
Some starting numbers seem to go on forever; the recurrence relation for 196 has been calculated for millions of repetitions forming numbers with millions of digits, without forming a palindrome.
These numbers that do not end in a palindrome are called Lychrel numbers.
For the purposes of this task a Lychrel number is any starting number that does not form a palindrome within 500 (or more) iterations.
Seed and related Lychrel numbers
Any integer produced in the sequence of a Lychrel number is also a Lychrel number.
In general, any sequence from one Lychrel number might converge to join the sequence from a prior Lychrel number candidate; for example the sequences for the numbers 196 and then 689 begin:
196
196 + 691 = 887
887 + 788 = 1675
1675 + 5761 = 7436
7436 + 6347 = 13783
13783 + 38731 = 52514
52514 + 41525 = 94039
...
689
689 + 986 = 1675
1675 + 5761 = 7436
...
So we see that the sequence starting with 689 converges to, and continues with the same numbers as that for 196.
Because of this we can further split the Lychrel numbers into true Seed Lychrel number candidates, and Related numbers that produce no palindromes but have integers in their sequence seen as part of the sequence generated from a lower Lychrel number.
Task
Find the number of seed Lychrel number candidates and related numbers for n in the range 1..10000 inclusive. (With that iteration limit of 500).
Print the number of seed Lychrels found; the actual seed Lychrels; and just the number of relateds found.
Print any seed Lychrel or related number that is itself a palindrome.
Show all output here.
References
What's special about 196? Numberphile video.
A023108 Positive integers which apparently never result in a palindrome under repeated applications of the function f(x) = x + (x with digits reversed).
Status of the 196 conjecture? Mathoverflow.
| #Kotlin | Kotlin | // version 1.0.6
import java.math.BigInteger
const val ITERATIONS = 500
const val LIMIT = 10000
val bigLimit = BigInteger.valueOf(LIMIT.toLong())
// In the sieve, 0 = not Lychrel, 1 = Seed Lychrel, 2 = Related Lychrel
val lychrelSieve = IntArray(LIMIT + 1) // all zero by default
val seedLychrels = mutableListOf<Int>()
val relatedLychrels = mutableSetOf<BigInteger>()
fun isPalindrome(bi: BigInteger): Boolean {
val s = bi.toString()
return s == s.reversed()
}
fun lychrelTest(i: Int, seq: MutableList<BigInteger>){
if (i < 1) return
var bi = BigInteger.valueOf(i.toLong())
(1 .. ITERATIONS).forEach {
bi += BigInteger(bi.toString().reversed())
seq.add(bi)
if (isPalindrome(bi)) return
}
for (j in 0 until seq.size) {
if (seq[j] <= bigLimit) lychrelSieve[seq[j].toInt()] = 2
else break
}
val sizeBefore = relatedLychrels.size
relatedLychrels.addAll(seq) // if all of these can be added 'i' must be a seed Lychrel
if (relatedLychrels.size - sizeBefore == seq.size) {
seedLychrels.add(i)
lychrelSieve[i] = 1
}
else {
relatedLychrels.add(BigInteger.valueOf(i.toLong()))
lychrelSieve[i] = 2
}
}
fun main(args: Array<String>) {
val seq = mutableListOf<BigInteger>()
for (i in 1 .. LIMIT)
if (lychrelSieve[i] == 0) {
seq.clear()
lychrelTest(i, seq)
}
var related = lychrelSieve.count { it == 2 }
println("Lychrel numbers in the range [1, $LIMIT]")
println("Maximum iterations = $ITERATIONS")
println("\nThere are ${seedLychrels.size} seed Lychrel numbers, namely")
println(seedLychrels)
println("\nThere are also $related related Lychrel numbers in this range")
val palindromes = mutableListOf<Int>()
for (i in 1 .. LIMIT)
if (lychrelSieve[i] > 0 && isPalindrome(BigInteger.valueOf(i.toLong()))) palindromes.add(i)
println("\nThere are ${palindromes.size} palindromic Lychrel numbers, namely")
println(palindromes)
} |
http://rosettacode.org/wiki/Magic_8-ball | Magic 8-ball | Task
Create Magic 8-Ball.
See details at: Magic 8-Ball.
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
| #uBasic.2F4tH | uBasic/4tH | Push Dup("It is certain"), Dup("It is decidedly so"), Dup("Without a doubt")
Push Dup("Yes, definitely"), Dup("You may rely on it")
Push Dup("As I see it, yes"), Dup("Most likely"), Dup("Outlook good")
Push Dup("Signs point to yes"), Dup("Yes"), Dup("Reply hazy, try again")
Push Dup("Ask again later"), Dup("Better not tell you now")
Push Dup("Cannot predict now"), Dup("Concentrate and ask again")
Push Dup("Don't bet on it"), Dup("My reply is no"), Dup("My sources say no")
Push Dup("Outlook not so good"), Dup("Very doubtful")
' read the replies
For x = 0 to Used() - 1 : @(x) = Pop(): Next
Print "Please enter your question or a blank line to quit.\n"
' now show the prompt
Do
r = Ask("? : ") ' ask a question
Until Len(r)=0 ' check for empty line
Print Show(@(Rnd(x))) : Print ' show the reply
Loop |
http://rosettacode.org/wiki/Magic_8-ball | Magic 8-ball | Task
Create Magic 8-Ball.
See details at: Magic 8-Ball.
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
| #UNIX_Shell | UNIX Shell | #!/bin/bash
RESPONSES=("It is certain" "It is decidedly so" "Without a doubt"
"Yes definitely" "You may rely on it" "As I see it yes"
"Most likely" "Outlook good" "Signs point to yes" "Yes"
"Reply hazy try again" "Ask again later"
"Better not tell you now" "Cannot predict now"
"Concentrate and ask again" "Don't bet on it"
"My reply is no" "My sources say no" "Outlook not so good"
"Very doubtful")
printf "Welcome to 8 ball! Enter your questions using the prompt below to
find the answers you seek. Type 'quit' to exit.\n\n"
while true; do
read -p 'Enter Question: ' question
if [ "$question" == "quit" ]; then
exit 0
fi
response_index=$(($RANDOM % 20))
printf "Response: ${RESPONSES[response_index]}\n\n"
done |
http://rosettacode.org/wiki/Mad_Libs | Mad Libs |
This page uses content from Wikipedia. The original article was at Mad Libs. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance)
Mad Libs is a phrasal template word game where one player prompts another for a list of words to substitute for blanks in a story, usually with funny results.
Task;
Write a program to create a Mad Libs like story.
The program should read an arbitrary multiline story from input.
The story will be terminated with a blank line.
Then, find each replacement to be made within the story, ask the user for a word to replace it with, and make all the replacements.
Stop when there are none left and print the final story.
The input should be an arbitrary story in the form:
<name> went for a walk in the park. <he or she>
found a <noun>. <name> decided to take it home.
Given this example, it should then ask for a name, a he or she and a noun (<name> gets replaced both times with the same value).
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
| #Icon_and_Unicon | Icon and Unicon | procedure main()
ml := "<name> went for a walk in the park. There <he or she> _
found a <noun>. <name> decided to take it home." # sample
MadLib(ml) # run it
end
link strings
procedure MadLib(story)
write("Please provide words for the following:")
V := []
story ? while ( tab(upto('<')), put(V,tab(upto('>')+1)) )
every writes(v := !set(V)," : ") do
story := replace(story,v,read())
write("\nYour MadLib follows:\n",story)
end |
http://rosettacode.org/wiki/Loops/With_multiple_ranges | Loops/With multiple ranges | Loops/With multiple ranges
You are encouraged to solve this task according to the task description, using any language you may know.
Some languages allow multiple loop ranges, such as the PL/I example (snippet) below.
/* all variables are DECLARED as integers. */
prod= 1; /*start with a product of unity. */
sum= 0; /* " " " sum " zero. */
x= +5;
y= -5;
z= -2;
one= 1;
three= 3;
seven= 7;
/*(below) ** is exponentiation: 4**3=64 */
do j= -three to 3**3 by three ,
-seven to +seven by x ,
555 to 550 - y ,
22 to -28 by -three ,
1927 to 1939 ,
x to y by z ,
11**x to 11**x + one;
/* ABS(n) = absolute value*/
sum= sum + abs(j); /*add absolute value of J.*/
if abs(prod)<2**27 & j¬=0 then prod=prod*j; /*PROD is small enough & J*/
end; /*not 0, then multiply it.*/
/*SUM and PROD are used for verification of J incrementation.*/
display (' sum= ' || sum); /*display strings to term.*/
display ('prod= ' || prod); /* " " " " */
Task
Simulate/translate the above PL/I program snippet as best as possible in your
language, with particular emphasis on the do loop construct.
The do index must be incremented/decremented in the same order shown.
If feasible, add commas to the two output numbers (being displayed).
Show all output here.
A simple PL/I DO loop (incrementing or decrementing) has the construct of:
DO variable = start_expression {TO ending_expression] {BY increment_expression} ;
---or---
DO variable = start_expression {BY increment_expression} {TO ending_expression] ;
where it is understood that all expressions will have a value. The variable is normally a
scaler variable, but need not be (but for this task, all variables and expressions are declared
to be scaler integers). If the BY expression is omitted, a BY value of unity is used.
All expressions are evaluated before the DO loop is executed, and those values are used
throughout the DO loop execution (even though, for instance, the value of Z may be
changed within the DO loop. This isn't the case here for this task.
A multiple-range DO loop can be constructed by using a comma (,) to separate additional ranges
(the use of multiple TO and/or BY keywords). This is the construct used in this task.
There are other forms of DO loops in PL/I involving the WHILE clause, but those won't be
needed here. DO loops without a TO clause might need a WHILE clause or some other
means of exiting the loop (such as LEAVE, RETURN, SIGNAL, GOTO, or STOP), or some other
(possible error) condition that causes transfer of control outside the DO loop.
Also, in PL/I, the check if the DO loop index value is outside the range is made at the
"head" (start) of the DO loop, so it's possible that the DO loop isn't executed, but
that isn't the case for any of the ranges used in this task.
In the example above, the clause: x to y by z
will cause the variable J to have to following values (in this order): 5 3 1 -1 -3 -5
In the example above, the clause: -seven to +seven by x
will cause the variable J to have to following values (in this order): -7 -2 3
Related tasks
Loop over multiple arrays simultaneously
Loops/Break
Loops/Continue
Loops/Do-while
Loops/Downward for
Loops/For
Loops/For with a specified step
Loops/Foreach
Loops/Increment loop index within loop body
Loops/Infinite
Loops/N plus one half
Loops/Nested
Loops/While
Loops/with multiple ranges
Loops/Wrong ranges
| #AutoHotkey | AutoHotkey | for_J(doFunction, start, stop, step:=1){
j := start
while (j<=stop) && (start<=stop) && (step>0)
%doFunction%(j), j+=step
while (j>=stop) && (start>stop) && (step<0)
%doFunction%(j), j+=step
} |
http://rosettacode.org/wiki/Loops/While | Loops/While | Task
Start an integer value at 1024.
Loop while it is greater than zero.
Print the value (with a newline) and divide it by two each time through the loop.
Related tasks
Loop over multiple arrays simultaneously
Loops/Break
Loops/Continue
Loops/Do-while
Loops/Downward for
Loops/For
Loops/For with a specified step
Loops/Foreachbas
Loops/Increment loop index within loop body
Loops/Infinite
Loops/N plus one half
Loops/Nested
Loops/While
Loops/with multiple ranges
Loops/Wrong ranges
| #11l | 11l | V n = 1024
L n > 0
print(n)
n I/= 2 |
http://rosettacode.org/wiki/Loops/While | Loops/While | Task
Start an integer value at 1024.
Loop while it is greater than zero.
Print the value (with a newline) and divide it by two each time through the loop.
Related tasks
Loop over multiple arrays simultaneously
Loops/Break
Loops/Continue
Loops/Do-while
Loops/Downward for
Loops/For
Loops/For with a specified step
Loops/Foreachbas
Loops/Increment loop index within loop body
Loops/Infinite
Loops/N plus one half
Loops/Nested
Loops/While
Loops/with multiple ranges
Loops/Wrong ranges
| #360_Assembly | 360 Assembly | * While 27/06/2016
WHILELOO CSECT program's control section
USING WHILELOO,12 set base register
LR 12,15 load base register
LA 6,1024 v=1024
LOOP LTR 6,6 while v>0
BNP ENDLOOP .
CVD 6,PACKED convert v to packed decimal
OI PACKED+7,X'0F' prepare unpack
UNPK WTOTXT,PACKED packed decimal to zoned printable
WTO MF=(E,WTOMSG) display v
SRA 6,1 v=v/2 by right shift
B LOOP end while
ENDLOOP BR 14 return to caller
PACKED DS PL8 packed decimal
WTOMSG DS 0F full word alignment for wto
WTOLEN DC AL2(8),H'0' length of wto buffer (4+1)
WTOTXT DC CL4' ' wto text
END WHILELOO |
http://rosettacode.org/wiki/Ludic_numbers | Ludic numbers | Ludic numbers are related to prime numbers as they are generated by a sieve quite like the Sieve of Eratosthenes is used to generate prime numbers.
The first ludic number is 1.
To generate succeeding ludic numbers create an array of increasing integers starting from 2.
2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 ...
(Loop)
Take the first member of the resultant array as the next ludic number 2.
Remove every 2nd indexed item from the array (including the first).
2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 ...
(Unrolling a few loops...)
Take the first member of the resultant array as the next ludic number 3.
Remove every 3rd indexed item from the array (including the first).
3 5 7 9 11 13 15 17 19 21 23 25 27 29 31 33 35 37 39 41 43 45 47 49 51 ...
Take the first member of the resultant array as the next ludic number 5.
Remove every 5th indexed item from the array (including the first).
5 7 11 13 17 19 23 25 29 31 35 37 41 43 47 49 53 55 59 61 65 67 71 73 77 ...
Take the first member of the resultant array as the next ludic number 7.
Remove every 7th indexed item from the array (including the first).
7 11 13 17 23 25 29 31 37 41 43 47 53 55 59 61 67 71 73 77 83 85 89 91 97 ...
...
Take the first member of the current array as the next ludic number L.
Remove every Lth indexed item from the array (including the first).
...
Task
Generate and show here the first 25 ludic numbers.
How many ludic numbers are there less than or equal to 1000?
Show the 2000..2005th ludic numbers.
Stretch goal
Show all triplets of ludic numbers < 250.
A triplet is any three numbers
x
,
{\displaystyle x,}
x
+
2
,
{\displaystyle x+2,}
x
+
6
{\displaystyle x+6}
where all three numbers are also ludic numbers.
| #JavaScript | JavaScript | /**
* Boilerplate to simply get an array filled between 2 numbers
* @param {!number} s Start here (inclusive)
* @param {!number} e End here (inclusive)
*/
const makeArr = (s, e) => new Array(e + 1 - s).fill(s).map((e, i) => e + i);
/**
* Remove every n-th element from the given array
* @param {!Array} arr
* @param {!number} n
* @return {!Array}
*/
const filterAtInc = (arr, n) => arr.filter((e, i) => (i + 1) % n);
/**
* Generate ludic numbers
* @param {!Array} arr
* @param {!Array} result
* @return {!Array}
*/
const makeLudic = (arr, result) => {
const iter = arr.shift();
result.push(iter);
return arr.length ? makeLudic(filterAtInc(arr, iter), result) : result;
};
/**
* Our Ludic numbers. This is a bit of a cheat, as we already know beforehand
* up to where our seed array needs to go in order to exactly get to the
* 2005th Ludic number.
* @type {!Array<!number>}
*/
const ludicResult = makeLudic(makeArr(2, 21512), [1]);
// Below is just logging out the results.
/**
* Given a number, return a function that takes an array, and return the
* count of all elements smaller than the given
* @param {!number} n
* @return {!Function}
*/
const smallerThanN = n => arr => {
return arr.reduce((p,c) => {
return c <= n ? p + 1 : p
}, 0)
};
const smallerThan1K = smallerThanN(1000);
console.log('\nFirst 25 Ludic Numbers:');
console.log(ludicResult.filter((e, i) => i < 25).join(', '));
console.log('\nTotal Ludic numbers smaller than 1000:');
console.log(smallerThan1K(ludicResult));
console.log('\nThe 2000th to 2005th ludic numbers:');
console.log(ludicResult.filter((e, i) => i > 1998).join(', '));
console.log('\nTriplets smaller than 250:');
ludicResult.forEach(e => {
if (e + 6 < 250 && ludicResult.indexOf(e + 2) > 0 && ludicResult.indexOf(e + 6) > 0) {
console.log([e, e + 2, e + 6].join(', '));
}
}); |
http://rosettacode.org/wiki/Loops/Wrong_ranges | Loops/Wrong ranges | Loops/Wrong ranges
You are encouraged to solve this task according to the task description, using any language you may know.
Some languages have syntax or function(s) to generate a range of numeric values from a start value, a stop value, and an increment.
The purpose of this task is to select the range syntax/function that would generate at least two increasing numbers when given a stop value more than the start value and a positive increment of less than half the difference. You are then to use that same syntax/function but with different parameters; and show, here, what would happen.
Use these values if possible:
start
stop
increment
Comment
-2
2
1
Normal
-2
2
0
Zero increment
-2
2
-1
Increments away from stop value
-2
2
10
First increment is beyond stop value
2
-2
1
Start more than stop: positive increment
2
2
1
Start equal stop: positive increment
2
2
-1
Start equal stop: negative increment
2
2
0
Start equal stop: zero increment
0
0
0
Start equal stop equal zero: zero increment
Related tasks
Loop over multiple arrays simultaneously
Loops/Break
Loops/Continue
Loops/Do-while
Loops/Downward for
Loops/For
Loops/For with a specified step
Loops/Foreach
Loops/Increment loop index within loop body
Loops/Infinite
Loops/N plus one half
Loops/Nested
Loops/While
Loops/with multiple ranges
Loops/Wrong ranges
| #Eiffel | Eiffel |
example
-- Loops/Wrong ranges
do
⟳ ic:(-2 |..| 2) ¦ do_nothing ⟲ -- 2 2 1 Normal
⟳ ic:(-2 |..| 2).new_cursor + 0 ¦ do_nothing ⟲ -- -2 2 0 Zero increment
⟳ ic:(-2 |..| 2).new_cursor - 1 ¦ do_nothing ⟲ -- -2 2 -1 Increments away from stop value
⟳ ic:(-2 |..| 2).new_cursor + 10 ¦ do_nothing ⟲ -- -2 2 10 First increment is beyond stop value
⟳ ic:(-2 |..| 2).new_cursor.reversed ¦ do_nothing ⟲ -- 2 -2 1 Start more than stop: positive increment
⟳ ic:(2 |..| 2) ¦ do_nothing ⟲ -- 2 2 1 Start equal stop: positive increment
⟳ ic:(2 |..| 2).new_cursor - 1 ¦ do_nothing ⟲ -- 2 2 -1 Start equal stop: negative increment
⟳ ic:(2 |..| 2).new_cursor + 0 ¦ do_nothing ⟲ -- 2 2 0 Start equal stop: zero increment
⟳ ic:(0 |..| 0).new_cursor + 0 ¦ do_nothing ⟲ -- 0 0 0 Start equal stop equal zero: zero increment
end
|
http://rosettacode.org/wiki/Loops/Wrong_ranges | Loops/Wrong ranges | Loops/Wrong ranges
You are encouraged to solve this task according to the task description, using any language you may know.
Some languages have syntax or function(s) to generate a range of numeric values from a start value, a stop value, and an increment.
The purpose of this task is to select the range syntax/function that would generate at least two increasing numbers when given a stop value more than the start value and a positive increment of less than half the difference. You are then to use that same syntax/function but with different parameters; and show, here, what would happen.
Use these values if possible:
start
stop
increment
Comment
-2
2
1
Normal
-2
2
0
Zero increment
-2
2
-1
Increments away from stop value
-2
2
10
First increment is beyond stop value
2
-2
1
Start more than stop: positive increment
2
2
1
Start equal stop: positive increment
2
2
-1
Start equal stop: negative increment
2
2
0
Start equal stop: zero increment
0
0
0
Start equal stop equal zero: zero increment
Related tasks
Loop over multiple arrays simultaneously
Loops/Break
Loops/Continue
Loops/Do-while
Loops/Downward for
Loops/For
Loops/For with a specified step
Loops/Foreach
Loops/Increment loop index within loop body
Loops/Infinite
Loops/N plus one half
Loops/Nested
Loops/While
Loops/with multiple ranges
Loops/Wrong ranges
| #Factor | Factor | USING: continuations formatting io kernel math.ranges
prettyprint sequences ;
: try-range ( from length step -- )
[ <range> { } like . ]
[ 4drop "Exception: divide by zero." print ] recover ;
{
{ -2 2 1 } { 2 2 0 } { -2 2 -1 } { -2 2 10 } { 2 -2 1 }
{ 2 2 1 } { 2 2 -1 } { 2 2 0 } { 0 0 0 }
}
[
first3
[ "%2d %2d %2d <range> => " printf ]
[ try-range ] 3bi
] each |
http://rosettacode.org/wiki/Luhn_test_of_credit_card_numbers | Luhn test of credit card numbers | The Luhn test is used by some credit card companies to distinguish valid credit card numbers from what could be a random selection of digits.
Those companies using credit card numbers that can be validated by the Luhn test have numbers that pass the following test:
Reverse the order of the digits in the number.
Take the first, third, ... and every other odd digit in the reversed digits and sum them to form the partial sum s1
Taking the second, fourth ... and every other even digit in the reversed digits:
Multiply each digit by two and sum the digits if the answer is greater than nine to form partial sums for the even digits
Sum the partial sums of the even digits to form s2
If s1 + s2 ends in zero then the original number is in the form of a valid credit card number as verified by the Luhn test.
For example, if the trial number is 49927398716:
Reverse the digits:
61789372994
Sum the odd digits:
6 + 7 + 9 + 7 + 9 + 4 = 42 = s1
The even digits:
1, 8, 3, 2, 9
Two times each even digit:
2, 16, 6, 4, 18
Sum the digits of each multiplication:
2, 7, 6, 4, 9
Sum the last:
2 + 7 + 6 + 4 + 9 = 28 = s2
s1 + s2 = 70 which ends in zero which means that 49927398716 passes the Luhn test
Task
Write a function/method/procedure/subroutine that will validate a number with the Luhn test, and
use it to validate the following numbers:
49927398716
49927398717
1234567812345678
1234567812345670
Related tasks
SEDOL
ISIN
| #ALGOL_68 | ALGOL 68 | PROC to int = (CHAR c)INT:
ABS c - ABS "0";
PROC confirm = (STRING id)BOOL:
(
BOOL is odd digit := TRUE;
INT s := 0;
STRING cp;
FOR cp key FROM UPB id BY -1 TO LWB id DO
INT k := to int(id[cp key]);
s +:=
IF is odd digit THEN k
ELIF k /= 9 THEN 2*k MOD 9
ELSE 9
FI;
is odd digit := NOT is odd digit
OD;
0 = s MOD 10
);
main:
(
[]STRING t cases = (
"49927398716",
"49927398717",
"1234567812345678",
"1234567812345670"
);
FOR cp key TO UPB t cases DO
STRING cp = t cases[cp key];
print((cp, ": ", confirm(cp), new line))
OD
) |
http://rosettacode.org/wiki/Lucas-Lehmer_test | Lucas-Lehmer test | Lucas-Lehmer Test:
for
p
{\displaystyle p}
an odd prime, the Mersenne number
2
p
−
1
{\displaystyle 2^{p}-1}
is prime if and only if
2
p
−
1
{\displaystyle 2^{p}-1}
divides
S
(
p
−
1
)
{\displaystyle S(p-1)}
where
S
(
n
+
1
)
=
(
S
(
n
)
)
2
−
2
{\displaystyle S(n+1)=(S(n))^{2}-2}
, and
S
(
1
)
=
4
{\displaystyle S(1)=4}
.
Task
Calculate all Mersenne primes up to the implementation's
maximum precision, or the 47th Mersenne prime (whichever comes first).
| #C | C | #include <stdio.h>
#include <stdlib.h>
#include <limits.h>
#include <gmp.h>
int lucas_lehmer(unsigned long p)
{
mpz_t V, mp, t;
unsigned long k, tlim;
int res;
if (p == 2) return 1;
if (!(p&1)) return 0;
mpz_init_set_ui(t, p);
if (!mpz_probab_prime_p(t, 25)) /* if p is composite, 2^p-1 is not prime */
{ mpz_clear(t); return 0; }
if (p < 23) /* trust the PRP test for these values */
{ mpz_clear(t); return (p != 11); }
mpz_init(mp);
mpz_setbit(mp, p);
mpz_sub_ui(mp, mp, 1);
/* If p=3 mod 4 and p,2p+1 both prime, then 2p+1 | 2^p-1. Cheap test. */
if (p > 3 && p % 4 == 3) {
mpz_mul_ui(t, t, 2);
mpz_add_ui(t, t, 1);
if (mpz_probab_prime_p(t,25) && mpz_divisible_p(mp, t))
{ mpz_clear(mp); mpz_clear(t); return 0; }
}
/* Do a little trial division first. Saves quite a bit of time. */
tlim = p/2;
if (tlim > (ULONG_MAX/(2*p)))
tlim = ULONG_MAX/(2*p);
for (k = 1; k < tlim; k++) {
unsigned long q = 2*p*k+1;
/* factor must be 1 or 7 mod 8 and a prime */
if ( (q%8==1 || q%8==7) &&
q % 3 && q % 5 && q % 7 &&
mpz_divisible_ui_p(mp, q) )
{ mpz_clear(mp); mpz_clear(t); return 0; }
}
mpz_init_set_ui(V, 4);
for (k = 3; k <= p; k++) {
mpz_mul(V, V, V);
mpz_sub_ui(V, V, 2);
/* mpz_mod(V, V, mp) but more efficiently done given mod 2^p-1 */
if (mpz_sgn(V) < 0) mpz_add(V, V, mp);
/* while (n > mp) { n = (n >> p) + (n & mp) } if (n==mp) n=0 */
/* but in this case we can have at most one loop plus a carry */
mpz_tdiv_r_2exp(t, V, p);
mpz_tdiv_q_2exp(V, V, p);
mpz_add(V, V, t);
while (mpz_cmp(V, mp) >= 0) mpz_sub(V, V, mp);
}
res = !mpz_sgn(V);
mpz_clear(t); mpz_clear(mp); mpz_clear(V);
return res;
}
int main(int argc, char* argv[]) {
unsigned long i, n = 43112609;
if (argc >= 2) n = strtoul(argv[1], 0, 10);
for (i = 1; i <= n; i++) {
if (lucas_lehmer(i)) {
printf("M%lu ", i);
fflush(stdout);
}
}
printf("\n");
return 0;
} |
http://rosettacode.org/wiki/Lucky_and_even_lucky_numbers | Lucky and even lucky numbers | Note that in the following explanation list indices are assumed to start at one.
Definition of lucky numbers
Lucky numbers are positive integers that are formed by:
Form a list of all the positive odd integers > 0
1
,
3
,
5
,
7
,
9
,
11
,
13
,
15
,
17
,
19
,
21
,
23
,
25
,
27
,
29
,
31
,
33
,
35
,
37
,
39...
{\displaystyle 1,3,5,7,9,11,13,15,17,19,21,23,25,27,29,31,33,35,37,39...}
Return the first number from the list (which is 1).
(Loop begins here)
Note then return the second number from the list (which is 3).
Discard every third, (as noted), number from the list to form the new list
1
,
3
,
7
,
9
,
13
,
15
,
19
,
21
,
25
,
27
,
31
,
33
,
37
,
39
,
43
,
45
,
49
,
51
,
55
,
57...
{\displaystyle 1,3,7,9,13,15,19,21,25,27,31,33,37,39,43,45,49,51,55,57...}
(Expanding the loop a few more times...)
Note then return the third number from the list (which is 7).
Discard every 7th, (as noted), number from the list to form the new list
1
,
3
,
7
,
9
,
13
,
15
,
21
,
25
,
27
,
31
,
33
,
37
,
43
,
45
,
49
,
51
,
55
,
57
,
63
,
67...
{\displaystyle 1,3,7,9,13,15,21,25,27,31,33,37,43,45,49,51,55,57,63,67...}
Note then return the 4th number from the list (which is 9).
Discard every 9th, (as noted), number from the list to form the new list
1
,
3
,
7
,
9
,
13
,
15
,
21
,
25
,
31
,
33
,
37
,
43
,
45
,
49
,
51
,
55
,
63
,
67
,
69
,
73...
{\displaystyle 1,3,7,9,13,15,21,25,31,33,37,43,45,49,51,55,63,67,69,73...}
Take the 5th, i.e. 13. Remove every 13th.
Take the 6th, i.e. 15. Remove every 15th.
Take the 7th, i.e. 21. Remove every 21th.
Take the 8th, i.e. 25. Remove every 25th.
(Rule for the loop)
Note the
n
{\displaystyle n}
th, which is
m
{\displaystyle m}
.
Remove every
m
{\displaystyle m}
th.
Increment
n
{\displaystyle n}
.
Definition of even lucky numbers
This follows the same rules as the definition of lucky numbers above except for the very first step:
Form a list of all the positive even integers > 0
2
,
4
,
6
,
8
,
10
,
12
,
14
,
16
,
18
,
20
,
22
,
24
,
26
,
28
,
30
,
32
,
34
,
36
,
38
,
40...
{\displaystyle 2,4,6,8,10,12,14,16,18,20,22,24,26,28,30,32,34,36,38,40...}
Return the first number from the list (which is 2).
(Loop begins here)
Note then return the second number from the list (which is 4).
Discard every 4th, (as noted), number from the list to form the new list
2
,
4
,
6
,
10
,
12
,
14
,
18
,
20
,
22
,
26
,
28
,
30
,
34
,
36
,
38
,
42
,
44
,
46
,
50
,
52...
{\displaystyle 2,4,6,10,12,14,18,20,22,26,28,30,34,36,38,42,44,46,50,52...}
(Expanding the loop a few more times...)
Note then return the third number from the list (which is 6).
Discard every 6th, (as noted), number from the list to form the new list
2
,
4
,
6
,
10
,
12
,
18
,
20
,
22
,
26
,
28
,
34
,
36
,
38
,
42
,
44
,
50
,
52
,
54
,
58
,
60...
{\displaystyle 2,4,6,10,12,18,20,22,26,28,34,36,38,42,44,50,52,54,58,60...}
Take the 4th, i.e. 10. Remove every 10th.
Take the 5th, i.e. 12. Remove every 12th.
(Rule for the loop)
Note the
n
{\displaystyle n}
th, which is
m
{\displaystyle m}
.
Remove every
m
{\displaystyle m}
th.
Increment
n
{\displaystyle n}
.
Task requirements
Write one or two subroutines (functions) to generate lucky numbers and even lucky numbers
Write a command-line interface to allow selection of which kind of numbers and which number(s). Since input is from the command line, tests should be made for the common errors:
missing arguments
too many arguments
number (or numbers) aren't legal
misspelled argument (lucky or evenLucky)
The command line handling should:
support mixed case handling of the (non-numeric) arguments
support printing a particular number
support printing a range of numbers by their index
support printing a range of numbers by their values
The resulting list of numbers should be printed on a single line.
The program should support the arguments:
what is displayed (on a single line)
argument(s) (optional verbiage is encouraged)
╔═══════════════════╦════════════════════════════════════════════════════╗
║ j ║ Jth lucky number ║
║ j , lucky ║ Jth lucky number ║
║ j , evenLucky ║ Jth even lucky number ║
║ ║ ║
║ j k ║ Jth through Kth (inclusive) lucky numbers ║
║ j k lucky ║ Jth through Kth (inclusive) lucky numbers ║
║ j k evenLucky ║ Jth through Kth (inclusive) even lucky numbers ║
║ ║ ║
║ j -k ║ all lucky numbers in the range j ──► |k| ║
║ j -k lucky ║ all lucky numbers in the range j ──► |k| ║
║ j -k evenLucky ║ all even lucky numbers in the range j ──► |k| ║
╚═══════════════════╩════════════════════════════════════════════════════╝
where |k| is the absolute value of k
Demonstrate the program by:
showing the first twenty lucky numbers
showing the first twenty even lucky numbers
showing all lucky numbers between 6,000 and 6,100 (inclusive)
showing all even lucky numbers in the same range as above
showing the 10,000th lucky number (extra credit)
showing the 10,000th even lucky number (extra credit)
See also
This task is related to the Sieve of Eratosthenes task.
OEIS Wiki Lucky numbers.
Sequence A000959 lucky numbers on The On-Line Encyclopedia of Integer Sequences.
Sequence A045954 even lucky numbers or ELN on The On-Line Encyclopedia of Integer Sequences.
Entry lucky numbers on The Eric Weisstein's World of Mathematics.
| #Mathematica.2FWolfram_Language | Mathematica/Wolfram Language | ClearAll[GetLuckies, GetEvenLuckies]
GetLuckies[max_] := Module[{luckies, f, i},
luckies = Range[1, max, 2];
f[n_] := Block[{k = luckies[[n]]}, luckies = Delete[luckies, Table[{k}, {k, k, Length@luckies, k}]]];
i = 2;
While[i < Length[luckies],
f[i];
i++
];
luckies
]
GetEvenLuckies[max_] := Module[{lst, i, len},
lst = Range[2, max, 2];
i = 2;
While[i <= (len = Length@lst) && (k = lst[[i]]) <= len,
lst = Drop[lst, {k, len, k}];
i++
];
lst
]
GiveLucky[s_String] := GiveLucky[StringSplit[s, " "]]
GiveLucky[args_List] := Module[{argc = Length[args], j, k, type},
If[argc > 3,
Print["Too many arguments"]
,
If[argc == 0,
Print["Too few arguments"]
,
Switch[argc, 1,
j = Interpreter["Integer"][args[[1]]];
If[! FailureQ[j],
If[j > 0,
Print@GetLuckies[20 j][[j]]
,
Print["j should be positive"]
]
,
Print["one argument that is not an integer"]
]
, 2,
j = Interpreter["Integer"][args[[1]]];
k = Interpreter["Integer"][args[[2]]];
If[! FailureQ[j] \[And] ! FailureQ[k],
If[j > 0,
If[k > 0,
Print@GetLuckies[20 k][[j ;; k]]
,
Print@Select[GetLuckies[-k], GreaterEqualThan[j]]
]
,
Print["j should be positive"]
]
,
Print["one of the two arguments is not an integer\[Ellipsis]"]
]
, 3,
If[args[[2]] === ",",
j = Interpreter["Integer"][args[[1]]];
If[! FailureQ[j],
If[j > 0,
type = args[[3]];
If[MatchQ[type, "evenLucky" | "lucky"],
If[type === "evenLucky",
Print@GetEvenLuckies[20 j][[j]]
,
Print@GetLuckies[20 j][[j]]
]
,
Print["unknown type ", type]
]
,
Print["j should be positive"]
]
,
Print["j should be an integer"]
]
,
j = Interpreter["Integer"][args[[1]]];
k = Interpreter["Integer"][args[[2]]];
If[! FailureQ[j] \[And] ! FailureQ[k],
If[j > 0,
type = args[[3]];
If[k > 0,
If[MatchQ[type, "evenLucky" | "lucky"],
If[type === "evenLucky",
Print@GetEvenLuckies[20 k][[j ;; k]]
,
Print@GetLuckies[20 k][[j ;; k]]
]
,
Print["unknown type ", type]
]
,
If[MatchQ[type, "evenLucky" | "lucky"],
If[type === "evenLucky",
Print@Select[GetEvenLuckies[-k], GreaterEqualThan[j]]
,
Print@Select[GetLuckies[-k], GreaterEqualThan[j]]
]
,
Print["unknown type ", type]
]
]
,
Print["j should be positive"]
]
,
Print["one of the two arguments is not an integer\[Ellipsis]"]
]
]
]
]
]
]
GiveLucky[Last@$ScriptCommandLine] |
Subsets and Splits
Select Specific Languages Codes
Retrieves specific programming language names and codes from training data, providing basic filtering but limited analytical value beyond identifying these particular languages.