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/Shell_one-liner | Shell one-liner | Task
Show how to specify and execute a short program in the language from a command shell, where the input to the command shell is only one line in length.
Avoid depending on the particular shell or operating system used as much as is reasonable; if the language has notable implementations which have different command argument syntax, or the systems those implementations run on have different styles of shells, it would be good to show multiple examples.
| #Vedit_macro_language | Vedit macro language | vpw -c'Get_Key("Hello!") exit' |
http://rosettacode.org/wiki/Shell_one-liner | Shell one-liner | Task
Show how to specify and execute a short program in the language from a command shell, where the input to the command shell is only one line in length.
Avoid depending on the particular shell or operating system used as much as is reasonable; if the language has notable implementations which have different command argument syntax, or the systems those implementations run on have different styles of shells, it would be good to show multiple examples.
| #Wart | Wart | echo "prn 34" |wart |
http://rosettacode.org/wiki/Shell_one-liner | Shell one-liner | Task
Show how to specify and execute a short program in the language from a command shell, where the input to the command shell is only one line in length.
Avoid depending on the particular shell or operating system used as much as is reasonable; if the language has notable implementations which have different command argument syntax, or the systems those implementations run on have different styles of shells, it would be good to show multiple examples.
| #Wren | Wren | echo 'System.print("Hello from Wren!")' > tmp.wren; wren tmp.wren |
http://rosettacode.org/wiki/Short-circuit_evaluation | Short-circuit evaluation | Control Structures
These are examples of control structures. You may also be interested in:
Conditional structures
Exceptions
Flow-control structures
Loops
Assume functions a and b return boolean values, and further, the execution of function b takes considerable resources without side effects, and is to be minimized.
If we needed to compute the conjunction (and):
x = a() and b()
Then it would be best to not compute the value of b() if the value of a() is computed as false, as the value of x can then only ever be false.
Similarly, if we needed to compute the disjunction (or):
y = a() or b()
Then it would be best to not compute the value of b() if the value of a() is computed as true, as the value of y can then only ever be true.
Some languages will stop further computation of boolean equations as soon as the result is known, so-called short-circuit evaluation of boolean expressions
Task
Create two functions named a and b, that take and return the same boolean value.
The functions should also print their name whenever they are called.
Calculate and assign the values of the following equations to a variable in such a way that function b is only called when necessary:
x = a(i) and b(j)
y = a(i) or b(j)
If the language does not have short-circuit evaluation, this might be achieved with nested if statements.
| #Haskell | Haskell | module ShortCircuit where
import Prelude hiding ((&&), (||))
import Debug.Trace
False && _ = False
True && False = False
_ && _ = True
True || _ = True
False || True = True
_ || _ = False
a p = trace ("<a " ++ show p ++ ">") p
b p = trace ("<b " ++ show p ++ ">") p
main = mapM_ print ( [ a p || b q | p <- [False, True], q <- [False, True] ]
++ [ a p && b q | p <- [False, True], q <- [False, True] ]) |
http://rosettacode.org/wiki/Set_puzzle | Set puzzle | Set Puzzles are created with a deck of cards from the Set Game™. The object of the puzzle is to find sets of 3 cards in a rectangle of cards that have been dealt face up.
There are 81 cards in a deck.
Each card contains a unique variation of the following four features: color, symbol, number and shading.
there are three colors:
red, green, purple
there are three symbols:
oval, squiggle, diamond
there is a number of symbols on the card:
one, two, three
there are three shadings:
solid, open, striped
Three cards form a set if each feature is either the same on each card, or is different on each card. For instance: all 3 cards are red, all 3 cards have a different symbol, all 3 cards have a different number of symbols, all 3 cards are striped.
There are two degrees of difficulty: basic and advanced. The basic mode deals 9 cards, that contain exactly 4 sets; the advanced mode deals 12 cards that contain exactly 6 sets.
When creating sets you may use the same card more than once.
Task
Write code that deals the cards (9 or 12, depending on selected mode) from a shuffled deck in which the total number of sets that could be found is 4 (or 6, respectively); and print the contents of the cards and the sets.
For instance:
DEALT 9 CARDS:
green, one, oval, striped
green, one, diamond, open
green, one, diamond, striped
green, one, diamond, solid
purple, one, diamond, open
purple, two, squiggle, open
purple, three, oval, open
red, three, oval, open
red, three, diamond, solid
CONTAINING 4 SETS:
green, one, oval, striped
purple, two, squiggle, open
red, three, diamond, solid
green, one, diamond, open
green, one, diamond, striped
green, one, diamond, solid
green, one, diamond, open
purple, two, squiggle, open
red, three, oval, open
purple, one, diamond, open
purple, two, squiggle, open
purple, three, oval, open
| #F.23 | F# | open System
type Number = One | Two | Three
type Color = Red | Green | Purple
type Fill = Solid | Open | Striped
type Symbol = Oval | Squiggle | Diamond
type Card = { Number: Number; Color: Color; Fill: Fill; Symbol: Symbol }
// A 'Set' is 3 cards in which each individual feature is either all the SAME on each card, OR all DIFFERENT on each card.
let SetSize = 3
type CardsGenerator() =
let _rand = Random()
let shuffleInPlace data =
Array.sortInPlaceBy (fun _ -> (_rand.Next(0, Array.length data))) data
let createCards() =
[| for n in [One; Two; Three] do
for c in [Red; Green; Purple] do
for f in [Solid; Open; Striped] do
for s in [Oval; Squiggle; Diamond] do
yield { Number = n; Color = c; Fill = f; Symbol = s } |]
let _cards = createCards()
member x.GetHand cardCount =
shuffleInPlace _cards
Seq.take cardCount _cards |> Seq.toList
// Find all the combinations of n elements
let rec combinations n items =
match n, items with
| 0, _ -> [[]]
| _, [] -> []
| k, (x::xs) -> List.map ((@) [x]) (combinations (k-1) xs) @ combinations k xs
let validCardSet (cards: Card list) =
// Valid feature if all features are the same or different
let validFeature = function
| [a; b; c] -> (a = b && b = c) || (a <> b && a <> c && b <> c)
| _ -> false
// Build and validate the feature lists
let isValid = cards |> List.fold (fun (ns, cs, fs, ss) c ->
(c.Number::ns, c.Color::cs, c.Fill::fs, c.Symbol::ss)) ([], [], [], [])
|> fun (ns, cs, fs, ss) ->
(validFeature ns) && (validFeature cs) && (validFeature fs) && (validFeature ss)
if isValid then Some cards else None
let findSolution cardCount setCount =
let cardsGen = CardsGenerator()
let rec search () =
let hand = cardsGen.GetHand cardCount
let foundSets = combinations SetSize hand |> List.choose validCardSet
if foundSets.Length = setCount then (hand, foundSets) else search()
search()
let displaySolution (hand: Card list, sets: Card list list) =
let printCardDetails (c: Card) =
printfn " %A %A %A %A" c.Number c.Color c.Symbol c.Fill
printfn "Dealt %d cards:" hand.Length
List.iter printCardDetails hand
printf "\n"
printfn "Found %d sets:" sets.Length
sets |> List.iter (fun cards -> List.iter printCardDetails cards; printf "\n" )
let playGame() =
let solve cardCount setCount =
displaySolution (findSolution cardCount setCount)
solve 9 4
solve 12 6
playGame() |
http://rosettacode.org/wiki/SHA-256 | SHA-256 | SHA-256 is the recommended stronger alternative to SHA-1. See FIPS PUB 180-4 for implementation details.
Either by using a dedicated library or implementing the algorithm in your language, show that the SHA-256 digest of the string "Rosetta code" is: 764faf5c61ac315f1497f9dfa542713965b785e5cc2f707d6468d7d1124cdfcf
| #Emacs_Lisp | Emacs Lisp | (secure-hash 'sha256 "Rosetta code") ;; as string of hex digits |
http://rosettacode.org/wiki/SHA-256 | SHA-256 | SHA-256 is the recommended stronger alternative to SHA-1. See FIPS PUB 180-4 for implementation details.
Either by using a dedicated library or implementing the algorithm in your language, show that the SHA-256 digest of the string "Rosetta code" is: 764faf5c61ac315f1497f9dfa542713965b785e5cc2f707d6468d7d1124cdfcf
| #Erlang | Erlang | 10> Binary = crypto:hash( sha256, "Rosetta code" ).
11> lists:append( [erlang:integer_to_list(X, 16) || <<X:8/integer>> <= Binary] ).
"764FAF5C61AC315F1497F9DFA542713965B785E5CC2F707D6468D7D1124CDFCF"
|
http://rosettacode.org/wiki/SHA-1 | SHA-1 | SHA-1 or SHA1 is a one-way hash function;
it computes a 160-bit message digest.
SHA-1 often appears in security protocols; for example,
many HTTPS websites use RSA with SHA-1 to secure their connections.
BitTorrent uses SHA-1 to verify downloads.
Git and Mercurial use SHA-1 digests to identify commits.
A US government standard, FIPS 180-1, defines SHA-1.
Find the SHA-1 message digest for a string of octets. You may either call a SHA-1 library, or implement SHA-1 in your language. Both approaches interest Rosetta Code.
Warning: SHA-1 has known weaknesses. Theoretical attacks may find a collision after 252 operations, or perhaps fewer.
This is much faster than a brute force attack of 280 operations. USgovernment deprecated SHA-1.
For production-grade cryptography, users may consider a stronger alternative, such as SHA-256 (from the SHA-2 family) or the upcoming SHA-3.
| #F.23 | F# |
let n = System.Security.Cryptography.SHA1.Create()
Array.iter (printf "%x ") (n.ComputeHash "Rosetta Code"B)
|
http://rosettacode.org/wiki/SHA-1 | SHA-1 | SHA-1 or SHA1 is a one-way hash function;
it computes a 160-bit message digest.
SHA-1 often appears in security protocols; for example,
many HTTPS websites use RSA with SHA-1 to secure their connections.
BitTorrent uses SHA-1 to verify downloads.
Git and Mercurial use SHA-1 digests to identify commits.
A US government standard, FIPS 180-1, defines SHA-1.
Find the SHA-1 message digest for a string of octets. You may either call a SHA-1 library, or implement SHA-1 in your language. Both approaches interest Rosetta Code.
Warning: SHA-1 has known weaknesses. Theoretical attacks may find a collision after 252 operations, or perhaps fewer.
This is much faster than a brute force attack of 280 operations. USgovernment deprecated SHA-1.
For production-grade cryptography, users may consider a stronger alternative, such as SHA-256 (from the SHA-2 family) or the upcoming SHA-3.
| #Factor | Factor | IN: scratchpad USING: checksums checksums.sha ;
IN: scratchpad "Rosetta Code" sha1 checksum-bytes hex-string .
"48c98f7e5a6e736d790ab740dfc3f51a61abe2b5"
|
http://rosettacode.org/wiki/Seven-sided_dice_from_five-sided_dice | Seven-sided dice from five-sided dice | Task
(Given an equal-probability generator of one of the integers 1 to 5
as dice5), create dice7 that generates a pseudo-random integer from
1 to 7 in equal probability using only dice5 as a source of random
numbers, and check the distribution for at least one million calls using the function created in Simple Random Distribution Checker.
Implementation suggestion:
dice7 might call dice5 twice, re-call if four of the 25
combinations are given, otherwise split the other 21 combinations
into 7 groups of three, and return the group index from the rolls.
(Task adapted from an answer here)
| #Forth | Forth | require random.fs
: d5 5 random 1+ ;
: discard? 5 = swap 1 > and ;
: d7
begin d5 d5 2dup discard? while 2drop repeat
1- 5 * + 1- 7 mod 1+ ; |
http://rosettacode.org/wiki/Seven-sided_dice_from_five-sided_dice | Seven-sided dice from five-sided dice | Task
(Given an equal-probability generator of one of the integers 1 to 5
as dice5), create dice7 that generates a pseudo-random integer from
1 to 7 in equal probability using only dice5 as a source of random
numbers, and check the distribution for at least one million calls using the function created in Simple Random Distribution Checker.
Implementation suggestion:
dice7 might call dice5 twice, re-call if four of the 25
combinations are given, otherwise split the other 21 combinations
into 7 groups of three, and return the group index from the rolls.
(Task adapted from an answer here)
| #Fortran | Fortran | module rand_mod
implicit none
contains
function rand5()
integer :: rand5
real :: r
call random_number(r)
rand5 = 5*r + 1
end function
function rand7()
integer :: rand7
do
rand7 = 5*rand5() + rand5() - 6
if (rand7 < 21) then
rand7 = rand7 / 3 + 1
return
end if
end do
end function
end module
program Randtest
use rand_mod
implicit none
integer, parameter :: samples = 1000000
call distcheck(rand7, samples, 0.005)
write(*,*)
call distcheck(rand7, samples, 0.001)
end program |
http://rosettacode.org/wiki/Sexy_primes | Sexy primes |
This page uses content from Wikipedia. The original article was at Sexy_prime. 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)
In mathematics, sexy primes are prime numbers that differ from each other by six.
For example, the numbers 5 and 11 are both sexy primes, because 11 minus 6 is 5.
The term "sexy prime" is a pun stemming from the Latin word for six: sex.
Sexy prime pairs: Sexy prime pairs are groups of two primes that differ by 6. e.g. (5 11), (7 13), (11 17)
See sequences: OEIS:A023201 and OEIS:A046117
Sexy prime triplets: Sexy prime triplets are groups of three primes where each differs from the next by 6. e.g. (5 11 17), (7 13 19), (17 23 29)
See sequences: OEIS:A046118, OEIS:A046119 and OEIS:A046120
Sexy prime quadruplets: Sexy prime quadruplets are groups of four primes where each differs from the next by 6. e.g. (5 11 17 23), (11 17 23 29)
See sequences: OEIS:A023271, OEIS:A046122, OEIS:A046123 and OEIS:A046124
Sexy prime quintuplets: Sexy prime quintuplets are groups of five primes with a common difference of 6. One of the terms must be divisible by 5, because 5 and 6 are relatively prime. Thus, the only possible sexy prime quintuplet is (5 11 17 23 29)
Task
For each of pairs, triplets, quadruplets and quintuplets, Find and display the count of each group type of sexy primes less than one million thirty-five (1,000,035).
Display at most the last 5, less than one million thirty-five, of each sexy prime group type.
Find and display the count of the unsexy primes less than one million thirty-five.
Find and display the last 10 unsexy primes less than one million thirty-five.
Note that 1000033 SHOULD NOT be counted in the pair count. It is sexy, but not in a pair within the limit. However, it also SHOULD NOT be listed in the unsexy primes since it is sexy.
| #Pascal | Pascal | program SexyPrimes;
uses
SysUtils
{$IFNDEF FPC}
,windows // GettickCount64
{$ENDIF}
const
ctext: array[0..5] of string = ('Primes',
'sexy prime pairs',
'sexy prime triplets',
'sexy prime quadruplets',
'sexy prime quintuplet',
'sexy prime sextuplet');
primeLmt = 1000 * 1000 + 35;
type
sxPrtpl = record
spCnt,
splast5Idx: nativeInt;
splast5: array[0..6] of NativeInt;
end;
var
sieve: array[0..primeLmt] of byte;
sexyPrimesTpl: array[0..5] of sxPrtpl;
unsexyprimes: NativeUint;
procedure dosieve;
var
p, delPos, fact: NativeInt;
begin
p := 2;
repeat
if sieve[p] = 0 then
begin
delPos := primeLmt div p;
if delPos < p then
BREAK;
fact := delPos * p;
while delPos >= p do
begin
if sieve[delPos] = 0 then
sieve[fact] := 1;
Dec(delPos);
Dec(fact, p);
end;
end;
Inc(p);
until False;
end;
procedure CheckforSexy;
var
i, idx, sieveMask, tstMask: NativeInt;
begin
sieveMask := -1;
for i := 2 to primelmt do
begin
tstMask := 1;
sieveMask := sieveMask + sieveMask + sieve[i];
idx := 0;
repeat
if (tstMask and sieveMask) = 0 then
with sexyPrimesTpl[idx] do
begin
Inc(spCnt);
//memorize the last entry
Inc(splast5idx);
if splast5idx > 5 then
splast5idx := 1;
splast5[splast5idx] := i;
tstMask := tstMask shl 6 + 1;
end
else
begin
BREAK;
end;
Inc(idx);
until idx > 5;
end;
end;
procedure CheckforUnsexy;
var
i: NativeInt;
begin
for i := 2 to 6 do
begin
if (Sieve[i] = 0) and (Sieve[i + 6] = 1) then
Inc(unsexyprimes);
end;
for i := 2 + 6 to primelmt - 6 do
begin
if (Sieve[i] = 0) and (Sieve[i - 6] = 1) and (Sieve[i + 6] = 1) then
Inc(unsexyprimes);
end;
end;
procedure OutLast5(idx: NativeInt);
var
i, j, k: nativeInt;
begin
with sexyPrimesTpl[idx] do
begin
writeln(cText[idx], ' ', spCnt);
i := splast5idx + 1;
for j := 1 to 5 do
begin
if i > 5 then
i := 1;
if splast5[i] <> 0 then
begin
Write('[');
for k := idx downto 1 do
Write(splast5[i] - k * 6, ' ');
Write(splast5[i], ']');
end;
Inc(i);
end;
end;
writeln;
end;
procedure OutLastUnsexy(cnt:NativeInt);
var
i: NativeInt;
erg: array of NativeUint;
begin
if cnt < 1 then
EXIT;
setlength(erg,cnt);
dec(cnt);
if cnt < 0 then
EXIT;
for i := primelmt downto 2 + 6 do
begin
if (Sieve[i] = 0) and (Sieve[i - 6] = 1) and (Sieve[i + 6] = 1) then
Begin
erg[cnt] := i;
dec(cnt);
If cnt < 0 then
BREAK;
end;
end;
write('the last ',High(Erg)+1,' unsexy primes ');
For i := 0 to High(erg)-1 do
write(erg[i],',');
write(erg[High(erg)]);
end;
var
T1, T0: int64;
i: nativeInt;
begin
T0 := GettickCount64;
dosieve;
T1 := GettickCount64;
writeln('Sieving is done in ', T1 - T0, ' ms');
T0 := GettickCount64;
CheckforSexy;
T1 := GettickCount64;
writeln('Checking is done in ', T1 - T0, ' ms');
unsexyprimes := 0;
T0 := GettickCount64;
CheckforUnsexy;
T1 := GettickCount64;
writeln('Checking unsexy is done in ', T1 - T0, ' ms');
writeln('Limit : ', primelmt);
for i := 0 to 4 do
begin
OutLast5(i);
end;
writeln;
writeln(unsexyprimes,' unsexy primes');
OutLastUnsexy(10);
end. |
http://rosettacode.org/wiki/Show_ASCII_table | Show ASCII table | Task
Show the ASCII character set from values 32 to 127 (decimal) in a table format.
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
| #Dc | Dc | [ [1q]S.[>.0]xs.L. ] sl ## l: islt
## for initcode condcode incrcode body
## [1] [2] [3] [4]
[ [q]S. 4:. 3:. 2:. 1:. 1;.x [2;.x 0=. 4;.x 3;.x 0;.x]d0:.x Os.L.o ] sf
## f: for
## for( i=0 ; i<16 ; ++i ) {
## for( j=32+i ; j<128 ; j+=16 ) {
## pr "%3d", j, " : "
## ok = 0;
## if( j == 32 ) { pr "Spc"; ok=1; }
## if( j == 127 ) { pr "Del"; ok=1; }
## if( !ok ) { pr "%c ", j; }
## pr " "
## }
## pr NL
## }
[0si] [li 16 llx] [li1+si] [
[32 li+ sj] [lj 128 llx] [lj 16+ sj] [
[[ ]P]sT 100 lj <T
10 lj <T
ljn [ : ]P
0so
[[Spc]P 1so]sT lj 32 =T
[[Del]P 1so]sT lj 127 =T
[ljP [ ]P ]sT lo 0 =T
[ ]P
] lfx
[]pP
] lfx |
http://rosettacode.org/wiki/Sierpinski_triangle | Sierpinski triangle | Task
Produce an ASCII representation of a Sierpinski triangle of order N.
Example
The Sierpinski triangle of order 4 should look like this:
*
* *
* *
* * * *
* *
* * * *
* * * *
* * * * * * * *
* *
* * * *
* * * *
* * * * * * * *
* * * *
* * * * * * * *
* * * * * * * *
* * * * * * * * * * * * * * * *
Related tasks
Sierpinski triangle/Graphical for graphics images of this pattern.
Sierpinski carpet
| #Mathematica.2FWolfram_Language | Mathematica/Wolfram Language | n=4;Grid[CellularAutomaton[90,{{1},0},2^n-1]/.{0->" ",1->"*"},ItemSize->All] |
http://rosettacode.org/wiki/Sierpinski_carpet | Sierpinski carpet | Task
Produce a graphical or ASCII-art representation of a Sierpinski carpet of order N.
For example, the Sierpinski carpet of order 3 should look like this:
###########################
# ## ## ## ## ## ## ## ## #
###########################
### ###### ###### ###
# # # ## # # ## # # #
### ###### ###### ###
###########################
# ## ## ## ## ## ## ## ## #
###########################
######### #########
# ## ## # # ## ## #
######### #########
### ### ### ###
# # # # # # # #
### ### ### ###
######### #########
# ## ## # # ## ## #
######### #########
###########################
# ## ## ## ## ## ## ## ## #
###########################
### ###### ###### ###
# # # ## # # ## # # #
### ###### ###### ###
###########################
# ## ## ## ## ## ## ## ## #
###########################
The use of the # character is not rigidly required for ASCII art.
The important requirement is the placement of whitespace and non-whitespace characters.
Related task
Sierpinski triangle
| #FreeBASIC | FreeBASIC |
Function in_carpet(x As Uinteger, y As Uinteger) As Boolean
While x <> 0 And y <> 0
If(x Mod 3) = 1 And (y Mod 3) = 1 Then Return False
y = y \ 3: x = x \ 3
Wend
Return True
End Function
Sub carpet(n As Uinteger)
Dim As Uinteger i, j, k = (3^n)-1
For i = 0 To k
For j = 0 To k
If in_carpet(i, j) Then Print("#"); Else Print(" ");
Next j
Print
Next i
End Sub
For k As Byte = 0 To 4
Print !"\nN ="; k
carpet(k)
Next k
Sleep
|
http://rosettacode.org/wiki/Shell_one-liner | Shell one-liner | Task
Show how to specify and execute a short program in the language from a command shell, where the input to the command shell is only one line in length.
Avoid depending on the particular shell or operating system used as much as is reasonable; if the language has notable implementations which have different command argument syntax, or the systems those implementations run on have different styles of shells, it would be good to show multiple examples.
| #zkl | zkl | echo 'println("Hello World ",5+6)' | zkl |
http://rosettacode.org/wiki/Short-circuit_evaluation | Short-circuit evaluation | Control Structures
These are examples of control structures. You may also be interested in:
Conditional structures
Exceptions
Flow-control structures
Loops
Assume functions a and b return boolean values, and further, the execution of function b takes considerable resources without side effects, and is to be minimized.
If we needed to compute the conjunction (and):
x = a() and b()
Then it would be best to not compute the value of b() if the value of a() is computed as false, as the value of x can then only ever be false.
Similarly, if we needed to compute the disjunction (or):
y = a() or b()
Then it would be best to not compute the value of b() if the value of a() is computed as true, as the value of y can then only ever be true.
Some languages will stop further computation of boolean equations as soon as the result is known, so-called short-circuit evaluation of boolean expressions
Task
Create two functions named a and b, that take and return the same boolean value.
The functions should also print their name whenever they are called.
Calculate and assign the values of the following equations to a variable in such a way that function b is only called when necessary:
x = a(i) and b(j)
y = a(i) or b(j)
If the language does not have short-circuit evaluation, this might be achieved with nested if statements.
| #Icon_and_Unicon | Icon and Unicon | procedure main()
&trace := -1 # ensures functions print their names
every (i := false | true ) & ( j := false | true) do {
write("i,j := ",image(i),", ",image(j))
write("i & j:")
x := i() & j() # invoke true/false
write("i | j:")
y := i() | j() # invoke true/false
}
end
procedure true() #: succeeds always (returning null)
return
end
procedure false() #: fails always
fail # for clarity but not needed as running into end has the same effect
end |
http://rosettacode.org/wiki/Short-circuit_evaluation | Short-circuit evaluation | Control Structures
These are examples of control structures. You may also be interested in:
Conditional structures
Exceptions
Flow-control structures
Loops
Assume functions a and b return boolean values, and further, the execution of function b takes considerable resources without side effects, and is to be minimized.
If we needed to compute the conjunction (and):
x = a() and b()
Then it would be best to not compute the value of b() if the value of a() is computed as false, as the value of x can then only ever be false.
Similarly, if we needed to compute the disjunction (or):
y = a() or b()
Then it would be best to not compute the value of b() if the value of a() is computed as true, as the value of y can then only ever be true.
Some languages will stop further computation of boolean equations as soon as the result is known, so-called short-circuit evaluation of boolean expressions
Task
Create two functions named a and b, that take and return the same boolean value.
The functions should also print their name whenever they are called.
Calculate and assign the values of the following equations to a variable in such a way that function b is only called when necessary:
x = a(i) and b(j)
y = a(i) or b(j)
If the language does not have short-circuit evaluation, this might be achieved with nested if statements.
| #Io | Io | a := method(bool,
writeln("a(#{bool}) called." interpolate)
bool
)
b := method(bool,
writeln("b(#{bool}) called." interpolate)
bool
)
list(true,false) foreach(avalue,
list(true,false) foreach(bvalue,
x := a(avalue) and b(bvalue)
writeln("x = a(#{avalue}) and b(#{bvalue}) is #{x}" interpolate)
writeln
y := a(avalue) or b(bvalue)
writeln("y = a(#{avalue}) or b(#{bvalue}) is #{y}" interpolate)
writeln
)
) |
http://rosettacode.org/wiki/Set_puzzle | Set puzzle | Set Puzzles are created with a deck of cards from the Set Game™. The object of the puzzle is to find sets of 3 cards in a rectangle of cards that have been dealt face up.
There are 81 cards in a deck.
Each card contains a unique variation of the following four features: color, symbol, number and shading.
there are three colors:
red, green, purple
there are three symbols:
oval, squiggle, diamond
there is a number of symbols on the card:
one, two, three
there are three shadings:
solid, open, striped
Three cards form a set if each feature is either the same on each card, or is different on each card. For instance: all 3 cards are red, all 3 cards have a different symbol, all 3 cards have a different number of symbols, all 3 cards are striped.
There are two degrees of difficulty: basic and advanced. The basic mode deals 9 cards, that contain exactly 4 sets; the advanced mode deals 12 cards that contain exactly 6 sets.
When creating sets you may use the same card more than once.
Task
Write code that deals the cards (9 or 12, depending on selected mode) from a shuffled deck in which the total number of sets that could be found is 4 (or 6, respectively); and print the contents of the cards and the sets.
For instance:
DEALT 9 CARDS:
green, one, oval, striped
green, one, diamond, open
green, one, diamond, striped
green, one, diamond, solid
purple, one, diamond, open
purple, two, squiggle, open
purple, three, oval, open
red, three, oval, open
red, three, diamond, solid
CONTAINING 4 SETS:
green, one, oval, striped
purple, two, squiggle, open
red, three, diamond, solid
green, one, diamond, open
green, one, diamond, striped
green, one, diamond, solid
green, one, diamond, open
purple, two, squiggle, open
red, three, oval, open
purple, one, diamond, open
purple, two, squiggle, open
purple, three, oval, open
| #Factor | Factor | USING: arrays backtrack combinators.short-circuit formatting
fry grouping io kernel literals math.combinatorics math.matrices
prettyprint qw random sequences sets ;
IN: rosetta-code.set-puzzle
CONSTANT: deck $[
[
qw{ red green purple } amb-lazy
qw{ one two three } amb-lazy
qw{ oval squiggle diamond } amb-lazy
qw{ solid open striped } amb-lazy 4array
] bag-of
]
: valid-category? ( seq -- ? )
{ [ all-equal? ] [ all-unique? ] } 1|| ;
: valid-set? ( seq -- ? )
[ valid-category? ] column-map t [ and ] reduce ;
: find-sets ( seq -- seq )
3 <combinations> [ valid-set? ] filter ;
: deal-hand ( m n -- seq valid? )
[ deck swap sample ] dip over find-sets length = ;
: find-valid-hand ( m n -- seq )
[ f ] 2dip '[ drop _ _ deal-hand not ] loop ;
: set-puzzle ( m n -- )
[ find-valid-hand ] 2keep
[ "Dealt %d cards:\n" printf simple-table. nl ]
[
"Containing %d sets:\n" printf find-sets
{ { " " " " " " " " } } join simple-table. nl
] bi-curry* bi ;
: main ( -- )
9 4 set-puzzle
12 6 set-puzzle ;
MAIN: main |
http://rosettacode.org/wiki/Set_puzzle | Set puzzle | Set Puzzles are created with a deck of cards from the Set Game™. The object of the puzzle is to find sets of 3 cards in a rectangle of cards that have been dealt face up.
There are 81 cards in a deck.
Each card contains a unique variation of the following four features: color, symbol, number and shading.
there are three colors:
red, green, purple
there are three symbols:
oval, squiggle, diamond
there is a number of symbols on the card:
one, two, three
there are three shadings:
solid, open, striped
Three cards form a set if each feature is either the same on each card, or is different on each card. For instance: all 3 cards are red, all 3 cards have a different symbol, all 3 cards have a different number of symbols, all 3 cards are striped.
There are two degrees of difficulty: basic and advanced. The basic mode deals 9 cards, that contain exactly 4 sets; the advanced mode deals 12 cards that contain exactly 6 sets.
When creating sets you may use the same card more than once.
Task
Write code that deals the cards (9 or 12, depending on selected mode) from a shuffled deck in which the total number of sets that could be found is 4 (or 6, respectively); and print the contents of the cards and the sets.
For instance:
DEALT 9 CARDS:
green, one, oval, striped
green, one, diamond, open
green, one, diamond, striped
green, one, diamond, solid
purple, one, diamond, open
purple, two, squiggle, open
purple, three, oval, open
red, three, oval, open
red, three, diamond, solid
CONTAINING 4 SETS:
green, one, oval, striped
purple, two, squiggle, open
red, three, diamond, solid
green, one, diamond, open
green, one, diamond, striped
green, one, diamond, solid
green, one, diamond, open
purple, two, squiggle, open
red, three, oval, open
purple, one, diamond, open
purple, two, squiggle, open
purple, three, oval, open
| #Go | Go | package main
import (
"fmt"
"math/rand"
"time"
)
const (
number = [3]string{"1", "2", "3"}
color = [3]string{"red", "green", "purple"}
shade = [3]string{"solid", "open", "striped"}
shape = [3]string{"oval", "squiggle", "diamond"}
)
type card int
func (c card) String() string {
return fmt.Sprintf("%s %s %s %s",
number[c/27],
color[c/9%3],
shade[c/3%3],
shape[c%3])
}
func main() {
rand.Seed(time.Now().Unix())
game("Basic", 9, 4)
game("Advanced", 12, 6)
}
func game(level string, cards, sets int) {
// create deck
d := make([]card, 81)
for i := range d {
d[i] = card(i)
}
var found [][3]card
for len(found) != sets {
found = found[:0]
// deal
for i := 0; i < cards; i++ {
j := rand.Intn(81 - i)
d[i], d[j] = d[j], d[i]
}
// consider all triplets
for i := 2; i < cards; i++ {
c1 := d[i]
for j := 1; j < i; j++ {
c2 := d[j]
l3:
for _, c3 := range d[:j] {
for f := card(1); f < 81; f *= 3 {
if (c1/f%3 + c2/f%3 + c3/f%3) % 3 != 0 {
continue l3 // not a set
}
}
// it's a set
found = append(found, [3]card{c1, c2, c3})
}
}
}
}
// found the right number
fmt.Printf("%s game. %d cards, %d sets.\n", level, cards, sets)
fmt.Println("Cards:")
for _, c := range d[:cards] {
fmt.Println(" ", c)
}
fmt.Println("Sets:")
for _, s := range found {
fmt.Printf(" %s\n %s\n %s\n",s[0],s[1],s[2])
}
} |
http://rosettacode.org/wiki/SHA-256 | SHA-256 | SHA-256 is the recommended stronger alternative to SHA-1. See FIPS PUB 180-4 for implementation details.
Either by using a dedicated library or implementing the algorithm in your language, show that the SHA-256 digest of the string "Rosetta code" is: 764faf5c61ac315f1497f9dfa542713965b785e5cc2f707d6468d7d1124cdfcf
| #F.23 | F# | open System.Security.Cryptography
open System.Text
"Rosetta code"
|> Encoding.ASCII.GetBytes
|> (new SHA256Managed()).ComputeHash
|> System.BitConverter.ToString
|> printfn "%s"
|
http://rosettacode.org/wiki/SHA-256 | SHA-256 | SHA-256 is the recommended stronger alternative to SHA-1. See FIPS PUB 180-4 for implementation details.
Either by using a dedicated library or implementing the algorithm in your language, show that the SHA-256 digest of the string "Rosetta code" is: 764faf5c61ac315f1497f9dfa542713965b785e5cc2f707d6468d7d1124cdfcf
| #Factor | Factor | USING: checksums checksums.sha io math.parser ;
"Rosetta code" sha-256 checksum-bytes bytes>hex-string print |
http://rosettacode.org/wiki/SHA-1 | SHA-1 | SHA-1 or SHA1 is a one-way hash function;
it computes a 160-bit message digest.
SHA-1 often appears in security protocols; for example,
many HTTPS websites use RSA with SHA-1 to secure their connections.
BitTorrent uses SHA-1 to verify downloads.
Git and Mercurial use SHA-1 digests to identify commits.
A US government standard, FIPS 180-1, defines SHA-1.
Find the SHA-1 message digest for a string of octets. You may either call a SHA-1 library, or implement SHA-1 in your language. Both approaches interest Rosetta Code.
Warning: SHA-1 has known weaknesses. Theoretical attacks may find a collision after 252 operations, or perhaps fewer.
This is much faster than a brute force attack of 280 operations. USgovernment deprecated SHA-1.
For production-grade cryptography, users may consider a stronger alternative, such as SHA-256 (from the SHA-2 family) or the upcoming SHA-3.
| #Fortran | Fortran | module sha1_mod
use kernel32
use advapi32
implicit none
integer, parameter :: SHA1LEN = 20
contains
subroutine sha1hash(name, hash, dwStatus, filesize)
implicit none
character(*) :: name
integer, parameter :: BUFLEN = 32768
integer(HANDLE) :: hFile, hProv, hHash
integer(DWORD) :: dwStatus, nRead
integer(BOOL) :: status
integer(BYTE) :: buffer(BUFLEN)
integer(BYTE) :: hash(SHA1LEN)
integer(UINT64) :: filesize
dwStatus = 0
filesize = 0
hFile = CreateFile(trim(name) // char(0), GENERIC_READ, FILE_SHARE_READ, NULL, &
OPEN_EXISTING, FILE_FLAG_SEQUENTIAL_SCAN, NULL)
if (hFile == INVALID_HANDLE_VALUE) then
dwStatus = GetLastError()
print *, "CreateFile failed."
return
end if
if (CryptAcquireContext(hProv, NULL, NULL, PROV_RSA_FULL, &
CRYPT_VERIFYCONTEXT) == FALSE) then
dwStatus = GetLastError()
print *, "CryptAcquireContext failed."
goto 3
end if
if (CryptCreateHash(hProv, CALG_SHA1, 0_ULONG_PTR, 0_DWORD, hHash) == FALSE) then
dwStatus = GetLastError()
print *, "CryptCreateHash failed."
go to 2
end if
do
status = ReadFile(hFile, loc(buffer), BUFLEN, nRead, NULL)
if (status == FALSE .or. nRead == 0) exit
filesize = filesize + nRead
if (CryptHashData(hHash, buffer, nRead, 0) == FALSE) then
dwStatus = GetLastError()
print *, "CryptHashData failed."
go to 1
end if
end do
if (status == FALSE) then
dwStatus = GetLastError()
print *, "ReadFile failed."
go to 1
end if
nRead = SHA1LEN
if (CryptGetHashParam(hHash, HP_HASHVAL, hash, nRead, 0) == FALSE) then
dwStatus = GetLastError()
print *, "CryptGetHashParam failed.", status, nRead, dwStatus
end if
1 status = CryptDestroyHash(hHash)
2 status = CryptReleaseContext(hProv, 0)
3 status = CloseHandle(hFile)
end subroutine
end module
program sha1
use sha1_mod
implicit none
integer :: n, m, i, j
character(:), allocatable :: name
integer(DWORD) :: dwStatus
integer(BYTE) :: hash(SHA1LEN)
integer(UINT64) :: filesize
n = command_argument_count()
do i = 1, n
call get_command_argument(i, length=m)
allocate(character(m) :: name)
call get_command_argument(i, name)
call sha1hash(name, hash, dwStatus, filesize)
if (dwStatus == 0) then
do j = 1, SHA1LEN
write(*, "(Z2.2)", advance="NO") hash(j)
end do
write(*, "(' ',A,' (',G0,' bytes)')") name, filesize
end if
deallocate(name)
end do
end program |
http://rosettacode.org/wiki/Seven-sided_dice_from_five-sided_dice | Seven-sided dice from five-sided dice | Task
(Given an equal-probability generator of one of the integers 1 to 5
as dice5), create dice7 that generates a pseudo-random integer from
1 to 7 in equal probability using only dice5 as a source of random
numbers, and check the distribution for at least one million calls using the function created in Simple Random Distribution Checker.
Implementation suggestion:
dice7 might call dice5 twice, re-call if four of the 25
combinations are given, otherwise split the other 21 combinations
into 7 groups of three, and return the group index from the rolls.
(Task adapted from an answer here)
| #FreeBASIC | FreeBASIC |
Function dice5() As Integer
Return Int(Rnd * 5) + 1
End Function
Function dice7() As Integer
Dim As Integer temp
Do
temp = dice5() * 5 + dice5() -6
Loop Until temp < 21
Return (temp Mod 7) +1
End Function
Dim Shared As Ulongint n = 1000000
Print "Testing "; n; " times"
If Not(distCheck(n, 0.05)) Then Print "Test failed" Else Print "Test passed"
Sleep
|
http://rosettacode.org/wiki/Sexy_primes | Sexy primes |
This page uses content from Wikipedia. The original article was at Sexy_prime. 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)
In mathematics, sexy primes are prime numbers that differ from each other by six.
For example, the numbers 5 and 11 are both sexy primes, because 11 minus 6 is 5.
The term "sexy prime" is a pun stemming from the Latin word for six: sex.
Sexy prime pairs: Sexy prime pairs are groups of two primes that differ by 6. e.g. (5 11), (7 13), (11 17)
See sequences: OEIS:A023201 and OEIS:A046117
Sexy prime triplets: Sexy prime triplets are groups of three primes where each differs from the next by 6. e.g. (5 11 17), (7 13 19), (17 23 29)
See sequences: OEIS:A046118, OEIS:A046119 and OEIS:A046120
Sexy prime quadruplets: Sexy prime quadruplets are groups of four primes where each differs from the next by 6. e.g. (5 11 17 23), (11 17 23 29)
See sequences: OEIS:A023271, OEIS:A046122, OEIS:A046123 and OEIS:A046124
Sexy prime quintuplets: Sexy prime quintuplets are groups of five primes with a common difference of 6. One of the terms must be divisible by 5, because 5 and 6 are relatively prime. Thus, the only possible sexy prime quintuplet is (5 11 17 23 29)
Task
For each of pairs, triplets, quadruplets and quintuplets, Find and display the count of each group type of sexy primes less than one million thirty-five (1,000,035).
Display at most the last 5, less than one million thirty-five, of each sexy prime group type.
Find and display the count of the unsexy primes less than one million thirty-five.
Find and display the last 10 unsexy primes less than one million thirty-five.
Note that 1000033 SHOULD NOT be counted in the pair count. It is sexy, but not in a pair within the limit. However, it also SHOULD NOT be listed in the unsexy primes since it is sexy.
| #Perl | Perl | use ntheory qw/prime_iterator is_prime/;
sub tuple_tail {
my($n,$cnt,@array) = @_;
$n = @array if $n > @array;
my @tail;
for (1..$n) {
my $p = $array[-$n+$_-1];
push @tail, "(" . join(" ", map { $p+6*$_ } 0..$cnt-1) . ")";
}
return @tail;
}
sub comma {
(my $s = reverse shift) =~ s/(.{3})/$1,/g;
($s = reverse $s) =~ s/^,//;
return $s;
}
sub sexy_string { my $p = shift; is_prime($p+6) || is_prime($p-6) ? 'sexy' : 'unsexy' }
my $max = 1_000_035;
my $cmax = comma $max;
my $iter = prime_iterator;
my $p = $iter->();
my %primes;
push @{$primes{sexy_string($p)}}, $p;
while ( ($p = $iter->()) < $max) {
push @{$primes{sexy_string($p)}}, $p;
$p+ 6 < $max && is_prime($p+ 6) ? push @{$primes{'pair'}}, $p : next;
$p+12 < $max && is_prime($p+12) ? push @{$primes{'triplet'}}, $p : next;
$p+18 < $max && is_prime($p+18) ? push @{$primes{'quadruplet'}}, $p : next;
$p+24 < $max && is_prime($p+24) ? push @{$primes{'quintuplet'}}, $p : next;
}
print "Total primes less than $cmax: " . comma(@{$primes{'sexy'}} + @{$primes{'unsexy'}}) . "\n\n";
for (['pair', 2], ['triplet', 3], ['quadruplet', 4], ['quintuplet', 5]) {
my($sexy,$cnt) = @$_;
print "Number of sexy prime ${sexy}s less than $cmax: " . comma(scalar @{$primes{$sexy}}) . "\n";
print " Last 5 sexy prime ${sexy}s less than $cmax: " . join(' ', tuple_tail(5,$cnt,@{$primes{$sexy}})) . "\n";
print "\n";
}
print "Number of unsexy primes less than $cmax: ". comma(scalar @{$primes{unsexy}}) . "\n";
print " Last 10 unsexy primes less than $cmax: ". join(' ', @{$primes{unsexy}}[-10..-1]) . "\n"; |
http://rosettacode.org/wiki/Show_ASCII_table | Show ASCII table | Task
Show the ASCII character set from values 32 to 127 (decimal) in a table format.
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
| #Delphi | Delphi |
program Show_Ascii_table;
{$APPTYPE CONSOLE}
var
i, j: Integer;
k: string;
begin
for i := 0 to 15 do
begin
j := 32 + i;
while j < 128 do
begin
case j of
32:
k := 'Spc';
127:
k := 'Del';
else
k := chr(j);
end;
Write(j: 3, ' : ', k: 3, ' ');
inc(j, 16);
end;
Writeln;
end;
Readln;
end.
|
http://rosettacode.org/wiki/Sierpinski_triangle | Sierpinski triangle | Task
Produce an ASCII representation of a Sierpinski triangle of order N.
Example
The Sierpinski triangle of order 4 should look like this:
*
* *
* *
* * * *
* *
* * * *
* * * *
* * * * * * * *
* *
* * * *
* * * *
* * * * * * * *
* * * *
* * * * * * * *
* * * * * * * *
* * * * * * * * * * * * * * * *
Related tasks
Sierpinski triangle/Graphical for graphics images of this pattern.
Sierpinski carpet
| #MATLAB | MATLAB | n = 4;
d = string('*');
for k = 0 : n - 1
sp = repelem(' ', 2 ^ k);
d = [sp + d + sp, d + ' ' + d];
end
disp(d.join(char(10)))
|
http://rosettacode.org/wiki/Sierpinski_carpet | Sierpinski carpet | Task
Produce a graphical or ASCII-art representation of a Sierpinski carpet of order N.
For example, the Sierpinski carpet of order 3 should look like this:
###########################
# ## ## ## ## ## ## ## ## #
###########################
### ###### ###### ###
# # # ## # # ## # # #
### ###### ###### ###
###########################
# ## ## ## ## ## ## ## ## #
###########################
######### #########
# ## ## # # ## ## #
######### #########
### ### ### ###
# # # # # # # #
### ### ### ###
######### #########
# ## ## # # ## ## #
######### #########
###########################
# ## ## ## ## ## ## ## ## #
###########################
### ###### ###### ###
# # # ## # # ## # # #
### ###### ###### ###
###########################
# ## ## ## ## ## ## ## ## #
###########################
The use of the # character is not rigidly required for ASCII art.
The important requirement is the placement of whitespace and non-whitespace characters.
Related task
Sierpinski triangle
| #Gnuplot | Gnuplot |
## SCff.gp 1/14/17 aev
## Plotting Sierpinski carpet fractal.
## dat-files are PARI/GP generated output files:
## http://rosettacode.org/wiki/Sierpinski_carpet#PARI.2FGP
#cd 'C:\gnupData'
##SC5
clr = '"green"'
filename = "SC5gp1"
ttl = "Sierpinski carpet fractal, v.#1"
load "plotff.gp"
|
http://rosettacode.org/wiki/Short-circuit_evaluation | Short-circuit evaluation | Control Structures
These are examples of control structures. You may also be interested in:
Conditional structures
Exceptions
Flow-control structures
Loops
Assume functions a and b return boolean values, and further, the execution of function b takes considerable resources without side effects, and is to be minimized.
If we needed to compute the conjunction (and):
x = a() and b()
Then it would be best to not compute the value of b() if the value of a() is computed as false, as the value of x can then only ever be false.
Similarly, if we needed to compute the disjunction (or):
y = a() or b()
Then it would be best to not compute the value of b() if the value of a() is computed as true, as the value of y can then only ever be true.
Some languages will stop further computation of boolean equations as soon as the result is known, so-called short-circuit evaluation of boolean expressions
Task
Create two functions named a and b, that take and return the same boolean value.
The functions should also print their name whenever they are called.
Calculate and assign the values of the following equations to a variable in such a way that function b is only called when necessary:
x = a(i) and b(j)
y = a(i) or b(j)
If the language does not have short-circuit evaluation, this might be achieved with nested if statements.
| #J | J | labeled=:1 :'[ smoutput@,&":~&m'
A=: 'A ' labeled
B=: 'B ' labeled
and=: ^:
or=: 2 :'u^:(-.@v)' |
http://rosettacode.org/wiki/Short-circuit_evaluation | Short-circuit evaluation | Control Structures
These are examples of control structures. You may also be interested in:
Conditional structures
Exceptions
Flow-control structures
Loops
Assume functions a and b return boolean values, and further, the execution of function b takes considerable resources without side effects, and is to be minimized.
If we needed to compute the conjunction (and):
x = a() and b()
Then it would be best to not compute the value of b() if the value of a() is computed as false, as the value of x can then only ever be false.
Similarly, if we needed to compute the disjunction (or):
y = a() or b()
Then it would be best to not compute the value of b() if the value of a() is computed as true, as the value of y can then only ever be true.
Some languages will stop further computation of boolean equations as soon as the result is known, so-called short-circuit evaluation of boolean expressions
Task
Create two functions named a and b, that take and return the same boolean value.
The functions should also print their name whenever they are called.
Calculate and assign the values of the following equations to a variable in such a way that function b is only called when necessary:
x = a(i) and b(j)
y = a(i) or b(j)
If the language does not have short-circuit evaluation, this might be achieved with nested if statements.
| #Java | Java | public class ShortCirc {
public static void main(String[] args){
System.out.println("F and F = " + (a(false) && b(false)) + "\n");
System.out.println("F or F = " + (a(false) || b(false)) + "\n");
System.out.println("F and T = " + (a(false) && b(true)) + "\n");
System.out.println("F or T = " + (a(false) || b(true)) + "\n");
System.out.println("T and F = " + (a(true) && b(false)) + "\n");
System.out.println("T or F = " + (a(true) || b(false)) + "\n");
System.out.println("T and T = " + (a(true) && b(true)) + "\n");
System.out.println("T or T = " + (a(true) || b(true)) + "\n");
}
public static boolean a(boolean a){
System.out.println("a");
return a;
}
public static boolean b(boolean b){
System.out.println("b");
return b;
}
} |
http://rosettacode.org/wiki/Set_puzzle | Set puzzle | Set Puzzles are created with a deck of cards from the Set Game™. The object of the puzzle is to find sets of 3 cards in a rectangle of cards that have been dealt face up.
There are 81 cards in a deck.
Each card contains a unique variation of the following four features: color, symbol, number and shading.
there are three colors:
red, green, purple
there are three symbols:
oval, squiggle, diamond
there is a number of symbols on the card:
one, two, three
there are three shadings:
solid, open, striped
Three cards form a set if each feature is either the same on each card, or is different on each card. For instance: all 3 cards are red, all 3 cards have a different symbol, all 3 cards have a different number of symbols, all 3 cards are striped.
There are two degrees of difficulty: basic and advanced. The basic mode deals 9 cards, that contain exactly 4 sets; the advanced mode deals 12 cards that contain exactly 6 sets.
When creating sets you may use the same card more than once.
Task
Write code that deals the cards (9 or 12, depending on selected mode) from a shuffled deck in which the total number of sets that could be found is 4 (or 6, respectively); and print the contents of the cards and the sets.
For instance:
DEALT 9 CARDS:
green, one, oval, striped
green, one, diamond, open
green, one, diamond, striped
green, one, diamond, solid
purple, one, diamond, open
purple, two, squiggle, open
purple, three, oval, open
red, three, oval, open
red, three, diamond, solid
CONTAINING 4 SETS:
green, one, oval, striped
purple, two, squiggle, open
red, three, diamond, solid
green, one, diamond, open
green, one, diamond, striped
green, one, diamond, solid
green, one, diamond, open
purple, two, squiggle, open
red, three, oval, open
purple, one, diamond, open
purple, two, squiggle, open
purple, three, oval, open
| #Haskell | Haskell | import Control.Monad.State
(State, evalState, replicateM, runState, state)
import System.Random (StdGen, newStdGen, randomR)
import Data.List (find, nub, sort)
combinations :: Int -> [a] -> [[a]]
combinations 0 _ = [[]]
combinations _ [] = []
combinations k (y:ys) = map (y :) (combinations (k - 1) ys) ++ combinations k ys
data Color
= Red
| Green
| Purple
deriving (Show, Enum, Bounded, Ord, Eq)
data Symbol
= Oval
| Squiggle
| Diamond
deriving (Show, Enum, Bounded, Ord, Eq)
data Count
= One
| Two
| Three
deriving (Show, Enum, Bounded, Ord, Eq)
data Shading
= Solid
| Open
| Striped
deriving (Show, Enum, Bounded, Ord, Eq)
data Card = Card
{ color :: Color
, symbol :: Symbol
, count :: Count
, shading :: Shading
} deriving (Show)
-- Identify a set of three cards by counting all attribute types.
-- if each count is 3 or 1 ( not 2 ) the the cards compose a set.
isSet :: [Card] -> Bool
isSet cs =
let total = length . nub . sort . flip map cs
in notElem 2 [total color, total symbol, total count, total shading]
-- Get a random card from a deck. Returns the card and removes it from the deck.
getCard :: State (StdGen, [Card]) Card
getCard =
state $
\(gen, cs) ->
let (i, newGen) = randomR (0, length cs - 1) gen
(a, b) = splitAt i cs
in (head b, (newGen, a ++ tail b))
-- Get a hand of cards. Starts with new deck and then removes the
-- appropriate number of cards from that deck.
getHand :: Int -> State StdGen [Card]
getHand n =
state $
\gen ->
let az = [minBound .. maxBound]
deck =
[ Card co sy ct sh
| co <- az
, sy <- az
, ct <- az
, sh <- az ]
(a, (newGen, _)) = runState (replicateM n getCard) (gen, deck)
in (a, newGen)
-- Get an unbounded number of hands of the appropriate number of cards.
getManyHands :: Int -> State StdGen [[Card]]
getManyHands n = (sequence . repeat) (getHand n)
-- Deal out hands of the appropriate size until one with the desired number
-- of sets is found. then print the hand and the sets.
showSolutions :: Int -> Int -> IO ()
showSolutions cardCount solutionCount = do
putStrLn $
"Showing hand of " ++
show cardCount ++ " cards with " ++ show solutionCount ++ " solutions."
gen <- newStdGen
let Just z =
find ((solutionCount ==) . length . filter isSet . combinations 3) $
evalState (getManyHands cardCount) gen
mapM_ print z
putStrLn ""
putStrLn "Solutions:"
mapM_ putSet $ filter isSet $ combinations 3 z
where
putSet st = do
mapM_ print st
putStrLn ""
-- Show a hand of 9 cards with 4 solutions
-- and a hand of 12 cards with 6 solutions.
main :: IO ()
main = do
showSolutions 9 4
showSolutions 12 6 |
http://rosettacode.org/wiki/SHA-256 | SHA-256 | SHA-256 is the recommended stronger alternative to SHA-1. See FIPS PUB 180-4 for implementation details.
Either by using a dedicated library or implementing the algorithm in your language, show that the SHA-256 digest of the string "Rosetta code" is: 764faf5c61ac315f1497f9dfa542713965b785e5cc2f707d6468d7d1124cdfcf
| #Forth | Forth |
c-library crypto
s" ssl" add-lib
s" crypto" add-lib
\c #include <openssl/sha.h>
c-function sha256 SHA256 a n a -- a
end-c-library
: 2h. ( n1 -- ) base @ swap hex s>d <# # # #> type base ! ;
: .digest ( a -- )
32 bounds do i c@ 2h. loop space ;
s" Rosetta code" 0 sha256 .digest cr
bye
|
http://rosettacode.org/wiki/SHA-256 | SHA-256 | SHA-256 is the recommended stronger alternative to SHA-1. See FIPS PUB 180-4 for implementation details.
Either by using a dedicated library or implementing the algorithm in your language, show that the SHA-256 digest of the string "Rosetta code" is: 764faf5c61ac315f1497f9dfa542713965b785e5cc2f707d6468d7d1124cdfcf
| #Fortran | Fortran | sha256 rc.txt
764FAF5C61AC315F1497F9DFA542713965B785E5CC2F707D6468D7D1124CDFCF rc.txt (12 bytes) |
http://rosettacode.org/wiki/SHA-1 | SHA-1 | SHA-1 or SHA1 is a one-way hash function;
it computes a 160-bit message digest.
SHA-1 often appears in security protocols; for example,
many HTTPS websites use RSA with SHA-1 to secure their connections.
BitTorrent uses SHA-1 to verify downloads.
Git and Mercurial use SHA-1 digests to identify commits.
A US government standard, FIPS 180-1, defines SHA-1.
Find the SHA-1 message digest for a string of octets. You may either call a SHA-1 library, or implement SHA-1 in your language. Both approaches interest Rosetta Code.
Warning: SHA-1 has known weaknesses. Theoretical attacks may find a collision after 252 operations, or perhaps fewer.
This is much faster than a brute force attack of 280 operations. USgovernment deprecated SHA-1.
For production-grade cryptography, users may consider a stronger alternative, such as SHA-256 (from the SHA-2 family) or the upcoming SHA-3.
| #FreeBASIC | FreeBASIC | ' version 18-10-2016
' started with SHA-1/FIPS-180-1
' but used the BBC BASIC native version to finish.
' compile with: fbc -s console
Function SHA_1(test_str As String) As String
Dim As String message = test_str ' strings are passed as ByRef's
Dim As Long i, j
Dim As UByte Ptr ww1
Dim As UInteger<32> Ptr ww4
Dim As ULongInt l = Len(message)
' set the first bit after the message to 1
message = message + Chr(1 Shl 7)
' add one char to the length
Dim As ULong padding = 64 - ((l +1) Mod (512 \ 8)) ' 512 \ 8 = 64 char.
' check if we have enough room for inserting the length
If padding < 8 Then padding = padding + 64
message = message + String(padding, Chr(0)) ' adjust length
Dim As ULong l1 = Len(message) ' new length
l = l * 8 ' orignal length in bits
' create ubyte ptr to point to l ( = length in bits)
Dim As UByte Ptr ub_ptr = Cast(UByte Ptr, @l)
For i = 0 To 7 'copy length of message to the last 8 bytes
message[l1 -1 - i] = ub_ptr[i]
Next
Dim As UInteger<32> A, B, C, D, E, k, temp, W(0 To 79)
Dim As UInteger<32> H0 = &H67452301
Dim As UInteger<32> H1 = &HEFCDAB89
Dim As UInteger<32> H2 = &H98BADCFE
Dim As UInteger<32> H3 = &H10325476
Dim As UInteger<32> H4 = &HC3D2E1F0
For j = 0 To (l1 -1) \ 64 ' split into block of 64 bytes
ww1 = Cast(Ubyte Ptr, @message[j * 64])
ww4 = Cast(UInteger<32> Ptr, @message[j * 64])
For i = 0 To 60 Step 4 'little endian -> big endian
Swap ww1[i ], ww1[i +3]
Swap ww1[i +1], ww1[i +2]
Next
For i = 0 To 15 ' copy the 16 32bit block into the array
W(i) = ww4[i]
Next
For i = 16 To 79 ' fill the rest of the array
temp = W(i -3) Xor W(i -8) Xor W(i -14) Xor W(i -16)
temp = temp Shl 1 + temp Shr 31
W(i) = temp
Next
A = h0 : B = h1 : C = h2 : D = h3 : E = h4
For i = 0 To 79
Select Case As Const i
Case 0 To 19
temp = (B And C) or ((Not B) And D)
k = &H5A827999
Case 20 To 39
temp = B Xor C Xor D
k = &H6ED9EBA1
Case 40 To 59
temp = (B And C) Or (B And D) Or (C And D)
k = &H8F1BBCDC
Case 60 To 79
temp = B Xor C Xor D
k = &hCA62C1D6
End Select
temp = A Shl 5 + A Shr 27 + temp + E + k + W(i)
E = D
D = C
C = (B Shl 30) or (B Shr 2)
B = A
A = temp
Next
h0 += A : h1 += B : h2 += C : h3 += D : h4 += E
Next
Return Hex(h0, 8) + Hex(h1, 8) + Hex(h2, 8) + Hex(h3, 8) + Hex(h4, 8)
End Function
' ------=< MAIN >=------
Dim As String test = "Rosetta Code"
Print test; " => "; SHA_1(test)
' empty keyboard buffer
While InKey <> "" : Wend
Print : Print "hit any key to end program"
Sleep
End |
http://rosettacode.org/wiki/Seven-sided_dice_from_five-sided_dice | Seven-sided dice from five-sided dice | Task
(Given an equal-probability generator of one of the integers 1 to 5
as dice5), create dice7 that generates a pseudo-random integer from
1 to 7 in equal probability using only dice5 as a source of random
numbers, and check the distribution for at least one million calls using the function created in Simple Random Distribution Checker.
Implementation suggestion:
dice7 might call dice5 twice, re-call if four of the 25
combinations are given, otherwise split the other 21 combinations
into 7 groups of three, and return the group index from the rolls.
(Task adapted from an answer here)
| #Go | Go | package main
import (
"fmt"
"math"
"math/rand"
"time"
)
// "given"
func dice5() int {
return rand.Intn(5) + 1
}
// function specified by task "Seven-sided dice from five-sided dice"
func dice7() (i int) {
for {
i = 5*dice5() + dice5()
if i < 27 {
break
}
}
return (i / 3) - 1
}
// function specified by task "Verify distribution uniformity/Naive"
//
// Parameter "f" is expected to return a random integer in the range 1..n.
// (Values out of range will cause an unceremonious crash.)
// "Max" is returned as an "indication of distribution achieved."
// It is the maximum delta observed from the count representing a perfectly
// uniform distribution.
// Also returned is a boolean, true if "max" is less than threshold
// parameter "delta."
func distCheck(f func() int, n int,
repeats int, delta float64) (max float64, flatEnough bool) {
count := make([]int, n)
for i := 0; i < repeats; i++ {
count[f()-1]++
}
expected := float64(repeats) / float64(n)
for _, c := range count {
max = math.Max(max, math.Abs(float64(c)-expected))
}
return max, max < delta
}
// Driver, produces output satisfying both tasks.
func main() {
rand.Seed(time.Now().UnixNano())
const calls = 1000000
max, flatEnough := distCheck(dice7, 7, calls, 500)
fmt.Println("Max delta:", max, "Flat enough:", flatEnough)
max, flatEnough = distCheck(dice7, 7, calls, 500)
fmt.Println("Max delta:", max, "Flat enough:", flatEnough)
} |
http://rosettacode.org/wiki/Sexy_primes | Sexy primes |
This page uses content from Wikipedia. The original article was at Sexy_prime. 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)
In mathematics, sexy primes are prime numbers that differ from each other by six.
For example, the numbers 5 and 11 are both sexy primes, because 11 minus 6 is 5.
The term "sexy prime" is a pun stemming from the Latin word for six: sex.
Sexy prime pairs: Sexy prime pairs are groups of two primes that differ by 6. e.g. (5 11), (7 13), (11 17)
See sequences: OEIS:A023201 and OEIS:A046117
Sexy prime triplets: Sexy prime triplets are groups of three primes where each differs from the next by 6. e.g. (5 11 17), (7 13 19), (17 23 29)
See sequences: OEIS:A046118, OEIS:A046119 and OEIS:A046120
Sexy prime quadruplets: Sexy prime quadruplets are groups of four primes where each differs from the next by 6. e.g. (5 11 17 23), (11 17 23 29)
See sequences: OEIS:A023271, OEIS:A046122, OEIS:A046123 and OEIS:A046124
Sexy prime quintuplets: Sexy prime quintuplets are groups of five primes with a common difference of 6. One of the terms must be divisible by 5, because 5 and 6 are relatively prime. Thus, the only possible sexy prime quintuplet is (5 11 17 23 29)
Task
For each of pairs, triplets, quadruplets and quintuplets, Find and display the count of each group type of sexy primes less than one million thirty-five (1,000,035).
Display at most the last 5, less than one million thirty-five, of each sexy prime group type.
Find and display the count of the unsexy primes less than one million thirty-five.
Find and display the last 10 unsexy primes less than one million thirty-five.
Note that 1000033 SHOULD NOT be counted in the pair count. It is sexy, but not in a pair within the limit. However, it also SHOULD NOT be listed in the unsexy primes since it is sexy.
| #Phix | Phix | function create_sieve(integer limit)
sequence sieve = repeat(true,limit)
sieve[1] = false
for i=4 to limit by 2 do
sieve[i] = false
end for
for p=3 to floor(sqrt(limit)) by 2 do
integer p2 = p*p
if sieve[p2] then
for k=p2 to limit by p*2 do
sieve[k] = false
end for
end if
end for
return sieve
end function
constant lim = 1000035,
--constant lim = 100, -- (this works too)
limit = lim-(and_bits(lim,1)=0), -- (limit must be odd)
sieve = create_sieve(limit+6) -- (+6 to check for sexiness)
sequence sets = repeat({},5), -- (unsexy,pairs,trips,quads,quins)
limits = {10,5,4,3,1},
counts = 1&repeat(0,4) -- (2 is an unsexy prime)
integer total = 1 -- ""
for i=limit to 3 by -2 do -- (this loop skips 2)
if sieve[i] then
total += 1
if sieve[i+6]=false and (i-6<0 or sieve[i-6]=false) then
counts[1] += 1 -- unsexy
if length(sets[1])<limits[1] then
sets[1] = prepend(sets[1],i)
end if
else
sequence set = {i}
for j=i-6 to 3 by -6 do
if j<=0 or sieve[j]=false then exit end if
set = prepend(set,j)
integer l = length(set)
if length(sets[l])<limits[l] then
sets[l] = prepend(sets[l],set)
end if
counts[l] += 1
end for
end if
end if
end for
if length(sets[1])<limits[1] then
sets[1] = prepend(sets[1],2) -- (as 2 skipped above)
end if
constant fmt = """
Of %,d primes less than %,d there are:
%,d unsexy primes, the last %d being %s
%,d pairs, the last %d being %s
%,d triplets, the last %d being %s
%,d quadruplets, the last %d being %s
%,d quintuplet, the last %d being %s
"""
sequence results = {total,lim,
0,0,"",
0,0,"",
0,0,"",
0,0,"",
0,0,""}
for i=1 to 5 do
results[i*3..i*3+2] = {counts[i],length(sets[i]),sprint(sets[i])}
end for
printf(1,fmt,results)
|
http://rosettacode.org/wiki/Show_ASCII_table | Show ASCII table | Task
Show the ASCII character set from values 32 to 127 (decimal) in a table format.
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
| #Excel | Excel | asciiTable
=LAMBDA(i,
justifyRight(3)(" ")(i) & ": " & (
justifyRight(
3
)(" ")(
IF(32 = i,
"Spc",
IF(127 = i,
"Del",
CHAR(i)
)
)
)
)
)(
SEQUENCE(16, 6, 32, 1)
) |
http://rosettacode.org/wiki/Sierpinski_triangle | Sierpinski triangle | Task
Produce an ASCII representation of a Sierpinski triangle of order N.
Example
The Sierpinski triangle of order 4 should look like this:
*
* *
* *
* * * *
* *
* * * *
* * * *
* * * * * * * *
* *
* * * *
* * * *
* * * * * * * *
* * * *
* * * * * * * *
* * * * * * * *
* * * * * * * * * * * * * * * *
Related tasks
Sierpinski triangle/Graphical for graphics images of this pattern.
Sierpinski carpet
| #NetRexx | NetRexx | /* NetRexx */
options replace format comments java crossref symbols nobinary
numeric digits 1000
runSample(arg)
return
-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
method runSample(arg) public static
BLACK_UPPOINTING_TRIANGLE = '\u25b2'
parse arg ordr filr .
if ordr = '' | ordr = '.' then ordr = 4
if filr = '' | filr = '.' then filler = BLACK_UPPOINTING_TRIANGLE
else filler = filr
drawSierpinskiTriangle(ordr, filler)
return
-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
method drawSierpinskiTriangle(ordr, filler = Rexx '^') public static
n = 1 * (2 ** ordr)
line = ' '.copies(2 * n)
line = line.overlay(filler, n + 1) -- set the top point of the triangle
loop row = 1 to n -- NetRexx arrays, lists etc. index from 1
say line.strip('t')
u = filler
loop col = 2 + n - row to n + row
cl = line.substr(col - 1, 1)
cr = line.substr(col + 1, 1)
if cl == cr then t = ' '
else t = filler
line = line.overlay(u, col - 1)
u = t
end col
j2 = n + row - 1
j3 = n + row
line = line.overlay(t, j2 + 1)
line = line.overlay(filler, j3 + 1)
end row
return
|
http://rosettacode.org/wiki/Sierpinski_carpet | Sierpinski carpet | Task
Produce a graphical or ASCII-art representation of a Sierpinski carpet of order N.
For example, the Sierpinski carpet of order 3 should look like this:
###########################
# ## ## ## ## ## ## ## ## #
###########################
### ###### ###### ###
# # # ## # # ## # # #
### ###### ###### ###
###########################
# ## ## ## ## ## ## ## ## #
###########################
######### #########
# ## ## # # ## ## #
######### #########
### ### ### ###
# # # # # # # #
### ### ### ###
######### #########
# ## ## # # ## ## #
######### #########
###########################
# ## ## ## ## ## ## ## ## #
###########################
### ###### ###### ###
# # # ## # # ## # # #
### ###### ###### ###
###########################
# ## ## ## ## ## ## ## ## #
###########################
The use of the # character is not rigidly required for ASCII art.
The important requirement is the placement of whitespace and non-whitespace characters.
Related task
Sierpinski triangle
| #Go | Go | package main
import (
"fmt"
"strings"
"unicode/utf8"
)
var order = 3
var grain = "#"
func main() {
carpet := []string{grain}
for ; order > 0; order-- {
// repeat expression allows for multiple character
// grain and for multi-byte UTF-8 characters.
hole := strings.Repeat(" ", utf8.RuneCountInString(carpet[0]))
middle := make([]string, len(carpet))
for i, s := range carpet {
middle[i] = s + hole + s
carpet[i] = strings.Repeat(s, 3)
}
carpet = append(append(carpet, middle...), carpet...)
}
for _, r := range carpet {
fmt.Println(r)
}
} |
http://rosettacode.org/wiki/Short-circuit_evaluation | Short-circuit evaluation | Control Structures
These are examples of control structures. You may also be interested in:
Conditional structures
Exceptions
Flow-control structures
Loops
Assume functions a and b return boolean values, and further, the execution of function b takes considerable resources without side effects, and is to be minimized.
If we needed to compute the conjunction (and):
x = a() and b()
Then it would be best to not compute the value of b() if the value of a() is computed as false, as the value of x can then only ever be false.
Similarly, if we needed to compute the disjunction (or):
y = a() or b()
Then it would be best to not compute the value of b() if the value of a() is computed as true, as the value of y can then only ever be true.
Some languages will stop further computation of boolean equations as soon as the result is known, so-called short-circuit evaluation of boolean expressions
Task
Create two functions named a and b, that take and return the same boolean value.
The functions should also print their name whenever they are called.
Calculate and assign the values of the following equations to a variable in such a way that function b is only called when necessary:
x = a(i) and b(j)
y = a(i) or b(j)
If the language does not have short-circuit evaluation, this might be achieved with nested if statements.
| #JavaScript | JavaScript | (function () {
'use strict';
function a(bool) {
console.log('a -->', bool);
return bool;
}
function b(bool) {
console.log('b -->', bool);
return bool;
}
var x = a(false) && b(true),
y = a(true) || b(false),
z = true ? a(true) : b(false);
return [x, y, z];
})(); |
http://rosettacode.org/wiki/Short-circuit_evaluation | Short-circuit evaluation | Control Structures
These are examples of control structures. You may also be interested in:
Conditional structures
Exceptions
Flow-control structures
Loops
Assume functions a and b return boolean values, and further, the execution of function b takes considerable resources without side effects, and is to be minimized.
If we needed to compute the conjunction (and):
x = a() and b()
Then it would be best to not compute the value of b() if the value of a() is computed as false, as the value of x can then only ever be false.
Similarly, if we needed to compute the disjunction (or):
y = a() or b()
Then it would be best to not compute the value of b() if the value of a() is computed as true, as the value of y can then only ever be true.
Some languages will stop further computation of boolean equations as soon as the result is known, so-called short-circuit evaluation of boolean expressions
Task
Create two functions named a and b, that take and return the same boolean value.
The functions should also print their name whenever they are called.
Calculate and assign the values of the following equations to a variable in such a way that function b is only called when necessary:
x = a(i) and b(j)
y = a(i) or b(j)
If the language does not have short-circuit evaluation, this might be achieved with nested if statements.
| #jq | jq | def a(x): " a(\(x))" | stderr | x;
def b(y): " b(\(y))" | stderr | y;
"and:", (a(true) and b(true)),
"or:", (a(true) or b(true)),
"and:", (a(false) and b(true)),
"or:", (a(false) or b(true)) |
http://rosettacode.org/wiki/Set_puzzle | Set puzzle | Set Puzzles are created with a deck of cards from the Set Game™. The object of the puzzle is to find sets of 3 cards in a rectangle of cards that have been dealt face up.
There are 81 cards in a deck.
Each card contains a unique variation of the following four features: color, symbol, number and shading.
there are three colors:
red, green, purple
there are three symbols:
oval, squiggle, diamond
there is a number of symbols on the card:
one, two, three
there are three shadings:
solid, open, striped
Three cards form a set if each feature is either the same on each card, or is different on each card. For instance: all 3 cards are red, all 3 cards have a different symbol, all 3 cards have a different number of symbols, all 3 cards are striped.
There are two degrees of difficulty: basic and advanced. The basic mode deals 9 cards, that contain exactly 4 sets; the advanced mode deals 12 cards that contain exactly 6 sets.
When creating sets you may use the same card more than once.
Task
Write code that deals the cards (9 or 12, depending on selected mode) from a shuffled deck in which the total number of sets that could be found is 4 (or 6, respectively); and print the contents of the cards and the sets.
For instance:
DEALT 9 CARDS:
green, one, oval, striped
green, one, diamond, open
green, one, diamond, striped
green, one, diamond, solid
purple, one, diamond, open
purple, two, squiggle, open
purple, three, oval, open
red, three, oval, open
red, three, diamond, solid
CONTAINING 4 SETS:
green, one, oval, striped
purple, two, squiggle, open
red, three, diamond, solid
green, one, diamond, open
green, one, diamond, striped
green, one, diamond, solid
green, one, diamond, open
purple, two, squiggle, open
red, three, oval, open
purple, one, diamond, open
purple, two, squiggle, open
purple, three, oval, open
| #J | J | require 'stats/base'
Number=: ;:'one two three'
Colour=: ;:'red green purple'
Fill=: ;:'solid open striped'
Symbol=: ;:'oval squiggle diamond'
Features=: Number ; Colour ; Fill ;< Symbol
Deck=: > ; <"1 { i.@#&.> Features
sayCards=: (', ' joinstring Features {&>~ ])"1
drawRandom=: ] {~ (? #)
isSet=: *./@:(1 3 e.~ [: #@~."1 |:)"2
getSets=: [: (] #~ isSet) ] {~ 3 comb #
countSets=: #@:getSets
set_puzzle=: verb define
target=. <. -: y
whilst. target ~: countSets Hand do.
Hand=. y drawRandom Deck
end.
echo 'Dealt ',(": y),' Cards:'
echo sayCards sort Hand
echo LF,'Found ',(":target),' Sets:'
echo sayCards sort"2 getSets Hand
) |
http://rosettacode.org/wiki/Set_puzzle | Set puzzle | Set Puzzles are created with a deck of cards from the Set Game™. The object of the puzzle is to find sets of 3 cards in a rectangle of cards that have been dealt face up.
There are 81 cards in a deck.
Each card contains a unique variation of the following four features: color, symbol, number and shading.
there are three colors:
red, green, purple
there are three symbols:
oval, squiggle, diamond
there is a number of symbols on the card:
one, two, three
there are three shadings:
solid, open, striped
Three cards form a set if each feature is either the same on each card, or is different on each card. For instance: all 3 cards are red, all 3 cards have a different symbol, all 3 cards have a different number of symbols, all 3 cards are striped.
There are two degrees of difficulty: basic and advanced. The basic mode deals 9 cards, that contain exactly 4 sets; the advanced mode deals 12 cards that contain exactly 6 sets.
When creating sets you may use the same card more than once.
Task
Write code that deals the cards (9 or 12, depending on selected mode) from a shuffled deck in which the total number of sets that could be found is 4 (or 6, respectively); and print the contents of the cards and the sets.
For instance:
DEALT 9 CARDS:
green, one, oval, striped
green, one, diamond, open
green, one, diamond, striped
green, one, diamond, solid
purple, one, diamond, open
purple, two, squiggle, open
purple, three, oval, open
red, three, oval, open
red, three, diamond, solid
CONTAINING 4 SETS:
green, one, oval, striped
purple, two, squiggle, open
red, three, diamond, solid
green, one, diamond, open
green, one, diamond, striped
green, one, diamond, solid
green, one, diamond, open
purple, two, squiggle, open
red, three, oval, open
purple, one, diamond, open
purple, two, squiggle, open
purple, three, oval, open
| #Java | Java | import java.util.*;
public class SetPuzzle {
enum Color {
GREEN(0), PURPLE(1), RED(2);
private Color(int v) {
val = v;
}
public final int val;
}
enum Number {
ONE(0), TWO(1), THREE(2);
private Number(int v) {
val = v;
}
public final int val;
}
enum Symbol {
OVAL(0), DIAMOND(1), SQUIGGLE(2);
private Symbol(int v) {
val = v;
}
public final int val;
}
enum Fill {
OPEN(0), STRIPED(1), SOLID(2);
private Fill(int v) {
val = v;
}
public final int val;
}
private static class Card implements Comparable<Card> {
Color c;
Number n;
Symbol s;
Fill f;
@Override
public String toString() {
return String.format("[Card: %s, %s, %s, %s]", c, n, s, f);
}
@Override
public int compareTo(Card o) {
return (c.val - o.c.val) * 10 + (n.val - o.n.val);
}
}
private static Card[] deck;
public static void main(String[] args) {
deck = new Card[81];
Color[] colors = Color.values();
Number[] numbers = Number.values();
Symbol[] symbols = Symbol.values();
Fill[] fillmodes = Fill.values();
for (int i = 0; i < deck.length; i++) {
deck[i] = new Card();
deck[i].c = colors[i / 27];
deck[i].n = numbers[(i / 9) % 3];
deck[i].s = symbols[(i / 3) % 3];
deck[i].f = fillmodes[i % 3];
}
findSets(12);
}
private static void findSets(int numCards) {
int target = numCards / 2;
Card[] cards;
Card[][] sets = new Card[target][3];
int cnt;
do {
Collections.shuffle(Arrays.asList(deck));
cards = Arrays.copyOfRange(deck, 0, numCards);
cnt = 0;
outer:
for (int i = 0; i < cards.length - 2; i++) {
for (int j = i + 1; j < cards.length - 1; j++) {
for (int k = j + 1; k < cards.length; k++) {
if (validSet(cards[i], cards[j], cards[k])) {
if (cnt < target)
sets[cnt] = new Card[]{cards[i], cards[j], cards[k]};
if (++cnt > target) {
break outer;
}
}
}
}
}
} while (cnt != target);
Arrays.sort(cards);
System.out.printf("GIVEN %d CARDS:\n\n", numCards);
for (Card c : cards) {
System.out.println(c);
}
System.out.println();
System.out.println("FOUND " + target + " SETS:\n");
for (Card[] set : sets) {
for (Card c : set) {
System.out.println(c);
}
System.out.println();
}
}
private static boolean validSet(Card c1, Card c2, Card c3) {
int tot = 0;
tot += (c1.c.val + c2.c.val + c3.c.val) % 3;
tot += (c1.n.val + c2.n.val + c3.n.val) % 3;
tot += (c1.s.val + c2.s.val + c3.s.val) % 3;
tot += (c1.f.val + c2.f.val + c3.f.val) % 3;
return tot == 0;
}
} |
http://rosettacode.org/wiki/SHA-256 | SHA-256 | SHA-256 is the recommended stronger alternative to SHA-1. See FIPS PUB 180-4 for implementation details.
Either by using a dedicated library or implementing the algorithm in your language, show that the SHA-256 digest of the string "Rosetta code" is: 764faf5c61ac315f1497f9dfa542713965b785e5cc2f707d6468d7d1124cdfcf
| #Free_Pascal | Free Pascal | program rosettaCodeSHA256;
uses
SysUtils, DCPsha256;
var
ros: String;
sha256 : TDCP_sha256;
digest : array[0..63] of byte;
i: Integer;
output: String;
begin
ros := 'Rosetta code';
sha256 := TDCP_sha256.Create(nil);
sha256.init;
sha256.UpdateStr(ros);
sha256.Final(digest);
output := '';
for i := 0 to 31 do begin
output := output + intToHex(digest[i], 2);
end;
writeln(lowerCase(output));
end. |
http://rosettacode.org/wiki/Sequence:_smallest_number_greater_than_previous_term_with_exactly_n_divisors | Sequence: smallest number greater than previous term with exactly n divisors | Calculate the sequence where each term an is the smallest natural number greater than the previous term, that has exactly n divisors.
Task
Show here, on this page, at least the first 15 terms of the sequence.
See also
OEIS:A069654
Related tasks
Sequence: smallest number with exactly n divisors
Sequence: nth number with exactly n divisors
| #11l | 11l | F divisors(n)
V divs = [1]
L(ii) 2 .< Int(n ^ 0.5) + 3
I n % ii == 0
divs.append(ii)
divs.append(Int(n / ii))
divs.append(n)
R Array(Set(divs))
F sequence(max_n)
V previous = 0
V n = 0
[Int] r
L
n++
V ii = previous
I n > max_n
L.break
L
ii++
I divisors(ii).len == n
r.append(ii)
previous = ii
L.break
R r
L(item) sequence(15)
print(item) |
http://rosettacode.org/wiki/SHA-1 | SHA-1 | SHA-1 or SHA1 is a one-way hash function;
it computes a 160-bit message digest.
SHA-1 often appears in security protocols; for example,
many HTTPS websites use RSA with SHA-1 to secure their connections.
BitTorrent uses SHA-1 to verify downloads.
Git and Mercurial use SHA-1 digests to identify commits.
A US government standard, FIPS 180-1, defines SHA-1.
Find the SHA-1 message digest for a string of octets. You may either call a SHA-1 library, or implement SHA-1 in your language. Both approaches interest Rosetta Code.
Warning: SHA-1 has known weaknesses. Theoretical attacks may find a collision after 252 operations, or perhaps fewer.
This is much faster than a brute force attack of 280 operations. USgovernment deprecated SHA-1.
For production-grade cryptography, users may consider a stronger alternative, such as SHA-256 (from the SHA-2 family) or the upcoming SHA-3.
| #Frink | Frink | println[messageDigest["Rosetta Code", "SHA-1"]] |
http://rosettacode.org/wiki/SHA-1 | SHA-1 | SHA-1 or SHA1 is a one-way hash function;
it computes a 160-bit message digest.
SHA-1 often appears in security protocols; for example,
many HTTPS websites use RSA with SHA-1 to secure their connections.
BitTorrent uses SHA-1 to verify downloads.
Git and Mercurial use SHA-1 digests to identify commits.
A US government standard, FIPS 180-1, defines SHA-1.
Find the SHA-1 message digest for a string of octets. You may either call a SHA-1 library, or implement SHA-1 in your language. Both approaches interest Rosetta Code.
Warning: SHA-1 has known weaknesses. Theoretical attacks may find a collision after 252 operations, or perhaps fewer.
This is much faster than a brute force attack of 280 operations. USgovernment deprecated SHA-1.
For production-grade cryptography, users may consider a stronger alternative, such as SHA-256 (from the SHA-2 family) or the upcoming SHA-3.
| #Genie | Genie | print Checksum.compute_for_string(ChecksumType.SHA1, "Rosetta code", -1) |
http://rosettacode.org/wiki/Seven-sided_dice_from_five-sided_dice | Seven-sided dice from five-sided dice | Task
(Given an equal-probability generator of one of the integers 1 to 5
as dice5), create dice7 that generates a pseudo-random integer from
1 to 7 in equal probability using only dice5 as a source of random
numbers, and check the distribution for at least one million calls using the function created in Simple Random Distribution Checker.
Implementation suggestion:
dice7 might call dice5 twice, re-call if four of the 25
combinations are given, otherwise split the other 21 combinations
into 7 groups of three, and return the group index from the rolls.
(Task adapted from an answer here)
| #Groovy | Groovy | random = new Random()
int rand5() {
random.nextInt(5) + 1
}
int rand7From5() {
def raw = 25
while (raw > 21) {
raw = 5*(rand5() - 1) + rand5()
}
(raw % 7) + 1
} |
http://rosettacode.org/wiki/Seven-sided_dice_from_five-sided_dice | Seven-sided dice from five-sided dice | Task
(Given an equal-probability generator of one of the integers 1 to 5
as dice5), create dice7 that generates a pseudo-random integer from
1 to 7 in equal probability using only dice5 as a source of random
numbers, and check the distribution for at least one million calls using the function created in Simple Random Distribution Checker.
Implementation suggestion:
dice7 might call dice5 twice, re-call if four of the 25
combinations are given, otherwise split the other 21 combinations
into 7 groups of three, and return the group index from the rolls.
(Task adapted from an answer here)
| #Haskell | Haskell | import System.Random
import Data.List
sevenFrom5Dice = do
d51 <- randomRIO(1,5) :: IO Int
d52 <- randomRIO(1,5) :: IO Int
let d7 = 5*d51+d52-6
if d7 > 20 then sevenFrom5Dice
else return $ 1 + d7 `mod` 7 |
http://rosettacode.org/wiki/Sexy_primes | Sexy primes |
This page uses content from Wikipedia. The original article was at Sexy_prime. 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)
In mathematics, sexy primes are prime numbers that differ from each other by six.
For example, the numbers 5 and 11 are both sexy primes, because 11 minus 6 is 5.
The term "sexy prime" is a pun stemming from the Latin word for six: sex.
Sexy prime pairs: Sexy prime pairs are groups of two primes that differ by 6. e.g. (5 11), (7 13), (11 17)
See sequences: OEIS:A023201 and OEIS:A046117
Sexy prime triplets: Sexy prime triplets are groups of three primes where each differs from the next by 6. e.g. (5 11 17), (7 13 19), (17 23 29)
See sequences: OEIS:A046118, OEIS:A046119 and OEIS:A046120
Sexy prime quadruplets: Sexy prime quadruplets are groups of four primes where each differs from the next by 6. e.g. (5 11 17 23), (11 17 23 29)
See sequences: OEIS:A023271, OEIS:A046122, OEIS:A046123 and OEIS:A046124
Sexy prime quintuplets: Sexy prime quintuplets are groups of five primes with a common difference of 6. One of the terms must be divisible by 5, because 5 and 6 are relatively prime. Thus, the only possible sexy prime quintuplet is (5 11 17 23 29)
Task
For each of pairs, triplets, quadruplets and quintuplets, Find and display the count of each group type of sexy primes less than one million thirty-five (1,000,035).
Display at most the last 5, less than one million thirty-five, of each sexy prime group type.
Find and display the count of the unsexy primes less than one million thirty-five.
Find and display the last 10 unsexy primes less than one million thirty-five.
Note that 1000033 SHOULD NOT be counted in the pair count. It is sexy, but not in a pair within the limit. However, it also SHOULD NOT be listed in the unsexy primes since it is sexy.
| #Prolog | Prolog | sexy_prime_group(1, N, _, [N]):-
is_prime(N),
!.
sexy_prime_group(Size, N, Limit, [N|Group]):-
is_prime(N),
N1 is N + 6,
N1 =< Limit,
S1 is Size - 1,
sexy_prime_group(S1, N1, Limit, Group).
print_sexy_prime_groups(Size, Limit):-
findall(G, (is_prime(P), P =< Limit, sexy_prime_group(Size, P, Limit, G)), Groups),
length(Groups, Len),
writef('Number of groups of size %t is %t\n', [Size, Len]),
last_n(Groups, 5, Len, Last, Last_len),
writef('Last %t groups of size %t: %t\n\n', [Last_len, Size, Last]).
last_n([], _, L, [], L):-!.
last_n([_|List], Max, Length, Last, Last_len):-
Max < Length,
!,
Len1 is Length - 1,
last_n(List, Max, Len1, Last, Last_len).
last_n([E|List], Max, Length, [E|Last], Last_len):-
last_n(List, Max, Length, Last, Last_len).
unsexy(P):-
P1 is P + 6,
\+is_prime(P1),
P2 is P - 6,
\+is_prime(P2).
main(Limit):-
Max is Limit + 6,
find_prime_numbers(Max),
print_sexy_prime_groups(2, Limit),
print_sexy_prime_groups(3, Limit),
print_sexy_prime_groups(4, Limit),
print_sexy_prime_groups(5, Limit),
findall(P, (is_prime(P), P =< Limit, unsexy(P)), Unsexy),
length(Unsexy, Count),
writef('Number of unsexy primes is %t\n', [Count]),
last_n(Unsexy, 10, Count, Last10, _),
writef('Last 10 unsexy primes: %t', [Last10]).
main:-
main(1000035). |
http://rosettacode.org/wiki/Show_ASCII_table | Show ASCII table | Task
Show the ASCII character set from values 32 to 127 (decimal) in a table format.
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
| #Factor | Factor | USING: combinators formatting io kernel math math.ranges
pair-rocket sequences ;
IN: rosetta-code.ascii-table
: row-values ( n -- seq ) [ 32 + ] [ 112 + ] bi 16 <range> ;
: ascii>output ( n -- str )
{ 32 => [ "Spc" ] 127 => [ "Del" ] [ "" 1sequence ] } case ;
: print-row ( n -- )
row-values [ dup ascii>output "%3d : %-3s " printf ] each nl ;
: print-ascii-table ( -- ) 16 <iota> [ print-row ] each ;
MAIN: print-ascii-table |
http://rosettacode.org/wiki/Sierpinski_triangle | Sierpinski triangle | Task
Produce an ASCII representation of a Sierpinski triangle of order N.
Example
The Sierpinski triangle of order 4 should look like this:
*
* *
* *
* * * *
* *
* * * *
* * * *
* * * * * * * *
* *
* * * *
* * * *
* * * * * * * *
* * * *
* * * * * * * *
* * * * * * * *
* * * * * * * * * * * * * * * *
Related tasks
Sierpinski triangle/Graphical for graphics images of this pattern.
Sierpinski carpet
| #Nim | Nim | const size = 1 shl 4 - 1
for y in countdown(size, 0):
for i in 0 .. <y:
stdout.write " "
for x in 0 .. size-y:
if (x and y) != 0:
stdout.write " "
else:
stdout.write "* "
stdout.write "\n" |
http://rosettacode.org/wiki/Sierpinski_carpet | Sierpinski carpet | Task
Produce a graphical or ASCII-art representation of a Sierpinski carpet of order N.
For example, the Sierpinski carpet of order 3 should look like this:
###########################
# ## ## ## ## ## ## ## ## #
###########################
### ###### ###### ###
# # # ## # # ## # # #
### ###### ###### ###
###########################
# ## ## ## ## ## ## ## ## #
###########################
######### #########
# ## ## # # ## ## #
######### #########
### ### ### ###
# # # # # # # #
### ### ### ###
######### #########
# ## ## # # ## ## #
######### #########
###########################
# ## ## ## ## ## ## ## ## #
###########################
### ###### ###### ###
# # # ## # # ## # # #
### ###### ###### ###
###########################
# ## ## ## ## ## ## ## ## #
###########################
The use of the # character is not rigidly required for ASCII art.
The important requirement is the placement of whitespace and non-whitespace characters.
Related task
Sierpinski triangle
| #Groovy | Groovy | def base3 = { BigInteger i -> i.toString(3) }
def sierpinskiCarpet = { int order ->
StringBuffer sb = new StringBuffer()
def positions = 0..<(3**order)
def digits = 0..<([order,1].max())
positions.each { i ->
String i3 = base3(i).padLeft(order, '0')
positions.each { j ->
String j3 = base3(j).padLeft(order, '0')
sb << (digits.any{ i3[it] == '1' && j3[it] == '1' } ? ' ' : order.toString().padRight(2) )
}
sb << '\n'
}
sb.toString()
} |
http://rosettacode.org/wiki/Short-circuit_evaluation | Short-circuit evaluation | Control Structures
These are examples of control structures. You may also be interested in:
Conditional structures
Exceptions
Flow-control structures
Loops
Assume functions a and b return boolean values, and further, the execution of function b takes considerable resources without side effects, and is to be minimized.
If we needed to compute the conjunction (and):
x = a() and b()
Then it would be best to not compute the value of b() if the value of a() is computed as false, as the value of x can then only ever be false.
Similarly, if we needed to compute the disjunction (or):
y = a() or b()
Then it would be best to not compute the value of b() if the value of a() is computed as true, as the value of y can then only ever be true.
Some languages will stop further computation of boolean equations as soon as the result is known, so-called short-circuit evaluation of boolean expressions
Task
Create two functions named a and b, that take and return the same boolean value.
The functions should also print their name whenever they are called.
Calculate and assign the values of the following equations to a variable in such a way that function b is only called when necessary:
x = a(i) and b(j)
y = a(i) or b(j)
If the language does not have short-circuit evaluation, this might be achieved with nested if statements.
| #Julia | Julia | a(x) = (println("\t# Called a($x)"); return x)
b(x) = (println("\t# Called b($x)"); return x)
for i in [true,false], j in [true, false]
println("\nCalculating: x = a($i) && b($j)"); x = a(i) && b(j)
println("\tResult: x = $x")
println("\nCalculating: y = a($i) || b($j)"); y = a(i) || b(j)
println("\tResult: y = $y")
end |
http://rosettacode.org/wiki/Short-circuit_evaluation | Short-circuit evaluation | Control Structures
These are examples of control structures. You may also be interested in:
Conditional structures
Exceptions
Flow-control structures
Loops
Assume functions a and b return boolean values, and further, the execution of function b takes considerable resources without side effects, and is to be minimized.
If we needed to compute the conjunction (and):
x = a() and b()
Then it would be best to not compute the value of b() if the value of a() is computed as false, as the value of x can then only ever be false.
Similarly, if we needed to compute the disjunction (or):
y = a() or b()
Then it would be best to not compute the value of b() if the value of a() is computed as true, as the value of y can then only ever be true.
Some languages will stop further computation of boolean equations as soon as the result is known, so-called short-circuit evaluation of boolean expressions
Task
Create two functions named a and b, that take and return the same boolean value.
The functions should also print their name whenever they are called.
Calculate and assign the values of the following equations to a variable in such a way that function b is only called when necessary:
x = a(i) and b(j)
y = a(i) or b(j)
If the language does not have short-circuit evaluation, this might be achieved with nested if statements.
| #Kotlin | Kotlin | // version 1.1.2
fun a(v: Boolean): Boolean {
println("'a' called")
return v
}
fun b(v: Boolean): Boolean {
println("'b' called")
return v
}
fun main(args: Array<String>){
val pairs = arrayOf(Pair(true, true), Pair(true, false), Pair(false, true), Pair(false, false))
for (pair in pairs) {
val x = a(pair.first) && b(pair.second)
println("${pair.first} && ${pair.second} = $x")
val y = a(pair.first) || b(pair.second)
println("${pair.first} || ${pair.second} = $y")
println()
}
} |
http://rosettacode.org/wiki/Set_puzzle | Set puzzle | Set Puzzles are created with a deck of cards from the Set Game™. The object of the puzzle is to find sets of 3 cards in a rectangle of cards that have been dealt face up.
There are 81 cards in a deck.
Each card contains a unique variation of the following four features: color, symbol, number and shading.
there are three colors:
red, green, purple
there are three symbols:
oval, squiggle, diamond
there is a number of symbols on the card:
one, two, three
there are three shadings:
solid, open, striped
Three cards form a set if each feature is either the same on each card, or is different on each card. For instance: all 3 cards are red, all 3 cards have a different symbol, all 3 cards have a different number of symbols, all 3 cards are striped.
There are two degrees of difficulty: basic and advanced. The basic mode deals 9 cards, that contain exactly 4 sets; the advanced mode deals 12 cards that contain exactly 6 sets.
When creating sets you may use the same card more than once.
Task
Write code that deals the cards (9 or 12, depending on selected mode) from a shuffled deck in which the total number of sets that could be found is 4 (or 6, respectively); and print the contents of the cards and the sets.
For instance:
DEALT 9 CARDS:
green, one, oval, striped
green, one, diamond, open
green, one, diamond, striped
green, one, diamond, solid
purple, one, diamond, open
purple, two, squiggle, open
purple, three, oval, open
red, three, oval, open
red, three, diamond, solid
CONTAINING 4 SETS:
green, one, oval, striped
purple, two, squiggle, open
red, three, diamond, solid
green, one, diamond, open
green, one, diamond, striped
green, one, diamond, solid
green, one, diamond, open
purple, two, squiggle, open
red, three, oval, open
purple, one, diamond, open
purple, two, squiggle, open
purple, three, oval, open
| #Julia | Julia | using Random, IterTools, Combinatorics
function SetGameTM(basic = true)
drawsize = basic ? 9 : 12
setsneeded = div(drawsize, 2)
setsof3 = Vector{Vector{NTuple{4, String}}}()
draw = Vector{NTuple{4, String}}()
deck = collect(Iterators.product(["red", "green", "purple"], ["one", "two", "three"],
["oval", "squiggle", "diamond"], ["solid", "open", "striped"]))
while length(setsof3) != setsneeded
empty!(draw)
empty!(setsof3)
map(x -> push!(draw, x), shuffle(deck)[1:drawsize])
for threecards in combinations(draw, 3)
canuse = true
for i in 1:4
u = length(unique(map(x->x[i], threecards)))
if u != 3 && u != 1
canuse = false
end
end
if canuse
push!(setsof3, threecards)
end
end
end
println("Dealt $drawsize cards:")
for card in draw
println(" $card")
end
println("\nFormed these cards into $setsneeded sets:")
for set in setsof3
for card in set
println(" $card")
end
println()
end
end
SetGameTM()
SetGameTM(false)
|
http://rosettacode.org/wiki/Set_puzzle | Set puzzle | Set Puzzles are created with a deck of cards from the Set Game™. The object of the puzzle is to find sets of 3 cards in a rectangle of cards that have been dealt face up.
There are 81 cards in a deck.
Each card contains a unique variation of the following four features: color, symbol, number and shading.
there are three colors:
red, green, purple
there are three symbols:
oval, squiggle, diamond
there is a number of symbols on the card:
one, two, three
there are three shadings:
solid, open, striped
Three cards form a set if each feature is either the same on each card, or is different on each card. For instance: all 3 cards are red, all 3 cards have a different symbol, all 3 cards have a different number of symbols, all 3 cards are striped.
There are two degrees of difficulty: basic and advanced. The basic mode deals 9 cards, that contain exactly 4 sets; the advanced mode deals 12 cards that contain exactly 6 sets.
When creating sets you may use the same card more than once.
Task
Write code that deals the cards (9 or 12, depending on selected mode) from a shuffled deck in which the total number of sets that could be found is 4 (or 6, respectively); and print the contents of the cards and the sets.
For instance:
DEALT 9 CARDS:
green, one, oval, striped
green, one, diamond, open
green, one, diamond, striped
green, one, diamond, solid
purple, one, diamond, open
purple, two, squiggle, open
purple, three, oval, open
red, three, oval, open
red, three, diamond, solid
CONTAINING 4 SETS:
green, one, oval, striped
purple, two, squiggle, open
red, three, diamond, solid
green, one, diamond, open
green, one, diamond, striped
green, one, diamond, solid
green, one, diamond, open
purple, two, squiggle, open
red, three, oval, open
purple, one, diamond, open
purple, two, squiggle, open
purple, three, oval, open
| #Kotlin | Kotlin | // version 1.1.3
import java.util.Collections.shuffle
enum class Color { RED, GREEN, PURPLE }
enum class Symbol { OVAL, SQUIGGLE, DIAMOND }
enum class Number { ONE, TWO, THREE }
enum class Shading { SOLID, OPEN, STRIPED }
enum class Degree { BASIC, ADVANCED }
class Card(
val color: Color,
val symbol: Symbol,
val number: Number,
val shading: Shading
) : Comparable<Card> {
private val value =
color.ordinal * 27 + symbol.ordinal * 9 + number.ordinal * 3 + shading.ordinal
override fun compareTo(other: Card) = value.compareTo(other.value)
override fun toString() = (
color.name.padEnd(8) +
symbol.name.padEnd(10) +
number.name.padEnd(7) +
shading.name.padEnd(7)
).toLowerCase()
companion object {
val zero = Card(Color.RED, Symbol.OVAL, Number.ONE, Shading.SOLID)
}
}
fun createDeck() =
List<Card>(81) {
val col = Color.values() [it / 27]
val sym = Symbol.values() [it / 9 % 3]
val num = Number.values() [it / 3 % 3]
val shd = Shading.values()[it % 3]
Card(col, sym, num, shd)
}
fun playGame(degree: Degree) {
val deck = createDeck()
val nCards = if (degree == Degree.BASIC) 9 else 12
val nSets = nCards / 2
val sets = Array(nSets) { Array(3) { Card.zero } }
var hand: Array<Card>
outer@ while (true) {
shuffle(deck)
hand = deck.take(nCards).toTypedArray()
var count = 0
for (i in 0 until hand.size - 2) {
for (j in i + 1 until hand.size - 1) {
for (k in j + 1 until hand.size) {
val trio = arrayOf(hand[i], hand[j], hand[k])
if (isSet(trio)) {
sets[count++] = trio
if (count == nSets) break@outer
}
}
}
}
}
hand.sort()
println("DEALT $nCards CARDS:\n")
println(hand.joinToString("\n"))
println("\nCONTAINING $nSets SETS:\n")
for (s in sets) {
s.sort()
println(s.joinToString("\n"))
println()
}
}
fun isSet(trio: Array<Card>): Boolean {
val r1 = trio.sumBy { it.color.ordinal } % 3
val r2 = trio.sumBy { it.symbol.ordinal } % 3
val r3 = trio.sumBy { it.number.ordinal } % 3
val r4 = trio.sumBy { it.shading.ordinal } % 3
return (r1 + r2 + r3 + r4) == 0
}
fun main(args: Array<String>) {
playGame(Degree.BASIC)
println()
playGame(Degree.ADVANCED)
} |
http://rosettacode.org/wiki/SHA-256 | SHA-256 | SHA-256 is the recommended stronger alternative to SHA-1. See FIPS PUB 180-4 for implementation details.
Either by using a dedicated library or implementing the algorithm in your language, show that the SHA-256 digest of the string "Rosetta code" is: 764faf5c61ac315f1497f9dfa542713965b785e5cc2f707d6468d7d1124cdfcf
| #FreeBASIC | FreeBASIC | ' version 20-10-2016
' FIPS PUB 180-4
' compile with: fbc -s console
Function SHA_256(test_str As String) As String
#Macro Ch (x, y, z)
(((x) And (y)) Xor ((Not (x)) And z))
#EndMacro
#Macro Maj (x, y, z)
(((x) And (y)) Xor ((x) And (z)) Xor ((y) And (z)))
#EndMacro
#Macro sigma0 (x)
(((x) Shr 2 Or (x) Shl 30) Xor ((x) Shr 13 Or (x) Shl 19) Xor ((x) Shr 22 Or (x) Shl 10))
#EndMacro
#Macro sigma1 (x)
(((x) Shr 6 Or (x) Shl 26) Xor ((x) Shr 11 Or (x) Shl 21) Xor ((x) Shr 25 Or (x) Shl 7))
#EndMacro
#Macro sigma2 (x)
(((x) Shr 7 Or (x) Shl 25) Xor ((x) Shr 18 Or (x) Shl 14) Xor ((x) Shr 3))
#EndMacro
#Macro sigma3 (x)
(((x) Shr 17 Or (x) Shl 15) Xor ((x) Shr 19 Or (x) Shl 13) Xor ((x) Shr 10))
#EndMacro
Dim As String message = test_str ' strings are passed as ByRef's
Dim As Long i, j
Dim As UByte Ptr ww1
Dim As UInteger<32> Ptr ww4
Dim As ULongInt l = Len(message)
' set the first bit after the message to 1
message = message + Chr(1 Shl 7)
' add one char to the length
Dim As ULong padding = 64 - ((l +1) Mod (512 \ 8)) ' 512 \ 8 = 64 char.
' check if we have enough room for inserting the length
If padding < 8 Then padding = padding + 64
message = message + String(padding, Chr(0)) ' adjust length
Dim As ULong l1 = Len(message) ' new length
l = l * 8 ' orignal length in bits
' create ubyte ptr to point to l ( = length in bits)
Dim As UByte Ptr ub_ptr = Cast(UByte Ptr, @l)
For i = 0 To 7 'copy length of message to the last 8 bytes
message[l1 -1 - i] = ub_ptr[i]
Next
'table of constants
Dim As UInteger<32> K(0 To ...) = _
{ &H428a2f98, &H71374491, &Hb5c0fbcf, &He9b5dba5, &H3956c25b, &H59f111f1, _
&H923f82a4, &Hab1c5ed5, &Hd807aa98, &H12835b01, &H243185be, &H550c7dc3, _
&H72be5d74, &H80deb1fe, &H9bdc06a7, &Hc19bf174, &He49b69c1, &Hefbe4786, _
&H0fc19dc6, &H240ca1cc, &H2de92c6f, &H4a7484aa, &H5cb0a9dc, &H76f988da, _
&H983e5152, &Ha831c66d, &Hb00327c8, &Hbf597fc7, &Hc6e00bf3, &Hd5a79147, _
&H06ca6351, &H14292967, &H27b70a85, &H2e1b2138, &H4d2c6dfc, &H53380d13, _
&H650a7354, &H766a0abb, &H81c2c92e, &H92722c85, &Ha2bfe8a1, &Ha81a664b, _
&Hc24b8b70, &Hc76c51a3, &Hd192e819, &Hd6990624, &Hf40e3585, &H106aa070, _
&H19a4c116, &H1e376c08, &H2748774c, &H34b0bcb5, &H391c0cb3, &H4ed8aa4a, _
&H5b9cca4f, &H682e6ff3, &H748f82ee, &H78a5636f, &H84c87814, &H8cc70208, _
&H90befffa, &Ha4506ceb, &Hbef9a3f7, &Hc67178f2 }
Dim As UInteger<32> h0 = &H6a09e667
Dim As UInteger<32> h1 = &Hbb67ae85
Dim As UInteger<32> h2 = &H3c6ef372
Dim As UInteger<32> h3 = &Ha54ff53a
Dim As UInteger<32> h4 = &H510e527f
Dim As UInteger<32> h5 = &H9b05688c
Dim As UInteger<32> h6 = &H1f83d9ab
Dim As UInteger<32> h7 = &H5be0cd19
Dim As UInteger<32> a, b, c, d, e, f, g, h
Dim As UInteger<32> t1, t2, w(0 To 63)
For j = 0 To (l1 -1) \ 64 ' split into block of 64 bytes
ww1 = Cast(UByte Ptr, @message[j * 64])
ww4 = Cast(UInteger<32> Ptr, @message[j * 64])
For i = 0 To 60 Step 4 'little endian -> big endian
Swap ww1[i ], ww1[i +3]
Swap ww1[i +1], ww1[i +2]
Next
For i = 0 To 15 ' copy the 16 32bit block into the array
W(i) = ww4[i]
Next
For i = 16 To 63 ' fill the rest of the array
w(i) = sigma3(W(i -2)) + W(i -7) + sigma2(W(i -15)) + W(i -16)
Next
a = h0 : b = h1 : c = h2 : d = h3 : e = h4 : f = h5 : g = h6 : h = h7
For i = 0 To 63
t1 = h + sigma1(e) + Ch(e, f, g) + K(i) + W(i)
t2 = sigma0(a) + Maj(a, b, c)
h = g : g = f : f = e
e = d + t1
d = c : c = b : b = a
a = t1 + t2
Next
h0 += a : h1 += b : h2 += c : h3 += d
h4 += e : h5 += f : h6 += g : h7 += h
Next j
Dim As String answer = Hex(h0, 8) + Hex(h1, 8) + Hex(h2, 8) + Hex(h3, 8)
answer += Hex(h4, 8) + Hex(h5, 8) + Hex(h6, 8) + Hex(h7, 8)
Return LCase(answer)
End Function
' ------=< MAIN >=------
Dim As String test = "Rosetta code"
Print test; " => "; SHA_256(test)
' empty keyboard buffer
While Inkey <> "" : Wend
Print : Print "hit any key to end program"
Sleep
End |
http://rosettacode.org/wiki/Sequence:_smallest_number_greater_than_previous_term_with_exactly_n_divisors | Sequence: smallest number greater than previous term with exactly n divisors | Calculate the sequence where each term an is the smallest natural number greater than the previous term, that has exactly n divisors.
Task
Show here, on this page, at least the first 15 terms of the sequence.
See also
OEIS:A069654
Related tasks
Sequence: smallest number with exactly n divisors
Sequence: nth number with exactly n divisors
| #Action.21 | Action! | CARD FUNC CountDivisors(CARD a)
CARD i,count
i=1 count=0
WHILE i*i<=a
DO
IF a MOD i=0 THEN
IF i=a/i THEN
count==+1
ELSE
count==+2
FI
FI
i==+1
OD
RETURN (count)
PROC Main()
CARD a
BYTE i
a=1
FOR i=1 TO 15
DO
WHILE CountDivisors(a)#i
DO
a==+1
OD
IF i>1 THEN
Print(", ")
FI
PrintC(a)
OD
RETURN |
http://rosettacode.org/wiki/SHA-1 | SHA-1 | SHA-1 or SHA1 is a one-way hash function;
it computes a 160-bit message digest.
SHA-1 often appears in security protocols; for example,
many HTTPS websites use RSA with SHA-1 to secure their connections.
BitTorrent uses SHA-1 to verify downloads.
Git and Mercurial use SHA-1 digests to identify commits.
A US government standard, FIPS 180-1, defines SHA-1.
Find the SHA-1 message digest for a string of octets. You may either call a SHA-1 library, or implement SHA-1 in your language. Both approaches interest Rosetta Code.
Warning: SHA-1 has known weaknesses. Theoretical attacks may find a collision after 252 operations, or perhaps fewer.
This is much faster than a brute force attack of 280 operations. USgovernment deprecated SHA-1.
For production-grade cryptography, users may consider a stronger alternative, such as SHA-256 (from the SHA-2 family) or the upcoming SHA-3.
| #Go | Go | package main
import (
"crypto/sha1"
"fmt"
)
func main() {
h := sha1.New()
h.Write([]byte("Rosetta Code"))
fmt.Printf("%x\n", h.Sum(nil))
} |
http://rosettacode.org/wiki/Seven-sided_dice_from_five-sided_dice | Seven-sided dice from five-sided dice | Task
(Given an equal-probability generator of one of the integers 1 to 5
as dice5), create dice7 that generates a pseudo-random integer from
1 to 7 in equal probability using only dice5 as a source of random
numbers, and check the distribution for at least one million calls using the function created in Simple Random Distribution Checker.
Implementation suggestion:
dice7 might call dice5 twice, re-call if four of the 25
combinations are given, otherwise split the other 21 combinations
into 7 groups of three, and return the group index from the rolls.
(Task adapted from an answer here)
| #Icon_and_Unicon | Icon and Unicon |
$include "distribution-checker.icn"
# return a uniformly distributed number from 1 to 7,
# but only using a random number in range 1 to 5.
procedure die_7 ()
while rnd := 5*?5 + ?5 - 6 do {
if rnd < 21 then suspend rnd % 7 + 1
}
end
procedure main ()
if verify_uniform (create (|die_7()), 1000000, 0.01)
then write ("uniform")
else write ("skewed")
end
|
http://rosettacode.org/wiki/Seven-sided_dice_from_five-sided_dice | Seven-sided dice from five-sided dice | Task
(Given an equal-probability generator of one of the integers 1 to 5
as dice5), create dice7 that generates a pseudo-random integer from
1 to 7 in equal probability using only dice5 as a source of random
numbers, and check the distribution for at least one million calls using the function created in Simple Random Distribution Checker.
Implementation suggestion:
dice7 might call dice5 twice, re-call if four of the 25
combinations are given, otherwise split the other 21 combinations
into 7 groups of three, and return the group index from the rolls.
(Task adapted from an answer here)
| #J | J | rollD5=: [: >: ] ?@$ 5: NB. makes a y shape array of 5s, "rolls" the array and increments.
roll2xD5=: [: rollD5 2 ,~ */ NB. rolls D5 twice for each desired D7 roll (y rows, 2 cols)
toBase10=: 5 #. <: NB. decrements and converts rows from base 5 to 10
keepGood=: #~ 21&> NB. compress out values not less than 21
groupin3s=: [: >. >: % 3: NB. increments, divides by 3 and takes ceiling
getD7=: groupin3s@keepGood@toBase10@roll2xD5 |
http://rosettacode.org/wiki/Sexy_primes | Sexy primes |
This page uses content from Wikipedia. The original article was at Sexy_prime. 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)
In mathematics, sexy primes are prime numbers that differ from each other by six.
For example, the numbers 5 and 11 are both sexy primes, because 11 minus 6 is 5.
The term "sexy prime" is a pun stemming from the Latin word for six: sex.
Sexy prime pairs: Sexy prime pairs are groups of two primes that differ by 6. e.g. (5 11), (7 13), (11 17)
See sequences: OEIS:A023201 and OEIS:A046117
Sexy prime triplets: Sexy prime triplets are groups of three primes where each differs from the next by 6. e.g. (5 11 17), (7 13 19), (17 23 29)
See sequences: OEIS:A046118, OEIS:A046119 and OEIS:A046120
Sexy prime quadruplets: Sexy prime quadruplets are groups of four primes where each differs from the next by 6. e.g. (5 11 17 23), (11 17 23 29)
See sequences: OEIS:A023271, OEIS:A046122, OEIS:A046123 and OEIS:A046124
Sexy prime quintuplets: Sexy prime quintuplets are groups of five primes with a common difference of 6. One of the terms must be divisible by 5, because 5 and 6 are relatively prime. Thus, the only possible sexy prime quintuplet is (5 11 17 23 29)
Task
For each of pairs, triplets, quadruplets and quintuplets, Find and display the count of each group type of sexy primes less than one million thirty-five (1,000,035).
Display at most the last 5, less than one million thirty-five, of each sexy prime group type.
Find and display the count of the unsexy primes less than one million thirty-five.
Find and display the last 10 unsexy primes less than one million thirty-five.
Note that 1000033 SHOULD NOT be counted in the pair count. It is sexy, but not in a pair within the limit. However, it also SHOULD NOT be listed in the unsexy primes since it is sexy.
| #PureBasic | PureBasic | DisableDebugger
EnableExplicit
#LIM=1000035
Macro six(mul)
6*mul
EndMacro
Macro form(n)
RSet(Str(n),8)
EndMacro
Macro put(m,g,n)
PrintN(Str(m)+" "+g)
PrintN(n)
EndMacro
Define c1.i=2,c2.i,c3.i,c4.i,c5.i,t1$,t2$,t3$,t4$,t5$,i.i,j.i
Global Dim soe.b(#LIM)
FillMemory(@soe(0),#LIM,#True,#PB_Byte)
If Not OpenConsole("")
End 1
EndIf
For i=2 To Sqr(#LIM)
If soe(i)=#True
j=i*i
While j<=#LIM
soe(j)=#False
j+i
Wend
EndIf
Next
Procedure.s formtab(t$,l.i)
If CountString(t$,~"\n")>l
t$=Mid(t$,FindString(t$,~"\n")+1)
EndIf
ProcedureReturn t$
EndProcedure
For i=3 To #LIM Step 2
If i>5 And i<#LIM-6 And soe(i)&~(soe(i-six(1))|soe(i+six(1)))
c1+1
t1$+form(i)+~"\n"
t1$=formtab(t1$,10)
Continue
EndIf
If i<#LIM-six(1) And soe(i)&soe(i+six(1))
c2+1
t2$+form(i)+form(i+six(1))+~"\n"
t2$=formtab(t2$,5)
EndIf
If i<#LIM-six(2) And soe(i)&soe(i+six(1))&soe(i+six(2))
c3+1
t3$+form(i)+form(i+six(1))+form(i+six(2))+~"\n"
t3$=formtab(t3$,5)
EndIf
If i<#LIM-six(3) And soe(i)&soe(i+six(1))&soe(i+six(2))&soe(i+six(3))
c4+1
t4$+form(i)+form(i+six(1))+form(i+six(2))+form(i+six(3))+~"\n"
t4$=formtab(t4$,5)
EndIf
If i<#LIM-six(4) And soe(i)&soe(i+six(1))&soe(i+six(2))&soe(i+six(3))&soe(i+six(4))
c5+1
t5$+form(i)+form(i+six(1))+form(i+six(2))+form(i+six(3))+form(i+six(4))+~"\n"
t5$=formtab(t5$,5)
EndIf
Next
put(c2,"pairs ending with ...",t2$)
put(c3,"triplets ending with ...",t3$)
put(c4,"quadruplets ending with ...",t4$)
put(c5,"quintuplets ending with ...",t5$)
put(c1,"unsexy primes ending with ...",t1$)
Input() |
http://rosettacode.org/wiki/Show_ASCII_table | Show ASCII table | Task
Show the ASCII character set from values 32 to 127 (decimal) in a table format.
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
| #Forth | Forth | DECIMAL
: ###: ( c -- ) 3 .R ." : " ;
: .CHAR ( c -- )
DUP
CASE
BL OF ###: ." spc" ENDOF
127 OF ###: ." del" ENDOF
DUP ###: EMIT 2 SPACES
ENDCASE
3 SPACES ;
: .ROW ( n2 n1 -- )
CR DO I .CHAR 16 +LOOP ;
: ASCII.TABLE ( -- )
16 0 DO 113 I + 32 I + .ROW LOOP ; |
http://rosettacode.org/wiki/Sierpinski_triangle | Sierpinski triangle | Task
Produce an ASCII representation of a Sierpinski triangle of order N.
Example
The Sierpinski triangle of order 4 should look like this:
*
* *
* *
* * * *
* *
* * * *
* * * *
* * * * * * * *
* *
* * * *
* * * *
* * * * * * * *
* * * *
* * * * * * * *
* * * * * * * *
* * * * * * * * * * * * * * * *
Related tasks
Sierpinski triangle/Graphical for graphics images of this pattern.
Sierpinski carpet
| #OCaml | OCaml | let sierpinski n =
let rec loop down space n =
if n = 0 then
down
else
loop (List.map (fun x -> space ^ x ^ space) down @
List.map (fun x -> x ^ " " ^ x) down)
(space ^ space)
(n - 1)
in loop ["*"] " " n
let () =
List.iter print_endline (sierpinski 4) |
http://rosettacode.org/wiki/Sierpinski_carpet | Sierpinski carpet | Task
Produce a graphical or ASCII-art representation of a Sierpinski carpet of order N.
For example, the Sierpinski carpet of order 3 should look like this:
###########################
# ## ## ## ## ## ## ## ## #
###########################
### ###### ###### ###
# # # ## # # ## # # #
### ###### ###### ###
###########################
# ## ## ## ## ## ## ## ## #
###########################
######### #########
# ## ## # # ## ## #
######### #########
### ### ### ###
# # # # # # # #
### ### ### ###
######### #########
# ## ## # # ## ## #
######### #########
###########################
# ## ## ## ## ## ## ## ## #
###########################
### ###### ###### ###
# # # ## # # ## # # #
### ###### ###### ###
###########################
# ## ## ## ## ## ## ## ## #
###########################
The use of the # character is not rigidly required for ASCII art.
The important requirement is the placement of whitespace and non-whitespace characters.
Related task
Sierpinski triangle
| #Haskell | Haskell | inCarpet :: Int -> Int -> Bool
inCarpet 0 _ = True
inCarpet _ 0 = True
inCarpet x y = not ((xr == 1) && (yr == 1)) && inCarpet xq yq
where ((xq, xr), (yq, yr)) = (x `divMod` 3, y `divMod` 3)
carpet :: Int -> [String]
carpet n = map
(zipWith
(\x y -> if inCarpet x y then '#' else ' ')
[0..3^n-1]
. repeat)
[0..3^n-1]
printCarpet :: Int -> IO ()
printCarpet = mapM_ putStrLn . carpet |
http://rosettacode.org/wiki/Short-circuit_evaluation | Short-circuit evaluation | Control Structures
These are examples of control structures. You may also be interested in:
Conditional structures
Exceptions
Flow-control structures
Loops
Assume functions a and b return boolean values, and further, the execution of function b takes considerable resources without side effects, and is to be minimized.
If we needed to compute the conjunction (and):
x = a() and b()
Then it would be best to not compute the value of b() if the value of a() is computed as false, as the value of x can then only ever be false.
Similarly, if we needed to compute the disjunction (or):
y = a() or b()
Then it would be best to not compute the value of b() if the value of a() is computed as true, as the value of y can then only ever be true.
Some languages will stop further computation of boolean equations as soon as the result is known, so-called short-circuit evaluation of boolean expressions
Task
Create two functions named a and b, that take and return the same boolean value.
The functions should also print their name whenever they are called.
Calculate and assign the values of the following equations to a variable in such a way that function b is only called when necessary:
x = a(i) and b(j)
y = a(i) or b(j)
If the language does not have short-circuit evaluation, this might be achieved with nested if statements.
| #Lambdatalk | Lambdatalk |
{def A {lambda {:bool} :bool}} -> A
{def B {lambda {:bool} :bool}} -> B
{and {A true} {B true}} -> true
{and {A true} {B false}} -> false
{and {A false} {B true}} -> false
{and {A false} {B false}} -> false
{or {A true} {B true}} -> true
{or {A true} {B false}} -> true
{or {A false} {B true}} -> true
{or {A false} {B false}} -> false
|
http://rosettacode.org/wiki/Set_puzzle | Set puzzle | Set Puzzles are created with a deck of cards from the Set Game™. The object of the puzzle is to find sets of 3 cards in a rectangle of cards that have been dealt face up.
There are 81 cards in a deck.
Each card contains a unique variation of the following four features: color, symbol, number and shading.
there are three colors:
red, green, purple
there are three symbols:
oval, squiggle, diamond
there is a number of symbols on the card:
one, two, three
there are three shadings:
solid, open, striped
Three cards form a set if each feature is either the same on each card, or is different on each card. For instance: all 3 cards are red, all 3 cards have a different symbol, all 3 cards have a different number of symbols, all 3 cards are striped.
There are two degrees of difficulty: basic and advanced. The basic mode deals 9 cards, that contain exactly 4 sets; the advanced mode deals 12 cards that contain exactly 6 sets.
When creating sets you may use the same card more than once.
Task
Write code that deals the cards (9 or 12, depending on selected mode) from a shuffled deck in which the total number of sets that could be found is 4 (or 6, respectively); and print the contents of the cards and the sets.
For instance:
DEALT 9 CARDS:
green, one, oval, striped
green, one, diamond, open
green, one, diamond, striped
green, one, diamond, solid
purple, one, diamond, open
purple, two, squiggle, open
purple, three, oval, open
red, three, oval, open
red, three, diamond, solid
CONTAINING 4 SETS:
green, one, oval, striped
purple, two, squiggle, open
red, three, diamond, solid
green, one, diamond, open
green, one, diamond, striped
green, one, diamond, solid
green, one, diamond, open
purple, two, squiggle, open
red, three, oval, open
purple, one, diamond, open
purple, two, squiggle, open
purple, three, oval, open
| #Mathematica.2FWolfram_Language | Mathematica/Wolfram Language | colors = {Red, Green, Purple};
symbols = {"0", "\[TildeTilde]", "\[Diamond]"};
numbers = {1, 2, 3};
shadings = {"\[FilledSquare]", "\[Square]", "\[DoublePrime]"};
validTripleQ[l_List] := Entropy[l] != Entropy[{1, 1, 2}];
validSetQ[cards_List] := And @@ (validTripleQ /@ Transpose[cards]);
allCards = Tuples[{colors, symbols, numbers, shadings}];
deal[{numDeal_, setNum_}] := Module[{cards, count = 0},
While[count != setNum,
cards = RandomSample[allCards, numDeal];
count = Count[Subsets[cards, {3}], _?validSetQ]];
cards];
Row[{Style[#2, #1], #3, #4}] & @@@ deal[{9, 4}] |
http://rosettacode.org/wiki/Set_puzzle | Set puzzle | Set Puzzles are created with a deck of cards from the Set Game™. The object of the puzzle is to find sets of 3 cards in a rectangle of cards that have been dealt face up.
There are 81 cards in a deck.
Each card contains a unique variation of the following four features: color, symbol, number and shading.
there are three colors:
red, green, purple
there are three symbols:
oval, squiggle, diamond
there is a number of symbols on the card:
one, two, three
there are three shadings:
solid, open, striped
Three cards form a set if each feature is either the same on each card, or is different on each card. For instance: all 3 cards are red, all 3 cards have a different symbol, all 3 cards have a different number of symbols, all 3 cards are striped.
There are two degrees of difficulty: basic and advanced. The basic mode deals 9 cards, that contain exactly 4 sets; the advanced mode deals 12 cards that contain exactly 6 sets.
When creating sets you may use the same card more than once.
Task
Write code that deals the cards (9 or 12, depending on selected mode) from a shuffled deck in which the total number of sets that could be found is 4 (or 6, respectively); and print the contents of the cards and the sets.
For instance:
DEALT 9 CARDS:
green, one, oval, striped
green, one, diamond, open
green, one, diamond, striped
green, one, diamond, solid
purple, one, diamond, open
purple, two, squiggle, open
purple, three, oval, open
red, three, oval, open
red, three, diamond, solid
CONTAINING 4 SETS:
green, one, oval, striped
purple, two, squiggle, open
red, three, diamond, solid
green, one, diamond, open
green, one, diamond, striped
green, one, diamond, solid
green, one, diamond, open
purple, two, squiggle, open
red, three, oval, open
purple, one, diamond, open
purple, two, squiggle, open
purple, three, oval, open
| #Nim | Nim | import algorithm, math, random, sequtils, strformat, strutils
type
# Card features.
Number {.pure.} = enum One, Two, Three
Color {.pure.} = enum Red, Green, Purple
Symbol {.pure.} = enum Oval, Squiggle, Diamond
Shading {.pure.} = enum Solid, Open, Striped
# Cards and list of cards.
Card = tuple[number: Number; color: Color; symbol: Symbol; shading: Shading]
Triplet = array[3, Card]
Deck = array[81, Card]
# Game level.
Level {.pure.} = enum Basic = "basic", Advanced = "advanced"
proc `$`(card: Card): string =
## Return the string representation of a card.
toLowerAscii(&"{card.number:<5} {card.color:<6} {card.symbol:<8} {card.shading:<7}")
proc initDeck(): Deck =
## Create a new deck.
var i = 0
for num in Number.low..Number.high:
for col in Color.low..Color.high:
for sym in Symbol.low..Symbol.high:
for sh in Shading.low..Shading.high:
result[i] = (number: num, color: col, symbol: sym, shading: sh)
inc i
proc isSet(triplet: Triplet): bool =
## Check if a triplets of cards is a set.
sum(triplet.mapIt(ord(it.number))) mod 3 == 0 and
sum(triplet.mapIt(ord(it.color))) mod 3 == 0 and
sum(triplet.mapIt(ord(it.symbol))) mod 3 == 0 and
sum(triplet.mapIt(ord(it.shading))) mod 3 == 0
proc playGame(level: Level) =
## Play the game at given level.
var deck = initDeck()
let (nCards, nSets) = if level == Basic: (9, 4) else: (12, 6)
var sets: seq[Triplet]
var hand: seq[Card]
echo &"Playing {level} game: {nCards} cards, {nSets} sets."
block searchHand:
while true:
sets.setLen(0)
deck.shuffle()
hand = deck[0..<nCards]
block countSets:
for i in 0..(nCards - 3):
for j in (i + 1)..(nCards - 2):
for k in (j + 1)..(nCards - 1):
let triplet = [hand[i], hand[j], hand[k]]
if triplet.isSet():
sets.add triplet
if sets.len > nSets:
break countSets # Too much sets. Try with a new hand.
if sets.len == nSets:
break searchHand # Found: terminate search.
# Display the hand and the sets.
echo "\nCards:"
for card in sorted(hand): echo " ", card
echo "\nSets:"
for s in sets:
for card in sorted(s): echo " ", card
echo()
randomize()
playGame(Basic)
echo()
playGame(Advanced) |
http://rosettacode.org/wiki/Sequence:_smallest_number_with_exactly_n_divisors | Sequence: smallest number with exactly n divisors | Calculate the sequence where each term an is the smallest natural number that has exactly n divisors.
Task
Show here, on this page, at least the first 15 terms of the sequence.
Related tasks
Sequence: smallest number greater than previous term with exactly n divisors
Sequence: nth number with exactly n divisors
See also
OEIS:A005179
| #11l | 11l | F divisors(n)
V divs = [1]
L(ii) 2 .< Int(n ^ 0.5) + 3
I n % ii == 0
divs.append(ii)
divs.append(Int(n / ii))
divs.append(n)
R Array(Set(divs))
F sequence(max_n)
V n = 0
[Int] r
L
n++
V ii = 0
I n > max_n
L.break
L
ii++
I divisors(ii).len == n
r.append(ii)
L.break
R r
L(item) sequence(15)
print(item) |
http://rosettacode.org/wiki/SHA-256 | SHA-256 | SHA-256 is the recommended stronger alternative to SHA-1. See FIPS PUB 180-4 for implementation details.
Either by using a dedicated library or implementing the algorithm in your language, show that the SHA-256 digest of the string "Rosetta code" is: 764faf5c61ac315f1497f9dfa542713965b785e5cc2f707d6468d7d1124cdfcf
| #Frink | Frink | println[messageDigest["Rosetta code", "SHA-256"]] |
http://rosettacode.org/wiki/SHA-256 | SHA-256 | SHA-256 is the recommended stronger alternative to SHA-1. See FIPS PUB 180-4 for implementation details.
Either by using a dedicated library or implementing the algorithm in your language, show that the SHA-256 digest of the string "Rosetta code" is: 764faf5c61ac315f1497f9dfa542713965b785e5cc2f707d6468d7d1124cdfcf
| #FunL | FunL | native java.security.MessageDigest
def sha256Java( message ) = map( a -> format('%02x', a), list(MessageDigest.getInstance('SHA-256').digest(message.getBytes('UTF-8'))) ).mkString() |
http://rosettacode.org/wiki/Sequence:_smallest_number_greater_than_previous_term_with_exactly_n_divisors | Sequence: smallest number greater than previous term with exactly n divisors | Calculate the sequence where each term an is the smallest natural number greater than the previous term, that has exactly n divisors.
Task
Show here, on this page, at least the first 15 terms of the sequence.
See also
OEIS:A069654
Related tasks
Sequence: smallest number with exactly n divisors
Sequence: nth number with exactly n divisors
| #Ada | Ada | with Ada.Text_IO;
procedure Show_Sequence is
function Count_Divisors (N : in Natural) return Natural is
Count : Natural := 0;
I : Natural;
begin
I := 1;
while I**2 <= N loop
if N mod I = 0 then
if I = N / I then
Count := Count + 1;
else
Count := Count + 2;
end if;
end if;
I := I + 1;
end loop;
return Count;
end Count_Divisors;
procedure Show (Max : in Natural) is
use Ada.Text_IO;
N : Natural := 1;
Begin
Put_Line ("The first" & Max'Image & "terms of the sequence are:");
for Divisors in 1 .. Max loop
while Count_Divisors (N) /= Divisors loop
N := N + 1;
end loop;
Put (N'Image);
end loop;
New_Line;
end Show;
begin
Show (15);
end Show_Sequence; |
http://rosettacode.org/wiki/Sequence:_smallest_number_greater_than_previous_term_with_exactly_n_divisors | Sequence: smallest number greater than previous term with exactly n divisors | Calculate the sequence where each term an is the smallest natural number greater than the previous term, that has exactly n divisors.
Task
Show here, on this page, at least the first 15 terms of the sequence.
See also
OEIS:A069654
Related tasks
Sequence: smallest number with exactly n divisors
Sequence: nth number with exactly n divisors
| #ALGOL_68 | ALGOL 68 | BEGIN
PROC count divisors = ( INT n )INT:
BEGIN
INT i2, count := 0;
FOR i WHILE ( i2 := i * i ) < n DO
IF n MOD i = 0 THEN count +:= 2 FI
OD;
IF i2 = n THEN count + 1 ELSE count FI
END # count divisors # ;
INT max = 15;
print( ( "The first ", whole( max, 0 ), " terms of the sequence are:" ) );
INT next := 1;
FOR i WHILE next <= max DO
IF next = count divisors( i ) THEN
print( ( " ", whole( i, 0 ) ) );
next +:= 1
FI
OD
END |
http://rosettacode.org/wiki/SHA-1 | SHA-1 | SHA-1 or SHA1 is a one-way hash function;
it computes a 160-bit message digest.
SHA-1 often appears in security protocols; for example,
many HTTPS websites use RSA with SHA-1 to secure their connections.
BitTorrent uses SHA-1 to verify downloads.
Git and Mercurial use SHA-1 digests to identify commits.
A US government standard, FIPS 180-1, defines SHA-1.
Find the SHA-1 message digest for a string of octets. You may either call a SHA-1 library, or implement SHA-1 in your language. Both approaches interest Rosetta Code.
Warning: SHA-1 has known weaknesses. Theoretical attacks may find a collision after 252 operations, or perhaps fewer.
This is much faster than a brute force attack of 280 operations. USgovernment deprecated SHA-1.
For production-grade cryptography, users may consider a stronger alternative, such as SHA-256 (from the SHA-2 family) or the upcoming SHA-3.
| #Halon | Halon | $var = "Rosetta Code";
echo sha1($var); |
http://rosettacode.org/wiki/SHA-1 | SHA-1 | SHA-1 or SHA1 is a one-way hash function;
it computes a 160-bit message digest.
SHA-1 often appears in security protocols; for example,
many HTTPS websites use RSA with SHA-1 to secure their connections.
BitTorrent uses SHA-1 to verify downloads.
Git and Mercurial use SHA-1 digests to identify commits.
A US government standard, FIPS 180-1, defines SHA-1.
Find the SHA-1 message digest for a string of octets. You may either call a SHA-1 library, or implement SHA-1 in your language. Both approaches interest Rosetta Code.
Warning: SHA-1 has known weaknesses. Theoretical attacks may find a collision after 252 operations, or perhaps fewer.
This is much faster than a brute force attack of 280 operations. USgovernment deprecated SHA-1.
For production-grade cryptography, users may consider a stronger alternative, such as SHA-256 (from the SHA-2 family) or the upcoming SHA-3.
| #Hare | Hare | use crypto::sha1;
use encoding::hex;
use fmt;
use hash;
use os;
use strings;
export fn main() void = {
const sha = sha1::sha1();
hash::write(&sha, strings::toutf8("Rosetta Code"));
let sum: [sha1::SIZE]u8 = [0...];
hash::sum(&sha, sum);
hex::encode(os::stdout, sum)!;
fmt::println()!;
}; |
http://rosettacode.org/wiki/Seven-sided_dice_from_five-sided_dice | Seven-sided dice from five-sided dice | Task
(Given an equal-probability generator of one of the integers 1 to 5
as dice5), create dice7 that generates a pseudo-random integer from
1 to 7 in equal probability using only dice5 as a source of random
numbers, and check the distribution for at least one million calls using the function created in Simple Random Distribution Checker.
Implementation suggestion:
dice7 might call dice5 twice, re-call if four of the 25
combinations are given, otherwise split the other 21 combinations
into 7 groups of three, and return the group index from the rolls.
(Task adapted from an answer here)
| #Java | Java | import java.util.Random;
public class SevenSidedDice
{
private static final Random rnd = new Random();
public static void main(String[] args)
{
SevenSidedDice now=new SevenSidedDice();
System.out.println("Random number from 1 to 7: "+now.seven());
}
int seven()
{
int v=21;
while(v>20)
v=five()+five()*5-6;
return 1+v%7;
}
int five()
{
return 1+rnd.nextInt(5);
}
} |
http://rosettacode.org/wiki/Seven-sided_dice_from_five-sided_dice | Seven-sided dice from five-sided dice | Task
(Given an equal-probability generator of one of the integers 1 to 5
as dice5), create dice7 that generates a pseudo-random integer from
1 to 7 in equal probability using only dice5 as a source of random
numbers, and check the distribution for at least one million calls using the function created in Simple Random Distribution Checker.
Implementation suggestion:
dice7 might call dice5 twice, re-call if four of the 25
combinations are given, otherwise split the other 21 combinations
into 7 groups of three, and return the group index from the rolls.
(Task adapted from an answer here)
| #JavaScript | JavaScript | function dice5()
{
return 1 + Math.floor(5 * Math.random());
}
function dice7()
{
while (true)
{
var dice55 = 5 * dice5() + dice5() - 6;
if (dice55 < 21)
return dice55 % 7 + 1;
}
}
distcheck(dice5, 1000000);
print();
distcheck(dice7, 1000000); |
http://rosettacode.org/wiki/Sexy_primes | Sexy primes |
This page uses content from Wikipedia. The original article was at Sexy_prime. 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)
In mathematics, sexy primes are prime numbers that differ from each other by six.
For example, the numbers 5 and 11 are both sexy primes, because 11 minus 6 is 5.
The term "sexy prime" is a pun stemming from the Latin word for six: sex.
Sexy prime pairs: Sexy prime pairs are groups of two primes that differ by 6. e.g. (5 11), (7 13), (11 17)
See sequences: OEIS:A023201 and OEIS:A046117
Sexy prime triplets: Sexy prime triplets are groups of three primes where each differs from the next by 6. e.g. (5 11 17), (7 13 19), (17 23 29)
See sequences: OEIS:A046118, OEIS:A046119 and OEIS:A046120
Sexy prime quadruplets: Sexy prime quadruplets are groups of four primes where each differs from the next by 6. e.g. (5 11 17 23), (11 17 23 29)
See sequences: OEIS:A023271, OEIS:A046122, OEIS:A046123 and OEIS:A046124
Sexy prime quintuplets: Sexy prime quintuplets are groups of five primes with a common difference of 6. One of the terms must be divisible by 5, because 5 and 6 are relatively prime. Thus, the only possible sexy prime quintuplet is (5 11 17 23 29)
Task
For each of pairs, triplets, quadruplets and quintuplets, Find and display the count of each group type of sexy primes less than one million thirty-five (1,000,035).
Display at most the last 5, less than one million thirty-five, of each sexy prime group type.
Find and display the count of the unsexy primes less than one million thirty-five.
Find and display the last 10 unsexy primes less than one million thirty-five.
Note that 1000033 SHOULD NOT be counted in the pair count. It is sexy, but not in a pair within the limit. However, it also SHOULD NOT be listed in the unsexy primes since it is sexy.
| #Python | Python | LIMIT = 1_000_035
def primes2(limit=LIMIT):
if limit < 2: return []
if limit < 3: return [2]
lmtbf = (limit - 3) // 2
buf = [True] * (lmtbf + 1)
for i in range((int(limit ** 0.5) - 3) // 2 + 1):
if buf[i]:
p = i + i + 3
s = p * (i + 1) + i
buf[s::p] = [False] * ((lmtbf - s) // p + 1)
return [2] + [i + i + 3 for i, v in enumerate(buf) if v]
primes = primes2(LIMIT +6)
primeset = set(primes)
primearray = [n in primeset for n in range(LIMIT)]
#%%
s = [[] for x in range(4)]
unsexy = []
for p in primes:
if p > LIMIT:
break
if p + 6 in primeset and p + 6 < LIMIT:
s[0].append((p, p+6))
elif p + 6 in primeset:
break
else:
if p - 6 not in primeset:
unsexy.append(p)
continue
if p + 12 in primeset and p + 12 < LIMIT:
s[1].append((p, p+6, p+12))
else:
continue
if p + 18 in primeset and p + 18 < LIMIT:
s[2].append((p, p+6, p+12, p+18))
else:
continue
if p + 24 in primeset and p + 24 < LIMIT:
s[3].append((p, p+6, p+12, p+18, p+24))
#%%
print('"SEXY" PRIME GROUPINGS:')
for sexy, name in zip(s, 'pairs triplets quadruplets quintuplets'.split()):
print(f' {len(sexy)} {na (not isPrime(n-6))))) |> Array.ofSeq
printfn "There are %d unsexy primes less than 1,000,035. The last 10 are:" n.Length
Array.skip (n.Length-10) n |> Array.iter(fun n->printf "%d " n); printfn ""
let ni=pCache |> Seq.takeWhile(fun n->nme} ending with ...')
for sx in sexy[-5:]:
print(' ',sx)
print(f'\nThere are {len(unsexy)} unsexy primes ending with ...')
for usx in unsexy[-10:]:
print(' ',usx) |
http://rosettacode.org/wiki/Show_ASCII_table | Show ASCII table | Task
Show the ASCII character set from values 32 to 127 (decimal) in a table format.
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
| #Fortran | Fortran | PROGRAM ASCTBL ! show the ASCII characters from 32-127
IMPLICIT NONE
INTEGER I, J
CHARACTER*3 H
10 FORMAT (I3, ':', A3, ' ', $)
20 FORMAT ()
DO J = 0, 15, +1
DO I = 32+J, 127, +16
IF (I > 32 .AND. I < 127) THEN
H = ' ' // ACHAR(I) // ' '
ELSE IF (I .EQ. 32) THEN
H = 'Spc'
ELSE IF (I .EQ. 127) THEN
H = 'Del'
ELSE
STOP 'bad value of i'
END IF
PRINT 10, I, H
END DO
PRINT 20
END DO
END
|
http://rosettacode.org/wiki/Sierpinski_triangle | Sierpinski triangle | Task
Produce an ASCII representation of a Sierpinski triangle of order N.
Example
The Sierpinski triangle of order 4 should look like this:
*
* *
* *
* * * *
* *
* * * *
* * * *
* * * * * * * *
* *
* * * *
* * * *
* * * * * * * *
* * * *
* * * * * * * *
* * * * * * * *
* * * * * * * * * * * * * * * *
Related tasks
Sierpinski triangle/Graphical for graphics images of this pattern.
Sierpinski carpet
| #Oforth | Oforth | : nextGen(l, r)
| i |
StringBuffer new
l size loop: i [
l at(i 1 -) '*' == 4 *
l at(i) '*' == 2 * +
l at(i 1 +) '*' == +
2 swap pow r bitAnd ifTrue: [ '*' ] else: [ ' ' ] over addChar
] ;
: automat(rule, n)
StringBuffer new " " <<n(n) "*" over + +
#[ dup println rule nextGen ] times(n) drop ;
: sierpinskiTriangle(n)
90 4 n * automat ; |
http://rosettacode.org/wiki/Sierpinski_carpet | Sierpinski carpet | Task
Produce a graphical or ASCII-art representation of a Sierpinski carpet of order N.
For example, the Sierpinski carpet of order 3 should look like this:
###########################
# ## ## ## ## ## ## ## ## #
###########################
### ###### ###### ###
# # # ## # # ## # # #
### ###### ###### ###
###########################
# ## ## ## ## ## ## ## ## #
###########################
######### #########
# ## ## # # ## ## #
######### #########
### ### ### ###
# # # # # # # #
### ### ### ###
######### #########
# ## ## # # ## ## #
######### #########
###########################
# ## ## ## ## ## ## ## ## #
###########################
### ###### ###### ###
# # # ## # # ## # # #
### ###### ###### ###
###########################
# ## ## ## ## ## ## ## ## #
###########################
The use of the # character is not rigidly required for ASCII art.
The important requirement is the placement of whitespace and non-whitespace characters.
Related task
Sierpinski triangle
| #Icon_and_Unicon | Icon and Unicon | $define FILLER "*" # the filler character
procedure main(A)
width := 3 ^ ( order := (0 < \A[1]) | 3 )
write("Carpet order= ",order)
every !(canvas := list(width)) := list(width," ") # prime the canvas
every y := 1 to width & x := 1 to width do # traverse it
if IsFilled(x-1,y-1) then canvas[x,y] := FILLER # fill
every x := 1 to width & y := 1 to width do
writes((y=1,"\n")|"",canvas[x,y]," ") # print
end
procedure IsFilled(x,y) # succeed if x,y should be filled
while x ~= 0 & y ~= 0 do {
if x % 3 = y %3 = 1 then fail
x /:= 3
y /:=3
}
return
end |
http://rosettacode.org/wiki/Short-circuit_evaluation | Short-circuit evaluation | Control Structures
These are examples of control structures. You may also be interested in:
Conditional structures
Exceptions
Flow-control structures
Loops
Assume functions a and b return boolean values, and further, the execution of function b takes considerable resources without side effects, and is to be minimized.
If we needed to compute the conjunction (and):
x = a() and b()
Then it would be best to not compute the value of b() if the value of a() is computed as false, as the value of x can then only ever be false.
Similarly, if we needed to compute the disjunction (or):
y = a() or b()
Then it would be best to not compute the value of b() if the value of a() is computed as true, as the value of y can then only ever be true.
Some languages will stop further computation of boolean equations as soon as the result is known, so-called short-circuit evaluation of boolean expressions
Task
Create two functions named a and b, that take and return the same boolean value.
The functions should also print their name whenever they are called.
Calculate and assign the values of the following equations to a variable in such a way that function b is only called when necessary:
x = a(i) and b(j)
y = a(i) or b(j)
If the language does not have short-circuit evaluation, this might be achieved with nested if statements.
| #Liberty_BASIC | Liberty BASIC | print "AND"
for i = 0 to 1
for j = 0 to 1
print "a("; i; ") AND b( "; j; ")"
res =a( i) 'call always
if res <>0 then 'short circuit if 0
res = b( j)
end if
print "=>",res
next
next
print "---------------------------------"
print "OR"
for i = 0 to 1
for j = 0 to 1
print "a("; i; ") OR b("; j; ")"
res =a( i) 'call always
if res = 0 then 'short circuit if <>0
res = b( j)
end if
print "=>", res
next
next
'----------------------------------------
function a( t)
print ,"calls func a"
a = t
end function
function b( t)
print ,"calls func b"
b = t
end function |
http://rosettacode.org/wiki/Set_puzzle | Set puzzle | Set Puzzles are created with a deck of cards from the Set Game™. The object of the puzzle is to find sets of 3 cards in a rectangle of cards that have been dealt face up.
There are 81 cards in a deck.
Each card contains a unique variation of the following four features: color, symbol, number and shading.
there are three colors:
red, green, purple
there are three symbols:
oval, squiggle, diamond
there is a number of symbols on the card:
one, two, three
there are three shadings:
solid, open, striped
Three cards form a set if each feature is either the same on each card, or is different on each card. For instance: all 3 cards are red, all 3 cards have a different symbol, all 3 cards have a different number of symbols, all 3 cards are striped.
There are two degrees of difficulty: basic and advanced. The basic mode deals 9 cards, that contain exactly 4 sets; the advanced mode deals 12 cards that contain exactly 6 sets.
When creating sets you may use the same card more than once.
Task
Write code that deals the cards (9 or 12, depending on selected mode) from a shuffled deck in which the total number of sets that could be found is 4 (or 6, respectively); and print the contents of the cards and the sets.
For instance:
DEALT 9 CARDS:
green, one, oval, striped
green, one, diamond, open
green, one, diamond, striped
green, one, diamond, solid
purple, one, diamond, open
purple, two, squiggle, open
purple, three, oval, open
red, three, oval, open
red, three, diamond, solid
CONTAINING 4 SETS:
green, one, oval, striped
purple, two, squiggle, open
red, three, diamond, solid
green, one, diamond, open
green, one, diamond, striped
green, one, diamond, solid
green, one, diamond, open
purple, two, squiggle, open
red, three, oval, open
purple, one, diamond, open
purple, two, squiggle, open
purple, three, oval, open
| #PARI.2FGP | PARI/GP | dealraw(cards)=vector(cards,i,vector(4,j,1<<random(3)));
howmany(a,b,c)=hammingweight(bitor(a,bitor(b,c)));
name(v)=Str(["red","green",0,"purple"][v[1]],", ",["oval","squiggle",0,"diamond"][v[2]],", ",["one","two",0,"three"][v[3]],", ",["solid","open",0,"striped"][v[4]]);
check(D,sets)={
my(S=List());
for(i=1,#D-2,for(j=i+1,#D-1,for(k=j+1,#D,
for(x=1,4,
if(howmany(D[i][x],D[j][x],D[k][x])==2,next(2))
);
listput(S,[i,j,k]);
if(#S>sets,return(0))
)));
if(#S==sets,Vec(S),0)
};
deal(cards,sets)={
my(v,s);
until(s,
s=check(v=dealraw(cards),sets)
);
v=apply(name,v);
for(i=1,cards,print(v[i]));
for(i=1,sets,
print("Set #"i);
for(j=1,3,print(" "v[s[i][j]]))
)
};
deal(9,4)
deal(12,6) |
http://rosettacode.org/wiki/Sequence:_smallest_number_with_exactly_n_divisors | Sequence: smallest number with exactly n divisors | Calculate the sequence where each term an is the smallest natural number that has exactly n divisors.
Task
Show here, on this page, at least the first 15 terms of the sequence.
Related tasks
Sequence: smallest number greater than previous term with exactly n divisors
Sequence: nth number with exactly n divisors
See also
OEIS:A005179
| #Action.21 | Action! | CARD FUNC CountDivisors(CARD a)
CARD i,count
i=1 count=0
WHILE i*i<=a
DO
IF a MOD i=0 THEN
IF i=a/i THEN
count==+1
ELSE
count==+2
FI
FI
i==+1
OD
RETURN (count)
PROC Main()
DEFINE MAX="15"
CARD a,count
BYTE i
CARD ARRAY seq(MAX)
FOR i=0 TO MAX-1
DO
seq(i)=0
OD
i=0 a=1
WHILE i<MAX
DO
count=CountDivisors(a)
IF count<=MAX AND seq(count-1)=0 THEN
seq(count-1)=a
i==+1
FI
a==+1
OD
FOR i=0 TO MAX-1
DO
IF i>0 THEN
Print(", ")
FI
PrintC(seq(i))
OD
RETURN |
http://rosettacode.org/wiki/Sequence:_smallest_number_with_exactly_n_divisors | Sequence: smallest number with exactly n divisors | Calculate the sequence where each term an is the smallest natural number that has exactly n divisors.
Task
Show here, on this page, at least the first 15 terms of the sequence.
Related tasks
Sequence: smallest number greater than previous term with exactly n divisors
Sequence: nth number with exactly n divisors
See also
OEIS:A005179
| #ALGOL_68 | ALGOL 68 | BEGIN
PROC count divisors = ( INT n )INT:
BEGIN
INT count := 0;
FOR i WHILE i*i <= n DO
IF n MOD i = 0 THEN
count +:= IF i = n OVER i THEN 1 ELSE 2 FI
FI
OD;
count
END # count divisors # ;
INT max = 15;
[ max ]INT seq;FOR i TO max DO seq[ i ] := 0 OD;
INT found := 0;
FOR i WHILE found < max DO
IF INT divisors = count divisors( i );
divisors <= max
THEN
# have an i with an appropriate number of divisors #
IF seq[ divisors ] = 0 THEN
# this is the first i with that many divisors #
seq[ divisors ] := i;
found +:= 1
FI
FI
OD;
print( ( "The first ", whole( max, 0 ), " terms of the sequence are:", newline ) );
FOR i TO max DO
print( ( whole( seq( i ), 0 ), " " ) )
OD;
print( ( newline ) )
END |
http://rosettacode.org/wiki/SHA-256 | SHA-256 | SHA-256 is the recommended stronger alternative to SHA-1. See FIPS PUB 180-4 for implementation details.
Either by using a dedicated library or implementing the algorithm in your language, show that the SHA-256 digest of the string "Rosetta code" is: 764faf5c61ac315f1497f9dfa542713965b785e5cc2f707d6468d7d1124cdfcf
| #Genie | Genie | [indent=4]
/*
SHA-256 in Genie
valac SHA-256.gs
./SHA-256
*/
init
var msg = "Rosetta code"
var digest = Checksum.compute_for_string(ChecksumType.SHA256, msg, -1)
print msg
print digest
assert(digest == "764faf5c61ac315f1497f9dfa542713965b785e5cc2f707d6468d7d1124cdfcf") |
http://rosettacode.org/wiki/SHA-256 | SHA-256 | SHA-256 is the recommended stronger alternative to SHA-1. See FIPS PUB 180-4 for implementation details.
Either by using a dedicated library or implementing the algorithm in your language, show that the SHA-256 digest of the string "Rosetta code" is: 764faf5c61ac315f1497f9dfa542713965b785e5cc2f707d6468d7d1124cdfcf
| #Go | Go | package main
import (
"crypto/sha256"
"fmt"
"log"
)
func main() {
h := sha256.New()
if _, err := h.Write([]byte("Rosetta code")); err != nil {
log.Fatal(err)
}
fmt.Printf("%x\n", h.Sum(nil))
} |
http://rosettacode.org/wiki/Sequence:_smallest_number_greater_than_previous_term_with_exactly_n_divisors | Sequence: smallest number greater than previous term with exactly n divisors | Calculate the sequence where each term an is the smallest natural number greater than the previous term, that has exactly n divisors.
Task
Show here, on this page, at least the first 15 terms of the sequence.
See also
OEIS:A069654
Related tasks
Sequence: smallest number with exactly n divisors
Sequence: nth number with exactly n divisors
| #ALGOL_W | ALGOL W | begin
integer max, next, i;
integer procedure countDivisors ( Integer value n ) ;
begin
integer count, i, i2;
count := 0;
i := 1;
while begin i2 := i * i;
i2 < n
end do begin
if n rem i = 0 then count := count + 2;
i := i + 1
end;
if i2 = n then count + 1 else count
end countDivisors ;
max := 15;
write( i_w := 1, s_w := 0, "The first ", max, " terms of the sequence are: " );
i := next := 1;
while next <= max do begin
if next = countDivisors( i ) then begin
writeon( i_w := 1, s_w := 0, " ", i );
next := next + 1
end;
i := i + 1
end;
write()
end. |
http://rosettacode.org/wiki/Sequence:_smallest_number_greater_than_previous_term_with_exactly_n_divisors | Sequence: smallest number greater than previous term with exactly n divisors | Calculate the sequence where each term an is the smallest natural number greater than the previous term, that has exactly n divisors.
Task
Show here, on this page, at least the first 15 terms of the sequence.
See also
OEIS:A069654
Related tasks
Sequence: smallest number with exactly n divisors
Sequence: nth number with exactly n divisors
| #Arturo | Arturo | i: new 0
next: new 1
MAX: 15
while [next =< MAX][
if next = size factors i [
prints ~"|i| "
inc 'next
]
inc 'i
]
print "" |
http://rosettacode.org/wiki/SHA-1 | SHA-1 | SHA-1 or SHA1 is a one-way hash function;
it computes a 160-bit message digest.
SHA-1 often appears in security protocols; for example,
many HTTPS websites use RSA with SHA-1 to secure their connections.
BitTorrent uses SHA-1 to verify downloads.
Git and Mercurial use SHA-1 digests to identify commits.
A US government standard, FIPS 180-1, defines SHA-1.
Find the SHA-1 message digest for a string of octets. You may either call a SHA-1 library, or implement SHA-1 in your language. Both approaches interest Rosetta Code.
Warning: SHA-1 has known weaknesses. Theoretical attacks may find a collision after 252 operations, or perhaps fewer.
This is much faster than a brute force attack of 280 operations. USgovernment deprecated SHA-1.
For production-grade cryptography, users may consider a stronger alternative, such as SHA-256 (from the SHA-2 family) or the upcoming SHA-3.
| #Haskell | Haskell | module Digestor
where
import Data.Digest.Pure.SHA
import qualified Data.ByteString.Lazy as B
convertString :: String -> B.ByteString
convertString phrase = B.pack $ map ( fromIntegral . fromEnum ) phrase
convertToSHA1 :: String -> String
convertToSHA1 word = showDigest $ sha1 $ convertString word
main = do
putStr "Rosetta Code SHA1-codiert: "
putStrLn $ convertToSHA1 "Rosetta Code"
|
http://rosettacode.org/wiki/Seven-sided_dice_from_five-sided_dice | Seven-sided dice from five-sided dice | Task
(Given an equal-probability generator of one of the integers 1 to 5
as dice5), create dice7 that generates a pseudo-random integer from
1 to 7 in equal probability using only dice5 as a source of random
numbers, and check the distribution for at least one million calls using the function created in Simple Random Distribution Checker.
Implementation suggestion:
dice7 might call dice5 twice, re-call if four of the 25
combinations are given, otherwise split the other 21 combinations
into 7 groups of three, and return the group index from the rolls.
(Task adapted from an answer here)
| #Julia | Julia | dice5() = rand(1:5)
function dice7()
r = 5*dice5() + dice5() - 6
r < 21 ? (r%7 + 1) : dice7()
end |
http://rosettacode.org/wiki/Seven-sided_dice_from_five-sided_dice | Seven-sided dice from five-sided dice | Task
(Given an equal-probability generator of one of the integers 1 to 5
as dice5), create dice7 that generates a pseudo-random integer from
1 to 7 in equal probability using only dice5 as a source of random
numbers, and check the distribution for at least one million calls using the function created in Simple Random Distribution Checker.
Implementation suggestion:
dice7 might call dice5 twice, re-call if four of the 25
combinations are given, otherwise split the other 21 combinations
into 7 groups of three, and return the group index from the rolls.
(Task adapted from an answer here)
| #Kotlin | Kotlin | // version 1.1.3
import java.util.Random
val r = Random()
fun dice5() = 1 + r.nextInt(5)
fun dice7(): Int {
while (true) {
val t = (dice5() - 1) * 5 + dice5() - 1
if (t >= 21) continue
return 1 + t / 3
}
}
fun checkDist(gen: () -> Int, nRepeats: Int, tolerance: Double = 0.5) {
val occurs = mutableMapOf<Int, Int>()
for (i in 1..nRepeats) {
val d = gen()
if (occurs.containsKey(d))
occurs[d] = occurs[d]!! + 1
else
occurs.put(d, 1)
}
val expected = (nRepeats.toDouble()/ occurs.size).toInt()
val maxError = (expected * tolerance / 100.0).toInt()
println("Repetitions = $nRepeats, Expected = $expected")
println("Tolerance = $tolerance%, Max Error = $maxError\n")
println("Integer Occurrences Error Acceptable")
val f = " %d %5d %5d %s"
var allAcceptable = true
for ((k,v) in occurs.toSortedMap()) {
val error = Math.abs(v - expected)
val acceptable = if (error <= maxError) "Yes" else "No"
if (acceptable == "No") allAcceptable = false
println(f.format(k, v, error, acceptable))
}
println("\nAcceptable overall: ${if (allAcceptable) "Yes" else "No"}")
}
fun main(args: Array<String>) {
checkDist(::dice7, 1_400_000)
} |
http://rosettacode.org/wiki/Sexy_primes | Sexy primes |
This page uses content from Wikipedia. The original article was at Sexy_prime. 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)
In mathematics, sexy primes are prime numbers that differ from each other by six.
For example, the numbers 5 and 11 are both sexy primes, because 11 minus 6 is 5.
The term "sexy prime" is a pun stemming from the Latin word for six: sex.
Sexy prime pairs: Sexy prime pairs are groups of two primes that differ by 6. e.g. (5 11), (7 13), (11 17)
See sequences: OEIS:A023201 and OEIS:A046117
Sexy prime triplets: Sexy prime triplets are groups of three primes where each differs from the next by 6. e.g. (5 11 17), (7 13 19), (17 23 29)
See sequences: OEIS:A046118, OEIS:A046119 and OEIS:A046120
Sexy prime quadruplets: Sexy prime quadruplets are groups of four primes where each differs from the next by 6. e.g. (5 11 17 23), (11 17 23 29)
See sequences: OEIS:A023271, OEIS:A046122, OEIS:A046123 and OEIS:A046124
Sexy prime quintuplets: Sexy prime quintuplets are groups of five primes with a common difference of 6. One of the terms must be divisible by 5, because 5 and 6 are relatively prime. Thus, the only possible sexy prime quintuplet is (5 11 17 23 29)
Task
For each of pairs, triplets, quadruplets and quintuplets, Find and display the count of each group type of sexy primes less than one million thirty-five (1,000,035).
Display at most the last 5, less than one million thirty-five, of each sexy prime group type.
Find and display the count of the unsexy primes less than one million thirty-five.
Find and display the last 10 unsexy primes less than one million thirty-five.
Note that 1000033 SHOULD NOT be counted in the pair count. It is sexy, but not in a pair within the limit. However, it also SHOULD NOT be listed in the unsexy primes since it is sexy.
| #Raku | Raku | use Math::Primesieve;
my $sieve = Math::Primesieve.new;
my $max = 1_000_035;
my @primes = $sieve.primes($max);
my $filter = @primes.Set;
my $primes = @primes.categorize: &sexy;
say "Total primes less than {comma $max}: ", comma +@primes;
for <pair 2 triplet 3 quadruplet 4 quintuplet 5> -> $sexy, $cnt {
say "Number of sexy prime {$sexy}s less than {comma $max}: ", comma +$primes{$sexy};
say " Last 5 sexy prime {$sexy}s less than {comma $max}: ",
join ' ', $primes{$sexy}.tail(5).grep(*.defined).map:
{ "({ $_ «+« (0,6 … 24)[^$cnt] })" }
say '';
}
say "Number of unsexy primes less than {comma $max}: ", comma +$primes<unsexy>;
say " Last 10 unsexy primes less than {comma $max}: ", $primes<unsexy>.tail(10);
sub sexy ($i) {
gather {
take 'quintuplet' if all($filter{$i «+« (6,12,18,24)});
take 'quadruplet' if all($filter{$i «+« (6,12,18)});
take 'triplet' if all($filter{$i «+« (6,12)});
take 'pair' if $filter{$i + 6};
take (($i >= $max - 6) && ($i + 6).is-prime) ||
(so any($filter{$i «+« (6, -6)})) ?? 'sexy' !! 'unsexy';
}
}
sub comma { $^i.flip.comb(3).join(',').flip } |
http://rosettacode.org/wiki/Show_ASCII_table | Show ASCII table | Task
Show the ASCII character set from values 32 to 127 (decimal) in a table format.
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
| #FreeBASIC | FreeBASIC | function getasc( n as unsigned byte ) as string
if n=32 then return "Spc"
if n=127 then return "Del"
return chr(n)+" "
end function
function padto( i as ubyte, j as integer ) as string
return wspace(i-len(str(j)))+str(j)
end function
dim as unsigned byte r, c, n
dim as string disp
for r = 0 to 15
disp = ""
for c = 0 to 5
n = 32 + 6*r + c
disp = disp + padto(3, n) + ": " + getasc(n) + " "
next c
print disp
next r
|
http://rosettacode.org/wiki/Sierpinski_triangle | Sierpinski triangle | Task
Produce an ASCII representation of a Sierpinski triangle of order N.
Example
The Sierpinski triangle of order 4 should look like this:
*
* *
* *
* * * *
* *
* * * *
* * * *
* * * * * * * *
* *
* * * *
* * * *
* * * * * * * *
* * * *
* * * * * * * *
* * * * * * * *
* * * * * * * * * * * * * * * *
Related tasks
Sierpinski triangle/Graphical for graphics images of this pattern.
Sierpinski carpet
| #Oz | Oz | declare
fun {NextTriangle Triangle}
Sp = {Spaces {Length Triangle}}
in
{Flatten
[{Map Triangle fun {$ X} Sp#X#Sp end}
{Map Triangle fun {$ X} X#" "#X end}
]}
end
fun {Spaces N} if N == 0 then nil else & |{Spaces N-1} end end
fun lazy {Iterate F X}
X|{Iterate F {F X}}
end
SierpinskiTriangles = {Iterate NextTriangle ["*"]}
in
{ForAll {Nth SierpinskiTriangles 5} System.showInfo} |
http://rosettacode.org/wiki/Sierpinski_carpet | Sierpinski carpet | Task
Produce a graphical or ASCII-art representation of a Sierpinski carpet of order N.
For example, the Sierpinski carpet of order 3 should look like this:
###########################
# ## ## ## ## ## ## ## ## #
###########################
### ###### ###### ###
# # # ## # # ## # # #
### ###### ###### ###
###########################
# ## ## ## ## ## ## ## ## #
###########################
######### #########
# ## ## # # ## ## #
######### #########
### ### ### ###
# # # # # # # #
### ### ### ###
######### #########
# ## ## # # ## ## #
######### #########
###########################
# ## ## ## ## ## ## ## ## #
###########################
### ###### ###### ###
# # # ## # # ## # # #
### ###### ###### ###
###########################
# ## ## ## ## ## ## ## ## #
###########################
The use of the # character is not rigidly required for ASCII art.
The important requirement is the placement of whitespace and non-whitespace characters.
Related task
Sierpinski triangle
| #Io | Io | sierpinskiCarpet := method(n,
carpet := list("@")
n repeat(
next := list()
carpet foreach(s, next append(s .. s .. s))
carpet foreach(s, next append(s .. (s asMutable replaceSeq("@"," ")) .. s))
carpet foreach(s, next append(s .. s .. s))
carpet = next
)
carpet join("\n")
)
sierpinskiCarpet(3) println |
http://rosettacode.org/wiki/Short-circuit_evaluation | Short-circuit evaluation | Control Structures
These are examples of control structures. You may also be interested in:
Conditional structures
Exceptions
Flow-control structures
Loops
Assume functions a and b return boolean values, and further, the execution of function b takes considerable resources without side effects, and is to be minimized.
If we needed to compute the conjunction (and):
x = a() and b()
Then it would be best to not compute the value of b() if the value of a() is computed as false, as the value of x can then only ever be false.
Similarly, if we needed to compute the disjunction (or):
y = a() or b()
Then it would be best to not compute the value of b() if the value of a() is computed as true, as the value of y can then only ever be true.
Some languages will stop further computation of boolean equations as soon as the result is known, so-called short-circuit evaluation of boolean expressions
Task
Create two functions named a and b, that take and return the same boolean value.
The functions should also print their name whenever they are called.
Calculate and assign the values of the following equations to a variable in such a way that function b is only called when necessary:
x = a(i) and b(j)
y = a(i) or b(j)
If the language does not have short-circuit evaluation, this might be achieved with nested if statements.
| #LiveCode | LiveCode | global outcome
function a bool
put "a called with" && bool & cr after outcome
return bool
end a
function b bool
put "b called with" && bool & cr after outcome
return bool
end b
on mouseUp
local tExp
put empty into outcome
repeat for each item op in "and,or"
repeat for each item x in "true,false"
put merge("a([[x]]) [[op]] b([[x]])") into tExp
put merge(tExp && "is [[" & tExp & "]]") & cr after outcome
put merge("a([[x]]) [[op]] b([[not x]])") into tExp
put merge(tExp && "is [[" & tExp & "]]") & cr after outcome
end repeat
put cr after outcome
end repeat
put outcome
end mouseUp |
http://rosettacode.org/wiki/Short-circuit_evaluation | Short-circuit evaluation | Control Structures
These are examples of control structures. You may also be interested in:
Conditional structures
Exceptions
Flow-control structures
Loops
Assume functions a and b return boolean values, and further, the execution of function b takes considerable resources without side effects, and is to be minimized.
If we needed to compute the conjunction (and):
x = a() and b()
Then it would be best to not compute the value of b() if the value of a() is computed as false, as the value of x can then only ever be false.
Similarly, if we needed to compute the disjunction (or):
y = a() or b()
Then it would be best to not compute the value of b() if the value of a() is computed as true, as the value of y can then only ever be true.
Some languages will stop further computation of boolean equations as soon as the result is known, so-called short-circuit evaluation of boolean expressions
Task
Create two functions named a and b, that take and return the same boolean value.
The functions should also print their name whenever they are called.
Calculate and assign the values of the following equations to a variable in such a way that function b is only called when necessary:
x = a(i) and b(j)
y = a(i) or b(j)
If the language does not have short-circuit evaluation, this might be achieved with nested if statements.
| #Logo | Logo | and [notequal? :x 0] [1/:x > 3]
(or [:x < 0] [:y < 0] [sqrt :x + sqrt :y < 3]) |
http://rosettacode.org/wiki/Set_puzzle | Set puzzle | Set Puzzles are created with a deck of cards from the Set Game™. The object of the puzzle is to find sets of 3 cards in a rectangle of cards that have been dealt face up.
There are 81 cards in a deck.
Each card contains a unique variation of the following four features: color, symbol, number and shading.
there are three colors:
red, green, purple
there are three symbols:
oval, squiggle, diamond
there is a number of symbols on the card:
one, two, three
there are three shadings:
solid, open, striped
Three cards form a set if each feature is either the same on each card, or is different on each card. For instance: all 3 cards are red, all 3 cards have a different symbol, all 3 cards have a different number of symbols, all 3 cards are striped.
There are two degrees of difficulty: basic and advanced. The basic mode deals 9 cards, that contain exactly 4 sets; the advanced mode deals 12 cards that contain exactly 6 sets.
When creating sets you may use the same card more than once.
Task
Write code that deals the cards (9 or 12, depending on selected mode) from a shuffled deck in which the total number of sets that could be found is 4 (or 6, respectively); and print the contents of the cards and the sets.
For instance:
DEALT 9 CARDS:
green, one, oval, striped
green, one, diamond, open
green, one, diamond, striped
green, one, diamond, solid
purple, one, diamond, open
purple, two, squiggle, open
purple, three, oval, open
red, three, oval, open
red, three, diamond, solid
CONTAINING 4 SETS:
green, one, oval, striped
purple, two, squiggle, open
red, three, diamond, solid
green, one, diamond, open
green, one, diamond, striped
green, one, diamond, solid
green, one, diamond, open
purple, two, squiggle, open
red, three, oval, open
purple, one, diamond, open
purple, two, squiggle, open
purple, three, oval, open
| #Perl | Perl | #!perl
use strict;
use warnings;
# This code was adapted from the Raku solution for this task.
# Each element of the deck is an integer, which, when written
# in octal, has four digits, which are all either 1, 2, or 4.
my $fmt = '%4o';
my @deck = grep sprintf($fmt, $_) !~ tr/124//c, 01111 .. 04444;
# Given a feature digit (1, 2, or 4), produce the feature's name.
# Note that digits 0 and 3 are unused.
my @features = map [split ' '], split /\n/,<<'';
! red green ! purple
! one two ! three
! oval squiggle ! diamond
! solid open ! striped
81 == @deck or die "There are ".@deck." cards (should be 81)";
# By default, draw 9 cards, but if the user
# supplied a parameter, use that.
my $draw = shift(@ARGV) || 9;
my $goal = int($draw/2);
# Get the possible combinations of 3 indices into $draw elements.
my @combinations = combine(3, 0 .. $draw-1);
my @sets;
do {
# Shuffle the first $draw elements of @deck.
for my $i ( 0 .. $draw-1 ) {
my $j = $i + int rand(@deck - $i);
@deck[$i, $j] = @deck[$j, $i];
}
# Find all valid sets using the shuffled elements.
@sets = grep {
my $or = 0;
$or |= $_ for @deck[@$_];
# If all colors (or whatever) are the same, then
# a 1, 2, or 4 will result when we OR them together.
# If they're all different, then a 7 will result.
# If any other digit occurs, the set is invalid.
sprintf($fmt, $or) !~ tr/1247//c;
} @combinations;
# Continue until there are exactly $goal valid sets.
} until @sets == $goal;
print "Drew $draw cards:\n";
for my $i ( 0 .. $#sets ) {
print "Set ", $i+1, ":\n";
my @cards = @deck[ @{$sets[$i]} ];
for my $card ( @cards ) {
my @octal = split //, sprintf '%4o', $card;
my @f = map $features[$_][$octal[$_]], 0 .. 3;
printf " %-6s %-5s %-8s %s\n", @f;
}
}
exit;
# This function is adapted from the perl5i solution for the
# RosettaCode Combinations task.
sub combine {
my $n = shift;
return unless @_;
return map [$_], @_ if $n == 1;
my $head = shift;
my @result = combine( $n-1, @_ );
unshift @$_, $head for @result;
@result, combine( $n, @_ );
}
__END__
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.