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/Deconvolution/2D%2B | Deconvolution/2D+ | This task is a straightforward generalization of Deconvolution/1D to higher dimensions. For example, the one dimensional case would be applicable to audio signals, whereas two dimensions would pertain to images. Define the discrete convolution in
d
{\displaystyle {\mathit {d}}}
dimensions of two functions
H
,
F
:
Z
d
→
R
{\displaystyle H,F:\mathbb {Z} ^{d}\rightarrow \mathbb {R} }
taking
d
{\displaystyle {\mathit {d}}}
-tuples of integers to real numbers as the function
G
:
Z
d
→
R
{\displaystyle G:\mathbb {Z} ^{d}\rightarrow \mathbb {R} }
also taking
d
{\displaystyle {\mathit {d}}}
-tuples of integers to reals and satisfying
G
(
n
0
,
…
,
n
d
−
1
)
=
∑
m
0
=
−
∞
∞
…
∑
m
d
−
1
=
−
∞
∞
F
(
m
0
,
…
,
m
d
−
1
)
H
(
n
0
−
m
0
,
…
,
n
d
−
1
−
m
d
−
1
)
{\displaystyle G(n_{0},\dots ,n_{d-1})=\sum _{m_{0}=-\infty }^{\infty }\dots \sum _{m_{d-1}=-\infty }^{\infty }F(m_{0},\dots ,m_{d-1})H(n_{0}-m_{0},\dots ,n_{d-1}-m_{d-1})}
for all
d
{\displaystyle {\mathit {d}}}
-tuples of integers
(
n
0
,
…
,
n
d
−
1
)
∈
Z
d
{\displaystyle (n_{0},\dots ,n_{d-1})\in \mathbb {Z} ^{d}}
. Assume
F
{\displaystyle {\mathit {F}}}
and
H
{\displaystyle {\mathit {H}}}
(and therefore
G
{\displaystyle {\mathit {G}}}
) are non-zero over only a finite domain bounded by the origin, hence possible to represent as finite multi-dimensional arrays or nested lists
f
{\displaystyle {\mathit {f}}}
,
h
{\displaystyle {\mathit {h}}}
, and
g
{\displaystyle {\mathit {g}}}
.
For this task, implement a function (or method, procedure, subroutine, etc.) deconv to perform deconvolution (i.e., the inverse of convolution) by solving for
h
{\displaystyle {\mathit {h}}}
given
f
{\displaystyle {\mathit {f}}}
and
g
{\displaystyle {\mathit {g}}}
. (See Deconvolution/1D for details.)
The function should work for
g
{\displaystyle {\mathit {g}}}
of arbitrary length in each dimension (i.e., not hard coded or constant) and
f
{\displaystyle {\mathit {f}}}
of any length up to that of
g
{\displaystyle {\mathit {g}}}
in the corresponding dimension.
The deconv function will need to be parameterized by the dimension
d
{\displaystyle {\mathit {d}}}
unless the dimension can be inferred from the data structures representing
g
{\displaystyle {\mathit {g}}}
and
f
{\displaystyle {\mathit {f}}}
.
There may be more equations than unknowns. If convenient, use a function from a library that finds the best fitting solution to an overdetermined system of linear equations (as in the Multiple regression task). Otherwise, prune the set of equations as needed and solve as in the Reduced row echelon form task.
Debug your solution using this test data, of which a portion is shown below. Be sure to verify both that the deconvolution of
g
{\displaystyle {\mathit {g}}}
with
f
{\displaystyle {\mathit {f}}}
is
h
{\displaystyle {\mathit {h}}}
and that the deconvolution of
g
{\displaystyle {\mathit {g}}}
with
h
{\displaystyle {\mathit {h}}}
is
f
{\displaystyle {\mathit {f}}}
. Display the results in a human readable form for the three dimensional case only.
dimension 1:
h: [-8, 2, -9, -2, 9, -8, -2]
f: [ 6, -9, -7, -5]
g: [-48, 84, -16, 95, 125, -70, 7, 29, 54, 10]
dimension 2:
h: [
[-8, 1, -7, -2, -9, 4],
[4, 5, -5, 2, 7, -1],
[-6, -3, -3, -6, 9, 5]]
f: [
[-5, 2, -2, -6, -7],
[9, 7, -6, 5, -7],
[1, -1, 9, 2, -7],
[5, 9, -9, 2, -5],
[-8, 5, -2, 8, 5]]
g: [
[40, -21, 53, 42, 105, 1, 87, 60, 39, -28],
[-92, -64, 19, -167, -71, -47, 128, -109, 40, -21],
[58, 85, -93, 37, 101, -14, 5, 37, -76, -56],
[-90, -135, 60, -125, 68, 53, 223, 4, -36, -48],
[78, 16, 7, -199, 156, -162, 29, 28, -103, -10],
[-62, -89, 69, -61, 66, 193, -61, 71, -8, -30],
[48, -6, 21, -9, -150, -22, -56, 32, 85, 25]]
dimension 3:
h: [
[[-6, -8, -5, 9], [-7, 9, -6, -8], [2, -7, 9, 8]],
[[7, 4, 4, -6], [9, 9, 4, -4], [-3, 7, -2, -3]]]
f: [
[[-9, 5, -8], [3, 5, 1]],
[[-1, -7, 2], [-5, -6, 6]],
[[8, 5, 8],[-2, -6, -4]]]
g: [
[
[54, 42, 53, -42, 85, -72],
[45, -170, 94, -36, 48, 73],
[-39, 65, -112, -16, -78, -72],
[6, -11, -6, 62, 49, 8]],
[
[-57, 49, -23, 52, -135, 66],
[-23, 127, -58, -5, -118, 64],
[87, -16, 121, 23, -41, -12],
[-19, 29, 35, -148, -11, 45]],
[
[-55, -147, -146, -31, 55, 60],
[-88, -45, -28, 46, -26, -144],
[-12, -107, -34, 150, 249, 66],
[11, -15, -34, 27, -78, -50]],
[
[56, 67, 108, 4, 2, -48],
[58, 67, 89, 32, 32, -8],
[-42, -31, -103, -30, -23, -8],
[6, 4, -26, -10, 26, 12]]]
| #Tcl | Tcl | package require Tcl 8.5
namespace path {::tcl::mathfunc ::tcl::mathop}
# Utility to extract the number of dimensions of a matrix
proc rank m {
for {set rank 0} {[llength $m] > 1} {incr rank} {
set m [lindex $m 0]
}
return $rank
}
# Utility to get the size of a matrix, as a list of lengths
proc size m {
set r [rank $m]
set index {}
set size {}
for {set i 0} {$i<$r} {incr i} {
lappend size [llength [lindex $m $index]]
lappend index 0
}
return $size
}
# Utility that iterates over the space of coordinates within a matrix.
#
# Arguments:
# var The name of the variable (in the caller's context) to set to each
# coordinate.
# size The size of matrix whose coordinates are to be iterated over.
# body The script to evaluate (in the caller's context) for each coordinate,
# with the variable named by 'var' set to the coordinate for the particular
# iteration.
proc loopcoords {var size body} {
upvar 1 $var v
set count [* {*}$size]
for {set i 0} {$i < $count} {incr i} {
set coords {}
set j $i
for {set s $size} {[llength $s]} {set s [lrange $s 0 end-1]} {
set dimension [lindex $s end]
lappend coords [expr {$j % $dimension}]
set j [expr {$j / $dimension}]
}
set v [lreverse $coords]
uplevel 1 $body
}
}
# Assembles a row, which is one of the simultaneous equations that needs
# to be solved by reducing the whole set to reduced row echelon form. Note
# that each row describes the equation for a single cell of the 'g' function.
#
# Arguments:
# g The "result" matrix of the convolution being undone.
# h The known "input" matrix of the convolution being undone.
# gs The size descriptor of 'g', passed as argument for efficiency.
# gc The coordinate in 'g' that we are generating the equation for.
# fs The size descriptor of 'f', passed as argument for efficiency.
# hs The size descriptor of 'h' (the unknown "input" matrix), passed
# as argument for efficiency.
proc row {g f gs gc fs hs} {
loopcoords hc $hs {
set fc {}
set ok 1
foreach a $gc b $fs c $hc {
set d [expr {$a - $c}]
if {$d < 0 || $d >= $b} {
set ok 0
break
}
lappend fc $d
}
if {$ok} {
lappend row [lindex $f $fc]
} else {
lappend row 0
}
}
return [lappend row [lindex $g $gc]]
}
# Utility for converting a matrix to Reduced Row Echelon Form
# From http://rosettacode.org/wiki/Reduced_row_echelon_form#Tcl
proc toRREF {m} {
set lead 0
set rows [llength $m]
set cols [llength [lindex $m 0]]
for {set r 0} {$r < $rows} {incr r} {
if {$cols <= $lead} {
break
}
set i $r
while {[lindex $m $i $lead] == 0} {
incr i
if {$rows == $i} {
set i $r
incr lead
if {$cols == $lead} {
# Tcl can't break out of nested loops
return $m
}
}
}
# swap rows i and r
foreach j [list $i $r] row [list [lindex $m $r] [lindex $m $i]] {
lset m $j $row
}
# divide row r by m(r,lead)
set val [lindex $m $r $lead]
for {set j 0} {$j < $cols} {incr j} {
lset m $r $j [/ [double [lindex $m $r $j]] $val]
}
for {set i 0} {$i < $rows} {incr i} {
if {$i != $r} {
# subtract m(i,lead) multiplied by row r from row i
set val [lindex $m $i $lead]
for {set j 0} {$j < $cols} {incr j} {
lset m $i $j \
[- [lindex $m $i $j] [* $val [lindex $m $r $j]]]
}
}
}
incr lead
}
return $m
}
# Deconvolve a pair of matrixes. Solves for 'h' such that 'g = f convolve h'.
#
# Arguments:
# g The matrix of data to be deconvolved.
# f The matrix describing the convolution to be removed.
# type Optional description of the type of data expected. Defaults to 32-bit
# integer data; use 'double' for floating-point data.
proc deconvolve {g f {type int}} {
# Compute the sizes of the various matrixes involved.
set gsize [size $g]
set fsize [size $f]
foreach gs $gsize fs $fsize {
lappend hsize [expr {$gs - $fs + 1}]
}
# Prepare the set of simultaneous equations to solve
set toSolve {}
loopcoords coords $gsize {
lappend toSolve [row $g $f $gsize $coords $fsize $hsize]
}
# Solve the equations
set solved [toRREF $toSolve]
# Make a dummy result matrix of the right size
set h 0
foreach hs [lreverse $hsize] {set h [lrepeat $hs $h]}
# Fill the results from the equations into the result matrix
set idx 0
loopcoords coords $hsize {
lset h $coords [$type [lindex $solved $idx end]]
incr idx
}
return $h
} |
http://rosettacode.org/wiki/Deal_cards_for_FreeCell | Deal cards for FreeCell | Free Cell is the solitaire card game that Paul Alfille introduced to the PLATO system in 1978. Jim Horne, at Microsoft, changed the name to FreeCell and reimplemented the game for DOS, then Windows.
This version introduced 32000 numbered deals. (The FreeCell FAQ tells this history.)
As the game became popular, Jim Horne disclosed the algorithm, and other implementations of FreeCell began to reproduce the Microsoft deals.
These deals are numbered from 1 to 32000.
Newer versions from Microsoft have 1 million deals, numbered from 1 to 1000000; some implementations allow numbers outside that range.
The algorithm uses this linear congruential generator from Microsoft C:
s
t
a
t
e
n
+
1
≡
214013
×
s
t
a
t
e
n
+
2531011
(
mod
2
31
)
{\displaystyle state_{n+1}\equiv 214013\times state_{n}+2531011{\pmod {2^{31}}}}
r
a
n
d
n
=
s
t
a
t
e
n
÷
2
16
{\displaystyle rand_{n}=state_{n}\div 2^{16}}
r
a
n
d
n
{\displaystyle rand_{n}}
is in range 0 to 32767.
Rosetta Code has another task, linear congruential generator, with code for this RNG in several languages.
The algorithm follows:
Seed the RNG with the number of the deal.
Create an array of 52 cards: Ace of Clubs, Ace of Diamonds, Ace of Hearts, Ace of Spades, 2 of Clubs, 2 of Diamonds, and so on through the ranks: Ace, 2, 3, 4, 5, 6, 7, 8, 9, 10, Jack, Queen, King. The array indexes are 0 to 51, with Ace of Clubs at 0, and King of Spades at 51.
Until the array is empty:
Choose a random card at index ≡ next random number (mod array length).
Swap this random card with the last card of the array.
Remove this random card from the array. (Array length goes down by 1.)
Deal this random card.
Deal all 52 cards, face up, across 8 columns. The first 8 cards go in 8 columns, the next 8 cards go on the first 8 cards, and so on.
Order to deal cards
Game #1
Game #617
1 2 3 4 5 6 7 8
9 10 11 12 13 14 15 16
17 18 19 20 21 22 23 24
25 26 27 28 29 30 31 32
33 34 35 36 37 38 39 40
41 42 43 44 45 46 47 48
49 50 51 52
JD 2D 9H JC 5D 7H 7C 5H
KD KC 9S 5S AD QC KH 3H
2S KS 9D QD JS AS AH 3C
4C 5C TS QH 4H AC 4D 7S
3S TD 4S TH 8H 2C JH 7D
6D 8S 8D QS 6C 3D 8C TC
6S 9C 2H 6H
7D AD 5C 3S 5S 8C 2D AH
TD 7S QD AC 6D 8H AS KH
TH QC 3H 9D 6S 8D 3D TC
KD 5H 9S 3C 8S 7H 4D JS
4C QS 9C 9H 7C 6H 2C 2S
4S TS 2H 5D JC 6C JH QH
JD KS KC 4H
Deals can also be checked against FreeCell solutions to 1000000 games.
(Summon a video solution, and it displays the initial deal.)
Write a program to take a deal number and deal cards in the same order as this algorithm.
The program may display the cards with ASCII, with Unicode, by drawing graphics, or any other way.
Related tasks:
Playing cards
Card shuffles
War Card_Game
Poker hand_analyser
Go Fish
| #F.C5.8Drmul.C3.A6 | Fōrmulæ | package main
import (
"fmt"
"math"
"math/rand"
"os"
"strconv"
"time"
)
const sSuits = "CDHS"
const sNums = "A23456789TJQK"
const rMax32 = math.MaxInt32
var seed = 1
func rnd() int {
seed = (seed*214013 + 2531011) & rMax32
return seed >> 16
}
func deal(s int) []int {
seed = s
t := make([]int, 52)
for i := 0; i < 52; i++ {
t[i] = 51 - i
}
for i := 0; i < 51; i++ {
j := 51 - rnd()%(52-i)
t[i], t[j] = t[j], t[i]
}
return t
}
func show(cs []int) {
for i, c := range cs {
fmt.Printf(" %c%c", sNums[c/4], sSuits[c%4])
if (i+1)%8 == 0 || i+1 == len(cs) {
fmt.Println()
}
}
}
func main() {
var game int
switch len(os.Args) {
case 1:
rand.Seed(time.Now().UnixNano())
game = 1 + rand.Intn(32000)
case 2:
var err error
game, err = strconv.Atoi(os.Args[1])
if err == nil && game >= 1 && game <= 32000 {
break
}
fallthrough
default:
fmt.Println("usage: deal [game]")
fmt.Println(" where game is a number in the range 1 to 32000")
return
}
fmt.Printf("\nGame #%d\n", game)
show(deal(game))
} |
http://rosettacode.org/wiki/De_Bruijn_sequences | de Bruijn sequences | The sequences are named after the Dutch mathematician Nicolaas Govert de Bruijn.
A note on Dutch capitalization: Nicolaas' last name is de Bruijn, the de isn't normally capitalized
unless it's the first word in a sentence. Rosetta Code (more or less by default or by fiat) requires the first word in the task name to be
capitalized.
In combinatorial mathematics, a de Bruijn sequence of order n on
a size-k alphabet (computer science) A is a cyclic sequence in which every
possible length-n string (computer science, formal theory) on A occurs
exactly once as a contiguous substring.
Such a sequence is denoted by B(k, n) and has
length kn, which is also the number of distinct substrings of
length n on A;
de Bruijn sequences are therefore optimally short.
There are:
(k!)k(n-1) ÷ kn
distinct de Bruijn sequences B(k, n).
Task
For this Rosetta Code task, a de Bruijn sequence is to be generated that can be used to shorten a brute-force attack on
a PIN-like code lock that does not have an "enter"
key and accepts the last n digits entered.
Note: automated teller machines (ATMs) used to work like
this, but their software has been updated to not allow a brute-force attack.
Example
A digital door lock with a 4-digit code would
have B (10, 4) solutions, with a length of 10,000 (digits).
Therefore, only at most 10,000 + 3 (as the solutions are cyclic or wrap-around) presses are needed to
open the lock.
Trying all 4-digit codes separately would require 4 × 10,000 or 40,000 presses.
Task requirements
Generate a de Bruijn sequence for a 4-digit (decimal) PIN code.
Show the length of the generated de Bruijn sequence.
(There are many possible de Bruijn sequences that solve this task, one solution is shown on the discussion page).
Show the first and last 130 digits of the de Bruijn sequence.
Verify that all four-digit (decimal) 1,000 PIN codes are contained within the de Bruijn sequence.
0000, 0001, 0002, 0003, ... 9996, 9997, 9998, 9999 (note the leading zeros).
Reverse the de Bruijn sequence.
Again, perform the (above) verification test.
Replace the 4,444th digit with a period (.) in the original de Bruijn sequence.
Perform the verification test (again). There should be four PIN codes missing.
(The last requirement is to ensure that the verification tests performs correctly. The verification processes should list
any and all missing PIN codes.)
Show all output here, on this page.
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
References
Wikipedia entry: de Bruijn sequence.
MathWorld entry: de Bruijn sequence.
An OEIS entry: A166315 lexicographically earliest binary de Bruijn sequences, B(2,n) --- Not B(10,4), but possibly relevant.
| #Python | Python |
# from https://en.wikipedia.org/wiki/De_Bruijn_sequence
def de_bruijn(k, n):
"""
de Bruijn sequence for alphabet k
and subsequences of length n.
"""
try:
# let's see if k can be cast to an integer;
# if so, make our alphabet a list
_ = int(k)
alphabet = list(map(str, range(k)))
except (ValueError, TypeError):
alphabet = k
k = len(k)
a = [0] * k * n
sequence = []
def db(t, p):
if t > n:
if n % p == 0:
sequence.extend(a[1:p + 1])
else:
a[t] = a[t - p]
db(t + 1, p)
for j in range(a[t - p] + 1, k):
a[t] = j
db(t + 1, t)
db(1, 1)
return "".join(alphabet[i] for i in sequence)
def validate(db):
"""
Check that all 10,000 combinations of 0-9 are present in
De Bruijn string db.
Validating the reversed deBruijn sequence:
No errors found
Validating the overlaid deBruijn sequence:
4 errors found:
PIN number 1459 missing
PIN number 4591 missing
PIN number 5814 missing
PIN number 8145 missing
"""
dbwithwrap = db+db[0:3]
digits = '0123456789'
errorstrings = []
for d1 in digits:
for d2 in digits:
for d3 in digits:
for d4 in digits:
teststring = d1+d2+d3+d4
if teststring not in dbwithwrap:
errorstrings.append(teststring)
if len(errorstrings) > 0:
print(" "+str(len(errorstrings))+" errors found:")
for e in errorstrings:
print(" PIN number "+e+" missing")
else:
print(" No errors found")
db = de_bruijn(10, 4)
print(" ")
print("The length of the de Bruijn sequence is ", str(len(db)))
print(" ")
print("The first 130 digits of the de Bruijn sequence are: "+db[0:130])
print(" ")
print("The last 130 digits of the de Bruijn sequence are: "+db[-130:])
print(" ")
print("Validating the deBruijn sequence:")
validate(db)
dbreversed = db[::-1]
print(" ")
print("Validating the reversed deBruijn sequence:")
validate(dbreversed)
dboverlaid = db[0:4443]+'.'+db[4444:]
print(" ")
print("Validating the overlaid deBruijn sequence:")
validate(dboverlaid)
|
http://rosettacode.org/wiki/Define_a_primitive_data_type | Define a primitive data type | Demonstrate how to define a type that behaves like an integer but has a lowest valid value of 1 and a highest valid value of 10. Include all bounds checking you need to write, or explain how the compiler or interpreter creates those bounds checks for you.
| #Modula-3 | Modula-3 | TYPE MyInt = [1..10]; |
http://rosettacode.org/wiki/Define_a_primitive_data_type | Define a primitive data type | Demonstrate how to define a type that behaves like an integer but has a lowest valid value of 1 and a highest valid value of 10. Include all bounds checking you need to write, or explain how the compiler or interpreter creates those bounds checks for you.
| #Nim | Nim | type
MyInt = range[1..10]
var x: MyInt = 5
x = x + 6 # Runtime error: unhandled exception: value out of range: 11 notin 1 .. 10 [RangeDefect]
x = 12 # Compile-time error: conversion from int literal(12) to MyInt is invalid |
http://rosettacode.org/wiki/Death_Star | Death Star |
Task
Display a region that consists of a large sphere with part of a smaller sphere removed from it as a result of geometric subtraction.
(This will basically produce a shape like a "death star".)
Related tasks
draw a sphere
draw a cuboid
draw a rotating cube
write language name in 3D ASCII
| #POV-Ray | POV-Ray | camera { perspective location <0.0 , .8 ,-3.0> look_at 0
aperture .1 blur_samples 20 variance 1/100000 focal_point 0}
light_source{< 3,3,-3> color rgb 1}
sky_sphere { pigment{ color rgb <0,.2,.5>}}
plane {y,-5 pigment {color rgb .54} normal {hexagon} }
difference {
sphere { 0,1 }
sphere { <-1,1,-1>,1 }
texture {
pigment{ granite }
finish { phong 1 reflection {0.10 metallic 0.5} }
}
} |
http://rosettacode.org/wiki/Death_Star | Death Star |
Task
Display a region that consists of a large sphere with part of a smaller sphere removed from it as a result of geometric subtraction.
(This will basically produce a shape like a "death star".)
Related tasks
draw a sphere
draw a cuboid
draw a rotating cube
write language name in 3D ASCII
| #Python | Python | import sys, math, collections
Sphere = collections.namedtuple("Sphere", "cx cy cz r")
V3 = collections.namedtuple("V3", "x y z")
def normalize((x, y, z)):
len = math.sqrt(x**2 + y**2 + z**2)
return V3(x / len, y / len, z / len)
def dot(v1, v2):
d = v1.x*v2.x + v1.y*v2.y + v1.z*v2.z
return -d if d < 0 else 0.0
def hit_sphere(sph, x0, y0):
x = x0 - sph.cx
y = y0 - sph.cy
zsq = sph.r ** 2 - (x ** 2 + y ** 2)
if zsq < 0:
return (False, 0, 0)
szsq = math.sqrt(zsq)
return (True, sph.cz - szsq, sph.cz + szsq)
def draw_sphere(k, ambient, light):
shades = ".:!*oe&#%@"
pos = Sphere(20.0, 20.0, 0.0, 20.0)
neg = Sphere(1.0, 1.0, -6.0, 20.0)
for i in xrange(int(math.floor(pos.cy - pos.r)),
int(math.ceil(pos.cy + pos.r) + 1)):
y = i + 0.5
for j in xrange(int(math.floor(pos.cx - 2 * pos.r)),
int(math.ceil(pos.cx + 2 * pos.r) + 1)):
x = (j - pos.cx) / 2.0 + 0.5 + pos.cx
(h, zb1, zb2) = hit_sphere(pos, x, y)
if not h:
hit_result = 0
else:
(h, zs1, zs2) = hit_sphere(neg, x, y)
if not h:
hit_result = 1
elif zs1 > zb1:
hit_result = 1
elif zs2 > zb2:
hit_result = 0
elif zs2 > zb1:
hit_result = 2
else:
hit_result = 1
if hit_result == 0:
sys.stdout.write(' ')
continue
elif hit_result == 1:
vec = V3(x - pos.cx, y - pos.cy, zb1 - pos.cz)
elif hit_result == 2:
vec = V3(neg.cx-x, neg.cy-y, neg.cz-zs2)
vec = normalize(vec)
b = dot(light, vec) ** k + ambient
intensity = int((1 - b) * len(shades))
intensity = min(len(shades), max(0, intensity))
sys.stdout.write(shades[intensity])
print
light = normalize(V3(-50, 30, 50))
draw_sphere(2, 0.5, light) |
http://rosettacode.org/wiki/Day_of_the_week | Day of the week | A company decides that whenever Xmas falls on a Sunday they will give their workers all extra paid holidays so that, together with any public holidays, workers will not have to work the following week (between the 25th of December and the first of January).
Task
In what years between 2008 and 2121 will the 25th of December be a Sunday?
Using any standard date handling libraries of your programming language;
compare the dates calculated with the output of other languages to discover any anomalies in the handling of dates which may be due to, for example, overflow in types used to represent dates/times similar to y2k type problems.
| #ALGOL_68 | ALGOL 68 | # example from: http://www.xs4all.nl/~jmvdveer/algol.html - GPL #
INT sun=0 # , mon=1, tue=2, wed=3, thu=4, fri=5, sat=6 #;
PROC day of week = (INT year, month, day) INT: (
# Day of the week by Zeller’s Congruence algorithm from 1887 #
INT y := year, m := month, d := day, c;
IF m <= 2 THEN
m +:= 12; y -:= 1
FI;
c := y OVER 100;
y %*:= 100;
(d - 1 + ((m + 1) * 26) OVER 10 + y + y OVER 4 + c OVER 4 - 2 * c) MOD 7
);
test:(
print("December 25th is a Sunday in:");
FOR year FROM 2008 TO 2121 DO
INT wd = day of week(year, 12, 25);
IF wd = sun THEN print(whole(year,-5)) FI
OD;
new line(stand out)
)
|
http://rosettacode.org/wiki/Cyclops_numbers | Cyclops numbers | A cyclops number is a number with an odd number of digits that has a zero in the center, but nowhere else. They are named so in tribute to the one eyed giants Cyclops from Greek mythology.
Cyclops numbers can be found in any base. This task strictly is looking for cyclops numbers in base 10.
There are many different classifications of cyclops numbers with minor differences in characteristics. In an effort to head off a whole series of tasks with tiny variations, we will cover several variants here.
Task
Find and display here on this page the first 50 cyclops numbers in base 10 (all of the sub tasks are restricted to base 10).
Find and display here on this page the first 50 prime cyclops numbers. (cyclops numbers that are prime.)
Find and display here on this page the first 50 blind prime cyclops numbers. (prime cyclops numbers that remain prime when "blinded"; the zero is removed from the center.)
Find and display here on this page the first 50 palindromic prime cyclops numbers. (prime cyclops numbers that are palindromes.)
Stretch
Find and display the first cyclops number greater than ten million (10,000,000) and the index (place) in the series where it is found.
Find and display the first prime cyclops number greater than ten million (10,000,000) and the index (place) in the series where it is found.
Find and display the first blind prime cyclops number greater than ten million (10,000,000) and the index (place) in the series where it is found.
Find and display the first palindromic prime cyclops number greater than ten million (10,000,000) and the index (place) in the series where it is found.
(Note: there are no cyclops numbers between ten million and one hundred million, they need to have an odd number of digits)
See also
OEIS A134808 - Cyclops numbers
OEIS A134809 - Cyclops primes
OEIS A329737 - Cyclops primes that remain prime after being "blinded"
OEIS A136098 - Prime palindromic cyclops numbers
| #ALGOL_68 | ALGOL 68 | BEGIN # show cyclops numbers - numbers with a 0 in the middle and no other 0 digits #
INT max prime = 100 000;
# sieve the primes to max prime #
PR read "primes.incl.a68" PR
[]BOOL prime = PRIMESIEVE max prime;
# returns TRUE if c is prime, FALSE otherwise #
PROC have a prime = ( INT c )BOOL:
IF c < 2 THEN FALSE
ELIF c < max prime
THEN prime[ c ]
ELSE # the cyclops number is too large for the sieve, use trial division #
BOOL possibly prime := ODD c;
FOR d FROM 3 BY 2 WHILE d * d <= c AND possibly prime DO possibly prime := c MOD d /= 0 OD;
possibly prime
FI # have a prime # ;
# arrays of the cyclops numbers we must show #
[ 1 : 50 ]INT first cyclops; INT cyclops count := 0;
[ 1 : 50 ]INT first prime cyclops; INT prime cyclops count := 0;
[ 1 : 50 ]INT first palindromic prime cyclops; INT palindromic prime cyclops count := 0;
[ 1 : 50 ]INT first blind prime cyclops; INT blind prime cyclops count := 0;
# notes c is a cyclops number, palindromic indicates whether it is palindromic or not #
# bc should be c c with the middle 0 removed #
# if c is one of the first 50 of various classifications, #
# it is stored in the appropriate array #
PROC have cyclops = ( INT c, BOOL palindromic, INT bc )VOID:
BEGIN
cyclops count +:= 1;
IF cyclops count <= UPB first cyclops THEN first cyclops[ cyclops count ] := c FI;
IF prime cyclops count < UPB first prime cyclops
OR ( palindromic prime cyclops count < UPB first palindromic prime cyclops AND palindromic )
OR blind prime cyclops count < UPB first blind prime cyclops
THEN
IF have a prime( c ) THEN
# have a prime cyclops #
IF prime cyclops count < UPB first prime cyclops THEN
first prime cyclops[ prime cyclops count +:= 1 ] := c
FI;
IF palindromic prime cyclops count < UPB first palindromic prime cyclops AND palindromic THEN
first palindromic prime cyclops[ palindromic prime cyclops count +:= 1 ] := c
FI;
IF blind prime cyclops count < UPB first blind prime cyclops THEN
IF have a prime( bc ) THEN
first blind prime cyclops[ blind prime cyclops count +:= 1 ] := c
FI
FI
FI
FI
END # have cyclops # ;
# prints a cyclops sequence #
PROC print cyclops = ( []INT seq, STRING legend, INT elements per line )VOID:
BEGIN
print( ( "The first ", whole( ( UPB seq - LWB seq ) + 1, 0 ), " ", legend, ":", newline, " " ) );
FOR i FROM LWB seq TO UPB seq DO
print( ( " ", whole( seq[ i ], -7 ) ) );
IF i MOD elements per line = 0 THEN print( ( newline, " " ) ) FI
OD;
print( ( newline ) )
END # print cyclops # ;
# generate the cyclops numbers #
# 0 is the first and only cyclops number with less than three digits #
have cyclops( 0, TRUE, 0 );
# generate the 3 digit cyclops numbers #
FOR f TO 9 DO
FOR b TO 9 DO
have cyclops( ( f * 100 ) + b
, f = b
, ( f * 10 ) + b
)
OD
OD;
# generate the 5 digit cyclops numbers #
FOR d1 TO 9 DO
FOR d2 TO 9 DO
INT d1200 = ( ( d1 * 10 ) + d2 ) * 100;
INT d12000 = d1200 * 10;
FOR d4 TO 9 DO
INT d40 = d4 * 10;
FOR d5 TO 9 DO
INT d45 = d40 + d5;
have cyclops( d12000 + d45
, d1 = d5 AND d2 = d4
, d1200 + d45
)
OD
OD
OD
OD;
# generate the 7 digit cyclops numbers #
FOR d1 TO 9 DO
FOR d2 TO 9 DO
FOR d3 TO 9 DO
INT d123000 = ( ( ( ( d1 * 10 ) + d2 ) * 10 ) + d3 ) * 1000;
INT d1230000 = d123000 * 10;
FOR d5 TO 9 DO
INT d500 = d5 * 100;
FOR d6 TO 9 DO
INT d560 = d500 + ( d6 * 10 );
FOR d7 TO 9 DO
INT d567 = d560 + d7;
have cyclops( d1230000 + d567
, d1 = d7 AND d2 = d6 AND d3 = d5
, d123000 + d567
)
OD
OD
OD
OD
OD
OD;
# show parts of the sequence #
print cyclops( first cyclops, "cyclops numbers", 10 );
print cyclops( first prime cyclops, "prime cyclops numbers", 10 );
print cyclops( first blind prime cyclops, "blind prime cyclops numbers", 10 );
print cyclops( first palindromic prime cyclops, "palindromic prime cyclops numbers", 10 )
END |
http://rosettacode.org/wiki/Deconvolution/2D%2B | Deconvolution/2D+ | This task is a straightforward generalization of Deconvolution/1D to higher dimensions. For example, the one dimensional case would be applicable to audio signals, whereas two dimensions would pertain to images. Define the discrete convolution in
d
{\displaystyle {\mathit {d}}}
dimensions of two functions
H
,
F
:
Z
d
→
R
{\displaystyle H,F:\mathbb {Z} ^{d}\rightarrow \mathbb {R} }
taking
d
{\displaystyle {\mathit {d}}}
-tuples of integers to real numbers as the function
G
:
Z
d
→
R
{\displaystyle G:\mathbb {Z} ^{d}\rightarrow \mathbb {R} }
also taking
d
{\displaystyle {\mathit {d}}}
-tuples of integers to reals and satisfying
G
(
n
0
,
…
,
n
d
−
1
)
=
∑
m
0
=
−
∞
∞
…
∑
m
d
−
1
=
−
∞
∞
F
(
m
0
,
…
,
m
d
−
1
)
H
(
n
0
−
m
0
,
…
,
n
d
−
1
−
m
d
−
1
)
{\displaystyle G(n_{0},\dots ,n_{d-1})=\sum _{m_{0}=-\infty }^{\infty }\dots \sum _{m_{d-1}=-\infty }^{\infty }F(m_{0},\dots ,m_{d-1})H(n_{0}-m_{0},\dots ,n_{d-1}-m_{d-1})}
for all
d
{\displaystyle {\mathit {d}}}
-tuples of integers
(
n
0
,
…
,
n
d
−
1
)
∈
Z
d
{\displaystyle (n_{0},\dots ,n_{d-1})\in \mathbb {Z} ^{d}}
. Assume
F
{\displaystyle {\mathit {F}}}
and
H
{\displaystyle {\mathit {H}}}
(and therefore
G
{\displaystyle {\mathit {G}}}
) are non-zero over only a finite domain bounded by the origin, hence possible to represent as finite multi-dimensional arrays or nested lists
f
{\displaystyle {\mathit {f}}}
,
h
{\displaystyle {\mathit {h}}}
, and
g
{\displaystyle {\mathit {g}}}
.
For this task, implement a function (or method, procedure, subroutine, etc.) deconv to perform deconvolution (i.e., the inverse of convolution) by solving for
h
{\displaystyle {\mathit {h}}}
given
f
{\displaystyle {\mathit {f}}}
and
g
{\displaystyle {\mathit {g}}}
. (See Deconvolution/1D for details.)
The function should work for
g
{\displaystyle {\mathit {g}}}
of arbitrary length in each dimension (i.e., not hard coded or constant) and
f
{\displaystyle {\mathit {f}}}
of any length up to that of
g
{\displaystyle {\mathit {g}}}
in the corresponding dimension.
The deconv function will need to be parameterized by the dimension
d
{\displaystyle {\mathit {d}}}
unless the dimension can be inferred from the data structures representing
g
{\displaystyle {\mathit {g}}}
and
f
{\displaystyle {\mathit {f}}}
.
There may be more equations than unknowns. If convenient, use a function from a library that finds the best fitting solution to an overdetermined system of linear equations (as in the Multiple regression task). Otherwise, prune the set of equations as needed and solve as in the Reduced row echelon form task.
Debug your solution using this test data, of which a portion is shown below. Be sure to verify both that the deconvolution of
g
{\displaystyle {\mathit {g}}}
with
f
{\displaystyle {\mathit {f}}}
is
h
{\displaystyle {\mathit {h}}}
and that the deconvolution of
g
{\displaystyle {\mathit {g}}}
with
h
{\displaystyle {\mathit {h}}}
is
f
{\displaystyle {\mathit {f}}}
. Display the results in a human readable form for the three dimensional case only.
dimension 1:
h: [-8, 2, -9, -2, 9, -8, -2]
f: [ 6, -9, -7, -5]
g: [-48, 84, -16, 95, 125, -70, 7, 29, 54, 10]
dimension 2:
h: [
[-8, 1, -7, -2, -9, 4],
[4, 5, -5, 2, 7, -1],
[-6, -3, -3, -6, 9, 5]]
f: [
[-5, 2, -2, -6, -7],
[9, 7, -6, 5, -7],
[1, -1, 9, 2, -7],
[5, 9, -9, 2, -5],
[-8, 5, -2, 8, 5]]
g: [
[40, -21, 53, 42, 105, 1, 87, 60, 39, -28],
[-92, -64, 19, -167, -71, -47, 128, -109, 40, -21],
[58, 85, -93, 37, 101, -14, 5, 37, -76, -56],
[-90, -135, 60, -125, 68, 53, 223, 4, -36, -48],
[78, 16, 7, -199, 156, -162, 29, 28, -103, -10],
[-62, -89, 69, -61, 66, 193, -61, 71, -8, -30],
[48, -6, 21, -9, -150, -22, -56, 32, 85, 25]]
dimension 3:
h: [
[[-6, -8, -5, 9], [-7, 9, -6, -8], [2, -7, 9, 8]],
[[7, 4, 4, -6], [9, 9, 4, -4], [-3, 7, -2, -3]]]
f: [
[[-9, 5, -8], [3, 5, 1]],
[[-1, -7, 2], [-5, -6, 6]],
[[8, 5, 8],[-2, -6, -4]]]
g: [
[
[54, 42, 53, -42, 85, -72],
[45, -170, 94, -36, 48, 73],
[-39, 65, -112, -16, -78, -72],
[6, -11, -6, 62, 49, 8]],
[
[-57, 49, -23, 52, -135, 66],
[-23, 127, -58, -5, -118, 64],
[87, -16, 121, 23, -41, -12],
[-19, 29, 35, -148, -11, 45]],
[
[-55, -147, -146, -31, 55, 60],
[-88, -45, -28, 46, -26, -144],
[-12, -107, -34, 150, 249, 66],
[11, -15, -34, 27, -78, -50]],
[
[56, 67, 108, 4, 2, -48],
[58, 67, 89, 32, 32, -8],
[-42, -31, -103, -30, -23, -8],
[6, 4, -26, -10, 26, 12]]]
| #Ursala | Ursala | #import std
#import nat
break = ~&r**+ zipt*+ ~&lh*~+ ~&lzyCPrX|\+ -*^|\~&tK33 :^/~& 0!*t
band = pad0+ ~&rSS+ zipt^*D(~&r,^lrrSPT/~<K33tx zipt^/~&r ~&lSNyCK33+ zipp0)^/~&rx ~&B->NlNSPC ~&bt
deconv = # takes a natural number n to the n-dimensional deconvolution function
~&?\math..div! iota; ~&!*; @h|\; (~&al^?\~&ar break@alh2faltPrXPRX)^^(
~&B->NlC~&bt*++ gang@t+ ~~*,
lapack..dgelsd^^(
(~&||0.!**+ ~&B^?a\~&Y@a ^lriFhNSS2iDrlYSK7LS2SL2rQ/~&alt band@alh2faltPrDPMX)^|\~&+ gang,
@t =>~&l ~&L+@r)) |
http://rosettacode.org/wiki/Deal_cards_for_FreeCell | Deal cards for FreeCell | Free Cell is the solitaire card game that Paul Alfille introduced to the PLATO system in 1978. Jim Horne, at Microsoft, changed the name to FreeCell and reimplemented the game for DOS, then Windows.
This version introduced 32000 numbered deals. (The FreeCell FAQ tells this history.)
As the game became popular, Jim Horne disclosed the algorithm, and other implementations of FreeCell began to reproduce the Microsoft deals.
These deals are numbered from 1 to 32000.
Newer versions from Microsoft have 1 million deals, numbered from 1 to 1000000; some implementations allow numbers outside that range.
The algorithm uses this linear congruential generator from Microsoft C:
s
t
a
t
e
n
+
1
≡
214013
×
s
t
a
t
e
n
+
2531011
(
mod
2
31
)
{\displaystyle state_{n+1}\equiv 214013\times state_{n}+2531011{\pmod {2^{31}}}}
r
a
n
d
n
=
s
t
a
t
e
n
÷
2
16
{\displaystyle rand_{n}=state_{n}\div 2^{16}}
r
a
n
d
n
{\displaystyle rand_{n}}
is in range 0 to 32767.
Rosetta Code has another task, linear congruential generator, with code for this RNG in several languages.
The algorithm follows:
Seed the RNG with the number of the deal.
Create an array of 52 cards: Ace of Clubs, Ace of Diamonds, Ace of Hearts, Ace of Spades, 2 of Clubs, 2 of Diamonds, and so on through the ranks: Ace, 2, 3, 4, 5, 6, 7, 8, 9, 10, Jack, Queen, King. The array indexes are 0 to 51, with Ace of Clubs at 0, and King of Spades at 51.
Until the array is empty:
Choose a random card at index ≡ next random number (mod array length).
Swap this random card with the last card of the array.
Remove this random card from the array. (Array length goes down by 1.)
Deal this random card.
Deal all 52 cards, face up, across 8 columns. The first 8 cards go in 8 columns, the next 8 cards go on the first 8 cards, and so on.
Order to deal cards
Game #1
Game #617
1 2 3 4 5 6 7 8
9 10 11 12 13 14 15 16
17 18 19 20 21 22 23 24
25 26 27 28 29 30 31 32
33 34 35 36 37 38 39 40
41 42 43 44 45 46 47 48
49 50 51 52
JD 2D 9H JC 5D 7H 7C 5H
KD KC 9S 5S AD QC KH 3H
2S KS 9D QD JS AS AH 3C
4C 5C TS QH 4H AC 4D 7S
3S TD 4S TH 8H 2C JH 7D
6D 8S 8D QS 6C 3D 8C TC
6S 9C 2H 6H
7D AD 5C 3S 5S 8C 2D AH
TD 7S QD AC 6D 8H AS KH
TH QC 3H 9D 6S 8D 3D TC
KD 5H 9S 3C 8S 7H 4D JS
4C QS 9C 9H 7C 6H 2C 2S
4S TS 2H 5D JC 6C JH QH
JD KS KC 4H
Deals can also be checked against FreeCell solutions to 1000000 games.
(Summon a video solution, and it displays the initial deal.)
Write a program to take a deal number and deal cards in the same order as this algorithm.
The program may display the cards with ASCII, with Unicode, by drawing graphics, or any other way.
Related tasks:
Playing cards
Card shuffles
War Card_Game
Poker hand_analyser
Go Fish
| #Go | Go | package main
import (
"fmt"
"math"
"math/rand"
"os"
"strconv"
"time"
)
const sSuits = "CDHS"
const sNums = "A23456789TJQK"
const rMax32 = math.MaxInt32
var seed = 1
func rnd() int {
seed = (seed*214013 + 2531011) & rMax32
return seed >> 16
}
func deal(s int) []int {
seed = s
t := make([]int, 52)
for i := 0; i < 52; i++ {
t[i] = 51 - i
}
for i := 0; i < 51; i++ {
j := 51 - rnd()%(52-i)
t[i], t[j] = t[j], t[i]
}
return t
}
func show(cs []int) {
for i, c := range cs {
fmt.Printf(" %c%c", sNums[c/4], sSuits[c%4])
if (i+1)%8 == 0 || i+1 == len(cs) {
fmt.Println()
}
}
}
func main() {
var game int
switch len(os.Args) {
case 1:
rand.Seed(time.Now().UnixNano())
game = 1 + rand.Intn(32000)
case 2:
var err error
game, err = strconv.Atoi(os.Args[1])
if err == nil && game >= 1 && game <= 32000 {
break
}
fallthrough
default:
fmt.Println("usage: deal [game]")
fmt.Println(" where game is a number in the range 1 to 32000")
return
}
fmt.Printf("\nGame #%d\n", game)
show(deal(game))
} |
http://rosettacode.org/wiki/De_Bruijn_sequences | de Bruijn sequences | The sequences are named after the Dutch mathematician Nicolaas Govert de Bruijn.
A note on Dutch capitalization: Nicolaas' last name is de Bruijn, the de isn't normally capitalized
unless it's the first word in a sentence. Rosetta Code (more or less by default or by fiat) requires the first word in the task name to be
capitalized.
In combinatorial mathematics, a de Bruijn sequence of order n on
a size-k alphabet (computer science) A is a cyclic sequence in which every
possible length-n string (computer science, formal theory) on A occurs
exactly once as a contiguous substring.
Such a sequence is denoted by B(k, n) and has
length kn, which is also the number of distinct substrings of
length n on A;
de Bruijn sequences are therefore optimally short.
There are:
(k!)k(n-1) ÷ kn
distinct de Bruijn sequences B(k, n).
Task
For this Rosetta Code task, a de Bruijn sequence is to be generated that can be used to shorten a brute-force attack on
a PIN-like code lock that does not have an "enter"
key and accepts the last n digits entered.
Note: automated teller machines (ATMs) used to work like
this, but their software has been updated to not allow a brute-force attack.
Example
A digital door lock with a 4-digit code would
have B (10, 4) solutions, with a length of 10,000 (digits).
Therefore, only at most 10,000 + 3 (as the solutions are cyclic or wrap-around) presses are needed to
open the lock.
Trying all 4-digit codes separately would require 4 × 10,000 or 40,000 presses.
Task requirements
Generate a de Bruijn sequence for a 4-digit (decimal) PIN code.
Show the length of the generated de Bruijn sequence.
(There are many possible de Bruijn sequences that solve this task, one solution is shown on the discussion page).
Show the first and last 130 digits of the de Bruijn sequence.
Verify that all four-digit (decimal) 1,000 PIN codes are contained within the de Bruijn sequence.
0000, 0001, 0002, 0003, ... 9996, 9997, 9998, 9999 (note the leading zeros).
Reverse the de Bruijn sequence.
Again, perform the (above) verification test.
Replace the 4,444th digit with a period (.) in the original de Bruijn sequence.
Perform the verification test (again). There should be four PIN codes missing.
(The last requirement is to ensure that the verification tests performs correctly. The verification processes should list
any and all missing PIN codes.)
Show all output here, on this page.
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
References
Wikipedia entry: de Bruijn sequence.
MathWorld entry: de Bruijn sequence.
An OEIS entry: A166315 lexicographically earliest binary de Bruijn sequences, B(2,n) --- Not B(10,4), but possibly relevant.
| #Racket | Racket | #lang racket
(define (de-bruijn k n)
(define a (make-vector (* k n) 0))
(define seq '())
(define (db t p)
(cond
[(> t n) (when (= (modulo n p) 0)
(set! seq (cons (call-with-values
(thunk (vector->values a 1 (add1 p)))
list)
seq)))]
[else (vector-set! a t (vector-ref a (- t p)))
(db (add1 t) p)
(for ([j (in-range (add1 (vector-ref a (- t p))) k)])
(vector-set! a t j)
(db (add1 t) t))]))
(db 1 1)
(define seq* (append* (reverse seq)))
(append seq* (take seq* (sub1 n))))
(define seq (de-bruijn 10 4))
(printf "The length of the de Bruijn sequence is ~a\n\n" (length seq))
(printf "The first 130 digits of the de Bruijn sequence are:\n~a\n\n"
(take seq 130))
(printf "The last 130 digits of the de Bruijn sequence are:\n~a\n\n"
(take-right seq 130))
(define (validate name seq)
(printf "Validating the ~ade Bruijn sequence:\n" name)
(define expected (for/set ([i (in-range 0 10000)]) i))
(define actual (for/set ([a (in-list seq)]
[b (in-list (rest seq))]
[c (in-list (rest (rest seq)))]
[d (in-list (rest (rest (rest seq))))])
(+ (* 1000 a) (* 100 b) (* 10 c) d)))
(define diff (set-subtract expected actual))
(cond
[(set-empty? diff) (printf " No errors found\n")]
[else (for ([n (in-set diff)])
(printf " ~a is missing\n" (~a n #:width 4 #:pad-string "0")))])
(newline))
(validate "" seq)
(validate "reversed " (reverse seq))
(validate "overlaid " (list-update seq 4443 add1)) |
http://rosettacode.org/wiki/De_Bruijn_sequences | de Bruijn sequences | The sequences are named after the Dutch mathematician Nicolaas Govert de Bruijn.
A note on Dutch capitalization: Nicolaas' last name is de Bruijn, the de isn't normally capitalized
unless it's the first word in a sentence. Rosetta Code (more or less by default or by fiat) requires the first word in the task name to be
capitalized.
In combinatorial mathematics, a de Bruijn sequence of order n on
a size-k alphabet (computer science) A is a cyclic sequence in which every
possible length-n string (computer science, formal theory) on A occurs
exactly once as a contiguous substring.
Such a sequence is denoted by B(k, n) and has
length kn, which is also the number of distinct substrings of
length n on A;
de Bruijn sequences are therefore optimally short.
There are:
(k!)k(n-1) ÷ kn
distinct de Bruijn sequences B(k, n).
Task
For this Rosetta Code task, a de Bruijn sequence is to be generated that can be used to shorten a brute-force attack on
a PIN-like code lock that does not have an "enter"
key and accepts the last n digits entered.
Note: automated teller machines (ATMs) used to work like
this, but their software has been updated to not allow a brute-force attack.
Example
A digital door lock with a 4-digit code would
have B (10, 4) solutions, with a length of 10,000 (digits).
Therefore, only at most 10,000 + 3 (as the solutions are cyclic or wrap-around) presses are needed to
open the lock.
Trying all 4-digit codes separately would require 4 × 10,000 or 40,000 presses.
Task requirements
Generate a de Bruijn sequence for a 4-digit (decimal) PIN code.
Show the length of the generated de Bruijn sequence.
(There are many possible de Bruijn sequences that solve this task, one solution is shown on the discussion page).
Show the first and last 130 digits of the de Bruijn sequence.
Verify that all four-digit (decimal) 1,000 PIN codes are contained within the de Bruijn sequence.
0000, 0001, 0002, 0003, ... 9996, 9997, 9998, 9999 (note the leading zeros).
Reverse the de Bruijn sequence.
Again, perform the (above) verification test.
Replace the 4,444th digit with a period (.) in the original de Bruijn sequence.
Perform the verification test (again). There should be four PIN codes missing.
(The last requirement is to ensure that the verification tests performs correctly. The verification processes should list
any and all missing PIN codes.)
Show all output here, on this page.
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
References
Wikipedia entry: de Bruijn sequence.
MathWorld entry: de Bruijn sequence.
An OEIS entry: A166315 lexicographically earliest binary de Bruijn sequences, B(2,n) --- Not B(10,4), but possibly relevant.
| #Raku | Raku | # Generate the sequence
my $seq;
for ^100 {
my $a = .fmt: '%02d';
next if $a.substr(1,1) < $a.substr(0,1);
$seq ~= ($a.substr(0,1) == $a.substr(1,1)) ?? $a.substr(0,1) !! $a;
for +$a ^..^ 100 {
next if .fmt('%02d').substr(1,1) <= $a.substr(0,1);
$seq ~= sprintf "%s%02d", $a, $_ ;
}
}
$seq = $seq.comb.list.rotate((^10000).pick).join;
$seq ~= $seq.substr(0,3);
sub check ($seq) {
my %chk;
for ^($seq.chars) { %chk{$seq.substr( $_, 4 )}++ }
put 'Missing: ', (^9999).grep( { not %chk{ .fmt: '%04d' } } ).fmt: '%04d';
put 'Extra: ', %chk.grep( *.value > 1 )».key.sort.fmt: '%04d';
}
## The Task
put "de Bruijn sequence length: " ~ $seq.chars;
put "\nFirst 130 characters:\n" ~ $seq.substr( 0, 130 );
put "\nLast 130 characters:\n" ~ $seq.substr( * - 130 );
put "\nIncorrect 4 digit PINs in this sequence:";
check $seq;
put "\nIncorrect 4 digit PINs in the reversed sequence:";
check $seq.flip;
my $digit = $seq.substr(4443,1);
put "\nReplacing the 4444th digit, ($digit) with { ($digit += 1) %= 10 }";
put "Incorrect 4 digit PINs in the revised sequence:";
$seq.substr-rw(4443,1) = $digit;
check $seq; |
http://rosettacode.org/wiki/Define_a_primitive_data_type | Define a primitive data type | Demonstrate how to define a type that behaves like an integer but has a lowest valid value of 1 and a highest valid value of 10. Include all bounds checking you need to write, or explain how the compiler or interpreter creates those bounds checks for you.
| #OCaml | OCaml | exception Out_of_bounds
type 'a bounds = { min: 'a; max: 'a }
type 'a bounded = { value: 'a; bounds: 'a bounds }
let mk_bounds ~min ~max = { min=min; max=max } ;;
(** val mk_bounds : min:'a -> max:'a -> 'a bounds *)
let check_bounds ~value ~bounds =
if value < bounds.min || value > bounds.max then
raise Out_of_bounds ;;
(** val check_bounds : value:'a -> bounds:'a bounds -> unit *)
let mk_bounded ~value ~bounds =
check_bounds ~value ~bounds;
{ value=value; bounds=bounds } ;;
(** val mk_bounded : value:'a -> bounds:'a bounds -> 'a bounded *)
let op f a b =
if a.bounds <> b.bounds then
invalid_arg "different bounds";
let res = f a.value b.value in
check_bounds res a.bounds;
(mk_bounded res a.bounds)
;;
(** val op : ('a -> 'a -> 'a) -> 'a bounded -> 'a bounded -> 'a bounded *) |
http://rosettacode.org/wiki/Death_Star | Death Star |
Task
Display a region that consists of a large sphere with part of a smaller sphere removed from it as a result of geometric subtraction.
(This will basically produce a shape like a "death star".)
Related tasks
draw a sphere
draw a cuboid
draw a rotating cube
write language name in 3D ASCII
| #Q | Q |
/ https://en.wikipedia.org/wiki/BMP_file_format
/ BITMAPINFOHEADER / RGB24
/ generate a header
genheader:{[w;h]
0x424d, "x"$(f2i4[54+4*h*w],0,0,0,0,54,0,0,0,40,0,0,0,
f2i4[h],f2i4[w],1,0,24,0,0,0,0,0,
f2i4[h*((w*3)+((w*3)mod 4))],
19,11,0,0,19,11,0,0,0,0,0,0,0,0,0,0)};
/ generate a raster line at a vertical position
genrow:{[w;y;fcn]
row:enlist 0i;xx:0i;do[w;row,:fcn[xx;y];xx+:1i];row,:((w mod 4)#0i);1_row};
/ generate a bitmap
genbitmap:{[w;h;fcn]
ary:enlist 0i;yy:0i;do[h;ary,:genrow[w;yy;fcn];yy+:1i];"x"$1_ary};
/ deal with endianness
/ might need to reverse last line if host computer is not a PC
f2i4:{[x] r:x;
s0:r mod 256;r-:s0; r%:256;
s1:r mod 256;r-:s1; r%:256;
s2:r mod 256;r-:s2; r%:256;
s3:r mod 256;
"h"$(s0,s1,s2,s3)}
/ compose and write a file
writebmp:{[w;h;fcn;fn]
fn 1: (genheader[h;w],genbitmap[w;h;fcn])};
/ / usage example:
/ w:400;
/ h:300;
/ fcn:{x0:x-w%2;y0:y-h%2;r:175;$[(r*r)>((x0*x0)+(y0*y0));(0;0;255);(0;255;0)]};
/ fn:`:demo.bmp;
/ writebmp[w;h;fcn;fn];
|
http://rosettacode.org/wiki/Day_of_the_week | Day of the week | A company decides that whenever Xmas falls on a Sunday they will give their workers all extra paid holidays so that, together with any public holidays, workers will not have to work the following week (between the 25th of December and the first of January).
Task
In what years between 2008 and 2121 will the 25th of December be a Sunday?
Using any standard date handling libraries of your programming language;
compare the dates calculated with the output of other languages to discover any anomalies in the handling of dates which may be due to, for example, overflow in types used to represent dates/times similar to y2k type problems.
| #ALGOL_W | ALGOL W | begin % find years where Christmas day falls on a Sunday %
integer procedure Day_of_week ( integer value d, m, y );
begin
integer j, k, mm, yy;
mm := m;
yy := y;
if mm <= 2 then begin
mm := mm + 12;
yy := yy - 1;
end if_m_le_2;
j := yy div 100;
k := yy rem 100;
(d + ( ( mm + 1 ) * 26 ) div 10 + k + k div 4 + j div 4 + 5 * j ) rem 7
end Day_of_week;
write( "25th of December is a Sunday in" );
for year := 2008 until 2121 do begin
integer day;
day := Day_of_week( 25, 12, year );
if day = 1 then writeon( I_W := 5, S_W := 0, year );
end for_year
end. |
http://rosettacode.org/wiki/Day_of_the_week | Day of the week | A company decides that whenever Xmas falls on a Sunday they will give their workers all extra paid holidays so that, together with any public holidays, workers will not have to work the following week (between the 25th of December and the first of January).
Task
In what years between 2008 and 2121 will the 25th of December be a Sunday?
Using any standard date handling libraries of your programming language;
compare the dates calculated with the output of other languages to discover any anomalies in the handling of dates which may be due to, for example, overflow in types used to represent dates/times similar to y2k type problems.
| #ALGOL-M | ALGOL-M |
BEGIN
% CALCULATE P MOD Q %
INTEGER FUNCTION MOD(P, Q);
INTEGER P, Q;
BEGIN
MOD := P - Q * (P / Q);
END;
COMMENT
RETURN DAY OF WEEK (SUN=0, MON=1, ETC.) FOR A GIVEN
GREGORIAN CALENDAR DATE USING ZELLER'S CONGRUENCE;
INTEGER FUNCTION DAYOFWEEK(MO, DA, YR);
INTEGER MO, DA, YR;
BEGIN
INTEGER Y, C, Z;
IF MO < 3 THEN
BEGIN
MO := MO + 10;
YR := YR - 1;
END
ELSE MO := MO - 2;
Y := MOD(YR, 100);
C := YR / 100;
Z := (26 * MO - 2) / 10;
Z := Z + DA + Y + (Y / 4) + (C /4) - 2 * C + 777;
DAYOFWEEK := MOD(Z, 7);
END;
% MAIN PROGRAM STARTS HERE %
INTEGER YEAR, SUNDAY;
SUNDAY := 0;
WRITE("CHRISTMAS WILL FALL ON A SUNDAY IN THESE YEARS:");
FOR YEAR := 2008 STEP 1 UNTIL 2121 DO
BEGIN
IF DAYOFWEEK(12, 25, YEAR) = SUNDAY THEN
WRITE(YEAR);
END;
END
|
http://rosettacode.org/wiki/Cyclops_numbers | Cyclops numbers | A cyclops number is a number with an odd number of digits that has a zero in the center, but nowhere else. They are named so in tribute to the one eyed giants Cyclops from Greek mythology.
Cyclops numbers can be found in any base. This task strictly is looking for cyclops numbers in base 10.
There are many different classifications of cyclops numbers with minor differences in characteristics. In an effort to head off a whole series of tasks with tiny variations, we will cover several variants here.
Task
Find and display here on this page the first 50 cyclops numbers in base 10 (all of the sub tasks are restricted to base 10).
Find and display here on this page the first 50 prime cyclops numbers. (cyclops numbers that are prime.)
Find and display here on this page the first 50 blind prime cyclops numbers. (prime cyclops numbers that remain prime when "blinded"; the zero is removed from the center.)
Find and display here on this page the first 50 palindromic prime cyclops numbers. (prime cyclops numbers that are palindromes.)
Stretch
Find and display the first cyclops number greater than ten million (10,000,000) and the index (place) in the series where it is found.
Find and display the first prime cyclops number greater than ten million (10,000,000) and the index (place) in the series where it is found.
Find and display the first blind prime cyclops number greater than ten million (10,000,000) and the index (place) in the series where it is found.
Find and display the first palindromic prime cyclops number greater than ten million (10,000,000) and the index (place) in the series where it is found.
(Note: there are no cyclops numbers between ten million and one hundred million, they need to have an odd number of digits)
See also
OEIS A134808 - Cyclops numbers
OEIS A134809 - Cyclops primes
OEIS A329737 - Cyclops primes that remain prime after being "blinded"
OEIS A136098 - Prime palindromic cyclops numbers
| #Arturo | Arturo | cyclops?: function [n][
digs: digits n
all? @[
-> odd? size digs
-> zero? digs\[(size digs)/2]
-> 1 = size match to :string n "0"
]
]
blind: function [x][
s: to :string x
half: (size s)/2
to :integer (slice s 0 dec half)++(slice s inc half dec size s)
]
findFirst50: function [what, start, predicate][
print ["First 50" what++"cyclops numbers:"]
first50: new start
i: 100
while [50 > size first50][
if do predicate -> 'first50 ++ i
i: i + 1
]
loop split.every:10 first50 'row [
print map to [:string] row 'item -> pad item 7
]
print ""
]
findFirst50 "" [0] -> cyclops? i
findFirst50 "prime " [] -> and? [prime? i][cyclops? i]
findFirst50 "blind prime " [] -> all? @[
-> prime? i
-> cyclops? i
-> prime? blind i
]
candidates: map 1..999 'x ->
to :integer (to :string x)++"0"++(reverse to :string x)
print "First 50 palindromic prime cyclops numbers:"
loop split.every:10 first.n: 50 select candidates 'x -> and? [prime? x][cyclops? x] 'row [
print map to [:string] row 'item -> pad item 7
] |
http://rosettacode.org/wiki/Deconvolution/2D%2B | Deconvolution/2D+ | This task is a straightforward generalization of Deconvolution/1D to higher dimensions. For example, the one dimensional case would be applicable to audio signals, whereas two dimensions would pertain to images. Define the discrete convolution in
d
{\displaystyle {\mathit {d}}}
dimensions of two functions
H
,
F
:
Z
d
→
R
{\displaystyle H,F:\mathbb {Z} ^{d}\rightarrow \mathbb {R} }
taking
d
{\displaystyle {\mathit {d}}}
-tuples of integers to real numbers as the function
G
:
Z
d
→
R
{\displaystyle G:\mathbb {Z} ^{d}\rightarrow \mathbb {R} }
also taking
d
{\displaystyle {\mathit {d}}}
-tuples of integers to reals and satisfying
G
(
n
0
,
…
,
n
d
−
1
)
=
∑
m
0
=
−
∞
∞
…
∑
m
d
−
1
=
−
∞
∞
F
(
m
0
,
…
,
m
d
−
1
)
H
(
n
0
−
m
0
,
…
,
n
d
−
1
−
m
d
−
1
)
{\displaystyle G(n_{0},\dots ,n_{d-1})=\sum _{m_{0}=-\infty }^{\infty }\dots \sum _{m_{d-1}=-\infty }^{\infty }F(m_{0},\dots ,m_{d-1})H(n_{0}-m_{0},\dots ,n_{d-1}-m_{d-1})}
for all
d
{\displaystyle {\mathit {d}}}
-tuples of integers
(
n
0
,
…
,
n
d
−
1
)
∈
Z
d
{\displaystyle (n_{0},\dots ,n_{d-1})\in \mathbb {Z} ^{d}}
. Assume
F
{\displaystyle {\mathit {F}}}
and
H
{\displaystyle {\mathit {H}}}
(and therefore
G
{\displaystyle {\mathit {G}}}
) are non-zero over only a finite domain bounded by the origin, hence possible to represent as finite multi-dimensional arrays or nested lists
f
{\displaystyle {\mathit {f}}}
,
h
{\displaystyle {\mathit {h}}}
, and
g
{\displaystyle {\mathit {g}}}
.
For this task, implement a function (or method, procedure, subroutine, etc.) deconv to perform deconvolution (i.e., the inverse of convolution) by solving for
h
{\displaystyle {\mathit {h}}}
given
f
{\displaystyle {\mathit {f}}}
and
g
{\displaystyle {\mathit {g}}}
. (See Deconvolution/1D for details.)
The function should work for
g
{\displaystyle {\mathit {g}}}
of arbitrary length in each dimension (i.e., not hard coded or constant) and
f
{\displaystyle {\mathit {f}}}
of any length up to that of
g
{\displaystyle {\mathit {g}}}
in the corresponding dimension.
The deconv function will need to be parameterized by the dimension
d
{\displaystyle {\mathit {d}}}
unless the dimension can be inferred from the data structures representing
g
{\displaystyle {\mathit {g}}}
and
f
{\displaystyle {\mathit {f}}}
.
There may be more equations than unknowns. If convenient, use a function from a library that finds the best fitting solution to an overdetermined system of linear equations (as in the Multiple regression task). Otherwise, prune the set of equations as needed and solve as in the Reduced row echelon form task.
Debug your solution using this test data, of which a portion is shown below. Be sure to verify both that the deconvolution of
g
{\displaystyle {\mathit {g}}}
with
f
{\displaystyle {\mathit {f}}}
is
h
{\displaystyle {\mathit {h}}}
and that the deconvolution of
g
{\displaystyle {\mathit {g}}}
with
h
{\displaystyle {\mathit {h}}}
is
f
{\displaystyle {\mathit {f}}}
. Display the results in a human readable form for the three dimensional case only.
dimension 1:
h: [-8, 2, -9, -2, 9, -8, -2]
f: [ 6, -9, -7, -5]
g: [-48, 84, -16, 95, 125, -70, 7, 29, 54, 10]
dimension 2:
h: [
[-8, 1, -7, -2, -9, 4],
[4, 5, -5, 2, 7, -1],
[-6, -3, -3, -6, 9, 5]]
f: [
[-5, 2, -2, -6, -7],
[9, 7, -6, 5, -7],
[1, -1, 9, 2, -7],
[5, 9, -9, 2, -5],
[-8, 5, -2, 8, 5]]
g: [
[40, -21, 53, 42, 105, 1, 87, 60, 39, -28],
[-92, -64, 19, -167, -71, -47, 128, -109, 40, -21],
[58, 85, -93, 37, 101, -14, 5, 37, -76, -56],
[-90, -135, 60, -125, 68, 53, 223, 4, -36, -48],
[78, 16, 7, -199, 156, -162, 29, 28, -103, -10],
[-62, -89, 69, -61, 66, 193, -61, 71, -8, -30],
[48, -6, 21, -9, -150, -22, -56, 32, 85, 25]]
dimension 3:
h: [
[[-6, -8, -5, 9], [-7, 9, -6, -8], [2, -7, 9, 8]],
[[7, 4, 4, -6], [9, 9, 4, -4], [-3, 7, -2, -3]]]
f: [
[[-9, 5, -8], [3, 5, 1]],
[[-1, -7, 2], [-5, -6, 6]],
[[8, 5, 8],[-2, -6, -4]]]
g: [
[
[54, 42, 53, -42, 85, -72],
[45, -170, 94, -36, 48, 73],
[-39, 65, -112, -16, -78, -72],
[6, -11, -6, 62, 49, 8]],
[
[-57, 49, -23, 52, -135, 66],
[-23, 127, -58, -5, -118, 64],
[87, -16, 121, 23, -41, -12],
[-19, 29, 35, -148, -11, 45]],
[
[-55, -147, -146, -31, 55, 60],
[-88, -45, -28, 46, -26, -144],
[-12, -107, -34, 150, 249, 66],
[11, -15, -34, 27, -78, -50]],
[
[56, 67, 108, 4, 2, -48],
[58, 67, 89, 32, 32, -8],
[-42, -31, -103, -30, -23, -8],
[6, 4, -26, -10, 26, 12]]]
| #Wren | Wren | import "/complex" for Complex
import "/fmt" for Fmt
var fft2 // recursive
fft2 = Fn.new { |buf, out, n, step, start|
if (step < n) {
fft2.call(out, buf, n, step*2, start)
fft2.call(out, buf, n, step*2, start + step)
var j = 0
while (j < n) {
var t = (Complex.imagMinusOne * Num.pi * j / n).exp * out[j+step+start]
buf[(j/2).floor + start] = out[j+start] + t
buf[((j+n)/2).floor + start] = out[j+start] - t
j = j + 2 * step
}
}
}
var fft = Fn.new { |buf, n|
var out = List.filled(n, null)
for (i in 0...n) out[i] = buf[i]
fft2.call(buf, out, n, 1, 0)
}
/* pad list length to power of two */
var padTwo = Fn.new { |g, le, nsl|
var n = 1
var ns = nsl[0]
if (ns != 0) {
n = ns
} else {
while (n < le) n = n * 2
}
var buf = List.filled(n, Complex.zero)
for (i in 0...le) buf[i] = Complex.new(g[i], 0)
nsl[0] = n
return buf
}
var deconv = Fn.new { |g, lg, f, lf, out, rowLe|
var ns = 0
var nsl = [ns]
var g2 = padTwo.call(g, lg, nsl)
var f2 = padTwo.call(f, lf, nsl)
ns = nsl[0]
fft.call(g2, ns)
fft.call(f2, ns)
var h = List.filled(ns, null)
for (i in 0...ns) h[i] = g2[i] / f2[i]
fft.call(h, ns)
for (i in 0...ns) {
if (h[i].real.abs < 1e-10) h[i] = Complex.zero
}
var i = 0
while (i > lf-lg-rowLe) {
out[-i] = (h[(i+ns)%ns]/32).real
i = i - 1
}
}
var unpack2 = Fn.new { |m, rows, le, toLe|
var buf = List.filled(rows*toLe, 0)
for (i in 0...rows) {
for (j in 0...le) buf[i*toLe+j] = m[i][j]
}
return buf
}
var pack2 = Fn.new { |buf, rows, fromLe, toLe, out|
for (i in 0...rows) {
for (j in 0...toLe) out[i][j] = buf[i*fromLe+j] / 4
}
}
var deconv2 = Fn.new { |g, rowG, colG, f, rowF, colF, out|
var g2 = unpack2.call(g, rowG, colG, colG)
var f2 = unpack2.call(f, rowF, colF, colG)
var ff = List.filled((rowG-rowF+1)*colG, 0)
deconv.call(g2, rowG*colG, f2, rowF*colG, ff, colG)
pack2.call(ff, rowG-rowF+1, colG, colG-colF+1, out)
}
var unpack3 = Fn.new { |m, x, y, z, toY, toZ|
var buf = List.filled(x*toY*toZ, 0)
for (i in 0...x) {
for (j in 0...y) {
for (k in 0...z) {
buf[(i*toY+j)*toZ+k] = m[i][j][k]
}
}
}
return buf
}
var pack3 = Fn.new { |buf, x, y, z, toY, toZ, out|
for (i in 0...x) {
for (j in 0...toY) {
for (k in 0...toZ) {
out[i][j][k] = buf[(i*y+j)*z+k] / 4
}
}
}
}
var deconv3 = Fn.new { |g, gx, gy, gz, f, fx, fy, fz, out|
var g2 = unpack3.call(g, gx, gy, gz, gy, gz)
var f2 = unpack3.call(f, fx, fy, fz, gy, gz)
var ff = List.filled((gx-fx+1)*gy*gz, 0)
deconv.call(g2, gx*gy*gz, f2, fx*gy*gz, ff, gy*gz)
pack3.call(ff, gx-fx+1, gy, gz, gy-fy+1, gz-fz+1, out)
}
var f = [
[[-9, 5, -8], [ 3, 5, 1]],
[[-1, -7, 2], [-5, -6, 6]],
[[ 8, 5, 8], [-2, -6, -4]]
]
var fx = f.count
var fy = f[0].count
var fz = f[0][0].count
var g = [
[[ 54, 42, 53, -42, 85, -72], [45, -170, 94, -36, 48, 73],
[-39, 65, -112, -16, -78, -72], [6, -11, -6, 62, 49, 8]],
[[-57, 49, -23, 52, -135, 66], [-23, 127, -58, -5, -118, 64],
[ 87, -16, 121, 23, -41, -12], [-19, 29, 35, -148, -11, 45]],
[[-55, -147, -146, -31, 55, 60], [-88, -45, -28, 46, -26, -144],
[-12, -107, -34, 150, 249, 66], [11, -15, -34, 27, -78, -50]],
[[ 56, 67, 108, 4, 2, -48], [58, 67, 89, 32, 32, -8],
[-42, -31, -103, -30, -23, -8], [6, 4, -26, -10, 26, 12]]
]
var gx = g.count
var gy = g[0].count
var gz = g[0][0].count
var h = [
[[-6, -8, -5, 9], [-7, 9, -6, -8], [ 2, -7, 9, 8]],
[[ 7, 4, 4, -6], [ 9, 9, 4, -4], [-3, 7, -2, -3]]
]
var hx = gx - fx + 1
var hy = gy - fy + 1
var hz = gz - fz + 1
var h2 = List.filled(hx, null)
for (i in 0...hx) {
h2[i] = List.filled(hy, 0)
for (j in 0...hy) h2[i][j] = List.filled(hz, 0)
}
deconv3.call(g, gx, gy, gz, f, fx, fy, fz, h2)
System.print("deconv3(g, f):\n")
for (i in 0...hx) {
for (j in 0...hy) {
for (k in 0...hz) Fmt.write("$9.6h ", h2[i][j][k])
System.print()
}
if (i < hx-1) System.print()
}
var kx = gx - hx + 1
var ky = gy - hy + 1
var kz = gz - hz + 1
var f2 = List.filled(kx, null)
for (i in 0...kx) {
f2[i] = List.filled(ky, 0)
for (j in 0...ky) f2[i][j] = List.filled(kz, 0)
}
deconv3.call(g, gx, gy, gz, h, hx, hy, hz, f2)
System.print("\ndeconv3(g, h):\n")
for (i in 0...kx) {
for (j in 0...ky) {
for (k in 0...kz) Fmt.write("$9.6h ", f2[i][j][k])
System.print()
}
if (i < kx-1) System.print()
} |
http://rosettacode.org/wiki/Deal_cards_for_FreeCell | Deal cards for FreeCell | Free Cell is the solitaire card game that Paul Alfille introduced to the PLATO system in 1978. Jim Horne, at Microsoft, changed the name to FreeCell and reimplemented the game for DOS, then Windows.
This version introduced 32000 numbered deals. (The FreeCell FAQ tells this history.)
As the game became popular, Jim Horne disclosed the algorithm, and other implementations of FreeCell began to reproduce the Microsoft deals.
These deals are numbered from 1 to 32000.
Newer versions from Microsoft have 1 million deals, numbered from 1 to 1000000; some implementations allow numbers outside that range.
The algorithm uses this linear congruential generator from Microsoft C:
s
t
a
t
e
n
+
1
≡
214013
×
s
t
a
t
e
n
+
2531011
(
mod
2
31
)
{\displaystyle state_{n+1}\equiv 214013\times state_{n}+2531011{\pmod {2^{31}}}}
r
a
n
d
n
=
s
t
a
t
e
n
÷
2
16
{\displaystyle rand_{n}=state_{n}\div 2^{16}}
r
a
n
d
n
{\displaystyle rand_{n}}
is in range 0 to 32767.
Rosetta Code has another task, linear congruential generator, with code for this RNG in several languages.
The algorithm follows:
Seed the RNG with the number of the deal.
Create an array of 52 cards: Ace of Clubs, Ace of Diamonds, Ace of Hearts, Ace of Spades, 2 of Clubs, 2 of Diamonds, and so on through the ranks: Ace, 2, 3, 4, 5, 6, 7, 8, 9, 10, Jack, Queen, King. The array indexes are 0 to 51, with Ace of Clubs at 0, and King of Spades at 51.
Until the array is empty:
Choose a random card at index ≡ next random number (mod array length).
Swap this random card with the last card of the array.
Remove this random card from the array. (Array length goes down by 1.)
Deal this random card.
Deal all 52 cards, face up, across 8 columns. The first 8 cards go in 8 columns, the next 8 cards go on the first 8 cards, and so on.
Order to deal cards
Game #1
Game #617
1 2 3 4 5 6 7 8
9 10 11 12 13 14 15 16
17 18 19 20 21 22 23 24
25 26 27 28 29 30 31 32
33 34 35 36 37 38 39 40
41 42 43 44 45 46 47 48
49 50 51 52
JD 2D 9H JC 5D 7H 7C 5H
KD KC 9S 5S AD QC KH 3H
2S KS 9D QD JS AS AH 3C
4C 5C TS QH 4H AC 4D 7S
3S TD 4S TH 8H 2C JH 7D
6D 8S 8D QS 6C 3D 8C TC
6S 9C 2H 6H
7D AD 5C 3S 5S 8C 2D AH
TD 7S QD AC 6D 8H AS KH
TH QC 3H 9D 6S 8D 3D TC
KD 5H 9S 3C 8S 7H 4D JS
4C QS 9C 9H 7C 6H 2C 2S
4S TS 2H 5D JC 6C JH QH
JD KS KC 4H
Deals can also be checked against FreeCell solutions to 1000000 games.
(Summon a video solution, and it displays the initial deal.)
Write a program to take a deal number and deal cards in the same order as this algorithm.
The program may display the cards with ASCII, with Unicode, by drawing graphics, or any other way.
Related tasks:
Playing cards
Card shuffles
War Card_Game
Poker hand_analyser
Go Fish
| #Groovy | Groovy |
class FreeCell{
int seed
List<String> createDeck(){
List<String> suits = ['♣','♦','♥','♠']
List<String> values = ['A','2','3','4','5','6','7','8','9','10','J','Q','K']
return [suits,values].combinations{suit,value -> "$suit$value"}
}
int random() {
seed = (214013 * seed + 2531011) & Integer.MAX_VALUE
return seed >> 16
}
List<String> shuffledDeck(List<String> cards) {
List<String> deck = cards.clone()
(deck.size() - 1..1).each{index ->
int r = random() % (index + 1)
deck.swap(r, index)
}
return deck
}
List<String> dealGame(int seed = 1){
this.seed= seed
List<String> cards = shuffledDeck(createDeck())
(1..cards.size()).each{ number->
print "${cards.pop()}\t"
if(number % 8 == 0) println('')
}
println('\n')
}
}
def freecell = new FreeCell()
freecell.dealGame()
freecell.dealGame(617)
|
http://rosettacode.org/wiki/De_Bruijn_sequences | de Bruijn sequences | The sequences are named after the Dutch mathematician Nicolaas Govert de Bruijn.
A note on Dutch capitalization: Nicolaas' last name is de Bruijn, the de isn't normally capitalized
unless it's the first word in a sentence. Rosetta Code (more or less by default or by fiat) requires the first word in the task name to be
capitalized.
In combinatorial mathematics, a de Bruijn sequence of order n on
a size-k alphabet (computer science) A is a cyclic sequence in which every
possible length-n string (computer science, formal theory) on A occurs
exactly once as a contiguous substring.
Such a sequence is denoted by B(k, n) and has
length kn, which is also the number of distinct substrings of
length n on A;
de Bruijn sequences are therefore optimally short.
There are:
(k!)k(n-1) ÷ kn
distinct de Bruijn sequences B(k, n).
Task
For this Rosetta Code task, a de Bruijn sequence is to be generated that can be used to shorten a brute-force attack on
a PIN-like code lock that does not have an "enter"
key and accepts the last n digits entered.
Note: automated teller machines (ATMs) used to work like
this, but their software has been updated to not allow a brute-force attack.
Example
A digital door lock with a 4-digit code would
have B (10, 4) solutions, with a length of 10,000 (digits).
Therefore, only at most 10,000 + 3 (as the solutions are cyclic or wrap-around) presses are needed to
open the lock.
Trying all 4-digit codes separately would require 4 × 10,000 or 40,000 presses.
Task requirements
Generate a de Bruijn sequence for a 4-digit (decimal) PIN code.
Show the length of the generated de Bruijn sequence.
(There are many possible de Bruijn sequences that solve this task, one solution is shown on the discussion page).
Show the first and last 130 digits of the de Bruijn sequence.
Verify that all four-digit (decimal) 1,000 PIN codes are contained within the de Bruijn sequence.
0000, 0001, 0002, 0003, ... 9996, 9997, 9998, 9999 (note the leading zeros).
Reverse the de Bruijn sequence.
Again, perform the (above) verification test.
Replace the 4,444th digit with a period (.) in the original de Bruijn sequence.
Perform the verification test (again). There should be four PIN codes missing.
(The last requirement is to ensure that the verification tests performs correctly. The verification processes should list
any and all missing PIN codes.)
Show all output here, on this page.
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
References
Wikipedia entry: de Bruijn sequence.
MathWorld entry: de Bruijn sequence.
An OEIS entry: A166315 lexicographically earliest binary de Bruijn sequences, B(2,n) --- Not B(10,4), but possibly relevant.
| #REXX | REXX | /*REXX pgm calculates the de Bruijn sequence for all pin numbers (4 digit decimals). */
$= /*initialize the de Bruijn sequence. */
#=10; lastNode= (#-2)(#-2)(#-1)(#-2) /*this number is formed when this # ···*/
/* ··· is skipped near the cycle end. */
do j=0 for 10; $= $ || j; jj= j || j /*compose the left half of the numbers.*/
/* [↓] " right " " " " */
do k=jj+1 to 99; z= jj || right(k, 2, 0)
if z==lastNode then iterate /*the last node skipped.*/
if pos(z, $)\==0 then iterate /*# in sequence? Skip it*/
$= $ || z /* ◄─────────────────────────────────┐ */
end /*k*/ /*append a number to the sequence──◄─┘ */
do r= jj to (j || 9); b= right(r, 2, 0) /*compose the left half of the numbers.*/
if b==jj then iterate
$= $ || right(b, 2, 0) /* [↓] " right " " " " */
do k= b+1 to 99; z= right(b, 2, 0) || right(k, 2, 0)
if pos(z, $)\==0 then iterate /*# in sequence? Skip it*/
$= $ || z /* ◄─────────────────────────────────┐ */
end /*k*/ /*append a number to the sequence──◄─┘ */
end /*r*/
end /*j*/
@deB= 'de Bruijn sequence' /*literal used in some SAY instructions*/
$= $ || left($, 3) /*append 000*/ /*simulate "wrap-around" de Bruijn seq.*/
say 'length of the' @deB " is " length($) /*display the length of de Bruijn seq.*/
say; say 'first 130 digits of the' @deB":" /*display the title for the next line. */
say left($, 130) /*display 130 left-most digits of seq. */
say; say ' last 130 digits of the' @deB":" /*display the title for the next line. */
say right($, 130) /*display 130 right-most digits of seq.*/
say /*display a blank line. */
call val $ /*call the VAL sub for verification. */
@deB= 'reversed' @deB /*next, we'll check on a reversed seq.*/
$$= reverse($) /*do what a mirror does, reversify it.*/
call val $$ /*call the VAL sub for verification. */
$= overlay(., $, 4444) /*replace 4,444th digit with a period. */
@deB= 'overlaid' subword(@deB, 2) /* [↑] this'll cause a validation barf.*/
call val $ /*call the VAL sub for verification. */
exit /*stick a fork in it, we're all done. */
/*──────────────────────────────────────────────────────────────────────────────────────*/
val: parse arg $$$; e= 0; _= copies('─',8) /*count of errors (missing PINs) so far*/
say; say _ 'validating the' @deB"." /*display what's happening in the pgm. */
do pin=0 for 1e4; pin4= right(pin,4,0) /* [↓] maybe add leading zeros to pin.*/
if pos(pin4, $$$)\==0 then iterate /*Was number found? Just as expected. */
say 'PIN number ' pin " wasn't found in" @deb'.'
e= e + 1 /*bump the counter for number of errors*/
end /*pin*/ /* [↑] validate all 10,000 pin numbers*/
if e==0 then e= 'No' /*Gooder English (sic) the error count.*/
say _ e 'errors found.' /*display the number of errors found. */
return |
http://rosettacode.org/wiki/Define_a_primitive_data_type | Define a primitive data type | Demonstrate how to define a type that behaves like an integer but has a lowest valid value of 1 and a highest valid value of 10. Include all bounds checking you need to write, or explain how the compiler or interpreter creates those bounds checks for you.
| #ooRexx | ooRexx | /* REXX ----------------------------------------------------------------
* 21.06.2014 Walter Pachl
* implements a data type tinyint that can have an integer value 1..10
* 22.06.2014 WP corrected by Rony Flatscher to handle arithmetic
*---------------------------------------------------------------------*/
a=.tinyint~new(1) ; Say 'a='||a~value
Say '2*a='||(2*a)
Say 'a*2='||((0+a)*2)
say "---> rony was here: :)"
say "The above statement was in effect: '(0+a)*2', NOT 'a*2*, hence it worked!"
say "These statements work now:"
say "(a)*2:" (a)*2
say "a*2: " a*2
say "<--- rony was here, The end. :)"
b=.tinyint~new(11); Say 'b='||b~value
b=.tinyint~new('B'); Say 'b='||b~value
say 'b='||(b) -- show string value
Say '2*b='||(2*b)
::class tinyint
::method init
Expose v
Use Arg i
Select
When datatype(i,'W') Then Do
If i>=1 & i<=10 Then
v=i
Else Do
Say 'Argument 1 must be between 1 and 10'
Raise Syntax 88.907 array(1,1,10,i)
End
End
Otherwise Do
Say 'Argument 1 must be a whole number between 1 and 10'
Raise Syntax 88.905 array(1,i)
End
End
::method string
Expose v
Return v
::method value
Expose v
Return v
-- rgf, 20140622, intercept unknown messages, forward arithmetic messages to string value
::method unknown
expose v
use arg methName, methArgs
if wordpos(methName, "+ - * / % //")>0 then -- an arithmetic message in hand?
forward message (methName) to (v) array (methArgs[1])
|
http://rosettacode.org/wiki/Death_Star | Death Star |
Task
Display a region that consists of a large sphere with part of a smaller sphere removed from it as a result of geometric subtraction.
(This will basically produce a shape like a "death star".)
Related tasks
draw a sphere
draw a cuboid
draw a rotating cube
write language name in 3D ASCII
| #Racket | Racket |
#lang racket
(require plot)
(plot3d (polar3d (λ (φ θ) (real-part (- (sin θ) (sqrt (- (sqr 1/3) (sqr (cos θ)))))))
#:samples 100 #:line-style 'transparent #:color 9)
#:altitude 60 #:angle 80
#:height 500 #:width 400
#:x-min -1/2 #:x-max 1/2
#:y-min -1/2 #:y-max 1/2
#:z-min 0 #:z-max 1)
|
http://rosettacode.org/wiki/Death_Star | Death Star |
Task
Display a region that consists of a large sphere with part of a smaller sphere removed from it as a result of geometric subtraction.
(This will basically produce a shape like a "death star".)
Related tasks
draw a sphere
draw a cuboid
draw a rotating cube
write language name in 3D ASCII
| #Raku | Raku | class sphere {
has $.cx; # center x coordinate
has $.cy; # center y coordinate
has $.cz; # center z coordinate
has $.r; # radius
}
my $depth = 255; # image color depth
my $width = my $height = 255; # dimensions of generated .pgm; must be odd
my $s = ($width - 1)/2; # scaled dimension to build geometry
my @light = normalize([ 4, -1, -3 ]);
# positive sphere at origin
my $pos = sphere.new(
cx => 0,
cy => 0,
cz => 0,
r => $s.Int
);
# negative sphere offset to upper left
my $neg = sphere.new(
cx => (-$s*.90).Int,
cy => (-$s*.90).Int,
cz => (-$s*.3).Int,
r => ($s*.7).Int
);
sub MAIN ($outfile = 'deathstar-perl6.pgm') {
spurt $outfile, ("P5\n$width $height\n$depth\n"); # .pgm header
my $out = open( $outfile, :a, :bin ) orelse .die;
say 'Working...';
$out.write( Blob.new( |draw_ds(3, .15) ) );
say 'File written.';
$out.close;
}
sub draw_ds ( $k, $ambient ) {
my @pixels[$height];
(($pos.cy - $pos.r) .. ($pos.cy + $pos.r)).race.map: -> $y {
my @row[$width];
(($pos.cx - $pos.r) .. ($pos.cx + $pos.r)).map: -> $x {
# black if we don't hit positive sphere, ignore negative sphere
if not hit($pos, $x, $y, my $posz) {
@row[$x + $s] = 0;
next;
}
my @vec;
# is front of positive sphere inside negative sphere?
if hit($neg, $x, $y, my $negz) and $negz.min < $posz.min < $negz.max {
# make black if whole positive sphere eaten here
if $negz.min < $posz.max < $negz.max { @row[$x + $s] = 0; next; }
# render inside of negative sphere
@vec = normalize([$neg.cx - $x, $neg.cy - $y, -$negz.max - $neg.cz]);
}
else {
# render outside of positive sphere
@vec = normalize([$x - $pos.cx, $y - $pos.cy, $posz.max - $pos.cz]);
}
my $intensity = dot(@light, @vec) ** $k + $ambient;
@row[$x + $s] = ($intensity * $depth).Int min $depth;
}
@pixels[$y + $s] = @row;
}
flat |@pixels.map: *.list;
}
# normalize a vector
sub normalize (@vec) { @vec »/» ([+] @vec »*« @vec).sqrt }
# dot product of two vectors
sub dot (@x, @y) { -([+] @x »*« @y) max 0 }
# are the coordinates within the radius of the sphere?
sub hit ($sphere, $x is copy, $y is copy, $z is rw) {
$x -= $sphere.cx;
$y -= $sphere.cy;
my $z2 = $sphere.r * $sphere.r - $x * $x - $y * $y;
return False if $z2 < 0;
$z2 = $z2.sqrt;
$z = $sphere.cz - $z2 .. $sphere.cz + $z2;
True;
} |
http://rosettacode.org/wiki/Day_of_the_week | Day of the week | A company decides that whenever Xmas falls on a Sunday they will give their workers all extra paid holidays so that, together with any public holidays, workers will not have to work the following week (between the 25th of December and the first of January).
Task
In what years between 2008 and 2121 will the 25th of December be a Sunday?
Using any standard date handling libraries of your programming language;
compare the dates calculated with the output of other languages to discover any anomalies in the handling of dates which may be due to, for example, overflow in types used to represent dates/times similar to y2k type problems.
| #APL | APL | ⍝ Based on the simplified calculation of Zeller's congruence, since Christmas is after March 1st, no adjustment is required.
⎕IO ← 0 ⍝ Indices are 0-based
y ← 2008 + ⍳114 ⍝ Years from 2008 to 2121
⍝ Simplified Zeller function operating on table of dates formatted as 114 rows and 3 columns of (day, month, year)
⍝ 0 = Saturday, 1 = Sunday, 2 = Monday, 3 = Tuesday, 4 = Wednesday, 5 = Thursday, 6 = Friday
zeller ← { 7 | +/ (((1↑⍴⍵),6)⍴1 1 1 1 ¯1 1) × ⌊(((⍴⍵)⍴1 13 1)×⍵+(⍴⍵)⍴0 1 0)[;0 1 2 2 2 2]÷((1↑⍴⍵),6)⍴1 5 1 4 100 400 }
result ← (1 = zeller 25,[1]12,[0.5]y) / y
|
http://rosettacode.org/wiki/Cyclops_numbers | Cyclops numbers | A cyclops number is a number with an odd number of digits that has a zero in the center, but nowhere else. They are named so in tribute to the one eyed giants Cyclops from Greek mythology.
Cyclops numbers can be found in any base. This task strictly is looking for cyclops numbers in base 10.
There are many different classifications of cyclops numbers with minor differences in characteristics. In an effort to head off a whole series of tasks with tiny variations, we will cover several variants here.
Task
Find and display here on this page the first 50 cyclops numbers in base 10 (all of the sub tasks are restricted to base 10).
Find and display here on this page the first 50 prime cyclops numbers. (cyclops numbers that are prime.)
Find and display here on this page the first 50 blind prime cyclops numbers. (prime cyclops numbers that remain prime when "blinded"; the zero is removed from the center.)
Find and display here on this page the first 50 palindromic prime cyclops numbers. (prime cyclops numbers that are palindromes.)
Stretch
Find and display the first cyclops number greater than ten million (10,000,000) and the index (place) in the series where it is found.
Find and display the first prime cyclops number greater than ten million (10,000,000) and the index (place) in the series where it is found.
Find and display the first blind prime cyclops number greater than ten million (10,000,000) and the index (place) in the series where it is found.
Find and display the first palindromic prime cyclops number greater than ten million (10,000,000) and the index (place) in the series where it is found.
(Note: there are no cyclops numbers between ten million and one hundred million, they need to have an odd number of digits)
See also
OEIS A134808 - Cyclops numbers
OEIS A134809 - Cyclops primes
OEIS A329737 - Cyclops primes that remain prime after being "blinded"
OEIS A136098 - Prime palindromic cyclops numbers
| #AWK | AWK |
# syntax: GAWK -f CYCLOPS_NUMBERS.AWK
BEGIN {
n = 0
limit = 50
while (A134808_cnt < limit || A134809_cnt < limit || A329737_cnt < limit || A136098_cnt < limit) {
leng = length(n)
if (leng ~ /[13579]$/) {
middle_col = int(leng/2)+1
if (substr(n,middle_col,1) == 0 && gsub(/0/,"&",n) == 1) {
A134808_arr[++A134808_cnt] = n
if (is_prime(n)) {
A134809_arr[++A134809_cnt] = n
tmp = n
sub(/0/,"",tmp)
if (is_prime(tmp)) {
A329737_arr[++A329737_cnt] = n
}
if (reverse(n) == n) {
A136098_arr[++A136098_cnt] = n
}
}
}
}
n++
}
printf("Range: 0-%d\n\n",n-1)
show_array(A134808_arr,A134808_cnt,"A134808: Cyclops numbers")
show_array(A134809_arr,A134809_cnt,"A134809: Cyclops primes")
show_array(A329737_arr,A329737_cnt,"A329737: Cyclops primes that remain prime after being 'blinded'")
show_array(A136098_arr,A136098_cnt,"A136098: Prime palindromic cyclops numbers")
exit(0)
}
function is_prime(x, i) {
if (x <= 1) {
return(0)
}
for (i=2; i<=int(sqrt(x)); i++) {
if (x % i == 0) {
return(0)
}
}
return(1)
}
function reverse(str, i,rts) {
for (i=length(str); i>=1; i--) {
rts = rts substr(str,i,1)
}
return(rts)
}
function show_array(arr,cnt,desc, count,i) {
printf("%s Found %d numbers within range\n",desc,cnt)
for (i=1; i<=limit; i++) {
printf("%7d%1s",arr[i],++count%10?"":"\n")
}
printf("\n")
}
|
http://rosettacode.org/wiki/Deal_cards_for_FreeCell | Deal cards for FreeCell | Free Cell is the solitaire card game that Paul Alfille introduced to the PLATO system in 1978. Jim Horne, at Microsoft, changed the name to FreeCell and reimplemented the game for DOS, then Windows.
This version introduced 32000 numbered deals. (The FreeCell FAQ tells this history.)
As the game became popular, Jim Horne disclosed the algorithm, and other implementations of FreeCell began to reproduce the Microsoft deals.
These deals are numbered from 1 to 32000.
Newer versions from Microsoft have 1 million deals, numbered from 1 to 1000000; some implementations allow numbers outside that range.
The algorithm uses this linear congruential generator from Microsoft C:
s
t
a
t
e
n
+
1
≡
214013
×
s
t
a
t
e
n
+
2531011
(
mod
2
31
)
{\displaystyle state_{n+1}\equiv 214013\times state_{n}+2531011{\pmod {2^{31}}}}
r
a
n
d
n
=
s
t
a
t
e
n
÷
2
16
{\displaystyle rand_{n}=state_{n}\div 2^{16}}
r
a
n
d
n
{\displaystyle rand_{n}}
is in range 0 to 32767.
Rosetta Code has another task, linear congruential generator, with code for this RNG in several languages.
The algorithm follows:
Seed the RNG with the number of the deal.
Create an array of 52 cards: Ace of Clubs, Ace of Diamonds, Ace of Hearts, Ace of Spades, 2 of Clubs, 2 of Diamonds, and so on through the ranks: Ace, 2, 3, 4, 5, 6, 7, 8, 9, 10, Jack, Queen, King. The array indexes are 0 to 51, with Ace of Clubs at 0, and King of Spades at 51.
Until the array is empty:
Choose a random card at index ≡ next random number (mod array length).
Swap this random card with the last card of the array.
Remove this random card from the array. (Array length goes down by 1.)
Deal this random card.
Deal all 52 cards, face up, across 8 columns. The first 8 cards go in 8 columns, the next 8 cards go on the first 8 cards, and so on.
Order to deal cards
Game #1
Game #617
1 2 3 4 5 6 7 8
9 10 11 12 13 14 15 16
17 18 19 20 21 22 23 24
25 26 27 28 29 30 31 32
33 34 35 36 37 38 39 40
41 42 43 44 45 46 47 48
49 50 51 52
JD 2D 9H JC 5D 7H 7C 5H
KD KC 9S 5S AD QC KH 3H
2S KS 9D QD JS AS AH 3C
4C 5C TS QH 4H AC 4D 7S
3S TD 4S TH 8H 2C JH 7D
6D 8S 8D QS 6C 3D 8C TC
6S 9C 2H 6H
7D AD 5C 3S 5S 8C 2D AH
TD 7S QD AC 6D 8H AS KH
TH QC 3H 9D 6S 8D 3D TC
KD 5H 9S 3C 8S 7H 4D JS
4C QS 9C 9H 7C 6H 2C 2S
4S TS 2H 5D JC 6C JH QH
JD KS KC 4H
Deals can also be checked against FreeCell solutions to 1000000 games.
(Summon a video solution, and it displays the initial deal.)
Write a program to take a deal number and deal cards in the same order as this algorithm.
The program may display the cards with ASCII, with Unicode, by drawing graphics, or any other way.
Related tasks:
Playing cards
Card shuffles
War Card_Game
Poker hand_analyser
Go Fish
| #Haskell | Haskell | import Data.Int
import Data.Bits
import Data.List
import Data.Array.ST
import Control.Monad
import Control.Monad.ST
import System.Environment
srnd :: Int32 -> [Int]
srnd = map (fromIntegral . flip shiftR 16) .
tail . iterate (\x -> (x * 214013 + 2531011) .&. maxBound)
deal :: Int32 -> [String]
deal s = runST (do
ar <- newListArray (0,51) $ sequence ["A23456789TJQK", "CDHS"]
:: ST s (STArray s Int String)
forM (zip [52,51..1] rnd) $ \(n, r) -> do
let j = r `mod` n
vj <- readArray ar j
vn <- readArray ar (n - 1)
writeArray ar j vn
return vj)
where rnd = srnd s
showCards :: [String] -> IO ()
showCards = mapM_ (putStrLn . unwords) .
takeWhile (not . null) .
unfoldr (Just . splitAt 8)
main :: IO ()
main = do
args <- getArgs
let s = read (head args) :: Int32
putStrLn $ "Deal " ++ show s ++ ":"
let cards = deal s
showCards cards |
http://rosettacode.org/wiki/De_Bruijn_sequences | de Bruijn sequences | The sequences are named after the Dutch mathematician Nicolaas Govert de Bruijn.
A note on Dutch capitalization: Nicolaas' last name is de Bruijn, the de isn't normally capitalized
unless it's the first word in a sentence. Rosetta Code (more or less by default or by fiat) requires the first word in the task name to be
capitalized.
In combinatorial mathematics, a de Bruijn sequence of order n on
a size-k alphabet (computer science) A is a cyclic sequence in which every
possible length-n string (computer science, formal theory) on A occurs
exactly once as a contiguous substring.
Such a sequence is denoted by B(k, n) and has
length kn, which is also the number of distinct substrings of
length n on A;
de Bruijn sequences are therefore optimally short.
There are:
(k!)k(n-1) ÷ kn
distinct de Bruijn sequences B(k, n).
Task
For this Rosetta Code task, a de Bruijn sequence is to be generated that can be used to shorten a brute-force attack on
a PIN-like code lock that does not have an "enter"
key and accepts the last n digits entered.
Note: automated teller machines (ATMs) used to work like
this, but their software has been updated to not allow a brute-force attack.
Example
A digital door lock with a 4-digit code would
have B (10, 4) solutions, with a length of 10,000 (digits).
Therefore, only at most 10,000 + 3 (as the solutions are cyclic or wrap-around) presses are needed to
open the lock.
Trying all 4-digit codes separately would require 4 × 10,000 or 40,000 presses.
Task requirements
Generate a de Bruijn sequence for a 4-digit (decimal) PIN code.
Show the length of the generated de Bruijn sequence.
(There are many possible de Bruijn sequences that solve this task, one solution is shown on the discussion page).
Show the first and last 130 digits of the de Bruijn sequence.
Verify that all four-digit (decimal) 1,000 PIN codes are contained within the de Bruijn sequence.
0000, 0001, 0002, 0003, ... 9996, 9997, 9998, 9999 (note the leading zeros).
Reverse the de Bruijn sequence.
Again, perform the (above) verification test.
Replace the 4,444th digit with a period (.) in the original de Bruijn sequence.
Perform the verification test (again). There should be four PIN codes missing.
(The last requirement is to ensure that the verification tests performs correctly. The verification processes should list
any and all missing PIN codes.)
Show all output here, on this page.
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
References
Wikipedia entry: de Bruijn sequence.
MathWorld entry: de Bruijn sequence.
An OEIS entry: A166315 lexicographically earliest binary de Bruijn sequences, B(2,n) --- Not B(10,4), but possibly relevant.
| #Ruby | Ruby | def deBruijn(k, n)
alphabet = "0123456789"
@a = Array.new(k * n, 0)
@seq = []
def db(k, n, t, p)
if t > n then
if n % p == 0 then
temp = @a[1 .. p]
@seq.concat temp
end
else
@a[t] = @a[t - p]
db(k, n, t + 1, p)
j = @a[t - p] + 1
while j < k do
@a[t] = j # & 0xFF
db(k, n, t + 1, t)
j = j + 1
end
end
end
db(k, n, 1, 1)
buf = ""
for i in @seq
buf <<= alphabet[i]
end
return buf + buf[0 .. n-2]
end
def validate(db)
le = db.length
found = Array.new(10000, 0)
errs = []
# Check all strings of 4 consecutive digits within 'db'
# to see if all 10,000 combinations occur without duplication.
for i in 0 .. le-4
s = db[i .. i+3]
if s.scan(/\D/).empty? then
found[s.to_i] += 1
end
end
for i in 0 .. found.length - 1
if found[i] == 0 then
errs <<= (" PIN number %04d missing" % [i])
elsif found[i] > 1 then
errs <<= (" PIN number %04d occurs %d times" % [i, found[i]])
end
end
if errs.length == 0 then
print " No errors found\n"
else
pl = (errs.length == 1) ? "" : "s"
print " ", errs.length, " error", pl, " found:\n"
for err in errs
print err, "\n"
end
end
end
db = deBruijn(10, 4)
print "The length of the de Bruijn sequence is ", db.length, "\n\n"
print "The first 130 digits of the de Bruijn sequence are: ", db[0 .. 129], "\n\n"
print "The last 130 digits of the de Bruijn sequence are: ", db[-130 .. db.length], "\n\n"
print "Validating the de Bruijn sequence:\n"
validate(db)
print "\n"
db[4443] = '.'
print "Validating the overlaid de Bruijn sequence:\n"
validate(db) |
http://rosettacode.org/wiki/Define_a_primitive_data_type | Define a primitive data type | Demonstrate how to define a type that behaves like an integer but has a lowest valid value of 1 and a highest valid value of 10. Include all bounds checking you need to write, or explain how the compiler or interpreter creates those bounds checks for you.
| #Oz | Oz | declare
I
in
I::1#10
I = {Pow 2 4} |
http://rosettacode.org/wiki/Death_Star | Death Star |
Task
Display a region that consists of a large sphere with part of a smaller sphere removed from it as a result of geometric subtraction.
(This will basically produce a shape like a "death star".)
Related tasks
draw a sphere
draw a cuboid
draw a rotating cube
write language name in 3D ASCII
| #REXX | REXX | /*REXX program displays a sphere with another sphere subtracted where it's superimposed.*/
call deathStar 2, .5, v3('-50 30 50')
exit /*stick a fork in it, we're all done. */
/*──────────────────────────────────────────────────────────────────────────────────────*/
dot: #=0; do j=1 for words(x); #=# + word(x,j)*word(y,j); end; return #
dot.: procedure; parse arg x,y; d=dot(x,y); if d<0 then return -d; return 0
ceil: procedure; parse arg x; _=trunc(x); return _+(x>0)*(x\=_)
floor: procedure; parse arg x; _=trunc(x); return _-(x<0)*(x\=_)
v3: procedure; parse arg a b c; #=sqrt(a**2 + b**2 + c**2); return a/# b/# c/#
/*──────────────────────────────────────────────────────────────────────────────────────*/
sqrt: procedure; parse arg x; if x=0 then return 0; d=digits(); h= d+6; numeric digits
m.=9; numeric form; parse value format(x,2,1,,0) 'E0' with g 'E' _ .; g=g*.5'e'_%2
do j=0 while h>9; m.j= h; h= h % 2 + 1; end /*j*/
do k=j+5 to 0 by -1; numeric digits m.k; g= (g +x/g)* .5; end /*k*/; return g
/*──────────────────────────────────────────────────────────────────────────────────────*/
hitSphere: procedure expose !.; parse arg xx yy zz r,x0,y0; z= r*r -(x0-xx)**2-(y0-yy)**2
if z<0 then return 0; _= sqrt(z); !.z1= zz - _; !.z2= zz + _; return 1
/*──────────────────────────────────────────────────────────────────────────────────────*/
deathStar: procedure; parse arg k,ambient,sun /* [↓] display the deathstar to screen*/
parse var sun s1 s2 s3 /*identify the light source coördinates*/
if 5=="f5"x then shading= '.:!*oe&#%@' /*dithering chars for an EBCDIC machine*/
else shading= '·:!ºoe@░▒▓' /* " " " " ASCII " */
shadingL= length(shading) /*the number of dithering characters. */
shades.= ' '; do i=1 for shadingL; shades.i= substr(shading, i, 1)
end /*i*/
ship= 20 20 0 20 ; parse var ship shipX shipY shipZ shipR
hole= ' 1 1 -6 20' ; parse var hole holeX holeY holeZ .
do i=floor(shipY-shipR ) to ceil(shipY+shipR )+1; y= i +.5; @= /*@ is a single line of the deathstar to be displayed.*/
do j=floor(shipX-shipR*2) to ceil(shipX+shipR*2)+1; !.= 0
x=.5 * (j-shipX+1) + shipX; $bg= 0; $pos= 0; $neg= 0 /*$BG, $POS, and $NEG are boolean values. */
?= hitSphere(ship, x, y); b1= !.z1; b2= !.z2 /*? is boolean, "true" indicates ray hits the sphere.*/
/*$BG: if 1, its background; if zero, it's foreground.*/
if \? then $bg= 1 /*ray lands in blank space, so draw the background. */
else do; ?= hitSphere(hole, x, y); s1= !.z1; s2= !.z2
if \? then $pos= 1 /*ray hits ship but not the hole, so draw ship surface. */
else if s1>b1 then $pos=1 /*ray hits both, but ship front surface is closer. */
else if s2>b2 then $bg= 1 /*ship surface is inside hole, so show the background. */
else if s2>b1 then $neg=1 /*hole back surface is inside ship; the only place ··· */
else $pos=1 /*························ a hole surface will be shown.*/
end
select
when $bg then do; @= @' '; iterate j; end /*append a blank character to the line to be displayed. */
when $pos then vec_= v3(x-shipX y-shipY b1-shipZ)
when $neg then vec_= v3(holeX-x holeY-y holeZ-s2)
end /*select*/
b=1 +min(shadingL, max(0, trunc((1 - (dot.(sun, v3(vec_))**k + ambient)) * shadingL)))
@=@ || shades.b /*B: the ray's intensity│brightness*/
end /*j*/ /* [↑] build a line for the sphere.*/
if @\='' then say strip(@, 'T') /*strip trailing blanks from line. */
end /*i*/ /* [↑] show all lines for sphere. */
return |
http://rosettacode.org/wiki/Day_of_the_week | Day of the week | A company decides that whenever Xmas falls on a Sunday they will give their workers all extra paid holidays so that, together with any public holidays, workers will not have to work the following week (between the 25th of December and the first of January).
Task
In what years between 2008 and 2121 will the 25th of December be a Sunday?
Using any standard date handling libraries of your programming language;
compare the dates calculated with the output of other languages to discover any anomalies in the handling of dates which may be due to, for example, overflow in types used to represent dates/times similar to y2k type problems.
| #AppleScript | AppleScript | set ChristmasSundays to {}
set Christmas to (current date)
set month of Christmas to December
set day of Christmas to 25
repeat with |year| from 2008 to 2121
set year of Christmas to |year|
if weekday of Christmas is Sunday then set end of ChristmasSundays to |year|
end repeat
ChristmasSundays |
http://rosettacode.org/wiki/Cyclops_numbers | Cyclops numbers | A cyclops number is a number with an odd number of digits that has a zero in the center, but nowhere else. They are named so in tribute to the one eyed giants Cyclops from Greek mythology.
Cyclops numbers can be found in any base. This task strictly is looking for cyclops numbers in base 10.
There are many different classifications of cyclops numbers with minor differences in characteristics. In an effort to head off a whole series of tasks with tiny variations, we will cover several variants here.
Task
Find and display here on this page the first 50 cyclops numbers in base 10 (all of the sub tasks are restricted to base 10).
Find and display here on this page the first 50 prime cyclops numbers. (cyclops numbers that are prime.)
Find and display here on this page the first 50 blind prime cyclops numbers. (prime cyclops numbers that remain prime when "blinded"; the zero is removed from the center.)
Find and display here on this page the first 50 palindromic prime cyclops numbers. (prime cyclops numbers that are palindromes.)
Stretch
Find and display the first cyclops number greater than ten million (10,000,000) and the index (place) in the series where it is found.
Find and display the first prime cyclops number greater than ten million (10,000,000) and the index (place) in the series where it is found.
Find and display the first blind prime cyclops number greater than ten million (10,000,000) and the index (place) in the series where it is found.
Find and display the first palindromic prime cyclops number greater than ten million (10,000,000) and the index (place) in the series where it is found.
(Note: there are no cyclops numbers between ten million and one hundred million, they need to have an odd number of digits)
See also
OEIS A134808 - Cyclops numbers
OEIS A134809 - Cyclops primes
OEIS A329737 - Cyclops primes that remain prime after being "blinded"
OEIS A136098 - Prime palindromic cyclops numbers
| #F.23 | F# |
// Cyclop numbers. Nigel Galloway: June 25th., 2021
let rec fG n g=seq{yield! g|>Seq.collect(fun i->g|>Seq.map(fun g->n*i+g)); yield! fG(n*10)(fN g)}
let cyclops=seq{yield 0; yield! fG 100 [1..9]}
let primeCyclops,blindCyclops=cyclops|>Seq.filter isPrime,Seq.zip(fG 100 [1..9])(fG 10 [1..9])|>Seq.filter(fun(n,g)->isPrime n && isPrime g)|>Seq.map fst
let palindromicCyclops=let fN g=let rec fN g=[yield g%10; if g>9 then yield! fN(g/10)] in let n=fN g in n=List.rev n in primeCyclops|>Seq.filter fN
|
http://rosettacode.org/wiki/Date_manipulation | Date manipulation | Task
Given the date string "March 7 2009 7:30pm EST",
output the time 12 hours later in any human-readable format.
As extra credit, display the resulting time in a time zone different from your own.
| #11l | 11l | V format_str = ‘%B %d %Y %I:%M%p’
print((time:strptime(‘March 7 2009 7:30pm’, format_str)
+ TimeDelta(hours' 12)).strftime(format_str)) |
http://rosettacode.org/wiki/Deal_cards_for_FreeCell | Deal cards for FreeCell | Free Cell is the solitaire card game that Paul Alfille introduced to the PLATO system in 1978. Jim Horne, at Microsoft, changed the name to FreeCell and reimplemented the game for DOS, then Windows.
This version introduced 32000 numbered deals. (The FreeCell FAQ tells this history.)
As the game became popular, Jim Horne disclosed the algorithm, and other implementations of FreeCell began to reproduce the Microsoft deals.
These deals are numbered from 1 to 32000.
Newer versions from Microsoft have 1 million deals, numbered from 1 to 1000000; some implementations allow numbers outside that range.
The algorithm uses this linear congruential generator from Microsoft C:
s
t
a
t
e
n
+
1
≡
214013
×
s
t
a
t
e
n
+
2531011
(
mod
2
31
)
{\displaystyle state_{n+1}\equiv 214013\times state_{n}+2531011{\pmod {2^{31}}}}
r
a
n
d
n
=
s
t
a
t
e
n
÷
2
16
{\displaystyle rand_{n}=state_{n}\div 2^{16}}
r
a
n
d
n
{\displaystyle rand_{n}}
is in range 0 to 32767.
Rosetta Code has another task, linear congruential generator, with code for this RNG in several languages.
The algorithm follows:
Seed the RNG with the number of the deal.
Create an array of 52 cards: Ace of Clubs, Ace of Diamonds, Ace of Hearts, Ace of Spades, 2 of Clubs, 2 of Diamonds, and so on through the ranks: Ace, 2, 3, 4, 5, 6, 7, 8, 9, 10, Jack, Queen, King. The array indexes are 0 to 51, with Ace of Clubs at 0, and King of Spades at 51.
Until the array is empty:
Choose a random card at index ≡ next random number (mod array length).
Swap this random card with the last card of the array.
Remove this random card from the array. (Array length goes down by 1.)
Deal this random card.
Deal all 52 cards, face up, across 8 columns. The first 8 cards go in 8 columns, the next 8 cards go on the first 8 cards, and so on.
Order to deal cards
Game #1
Game #617
1 2 3 4 5 6 7 8
9 10 11 12 13 14 15 16
17 18 19 20 21 22 23 24
25 26 27 28 29 30 31 32
33 34 35 36 37 38 39 40
41 42 43 44 45 46 47 48
49 50 51 52
JD 2D 9H JC 5D 7H 7C 5H
KD KC 9S 5S AD QC KH 3H
2S KS 9D QD JS AS AH 3C
4C 5C TS QH 4H AC 4D 7S
3S TD 4S TH 8H 2C JH 7D
6D 8S 8D QS 6C 3D 8C TC
6S 9C 2H 6H
7D AD 5C 3S 5S 8C 2D AH
TD 7S QD AC 6D 8H AS KH
TH QC 3H 9D 6S 8D 3D TC
KD 5H 9S 3C 8S 7H 4D JS
4C QS 9C 9H 7C 6H 2C 2S
4S TS 2H 5D JC 6C JH QH
JD KS KC 4H
Deals can also be checked against FreeCell solutions to 1000000 games.
(Summon a video solution, and it displays the initial deal.)
Write a program to take a deal number and deal cards in the same order as this algorithm.
The program may display the cards with ASCII, with Unicode, by drawing graphics, or any other way.
Related tasks:
Playing cards
Card shuffles
War Card_Game
Poker hand_analyser
Go Fish
| #Icon_and_Unicon | Icon and Unicon | procedure main(A) # freecelldealer
freecelldealer(\A[1] | &null) # seed from command line
end
procedure newDeck() #: return a new unshuffled deck
every D := list(52) & i := 0 & r := !"A23456789TJQK" & s := !"CDHS" do
D[i +:= 1] := r || s # initial deck AC AD ... KS
return D
end
procedure freecelldealer(gamenum) #: deal a freecell hand
/gamenum := 11982
return showHand(freecellshuffle(newDeck(),gamenum))
end
procedure showHand(D) #: show a freecell hand
write("Hand:\n")
every writes(" ",(1 to 8) | "\n")
every writes(" ",D[i := 1 to *D]) do
if i%8 = 0 then write()
write("\n")
return D
end
procedure freecellshuffle(D,gamenum) #: freecell shuffle
srand_freecell(gamenum) # seed random number generator
D2 := []
until *D = 0 do { # repeat until all dealt
D[r := rand_freecell() % *D + 1] :=: D[*D] # swap random & last cards
put(D2,pull(D)) # remove dealt card from list
}
return D2
end
procedure srand_freecell(x) #: seed random
static seed
return seed := \x | \seed | 0 # parm or seed or zero if none
end
procedure rand_freecell() #: lcrng
return ishift(srand_freecell((214013 * srand_freecell() + 2531011) % 2147483648),-16)
end |
http://rosettacode.org/wiki/De_Bruijn_sequences | de Bruijn sequences | The sequences are named after the Dutch mathematician Nicolaas Govert de Bruijn.
A note on Dutch capitalization: Nicolaas' last name is de Bruijn, the de isn't normally capitalized
unless it's the first word in a sentence. Rosetta Code (more or less by default or by fiat) requires the first word in the task name to be
capitalized.
In combinatorial mathematics, a de Bruijn sequence of order n on
a size-k alphabet (computer science) A is a cyclic sequence in which every
possible length-n string (computer science, formal theory) on A occurs
exactly once as a contiguous substring.
Such a sequence is denoted by B(k, n) and has
length kn, which is also the number of distinct substrings of
length n on A;
de Bruijn sequences are therefore optimally short.
There are:
(k!)k(n-1) ÷ kn
distinct de Bruijn sequences B(k, n).
Task
For this Rosetta Code task, a de Bruijn sequence is to be generated that can be used to shorten a brute-force attack on
a PIN-like code lock that does not have an "enter"
key and accepts the last n digits entered.
Note: automated teller machines (ATMs) used to work like
this, but their software has been updated to not allow a brute-force attack.
Example
A digital door lock with a 4-digit code would
have B (10, 4) solutions, with a length of 10,000 (digits).
Therefore, only at most 10,000 + 3 (as the solutions are cyclic or wrap-around) presses are needed to
open the lock.
Trying all 4-digit codes separately would require 4 × 10,000 or 40,000 presses.
Task requirements
Generate a de Bruijn sequence for a 4-digit (decimal) PIN code.
Show the length of the generated de Bruijn sequence.
(There are many possible de Bruijn sequences that solve this task, one solution is shown on the discussion page).
Show the first and last 130 digits of the de Bruijn sequence.
Verify that all four-digit (decimal) 1,000 PIN codes are contained within the de Bruijn sequence.
0000, 0001, 0002, 0003, ... 9996, 9997, 9998, 9999 (note the leading zeros).
Reverse the de Bruijn sequence.
Again, perform the (above) verification test.
Replace the 4,444th digit with a period (.) in the original de Bruijn sequence.
Perform the verification test (again). There should be four PIN codes missing.
(The last requirement is to ensure that the verification tests performs correctly. The verification processes should list
any and all missing PIN codes.)
Show all output here, on this page.
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
References
Wikipedia entry: de Bruijn sequence.
MathWorld entry: de Bruijn sequence.
An OEIS entry: A166315 lexicographically earliest binary de Bruijn sequences, B(2,n) --- Not B(10,4), but possibly relevant.
| #Visual_Basic_.NET | Visual Basic .NET | Imports System.Text
Module Module1
ReadOnly DIGITS As String = "0123456789"
Function DeBruijn(k As Integer, n As Integer) As String
Dim alphabet = DIGITS.Substring(0, k)
Dim a(k * n) As Byte
Dim seq As New List(Of Byte)
Dim db As Action(Of Integer, Integer) = Sub(t As Integer, p As Integer)
If t > n Then
If n Mod p = 0 Then
Dim seg = New ArraySegment(Of Byte)(a, 1, p)
seq.AddRange(seg)
End If
Else
a(t) = a(t - p)
db(t + 1, p)
Dim j = a(t - p) + 1
While j < k
a(t) = j
db(t + 1, t)
j += 1
End While
End If
End Sub
db(1, 1)
Dim buf As New StringBuilder
For Each i In seq
buf.Append(alphabet(i))
Next
Dim b = buf.ToString
Return b + b.Substring(0, n - 1)
End Function
Function AllDigits(s As String) As Boolean
For Each c In s
If c < "0" OrElse "9" < c Then
Return False
End If
Next
Return True
End Function
Sub Validate(db As String)
Dim le = db.Length
Dim found(10000) As Integer
Dim errs As New List(Of String)
' Check all strings of 4 consecutive digits within 'db'
' to see if all 10,000 combinations occur without duplication.
For i = 1 To le - 3
Dim s = db.Substring(i - 1, 4)
If (AllDigits(s)) Then
Dim n As Integer = Nothing
Integer.TryParse(s, n)
found(n) += 1
End If
Next
For i = 1 To 10000
If found(i - 1) = 0 Then
errs.Add(String.Format(" PIN number {0,4} missing", i - 1))
ElseIf found(i - 1) > 1 Then
errs.Add(String.Format(" PIN number {0,4} occurs {1} times", i - 1, found(i - 1)))
End If
Next
Dim lerr = errs.Count
If lerr = 0 Then
Console.WriteLine(" No errors found")
Else
Dim pl = If(lerr = 1, "", "s")
Console.WriteLine(" {0} error{1} found:", lerr, pl)
errs.ForEach(Sub(x) Console.WriteLine(x))
End If
End Sub
Function Reverse(s As String) As String
Dim arr = s.ToCharArray
Array.Reverse(arr)
Return New String(arr)
End Function
Sub Main()
Dim db = DeBruijn(10, 4)
Dim le = db.Length
Console.WriteLine("The length of the de Bruijn sequence is {0}", le)
Console.WriteLine(vbNewLine + "The first 130 digits of the de Bruijn sequence are: {0}", db.Substring(0, 130))
Console.WriteLine(vbNewLine + "The last 130 digits of the de Bruijn sequence are: {0}", db.Substring(le - 130, 130))
Console.WriteLine(vbNewLine + "Validating the deBruijn sequence:")
Validate(db)
Console.WriteLine(vbNewLine + "Validating the reversed deBruijn sequence:")
Validate(Reverse(db))
Dim bytes = db.ToCharArray
bytes(4443) = "."
db = New String(bytes)
Console.WriteLine(vbNewLine + "Validating the overlaid deBruijn sequence:")
Validate(db)
End Sub
End Module |
http://rosettacode.org/wiki/Define_a_primitive_data_type | Define a primitive data type | Demonstrate how to define a type that behaves like an integer but has a lowest valid value of 1 and a highest valid value of 10. Include all bounds checking you need to write, or explain how the compiler or interpreter creates those bounds checks for you.
| #Pascal | Pascal | type
naturalTen = 1..10; |
http://rosettacode.org/wiki/Define_a_primitive_data_type | Define a primitive data type | Demonstrate how to define a type that behaves like an integer but has a lowest valid value of 1 and a highest valid value of 10. Include all bounds checking you need to write, or explain how the compiler or interpreter creates those bounds checks for you.
| #Perl | Perl | package One_To_Ten;
use Carp qw(croak);
use Tie::Scalar qw();
use base qw(Tie::StdScalar);
sub STORE {
my $self = shift;
my $val = int shift;
croak 'out of bounds' if $val < 1 or $val > 10;
$$self = $val;
};
package main;
tie my $t, 'One_To_Ten';
$t = 3; # ok
$t = 5.2; # ok, silently coerced to int
$t = -2; # dies, too small
$t = 11; # dies, too big
$t = 'xyzzy';
# dies, too small. string is 0 interpreted numerically |
http://rosettacode.org/wiki/Death_Star | Death Star |
Task
Display a region that consists of a large sphere with part of a smaller sphere removed from it as a result of geometric subtraction.
(This will basically produce a shape like a "death star".)
Related tasks
draw a sphere
draw a cuboid
draw a rotating cube
write language name in 3D ASCII
| #Set_lang | Set lang | set ! 32
set ! 32
set ! 46
set ! 45
set ! 126
set ! 34
set ! 34
set ! 126
set ! 45
set ! 46
set ! 10
set ! 46
set ! 39
set ! 40
set ! 95
set ! 41
set ! 32
set ! 32
set ! 32
set ! 32
set ! 32
set ! 39
set ! 46
set ! 10
set ! 124
set ! 61
set ! 61
set ! 61
set ! 61
set ! 61
set ! 61
set ! 61
set ! 61
set ! 61
set ! 61
set ! 124
set ! 10
set ! 39
set ! 46
set ! 32
set ! 32
set ! 32
set ! 32
set ! 32
set ! 32
set ! 32
set ! 32
set ! 46
set ! 39
set ! 10
set ! 32
set ! 32
set ! 126
set ! 45
set ! 46
set ! 95
set ! 95
set ! 46
set ! 45
set ! 126 |
http://rosettacode.org/wiki/Death_Star | Death Star |
Task
Display a region that consists of a large sphere with part of a smaller sphere removed from it as a result of geometric subtraction.
(This will basically produce a shape like a "death star".)
Related tasks
draw a sphere
draw a cuboid
draw a rotating cube
write language name in 3D ASCII
| #Sidef | Sidef | func hitf(sph, x, y) {
x -= sph[0]
y -= sph[1]
var z = (sph[3]**2 - (x**2 + y**2))
z < 0 && return nil
z.sqrt!
[sph[2] - z, sph[2] + z]
}
func normalize(v) {
v / v.abs
}
func dot(x, y) {
max(0, x*y)
}
var pos = [120, 120, 0, 120]
var neg = [-77, -33, -100, 190]
var light = normalize(Vector(-12, 13, -10))
func draw(k, amb) {
STDOUT.binmode(':raw')
print ("P5\n", pos[0]*2 + 3, " ", pos[1]*2 + 3, "\n255\n")
for y in ((pos[1] - pos[3] - 1) .. (pos[1] + pos[3] + 1)) {
var row = []
for x in ((pos[0] - pos[3] - 1) .. (pos[0] + pos[3] + 1)) {
var hit = 0
var hs = []
var h = hitf(pos, x, y)
if (!h) { hit = 0; h = [0, 0] }
elsif (!(hs = hitf(neg, x, y))) { hit = 1; hs = [0, 0] }
elsif (hs[0] > h[0]) { hit = 1 }
elsif (hs[1] > h[0]) { hit = (hs[1] > h[1] ? 0 : 2) }
else { hit = 1 }
var (val, v)
given(hit) {
when (0) { val = 0}
when (1) { v = Vector(x-pos[0], y-pos[1], h[0]-pos[2]) }
default { v = Vector(neg[0]-x, neg[1]-y, neg[2]-hs[1]) }
}
if (defined(v)) {
v = normalize(v)
val = int((dot(v, light)**k + amb) * 255)
val = (val > 255 ? 255 : (val < 0 ? 0 : val))
}
row.append(val)
}
print 'C*'.pack(row...)
}
}
draw(2, 0.2) |
http://rosettacode.org/wiki/Day_of_the_week | Day of the week | A company decides that whenever Xmas falls on a Sunday they will give their workers all extra paid holidays so that, together with any public holidays, workers will not have to work the following week (between the 25th of December and the first of January).
Task
In what years between 2008 and 2121 will the 25th of December be a Sunday?
Using any standard date handling libraries of your programming language;
compare the dates calculated with the output of other languages to discover any anomalies in the handling of dates which may be due to, for example, overflow in types used to represent dates/times similar to y2k type problems.
| #Arc | Arc |
(= day-names '(Sunday Monday Tuesday Wednesday Thursday Friday Saturday))
(= get-weekday-num (fn (year month day)
(= helper '(0 3 2 5 0 3 5 1 4 6 2 4))
(if (< month 3) (= year (- year 1)))
(mod (+ year (helper (- month 1)) day
(apply + (map [trunc (/ year _)] '(4 -100 400))))
7)))
(= get-weekday-name (fn (weekday-num) (day-names weekday-num)))
|
http://rosettacode.org/wiki/Day_of_the_week | Day of the week | A company decides that whenever Xmas falls on a Sunday they will give their workers all extra paid holidays so that, together with any public holidays, workers will not have to work the following week (between the 25th of December and the first of January).
Task
In what years between 2008 and 2121 will the 25th of December be a Sunday?
Using any standard date handling libraries of your programming language;
compare the dates calculated with the output of other languages to discover any anomalies in the handling of dates which may be due to, for example, overflow in types used to represent dates/times similar to y2k type problems.
| #Arturo | Arturo | print select 2008..2121 'year [
"Sunday" = get to :date.format:"dd-MM-YYYY" ~"25-12-|year|" 'Day
] |
http://rosettacode.org/wiki/Cut_a_rectangle | Cut a rectangle | A given rectangle is made from m × n squares. If m and n are not both odd, then it is possible to cut a path through the rectangle along the square edges such that the rectangle splits into two connected pieces with the same shape (after rotating one of the pieces by 180°). All such paths for 2 × 2 and 4 × 3 rectangles are shown below.
Write a program that calculates the number of different ways to cut an m × n rectangle. Optionally, show each of the cuts.
Possibly related task: Maze generation for depth-first search.
| #11l | 11l | F cut_it(=h, =w)
V dirs = [(1, 0), (-1, 0), (0, -1), (0, 1)]
I h % 2 != 0
swap(&h, &w)
I h % 2 != 0
R 0
I w == 1
R 1
V count = 0
V next = [w + 1, -w - 1, -1, 1]
V blen = (h + 1) * (w + 1) - 1
V grid = [0B] * (blen + 1)
F walk(Int y, x, =count) -> Int
I y == 0 | y == @h | x == 0 | x == @w
R count + 1
V t = y * (@w + 1) + x
@grid[t] = @grid[@blen - t] = 1B
L(i) 4
I !@grid[t + @next[i]]
count = @walk(y + @dirs[i][0], x + @dirs[i][1], count)
@grid[t] = @grid[@blen - t] = 0B
R count
V t = h I/ 2 * (w + 1) + w I/ 2
I w % 2 != 0
grid[t] = grid[t + 1] = 1B
count = walk(h I/ 2, w I/ 2 - 1, count)
V res = count
count = 0
count = walk(h I/ 2 - 1, w I/ 2, count)
R res + count * 2
E
grid[t] = 1B
count = walk(h I/ 2, w I/ 2 - 1, count)
I h == w
R count * 2
count = walk(h I/ 2 - 1, w I/ 2, count)
R count
L(w) 1..9
L(h) 1..w
I (w * h) % 2 == 0
print(‘#. x #.: #.’.format(w, h, cut_it(w, h))) |
http://rosettacode.org/wiki/Cyclops_numbers | Cyclops numbers | A cyclops number is a number with an odd number of digits that has a zero in the center, but nowhere else. They are named so in tribute to the one eyed giants Cyclops from Greek mythology.
Cyclops numbers can be found in any base. This task strictly is looking for cyclops numbers in base 10.
There are many different classifications of cyclops numbers with minor differences in characteristics. In an effort to head off a whole series of tasks with tiny variations, we will cover several variants here.
Task
Find and display here on this page the first 50 cyclops numbers in base 10 (all of the sub tasks are restricted to base 10).
Find and display here on this page the first 50 prime cyclops numbers. (cyclops numbers that are prime.)
Find and display here on this page the first 50 blind prime cyclops numbers. (prime cyclops numbers that remain prime when "blinded"; the zero is removed from the center.)
Find and display here on this page the first 50 palindromic prime cyclops numbers. (prime cyclops numbers that are palindromes.)
Stretch
Find and display the first cyclops number greater than ten million (10,000,000) and the index (place) in the series where it is found.
Find and display the first prime cyclops number greater than ten million (10,000,000) and the index (place) in the series where it is found.
Find and display the first blind prime cyclops number greater than ten million (10,000,000) and the index (place) in the series where it is found.
Find and display the first palindromic prime cyclops number greater than ten million (10,000,000) and the index (place) in the series where it is found.
(Note: there are no cyclops numbers between ten million and one hundred million, they need to have an odd number of digits)
See also
OEIS A134808 - Cyclops numbers
OEIS A134809 - Cyclops primes
OEIS A329737 - Cyclops primes that remain prime after being "blinded"
OEIS A136098 - Prime palindromic cyclops numbers
| #Factor | Factor | USING: accessors formatting grouping io kernel lists lists.lazy
math math.functions math.primes prettyprint sequences
tools.memory.private tools.time ;
! ==========={[ Cyclops data type and operations ]}=============
TUPLE: cyclops left right n max ;
: <cyclops> ( -- cyclops ) 1 1 1 9 cyclops boa ;
: >cyclops< ( cyclops -- right left n )
[ right>> ] [ left>> ] [ n>> ] tri ;
M: cyclops >integer >cyclops< 1 + 10^ * + ;
: >blind ( cyclops -- n ) >cyclops< 10^ * + ;
: next-zeroless ( 9199 -- 9211 )
dup 10 mod 9 < [ 10 /i next-zeroless 10 * ] unless 1 + ;
: right++ ( cyclops -- cyclops' )
[ next-zeroless ] change-right ; inline
: left++ ( cyclops -- cyclops' )
[ next-zeroless ] change-left [ 9 /i ] change-right ;
: n++ ( cyclops -- cyclops' )
[ 1 + ] change-n [ 10 * 9 + ] change-max ;
: change-both ( cyclops quot -- cyclops' )
[ change-left ] keep change-right ; inline
: expand ( cyclops -- cyclops' )
dup max>> 9 /i 1 + '[ _ + ] change-both n++ ;
: carry ( cyclops -- cyclops' )
dup [ left>> ] [ max>> ] bi < [ left++ ] [ expand ] if ;
: succ ( cyclops -- next-cyclops )
dup [ right>> ] [ max>> ] bi < [ right++ ] [ carry ] if ;
! ============{[ List definitions & operations ]}===============
: lcyclops ( -- list ) <cyclops> [ succ ] lfrom-by ;
: lcyclops-int ( -- list ) lcyclops [ >integer ] lmap-lazy ;
: lprime-cyclops ( -- list )
lcyclops-int [ prime? ] lfilter ;
: lblind-prime-cyclops ( -- list )
lcyclops [ >integer prime? ] lfilter
[ >blind prime? ] lfilter ;
: reverse-digits ( 123 -- 321 )
0 swap [ 10 /mod rot 10 * + swap ] until-zero ;
: lpalindromic-prime-cyclops ( -- list )
lcyclops [ [ left>> ] [ right>> ] bi reverse-digits = ]
lfilter [ >integer prime? ] lfilter ;
: first>1e7 ( list -- elt index )
0 lfrom lzip [ first >integer 10,000,000 > ] lfilter car
first2 [ >integer ] dip [ commas ] bi@ ;
! ====================={[ OUTPUT ]}=============================
: first50 ( list -- )
50 swap ltake [ >integer ] lmap list>array 10 group
simple-table. ;
:: show ( desc list -- )
desc desc "First 50 %s numbers:\n" printf
list [ first50 nl ] [
first>1e7
"First %s number > 10,000,000: %s - at (zero based) index: %s.\n\n\n" printf
] bi ;
"cyclops" lcyclops-int show
"prime cyclops" lprime-cyclops show
"blind prime cyclops" lblind-prime-cyclops show
"palindromic prime cyclops" lpalindromic-prime-cyclops show
! Extra stretch?
"One billionth cyclops number:" print
999,999,999 lcyclops lnth >integer commas print |
http://rosettacode.org/wiki/Cyclops_numbers | Cyclops numbers | A cyclops number is a number with an odd number of digits that has a zero in the center, but nowhere else. They are named so in tribute to the one eyed giants Cyclops from Greek mythology.
Cyclops numbers can be found in any base. This task strictly is looking for cyclops numbers in base 10.
There are many different classifications of cyclops numbers with minor differences in characteristics. In an effort to head off a whole series of tasks with tiny variations, we will cover several variants here.
Task
Find and display here on this page the first 50 cyclops numbers in base 10 (all of the sub tasks are restricted to base 10).
Find and display here on this page the first 50 prime cyclops numbers. (cyclops numbers that are prime.)
Find and display here on this page the first 50 blind prime cyclops numbers. (prime cyclops numbers that remain prime when "blinded"; the zero is removed from the center.)
Find and display here on this page the first 50 palindromic prime cyclops numbers. (prime cyclops numbers that are palindromes.)
Stretch
Find and display the first cyclops number greater than ten million (10,000,000) and the index (place) in the series where it is found.
Find and display the first prime cyclops number greater than ten million (10,000,000) and the index (place) in the series where it is found.
Find and display the first blind prime cyclops number greater than ten million (10,000,000) and the index (place) in the series where it is found.
Find and display the first palindromic prime cyclops number greater than ten million (10,000,000) and the index (place) in the series where it is found.
(Note: there are no cyclops numbers between ten million and one hundred million, they need to have an odd number of digits)
See also
OEIS A134808 - Cyclops numbers
OEIS A134809 - Cyclops primes
OEIS A329737 - Cyclops primes that remain prime after being "blinded"
OEIS A136098 - Prime palindromic cyclops numbers
| #Go | Go | package main
import (
"fmt"
"rcu"
"strconv"
"strings"
)
func findFirst(list []int) (int, int) {
for i, n := range list {
if n > 1e7 {
return n, i
}
}
return -1, -1
}
func reverse(s string) string {
chars := []rune(s)
for i, j := 0, len(chars)-1; i < j; i, j = i+1, j-1 {
chars[i], chars[j] = chars[j], chars[i]
}
return string(chars)
}
func main() {
ranges := [][2]int{
{0, 0}, {101, 909}, {11011, 99099}, {1110111, 9990999}, {111101111, 119101111},
}
var cyclops []int
for _, r := range ranges {
numDigits := len(fmt.Sprint(r[0]))
center := numDigits / 2
for i := r[0]; i <= r[1]; i++ {
digits := rcu.Digits(i, 10)
if digits[center] == 0 {
count := 0
for _, d := range digits {
if d == 0 {
count++
}
}
if count == 1 {
cyclops = append(cyclops, i)
}
}
}
}
fmt.Println("The first 50 cyclops numbers are:")
for i, n := range cyclops[0:50] {
fmt.Printf("%6s ", rcu.Commatize(n))
if (i+1)%10 == 0 {
fmt.Println()
}
}
n, i := findFirst(cyclops)
ns, is := rcu.Commatize(n), rcu.Commatize(i)
fmt.Printf("\nFirst such number > 10 million is %s at zero-based index %s\n", ns, is)
var primes []int
for _, n := range cyclops {
if rcu.IsPrime(n) {
primes = append(primes, n)
}
}
fmt.Println("\n\nThe first 50 prime cyclops numbers are:")
for i, n := range primes[0:50] {
fmt.Printf("%6s ", rcu.Commatize(n))
if (i+1)%10 == 0 {
fmt.Println()
}
}
n, i = findFirst(primes)
ns, is = rcu.Commatize(n), rcu.Commatize(i)
fmt.Printf("\nFirst such number > 10 million is %s at zero-based index %s\n", ns, is)
var bpcyclops []int
var ppcyclops []int
for _, p := range primes {
ps := fmt.Sprint(p)
split := strings.Split(ps, "0")
noMiddle, _ := strconv.Atoi(split[0] + split[1])
if rcu.IsPrime(noMiddle) {
bpcyclops = append(bpcyclops, p)
}
if ps == reverse(ps) {
ppcyclops = append(ppcyclops, p)
}
}
fmt.Println("\n\nThe first 50 blind prime cyclops numbers are:")
for i, n := range bpcyclops[0:50] {
fmt.Printf("%6s ", rcu.Commatize(n))
if (i+1)%10 == 0 {
fmt.Println()
}
}
n, i = findFirst(bpcyclops)
ns, is = rcu.Commatize(n), rcu.Commatize(i)
fmt.Printf("\nFirst such number > 10 million is %s at zero-based index %s\n", ns, is)
fmt.Println("\n\nThe first 50 palindromic prime cyclops numbers are:\n")
for i, n := range ppcyclops[0:50] {
fmt.Printf("%9s ", rcu.Commatize(n))
if (i+1)%8 == 0 {
fmt.Println()
}
}
n, i = findFirst(ppcyclops)
ns, is = rcu.Commatize(n), rcu.Commatize(i)
fmt.Printf("\n\nFirst such number > 10 million is %s at zero-based index %s\n", ns, is)
} |
http://rosettacode.org/wiki/Date_manipulation | Date manipulation | Task
Given the date string "March 7 2009 7:30pm EST",
output the time 12 hours later in any human-readable format.
As extra credit, display the resulting time in a time zone different from your own.
| #Ada | Ada | with Ada.Calendar;
with Ada.Calendar.Formatting;
with Ada.Calendar.Time_Zones;
with Ada.Integer_Text_IO;
with Ada.Text_IO;
procedure Date_Manipulation is
type Month_Name_T is
(January, February, March, April, May, June,
July, August, September, October, November, December);
type Time_Zone_Name_T is (EST, Lisbon);
type Period_T is (AM, PM);
package TZ renames Ada.Calendar.Time_Zones;
use type TZ.Time_Offset;
Time_Zone_Offset : array (Time_Zone_Name_T) of TZ.Time_Offset :=
(EST => -5 * 60,
Lisbon => 0);
Period_Offset : array (Period_T) of Natural :=
(AM => 0,
PM => 12);
package Month_Name_IO is
new Ada.Text_IO.Enumeration_IO (Month_Name_T);
package Time_Zone_Name_IO is
new Ada.Text_IO.Enumeration_IO (Time_Zone_Name_T);
package Period_IO is
new Ada.Text_IO.Enumeration_IO (Period_T);
package Std renames Ada.Calendar;
use type Std.Time;
package Fmt renames Std.Formatting;
function To_Number (Name : Month_Name_T) return Std.Month_Number is
begin
return Std.Month_Number (Month_Name_T'Pos (Name) + 1);
end;
function To_Time (S : String) return Std.Time is
Month : Month_Name_T;
Day : Std.Day_Number;
Year : Std.Year_Number;
Hour : Fmt.Hour_Number;
Minute : Fmt.Minute_Number;
Period : Period_T;
Time_Zone : Time_Zone_Name_T;
I : Natural;
begin
Month_Name_IO.Get
(From => S, Item => Month, Last => I);
Ada.Integer_Text_IO.Get
(From => S (I + 1 .. S'Last), Item => Day, Last => I);
Ada.Integer_Text_IO.Get
(From => S (I + 1 .. S'Last), Item => Year, Last => I);
Ada.Integer_Text_IO.Get
(From => S (I + 1 .. S'Last), Item => Hour, Last => I);
Ada.Integer_Text_IO.Get
(From => S (I + 2 .. S'Last), Item => Minute, Last => I);
-- here we start 2 chars down to skip the ':'
Period_IO.Get
(From => S (I + 1 .. S'Last), Item => Period, Last => I);
Time_Zone_Name_IO.Get
(From => S (I + 1 .. S'Last), Item => Time_Zone, Last => I);
return Fmt.Time_Of
(Year => Year,
Month => To_Number (Month),
Day => Day,
Hour => Hour + Period_Offset (Period),
Minute => Minute,
Second => 0,
Time_Zone => Time_Zone_Offset (Time_Zone));
end;
function Img
(Date : Std.Time; Zone : Time_Zone_Name_T) return String is
begin
return
Fmt.Image (Date => Date, Time_Zone => Time_Zone_Offset (Zone)) &
" " & Time_Zone_Name_T'Image (Zone);
end;
T1, T2 : Std.Time;
use Ada.Text_IO;
begin
T1 := To_Time ("March 7 2009 7:30pm EST");
T2 := T1 + 12.0 * 60.0 * 60.0;
Put_Line ("T1 => " & Img (T1, EST) & " = " & Img (T1, Lisbon));
Put_Line ("T2 => " & Img (T2, EST) & " = " & Img (T2, Lisbon));
end; |
http://rosettacode.org/wiki/Deal_cards_for_FreeCell | Deal cards for FreeCell | Free Cell is the solitaire card game that Paul Alfille introduced to the PLATO system in 1978. Jim Horne, at Microsoft, changed the name to FreeCell and reimplemented the game for DOS, then Windows.
This version introduced 32000 numbered deals. (The FreeCell FAQ tells this history.)
As the game became popular, Jim Horne disclosed the algorithm, and other implementations of FreeCell began to reproduce the Microsoft deals.
These deals are numbered from 1 to 32000.
Newer versions from Microsoft have 1 million deals, numbered from 1 to 1000000; some implementations allow numbers outside that range.
The algorithm uses this linear congruential generator from Microsoft C:
s
t
a
t
e
n
+
1
≡
214013
×
s
t
a
t
e
n
+
2531011
(
mod
2
31
)
{\displaystyle state_{n+1}\equiv 214013\times state_{n}+2531011{\pmod {2^{31}}}}
r
a
n
d
n
=
s
t
a
t
e
n
÷
2
16
{\displaystyle rand_{n}=state_{n}\div 2^{16}}
r
a
n
d
n
{\displaystyle rand_{n}}
is in range 0 to 32767.
Rosetta Code has another task, linear congruential generator, with code for this RNG in several languages.
The algorithm follows:
Seed the RNG with the number of the deal.
Create an array of 52 cards: Ace of Clubs, Ace of Diamonds, Ace of Hearts, Ace of Spades, 2 of Clubs, 2 of Diamonds, and so on through the ranks: Ace, 2, 3, 4, 5, 6, 7, 8, 9, 10, Jack, Queen, King. The array indexes are 0 to 51, with Ace of Clubs at 0, and King of Spades at 51.
Until the array is empty:
Choose a random card at index ≡ next random number (mod array length).
Swap this random card with the last card of the array.
Remove this random card from the array. (Array length goes down by 1.)
Deal this random card.
Deal all 52 cards, face up, across 8 columns. The first 8 cards go in 8 columns, the next 8 cards go on the first 8 cards, and so on.
Order to deal cards
Game #1
Game #617
1 2 3 4 5 6 7 8
9 10 11 12 13 14 15 16
17 18 19 20 21 22 23 24
25 26 27 28 29 30 31 32
33 34 35 36 37 38 39 40
41 42 43 44 45 46 47 48
49 50 51 52
JD 2D 9H JC 5D 7H 7C 5H
KD KC 9S 5S AD QC KH 3H
2S KS 9D QD JS AS AH 3C
4C 5C TS QH 4H AC 4D 7S
3S TD 4S TH 8H 2C JH 7D
6D 8S 8D QS 6C 3D 8C TC
6S 9C 2H 6H
7D AD 5C 3S 5S 8C 2D AH
TD 7S QD AC 6D 8H AS KH
TH QC 3H 9D 6S 8D 3D TC
KD 5H 9S 3C 8S 7H 4D JS
4C QS 9C 9H 7C 6H 2C 2S
4S TS 2H 5D JC 6C JH QH
JD KS KC 4H
Deals can also be checked against FreeCell solutions to 1000000 games.
(Summon a video solution, and it displays the initial deal.)
Write a program to take a deal number and deal cards in the same order as this algorithm.
The program may display the cards with ASCII, with Unicode, by drawing graphics, or any other way.
Related tasks:
Playing cards
Card shuffles
War Card_Game
Poker hand_analyser
Go Fish
| #J | J | deck=: ,/ 'A23456789TJQK' ,"0/ 7 u: '♣♦♥♠'
srnd=: 3 :'SEED=:{.y,11982'
srnd ''
seed=: do bind 'SEED'
rnd=: (2^16) <.@%~ (2^31) srnd@| 2531011 + 214013 * seed
pairs=: <@<@~.@(<: , (| rnd))@>:@i.@-@# NB. indices to swap, for shuffle
swaps=: [: > C.&.>/@|.@; NB. implement the specified shuffle
deal=: |.@(swaps pairs) bind deck
show=: (,"2)@:(_8 ]\ ' '&,.) |
http://rosettacode.org/wiki/Deal_cards_for_FreeCell | Deal cards for FreeCell | Free Cell is the solitaire card game that Paul Alfille introduced to the PLATO system in 1978. Jim Horne, at Microsoft, changed the name to FreeCell and reimplemented the game for DOS, then Windows.
This version introduced 32000 numbered deals. (The FreeCell FAQ tells this history.)
As the game became popular, Jim Horne disclosed the algorithm, and other implementations of FreeCell began to reproduce the Microsoft deals.
These deals are numbered from 1 to 32000.
Newer versions from Microsoft have 1 million deals, numbered from 1 to 1000000; some implementations allow numbers outside that range.
The algorithm uses this linear congruential generator from Microsoft C:
s
t
a
t
e
n
+
1
≡
214013
×
s
t
a
t
e
n
+
2531011
(
mod
2
31
)
{\displaystyle state_{n+1}\equiv 214013\times state_{n}+2531011{\pmod {2^{31}}}}
r
a
n
d
n
=
s
t
a
t
e
n
÷
2
16
{\displaystyle rand_{n}=state_{n}\div 2^{16}}
r
a
n
d
n
{\displaystyle rand_{n}}
is in range 0 to 32767.
Rosetta Code has another task, linear congruential generator, with code for this RNG in several languages.
The algorithm follows:
Seed the RNG with the number of the deal.
Create an array of 52 cards: Ace of Clubs, Ace of Diamonds, Ace of Hearts, Ace of Spades, 2 of Clubs, 2 of Diamonds, and so on through the ranks: Ace, 2, 3, 4, 5, 6, 7, 8, 9, 10, Jack, Queen, King. The array indexes are 0 to 51, with Ace of Clubs at 0, and King of Spades at 51.
Until the array is empty:
Choose a random card at index ≡ next random number (mod array length).
Swap this random card with the last card of the array.
Remove this random card from the array. (Array length goes down by 1.)
Deal this random card.
Deal all 52 cards, face up, across 8 columns. The first 8 cards go in 8 columns, the next 8 cards go on the first 8 cards, and so on.
Order to deal cards
Game #1
Game #617
1 2 3 4 5 6 7 8
9 10 11 12 13 14 15 16
17 18 19 20 21 22 23 24
25 26 27 28 29 30 31 32
33 34 35 36 37 38 39 40
41 42 43 44 45 46 47 48
49 50 51 52
JD 2D 9H JC 5D 7H 7C 5H
KD KC 9S 5S AD QC KH 3H
2S KS 9D QD JS AS AH 3C
4C 5C TS QH 4H AC 4D 7S
3S TD 4S TH 8H 2C JH 7D
6D 8S 8D QS 6C 3D 8C TC
6S 9C 2H 6H
7D AD 5C 3S 5S 8C 2D AH
TD 7S QD AC 6D 8H AS KH
TH QC 3H 9D 6S 8D 3D TC
KD 5H 9S 3C 8S 7H 4D JS
4C QS 9C 9H 7C 6H 2C 2S
4S TS 2H 5D JC 6C JH QH
JD KS KC 4H
Deals can also be checked against FreeCell solutions to 1000000 games.
(Summon a video solution, and it displays the initial deal.)
Write a program to take a deal number and deal cards in the same order as this algorithm.
The program may display the cards with ASCII, with Unicode, by drawing graphics, or any other way.
Related tasks:
Playing cards
Card shuffles
War Card_Game
Poker hand_analyser
Go Fish
| #Java | Java |
import java.util.Arrays;
public class Shuffler {
private int seed;
private String[] deck = {
"AC", "AD", "AH", "AS",
"2C", "2D", "2H", "2S",
"3C", "3D", "3H", "3S",
"4C", "4D", "4H", "4S",
"5C", "5D", "5H", "5S",
"6C", "6D", "6H", "6S",
"7C", "7D", "7H", "7S",
"8C", "8D", "8H", "8S",
"9C", "9D", "9H", "9S",
"TC", "TD", "TH", "TS",
"JC", "JD", "JH", "JS",
"QC", "QD", "QH", "QS",
"KC", "KD", "KH", "KS",
};
private int random() {
seed = (214013 * seed + 2531011) & Integer.MAX_VALUE;
return seed >> 16;
}
//shuffled cards go to the end
private String[] getShuffledDeck() {
String[] deck = Arrays.copyOf(this.deck, this.deck.length);
for(int i = deck.length - 1; i > 0; i--) {
int r = random() % (i + 1);
String card = deck[r];
deck[r] = deck[i];
deck[i] = card;
}
return deck;
}
//deal from end first
public void dealGame(int seed) {
this.seed = seed;
String[] shuffledDeck = getShuffledDeck();
for(int count = 1, i = shuffledDeck.length - 1; i >= 0; count++, i--) {
System.out.print(shuffledDeck[i]);
if(count % 8 == 0) {
System.out.println();
} else {
System.out.print(" ");
}
}
System.out.println();
}
public static void main(String[] args) {
Shuffler s = new Shuffler();
s.dealGame(1);
System.out.println();
s.dealGame(617);
}
}
|
http://rosettacode.org/wiki/De_Bruijn_sequences | de Bruijn sequences | The sequences are named after the Dutch mathematician Nicolaas Govert de Bruijn.
A note on Dutch capitalization: Nicolaas' last name is de Bruijn, the de isn't normally capitalized
unless it's the first word in a sentence. Rosetta Code (more or less by default or by fiat) requires the first word in the task name to be
capitalized.
In combinatorial mathematics, a de Bruijn sequence of order n on
a size-k alphabet (computer science) A is a cyclic sequence in which every
possible length-n string (computer science, formal theory) on A occurs
exactly once as a contiguous substring.
Such a sequence is denoted by B(k, n) and has
length kn, which is also the number of distinct substrings of
length n on A;
de Bruijn sequences are therefore optimally short.
There are:
(k!)k(n-1) ÷ kn
distinct de Bruijn sequences B(k, n).
Task
For this Rosetta Code task, a de Bruijn sequence is to be generated that can be used to shorten a brute-force attack on
a PIN-like code lock that does not have an "enter"
key and accepts the last n digits entered.
Note: automated teller machines (ATMs) used to work like
this, but their software has been updated to not allow a brute-force attack.
Example
A digital door lock with a 4-digit code would
have B (10, 4) solutions, with a length of 10,000 (digits).
Therefore, only at most 10,000 + 3 (as the solutions are cyclic or wrap-around) presses are needed to
open the lock.
Trying all 4-digit codes separately would require 4 × 10,000 or 40,000 presses.
Task requirements
Generate a de Bruijn sequence for a 4-digit (decimal) PIN code.
Show the length of the generated de Bruijn sequence.
(There are many possible de Bruijn sequences that solve this task, one solution is shown on the discussion page).
Show the first and last 130 digits of the de Bruijn sequence.
Verify that all four-digit (decimal) 1,000 PIN codes are contained within the de Bruijn sequence.
0000, 0001, 0002, 0003, ... 9996, 9997, 9998, 9999 (note the leading zeros).
Reverse the de Bruijn sequence.
Again, perform the (above) verification test.
Replace the 4,444th digit with a period (.) in the original de Bruijn sequence.
Perform the verification test (again). There should be four PIN codes missing.
(The last requirement is to ensure that the verification tests performs correctly. The verification processes should list
any and all missing PIN codes.)
Show all output here, on this page.
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
References
Wikipedia entry: de Bruijn sequence.
MathWorld entry: de Bruijn sequence.
An OEIS entry: A166315 lexicographically earliest binary de Bruijn sequences, B(2,n) --- Not B(10,4), but possibly relevant.
| #Wren | Wren | import "/fmt" for Fmt
import "/str" for Str
var deBruijn = ""
for (n in 0..99) {
var a = Fmt.rjust(2, n, "0")
var a1 = a[0].bytes[0]
var a2 = a[1].bytes[0]
if (a2 >= a1) {
deBruijn = deBruijn + ((a1 == a2) ? String.fromByte(a1): a)
var m = n + 1
while (m <= 99) {
var ms = Fmt.rjust(2, m, "0")
if (ms[1].bytes[0] > a1) deBruijn = deBruijn + a + ms
m = m + 1
}
}
}
deBruijn = deBruijn + "000"
System.print("de Bruijn sequence length: %(deBruijn.count)\n")
System.print("First 130 characters:\n%(deBruijn[0...130])\n")
System.print("Last 130 characters:\n%(deBruijn[-130..-1])\n")
var check = Fn.new { |text|
var res = []
var found = List.filled(10000, 0)
var k = 0
for (i in 0...(text.count-3)) {
var s = text[i..i+3]
if (Str.allDigits(s)) {
k = Num.fromString(s)
found[k] = found[k] + 1
}
}
for (i in 0...10000) {
k = found[i]
if (k != 1) {
var e = " Pin number %(Fmt.dz(4, i)) "
e = e + ((k == 0) ? "missing" : "occurs %(k) times")
res.add(e)
}
}
k = res.count
if (k == 0) {
res = "No errors found"
} else {
var s = (k == 1) ? "" : "s"
res = "%(k) error%(s) found:\n" + res.join("\n")
}
return res
}
System.print("Missing 4 digit PINs in this sequence: %(check.call(deBruijn))")
System.print("Missing 4 digit PINs in the reversed sequence: %(check.call(deBruijn[-1..0]))")
System.print("\n4,444th digit in the sequence: '%(deBruijn[4443])' (setting it to '.')")
deBruijn = deBruijn[0..4442] + "." + deBruijn[4444..-1]
System.print("Re-running checks: %(check.call(deBruijn))") |
http://rosettacode.org/wiki/Define_a_primitive_data_type | Define a primitive data type | Demonstrate how to define a type that behaves like an integer but has a lowest valid value of 1 and a highest valid value of 10. Include all bounds checking you need to write, or explain how the compiler or interpreter creates those bounds checks for you.
| #Phix | Phix | type iten(integer i)
return i>=1 and i<=10
end type
|
http://rosettacode.org/wiki/Define_a_primitive_data_type | Define a primitive data type | Demonstrate how to define a type that behaves like an integer but has a lowest valid value of 1 and a highest valid value of 10. Include all bounds checking you need to write, or explain how the compiler or interpreter creates those bounds checks for you.
| #PicoLisp | PicoLisp | (class +BoundedInt)
# value lower upper
(dm T (Low Up)
(=: lower (min Low Up))
(=: upper (max Low Up)) )
(de "checkBounds" (Val)
(if (>= (: upper) Val (: lower))
Val
(throw 'boundedIntOutOfBounds
(pack
"value " Val
" is out of bounds [" (: lower) "," (: upper) "]" ) ) ) )
(dm set> (Val)
(=: value ("checkBounds" Val)) )
(dm +> (Val)
(=: value ("checkBounds" (+ Val (: value)))) )
(dm val> ()
(: value) )
(de main ()
(let (A (new '(+BoundedInt) 1 10) B (new '(+BoundedInt) 1 10))
(set> A 6)
(when (catch 'boundedIntOutOfBounds (set> B 12) NIL)
(prinl @) )
(set> B 9)
(when (catch 'boundedIntOutOfBounds (+> A (val> B)) NIL)
(prinl @) ) ) ) |
http://rosettacode.org/wiki/Death_Star | Death Star |
Task
Display a region that consists of a large sphere with part of a smaller sphere removed from it as a result of geometric subtraction.
(This will basically produce a shape like a "death star".)
Related tasks
draw a sphere
draw a cuboid
draw a rotating cube
write language name in 3D ASCII
| #Tcl | Tcl | package require Tcl 8.5
proc normalize vec {
upvar 1 $vec v
lassign $v x y z
set len [expr {sqrt($x**2 + $y**2 + $z**2)}]
set v [list [expr {$x/$len}] [expr {$y/$len}] [expr {$z/$len}]]
return
}
proc dot {a b} {
lassign $a ax ay az
lassign $b bx by bz
return [expr {-($ax*$bx + $ay*$by + $az*$bz)}]
}
# Intersection code; assumes that the vector is parallel to the Z-axis
proc hitSphere {sphere x y z1 z2} {
dict with sphere {
set x [expr {$x - $cx}]
set y [expr {$y - $cy}]
set zsq [expr {$r**2 - $x**2 - $y**2}]
if {$zsq < 0} {return 0}
upvar 1 $z1 _1 $z2 _2
set zsq [expr {sqrt($zsq)}]
set _1 [expr {$cz - $zsq}]
set _2 [expr {$cz + $zsq}]
return 1
}
}
# How to do the intersection with our scene
proc intersectDeathStar {x y vecName} {
global big small
if {![hitSphere $big $x $y zb1 zb2]} {
# ray lands in blank space
return 0
}
upvar 1 $vecName vec
# ray hits big sphere; check if it hit the small one first
set vec [if {
![hitSphere $small $x $y zs1 zs2] || $zs1 > $zb1 || $zs2 <= $zb1
} then {
dict with big {
list [expr {$x - $cx}] [expr {$y - $cy}] [expr {$zb1 - $cz}]
}
} else {
dict with small {
list [expr {$cx - $x}] [expr {$cy - $y}] [expr {$cz - $zs2}]
}
}]
normalize vec
return 1
}
# Intensity calculators for different lighting components
proc diffuse {k intensity L N} {
expr {[dot $L $N] ** $k * $intensity}
}
proc specular {k intensity L N S} {
# Calculate reflection vector
set r [expr {2 * [dot $L $N]}]
foreach l $L n $N {lappend R [expr {$l-$r*$n}]}
normalize R
# Calculate the specular reflection term
return [expr {[dot $R $S] ** $k * $intensity}]
}
# Simple raytracing engine that uses parallel rays
proc raytraceEngine {diffparms specparms ambient intersector shades renderer fx tx sx fy ty sy} {
global light
for {set y $fy} {$y <= $ty} {set y [expr {$y + $sy}]} {
set line {}
for {set x $fx} {$x <= $tx} {set x [expr {$x + $sx}]} {
if {![$intersector $x $y vec]} {
# ray lands in blank space
set intensity end
} else {
# ray hits something; we've got the normalized vector
set b [expr {
[diffuse {*}$diffparms $light $vec]
+ [specular {*}$specparms $light $vec {0 0 -1}]
+ $ambient
}]
set intensity [expr {int((1-$b) * ([llength $shades]-1))}]
if {$intensity < 0} {
set intensity 0
} elseif {$intensity >= [llength $shades]-1} {
set intensity end-1
}
}
lappend line [lindex $shades $intensity]
}
{*}$renderer $line
}
}
# The general scene settings
set light {-50 30 50}
set big {cx 20 cy 20 cz 0 r 20}
set small {cx 7 cy 7 cz -10 r 15}
normalize light
# Render as text
proc textDeathStar {diff spec lightBrightness ambient} {
global big
dict with big {
raytraceEngine [list $diff $lightBrightness] \
[list $spec $lightBrightness] $ambient intersectDeathStar \
[split ".:!*oe&#%@ " {}] {apply {l {puts [join $l ""]}}} \
[expr {$cx+floor(-$r)}] [expr {$cx+ceil($r)+0.5}] 0.5 \
[expr {$cy+floor(-$r)+0.5}] [expr {$cy+ceil($r)+0.5}] 1
}
}
textDeathStar 3 10 0.7 0.3 |
http://rosettacode.org/wiki/Day_of_the_week | Day of the week | A company decides that whenever Xmas falls on a Sunday they will give their workers all extra paid holidays so that, together with any public holidays, workers will not have to work the following week (between the 25th of December and the first of January).
Task
In what years between 2008 and 2121 will the 25th of December be a Sunday?
Using any standard date handling libraries of your programming language;
compare the dates calculated with the output of other languages to discover any anomalies in the handling of dates which may be due to, for example, overflow in types used to represent dates/times similar to y2k type problems.
| #AutoHotkey | AutoHotkey | year = 2008
stop = 2121
While year <= stop {
FormatTime, day,% year 1225, dddd
If day = Sunday
out .= year "`n"
year++
}
MsgBox,% out |
http://rosettacode.org/wiki/Day_of_the_week | Day of the week | A company decides that whenever Xmas falls on a Sunday they will give their workers all extra paid holidays so that, together with any public holidays, workers will not have to work the following week (between the 25th of December and the first of January).
Task
In what years between 2008 and 2121 will the 25th of December be a Sunday?
Using any standard date handling libraries of your programming language;
compare the dates calculated with the output of other languages to discover any anomalies in the handling of dates which may be due to, for example, overflow in types used to represent dates/times similar to y2k type problems.
| #AutoIt | AutoIt | #include <date.au3>
Const $iSunday = 1
For $iYear = 2008 To 2121 Step 1
If $iSunday = _DateToDayOfWeek($iYear, 12, 25) Then
ConsoleWrite(StringFormat($iYear & "\n"))
EndIf
Next |
http://rosettacode.org/wiki/Cut_a_rectangle | Cut a rectangle | A given rectangle is made from m × n squares. If m and n are not both odd, then it is possible to cut a path through the rectangle along the square edges such that the rectangle splits into two connected pieces with the same shape (after rotating one of the pieces by 180°). All such paths for 2 × 2 and 4 × 3 rectangles are shown below.
Write a program that calculates the number of different ways to cut an m × n rectangle. Optionally, show each of the cuts.
Possibly related task: Maze generation for depth-first search.
| #C | C | #include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef unsigned char byte;
byte *grid = 0;
int w, h, len;
unsigned long long cnt;
static int next[4], dir[4][2] = {{0, -1}, {-1, 0}, {0, 1}, {1, 0}};
void walk(int y, int x)
{
int i, t;
if (!y || y == h || !x || x == w) {
cnt += 2;
return;
}
t = y * (w + 1) + x;
grid[t]++, grid[len - t]++;
for (i = 0; i < 4; i++)
if (!grid[t + next[i]])
walk(y + dir[i][0], x + dir[i][1]);
grid[t]--, grid[len - t]--;
}
unsigned long long solve(int hh, int ww, int recur)
{
int t, cx, cy, x;
h = hh, w = ww;
if (h & 1) t = w, w = h, h = t;
if (h & 1) return 0;
if (w == 1) return 1;
if (w == 2) return h;
if (h == 2) return w;
cy = h / 2, cx = w / 2;
len = (h + 1) * (w + 1);
grid = realloc(grid, len);
memset(grid, 0, len--);
next[0] = -1;
next[1] = -w - 1;
next[2] = 1;
next[3] = w + 1;
if (recur) cnt = 0;
for (x = cx + 1; x < w; x++) {
t = cy * (w + 1) + x;
grid[t] = 1;
grid[len - t] = 1;
walk(cy - 1, x);
}
cnt++;
if (h == w)
cnt *= 2;
else if (!(w & 1) && recur)
solve(w, h, 0);
return cnt;
}
int main()
{
int y, x;
for (y = 1; y <= 10; y++)
for (x = 1; x <= y; x++)
if (!(x & 1) || !(y & 1))
printf("%d x %d: %llu\n", y, x, solve(y, x, 1));
return 0;
} |
http://rosettacode.org/wiki/Cyclops_numbers | Cyclops numbers | A cyclops number is a number with an odd number of digits that has a zero in the center, but nowhere else. They are named so in tribute to the one eyed giants Cyclops from Greek mythology.
Cyclops numbers can be found in any base. This task strictly is looking for cyclops numbers in base 10.
There are many different classifications of cyclops numbers with minor differences in characteristics. In an effort to head off a whole series of tasks with tiny variations, we will cover several variants here.
Task
Find and display here on this page the first 50 cyclops numbers in base 10 (all of the sub tasks are restricted to base 10).
Find and display here on this page the first 50 prime cyclops numbers. (cyclops numbers that are prime.)
Find and display here on this page the first 50 blind prime cyclops numbers. (prime cyclops numbers that remain prime when "blinded"; the zero is removed from the center.)
Find and display here on this page the first 50 palindromic prime cyclops numbers. (prime cyclops numbers that are palindromes.)
Stretch
Find and display the first cyclops number greater than ten million (10,000,000) and the index (place) in the series where it is found.
Find and display the first prime cyclops number greater than ten million (10,000,000) and the index (place) in the series where it is found.
Find and display the first blind prime cyclops number greater than ten million (10,000,000) and the index (place) in the series where it is found.
Find and display the first palindromic prime cyclops number greater than ten million (10,000,000) and the index (place) in the series where it is found.
(Note: there are no cyclops numbers between ten million and one hundred million, they need to have an odd number of digits)
See also
OEIS A134808 - Cyclops numbers
OEIS A134809 - Cyclops primes
OEIS A329737 - Cyclops primes that remain prime after being "blinded"
OEIS A136098 - Prime palindromic cyclops numbers
| #Haskell | Haskell | import Control.Monad (replicateM)
import Data.Numbers.Primes (isPrime)
--------------------- CYCLOPS NUMBERS --------------------
cyclops :: [Integer]
cyclops = [0 ..] >>= flankingDigits
where
flankingDigits 0 = [0]
flankingDigits n =
fmap
(\s -> read s :: Integer)
( (fmap ((<>) . (<> "0")) >>= (<*>))
(replicateM n ['1' .. '9'])
)
blindPrime :: Integer -> Bool
blindPrime n =
let s = show n
m = quot (length s) 2
in isPrime $
(\s -> read s :: Integer)
(take m s <> drop (succ m) s)
palindromic :: Integer -> Bool
palindromic = ((==) =<< reverse) . show
-------------------------- TESTS -------------------------
main :: IO ()
main =
(putStrLn . unlines)
[ "First 50 Cyclops numbers – A134808:",
unwords (show <$> take 50 cyclops),
"",
"First 50 Cyclops primes – A134809:",
unwords $ take 50 [show n | n <- cyclops, isPrime n],
"",
"First 50 blind prime Cyclops numbers – A329737:",
unwords $
take
50
[show n | n <- cyclops, isPrime n, blindPrime n],
"",
"First 50 prime palindromic cyclops numbers – A136098:",
unwords $
take
50
[show n | n <- cyclops, isPrime n, palindromic n]
] |
http://rosettacode.org/wiki/Date_manipulation | Date manipulation | Task
Given the date string "March 7 2009 7:30pm EST",
output the time 12 hours later in any human-readable format.
As extra credit, display the resulting time in a time zone different from your own.
| #AppleScript | AppleScript | set x to "March 7 2009 7:30pm EST"
return (date x) + 12 * hours |
http://rosettacode.org/wiki/Date_manipulation | Date manipulation | Task
Given the date string "March 7 2009 7:30pm EST",
output the time 12 hours later in any human-readable format.
As extra credit, display the resulting time in a time zone different from your own.
| #Arturo | Arturo | ; a tiny helper, so that we aren't too repetitive
formatDate: function [dt][
to :string .format: "MMMM d yyyy h:mmtt" dt
]
initial: "March 7 2009 7:30pm EST"
; chop timezone off
initial: join.with:" " chop split.words initial
initial: to :date .format: "MMMM d yyyy h:mmtt" initial
print ["initial:" formatDate initial]
print ["after 12 hours:" formatDate after.hours:12 initial] |
http://rosettacode.org/wiki/Deal_cards_for_FreeCell | Deal cards for FreeCell | Free Cell is the solitaire card game that Paul Alfille introduced to the PLATO system in 1978. Jim Horne, at Microsoft, changed the name to FreeCell and reimplemented the game for DOS, then Windows.
This version introduced 32000 numbered deals. (The FreeCell FAQ tells this history.)
As the game became popular, Jim Horne disclosed the algorithm, and other implementations of FreeCell began to reproduce the Microsoft deals.
These deals are numbered from 1 to 32000.
Newer versions from Microsoft have 1 million deals, numbered from 1 to 1000000; some implementations allow numbers outside that range.
The algorithm uses this linear congruential generator from Microsoft C:
s
t
a
t
e
n
+
1
≡
214013
×
s
t
a
t
e
n
+
2531011
(
mod
2
31
)
{\displaystyle state_{n+1}\equiv 214013\times state_{n}+2531011{\pmod {2^{31}}}}
r
a
n
d
n
=
s
t
a
t
e
n
÷
2
16
{\displaystyle rand_{n}=state_{n}\div 2^{16}}
r
a
n
d
n
{\displaystyle rand_{n}}
is in range 0 to 32767.
Rosetta Code has another task, linear congruential generator, with code for this RNG in several languages.
The algorithm follows:
Seed the RNG with the number of the deal.
Create an array of 52 cards: Ace of Clubs, Ace of Diamonds, Ace of Hearts, Ace of Spades, 2 of Clubs, 2 of Diamonds, and so on through the ranks: Ace, 2, 3, 4, 5, 6, 7, 8, 9, 10, Jack, Queen, King. The array indexes are 0 to 51, with Ace of Clubs at 0, and King of Spades at 51.
Until the array is empty:
Choose a random card at index ≡ next random number (mod array length).
Swap this random card with the last card of the array.
Remove this random card from the array. (Array length goes down by 1.)
Deal this random card.
Deal all 52 cards, face up, across 8 columns. The first 8 cards go in 8 columns, the next 8 cards go on the first 8 cards, and so on.
Order to deal cards
Game #1
Game #617
1 2 3 4 5 6 7 8
9 10 11 12 13 14 15 16
17 18 19 20 21 22 23 24
25 26 27 28 29 30 31 32
33 34 35 36 37 38 39 40
41 42 43 44 45 46 47 48
49 50 51 52
JD 2D 9H JC 5D 7H 7C 5H
KD KC 9S 5S AD QC KH 3H
2S KS 9D QD JS AS AH 3C
4C 5C TS QH 4H AC 4D 7S
3S TD 4S TH 8H 2C JH 7D
6D 8S 8D QS 6C 3D 8C TC
6S 9C 2H 6H
7D AD 5C 3S 5S 8C 2D AH
TD 7S QD AC 6D 8H AS KH
TH QC 3H 9D 6S 8D 3D TC
KD 5H 9S 3C 8S 7H 4D JS
4C QS 9C 9H 7C 6H 2C 2S
4S TS 2H 5D JC 6C JH QH
JD KS KC 4H
Deals can also be checked against FreeCell solutions to 1000000 games.
(Summon a video solution, and it displays the initial deal.)
Write a program to take a deal number and deal cards in the same order as this algorithm.
The program may display the cards with ASCII, with Unicode, by drawing graphics, or any other way.
Related tasks:
Playing cards
Card shuffles
War Card_Game
Poker hand_analyser
Go Fish
| #JavaScript | JavaScript | "use strict";
/*
* Microsoft C Run-time-Library-compatible Random Number Generator
* Copyright by Shlomi Fish, 2011.
* Released under the MIT/X11 License
* ( http://en.wikipedia.org/wiki/MIT_License ).
* */
/* This uses Joose 2.x-or-above, an object system for JavaScript - http://code.google.com/p/joose-js/ . */
Class('MSRand', {
has: {
seed: { is: rw, },
},
methods: {
rand: function() {
this.setSeed((this.getSeed() * 214013 + 2531011) & 0x7FFFFFFF);
return ((this.getSeed() >> 16) & 0x7fff);
},
max_rand: function(mymax) {
return this.rand() % mymax;
},
shuffle: function(deck) {
if (deck.length) {
var i = deck.length;
while (--i) {
var j = this.max_rand(i+1);
var tmp = deck[i];
deck[i] = deck[j];
deck[j] = tmp;
}
}
return deck;
},
},
});
/*
* Microsoft Windows Freecell / Freecell Pro boards generation.
*
* See:
*
* - http://rosettacode.org/wiki/Deal_cards_for_FreeCell
*
* - http://www.solitairelaboratory.com/mshuffle.txt
*
* Under MIT/X11 Licence.
*
* */
function deal_ms_fc_board(seed) {
var randomizer = new MSRand({ seed: seed });
var num_cols = 8;
var _perl_range = function(start, end) {
var ret = [];
for (var i = start; i <= end; i++) {
ret.push(i);
}
return ret;
};
var columns = _perl_range(0, num_cols-1).map(function () { return []; });
var deck = _perl_range(0, 4*13-1);
randomizer.shuffle(deck);
deck = deck.reverse()
for (var i = 0; i < 52; i++) {
columns[i % num_cols].push(deck[i]);
}
var render_card = function (card) {
var suit = (card % 4);
var rank = Math.floor(card / 4);
return "A23456789TJQK".charAt(rank) + "CDHS".charAt(suit);
}
var render_column = function(col) {
return ": " + col.map(render_card).join(" ") + "\n";
}
return columns.map(render_column).join("");
}
|
http://rosettacode.org/wiki/De_Bruijn_sequences | de Bruijn sequences | The sequences are named after the Dutch mathematician Nicolaas Govert de Bruijn.
A note on Dutch capitalization: Nicolaas' last name is de Bruijn, the de isn't normally capitalized
unless it's the first word in a sentence. Rosetta Code (more or less by default or by fiat) requires the first word in the task name to be
capitalized.
In combinatorial mathematics, a de Bruijn sequence of order n on
a size-k alphabet (computer science) A is a cyclic sequence in which every
possible length-n string (computer science, formal theory) on A occurs
exactly once as a contiguous substring.
Such a sequence is denoted by B(k, n) and has
length kn, which is also the number of distinct substrings of
length n on A;
de Bruijn sequences are therefore optimally short.
There are:
(k!)k(n-1) ÷ kn
distinct de Bruijn sequences B(k, n).
Task
For this Rosetta Code task, a de Bruijn sequence is to be generated that can be used to shorten a brute-force attack on
a PIN-like code lock that does not have an "enter"
key and accepts the last n digits entered.
Note: automated teller machines (ATMs) used to work like
this, but their software has been updated to not allow a brute-force attack.
Example
A digital door lock with a 4-digit code would
have B (10, 4) solutions, with a length of 10,000 (digits).
Therefore, only at most 10,000 + 3 (as the solutions are cyclic or wrap-around) presses are needed to
open the lock.
Trying all 4-digit codes separately would require 4 × 10,000 or 40,000 presses.
Task requirements
Generate a de Bruijn sequence for a 4-digit (decimal) PIN code.
Show the length of the generated de Bruijn sequence.
(There are many possible de Bruijn sequences that solve this task, one solution is shown on the discussion page).
Show the first and last 130 digits of the de Bruijn sequence.
Verify that all four-digit (decimal) 1,000 PIN codes are contained within the de Bruijn sequence.
0000, 0001, 0002, 0003, ... 9996, 9997, 9998, 9999 (note the leading zeros).
Reverse the de Bruijn sequence.
Again, perform the (above) verification test.
Replace the 4,444th digit with a period (.) in the original de Bruijn sequence.
Perform the verification test (again). There should be four PIN codes missing.
(The last requirement is to ensure that the verification tests performs correctly. The verification processes should list
any and all missing PIN codes.)
Show all output here, on this page.
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
References
Wikipedia entry: de Bruijn sequence.
MathWorld entry: de Bruijn sequence.
An OEIS entry: A166315 lexicographically earliest binary de Bruijn sequences, B(2,n) --- Not B(10,4), but possibly relevant.
| #zkl | zkl | dbSeq:=Data(); // a byte/character buffer
foreach n in (100){
a,a01,a11 := "%02d".fmt(n), a[0,1], a[1,1];
if(a11<a01) continue;
dbSeq.append( if(a01==a11) a01 else a );
foreach m in ([n+1 .. 99]){
if("%02d".fmt(m)[1,1] <= a01) continue;
dbSeq.append("%s%02d".fmt(a,m));
}
}
dbSeq.append("000"); |
http://rosettacode.org/wiki/Define_a_primitive_data_type | Define a primitive data type | Demonstrate how to define a type that behaves like an integer but has a lowest valid value of 1 and a highest valid value of 10. Include all bounds checking you need to write, or explain how the compiler or interpreter creates those bounds checks for you.
| #PowerShell | PowerShell |
[Int][ValidateRange(1,10)]$n = 3 # $n can only accept integers between 1 and 10
|
http://rosettacode.org/wiki/Define_a_primitive_data_type | Define a primitive data type | Demonstrate how to define a type that behaves like an integer but has a lowest valid value of 1 and a highest valid value of 10. Include all bounds checking you need to write, or explain how the compiler or interpreter creates those bounds checks for you.
| #PureBasic | PureBasic | If OpenConsole()
Structure Persona
nombre.s{15}
apellido.s{30}
edad.w
List amigos$()
EndStructure
Dim MyFriends.Persona(100)
; Aquí la posición '1' del array MyFriends()
; contendrá una persona y su propia información
MyFriends(1)\nombre = "Carlos"
MyFriends(1)\apellido = "Gzlez."
MyFriends(1)\edad = 47
individuo.Persona
individuo\nombre = "Juan"
individuo\apellido = "Hdez."
individuo\edad = 49
; Ahora, agrega algunos amigos
AddElement(individuo\amigos$())
individuo\amigos$() = "Lucia"
AddElement(individuo\amigos$())
individuo\amigos$() = "Isabel"
ForEach individuo\amigos$()
Debug individuo\amigos$()
Next
;Estructura extendida
Structure Domicilio Extends Persona
calle.s
numero.b
EndStructure
MyFriends.Domicilio\calle = "Grillo"
MyFriends.Domicilio\numero = 20
PrintN(individuo\nombre + " " + individuo\apellido + " " + Str(individuo\edad) + " " + Str(MyFriends.Domicilio\numero))
PrintN(MyFriends(1)\nombre + " " + MyFriends(1)\apellido + " " + Str(MyFriends(1)\edad))
If TypeOf(Persona\edad) = #PB_Word
Debug "Edad ess un 'Word'"
EndIf
superficie.f
If TypeOf(superficie) = #PB_Float
Debug "superficie es un 'Float'"
EndIf
Print(#CRLF$ + #CRLF$ + "--- terminado, pulsa RETURN---"): Input()
CloseConsole()
EndIf |
http://rosettacode.org/wiki/Death_Star | Death Star |
Task
Display a region that consists of a large sphere with part of a smaller sphere removed from it as a result of geometric subtraction.
(This will basically produce a shape like a "death star".)
Related tasks
draw a sphere
draw a cuboid
draw a rotating cube
write language name in 3D ASCII
| #Wren | Wren | import "dome" for Window
import "graphics" for Canvas, Color, ImageData
import "math" for Vector
var Normalize = Fn.new{ |vec|
var invLen = 1 / vec.dot(vec).sqrt
vec.x = vec.x * invLen
vec.y = vec.y * invLen
vec.z = vec.z * invLen
}
class Sphere {
construct new(cx, cy, cz, r) {
_cx = cx
_cy = cy
_cz = cz
_r = r
}
cx { _cx }
cy { _cy }
cz { _cz }
r { _r }
hit(x, y) {
x = x - _cx
y = y - _cy
var zsq = _r*_r - x*x - y*y
if (zsq >= 0) {
var zsqrt = zsq.sqrt
return [_cz - zsqrt, _cz + zsqrt, true]
}
return [0, 0, false]
}
}
class DeathStar {
construct new(width, height) {
Window.title = "Death star"
Window.resize(width, height)
Canvas.resize(width, height)
}
init() {
Canvas.cls(Color.white)
var dir = Vector.new(20, -40, 10)
Normalize.call(dir)
var pos = Sphere.new(220, 190, 220, 120)
var neg = Sphere.new(130, 100, 190, 100)
deathStar(pos, neg, 1.5, 0.2, dir)
}
deathStar(pos, neg, k, amb, dir) {
var w = pos.r * 4
var h = pos.r * 3
var img = ImageData.create("deathStar", w, h)
var vec = Vector.new(0, 0, 0)
for (y in pos.cy - pos.r..pos.cy + pos.r) {
for (x in pos.cx - pos.r..pos.cx + pos.r) {
var res = pos.hit(x, y)
var zb1 = res[0]
var zb2 = res[1]
var hit = res[2]
if (!hit) continue
res = neg.hit(x, y)
var zs1 = res[0]
var zs2 = res[1]
hit = res[2]
if (hit) {
if (zs1 > zb1) {
hit = false
} else if (zs2 > zb2) {
continue
}
}
if (hit) {
vec.x = neg.cx - x
vec.y = neg.cy - y
vec.z = neg.cz - zs2
} else {
vec.x = x - pos.cx
vec.y = y - pos.cy
vec.z = zb1 - pos.cz
}
Normalize.call(vec)
var s = dir.dot(vec)
if (s < 0) s = 0
var lum = 255 * (s.pow(k) + amb) / (1 + amb)
lum = lum.clamp(0, 255)
img.pset(x, y, Color.rgb(lum, lum, lum))
}
}
img.draw(pos.cx - w/2, pos.cy - h/2)
img.saveToFile("deathStar.png")
}
update() {
}
draw(alpha) {
}
}
var Game = DeathStar.new(400, 400) |
http://rosettacode.org/wiki/Day_of_the_week | Day of the week | A company decides that whenever Xmas falls on a Sunday they will give their workers all extra paid holidays so that, together with any public holidays, workers will not have to work the following week (between the 25th of December and the first of January).
Task
In what years between 2008 and 2121 will the 25th of December be a Sunday?
Using any standard date handling libraries of your programming language;
compare the dates calculated with the output of other languages to discover any anomalies in the handling of dates which may be due to, for example, overflow in types used to represent dates/times similar to y2k type problems.
| #AWK | AWK |
# syntax: GAWK -f DAY_OF_THE_WEEK.AWK
# runtime does not support years > 2037 on my 32-bit Windows XP O/S
BEGIN {
for (i=2008; i<=2121; i++) {
x = strftime("%Y/%m/%d %a",mktime(sprintf("%d 12 25 0 0 0",i)))
if (x ~ /Sun/) { print(x) }
}
}
|
http://rosettacode.org/wiki/Date_format | Date format | This task has been clarified. Its programming examples are in need of review to ensure that they still fit the requirements of the task.
Task
Display the current date in the formats of:
2007-11-23 and
Friday, November 23, 2007
| #11l | 11l | print(Time().format(‘YYYY-MM-DD’))
print(Time().strftime(‘%A, %B %e, %Y’)) |
http://rosettacode.org/wiki/Damm_algorithm | Damm algorithm | The Damm algorithm is a checksum algorithm which detects all single digit errors and adjacent transposition errors.
The algorithm is named after H. Michael Damm.
Task
Verify the checksum, stored as last digit of an input.
| #11l | 11l | V matrix = [
[0, 3, 1, 7, 5, 9, 8, 6, 4, 2],
[7, 0, 9, 2, 1, 5, 4, 8, 6, 3],
[4, 2, 0, 6, 8, 7, 1, 3, 5, 9],
[1, 7, 5, 0, 9, 8, 3, 4, 2, 6],
[6, 1, 2, 3, 0, 4, 5, 9, 7, 8],
[3, 6, 7, 4, 2, 0, 9, 5, 8, 1],
[5, 8, 6, 9, 7, 2, 0, 1, 3, 4],
[8, 9, 4, 5, 3, 6, 2, 0, 1, 7],
[9, 4, 3, 8, 6, 1, 7, 2, 0, 5],
[2, 5, 8, 1, 4, 3, 6, 7, 9, 0]
]
F damm(Int num) -> Bool
V row = 0
L(digit) String(num)
row = :matrix[row][Int(digit)]
R row == 0
L(test) [5724, 5727, 112946]
print(test"\t Validates as: "damm(test)) |
http://rosettacode.org/wiki/Cut_a_rectangle | Cut a rectangle | A given rectangle is made from m × n squares. If m and n are not both odd, then it is possible to cut a path through the rectangle along the square edges such that the rectangle splits into two connected pieces with the same shape (after rotating one of the pieces by 180°). All such paths for 2 × 2 and 4 × 3 rectangles are shown below.
Write a program that calculates the number of different ways to cut an m × n rectangle. Optionally, show each of the cuts.
Possibly related task: Maze generation for depth-first search.
| #C.2B.2B | C++ | #include <array>
#include <iostream>
#include <stack>
#include <vector>
const std::array<std::pair<int, int>, 4> DIRS = {
std::make_pair(0, -1),
std::make_pair(-1, 0),
std::make_pair(0, 1),
std::make_pair(1, 0),
};
void printResult(const std::vector<std::vector<int>> &v) {
for (auto &row : v) {
auto it = row.cbegin();
auto end = row.cend();
std::cout << '[';
if (it != end) {
std::cout << *it;
it = std::next(it);
}
while (it != end) {
std::cout << ", " << *it;
it = std::next(it);
}
std::cout << "]\n";
}
}
void cutRectangle(int w, int h) {
if (w % 2 == 1 && h % 2 == 1) {
return;
}
std::vector<std::vector<int>> grid(h, std::vector<int>(w));
std::stack<int> stack;
int half = (w * h) / 2;
long bits = (long)pow(2, half) - 1;
for (; bits > 0; bits -= 2) {
for (int i = 0; i < half; i++) {
int r = i / w;
int c = i % w;
grid[r][c] = (bits & (1 << i)) != 0 ? 1 : 0;
grid[h - r - 1][w - c - 1] = 1 - grid[r][c];
}
stack.push(0);
grid[0][0] = 2;
int count = 1;
while (!stack.empty()) {
int pos = stack.top();
stack.pop();
int r = pos / w;
int c = pos % w;
for (auto dir : DIRS) {
int nextR = r + dir.first;
int nextC = c + dir.second;
if (nextR >= 0 && nextR < h && nextC >= 0 && nextC < w) {
if (grid[nextR][nextC] == 1) {
stack.push(nextR * w + nextC);
grid[nextR][nextC] = 2;
count++;
}
}
}
}
if (count == half) {
printResult(grid);
std::cout << '\n';
}
}
}
int main() {
cutRectangle(2, 2);
cutRectangle(4, 3);
return 0;
} |
http://rosettacode.org/wiki/Cyclops_numbers | Cyclops numbers | A cyclops number is a number with an odd number of digits that has a zero in the center, but nowhere else. They are named so in tribute to the one eyed giants Cyclops from Greek mythology.
Cyclops numbers can be found in any base. This task strictly is looking for cyclops numbers in base 10.
There are many different classifications of cyclops numbers with minor differences in characteristics. In an effort to head off a whole series of tasks with tiny variations, we will cover several variants here.
Task
Find and display here on this page the first 50 cyclops numbers in base 10 (all of the sub tasks are restricted to base 10).
Find and display here on this page the first 50 prime cyclops numbers. (cyclops numbers that are prime.)
Find and display here on this page the first 50 blind prime cyclops numbers. (prime cyclops numbers that remain prime when "blinded"; the zero is removed from the center.)
Find and display here on this page the first 50 palindromic prime cyclops numbers. (prime cyclops numbers that are palindromes.)
Stretch
Find and display the first cyclops number greater than ten million (10,000,000) and the index (place) in the series where it is found.
Find and display the first prime cyclops number greater than ten million (10,000,000) and the index (place) in the series where it is found.
Find and display the first blind prime cyclops number greater than ten million (10,000,000) and the index (place) in the series where it is found.
Find and display the first palindromic prime cyclops number greater than ten million (10,000,000) and the index (place) in the series where it is found.
(Note: there are no cyclops numbers between ten million and one hundred million, they need to have an odd number of digits)
See also
OEIS A134808 - Cyclops numbers
OEIS A134809 - Cyclops primes
OEIS A329737 - Cyclops primes that remain prime after being "blinded"
OEIS A136098 - Prime palindromic cyclops numbers
| #jq | jq |
## Generic helper functions
def count(s): reduce s as $x (0; .+1);
# counting from 0
def enumerate(s): foreach s as $x (-1; .+1; [., $x]);
def lpad($len): tostring | ($len - length) as $l | (" " * $l)[:$l] + .;
## Prime numbers
def is_prime:
if . == 2 then true
else
2 < . and . % 2 == 1 and
(. as $in
| (($in + 1) | sqrt) as $m
| [false, 3] | until( .[0] or .[1] > $m; [$in % .[1] == 0, .[1] + 2])
| .[0]
| not)
end ;
## Cyclops numbers
def iscyclops:
(tostring | explode) as $d
| ($d|length) as $l
| (($l + 1) / 2 - 1) as $m
| ($l % 2 == 1) and $d[$m] == 48 and count($d[] | select(.== 48)) == 1 # "0"
;
# Generate a stream of cyclops numbers, in increasing numeric order, from 0
def cyclops:
# generate a stream of cyclops numbers with $n digits on each side of the central 0
def w:
if . == 0 then ""
else (.-1)|w as $left
| $left + (range(1;10)|tostring)
end;
def c: w as $left | $left + "0" + w;
range(0; infinite) | c | tonumber;
# Generate a stream of palindromic cyclops numbers, in increasing numeric order, from 0
def palindromiccyclops:
def r: explode|reverse|implode;
def c: . as $n
| if $n == 0 then "0"
elif $n == 1
then (range(1;10)|tostring) as $base
| $base + "0" + ($base | r)
else (range(pow(10;$n-1); pow(10; $n))|tostring|select(test("0")|not)) as $base
| $base + "0" + ($base | r)
end;
range(0; infinite) | c | tonumber;
# check that a cyclops number minus the 0 is prime
def cyclops_isblind:
(tostring | explode) as $d
| ($d|length) as $l
| (($l + 1) / 2 - 1) as $m
| ((( $d[:$m] + $d[$m+1:] ) | implode | tonumber) | is_prime);
# check that a cyclops number is a palindrome
def cyclops_ispalindromic:
. as $in
| (tostring | explode) as $d
| ($d|length) as $l
| (($l + 1) / 2 - 1) as $m
| $d[:$m] == ( $d[$m+1:] | reverse) ;
|
http://rosettacode.org/wiki/Cyclops_numbers | Cyclops numbers | A cyclops number is a number with an odd number of digits that has a zero in the center, but nowhere else. They are named so in tribute to the one eyed giants Cyclops from Greek mythology.
Cyclops numbers can be found in any base. This task strictly is looking for cyclops numbers in base 10.
There are many different classifications of cyclops numbers with minor differences in characteristics. In an effort to head off a whole series of tasks with tiny variations, we will cover several variants here.
Task
Find and display here on this page the first 50 cyclops numbers in base 10 (all of the sub tasks are restricted to base 10).
Find and display here on this page the first 50 prime cyclops numbers. (cyclops numbers that are prime.)
Find and display here on this page the first 50 blind prime cyclops numbers. (prime cyclops numbers that remain prime when "blinded"; the zero is removed from the center.)
Find and display here on this page the first 50 palindromic prime cyclops numbers. (prime cyclops numbers that are palindromes.)
Stretch
Find and display the first cyclops number greater than ten million (10,000,000) and the index (place) in the series where it is found.
Find and display the first prime cyclops number greater than ten million (10,000,000) and the index (place) in the series where it is found.
Find and display the first blind prime cyclops number greater than ten million (10,000,000) and the index (place) in the series where it is found.
Find and display the first palindromic prime cyclops number greater than ten million (10,000,000) and the index (place) in the series where it is found.
(Note: there are no cyclops numbers between ten million and one hundred million, they need to have an odd number of digits)
See also
OEIS A134808 - Cyclops numbers
OEIS A134809 - Cyclops primes
OEIS A329737 - Cyclops primes that remain prime after being "blinded"
OEIS A136098 - Prime palindromic cyclops numbers
| #Julia | Julia |
print5x10(a, w = 8) = for i in 0:4, j in 1:10 print(lpad(a[10i + j], w), j == 10 ? "\n" : "") end
function iscyclops(n)
d = digits(n)
l = length(d)
return isodd(l) && d[l ÷ 2 + 1] == 0 && count(x -> x == 0, d) == 1
end
function isblindprimecyclops(n)
d = digits(n)
l = length(d)
m = l ÷ 2 + 1
(n == 0 || iseven(l) || d[m] != 0 || count(x -> x == 0, d) != 1) && return false
return isprime(evalpoly(10, [d[1:m-1]; d[m+1:end]]))
end
function ispalindromicprimecyclops(n)
d = digits(n)
l = length(d)
return n > 0 && isodd(l) && d[l ÷ 2 + 1] == 0 && count(x -> x == 0, d) == 1 && d == reverse(d)
end
function findcyclops(N, iscycs, nextcandidate)
i, list = nextcandidate(-1), Int[]
while length(list) < N
iscycs(i) && push!(list, i)
i = nextcandidate(i)
end
return list
end
function nthcyclopsfirstafter(lowerlimit, iscycs, nextcandidate)
i, found = 0, 0
while true
if iscycs(i)
found += 1
i >= lowerlimit && break
end
i = nextcandidate(i)
end
return i, found
end
function testcyclops()
println("The first 50 cyclops numbers are:")
print5x10(findcyclops(50, iscyclops, x -> x + 1))
n, c = nthcyclopsfirstafter(10000000, iscyclops, x -> x + 1)
println("\nThe next cyclops number after 10,000,000 is $n at position $c.")
println("\nThe first 50 prime cyclops numbers are:")
print5x10(findcyclops(50, iscyclops, x -> nextprime(x + 1)))
n, c = nthcyclopsfirstafter(10000000, iscyclops, x -> nextprime(x + 1))
println("\nThe next prime cyclops number after 10,000,000 is $n at position $c.")
println("\nThe first 50 blind prime cyclops numbers are:")
print5x10(findcyclops(50, isblindprimecyclops, x -> nextprime(x + 1)))
n, c = nthcyclopsfirstafter(10000000, isblindprimecyclops, x -> nextprime(x + 1))
println("\nThe next prime cyclops number after 10,000,000 is $n at position $c.")
println("\nThe first 50 palindromic prime cyclops numbers are:")
print5x10(findcyclops(50, ispalindromicprimecyclops, x -> nextprime(x + 1)))
n, c = nthcyclopsfirstafter(10000000, ispalindromicprimecyclops, x -> nextprime(x + 1))
println("\nThe next prime cyclops number after 10,000,000 is $n at position $c.")
end
testcyclops()
|
http://rosettacode.org/wiki/Date_manipulation | Date manipulation | Task
Given the date string "March 7 2009 7:30pm EST",
output the time 12 hours later in any human-readable format.
As extra credit, display the resulting time in a time zone different from your own.
| #AutoHotkey | AutoHotkey | DateString := "March 7 2009 7:30pm EST"
; split the given string with RegExMatch
Needle := "^(?P<mm>\S*) (?P<d>\S*) (?P<y>\S*) (?P<t>\S*) (?P<tz>\S*)$"
RegExMatch(DateString, Needle, $)
; split the time with RegExMatch
Needle := "^(?P<h>\d+):(?P<min>\d+)(?P<xm>[amp]+)$"
RegExMatch($t, Needle, $)
; convert am/pm to 24h format
$h += ($xm = "am") ? 0 : 12
; knitting YYYYMMDDHH24MI format
_YYYY := $y
_MM := Get_MonthNr($mm)
_DD := SubStr("00" $d, -1) ; last 2 chars
_HH24 := SubStr("00" $h, -1) ; last 2 chars
_MI := $min
YYYYMMDDHH24MI := _YYYY _MM _DD _HH24 _MI
; add 12 hours as requested
EnvAdd, YYYYMMDDHH24MI, 12, Hours
FormatTime, HumanReadable, %YYYYMMDDHH24MI%, d/MMM/yyyy HH:mm
; add 5 hours to convert to different timezone (GMT)
EnvAdd, YYYYMMDDHH24MI, 5, Hours
FormatTime, HumanReadable_GMT, %YYYYMMDDHH24MI%, d/MMM/yyyy HH:mm
; output
MsgBox, % "Given: " DateString "`n`n"
. "12 hours later:`n"
. "(" $tz "):`t" HumanReadable "h`n"
. "(GMT):`t" HumanReadable_GMT "h`n"
;---------------------------------------------------------------------------
Get_MonthNr(Month) { ; convert named month to 2-digit number
;---------------------------------------------------------------------------
If (Month = "January")
Result := "01"
Else If (Month = "February")
Result := "02"
Else If (Month = "March")
Result := "03"
Else If (Month = "April")
Result := "04"
Else If (Month = "May")
Result := "05"
Else If (Month = "June")
Result := "06"
Else If (Month = "July")
Result := "07"
Else If (Month = "August")
Result := "08"
Else If (Month = "September")
Result := "09"
Else If (Month = "October")
Result := "10"
Else If (Month = "November")
Result := "11"
Else If (Month = "December")
Result := "12"
Return, Result
} |
http://rosettacode.org/wiki/Deal_cards_for_FreeCell | Deal cards for FreeCell | Free Cell is the solitaire card game that Paul Alfille introduced to the PLATO system in 1978. Jim Horne, at Microsoft, changed the name to FreeCell and reimplemented the game for DOS, then Windows.
This version introduced 32000 numbered deals. (The FreeCell FAQ tells this history.)
As the game became popular, Jim Horne disclosed the algorithm, and other implementations of FreeCell began to reproduce the Microsoft deals.
These deals are numbered from 1 to 32000.
Newer versions from Microsoft have 1 million deals, numbered from 1 to 1000000; some implementations allow numbers outside that range.
The algorithm uses this linear congruential generator from Microsoft C:
s
t
a
t
e
n
+
1
≡
214013
×
s
t
a
t
e
n
+
2531011
(
mod
2
31
)
{\displaystyle state_{n+1}\equiv 214013\times state_{n}+2531011{\pmod {2^{31}}}}
r
a
n
d
n
=
s
t
a
t
e
n
÷
2
16
{\displaystyle rand_{n}=state_{n}\div 2^{16}}
r
a
n
d
n
{\displaystyle rand_{n}}
is in range 0 to 32767.
Rosetta Code has another task, linear congruential generator, with code for this RNG in several languages.
The algorithm follows:
Seed the RNG with the number of the deal.
Create an array of 52 cards: Ace of Clubs, Ace of Diamonds, Ace of Hearts, Ace of Spades, 2 of Clubs, 2 of Diamonds, and so on through the ranks: Ace, 2, 3, 4, 5, 6, 7, 8, 9, 10, Jack, Queen, King. The array indexes are 0 to 51, with Ace of Clubs at 0, and King of Spades at 51.
Until the array is empty:
Choose a random card at index ≡ next random number (mod array length).
Swap this random card with the last card of the array.
Remove this random card from the array. (Array length goes down by 1.)
Deal this random card.
Deal all 52 cards, face up, across 8 columns. The first 8 cards go in 8 columns, the next 8 cards go on the first 8 cards, and so on.
Order to deal cards
Game #1
Game #617
1 2 3 4 5 6 7 8
9 10 11 12 13 14 15 16
17 18 19 20 21 22 23 24
25 26 27 28 29 30 31 32
33 34 35 36 37 38 39 40
41 42 43 44 45 46 47 48
49 50 51 52
JD 2D 9H JC 5D 7H 7C 5H
KD KC 9S 5S AD QC KH 3H
2S KS 9D QD JS AS AH 3C
4C 5C TS QH 4H AC 4D 7S
3S TD 4S TH 8H 2C JH 7D
6D 8S 8D QS 6C 3D 8C TC
6S 9C 2H 6H
7D AD 5C 3S 5S 8C 2D AH
TD 7S QD AC 6D 8H AS KH
TH QC 3H 9D 6S 8D 3D TC
KD 5H 9S 3C 8S 7H 4D JS
4C QS 9C 9H 7C 6H 2C 2S
4S TS 2H 5D JC 6C JH QH
JD KS KC 4H
Deals can also be checked against FreeCell solutions to 1000000 games.
(Summon a video solution, and it displays the initial deal.)
Write a program to take a deal number and deal cards in the same order as this algorithm.
The program may display the cards with ASCII, with Unicode, by drawing graphics, or any other way.
Related tasks:
Playing cards
Card shuffles
War Card_Game
Poker hand_analyser
Go Fish
| #Julia | Julia | const rank = split("A23456789TJQK", "")
const suit = split("♣♦♥♠", "")
const deck = Vector{String}()
const mslcg = [0]
rng() = (mslcg[1] = ((mslcg[1] * 214013 + 2531011) & 0x7fffffff)) >> 16
initdeck() = for r in rank, s in suit push!(deck, "$r$s") end
function deal(num = rand(UInt,1)[1] % 32000 + 1)
initdeck()
mslcg[1] = num
println("\nGame # ", num)
while length(deck) > 0
choice = rng() % length(deck) + 1
deck[choice], deck[end] = deck[end], deck[choice]
print(" ", pop!(deck), length(deck) % 8 == 4 ? "\n" : "")
end
end
deal(1)
deal(617)
deal()
|
http://rosettacode.org/wiki/Deal_cards_for_FreeCell | Deal cards for FreeCell | Free Cell is the solitaire card game that Paul Alfille introduced to the PLATO system in 1978. Jim Horne, at Microsoft, changed the name to FreeCell and reimplemented the game for DOS, then Windows.
This version introduced 32000 numbered deals. (The FreeCell FAQ tells this history.)
As the game became popular, Jim Horne disclosed the algorithm, and other implementations of FreeCell began to reproduce the Microsoft deals.
These deals are numbered from 1 to 32000.
Newer versions from Microsoft have 1 million deals, numbered from 1 to 1000000; some implementations allow numbers outside that range.
The algorithm uses this linear congruential generator from Microsoft C:
s
t
a
t
e
n
+
1
≡
214013
×
s
t
a
t
e
n
+
2531011
(
mod
2
31
)
{\displaystyle state_{n+1}\equiv 214013\times state_{n}+2531011{\pmod {2^{31}}}}
r
a
n
d
n
=
s
t
a
t
e
n
÷
2
16
{\displaystyle rand_{n}=state_{n}\div 2^{16}}
r
a
n
d
n
{\displaystyle rand_{n}}
is in range 0 to 32767.
Rosetta Code has another task, linear congruential generator, with code for this RNG in several languages.
The algorithm follows:
Seed the RNG with the number of the deal.
Create an array of 52 cards: Ace of Clubs, Ace of Diamonds, Ace of Hearts, Ace of Spades, 2 of Clubs, 2 of Diamonds, and so on through the ranks: Ace, 2, 3, 4, 5, 6, 7, 8, 9, 10, Jack, Queen, King. The array indexes are 0 to 51, with Ace of Clubs at 0, and King of Spades at 51.
Until the array is empty:
Choose a random card at index ≡ next random number (mod array length).
Swap this random card with the last card of the array.
Remove this random card from the array. (Array length goes down by 1.)
Deal this random card.
Deal all 52 cards, face up, across 8 columns. The first 8 cards go in 8 columns, the next 8 cards go on the first 8 cards, and so on.
Order to deal cards
Game #1
Game #617
1 2 3 4 5 6 7 8
9 10 11 12 13 14 15 16
17 18 19 20 21 22 23 24
25 26 27 28 29 30 31 32
33 34 35 36 37 38 39 40
41 42 43 44 45 46 47 48
49 50 51 52
JD 2D 9H JC 5D 7H 7C 5H
KD KC 9S 5S AD QC KH 3H
2S KS 9D QD JS AS AH 3C
4C 5C TS QH 4H AC 4D 7S
3S TD 4S TH 8H 2C JH 7D
6D 8S 8D QS 6C 3D 8C TC
6S 9C 2H 6H
7D AD 5C 3S 5S 8C 2D AH
TD 7S QD AC 6D 8H AS KH
TH QC 3H 9D 6S 8D 3D TC
KD 5H 9S 3C 8S 7H 4D JS
4C QS 9C 9H 7C 6H 2C 2S
4S TS 2H 5D JC 6C JH QH
JD KS KC 4H
Deals can also be checked against FreeCell solutions to 1000000 games.
(Summon a video solution, and it displays the initial deal.)
Write a program to take a deal number and deal cards in the same order as this algorithm.
The program may display the cards with ASCII, with Unicode, by drawing graphics, or any other way.
Related tasks:
Playing cards
Card shuffles
War Card_Game
Poker hand_analyser
Go Fish
| #Kotlin | Kotlin | // version 1.1.3
class Lcg(val a: Long, val c: Long, val m: Long, val d: Long, val s: Long) {
private var state = s
fun nextInt(): Long {
state = (a * state + c) % m
return state / d
}
}
const val CARDS = "A23456789TJQK"
const val SUITS = "♣♦♥♠"
fun deal(): Array<String?> {
val cards = arrayOfNulls<String>(52)
for (i in 0 until 52) {
val card = CARDS[i / 4]
val suit = SUITS[i % 4]
cards[i] = "$card$suit"
}
return cards
}
fun game(n: Int) {
require(n > 0)
println("Game #$n:")
val msc = Lcg(214013, 2531011, 1 shl 31, 1 shl 16, n.toLong())
val cards = deal()
for (m in 52 downTo 1) {
val index = (msc.nextInt() % m).toInt()
val temp = cards[index]
cards[index] = cards[m - 1]
print("$temp ")
if ((53 - m) % 8 == 0) println()
}
println("\n")
}
fun main(args: Array<String>) {
game(1)
game(617)
} |
http://rosettacode.org/wiki/Define_a_primitive_data_type | Define a primitive data type | Demonstrate how to define a type that behaves like an integer but has a lowest valid value of 1 and a highest valid value of 10. Include all bounds checking you need to write, or explain how the compiler or interpreter creates those bounds checks for you.
| #Python | Python | >>> class num(int):
def __init__(self, b):
if 1 <= b <= 10:
return int.__init__(self+0)
else:
raise ValueError,"Value %s should be >=0 and <= 10" % b
>>> x = num(3)
>>> x = num(11)
Traceback (most recent call last):
File "<pyshell#394>", line 1, in <module>
x = num(11)
File "<pyshell#392>", line 6, in __init__
raise ValueError,"Value %s should be >=0 and <= 10" % b
ValueError: Value 11 should be >=0 and <= 10
>>> x
3
>>> type(x)
<class '__main__.num'>
>>> |
http://rosettacode.org/wiki/Death_Star | Death Star |
Task
Display a region that consists of a large sphere with part of a smaller sphere removed from it as a result of geometric subtraction.
(This will basically produce a shape like a "death star".)
Related tasks
draw a sphere
draw a cuboid
draw a rotating cube
write language name in 3D ASCII
| #Yabasic | Yabasic | open window 100,100
window origin "cc"
backcolor 0,0,0
clear window
tonos = 100
interv = int(255 / tonos)
dim shades(tonos)
shades(1) = 255
for i = 2 to tonos
shades(i) = shades(i-1) - interv
next i
dim light(3)
light(0) = 30
light(1) = 30
light(2) = -50
sub normalize(v())
local long
long = sqrt(v(0)*v(0) + v(1)*v(1) + v(2)*v(2))
v(0) = v(0) / long
v(1) = v(1) / long
v(2) = v(2) / long
end sub
sub punto(x(), y())
local d
d = x(0)*y(0) + x(1)*y(1) + x(2)*y(2)
if d < 0 then
return -d
else
return 0
end if
end sub
//* positive shpere and negative sphere */
dim pos(3)
dim neg(3)
// x, y, z, r
pos(0) = 10
pos(1) = 10
pos(2) = 0
pos(3) = 20
neg(0) = 0
neg(1) = 0
neg(2) = -5
neg(3) = 15
sub hit_sphere(sph(), x, y)
local zsq
x = x - sph(0)
y = y - sph(1)
zsq = sph(3) * sph(3) - (x * x + y * y)
if (zsq < 0) then
return 0
else
return sqrt(zsq)
end if
end sub
sub draw_sphere(k, ambient)
local i, j, intensity, hit_result, result, b, vec(3), x, y, zb1, zb2, zs1, zs2, ini1, fin1, ini2, fin2
ini1 = int(pos(1) - pos(3))
fin1 = int(pos(1) + pos(3) + .5)
for i = ini1 to fin1
y = i + .5
ini2 = int(pos(0) - 2 * pos(3))
fin2 = int(pos(0) + 2 * pos(3) + .5)
for j = ini2 to fin2
x = (j - pos(0)) / 2 + .5 + pos(0)
// ray lands in blank space, draw bg
result = hit_sphere(pos(), x, y)
if not result then
hit_result = 0
//* ray hits pos sphere but not neg, draw pos sphere surface */
else
zb1 = pos(2) - result
zb2 = pos(2) + result
result = hit_sphere(neg(), x, y)
if not result then
hit_result = 1
else
zs1 = neg(2) - result
zs2 = neg(2) + result
if (zs1 > zb1) then
hit_result = 1
elseif (zs2 > zb2) then
hit_result = 0
elseif (zs2 > zb1) then
hit_result = 2
else
hit_result = 1
end if
end if
end if
if not hit_result then
color 0,0,0
dot x, y
else
switch(hit_result)
case 1:
vec(0) = x - pos(0)
vec(1) = y - pos(1)
vec(2) = zb1 - pos(2)
break
default:
vec(0) = neg(0) - x
vec(1) = neg(1) - y
vec(2) = neg(2) - zs2
end switch
normalize(vec())
b = (punto(light(), vec())^k) + ambient
intensity = (1 - b) * tonos
if (intensity < 1) intensity = 1
if (intensity > tonos) intensity = tonos
color shades(intensity),shades(intensity),shades(intensity)
dot x,y
end if
next j
next i
end sub
ang = 0
while(true)
//clear window
light(1) = cos(ang * 2)
light(2) = cos(ang)
light(0) = sin(ang)
normalize(light())
ang = ang + .05
draw_sphere(2, .3)
wend
|
http://rosettacode.org/wiki/Day_of_the_week | Day of the week | A company decides that whenever Xmas falls on a Sunday they will give their workers all extra paid holidays so that, together with any public holidays, workers will not have to work the following week (between the 25th of December and the first of January).
Task
In what years between 2008 and 2121 will the 25th of December be a Sunday?
Using any standard date handling libraries of your programming language;
compare the dates calculated with the output of other languages to discover any anomalies in the handling of dates which may be due to, for example, overflow in types used to represent dates/times similar to y2k type problems.
| #BASIC | BASIC | Declare Function modulo(x As Double, y As Double) As Double
Declare Function wd(m As Double, d As Double, y As Double) As Integer
Cls
Dim yr As Double
For yr = 2008 To 2121
If wd(12,25,yr) = 1 Then
Print "Dec " & 25 & ", " & yr
EndIf
Next
Sleep
Function modulo(x As Double, y As Double) As Double
If y = 0 Then
Return x
Else
Return x - y * Int(x / y)
End If
End Function
Function wd(m As Double, d As Double, y As Double) As Integer
If m = 1 Or m = 2 Then
m += 12
y-= 1
End If
Return modulo(365 * y + Fix(y / 4) - Fix(y / 100) + Fix(y / 400) + d + Fix((153 * m + 8) / 5), 7) + 1
End Function
Dec 25, 2011
Dec 25, 2016
Dec 25, 2022
Dec 25, 2033
Dec 25, 2039
Dec 25, 2044
Dec 25, 2050
Dec 25, 2061
Dec 25, 2067
Dec 25, 2072
Dec 25, 2078
Dec 25, 2089
Dec 25, 2095
Dec 25, 2101
Dec 25, 2107
Dec 25, 2112
Dec 25, 2118 |
http://rosettacode.org/wiki/Day_of_the_week | Day of the week | A company decides that whenever Xmas falls on a Sunday they will give their workers all extra paid holidays so that, together with any public holidays, workers will not have to work the following week (between the 25th of December and the first of January).
Task
In what years between 2008 and 2121 will the 25th of December be a Sunday?
Using any standard date handling libraries of your programming language;
compare the dates calculated with the output of other languages to discover any anomalies in the handling of dates which may be due to, for example, overflow in types used to represent dates/times similar to y2k type problems.
| #Batch_File | Batch File | :: Day of the Week task from Rosetta Code
:: Batch File Implementation
:: Question: In what years between 2008 and 2121 will the 25th of December be a Sunday?
:: Method: Zeller's Rule
@echo off
rem set month code for December
set mon=33
rem set day number
set day=25
for /L %%y in (2008,1,2121) do (
setlocal enabledelayedexpansion
set /a "a=%%y/100"
set /a "b=%%y-(a*100)"
set /a "weekday=(day+mon+b+(b/4)+(a/4)+(5*a))%%7"
if "!weekday!"=="1" echo(Dec 25, %%y is a Sunday.
endlocal
)
pause
exit /b 0 |
http://rosettacode.org/wiki/Date_format | Date format | This task has been clarified. Its programming examples are in need of review to ensure that they still fit the requirements of the task.
Task
Display the current date in the formats of:
2007-11-23 and
Friday, November 23, 2007
| #68000_Assembly | 68000 Assembly | JSR SYS_READ_CALENDAR ;outputs calendar date to BIOS RAM
MOVE.B #'2',D0 ;a character in single or double quotes refers to its ascii equivalent.
JSR PrintChar
MOVE.B #'0',D0
JSR PrintChar
LEA BIOS_YEAR,A1
MOVE.B (A1)+,D0 ;stores last 2 digits of year into D0, in binary coded decimal
JSR UnpackNibbles8 ;separate the digits into high and low nibbles: D0 = 00020001
ADD.L #$00300030,D0 ;convert both numerals to their ascii equivalents.
SWAP D0 ;print the "2" first
JSR PrintChar
SWAP D0 ;then the "1"
JSR PrintChar
MOVE.B #'-',D0
JSR PrintChar
MOVE.B (A1)+,D0 ;get the month
JSR UnpackNibbles8
ADD.L #$00300030,D0
SWAP D0
JSR PrintChar
SWAP D0
JSR PrintChar
MOVE.B #'-',D0
JSR PrintChar
MOVE.B (A1)+,D0 ;get the day
JSR UnpackNibbles8
ADD.L #$00300030,D0
SWAP D0
JSR PrintChar
SWAP D0
JSR PrintChar
;now the date is printed.
;Now do it again only written out:
jsr NewLine
CLR.L D0 ;reset D0
MOVE.B (A1),D0 ;A1 happens to point to the weekday
LSL.W #2,D0 ;we are indexing into a table of longs
LEA Days_Lookup,A2
LEA (A2,D0),A2
MOVEA.L (A2),A3 ;dereference the pointer into A3, which the PrintString routine takes as an argument.
JSR PrintString
CLR.L D0
LEA BIOS_MONTH,A1 ;GET THE MONTH
MOVE.B (A1)+,D0
LSL.W #2,D0
LEA Months_Lookup,A2
LEA (A2,D0),A2
MOVEA.L (A2),A3
JSR PrintString
MOVE.B (A1),D0 ;GET THE DAY
JSR UnpackNibbles8
ADD.L #$00300030,D0
SWAP D0
JSR PrintChar
SWAP D0
JSR PrintChar
MOVE.B #',',D0
JSR PrintChar
MOVE.B #' ',D0
JSR PrintChar
MOVE.B #'2',D0
JSR PrintChar
MOVE.B #'0',D0
JSR PrintChar
LEA BIOS_YEAR,A1
MOVE.B (A1)+,D0 ;stores last 2 digits of year into D0, in binary coded decimal
JSR UnpackNibbles8 ;separate the digits into high and low nibbles: D0 = 00020001
ADD.L #$00300030,D0 ;convert both numerals to their ascii equivalents.
SWAP D0 ;print the "2" first
JSR PrintChar
SWAP D0 ;then the "1"
JSR PrintChar
forever:
bra forever ;trap the program counter
UnpackNibbles8:
; INPUT: D0 = THE VALUE YOU WISH TO UNPACK.
; HIGH NIBBLE IN HIGH WORD OF D0, LOW NIBBLE IN LOW WORD. SWAP D0 TO GET THE OTHER HALF.
pushWord D1
CLR.W D1
MOVE.B D0,D1
CLR.L D0
MOVE.B D1,D0 ;now D0 = D1 = $000000II, where I = input
AND.B #$F0,D0 ;chop off bottom nibble
LSR.B #4,D0 ;downshift top nibble into bottom nibble of the word
SWAP D0 ;store in high word
AND.B #$0F,D1 ;chop off bottom nibble
MOVE.B D1,D0 ;store in low word
popWord D1
rts |
http://rosettacode.org/wiki/Damm_algorithm | Damm algorithm | The Damm algorithm is a checksum algorithm which detects all single digit errors and adjacent transposition errors.
The algorithm is named after H. Michael Damm.
Task
Verify the checksum, stored as last digit of an input.
| #8080_Assembly | 8080 Assembly | org 100h
jmp demo
;;; Given an 0-terminated ASCII string containing digits in [DE],
;;; see if it matches its check digit. Returns with zero flag set
;;; if the string matches.
damm: mvi c,0 ; Interim digit in C, starts off at 0.
ldax d ; Get current byte from string
inx d ; Advance the pointer
ana a ; Is the byte zero?
jnz $+5 ; If not, go look up interim digit
cmp c ; But if so, see if the interim digit is also zero
ret ; And return whether this was the case
sui '0' ; Subtract ASCII 0
mov b,a ; Keep digit to be processed in B
mov a,c ; Calculate C*10 (interim digit row index)
add a ; * 2
add a ; * 4
add c ; * 5
add a ; * 10
add b ; Add column index
lxi h,dammit
add l ; Table lookup (assuming H doesn't change, i.e. it
mov l,a ; doesn't cross a page boundary).
mov c,m ; Get new interim digit from table
jmp damm+2 ; And check next character
;;; Table of interim digits
;;; NOTE: must not cross page boundary
dammit: db 0,3,1,7,5,9,8,6,4,2
db 7,0,9,2,1,5,4,8,6,3
db 4,2,0,6,8,7,1,3,5,9
db 1,7,5,0,9,8,3,4,2,6
db 6,1,2,3,0,4,5,9,7,8
db 3,6,7,4,2,0,9,5,8,1
db 5,8,6,9,7,2,0,1,3,4
db 8,9,4,5,3,6,2,0,1,7
db 9,4,3,8,6,1,7,2,0,5
db 2,5,8,1,4,3,6,7,9,0
;;; Demo code: see if the argument on the CP/M command line
;;; matches its input.
demo: lxi h,80h ; Zero-terminate input
mov e,m
mvi d,0
inx d
dad d
mov m,d
lxi d,82h ; Command line argument, skipping first space
call damm ; See if it validates
mvi c,9
lxi d,ok ; Print OK...
jz 5 ; ...if the checksum matches,
lxi d,no ; Print NOT OK otherwise.
jmp 5
no: db 'NOT '
ok: db 'OK$' |
http://rosettacode.org/wiki/Damm_algorithm | Damm algorithm | The Damm algorithm is a checksum algorithm which detects all single digit errors and adjacent transposition errors.
The algorithm is named after H. Michael Damm.
Task
Verify the checksum, stored as last digit of an input.
| #8086_Assembly | 8086 Assembly | cpu 8086
bits 16
section .text
org 100h
jmp demo
;;; Given a 0-terminated ASCII string containing digits in
;;; [DS:SI], see if the check digit matches. Returns with zero flag
;;; set if it matches.
damm: xor cl,cl ; Interim digit starts out at 0
mov bx,.tab ; Index for table lookup
.dgt: lodsb ; Get next string byte
test al,al ; If it is zero, we're done
jz .out
sub al,'0' ; Make ASCII digit
mov ah,cl ; Table lookup, AH = interim digit
aad ; AL += AH * 10 (such handy instructions the 8086 has)
cs xlatb ; AL = CS:table[AL]
mov cl,al ; CL = new interim digit
jmp .dgt ; Get next string
.out: test cl,cl ; Interim digit should be zero at the end
ret
.tab: db 0,3,1,7,5,9,8,6,4,2 ; Table can be stored as part of the
db 7,0,9,2,1,5,4,8,6,3 ; code
db 4,2,0,6,8,7,1,3,5,9
db 1,7,5,0,9,8,3,4,2,6
db 6,1,2,3,0,4,5,9,7,8
db 3,6,7,4,2,0,9,5,8,1
db 5,8,6,9,7,2,0,1,3,4
db 8,9,4,5,3,6,2,0,1,7
db 9,4,3,8,6,1,7,2,0,5
db 2,5,8,1,4,3,6,7,9,0
;;; Demo: see if the argument on the MS-DOS command line is valid
demo: xor bh,bh ; Zero-terminate the input
mov bl,[80h]
mov [bx+81h],bh
mov si,82h ; Start of input skipping first space
call damm ; Is it valid?
mov dx,ok ; If so, print OK
jz .print
mov dx,no ; Otherwise, print NOT OK
.print: mov ah,9
int 21h
ret
section .data
no: db 'NOT '
ok: db 'OK$' |
http://rosettacode.org/wiki/Curzon_numbers | Curzon numbers | A Curzon number is defined to be a positive integer n for which 2n + 1 is evenly divisible by 2 × n + 1.
Generalized Curzon numbers are those where the positive integer n, using a base integer k, satisfy the condition that kn + 1 is evenly divisible by k × n + 1.
Base here does not imply the radix of the counting system; rather the integer the equation is based on. All calculations should be done in base 10.
Generalized Curzon numbers only exist for even base integers.
Task
Find and show the first 50 Generalized Curzon numbers for even base integers from 2 through 10.
Stretch
Find and show the one thousandth.
See also
Numbers Aplenty - Curzon numbers
OEIS:A224486 - Numbers k such that 2*k+1 divides 2^k+1 (Curzon numbers)
and even though it is not specifically mentioned that they are Curzon numbers:
OEIS:A230076 - (A007521(n)-1)/4 (Generalized Curzon numbers with a base 4)
| #Arturo | Arturo | curzon?: function [n,base]->
zero? (inc base^n) % inc base*n
first50: function [b][
result: new []
i: 1
while [50 > size result][
if curzon? i b -> 'result ++ i
i: i + 1
]
return result
]
oneThousandth: function [b][
cnt: 0
i: 1
while [cnt < 1000][
if curzon? i b -> cnt: cnt+1
i: i + 1
]
return dec i
]
loop select 2..10 => even? 'withBase [
print ["First 50 Curzon numbers with base" withBase]
loop split.every: 10 first50 withBase 'row [
print map to [:string] row 'item -> pad item 4
]
print ["\n1000th Curzon with base" withBase "=" oneThousandth withBase]
print ""
] |
http://rosettacode.org/wiki/Cut_a_rectangle | Cut a rectangle | A given rectangle is made from m × n squares. If m and n are not both odd, then it is possible to cut a path through the rectangle along the square edges such that the rectangle splits into two connected pieces with the same shape (after rotating one of the pieces by 180°). All such paths for 2 × 2 and 4 × 3 rectangles are shown below.
Write a program that calculates the number of different ways to cut an m × n rectangle. Optionally, show each of the cuts.
Possibly related task: Maze generation for depth-first search.
| #Common_Lisp | Common Lisp | (defun cut-it (w h &optional (recur t))
(if (oddp (* w h)) (return-from cut-it 0))
(if (oddp h) (rotatef w h))
(if (= w 1) (return-from cut-it 1))
(let ((cnt 0)
(m (make-array (list (1+ h) (1+ w))
:element-type 'bit
:initial-element 0))
(cy (truncate h 2))
(cx (truncate w 2)))
(setf (aref m cy cx) 1)
(if (oddp w) (setf (aref m cy (1+ cx)) 1))
(labels
((walk (y x turned)
(when (or (= y 0) (= y h) (= x 0) (= x w))
(incf cnt (if turned 2 1))
(return-from walk))
(setf (aref m y x) 1)
(setf (aref m (- h y) (- w x)) 1)
(loop for i from 0
for (dy dx) in '((0 -1) (-1 0) (0 1) (1 0))
while (or turned (< i 2)) do
(let ((y2 (+ y dy))
(x2 (+ x dx)))
(when (zerop (aref m y2 x2))
(walk y2 x2 (or turned (> i 0))))))
(setf (aref m (- h y) (- w x)) 0)
(setf (aref m y x) 0)))
(walk cy (1- cx) nil)
(cond ((= h w) (incf cnt cnt))
((oddp w) (walk (1- cy) cx t))
(recur (incf cnt (cut-it h w nil))))
cnt)))
(loop for w from 1 to 9 do
(loop for h from 1 to w do
(if (evenp (* w h))
(format t "~d x ~d: ~d~%" w h (cut-it w h))))) |
http://rosettacode.org/wiki/Cyclops_numbers | Cyclops numbers | A cyclops number is a number with an odd number of digits that has a zero in the center, but nowhere else. They are named so in tribute to the one eyed giants Cyclops from Greek mythology.
Cyclops numbers can be found in any base. This task strictly is looking for cyclops numbers in base 10.
There are many different classifications of cyclops numbers with minor differences in characteristics. In an effort to head off a whole series of tasks with tiny variations, we will cover several variants here.
Task
Find and display here on this page the first 50 cyclops numbers in base 10 (all of the sub tasks are restricted to base 10).
Find and display here on this page the first 50 prime cyclops numbers. (cyclops numbers that are prime.)
Find and display here on this page the first 50 blind prime cyclops numbers. (prime cyclops numbers that remain prime when "blinded"; the zero is removed from the center.)
Find and display here on this page the first 50 palindromic prime cyclops numbers. (prime cyclops numbers that are palindromes.)
Stretch
Find and display the first cyclops number greater than ten million (10,000,000) and the index (place) in the series where it is found.
Find and display the first prime cyclops number greater than ten million (10,000,000) and the index (place) in the series where it is found.
Find and display the first blind prime cyclops number greater than ten million (10,000,000) and the index (place) in the series where it is found.
Find and display the first palindromic prime cyclops number greater than ten million (10,000,000) and the index (place) in the series where it is found.
(Note: there are no cyclops numbers between ten million and one hundred million, they need to have an odd number of digits)
See also
OEIS A134808 - Cyclops numbers
OEIS A134809 - Cyclops primes
OEIS A329737 - Cyclops primes that remain prime after being "blinded"
OEIS A136098 - Prime palindromic cyclops numbers
| #Ksh | Ksh |
#!/bin/ksh
# Cyclops numbers (odd number of digits that has a zero in the center)
# - first 50 cyclops numbers
# - first 50 prime cyclops numbers
# - first 50 blind prime cyclops numbers
# - first 50 palindromic prime cyclops numbers
# # Variables:
#
integer MAXN=50
# # Functions:
#
# # Function _isprime(n) return 1 for prime, 0 for not prime
#
function _isprime {
typeset _n ; integer _n=$1
typeset _i ; integer _i
(( _n < 2 )) && return 0
for (( _i=2 ; _i*_i<=_n ; _i++ )); do
(( ! ( _n % _i ) )) && return 0
done
return 1
}
# # Function _iscyclops(n) - return 1 for cyclops number
#
function _iscyclops {
typeset _n ; integer _n=$1
(( ! ${#_n}&1 )) && return 0 # must have odd number of digits
(( ${_n:$((${#_n}/2)):1} )) && return 0 # must have center zero
[[ $(_blind ${_n}) == *0* ]] && return 0 # No other zeros
return 1
}
# # Function _blind(n) - return a "blinded" cyclops number
#
function _blind {
typeset _n ; _n="$1"
echo "${_n:0:$((${#_n}/2))}${_n:$((${#_n}/2+1)):$((${#_n}/2))}"
}
# # Function _ispalindrome(n) - return 1 for palindromic number
#
function _ispalindrome {
typeset _n ; _n="$1"
typeset _flippedn
_flippedn=$(_flipit ${_n:$((${#_n}/2+1)):$((${#_n}/2))})
[[ ${_n:0:$((${#_n}/2))} != ${_flippedn} ]] && return 0
return 1
}
# # Function _flipit(string) - return flipped string
#
function _flipit {
typeset _buf ; _buf="$1"
typeset _tmp ; unset _tmp
for (( _i=$(( ${#_buf}-1 )); _i>=0; _i-- )); do
_tmp="${_tmp}${_buf:${_i}:1}"
done
echo "${_tmp}"
}
######
# main #
######
integer cy=prcy=blprcy=palprcy=0 # counters
typeset -a cyarr prcyarr blprcyarr palprcyarr
for i in {101..909} {11011..99099} {1110111..9990999}; do
_iscyclops ${i} ; (( ! $? )) && continue
(( ++cy <= MAXN )) && cyarr+=( ${i} )
_isprime ${i} ; (( ! $? )) && continue
(( ++prcy <= MAXN )) && prcyarr+=( ${i} )
if (( blprcy < MAXN )); then
_isprime $(_blind ${i})
(( $? )) && { (( blprcy++ )) ; blprcyarr+=( ${i} ) }
fi
if (( palprcy < MAXN )); then
_ispalindrome ${i}
(( $? )) && { (( palprcy++ )) ; palprcyarr+=( ${i} ) }
fi
(( palprcy >= MAXN && blprcy >= MAXN && prcy >= MAXN && cy >= MAXN )) && break
done
print "First $MAXN cyclops numbers:"
print ${cyarr[@]}
print "\nFirst $MAXN prime cyclops numbers:"
print ${prcyarr[@]}
print "\nFirst $MAXN blind prime cyclops numbers:"
print ${blprcyarr[@]}
print "\nFirst $MAXN palindromic prime cyclops numbers:"
print ${palprcyarr[@]}
|
http://rosettacode.org/wiki/Cyclops_numbers | Cyclops numbers | A cyclops number is a number with an odd number of digits that has a zero in the center, but nowhere else. They are named so in tribute to the one eyed giants Cyclops from Greek mythology.
Cyclops numbers can be found in any base. This task strictly is looking for cyclops numbers in base 10.
There are many different classifications of cyclops numbers with minor differences in characteristics. In an effort to head off a whole series of tasks with tiny variations, we will cover several variants here.
Task
Find and display here on this page the first 50 cyclops numbers in base 10 (all of the sub tasks are restricted to base 10).
Find and display here on this page the first 50 prime cyclops numbers. (cyclops numbers that are prime.)
Find and display here on this page the first 50 blind prime cyclops numbers. (prime cyclops numbers that remain prime when "blinded"; the zero is removed from the center.)
Find and display here on this page the first 50 palindromic prime cyclops numbers. (prime cyclops numbers that are palindromes.)
Stretch
Find and display the first cyclops number greater than ten million (10,000,000) and the index (place) in the series where it is found.
Find and display the first prime cyclops number greater than ten million (10,000,000) and the index (place) in the series where it is found.
Find and display the first blind prime cyclops number greater than ten million (10,000,000) and the index (place) in the series where it is found.
Find and display the first palindromic prime cyclops number greater than ten million (10,000,000) and the index (place) in the series where it is found.
(Note: there are no cyclops numbers between ten million and one hundred million, they need to have an odd number of digits)
See also
OEIS A134808 - Cyclops numbers
OEIS A134809 - Cyclops primes
OEIS A329737 - Cyclops primes that remain prime after being "blinded"
OEIS A136098 - Prime palindromic cyclops numbers
| #Mathematica_.2F_Wolfram_Language | Mathematica / Wolfram Language | a = Flatten[Table[FromDigits[{i, 0, j}], {i, 9}, {j, 9}], 1];
b = Flatten@Table[FromDigits@{i, j}, {i, 9}, {j, 9}];
c = Flatten@Table[FromDigits@{i, j, k}, {i, 9}, {j, 9}, {k, 9}];
blindPrimeQ[n_] :=
Block[{digits = IntegerDigits@n, m},
m = Floor[Length[digits]/2];
PrimeQ[FromDigits@Join[digits[[;; m]], digits[[-m ;;]]]]]
palindromeQ[n_] :=
Block[{digits = IntegerDigits@n}, digits === Reverse[digits]]
cyclopsQ[n_] :=
Block[{digits = IntegerDigits@n, len, ctr},
len = Length[digits];
ctr = Ceiling[len/2];
And @@ {Mod[len, 2] == 1, ctr > 0, digits[[ctr]] == 0,
FreeQ[Drop[digits, {ctr}], 0]}]
cyclops = (* all Cyclops numbers with 3, 5 or 7 digits *)
Flatten@{a,
Outer[
FromDigits@Flatten@{IntegerDigits@#1, 0, IntegerDigits@#2} &, b,
b],
Outer[
FromDigits@Flatten@{IntegerDigits@#1, 0, IntegerDigits@#2} &, c,
c]};
x = NestWhile[NextPrime, 10^8, ! (cyclopsQ@# && PrimeQ@#) &];
Labeled[Partition[Flatten[{0, a}][[;; 50]], 10] //
TableForm, "First 50 Cyclop numbers", Top]
Labeled[Partition[(primeCyclops = Cases[cyclops, _?PrimeQ])[[;; 50]],
10] // TableForm, "First 50 prime cyclops numbers", Top]
Labeled[Partition[(blind = Cases[primeCyclops, _?blindPrimeQ])[[;;
50]], 10] //
TableForm, "First 50 blind prime cyclops numbers", Top]
Labeled[Partition[(p = Cases[primeCyclops, _?palindromeQ])[[;; 50]],
10] // TableForm, "First 50 palindromic prime Cyclops Numbers", Top]
Labeled[TableForm[{{x,
Length@primeCyclops}, {NestWhile[NextPrime,
x + 1, ! (cyclopsQ@# && PrimeQ@# && blindPrimeQ@#) &],
Length@blind}, {NestWhile[NextPrime,
x + 1, ! (cyclopsQ@# && PrimeQ@# && palindromeQ@#) &],
Length@p}},
TableHeadings -> {{"Prime", "Blind Prime",
"Palindromic Prime"}, {"Value",
"Index"}}], "First Cyclops numeber > 10,000,000", Top] |
http://rosettacode.org/wiki/Date_manipulation | Date manipulation | Task
Given the date string "March 7 2009 7:30pm EST",
output the time 12 hours later in any human-readable format.
As extra credit, display the resulting time in a time zone different from your own.
| #AWK | AWK |
# syntax: GAWK -f DATE_MANIPULATION.AWK
BEGIN {
fmt = "%a %Y-%m-%d %H:%M:%S %Z" # DAY YYYY-MM-DD HH:MM:SS TZ
split("March 7 2009 7:30pm EST",arr," ")
M = (index("JanFebMarAprMayJunJulAugSepOctNovDec",substr(arr[1],1,3)) + 2) / 3
D = arr[2]
Y = arr[3]
hhmm = arr[4]
hh = substr(hhmm,1,index(hhmm,":")-1) + 0
mm = substr(hhmm,index(hhmm,":")+1,2) + 0
if (hh == 12 && hhmm ~ /am/) { hh = 0 }
else if (hh < 12 && hhmm ~ /pm/) { hh += 12 }
time = mktime(sprintf("%d %d %d %d %d %d",Y,M,D,hh,mm,0))
printf("time: %s\n",strftime(fmt,time))
time += 12*60*60
printf("+12 hrs: %s\n",strftime(fmt,time))
exit(0)
}
|
http://rosettacode.org/wiki/Deal_cards_for_FreeCell | Deal cards for FreeCell | Free Cell is the solitaire card game that Paul Alfille introduced to the PLATO system in 1978. Jim Horne, at Microsoft, changed the name to FreeCell and reimplemented the game for DOS, then Windows.
This version introduced 32000 numbered deals. (The FreeCell FAQ tells this history.)
As the game became popular, Jim Horne disclosed the algorithm, and other implementations of FreeCell began to reproduce the Microsoft deals.
These deals are numbered from 1 to 32000.
Newer versions from Microsoft have 1 million deals, numbered from 1 to 1000000; some implementations allow numbers outside that range.
The algorithm uses this linear congruential generator from Microsoft C:
s
t
a
t
e
n
+
1
≡
214013
×
s
t
a
t
e
n
+
2531011
(
mod
2
31
)
{\displaystyle state_{n+1}\equiv 214013\times state_{n}+2531011{\pmod {2^{31}}}}
r
a
n
d
n
=
s
t
a
t
e
n
÷
2
16
{\displaystyle rand_{n}=state_{n}\div 2^{16}}
r
a
n
d
n
{\displaystyle rand_{n}}
is in range 0 to 32767.
Rosetta Code has another task, linear congruential generator, with code for this RNG in several languages.
The algorithm follows:
Seed the RNG with the number of the deal.
Create an array of 52 cards: Ace of Clubs, Ace of Diamonds, Ace of Hearts, Ace of Spades, 2 of Clubs, 2 of Diamonds, and so on through the ranks: Ace, 2, 3, 4, 5, 6, 7, 8, 9, 10, Jack, Queen, King. The array indexes are 0 to 51, with Ace of Clubs at 0, and King of Spades at 51.
Until the array is empty:
Choose a random card at index ≡ next random number (mod array length).
Swap this random card with the last card of the array.
Remove this random card from the array. (Array length goes down by 1.)
Deal this random card.
Deal all 52 cards, face up, across 8 columns. The first 8 cards go in 8 columns, the next 8 cards go on the first 8 cards, and so on.
Order to deal cards
Game #1
Game #617
1 2 3 4 5 6 7 8
9 10 11 12 13 14 15 16
17 18 19 20 21 22 23 24
25 26 27 28 29 30 31 32
33 34 35 36 37 38 39 40
41 42 43 44 45 46 47 48
49 50 51 52
JD 2D 9H JC 5D 7H 7C 5H
KD KC 9S 5S AD QC KH 3H
2S KS 9D QD JS AS AH 3C
4C 5C TS QH 4H AC 4D 7S
3S TD 4S TH 8H 2C JH 7D
6D 8S 8D QS 6C 3D 8C TC
6S 9C 2H 6H
7D AD 5C 3S 5S 8C 2D AH
TD 7S QD AC 6D 8H AS KH
TH QC 3H 9D 6S 8D 3D TC
KD 5H 9S 3C 8S 7H 4D JS
4C QS 9C 9H 7C 6H 2C 2S
4S TS 2H 5D JC 6C JH QH
JD KS KC 4H
Deals can also be checked against FreeCell solutions to 1000000 games.
(Summon a video solution, and it displays the initial deal.)
Write a program to take a deal number and deal cards in the same order as this algorithm.
The program may display the cards with ASCII, with Unicode, by drawing graphics, or any other way.
Related tasks:
Playing cards
Card shuffles
War Card_Game
Poker hand_analyser
Go Fish
| #Logo | Logo | ; Linear congruential random number generator
make "_lcg_state 0
to seed_lcg :seed
make "_lcg_state :seed
end
to sample_lcg
make "_lcg_state modulo sum product 214013 :_lcg_state 2531011 2147483648
output int quotient :_lcg_state 65536
end
; FreeCell
to card_from_number :number
output word item sum 1 int quotient :number 4 "A23456789TJQK item sum 1 modulo :number 4 "CDHS
end
to generate_deal :number
(local "deck "size "index "deal)
seed_lcg :number
make "deck []
repeat 52 [
make "deck lput difference # 1 :deck
]
make "deck listtoarray :deck
make "deal []
repeat 52 [
make "size difference 53 #
make "index sum 1 modulo sample_lcg :size
make "deal lput item :index :deck :deal
setitem :index :deck item :size :deck
]
output :deal
end
to print_deal :number
(local "deal "i "j "index)
make "deal generate_deal :number
repeat 7 [
make "i difference # 1
repeat (ifelse [equal? :i 6] 4 8) [
make "j difference # 1
make "index (sum 1 product :i 8 :j)
type (word (card_from_number item :index :deal) "| |)
]
print "||
]
end
print [Game #1]
print_deal 1
print "||
print [Game #617]
print_deal 617
print "||
bye |
http://rosettacode.org/wiki/Deal_cards_for_FreeCell | Deal cards for FreeCell | Free Cell is the solitaire card game that Paul Alfille introduced to the PLATO system in 1978. Jim Horne, at Microsoft, changed the name to FreeCell and reimplemented the game for DOS, then Windows.
This version introduced 32000 numbered deals. (The FreeCell FAQ tells this history.)
As the game became popular, Jim Horne disclosed the algorithm, and other implementations of FreeCell began to reproduce the Microsoft deals.
These deals are numbered from 1 to 32000.
Newer versions from Microsoft have 1 million deals, numbered from 1 to 1000000; some implementations allow numbers outside that range.
The algorithm uses this linear congruential generator from Microsoft C:
s
t
a
t
e
n
+
1
≡
214013
×
s
t
a
t
e
n
+
2531011
(
mod
2
31
)
{\displaystyle state_{n+1}\equiv 214013\times state_{n}+2531011{\pmod {2^{31}}}}
r
a
n
d
n
=
s
t
a
t
e
n
÷
2
16
{\displaystyle rand_{n}=state_{n}\div 2^{16}}
r
a
n
d
n
{\displaystyle rand_{n}}
is in range 0 to 32767.
Rosetta Code has another task, linear congruential generator, with code for this RNG in several languages.
The algorithm follows:
Seed the RNG with the number of the deal.
Create an array of 52 cards: Ace of Clubs, Ace of Diamonds, Ace of Hearts, Ace of Spades, 2 of Clubs, 2 of Diamonds, and so on through the ranks: Ace, 2, 3, 4, 5, 6, 7, 8, 9, 10, Jack, Queen, King. The array indexes are 0 to 51, with Ace of Clubs at 0, and King of Spades at 51.
Until the array is empty:
Choose a random card at index ≡ next random number (mod array length).
Swap this random card with the last card of the array.
Remove this random card from the array. (Array length goes down by 1.)
Deal this random card.
Deal all 52 cards, face up, across 8 columns. The first 8 cards go in 8 columns, the next 8 cards go on the first 8 cards, and so on.
Order to deal cards
Game #1
Game #617
1 2 3 4 5 6 7 8
9 10 11 12 13 14 15 16
17 18 19 20 21 22 23 24
25 26 27 28 29 30 31 32
33 34 35 36 37 38 39 40
41 42 43 44 45 46 47 48
49 50 51 52
JD 2D 9H JC 5D 7H 7C 5H
KD KC 9S 5S AD QC KH 3H
2S KS 9D QD JS AS AH 3C
4C 5C TS QH 4H AC 4D 7S
3S TD 4S TH 8H 2C JH 7D
6D 8S 8D QS 6C 3D 8C TC
6S 9C 2H 6H
7D AD 5C 3S 5S 8C 2D AH
TD 7S QD AC 6D 8H AS KH
TH QC 3H 9D 6S 8D 3D TC
KD 5H 9S 3C 8S 7H 4D JS
4C QS 9C 9H 7C 6H 2C 2S
4S TS 2H 5D JC 6C JH QH
JD KS KC 4H
Deals can also be checked against FreeCell solutions to 1000000 games.
(Summon a video solution, and it displays the initial deal.)
Write a program to take a deal number and deal cards in the same order as this algorithm.
The program may display the cards with ASCII, with Unicode, by drawing graphics, or any other way.
Related tasks:
Playing cards
Card shuffles
War Card_Game
Poker hand_analyser
Go Fish
| #Lua | Lua | deck = {}
rank = {"A", "2", "3", "4", "5", "6", "7", "8", "9", "T", "J", "Q", "K"}
suit = {"C", "D", "H", "S"}
two31, state = bit32.lshift(1, 31), 0
function rng()
state = (214013 * state + 2531011) % two31
return bit32.rshift(state, 16)
end
function initdeck()
for i, r in ipairs(rank) do
for j, s in ipairs(suit) do
table.insert(deck, r .. s)
end
end
end
function deal(num)
initdeck()
state = num
print("Game #" .. num)
repeat
choice = rng(num) % #deck + 1
deck[choice], deck[#deck] = deck[#deck], deck[choice]
io.write(" " .. deck[#deck])
if (#deck % 8 == 5) then
print()
end
deck[#deck] = nil
until #deck == 0
print()
end
deal(1)
deal(617) |
http://rosettacode.org/wiki/Define_a_primitive_data_type | Define a primitive data type | Demonstrate how to define a type that behaves like an integer but has a lowest valid value of 1 and a highest valid value of 10. Include all bounds checking you need to write, or explain how the compiler or interpreter creates those bounds checks for you.
| #QBasic | QBasic |
TYPE TipoUsuario
nombre AS STRING * 15
apellido AS STRING * 30
edad AS INTEGER
END TYPE
DIM usuario(1 TO 20) AS TipoUsuario
usuario(1).nombre = "Juan"
usuario(1).apellido = "Hdez."
usuario(1).edad = 49
PRINT usuario(1).nombre, usuario(1).apellido, usuario(1).edad
|
http://rosettacode.org/wiki/Day_of_the_week | Day of the week | A company decides that whenever Xmas falls on a Sunday they will give their workers all extra paid holidays so that, together with any public holidays, workers will not have to work the following week (between the 25th of December and the first of January).
Task
In what years between 2008 and 2121 will the 25th of December be a Sunday?
Using any standard date handling libraries of your programming language;
compare the dates calculated with the output of other languages to discover any anomalies in the handling of dates which may be due to, for example, overflow in types used to represent dates/times similar to y2k type problems.
| #BBC_BASIC | BBC BASIC | INSTALL @lib$+"DATELIB"
FOR year% = 2008 TO 2121
IF FN_dow(FN_mjd(25, 12, year%)) = 0 THEN
PRINT "Christmas Day is a Sunday in "; year%
ENDIF
NEXT |
http://rosettacode.org/wiki/Day_of_the_week | Day of the week | A company decides that whenever Xmas falls on a Sunday they will give their workers all extra paid holidays so that, together with any public holidays, workers will not have to work the following week (between the 25th of December and the first of January).
Task
In what years between 2008 and 2121 will the 25th of December be a Sunday?
Using any standard date handling libraries of your programming language;
compare the dates calculated with the output of other languages to discover any anomalies in the handling of dates which may be due to, for example, overflow in types used to represent dates/times similar to y2k type problems.
| #bc | bc | scale = 0
/*
* Returns day of week (0 to 6) for year, month m, day d in proleptic
* Gregorian calendar. Sunday is 0. Assumes y >= 1, scale = 0.
*/
define w(y, m, d) {
auto a
/* Calculate Zeller's congruence. */
a = (14 - m) / 12
m += 12 * a
y -= a
return ((d + (13 * m + 8) / 5 + \
y + y / 4 - y / 100 + y / 400) % 7)
}
for (y = 2008; y <= 2121; y++) {
/* If December 25 is a Sunday, print year. */
if (w(y, 12, 25) == 0) y
}
quit |
http://rosettacode.org/wiki/CUSIP | CUSIP |
This page uses content from Wikipedia. The original article was at CUSIP. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance)
A CUSIP is a nine-character alphanumeric code that identifies a North American financial security for the purposes of facilitating clearing and settlement of trades. The CUSIP was adopted as an American National Standard under Accredited Standards X9.6.
Task
Ensure the last digit (i.e., the check digit) of the CUSIP code (the 1st column) is correct, against the following:
037833100 Apple Incorporated
17275R102 Cisco Systems
38259P508 Google Incorporated
594918104 Microsoft Corporation
68389X106 Oracle Corporation (incorrect)
68389X105 Oracle Corporation
Example pseudo-code below.
algorithm Cusip-Check-Digit(cusip) is
Input: an 8-character CUSIP
sum := 0
for 1 ≤ i ≤ 8 do
c := the ith character of cusip
if c is a digit then
v := numeric value of the digit c
else if c is a letter then
p := ordinal position of c in the alphabet (A=1, B=2...)
v := p + 9
else if c = "*" then
v := 36
else if c = "@" then
v := 37
else if' c = "#" then
v := 38
end if
if i is even then
v := v × 2
end if
sum := sum + int ( v div 10 ) + v mod 10
repeat
return (10 - (sum mod 10)) mod 10
end function
See related tasks
SEDOL
ISIN
| #11l | 11l | F cusip_check(=cusip)
I cusip.len != 9
X ValueError(‘CUSIP must be 9 characters’)
cusip = cusip.uppercase()
V total = 0
L(i) 8
V v = 0
V c = cusip[i]
I c.is_digit()
v = Int(c)
E I c.is_alpha()
V p = c.code - ‘A’.code + 1
v = p + 9
E I c == ‘*’
v = 36
E I c == ‘@’
v = 37
E I c == ‘#’
v = 38
I i % 2 != 0
v *= 2
total += v I/ 10 + v % 10
V check = (10 - (total % 10)) % 10
R String(check) == cusip.last
V codes = [‘037833100’,
‘17275R102’,
‘38259P508’,
‘594918104’,
‘68389X106’,
‘68389X105’]
L(code) codes
print(code‘: ’(I cusip_check(code) {‘valid’} E ‘invalid’)) |
http://rosettacode.org/wiki/Date_format | Date format | This task has been clarified. Its programming examples are in need of review to ensure that they still fit the requirements of the task.
Task
Display the current date in the formats of:
2007-11-23 and
Friday, November 23, 2007
| #8th | 8th |
d:new
"%Y-%M-%D" over d:format . cr
"%W, %N %D, %Y" over d:format . cr
bye
|
http://rosettacode.org/wiki/Date_format | Date format | This task has been clarified. Its programming examples are in need of review to ensure that they still fit the requirements of the task.
Task
Display the current date in the formats of:
2007-11-23 and
Friday, November 23, 2007
| #AArch64_Assembly | AArch64 Assembly |
/* ARM assembly AARCH64 Raspberry PI 3B */
/* program dateFormat64.s */
/*******************************************/
/* Constantes file */
/*******************************************/
/* for this file see task include a file in language AArch64 assembly*/
.include "../includeConstantesARM64.inc"
.equ GETTIME, 169 // call system linux gettimeofday
/*******************************************/
/* Structures */
/********************************************/
/* example structure time */
.struct 0
timeval_sec: //
.struct timeval_sec + 8
timeval_usec: //
.struct timeval_usec + 8
timeval_end:
.struct 0
timezone_min: //
.struct timezone_min + 8
timezone_dsttime: //
.struct timezone_dsttime + 8
timezone_end:
/*********************************/
/* Initialized data */
/*********************************/
.data
szMessError: .asciz "Error detected !!!!. \n"
szMessResult: .asciz "Date : @/@/@ \n" // message result
szMessResult1: .asciz "Date day : @ @ @ @ \n" // message result
szJan: .asciz "Janvier"
szFev: .asciz "Fèvrier"
szMars: .asciz "Mars"
szAvril: .asciz "Avril"
szMai: .asciz "Mai"
szJuin: .asciz "Juin"
szJuil: .asciz "Juillet"
szAout: .asciz "Aout"
szSept: .asciz "Septembre"
szOct: .asciz "Octobre"
szNov: .asciz "Novembre"
szDec: .asciz "Décembre"
szLundi: .asciz "Lundi"
szMardi: .asciz "Mardi"
szMercredi: .asciz "Mercredi"
szJeudi: .asciz "Jeudi"
szVendredi: .asciz "Vendredi"
szSamedi: .asciz "Samedi"
szDimanche: .asciz "Dimanche"
szCarriageReturn: .asciz "\n"
.align 4
tbDayMonthYear: .quad 0, 31, 60, 91, 121, 152, 182, 213, 244, 274, 305, 335
.quad 366, 397, 425, 456, 486, 517, 547, 578, 609, 639, 670, 700
.quad 731, 762, 790, 821, 851, 882, 912, 943, 974,1004,1035,1065
.quad 1096,1127,1155,1186,1216,1247,1277,1308,1339,1369,1400,1430
tbMonthName: .quad szJan
.quad szFev
.quad szMars
.quad szAvril
.quad szMai
.quad szJuin
.quad szJuil
.quad szAout
.quad szSept
.quad szOct
.quad szNov
.quad szDec
tbDayName: .quad szLundi
.quad szMardi
.quad szMercredi
.quad szJeudi
.quad szVendredi
.quad szSamedi
.quad szDimanche
/*********************************/
/* UnInitialized data */
/*********************************/
.bss
.align 4
stTVal: .skip timeval_end
stTZone: .skip timezone_end
sZoneConv: .skip 24
/*********************************/
/* code section */
/*********************************/
.text
.global main
main: // entry of program
ldr x0,qAdrstTVal
ldr x1,qAdrstTZone
mov x8,#GETTIME
svc 0
cmp x0,#-1 // error ?
beq 99f
ldr x1,qAdrstTVal
ldr x0,[x1,#timeval_sec] // timestamp in second
bl dateFormatNum
ldr x0,[x1,#timeval_sec] // timestamp in second
bl dateFormatAlpha
ldr x0,qTStest1
bl dateFormatNum
ldr x0,qTStest1
bl dateFormatAlpha
ldr x0,qTStest2
bl dateFormatNum
ldr x0,qTStest2
bl dateFormatAlpha
ldr x0,qTStest3
bl dateFormatNum
ldr x0,qTStest3
bl dateFormatAlpha
b 100f
99:
ldr x0,qAdrszMessError
bl affichageMess
100: // standard end of the program
mov x0,#0 // return code
mov x8,#EXIT // request to exit program
svc 0 // perform the system call
qAdrszMessError: .quad szMessError
qAdrstTVal: .quad stTVal
qAdrstTZone: .quad stTZone
qAdrszCarriageReturn: .quad szCarriageReturn
qAdrsZoneConv: .quad sZoneConv
qTStest1: .quad 1609508339 // 01/01/2021
qTStest2: .quad 1657805939 // 14/07/2022
qTStest3: .quad 1767221999 // 31/12/2025
/******************************************************************/
/* date format numeric */
/******************************************************************/
/* x0 contains the timestamp in seconds */
dateFormatNum:
stp x1,lr,[sp,-16]! // save registers
ldr x2,qSecJan2020
sub x0,x0,x2 // total secondes to 01/01/2020
mov x1,60
udiv x0,x0,x1 // divide secondes
udiv x0,x0,x1 // divide minutes
mov x1,#24
udiv x0,x0,x1 // divide hours
mov x11,x0
mov x1,#(365 * 4 + 1)
udiv x9,x0,x1
lsl x9,x9,#2 // multiply by 4 = year1
mov x1,#(365 * 4 + 1)
udiv x2,x11,x1
msub x10,x2,x1,x11
ldr x1,qAdrtbDayMonthYear
mov x2,#3
mov x3,#12
1:
mul x11,x3,x2
ldr x4,[x1,x11,lsl 3] // load days by year
cmp x10,x4
bge 2f
sub x2,x2,1
cbnz x2,1b
2: // x2 = year2
mov x5,11
mul x11,x3,x2
lsl x11,x11,3
add x11,x11,x1 // table address
3:
ldr x4,[x11,x5,lsl 3] // load days by month
cmp x10,x4
bge 4f
subs x5,x5,1
bne 3b
4: // x5 = month - 1
mul x11,x3,x2
add x11,x11,x5
ldr x1,qAdrtbDayMonthYear
ldr x3,[x1,x11,lsl 3]
sub x0,x10,x3
add x0,x0,1 // final compute day
ldr x1,qAdrsZoneConv
bl conversion10 // this function do not zero final
ldr x0,qAdrszMessResult
ldr x1,qAdrsZoneConv
bl strInsertAtCharInc // insert result at first // character
mov x3,x0
add x0,x5,1 // final compute month
cmp x0,12
sub x1,x0,12
csel x0,x1,x0,gt
ldr x1,qAdrsZoneConv
bl conversion10
mov x0,x3
ldr x1,qAdrsZoneConv
bl strInsertAtCharInc // insert result at next // character
mov x3,x0
ldr x11,qYearStart
add x0,x9,x11
add x0,x0,x2 // final compute year = 2020 + yeax1 + yeax2
ldr x1,qAdrsZoneConv
bl conversion10
mov x0,x3
ldr x1,qAdrsZoneConv
bl strInsertAtCharInc // insert result at next // character
bl affichageMess
100:
ldp x1,lr,[sp],16 // restaur 2 registers
ret // return to address lr x30
qAdrszMessResult: .quad szMessResult
/******************************************************************/
/* date format alphanumeric */
/******************************************************************/
/* x0 contains the timestamp in seconds */
dateFormatAlpha:
stp x1,lr,[sp,-16]! // save registers
ldr x2,qSecJan2020
sub x0,x0,x2 // total secondes to 01/01/2020
mov x6,x0
mov x1,60
udiv x0,x0,x1
udiv x0,x0,x1
mov x1,24
udiv x0,x0,x1
mov x7,x0
mov x1,(365 * 4 + 1)
udiv x9,x0,x1
lsl x9,x9,#2 // multiply by 4 = year1
mov x1,(365 * 4 + 1)
udiv x0,x7,x1
msub x10,x0,x1,x7
ldr x1,qAdrtbDayMonthYear
mov x8,3
mov x3,12
1:
mul x7,x3,x8
ldr x4,[x1,x7,lsl 3] // load days by year
cmp x10,x4
bge 2f
sub x8,x8,1
cmp x8,0
bne 1b
2: // x8 = yeax2
mov x5,#11
mul x7,x3,x8
lsl x7,x7,3
add x7,x7,x1
3:
ldr x4,[x7,x5,lsl 3] // load days by month
cmp x10,x4
bge 4f
subs x5,x5,1
bne 3b
4: // x5 = month - 1
mov x0,x6 // number secondes depuis 01/01/2020
ldr x1,qNbSecByDay
udiv x0,x6,x1
mov x1,7
udiv x2,x0,x1
msub x3,x2,x1,x0
add x2,x3,2
cmp x2,7
sub x3,x2,7
csel x2,x3,x2,ge
ldr x1,qAdrtbDayName
ldr x1,[x1,x2,lsl 3]
ldr x0,qAdrszMessResult1
bl strInsertAtCharInc // insert result at next // character
mov x3,x0
mov x7,12
mul x11,x7,x8
add x11,x11,x5
ldr x1,qAdrtbDayMonthYear
ldr x7,[x1,x11,lsl 3]
sub x0,x10,x7
add x0,x0,1 // final compute day
ldr x1,qAdrsZoneConv
bl conversion10 // this function do not zero final
mov x0,x3
ldr x1,qAdrsZoneConv
bl strInsertAtCharInc // insert result at first // character
mov x3,x0
ldr x1,qAdrtbMonthName
cmp x5,12
sub x2,x5,12
csel x5,x2,x5,ge
ldr x1,[x1,x5,lsl 3] // month name
mov x0,x3
bl strInsertAtCharInc // insert result at first // character
mov x3,x0
ldr x0,qYearStart
add x0,x0,x8
add x0,x0,x9 // final compute year = 2020 + yeax1 + yeax2
ldr x1,qAdrsZoneConv
bl conversion10 // this function do not zero final
mov x0,x3
ldr x1,qAdrsZoneConv
bl strInsertAtCharInc // insert result at first // character
bl affichageMess
100:
ldp x1,lr,[sp],16 // restaur 2 registers
ret // return to address lr x30
qAdrszMessResult1: .quad szMessResult1
qSecJan2020: .quad 1577836800
qAdrtbDayMonthYear: .quad tbDayMonthYear
qYearStart: .quad 2020
qAdrtbMonthName: .quad tbMonthName
qAdrtbDayName: .quad tbDayName
qNbSecByDay: .quad 3600 * 24
/********************************************************/
/* File Include fonctions */
/********************************************************/
/* for this file see task include a file in language AArch64 assembly */
.include "../includeARM64.inc"
|
http://rosettacode.org/wiki/Damm_algorithm | Damm algorithm | The Damm algorithm is a checksum algorithm which detects all single digit errors and adjacent transposition errors.
The algorithm is named after H. Michael Damm.
Task
Verify the checksum, stored as last digit of an input.
| #Action.21 | Action! | BYTE FUNC Damm(CHAR ARRAY a)
BYTE ARRAY table=[
0 3 1 7 5 9 8 6 4 2
7 0 9 2 1 5 4 8 6 3
4 2 0 6 8 7 1 3 5 9
1 7 5 0 9 8 3 4 2 6
6 1 2 3 0 4 5 9 7 8
3 6 7 4 2 0 9 5 8 1
5 8 6 9 7 2 0 1 3 4
8 9 4 5 3 6 2 0 1 7
9 4 3 8 6 1 7 2 0 5
2 5 8 1 4 3 6 7 9 0]
BYTE i,x,c
x=0
FOR i=1 TO a(0)
DO
c=a(i)
IF c<'0 OR c>'9 THEN
RETURN (0)
FI
c==-'0
x=table(x*10+c)
OD
IF x=0 THEN
RETURN (1)
FI
RETURN (0)
PROC Test(CHAR ARRAY a)
BYTE i
Print(a) Print(" -> ")
IF Damm(a)=1 THEN
PrintE("valid")
ELSE
PrintE("invalid")
FI
RETURN
PROC Main()
Test("5724")
Test("5727")
Test("112946")
Test("112949")
RETURN |
http://rosettacode.org/wiki/Damm_algorithm | Damm algorithm | The Damm algorithm is a checksum algorithm which detects all single digit errors and adjacent transposition errors.
The algorithm is named after H. Michael Damm.
Task
Verify the checksum, stored as last digit of an input.
| #Ada | Ada | with Ada.Text_IO;
procedure Damm_Algorithm is
function Damm (Input : in String) return Boolean
is
subtype Digit is Character range '0' .. '9';
Table : constant array (Digit, Digit) of Digit :=
(('0', '3', '1', '7', '5', '9', '8', '6', '4', '2'),
('7', '0', '9', '2', '1', '5', '4', '8', '6', '3'),
('4', '2', '0', '6', '8', '7', '1', '3', '5', '9'),
('1', '7', '5', '0', '9', '8', '3', '4', '2', '6'),
('6', '1', '2', '3', '0', '4', '5', '9', '7', '8'),
('3', '6', '7', '4', '2', '0', '9', '5', '8', '1'),
('5', '8', '6', '9', '7', '2', '0', '1', '3', '4'),
('8', '9', '4', '5', '3', '6', '2', '0', '1', '7'),
('9', '4', '3', '8', '6', '1', '7', '2', '0', '5'),
('2', '5', '8', '1', '4', '3', '6', '7', '9', '0'));
Intern : Digit := '0';
begin
for D of Input loop
Intern := Table (Intern, D);
end loop;
return Intern = '0';
end Damm;
procedure Put_Damm (Input : in String) is
use Ada.Text_IO;
begin
Put_Line ("Damm of " & Input & " validates as " & Damm (Input)'Image);
end Put_Damm;
begin
Put_Damm ("5724");
Put_Damm ("5727");
Put_Damm ("112946");
Put_Damm ("112949");
end Damm_Algorithm; |
http://rosettacode.org/wiki/Curzon_numbers | Curzon numbers | A Curzon number is defined to be a positive integer n for which 2n + 1 is evenly divisible by 2 × n + 1.
Generalized Curzon numbers are those where the positive integer n, using a base integer k, satisfy the condition that kn + 1 is evenly divisible by k × n + 1.
Base here does not imply the radix of the counting system; rather the integer the equation is based on. All calculations should be done in base 10.
Generalized Curzon numbers only exist for even base integers.
Task
Find and show the first 50 Generalized Curzon numbers for even base integers from 2 through 10.
Stretch
Find and show the one thousandth.
See also
Numbers Aplenty - Curzon numbers
OEIS:A224486 - Numbers k such that 2*k+1 divides 2^k+1 (Curzon numbers)
and even though it is not specifically mentioned that they are Curzon numbers:
OEIS:A230076 - (A007521(n)-1)/4 (Generalized Curzon numbers with a base 4)
| #C.2B.2B | C++ | #include <iomanip>
#include <iostream>
#include <vector>
#include <gmpxx.h>
bool is_curzon(int n, int k) {
mpz_class p;
mpz_ui_pow_ui(p.get_mpz_t(), k, n);
return (p + 1) % (k * n + 1) == 0;
}
int main() {
for (int k = 2; k <= 10; k += 2) {
std::cout << "Curzon numbers with base " << k << ":\n";
int count = 0, n = 1;
for (; count < 50; ++n) {
if (is_curzon(n, k)) {
std::cout << std::setw(4) << n
<< (++count % 10 == 0 ? '\n' : ' ');
}
}
for (;;) {
if (is_curzon(n, k))
++count;
if (count == 1000)
break;
++n;
}
std::cout << "1000th Curzon number with base " << k << ": " << n
<< "\n\n";
}
return 0;
} |
http://rosettacode.org/wiki/Curzon_numbers | Curzon numbers | A Curzon number is defined to be a positive integer n for which 2n + 1 is evenly divisible by 2 × n + 1.
Generalized Curzon numbers are those where the positive integer n, using a base integer k, satisfy the condition that kn + 1 is evenly divisible by k × n + 1.
Base here does not imply the radix of the counting system; rather the integer the equation is based on. All calculations should be done in base 10.
Generalized Curzon numbers only exist for even base integers.
Task
Find and show the first 50 Generalized Curzon numbers for even base integers from 2 through 10.
Stretch
Find and show the one thousandth.
See also
Numbers Aplenty - Curzon numbers
OEIS:A224486 - Numbers k such that 2*k+1 divides 2^k+1 (Curzon numbers)
and even though it is not specifically mentioned that they are Curzon numbers:
OEIS:A230076 - (A007521(n)-1)/4 (Generalized Curzon numbers with a base 4)
| #Factor | Factor | USING: grouping interpolate io kernel make math math.functions
prettyprint ranges sequences ;
: curzon? ( k n -- ? ) [ ^ 1 + ] 2keep * 1 + divisor? ;
: next ( k n -- k n' ) [ 2dup curzon? ] [ 1 + ] do until ;
: curzon ( k -- seq )
1 [ 50 [ dup , next ] times ] { } make 2nip ;
: curzon. ( k -- )
dup [I Curzon numbers with base ${}:I] nl
curzon 10 group simple-table. ;
2 10 2 <range> [ curzon. nl ] each |
http://rosettacode.org/wiki/Curzon_numbers | Curzon numbers | A Curzon number is defined to be a positive integer n for which 2n + 1 is evenly divisible by 2 × n + 1.
Generalized Curzon numbers are those where the positive integer n, using a base integer k, satisfy the condition that kn + 1 is evenly divisible by k × n + 1.
Base here does not imply the radix of the counting system; rather the integer the equation is based on. All calculations should be done in base 10.
Generalized Curzon numbers only exist for even base integers.
Task
Find and show the first 50 Generalized Curzon numbers for even base integers from 2 through 10.
Stretch
Find and show the one thousandth.
See also
Numbers Aplenty - Curzon numbers
OEIS:A224486 - Numbers k such that 2*k+1 divides 2^k+1 (Curzon numbers)
and even though it is not specifically mentioned that they are Curzon numbers:
OEIS:A230076 - (A007521(n)-1)/4 (Generalized Curzon numbers with a base 4)
| #FreeBASIC | FreeBASIC | ' limit: k * n +1 must be smaller then 2^32-1
Function pow_mod(b As ULongInt, power As ULongInt, modulus As ULongInt) As ULongInt
' returns b ^ power mod modulus
Dim As ULongInt x = 1
While power > 0
If (power And 1) = 1 Then
x = (x * b) Mod modulus
End If
b = (b * b) Mod modulus
power = power Shr 1
Wend
Return x
End Function
For k As ULongInt= 2 To 10 Step 2
Print "The first 50 Curzon numbers using a base of "; k; ":"
Dim As ULongInt count, n = 1, p, m
Do
m = k * n +1
p = pow_mod(k, n ,m) +1
If p = m Then
count += 1
If count <= 50 Then
Print Using "#####"; n;
If (count Mod 10) = 0 Then Print
ElseIf count = 1000 Then
Print : Print "One thousandth: "; n
Print : Print
Exit Do
End If
End If
n += 1
Loop
Next
Sleep |
http://rosettacode.org/wiki/Cut_a_rectangle | Cut a rectangle | A given rectangle is made from m × n squares. If m and n are not both odd, then it is possible to cut a path through the rectangle along the square edges such that the rectangle splits into two connected pieces with the same shape (after rotating one of the pieces by 180°). All such paths for 2 × 2 and 4 × 3 rectangles are shown below.
Write a program that calculates the number of different ways to cut an m × n rectangle. Optionally, show each of the cuts.
Possibly related task: Maze generation for depth-first search.
| #D | D | import core.stdc.stdio, core.stdc.stdlib, core.stdc.string, std.typecons;
enum int[2][4] dir = [[0, -1], [-1, 0], [0, 1], [1, 0]];
__gshared ubyte[] grid;
__gshared uint w, h, len;
__gshared ulong cnt;
__gshared uint[4] next;
void walk(in uint y, in uint x) nothrow @nogc {
if (!y || y == h || !x || x == w) {
cnt += 2;
return;
}
immutable t = y * (w + 1) + x;
grid[t]++;
grid[len - t]++;
foreach (immutable i; staticIota!(0, 4))
if (!grid[t + next[i]])
walk(y + dir[i][0], x + dir[i][1]);
grid[t]--;
grid[len - t]--;
}
ulong solve(in uint hh, in uint ww, in bool recur) nothrow @nogc {
h = (hh & 1) ? ww : hh;
w = (hh & 1) ? hh : ww;
if (h & 1) return 0;
if (w == 1) return 1;
if (w == 2) return h;
if (h == 2) return w;
immutable cy = h / 2;
immutable cx = w / 2;
len = (h + 1) * (w + 1);
{
// grid.length = len; // Slower.
alias T = typeof(grid[0]);
auto ptr = cast(T*)alloca(len * T.sizeof);
if (ptr == null)
exit(1);
grid = ptr[0 .. len];
}
grid[] = 0;
len--;
next = [-1, -w - 1, 1, w + 1];
if (recur)
cnt = 0;
foreach (immutable x; cx + 1 .. w) {
immutable t = cy * (w + 1) + x;
grid[t] = 1;
grid[len - t] = 1;
walk(cy - 1, x);
}
cnt++;
if (h == w)
cnt *= 2;
else if (!(w & 1) && recur)
solve(w, h, 0);
return cnt;
}
void main() {
foreach (immutable uint y; 1 .. 11)
foreach (immutable uint x; 1 .. y + 1)
if (!(x & 1) || !(y & 1))
printf("%d x %d: %llu\n", y, x, solve(y, x, true));
} |
http://rosettacode.org/wiki/Cyclops_numbers | Cyclops numbers | A cyclops number is a number with an odd number of digits that has a zero in the center, but nowhere else. They are named so in tribute to the one eyed giants Cyclops from Greek mythology.
Cyclops numbers can be found in any base. This task strictly is looking for cyclops numbers in base 10.
There are many different classifications of cyclops numbers with minor differences in characteristics. In an effort to head off a whole series of tasks with tiny variations, we will cover several variants here.
Task
Find and display here on this page the first 50 cyclops numbers in base 10 (all of the sub tasks are restricted to base 10).
Find and display here on this page the first 50 prime cyclops numbers. (cyclops numbers that are prime.)
Find and display here on this page the first 50 blind prime cyclops numbers. (prime cyclops numbers that remain prime when "blinded"; the zero is removed from the center.)
Find and display here on this page the first 50 palindromic prime cyclops numbers. (prime cyclops numbers that are palindromes.)
Stretch
Find and display the first cyclops number greater than ten million (10,000,000) and the index (place) in the series where it is found.
Find and display the first prime cyclops number greater than ten million (10,000,000) and the index (place) in the series where it is found.
Find and display the first blind prime cyclops number greater than ten million (10,000,000) and the index (place) in the series where it is found.
Find and display the first palindromic prime cyclops number greater than ten million (10,000,000) and the index (place) in the series where it is found.
(Note: there are no cyclops numbers between ten million and one hundred million, they need to have an odd number of digits)
See also
OEIS A134808 - Cyclops numbers
OEIS A134809 - Cyclops primes
OEIS A329737 - Cyclops primes that remain prime after being "blinded"
OEIS A136098 - Prime palindromic cyclops numbers
| #Nim | Nim | import strutils, times
const Ranges = [0..0, 101..909, 11011..99099, 1110111..9990999, 111101111..999909999]
func isCyclops(d: string): bool =
d[d.len shr 1] == '0' and d.count('0') == 1
func isPrime(n: Natural): bool =
if n < 2: return
if n mod 2 == 0: return n == 2
if n mod 3 == 0: return n == 3
var d = 5
while d * d <= n:
if n mod d == 0: return false
inc d, 2
if n mod d == 0: return false
inc d, 4
return true
func isBlind(d: string): bool =
var d = d
let m = d.len shr 1
result = (d[0..m-1] & d[m+1..^1]).parseInt().isPrime
func isPalindromic(d: string): bool =
for i in 1..d.len:
if d[i-1] != d[^i]: return
result = true
iterator cyclops(): (int, int) =
var count = 0
for r in Ranges:
for n in r:
if ($n).isCyclops:
inc count
yield (count, n)
iterator primeCyclops(): (int, int) =
var count = 0
for (_, n) in cyclops():
if n.isPrime:
inc count
yield (count, n)
iterator blindPrimeCyclops(): (int, int) =
var count = 0
for (_, n) in primeCyclops():
if ($n).isBlind:
inc count
yield (count, n)
iterator palindromicPrimeCyclops(): (int, int) =
var count = 0
for r in Ranges:
for n in r:
let d = $n
if d.isCyclops and d.isPalindromic and n.isPrime:
inc count
yield (count, n)
let t0 = cpuTime()
echo "List of first 50 cyclops numbers:"
for i, n in cyclops():
stdout.write ($n).align(3), if i mod 10 == 0: '\n' else: ' '
if i == 50: break
echo "\nList of first 50 prime cyclops numbers:"
for i, n in primeCyclops():
stdout.write ($n).align(5), if i mod 10 == 0: '\n' else: ' '
if i == 50: break
echo "\nList of first 50 blind prime cyclops numbers:"
for i, n in blindPrimeCyclops():
stdout.write ($n).align(5), if i mod 10 == 0: '\n' else: ' '
if i == 50: break
echo "\nList of first 50 palindromic prime cyclops numbers:"
for i, n in palindromicPrimeCyclops():
stdout.write ($n).align(7), if i mod 10 == 0: '\n' else: ' '
if i == 50: break
for i, n in cyclops():
if n > 10_000_000:
echo "\nFirst cyclops number greater than ten million is ",
($n).insertSep(), " at 1-based index: ", i
break
for i, n in primeCyclops():
if n > 10_000_000:
echo "\nFirst prime cyclops number greater than ten million is ",
($n).insertSep(), " at 1-based index: ", i
break
for i, n in blindPrimeCyclops():
if n > 10_000_000:
echo "\nFirst blind prime cyclops number greater than ten million is ",
($n).insertSep(), " at 1-based index: ", i
break
for i, n in palindromicPrimeCyclops():
if n > 10_000_000:
echo "\nFirst palindromic prime cyclops number greater than ten million is ",
($n).insertSep(), " at 1-based index: ", i
break
echo "\nExecution time: ", (cpuTime() - t0).formatFloat(ffDecimal, precision = 3), " seconds." |
http://rosettacode.org/wiki/Cyclops_numbers | Cyclops numbers | A cyclops number is a number with an odd number of digits that has a zero in the center, but nowhere else. They are named so in tribute to the one eyed giants Cyclops from Greek mythology.
Cyclops numbers can be found in any base. This task strictly is looking for cyclops numbers in base 10.
There are many different classifications of cyclops numbers with minor differences in characteristics. In an effort to head off a whole series of tasks with tiny variations, we will cover several variants here.
Task
Find and display here on this page the first 50 cyclops numbers in base 10 (all of the sub tasks are restricted to base 10).
Find and display here on this page the first 50 prime cyclops numbers. (cyclops numbers that are prime.)
Find and display here on this page the first 50 blind prime cyclops numbers. (prime cyclops numbers that remain prime when "blinded"; the zero is removed from the center.)
Find and display here on this page the first 50 palindromic prime cyclops numbers. (prime cyclops numbers that are palindromes.)
Stretch
Find and display the first cyclops number greater than ten million (10,000,000) and the index (place) in the series where it is found.
Find and display the first prime cyclops number greater than ten million (10,000,000) and the index (place) in the series where it is found.
Find and display the first blind prime cyclops number greater than ten million (10,000,000) and the index (place) in the series where it is found.
Find and display the first palindromic prime cyclops number greater than ten million (10,000,000) and the index (place) in the series where it is found.
(Note: there are no cyclops numbers between ten million and one hundred million, they need to have an odd number of digits)
See also
OEIS A134808 - Cyclops numbers
OEIS A134809 - Cyclops primes
OEIS A329737 - Cyclops primes that remain prime after being "blinded"
OEIS A136098 - Prime palindromic cyclops numbers
| #Pascal | Pascal | program cyclops;
{$IFDEF FPC}
{$MODE DELPHI}
{$OPTIMIZATION ON,ALL}
{$CodeAlign proc=32,loop=1}
{$ENDIF}
//extra https://oeis.org/A136098/b136098.txt take ~37 s( TIO.RUN )
uses
sysutils;
const
BIGLIMIT = 10*1000*1000;
type
//number in base 9
tnumdgts = array[0..10] of byte;
tpnumdgts = pByte;
tnum9 = packed record
nmdgts : tnumdgts;
nmMaxDgtIdx :byte;
nmNum : uint32;
end;
tCN = record
cnRight,
cnLeft : tNum9;
cnNum : Uint64;
cndigits,
cnIdx : Uint32;
end;
tCyclopsList = array of Uint64;
procedure InitCycNum(var cn:tCN);forward;
var
cnMin,cnPow10Shift,cnPow9 : array[0..15] of Uint64;
Cyclops :tCyclopsList;
function IndexToCyclops(n:Uint64):tCN;
//zero-based index
var
dgtCnt,i,num : UInt32;
q,p9: Uint64;
Begin
InitCycNum(result);
if n = 0 then
EXIT;
result.cnIdx := n;
dgtCnt := 0;
repeat
p9 := sqr(cnPow9[dgtCnt]);
if n < p9 then
break;
n -= p9;
inc(dgtCnt)
until dgtcnt>10;
dec(dgtCnt);
with result do
Begin
with cnRight do
Begin
nmMaxDgtIdx := dgtCnt;
For i := 0 to dgtCnt do
begin
q := n DIV 9;
nmdgts[i] := n-9*q;
n := q;
end;
num :=0;
For i := dgtcnt downto 0 do
num := num*10+nmdgts[i]+1;
nmNum:= num;
cnNum := num;
end;
with cnLeft do
Begin
nmMaxDgtIdx := dgtCnt;
For i := 0 to dgtCnt do
begin
q := n DIV 9;
nmdgts[i] := n-9*q;
n := q;
end;
num :=0;
For i := dgtcnt downto 0 do
num := num*10+nmdgts[i]+1;
nmNum:= num;
cnNum += num*cnPow10Shift[dgtCnt];
cndigits := dgtCnt;
end;
end;
end;
procedure Out_Cyclops(const cl:tCyclopsList;colw,colc:NativeInt);
var
i,n : NativeInt;
Begin
n := High(cl);
If n > 100 then
n := 100;
For i := 0 to n do
begin
write(cl[i]:colw);
if (i+1) mod colc = 0 then
writeln;
end;
if (i+1) mod colc <> 0 then
writeln;
if n< High(cl) then
writeln(High(cl)+1,' : ',cl[High(cl)]);
end;
procedure InitCnMinPow;
//min = (0,1,11,111,1111,11111,111111,1111111,11111111,...);
var
i,min,pow,pow9 : Uint64;
begin
min := 0;
pow := 100;
pow9 := 1;
For i :=0 to High(cnMin) do
begin
cnMin[i] := min;
min := 10*min+1;
cnPow10Shift[i] := pow;
pow *= 10;
cnPow9[i] := pow9;
pow9 *= 9;
end;
end;
procedure ClearNum9(var tn:tNum9;idx:Uint32);
begin
fillchar(tn,SizeOf(tn),#0);
tn.nmNum := cnMin[idx+1];
end;
Procedure InitCycNum(var cn:tCN);
Begin
with cn do
Begin
cndigits := 0;
ClearNum9(cnLeft,0);
ClearNum9(cnRight,0);
cnNum := 0;
cnIdx := 0;
end;
end;
procedure IncNum9(var tn:tNum9);
var
idx,fac,n: Uint32;
begin
idx := 0;
with tn do
Begin
fac := 1;
n := nmdgts[0]+1;
inc(nmNum);
repeat
if n < 9 then
break;
inc(nmNum,fac);
nmdgts[idx] :=0;
inc(idx);
fac *= 10;
n := nmdgts[idx]+1;
until idx > nmMaxDgtIdx;
If idx > High(nmdgts) then
EXIT;
nmdgts[idx] := n;
if nmMaxDgtIdx<Idx then
nmMaxDgtIdx := Idx;
end;
end;
procedure NextCycNum(var cycnum:tCN);
begin
with cycnum do
Begin
if cnIdx <> 0 then
begin
//increment right digits
IncNum9(cnRight);
if cnRight.nmMaxDgtIdx > cndigits then
Begin
//set right digits to minimum
ClearNum9(cnRight,cndigits);
//increment left digits
IncNum9(cnLeft);
//One more digit ?
if cnLeft.nmMaxDgtIdx > cndigits then
Begin
inc(cndigits);
ClearNum9(cnLeft,cndigits);
ClearNum9(cnRight,cndigits);
if cndigits>High(tnumdgts) then
cndigits := High(tnumdgts);
end;
end;
cnNum := cnLeft.nmNum*cnPow10Shift[cndigits]+cnRight.nmNUm;
inc(cnIdx);
end
else
Begin
cnNum := 101;
cnIdx := 1;
end;
end;
end;
procedure MakePalinCycNum(var cycnum:tCN);
//make right to be palin of left
var
n,dgt : Uint32;
i,j:NativeInt;
Begin
n := 0;
with cycnum do
Begin
i := 0;
For j := cnDigits downto 0 do
begin
dgt := cnLeft.nmdgts[i];
cnRight.nmdgts[j] := dgt;
n := 10*n+(dgt+1);
inc(i);
end;
cnRight.nmNum := n;
cnNum := cnLeft.nmNum*cnPow10Shift[cndigits]+n;
end;
end;
procedure IncLeftCn(var cn:tCN);
Begin
with cn do
Begin
//set right digits to minimum
ClearNum9(cnRight,cndigits);
//increment left digits
IncNum9(cnLeft);
//One more digit ?
if cnLeft.nmMaxDgtIdx > cndigits then
Begin
inc(cndigits);
ClearNum9(cnLeft,cndigits);
ClearNum9(cnRight,cndigits);
if cndigits>High(tnumdgts) then
cndigits := High(tnumdgts);
end;
cnNum := cnLeft.nmNum*cnPow10Shift[cndigits]+cnRight.nmNUm;
end;
end;
function isPalinCycNum(const cycnum:tCN):boolean;
var
i,j:NativeInt;
Begin
with cycnum do
Begin
i := cnDigits;
j := 0;
repeat
result := (cnRight.nmdgts[i]=cnLeft.nmdgts[j]);
if not(result) then
BREAK;
dec(i);
inc(j);
until i<0;
end;
end;
function FirstCyclops(cnt:NativeInt):tCN;
var
i: NativeInt;
begin
setlength(Cyclops,cnt);
i := 0;
InitCycNum(result);
while i < cnt do
begin
Cyclops[i] := result.cnNum;
inc(i);
NextCycNum(result);
end;
repeat
NextCycNum(result);
inc(i);
until result.cnNum> BIGLIMIT;
end;
function isPrime(n:Uint64):boolean;
var
p,q : Uint64;
Begin
{
if n< 4 then
Begin
if n < 2 then
EXIT(false);
EXIT(true);
end;
if n = 5 then
exit(true);}
if (n AND 1 = 0) then
EXIT(false);
q := n div 3;
if n - 3*q = 0 then
EXIT(false);
p := 5;
{$CodeAlign loop=1}
repeat
q := n div p;
if n-q*p = 0 then
EXIT(false);
p += 2;
q := n div p;
if n-q*p = 0 then
EXIT(false);
if q < p then
break;
p += 4;
until false;
EXIT(true);
end;
function FirstPrimeCyclops(cnt:NativeInt):tCN;
var
i: NativeInt;
begin
i := 0;
setlength(Cyclops,cnt);
InitCycNum(result);
while i<cnt do
begin
if isPrime(result.cnNum) then
Begin
Cyclops[i] := result.cnNum;
inc(i);
end;
NextCycNum(result);
end;
repeat
if isPrime(result.cnNum) then
begin;
inc(i);
if result.cnNum > BIGLIMIT then
BREAK;
end;
NextCycNum(result);
until false;
result.cnIdx := i;
end;
function FirstBlindPrimeCyclops(cnt:NativeInt):tCN;
var
n: Uint64;
i: NativeInt;
isPr:Boolean;
begin
i := 0;
setlength(Cyclops,cnt);
InitCycNum(result);
while i< cnt do
begin
with result do
if isPrime(cnNum) then
Begin
n:= cnRight.nmNum;
if cndigits > 0 then
n += cnLeft.nmNum*cnPow10Shift[cndigits-1]
else
n += cnLeft.nmNum*10;
if isPrime(n) then
Begin
Cyclops[i] := cnNum;
inc(i);
end;
end;
NextCycNum(result);
end;
repeat
with result do
if isPrime(cnNum) then
Begin
n:= cnRight.nmNum;
if cndigits > 0 then
n += cnLeft.nmNum*cnPow10Shift[cndigits-1]
else
n += cnLeft.nmNum*10;
isPr:= isPrime(n);
inc(i,Ord(isPr));
if isPr AND (cnNum > BIGLIMIT) then
BREAK;
end;
NextCycNum(result);
until false;
result.cnIdx := i;
end;
function FirstPalinPrimeCyclops(cnt:NativeInt):tCN;
var
i: NativeInt;
begin
i := 0;
setlength(Cyclops,cnt);
InitCycNum(result);
while i< cnt do
Begin
MakePalinCycNum(result);
with result do
if isPrime(cnNum) then
Begin
Cyclops[i] := cnNum;
inc(i);
end;
IncLeftCn(result);
while Not(result.cnLeft.nmdgts[result.cnDigits]+1 in [1,3,7,9]) do
IncLeftCn(result);
end;
repeat
MakePalinCycNum(result);
with result do
if isPrime(cnNum) then
begin
inc(i);
if cnNum >BIGLIMIT then
break;
end;
IncLeftCn(result);
while Not(result.cnLeft.nmdgts[result.cnDigits]+1 in [1,3,7,9]) do
IncLeftCn(result);
until false;
result.cnIdx := i;
end;
var
cycnum:tCN;
T0 : Int64;
cnt : NativeUint;
begin
InitCnMinPow;
cnt := 50;
writeln('The first ',cnt,' cyclops numbers are:');
cycnum := FirstCyclops(cnt);
Out_Cyclops(Cyclops,5,10);
writeln('First such number > ',BIGLIMIT,' is ',cycnum.cnNum,
' at zero-based index ',cycnum.cnIdx);
writeln;
cnt := 50;
writeln('The first ',cnt,' prime cyclops numbers are:');
T0 := GetTickCount64;
cycnum := FirstPrimeCyclops(cnt);
T0 := GetTickCOunt64-T0;
Out_Cyclops(Cyclops,7,10);
writeln('First such number > ',BIGLIMIT,' is ',cycnum.cnNum,
' at one-based index ',cycnum.cnIdx);
writeln(cycnum.cnIdx,'.th = ',cycnum.cnNum,' in ',T0/1000:6:3,' s');
writeln;
cnt := 50;
writeln('The first ',cnt,' blind prime cyclops numbers are:');
T0 := GetTickCount64;
cycnum := FirstBlindPrimeCyclops(cnt);
T0 := GetTickCOunt64-T0;
Out_Cyclops(Cyclops,7,10);
writeln('First such number > ',BIGLIMIT,' is ',cycnum.cnNum,
' at one-based index ',cycnum.cnIdx);
writeln(cycnum.cnIdx,'.th = ',cycnum.cnNum,' in ',T0/1000:6:3,' s');
writeln;
cnt := 50;
writeln('The first ',cnt,' palindromatic prime cyclops numbers are:');
cycnum := FirstPalinPrimeCyclops(cnt);
Out_Cyclops(Cyclops,15,5);
writeln('First such number > ',BIGLIMIT,' is ',cycnum.cnNum,
' at one-based index ',cycnum.cnIdx);
writeln;
cnt := 100;
repeat
write(cnt:17,'.th = ');
if cnt <= 10*1000 then
Begin
InitCycNum(cycnum);
repeat
NextCycNum(cycnum);
until cycnum.cnIdx = cnt;
write(cycnum.cnNum);
end;
cycnum:= IndexToCyclops(cnt);
writeln(' calc ',cycnum.cnNum);
cnt *= 10;
until cnt >1000*1000*1000*1000*1000;
end.
|
http://rosettacode.org/wiki/Date_manipulation | Date manipulation | Task
Given the date string "March 7 2009 7:30pm EST",
output the time 12 hours later in any human-readable format.
As extra credit, display the resulting time in a time zone different from your own.
| #Batch_File | Batch File |
@echo off
call:Date_Manipulation "March 7 2009 7:30pm EST"
call:Date_Manipulation "February 28 2009 2:28pm EST"
call:Date_Manipulation "February 29 2000 9:52pm EST"
pause>nul
exit /b
:Date_Manipulation
setlocal enabledelayedexpansion
:: These are the arrays we'll be using
set daysinmonth=31 28 31 30 31 30 31 31 30 31 30 31
set namesofmonths=January February March April May June July August September October November December
:: Separate the date given ("%1") into respective variables. Note: For now the "am/pm" is attached to %minutes%
for /f "tokens=1,2,3,4,5,6 delims=: " %%i in ("%~1") do (
set monthname=%%i
set day=%%j
set year=%%k
set hour=%%l
set minutes=%%m
set timezone=%%n
)
:: Separate the am/pm and the minutes value into different variables
set ampm=%minutes:~2,2%
set minutes=%minutes:~0,2%
:: Check if the day needs to be changed based on the status of "am/pm"
if %ampm%==pm (
set /a day+=1
set ampm=am
) else (
set ampm=pm
)
:: Get the number corresponding to the month given
set tempcount=0
for %%i in (%namesofmonths%) do (
set /a tempcount+=1
if %monthname%==%%i set monthcount=!tempcount!
)
:: As this step may may be needed to repeat if the month needs to be changed, we add a label here
:getdaysinthemonth
:: Work out how many days are in the current month
set tempcount=0
for %%i in (%daysinmonth%) do (
set /a tempcount+=1
if %monthcount%==!tempcount! set daysinthemonth=%%i
)
:: If the month is February, check if it is a leap year. If so, add 1 to the amount of days in the month
if %daysinthemonth%==28 (
set /a leapyearcheck=%year% %% 4
if !leapyearcheck!==0 set /a daysinthemonth+=1
)
:: Check if the month needs to be changed based on the current day and how many days there are in the current month
if %day% gtr %daysinthemonth% (
set /a monthcount+=1
set day=1
if !monthcount! gtr 12 (
set monthcount=1
set /a year+=1
)
goto getdaysinthemonth
)
:: Everything from :getdaysinthemonth will be repeated once if the month needs to be changed
:: This block is only required to change the name of the month for the output, however as you have %monthcount%, this is optional
set tempcount=0
for %%i in (%namesofmonths%) do (
set /a tempcount+=1
if %monthcount%==!tempcount! set monthname=%%i
)
echo Original - %~1
echo Manipulated - %monthname% %day% %year% %hour%:%minutes%%ampm% %timezone%
exit /b
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.