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/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.
| #Fantom | Fantom | class Main
{
static Bool a (Bool value)
{
echo ("in a")
return value
}
static Bool b (Bool value)
{
echo ("in b")
return value
}
public static Void main ()
{
[false,true].each |i|
{
[false,true].each |j|
{
Bool result := a(i) && b(j)
echo ("a($i) && b($j): " + result)
result = a(i) || b(j)
echo ("a($i) || b($j): " + result)
}
}
}
} |
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
| #C | C | #include <stdio.h>
#include <stdlib.h>
char *names[4][3] = {
{ "red", "green", "purple" },
{ "oval", "squiggle", "diamond" },
{ "one", "two", "three" },
{ "solid", "open", "striped" }
};
int set[81][81];
void init_sets(void)
{
int i, j, t, a, b;
for (i = 0; i < 81; i++) {
for (j = 0; j < 81; j++) {
for (t = 27; t; t /= 3) {
a = (i / t) % 3;
b = (j / t) % 3;
set[i][j] += t * (a == b ? a : 3 - a - b);
}
}
}
}
void deal(int *out, int n)
{
int i, j, t, c[81];
for (i = 0; i < 81; i++) c[i] = i;
for (i = 0; i < n; i++) {
j = i + (rand() % (81 - i));
t = c[i], c[i] = out[i] = c[j], c[j] = t;
}
}
int get_sets(int *cards, int n, int sets[][3])
{
int i, j, k, s = 0;
for (i = 0; i < n; i++) {
for (j = i + 1; j < n; j++) {
for (k = j + 1; k < n; k++) {
if (set[cards[i]][cards[j]] == cards[k])
sets[s][0] = i,
sets[s][1] = j,
sets[s][2] = k,
s++;
}
}
}
return s;
}
void show_card(int c)
{
int i, t;
for (i = 0, t = 27; t; i++, t /= 3)
printf("%9s", names[i][(c/t)%3]);
putchar('\n');
}
void deal_sets(int ncard, int nset)
{
int c[81];
int csets[81][3]; // might not be enough for large ncard
int i, j, s;
do deal(c, ncard); while ((s = get_sets(c, ncard, csets)) != nset);
printf("dealt %d cards\n", ncard);
for (i = 0; i < ncard; i++) {
printf("%2d:", i);
show_card(c[i]);
}
printf("\nsets:\n");
for (i = 0; i < s; i++) {
for (j = 0; j < 3; j++) {
printf("%2d:", csets[i][j]);
show_card(c[csets[i][j]]);
}
putchar('\n');
}
}
int main(void)
{
init_sets();
deal_sets(9, 4);
while (1) deal_sets(12, 6);
return 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
| #C.23 | C# | using System;
using System.Security.Cryptography;
using System.Text;
using Microsoft.VisualStudio.TestTools.UnitTesting;
namespace RosettaCode.SHA256
{
[TestClass]
public class SHA256ManagedTest
{
[TestMethod]
public void TestComputeHash()
{
var buffer = Encoding.UTF8.GetBytes("Rosetta code");
var hashAlgorithm = new SHA256Managed();
var hash = hashAlgorithm.ComputeHash(buffer);
Assert.AreEqual(
"76-4F-AF-5C-61-AC-31-5F-14-97-F9-DF-A5-42-71-39-65-B7-85-E5-CC-2F-70-7D-64-68-D7-D1-12-4C-DF-CF",
BitConverter.ToString(hash));
}
}
} |
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.
| #Cach.C3.A9_ObjectScript | Caché ObjectScript | USER>set hash=$System.Encryption.SHA1Hash("Rosetta Code")
USER>zzdump hash
0000: 48 C9 8F 7E 5A 6E 73 6D 79 0A B7 40 DF C3 F5 1A
0010: 61 AB E2 B5 |
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.
| #Clojure | Clojure | ;;; in addition to sha1, ironclad provides sha224, sha256, sha384, and sha512.
(defun sha1-hash (data)
(let ((sha1 (ironclad:make-digest 'ironclad:sha1))
(bin-data (ironclad:ascii-string-to-byte-array data)))
(ironclad:update-digest sha1 bin-data)
(ironclad:byte-array-to-hex-string (ironclad:produce-digest sha1))))
|
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)
| #C | C | int rand5()
{
int r, rand_max = RAND_MAX - (RAND_MAX % 5);
while ((r = rand()) >= rand_max);
return r / (rand_max / 5) + 1;
}
int rand5_7()
{
int r;
while ((r = rand5() * 5 + rand5()) >= 27);
return r / 3 - 1;
}
int main()
{
printf(check(rand5, 5, 1000000, .05) ? "flat\n" : "not flat\n");
printf(check(rand7, 7, 1000000, .05) ? "flat\n" : "not flat\n");
return 0;
} |
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)
| #C.23 | C# |
using System;
public class SevenSidedDice
{
Random random = new Random();
static void Main(string[] args)
{
SevenSidedDice sevenDice = new SevenSidedDice();
Console.WriteLine("Random number from 1 to 7: "+ sevenDice.seven());
Console.Read();
}
int seven()
{
int v=21;
while(v>20)
v=five()+five()*5-6;
return 1+v%7;
}
int five()
{
return 1 + random.Next(5);
}
} |
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.
| #Haskell | Haskell | import Text.Printf (printf)
import Data.Numbers.Primes (isPrime, primes)
type Pair = (Int, Int)
type Triplet = (Int, Int, Int)
type Quad = (Int, Int, Int, Int)
type Quin = (Int, Int, Int, Int, Int)
type Result = ([Pair], [Triplet], [Quad], [Quin], [Int])
groups :: Int -> Result -> Result
groups n r@(p, t, q, qn, u)
| isPrime n4 && isPrime n3 && isPrime n2 && isPrime n1 = (addPair, addTriplet, addQuad, addQuin, u)
| isPrime n3 && isPrime n2 && isPrime n1 = (addPair, addTriplet, addQuad, qn, u)
| isPrime n2 && isPrime n1 = (addPair, addTriplet, q, qn, u)
| isPrime n1 = (addPair, t, q, qn, u)
| not (isPrime (n+6)) && not (isPrime n1) = (p, t, q, qn, n : u)
| otherwise = r
where addPair = (n1, n) : p
addTriplet = (n2, n1, n) : t
addQuad = (n3, n2, n1, n) : q
addQuin = (n4, n3, n2, n1, n) : qn
n1 = n - 6
n2 = n - 12
n3 = n - 18
n4 = n - 24
main :: IO ()
main = do
printf ("Number of sexy prime pairs: %d\n" <> lastFiveText) (length pairs) (lastFive pairs)
printf ("Number of sexy prime triplets: %d\n" <> lastFiveText) (length triplets) (lastFive triplets)
printf ("Number of sexy prime quadruplets: %d\n" <> lastFiveText) (length quads) (lastFive quads)
printf "Number of sexy prime quintuplets: %d\n Last 1 : %s\n\n" (length quins) (show $ last quins)
printf "Number of unsexy primes: %d\n Last 10: %s\n\n" (length unsexy) (show $ drop (length unsexy - 10) unsexy)
where (pairs, triplets, quads, quins, unsexy) = foldr groups ([], [], [], [], []) $ takeWhile (< 1000035) primes
lastFive xs = show $ drop (length xs - 5) xs
lastFiveText = " Last 5 : %s\n\n" |
http://rosettacode.org/wiki/SHA-256_Merkle_tree | SHA-256 Merkle tree | As described in its documentation, Amazon S3 Glacier requires that all uploaded files come with a checksum computed as a Merkle Tree using SHA-256.
Specifically, the SHA-256 hash is computed for each 1MiB block of the file. And then, starting from the beginning of the file, the raw hashes of consecutive blocks are paired up and concatenated together, and a new hash is computed from each concatenation. Then these are paired up and concatenated and hashed, and the process continues until there is only one hash left, which is the final checksum. The hexadecimal representation of this checksum is the value that must be included with the AWS API call to upload the object (or complete a multipart upload).
Implement this algorithm in your language; you can use the code from the SHA-256 task for the actual hash computations. For better manageability and portability, build the tree using a smaller block size of only 1024 bytes, and demonstrate it on the RosettaCode title image with that block size. The final result should be the hexadecimal digest value a4f902cf9d51fe51eda156a6792e1445dff65edf3a217a1f3334cc9cf1495c2c.
| #Phix | Phix | without javascript_semantics
include builtins\libcurl.e
include builtins\sha256.e
constant ONE_MB = 1024 * 1024
function merkle(string filename, url, integer block_size=ONE_MB)
if not file_exists(filename) then
printf(1,"Downloading %s...\n",{filename})
CURLcode res = curl_easy_get_file(url,"",filename) -- (no proxy)
if res!=CURLE_OK then
string error = sprintf("%d",res)
if res=CURLE_COULDNT_RESOLVE_HOST then
error &= " [CURLE_COULDNT_RESOLVE_HOST]"
end if
crash("Error %s downloading file\n", {error})
end if
end if
string data = get_text(filename)
sequence blocks = {}
for i=1 to length(data) by block_size do
blocks = append(blocks,sha256(data[i..min(i+block_size-1,length(data))]))
end for
while length(blocks)>1 do
integer l = 0
for i=1 to length(blocks) by 2 do
l += 1
blocks[l] = iff(i<length(blocks)?sha256(blocks[i]&blocks[i+1])
:blocks[i])
end for
blocks = blocks[1..l]
end while
return blocks[1]
end function
function asHex(string s)
string res = ""
for i=1 to length(s) do
res &= sprintf("%02X",s[i])
end for
return res
end function
printf(1,"%s\n",asHex(merkle("title.png", "https://rosettacode.org/mw/title.png", 1024)))
|
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
| #CLU | CLU | ascii = proc (n: int) returns (string)
if n=32 then return("Spc")
elseif n=127 then return("Del")
else return(string$c2s(char$i2c(n)))
end
end ascii
start_up = proc ()
po: stream := stream$primary_output()
for i: int in int$from_to(32, 47) do
for j: int in int$from_to_by(i, 127, 16) do
stream$putright(po, int$unparse(j), 3)
stream$puts(po, ": ")
stream$putleft(po, ascii(j), 5)
end
stream$putl(po, "")
end
end start_up |
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
| #Julia | Julia | function sierpinski(n, token::AbstractString="*")
x = fill(token, 1, 1)
for _ in 1:n
h, w = size(x)
s = fill(" ", h,(w + 1) ÷ 2)
t = fill(" ", h,1)
x = [[s x s] ; [x t x]]
end
return x
end
function printsierpinski(m::Matrix)
for r in 1:size(m, 1)
println(join(m[r, :]))
end
end
sierpinski(4) |> printsierpinski |
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
| #F.23 | F# | open System
let blank x = new String(' ', String.length x)
let nextCarpet carpet =
List.map (fun x -> x + x + x) carpet @
List.map (fun x -> x + (blank x) + x) carpet @
List.map (fun x -> x + x + x) carpet
let rec sierpinskiCarpet n =
let rec aux n carpet =
if n = 0 then carpet
else aux (n-1) (nextCarpet carpet)
aux n ["#"]
List.iter (printfn "%s") (sierpinskiCarpet 3) |
http://rosettacode.org/wiki/Shoelace_formula_for_polygonal_area | Shoelace formula for polygonal area | Given the n + 1 vertices x[0], y[0] .. x[N], y[N] of a simple polygon described in a clockwise direction, then the polygon's area can be calculated by:
abs( (sum(x[0]*y[1] + ... x[n-1]*y[n]) + x[N]*y[0]) -
(sum(x[1]*y[0] + ... x[n]*y[n-1]) + x[0]*y[N])
) / 2
(Where abs returns the absolute value)
Task
Write a function/method/routine to use the the Shoelace formula to calculate the area of the polygon described by the ordered points:
(3,4), (5,11), (12,8), (9,5), and (5,6)
Show the answer here, on this page.
| #Visual_Basic_.NET | Visual Basic .NET | Option Strict On
Imports Point = System.Tuple(Of Double, Double)
Module Module1
Function ShoelaceArea(v As List(Of Point)) As Double
Dim n = v.Count
Dim a = 0.0
For i = 0 To n - 2
a += v(i).Item1 * v(i + 1).Item2 - v(i + 1).Item1 * v(i).Item2
Next
Return Math.Abs(a + v(n - 1).Item1 * v(0).Item2 - v(0).Item1 * v(n - 1).Item2) / 2.0
End Function
Sub Main()
Dim v As New List(Of Point) From {
New Point(3, 4),
New Point(5, 11),
New Point(12, 8),
New Point(9, 5),
New Point(5, 6)
}
Dim area = ShoelaceArea(v)
Console.WriteLine("Given a polygon with vertices [{0}],", String.Join(", ", v))
Console.WriteLine("its area is {0}.", area)
End Sub
End Module |
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.
| #R | R | $ echo 'cat("Hello\n")' | R --slave
Hello |
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.
| #Racket | Racket | $ racket -e "(displayln \"Hello World\")"
Hello World |
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.
| #Raku | Raku | $ raku -e 'say "Hello, world!"'
Hello, world! |
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.
| #REBOL | REBOL | rebview -vswq --do "print {Hello!} quit" |
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.
| #Forth | Forth | \ Short-circuit evaluation definitions from Wil Baden, with minor name changes
: ENDIF postpone THEN ; immediate
: COND 0 ; immediate
: ENDIFS BEGIN DUP WHILE postpone ENDIF REPEAT DROP ; immediate
: ORELSE s" ?DUP 0= IF" evaluate ; immediate
: ANDIF s" DUP IF DROP" evaluate ; immediate
: .bool IF ." true " ELSE ." false " THEN ;
: A ." A=" DUP .bool ;
: B ." B=" DUP .bool ;
: test
CR
1 -1 DO 1 -1 DO
COND I A ANDIF J B ENDIFS ." ANDIF=" .bool CR
COND I A ORELSE J B ENDIFS ." ORELSE=" .bool CR
LOOP LOOP ;
\ An alternative based on explicitly short-circuiting conditionals, Dave Keenan
: END-PRIOR-IF 1 CS-ROLL postpone ENDIF ; immediate
: test
CR
1 -1 DO 1 -1 DO
I A IF J B IF 1 ELSE END-PRIOR-IF 0 ENDIF ." ANDIF=" .bool CR
I A 0= IF J B IF END-PRIOR-IF 1 ELSE 0 ENDIF ." ORELSE=" .bool CR
LOOP LOOP ; |
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.
| #Fortran | Fortran | program Short_Circuit_Eval
implicit none
logical :: x, y
logical, dimension(2) :: l = (/ .false., .true. /)
integer :: i, j
do i = 1, 2
do j = 1, 2
write(*, "(a,l1,a,l1,a)") "Calculating x = a(", l(i), ") and b(", l(j), ")"
! a AND b
x = a(l(i))
if(x) then
x = b(l(j))
write(*, "(a,l1)") "x = ", x
else
write(*, "(a,l1)") "x = ", x
end if
write(*,*)
write(*, "(a,l1,a,l1,a)") "Calculating y = a(", l(i), ") or b(", l(j), ")"
! a OR b
y = a(l(i))
if(y) then
write(*, "(a,l1)") "y = ", y
else
y = b(l(j))
write(*, "(a,l1)") "y = ", y
end if
write(*,*)
end do
end do
contains
function a(value)
logical :: a
logical, intent(in) :: value
a = value
write(*, "(a,l1,a)") "Called function a(", value, ")"
end function
function b(value)
logical :: b
logical, intent(in) :: value
b = value
write(*, "(a,l1,a)") "Called function b(", value, ")"
end function
end program |
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
| #C.23 | C# | using System;
using System.Collections.Generic;
using static System.Linq.Enumerable;
public static class SetPuzzle
{
static readonly Feature[] numbers = { (1, "One"), (2, "Two"), (3, "Three") };
static readonly Feature[] colors = { (1, "Red"), (2, "Green"), (3, "Purple") };
static readonly Feature[] shadings = { (1, "Open"), (2, "Striped"), (3, "Solid") };
static readonly Feature[] symbols = { (1, "Oval"), (2, "Squiggle"), (3, "Diamond") };
private readonly struct Feature
{
public Feature(int value, string name) => (Value, Name) = (value, name);
public int Value { get; }
public string Name { get; }
public static implicit operator int(Feature f) => f.Value;
public static implicit operator Feature((int value, string name) t) => new Feature(t.value, t.name);
public override string ToString() => Name;
}
private readonly struct Card : IEquatable<Card>
{
public Card(Feature number, Feature color, Feature shading, Feature symbol) =>
(Number, Color, Shading, Symbol) = (number, color, shading, symbol);
public Feature Number { get; }
public Feature Color { get; }
public Feature Shading { get; }
public Feature Symbol { get; }
public override string ToString() => $"{Number} {Color} {Shading} {Symbol}(s)";
public bool Equals(Card other) => Number == other.Number && Color == other.Color && Shading == other.Shading && Symbol == other.Symbol;
}
public static void Main() {
Card[] deck = (
from number in numbers
from color in colors
from shading in shadings
from symbol in symbols
select new Card(number, color, shading, symbol)
).ToArray();
var random = new Random();
Deal(deck, 9, 4, random);
Console.WriteLine();
Console.WriteLine();
Deal(deck, 12, 6, random);
}
static void Deal(Card[] deck, int size, int target, Random random) {
List<(Card a, Card b, Card c)> sets;
do {
Shuffle(deck, random.Next);
sets = (
from i in 0.To(size - 2)
from j in (i + 1).To(size - 1)
from k in (j + 1).To(size)
select (deck[i], deck[j], deck[k])
).Where(IsSet).ToList();
} while (sets.Count != target);
Console.WriteLine("The board:");
foreach (Card card in deck.Take(size)) Console.WriteLine(card);
Console.WriteLine();
Console.WriteLine("Sets:");
foreach (var s in sets) Console.WriteLine(s);
}
static void Shuffle<T>(T[] array, Func<int, int, int> rng) {
for (int i = 0; i < array.Length; i++) {
int r = rng(i, array.Length);
(array[r], array[i]) = (array[i], array[r]);
}
}
static bool IsSet((Card a, Card b, Card c) t) =>
AreSameOrDifferent(t.a.Number, t.b.Number, t.c.Number) &&
AreSameOrDifferent(t.a.Color, t.b.Color, t.c.Color) &&
AreSameOrDifferent(t.a.Shading, t.b.Shading, t.c.Shading) &&
AreSameOrDifferent(t.a.Symbol, t.b.Symbol, t.c.Symbol);
static bool AreSameOrDifferent(int a, int b, int c) => (a + b + c) % 3 == 0;
static IEnumerable<int> To(this int start, int end) => Range(start, end - start - 1);
} |
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
| #C.2B.2B | C++ | #include <iostream>
#include <cryptopp/filters.h>
#include <cryptopp/hex.h>
#include <cryptopp/sha.h>
int main(int argc, char **argv){
CryptoPP::SHA256 hash;
std::string digest;
std::string message = "Rosetta code";
CryptoPP::StringSource s(message, true,
new CryptoPP::HashFilter(hash,
new CryptoPP::HexEncoder(
new CryptoPP::StringSink(digest))));
std::cout << digest << std::endl;
return 0;
}
|
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.
| #Common_Lisp | Common Lisp | ;;; in addition to sha1, ironclad provides sha224, sha256, sha384, and sha512.
(defun sha1-hash (data)
(let ((sha1 (ironclad:make-digest 'ironclad:sha1))
(bin-data (ironclad:ascii-string-to-byte-array data)))
(ironclad:update-digest sha1 bin-data)
(ironclad:byte-array-to-hex-string (ironclad:produce-digest sha1))))
|
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)
| #C.2B.2B | C++ | template<typename F> class fivetoseven
{
public:
fivetoseven(F f): d5(f), rem(0), max(1) {}
int operator()();
private:
F d5;
int rem, max;
};
template<typename F>
int fivetoseven<F>::operator()()
{
while (rem/7 == max/7)
{
while (max < 7)
{
int rand5 = d5()-1;
max *= 5;
rem = 5*rem + rand5;
}
int groups = max / 7;
if (rem >= 7*groups)
{
rem -= 7*groups;
max -= 7*groups;
}
}
int result = rem % 7;
rem /= 7;
max /= 7;
return result+1;
}
int d5()
{
return 5.0*std::rand()/(RAND_MAX + 1.0) + 1;
}
fivetoseven<int(*)()> d7(d5);
int main()
{
srand(time(0));
test_distribution(d5, 1000000, 0.001);
test_distribution(d7, 1000000, 0.001);
} |
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.
| #J | J | NB. Primes Not Greater Than (the input)
NB. The 1 _1 p: ... logic here allows the input value to
NB. be included in the list in the case it itself is prime
pngt =: p:@:i.@:([: +/ 1 _1 p:"0 ])
NB. Add 6 and see which sums appear in input list
sexy =: ] #~ + e. ]
NB. Iterate "sexy" logic up to orgy size
orgy =: sexy&.>^:( ({.@:[) ` (<@:{:@:[) ` (<@:]) )
sp =: dyad define
'pd os' =. x NB. x is prime distance (6), orgy size (5)
p =. pngt y
o =. x orgy p
g =. o +/&.> <\ +/\ _1 |.!.0 os # pd NB. Groups
's g' =. split g NB. Split singles from groups
l =. (({.~ -) 5 <. #)&.> g NB. Last (max) 5 groups
NB. I'm sure there's something clever with p-.s or similar,
NB. but (a) I don't want to think through it, and (b)
NB. it causes the kind of edge-case issues the spec warns
NB. about with 1000033
us =. p (] #~ 1 +:/@:p: +/)~ (+,-) pd NB. Unsexy numbers
( (# ; _10&{.) us ) , (#&.> g) ,. l
) |
http://rosettacode.org/wiki/SHA-256_Merkle_tree | SHA-256 Merkle tree | As described in its documentation, Amazon S3 Glacier requires that all uploaded files come with a checksum computed as a Merkle Tree using SHA-256.
Specifically, the SHA-256 hash is computed for each 1MiB block of the file. And then, starting from the beginning of the file, the raw hashes of consecutive blocks are paired up and concatenated together, and a new hash is computed from each concatenation. Then these are paired up and concatenated and hashed, and the process continues until there is only one hash left, which is the final checksum. The hexadecimal representation of this checksum is the value that must be included with the AWS API call to upload the object (or complete a multipart upload).
Implement this algorithm in your language; you can use the code from the SHA-256 task for the actual hash computations. For better manageability and portability, build the tree using a smaller block size of only 1024 bytes, and demonstrate it on the RosettaCode title image with that block size. The final result should be the hexadecimal digest value a4f902cf9d51fe51eda156a6792e1445dff65edf3a217a1f3334cc9cf1495c2c.
| #Python | Python | #!/usr/bin/env python
# compute the root label for a SHA256 Merkle tree built on blocks of a given
# size (default 1MB) taken from the given file(s)
import argh
import hashlib
import sys
@argh.arg('filename', nargs='?', default=None)
def main(filename, block_size=1024*1024):
if filename:
fin = open(filename, 'rb')
else:
fin = sys.stdin
stack = []
block = fin.read(block_size)
while block:
# a node is a pair: ( tree-level, hash )
node = (0, hashlib.sha256(block).digest())
stack.append(node)
# concatenate adjacent pairs at the same level
while len(stack) >= 2 and stack[-2][0] == stack[-1][0]:
a = stack[-2]
b = stack[-1]
l = a[0]
stack[-2:] = [(l+1, hashlib.sha256(a[1] + b[1]).digest())]
block = fin.read(block_size)
while len(stack) > 1:
# at the end we have to concatenate even across levels
a = stack[-2]
b = stack[-1]
al = a[0]
bl = b[0]
stack[-2:] = [(max(al, bl)+1, hashlib.sha256(a[1] + b[1]).digest())]
print(stack[0][1].hex())
argh.dispatch_command(main)
|
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
| #COBOL | COBOL |
IDENTIFICATION DIVISION.
PROGRAM-ID. CHARSET.
DATA DIVISION.
WORKING-STORAGE SECTION.
01 CHARCODE PIC 9(3) VALUE 32.
PROCEDURE DIVISION.
MAIN-PROCEDURE.
PERFORM UNTIL CHARCODE=128
DISPLAY FUNCTION CONCATENATE(
FUNCTION CONCATENATE(
CHARCODE,
" : "
),
FUNCTION CONCATENATE(
FUNCTION CHAR(CHARCODE),
" "
)
)
WITH NO ADVANCING
ADD 1 TO CHARCODE
END-PERFORM.
END PROGRAM CHARSET.
|
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
| #Kotlin | Kotlin | // version 1.1.2
const val ORDER = 4
const val SIZE = 1 shl ORDER
fun main(args: Array<String>) {
for (y in SIZE - 1 downTo 0) {
for (i in 0 until y) print(" ")
for (x in 0 until SIZE - y) print(if ((x and y) != 0) " " else "* ")
println()
}
} |
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
| #Factor | Factor | USING: kernel math math.matrices prettyprint ;
: sierpinski ( n -- )
1 - { { 1 1 1 } { 1 0 1 } { 1 1 1 } } swap over [ kron ]
curry times [ 1 = "#" " " ? ] matrix-map simple-table. ;
3 sierpinski |
http://rosettacode.org/wiki/Shoelace_formula_for_polygonal_area | Shoelace formula for polygonal area | Given the n + 1 vertices x[0], y[0] .. x[N], y[N] of a simple polygon described in a clockwise direction, then the polygon's area can be calculated by:
abs( (sum(x[0]*y[1] + ... x[n-1]*y[n]) + x[N]*y[0]) -
(sum(x[1]*y[0] + ... x[n]*y[n-1]) + x[0]*y[N])
) / 2
(Where abs returns the absolute value)
Task
Write a function/method/routine to use the the Shoelace formula to calculate the area of the polygon described by the ordered points:
(3,4), (5,11), (12,8), (9,5), and (5,6)
Show the answer here, on this page.
| #Wren | Wren | var shoelace = Fn.new { |pts|
var area = 0
for (i in 0...pts.count-1) {
area = area + pts[i][0]*pts[i+1][1] - pts[i+1][0]*pts[i][1]
}
return (area + pts[-1][0]*pts[0][1] - pts[0][0]*pts[-1][1]).abs / 2
}
var pts = [ [3, 4], [5, 11], [12, 8], [9, 5], [5, 6] ]
System.print("The polygon with vertices at %(pts) has an area of %(shoelace.call(pts)).") |
http://rosettacode.org/wiki/Shoelace_formula_for_polygonal_area | Shoelace formula for polygonal area | Given the n + 1 vertices x[0], y[0] .. x[N], y[N] of a simple polygon described in a clockwise direction, then the polygon's area can be calculated by:
abs( (sum(x[0]*y[1] + ... x[n-1]*y[n]) + x[N]*y[0]) -
(sum(x[1]*y[0] + ... x[n]*y[n-1]) + x[0]*y[N])
) / 2
(Where abs returns the absolute value)
Task
Write a function/method/routine to use the the Shoelace formula to calculate the area of the polygon described by the ordered points:
(3,4), (5,11), (12,8), (9,5), and (5,6)
Show the answer here, on this page.
| #XPL0 | XPL0 | proc real Shoelace(N, X, Y);
int N, X, Y;
int S, I;
[S:= 0;
for I:= 0 to N-2 do
S:= S + X(I)*Y(I+1) - X(I+1)*Y(I);
S:= S + X(I)*Y(0) - X(0)*Y(I);
return float(abs(S)) / 2.0;
];
RlOut(0, Shoelace(5, [3, 5, 12, 9, 5], [4, 11, 8, 5, 6])) |
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.
| #Retro | Retro | echo '\'hello s:put nl bye' | retro |
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.
| #REXX | REXX |
╔══════════════════════════════════════════════╗
║ ║
║ from the MS Window command line (cmd.exe) ║
║ ║
╚══════════════════════════════════════════════╝
echo do j=10 by 20 for 4; say right('hello',j); end | regina |
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.
| #Ring | Ring |
see "Hello World!" + nl
|
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.
| #Ruby | Ruby | $ ruby -e 'puts "Hello"'
Hello |
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.
| #FreeBASIC | FreeBASIC | ' FB 1.05.0 Win64
Function a(p As Boolean) As Boolean
Print "a() called"
Return p
End Function
Function b(p As Boolean) As Boolean
Print "b() called"
Return p
End Function
Dim As Boolean i, j, x, y
i = False
j = True
Print "Without short-circuit evaluation :"
Print
x = a(i) And b(j)
y = a(i) Or b(j)
Print "x = "; x; " y = "; y
Print
Print "With short-circuit evaluation :"
Print
x = a(i) AndAlso b(j) '' b(j) not called as a(i) = false and so x must be false
y = a(i) OrElse b(j) '' b(j) still called as can't determine y unless it is
Print "x = "; x; " y = "; y
Print
Print "Press any key to quit"
Sleep |
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
| #C.2B.2B | C++ |
#include <time.h>
#include <algorithm>
#include <iostream>
#include <iomanip>
#include <vector>
#include <string>
enum color {
red, green, purple
};
enum symbol {
oval, squiggle, diamond
};
enum number {
one, two, three
};
enum shading {
solid, open, striped
};
class card {
public:
card( color c, symbol s, number n, shading h ) {
clr = c; smb = s; nbr = n; shd = h;
}
color getColor() {
return clr;
}
symbol getSymbol() {
return smb;
}
number getNumber() {
return nbr;
}
shading getShading() {
return shd;
}
std::string toString() {
std::string str = "[";
str += clr == red ? "red " : clr == green ? "green " : "purple ";
str += nbr == one ? "one " : nbr == two ? "two " : "three ";
str += smb == oval ? "oval " : smb == squiggle ? "squiggle " : "diamond ";
str += shd == solid ? "solid" : shd == open ? "open" : "striped";
return str + "]";
}
private:
color clr;
symbol smb;
number nbr;
shading shd;
};
typedef struct {
std::vector<size_t> index;
} set;
class setPuzzle {
public:
setPuzzle() {
for( size_t c = red; c <= purple; c++ ) {
for( size_t s = oval; s <= diamond; s++ ) {
for( size_t n = one; n <= three; n++ ) {
for( size_t h = solid; h <= striped; h++ ) {
card crd( static_cast<color> ( c ),
static_cast<symbol> ( s ),
static_cast<number> ( n ),
static_cast<shading>( h ) );
_cards.push_back( crd );
}
}
}
}
}
void create( size_t countCards, size_t countSets, std::vector<card>& cards, std::vector<set>& sets ) {
while( true ) {
sets.clear();
cards.clear();
std::random_shuffle( _cards.begin(), _cards.end() );
for( size_t f = 0; f < countCards; f++ ) {
cards.push_back( _cards.at( f ) );
}
for( size_t c1 = 0; c1 < cards.size() - 2; c1++ ) {
for( size_t c2 = c1 + 1; c2 < cards.size() - 1; c2++ ) {
for( size_t c3 = c2 + 1; c3 < cards.size(); c3++ ) {
if( testSet( &cards.at( c1 ), &cards.at( c2 ), &cards.at( c3 ) ) ) {
set s;
s.index.push_back( c1 ); s.index.push_back( c2 ); s.index.push_back( c3 );
sets.push_back( s );
}
}
}
}
if( sets.size() == countSets ) return;
}
}
private:
bool testSet( card* c1, card* c2, card* c3 ) {
int
c = ( c1->getColor() + c2->getColor() + c3->getColor() ) % 3,
s = ( c1->getSymbol() + c2->getSymbol() + c3->getSymbol() ) % 3,
n = ( c1->getNumber() + c2->getNumber() + c3->getNumber() ) % 3,
h = ( c1->getShading() + c2->getShading() + c3->getShading() ) % 3;
return !( c + s + n + h );
}
std::vector<card> _cards;
};
void displayCardsSets( std::vector<card>& cards, std::vector<set>& sets ) {
size_t cnt = 1;
std::cout << " ** DEALT " << cards.size() << " CARDS: **\n";
for( std::vector<card>::iterator i = cards.begin(); i != cards.end(); i++ ) {
std::cout << std::setw( 2 ) << cnt++ << ": " << ( *i ).toString() << "\n";
}
std::cout << "\n ** CONTAINING " << sets.size() << " SETS: **\n";
for( std::vector<set>::iterator i = sets.begin(); i != sets.end(); i++ ) {
for( size_t j = 0; j < ( *i ).index.size(); j++ ) {
std::cout << " " << std::setiosflags( std::ios::left ) << std::setw( 34 )
<< cards.at( ( *i ).index.at( j ) ).toString() << " : "
<< std::resetiosflags( std::ios::left ) << std::setw( 2 ) << ( *i ).index.at( j ) + 1 << "\n";
}
std::cout << "\n";
}
std::cout << "\n\n";
}
int main( int argc, char* argv[] ) {
srand( static_cast<unsigned>( time( NULL ) ) );
setPuzzle p;
std::vector<card> v9, v12;
std::vector<set> s4, s6;
p.create( 9, 4, v9, s4 );
p.create( 12, 6, v12, s6 );
displayCardsSets( v9, s4 );
displayCardsSets( v12, s6 );
return 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
| #Cach.C3.A9_ObjectScript | Caché ObjectScript | USER>set hash=$System.Encryption.SHAHash(256, "Rosetta code")
USER>zzdump hash
0000: 76 4F AF 5C 61 AC 31 5F 14 97 F9 DF A5 42 71 39
0010: 65 B7 85 E5 CC 2F 70 7D 64 68 D7 D1 12 4C DF CF |
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
| #Clojure | Clojure | (use 'pandect.core)
(sha256 "Rosetta code") |
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.
| #Crystal | Crystal | require "openssl"
puts OpenSSL::Digest.new("sha1").update("Rosetta Code") |
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.
| #D | D | void main() {
import std.stdio, std.digest.sha;
writefln("%-(%02x%)", "Ars longa, vita brevis".sha1Of);
} |
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)
| #Clojure | Clojure | (def dice5 #(rand-int 5))
(defn dice7 []
(quot (->> dice5 ; do the following to dice5
(repeatedly 2) ; call it twice
(apply #(+ %1 (* 5 %2))) ; d1 + 5*d2 => 0..24
#() ; wrap that up in a function
repeatedly ; make infinite sequence of the above
(drop-while #(> % 20)) ; throw away anything > 20
first) ; grab first acceptable element
3)) ; divide by three rounding down
(doseq [n [100 1000 10000] [num count okay?] (verify dice7 n)]
(println "Saw" num count "times:"
(if okay? "that's" " not") "acceptable")) |
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)
| #Common_Lisp | Common Lisp | (defun d5 ()
(1+ (random 5)))
(defun d7 ()
(loop for d55 = (+ (* 5 (d5)) (d5) -6)
until (< d55 21)
finally (return (1+ (mod d55 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.
| #Java | Java |
import java.util.ArrayList;
import java.util.List;
public class SexyPrimes {
public static void main(String[] args) {
sieve();
int pairs = 0;
List<String> pairList = new ArrayList<>();
int triples = 0;
List<String> tripleList = new ArrayList<>();
int quadruplets = 0;
List<String> quadrupletList = new ArrayList<>();
int unsexyCount = 1; // 2 (the even prime) not found in tests below.
List<String> unsexyList = new ArrayList<>();
for ( int i = 3 ; i < MAX ; i++ ) {
if ( i-6 >= 3 && primes[i-6] && primes[i] ) {
pairs++;
pairList.add((i-6) + " " + i);
if ( pairList.size() > 5 ) {
pairList.remove(0);
}
}
else if ( i < MAX-2 && primes[i] && ! (i+6<MAX && primes[i] && primes[i+6])) {
unsexyCount++;
unsexyList.add("" + i);
if ( unsexyList.size() > 10 ) {
unsexyList.remove(0);
}
}
if ( i-12 >= 3 && primes[i-12] && primes[i-6] && primes[i] ) {
triples++;
tripleList.add((i-12) + " " + (i-6) + " " + i);
if ( tripleList.size() > 5 ) {
tripleList.remove(0);
}
}
if ( i-16 >= 3 && primes[i-18] && primes[i-12] && primes[i-6] && primes[i] ) {
quadruplets++;
quadrupletList.add((i-18) + " " + (i-12) + " " + (i-6) + " " + i);
if ( quadrupletList.size() > 5 ) {
quadrupletList.remove(0);
}
}
}
System.out.printf("Count of sexy triples less than %,d = %,d%n", MAX, pairs);
System.out.printf("The last 5 sexy pairs:%n %s%n%n", pairList.toString().replaceAll(", ", "], ["));
System.out.printf("Count of sexy triples less than %,d = %,d%n", MAX, triples);
System.out.printf("The last 5 sexy triples:%n %s%n%n", tripleList.toString().replaceAll(", ", "], ["));
System.out.printf("Count of sexy quadruplets less than %,d = %,d%n", MAX, quadruplets);
System.out.printf("The last 5 sexy quadruplets:%n %s%n%n", quadrupletList.toString().replaceAll(", ", "], ["));
System.out.printf("Count of unsexy primes less than %,d = %,d%n", MAX, unsexyCount);
System.out.printf("The last 10 unsexy primes:%n %s%n%n", unsexyList.toString().replaceAll(", ", "], ["));
}
private static int MAX = 1_000_035;
private static boolean[] primes = new boolean[MAX];
private static final void sieve() {
// primes
for ( int i = 2 ; i < MAX ; i++ ) {
primes[i] = true;
}
for ( int i = 2 ; i < MAX ; i++ ) {
if ( primes[i] ) {
for ( int j = 2*i ; j < MAX ; j += i ) {
primes[j] = false;
}
}
}
}
}
|
http://rosettacode.org/wiki/SHA-256_Merkle_tree | SHA-256 Merkle tree | As described in its documentation, Amazon S3 Glacier requires that all uploaded files come with a checksum computed as a Merkle Tree using SHA-256.
Specifically, the SHA-256 hash is computed for each 1MiB block of the file. And then, starting from the beginning of the file, the raw hashes of consecutive blocks are paired up and concatenated together, and a new hash is computed from each concatenation. Then these are paired up and concatenated and hashed, and the process continues until there is only one hash left, which is the final checksum. The hexadecimal representation of this checksum is the value that must be included with the AWS API call to upload the object (or complete a multipart upload).
Implement this algorithm in your language; you can use the code from the SHA-256 task for the actual hash computations. For better manageability and portability, build the tree using a smaller block size of only 1024 bytes, and demonstrate it on the RosettaCode title image with that block size. The final result should be the hexadecimal digest value a4f902cf9d51fe51eda156a6792e1445dff65edf3a217a1f3334cc9cf1495c2c.
| #Raku | Raku | use Digest::SHA256::Native;
unit sub MAIN(Int :b(:$block-size) = 1024 × 1024, *@args);
my $in = @args ?? IO::CatHandle.new(@args) !! $*IN;
my @blocks = do while my $block = $in.read: $block-size { sha256 $block };
while @blocks > 1 {
@blocks = @blocks.batch(2).map: { $_ > 1 ?? sha256([~] $_) !! .[0] }
}
say @blocks[0]».fmt('%02x').join; |
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
| #Commodore_BASIC | Commodore BASIC | 100 PRINT CHR$(147);:REM CLEAR SCREEN
110 PRINT CHR$(14);:REM CHARACTER SET 2
120 PRINT "COMMODORE 64 - BASIC V2"
130 PRINT "CHARACTER SET 2"
140 PRINT
150 FOR R=0 TO 15
160 FOR C=0 TO 5
170 A=32+R+C*16
180 PRINT RIGHT$(" "+STR$(A),4);":";CHR$(A);
190 NEXT C
200 PRINT
210 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
| #Liberty_BASIC | Liberty BASIC | nOrder=4
call triangle 1, 1, nOrder
end
SUB triangle x, y, n
IF n = 0 THEN
LOCATE x,y: PRINT "*";
ELSE
n=n-1
length=2^n
call triangle x, y+length, n
call triangle x+length, y, n
call triangle x+length*2, y+length, n
END IF
END SUB |
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
| #Fan | Fan | **
** Generates a square Sierpinski gasket
**
class SierpinskiCarpet
{
public static Bool inCarpet(Int x, Int y){
while(x!=0 && y!=0){
if (x % 3 == 1 && y % 3 == 1)
return false;
x /= 3;
y /= 3;
}
return true;
}
static Int pow(Int n, Int exp)
{
rslt := 1
exp.times { rslt *= n }
return rslt
}
public static Void carpet(Int n){
for(i := 0; i < pow(3, n); i++){
buf := StrBuf()
for(j := 0; j < pow(3, n); j++){
if( inCarpet(i, j))
buf.add("*");
else
buf.add(" ");
}
echo(buf);
}
}
Void main()
{
carpet(4)
}
} |
http://rosettacode.org/wiki/Shoelace_formula_for_polygonal_area | Shoelace formula for polygonal area | Given the n + 1 vertices x[0], y[0] .. x[N], y[N] of a simple polygon described in a clockwise direction, then the polygon's area can be calculated by:
abs( (sum(x[0]*y[1] + ... x[n-1]*y[n]) + x[N]*y[0]) -
(sum(x[1]*y[0] + ... x[n]*y[n-1]) + x[0]*y[N])
) / 2
(Where abs returns the absolute value)
Task
Write a function/method/routine to use the the Shoelace formula to calculate the area of the polygon described by the ordered points:
(3,4), (5,11), (12,8), (9,5), and (5,6)
Show the answer here, on this page.
| #zkl | zkl | fcn areaByShoelace(points){ // ( (x,y),(x,y)...)
xs,ys:=Utils.Helpers.listUnzip(points); // (x,x,...), (y,y,,,)
( xs.zipWith('*,ys[1,*]).sum(0) + xs[-1]*ys[0] -
xs[1,*].zipWith('*,ys).sum(0) - xs[0]*ys[-1] )
.abs().toFloat()/2;
} |
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.
| #Run_BASIC | Run BASIC | print shell$("echo hello world") |
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.
| #Rust | Rust | $ echo 'fn main(){println!("Hello!")}' | rustc -;./rust_out |
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.
| #S-lang | S-lang | slsh -e 'print("Hello, World")' |
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.
| #Scala | Scala | C:\>scala -e "println(\"Hello\")"
Hello |
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.
| #F.C5.8Drmul.C3.A6 | Fōrmulæ | package main
import "fmt"
func a(v bool) bool {
fmt.Print("a")
return v
}
func b(v bool) bool {
fmt.Print("b")
return v
}
func test(i, j bool) {
fmt.Printf("Testing a(%t) && b(%t)\n", i, j)
fmt.Print("Trace: ")
fmt.Println("\nResult:", a(i) && b(j))
fmt.Printf("Testing a(%t) || b(%t)\n", i, j)
fmt.Print("Trace: ")
fmt.Println("\nResult:", a(i) || b(j))
fmt.Println("")
}
func main() {
test(false, false)
test(false, true)
test(true, false)
test(true, 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
| #Ceylon | Ceylon | import ceylon.random {
Random,
DefaultRandom
}
abstract class Feature() of Color | Symbol | NumberOfSymbols | Shading {}
abstract class Color()
of red | green | purple
extends Feature() {}
object red extends Color() {
string => "red";
}
object green extends Color() {
string => "green";
}
object purple extends Color() {
string => "purple";
}
abstract class Symbol()
of oval | squiggle | diamond
extends Feature() {}
object oval extends Symbol() {
string => "oval";
}
object squiggle extends Symbol() {
string => "squiggle";
}
object diamond extends Symbol() {
string => "diamond";
}
abstract class NumberOfSymbols()
of one | two | three
extends Feature() {}
object one extends NumberOfSymbols() {
string => "one";
}
object two extends NumberOfSymbols() {
string => "two";
}
object three extends NumberOfSymbols() {
string => "three";
}
abstract class Shading()
of solid | open | striped
extends Feature() {}
object solid extends Shading() {
string => "solid";
}
object open extends Shading() {
string => "open";
}
object striped extends Shading() {
string => "striped";
}
class Card(color, symbol, number, shading) {
shared Color color;
shared Symbol symbol;
shared NumberOfSymbols number;
shared Shading shading;
value plural => number == one then "" else "s";
string => "``number`` ``shading`` ``color`` ``symbol````plural``";
}
{Card*} deck = {
for(color in `Color`.caseValues)
for(symbol in `Symbol`.caseValues)
for(number in `NumberOfSymbols`.caseValues)
for(shading in `Shading`.caseValues)
Card(color, symbol, number, shading)
};
alias CardSet => [Card+];
Boolean validSet(CardSet cards) {
function allOrOne({Feature*} features) =>
let(uniques = features.distinct.size)
uniques == 3 || uniques == 1;
return allOrOne(cards*.color) &&
allOrOne(cards*.number) &&
allOrOne(cards*.shading) &&
allOrOne(cards*.symbol);
}
{CardSet*} findSets(Card* cards) =>
cards
.sequence()
.combinations(3)
.filter(validSet);
Random random = DefaultRandom();
class Mode of basic | advanced {
shared Integer numberOfCards;
shared Integer numberOfSets;
shared new basic {
numberOfCards = 9;
numberOfSets = 4;
}
shared new advanced {
numberOfCards = 12;
numberOfSets = 6;
}
}
[{Card*}, {CardSet*}] deal(Mode mode) {
value randomStream = random.elements(deck);
while(true) {
value cards = randomStream.distinct.take(mode.numberOfCards).sequence();
value sets = findSets(*cards);
if(sets.size == mode.numberOfSets) {
return [cards, sets];
}
}
}
shared void run() {
value [cards, sets] = deal(Mode.basic);
print("The cards dealt are:
");
cards.each(print);
print("
Containing the sets:
");
for(cardSet in sets) {
cardSet.each(print);
print("");
}
} |
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
| #D | D | import std.stdio, std.random, std.array, std.conv, std.traits,
std.exception, std.range, std.algorithm;
const class SetDealer {
protected {
enum Color: ubyte {green, purple, red}
enum Number: ubyte {one, two, three}
enum Symbol: ubyte {oval, diamond, squiggle}
enum Fill: ubyte {open, striped, solid}
static struct Card {
Color c;
Number n;
Symbol s;
Fill f;
}
static immutable Card[81] deck;
}
static this() pure nothrow @safe {
immutable colors = [EnumMembers!Color];
immutable numbers = [EnumMembers!Number];
immutable symbols = [EnumMembers!Symbol];
immutable fill = [EnumMembers!Fill];
deck = deck.length.iota.map!(i => Card(colors[i / 27],
numbers[(i / 9) % 3],
symbols[(i / 3) % 3],
fill[i % 3])).array;
}
// randomSample produces a sorted output that's convenient in our
// case because we're printing to stout. Normally you would want
// to shuffle.
immutable(Card)[] deal(in uint numCards) const {
enforce(numCards < deck.length, "Number of cards too large");
return deck[].randomSample(numCards).array;
}
// The summed enums of valid sets are always zero or a multiple
// of 3.
bool validSet(in ref Card c1, in ref Card c2, in ref Card c3)
const pure nothrow @safe @nogc {
return !((c1.c + c2.c + c3.c) % 3 ||
(c1.n + c2.n + c3.n) % 3 ||
(c1.s + c2.s + c3.s) % 3 ||
(c1.f + c2.f + c3.f) % 3);
}
immutable(Card)[3][] findSets(in Card[] cards, in uint target = 0)
const pure nothrow @safe {
immutable len = cards.length;
if (len < 3)
return null;
typeof(return) sets;
foreach (immutable i; 0 .. len - 2)
foreach (immutable j; i + 1 .. len - 1)
foreach (immutable k; j + 1 .. len)
if (validSet(cards[i], cards[j], cards[k])) {
sets ~= [cards[i], cards[j], cards[k]];
if (target != 0 && sets.length > target)
return null;
}
return sets;
}
}
const final class SetPuzzleDealer : SetDealer {
enum {basic = 9, advanced = 12}
override immutable(Card)[] deal(in uint numCards = basic) const {
immutable numSets = numCards / 2;
typeof(return) cards;
do {
cards = super.deal(numCards);
} while (findSets(cards, numSets).length != numSets);
return cards;
}
}
void main() {
const dealer = new SetPuzzleDealer;
const cards = dealer.deal;
writefln("DEALT %d CARDS:", cards.length);
writefln("%(%s\n%)", cards);
immutable sets = dealer.findSets(cards);
immutable len = sets.length;
writefln("\nFOUND %d SET%s:", len, len == 1 ? "" : "S");
writefln("%(%(%s\n%)\n\n%)", sets);
} |
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
| #Common_Lisp | Common Lisp | (ql:quickload 'ironclad)
(defun sha-256 (str)
(ironclad:byte-array-to-hex-string
(ironclad:digest-sequence :sha256
(ironclad:ascii-string-to-byte-array str))))
(sha-256 "Rosetta code") |
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
| #Crystal | Crystal | require "openssl"
puts OpenSSL::Digest.new("SHA256").update("Rosetta code")
|
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.
| #Delphi | Delphi |
program Sha_1;
{$APPTYPE CONSOLE}
uses
System.SysUtils,
DCPsha1;
function SHA1(const Str: string): string;
var
HashDigest: array of byte;
d: Byte;
begin
Result := '';
with TDCP_sha1.Create(nil) do
begin
Init;
UpdateStr(Str);
SetLength(HashDigest, GetHashSize div 8);
final(HashDigest[0]);
for d in HashDigest do
Result := Result + d.ToHexString(2);
Free;
end;
end;
begin
Writeln(SHA1('Rosetta Code'));
readln;
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)
| #D | D | import std.random;
import verify_distribution_uniformity_naive: distCheck;
/// Generates a random number in [1, 5].
int dice5() /*pure nothrow*/ @safe {
return uniform(1, 6);
}
/// Naive, generates a random number in [1, 7] using dice5.
int fiveToSevenNaive() /*pure nothrow*/ @safe {
immutable int r = dice5() + dice5() * 5 - 6;
return (r < 21) ? (r % 7) + 1 : fiveToSevenNaive();
}
/**
Generates a random number in [1, 7] using dice5,
minimizing calls to dice5.
*/
int fiveToSevenSmart() @safe {
static int rem = 0, max = 1;
while (rem / 7 == max / 7) {
while (max < 7) {
immutable int rand5 = dice5() - 1;
max *= 5;
rem = 5 * rem + rand5;
}
immutable int groups = max / 7;
if (rem >= 7 * groups) {
rem -= 7 * groups;
max -= 7 * groups;
}
}
immutable int result = rem % 7;
rem /= 7;
max /= 7;
return result + 1;
}
void main() /*@safe*/ {
enum int N = 400_000;
distCheck(&dice5, N, 1);
distCheck(&fiveToSevenNaive, N, 1);
distCheck(&fiveToSevenSmart, N, 1);
} |
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.
| #Julia | Julia |
using Primes
function nextby6(n, a)
top = length(a)
i = n + 1
j = n + 2
k = n + 3
if n >= top
return n
end
possiblenext = a[n] + 6
if i <= top && possiblenext == a[i]
return i
elseif j <= top && possiblenext == a[j]
return j
elseif k <= top && possiblenext == a[k]
return k
end
return n
end
function lastones(dict, n)
arr = sort(collect(keys(dict)))
beginidx = max(1, length(arr) - n + 1)
arr[beginidx: end]
end
function lastoneslessthan(dict, n, ceiling)
arr = filter(y -> y < ceiling, lastones(dict, n+3))
beginidx = max(1, length(arr) - n + 1)
arr[beginidx: end]
end
function primesbysexiness(x)
twins = Dict{Int64, Array{Int64,1}}()
triplets = Dict{Int64, Array{Int64,1}}()
quadruplets = Dict{Int64, Array{Int64,1}}()
quintuplets = Dict{Int64, Array{Int64,1}}()
possibles = primes(x + 30)
singles = filter(y -> y <= x - 6, possibles)
unsexy = Dict(p => true for p in singles)
for (i, p) in enumerate(singles)
twinidx = nextby6(i, possibles)
if twinidx > i
delete!(unsexy, p)
delete!(unsexy, p + 6)
twins[p] = [i, twinidx]
tripidx = nextby6(twinidx, possibles)
if tripidx > twinidx
triplets[p] = [i, twinidx, tripidx]
quadidx = nextby6(tripidx, possibles)
if quadidx > tripidx
quadruplets[p] = [i, twinidx, tripidx, quadidx]
quintidx = nextby6(quadidx, possibles)
if quintidx > quadidx
quintuplets[p] = [i, twinidx, tripidx, quadidx, quintidx]
end
end
end
end
end
# Find and display the count of each group
println("There are:\n$(length(twins)) twins,\n",
"$(length(triplets)) triplets,\n",
"$(length(quadruplets)) quadruplets, and\n",
"$(length(quintuplets)) quintuplets less than $x.")
println("The last 5 twin primes start with ", lastoneslessthan(twins, 5, x - 6))
println("The last 5 triplet primes start with ", lastones(triplets, 5))
println("The last 5 quadruplet primes start with ", lastones(quadruplets, 5))
println("The quintuplet primes start with ", lastones(quintuplets, 5))
println("There are $(length(unsexy)) unsexy primes less than $x.")
lastunsexy = sort(collect(keys(unsexy)))[length(unsexy) - 9: end]
println("The last 10 unsexy primes are: $lastunsexy")
end
primesbysexiness(1000035) |
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.
| #Kotlin | Kotlin | // Version 1.2.71
fun sieve(lim: Int): BooleanArray {
var limit = lim + 1
// True denotes composite, false denotes prime.
val c = BooleanArray(limit) // all false by default
c[0] = true
c[1] = true
// No need to bother with even numbers over 2 for this task.
var p = 3 // Start from 3.
while (true) {
val p2 = p * p
if (p2 >= limit) break
for (i in p2 until limit step 2 * p) c[i] = true
while (true) {
p += 2
if (!c[p]) break
}
}
return c
}
fun printHelper(cat: String, len: Int, lim: Int, max: Int): Pair<Int, String> {
val cat2 = if (cat != "unsexy primes") "sexy prime " + cat else cat
System.out.printf("Number of %s less than %d = %,d\n", cat2, lim, len)
val last = if (len < max) len else max
val verb = if (last == 1) "is" else "are"
return last to verb
}
fun main(args: Array<String>) {
val lim = 1_000_035
val sv = sieve(lim - 1)
val pairs = mutableListOf<List<Int>>()
val trips = mutableListOf<List<Int>>()
val quads = mutableListOf<List<Int>>()
val quins = mutableListOf<List<Int>>()
val unsexy = mutableListOf(2, 3)
for (i in 3 until lim step 2) {
if (i > 5 && i < lim - 6 && !sv[i] && sv[i - 6] && sv[i + 6]) {
unsexy.add(i)
continue
}
if (i < lim - 6 && !sv[i] && !sv[i + 6]) {
val pair = listOf(i, i + 6)
pairs.add(pair)
} else continue
if (i < lim - 12 && !sv[i + 12]) {
val trip = listOf(i, i + 6, i + 12)
trips.add(trip)
} else continue
if (i < lim - 18 && !sv[i + 18]) {
val quad = listOf(i, i + 6, i + 12, i + 18)
quads.add(quad)
} else continue
if (i < lim - 24 && !sv[i + 24]) {
val quin = listOf(i, i + 6, i + 12, i + 18, i + 24)
quins.add(quin)
}
}
var (n2, verb2) = printHelper("pairs", pairs.size, lim, 5)
System.out.printf("The last %d %s:\n %s\n\n", n2, verb2, pairs.takeLast(n2))
var (n3, verb3) = printHelper("triplets", trips.size, lim, 5)
System.out.printf("The last %d %s:\n %s\n\n", n3, verb3, trips.takeLast(n3))
var (n4, verb4) = printHelper("quadruplets", quads.size, lim, 5)
System.out.printf("The last %d %s:\n %s\n\n", n4, verb4, quads.takeLast(n4))
var (n5, verb5) = printHelper("quintuplets", quins.size, lim, 5)
System.out.printf("The last %d %s:\n %s\n\n", n5, verb5, quins.takeLast(n5))
var (nu, verbu) = printHelper("unsexy primes", unsexy.size, lim, 10)
System.out.printf("The last %d %s:\n %s\n\n", nu, verbu, unsexy.takeLast(nu))
} |
http://rosettacode.org/wiki/SHA-256_Merkle_tree | SHA-256 Merkle tree | As described in its documentation, Amazon S3 Glacier requires that all uploaded files come with a checksum computed as a Merkle Tree using SHA-256.
Specifically, the SHA-256 hash is computed for each 1MiB block of the file. And then, starting from the beginning of the file, the raw hashes of consecutive blocks are paired up and concatenated together, and a new hash is computed from each concatenation. Then these are paired up and concatenated and hashed, and the process continues until there is only one hash left, which is the final checksum. The hexadecimal representation of this checksum is the value that must be included with the AWS API call to upload the object (or complete a multipart upload).
Implement this algorithm in your language; you can use the code from the SHA-256 task for the actual hash computations. For better manageability and portability, build the tree using a smaller block size of only 1024 bytes, and demonstrate it on the RosettaCode title image with that block size. The final result should be the hexadecimal digest value a4f902cf9d51fe51eda156a6792e1445dff65edf3a217a1f3334cc9cf1495c2c.
| #Rust | Rust | extern crate crypto;
use crypto::digest::Digest;
use crypto::sha2::Sha256;
use std::fs::File;
use std::io::prelude::*;
use std::io::BufReader;
fn sha256_merkle_tree(filename: &str, block_size: usize) -> std::io::Result<Option<Vec<u8>>> {
let mut md = Sha256::new();
let mut input = BufReader::new(File::open(filename)?);
let mut buffer = vec![0; block_size];
let mut digest = vec![0; md.output_bytes()];
let mut digests = Vec::new();
loop {
let bytes = input.read(&mut buffer)?;
if bytes == 0 {
break;
}
md.reset();
md.input(&buffer[0..bytes]);
md.result(&mut digest);
digests.push(digest.clone());
}
let mut len = digests.len();
if len == 0 {
return Ok(None);
}
while len > 1 {
let mut j = 0;
let mut i = 0;
while i < len {
if i + 1 < len {
md.reset();
md.input(&digests[i]);
md.input(&digests[i + 1]);
md.result(&mut digests[j]);
} else {
digests.swap(i, j);
}
i += 2;
j += 1;
}
len = j;
}
Ok(Some(digests[0].clone()))
}
fn digest_to_string(digest: &[u8]) -> String {
let mut result = String::new();
for x in digest {
result.push_str(&format!("{:02x}", x));
}
result
}
fn main() {
match sha256_merkle_tree("title.png", 1024) {
Ok(Some(digest)) => println!("{}", digest_to_string(&digest)),
Ok(None) => {}
Err(error) => eprintln!("I/O error: {}", error),
}
} |
http://rosettacode.org/wiki/SHA-256_Merkle_tree | SHA-256 Merkle tree | As described in its documentation, Amazon S3 Glacier requires that all uploaded files come with a checksum computed as a Merkle Tree using SHA-256.
Specifically, the SHA-256 hash is computed for each 1MiB block of the file. And then, starting from the beginning of the file, the raw hashes of consecutive blocks are paired up and concatenated together, and a new hash is computed from each concatenation. Then these are paired up and concatenated and hashed, and the process continues until there is only one hash left, which is the final checksum. The hexadecimal representation of this checksum is the value that must be included with the AWS API call to upload the object (or complete a multipart upload).
Implement this algorithm in your language; you can use the code from the SHA-256 task for the actual hash computations. For better manageability and portability, build the tree using a smaller block size of only 1024 bytes, and demonstrate it on the RosettaCode title image with that block size. The final result should be the hexadecimal digest value a4f902cf9d51fe51eda156a6792e1445dff65edf3a217a1f3334cc9cf1495c2c.
| #Wren | Wren | import "io" for File
import "/crypto" for Sha256, Bytes
import "/seq" for Lst
import "/str" for Str
import "/fmt" for Conv
var bytes = File.read("title.png").bytes.toList
var chunks = Lst.chunks(bytes, 1024)
var hashes = List.filled(chunks.count, null)
var i = 0
for (chunk in chunks) {
var h = Sha256.digest(chunk.map { |b| String.fromByte(b) }.join())
hashes[i] = Str.chunks(h, 2).map { |x| Conv.atoi(x, 16) }.toList
i = i + 1
}
var buffer = List.filled(64, 0)
while (hashes.count > 1) {
var hashes2 = []
var i = 0
while (i < hashes.count) {
if (i < hashes.count - 1) {
for (j in 0..31) buffer[j] = hashes[i][j]
for (j in 0..31) buffer[j+32] = hashes[i+1][j]
var h = Sha256.digest(buffer.map { |b| String.fromByte(b) }.join())
var hb = Str.chunks(h, 2).map { |x| Conv.atoi(x, 16) }.toList
hashes2.add(hb)
} else {
hashes2.add(hashes[i])
}
i = i + 2
}
hashes = hashes2
}
System.print(Bytes.toHexString(hashes[0])) |
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
| #Common_Lisp | Common Lisp | (setq startVal 32)
(setq endVal 127)
(setq cols 6)
(defun print-val (val) "Prints the value for that ascii number"
(cond
((= val 32) (format t " 32: SPC "))
((= val 127) (format t "127: DEL~%"))
((and (zerop (mod (- val startVal) cols)) (< val 100)) (format t "~% ~d: ~a " val (int-char val)))
((and (zerop (mod (- val startVal) cols)) (>= val 100)) (format t "~%~d: ~a " val (int-char val)))
((< val 100) (format t " ~d: ~a " val (int-char val)))
((>= val 100) (format t "~d: ~a " val (int-char val)))
(t nil)))
(defun get-range (lower upper) "Returns a list of range lower to upper"
(if (> lower upper) '() (cons lower (get-range (+ 1 lower) upper))))
(mapcar #'print-val (get-range startVal endVal)) |
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
| #Logo | Logo | ; Print rows of the triangle from 0 to :limit inclusive.
; limit=15 gives the order 4 form per the task.
; The range of :y is arbitrary, any rows of the triangle can be printed.
make "limit 15
for [y 0 :limit] [
for [x -:limit :y] [
type ifelse (and :y+:x >= 0 ; blank left of triangle
(remainder :y+:x 2) = 0 ; only "even" squares
(bitand :y+:x :y-:x) = 0 ; Sierpinski bit test
) ["*] ["| |] ; star or space
]
print []
] |
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
| #Fennel | Fennel | (fn in-carpet? [x y]
(if
(or (= 0 x) (= 0 y)) true
(and (= 1 (% x 3)) (= 1 (% y 3))) false
(in-carpet? (// x 3) (// y 3))))
(fn make-carpet [size]
(for [y 0 (- (^ 3 size) 1)]
(for [x 0 (- (^ 3 size) 1)]
(if (in-carpet? x y)
(io.write "#")
(io.write " ")))
(io.write "\n")))
(for [i 0 3]
(make-carpet i)
(print)) |
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.
| #Scheme | Scheme | guile -c '(display "Hello, world!\n")' |
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.
| #Shiny | Shiny | shiny -e "say 'hi'" |
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.
| #Sidef | Sidef | % sidef -E "say 'hello'" |
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.
| #Slate | Slate | ./slate --eval "[inform: 'hello'] ensure: [exit: 0].". |
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.
| #Go | Go | package main
import "fmt"
func a(v bool) bool {
fmt.Print("a")
return v
}
func b(v bool) bool {
fmt.Print("b")
return v
}
func test(i, j bool) {
fmt.Printf("Testing a(%t) && b(%t)\n", i, j)
fmt.Print("Trace: ")
fmt.Println("\nResult:", a(i) && b(j))
fmt.Printf("Testing a(%t) || b(%t)\n", i, j)
fmt.Print("Trace: ")
fmt.Println("\nResult:", a(i) || b(j))
fmt.Println("")
}
func main() {
test(false, false)
test(false, true)
test(true, false)
test(true, 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
| #EchoLisp | EchoLisp |
(require 'list)
;; a card is a vector [id color number symb shading], 0 <= id < 81
(define (make-deck (id -1))
(for*/vector(
[ color '(red green purple)]
[ number '(one two three)]
[ symb '( oval squiggle diamond)]
[ shading '(solid open striped)]) (++ id) (vector id color number symb shading)))
(define DECK (make-deck))
;; pre-generate 531441 ordered triples, among which 6561 are winners
(define TRIPLES (make-vector (* 81 81 81)))
(define (make-triples )
(for* ((i 81)(j 81)(k 81))
(vector-set! TRIPLES (+ i (* 81 j) (* 6561 k))
(check-set [DECK i] [DECK j] [DECK k]))))
;; a deal is a list of cards id's.
(define (show-deal deal)
(for ((card deal)) (writeln [DECK card]))
(for ((set (combinations deal 3)))
(when
(check-set [DECK (first set)] [DECK (second set)][DECK (third set)])
(writeln 'winner set))))
;; rules of game here
(define (check-set cards: a b c)
(for ((i (in-range 1 5))) ;; each feature
#:continue (and (= [a i] [b i]) (= [a i] [c i]))
#:continue (and (!= [a i] [b i]) (!= [a i] [c i]) (!= [b i][c i]))
#:break #t => #f ))
;; sets = list of triples (card-id card-id card-id)
(define (count-sets sets )
(for/sum ((s sets))
(if [TRIPLES ( + (first s) (* 81 (second s)) (* 6561 (third s)))]
1 0)))
;; task
(make-triples)
(define (play (n 9) (cmax 4) (sets) (deal))
(while #t
(set! deal (take (shuffle (iota 81)) n))
(set! sets (combinations deal 3))
#:break (= (count-sets sets) cmax) => (show-deal deal)
))
|
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
| #D | D | void main() {
import std.stdio, std.digest.sha;
writefln("%-(%02x%)", "Rosetta code".sha256Of);
} |
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
| #Delphi | Delphi |
program SHA_256;
{$APPTYPE CONSOLE}
uses
System.SysUtils,
DCPsha256;
function SHA256(const Str: string): string;
var
HashDigest: array of byte;
d: Byte;
begin
Result := '';
with TDCP_sha256.Create(nil) do
begin
Init;
UpdateStr(Str);
SetLength(HashDigest, GetHashSize div 8);
final(HashDigest[0]);
for d in HashDigest do
Result := Result + d.ToHexString(2);
Free;
end;
end;
begin
Writeln(SHA256('Rosetta code'));
readln;
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.
| #DWScript | DWScript | PrintLn( HashSHA1.HashData('Rosetta code') ); |
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.
| #Elixir | Elixir |
iex(1)> :crypto.hash(:sha, "A string")
<<110, 185, 174, 8, 151, 66, 9, 104, 174, 225, 10, 43, 9, 92, 82, 190, 197, 150,
224, 92>>
|
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)
| #E | E | def dice5() {
return entropy.nextInt(5) + 1
}
def dice7() {
var d55 := null
while ((d55 := 5 * dice5() + dice5() - 6) >= 21) {}
return d55 %% 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)
| #Elixir | Elixir | defmodule Dice do
def dice5, do: :rand.uniform( 5 )
def dice7 do
dice7_from_dice5
end
defp dice7_from_dice5 do
d55 = 5*dice5 + dice5 - 6 # 0..24
if d55 < 21, do: rem( d55, 7 ) + 1,
else: dice7_from_dice5
end
end
fun5 = fn -> Dice.dice5 end
IO.inspect VerifyDistribution.naive( fun5, 1000000, 3 )
fun7 = fn -> Dice.dice7 end
IO.inspect VerifyDistribution.naive( fun7, 1000000, 3 ) |
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.
| #Lua | Lua | local N = 1000035
-- FUNCS:
local function T(t) return setmetatable(t, {__index=table}) end
table.filter = function(t,f) local s=T{} for _,v in ipairs(t) do if f(v) then s[#s+1]=v end end return s end
table.map = function(t,f,...) local s=T{} for _,v in ipairs(t) do s[#s+1]=f(v,...) end return s end
table.lastn = function(t,n) local s=T{} n=n>#t and #t or n for i = 1,n do s[i]=t[#t-n+i] end return s end
table.each = function(t,f,...) for _,v in ipairs(t) do f(v,...) end end
-- PRIMES:
local sieve, primes = {false}, T{}
for i = 2,N+6 do sieve[i]=true end
for i = 2,N+6 do if sieve[i] then for j=i*i,N+6,i do sieve[j]=nil end end end
for i = 2,N+6 do if sieve[i] then primes[#primes+1]=i end end
-- TASKS:
local sexy, name = { primes }, { "primes", "pairs", "triplets", "quadruplets", "quintuplets" }
local function sexy2str(v,n) local s=T{} for i=1,n do s[i]=v+(i-1)*6 end return "("..s:concat(" ")..")" end
for i = 2, 5 do
sexy[i] = sexy[i-1]:filter(function(v) return v+(i-1)*6<N and sieve[v+(i-1)*6] end)
print(#sexy[i] .. " " .. name[i] .. ", ending with: " .. sexy[i]:lastn(5):map(sexy2str,i):concat(" "))
end
local unsexy = primes:filter(function(v) return not (v>=N or sieve[v-6] or sieve[v+6]) end)
print(#unsexy .. " unsexy, ending with: " ..unsexy:lastn(10):concat(" ")) |
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
| #Cowgol | Cowgol | include "cowgol.coh";
# Print number with preceding space if <100 and trailing colon
sub print_num(n: uint8) is
if n < 100 then print_char(' '); end if;
print_i8(n);
print(": ");
end sub;
# Print character / Spc / Del padded to 5 spaces
sub print_ch(c: uint8) is
if c == ' ' then print("Spc ");
elseif c == 127 then print("Del ");
else
print_char(c);
print(" ");
end if;
end sub;
var c: uint8 := 32;
loop
print_num(c);
print_ch(c);
if c == 127 then
break;
end if;
c := c + 16;
if c > 127 then
print_nl();
c := c - 95;
end if;
end loop;
print_nl(); |
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
| #Lua | Lua | function sierpinski(depth)
lines = {}
lines[1] = '*'
for i = 2, depth+1 do
sp = string.rep(' ', 2^(i-2))
tmp = {}
for idx, line in ipairs(lines) do
tmp[idx] = sp .. line .. sp
tmp[idx+#lines] = line .. ' ' .. line
end
lines = tmp
end
return table.concat(lines, '\n')
end
print(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
| #Forth | Forth | \ Generates a square Sierpinski gasket
: 1? over 3 mod 1 = ; ( n1 n2 -- n1 n2 f)
: 3/ 3 / swap ; ( n1 n2 -- n2/3 n1)
\ is this cell in the carpet?
: incarpet ( n1 n2 -- f)
begin over over or while 1? 1? and if 2drop false exit then 3/ 3/ repeat
2drop true \ return true if in the carpet
;
\ draw a carpet of n size
: carpet ( n --)
1 swap 0 ?do 3 * loop dup \ calculate power of 3
0 ?do dup 0 ?do i j incarpet if [char] # else bl then emit loop cr loop
drop \ evaluate every cell in the carpet
;
cr 4 carpet |
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.
| #SNOBOL4 | SNOBOL4 | echo 'a output = "Hello, World!";end' | snobol4 -b |
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.
| #Tcl | Tcl | $ echo 'puts Hello' | tclsh
Hello |
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.
| #TXR | TXR | $ echo 123-456-7890 | txr -c '@a-@b-@c' -
a="123"
b="456"
c="7890"
|
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.
| #UNIX_Shell | UNIX Shell | $ sh -c ls |
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.
| #Groovy | Groovy | def f = { println ' AHA!'; it instanceof String }
def g = { printf ('%5d ', it); it > 50 }
println 'bitwise'
assert g(100) & f('sss')
assert g(2) | f('sss')
assert ! (g(1) & f('sss'))
assert g(200) | f('sss')
println '''
logical'''
assert g(100) && f('sss')
assert g(2) || f('sss')
assert ! (g(1) && f('sss'))
assert g(200) || f('sss') |
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
| #Elixir | Elixir | defmodule RC do
def set_puzzle(deal, goal) do
{puzzle, sets} = get_puzzle_and_answer(deal, goal, produce_deck)
IO.puts "Dealt #{length(puzzle)} cards:"
print_cards(puzzle)
IO.puts "Containing #{length(sets)} sets:"
Enum.each(sets, fn set -> print_cards(set) end)
end
defp get_puzzle_and_answer(hand_size, num_sets_goal, deck) do
hand = Enum.take_random(deck, hand_size)
sets = get_all_sets(hand)
if length(sets) == num_sets_goal do
{hand, sets}
else
get_puzzle_and_answer(hand_size, num_sets_goal, deck)
end
end
defp get_all_sets(hand) do
Enum.filter(comb(hand, 3), fn candidate ->
List.flatten(candidate)
|> Enum.group_by(&(&1))
|> Map.values
|> Enum.all?(fn v -> length(v) != 2 end)
end)
end
defp print_cards(cards) do
Enum.each(cards, fn card ->
:io.format " ~-8s ~-8s ~-8s ~-8s~n", card
end)
IO.puts ""
end
@colors ~w(red green purple)a
@symbols ~w(oval squiggle diamond)a
@numbers ~w(one two three)a
@shadings ~w(solid open striped)a
defp produce_deck do
for color <- @colors, symbol <- @symbols, number <- @numbers, shading <- @shadings,
do: [color, symbol, number, shading]
end
defp comb(_, 0), do: [[]]
defp comb([], _), do: []
defp comb([h|t], m) do
(for l <- comb(t, m-1), do: [h|l]) ++ comb(t, m)
end
end
RC.set_puzzle(9, 4)
RC.set_puzzle(12, 6) |
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
| #Erlang | Erlang |
-module( set ).
-export( [deck/0, is_set/3, shuffle_deck/1, task/0] ).
-record( card, {number, symbol, shading, colour} ).
deck() -> [#card{number=N, symbol=Sy, shading=Sh, colour=C} || N <- [1,2,3], Sy <- [diamond, squiggle, oval], Sh <- [solid, striped, open], C <- [red, green, purple]].
is_set( Card1, Card2, Card3 ) ->
is_colour_correct( Card1, Card2, Card3 )
andalso is_number_correct( Card1, Card2, Card3 )
andalso is_shading_correct( Card1, Card2, Card3 )
andalso is_symbol_correct( Card1, Card2, Card3 ).
shuffle_deck( Deck ) -> knuth_shuffle:list( Deck ).
task() ->
basic(),
advanced().
advanced() -> common( 6, 12 ).
basic() -> common( 4, 9 ).
common( X, Y ) ->
{Sets, Cards} = find_x_sets_in_y_cards( X, Y, deck() ),
io:fwrite( "Cards ~p~n", [Cards] ),
io:fwrite( "Gives sets:~n" ),
[io:fwrite( "~p~n", [S] ) || S <- Sets].
find_x_sets_in_y_cards( X, Y, Deck ) ->
{Cards, _T} = lists:split( Y, shuffle_deck(Deck) ),
find_x_sets_in_y_cards( X, Y, Cards, make_sets1(Cards, []) ).
find_x_sets_in_y_cards( X, _Y, _Deck, Cards, Sets ) when erlang:length(Sets) =:= X -> {Sets, Cards};
find_x_sets_in_y_cards( X, Y, Deck, _Cards, _Sets ) -> find_x_sets_in_y_cards( X, Y, Deck ).
is_colour_correct( Card1, Card2, Card3 ) -> is_colour_different( Card1, Card2, Card3 ) orelse is_colour_same( Card1, Card2, Card3 ).
is_colour_different( #card{colour=C1}, #card{colour=C2}, #card{colour=C3} ) when C1 =/= C2, C1 =/= C3, C2 =/= C3 -> true;
is_colour_different( _Card1, _Card2, _Card3 ) -> false.
is_colour_same( #card{colour=C}, #card{colour=C}, #card{colour=C} ) -> true;
is_colour_same( _Card1, _Card2, _Card3 ) -> false.
is_number_correct( Card1, Card2, Card3 ) -> is_number_different( Card1, Card2, Card3 ) orelse is_number_same( Card1, Card2, Card3 ).
is_number_different( #card{number=N1}, #card{number=N2}, #card{number=N3} ) when N1 =/= N2, N1 =/= N3, N2 =/= N3 -> true;
is_number_different( _Card1, _Card2, _Card3 ) -> false.
is_number_same( #card{number=N}, #card{number=N}, #card{number=N} ) -> true;
is_number_same( _Card1, _Card2, _Card3 ) -> false.
is_shading_correct( Card1, Card2, Card3 ) -> is_shading_different( Card1, Card2, Card3 ) orelse is_shading_same( Card1, Card2, Card3 ).
is_shading_different( #card{shading=S1}, #card{shading=S2}, #card{shading=S3} ) when S1 =/= S2, S1 =/= S3, S2 =/= S3 -> true;
is_shading_different( _Card1, _Card2, _Card3 ) -> false.
is_shading_same( #card{shading=S}, #card{shading=S}, #card{shading=S} ) -> true;
is_shading_same( _Card1, _Card2, _Card3 ) -> false.
is_symbol_correct( Card1, Card2, Card3 ) -> is_symbol_different( Card1, Card2, Card3 ) orelse is_symbol_same( Card1, Card2, Card3 ).
is_symbol_different( #card{symbol=S1}, #card{symbol=S2}, #card{symbol=S3} ) when S1 =/= S2, S1 =/= S3, S2 =/= S3 -> true;
is_symbol_different( _Card1, _Card2, _Card3 ) -> false.
is_symbol_same( #card{symbol=S}, #card{symbol=S}, #card{symbol=S} ) -> true;
is_symbol_same( _Card1, _Card2, _Card3 ) -> false.
%% Nested loops 1, 2 and 3
make_sets1( [_Second_to_last, _Last], Sets ) -> Sets;
make_sets1( [Card | T], Sets ) -> make_sets1( T, make_sets2(Card, T, Sets) ).
make_sets2( _Card, [_Last], Sets ) -> Sets;
make_sets2( Card1, [Card2 | T], Sets ) -> make_sets2( Card1, T, make_sets3( Card1, Card2, T, Sets) ).
make_sets3( _Card1, _Card2, [], Sets ) -> Sets;
make_sets3( Card1, Card2, [Card3 | T], Sets ) ->
make_sets3( Card1, Card2, T, make_sets_acc(is_set(Card1, Card2, Card3), {Card1, Card2, Card3}, Sets) ).
make_sets_acc( true, Set, Sets ) -> [Set | Sets];
make_sets_acc( false, _Set, Sets ) -> Sets.
|
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
| #DWScript | DWScript | PrintLn( HashSHA256.HashData('Rosetta code') ); |
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.
| #Emacs_Lisp | Emacs Lisp |
(sha1 "Rosetta Code") ;=> "48c98f7e5a6e736d790ab740dfc3f51a61abe2b5"
(secure-hash 'sha1 "Rosetta Code") ;=> "48c98f7e5a6e736d790ab740dfc3f51a61abe2b5"
|
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.
| #Erlang | Erlang | 12> crypto:hash( sha, "A string" ).
<<110,185,174,8,151,66,9,104,174,225,10,43,9,92,82,190,197,150,224,92>>
|
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)
| #Erlang | Erlang |
-module( dice ).
-export( [dice5/0, dice7/0, task/0] ).
dice5() -> random:uniform( 5 ).
dice7() ->
dice7_small_enough( dice5() * 5 + dice5() - 6 ). % 0 - 24
task() ->
verify_distribution_uniformity:naive( fun dice7/0, 1000000, 1 ).
dice7_small_enough( N ) when N < 21 -> N div 3 + 1;
dice7_small_enough( _N ) -> dice7().
|
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)
| #Factor | Factor | USING: kernel random sequences assocs locals sorting prettyprint
math math.functions math.statistics math.vectors math.ranges ;
IN: rosetta-code.dice7
! Output a random integer 1..5.
: dice5 ( -- x )
5 [1,b] random
;
! Output a random integer 1..7 using dice5 as randomness source.
: dice7 ( -- x )
0 [ dup 21 < ] [ drop dice5 5 * dice5 + 6 - ] do until
7 rem 1 +
;
! Roll the die by calling the quotation the given number of times and return
! an array with roll results.
! Sample call: 1000 [ dice7 ] roll
: roll ( times quot: ( -- x ) -- array )
[ call( -- x ) ] curry replicate
;
! Input array contains outcomes of a number of die throws. Each die result is
! an integer in the range 1..X. Calculate and return the number of each
! of the results in the array so that in the first position of the result
! there is the number of ones in the input array, in the second position
! of the result there is the number of twos in the input array, etc.
: count-dice-outcomes ( X array -- array )
histogram
swap [1,b] [ over [ 0 or ] change-at ] each
sort-keys values
;
! Verify distribution uniformity/Naive. Delta is the acceptable deviation
! from the ideal number of items in each bucket, expressed as a fraction of
! the total count. Sides is the number of die sides. Die-func is a word that
! produces a random number on stack in the range [1..sides], times is the
! number of times to call it.
! Sample call: 0.02 7 [ dice7 ] 100000 verify
:: verify ( delta sides die-func: ( -- random ) times -- )
sides
times die-func roll
count-dice-outcomes
dup .
times sides / :> ideal-count
ideal-count v-n vabs
times v/n
delta [ < ] curry all?
[ "Random enough" . ] [ "Not random enough" . ] if
;
! Call verify with 1, 10, 100, ... 1000000 rolls of 7-sided die.
: verify-all ( -- )
{ 1 10 100 1000 10000 100000 1000000 }
[| times | 0.02 7 [ dice7 ] times verify ] each
; |
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.
| #Mathematica_.2F_Wolfram_Language | Mathematica / Wolfram Language | ClearAll[AllSublengths]
AllSublengths[l_List] := If[Length[l] > 2,
Catenate[Partition[l, #, 1] & /@ Range[2, Length[l]]]
,
{l}
]
primes = Prime[Range[PrimePi[1000035]]];
ps = Union[Intersection[primes + 6, primes] - 6, Intersection[primes - 6, primes] + 6];
a = Intersection[ps + 6, ps] - 6;
b = Intersection[ps - 6, ps] + 6;
g = Graph[DeleteDuplicates[Thread[a \[UndirectedEdge] (a + 6)]~Join~Thread[(b - 6) \[UndirectedEdge] b]]];
sp = Sort /@ ConnectedComponents[g];
sp //= SortBy[First];
sp //= Map[AllSublengths];
sp //= Catenate;
sp //= SortBy[First];
sp //= DeleteDuplicates;
sel = Select[sp, Length /* EqualTo[2]];
Length[sel]
sel[[-5 ;;]] // Column
sel = Select[sp, Length /* EqualTo[3]];
Length[sel]
sel[[-5 ;;]] // Column
sel = Select[sp, Length /* EqualTo[4]];
Length[sel]
sel[[-5 ;;]] // Column
sel = Select[sp, Length /* EqualTo[5]];
Length[sel]
sel // Column
Select[Complement[primes, DeleteDuplicates[Catenate@sp]][[-20 ;;]], ! (PrimeQ[# + 6] \[Or] PrimeQ[# - 6]) &][[-10 ;;]] // Column |
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.
| #Nim | Nim | import math, strformat, strutils
const Lim = 1_000_035
type Group {.pure.} = enum # "ord" gives the number of terms.
Unsexy = (1, "unsexy primes")
Pairs = (2, "sexy prime pairs")
Triplets = (3, "sexy prime triplets")
Quadruplets = (4, "sexy prime quadruplets")
Quintuplets = (5, "sexy prime quintuplets")
# Sieve of Erathosthenes.
var composite: array[1..Lim, bool] # Default is false.
composite[1] = true
for p in countup(3, sqrt(Lim.toFloat).int, 2): # Ignore even numbers.
if not composite[p]:
for k in countup(p * p, Lim, 2 * p):
composite[k] = true
template isPrime(n: int): bool = not composite[n]
proc expandGroup(n: int; group: Group): string =
## Given the first term of a group, return the full group
## representation as a string.
var n = n
for _ in 1..ord(group):
result.addSep(", ")
result.add $n
inc n, 6
if group != Unsexy: result = '(' & result & ')'
proc printResult(group: Group; values: seq[int]; count: int) =
## Print a result.
echo &"\nNumber of {group} less than {Lim}: {values.len}"
let last = min(values.len, count)
let verb = if last == 1: "is" else: "are"
echo &"The last {last} {verb}:"
var line = ""
for i in countdown(last, 1):
line.addSep(", ")
line.add expandGroup(values[^i], group)
echo " ", line
var
pairs, trips, quads, quints: seq[int] # Keep only the first prime of the group.
unsexy = @[2, 3]
for n in countup(3, Lim, 2):
if composite[n]: continue
if n in 7..(Lim - 8) and composite[n - 6] and composite[n + 6]:
unsexy.add n
continue
if n < Lim - 6 and isPrime(n + 6):
pairs.add n
else: continue
if n < Lim - 12 and isPrime(n + 12):
trips.add n
else: continue
if n < Lim - 18 and isPrime(n + 18):
quads.add n
else: continue
if n < Lim - 24 and isPrime(n + 24):
quints.add n
printResult(Pairs, pairs, 5)
printResult(Triplets, trips, 5)
printResult(Quadruplets, quads, 5)
printResult(Quintuplets, quints, 5)
printResult(Unsexy, unsexy, 10) |
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
| #D | D | import std.stdio;
void main() {
for (int i = 0; i < 16; ++i) {
for (int j = 32 + i; j < 128; j += 16) {
switch (j) {
case 32:
writef("%3d : Spc ", j);
break;
case 127:
writef("%3d : Del ", j);
break;
default:
writef("%3d : %-3s ", j, cast(char)j);
break;
}
}
writeln;
}
} |
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
| #Maple | Maple | S := proc(n)
local i, j, values, position;
values := [ seq(" ",i=1..2^n-1), "*" ];
printf("%s\n",cat(op(values)));
for i from 2 to 2^n do
position := [ ListTools:-SearchAll( "*", values ) ];
values := Array([ seq(0, i=1..2^n+i-1) ]);
for j to numelems(position) do
values[position[j]-1] := values[position[j]-1] + 1;
values[position[j]+1] := values[position[j]+1] + 1;
end do;
values := subs( { 2 = " ", 0 = " ", 1 = "*"}, values );
printf("%s\n",cat(op(convert(values, list))));
end do:
end proc: |
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
| #Fortran | Fortran | program Sierpinski_carpet
implicit none
call carpet(4)
contains
function In_carpet(a, b)
logical :: in_carpet
integer, intent(in) :: a, b
integer :: x, y
x = a ; y = b
do
if(x == 0 .or. y == 0) then
In_carpet = .true.
return
else if(mod(x, 3) == 1 .and. mod(y, 3) == 1) then
In_carpet = .false.
return
end if
x = x / 3
y = y / 3
end do
end function
subroutine Carpet(n)
integer, intent(in) :: n
integer :: i, j
do i = 0, 3**n - 1
do j = 0, 3**n - 1
if(In_carpet(i, j)) then
write(*, "(a)", advance="no") "#"
else
write(*, "(a)", advance="no") " "
end if
end do
write(*,*)
end do
end subroutine Carpet
end program Sierpinski_carpet |
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.
| #Ursala | Ursala | $ fun --main=-[hello]- --show
hello
$ fun --main="power/2 32" --cast %n
4294967296
$ fun --m="..mp2str mpfr..pi 120" --c %s
'3.1415926535897932384626433832795028847E+00' |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.