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/Pisano_period | Pisano period | The Fibonacci sequence taken modulo 2 is a periodic sequence of period 3 : 0, 1, 1, 0, 1, 1, ...
For any integer n, the Fibonacci sequence taken modulo n is periodic and the length of the periodic cycle is referred to as the Pisano period.
Prime numbers are straightforward; the Pisano period of a prime number p is simply: pisano(p). The Pisano period of a composite number c may be found in different ways. It may be calculated directly: pisano(c), which works, but may be time consuming to find, especially for larger integers, or, it may be calculated by finding the least common multiple of the Pisano periods of each composite component.
E.G.
Given a Pisano period function: pisano(x), and a least common multiple function lcm(x, y):
pisano(m × n) is equivalent to lcm(pisano(m), pisano(n)) where m and n are coprime
A formulae to calculate the pisano period for integer powers k of prime numbers p is:
pisano(pk) == p(k-1)pisano(p)
The equation is conjectured, no exceptions have been seen.
If a positive integer i is split into its prime factors, then the second and first equations above can be applied to generate the pisano period.
Task
Write 2 functions: pisanoPrime(p,k) and pisano(m).
pisanoPrime(p,k) should return the Pisano period of pk where p is prime and k is a positive integer.
pisano(m) should use pisanoPrime to return the Pisano period of m where m is a positive integer.
Print pisanoPrime(p,2) for every prime lower than 15.
Print pisanoPrime(p,1) for every prime lower than 180.
Print pisano(m) for every integer from 1 to 180.
Related tasks
Fibonacci sequence
Prime decomposition
Least common multiple
| #Go | Go | package main
import "fmt"
func gcd(a, b uint) uint {
if b == 0 {
return a
}
return gcd(b, a%b)
}
func lcm(a, b uint) uint {
return a / gcd(a, b) * b
}
func ipow(x, p uint) uint {
prod := uint(1)
for p > 0 {
if p&1 != 0 {
prod *= x
}
p >>= 1
x *= x
}
return prod
}
// Gets the prime decomposition of n.
func getPrimes(n uint) []uint {
var primes []uint
for i := uint(2); i <= n; i++ {
div := n / i
mod := n % i
for mod == 0 {
primes = append(primes, i)
n = div
div = n / i
mod = n % i
}
}
return primes
}
// OK for 'small' numbers.
func isPrime(n uint) bool {
switch {
case n < 2:
return false
case n%2 == 0:
return n == 2
case n%3 == 0:
return n == 3
default:
d := uint(5)
for d*d <= n {
if n%d == 0 {
return false
}
d += 2
if n%d == 0 {
return false
}
d += 4
}
return true
}
}
// Calculates the Pisano period of 'm' from first principles.
func pisanoPeriod(m uint) uint {
var p, c uint = 0, 1
for i := uint(0); i < m*m; i++ {
p, c = c, (p+c)%m
if p == 0 && c == 1 {
return i + 1
}
}
return 1
}
// Calculates the Pisano period of p^k where 'p' is prime and 'k' is a positive integer.
func pisanoPrime(p uint, k uint) uint {
if !isPrime(p) || k == 0 {
return 0 // can't do this one
}
return ipow(p, k-1) * pisanoPeriod(p)
}
// Calculates the Pisano period of 'm' using pisanoPrime.
func pisano(m uint) uint {
primes := getPrimes(m)
primePowers := make(map[uint]uint)
for _, p := range primes {
primePowers[p]++
}
var pps []uint
for k, v := range primePowers {
pps = append(pps, pisanoPrime(k, v))
}
if len(pps) == 0 {
return 1
}
if len(pps) == 1 {
return pps[0]
}
f := pps[0]
for i := 1; i < len(pps); i++ {
f = lcm(f, pps[i])
}
return f
}
func main() {
for p := uint(2); p < 15; p++ {
pp := pisanoPrime(p, 2)
if pp > 0 {
fmt.Printf("pisanoPrime(%2d: 2) = %d\n", p, pp)
}
}
fmt.Println()
for p := uint(2); p < 180; p++ {
pp := pisanoPrime(p, 1)
if pp > 0 {
fmt.Printf("pisanoPrime(%3d: 1) = %d\n", p, pp)
}
}
fmt.Println()
fmt.Println("pisano(n) for integers 'n' from 1 to 180 are:")
for n := uint(1); n <= 180; n++ {
fmt.Printf("%3d ", pisano(n))
if n != 1 && n%15 == 0 {
fmt.Println()
}
}
fmt.Println()
} |
http://rosettacode.org/wiki/Pinstripe/Display | Pinstripe/Display | Sample image
The task is to demonstrate the creation of a series of vertical pinstripes across the entire width of the display.
in the first quarter the pinstripes should alternate one pixel white, one pixel black = 1 pixel wide vertical pinestripes
Quarter of the way down the display, we can switch to a wider 2 pixel wide vertical pinstripe pattern, alternating two pixels white, two pixels black.
Half way down the display, we switch to 3 pixels wide,
for the lower quarter of the display we use 4 pixels.
c.f. Colour_pinstripe/Display
| #6502_Assembly | 6502 Assembly | define color $00
define looptemp $01
lda #1
sta color
loop_1wide:
lda color
and #$01
; this takes advantage of the fact that Easy6502 maps black to 0 and white to 1.
; Thus if we clear all but bit 0 the color will be either black or white, alternating infinitely regardless of the actual value
; of the color variable.
sta $0200,x
inc color
inx
bne loop_1wide
loop_2wide:
lda color
and #$01
sta $0300,x
inx
sta $0300,x
inc color
inx
bne loop_2wide
lda #1
sta color
lda #0
tax
tay
sta looptemp ;reset regs
loop_3wide:
lda color
and #$01
sta $0400,x
inc looptemp
inx
sta $0400,x
inc looptemp
inx
sta $0400,x
inc looptemp
inc color
inx
lda looptemp
cmp #$1e
bne loop_3wide
lda color ;loop overhead
and #$01
sta $0400,x ;can't fit all of this stripe.
;two columns will have to do.
inx
lda color
and #$01
sta $0400,x
inx
lda #1
sta color
lda #0
sta looptemp ;reset color and looptemp
iny
cpy #$08 ;check secondary loop counter
bne loop_3wide
lda #1
sta color
lda #0
tax
tay
sta looptemp
loop_4wide:
lda color
and #$01
sta $0500,x
inx
inc looptemp
sta $0500,x
inx
inc looptemp
sta $0500,x
inx
inc looptemp
sta $0500,x
inc color
inc looptemp
inx
lda looptemp
cmp #$20
bne loop_4wide
lda #0
sta looptemp
lda #1
sta color
iny
cpy #$8
bcc loop_4wide
brk ;program end |
http://rosettacode.org/wiki/Primality_by_trial_division | Primality by trial division | Task
Write a boolean function that tells whether a given integer is prime.
Remember that 1 and all non-positive numbers are not prime.
Use trial division.
Even numbers greater than 2 may be eliminated right away.
A loop from 3 to √ n will suffice, but other loops are allowed.
Related tasks
count in factors
prime decomposition
AKS test for primes
factors of an integer
Sieve of Eratosthenes
factors of a Mersenne number
trial factoring of a Mersenne number
partition an integer X into N primes
sequence of primes by Trial Division
| #Oforth | Oforth | Integer method: isPrime
| i |
self 1 <= ifTrue: [ false return ]
self 3 <= ifTrue: [ true return ]
self isEven ifTrue: [ false return ]
3 self sqrt asInteger for: i [ self i mod ifzero: [ false return ] ]
true ; |
http://rosettacode.org/wiki/Prime_decomposition | Prime decomposition | The prime decomposition of a number is defined as a list of prime numbers
which when all multiplied together, are equal to that number.
Example
12 = 2 × 2 × 3, so its prime decomposition is {2, 2, 3}
Task
Write a function which returns an array or collection which contains the prime decomposition of a given number
n
{\displaystyle n}
greater than 1.
If your language does not have an isPrime-like function available,
you may assume that you have a function which determines
whether a number is prime (note its name before your code).
If you would like to test code from this task, you may use code from trial division or the Sieve of Eratosthenes.
Note: The program must not be limited by the word size of your computer or some other artificial limit; it should work for any number regardless of size (ignoring the physical limits of RAM etc).
Related tasks
count in factors
factors of an integer
Sieve of Eratosthenes
primality by trial division
factors of a Mersenne number
trial factoring of a Mersenne number
partition an integer X into N primes
sequence of primes by Trial Division
| #Tcl | Tcl | proc factors {x} {
# list the prime factors of x in ascending order
set result [list]
while {$x % 2 == 0} {
lappend result 2
set x [expr {$x / 2}]
}
for {set i 3} {$i*$i <= $x} {incr i 2} {
while {$x % $i == 0} {
lappend result $i
set x [expr {$x / $i}]
}
}
if {$x != 1} {lappend result $x}
return $result
}
|
http://rosettacode.org/wiki/Play_recorded_sounds | Play recorded sounds | Load at least two prerecorded sounds, and demonstrate as many of these features as you can:
playing them individually and simultaneously
stopping before the end of the sound
looping (preferably glitch-free)
setting the volume of each sound
stereo or 3D positional mixing
performing other actions when marked times in the sound arrive
Describe:
The supported audio formats, briefly.
Whether it is suitable for game sound effects (low-latency start, resource efficiency, supports many simultaneous sounds, etc.)
Whether it is suitable for playing music (long duration ).
[Note: If it seems to be a good idea, this task may be revised to specify a particular timeline rather than just 'demonstrate these features'.]
Where applicable, please categorize examples primarily by the audio facility used (library/API/program/platform) rather than the language if the language is incidental (e.g. "Mac OS X CoreAudio" or "mplayer" rather than "C" or "bash").
| #Python | Python | import time
from pygame import mixer
mixer.init(frequency=16000) #set frequency for wav file
s1 = mixer.Sound('test.wav')
s2 = mixer.Sound('test2.wav')
#individual
s1.play(-1) #loops indefinitely
time.sleep(0.5)
#simultaneously
s2.play() #play once
time.sleep(2)
s2.play(2) #optional parameter loops three times
time.sleep(10)
#set volume down
s1.set_volume(0.1)
time.sleep(5)
#set volume up
s1.set_volume(1)
time.sleep(5)
s1.stop()
s2.stop()
mixer.quit() |
http://rosettacode.org/wiki/Pisano_period | Pisano period | The Fibonacci sequence taken modulo 2 is a periodic sequence of period 3 : 0, 1, 1, 0, 1, 1, ...
For any integer n, the Fibonacci sequence taken modulo n is periodic and the length of the periodic cycle is referred to as the Pisano period.
Prime numbers are straightforward; the Pisano period of a prime number p is simply: pisano(p). The Pisano period of a composite number c may be found in different ways. It may be calculated directly: pisano(c), which works, but may be time consuming to find, especially for larger integers, or, it may be calculated by finding the least common multiple of the Pisano periods of each composite component.
E.G.
Given a Pisano period function: pisano(x), and a least common multiple function lcm(x, y):
pisano(m × n) is equivalent to lcm(pisano(m), pisano(n)) where m and n are coprime
A formulae to calculate the pisano period for integer powers k of prime numbers p is:
pisano(pk) == p(k-1)pisano(p)
The equation is conjectured, no exceptions have been seen.
If a positive integer i is split into its prime factors, then the second and first equations above can be applied to generate the pisano period.
Task
Write 2 functions: pisanoPrime(p,k) and pisano(m).
pisanoPrime(p,k) should return the Pisano period of pk where p is prime and k is a positive integer.
pisano(m) should use pisanoPrime to return the Pisano period of m where m is a positive integer.
Print pisanoPrime(p,2) for every prime lower than 15.
Print pisanoPrime(p,1) for every prime lower than 180.
Print pisano(m) for every integer from 1 to 180.
Related tasks
Fibonacci sequence
Prime decomposition
Least common multiple
| #Haskell | Haskell | import qualified Data.Text as T
main = do
putStrLn "PisanoPrime(p,2) for prime p lower than 15"
putStrLn . see 15 . map (`pisanoPrime` 2) . filter isPrime $ [1 .. 15]
putStrLn "PisanoPrime(p,1) for prime p lower than 180"
putStrLn . see 15 . map (`pisanoPrime` 1) . filter isPrime $ [1 .. 180]
let ns = [1 .. 180] :: [Int]
let xs = map pisanoPeriod ns
let ys = map pisano ns
let zs = map pisanoConjecture ns
putStrLn "Pisano(m) for m from 1 to 180"
putStrLn . see 15 $ map pisano [1 .. 180]
putStrLn $
"map pisanoPeriod [1..180] == map pisano [1..180] = " ++ show (xs == ys)
putStrLn $
"map pisanoPeriod [1..180] == map pisanoConjecture [1..180] = " ++
show (ys == zs)
bagOf :: Int -> [a] -> [[a]]
bagOf _ [] = []
bagOf n xs =
let (us, vs) = splitAt n xs
in us : bagOf n vs
see
:: Show a
=> Int -> [a] -> String
see n =
unlines .
map unwords . bagOf n . map (T.unpack . T.justifyRight 3 ' ' . T.pack . show)
fibMod
:: Integral a
=> a -> [a]
fibMod 1 = repeat 0
fibMod n = fib
where
fib = 0 : 1 : zipWith (\x y -> rem (x + y) n) fib (tail fib)
pisanoPeriod
:: Integral a
=> a -> a
pisanoPeriod m
| m <= 0 = 0
pisanoPeriod 1 = 1
pisanoPeriod m = go 1 (tail $ fibMod m)
where
go t (0:1:_) = t
go t (_:xs) = go (succ t) xs
powMod
:: Integral a
=> a -> a -> a -> a
powMod _ _ k
| k < 0 = error "negative power"
powMod m _ _
| 1 == abs m = 0
powMod m p k
| 1 == abs p = mod v m
where
v
| 1 == p || even k = 1
| otherwise = p
powMod m p k = go p k
where
to x y = mod (x * y) m
go _ 0 = 1
go u 1 = mod u m
go u i
| even i = to w w
| otherwise = to u (to w w)
where
w = go u (quot i 2)
-- Fermat primality test
probablyPrime
:: Integral a
=> a -> Bool
probablyPrime p
| p < 2 || even p = 2 == p
| otherwise = 1 == powMod p 2 (p - 1)
primes
:: Integral a
=> [a]
primes =
2 :
3 :
5 :
7 :
[ p
| p <- [11,13 ..]
, isPrime p ]
limitDivisor
:: Integral a
=> a -> a
limitDivisor = floor . (+ 0.05) . sqrt . fromIntegral
isPrime
:: Integral a
=> a -> Bool
isPrime p
| not $ probablyPrime p = False
isPrime p = go primes
where
stop = limitDivisor p
go (n:_)
| stop < n = True
go (n:ns) = (0 /= rem p n) && go ns
go [] = True
factor
:: Integral a
=> a -> [(a, a)]
factor n
| n <= 1 = []
factor n = go n primes
where
fun x d c
| 0 /= rem x d = (x, c)
| otherwise = fun (quot x d) d (succ c)
go 1 _ = []
go _ [] = []
go x (d:ds)
| 0 /= rem x d = go x $ dropWhile ((0 /=) . rem x) ds
go x (d:ds) =
let (u, c) = fun (quot x d) d 1
in (d, c) : go u ds
pisanoPrime
:: Integral a
=> a -> a -> a
pisanoPrime p k
| p <= 0 || k < 0 = 0
pisanoPrime p k = pisanoPeriod $ p ^ k
pisano
:: Integral a
=> a -> a
pisano m
| m < 1 = 0
pisano 1 = 1
pisano m = foldl1 lcm . map (uncurry pisanoPrime) $ factor m
pisanoConjecture
:: Integral a
=> a -> a
pisanoConjecture m
| m < 1 = 0
pisanoConjecture 1 = 1
pisanoConjecture m = foldl1 lcm . map (uncurry pisanoPrime') $ factor m
where
pisanoPrime' p k = (p ^ (k - 1)) * pisanoPeriod p |
http://rosettacode.org/wiki/Pinstripe/Display | Pinstripe/Display | Sample image
The task is to demonstrate the creation of a series of vertical pinstripes across the entire width of the display.
in the first quarter the pinstripes should alternate one pixel white, one pixel black = 1 pixel wide vertical pinestripes
Quarter of the way down the display, we can switch to a wider 2 pixel wide vertical pinstripe pattern, alternating two pixels white, two pixels black.
Half way down the display, we switch to 3 pixels wide,
for the lower quarter of the display we use 4 pixels.
c.f. Colour_pinstripe/Display
| #8086_Assembly | 8086 Assembly | ;;; Display pinstripes on a PC, using 8086 assembly.
;;; The 640x200 CGA video mode is used. If you are on an MDA, the
;;; program does not run.
bits 16
cpu 8086
;;; IBM BIOS (INT 10h) calls
vmode: equ 0Fh ; Get current video mode
;;; Video modes
MDATXT: equ 7 ; MDA text mode (to check current mode against)
CGAHI: equ 6 ; CGA "high resolution" mode (640x200)
;;; Video memory
M_EVEN: equ 0B800h ; Video memory segment for even scanlines
M_ODD: equ 0BA00h ; Video memory segment for odd scanlines
section .text
org 100h
cld ; Make sure string instructions go forward
mov ah,vmode ; Get current video mode
int 10h
cmp al,MDATXT ; Are we in MDA text mode?
jne gr_ok
ret ; Then stop (no graphics support)
gr_ok: mov [oldmod],al ; otherwise, store old graphics mode,
mov ax,CGAHI ; and switch to hi-res CGA mode
int 10h
;;; There are 200 lines on the screen, but even and odd scanlines
;;; are stored separately. Because we're drawing vertical lines
;;; at a quarter of the screen, every odd scanline matches the
;;; even one before it. This means we really only need 100 lines,
;;; which means a quarter of the screen is 25 lines. There are
;;; 640 pixels per line, so each quarter consists of 16.000 pixels,
;;; or 2000 bytes, or 1000 words.
mov bp,1000 ; Keep a '1000' constant loaded
mov ax,M_EVEN ; Start with the even scan lines
mov dl,2 ; Let DL = 2 (we are doing the loop twice)
screen: mov es,ax ; Let ES be the video segment
xor di,di ; Start at the beginning
mov si,one ; Starting with pattern one
lodsw
mov cx,bp ; Write 1000 words of pattern one
rep stosw
lodsw
mov cx,bp ; Write 1000 words of pattern two
rep stosw
lodsb ; Pattern three is more complicated
xchg al,bl ; Let BL be the 3rd byte,
lodsw ; and AX be the first two.
mov bh,25 ; We need to write 25 lines,
quart3: mov cx,26 ; and every line we need to write 26*3 bytes
line3: stosw
xchg al,bl
stosb
xchg al,bl
loop line3
stosw ; Plus two final bytes per line
dec bh
jnz quart3
lodsw ; Finally, write 1000 words of pattern four
mov cx,bp
rep stosw
mov ax,M_ODD ; Then, do the odd scanlines
dec dl ; If we haven't already done them
jnz screen
;;; We are now done. Wait for a key, restore the old video mode,
;;; and exit.
xor ah,ah ; Wait for a key
int 16h
xor ah,ah ; Restore the old video mode
mov al,[oldmod]
int 10h
ret ; And exit
section .data
;;; Pattern data
one: dw 0AAAAh ; one on, one off pattern
two: dw 0CCCCh ; two on, two off pattern
three: db 38h ; three isn't divisible by 16
dw 8EE3h ; we need 24 bits for the pattern to repeat
four: dw 0F0F0h ; four on, four off pattern
section .bss
oldmod: resb 1 ; place to keep old video mode, in order to
; restore it. |
http://rosettacode.org/wiki/Primality_by_trial_division | Primality by trial division | Task
Write a boolean function that tells whether a given integer is prime.
Remember that 1 and all non-positive numbers are not prime.
Use trial division.
Even numbers greater than 2 may be eliminated right away.
A loop from 3 to √ n will suffice, but other loops are allowed.
Related tasks
count in factors
prime decomposition
AKS test for primes
factors of an integer
Sieve of Eratosthenes
factors of a Mersenne number
trial factoring of a Mersenne number
partition an integer X into N primes
sequence of primes by Trial Division
| #Ol | Ol |
(define (prime? number)
(define max (sqrt number))
(define (loop divisor)
(or (> divisor max)
(and (> (modulo number divisor) 0)
(loop (+ divisor 2)))))
(or (= number 1)
(= number 2)
(and
(> (modulo number 2) 0)
(loop 3))))
|
http://rosettacode.org/wiki/Prime_decomposition | Prime decomposition | The prime decomposition of a number is defined as a list of prime numbers
which when all multiplied together, are equal to that number.
Example
12 = 2 × 2 × 3, so its prime decomposition is {2, 2, 3}
Task
Write a function which returns an array or collection which contains the prime decomposition of a given number
n
{\displaystyle n}
greater than 1.
If your language does not have an isPrime-like function available,
you may assume that you have a function which determines
whether a number is prime (note its name before your code).
If you would like to test code from this task, you may use code from trial division or the Sieve of Eratosthenes.
Note: The program must not be limited by the word size of your computer or some other artificial limit; it should work for any number regardless of size (ignoring the physical limits of RAM etc).
Related tasks
count in factors
factors of an integer
Sieve of Eratosthenes
primality by trial division
factors of a Mersenne number
trial factoring of a Mersenne number
partition an integer X into N primes
sequence of primes by Trial Division
| #TI-83_BASIC | TI-83 BASIC | ::prgmPREMIER
Disp "FACTEURS PREMIER"
Prompt N
If N<1:Stop
ClrList L1�,L2
0→K
iPart(√(N))→L
N→M
For(I,2,L)
0→J
While fPart(M/I)=0
J+1→J
M/I→M
End
If J≠0
Then
K+1→K
I→L�1(K)
J→L2(K)
I→Z:prgmVSTR
" "+Str0→Str1
If J≠1
Then
J→Z:prgmVSTR
Str1+"^"+Str0→Str1
End
Disp Str1
End
If M=1:Stop
End
If M≠1
Then
If M≠N
Then
M→Z:prgmVSTR
" "+Str0→Str1
Disp Str1
Else
Disp "PREMIER"
End
End
::prgmVSTR
{Z,Z}→L5
{1,2}→L6
LinReg(ax+b)L6,L5,Y�₀
Equ►String(Y₀,Str0)
length(Str0)→O
sub(Str0,4,O-3)→Str0
ClrList L5,L6
DelVar Y� |
http://rosettacode.org/wiki/Play_recorded_sounds | Play recorded sounds | Load at least two prerecorded sounds, and demonstrate as many of these features as you can:
playing them individually and simultaneously
stopping before the end of the sound
looping (preferably glitch-free)
setting the volume of each sound
stereo or 3D positional mixing
performing other actions when marked times in the sound arrive
Describe:
The supported audio formats, briefly.
Whether it is suitable for game sound effects (low-latency start, resource efficiency, supports many simultaneous sounds, etc.)
Whether it is suitable for playing music (long duration ).
[Note: If it seems to be a good idea, this task may be revised to specify a particular timeline rather than just 'demonstrate these features'.]
Where applicable, please categorize examples primarily by the audio facility used (library/API/program/platform) rather than the language if the language is incidental (e.g. "Mac OS X CoreAudio" or "mplayer" rather than "C" or "bash").
| #R | R |
#Setup
# Warning: The example files are Windows specific.
library(sound)
media_dir <- file.path(Sys.getenv("SYSTEMROOT"), "Media")
chimes <- loadSample(file.path(media_dir, "chimes.wav"))
chord <- loadSample(file.path(media_dir, "chord.wav"))
# Play sequentially
play(appendSample(chimes, chord))
# Play simultaneously
play(chimes + chord)
# Stopping before the end
play(cutSample(chimes, 0, 0.2))
#Looping
for(i in 1:3) play(chimes) #leaves a gap between instances
three_chimes <- lapply(vector(3, mode = "list"), function(x) chimes)
play(do.call(appendSample, three_chimes)) #no gap, see also cutSampleEnds
# Volume control
play(3 * chimes)
#Stereo effect
play(stereo(chimes, chord))
#Other actions (not obviously possible)
|
http://rosettacode.org/wiki/Play_recorded_sounds | Play recorded sounds | Load at least two prerecorded sounds, and demonstrate as many of these features as you can:
playing them individually and simultaneously
stopping before the end of the sound
looping (preferably glitch-free)
setting the volume of each sound
stereo or 3D positional mixing
performing other actions when marked times in the sound arrive
Describe:
The supported audio formats, briefly.
Whether it is suitable for game sound effects (low-latency start, resource efficiency, supports many simultaneous sounds, etc.)
Whether it is suitable for playing music (long duration ).
[Note: If it seems to be a good idea, this task may be revised to specify a particular timeline rather than just 'demonstrate these features'.]
Where applicable, please categorize examples primarily by the audio facility used (library/API/program/platform) rather than the language if the language is incidental (e.g. "Mac OS X CoreAudio" or "mplayer" rather than "C" or "bash").
| #Racket | Racket |
#lang racket/gui
(play-sound "some-sound.wav" #f)
|
http://rosettacode.org/wiki/Play_recorded_sounds | Play recorded sounds | Load at least two prerecorded sounds, and demonstrate as many of these features as you can:
playing them individually and simultaneously
stopping before the end of the sound
looping (preferably glitch-free)
setting the volume of each sound
stereo or 3D positional mixing
performing other actions when marked times in the sound arrive
Describe:
The supported audio formats, briefly.
Whether it is suitable for game sound effects (low-latency start, resource efficiency, supports many simultaneous sounds, etc.)
Whether it is suitable for playing music (long duration ).
[Note: If it seems to be a good idea, this task may be revised to specify a particular timeline rather than just 'demonstrate these features'.]
Where applicable, please categorize examples primarily by the audio facility used (library/API/program/platform) rather than the language if the language is incidental (e.g. "Mac OS X CoreAudio" or "mplayer" rather than "C" or "bash").
| #Ring | Ring |
Load "guilib.ring"
new qapp {
q1=NULL q2=NULL
win1 = new qwidget() {
setwindowtitle("play sound!") show()
setgeometry(100,100,400,400)
}
new qpushbutton(win1) {
setgeometry(50,50,100,30)
settext("play1")
setclickevent("playmusic1()")
show()
}
new qpushbutton(win1) {
setgeometry(200,50,100,30)
settext("play2")
setclickevent("playmusic2()")
show()
}
new qpushbutton(win1) {
setgeometry(50,100,100,30)
settext("pause1")
setclickevent("pauseplay1()")
show()
}
new qpushbutton(win1) {
setgeometry(200,100,100,30)
settext("pause2")
setclickevent("pauseplay2()")
show()
}
new qpushbutton(win1) {
setgeometry(50,150,100,30)
settext("stop1")
setclickevent("stopplay1()")
show()
}
new qpushbutton(win1) {
setgeometry(200,150,100,30)
settext("stop2")
setclickevent("stopplay2()")
show()
}
lineedit1 = new qlineedit(win1) {
setGeometry(50,200,100,30)
settext("50")
show()
}
lineedit2 = new qlineedit(win1) {
setGeometry(200,200,100,30)
settext("50")
show()
}
new qpushbutton(win1) {
setgeometry(50,250,100,30)
settext("volume1")
setclickevent("volume1()")
show()
}
new qpushbutton(win1) {
setgeometry(200,250,100,30)
settext("volume2")
setclickevent("volume2()")
show()
}
new qpushbutton(win1) {
setgeometry(50,300,100,30)
settext("mute1")
setclickevent("mute1()")
show()
}
new qpushbutton(win1) {
setgeometry(200,300,100,30)
settext("mute2")
setclickevent("mute2()")
show()
}
exec()
}
func playmusic1
q1 = new qmediaplayer(win1) {
setmedia(new qurl("music1.wav"))
setvolume(50) play()
}
func playmusic2
q2 = new qmediaplayer(win1) {
setmedia(new qurl("music2.wav"))
setvolume(50) play()
}
func pauseplay1
q1.pause()
func pauseplay2
q2.pause()
func stopplay1
q1.stop()
func stopplay2
q2.stop()
func volume1
lineedit1 { vol1 = text() }
q1 {setvolume(number(vol1))}
func volume2
lineedit2 { vol2 = text() }
q2 {setvolume(number(vol2))}
func mute1
q1.setmuted(true)
func mute2
q2.setmuted(true)
|
http://rosettacode.org/wiki/Play_recorded_sounds | Play recorded sounds | Load at least two prerecorded sounds, and demonstrate as many of these features as you can:
playing them individually and simultaneously
stopping before the end of the sound
looping (preferably glitch-free)
setting the volume of each sound
stereo or 3D positional mixing
performing other actions when marked times in the sound arrive
Describe:
The supported audio formats, briefly.
Whether it is suitable for game sound effects (low-latency start, resource efficiency, supports many simultaneous sounds, etc.)
Whether it is suitable for playing music (long duration ).
[Note: If it seems to be a good idea, this task may be revised to specify a particular timeline rather than just 'demonstrate these features'.]
Where applicable, please categorize examples primarily by the audio facility used (library/API/program/platform) rather than the language if the language is incidental (e.g. "Mac OS X CoreAudio" or "mplayer" rather than "C" or "bash").
| #Ruby | Ruby | require 'win32/sound'
include Win32
sound1 = ENV['WINDIR'] + '\Media\Windows XP Startup.wav'
sound2 = ENV['WINDIR'] + '\Media\Windows XP Shutdown.wav'
puts "play the sounds sequentially"
[sound1, sound2].each do |s|
t1 = Time.now
Sound.play(s)
puts "'#{s}' duration: #{(Time.now.to_f - t1.to_f)} seconds"
end
puts "attempt to play the sounds simultaneously"
[sound1, sound2].each {|s| Sound.play(s, Sound::ASYNC)}
puts <<END
the above only plays the second sound2 because the library only appears
to be able to play one sound at a time.
END
puts "loop a sound for a few seconds"
puts Time.now
Sound.play(sound1, Sound::ASYNC + Sound::LOOP)
sleep 10
Sound.stop
puts Time.now
puts "manipulate the volume"
vol_left, vol_right = Sound.wave_volume
Sound.play(sound1, Sound::ASYNC)
sleep 1
puts "right channel quiet"
Sound.set_wave_volume(vol_left, 0)
sleep 1
puts "left channel quiet"
Sound.set_wave_volume(0, vol_right)
sleep 1
puts "restore volume"
Sound.set_wave_volume(vol_left, vol_right)
sleep 1
puts "the asynchronous sound is cancelled when the program exits" |
http://rosettacode.org/wiki/Pisano_period | Pisano period | The Fibonacci sequence taken modulo 2 is a periodic sequence of period 3 : 0, 1, 1, 0, 1, 1, ...
For any integer n, the Fibonacci sequence taken modulo n is periodic and the length of the periodic cycle is referred to as the Pisano period.
Prime numbers are straightforward; the Pisano period of a prime number p is simply: pisano(p). The Pisano period of a composite number c may be found in different ways. It may be calculated directly: pisano(c), which works, but may be time consuming to find, especially for larger integers, or, it may be calculated by finding the least common multiple of the Pisano periods of each composite component.
E.G.
Given a Pisano period function: pisano(x), and a least common multiple function lcm(x, y):
pisano(m × n) is equivalent to lcm(pisano(m), pisano(n)) where m and n are coprime
A formulae to calculate the pisano period for integer powers k of prime numbers p is:
pisano(pk) == p(k-1)pisano(p)
The equation is conjectured, no exceptions have been seen.
If a positive integer i is split into its prime factors, then the second and first equations above can be applied to generate the pisano period.
Task
Write 2 functions: pisanoPrime(p,k) and pisano(m).
pisanoPrime(p,k) should return the Pisano period of pk where p is prime and k is a positive integer.
pisano(m) should use pisanoPrime to return the Pisano period of m where m is a positive integer.
Print pisanoPrime(p,2) for every prime lower than 15.
Print pisanoPrime(p,1) for every prime lower than 180.
Print pisano(m) for every integer from 1 to 180.
Related tasks
Fibonacci sequence
Prime decomposition
Least common multiple
| #Java | Java |
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;
public class PisanoPeriod {
public static void main(String[] args) {
System.out.printf("Print pisano(p^2) for every prime p lower than 15%n");
for ( long i = 2 ; i < 15 ; i++ ) {
if ( isPrime(i) ) {
long n = i*i;
System.out.printf("pisano(%d) = %d%n", n, pisano(n));
}
}
System.out.printf("%nPrint pisano(p) for every prime p lower than 180%n");
for ( long n = 2 ; n < 180 ; n++ ) {
if ( isPrime(n) ) {
System.out.printf("pisano(%d) = %d%n", n, pisano(n));
}
}
System.out.printf("%nPrint pisano(n) for every integer from 1 to 180%n");
for ( long n = 1 ; n <= 180 ; n++ ) {
System.out.printf("%3d ", pisano(n));
if ( n % 10 == 0 ) {
System.out.printf("%n");
}
}
}
private static final boolean isPrime(long test) {
if ( test == 2 ) {
return true;
}
if ( test % 2 == 0 ) {
return false;
}
for ( long i = 3 ; i <= Math.sqrt(test) ; i += 2 ) {
if ( test % i == 0 ) {
return false;
}
}
return true;
}
private static Map<Long,Long> PERIOD_MEMO = new HashMap<>();
static {
PERIOD_MEMO.put(2L, 3L);
PERIOD_MEMO.put(3L, 8L);
PERIOD_MEMO.put(5L, 20L);
}
// See http://webspace.ship.edu/msrenault/fibonacci/fib.htm
private static long pisano(long n) {
if ( PERIOD_MEMO.containsKey(n) ) {
return PERIOD_MEMO.get(n);
}
if ( n == 1 ) {
return 1;
}
Map<Long,Long> factors = getFactors(n);
// Special cases
// pisano(2^k) = 3*n/2
if ( factors.size() == 1 & factors.get(2L) != null && factors.get(2L) > 0 ) {
long result = 3 * n / 2;
PERIOD_MEMO.put(n, result);
return result;
}
// pisano(5^k) = 4*n
if ( factors.size() == 1 & factors.get(5L) != null && factors.get(5L) > 0 ) {
long result = 4*n;
PERIOD_MEMO.put(n, result);
return result;
}
// pisano(2*5^k) = 6*n
if ( factors.size() == 2 & factors.get(2L) != null && factors.get(2L) == 1 && factors.get(5L) != null && factors.get(5L) > 0 ) {
long result = 6*n;
PERIOD_MEMO.put(n, result);
return result;
}
List<Long> primes = new ArrayList<>(factors.keySet());
long prime = primes.get(0);
if ( factors.size() == 1 && factors.get(prime) == 1 ) {
List<Long> divisors = new ArrayList<>();
if ( n % 10 == 1 || n % 10 == 9 ) {
for ( long divisor : getDivisors(prime-1) ) {
if ( divisor % 2 == 0 ) {
divisors.add(divisor);
}
}
}
else {
List<Long> pPlus1Divisors = getDivisors(prime+1);
for ( long divisor : getDivisors(2*prime+2) ) {
if ( ! pPlus1Divisors.contains(divisor) ) {
divisors.add(divisor);
}
}
}
Collections.sort(divisors);
for ( long divisor : divisors ) {
if ( fibModIdentity(divisor, prime) ) {
PERIOD_MEMO.put(prime, divisor);
return divisor;
}
}
throw new RuntimeException("ERROR 144: Divisor not found.");
}
long period = (long) Math.pow(prime, factors.get(prime)-1) * pisano(prime);
for ( int i = 1 ; i < primes.size() ; i++ ) {
prime = primes.get(i);
period = lcm(period, (long) Math.pow(prime, factors.get(prime)-1) * pisano(prime));
}
PERIOD_MEMO.put(n, period);
return period;
}
// Use Matrix multiplication to compute Fibonacci numbers.
private static boolean fibModIdentity(long n, long mod) {
long aRes = 0;
long bRes = 1;
long cRes = 1;
long aBase = 0;
long bBase = 1;
long cBase = 1;
while ( n > 0 ) {
if ( n % 2 == 1 ) {
long temp1 = 0, temp2 = 0, temp3 = 0;
if ( aRes > SQRT || aBase > SQRT || bRes > SQRT || bBase > SQRT || cBase > SQRT || cRes > SQRT ) {
temp1 = (multiply(aRes, aBase, mod) + multiply(bRes, bBase, mod)) % mod;
temp2 = (multiply(aBase, bRes, mod) + multiply(bBase, cRes, mod)) % mod;
temp3 = (multiply(bBase, bRes, mod) + multiply(cBase, cRes, mod)) % mod;
}
else {
temp1 = ((aRes*aBase % mod) + (bRes*bBase % mod)) % mod;
temp2 = ((aBase*bRes % mod) + (bBase*cRes % mod)) % mod;
temp3 = ((bBase*bRes % mod) + (cBase*cRes % mod)) % mod;
}
aRes = temp1;
bRes = temp2;
cRes = temp3;
}
n >>= 1L;
long temp1 = 0, temp2 = 0, temp3 = 0;
if ( aBase > SQRT || bBase > SQRT || cBase > SQRT ) {
temp1 = (multiply(aBase, aBase, mod) + multiply(bBase, bBase, mod)) % mod;
temp2 = (multiply(aBase, bBase, mod) + multiply(bBase, cBase, mod)) % mod;
temp3 = (multiply(bBase, bBase, mod) + multiply(cBase, cBase, mod)) % mod;
}
else {
temp1 = ((aBase*aBase % mod) + (bBase*bBase % mod)) % mod;
temp2 = ((aBase*bBase % mod) + (bBase*cBase % mod)) % mod;
temp3 = ((bBase*bBase % mod) + (cBase*cBase % mod)) % mod;
}
aBase = temp1;
bBase = temp2;
cBase = temp3;
}
return aRes % mod == 0 && bRes % mod == 1 && cRes % mod == 1;
}
private static final long SQRT = (long) Math.sqrt(Long.MAX_VALUE);
// Result is a*b % mod, without overflow.
public static final long multiply(long a, long b, long modulus) {
//System.out.println(" multiply : a = " + a + ", b = " + b + ", mod = " + modulus);
long x = 0;
long y = a % modulus;
long t;
while ( b > 0 ) {
if ( b % 2 == 1 ) {
t = x + y;
x = (t > modulus ? t-modulus : t);
}
t = y << 1;
y = (t > modulus ? t-modulus : t);
b >>= 1;
}
//System.out.println(" multiply : answer = " + (x % modulus));
return x % modulus;
}
private static final List<Long> getDivisors(long number) {
List<Long> divisors = new ArrayList<>();
long sqrt = (long) Math.sqrt(number);
for ( long i = 1 ; i <= sqrt ; i++ ) {
if ( number % i == 0 ) {
divisors.add(i);
long div = number / i;
if ( div != i ) {
divisors.add(div);
}
}
}
return divisors;
}
public static long lcm(long a, long b) {
return a*b/gcd(a,b);
}
public static long gcd(long a, long b) {
if ( b == 0 ) {
return a;
}
return gcd(b, a%b);
}
private static final Map<Long,Map<Long,Long>> allFactors = new TreeMap<Long,Map<Long,Long>>();
static {
Map<Long,Long> factors = new TreeMap<Long,Long>();
factors.put(2L, 1L);
allFactors.put(2L, factors);
}
public static Long MAX_ALL_FACTORS = 100000L;
public static final Map<Long,Long> getFactors(Long number) {
if ( allFactors.containsKey(number) ) {
return allFactors.get(number);
}
Map<Long,Long> factors = new TreeMap<Long,Long>();
if ( number % 2 == 0 ) {
Map<Long,Long> factorsdDivTwo = getFactors(number/2);
factors.putAll(factorsdDivTwo);
factors.merge(2L, 1L, (v1, v2) -> v1 + v2);
if ( number < MAX_ALL_FACTORS ) {
allFactors.put(number, factors);
}
return factors;
}
boolean prime = true;
long sqrt = (long) Math.sqrt(number);
for ( long i = 3 ; i <= sqrt ; i += 2 ) {
if ( number % i == 0 ) {
prime = false;
factors.putAll(getFactors(number/i));
factors.merge(i, 1L, (v1, v2) -> v1 + v2);
if ( number < MAX_ALL_FACTORS ) {
allFactors.put(number, factors);
}
return factors;
}
}
if ( prime ) {
factors.put(number, 1L);
if ( number < MAX_ALL_FACTORS ) {
allFactors.put(number, factors);
}
}
return factors;
}
}
|
http://rosettacode.org/wiki/Pinstripe/Display | Pinstripe/Display | Sample image
The task is to demonstrate the creation of a series of vertical pinstripes across the entire width of the display.
in the first quarter the pinstripes should alternate one pixel white, one pixel black = 1 pixel wide vertical pinestripes
Quarter of the way down the display, we can switch to a wider 2 pixel wide vertical pinstripe pattern, alternating two pixels white, two pixels black.
Half way down the display, we switch to 3 pixels wide,
for the lower quarter of the display we use 4 pixels.
c.f. Colour_pinstripe/Display
| #Action.21 | Action! | PROC Main()
BYTE
CH=$02FC, ;Internal hardware value for last key pressed
COLOR0=$02C4,COLOR1=$02C5,COLOR2=$02C6,COLOR4=$02C8
CARD i
Graphics(8+16)
COLOR4=$04 ;gray
COLOR1=$00 ;black
COLOR2=$0F ;white
FOR i=0 TO 319
DO
Color=i MOD 2
Plot(i,0) DrawTo(i,47)
Color=i/2 MOD 2
Plot(i,48) DrawTo(i,95)
Color=i/3 MOD 2
Plot(i,96) DrawTo(i,143)
Color=i/4 MOD 2
Plot(i,144) DrawTo(i,191)
OD
DO UNTIL CH#$FF OD
CH=$FF
RETURN |
http://rosettacode.org/wiki/Pinstripe/Display | Pinstripe/Display | Sample image
The task is to demonstrate the creation of a series of vertical pinstripes across the entire width of the display.
in the first quarter the pinstripes should alternate one pixel white, one pixel black = 1 pixel wide vertical pinestripes
Quarter of the way down the display, we can switch to a wider 2 pixel wide vertical pinstripe pattern, alternating two pixels white, two pixels black.
Half way down the display, we switch to 3 pixels wide,
for the lower quarter of the display we use 4 pixels.
c.f. Colour_pinstripe/Display
| #ActionScript | ActionScript |
package {
import flash.display.Bitmap;
import flash.display.BitmapData;
import flash.display.Sprite;
import flash.events.Event;
public class Pinstripe extends Sprite {
public function Pinstripe():void {
if (stage) init();
else addEventListener(Event.ADDED_TO_STAGE, init);
}
private function init(e:Event = null):void {
var data:BitmapData = new BitmapData(stage.stageWidth, stage.stageHeight, false, 0xFFFFFFFF);
data.lock();
var w:uint = data.width, h:uint = data.height / 4;
var x:uint, y:uint = 0, i:uint, px:uint, colour:uint, maxy:uint = h;
for ( i = 1; i <= 4; i++ ) {
for ( ; y < maxy; y++ ) {
colour = 0xFF000000;
px = 1;
for ( x = 0; x < w; x++ ) {
if ( px == i ) {
colour = (colour == 0xFF000000) ? 0xFFFFFFFF : 0xFF000000;
px = 1;
}
else px++;
data.setPixel32(x, y, colour);
}
}
maxy += h;
}
data.unlock();
addChild(new Bitmap(data));
}
}
}
|
http://rosettacode.org/wiki/Primality_by_trial_division | Primality by trial division | Task
Write a boolean function that tells whether a given integer is prime.
Remember that 1 and all non-positive numbers are not prime.
Use trial division.
Even numbers greater than 2 may be eliminated right away.
A loop from 3 to √ n will suffice, but other loops are allowed.
Related tasks
count in factors
prime decomposition
AKS test for primes
factors of an integer
Sieve of Eratosthenes
factors of a Mersenne number
trial factoring of a Mersenne number
partition an integer X into N primes
sequence of primes by Trial Division
| #Oz | Oz | fun {Prime N}
local IPrime in
fun {IPrime N Acc}
if N < Acc*Acc then true
elseif (N mod Acc) == 0 then false
else {IPrime N Acc+1}
end
end
if N < 2 then false
else {IPrime N 2} end
end
end |
http://rosettacode.org/wiki/Prime_decomposition | Prime decomposition | The prime decomposition of a number is defined as a list of prime numbers
which when all multiplied together, are equal to that number.
Example
12 = 2 × 2 × 3, so its prime decomposition is {2, 2, 3}
Task
Write a function which returns an array or collection which contains the prime decomposition of a given number
n
{\displaystyle n}
greater than 1.
If your language does not have an isPrime-like function available,
you may assume that you have a function which determines
whether a number is prime (note its name before your code).
If you would like to test code from this task, you may use code from trial division or the Sieve of Eratosthenes.
Note: The program must not be limited by the word size of your computer or some other artificial limit; it should work for any number regardless of size (ignoring the physical limits of RAM etc).
Related tasks
count in factors
factors of an integer
Sieve of Eratosthenes
primality by trial division
factors of a Mersenne number
trial factoring of a Mersenne number
partition an integer X into N primes
sequence of primes by Trial Division
| #Tiny_BASIC | Tiny BASIC | 10 PRINT "Enter a number."
20 INPUT N
25 PRINT "------"
30 IF N<0 THEN LET N = -N
40 IF N<2 THEN END
50 LET I = 2
60 IF I*I > N THEN GOTO 200
70 IF (N/I)*I = N THEN GOTO 300
80 LET I = I + 1
90 GOTO 60
200 PRINT N
210 END
300 LET N = N / I
310 PRINT I
320 GOTO 50 |
http://rosettacode.org/wiki/Play_recorded_sounds | Play recorded sounds | Load at least two prerecorded sounds, and demonstrate as many of these features as you can:
playing them individually and simultaneously
stopping before the end of the sound
looping (preferably glitch-free)
setting the volume of each sound
stereo or 3D positional mixing
performing other actions when marked times in the sound arrive
Describe:
The supported audio formats, briefly.
Whether it is suitable for game sound effects (low-latency start, resource efficiency, supports many simultaneous sounds, etc.)
Whether it is suitable for playing music (long duration ).
[Note: If it seems to be a good idea, this task may be revised to specify a particular timeline rather than just 'demonstrate these features'.]
Where applicable, please categorize examples primarily by the audio facility used (library/API/program/platform) rather than the language if the language is incidental (e.g. "Mac OS X CoreAudio" or "mplayer" rather than "C" or "bash").
| #Swift | Swift | import AVFoundation
// This example uses AVAudioPlayer for playback.
// AVAudioPlayer is the player Apple recommends for playback, since it suitable for songs
// and offers control over numerous playback parameters.
// It can play any type that is natively supported by OSX or iOS
class PlayerControl: NSObject, AVAudioPlayerDelegate {
let player1:AVAudioPlayer!
let player2:AVAudioPlayer!
var playedBoth = false
var volume:Float {
get {
return player1.volume
}
set {
player1.volume = newValue
player2.volume = newValue
}
}
init(player1:AVAudioPlayer, player2:AVAudioPlayer) {
super.init()
self.player1 = player1
self.player2 = player2
self.player1.delegate = self
self.player2.delegate = self
}
func loop() {
player1.numberOfLoops = 1
player1.play()
let time = Int64((Double(player1.duration) + 2.0) * Double(NSEC_PER_SEC))
dispatch_after(dispatch_time(0, time), dispatch_get_main_queue()) {[weak self] in
println("Stopping track")
self?.player1.stop()
exit(0)
}
}
func playBoth() {
player1.play()
player2.play()
}
func audioPlayerDidFinishPlaying(player:AVAudioPlayer!, successfully flag:Bool) {
if player === player2 && !playedBoth {
playBoth()
playedBoth = true
} else if player === player2 && playedBoth {
loop()
}
}
}
let url1 = NSURL(string: "file:///file1.mp3")
let url2 = NSURL(string: "file:///file2.mp3")
var err:NSError?
let player1 = AVAudioPlayer(contentsOfURL: url1, error: &err)
let player2 = AVAudioPlayer(contentsOfURL: url2, error: &err)
let player = PlayerControl(player1: player1, player2: player2)
// Setting the volume
player.volume = 0.5
// Play track 2
// When this track finishes it will play both of them
// by calling the audioPlayerDidFinishPlaying delegate method
// Once both tracks finish playing, it will then loop the first track twice
// stopping the track after 2 seconds of the second play
player.player2.play()
CFRunLoopRun() |
http://rosettacode.org/wiki/Play_recorded_sounds | Play recorded sounds | Load at least two prerecorded sounds, and demonstrate as many of these features as you can:
playing them individually and simultaneously
stopping before the end of the sound
looping (preferably glitch-free)
setting the volume of each sound
stereo or 3D positional mixing
performing other actions when marked times in the sound arrive
Describe:
The supported audio formats, briefly.
Whether it is suitable for game sound effects (low-latency start, resource efficiency, supports many simultaneous sounds, etc.)
Whether it is suitable for playing music (long duration ).
[Note: If it seems to be a good idea, this task may be revised to specify a particular timeline rather than just 'demonstrate these features'.]
Where applicable, please categorize examples primarily by the audio facility used (library/API/program/platform) rather than the language if the language is incidental (e.g. "Mac OS X CoreAudio" or "mplayer" rather than "C" or "bash").
| #Tcl | Tcl | package require sound
# Potentially also require driver support for particular formats
# Load some sounds in; this part can be slow
snack::sound s1
s1 read $soundFile1
snack::sound s2
s2 read $soundFile2
# Play a sound for a while (0.1 seconds; this is a low-latency operation)
s1 play
after 100 set done 1; vwait done; # Run the event loop for a while
s1 stop
# Play two sounds at once (for 30 seconds) while mixing together
s1 play
s2 play
after 30000 set done 1; vwait done
s1 stop
s2 stop |
http://rosettacode.org/wiki/Play_recorded_sounds | Play recorded sounds | Load at least two prerecorded sounds, and demonstrate as many of these features as you can:
playing them individually and simultaneously
stopping before the end of the sound
looping (preferably glitch-free)
setting the volume of each sound
stereo or 3D positional mixing
performing other actions when marked times in the sound arrive
Describe:
The supported audio formats, briefly.
Whether it is suitable for game sound effects (low-latency start, resource efficiency, supports many simultaneous sounds, etc.)
Whether it is suitable for playing music (long duration ).
[Note: If it seems to be a good idea, this task may be revised to specify a particular timeline rather than just 'demonstrate these features'.]
Where applicable, please categorize examples primarily by the audio facility used (library/API/program/platform) rather than the language if the language is incidental (e.g. "Mac OS X CoreAudio" or "mplayer" rather than "C" or "bash").
| #TUSCRIPT | TUSCRIPT |
$$ MODE TUSCRIPT
audiofile="test.wav"
ERROR/STOP OPEN (audiofile,READ,-std-)
BROWSE $audiofile
|
http://rosettacode.org/wiki/Pisano_period | Pisano period | The Fibonacci sequence taken modulo 2 is a periodic sequence of period 3 : 0, 1, 1, 0, 1, 1, ...
For any integer n, the Fibonacci sequence taken modulo n is periodic and the length of the periodic cycle is referred to as the Pisano period.
Prime numbers are straightforward; the Pisano period of a prime number p is simply: pisano(p). The Pisano period of a composite number c may be found in different ways. It may be calculated directly: pisano(c), which works, but may be time consuming to find, especially for larger integers, or, it may be calculated by finding the least common multiple of the Pisano periods of each composite component.
E.G.
Given a Pisano period function: pisano(x), and a least common multiple function lcm(x, y):
pisano(m × n) is equivalent to lcm(pisano(m), pisano(n)) where m and n are coprime
A formulae to calculate the pisano period for integer powers k of prime numbers p is:
pisano(pk) == p(k-1)pisano(p)
The equation is conjectured, no exceptions have been seen.
If a positive integer i is split into its prime factors, then the second and first equations above can be applied to generate the pisano period.
Task
Write 2 functions: pisanoPrime(p,k) and pisano(m).
pisanoPrime(p,k) should return the Pisano period of pk where p is prime and k is a positive integer.
pisano(m) should use pisanoPrime to return the Pisano period of m where m is a positive integer.
Print pisanoPrime(p,2) for every prime lower than 15.
Print pisanoPrime(p,1) for every prime lower than 180.
Print pisano(m) for every integer from 1 to 180.
Related tasks
Fibonacci sequence
Prime decomposition
Least common multiple
| #Julia | Julia | using Primes
const pisanos = Dict{Int, Int}()
function pisano(p)
p < 2 && return 1
(i = get(pisanos, p, 0)) > 0 && return i
lastn, n = 0, 1
for i in 1:p^2
lastn, n = n, (lastn + n) % p
if lastn == 0 && n == 1
pisanos[p] = i
return i
end
end
return 1
end
pisanoprime(p, k) = (@assert(isprime(p)); p^(k-1) * pisano(p))
pisanotask(n) = mapreduce(p -> pisanoprime(p[1], p[2]), lcm, collect(factor(n)), init=1)
for i in 1:15
if isprime(i)
println("pisanoPrime($i, 2) = ", pisanoprime(i, 2))
end
end
for i in 1:180
if isprime(i)
println("pisanoPrime($i, 1) = ", pisanoprime(i, 1))
end
end
println("\nPisano(n) for n from 2 to 180:\n", [pisano(i) for i in 2:180])
println("\nPisano(n) using pisanoPrime for n from 2 to 180:\n", [pisanotask(i) for i in 2:180])
|
http://rosettacode.org/wiki/Pisano_period | Pisano period | The Fibonacci sequence taken modulo 2 is a periodic sequence of period 3 : 0, 1, 1, 0, 1, 1, ...
For any integer n, the Fibonacci sequence taken modulo n is periodic and the length of the periodic cycle is referred to as the Pisano period.
Prime numbers are straightforward; the Pisano period of a prime number p is simply: pisano(p). The Pisano period of a composite number c may be found in different ways. It may be calculated directly: pisano(c), which works, but may be time consuming to find, especially for larger integers, or, it may be calculated by finding the least common multiple of the Pisano periods of each composite component.
E.G.
Given a Pisano period function: pisano(x), and a least common multiple function lcm(x, y):
pisano(m × n) is equivalent to lcm(pisano(m), pisano(n)) where m and n are coprime
A formulae to calculate the pisano period for integer powers k of prime numbers p is:
pisano(pk) == p(k-1)pisano(p)
The equation is conjectured, no exceptions have been seen.
If a positive integer i is split into its prime factors, then the second and first equations above can be applied to generate the pisano period.
Task
Write 2 functions: pisanoPrime(p,k) and pisano(m).
pisanoPrime(p,k) should return the Pisano period of pk where p is prime and k is a positive integer.
pisano(m) should use pisanoPrime to return the Pisano period of m where m is a positive integer.
Print pisanoPrime(p,2) for every prime lower than 15.
Print pisanoPrime(p,1) for every prime lower than 180.
Print pisano(m) for every integer from 1 to 180.
Related tasks
Fibonacci sequence
Prime decomposition
Least common multiple
| #Nim | Nim | import math, strformat, tables
func primes(n: Positive): seq[int] =
## Return the list of prime divisors of "n".
var n = n.int
for d in 2..n:
var q = n div d
var m = n mod d
while m == 0:
result.add d
n = q
q = n div d
m = n mod d
func isPrime(n: Positive): bool =
## Return true if "n" is prime.
if n < 2: return false
if n mod 2 == 0: return n == 2
if n mod 3 == 0: return n == 3
var d = 5
while d <= sqrt(n.toFloat).int:
if n mod d == 0: return false
inc d, 2
if n mod d == 0: return false
inc d, 4
result = true
func pisanoPeriod(m: Positive): int =
## Calculate the Pisano period of 'm' from first principles.
var p = 0
var c = 1
for i in 0..<m*m:
p = (p + c) mod m
swap p, c
if p == 0 and c == 1: return i + 1
result = 1
func pisanoPrime(p, k: Positive): int =
## Calculate the Pisano period of p^k where 'p' is prime and 'k' is a positive integer.
if p.isPrime: p^(k-1) * p.pisanoPeriod() else: 0
func pisano(m: Positive): int =
## Calculate the Pisano period of 'm' using pisanoPrime.
let primes = m.primes
var primePowers = primes.toCountTable
var pps: seq[int]
for k, v in primePowers.pairs:
pps.add pisanoPrime(k, v)
if pps.len == 0: return 1
result = pps[0]
for i in 1..pps.high:
result = lcm(result, pps[i])
when isMainModule:
for p in 2..14:
let pp = pisanoPrime(p, 2)
if pp > 0:
echo &"pisanoPrime({p:2}, 2) = {pp}"
echo()
for p in 2..179:
let pp = pisanoPrime(p, 1)
if pp > 0:
echo &"pisanoPrime({p:3}, 1) = {pp}"
echo()
echo "pisano(n) for integers 'n' from 1 to 180 are:"
for n in 1..180:
stdout.write &"{pisano(n):3}", if n mod 15 == 0: '\n' else: ' ' |
http://rosettacode.org/wiki/Pinstripe/Display | Pinstripe/Display | Sample image
The task is to demonstrate the creation of a series of vertical pinstripes across the entire width of the display.
in the first quarter the pinstripes should alternate one pixel white, one pixel black = 1 pixel wide vertical pinestripes
Quarter of the way down the display, we can switch to a wider 2 pixel wide vertical pinstripe pattern, alternating two pixels white, two pixels black.
Half way down the display, we switch to 3 pixels wide,
for the lower quarter of the display we use 4 pixels.
c.f. Colour_pinstripe/Display
| #Ada | Ada | with SDL.Video.Windows.Makers;
with SDL.Video.Renderers.Makers;
with SDL.Events.Events;
procedure Pinstripe_Display is
Width : constant := 800;
Height : constant := 400;
Window : SDL.Video.Windows.Window;
Renderer : SDL.Video.Renderers.Renderer;
Event : SDL.Events.Events.Events;
use SDL;
use type SDL.C.int;
procedure Draw_Pinstripe (Line_Width : in C.int;
Line_Height : in C.int;
Screen_Width : in C.int;
Y : in C.int)
is
Count : constant C.int := Screen_Width / (2 * Line_Width);
begin
Renderer.Set_Draw_Colour (Colour => (255, 255, 255, 255));
for A in 0 .. Count loop
Renderer.Fill (Rectangle => (X => 2 * A * Line_Width, Y => Y,
Width => Line_Width,
Height => Line_Height));
end loop;
end Draw_Pinstripe;
procedure Wait is
use type SDL.Events.Event_Types;
begin
loop
while SDL.Events.Events.Poll (Event) loop
if Event.Common.Event_Type = SDL.Events.Quit then
return;
end if;
end loop;
delay 0.100;
end loop;
end Wait;
begin
if not SDL.Initialise (Flags => SDL.Enable_Screen) then
return;
end if;
SDL.Video.Windows.Makers.Create (Win => Window,
Title => "Pinstripe",
Position => SDL.Natural_Coordinates'(X => 10, Y => 10),
Size => SDL.Positive_Sizes'(Width, Height),
Flags => 0);
SDL.Video.Renderers.Makers.Create (Renderer, Window.Get_Surface);
Renderer.Set_Draw_Colour ((0, 0, 0, 255));
Renderer.Fill (Rectangle => (0, 0, Width, Height));
Draw_Pinstripe (1, Height / 4, Width, 0);
Draw_Pinstripe (2, Height / 4, Width, 100);
Draw_Pinstripe (3, Height / 4, Width, 200);
Draw_Pinstripe (4, Height / 4, Width, 300);
Window.Update_Surface;
Wait;
Window.Finalize;
SDL.Finalise;
end Pinstripe_Display; |
http://rosettacode.org/wiki/Primality_by_trial_division | Primality by trial division | Task
Write a boolean function that tells whether a given integer is prime.
Remember that 1 and all non-positive numbers are not prime.
Use trial division.
Even numbers greater than 2 may be eliminated right away.
A loop from 3 to √ n will suffice, but other loops are allowed.
Related tasks
count in factors
prime decomposition
AKS test for primes
factors of an integer
Sieve of Eratosthenes
factors of a Mersenne number
trial factoring of a Mersenne number
partition an integer X into N primes
sequence of primes by Trial Division
| #Panda | Panda | fun prime(p) type integer->integer
p.gt(1) where q=p.sqrt NO(p.mod(2..q)==0)
1..100.prime |
http://rosettacode.org/wiki/Prime_decomposition | Prime decomposition | The prime decomposition of a number is defined as a list of prime numbers
which when all multiplied together, are equal to that number.
Example
12 = 2 × 2 × 3, so its prime decomposition is {2, 2, 3}
Task
Write a function which returns an array or collection which contains the prime decomposition of a given number
n
{\displaystyle n}
greater than 1.
If your language does not have an isPrime-like function available,
you may assume that you have a function which determines
whether a number is prime (note its name before your code).
If you would like to test code from this task, you may use code from trial division or the Sieve of Eratosthenes.
Note: The program must not be limited by the word size of your computer or some other artificial limit; it should work for any number regardless of size (ignoring the physical limits of RAM etc).
Related tasks
count in factors
factors of an integer
Sieve of Eratosthenes
primality by trial division
factors of a Mersenne number
trial factoring of a Mersenne number
partition an integer X into N primes
sequence of primes by Trial Division
| #TXR | TXR | @(next :args)
@(do
(defun factor (n)
(if (> n 1)
(for ((max-d (isqrt n))
(d 2))
()
((inc d (if (evenp d) 1 2)))
(cond ((> d max-d) (return (list n)))
((zerop (mod n d))
(return (cons d (factor (trunc n d))))))))))
@{num /[0-9]+/}
@(bind factors @(factor (int-str num 10)))
@(output)
@num -> {@(rep)@factors, @(last)@factors@(end)}
@(end) |
http://rosettacode.org/wiki/Play_recorded_sounds | Play recorded sounds | Load at least two prerecorded sounds, and demonstrate as many of these features as you can:
playing them individually and simultaneously
stopping before the end of the sound
looping (preferably glitch-free)
setting the volume of each sound
stereo or 3D positional mixing
performing other actions when marked times in the sound arrive
Describe:
The supported audio formats, briefly.
Whether it is suitable for game sound effects (low-latency start, resource efficiency, supports many simultaneous sounds, etc.)
Whether it is suitable for playing music (long duration ).
[Note: If it seems to be a good idea, this task may be revised to specify a particular timeline rather than just 'demonstrate these features'.]
Where applicable, please categorize examples primarily by the audio facility used (library/API/program/platform) rather than the language if the language is incidental (e.g. "Mac OS X CoreAudio" or "mplayer" rather than "C" or "bash").
| #UNIX_Shell | UNIX Shell | #!/usr/bin/sh
# play.sh
# Plays .au files.
# Usage: play.sh <recorded_sound.au>
cat $1 >> /dev/audio # Write file $1 to the speaker's Character Special (/dev/audio). |
http://rosettacode.org/wiki/Play_recorded_sounds | Play recorded sounds | Load at least two prerecorded sounds, and demonstrate as many of these features as you can:
playing them individually and simultaneously
stopping before the end of the sound
looping (preferably glitch-free)
setting the volume of each sound
stereo or 3D positional mixing
performing other actions when marked times in the sound arrive
Describe:
The supported audio formats, briefly.
Whether it is suitable for game sound effects (low-latency start, resource efficiency, supports many simultaneous sounds, etc.)
Whether it is suitable for playing music (long duration ).
[Note: If it seems to be a good idea, this task may be revised to specify a particular timeline rather than just 'demonstrate these features'.]
Where applicable, please categorize examples primarily by the audio facility used (library/API/program/platform) rather than the language if the language is incidental (e.g. "Mac OS X CoreAudio" or "mplayer" rather than "C" or "bash").
| #VBA | VBA |
Declare Function libPlaySound Lib "winmm.dll" Alias "sndPlaySoundA" _
(ByVal filename As String, ByVal Flags As Long) As Long
Sub PlaySound(sWav As String)
Call libPlaySound(sWav, 1) '1 to play asynchronously
End Sub
|
http://rosettacode.org/wiki/Play_recorded_sounds | Play recorded sounds | Load at least two prerecorded sounds, and demonstrate as many of these features as you can:
playing them individually and simultaneously
stopping before the end of the sound
looping (preferably glitch-free)
setting the volume of each sound
stereo or 3D positional mixing
performing other actions when marked times in the sound arrive
Describe:
The supported audio formats, briefly.
Whether it is suitable for game sound effects (low-latency start, resource efficiency, supports many simultaneous sounds, etc.)
Whether it is suitable for playing music (long duration ).
[Note: If it seems to be a good idea, this task may be revised to specify a particular timeline rather than just 'demonstrate these features'.]
Where applicable, please categorize examples primarily by the audio facility used (library/API/program/platform) rather than the language if the language is incidental (e.g. "Mac OS X CoreAudio" or "mplayer" rather than "C" or "bash").
| #Wren | Wren | import "audio" for AudioEngine
import "dome" for Process
class Game {
static init() {
// load a .wav file and give it a friendly name
AudioEngine.load("a", "a.wav")
// play the file at volume v, looping l and pan p
__v = 2 // twice 'normal' volume
__l = true // loop when finished
__p = 0.5 // division between left and right audio channels (-1 to +1)
__chan1 = AudioEngine.play("a", __v, __l, __p)
__fc = 0 // frame counter, updates at 60 fps
}
static update() { __fc = __fc + 1 }
static draw(dt) {
if (__fc == 600) {
// after 10 seconds load and play a second .wav file simultaneously, same settings
AudioEngine.load("b", "b.wav")
__chan2 = AudioEngine.play("b", __v, __l, __p)
}
if (__fc == 1200) {
__chan1.stop() // after a further 10 seconds, stop the first file
AudioEngine.unload("a") // and unload it
} else if (__fc == 1800) {
__chan2.stop() // after another 10 seconds, stop the second file
AudioEngine.unload("b") // and unload it
Process.exit(0) // exit the application
}
}
} |
http://rosettacode.org/wiki/Pisano_period | Pisano period | The Fibonacci sequence taken modulo 2 is a periodic sequence of period 3 : 0, 1, 1, 0, 1, 1, ...
For any integer n, the Fibonacci sequence taken modulo n is periodic and the length of the periodic cycle is referred to as the Pisano period.
Prime numbers are straightforward; the Pisano period of a prime number p is simply: pisano(p). The Pisano period of a composite number c may be found in different ways. It may be calculated directly: pisano(c), which works, but may be time consuming to find, especially for larger integers, or, it may be calculated by finding the least common multiple of the Pisano periods of each composite component.
E.G.
Given a Pisano period function: pisano(x), and a least common multiple function lcm(x, y):
pisano(m × n) is equivalent to lcm(pisano(m), pisano(n)) where m and n are coprime
A formulae to calculate the pisano period for integer powers k of prime numbers p is:
pisano(pk) == p(k-1)pisano(p)
The equation is conjectured, no exceptions have been seen.
If a positive integer i is split into its prime factors, then the second and first equations above can be applied to generate the pisano period.
Task
Write 2 functions: pisanoPrime(p,k) and pisano(m).
pisanoPrime(p,k) should return the Pisano period of pk where p is prime and k is a positive integer.
pisano(m) should use pisanoPrime to return the Pisano period of m where m is a positive integer.
Print pisanoPrime(p,2) for every prime lower than 15.
Print pisanoPrime(p,1) for every prime lower than 180.
Print pisano(m) for every integer from 1 to 180.
Related tasks
Fibonacci sequence
Prime decomposition
Least common multiple
| #Perl | Perl | use strict;
use warnings;
use feature 'say';
use ntheory qw(primes factor_exp lcm);
sub pisano_period_pp {
my($a, $b, $n, $k) = (0, 1, $_[0]**$_[1]);
while (++$k) {
($a, $b) = ($b, ($a+$b) % $n);
return $k if $a == 0 and $b == 1;
}
}
sub pisano_period {
(lcm map { pisano_period_pp($$_[0],$$_[1]) } factor_exp($_[0])) or 1;
}
sub display { (sprintf "@{['%5d' x @_]}", @_) =~ s/(.{75})/$1\n/gr }
say "Pisano periods for squares of primes p <= 50:\n", display( map { pisano_period_pp($_, 2) } @{primes(1, 50)} ),
"\nPisano periods for primes p <= 180:\n", display( map { pisano_period_pp($_, 1) } @{primes(1, 180)} ),
"\n\nPisano periods for integers n from 1 to 180:\n", display( map { pisano_period ($_ ) } 1..180 ); |
http://rosettacode.org/wiki/Pinstripe/Display | Pinstripe/Display | Sample image
The task is to demonstrate the creation of a series of vertical pinstripes across the entire width of the display.
in the first quarter the pinstripes should alternate one pixel white, one pixel black = 1 pixel wide vertical pinestripes
Quarter of the way down the display, we can switch to a wider 2 pixel wide vertical pinstripe pattern, alternating two pixels white, two pixels black.
Half way down the display, we switch to 3 pixels wide,
for the lower quarter of the display we use 4 pixels.
c.f. Colour_pinstripe/Display
| #AutoHotkey | AutoHotkey | h := A_ScreenHeight
w := A_ScreenWidth
pToken := Gdip_Startup()
hdc := CreateCompatibleDC()
hbm := CreateDIBSection(w, h)
obm := SelectObject(hdc, hbm)
G := Gdip_GraphicsFromHDC(hdc)
OnExit, Exit
Gui -Caption +E0x80000 +LastFound +OwnDialogs +Owner +AlwaysOnTop
Gui Show, NA
hwnd := WinExist()
pBrushB := Gdip_BrushCreateSolid(0xFF000000)
pBrushW := Gdip_BrushCreateSolid(0xFFFFFFFF)
Loop 4
{
n := A_Index
Loop % w
BorW := A_Index & 1 ? "B" : "W"
,Gdip_FillRectangle(G, pBrush%BorW%
, A_Index*n-n, (n-1)*h/4, n, h/4)
}
UpdateLayeredWindow(hwnd, hdc, 0, 0, W, H)
Gdip_DeleteBrush(pBrushB)
Gdip_DeleteBrush(pBrushW)
SelectObject(hdc, obm)
DeleteObject(hbm)
DeleteDC(hdc)
Gdip_DeleteGraphics(G)
Return
Escape::
Exit:
Gdip_Shutdown(pToken)
ExitApp |
http://rosettacode.org/wiki/Primality_by_trial_division | Primality by trial division | Task
Write a boolean function that tells whether a given integer is prime.
Remember that 1 and all non-positive numbers are not prime.
Use trial division.
Even numbers greater than 2 may be eliminated right away.
A loop from 3 to √ n will suffice, but other loops are allowed.
Related tasks
count in factors
prime decomposition
AKS test for primes
factors of an integer
Sieve of Eratosthenes
factors of a Mersenne number
trial factoring of a Mersenne number
partition an integer X into N primes
sequence of primes by Trial Division
| #PARI.2FGP | PARI/GP | trial(n)={
if(n < 4, return(n > 1)); /* Handle negatives */
forprime(p=2,sqrtint(n),
if(n%p == 0, return(0))
);
1
}; |
http://rosettacode.org/wiki/Prime_decomposition | Prime decomposition | The prime decomposition of a number is defined as a list of prime numbers
which when all multiplied together, are equal to that number.
Example
12 = 2 × 2 × 3, so its prime decomposition is {2, 2, 3}
Task
Write a function which returns an array or collection which contains the prime decomposition of a given number
n
{\displaystyle n}
greater than 1.
If your language does not have an isPrime-like function available,
you may assume that you have a function which determines
whether a number is prime (note its name before your code).
If you would like to test code from this task, you may use code from trial division or the Sieve of Eratosthenes.
Note: The program must not be limited by the word size of your computer or some other artificial limit; it should work for any number regardless of size (ignoring the physical limits of RAM etc).
Related tasks
count in factors
factors of an integer
Sieve of Eratosthenes
primality by trial division
factors of a Mersenne number
trial factoring of a Mersenne number
partition an integer X into N primes
sequence of primes by Trial Division
| #V | V | [prime-decomposition
[inner [c p] let
[c c * p >]
[p unit]
[ [p c % zero?]
[c c p c / inner cons]
[c 1 + p inner]
ifte]
ifte].
2 swap inner]. |
http://rosettacode.org/wiki/Pisano_period | Pisano period | The Fibonacci sequence taken modulo 2 is a periodic sequence of period 3 : 0, 1, 1, 0, 1, 1, ...
For any integer n, the Fibonacci sequence taken modulo n is periodic and the length of the periodic cycle is referred to as the Pisano period.
Prime numbers are straightforward; the Pisano period of a prime number p is simply: pisano(p). The Pisano period of a composite number c may be found in different ways. It may be calculated directly: pisano(c), which works, but may be time consuming to find, especially for larger integers, or, it may be calculated by finding the least common multiple of the Pisano periods of each composite component.
E.G.
Given a Pisano period function: pisano(x), and a least common multiple function lcm(x, y):
pisano(m × n) is equivalent to lcm(pisano(m), pisano(n)) where m and n are coprime
A formulae to calculate the pisano period for integer powers k of prime numbers p is:
pisano(pk) == p(k-1)pisano(p)
The equation is conjectured, no exceptions have been seen.
If a positive integer i is split into its prime factors, then the second and first equations above can be applied to generate the pisano period.
Task
Write 2 functions: pisanoPrime(p,k) and pisano(m).
pisanoPrime(p,k) should return the Pisano period of pk where p is prime and k is a positive integer.
pisano(m) should use pisanoPrime to return the Pisano period of m where m is a positive integer.
Print pisanoPrime(p,2) for every prime lower than 15.
Print pisanoPrime(p,1) for every prime lower than 180.
Print pisano(m) for every integer from 1 to 180.
Related tasks
Fibonacci sequence
Prime decomposition
Least common multiple
| #Phix | Phix | with javascript_semantics
function pisano_period(integer m)
-- Calculates the Pisano period of 'm' from first principles. (copied from Go)
integer p = 0, c = 1
for i=0 to m*m-1 do
{p, c} = {c, mod(p+c,m)}
if p == 0 and c == 1 then
return i + 1
end if
end for
return 1
end function
function pisanoPrime(integer p, k)
if not is_prime(p) or k=0 then ?9/0 end if
return power(p,k-1)*pisano_period(p)
end function
function pisano(integer m)
-- Calculates the Pisano period of 'm' using pisanoPrime.
if m=1 then return 1 end if
sequence s = prime_factors(m, true, get_maxprime(m))&0,
pps = {}
integer k = 1, p = s[1]
for i=2 to length(s) do
integer n = s[i]
if n!=p then
pps = append(pps,pisanoPrime(p,k))
{k,p} = {1,n}
else
k += 1
end if
end for
return lcm(pps)
end function
procedure p(integer k, lim)
-- test harness
printf(1,"pisanoPrimes")
integer pdx = 1, c = 0
while true do
integer p = get_prime(pdx)
if p>=lim then exit end if
c += 1
if c=7 then puts(1,"\n ") c = 1
elsif pdx>1 then puts(1,", ") end if
printf(1,"(%3d,%d)=%3d",{p,k,pisanoPrime(p,k)})
pdx += 1
end while
printf(1,"\n")
end procedure
p(2,15)
p(1,180)
sequence p180 = {}
for n=1 to 180 do p180 &= pisano(n) end for
printf(1,"pisano(1..180):\n")
pp(p180,{pp_IntFmt,"%4d",pp_IntCh,false})
|
http://rosettacode.org/wiki/Pinstripe/Display | Pinstripe/Display | Sample image
The task is to demonstrate the creation of a series of vertical pinstripes across the entire width of the display.
in the first quarter the pinstripes should alternate one pixel white, one pixel black = 1 pixel wide vertical pinestripes
Quarter of the way down the display, we can switch to a wider 2 pixel wide vertical pinstripe pattern, alternating two pixels white, two pixels black.
Half way down the display, we switch to 3 pixels wide,
for the lower quarter of the display we use 4 pixels.
c.f. Colour_pinstripe/Display
| #BBC_BASIC | BBC BASIC | GWL_STYLE = -16
HWND_TOPMOST = -1
WS_VISIBLE = &10000000
WS_CLIPCHILDREN = &2000000
WS_CLIPSIBLINGS = &4000000
SYS "GetSystemMetrics", 0 TO xscreen%
SYS "GetSystemMetrics", 1 TO yscreen%
SYS "SetWindowLong", @hwnd%, GWL_STYLE, WS_VISIBLE + \
\ WS_CLIPCHILDREN + WS_CLIPSIBLINGS
SYS "SetWindowPos", @hwnd%, HWND_TOPMOST, 0, 0, xscreen%, yscreen%, 0
VDU 26
FOR X% = 0 TO xscreen%*4-4 STEP 4
RECTANGLE FILL X%,yscreen%*3/2,2,yscreen%/2
NEXT
FOR X% = 0 TO xscreen%*4-8 STEP 8
RECTANGLE FILL X%,yscreen%*2/2,4,yscreen%/2
NEXT
FOR X% = 0 TO xscreen%*4-12 STEP 12
RECTANGLE FILL X%,yscreen%*1/2,6,yscreen%/2
NEXT
FOR X% = 0 TO xscreen%*4-16 STEP 16
RECTANGLE FILL X%,yscreen%*0/2,8,yscreen%/2
NEXT |
http://rosettacode.org/wiki/Pinstripe/Display | Pinstripe/Display | Sample image
The task is to demonstrate the creation of a series of vertical pinstripes across the entire width of the display.
in the first quarter the pinstripes should alternate one pixel white, one pixel black = 1 pixel wide vertical pinestripes
Quarter of the way down the display, we can switch to a wider 2 pixel wide vertical pinstripe pattern, alternating two pixels white, two pixels black.
Half way down the display, we switch to 3 pixels wide,
for the lower quarter of the display we use 4 pixels.
c.f. Colour_pinstripe/Display
| #Befunge | Befunge | "%":*3-"`"8*>4/::8%00p8/10p4*\55+"1P",,v
,:.\.5vv-g025:\-1_$$55+,\:v1+*8g01g00_@>
024,+5<>/2%.1+\:>^<:\0:\-1_$20g1-:20p^1p |
http://rosettacode.org/wiki/Primality_by_trial_division | Primality by trial division | Task
Write a boolean function that tells whether a given integer is prime.
Remember that 1 and all non-positive numbers are not prime.
Use trial division.
Even numbers greater than 2 may be eliminated right away.
A loop from 3 to √ n will suffice, but other loops are allowed.
Related tasks
count in factors
prime decomposition
AKS test for primes
factors of an integer
Sieve of Eratosthenes
factors of a Mersenne number
trial factoring of a Mersenne number
partition an integer X into N primes
sequence of primes by Trial Division
| #Pascal | Pascal | program primes;
function prime(n: integer): boolean;
var
i: integer; max: real;
begin
if n = 2 then
prime := true
else if (n <= 1) or (n mod 2 = 0) then
prime := false
else begin
prime := true; i := 3; max := sqrt(n);
while i <= max do begin
if n mod i = 0 then begin
prime := false; exit
end;
i := i + 2
end
end
end;
{ Test and display primes 0 .. 50 }
var
n: integer;
begin
for n := 0 to 50 do
if (prime(n)) then
write(n, ' ');
end. |
http://rosettacode.org/wiki/Prime_decomposition | Prime decomposition | The prime decomposition of a number is defined as a list of prime numbers
which when all multiplied together, are equal to that number.
Example
12 = 2 × 2 × 3, so its prime decomposition is {2, 2, 3}
Task
Write a function which returns an array or collection which contains the prime decomposition of a given number
n
{\displaystyle n}
greater than 1.
If your language does not have an isPrime-like function available,
you may assume that you have a function which determines
whether a number is prime (note its name before your code).
If you would like to test code from this task, you may use code from trial division or the Sieve of Eratosthenes.
Note: The program must not be limited by the word size of your computer or some other artificial limit; it should work for any number regardless of size (ignoring the physical limits of RAM etc).
Related tasks
count in factors
factors of an integer
Sieve of Eratosthenes
primality by trial division
factors of a Mersenne number
trial factoring of a Mersenne number
partition an integer X into N primes
sequence of primes by Trial Division
| #VBScript | VBScript | Function PrimeFactors(n)
arrP = Split(ListPrimes(n)," ")
divnum = n
Do Until divnum = 1
'The -1 is to account for the null element of arrP
For i = 0 To UBound(arrP)-1
If divnum = 1 Then
Exit For
ElseIf divnum Mod arrP(i) = 0 Then
divnum = divnum/arrP(i)
PrimeFactors = PrimeFactors & arrP(i) & " "
End If
Next
Loop
End Function
Function IsPrime(n)
If n = 2 Then
IsPrime = True
ElseIf n <= 1 Or n Mod 2 = 0 Then
IsPrime = False
Else
IsPrime = True
For i = 3 To Int(Sqr(n)) Step 2
If n Mod i = 0 Then
IsPrime = False
Exit For
End If
Next
End If
End Function
Function ListPrimes(n)
ListPrimes = ""
For i = 1 To n
If IsPrime(i) Then
ListPrimes = ListPrimes & i & " "
End If
Next
End Function
WScript.StdOut.Write PrimeFactors(CInt(WScript.Arguments(0)))
WScript.StdOut.WriteLine |
http://rosettacode.org/wiki/Plasma_effect | Plasma effect | The plasma effect is a visual effect created by applying various functions, notably sine and cosine, to the color values of screen pixels. When animated (not a task requirement) the effect may give the impression of a colorful flowing liquid.
Task
Create a plasma effect.
See also
Computer Graphics Tutorial (lodev.org)
Plasma (bidouille.org)
| #AWK | AWK |
#!/usr/bin/awk -f
function clamp(val, a, b) { return (val<a) ? a : (val>b) ? b : val }
## return a timestamp with centisecond precision
function timex() {
getline < "/proc/uptime"
close("/proc/uptime")
return $1
}
## draw image to terminal
function draw(src, xpos, ypos, w,h, x,y, up,dn, line,screen) {
w = src["width"]
h = src["height"]
for (y=0; y<h; y+=2) {
line = sprintf("\033[%0d;%0dH", y/2+ypos+1, xpos+1)
for (x=0; x<w; x++) {
up = src[x,y+0]
dn = src[x,y+1]
line = line "\033[38;2;" palette[up] ";48;2;" palette[dn] "m▀"
}
screen = screen line "\033[0m"
}
printf("%s", screen)
}
## generate a palette
function paletteGen( i, r,g,b) {
# generate palette
for (i=0; i<256; i++) {
r = 128 + 128 * sin(3.14159265 * i / 32.0)
g = 128 + 128 * sin(3.14159265 * i / 64.0)
b = 128 + 128 * sin(3.14159265 * i / 128.0)
palette[i] = sprintf("%d;%d;%d", clamp(r,0,255), clamp(g,0,255), clamp(b,0,255))
}
}
## generate a plasma
function plasmaGen(plasma, w, h, x,y, color) {
for (y=0; y<h; y++) {
for (x=0; x<w; x++) {
color = ( \
128.0 + (128.0 * sin((x / 8.0) - cos(now/2) )) \
+ 128.0 + (128.0 * sin((y / 16.0) - sin(now)*2 )) \
+ 128.0 + (128.0 * sin(sqrt((x - w / 2.0) * (x - w / 2.0) + (y - h / 2.0) * (y - h / 2.0)) / 4.0)) \
+ 128.0 + (128.0 * sin((sqrt(x * x + y * y) / 4.0) - sin(now/4) )) \
) / 4;
plasma[x,y] = int(color)
}
}
}
BEGIN {
"stty size" | getline
buffer["height"] = h = ($1 ? $1 : 24) * 2
buffer["width"] = w = ($2 ? $2 : 80)
paletteGen()
start = timex()
while (elapsed < 30) {
elapsed = (now = timex()) - start
plasmaGen(plasma, w, h)
# copy plasma to buffer
for (y=0; y<h; y++)
for (x=0; x<w; x++)
buffer[x,y] = int(plasma[x,y] + now * 100) % 256
# draw buffer to terminal
draw(buffer)
}
printf("\n")
}
|
http://rosettacode.org/wiki/Pisano_period | Pisano period | The Fibonacci sequence taken modulo 2 is a periodic sequence of period 3 : 0, 1, 1, 0, 1, 1, ...
For any integer n, the Fibonacci sequence taken modulo n is periodic and the length of the periodic cycle is referred to as the Pisano period.
Prime numbers are straightforward; the Pisano period of a prime number p is simply: pisano(p). The Pisano period of a composite number c may be found in different ways. It may be calculated directly: pisano(c), which works, but may be time consuming to find, especially for larger integers, or, it may be calculated by finding the least common multiple of the Pisano periods of each composite component.
E.G.
Given a Pisano period function: pisano(x), and a least common multiple function lcm(x, y):
pisano(m × n) is equivalent to lcm(pisano(m), pisano(n)) where m and n are coprime
A formulae to calculate the pisano period for integer powers k of prime numbers p is:
pisano(pk) == p(k-1)pisano(p)
The equation is conjectured, no exceptions have been seen.
If a positive integer i is split into its prime factors, then the second and first equations above can be applied to generate the pisano period.
Task
Write 2 functions: pisanoPrime(p,k) and pisano(m).
pisanoPrime(p,k) should return the Pisano period of pk where p is prime and k is a positive integer.
pisano(m) should use pisanoPrime to return the Pisano period of m where m is a positive integer.
Print pisanoPrime(p,2) for every prime lower than 15.
Print pisanoPrime(p,1) for every prime lower than 180.
Print pisano(m) for every integer from 1 to 180.
Related tasks
Fibonacci sequence
Prime decomposition
Least common multiple
| #Python | Python | from sympy import isprime, lcm, factorint, primerange
from functools import reduce
def pisano1(m):
"Simple definition"
if m < 2:
return 1
lastn, n = 0, 1
for i in range(m ** 2):
lastn, n = n, (lastn + n) % m
if lastn == 0 and n == 1:
return i + 1
return 1
def pisanoprime(p, k):
"Use conjecture π(p ** k) == p ** (k − 1) * π(p) for prime p and int k > 1"
assert isprime(p) and k > 0
return p ** (k - 1) * pisano1(p)
def pisano_mult(m, n):
"pisano(m*n) where m and n assumed coprime integers"
return lcm(pisano1(m), pisano1(n))
def pisano2(m):
"Uses prime factorization of m"
return reduce(lcm, (pisanoprime(prime, mult)
for prime, mult in factorint(m).items()), 1)
if __name__ == '__main__':
for n in range(1, 181):
assert pisano1(n) == pisano2(n), "Wall-Sun-Sun prime exists??!!"
print("\nPisano period (p, 2) for primes less than 50\n ",
[pisanoprime(prime, 2) for prime in primerange(1, 50)])
print("\nPisano period (p, 1) for primes less than 180\n ",
[pisanoprime(prime, 1) for prime in primerange(1, 180)])
print("\nPisano period (p) for integers 1 to 180")
for i in range(1, 181):
print(" %3d" % pisano2(i), end="" if i % 10 else "\n") |
http://rosettacode.org/wiki/Pinstripe/Display | Pinstripe/Display | Sample image
The task is to demonstrate the creation of a series of vertical pinstripes across the entire width of the display.
in the first quarter the pinstripes should alternate one pixel white, one pixel black = 1 pixel wide vertical pinestripes
Quarter of the way down the display, we can switch to a wider 2 pixel wide vertical pinstripe pattern, alternating two pixels white, two pixels black.
Half way down the display, we switch to 3 pixels wide,
for the lower quarter of the display we use 4 pixels.
c.f. Colour_pinstripe/Display
| #C | C |
#include<graphics.h>
#include<conio.h>
#define sections 4
int main()
{
int d=DETECT,m,maxX,maxY,x,y,increment=1;
initgraph(&d,&m,"c:/turboc3/bgi");
maxX = getmaxx();
maxY = getmaxy();
for(y=0;y<maxY;y+=maxY/sections)
{
for(x=0;x<maxX;x+=increment)
{
setfillstyle(SOLID_FILL,(x/increment)%2==0?BLACK:WHITE); //The only line which differs
bar(x,y,x+increment,y+maxY/sections);
}
increment++;
}
getch();
closegraph();
return 0;
}
|
http://rosettacode.org/wiki/Primality_by_trial_division | Primality by trial division | Task
Write a boolean function that tells whether a given integer is prime.
Remember that 1 and all non-positive numbers are not prime.
Use trial division.
Even numbers greater than 2 may be eliminated right away.
A loop from 3 to √ n will suffice, but other loops are allowed.
Related tasks
count in factors
prime decomposition
AKS test for primes
factors of an integer
Sieve of Eratosthenes
factors of a Mersenne number
trial factoring of a Mersenne number
partition an integer X into N primes
sequence of primes by Trial Division
| #Perl | Perl | sub prime { my $n = shift || $_;
$n % $_ or return for 2 .. sqrt $n;
$n > 1
}
print join(', ' => grep prime, 1..100), "\n"; |
http://rosettacode.org/wiki/Prime_decomposition | Prime decomposition | The prime decomposition of a number is defined as a list of prime numbers
which when all multiplied together, are equal to that number.
Example
12 = 2 × 2 × 3, so its prime decomposition is {2, 2, 3}
Task
Write a function which returns an array or collection which contains the prime decomposition of a given number
n
{\displaystyle n}
greater than 1.
If your language does not have an isPrime-like function available,
you may assume that you have a function which determines
whether a number is prime (note its name before your code).
If you would like to test code from this task, you may use code from trial division or the Sieve of Eratosthenes.
Note: The program must not be limited by the word size of your computer or some other artificial limit; it should work for any number regardless of size (ignoring the physical limits of RAM etc).
Related tasks
count in factors
factors of an integer
Sieve of Eratosthenes
primality by trial division
factors of a Mersenne number
trial factoring of a Mersenne number
partition an integer X into N primes
sequence of primes by Trial Division
| #Wren | Wren | import "/big" for BigInt
import "/fmt" for Fmt
var vals = [1 << 31, 1234567, 333333, 987653, 2 * 3 * 5 * 7 * 11 * 13 * 17]
for (val in vals) {
Fmt.print("$10d -> $n", val, BigInt.primeFactors(val))
} |
http://rosettacode.org/wiki/Plasma_effect | Plasma effect | The plasma effect is a visual effect created by applying various functions, notably sine and cosine, to the color values of screen pixels. When animated (not a task requirement) the effect may give the impression of a colorful flowing liquid.
Task
Create a plasma effect.
See also
Computer Graphics Tutorial (lodev.org)
Plasma (bidouille.org)
| #C | C |
#include<windows.h>
#include<stdlib.h>
#include<stdio.h>
#include<time.h>
#include<math.h>
#define pi M_PI
int main()
{
CONSOLE_SCREEN_BUFFER_INFO info;
int cols, rows;
time_t t;
int i,j;
GetConsoleScreenBufferInfo(GetStdHandle(STD_OUTPUT_HANDLE), &info);
cols = info.srWindow.Right - info.srWindow.Left + 1;
rows = info.srWindow.Bottom - info.srWindow.Top + 1;
HANDLE console;
console = GetStdHandle(STD_OUTPUT_HANDLE);
system("@clear||cls");
srand((unsigned)time(&t));
for(i=0;i<rows;i++)
for(j=0;j<cols;j++){
SetConsoleTextAttribute(console,fabs(sin(pi*(rand()%254 + 1)/255.0))*254);
printf("%c",219);
}
getchar();
return 0;
}
|
http://rosettacode.org/wiki/Playfair_cipher | Playfair cipher | Playfair cipher
You are encouraged to solve this task according to the task description, using any language you may know.
Task
Implement a Playfair cipher for encryption and decryption.
The user must be able to choose J = I or no Q in the alphabet.
The output of the encrypted and decrypted message must be in capitalized digraphs, separated by spaces.
Output example
HI DE TH EG OL DI NT HE TR EX ES TU MP
| #11l | 11l | F uniq(seq)
[Char] seen
L(x) seq
I x !C seen
seen.append(x)
R seen
F partition(seq, n)
R (0 .< seq.len).step(n).map(i -> @seq[i .< i + @n])
F canonicalize(s)
R s.uppercase().filter(c -> c.is_uppercase()).join(‘’).replace(‘J’, ‘I’)
T Playfair
[String = String] dec, enc
F (key)
V m = partition(uniq(canonicalize(key‘ABCDEFGHIJKLMNOPQRSTUVWXYZ’)), 5)
L(row) m
L(i, j) cart_product(0.<5, 0.<5)
I i != j
.enc[row[i]‘’row[j]] = row[(i + 1) % 5]‘’row[(j + 1) % 5]
L(ci) 5
V c = [m[0][ci], m[1][ci], m[2][ci], m[3][ci], m[4][ci]]
L(i, j) cart_product(0.<5, 0.<5)
I i != j
.enc[c[i]‘’c[j]] = c[(i + 1) % 5]‘’c[(j + 1) % 5]
L(i1, j1, i2, j2) cart_product(0.<5, 0.<5, 0.<5, 0.<5)
I i1 != i2 & j1 != j2
.enc[m[i1][j1]‘’m[i2][j2]] = m[i1][j2]‘’m[i2][j1]
.dec = Dict(.enc.map((k, v) -> (v, k)))
F encode(txt)
V c = canonicalize(txt)
[String] lst
V i = 0
L i < c.len - 1
I c[i + 1] == c[i]
lst [+]= c[i]‘X’
i++
E
lst [+]= c[i]‘’c[i + 1]
i += 2
I i == c.len - 1
lst [+]= c.last‘X’
R lst.map(a -> @.enc[a]).join(‘ ’)
F decode(encoded)
R partition(canonicalize(encoded), 2).map(p -> @.dec[p]).join(‘ ’)
V playfair = Playfair(‘Playfair example’)
V orig = ‘Hide the gold in...the TREESTUMP!!!’
print(‘Original: ’orig)
V enc = playfair.encode(orig)
print(‘Encoded: ’enc)
print(‘Decoded: ’playfair.decode(enc)) |
http://rosettacode.org/wiki/Pisano_period | Pisano period | The Fibonacci sequence taken modulo 2 is a periodic sequence of period 3 : 0, 1, 1, 0, 1, 1, ...
For any integer n, the Fibonacci sequence taken modulo n is periodic and the length of the periodic cycle is referred to as the Pisano period.
Prime numbers are straightforward; the Pisano period of a prime number p is simply: pisano(p). The Pisano period of a composite number c may be found in different ways. It may be calculated directly: pisano(c), which works, but may be time consuming to find, especially for larger integers, or, it may be calculated by finding the least common multiple of the Pisano periods of each composite component.
E.G.
Given a Pisano period function: pisano(x), and a least common multiple function lcm(x, y):
pisano(m × n) is equivalent to lcm(pisano(m), pisano(n)) where m and n are coprime
A formulae to calculate the pisano period for integer powers k of prime numbers p is:
pisano(pk) == p(k-1)pisano(p)
The equation is conjectured, no exceptions have been seen.
If a positive integer i is split into its prime factors, then the second and first equations above can be applied to generate the pisano period.
Task
Write 2 functions: pisanoPrime(p,k) and pisano(m).
pisanoPrime(p,k) should return the Pisano period of pk where p is prime and k is a positive integer.
pisano(m) should use pisanoPrime to return the Pisano period of m where m is a positive integer.
Print pisanoPrime(p,2) for every prime lower than 15.
Print pisanoPrime(p,1) for every prime lower than 180.
Print pisano(m) for every integer from 1 to 180.
Related tasks
Fibonacci sequence
Prime decomposition
Least common multiple
| #Raku | Raku | use Prime::Factor;
constant @fib := 1,1,*+*…*;
my %cache;
multi pisano-period (Int $p where *.is-prime, Int $k where * > 0 = 1) {
return %cache{"$p|$k"} if %cache{"$p|$k"};
my $fibmod = @fib.map: * % $p**$k;
%cache{"$p|$k"} = (1..*).first: { !$fibmod[$_-1] and ($fibmod[$_] == 1) }
}
multi pisano-period (Int $p where * > 0 ) {
[lcm] prime-factors($p).Bag.map: { samewith .key, .value }
}
put "Pisano period (p, 2) for primes less than 50";
put (map { pisano-period($_, 2) }, ^50 .grep: *.is-prime )».fmt('%4d');
put "\nPisano period (p, 1) for primes less than 180";
.put for (map { pisano-period($_, 1) }, ^180 .grep: *.is-prime )».fmt('%4d').batch(15);
put "\nPisano period (p, 1) for integers 1 to 180";
.put for (1..180).map( { pisano-period($_) } )».fmt('%4d').batch(15); |
http://rosettacode.org/wiki/Pinstripe/Display | Pinstripe/Display | Sample image
The task is to demonstrate the creation of a series of vertical pinstripes across the entire width of the display.
in the first quarter the pinstripes should alternate one pixel white, one pixel black = 1 pixel wide vertical pinestripes
Quarter of the way down the display, we can switch to a wider 2 pixel wide vertical pinstripe pattern, alternating two pixels white, two pixels black.
Half way down the display, we switch to 3 pixels wide,
for the lower quarter of the display we use 4 pixels.
c.f. Colour_pinstripe/Display
| #C.23 | C# |
using System.Drawing;
public class Pinstripe
{
static void Main(string[] args)
{
var pinstripe = MakePinstripeImage(1366, 768);
pinstripe.Save("pinstripe.png");
}
public static Bitmap MakePinstripeImage(int width, int height)
{
var image = new Bitmap(width, height);
var quarterHeight = height / 4;
for (var y = 0; y < height; y++)
{
var stripeWidth = (y / quarterHeight) + 1;
for (var x = 0; x < width; x++)
{
var color = ((x / stripeWidth) % 2) == 0 ? Color.White : Color.Black;
image.SetPixel(x, y, color);
}
}
return image;
}
}
|
http://rosettacode.org/wiki/Primality_by_trial_division | Primality by trial division | Task
Write a boolean function that tells whether a given integer is prime.
Remember that 1 and all non-positive numbers are not prime.
Use trial division.
Even numbers greater than 2 may be eliminated right away.
A loop from 3 to √ n will suffice, but other loops are allowed.
Related tasks
count in factors
prime decomposition
AKS test for primes
factors of an integer
Sieve of Eratosthenes
factors of a Mersenne number
trial factoring of a Mersenne number
partition an integer X into N primes
sequence of primes by Trial Division
| #Phix | Phix | function is_prime_by_trial_division(integer n)
if n<2 then return 0 end if
if n=2 then return 1 end if
if remainder(n,2)=0 then return 0 end if
for i=3 to floor(sqrt(n)) by 2 do
if remainder(n,i)=0 then
return 0
end if
end for
return 1
end function
?filter(tagset(32),is_prime_by_trial_division)
|
http://rosettacode.org/wiki/Prime_decomposition | Prime decomposition | The prime decomposition of a number is defined as a list of prime numbers
which when all multiplied together, are equal to that number.
Example
12 = 2 × 2 × 3, so its prime decomposition is {2, 2, 3}
Task
Write a function which returns an array or collection which contains the prime decomposition of a given number
n
{\displaystyle n}
greater than 1.
If your language does not have an isPrime-like function available,
you may assume that you have a function which determines
whether a number is prime (note its name before your code).
If you would like to test code from this task, you may use code from trial division or the Sieve of Eratosthenes.
Note: The program must not be limited by the word size of your computer or some other artificial limit; it should work for any number regardless of size (ignoring the physical limits of RAM etc).
Related tasks
count in factors
factors of an integer
Sieve of Eratosthenes
primality by trial division
factors of a Mersenne number
trial factoring of a Mersenne number
partition an integer X into N primes
sequence of primes by Trial Division
| #XSLT | XSLT | <xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0">
<xsl:template match="/numbers">
<html>
<body>
<ul>
<xsl:apply-templates />
</ul>
</body>
</html>
</xsl:template>
<xsl:template match="number">
<li>
Number:
<xsl:apply-templates mode="value" />
Factors:
<xsl:apply-templates mode="factors" />
</li>
</xsl:template>
<xsl:template match="value" mode="value">
<xsl:apply-templates />
</xsl:template>
<xsl:template match="value" mode="factors">
<xsl:call-template name="generate">
<xsl:with-param name="number" select="number(current())" />
<xsl:with-param name="candidate" select="number(2)" />
</xsl:call-template>
</xsl:template>
<xsl:template name="generate">
<xsl:param name="number" />
<xsl:param name="candidate" />
<xsl:choose>
<!-- 1 is no prime and does not have any factors -->
<xsl:when test="$number = 1"></xsl:when>
<!-- if the candidate is larger than the sqrt of the number, it's prime and the last factor -->
<xsl:when test="$candidate * $candidate > $number">
<xsl:value-of select="$number" />
</xsl:when>
<!-- if the number is factored by the candidate, add the factor and try again with the same factor -->
<xsl:when test="$number mod $candidate = 0">
<xsl:value-of select="$candidate" />
<xsl:text> </xsl:text>
<xsl:call-template name="generate">
<xsl:with-param name="number" select="$number div $candidate" />
<xsl:with-param name="candidate" select="$candidate" />
</xsl:call-template>
</xsl:when>
<!-- else try again with the next factor -->
<xsl:otherwise>
<!-- increment by 2 to save stack depth -->
<xsl:choose>
<xsl:when test="$candidate = 2">
<xsl:call-template name="generate">
<xsl:with-param name="number" select="$number" />
<xsl:with-param name="candidate" select="$candidate + 1" />
</xsl:call-template>
</xsl:when>
<xsl:otherwise>
<xsl:call-template name="generate">
<xsl:with-param name="number" select="$number" />
<xsl:with-param name="candidate" select="$candidate + 2" />
</xsl:call-template>
</xsl:otherwise>
</xsl:choose>
</xsl:otherwise>
</xsl:choose>
</xsl:template>
</xsl:stylesheet> |
http://rosettacode.org/wiki/Plasma_effect | Plasma effect | The plasma effect is a visual effect created by applying various functions, notably sine and cosine, to the color values of screen pixels. When animated (not a task requirement) the effect may give the impression of a colorful flowing liquid.
Task
Create a plasma effect.
See also
Computer Graphics Tutorial (lodev.org)
Plasma (bidouille.org)
| #C.2B.2B | C++ |
#include <windows.h>
#include <math.h>
#include <string>
const int BMP_SIZE = 240, MY_TIMER = 987654;
class myBitmap {
public:
myBitmap() : pen( NULL ), brush( NULL ), clr( 0 ), wid( 1 ) {}
~myBitmap() {
DeleteObject( pen ); DeleteObject( brush );
DeleteDC( hdc ); DeleteObject( bmp );
}
bool create( int w, int h ) {
BITMAPINFO bi;
ZeroMemory( &bi, sizeof( bi ) );
bi.bmiHeader.biSize = sizeof( bi.bmiHeader );
bi.bmiHeader.biBitCount = sizeof( DWORD ) * 8;
bi.bmiHeader.biCompression = BI_RGB;
bi.bmiHeader.biPlanes = 1;
bi.bmiHeader.biWidth = w;
bi.bmiHeader.biHeight = -h;
HDC dc = GetDC( GetConsoleWindow() );
bmp = CreateDIBSection( dc, &bi, DIB_RGB_COLORS, &pBits, NULL, 0 );
if( !bmp ) return false;
hdc = CreateCompatibleDC( dc );
SelectObject( hdc, bmp );
ReleaseDC( GetConsoleWindow(), dc );
width = w; height = h;
return true;
}
void clear( BYTE clr = 0 ) {
memset( pBits, clr, width * height * sizeof( DWORD ) );
}
void setBrushColor( DWORD bClr ) {
if( brush ) DeleteObject( brush );
brush = CreateSolidBrush( bClr );
SelectObject( hdc, brush );
}
void setPenColor( DWORD c ) {
clr = c; createPen();
}
void setPenWidth( int w ) {
wid = w; createPen();
}
void saveBitmap( std::string path ) {
BITMAPFILEHEADER fileheader;
BITMAPINFO infoheader;
BITMAP bitmap;
DWORD wb;
GetObject( bmp, sizeof( bitmap ), &bitmap );
DWORD* dwpBits = new DWORD[bitmap.bmWidth * bitmap.bmHeight];
ZeroMemory( dwpBits, bitmap.bmWidth * bitmap.bmHeight * sizeof( DWORD ) );
ZeroMemory( &infoheader, sizeof( BITMAPINFO ) );
ZeroMemory( &fileheader, sizeof( BITMAPFILEHEADER ) );
infoheader.bmiHeader.biBitCount = sizeof( DWORD ) * 8;
infoheader.bmiHeader.biCompression = BI_RGB;
infoheader.bmiHeader.biPlanes = 1;
infoheader.bmiHeader.biSize = sizeof( infoheader.bmiHeader );
infoheader.bmiHeader.biHeight = bitmap.bmHeight;
infoheader.bmiHeader.biWidth = bitmap.bmWidth;
infoheader.bmiHeader.biSizeImage = bitmap.bmWidth * bitmap.bmHeight * sizeof( DWORD );
fileheader.bfType = 0x4D42;
fileheader.bfOffBits = sizeof( infoheader.bmiHeader ) + sizeof( BITMAPFILEHEADER );
fileheader.bfSize = fileheader.bfOffBits + infoheader.bmiHeader.biSizeImage;
GetDIBits( hdc, bmp, 0, height, ( LPVOID )dwpBits, &infoheader, DIB_RGB_COLORS );
HANDLE file = CreateFile( path.c_str(), GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL );
WriteFile( file, &fileheader, sizeof( BITMAPFILEHEADER ), &wb, NULL );
WriteFile( file, &infoheader.bmiHeader, sizeof( infoheader.bmiHeader ), &wb, NULL );
WriteFile( file, dwpBits, bitmap.bmWidth * bitmap.bmHeight * 4, &wb, NULL );
CloseHandle( file );
delete [] dwpBits;
}
HDC getDC() const { return hdc; }
DWORD* bits() { return ( DWORD* )pBits; }
private:
void createPen() {
if( pen ) DeleteObject( pen );
pen = CreatePen( PS_SOLID, wid, clr );
SelectObject( hdc, pen );
}
HBITMAP bmp; HDC hdc;
HPEN pen; HBRUSH brush;
void *pBits; int width, height, wid;
DWORD clr;
};
class plasma
{
public:
plasma() {
currentTime = 0; _WD = BMP_SIZE >> 1; _WV = BMP_SIZE << 1;
_bmp.create( BMP_SIZE, BMP_SIZE ); _bmp.clear();
plasma1 = new BYTE[BMP_SIZE * BMP_SIZE * 4];
plasma2 = new BYTE[BMP_SIZE * BMP_SIZE * 4];
int i, j, dst = 0;
double temp;
for( j = 0; j < BMP_SIZE * 2; j++ ) {
for( i = 0; i < BMP_SIZE * 2; i++ ) {
plasma1[dst] = ( BYTE )( 128.0 + 127.0 * ( cos( ( double )hypot( BMP_SIZE - j, BMP_SIZE - i ) / 64.0 ) ) );
plasma2[dst] = ( BYTE )( ( sin( ( sqrt( 128.0 + ( BMP_SIZE - i ) * ( BMP_SIZE - i ) +
( BMP_SIZE - j ) * ( BMP_SIZE - j ) ) - 4.0 ) / 32.0 ) + 1 ) * 90.0 );
dst++;
}
}
}
void update() {
DWORD dst;
BYTE a, c1,c2, c3;
currentTime += ( double )( rand() % 2 + 1 );
int x1 = _WD + ( int )( ( _WD - 1 ) * sin( currentTime / 137 ) ),
x2 = _WD + ( int )( ( _WD - 1 ) * sin( -currentTime / 75 ) ),
x3 = _WD + ( int )( ( _WD - 1 ) * sin( -currentTime / 125 ) ),
y1 = _WD + ( int )( ( _WD - 1 ) * cos( currentTime / 123 ) ),
y2 = _WD + ( int )( ( _WD - 1 ) * cos( -currentTime / 85 ) ),
y3 = _WD + ( int )( ( _WD - 1 ) * cos( -currentTime / 108 ) );
int src1 = y1 * _WV + x1, src2 = y2 * _WV + x2, src3 = y3 * _WV + x3;
DWORD* bits = _bmp.bits();
for( int j = 0; j < BMP_SIZE; j++ ) {
dst = j * BMP_SIZE;
for( int i= 0; i < BMP_SIZE; i++ ) {
a = plasma2[src1] + plasma1[src2] + plasma2[src3];
c1 = a << 1; c2 = a << 2; c3 = a << 3;
bits[dst + i] = RGB( c1, c2, c3 );
src1++; src2++; src3++;
}
src1 += BMP_SIZE; src2 += BMP_SIZE; src3 += BMP_SIZE;
}
draw();
}
void setHWND( HWND hwnd ) { _hwnd = hwnd; }
private:
void draw() {
HDC dc = _bmp.getDC(), wdc = GetDC( _hwnd );
BitBlt( wdc, 0, 0, BMP_SIZE, BMP_SIZE, dc, 0, 0, SRCCOPY );
ReleaseDC( _hwnd, wdc );
}
myBitmap _bmp; HWND _hwnd; float _ang;
BYTE *plasma1, *plasma2;
double currentTime; int _WD, _WV;
};
class wnd
{
public:
wnd() { _inst = this; }
int wnd::Run( HINSTANCE hInst ) {
_hInst = hInst; _hwnd = InitAll();
SetTimer( _hwnd, MY_TIMER, 15, NULL );
_plasma.setHWND( _hwnd );
ShowWindow( _hwnd, SW_SHOW );
UpdateWindow( _hwnd );
MSG msg;
ZeroMemory( &msg, sizeof( msg ) );
while( msg.message != WM_QUIT ) {
if( PeekMessage( &msg, NULL, 0, 0, PM_REMOVE ) != 0 ) {
TranslateMessage( &msg );
DispatchMessage( &msg );
}
}
return UnregisterClass( "_MY_PLASMA_", _hInst );
}
private:
void wnd::doPaint( HDC dc ) { _plasma.update(); }
void wnd::doTimer() { _plasma.update(); }
static int WINAPI wnd::WndProc( HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam ) {
switch( msg ) {
case WM_PAINT: {
PAINTSTRUCT ps;
_inst->doPaint( BeginPaint( hWnd, &ps ) );
EndPaint( hWnd, &ps );
return 0;
}
case WM_DESTROY: PostQuitMessage( 0 ); break;
case WM_TIMER: _inst->doTimer(); break;
default: return DefWindowProc( hWnd, msg, wParam, lParam );
}
return 0;
}
HWND InitAll() {
WNDCLASSEX wcex;
ZeroMemory( &wcex, sizeof( wcex ) );
wcex.cbSize = sizeof( WNDCLASSEX );
wcex.style = CS_HREDRAW | CS_VREDRAW;
wcex.lpfnWndProc = ( WNDPROC )WndProc;
wcex.hInstance = _hInst;
wcex.hCursor = LoadCursor( NULL, IDC_ARROW );
wcex.hbrBackground = ( HBRUSH )( COLOR_WINDOW + 1 );
wcex.lpszClassName = "_MY_PLASMA_";
RegisterClassEx( &wcex );
RECT rc = { 0, 0, BMP_SIZE, BMP_SIZE };
AdjustWindowRect( &rc, WS_SYSMENU | WS_CAPTION, FALSE );
int w = rc.right - rc.left, h = rc.bottom - rc.top;
return CreateWindow( "_MY_PLASMA_", ".: Plasma -- PJorente :.", WS_SYSMENU, CW_USEDEFAULT, 0, w, h, NULL, NULL, _hInst, NULL );
}
static wnd* _inst; HINSTANCE _hInst; HWND _hwnd; plasma _plasma;
};
wnd* wnd::_inst = 0;
int APIENTRY WinMain( HINSTANCE hInstance, HINSTANCE hPrevInstance, LPTSTR lpCmdLine, int nCmdShow ) {
wnd myWnd;
return myWnd.Run( hInstance );
}
|
http://rosettacode.org/wiki/Playfair_cipher | Playfair cipher | Playfair cipher
You are encouraged to solve this task according to the task description, using any language you may know.
Task
Implement a Playfair cipher for encryption and decryption.
The user must be able to choose J = I or no Q in the alphabet.
The output of the encrypted and decrypted message must be in capitalized digraphs, separated by spaces.
Output example
HI DE TH EG OL DI NT HE TR EX ES TU MP
| #C.2B.2B | C++ | #include <iostream>
#include <string>
using namespace std;
class playfair
{
public:
void doIt( string k, string t, bool ij, bool e )
{
createGrid( k, ij ); getTextReady( t, ij, e );
if( e ) doIt( 1 ); else doIt( -1 );
display();
}
private:
void doIt( int dir )
{
int a, b, c, d; string ntxt;
for( string::const_iterator ti = _txt.begin(); ti != _txt.end(); ti++ )
{
if( getCharPos( *ti++, a, b ) )
if( getCharPos( *ti, c, d ) )
{
if( a == c ) { ntxt += getChar( a, b + dir ); ntxt += getChar( c, d + dir ); }
else if( b == d ){ ntxt += getChar( a + dir, b ); ntxt += getChar( c + dir, d ); }
else { ntxt += getChar( c, b ); ntxt += getChar( a, d ); }
}
}
_txt = ntxt;
}
void display()
{
cout << "\n\n OUTPUT:\n=========" << endl;
string::iterator si = _txt.begin(); int cnt = 0;
while( si != _txt.end() )
{
cout << *si; si++; cout << *si << " "; si++;
if( ++cnt >= 26 ) cout << endl, cnt = 0;
}
cout << endl << endl;
}
char getChar( int a, int b )
{
return _m[ (b + 5) % 5 ][ (a + 5) % 5 ];
}
bool getCharPos( char l, int &a, int &b )
{
for( int y = 0; y < 5; y++ )
for( int x = 0; x < 5; x++ )
if( _m[y][x] == l )
{ a = x; b = y; return true; }
return false;
}
void getTextReady( string t, bool ij, bool e )
{
for( string::iterator si = t.begin(); si != t.end(); si++ )
{
*si = toupper( *si ); if( *si < 65 || *si > 90 ) continue;
if( *si == 'J' && ij ) *si = 'I';
else if( *si == 'Q' && !ij ) continue;
_txt += *si;
}
if( e )
{
string ntxt = ""; size_t len = _txt.length();
for( size_t x = 0; x < len; x += 2 )
{
ntxt += _txt[x];
if( x + 1 < len )
{
if( _txt[x] == _txt[x + 1] ) ntxt += 'X';
ntxt += _txt[x + 1];
}
}
_txt = ntxt;
}
if( _txt.length() & 1 ) _txt += 'X';
}
void createGrid( string k, bool ij )
{
if( k.length() < 1 ) k = "KEYWORD";
k += "ABCDEFGHIJKLMNOPQRSTUVWXYZ"; string nk = "";
for( string::iterator si = k.begin(); si != k.end(); si++ )
{
*si = toupper( *si ); if( *si < 65 || *si > 90 ) continue;
if( ( *si == 'J' && ij ) || ( *si == 'Q' && !ij ) )continue;
if( nk.find( *si ) == -1 ) nk += *si;
}
copy( nk.begin(), nk.end(), &_m[0][0] );
}
string _txt; char _m[5][5];
};
int main( int argc, char* argv[] )
{
string key, i, txt; bool ij, e;
cout << "(E)ncode or (D)ecode? "; getline( cin, i ); e = ( i[0] == 'e' || i[0] == 'E' );
cout << "Enter a en/decryption key: "; getline( cin, key );
cout << "I <-> J (Y/N): "; getline( cin, i ); ij = ( i[0] == 'y' || i[0] == 'Y' );
cout << "Enter the text: "; getline( cin, txt );
playfair pf; pf.doIt( key, txt, ij, e ); return system( "pause" );
} |
http://rosettacode.org/wiki/Pisano_period | Pisano period | The Fibonacci sequence taken modulo 2 is a periodic sequence of period 3 : 0, 1, 1, 0, 1, 1, ...
For any integer n, the Fibonacci sequence taken modulo n is periodic and the length of the periodic cycle is referred to as the Pisano period.
Prime numbers are straightforward; the Pisano period of a prime number p is simply: pisano(p). The Pisano period of a composite number c may be found in different ways. It may be calculated directly: pisano(c), which works, but may be time consuming to find, especially for larger integers, or, it may be calculated by finding the least common multiple of the Pisano periods of each composite component.
E.G.
Given a Pisano period function: pisano(x), and a least common multiple function lcm(x, y):
pisano(m × n) is equivalent to lcm(pisano(m), pisano(n)) where m and n are coprime
A formulae to calculate the pisano period for integer powers k of prime numbers p is:
pisano(pk) == p(k-1)pisano(p)
The equation is conjectured, no exceptions have been seen.
If a positive integer i is split into its prime factors, then the second and first equations above can be applied to generate the pisano period.
Task
Write 2 functions: pisanoPrime(p,k) and pisano(m).
pisanoPrime(p,k) should return the Pisano period of pk where p is prime and k is a positive integer.
pisano(m) should use pisanoPrime to return the Pisano period of m where m is a positive integer.
Print pisanoPrime(p,2) for every prime lower than 15.
Print pisanoPrime(p,1) for every prime lower than 180.
Print pisano(m) for every integer from 1 to 180.
Related tasks
Fibonacci sequence
Prime decomposition
Least common multiple
| #REXX | REXX | /*REXX pgm calculates pisano period for a range of N, and pisanoPrime(N,m) [for primes]*/
numeric digits 500 /*ensure enough decimal digits for Fib.*/
parse arg lim.1 lim.2 lim.3 . /*obtain optional arguments from the CL*/
if lim.1=='' | lim.1=="," then lim.1= 15 - 1 /*Not specified? Then use the default.*/
if lim.2=='' | lim.2=="," then lim.2= 180 - 1 /* " " " " " " */
if lim.3=='' | lim.3=="," then lim.3= 180 /* " " " " " " */
call Fib /* " " Fibonacci numbers. */
do i=1 for max(lim.1, lim.2, lim.3); call pisano(i) /*find pisano periods.*/
end /*i*/; w= length(i)
do j=1 for 2; #= word(2 1, j)
do p=1 for lim.j; if \isPrime(p) then iterate /*Not prime? Skip this number.*/
say ' pisanoPrime('right(p, w)", "#') = 'right( pisanoPrime(p, #), 5)
end /*p*/; say
end /*j*/
say center(' pisano numbers for 1──►'lim.3" ", 20*4 - 1, "═") /*display a title.*/
$=
do j=1 for lim.3; $= $ right(@.j, w) /*append pisano number to the $ list.*/
if j//20==0 then do; say substr($, 2); $=; end /*display 20 numbers to a line*/
end /*j*/
say substr($, 2) /*possible display any residuals──►term*/
exit 0 /*stick a fork in it, we're all done. */
/*──────────────────────────────────────────────────────────────────────────────────────*/
fib: procedure expose fib.; parse arg x; fib.=.; if x=='' then x= 1000
fib.0= 0; fib.1= 1; if fib.x\==. then return fib.x
do k=2 for x-1; a= k-1; b= k-2; fib.k= fib.a + fib.b
end /*k*/; return fib.k
/*──────────────────────────────────────────────────────────────────────────────────────*/
isPrime: parse arg n; if n<11 then return pos(n, '2 3 5 7')>0; if n//2==0 then return 0
do k=3 by 2 while k*k<=n; if n//k==0 then return 0; end /*k*/; return 1
/*──────────────────────────────────────────────────────────────────────────────────────*/
pisano: procedure expose @. fib.; parse arg m; if m==1 then do; @.m=1; return 1; end
do k=1; _= k+1; if fib.k//m==0 & fib._//m==1 then leave
end /*k*/; @.m= k; return k
/*──────────────────────────────────────────────────────────────────────────────────────*/
pisanoPrime: procedure expose @. fib.; parse arg m,n; return m**(n-1) * pisano(m) |
http://rosettacode.org/wiki/Pinstripe/Display | Pinstripe/Display | Sample image
The task is to demonstrate the creation of a series of vertical pinstripes across the entire width of the display.
in the first quarter the pinstripes should alternate one pixel white, one pixel black = 1 pixel wide vertical pinestripes
Quarter of the way down the display, we can switch to a wider 2 pixel wide vertical pinstripe pattern, alternating two pixels white, two pixels black.
Half way down the display, we switch to 3 pixels wide,
for the lower quarter of the display we use 4 pixels.
c.f. Colour_pinstripe/Display
| #C.2B.2B | C++ |
#include <windows.h>
//--------------------------------------------------------------------------------------------------
class pinstripe
{
public:
pinstripe() { createColors(); }
void setDimensions( int x, int y ) { _mw = x; _mh = y; }
void createColors()
{
colors[0] = 0; colors[1] = RGB( 255, 255, 255 );
}
void draw( HDC dc )
{
HPEN pen;
int lh = _mh / 4, row, cp;
for( int lw = 1; lw < 5; lw++ )
{
cp = 0;
row = ( lw - 1 ) * lh;
for( int x = 0 + lw > 1 ? lw > 3 ? 2 : 1 : 0; x < _mw; x += lw )
{
pen = CreatePen( PS_SOLID, lw, colors[cp] );
++cp %= 2;
SelectObject( dc, pen );
MoveToEx( dc, x, row, NULL );
LineTo( dc, x, row + lh );
DeleteObject( pen );
}
}
}
private:
int _mw, _mh;
DWORD colors[2];
};
//--------------------------------------------------------------------------------------------------
pinstripe pin;
//--------------------------------------------------------------------------------------------------
void PaintWnd( HWND hWnd )
{
PAINTSTRUCT ps;
HDC hdc = BeginPaint( hWnd, &ps );
pin.draw( hdc );
EndPaint( hWnd, &ps );
}
//--------------------------------------------------------------------------------------------------
LRESULT CALLBACK WndProc( HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam )
{
switch( msg )
{
case WM_DESTROY: PostQuitMessage( 0 ); break;
case WM_PAINT: PaintWnd( hWnd ); break;
default:
return DefWindowProc( hWnd, msg, wParam, lParam );
}
return 0;
}
//--------------------------------------------------------------------------------------------------
HWND InitAll( HINSTANCE hInstance )
{
WNDCLASSEX wcex;
ZeroMemory( &wcex, sizeof( wcex ) );
wcex.cbSize = sizeof( WNDCLASSEX );
wcex.style = CS_HREDRAW | CS_VREDRAW;
wcex.lpfnWndProc = WndProc;
wcex.hInstance = hInstance;
wcex.hCursor = LoadCursor( NULL, IDC_ARROW );
wcex.hbrBackground = ( HBRUSH )( COLOR_WINDOW + 1 );
wcex.lpszClassName = "_BW_PS_";
RegisterClassEx( &wcex );
return CreateWindow( "_BW_PS_", ".: Pinstripe -- PJorente :.", WS_POPUP, CW_USEDEFAULT, 0, 200, 200, NULL, NULL, hInstance, NULL );
}
//--------------------------------------------------------------------------------------------------
int APIENTRY _tWinMain( HINSTANCE hInstance, HINSTANCE hPrevInstance, LPTSTR lpCmdLine, int nCmdShow )
{
srand( GetTickCount() );
HWND hwnd = InitAll( hInstance );
if( !hwnd ) return -1;
int mw = GetSystemMetrics( SM_CXSCREEN ),
mh = GetSystemMetrics( SM_CYSCREEN );
pin.setDimensions( mw, mh );
RECT rc = { 0, 0, mw, mh };
AdjustWindowRectEx( &rc, WS_POPUP, FALSE, 0 );
int w = rc.right - rc.left,
h = rc.bottom - rc.top;
int posX = ( GetSystemMetrics( SM_CXSCREEN ) >> 1 ) - ( w >> 1 ),
posY = ( GetSystemMetrics( SM_CYSCREEN ) >> 1 ) - ( h >> 1 );
SetWindowPos( hwnd, HWND_TOP, posX, posY, w, h, SWP_NOZORDER );
ShowWindow( hwnd, nCmdShow );
UpdateWindow( hwnd );
MSG msg;
ZeroMemory( &msg, sizeof( msg ) );
while( msg.message != WM_QUIT )
{
if( PeekMessage( &msg, NULL, 0, 0, PM_REMOVE ) != 0 )
{
TranslateMessage( &msg );
DispatchMessage( &msg );
}
}
return UnregisterClass( "_BW_PS_", hInstance );
}
//--------------------------------------------------------------------------------------------------
|
http://rosettacode.org/wiki/Primality_by_trial_division | Primality by trial division | Task
Write a boolean function that tells whether a given integer is prime.
Remember that 1 and all non-positive numbers are not prime.
Use trial division.
Even numbers greater than 2 may be eliminated right away.
A loop from 3 to √ n will suffice, but other loops are allowed.
Related tasks
count in factors
prime decomposition
AKS test for primes
factors of an integer
Sieve of Eratosthenes
factors of a Mersenne number
trial factoring of a Mersenne number
partition an integer X into N primes
sequence of primes by Trial Division
| #PHP | PHP | <?php
function prime($a) {
if (($a % 2 == 0 && $a != 2) || $a < 2)
return false;
$limit = sqrt($a);
for ($i = 2; $i <= $limit; $i++)
if ($a % $i == 0)
return false;
return true;
}
foreach (range(1, 100) as $x)
if (prime($x)) echo "$x\n";
?> |
http://rosettacode.org/wiki/Prime_decomposition | Prime decomposition | The prime decomposition of a number is defined as a list of prime numbers
which when all multiplied together, are equal to that number.
Example
12 = 2 × 2 × 3, so its prime decomposition is {2, 2, 3}
Task
Write a function which returns an array or collection which contains the prime decomposition of a given number
n
{\displaystyle n}
greater than 1.
If your language does not have an isPrime-like function available,
you may assume that you have a function which determines
whether a number is prime (note its name before your code).
If you would like to test code from this task, you may use code from trial division or the Sieve of Eratosthenes.
Note: The program must not be limited by the word size of your computer or some other artificial limit; it should work for any number regardless of size (ignoring the physical limits of RAM etc).
Related tasks
count in factors
factors of an integer
Sieve of Eratosthenes
primality by trial division
factors of a Mersenne number
trial factoring of a Mersenne number
partition an integer X into N primes
sequence of primes by Trial Division
| #zkl | zkl | fcn primeFactors(n){ // Return a list of factors of n
acc:=fcn(n,k,acc,maxD){ // k is 2,3,5,7,9,... not optimum
if(n==1 or k>maxD) acc.close();
else{
q,r:=n.divr(k); // divr-->(quotient,remainder)
if(r==0) return(self.fcn(q,k,acc.write(k),q.toFloat().sqrt()));
return(self.fcn(n,k+1+k.isOdd,acc,maxD))
}
}(n,2,Sink(List),n.toFloat().sqrt());
m:=acc.reduce('*,1); // mulitply factors
if(n!=m) acc.append(n/m); // opps, missed last factor
else acc;
} |
http://rosettacode.org/wiki/Plasma_effect | Plasma effect | The plasma effect is a visual effect created by applying various functions, notably sine and cosine, to the color values of screen pixels. When animated (not a task requirement) the effect may give the impression of a colorful flowing liquid.
Task
Create a plasma effect.
See also
Computer Graphics Tutorial (lodev.org)
Plasma (bidouille.org)
| #Ceylon | Ceylon |
import javafx.application {
Application
}
import javafx.stage {
Stage
}
import javafx.scene {
Scene
}
import javafx.scene.layout {
BorderPane
}
import javafx.scene.image {
WritableImage,
ImageView
}
import ceylon.numeric.float {
sin,
sqrt,
remainder
}
import javafx.scene.paint {
Color
}
import javafx.animation {
AnimationTimer
}
shared void run() {
Application.launch(`Plasma`);
}
shared class Plasma() extends Application() {
function createPlasma(Integer width, Integer height) => [
for (j in 0:height) [
for (i in 0:width)
let (x = i.float, y = j.float)
( sin(x / 16.0)
+ sin(y / 8.0)
+ sin((x + y) / 16.0)
+ sin(sqrt(x ^ 2.0 + y ^ 2.0) / 8.0)
+ 4.0 )
/ 8.0
]
];
void writeImage(Float[][] plasma, WritableImage img, Float hueShift = 0.0) {
value writer = img.pixelWriter;
for(j->row in plasma.indexed) {
for(i->percent in row.indexed) {
value hue = remainder(hueShift + percent, 1.0) * 360.0;
writer.setColor(i, j, Color.hsb(hue, 1.0, 1.0));
}
}
}
shared actual void start(Stage primaryStage) {
value w = 500;
value h = 500;
value plasma = createPlasma(w, h);
value img = WritableImage(w, h);
writeImage(plasma, img);
value root = BorderPane();
root.center = ImageView(img);
variable value hueShift = 0.0;
value timer = object extends AnimationTimer() {
shared actual void handle(Integer now) {
hueShift = remainder(hueShift + 0.02, 1.0);
writeImage(plasma, img, hueShift);
}
};
timer.start();
value scene = Scene(root);
primaryStage.title = "Plasma";
primaryStage.setScene(scene);
primaryStage.sizeToScene();
primaryStage.show();
}
} |
http://rosettacode.org/wiki/Plasma_effect | Plasma effect | The plasma effect is a visual effect created by applying various functions, notably sine and cosine, to the color values of screen pixels. When animated (not a task requirement) the effect may give the impression of a colorful flowing liquid.
Task
Create a plasma effect.
See also
Computer Graphics Tutorial (lodev.org)
Plasma (bidouille.org)
| #Common_Lisp | Common Lisp | (require :lispbuilder-sdl)
(require :simple-rgb)
(defparameter *palette*
(let ((palette-aux (make-array 256 :element-type 'fixnum)))
(dotimes (i 256)
(let ((color_i (simple-rgb:hsv->rgb (simple-rgb:hsv (/ i 255.0) 1.0 1.0))))
(setf (aref palette-aux i) (loop :for component :across color_i
:for i :from 0
:sum (ash component (* 8 i))))))
palette-aux)
"palette")
(defun value->color (palette palette-shift index)
(aref palette (mod (+ index palette-shift) (length palette))))
(defun return-color-by-pos (x y &optional w h)
"returns a color index"
(floor
(/ (+ (+ 128.0 (* 128.0 (sin (/ x 16.0))))
(+ 128.0 (* 128.0 (sin (/ y 8.0))))
(+ 128.0 (* 128.0 (sin (/ (+ x y) 16.0))))
(+ 128.0 (* 128.0 (sin (/ (sqrt (+ (* x x) (* y y))) 8.0)))))
4.0)))
(defun return-color-by-pos-another (x y &optional w h)
"a different function that returns a color index"
(floor
(/ (+ (+ 128.0 (* 128.0 (sin (/ x 16.0))))
(+ 128.0 (* 128.0 (sin (/ y 32.0))))
(+ 128.0 (* 128.0 (sin (/ (sqrt (+ (expt (/ (- x w) 2.0) 2) (expt (/ (- y h) 2.0) 2))) 8.0))))
(+ 128.0 (* 128.0 (sin (/ (sqrt (+ (* x x) (* y y))) 8.0)))))
4.0)))
(defun plasma-render (surface palette-shift)
"render plasma"
(let ((width (sdl:width surface))
(height (sdl:height surface)))
(sdl-base::with-pixel (s (sdl:fp surface))
(dotimes (h height)
(dotimes (w width)
(sdl-base::write-pixel s w h (value->color *palette* palette-shift (funcall #'return-color-by-pos-another w h width height)))))))
surface)
(defun demo/plasma ()
"main function: shows a window rendering a plasma efect"
(sdl:with-init ()
(let ((win (sdl:window 320 240
:bpp 24
:resizable nil
:title-caption "demo/plasma"
:icon-caption "demo/plasma")))
(let ((palette-shift 0))
(sdl:update-display win)
(sdl:with-events ()
(:idle
(plasma-render win palette-shift)
(sdl:update-display win)
(incf palette-shift))
(:video-expose-event () (sdl:update-display win))
(:key-down-event (:key key)
(when (or
(sdl:key= key :sdl-key-escape)
(sdl:key= key :sdl-key-q))
(sdl:push-quit-event)))
(:quit-event () t))))))
(demo/plasma) |
http://rosettacode.org/wiki/Playfair_cipher | Playfair cipher | Playfair cipher
You are encouraged to solve this task according to the task description, using any language you may know.
Task
Implement a Playfair cipher for encryption and decryption.
The user must be able to choose J = I or no Q in the alphabet.
The output of the encrypted and decrypted message must be in capitalized digraphs, separated by spaces.
Output example
HI DE TH EG OL DI NT HE TR EX ES TU MP
| #D | D | import std.stdio, std.array, std.algorithm, std.range, std.ascii,
std.conv, std.string, std.regex, std.typecons;
string unique(in string s) pure nothrow @safe {
string result;
foreach (immutable char c; s)
if (!result.representation.canFind(c)) // Assumes ASCII string.
result ~= c;
return result;
}
struct Playfair {
string from, to;
string[string] enc, dec;
this(in string key, in string from_ = "J", in string to_ = null)
pure /*nothrow @safe*/ {
this.from = from_;
if (to_.empty)
this.to = (from_ == "J") ? "I" : "";
immutable m = _canonicalize(key ~ uppercase)
.unique
.chunks(5)
.map!text
.array;
auto I5 = 5.iota;
foreach (immutable R; m)
foreach (immutable i, immutable j; cartesianProduct(I5, I5))
if (i != j)
enc[[R[i], R[j]]] = [R[(i + 1) % 5], R[(j+1) % 5]];
foreach (immutable r; I5) {
immutable c = m.transversal(r).array;
foreach (immutable i, immutable j; cartesianProduct(I5, I5))
if (i != j)
enc[[c[i], c[j]]] = [c[(i + 1) % 5], c[(j+1) % 5]];
}
foreach (i1, j1, i2, j2; cartesianProduct(I5, I5, I5, I5))
if (i1 != i2 && j1 != j2)
enc[[m[i1][j1], m[i2][j2]]] = [m[i1][j2], m[i2][j1]];
dec = enc.byKeyValue.map!(t => tuple(t.value, t.key)).assocArray;
}
private string _canonicalize(in string s) const pure @safe {
return s.toUpper.removechars("^A-Z").replace(from, to);
}
string encode(in string s) const /*pure @safe*/ {
return _canonicalize(s)
.matchAll(r"(.)(?:(?!\1)(.))?")
.map!(m => enc[m[0].leftJustify(2, 'X')])
.join(' ');
}
string decode(in string s) const pure @safe {
return _canonicalize(s).chunks(2).map!(p => dec[p.text]).join(' ');
}
}
void main() /*@safe*/ {
/*immutable*/ const pf = Playfair("Playfair example");
immutable orig = "Hide the gold in...the TREESTUMP!!!";
writeln("Original: ", orig);
immutable enc = pf.encode(orig);
writeln(" Encoded: ", enc);
writeln(" Decoded: ", pf.decode(enc));
} |
http://rosettacode.org/wiki/Pisano_period | Pisano period | The Fibonacci sequence taken modulo 2 is a periodic sequence of period 3 : 0, 1, 1, 0, 1, 1, ...
For any integer n, the Fibonacci sequence taken modulo n is periodic and the length of the periodic cycle is referred to as the Pisano period.
Prime numbers are straightforward; the Pisano period of a prime number p is simply: pisano(p). The Pisano period of a composite number c may be found in different ways. It may be calculated directly: pisano(c), which works, but may be time consuming to find, especially for larger integers, or, it may be calculated by finding the least common multiple of the Pisano periods of each composite component.
E.G.
Given a Pisano period function: pisano(x), and a least common multiple function lcm(x, y):
pisano(m × n) is equivalent to lcm(pisano(m), pisano(n)) where m and n are coprime
A formulae to calculate the pisano period for integer powers k of prime numbers p is:
pisano(pk) == p(k-1)pisano(p)
The equation is conjectured, no exceptions have been seen.
If a positive integer i is split into its prime factors, then the second and first equations above can be applied to generate the pisano period.
Task
Write 2 functions: pisanoPrime(p,k) and pisano(m).
pisanoPrime(p,k) should return the Pisano period of pk where p is prime and k is a positive integer.
pisano(m) should use pisanoPrime to return the Pisano period of m where m is a positive integer.
Print pisanoPrime(p,2) for every prime lower than 15.
Print pisanoPrime(p,1) for every prime lower than 180.
Print pisano(m) for every integer from 1 to 180.
Related tasks
Fibonacci sequence
Prime decomposition
Least common multiple
| #Sidef | Sidef | func pisano_period_pp(p,k) is cached {
assert(k.is_pos, "k = #{k} must be positive")
assert(p.is_prime, "p = #{p} must be prime")
var (a, b, n) = (0, 1, p**k)
1..Inf -> first_by {
(a, b) = (b, (a+b) % n)
(a == 0) && (b == 1)
}
}
func pisano_period(n) {
n.factor_map {|p,k| pisano_period_pp(p, k) }.lcm
}
say "Pisano periods for squares of primes p <= 15:"
say 15.primes.map {|p| pisano_period_pp(p, 2) }
say "\nPisano periods for primes p <= 180:"
say 180.primes.map {|p| pisano_period_pp(p, 1) }
say "\nPisano periods for integers n from 1 to 180:"
say pisano_period.map(1..180) |
http://rosettacode.org/wiki/Pinstripe/Display | Pinstripe/Display | Sample image
The task is to demonstrate the creation of a series of vertical pinstripes across the entire width of the display.
in the first quarter the pinstripes should alternate one pixel white, one pixel black = 1 pixel wide vertical pinestripes
Quarter of the way down the display, we can switch to a wider 2 pixel wide vertical pinstripe pattern, alternating two pixels white, two pixels black.
Half way down the display, we switch to 3 pixels wide,
for the lower quarter of the display we use 4 pixels.
c.f. Colour_pinstripe/Display
| #FreeBASIC | FreeBASIC | ' version 14-03-2017
' compile with: fbc -s console
' or compile with: fbc -s gui
Dim As UInteger ps, col, h, w, x, y1, y2
ScreenInfo w, h
' create display size window, 8bit color (palette), no frame
ScreenRes w, h, 8,, 8
' vga palette black = 0 and white = 15
h = h \ 4 : y2 = h -1
For ps = 1 To 4
col = 0
For x = 0 To (w - ps -1) Step ps
Line (x, y1) - (x + ps -1, y2), col, bf
col = 15 - col ' col alternate between 0 (black) and 15 (white)
Next
y1 += h : y2 += h
Next
' empty keyboard buffer
While InKey <> "" : Wend
'Print : Print "hit any key to end program"
Sleep
End |
http://rosettacode.org/wiki/Primality_by_trial_division | Primality by trial division | Task
Write a boolean function that tells whether a given integer is prime.
Remember that 1 and all non-positive numbers are not prime.
Use trial division.
Even numbers greater than 2 may be eliminated right away.
A loop from 3 to √ n will suffice, but other loops are allowed.
Related tasks
count in factors
prime decomposition
AKS test for primes
factors of an integer
Sieve of Eratosthenes
factors of a Mersenne number
trial factoring of a Mersenne number
partition an integer X into N primes
sequence of primes by Trial Division
| #Picat | Picat | is_prime1(N) =>
if N == 2 then
true
elseif N <= 1 ; N mod 2 == 0 then
false
else
foreach(I in 3..2..ceiling(sqrt(N)))
N mod I > 0
end
end. |
http://rosettacode.org/wiki/Plasma_effect | Plasma effect | The plasma effect is a visual effect created by applying various functions, notably sine and cosine, to the color values of screen pixels. When animated (not a task requirement) the effect may give the impression of a colorful flowing liquid.
Task
Create a plasma effect.
See also
Computer Graphics Tutorial (lodev.org)
Plasma (bidouille.org)
| #Forth | Forth | : sqrt ( u -- sqrt ) ( Babylonian method )
dup 2/ ( first square root guess is half )
dup 0= if drop exit then ( sqrt[0]=0, sqrt[1]=1 )
begin dup >r 2dup / r> + 2/ ( stack: square old-guess new-guess )
2dup > while ( as long as guess is decreasing )
nip repeat ( forget old-guess and repeat )
drop nip ;
: sgn 0< if -1 else 1 then ;
: isin
256 mod 128 - \ full circle is 255 "degrees"
dup dup sgn * 128 swap - * \ second order approximation
negate 32 / ; \ amplitude is +/-128
: color-shape 256 mod 6 * 765 - abs 256 - 0 max 255 min ; \ trapezes
: hue
dup color-shape . \ red
dup 170 + color-shape . \ green
85 + color-shape . ; \ blue
: plasma
outfile-id >r
s" plasma.ppm" w/o create-file throw to outfile-id
s\" P3\n500 500\n255\n" type
500 0 do
500 0 do
i 2 * isin 128 +
j 4 * isin 128 + +
i j + isin 2 * 128 + +
i i * j j * + sqrt 4 * isin 128 + +
4 /
hue
s\" \n" type
loop
s\" \n" type
loop
outfile-id close-file throw
r> to outfile-id ;
plasma |
http://rosettacode.org/wiki/Plasma_effect | Plasma effect | The plasma effect is a visual effect created by applying various functions, notably sine and cosine, to the color values of screen pixels. When animated (not a task requirement) the effect may give the impression of a colorful flowing liquid.
Task
Create a plasma effect.
See also
Computer Graphics Tutorial (lodev.org)
Plasma (bidouille.org)
| #FreeBASIC | FreeBASIC | ' version 12-04-2017
' compile with: fbc -s gui
' Computer Graphics Tutorial (lodev.org), last example
#Define dist(a, b, c, d) Sqr(((a - c) * (a - c) + (b - d) * (b - d)))
Const As ULong w = 256
Const As ULong h = 256
ScreenRes w, h, 24
WindowTitle ("Plasma effect")
Dim As ULong x, y
Dim As UByte c
Dim As Double time_, value
Do
time_ += .99
ScreenLock
For x = 0 To w -1
For y = 0 To h -1
value = Sin(dist(x + time_, y, 128, 128) / 8) _
+ Sin(dist(x, y, 64, 64) / 8) _
+ Sin(dist(x, y + time_ / 7, 192, 64) / 7) _
+ Sin(dist(x, y, 192, 100) / 8) + 4
' c = Int(value) * 32
c = int(value * 32)
PSet(x, y), RGB(c, c * 2, 255 - c)
Next
Next
ScreenUnLock
Sleep 1
If Inkey <> "" Or Inkey = Chr(255) + "k" Then
End
End If
Loop |
http://rosettacode.org/wiki/Playfair_cipher | Playfair cipher | Playfair cipher
You are encouraged to solve this task according to the task description, using any language you may know.
Task
Implement a Playfair cipher for encryption and decryption.
The user must be able to choose J = I or no Q in the alphabet.
The output of the encrypted and decrypted message must be in capitalized digraphs, separated by spaces.
Output example
HI DE TH EG OL DI NT HE TR EX ES TU MP
| #FreeBASIC | FreeBASIC | ' FB 1.05.0 Win64
Enum PlayFairOption
noQ
iEqualsJ
End Enum
Dim Shared pfo As PlayFairOption '' set this before calling buildTable
Dim Shared table(1 To 5, 1 To 5) As UInteger
Sub buildTable(keyword As String)
Dim used(1 To 26) As Boolean '' all false by default
If pfo = noQ Then
used(17) = True
Else
used(10) = True
End If
Dim As String alphabet = UCase(keyword) + "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
Dim As UInteger i = 1, j = 1, k
Dim As Integer c
For k = 0 To Len(alphabet) - 1
c = alphabet[k] - 64
If c < 1 OrElse c > 26 Then Continue For
If Not used(c) Then
table(i, j) = c
used(c) = True
j += 1
If j = 6 Then
i += 1
If i = 6 Then Return '' table has been filled
j = 1
End If
End If
Next k
End Sub
Function getCleanText(plainText As String) As String
plainText = UCase(plainText) '' ensure everything is upper case
' get rid of any non-letters and insert X between duplicate letters
Dim As String cleanText = "", prevChar = "", nextChar
For i As UInteger = 1 To Len(plainText)
nextChar = Mid(plainText, i, 1)
' It appears that Q should be omitted altogether if noQ option is specified - we assume so anyway
If nextChar < "A" OrElse nextChar > "Z" OrElse (nextChar = "Q" AndAlso pfo = noQ) Then Continue For
' If iEqualsJ option specified, replace J with I
If nextChar = "J" AndAlso pfo = iEqualsJ Then nextChar = "I"
If nextChar <> prevChar Then
cleanText += nextChar
Else
cleanText += "X" + nextChar
End If
prevChar = nextChar
Next
If Len(cleanText) Mod 2 = 1 Then '' dangling letter at end so add another letter to complete digram
If Right(cleanText, 1) <> "X" Then
cleanText += "X"
Else
cleanText += "Z"
End If
End If
Return cleanText
End Function
Sub findChar(c As uInteger, ByRef row As UInteger, ByRef col As UInteger)
For i As UInteger = 1 To 5
For j As UInteger = 1 To 5
If table(i, j) = c Then
row = i
col = j
Return
End If
Next j
Next i
End Sub
Function encodePlayfair(plainText As String) As String
Dim As String cleanText = getCleanText(plainText)
Dim As String digram, cipherDigram, cipherText = ""
Dim As UInteger length = Len(cleanText)
Dim As UInteger char1, char2, row1, col1, row2, col2
For i As UInteger = 1 To length Step 2
digram = Mid(cleanText, i, 2)
char1 = digram[0] - 64
char2 = digram[1] - 64
findChar char1, row1, col1
findChar char2, row2, col2
If row1 = row2 Then
cipherDigram = Chr(table(row1, col1 Mod 5 + 1) + 64)
cipherDigram += Chr(table(row2, col2 Mod 5 + 1) + 64)
ElseIf col1 = col2 Then
cipherDigram = Chr(table(row1 Mod 5 + 1, col1) + 64)
cipherDigram += Chr(table(row2 Mod 5 + 1, col2) + 64)
Else
cipherDigram = Chr(table(row1, col2) + 64)
cipherDigram += Chr(table(row2, col1) + 64)
End If
cipherText += cipherDigram
If i < length Then cipherText += " "
Next i
Return cipherText
End Function
Function decodePlayfair(cipherText As String) As String
Dim As String digram, cipherDigram, decodedText = ""
Dim As UInteger length = Len(cipherText)
Dim As UInteger char1, char2, row1, col1, row2, col2
For i As UInteger = 1 To length Step 3 '' cipherText will include spaces so we need to skip them
cipherDigram = Mid(cipherText, i, 2)
char1 = cipherDigram[0] - 64
char2 = cipherDigram[1] - 64
findChar char1, row1, col1
findChar char2, row2, col2
If row1 = row2 Then
digram = Chr(table(row1, IIf(col1 > 1, col1 - 1, 5)) + 64)
digram += Chr(table(row2, IIf(col2 > 1, col2 - 1, 5)) + 64)
ElseIf col1 = col2 Then
digram = Chr(table(IIf(row1 > 1, row1 - 1, 5), col1) + 64)
digram += Chr(table(IIf(row2 > 1, row2 - 1, 5), col2) + 64)
Else
digram = Chr(table(row1, col2) + 64)
digram += Chr(table(row2, col1) + 64)
End If
decodedText += digram
If i < length Then decodedText += " "
Next i
Return decodedText
End Function
Dim As String keyword, ignoreQ, plainText, encodedText, decodedText
Line Input "Enter Playfair keyword : "; keyword
Do
Line Input "Ignore Q when buiding table y/n : "; ignoreQ
ignoreQ = LCase(ignoreQ)
Loop Until ignoreQ = "y" Or ignoreQ = "n"
pfo = IIf(ignoreQ = "y", noQ, iEqualsJ)
buildTable(keyword)
Print "The table to be used is : " : Print
For i As UInteger = 1 To 5
For j As UInteger = 1 To 5
Print Chr(table(i, j) + 64); " ";
Next j
Print
Next i
Print
Line Input "Enter plain text : "; plainText
Print
encodedText = encodePlayfair(plainText)
Print "Encoded text is : "; encodedText
decodedText = decodePlayFair(encodedText)
Print "Decoded text is : "; decodedText
Print
Print "Press any key to quit"
Sleep |
http://rosettacode.org/wiki/Pisano_period | Pisano period | The Fibonacci sequence taken modulo 2 is a periodic sequence of period 3 : 0, 1, 1, 0, 1, 1, ...
For any integer n, the Fibonacci sequence taken modulo n is periodic and the length of the periodic cycle is referred to as the Pisano period.
Prime numbers are straightforward; the Pisano period of a prime number p is simply: pisano(p). The Pisano period of a composite number c may be found in different ways. It may be calculated directly: pisano(c), which works, but may be time consuming to find, especially for larger integers, or, it may be calculated by finding the least common multiple of the Pisano periods of each composite component.
E.G.
Given a Pisano period function: pisano(x), and a least common multiple function lcm(x, y):
pisano(m × n) is equivalent to lcm(pisano(m), pisano(n)) where m and n are coprime
A formulae to calculate the pisano period for integer powers k of prime numbers p is:
pisano(pk) == p(k-1)pisano(p)
The equation is conjectured, no exceptions have been seen.
If a positive integer i is split into its prime factors, then the second and first equations above can be applied to generate the pisano period.
Task
Write 2 functions: pisanoPrime(p,k) and pisano(m).
pisanoPrime(p,k) should return the Pisano period of pk where p is prime and k is a positive integer.
pisano(m) should use pisanoPrime to return the Pisano period of m where m is a positive integer.
Print pisanoPrime(p,2) for every prime lower than 15.
Print pisanoPrime(p,1) for every prime lower than 180.
Print pisano(m) for every integer from 1 to 180.
Related tasks
Fibonacci sequence
Prime decomposition
Least common multiple
| #Wren | Wren | import "/math" for Int
import "/fmt" for Fmt
// Calculates the Pisano period of 'm' from first principles.
var pisanoPeriod = Fn.new { |m|
var p = 0
var c = 1
for (i in 0...m*m) {
var t = p
p = c
c = (t + c) % m
if (p == 0 && c == 1) return i + 1
}
return 1
}
// Calculates the Pisano period of p^k where 'p' is prime and 'k' is a positive integer.
var pisanoPrime = Fn.new { |p, k|
if (!Int.isPrime(p) || k == 0) return 0 // can't do this one
return p.pow(k-1) * pisanoPeriod.call(p)
}
// Calculates the Pisano period of 'm' using pisanoPrime.
var pisano = Fn.new { |m|
var primes = Int.primeFactors(m)
var primePowers = {}
for (p in primes) {
var v = primePowers[p]
primePowers[p] = v ? v + 1 : 1
}
var pps = []
for (me in primePowers) pps.add(pisanoPrime.call(me.key, me.value))
if (pps.count == 0) return 1
if (pps.count == 1) return pps[0]
var f = pps[0]
var i = 1
while (i < pps.count) {
f = Int.lcm(f, pps[i])
i = i + 1
}
return f
}
for (p in 2..14) {
var pp = pisanoPrime.call(p, 2)
if (pp > 0) Fmt.print("pisanoPrime($2d: 2) = $d", p, pp)
}
System.print()
for (p in 2..179) {
var pp = pisanoPrime.call(p, 1)
if (pp > 0) Fmt.print("pisanoPrime($3d: 1) = $d", p, pp)
}
System.print("\npisano(n) for integers 'n' from 1 to 180 are:")
for (n in 1..180) {
Fmt.write("$3d ", pisano.call(n))
if (n != 1 && n%15 == 0) System.print()
}
System.print() |
http://rosettacode.org/wiki/Pinstripe/Display | Pinstripe/Display | Sample image
The task is to demonstrate the creation of a series of vertical pinstripes across the entire width of the display.
in the first quarter the pinstripes should alternate one pixel white, one pixel black = 1 pixel wide vertical pinestripes
Quarter of the way down the display, we can switch to a wider 2 pixel wide vertical pinstripe pattern, alternating two pixels white, two pixels black.
Half way down the display, we switch to 3 pixels wide,
for the lower quarter of the display we use 4 pixels.
c.f. Colour_pinstripe/Display
| #Gambas | Gambas | 'WARNING this takes a time to display
'Use the 'gb.qt4' component
Public Sub Form_Open()
Dim iColour As Integer[] = [Color.Black, Color.white]
Dim hPanel As Panel
Dim siCount, siCounter, siSet As Short
With Me
.Arrangement = Arrange.Row
.Border = False
.Height = Desktop.Height
.Width = Desktop.Width
.Fullscreen = True
End With
For siCounter = 1 To 4
For siCount = 1 To Desktop.Width Step siCounter
hpanel = New Panel(Me)
hpanel.Width = siCounter
hpanel.Height = Desktop.Height / 4
HPanel.Background = iColour[siSet]
Inc siSet
If siSet > 1 Then siSet = 0
Next
Next
End |
http://rosettacode.org/wiki/Primality_by_trial_division | Primality by trial division | Task
Write a boolean function that tells whether a given integer is prime.
Remember that 1 and all non-positive numbers are not prime.
Use trial division.
Even numbers greater than 2 may be eliminated right away.
A loop from 3 to √ n will suffice, but other loops are allowed.
Related tasks
count in factors
prime decomposition
AKS test for primes
factors of an integer
Sieve of Eratosthenes
factors of a Mersenne number
trial factoring of a Mersenne number
partition an integer X into N primes
sequence of primes by Trial Division
| #PicoLisp | PicoLisp | (de prime? (N)
(or
(= N 2)
(and
(> N 1)
(bit? 1 N)
(let S (sqrt N)
(for (D 3 T (+ D 2))
(T (> D S) T)
(T (=0 (% N D)) NIL) ) ) ) ) ) |
http://rosettacode.org/wiki/Plasma_effect | Plasma effect | The plasma effect is a visual effect created by applying various functions, notably sine and cosine, to the color values of screen pixels. When animated (not a task requirement) the effect may give the impression of a colorful flowing liquid.
Task
Create a plasma effect.
See also
Computer Graphics Tutorial (lodev.org)
Plasma (bidouille.org)
| #Go | Go | $ convert plasma.gif -coalesce plasma2.gif
$ eog plasma2.gif
|
http://rosettacode.org/wiki/Playfair_cipher | Playfair cipher | Playfair cipher
You are encouraged to solve this task according to the task description, using any language you may know.
Task
Implement a Playfair cipher for encryption and decryption.
The user must be able to choose J = I or no Q in the alphabet.
The output of the encrypted and decrypted message must be in capitalized digraphs, separated by spaces.
Output example
HI DE TH EG OL DI NT HE TR EX ES TU MP
| #Go | Go | package main
import (
"bufio"
"fmt"
"os"
"strings"
)
type playfairOption int
const (
noQ playfairOption = iota
iEqualsJ
)
type playfair struct {
keyword string
pfo playfairOption
table [5][5]byte
}
func (p *playfair) init() {
// Build table.
var used [26]bool // all elements false
if p.pfo == noQ {
used[16] = true // Q used
} else {
used[9] = true // J used
}
alphabet := strings.ToUpper(p.keyword) + "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
for i, j, k := 0, 0, 0; k < len(alphabet); k++ {
c := alphabet[k]
if c < 'A' || c > 'Z' {
continue
}
d := int(c - 65)
if !used[d] {
p.table[i][j] = c
used[d] = true
j++
if j == 5 {
i++
if i == 5 {
break // table has been filled
}
j = 0
}
}
}
}
func (p *playfair) getCleanText(plainText string) string {
// Ensure everything is upper case.
plainText = strings.ToUpper(plainText)
// Get rid of any non-letters and insert X between duplicate letters.
var cleanText strings.Builder
// Safe to assume null byte won't be present in plainText.
prevByte := byte('\000')
for i := 0; i < len(plainText); i++ {
nextByte := plainText[i]
// It appears that Q should be omitted altogether if NO_Q option is specified;
// we assume so anyway.
if nextByte < 'A' || nextByte > 'Z' || (nextByte == 'Q' && p.pfo == noQ) {
continue
}
// If iEqualsJ option specified, replace J with I.
if nextByte == 'J' && p.pfo == iEqualsJ {
nextByte = 'I'
}
if nextByte != prevByte {
cleanText.WriteByte(nextByte)
} else {
cleanText.WriteByte('X')
cleanText.WriteByte(nextByte)
}
prevByte = nextByte
}
l := cleanText.Len()
if l%2 == 1 {
// Dangling letter at end so add another letter to complete digram.
if cleanText.String()[l-1] != 'X' {
cleanText.WriteByte('X')
} else {
cleanText.WriteByte('Z')
}
}
return cleanText.String()
}
func (p *playfair) findByte(c byte) (int, int) {
for i := 0; i < 5; i++ {
for j := 0; j < 5; j++ {
if p.table[i][j] == c {
return i, j
}
}
}
return -1, -1
}
func (p *playfair) encode(plainText string) string {
cleanText := p.getCleanText(plainText)
var cipherText strings.Builder
l := len(cleanText)
for i := 0; i < l; i += 2 {
row1, col1 := p.findByte(cleanText[i])
row2, col2 := p.findByte(cleanText[i+1])
switch {
case row1 == row2:
cipherText.WriteByte(p.table[row1][(col1+1)%5])
cipherText.WriteByte(p.table[row2][(col2+1)%5])
case col1 == col2:
cipherText.WriteByte(p.table[(row1+1)%5][col1])
cipherText.WriteByte(p.table[(row2+1)%5][col2])
default:
cipherText.WriteByte(p.table[row1][col2])
cipherText.WriteByte(p.table[row2][col1])
}
if i < l-1 {
cipherText.WriteByte(' ')
}
}
return cipherText.String()
}
func (p *playfair) decode(cipherText string) string {
var decodedText strings.Builder
l := len(cipherText)
// cipherText will include spaces so we need to skip them.
for i := 0; i < l; i += 3 {
row1, col1 := p.findByte(cipherText[i])
row2, col2 := p.findByte(cipherText[i+1])
switch {
case row1 == row2:
temp := 4
if col1 > 0 {
temp = col1 - 1
}
decodedText.WriteByte(p.table[row1][temp])
temp = 4
if col2 > 0 {
temp = col2 - 1
}
decodedText.WriteByte(p.table[row2][temp])
case col1 == col2:
temp := 4
if row1 > 0 {
temp = row1 - 1
}
decodedText.WriteByte(p.table[temp][col1])
temp = 4
if row2 > 0 {
temp = row2 - 1
}
decodedText.WriteByte(p.table[temp][col2])
default:
decodedText.WriteByte(p.table[row1][col2])
decodedText.WriteByte(p.table[row2][col1])
}
if i < l-1 {
decodedText.WriteByte(' ')
}
}
return decodedText.String()
}
func (p *playfair) printTable() {
fmt.Println("The table to be used is :\n")
for i := 0; i < 5; i++ {
for j := 0; j < 5; j++ {
fmt.Printf("%c ", p.table[i][j])
}
fmt.Println()
}
}
func main() {
scanner := bufio.NewScanner(os.Stdin)
fmt.Print("Enter Playfair keyword : ")
scanner.Scan()
keyword := scanner.Text()
var ignoreQ string
for ignoreQ != "y" && ignoreQ != "n" {
fmt.Print("Ignore Q when building table y/n : ")
scanner.Scan()
ignoreQ = strings.ToLower(scanner.Text())
}
pfo := noQ
if ignoreQ == "n" {
pfo = iEqualsJ
}
var table [5][5]byte
pf := &playfair{keyword, pfo, table}
pf.init()
pf.printTable()
fmt.Print("\nEnter plain text : ")
scanner.Scan()
plainText := scanner.Text()
if err := scanner.Err(); err != nil {
fmt.Fprintln(os.Stderr, "reading standard input:", err)
return
}
encodedText := pf.encode(plainText)
fmt.Println("\nEncoded text is :", encodedText)
decodedText := pf.decode(encodedText)
fmt.Println("Deccoded text is :", decodedText)
} |
http://rosettacode.org/wiki/Pisano_period | Pisano period | The Fibonacci sequence taken modulo 2 is a periodic sequence of period 3 : 0, 1, 1, 0, 1, 1, ...
For any integer n, the Fibonacci sequence taken modulo n is periodic and the length of the periodic cycle is referred to as the Pisano period.
Prime numbers are straightforward; the Pisano period of a prime number p is simply: pisano(p). The Pisano period of a composite number c may be found in different ways. It may be calculated directly: pisano(c), which works, but may be time consuming to find, especially for larger integers, or, it may be calculated by finding the least common multiple of the Pisano periods of each composite component.
E.G.
Given a Pisano period function: pisano(x), and a least common multiple function lcm(x, y):
pisano(m × n) is equivalent to lcm(pisano(m), pisano(n)) where m and n are coprime
A formulae to calculate the pisano period for integer powers k of prime numbers p is:
pisano(pk) == p(k-1)pisano(p)
The equation is conjectured, no exceptions have been seen.
If a positive integer i is split into its prime factors, then the second and first equations above can be applied to generate the pisano period.
Task
Write 2 functions: pisanoPrime(p,k) and pisano(m).
pisanoPrime(p,k) should return the Pisano period of pk where p is prime and k is a positive integer.
pisano(m) should use pisanoPrime to return the Pisano period of m where m is a positive integer.
Print pisanoPrime(p,2) for every prime lower than 15.
Print pisanoPrime(p,1) for every prime lower than 180.
Print pisano(m) for every integer from 1 to 180.
Related tasks
Fibonacci sequence
Prime decomposition
Least common multiple
| #zkl | zkl | var [const] BI=Import("zklBigNum"); // libGMP
fcn pisanoPeriod(p){
if(p<2) return(0);
lastn,n,t := 0,1,0;
foreach i in ([0..p*p]){
t,n,lastn = n, (lastn + n) % p, t;
if(lastn==0 and n==1) return(i + 1);
}
1
}
fcn pisanoPrime(p,k){
_assert_(BI(p).probablyPrime(), "%s is not a prime number".fmt(p));
pisanoPeriod(p.pow(k))
} |
http://rosettacode.org/wiki/Pinstripe/Display | Pinstripe/Display | Sample image
The task is to demonstrate the creation of a series of vertical pinstripes across the entire width of the display.
in the first quarter the pinstripes should alternate one pixel white, one pixel black = 1 pixel wide vertical pinestripes
Quarter of the way down the display, we can switch to a wider 2 pixel wide vertical pinstripe pattern, alternating two pixels white, two pixels black.
Half way down the display, we switch to 3 pixels wide,
for the lower quarter of the display we use 4 pixels.
c.f. Colour_pinstripe/Display
| #Go | Go | package main
import "github.com/fogleman/gg"
var palette = [2]string{
"FFFFFF", // white
"000000", // black
}
func pinstripe(dc *gg.Context) {
w := dc.Width()
h := dc.Height() / 4
for b := 1; b <= 4; b++ {
for x, ci := 0, 0; x < w; x, ci = x+b, ci+1 {
dc.SetHexColor(palette[ci%2])
y := h * (b - 1)
dc.DrawRectangle(float64(x), float64(y), float64(b), float64(h))
dc.Fill()
}
}
}
func main() {
dc := gg.NewContext(900, 600)
pinstripe(dc)
dc.SavePNG("w_pinstripe.png")
} |
http://rosettacode.org/wiki/Primality_by_trial_division | Primality by trial division | Task
Write a boolean function that tells whether a given integer is prime.
Remember that 1 and all non-positive numbers are not prime.
Use trial division.
Even numbers greater than 2 may be eliminated right away.
A loop from 3 to √ n will suffice, but other loops are allowed.
Related tasks
count in factors
prime decomposition
AKS test for primes
factors of an integer
Sieve of Eratosthenes
factors of a Mersenne number
trial factoring of a Mersenne number
partition an integer X into N primes
sequence of primes by Trial Division
| #PL.2FI | PL/I | is_prime: procedure (n) returns (bit(1));
declare n fixed (15);
declare i fixed (10);
if n < 2 then return ('0'b);
if n = 2 then return ('1'b);
if mod(n, 2) = 0 then return ('0'b);
do i = 3 to sqrt(n) by 2;
if mod(n, i) = 0 then return ('0'b);
end;
return ('1'b);
end is_prime; |
http://rosettacode.org/wiki/Plasma_effect | Plasma effect | The plasma effect is a visual effect created by applying various functions, notably sine and cosine, to the color values of screen pixels. When animated (not a task requirement) the effect may give the impression of a colorful flowing liquid.
Task
Create a plasma effect.
See also
Computer Graphics Tutorial (lodev.org)
Plasma (bidouille.org)
| #Gosu | Gosu |
uses javax.swing.*
uses java.awt.*
uses java.awt.image.*
uses java.awt.event.ActionEvent
uses java.awt.image.BufferedImage#*
uses java.lang.Math#*
var size = 400
EventQueue.invokeLater(\ -> showPlasma())
function showPlasma() {
var frame = new JFrame("Plasma") {:Resizable = false, :DefaultCloseOperation = JFrame.EXIT_ON_CLOSE}
frame.add(new Plasma(), BorderLayout.CENTER)
frame.pack()
frame.setLocationRelativeTo(null)
frame.Visible = true
}
class Plasma extends JPanel {
var hueShift: float
property get plasma: float[][] = createPlasma(size, size)
property get img: BufferedImage = new BufferedImage(size, size, TYPE_INT_RGB)
construct() {
PreferredSize = new Dimension(size, size)
new Timer(50, \ e -> {hueShift+=0.02 repaint()}).start()
}
private function createPlasma(w: int, h: int): float[][] {
var buffer = new float[h][w]
for(y in 0..|h)
for(x in 0..|w) {
var value = (sin(x / 16) + sin(y / 8) + sin((x + y) / 16) + sin(sqrt(x * x + y * y) / 8) + 4) / 8
buffer[y][x] = value as float
}
return buffer
}
override function paintComponent(g: Graphics) {
for(y in 0..|plasma.length)
for(x in 0..|plasma[0].length)
img.setRGB(x, y, Color.HSBtoRGB(hueShift + plasma[y][x], 1, 1))
g.drawImage(img, 0, 0, null)
}
}
|
http://rosettacode.org/wiki/Plasma_effect | Plasma effect | The plasma effect is a visual effect created by applying various functions, notably sine and cosine, to the color values of screen pixels. When animated (not a task requirement) the effect may give the impression of a colorful flowing liquid.
Task
Create a plasma effect.
See also
Computer Graphics Tutorial (lodev.org)
Plasma (bidouille.org)
| #J | J | require 'trig viewmat'
plasma=: 3 :0
'w h'=. y
X=. (i. % <:) w
Y=. (i. % <:) h
x1=. sin X*16
y1=. sin Y*32
xy1=. sin (Y+/X)*16
xy2=. sin (Y +&.*:/ X)*32
xy1+xy2+y1+/x1
) |
http://rosettacode.org/wiki/Playfair_cipher | Playfair cipher | Playfair cipher
You are encouraged to solve this task according to the task description, using any language you may know.
Task
Implement a Playfair cipher for encryption and decryption.
The user must be able to choose J = I or no Q in the alphabet.
The output of the encrypted and decrypted message must be in capitalized digraphs, separated by spaces.
Output example
HI DE TH EG OL DI NT HE TR EX ES TU MP
| #Haskell | Haskell |
import Control.Monad (guard)
import Data.Array (Array, assocs, elems, listArray, (!))
import Data.Char (toUpper)
import Data.List (nub, (\\))
import Data.List.Split (chunksOf)
import Data.Maybe (listToMaybe)
import Data.String.Utils (replace)
type Square a = Array (Int, Int) a
-- | Turns a list into an n*m-array.
array2D ::
(Int, Int) -- ^ n * m
-> [e] -> Square e
array2D maxCoord = listArray ((1, 1), maxCoord)
-- | Generates a playfair table starting with the specified string.
--
-- >>> makeTable "hello"
-- "HELOABCDFGIKMNPQRSTUVWXYZ"
makeTable :: String -> String
makeTable k = nub key ++ (alpha \\ key)
where
alpha = ['A' .. 'Z'] \\ "J"
key = map toUpper =<< words k
-- | Turns a playfair table into a 5*5 alphabet square.
makeSquare :: [a] -> Square a
makeSquare = array2D (5, 5)
-- | Displays a playfair square, formatted as a square.
showSquare :: Square Char -> String
showSquare d = unlines $ chunksOf 5 (elems d)
-- | Given a value and an association list of x-coordinate * y-coordinate * value, returns the coordinates
getIndex' :: (Eq a) => a -> [((Int, Int), a)] -> Maybe (Int, Int)
getIndex' el = fmap fst . listToMaybe . filter ((== el) . snd)
encodePair, decodePair :: Eq a => Square a -> (a, a) -> Maybe (a, a)
encodePair = pairHelper (\x -> if x == 5 then 1 else x + 1)
decodePair = pairHelper (\x -> if x == 1 then 5 else x - 1)
pairHelper :: (Eq t)
=> (Int -> Int) -- ^ a function used for wrapping around the square
-> Square t -- ^ a playfair square
-> (t, t) -- ^ two characters
-> Maybe (t, t) -- ^ the two resulting/encoded characters
pairHelper adjust sqr (c1, c2) =
do let ps = assocs sqr
-- assigns an association list of (x-coord * y-coord) * value to ps
(x1, y1) <- getIndex' c1 ps
(x2, y2) <- getIndex' c2 ps
-- returns the coordinates of two values in the square
-- these will later be swapped
guard $ c1 /= c2
-- the characters (and coordinates) cannot be the same
let get x = sqr ! x
-- a small utility function for extracting a value from the square
Just $
-- wrap the coordinates around and find the encrypted characters
case () of
() | y1 == y2 ->
(get (adjust x1, y1), get (adjust x2, y2))
| x1 == x2 ->
(get (x1, adjust y1), get (x2, adjust y2))
| otherwise ->
(get (x1, y2), get (x2, y1))
-- | Turns two characters into a tuple.
parsePair :: String -> [(Char, Char)]
parsePair = fmap (\[x, y] -> (x, y)) . words . fmap toUpper
-- | Turns a tuple of two characters into a string.
unparsePair :: [(Char, Char)] -> String
unparsePair = unwords . fmap (\(x, y) -> [x, y])
codeHelper :: (Square Char -> (Char, Char) -> Maybe (Char, Char))
-> String -> String -> Maybe String
codeHelper subs key =
fmap unparsePair .
mapM (subs (makeSquare $ makeTable key)) .
parsePair
playfair, unplayfair :: String -> String -> Maybe String
playfair key = codeHelper encodePair key . formatEncode
unplayfair = codeHelper decodePair
formatEncode :: String -> String
formatEncode =
map toUpper .
unwords .
map (\[x, y] -> if x == y then [x, 'x'] else [x, y]) .
chunksOf 2 .
replace "j" "i" .
concatMap adjustLength .
words .
filter (\n -> n `elem` (['A'..'Z'] ++ ['a'..'z']))
where
adjustLength str
| odd (length str) = str ++ "x"
| otherwise = str
|
http://rosettacode.org/wiki/Pinstripe/Display | Pinstripe/Display | Sample image
The task is to demonstrate the creation of a series of vertical pinstripes across the entire width of the display.
in the first quarter the pinstripes should alternate one pixel white, one pixel black = 1 pixel wide vertical pinestripes
Quarter of the way down the display, we can switch to a wider 2 pixel wide vertical pinstripe pattern, alternating two pixels white, two pixels black.
Half way down the display, we switch to 3 pixels wide,
for the lower quarter of the display we use 4 pixels.
c.f. Colour_pinstripe/Display
| #Icon_and_Unicon | Icon and Unicon | link graphics
procedure main() # pinstripe
WOpen("canvas=hidden") # hide for query
height := WAttrib("displayheight") - 45 # adjust for ...
width := WAttrib("displaywidth") - 20 # ... window 7 borders
WClose(&window)
W := WOpen("size="||width||","||height,"bg=black","fg=white") |
stop("Unable to open window")
maxbands := 4 # bands to draw
bandheight := height / maxbands # height of each band
every bands := 1 to maxbands do { # for each band
top := 1 + bandheight * (bands-1) # .. top of band
step := 2^bands # .. number of steps (width)
lines := step / 2 # .. number (width) of stripes
every c := 1 to width by step & l := 0 to lines-1 do
DrawLine(c+l,top,c+l,top+bandheight-1)
}
WDone(W) # q to exit
end |
http://rosettacode.org/wiki/Primality_by_trial_division | Primality by trial division | Task
Write a boolean function that tells whether a given integer is prime.
Remember that 1 and all non-positive numbers are not prime.
Use trial division.
Even numbers greater than 2 may be eliminated right away.
A loop from 3 to √ n will suffice, but other loops are allowed.
Related tasks
count in factors
prime decomposition
AKS test for primes
factors of an integer
Sieve of Eratosthenes
factors of a Mersenne number
trial factoring of a Mersenne number
partition an integer X into N primes
sequence of primes by Trial Division
| #PL.2FM | PL/M | 100H: /* TEST FOR PRIMALITY BY TRIAL DIVISION */
DECLARE FALSE LITERALLY '0', TRUE LITERALLY '0FFH';
/* CP/M BDOS SYSTEM CALL */
BDOS: PROCEDURE( FN, ARG ); DECLARE FN BYTE, ARG ADDRESS; GOTO 5; END;
PR$CHAR: PROCEDURE( C ); DECLARE C BYTE; CALL BDOS( 2, C ); END;
PR$STRING: PROCEDURE( S ); DECLARE S ADDRESS; CALL BDOS( 9, S ); END;
PR$NL: PROCEDURE; CALL PR$STRING( .( 0DH, 0AH, '$' ) ); END;
PR$NUMBER: PROCEDURE( N );
DECLARE N ADDRESS;
DECLARE V ADDRESS, N$STR( 6 ) BYTE, W BYTE;
N$STR( W := LAST( N$STR ) ) = '$';
N$STR( W := W - 1 ) = '0' + ( ( V := N ) MOD 10 );
DO WHILE( ( V := V / 10 ) > 0 );
N$STR( W := W - 1 ) = '0' + ( V MOD 10 );
END;
CALL PR$STRING( .N$STR( W ) );
END PR$NUMBER;
/* INTEGER SUARE ROOT: BASED ON THE ONE IN THE PL/M FOR FROBENIUS NUMBERS */
SQRT: PROCEDURE( N )ADDRESS;
DECLARE ( N, X0, X1 ) ADDRESS;
IF N <= 3 THEN DO;
IF N = 0 THEN X0 = 0; ELSE X0 = 1;
END;
ELSE DO;
X0 = SHR( N, 1 );
DO WHILE( ( X1 := SHR( X0 + ( N / X0 ), 1 ) ) < X0 );
X0 = X1;
END;
END;
RETURN X0;
END SQRT;
IS$PRIME: PROCEDURE( N )BYTE; /* RETURNS TRUE IF N IS PRIME, FALSE IF NOT */
DECLARE N ADDRESS;
IF N < 2 THEN RETURN FALSE;
ELSE IF ( N AND 1 ) = 0 THEN RETURN N = 2;
ELSE DO;
/* ODD NUMBER > 2 */
DECLARE I ADDRESS;
DO I = 3 TO SQRT( N ) BY 2;
IF N MOD I = 0 THEN RETURN FALSE;
END;
RETURN TRUE;
END;
END IS$PRIME;
/* TEST THE IS$PRIME PROCEDURE */
DECLARE I ADDRESS;
DO I = 0 TO 100;
IF IS$PRIME( I ) THEN DO;
CALL PR$CHAR( ' ' );
CALL PR$NUMBER( I );
END;
END;
CALL PR$NL;
EOF |
http://rosettacode.org/wiki/Plasma_effect | Plasma effect | The plasma effect is a visual effect created by applying various functions, notably sine and cosine, to the color values of screen pixels. When animated (not a task requirement) the effect may give the impression of a colorful flowing liquid.
Task
Create a plasma effect.
See also
Computer Graphics Tutorial (lodev.org)
Plasma (bidouille.org)
| #Java | Java | import java.awt.*;
import java.awt.event.*;
import java.awt.image.*;
import static java.awt.image.BufferedImage.*;
import static java.lang.Math.*;
import javax.swing.*;
public class PlasmaEffect extends JPanel {
float[][] plasma;
float hueShift = 0;
BufferedImage img;
public PlasmaEffect() {
Dimension dim = new Dimension(640, 640);
setPreferredSize(dim);
setBackground(Color.white);
img = new BufferedImage(dim.width, dim.height, TYPE_INT_RGB);
plasma = createPlasma(dim.height, dim.width);
// animate about 24 fps and shift hue value with every frame
new Timer(42, (ActionEvent e) -> {
hueShift = (hueShift + 0.02f) % 1;
repaint();
}).start();
}
float[][] createPlasma(int w, int h) {
float[][] buffer = new float[h][w];
for (int y = 0; y < h; y++)
for (int x = 0; x < w; x++) {
double value = sin(x / 16.0);
value += sin(y / 8.0);
value += sin((x + y) / 16.0);
value += sin(sqrt(x * x + y * y) / 8.0);
value += 4; // shift range from -4 .. 4 to 0 .. 8
value /= 8; // bring range down to 0 .. 1
// requires VM option -ea
assert (value >= 0.0 && value <= 1.0) : "Hue value out of bounds";
buffer[y][x] = (float) value;
}
return buffer;
}
void drawPlasma(Graphics2D g) {
int h = plasma.length;
int w = plasma[0].length;
for (int y = 0; y < h; y++)
for (int x = 0; x < w; x++) {
float hue = hueShift + plasma[y][x] % 1;
img.setRGB(x, y, Color.HSBtoRGB(hue, 1, 1));
}
g.drawImage(img, 0, 0, null);
}
@Override
public void paintComponent(Graphics gg) {
super.paintComponent(gg);
Graphics2D g = (Graphics2D) gg;
g.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
RenderingHints.VALUE_ANTIALIAS_ON);
drawPlasma(g);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> {
JFrame f = new JFrame();
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setTitle("Plasma Effect");
f.setResizable(false);
f.add(new PlasmaEffect(), BorderLayout.CENTER);
f.pack();
f.setLocationRelativeTo(null);
f.setVisible(true);
});
}
} |
http://rosettacode.org/wiki/Playfair_cipher | Playfair cipher | Playfair cipher
You are encouraged to solve this task according to the task description, using any language you may know.
Task
Implement a Playfair cipher for encryption and decryption.
The user must be able to choose J = I or no Q in the alphabet.
The output of the encrypted and decrypted message must be in capitalized digraphs, separated by spaces.
Output example
HI DE TH EG OL DI NT HE TR EX ES TU MP
| #J | J | choose=: verb define
sel=. 'Q' e. y
alph=: (sel { 'JQ') -.~ a. {~ 65 + i.26
norm=: [: dedouble alph restrict ('I' I.@:=&'J'@]} ])`(-.&'Q')@.sel@toupper
''
)
restrict=: ] -. -.~
splitDigraph=: ,`([,'X',])@.((= {.) *. 2 | #@])
dedouble=: splitDigraph/&.|. NB. progressively split digraphs in string
choose 'Q'
setkey=: verb define
key=. ~.norm y,alph
ref=: ,/ 2{."1 ~."1 (,"0/~ alph) ,"1 norm 'XQV'
mode=. #. =/"2 inds=. 5 5#:key i. ref
inds0=. (0 3,:2 1)&{@,"2 inds
inds1=. 5|1 0 +"1 inds NB. same column
inds2=. 5|0 1 +"1 inds NB. same row
alt=: key {~ 5 #. mode {"_1 inds0 ,"2 3 inds1 ,:"2 inds2
i. 0 0
)
pairs=: verb define
2{."1 -.&' '"1 ~."1 (_2]\ norm y) ,"1 'XQV'
)
encrypt=: verb define
;:inv ;/ alt{~ref i. pairs y
)
decrypt=: verb define
;:inv ;/ ref{~alt i. pairs y
) |
http://rosettacode.org/wiki/Pinstripe/Display | Pinstripe/Display | Sample image
The task is to demonstrate the creation of a series of vertical pinstripes across the entire width of the display.
in the first quarter the pinstripes should alternate one pixel white, one pixel black = 1 pixel wide vertical pinestripes
Quarter of the way down the display, we can switch to a wider 2 pixel wide vertical pinstripe pattern, alternating two pixels white, two pixels black.
Half way down the display, we switch to 3 pixels wide,
for the lower quarter of the display we use 4 pixels.
c.f. Colour_pinstripe/Display
| #J | J | load'viewmat'
NB. size=. 2{.".wd'qm' NB. J6
NB. size=. getscreenwh_jgtk_ '' NB. J7
size=. 3{".wd'qscreen' NB. J8
'rgb'viewmat- (4<.@%~{:size)# ({.size) $&> 1 2 3 4#&.> <0 1 |
http://rosettacode.org/wiki/Pinstripe/Display | Pinstripe/Display | Sample image
The task is to demonstrate the creation of a series of vertical pinstripes across the entire width of the display.
in the first quarter the pinstripes should alternate one pixel white, one pixel black = 1 pixel wide vertical pinestripes
Quarter of the way down the display, we can switch to a wider 2 pixel wide vertical pinstripe pattern, alternating two pixels white, two pixels black.
Half way down the display, we switch to 3 pixels wide,
for the lower quarter of the display we use 4 pixels.
c.f. Colour_pinstripe/Display
| #Java | Java | import java.awt.*;
import javax.swing.*;
public class PinstripeDisplay extends JPanel {
final int bands = 4;
public PinstripeDisplay() {
setPreferredSize(new Dimension(900, 600));
}
@Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
int h = getHeight();
for (int b = 1; b <= bands; b++) {
for (int x = 0, colIndex = 0; x < getWidth(); x += b, colIndex++) {
g.setColor(colIndex % 2 == 0 ? Color.white : Color.black);
g.fillRect(x, (b - 1) * (h / bands), x + b, b * (h / bands));
}
}
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
JFrame f = new JFrame();
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setTitle("PinstripeDisplay");
f.add(new PinstripeDisplay(), BorderLayout.CENTER);
f.pack();
f.setLocationRelativeTo(null);
f.setVisible(true);
}
});
}
} |
http://rosettacode.org/wiki/Primality_by_trial_division | Primality by trial division | Task
Write a boolean function that tells whether a given integer is prime.
Remember that 1 and all non-positive numbers are not prime.
Use trial division.
Even numbers greater than 2 may be eliminated right away.
A loop from 3 to √ n will suffice, but other loops are allowed.
Related tasks
count in factors
prime decomposition
AKS test for primes
factors of an integer
Sieve of Eratosthenes
factors of a Mersenne number
trial factoring of a Mersenne number
partition an integer X into N primes
sequence of primes by Trial Division
| #PowerShell | PowerShell |
function isPrime ($n) {
if ($n -eq 1) {$false}
elseif ($n -eq 2) {$true}
elseif ($n -eq 3) {$true}
else{
$m = [Math]::Floor([Math]::Sqrt($n))
(@(2..$m | where {($_ -lt $n) -and ($n % $_ -eq 0) }).Count -eq 0)
}
}
1..15 | foreach{"isPrime $_ : $(isPrime $_)"} |
http://rosettacode.org/wiki/Plasma_effect | Plasma effect | The plasma effect is a visual effect created by applying various functions, notably sine and cosine, to the color values of screen pixels. When animated (not a task requirement) the effect may give the impression of a colorful flowing liquid.
Task
Create a plasma effect.
See also
Computer Graphics Tutorial (lodev.org)
Plasma (bidouille.org)
| #JavaScript | JavaScript | <!DOCTYPE html>
<html lang='en'>
<head>
<meta charset='UTF-8'>
<style>
canvas {
position: absolute;
top: 50%;
left: 50%;
width: 700px;
height: 500px;
margin: -250px 0 0 -350px;
}
body {
background-color: navy;
}
</style>
</head>
<body>
<canvas></canvas>
<script>
'use strict';
var canvas = document.querySelector('canvas');
canvas.width = 700;
canvas.height = 500;
var g = canvas.getContext('2d');
var plasma = createPlasma(canvas.width, canvas.height);
var hueShift = 0;
function createPlasma(w, h) {
var buffer = new Array(h);
for (var y = 0; y < h; y++) {
buffer[y] = new Array(w);
for (var x = 0; x < w; x++) {
var value = Math.sin(x / 16.0);
value += Math.sin(y / 8.0);
value += Math.sin((x + y) / 16.0);
value += Math.sin(Math.sqrt(x * x + y * y) / 8.0);
value += 4; // shift range from -4 .. 4 to 0 .. 8
value /= 8; // bring range down to 0 .. 1
buffer[y][x] = value;
}
}
return buffer;
}
function drawPlasma(w, h) {
var img = g.getImageData(0, 0, w, h);
for (var y = 0; y < h; y++) {
for (var x = 0; x < w; x++) {
var hue = hueShift + plasma[y][x] % 1;
var rgb = HSVtoRGB(hue, 1, 1);
var pos = (y * w + x) * 4;
img.data[pos] = rgb.r;
img.data[pos + 1] = rgb.g;
img.data[pos + 2] = rgb.b;
}
}
g.putImageData(img, 0, 0);
}
/* copied from stackoverflow */
function HSVtoRGB(h, s, v) {
var r, g, b, i, f, p, q, t;
i = Math.floor(h * 6);
f = h * 6 - i;
p = v * (1 - s);
q = v * (1 - f * s);
t = v * (1 - (1 - f) * s);
switch (i % 6) {
case 0: r = v, g = t, b = p; break;
case 1: r = q, g = v, b = p; break;
case 2: r = p, g = v, b = t; break;
case 3: r = p, g = q, b = v; break;
case 4: r = t, g = p, b = v; break;
case 5: r = v, g = p, b = q; break;
}
return {
r: Math.round(r * 255),
g: Math.round(g * 255),
b: Math.round(b * 255)
};
}
function drawBorder() {
g.strokeStyle = "white";
g.lineWidth = 10;
g.strokeRect(0, 0, canvas.width, canvas.height);
}
function animate(lastFrameTime) {
var time = new Date().getTime();
var delay = 42;
if (lastFrameTime + delay < time) {
hueShift = (hueShift + 0.02) % 1;
drawPlasma(canvas.width, canvas.height);
drawBorder();
lastFrameTime = time;
}
requestAnimationFrame(function () {
animate(lastFrameTime);
});
}
g.fillRect(0, 0, canvas.width, canvas.height);
animate(0);
</script>
</body>
</html> |
http://rosettacode.org/wiki/Playfair_cipher | Playfair cipher | Playfair cipher
You are encouraged to solve this task according to the task description, using any language you may know.
Task
Implement a Playfair cipher for encryption and decryption.
The user must be able to choose J = I or no Q in the alphabet.
The output of the encrypted and decrypted message must be in capitalized digraphs, separated by spaces.
Output example
HI DE TH EG OL DI NT HE TR EX ES TU MP
| #Java | Java | import java.awt.Point;
import java.util.Scanner;
public class PlayfairCipher {
private static char[][] charTable;
private static Point[] positions;
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String key = prompt("Enter an encryption key (min length 6): ", sc, 6);
String txt = prompt("Enter the message: ", sc, 1);
String jti = prompt("Replace J with I? y/n: ", sc, 1);
boolean changeJtoI = jti.equalsIgnoreCase("y");
createTable(key, changeJtoI);
String enc = encode(prepareText(txt, changeJtoI));
System.out.printf("%nEncoded message: %n%s%n", enc);
System.out.printf("%nDecoded message: %n%s%n", decode(enc));
}
private static String prompt(String promptText, Scanner sc, int minLen) {
String s;
do {
System.out.print(promptText);
s = sc.nextLine().trim();
} while (s.length() < minLen);
return s;
}
private static String prepareText(String s, boolean changeJtoI) {
s = s.toUpperCase().replaceAll("[^A-Z]", "");
return changeJtoI ? s.replace("J", "I") : s.replace("Q", "");
}
private static void createTable(String key, boolean changeJtoI) {
charTable = new char[5][5];
positions = new Point[26];
String s = prepareText(key + "ABCDEFGHIJKLMNOPQRSTUVWXYZ", changeJtoI);
int len = s.length();
for (int i = 0, k = 0; i < len; i++) {
char c = s.charAt(i);
if (positions[c - 'A'] == null) {
charTable[k / 5][k % 5] = c;
positions[c - 'A'] = new Point(k % 5, k / 5);
k++;
}
}
}
private static String encode(String s) {
StringBuilder sb = new StringBuilder(s);
for (int i = 0; i < sb.length(); i += 2) {
if (i == sb.length() - 1)
sb.append(sb.length() % 2 == 1 ? 'X' : "");
else if (sb.charAt(i) == sb.charAt(i + 1))
sb.insert(i + 1, 'X');
}
return codec(sb, 1);
}
private static String decode(String s) {
return codec(new StringBuilder(s), 4);
}
private static String codec(StringBuilder text, int direction) {
int len = text.length();
for (int i = 0; i < len; i += 2) {
char a = text.charAt(i);
char b = text.charAt(i + 1);
int row1 = positions[a - 'A'].y;
int row2 = positions[b - 'A'].y;
int col1 = positions[a - 'A'].x;
int col2 = positions[b - 'A'].x;
if (row1 == row2) {
col1 = (col1 + direction) % 5;
col2 = (col2 + direction) % 5;
} else if (col1 == col2) {
row1 = (row1 + direction) % 5;
row2 = (row2 + direction) % 5;
} else {
int tmp = col1;
col1 = col2;
col2 = tmp;
}
text.setCharAt(i, charTable[row1][col1]);
text.setCharAt(i + 1, charTable[row2][col2]);
}
return text.toString();
}
} |
http://rosettacode.org/wiki/Pinstripe/Display | Pinstripe/Display | Sample image
The task is to demonstrate the creation of a series of vertical pinstripes across the entire width of the display.
in the first quarter the pinstripes should alternate one pixel white, one pixel black = 1 pixel wide vertical pinestripes
Quarter of the way down the display, we can switch to a wider 2 pixel wide vertical pinstripe pattern, alternating two pixels white, two pixels black.
Half way down the display, we switch to 3 pixels wide,
for the lower quarter of the display we use 4 pixels.
c.f. Colour_pinstripe/Display
| #Julia | Julia |
using Luxor
function drawbars(w, h, sections, dk, lt)
Drawing(w,h)
background("white")
width = 1
height = h/sections
for y in 0:height:h-1
setline(width)
for x in 0:w/width
sethue(x % 2 == 0 ? dk: lt)
line(Point(x*width,y), Point(x*width,y+height), :stroke)
end
width += 1
end
end
drawbars(1920, 1080, 4, "black", "white")
finish()
preview()
|
http://rosettacode.org/wiki/Pinstripe/Display | Pinstripe/Display | Sample image
The task is to demonstrate the creation of a series of vertical pinstripes across the entire width of the display.
in the first quarter the pinstripes should alternate one pixel white, one pixel black = 1 pixel wide vertical pinestripes
Quarter of the way down the display, we can switch to a wider 2 pixel wide vertical pinstripe pattern, alternating two pixels white, two pixels black.
Half way down the display, we switch to 3 pixels wide,
for the lower quarter of the display we use 4 pixels.
c.f. Colour_pinstripe/Display
| #Kotlin | Kotlin | // version 1.1.0
import java.awt.*
import javax.swing.*
class ColourPinstripeDisplay(): JPanel() {
private companion object {
val palette = arrayOf(Color.white, Color.black)
}
private val bands = 4
init {
preferredSize = Dimension(900, 600)
}
protected override fun paintComponent(g: Graphics) {
super.paintComponent(g)
for (b in 1..bands) {
var colIndex = 0
val h = height / bands
for (x in 0 until width step b) {
g.color = palette[colIndex % palette.size]
g.fillRect(x, (b - 1) * h, b, h)
colIndex++
}
}
}
}
fun main(args: Array<String>) {
SwingUtilities.invokeLater {
val f = JFrame()
f.defaultCloseOperation = JFrame.EXIT_ON_CLOSE
f.title = "PinstripeDisplay"
f.add(ColourPinstripeDisplay(), BorderLayout.CENTER)
f.pack()
f.setLocationRelativeTo(null)
f.setVisible(true)
}
} |
http://rosettacode.org/wiki/Primality_by_trial_division | Primality by trial division | Task
Write a boolean function that tells whether a given integer is prime.
Remember that 1 and all non-positive numbers are not prime.
Use trial division.
Even numbers greater than 2 may be eliminated right away.
A loop from 3 to √ n will suffice, but other loops are allowed.
Related tasks
count in factors
prime decomposition
AKS test for primes
factors of an integer
Sieve of Eratosthenes
factors of a Mersenne number
trial factoring of a Mersenne number
partition an integer X into N primes
sequence of primes by Trial Division
| #Prolog | Prolog | prime(2).
prime(N) :-
between(3, inf, N),
1 is N mod 2, % odd
M is floor(sqrt(N+1)), % round-off paranoia
Max is (M-1) // 2, % integer division
forall( between(1, Max, I), N mod (2*I+1) > 0 ). |
http://rosettacode.org/wiki/Plasma_effect | Plasma effect | The plasma effect is a visual effect created by applying various functions, notably sine and cosine, to the color values of screen pixels. When animated (not a task requirement) the effect may give the impression of a colorful flowing liquid.
Task
Create a plasma effect.
See also
Computer Graphics Tutorial (lodev.org)
Plasma (bidouille.org)
| #Julia | Julia | using Luxor, Colors
Drawing(800, 800)
function plasma(wid, hei)
for x in 1:wid, y in 1:hei
sethue(parse(Colorant, HSV(180 + 45sin(x/19) + 45sin(y/9) +
45sin((x+y)/25) + 45sin(sqrt(x^2 + y^2)/8), 1, 1)))
circle(Point(x, y), 1, :fill)
end
end
@png plasma(800, 800)
|
http://rosettacode.org/wiki/Plasma_effect | Plasma effect | The plasma effect is a visual effect created by applying various functions, notably sine and cosine, to the color values of screen pixels. When animated (not a task requirement) the effect may give the impression of a colorful flowing liquid.
Task
Create a plasma effect.
See also
Computer Graphics Tutorial (lodev.org)
Plasma (bidouille.org)
| #Kotlin | Kotlin | // version 1.1.2
import java.awt.*
import java.awt.image.BufferedImage
import javax.swing.*
class PlasmaEffect : JPanel() {
private val plasma: Array<FloatArray>
private var hueShift = 0.0f
private val img: BufferedImage
init {
val dim = Dimension(640, 640)
preferredSize = dim
background = Color.white
img = BufferedImage(dim.width, dim.height, BufferedImage.TYPE_INT_RGB)
plasma = createPlasma(dim.height, dim.width)
// animate about 24 fps and shift hue value with every frame
Timer(42) {
hueShift = (hueShift + 0.02f) % 1
repaint()
}.start()
}
private fun createPlasma(w: Int, h: Int): Array<FloatArray> {
val buffer = Array(h) { FloatArray(w) }
for (y in 0 until h)
for (x in 0 until w) {
var value = Math.sin(x / 16.0)
value += Math.sin(y / 8.0)
value += Math.sin((x + y) / 16.0)
value += Math.sin(Math.sqrt((x * x + y * y).toDouble()) / 8.0)
value += 4.0 // shift range from -4 .. 4 to 0 .. 8
value /= 8.0 // bring range down to 0 .. 1
if (value < 0.0 || value > 1.0) throw RuntimeException("Hue value out of bounds")
buffer[y][x] = value.toFloat()
}
return buffer
}
private fun drawPlasma(g: Graphics2D) {
val h = plasma.size
val w = plasma[0].size
for (y in 0 until h)
for (x in 0 until w) {
val hue = hueShift + plasma[y][x] % 1
img.setRGB(x, y, Color.HSBtoRGB(hue, 1.0f, 1.0f))
}
g.drawImage(img, 0, 0, null)
}
override fun paintComponent(gg: Graphics) {
super.paintComponent(gg)
val g = gg as Graphics2D
g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON)
drawPlasma(g);
}
}
fun main(args: Array<String>) {
SwingUtilities.invokeLater {
val f = JFrame()
f.defaultCloseOperation = JFrame.EXIT_ON_CLOSE
f.title = "Plasma Effect"
f.isResizable = false
f.add(PlasmaEffect(), BorderLayout.CENTER)
f.pack()
f.setLocationRelativeTo(null)
f.isVisible = true
}
} |
http://rosettacode.org/wiki/Playfair_cipher | Playfair cipher | Playfair cipher
You are encouraged to solve this task according to the task description, using any language you may know.
Task
Implement a Playfair cipher for encryption and decryption.
The user must be able to choose J = I or no Q in the alphabet.
The output of the encrypted and decrypted message must be in capitalized digraphs, separated by spaces.
Output example
HI DE TH EG OL DI NT HE TR EX ES TU MP
| #Julia | Julia | function playfair(key, txt, isencode=true, from = "J", to = "")
to = (to == "" && from == "J") ? "I" : to
function canonical(s, dup_toX=true)
s = replace(replace(uppercase(s), from => to), r"[^A-Z]" => "")
a, dupcount = [c for c in s], 0
for i in 1:2:length(a)-1
if s[i] == s[i + 1]
dup_toX && splice!(a, i+1+dupcount:i+dupcount, 'X')
dupcount += 1
end
end
s = String(a)
return isodd(length(s)) ? s * "X" : s
end
# Translate key into an encoding 5x5 translation matrix.
keyletters = unique([c for c in canonical(key * "ABCDEFGHIJKLMNOPQRSTUVWXYZ", false)])
m = Char.((reshape(UInt8.(keyletters[1:25]), 5, 5)'))
# encod is a dictionary of letter pairs for encoding.
encod = Dict()
# Map pairs in same row or same column of matrix m.
for i in 1:5, j in 1:5, k in 1:5
if j != k
encod[m[i, j] * m[i, k]] = m[i, mod1(j + 1, 5)] * m[i, mod1(k + 1, 5)]
end
if i != k
encod[m[i, j] * m[k, j]] = m[mod1(i + 1, 5), j] * m[mod1(k + 1, 5), j]
end
# Map pairs not on same row or same column.
for l in 1:5
if i != k && j != l
encod[m[i, j] * m[k, l]] = m[i, l] * m[k, j]
end
end
end
# Get array of pairs of letters from text.
canontxt = canonical(txt)
letterpairs = [canontxt[i:i+1] for i in 1:2:length(canontxt)-1]
if isencode
# Encode text
return join([encod[pair] for pair in letterpairs], " ")
else
# Decode text
decod = Dict((v, k) for (k, v) in encod)
return join([decod[pair] for pair in letterpairs], " ")
end
end
orig = "Hide the gold in...the TREESTUMP!!!"
println("Original: ", orig)
encoded = playfair("Playfair example", orig)
println("Encoded: ", encoded)
println("Decoded: ", playfair("Playfair example", encoded, false))
|
http://rosettacode.org/wiki/Pinstripe/Display | Pinstripe/Display | Sample image
The task is to demonstrate the creation of a series of vertical pinstripes across the entire width of the display.
in the first quarter the pinstripes should alternate one pixel white, one pixel black = 1 pixel wide vertical pinestripes
Quarter of the way down the display, we can switch to a wider 2 pixel wide vertical pinstripe pattern, alternating two pixels white, two pixels black.
Half way down the display, we switch to 3 pixels wide,
for the lower quarter of the display we use 4 pixels.
c.f. Colour_pinstripe/Display
| #Liberty_BASIC | Liberty BASIC |
nomainwin
UpperLeftX=1
UpperLeftY=1
WindowWidth=DisplayWidth
WindowHeight=DisplayHeight
graphicbox #gr.gr, -1, -1, DisplayWidth+4, DisplayHeight+1
open "Pinstripe/Display" for window_popup as #gr
#gr.gr "down"
#gr.gr "trapclose [quit]"
#gr.gr "color black"
#gr.gr "backcolor black"
for w = 1 to 4
y1=y2
y2=y1+DisplayHeight/4
for x = w to DisplayWidth+4 step w*2
#gr.gr "place ";x;" ";y1;"; boxfilled ";x+w;" ";y2
next
next
wait
[quit]
close #gr
end
|
http://rosettacode.org/wiki/Primality_by_trial_division | Primality by trial division | Task
Write a boolean function that tells whether a given integer is prime.
Remember that 1 and all non-positive numbers are not prime.
Use trial division.
Even numbers greater than 2 may be eliminated right away.
A loop from 3 to √ n will suffice, but other loops are allowed.
Related tasks
count in factors
prime decomposition
AKS test for primes
factors of an integer
Sieve of Eratosthenes
factors of a Mersenne number
trial factoring of a Mersenne number
partition an integer X into N primes
sequence of primes by Trial Division
| #PureBasic | PureBasic | Procedure.i IsPrime(n)
Protected k
If n = 2
ProcedureReturn #True
EndIf
If n <= 1 Or n % 2 = 0
ProcedureReturn #False
EndIf
For k = 3 To Int(Sqr(n)) Step 2
If n % k = 0
ProcedureReturn #False
EndIf
Next
ProcedureReturn #True
EndProcedure |
http://rosettacode.org/wiki/Pig_the_dice_game/Player | Pig the dice game/Player | Pig the dice game/Player
You are encouraged to solve this task according to the task description, using any language you may know.
Task
Create a dice simulator and scorer of Pig the dice game and add to it the ability to play the game to at least one strategy.
State here the play strategies involved.
Show play during a game here.
As a stretch goal:
Simulate playing the game a number of times with two players of given strategies and report here summary statistics such as, but not restricted to, the influence of going first or which strategy seems stronger.
Game Rules
The game of Pig is a multiplayer game played with a single six-sided die. The
object of the game is to reach 100 points or more.
Play is taken in turns. On each person's turn that person has the option of either
Rolling the dice: where a roll of two to six is added to their score for that turn and the player's turn continues as the player is given the same choice again; or a roll of 1 loses the player's total points for that turn and their turn finishes with play passing to the next player.
Holding: The player's score for that round is added to their total and becomes safe from the effects of throwing a one. The player's turn finishes with play passing to the next player.
References
Pig (dice)
The Math of Being a Pig and Pigs (extra) - Numberphile videos featuring Ben Sparks.
| #Ada | Ada | with Pig; with Ada.Text_IO; with Ada.Command_Line;
procedure automatic_Pig is
use Pig;
type Robot is new Actor with record
Bound: Natural := 20;
Final_Run: Natural := 0;
end record;
function Roll_More(A: Robot; Self, Opponent: Player'Class) return Boolean;
function Roll_More(A: Robot; Self, Opponent: Player'Class) return Boolean is
((Self.All_Recent < A.Bound) or
else (Opponent.Score-100 > A.Final_Run));
function Arg(Position: Positive; Default: Natural) return Natural is
package ACL renames Ada.Command_Line;
begin
return Natural'Value(ACL.Argument(Position));
exception
when Constraint_Error => return Default;
end Arg;
T: Robot := (Bound => Arg(2, 35), Final_Run => Arg(3, 0));
F: Robot := (Bound => Arg(4, 20), Final_Run => Arg(5, 30));
T_Wins: Boolean;
Win_Count: array(Boolean) of Natural := (True=> 0, False => 0);
begin
for I in 1 .. Arg(1, 1000) loop
Play(T, F, T_Wins);
Win_Count(T_Wins) := Win_Count(T_Wins) + 1;
end loop;
Ada.Text_IO.Put_Line(Natural'Image(Win_Count(True)) &
Natural'Image(Win_Count(False)));
end Automatic_Pig; |
http://rosettacode.org/wiki/Plasma_effect | Plasma effect | The plasma effect is a visual effect created by applying various functions, notably sine and cosine, to the color values of screen pixels. When animated (not a task requirement) the effect may give the impression of a colorful flowing liquid.
Task
Create a plasma effect.
See also
Computer Graphics Tutorial (lodev.org)
Plasma (bidouille.org)
| #Lua | Lua |
_ = love.graphics
p1, p2, points = {}, {}, {}
function hypotenuse( a, b )
return a * a + b * b
end
function love.load()
size = _.getWidth()
currentTime, doub, half = 0, size * 2, size / 2
local b1, b2
for j = 0, size * 2 do
for i = 0, size * 2 do
b1 = math.floor( 128 + 127 * ( math.cos( math.sqrt( hypotenuse( size - j , size - i ) ) / 64 ) ) )
b2 = math.floor( ( math.sin( ( math.sqrt( 128.0 + hypotenuse( size - i, size - j ) ) - 4.0 ) / 32.0 ) + 1 ) * 90 )
table.insert( p1, b1 ); table.insert( p2, b2 )
end
end
end
function love.draw()
local a, c1, c2, c3, s1, s2, s3
currentTime = currentTime + math.random( 2 ) * 3
local x1 = math.floor( half + ( half - 2 ) * math.sin( currentTime / 47 ) )
local x2 = math.floor( half + ( half / 7 ) * math.sin( -currentTime / 149 ) )
local x3 = math.floor( half + ( half - 3 ) * math.sin( -currentTime / 157 ) )
local y1 = math.floor( half + ( half / 11 ) * math.cos( currentTime / 71 ) )
local y2 = math.floor( half + ( half - 5 ) * math.cos( -currentTime / 181 ) )
local y3 = math.floor( half + ( half / 23 ) * math.cos( -currentTime / 137 ) )
s1 = y1 * doub + x1; s2 = y2 * doub + x2; s3 = y3 * doub + x3
for j = 0, size do
for i = 0, size do
a = p2[s1] + p1[s2] + p2[s3]
c1 = a * 2; c2 = a * 4; c3 = a * 8
table.insert( points, { i, j, c1, c2, c3, 255 } )
s1 = s1 + 1; s2 = s2 + 1; s3 = s3 + 1;
end
s1 = s1 + size; s2 = s2 + size; s3 = s3 + size
end
_.points( points )
end
|
http://rosettacode.org/wiki/Playfair_cipher | Playfair cipher | Playfair cipher
You are encouraged to solve this task according to the task description, using any language you may know.
Task
Implement a Playfair cipher for encryption and decryption.
The user must be able to choose J = I or no Q in the alphabet.
The output of the encrypted and decrypted message must be in capitalized digraphs, separated by spaces.
Output example
HI DE TH EG OL DI NT HE TR EX ES TU MP
| #Kotlin | Kotlin | // version 1.0.5-2
enum class PlayfairOption {
NO_Q,
I_EQUALS_J
}
class Playfair(keyword: String, val pfo: PlayfairOption) {
private val table: Array<CharArray> = Array(5, { CharArray(5) }) // 5 x 5 char array
init {
// build table
val used = BooleanArray(26) // all elements false
if (pfo == PlayfairOption.NO_Q)
used[16] = true // Q used
else
used[9] = true // J used
val alphabet = keyword.toUpperCase() + "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
var i = 0
var j = 0
var c: Char
var d: Int
for (k in 0 until alphabet.length) {
c = alphabet[k]
if (c !in 'A'..'Z') continue
d = c.toInt() - 65
if (!used[d]) {
table[i][j] = c
used[d] = true
if (++j == 5) {
if (++i == 5) break // table has been filled
j = 0
}
}
}
}
private fun getCleanText(plainText: String): String {
val plainText2 = plainText.toUpperCase() // ensure everything is upper case
// get rid of any non-letters and insert X between duplicate letters
var cleanText = ""
var prevChar = '\u0000' // safe to assume null character won't be present in plainText
var nextChar: Char
for (i in 0 until plainText2.length) {
nextChar = plainText2[i]
// It appears that Q should be omitted altogether if NO_Q option is specified - we assume so anyway
if (nextChar !in 'A'..'Z' || (nextChar == 'Q' && pfo == PlayfairOption.NO_Q)) continue
// If I_EQUALS_J option specified, replace J with I
if (nextChar == 'J' && pfo == PlayfairOption.I_EQUALS_J) nextChar = 'I'
if (nextChar != prevChar)
cleanText += nextChar
else
cleanText += "X" + nextChar
prevChar = nextChar
}
val len = cleanText.length
if (len % 2 == 1) { // dangling letter at end so add another letter to complete digram
if (cleanText[len - 1] != 'X')
cleanText += 'X'
else
cleanText += 'Z'
}
return cleanText
}
private fun findChar(c: Char): Pair<Int, Int> {
for (i in 0..4)
for (j in 0..4)
if (table[i][j] == c) return Pair(i, j)
return Pair(-1, -1)
}
fun encode(plainText: String): String {
val cleanText = getCleanText(plainText)
var cipherText = ""
val length = cleanText.length
for (i in 0 until length step 2) {
val (row1, col1) = findChar(cleanText[i])
val (row2, col2) = findChar(cleanText[i + 1])
cipherText += when {
row1 == row2 -> table[row1][(col1 + 1) % 5].toString() + table[row2][(col2 + 1) % 5]
col1 == col2 -> table[(row1 + 1) % 5][col1].toString() + table[(row2 + 1) % 5][col2]
else -> table[row1][col2].toString() + table[row2][col1]
}
if (i < length - 1) cipherText += " "
}
return cipherText
}
fun decode(cipherText: String): String {
var decodedText = ""
val length = cipherText.length
for (i in 0 until length step 3) { // cipherText will include spaces so we need to skip them
val (row1, col1) = findChar(cipherText[i])
val (row2, col2) = findChar(cipherText[i + 1])
decodedText += when {
row1 == row2 -> table[row1][if (col1 > 0) col1 - 1 else 4].toString() + table[row2][if (col2 > 0) col2 - 1 else 4]
col1 == col2 -> table[if (row1 > 0) row1- 1 else 4][col1].toString() + table[if (row2 > 0) row2 - 1 else 4][col2]
else -> table[row1][col2].toString() + table[row2][col1]
}
if (i < length - 1) decodedText += " "
}
return decodedText
}
fun printTable() {
println("The table to be used is :\n")
for (i in 0..4) {
for (j in 0..4) print(table[i][j] + " ")
println()
}
}
}
fun main(args: Array<String>) {
print("Enter Playfair keyword : ")
val keyword: String = readLine()!!
var ignoreQ: String
do {
print("Ignore Q when buiding table y/n : ")
ignoreQ = readLine()!!.toLowerCase()
}
while (ignoreQ != "y" && ignoreQ != "n")
val pfo = if (ignoreQ == "y") PlayfairOption.NO_Q else PlayfairOption.I_EQUALS_J
val playfair = Playfair(keyword, pfo)
playfair.printTable()
print("\nEnter plain text : ")
val plainText: String = readLine()!!
val encodedText = playfair.encode(plainText)
println("\nEncoded text is : $encodedText")
val decodedText = playfair.decode(encodedText)
println("Decoded text is : $decodedText")
} |
http://rosettacode.org/wiki/Pinstripe/Display | Pinstripe/Display | Sample image
The task is to demonstrate the creation of a series of vertical pinstripes across the entire width of the display.
in the first quarter the pinstripes should alternate one pixel white, one pixel black = 1 pixel wide vertical pinestripes
Quarter of the way down the display, we can switch to a wider 2 pixel wide vertical pinstripe pattern, alternating two pixels white, two pixels black.
Half way down the display, we switch to 3 pixels wide,
for the lower quarter of the display we use 4 pixels.
c.f. Colour_pinstripe/Display
| #Locomotive_Basic | Locomotive Basic | 10 MODE 2 ' finest resolution
20 sh=400 ' screen height
30 sw=640 ' screen width
40 INK 0,26 ' white ink for background pen (0)
50 INK 1,0 ' black ink for foreground pen (1)
60 FOR sn=1 TO 4 ' four sections
70 bh=INT (sh/4) ' bar height
80 bb=(4-sn)*bh ' bar baseline
90 dw=0 ' currently drawn bar width
100 dc=0 ' current drawing colour
110 FOR l=0 TO sw -1 ' pan width for each section
120 PLOT l,bb,dc
130 DRAWR 0,bh-1,dc ' subtract 1 pixel (already plotted)
140 dw=dw+1
150 ' section number corresponds to maximum bar width
160 ' change bar colour, if maximum bar width exceeded
170 IF dw>sn THEN dw=0:dc=dc+1 ' next colour
180 IF dc>1 THEN dc=0
190 NEXT l
200 NEXT sn |
http://rosettacode.org/wiki/Pinstripe/Display | Pinstripe/Display | Sample image
The task is to demonstrate the creation of a series of vertical pinstripes across the entire width of the display.
in the first quarter the pinstripes should alternate one pixel white, one pixel black = 1 pixel wide vertical pinestripes
Quarter of the way down the display, we can switch to a wider 2 pixel wide vertical pinstripe pattern, alternating two pixels white, two pixels black.
Half way down the display, we switch to 3 pixels wide,
for the lower quarter of the display we use 4 pixels.
c.f. Colour_pinstripe/Display
| #Lua | Lua |
function love.load()
WIDTH = love.graphics.getWidth()
ROW_HEIGHT = math.floor(love.graphics.getHeight()/4)
love.graphics.setBackgroundColor({0,0,0})
love.graphics.setLineWidth(1)
love.graphics.setLineStyle("rough")
end
function love.draw()
for j = 0, 3 do
for i = 0, WIDTH, (j+1)*2 do
love.graphics.setColor({255,255,255})
for h = 0, j do
love.graphics.line(i+h, j*ROW_HEIGHT, i+h, (j+1)*ROW_HEIGHT)
end
end
end
end
|
http://rosettacode.org/wiki/Primality_by_trial_division | Primality by trial division | Task
Write a boolean function that tells whether a given integer is prime.
Remember that 1 and all non-positive numbers are not prime.
Use trial division.
Even numbers greater than 2 may be eliminated right away.
A loop from 3 to √ n will suffice, but other loops are allowed.
Related tasks
count in factors
prime decomposition
AKS test for primes
factors of an integer
Sieve of Eratosthenes
factors of a Mersenne number
trial factoring of a Mersenne number
partition an integer X into N primes
sequence of primes by Trial Division
| #Python | Python | def prime(a):
return not (a < 2 or any(a % x == 0 for x in xrange(2, int(a**0.5) + 1))) |
http://rosettacode.org/wiki/Pig_the_dice_game/Player | Pig the dice game/Player | Pig the dice game/Player
You are encouraged to solve this task according to the task description, using any language you may know.
Task
Create a dice simulator and scorer of Pig the dice game and add to it the ability to play the game to at least one strategy.
State here the play strategies involved.
Show play during a game here.
As a stretch goal:
Simulate playing the game a number of times with two players of given strategies and report here summary statistics such as, but not restricted to, the influence of going first or which strategy seems stronger.
Game Rules
The game of Pig is a multiplayer game played with a single six-sided die. The
object of the game is to reach 100 points or more.
Play is taken in turns. On each person's turn that person has the option of either
Rolling the dice: where a roll of two to six is added to their score for that turn and the player's turn continues as the player is given the same choice again; or a roll of 1 loses the player's total points for that turn and their turn finishes with play passing to the next player.
Holding: The player's score for that round is added to their total and becomes safe from the effects of throwing a one. The player's turn finishes with play passing to the next player.
References
Pig (dice)
The Math of Being a Pig and Pigs (extra) - Numberphile videos featuring Ben Sparks.
| #AutoHotkey | AutoHotkey | #NoEnv
SetBatchLines, -1
#SingleInstance, Force
#Include Pig_the_dice_game_Optimal_Play.ahkl ; comment if you don't want to bother
Play:=10000 ; this is enough to give 2 digits of accuracy in win ratio
Wins0:=Wins1:=0
Player0(TurnSum, SumMe, SumOpp) {
Return practical(TurnSum, SumMe, SumOpp) ; set first player function name
}
Player1(TurnSum, SumMe, SumOpp) {
Return optimal(TurnSum, SumMe, SumOpp) ; set second player function name
}
Loop, % Play
{
;Random, FirstPlayer, 0, 1 ; to remove advantage of going first
CurrentPlayer := 0 ; set to FirstPlayer to compare same players with different N's
Sum0:=Sum1:=0
Loop
{
OtherPlayer:=!CurrentPlayer
If (Sum%CurrentPlayer%+TurnSum < 100
and Player%CurrentPlayer%(TurnSum, Sum%CurrentPlayer%, Sum%OtherPlayer%))
{
; Roll
Random, LastRoll, 1, 6
If (LastRoll != 1)
{
TurnSum += LastRoll
Continue
}
TurnSum := 0
}
; Hold
Sum%CurrentPlayer% += TurnSum
TurnSum := 0
If (Sum%CurrentPlayer% >= 100)
{
Wins%CurrentPlayer%++
Break
}
CurrentPlayer := !CurrentPlayer
}
}
Msgbox % "Player 0 won " Round(Wins0/Play*100,0) "%`nPlayer 1 won " Round(Wins1/Play*100,0) "%"
; Random; 1/N is ~ probablity of holding
Random(TurnSum, SumMe, SumOpp, N=9) {
Random, Roll, 0, N ; increase this last number to increase probability of rolling
Return Roll
}
; Always roll
Always(TurnSum, SumMe, SumOpp) {
Return 1
}
; Roll N times; N=6 beats all other RollNx players
RollNx(TurnSum, SumMe, SumOpp, N=6) {
Static Roll=0
Return Roll := TurnSum = 0 ? 1 : mod(Roll+1,N+1)
}
; Roll if TurnSum < N; N=19 beats all other RollToN players
RollToN(TurnSum, SumMe, SumOpp, N=19) {
Return Roll := TurnSum < N
}
; Roll if SumOpp > N or SumMe > N or TurnSum < 21 + (SumOpp - SumMe) / 8
Practical(TurnSum, SumMe, SumOpp, N=72) {
Return Roll := SumOpp > N or SumMe > N or TurnSum < 21+(SumOpp-SumMe)/8
}
; Optimal play per http://cs.gettysburg.edu/~tneller/nsf/pig/pig.pdf
Optimal(TurnSum, SumMe, SumOpp) {
Global Optimal
Roll := Optimal[SumMe,TurnSum,SumOpp+1]
Return Roll = "" ? 1 : Roll
} |
http://rosettacode.org/wiki/Plasma_effect | Plasma effect | The plasma effect is a visual effect created by applying various functions, notably sine and cosine, to the color values of screen pixels. When animated (not a task requirement) the effect may give the impression of a colorful flowing liquid.
Task
Create a plasma effect.
See also
Computer Graphics Tutorial (lodev.org)
Plasma (bidouille.org)
| #Mathematica_.2F_Wolfram_Language | Mathematica / Wolfram Language | s = 400;
Image@Table[
hue = Sin[i/16] + Sin[j/8] + Sin[(i + j)/16] + Sin[Sqrt[i^2 + j^2]/8];
hue = (hue + 4)/8;
Hue[hue, 1, 0.75]
,
{i, 1.0, s},
{j, 1.0, s}
] |
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.