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, an... | #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) &... |
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... | #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... |
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.G... |
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... | #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... | #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-d... |
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 R... | #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... |
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 R... | #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;
... |
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 ot... | #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,... |
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 pai... | #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,"",f... |
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
Bioin... | #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... |
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:
*
* *
* *
* * * *
* *
* * * *
... | #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... |
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:
###########################
# ## ## ## ## ## ## ## ## #
###########################
### ###### ###### ###
# # # ## # # ## # # #
### ###### ... | #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 ... |
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 ... | #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 Mat... |
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 comman... | #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 comman... | #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 comman... | #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 comman... | #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, an... | #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... |
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, an... | #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(... |
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... | #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[] sh... |
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::HexE... |
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... | #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-d... |
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 R... | #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*... |
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 ot... | #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 =: ... |
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 pai... | #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(file... |
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
Bioin... | #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 ... |
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:
*
* *
* *
* * * *
* *
* * * *
... | #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:
###########################
# ## ## ## ## ## ## ## ## #
###########################
### ###### ###### ###
# # # ## # # ## # # #
### ###### ... | #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 ... | #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 vert... |
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 ... | #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 comman... | #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 comman... | #REXX | REXX |
╔══════════════════════════════════════════════╗
║ ║
║ from the MS Window command line (cmd.exe) ║
║ ║
╚══════════════════════════════════════════════╝
echo do j=10 by 20 for 4;... |
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 comman... | #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 comman... | #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, an... | #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... |
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... | #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( col... |
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... | #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... | #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 R... | #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 ... |
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 R... | #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 ot... | #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... |
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 pai... | #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... |
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
Bioin... | #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:
*
* *
* *
* * * *
* *
* * * *
... | #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:
###########################
# ## ## ## ## ## ## ## ## #
###########################
### ###### ###### ###
# # # ## # # ## # # #
### ###### ... | #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... |
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 ... | #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 comman... | #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 comman... | #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 comman... | #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 comman... | #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, an... | #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) |... |
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... | #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... |
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... | #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: ... |
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... | #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(HashDiges... |
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 R... | #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... |
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 ot... | #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 && possible... |
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 ot... | #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.
... |
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 pai... | #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(... |
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 pai... | #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.... |
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
Bioin... | #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... |
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:
*
* *
* *
* * * *
* *
* * * *
... | #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
... |
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:
###########################
# ## ## ## ## ## ## ## ## #
###########################
### ###### ###### ###
# # # ## # # ## # # #
### ###### ... | #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"))... |
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 comman... | #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 comman... | #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 comman... | #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 comman... | #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, an... | #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) |... |
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... | #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 (... |
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(H... |
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... | #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... | #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 R... | #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 R... | #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 VerifyDistribu... |
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 ot... | #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 = fun... |
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
Bioin... | #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 ");
... |
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:
*
* *
* *
* * * *
* *
* * * *
... | #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(l... |
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:
###########################
# ## ## ## ## ## ## ## ## #
###########################
### ###### ###### ###
# # # ## # # ## # # #
### ###### ... | #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 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 comman... | #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 comman... | #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 comman... | #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 comman... | #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, an... | #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'))
asser... |
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... | #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_answe... |
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... | #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, Card... |
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... | #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... | #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 R... | #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_... |
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 R... | #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 2... |
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 ot... | #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 ... |
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 ot... | #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 quintupl... |
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
Bioin... | #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);
... |
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:
*
* *
* *
* * * *
* *
* * * *
... | #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
val... |
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:
###########################
# ## ## ## ## ## ## ## ## #
###########################
### ###### ###### ###
# # # ## # # ## # # #
### ###### ... | #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
... |
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 comman... | #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.