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/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:
###########################
# ## ## ## ## ## ## ## ## #
###########################
### ###### ###### ###
# # # ## # # ## # # #
### ###### ... | #E | E | def inCarpet(var x, var y) {
while (x > 0 && y > 0) {
if (x %% 3 <=> 1 && y %% 3 <=> 1) {
return false
}
x //= 3
y //= 3
}
return true
}
def carpet(order) {
for y in 0..!(3**order) {
for x in 0..!(3**order) {
print(inCarpet(x, y).pick("#"... |
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 ... | #Python | Python | >>> def area_by_shoelace(x, y):
"Assumes x,y points go around the polygon in one direction"
return abs( sum(i * j for i, j in zip(x, y[1:] + y[:1]))
-sum(i * j for i, j in zip(x[1:] + x[:1], y ))) / 2
>>> points = [(3,4), (5,11), (12,8), (9,5), (5,6)]
>>> x, y = zip(*poin... |
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 ... | #Racket | Racket | #lang racket/base
(struct P (x y))
(define (area . Ps)
(define (A P-a P-b)
(+ (for/sum ((p_i Ps)
(p_i+1 (in-sequences (cdr Ps)
(in-value (car Ps)))))
(* (P-a p_i) (P-b p_i+1)))))
(/ (abs (- (A P-x P-y) (A P-y P-x))) 2))
(module+ main
(area ... |
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... | #Objeck | Objeck | ./obc -run '"Hello"->PrintLine();' -dest hello.obe ; ./obr hello.obe |
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... | #OCaml | OCaml | $ ocaml <(echo 'print_endline "Hello"')
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... | #Octave | Octave | $ octave --eval 'printf("Hello World, it is %s!\n",datestr(now));'
Hello World, it is 28-Aug-2013 17:53:47! |
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... | #Delphi | Delphi | program ShortCircuitEvaluation;
{$APPTYPE CONSOLE}
uses SysUtils;
function A(aValue: Boolean): Boolean;
begin
Writeln('a');
Result := aValue;
end;
function B(aValue: Boolean): Boolean;
begin
Writeln('b');
Result := aValue;
end;
var
i, j: Boolean;
begin
for i in [False, True] do
begin
for j i... |
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
| #Ada | Ada | with Ada.Text_IO;
with CryptAda.Pragmatics;
with CryptAda.Digests.Message_Digests.SHA_256;
with CryptAda.Digests.Hashes;
with CryptAda.Utils.Format;
procedure RC_SHA_256 is
use CryptAda.Pragmatics;
use CryptAda.Digests.Message_Digests;
use CryptAda.Digests;
function To_Byte_Array (Item : String) retur... |
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... | #Arturo | Arturo | print digest.sha "The quick brown fox jumped over the lazy dog's back" |
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... | #Astro | Astro | import crypto { sha1 }
let hash = sha1.hexdigest('Ars longa, vita brevis')
print hash
|
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... | #C.2B.2B | C++ | #include <array>
#include <iostream>
#include <vector>
#include <boost/circular_buffer.hpp>
#include "prime_sieve.hpp"
int main() {
using std::cout;
using std::vector;
using boost::circular_buffer;
using group_buffer = circular_buffer<vector<int>>;
const int max = 1000035;
const int max_grou... |
http://rosettacode.org/wiki/Set_right-adjacent_bits | Set right-adjacent bits | Given a left-to-right ordered collection of e bits, b, where 1 <= e <= 10000,
and a zero or more integer n :
Output the result of setting the n bits to the right of any set bit in b
(if those bits are present in b and therefore also preserving the width, e).
Some examples:
Set of examples showing how one bit in... | #Factor | Factor | USING: formatting io kernel math math.parser math.ranges
sequences ;
: set-rab ( n b -- result )
[0,b] [ neg shift ] with [ bitor ] map-reduce ;
:: show ( n b e -- )
b e "n = %d; width = %d\n" printf
n n b set-rab [ >bin e CHAR: 0 pad-head print ] bi@ ;
{ 0b1000 0b0100 0b0010 0b0000 } [ 2 4 show nl ] ... |
http://rosettacode.org/wiki/Set_right-adjacent_bits | Set right-adjacent bits | Given a left-to-right ordered collection of e bits, b, where 1 <= e <= 10000,
and a zero or more integer n :
Output the result of setting the n bits to the right of any set bit in b
(if those bits are present in b and therefore also preserving the width, e).
Some examples:
Set of examples showing how one bit in... | #Go | Go | package main
import (
"fmt"
"strings"
)
type test struct {
bs string
n int
}
func setRightBits(bits []byte, e, n int) []byte {
if e == 0 || n <= 0 {
return bits
}
bits2 := make([]byte, len(bits))
copy(bits2, bits)
for i := 0; i < e-1; i++ {
c := bits[i]
... |
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... | #Haskell | Haskell | {-# LANGUAGE BangPatterns, LambdaCase #-}
import Control.Monad (mfilter)
import Crypto.Hash.SHA256 (hash)
import qualified Data.ByteString as B
import Data.ByteString.Builder (byteStringHex, char7, hPutBuilder)
import Data.Functor ((<&>))
import Data.Maybe (listToMaybe)
import Data.Strict.Tuple (Pair(..))
import qual... |
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... | #C | C | #include <stdio.h>
int main() {
int i, j;
char k[4];
for (i = 0; i < 16; ++i) {
for (j = 32 + i; j < 128; j += 16) {
switch (j) {
default: sprintf(k, "%c", j); break;
case 32: sprintf(k, "Spc"); break;
case 127: sprintf(k, "Del"); break... |
http://rosettacode.org/wiki/Simple_database | Simple database | Task
Write a simple tool to track a small set of data.
The tool should have a command-line interface to enter at least two different values.
The entered data should be stored in a structured format and saved to disk.
It does not matter what kind of data is being tracked. It could be a collection (CDs, coins, base... | #Wren | Wren | /* simdb.wren */
import "os" for Process
import "/ioutil" for File, FileFlags, FileUtil
import "/trait" for Comparable, Reversed
import "/date" for Date
import "/sort" for Sort
import "/str" for Str
var fileName = "simdb.csv"
Date.default = Date.isoDate
class Item is Comparable {
construct new(name, date, c... |
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:
*
* *
* *
* * * *
* *
* * * *
... | #J | J | |. _31]\ ,(,.~ , ])^: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:
###########################
# ## ## ## ## ## ## ## ## #
###########################
### ###### ###### ###
# # # ## # # ## # # #
### ###### ... | #Elixir | Elixir | defmodule RC do
def sierpinski_carpet(n), do: sierpinski_carpet(n, ["#"])
def sierpinski_carpet(0, carpet), do: carpet
def sierpinski_carpet(n, carpet) do
new_carpet = Enum.map(carpet, fn x -> x <> x <> x end) ++
Enum.map(carpet, fn x -> x <> String.replace(x, "#", " ") <> x end) ++
... |
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 ... | #Raku | Raku | sub area-by-shoelace(@p) {
(^@p).map({@p[$_;0] * @p[($_+1)%@p;1] - @p[$_;1] * @p[($_+1)%@p;0]}).sum.abs / 2
}
say area-by-shoelace( [ (3,4), (5,11), (12,8), (9,5), (5,6) ] ); |
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 ... | #REXX | REXX | /*REXX program uses a Shoelace formula to calculate the area of an N─sided polygon.*/
parse arg $; if $='' then $= "(3,4),(5,11),(12,8),(9,5),(5,6)" /*Use the default?*/
A= 0; @= space($, 0) /*init A; elide blanks from pts.*/
do #=1 until @==''; parse var @... |
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... | #Oforth | Oforth | oforth --P"1000 seq map(#sqrt) sum 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 comman... | #ooRexx | ooRexx |
rexx -e "say 'Goodbye, 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... | #Oz | Oz | echo >tmp.oz "{System.show hello}"; ozc -l System -e tmp.oz
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... | #PARI.2FGP | PARI/GP | echo "print(Pi)" | gp -q |
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... | #Dyalect | Dyalect | func a(v) {
print(nameof(a), terminator: "")
return v
}
func b(v) {
print(nameof(b), terminator: "")
return v
}
func testMe(i, j) {
print("Testing a(\(i)) && b(\(j))")
print("Trace: ", terminator: "")
print("\nResult: \(a(i) && b(j))")
print("Testing a(\(i)) || b(\(j))")
print(... |
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... | #E | E | def a(v) { println("a"); return v }
def b(v) { println("b"); return v }
def x := a(i) && b(j)
def y := b(i) || b(j) |
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
| #ARM_Assembly | ARM Assembly |
/* ARM assembly Raspberry PI */
/* program sha256.s */
/* REMARK 1 : this program use routines in a include file
see task Include a file language arm assembly
for the routine affichageMess conversion10
see at end of this program the instruction include */
/* for constantes see task include a file in... |
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... | #AutoHotkey | AutoHotkey | str := "Rosetta Code"
MsgBox, % "String:`n" (str) "`n`nSHA:`n" SHA(str)
; SHA ===============================================================================
SHA(string, encoding = "utf-8")
{
return CalcStringHash(string, 0x8004, encoding)
}
; CalcAddrHash ===================================================... |
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... | #Delphi | Delphi |
// Sexy primes. Nigel Galloway: October 2nd., 2018
let n=pCache |> Seq.takeWhile(fun n->n<1000035) |> Seq.filter(fun n->(not (isPrime(n+6)) && (not isPrime(n-6))))) |> Array.ofSeq
printfn "There are %d unsexy primes less than 1,000,035. The last 10 are:" n.Length
Array.skip (n.Length-10) n |> Array.iter(fun n->printf... |
http://rosettacode.org/wiki/Set_right-adjacent_bits | Set right-adjacent bits | Given a left-to-right ordered collection of e bits, b, where 1 <= e <= 10000,
and a zero or more integer n :
Output the result of setting the n bits to the right of any set bit in b
(if those bits are present in b and therefore also preserving the width, e).
Some examples:
Set of examples showing how one bit in... | #Julia | Julia | function setrightadj(s, n)
if n < 1
return s
else
arr = reverse(collect(s))
for (i, c) in enumerate(reverse(s))
if c == '1'
arr[max(1, i - n):i] .= '1'
end
end
return String(reverse(arr))
end
end
@show setrightadj("1000", 2)
@show se... |
http://rosettacode.org/wiki/Set_right-adjacent_bits | Set right-adjacent bits | Given a left-to-right ordered collection of e bits, b, where 1 <= e <= 10000,
and a zero or more integer n :
Output the result of setting the n bits to the right of any set bit in b
(if those bits are present in b and therefore also preserving the width, e).
Some examples:
Set of examples showing how one bit in... | #Perl | Perl | #!/usr/bin/perl
use strict; # https://rosettacode.org/wiki/Set_right-adjacent_bits
use warnings;
while( <DATA> )
{
my ($n, $input) = split;
my $width = length $input;
my $result = '';
$result |= substr 0 x $_ . $input, 0, $width for 0 .. $n;
print "n = $n width = $width\n input $input\nresult $result\n... |
http://rosettacode.org/wiki/Set_right-adjacent_bits | Set right-adjacent bits | Given a left-to-right ordered collection of e bits, b, where 1 <= e <= 10000,
and a zero or more integer n :
Output the result of setting the n bits to the right of any set bit in b
(if those bits are present in b and therefore also preserving the width, e).
Some examples:
Set of examples showing how one bit in... | #Phix | Phix | with javascript_semantics
function str_srb(string input, integer n)
string res = input
integer l = length(input),
m = min(n,l),
count = sum(sq_eq(input[-m..-1],'1')),
k = l-n
for i=l to 1 by -1 do
integer bit = odd(input[i])
count += iff(k>0?odd(input[k]):... |
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... | #Java | Java | import java.io.*;
import java.security.*;
import java.util.*;
public class SHA256MerkleTree {
public static void main(String[] args) {
if (args.length != 1) {
System.err.println("missing file argument");
System.exit(1);
}
try (InputStream in = new BufferedInputStrea... |
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... | #C.2B.2B | C++ | #include <string>
#include <iomanip>
#include <iostream>
#define HEIGHT 16
#define WIDTH 6
#define ASCII_START 32
#define ASCII_END 128
// ASCII special characters
#define SPACE 32
#define DELETE 127
std::string displayAscii(int ascii) {
switch(ascii) {
case SPACE:
... |
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:
*
* *
* *
* * * *
* *
* * * *
... | #Java | Java |
public class SierpinskiTriangle {
public static void main(String[] args) {
System.out.println(getSierpinskiTriangle(4));
}
private static final String getSierpinskiTriangle(int n) {
if ( n == 0 ) {
return "*";
}
String s = getSierpinskiTriangle(n-1);
... |
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:
###########################
# ## ## ## ## ## ## ## ## #
###########################
### ###### ###### ###
# # # ## # # ## # # #
### ###### ... | #Erlang | Erlang | % Implemented by Arjun Sunel
-module(carpet).
-export([main/0]).
main() ->
sierpinski_carpet(3).
sierpinski_carpet(N) ->
lists: foreach(fun(X) -> lists: foreach(fun(Y) -> carpet(X,Y) end,lists:seq(0,trunc(math:pow(3,N))-1)), io:format("\n") end, lists:seq(0,trunc(math:pow(3,N))-1)).
carpet(X,Y) ->
if
X=:=0... |
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 ... | #Ring | Ring |
# Project : Shoelace formula for polygonal area
p = [[3,4], [5,11], [12,8], [9,5], [5,6]]
see "The area of the polygon = " + shoelace(p)
func shoelace(p)
sum = 0
for i = 1 to len(p) -1
sum = sum + p[i][1] * p[i +1][2]
sum = sum - p[i +1][1] * p[i][2]
next
... |
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 ... | #Ruby | Ruby |
Point = Struct.new(:x,:y) do
def shoelace(other)
x * other.y - y * other.x
end
end
class Polygon
def initialize(*coords)
@points = coords.map{|c| Point.new(*c) }
end
def area
points = @points + [@points.first]
points.each_cons(2).sum{|p1,p2| p1.shoelace(p2) }.abs.fdiv(2)
end
e... |
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... | #Pascal | Pascal | $ perl -e 'print "Hello\n"'
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... | #Perl | Perl | $ perl -e 'print "Hello\n"'
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... | #Elena | Elena | import system'routines;
import extensions;
Func<bool, bool> a = (bool x){ console.writeLine:"a"; ^ x };
Func<bool, bool> b = (bool x){ console.writeLine:"b"; ^ x };
const bool[] boolValues = new bool[]{ false, true };
public program()
{
boolValues.forEach:(bool i)
{
boolValues.forEach:(bool j)
... |
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... | #Elixir | Elixir | defmodule Short_circuit do
defp a(bool) do
IO.puts "a( #{bool} ) called"
bool
end
defp b(bool) do
IO.puts "b( #{bool} ) called"
bool
end
def task do
Enum.each([true, false], fn i ->
Enum.each([true, false], fn j ->
IO.puts "a( #{i} ) and b( #{j} ) is #{a(i) and b(j)}.\n"
... |
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
| #AutoHotkey | AutoHotkey | str := "Rosetta code"
MsgBox, % "File:`n" (file) "`n`nSHA-256:`n" FileSHA256(file)
; SHA256 ============================================================================
SHA256(string, encoding = "utf-8")
{
return CalcStringHash(string, 0x800c, encoding)
}
; CalcAddrHash =========================================... |
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... | #BBC_BASIC | BBC BASIC | PRINT FNsha1("Rosetta Code")
END
DEF FNsha1(message$)
LOCAL buflen%, buffer%, hprov%, hhash%, hash$, i%
CALG_SHA1 = &8004
CRYPT_VERIFYCONTEXT = &F0000000
HP_HASHVAL = 2
PROV_RSA_FULL = 1
buflen% = 64
DIM buffer% LOCAL buflen%-1
SYS "CryptAcquireContext... |
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... | #C | C | #include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <openssl/sha.h>
int main()
{
int i;
unsigned char result[SHA_DIGEST_LENGTH];
const char *string = "Rosetta Code";
SHA1(string, strlen(string), result);
for(i = 0; i < SHA_DIGEST_LENGTH; i++)
printf("%02x%c", result[i], i < (SHA_DIGE... |
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... | #11l | 11l | F dice5()
R random:(1..5)
F dice7() -> Int
V r = dice5() + dice5() * 5 - 6
R I r < 21 {(r % 7) + 1} E dice7()
F distcheck(func, repeats, delta)
V bin = DefaultDict[Int, Int]()
L 1..repeats
bin[func()]++
V target = repeats I/ bin.len
V deltacount = Int(delta / 100.0 * target)
assert(all... |
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... | #F.23 | F# |
// Sexy primes. Nigel Galloway: October 2nd., 2018
let n=pCache |> Seq.takeWhile(fun n->n<1000035) |> Seq.filter(fun n->(not (isPrime(n+6)) && (not isPrime(n-6))))) |> Array.ofSeq
printfn "There are %d unsexy primes less than 1,000,035. The last 10 are:" n.Length
Array.skip (n.Length-10) n |> Array.iter(fun n->printf... |
http://rosettacode.org/wiki/Set_right-adjacent_bits | Set right-adjacent bits | Given a left-to-right ordered collection of e bits, b, where 1 <= e <= 10000,
and a zero or more integer n :
Output the result of setting the n bits to the right of any set bit in b
(if those bits are present in b and therefore also preserving the width, e).
Some examples:
Set of examples showing how one bit in... | #Python | Python | from operator import or_
from functools import reduce
def set_right_adjacent_bits(n: int, b: int) -> int:
return reduce(or_, (b >> x for x in range(n+1)), 0)
if __name__ == "__main__":
print("SAME n & Width.\n")
n = 2 # bits to the right of set bits, to also set
bits = "1000 0100 0010 0000"
f... |
http://rosettacode.org/wiki/Set_right-adjacent_bits | Set right-adjacent bits | Given a left-to-right ordered collection of e bits, b, where 1 <= e <= 10000,
and a zero or more integer n :
Output the result of setting the n bits to the right of any set bit in b
(if those bits are present in b and therefore also preserving the width, e).
Some examples:
Set of examples showing how one bit in... | #Raku | Raku | sub rab (Int $n, Int $b = 1) {
my $m = $n;
$m +|= ($n +> $_) for ^ $b+1;
$m
}
sub lab (Int $n, Int $b = 1) {
my $m = $n;
$m +|= ($n +< $_) for ^ $b+1;
$m
}
say "Powers of 2 ≤ 8, 0 - Right-adjacent-bits: 2";
.&rab(2).base(2).fmt('%04s').say for <8 4 2 1 0>;
# Test with a few integers.
for 8... |
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... | #Julia | Julia | using SHA
function merkletree(filename="title.png", blocksize=1024)
bytes = codeunits(read(filename, String))
len = length(bytes)
hsh = [sha256(view(bytes. i:min(i+blocksize-1, len)])) for i in 1:1024:len]
len = length(hsh)
while len > 1
hsh = [i == len ? hsh[i] : sha256(vcat(hsh[i], hsh[i... |
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... | #Mathematica.2FWolfram_Language | Mathematica/Wolfram Language | data=Import["https://rosettacode.org/mw/title.png","Byte"];
parts=Hash[ByteArray[#],"SHA256","ByteArray"]&/@Partition[data,UpTo[1024]];
parts=NestWhile[If[Length[#]==2,Hash[Join@@#,"SHA256","ByteArray"],First[#]]&/@Partition[#,UpTo[2]]&,parts,Length[#]>1&];
StringJoin[IntegerString[Normal[First[parts]],16]] |
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... | #C.23 | C# | using static System.Console;
using static System.Linq.Enumerable;
public class Program
{
static void Main()
{
for (int start = 32; start + 16 * 5 < 128; start++) {
WriteLine(string.Concat(Range(0, 6).Select(i => $"{start+16*i, 3} : {Text(start+16*i), -6}")));
}
string Tex... |
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:
*
* *
* *
* * * *
* *
* * * *
... | #JavaFX_Script | JavaFX Script | function sierpinski(n : Integer) {
var down = ["*"];
var space = " ";
for (i in [1..n]) {
down = [for (x in down) "{space}{x}{space}", for (x in down) "{x} {x}"];
space = "{space}{space}";
}
for (x in down) {
println("{x}")
}
}
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:
###########################
# ## ## ## ## ## ## ## ## #
###########################
### ###### ###### ###
# # # ## # # ## # # #
### ###### ... | #ERRE | ERRE |
PROGRAM SIERP_CARPET
! for rosettacode.org
!$INTEGER
BEGIN
OPEN("O",1,"OUT.PRN")
PRINT(CHR$(12);) !CLS
DEPTH=3
DIMM=1
FOR I=0 TO DEPTH-1 DO
DIMM=DIMM*3
END FOR
FOR I=0 TO DIMM-1 DO
FOR J=0 TO DIMM-1 DO
D=DIMM DIV 3
REPEAT
EXIT IF ((I MOD (D*3)) DIV D=1 AND (J MOD (D*3)) DIV ... |
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 ... | #Scala | Scala | case class Point( x:Int,y:Int ) { override def toString = "(" + x + "," + y + ")" }
case class Polygon( pp:List[Point] ) {
require( pp.size > 2, "A Polygon must consist of more than two points" )
override def toString = "Polygon(" + pp.mkString(" ", ", ", " ") + ")"
def area = {
// Calculate using the... |
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 ... | #Sidef | Sidef | func area_by_shoelace (*p) {
var x = p.map{_[0]}
var y = p.map{_[1]}
var s = (
(x ~Z* y.rotate(+1)).sum -
(x ~Z* y.rotate(-1)).sum
)
s.abs / 2
}
say area_by_shoelace([3,4], [5,11], [12,8], [9,5], [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... | #Phix | Phix | C:\Program Files (x86)\Phix>p -e ?357+452
809
C:\Program Files (x86)\Phix>p -e "?357+452"
809
|
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... | #PHP | PHP | $ php -r 'echo "Hello\n";'
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... | #PicoLisp | PicoLisp | $ picolisp -'prinl "Hello world!"' -bye
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... | #Pike | Pike | $ pike -e 'write("Hello\n");'
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... | #Erlang | Erlang |
-module( short_circuit_evaluation ).
-export( [task/0] ).
task() ->
[task_helper(X, Y) || X <- [true, false], Y <- [true, false]].
a( Boolean ) ->
io:fwrite( " a ~p~n", [Boolean] ),
Boolean.
b( Boolean ) ->
io:fwrite( " b ~p~n", [Boolean] ),
Boolean.
task_helper( Boolean1, Boolean2 ) ->
io:fwrite(... |
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... | #Ada | Ada | package Set_Puzzle is
type Three is range 1..3;
type Card is array(1 .. 4) of Three;
type Cards is array(Positive range <>) of Card;
type Set is array(Three) of Positive;
procedure Deal_Cards(Dealt: out Cards);
-- ouputs an array with disjoint cards
function To_String(C: Card) return Strin... |
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
| #AWK | AWK | {
("echo -n " $0 " | sha256sum") | getline sha;
gsub(/[^0-9a-zA-Z]/, "", sha);
print sha;
}
|
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
| #BaCon | BaCon | PRAGMA INCLUDE <openssl/sha.h>
PRAGMA LDFLAGS -lcrypto
OPTION MEMTYPE unsigned char
DECLARE result TYPE unsigned char*
result = SHA256("Rosetta code", 12, 0)
FOR i = 0 TO SHA256_DIGEST_LENGTH-1
PRINT PEEK(result+i) FORMAT "%02x"
NEXT
PRINT |
http://rosettacode.org/wiki/SHA-1 | SHA-1 | SHA-1 or SHA1 is a one-way hash function;
it computes a 160-bit message digest.
SHA-1 often appears in security protocols; for example,
many HTTPS websites use RSA with SHA-1 to secure their connections.
BitTorrent uses SHA-1 to verify downloads.
Git and Mercurial use SHA-1 digests to identify commits.
A US government... | #C.23 | C# | using System;
using System.Security.Cryptography;
using System.Text;
using Microsoft.VisualStudio.TestTools.UnitTesting;
namespace RosettaCode.SHA1
{
[TestClass]
public class SHA1CryptoServiceProviderTest
{
[TestMethod]
public void TestComputeHash()
{
var input = new UT... |
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... | #Ada | Ada | package Random_57 is
type Mod_7 is mod 7;
function Random7 return Mod_7;
-- a "fast" implementation, minimazing the calls to the Random5 generator
function Simple_Random7 return Mod_7;
-- a simple implementation
end Random_57; |
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... | #ALGOL_68 | ALGOL 68 | PROC dice5 = INT:
1 + ENTIER (5*random);
PROC mulby5 = (INT n)INT:
ABS (BIN n SHL 2) + n;
PROC dice7 = INT: (
INT d55 := 0;
INT m := 1;
WHILE
m := ABS ((2r1 AND BIN m) SHL 2) + ABS (BIN m SHR 1); # repeats 4 - 2 - 1 #
d55 := mulby5(mulby5(d55)) + mulby5(dice5) + dice5 - 6;
# WHILE # d55 < m DO S... |
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... | #Factor | Factor | USING: combinators.short-circuit fry interpolate io kernel
literals locals make math math.primes math.ranges prettyprint qw
sequences tools.memory.private ;
IN: rosetta-code.sexy-primes
CONSTANT: limit 1,000,035
CONSTANT: primes $[ limit primes-upto ]
CONSTANT: tuplet-names qw{ pair triplet quadruplet quintuplet }
... |
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... | #FreeBASIC | FreeBASIC | Function isPrime(Byval ValorEval As Uinteger) As Boolean
If ValorEval < 2 Then Return False
If ValorEval Mod 2 = 0 Then Return ValorEval = 2
If ValorEval Mod 3 = 0 Then Return ValorEval = 3
Dim d As Integer = 5
While d * d <= ValorEval
If ValorEval Mod d = 0 Then Return False Else d += 2
... |
http://rosettacode.org/wiki/Set_right-adjacent_bits | Set right-adjacent bits | Given a left-to-right ordered collection of e bits, b, where 1 <= e <= 10000,
and a zero or more integer n :
Output the result of setting the n bits to the right of any set bit in b
(if those bits are present in b and therefore also preserving the width, e).
Some examples:
Set of examples showing how one bit in... | #Rust | Rust | use std::ops::{BitOrAssign, Shr};
fn set_right_adjacent_bits<E: Clone + BitOrAssign + Shr<usize, Output = E>>(b: &mut E, n: usize) {
for _ in 1..=n {
*b |= b.clone() >> 1;
}
}
macro_rules! test {
( $t:ident, $n:expr, $e:expr, $g:ty, $b:expr, $c:expr$(,)? ) => {
#[test]
fn $t() {
... |
http://rosettacode.org/wiki/Set_right-adjacent_bits | Set right-adjacent bits | Given a left-to-right ordered collection of e bits, b, where 1 <= e <= 10000,
and a zero or more integer n :
Output the result of setting the n bits to the right of any set bit in b
(if those bits are present in b and therefore also preserving the width, e).
Some examples:
Set of examples showing how one bit in... | #Wren | Wren | var setRightBits = Fn.new { |bits, e, n|
if (e == 0 || n <= 0) return bits
var bits2 = bits.toList
for (i in 0...e - 1) {
var c = bits[i]
if (c == 1) {
var j = i + 1
while (j <= i + n && j < e) {
bits2[j] = 1
j = j + 1
}
... |
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... | #Nim | Nim |
import nimcrypto
const BlockSize = 1024
var hashes: seq[MDigest[256]]
let f = open("title.png")
var buffer: array[BlockSize, byte]
while true:
let n = f.readBytes(buffer, 0, BlockSize)
if n == 0: break
hashes.add sha256.digest(buffer[0].addr, n.uint)
f.close()
var ctx: sha256
while hashes.len != 1:
va... |
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... | #Pascal | Pascal |
program SHA256_Merkle_tree;
{$IFDEF WINDOWS}
{$APPTYPE CONSOLE}
{$ENDIF}
{$IFDEF DELPHI}
uses
System.SysUtils,
System.Classes,
DCPsha256;
type
TmyByte = TArray<Byte>;
TmyHashes = TArray<TArray<byte>>;
{$ENDIF}
{$IFDEF FPC}
{$Mode DELPHI}
uses
SysUtils,
Classes,
DCPsha256;
type
TmyByt... |
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... | #Cach.C3.A9_ObjectScript | Caché ObjectScript | SHOWASCII
; this is 96 characters, so do 6 columns of 16
for i = 32:1:127 {
; get remainder when div by 6, sort columns by remainder 2 3 4 5 0 1
set rem = i # 6
if rem = 2 {
write !
}
; spacing (tabs)
set x = $case(rem,2:0,3:8,4:16,5:24,0:32,:40)
; char to write
set wrtchr ... |
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:
*
* *
* *
* * * *
* *
* * * *
... | #JavaScript | JavaScript | (function (order) {
// Sierpinski triangle of order N constructed as
// Pascal triangle of 2^N rows mod 2
// with 1 encoded as "▲"
// and 0 encoded as " "
function sierpinski(intOrder) {
return function asciiPascalMod2(intRows) {
return range(1, intRows - 1)
.re... |
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:
###########################
# ## ## ## ## ## ## ## ## #
###########################
### ###### ###### ###
# # # ## # # ## # # #
### ###### ... | #Euphoria | Euphoria |
include std/math.e
integer order = 4
function InCarpet(atom x, atom y)
while 1 do
if x = 0 or y = 0 then
return 1
elsif floor(mod(x,3)) = 1 and floor(mod(y,3)) = 1 then
return 0
end if
x /= 3
y /= 3
end while
end function
for i = 0 to power(3,order)-1 do
for j = 0 to power(3,order)-1 do
if ... |
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 ... | #Swift | Swift | import Foundation
struct Point {
var x: Double
var y: Double
}
extension Point: CustomStringConvertible {
var description: String {
return "Point(x: \(x), y: \(y))"
}
}
struct Polygon {
var points: [Point]
var area: Double {
let xx = points.map({ $0.x })
let yy = points.map({ $0.y })
... |
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 ... | #TI-83_BASIC | TI-83 BASIC | [[3,4][5,11][12,8][9,5][5,6]]->[A]
Dim([A])->N:0->A
For(I,1,N)
I+1->J:If J>N:Then:1->J:End
A+[A](I,1)*[A](J,2)-[A](J,1)*[A](I,2)->A
End
Abs(A)/2->A |
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 ... | #VBA | VBA | Option Base 1
Public Enum axes
u = 1
v
End Enum
Private Function shoelace(s As Collection) As Double
Dim t As Double
If s.Count > 2 Then
s.Add s(1)
For i = 1 To s.Count - 1
t = t + s(i)(u) * s(i + 1)(v) - s(i + 1)(u) * s(i)(v)
Next i
End If
shoelace = Abs(t) /... |
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... | #PowerShell | PowerShell | > powershell -Command "Write-Host 'Hello'"
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... | #Processing | Processing | mkdir -p Tmp; echo "println(\"hello world\");" > Tmp/Tmp.pde; processing-java --sketch="`pwd`/Tmp" --run |
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... | #Prolog | Prolog | $ swipl -g "writeln('hello world')." -t 'halt.'
hello world
$ |
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.23 | F# | let a (x : bool) = printf "(a)"; x
let b (x : bool) = printf "(b)"; x
[for x in [true; false] do for y in [true; false] do yield (x, y)]
|> List.iter (fun (x, y) ->
printfn "%b AND %b = %b" x y ((a x) && (b y))
printfn "%b OR %b = %b" x y ((a x) || (b y))) |
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... | #AutoHotkey | AutoHotkey | ; Generate deck; card encoding from Raku
Loop, 81
deck .= ToBase(A_Index-1, 3)+1111 ","
deck := RegExReplace(deck, "3", "4")
; Shuffle
deck := shuffle(deck)
msgbox % clipboard := allValidSets(9, 4, deck)
msgbox % clipboard := allValidSets(12, 6, deck)
; Render a hand (or any list) of cards
PrettyHand(hand) {
C... |
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
| #BBC_BASIC | BBC BASIC | PRINT FNsha256("Rosetta code")
END
DEF FNsha256(message$)
LOCAL buflen%, buffer%, hcont%, hprov%, hhash%, hash$, i%
CALG_SHA_256 = &800C
HP_HASHVAL = 2
CRYPT_NEWKEYSET = 8
PROV_RSA_AES = 24
buflen% = 128
DIM buffer% LOCAL buflen%-1
SYS "CryptAcquireCon... |
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 | C | #include <stdio.h>
#include <string.h>
#include <openssl/sha.h>
int main (void) {
const char *s = "Rosetta code";
unsigned char *d = SHA256(s, strlen(s), 0);
int i;
for (i = 0; i < SHA256_DIGEST_LENGTH; i++)
printf("%02x", d[i]);
putchar('\n');
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... | #C.2B.2B | C++ | #include <string>
#include <iostream>
#include "Poco/SHA1Engine.h"
#include "Poco/DigestStream.h"
using Poco::DigestEngine ;
using Poco::SHA1Engine ;
using Poco::DigestOutputStream ;
int main( ) {
std::string myphrase ( "Rosetta Code" ) ;
SHA1Engine sha1 ;
DigestOutputStream outstr( sha1 ) ;
outstr << m... |
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... | #AutoHotkey | AutoHotkey | dice5()
{ Random, v, 1, 5
Return, v
}
dice7()
{ Loop
{ v := 5 * dice5() + dice5() - 6
IfLess v, 21, Return, (v // 3) + 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... | #BBC_BASIC | BBC BASIC | MAXRND = 7
FOR r% = 2 TO 5
check% = FNdistcheck(FNdice7, 10^r%, 0.1)
PRINT "Over "; 10^r% " runs dice7 ";
IF check% THEN
PRINT "failed distribution check with "; check% " bin(s) out of range"
ELSE
PRINT "passed distribution check"
ENDIF
NEXT
... |
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... | #Go | Go | package main
import "fmt"
func sieve(limit int) []bool {
limit++
// True denotes composite, false denotes prime.
c := make([]bool, limit) // all false by default
c[0] = true
c[1] = true
// no need to bother with even numbers over 2 for this task
p := 3 // Start from 3.
for {
... |
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... | #Perl | Perl | # 20210222 Perl programming solution
use strict;
use warnings;
use Crypt::Digest::SHA256 'sha256' ;
my @blocks;
open my $fh, '<:raw', './title.png';
while ( read $fh, my $chunk, 1024 ) { push @blocks, sha256 $chunk }
while ( scalar @blocks > 1 ) {
my @clone = @blocks and @blocks = ();
while ( @_ = spl... |
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... | #Clojure | Clojure |
(defn cell [code]
(let [text (get {32 "Spc", 127 "Del"} code (char code))]
(format "%3d: %3s" code text)))
(defn ascii-table [n-cols st-code end-code]
(let [n-cells (inc (- end-code st-code))
n-rows (/ n-cells n-cols)
code (fn [r c] (+ st-code r (* c n-rows)))
row-str (fn [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:
*
* *
* *
* * * *
* *
* * * *
... | #jq | jq | def elementwise(f):
transpose | map(f) ;
# input: an array of decimal numbers
def bitwise_and:
# Input: an integer
# Output: a stream of 0s and 1s
def stream:
recurse(if . > 0 then ./2|floor else empty end) | . % 2 ;
# Input: a 0-1 array
def toi:
reduce .[] as $c ( {power:1 , ans: 0};
.an... |
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:
###########################
# ## ## ## ## ## ## ## ## #
###########################
### ###### ###### ###
# # # ## # # ## # # #
### ###### ... | #Excel | Excel | SHOWBLOCKS
=LAMBDA(xs,
IF(0 <> xs, "█", " ")
)
SIERPCARPET
=LAMBDA(n,
APPLYN(n)(
SIERPWEAVE
)(1)
)
SIERPWEAVE
=LAMBDA(xs,
LET(
triple, REPLICATECOLS(3)(xs),
gap, LAMBDA(x, IF(x, 0, 0))(xs),
middle, APPENDCOLS(
APPENDCOLS(xs)(gap)
)(xs),
... |
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 ... | #VBScript | VBScript | ' Shoelace formula for polygonal area - VBScript
Dim points, x(),y()
points = Array(3,4, 5,11, 12,8, 9,5, 5,6)
n=(UBound(points)+1)\2
Redim x(n+1),y(n+1)
j=0
For i = 1 To n
x(i)=points(j)
y(i)=points(j+1)
j=j+2
Next 'i
x(i)=points(0)
y(i)=points(1)
For i =... |
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 | Visual Basic | Option Explicit
Public Function ShoelaceArea(x() As Double, y() As Double) As Double
Dim i As Long, j As Long
Dim Area As Double
j = UBound(x())
For i = LBound(x()) To UBound(x())
Area = Area + (y(j) + y(i)) * (x(j) - x(i))
j = i
Next i
ShoelaceArea = Abs(Area) / 2
End Function
Sub Main()
Dim v As... |
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... | #PureBasic | PureBasic | $ echo 'messagerequester("Greetings","hello")' > "dib.pb" && ./pbcompiler dib.pb -e "dib" && ./dib |
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... | #Python | Python | $ python -c 'print "Hello"'
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... | #Quackery | Quackery | $ QUACK=$(mktemp); echo "say 'hello'" > $QUACK; quackery $QUACK; rm $QUACK
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... | #Factor | Factor | USING: combinators.short-circuit.smart io prettyprint ;
IN: rosetta-code.short-circuit
: a ( ? -- ? ) "(a)" write ;
: b ( ? -- ? ) "(b)" write ;
"f && f = " write { [ f a ] [ f b ] } && .
"f || f = " write { [ f a ] [ f b ] } || .
"f && t = " write { [ f a ] [ t b ] } && .
"f || t = " write { [ f a ] [ t b ] } || .... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.