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: ########################### # ## ## ## ## ## ## ## ## # ########################### ### ###### ###### ### # # # ## # # ## # # # ### ###### ###### ### ########################### # ## ## ## ## ## ## ## ## # ########################### ######### ######### # ## ## # # ## ## # ######### ######### ### ### ### ### # # # # # # # # ### ### ### ### ######### ######### # ## ## # # ## ## # ######### ######### ########################### # ## ## ## ## ## ## ## ## # ########################### ### ###### ###### ### # # # ## # # ## # # # ### ###### ###### ### ########################### # ## ## ## ## ## ## ## ## # ########################### The use of the   #   character is not rigidly required for ASCII art. The important requirement is the placement of whitespace and non-whitespace characters. Related task   Sierpinski triangle
#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("#", " ")) } println() } }
http://rosettacode.org/wiki/Shoelace_formula_for_polygonal_area
Shoelace formula for polygonal area
Given the n + 1 vertices x[0], y[0] .. x[N], y[N] of a simple polygon described in a clockwise direction, then the polygon's area can be calculated by: abs( (sum(x[0]*y[1] + ... x[n-1]*y[n]) + x[N]*y[0]) - (sum(x[1]*y[0] + ... x[n]*y[n-1]) + x[0]*y[N]) ) / 2 (Where abs returns the absolute value) Task Write a function/method/routine to use the the Shoelace formula to calculate the area of the polygon described by the ordered points: (3,4), (5,11), (12,8), (9,5), and (5,6) Show the answer here, on this page.
#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(*points) >>> area_by_shoelace(x, y) 30.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 a function/method/routine to use the the Shoelace formula to calculate the area of the polygon described by the ordered points: (3,4), (5,11), (12,8), (9,5), and (5,6) Show the answer here, on this page.
#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 (P 3 4) (P 5 11) (P 12 8) (P 9 5) (P 5 6)))
http://rosettacode.org/wiki/Shell_one-liner
Shell one-liner
Task Show how to specify and execute a short program in the language from a command shell, where the input to the command shell is only one line in length. Avoid depending on the particular shell or operating system used as much as is reasonable; if the language has notable implementations which have different command argument syntax, or the systems those implementations run on have different styles of shells, it would be good to show multiple examples.
#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 command argument syntax, or the systems those implementations run on have different styles of shells, it would be good to show multiple examples.
#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 command argument syntax, or the systems those implementations run on have different styles of shells, it would be good to show multiple examples.
#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, and is to be minimized. If we needed to compute the conjunction   (and): x = a() and b() Then it would be best to not compute the value of   b()   if the value of   a()   is computed as   false,   as the value of   x   can then only ever be   false. Similarly, if we needed to compute the disjunction (or): y = a() or b() Then it would be best to not compute the value of   b()   if the value of   a()   is computed as   true,   as the value of   y   can then only ever be   true. Some languages will stop further computation of boolean equations as soon as the result is known, so-called   short-circuit evaluation   of boolean expressions Task Create two functions named   a   and   b,   that take and return the same boolean value. The functions should also print their name whenever they are called. Calculate and assign the values of the following equations to a variable in such a way that function   b   is only called when necessary: x = a(i) and b(j) y = a(i) or b(j) If the language does not have short-circuit evaluation, this might be achieved with nested     if     statements.
#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 in [False, True] do begin Writeln(Format('%s and %s = %s', [BoolToStr(i, True), BoolToStr(j, True), BoolToStr(A(i) and B(j), True)])); Writeln; Writeln(Format('%s or %s = %s', [BoolToStr(i, True), BoolToStr(j, True), BoolToStr(A(i) or B(j), True)])); Writeln; end; end; end.
http://rosettacode.org/wiki/SHA-256
SHA-256
SHA-256 is the recommended stronger alternative to SHA-1. See FIPS PUB 180-4 for implementation details. Either by using a dedicated library or implementing the algorithm in your language, show that the SHA-256 digest of the string "Rosetta code" is: 764faf5c61ac315f1497f9dfa542713965b785e5cc2f707d6468d7d1124cdfcf
#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) return Byte_Array is Result : Byte_Array (Item'Range); begin for I in Result'Range loop Result (I) := Byte (Character'Pos (Item (I))); end loop; return Result; end To_Byte_Array;   Text  : constant String  := "Rosetta code"; Bytes  : constant Byte_Array  := To_Byte_Array (Text); Handle  : constant Message_Digest_Handle := SHA_256.Get_Message_Digest_Handle; Pointer : constant Message_Digest_Ptr  := Get_Message_Digest_Ptr (Handle); Hash  : Hashes.Hash; begin Digest_Start (Pointer); Digest_Update (Pointer, Bytes); Digest_End (Pointer, Hash);   Ada.Text_IO.Put_Line ("""" & Text & """: " & CryptAda.Utils.Format.To_Hex_String (Hashes.Get_Bytes (Hash))); end RC_SHA_256;
http://rosettacode.org/wiki/SHA-1
SHA-1
SHA-1 or SHA1 is a one-way hash function; it computes a 160-bit message digest. SHA-1 often appears in security protocols; for example, many HTTPS websites use RSA with SHA-1 to secure their connections. BitTorrent uses SHA-1 to verify downloads. Git and Mercurial use SHA-1 digests to identify commits. A US government standard, FIPS 180-1, defines SHA-1. Find the SHA-1 message digest for a string of octets. You may either call a SHA-1 library, or implement SHA-1 in your language. Both approaches interest Rosetta Code. Warning: SHA-1 has known weaknesses. Theoretical attacks may find a collision after 252 operations, or perhaps fewer. This is much faster than a brute force attack of 280 operations. USgovernment deprecated SHA-1. For production-grade cryptography, users may consider a stronger alternative, such as SHA-256 (from the SHA-2 family) or the upcoming SHA-3.
#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 standard, FIPS 180-1, defines SHA-1. Find the SHA-1 message digest for a string of octets. You may either call a SHA-1 library, or implement SHA-1 in your language. Both approaches interest Rosetta Code. Warning: SHA-1 has known weaknesses. Theoretical attacks may find a collision after 252 operations, or perhaps fewer. This is much faster than a brute force attack of 280 operations. USgovernment deprecated SHA-1. For production-grade cryptography, users may consider a stronger alternative, such as SHA-256 (from the SHA-2 family) or the upcoming SHA-3.
#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 other by six. For example, the numbers 5 and 11 are both sexy primes, because 11 minus 6 is 5. The term "sexy prime" is a pun stemming from the Latin word for six: sex. Sexy prime pairs: Sexy prime pairs are groups of two primes that differ by 6. e.g. (5 11), (7 13), (11 17) See sequences: OEIS:A023201 and OEIS:A046117 Sexy prime triplets: Sexy prime triplets are groups of three primes where each differs from the next by 6. e.g. (5 11 17), (7 13 19), (17 23 29) See sequences: OEIS:A046118, OEIS:A046119 and OEIS:A046120 Sexy prime quadruplets: Sexy prime quadruplets are groups of four primes where each differs from the next by 6. e.g. (5 11 17 23), (11 17 23 29) See sequences: OEIS:A023271, OEIS:A046122, OEIS:A046123 and OEIS:A046124 Sexy prime quintuplets: Sexy prime quintuplets are groups of five primes with a common difference of 6. One of the terms must be divisible by 5, because 5 and 6 are relatively prime. Thus, the only possible sexy prime quintuplet is (5 11 17 23 29) Task For each of pairs, triplets, quadruplets and quintuplets, Find and display the count of each group type of sexy primes less than one million thirty-five (1,000,035). Display at most the last 5, less than one million thirty-five, of each sexy prime group type. Find and display the count of the unsexy primes less than one million thirty-five. Find and display the last 10 unsexy primes less than one million thirty-five. Note that 1000033 SHOULD NOT be counted in the pair count. It is sexy, but not in a pair within the limit. However, it also SHOULD NOT be listed in the unsexy primes since it is sexy.
#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_group_size = 5; const int diff = 6; const int array_size = max + diff; const int max_groups = 5; const int max_unsexy = 10;   // Use Sieve of Eratosthenes to find prime numbers up to max prime_sieve sieve(array_size);   std::array<int, max_group_size> group_count{0}; vector<group_buffer> groups(max_group_size, group_buffer(max_groups)); int unsexy_count = 0; circular_buffer<int> unsexy_primes(max_unsexy); vector<int> group;   for (int p = 2; p < max; ++p) { if (!sieve.is_prime(p)) continue; if (!sieve.is_prime(p + diff) && (p - diff < 2 || !sieve.is_prime(p - diff))) { // if p + diff and p - diff aren't prime then p can't be sexy ++unsexy_count; unsexy_primes.push_back(p); } else { // find the groups of sexy primes that begin with p group.clear(); group.push_back(p); for (int group_size = 1; group_size < max_group_size; group_size++) { int next_p = p + group_size * diff; if (next_p >= max || !sieve.is_prime(next_p)) break; group.push_back(next_p); ++group_count[group_size]; groups[group_size].push_back(group); } } }   for (int size = 1; size < max_group_size; ++size) { cout << "number of groups of size " << size + 1 << " is " << group_count[size] << '\n'; cout << "last " << groups[size].size() << " groups of size " << size + 1 << ":"; for (const vector<int>& group : groups[size]) { cout << " ("; for (size_t i = 0; i < group.size(); ++i) { if (i > 0) cout << ' '; cout << group[i]; } cout << ")"; } cout << "\n\n"; } cout << "number of unsexy primes is " << unsexy_count << '\n'; cout << "last " << unsexy_primes.size() << " unsexy primes:"; for (int prime : unsexy_primes) cout << ' ' << prime; cout << '\n'; return 0; }
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 a nibble gets changed: n = 2; Width e = 4: Input b: 1000 Result: 1110 Input b: 0100 Result: 0111 Input b: 0010 Result: 0011 Input b: 0000 Result: 0000 Set of examples with the same input with set bits of varying distance apart: n = 0; Width e = 66: Input b: 010000000000100000000010000000010000000100000010000010000100010010 Result: 010000000000100000000010000000010000000100000010000010000100010010 n = 1; Width e = 66: Input b: 010000000000100000000010000000010000000100000010000010000100010010 Result: 011000000000110000000011000000011000000110000011000011000110011011 n = 2; Width e = 66: Input b: 010000000000100000000010000000010000000100000010000010000100010010 Result: 011100000000111000000011100000011100000111000011100011100111011111 n = 3; Width e = 66: Input b: 010000000000100000000010000000010000000100000010000010000100010010 Result: 011110000000111100000011110000011110000111100011110011110111111111 Task: Implement a routine to perform the setting of right-adjacent bits on representations of bits that will scale over the given range of input width e. Use it to show, here, the results for the input examples above. Print the output aligned in a way that allows easy checking by eye of the binary input vs output.
#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 ] each 0x10020080404082112 4 <iota> [ 66 show nl ] with each
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 a nibble gets changed: n = 2; Width e = 4: Input b: 1000 Result: 1110 Input b: 0100 Result: 0111 Input b: 0010 Result: 0011 Input b: 0000 Result: 0000 Set of examples with the same input with set bits of varying distance apart: n = 0; Width e = 66: Input b: 010000000000100000000010000000010000000100000010000010000100010010 Result: 010000000000100000000010000000010000000100000010000010000100010010 n = 1; Width e = 66: Input b: 010000000000100000000010000000010000000100000010000010000100010010 Result: 011000000000110000000011000000011000000110000011000011000110011011 n = 2; Width e = 66: Input b: 010000000000100000000010000000010000000100000010000010000100010010 Result: 011100000000111000000011100000011100000111000011100011100111011111 n = 3; Width e = 66: Input b: 010000000000100000000010000000010000000100000010000010000100010010 Result: 011110000000111100000011110000011110000111100011110011110111111111 Task: Implement a routine to perform the setting of right-adjacent bits on representations of bits that will scale over the given range of input width e. Use it to show, here, the results for the input examples above. Print the output aligned in a way that allows easy checking by eye of the binary input vs output.
#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] if c == 1 { j := i + 1 for j <= i+n && j < e { bits2[j] = 1 j++ } } } return bits2 }   func main() { b := "010000000000100000000010000000010000000100000010000010000100010010" tests := []test{ test{"1000", 2}, test{"0100", 2}, test{"0010", 2}, test{"0000", 2}, test{b, 0}, test{b, 1}, test{b, 2}, test{b, 3}, } for _, test := range tests { bs := test.bs e := len(bs) n := test.n fmt.Println("n =", n, "\b; Width e =", e, "\b:") fmt.Println(" Input b:", bs) bits := []byte(bs) for i := 0; i < len(bits); i++ { bits[i] = bits[i] - '0' } bits = setRightBits(bits, e, n) var sb strings.Builder for i := 0; i < len(bits); i++ { sb.WriteByte(bits[i] + '0') } fmt.Println(" Result :", sb.String()) } }
http://rosettacode.org/wiki/SHA-256_Merkle_tree
SHA-256 Merkle tree
As described in its documentation, Amazon S3 Glacier requires that all uploaded files come with a checksum computed as a Merkle Tree using SHA-256. Specifically, the SHA-256 hash is computed for each 1MiB block of the file. And then, starting from the beginning of the file, the raw hashes of consecutive blocks are paired up and concatenated together, and a new hash is computed from each concatenation. Then these are paired up and concatenated and hashed, and the process continues until there is only one hash left, which is the final checksum. The hexadecimal representation of this checksum is the value that must be included with the AWS API call to upload the object (or complete a multipart upload). Implement this algorithm in your language; you can use the code from the SHA-256 task for the actual hash computations. For better manageability and portability, build the tree using a smaller block size of only 1024 bytes, and demonstrate it on the RosettaCode title image with that block size. The final result should be the hexadecimal digest value a4f902cf9d51fe51eda156a6792e1445dff65edf3a217a1f3334cc9cf1495c2c.
#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 qualified Data.Strict.Tuple as T import System.Environment (getArgs) import System.IO (Handle, stdin, stdout) import System.IO.Streams (InputStream) import qualified System.IO.Streams as S import Text.Read (readMaybe)   type Node a = Pair Int a type LevelPred = Int -> Int -> Bool type Combine a = a -> a -> a   -- From a stream of nodes construct the root of a tree from the bottom up. For -- each level of the tree pairs of nodes are combined to form a parent node one -- level higher. Use a stack to store nodes waiting to be combined with another -- node on their level. (An exception to this is at the end of processing, -- where all the nodes on the stack can be combined.) build :: Combine a -> [Node a] -> InputStream (Node a) -> IO (Maybe (Node a)) build combine !stack is = S.read is >>= \case Nothing -> return $ listToMaybe $ reduce always combine stack Just h -> build combine (reduce (==) combine (h:stack)) is   -- Given a predicate, combining function and a stack, then as long as the -- predicate is true, repeatedly replace the two top values on the stack with -- their combined values. reduce :: LevelPred -> Combine a -> [Node a] -> [Node a] reduce prd combine (x@(i :!: _):y@(j :!: _):zs) | prd i j = reduce prd combine (nodeLift combine y x : zs) reduce _ _ zs = zs   -- Apply a combining function to the values in two nodes while calculating the -- appropriate level for the new node. nodeLift :: Combine a -> Node a -> Node a -> Node a nodeLift f (i :!: x) (j :!: y) = max i j + 1 :!: f x y   always :: a -> b -> Bool always _ _ = True   -- Build a SHA256-based Merkle tree using bytes read from a handle, and hashing -- the data using the given chunk size. merkleTreeSha256 :: Int -> Handle -> IO (Maybe B.ByteString) merkleTreeSha256 sz h = mkHash <&> fmap T.snd where mkHash = S.makeInputStream getBuf >>= S.map (\bs -> 0 :!: hash bs) >>= build (\x y -> hash (x `B.append` y)) [] getBuf = B.hGet h sz <&> (mfilter (/= B.empty) . Just)   -- Print a ByteString in hex. printByteStringHex :: B.ByteString -> IO () printByteStringHex = hPutBuilder stdout . (<> char7 '\n') . byteStringHex   main :: IO () main = getArgs <&> map readMaybe >>= \case [Just sz] -> merkleTreeSha256 sz stdin >>= \case Nothing -> putStrLn "No input to hash" Just h -> printByteStringHex h _ -> putStrLn "Argument usage: chunk-size"
http://rosettacode.org/wiki/Show_ASCII_table
Show ASCII table
Task Show  the ASCII character set  from values   32   to   127   (decimal)   in a table format. Other tasks related to string operations: Metrics Array length String length Copy a string Empty string  (assignment) Counting Word frequency Letter frequency Jewels and stones I before E except after C Bioinformatics/base count Count occurrences of a substring Count how many vowels and consonants occur in a string Remove/replace XXXX redacted Conjugate a Latin verb Remove vowels from a string String interpolation (included) Strip block comments Strip comments from a string Strip a set of characters from a string Strip whitespace from a string -- top and tail Strip control codes and extended characters from a string Anagrams/Derangements/shuffling Word wheel ABC problem Sattolo cycle Knuth shuffle Ordered words Superpermutation minimisation Textonyms (using a phone text pad) Anagrams Anagrams/Deranged anagrams Permutations/Derangements Find/Search/Determine ABC words Odd words Word ladder Semordnilap Word search Wordiff  (game) String matching Tea cup rim text Alternade words Changeable words State name puzzle String comparison Unique characters Unique characters in each string Extract file extension Levenshtein distance Palindrome detection Common list elements Longest common suffix Longest common prefix Compare a list of strings Longest common substring Find common directory path Words from neighbour ones Change e letters to i in words Non-continuous subsequences Longest common subsequence Longest palindromic substrings Longest increasing subsequence Words containing "the" substring Sum of the digits of n is substring of n Determine if a string is numeric Determine if a string is collapsible Determine if a string is squeezable Determine if a string has all unique characters Determine if a string has all the same characters Longest substrings without repeating characters Find words which contains all the vowels Find words which contains most consonants Find words which contains more than 3 vowels Find words which first and last three letters are equals Find words which odd letters are consonants and even letters are vowels or vice_versa Formatting Substring Rep-string Word wrap String case Align columns Literals/String Repeat a string Brace expansion Brace expansion using ranges Reverse a string Phrase reversals Comma quibbling Special characters String concatenation Substring/Top and tail Commatizing numbers Reverse words in a string Suffixation of decimal numbers Long literals, with continuations Numerical and alphabetical suffixes Abbreviations, easy Abbreviations, simple Abbreviations, automatic Song lyrics/poems/Mad Libs/phrases Mad Libs Magic 8-ball 99 Bottles of Beer The Name Game (a song) The Old lady swallowed a fly The Twelve Days of Christmas Tokenize Text between Tokenize a string Word break problem Tokenize a string with escaping Split a character string based on change of character Sequences Show ASCII table De Bruijn sequences Self-referential sequences Generate lower case ASCII alphabet
#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; } printf("%3d : %-3s ", j, k); } printf("\n"); } return 0; }
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, baseball cards, books), a diary, an electronic organizer (birthdays/anniversaries/phone numbers/addresses), etc. You should track the following details: A description of the item. (e.g., title, name) A category or tag (genre, topic, relationship such as “friend” or “family”) A date (either the date when the entry was made or some other date that is meaningful, like the birthday); the date may be generated or entered manually Other optional fields The command should support the following Command-line arguments to run: Add a new entry Print the latest entry Print the latest entry for each category Print all entries sorted by a date The category may be realized as a tag or as structure (by making all entries in that category subitems) The file format on disk should be human readable, but it need not be standardized.   A natively available format that doesn't need an external library is preferred.   Avoid developing your own format if you can use an already existing one.   If there is no existing format available, pick one of:   JSON   S-Expressions   YAML   others Related task   Take notes on the command line
#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, category) { _name = name _date = date _category = category }   name { _name } date { _date } category { _category }   compare(other) { _date.compare(other.date) }   toString { "%(name), %(date.toString), %(category)" } }   var printUsage = Fn.new { System.print(""" Usage: wren simdb.wren cmd [categoryName] add add item name and date, followed by optional category latest print item with latest date, followed by optional category all print all For instance: add "some item name", "some item date", "some category name" Dates should be in format: yyyy-mm-dd """) }   var load = Fn.new { var db = [] var lines = FileUtil.readLines(fileName) for (line in lines) { if (line == "") break // end of file var item = line.split(", ") db.add(Item.new(item[0], Date.parse(item[1]), item[2])) } return db }   var store = Fn.new { |item| File.openWithFlags(fileName, FileFlags.writeOnly) { |f| f.writeBytes("%(item)\n") } }   var addItem = Fn.new { |input| if (input.count < 2) { printUsage.call() return } var date = Date.parse(input[1]) var cat = (input.count == 3) ? input[2] : "none" store.call(Item.new(input[0], date, cat)) }   var printLatest = Fn.new { |a| var db = load.call() if (db.isEmpty) { System.print("No entries in database.") return } Sort.quick(db) // sort by ascending date if (a.count == 1) { var found = false for (item in Reversed.new(db)) { if (item.category == a[0]) { System.print(item) found = true break } } if (!found) System.print("There are no items for category '%(a[0])'.") } else System.print(db[-1]) }   var printAll = Fn.new { var db = load.call() if (db.isEmpty) { System.print("No entries in database.") return } Sort.quick(db) // sort by ascending date for (item in db) System.print(item) }   var args = Process.arguments if (!(1..4).contains(args.count)) { printUsage.call() return } // create file if it doesn't already exist if (!File.exists(fileName)) { var f = File.create(fileName) f.close() }   var cmd = Str.lower(args[0]) if (cmd == "add") { addItem.call(args[1..-1]) } else if (cmd == "latest") { printLatest.call(args[1..-1]) } else if (cmd == "all") { printAll.call() } else { printUsage.call() }
http://rosettacode.org/wiki/Sierpinski_triangle
Sierpinski triangle
Task Produce an ASCII representation of a Sierpinski triangle of order   N. Example The Sierpinski triangle of order   4   should look like this: * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * Related tasks Sierpinski triangle/Graphical for graphics images of this pattern. Sierpinski carpet
#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: ########################### # ## ## ## ## ## ## ## ## # ########################### ### ###### ###### ### # # # ## # # ## # # # ### ###### ###### ### ########################### # ## ## ## ## ## ## ## ## # ########################### ######### ######### # ## ## # # ## ## # ######### ######### ### ### ### ### # # # # # # # # ### ### ### ### ######### ######### # ## ## # # ## ## # ######### ######### ########################### # ## ## ## ## ## ## ## ## # ########################### ### ###### ###### ### # # # ## # # ## # # # ### ###### ###### ### ########################### # ## ## ## ## ## ## ## ## # ########################### The use of the   #   character is not rigidly required for ASCII art. The important requirement is the placement of whitespace and non-whitespace characters. Related task   Sierpinski triangle
#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) ++ Enum.map(carpet, fn x -> x <> x <> x end) sierpinski_carpet(n-1, new_carpet) end end   Enum.each(0..3, fn n -> IO.puts "\nN=#{n}" Enum.each(RC.sierpinski_carpet(n), fn line -> IO.puts line end) 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 a function/method/routine to use the the Shoelace formula to calculate the area of the polygon described by the ordered points: (3,4), (5,11), (12,8), (9,5), and (5,6) Show the answer here, on this page.
#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 a function/method/routine to use the the Shoelace formula to calculate the area of the polygon described by the ordered points: (3,4), (5,11), (12,8), (9,5), and (5,6) Show the answer here, on this page.
#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 @ '(' x.# "," y.# ')' "," @ end /*#*/ /* [↨] get X and Y coördinates.*/ z= #+1; y.0= y.#; y.z= y.1 /*define low & high Y end points*/ do j=1 for #; jm= j-1; jp= j+1; A= A + x.j*(y.jm - y.jp) /*portion of area*/ end /*j*/ /*stick a fork in it, we're done*/ say 'polygon area of ' # " points: " $ ' is ───► ' abs(A/2)
http://rosettacode.org/wiki/Shell_one-liner
Shell one-liner
Task Show how to specify and execute a short program in the language from a command shell, where the input to the command shell is only one line in length. Avoid depending on the particular shell or operating system used as much as is reasonable; if the language has notable implementations which have different command argument syntax, or the systems those implementations run on have different styles of shells, it would be good to show multiple examples.
#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 command argument syntax, or the systems those implementations run on have different styles of shells, it would be good to show multiple examples.
#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 command argument syntax, or the systems those implementations run on have different styles of shells, it would be good to show multiple examples.
#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 command argument syntax, or the systems those implementations run on have different styles of shells, it would be good to show multiple examples.
#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, and is to be minimized. If we needed to compute the conjunction   (and): x = a() and b() Then it would be best to not compute the value of   b()   if the value of   a()   is computed as   false,   as the value of   x   can then only ever be   false. Similarly, if we needed to compute the disjunction (or): y = a() or b() Then it would be best to not compute the value of   b()   if the value of   a()   is computed as   true,   as the value of   y   can then only ever be   true. Some languages will stop further computation of boolean equations as soon as the result is known, so-called   short-circuit evaluation   of boolean expressions Task Create two functions named   a   and   b,   that take and return the same boolean value. The functions should also print their name whenever they are called. Calculate and assign the values of the following equations to a variable in such a way that function   b   is only called when necessary: x = a(i) and b(j) y = a(i) or b(j) If the language does not have short-circuit evaluation, this might be achieved with nested     if     statements.
#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("Trace: ", terminator: "") print("\nResult: \(a(i) || b(j))")   print() }   testMe(false, false) testMe(false, true) testMe(true, false) testMe(true, 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, and is to be minimized. If we needed to compute the conjunction   (and): x = a() and b() Then it would be best to not compute the value of   b()   if the value of   a()   is computed as   false,   as the value of   x   can then only ever be   false. Similarly, if we needed to compute the disjunction (or): y = a() or b() Then it would be best to not compute the value of   b()   if the value of   a()   is computed as   true,   as the value of   y   can then only ever be   true. Some languages will stop further computation of boolean equations as soon as the result is known, so-called   short-circuit evaluation   of boolean expressions Task Create two functions named   a   and   b,   that take and return the same boolean value. The functions should also print their name whenever they are called. Calculate and assign the values of the following equations to a variable in such a way that function   b   is only called when necessary: x = a(i) and b(j) y = a(i) or b(j) If the language does not have short-circuit evaluation, this might be achieved with nested     if     statements.
#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 arm assembly */ /************************************/ /* Constantes */ /************************************/ .include "../constantes.inc"   .equ LGHASH, 32 // result length   /*******************************************/ /* Structures */ /********************************************/ /* example structure variables */ .struct 0 var_a: // a .struct var_a + 4 var_b: // b .struct var_b + 4 var_c: // c .struct var_c + 4 var_d: // d .struct var_d + 4 var_e: // e .struct var_e + 4 var_f: // f .struct var_f + 4 var_g: // g .struct var_g + 4 var_h: // h .struct var_h + 4   /*********************************/ /* Initialized data */ /*********************************/ .data szMessRosetta: .asciz "Rosetta code" szMessTest1: .asciz "abc" szMessSup64: .ascii "ABCDEFGHIJKLMNOPQRSTUVWXYZ" .ascii "abcdefghijklmnopqrstuvwxyz" .asciz "1234567890AZERTYUIOP" szMessTest2: .asciz "abcdbcdecdefdefgefghfghighijhijkijkljklmklmnlmnomnopnopq" szMessFinPgm: .asciz "Program End ok.\n" szMessResult: .asciz "Rosetta code => " szCarriageReturn: .asciz "\n"   /* array constantes Hi */ tbConstHi: .int 0x6A09E667 @ H0 .int 0xBB67AE85 @ H1 .int 0x3C6EF372 @ H2 .int 0xA54FF53A @ H3 .int 0x510E527F @ H4 .int 0x9B05688C @ H5 .int 0x1F83D9AB @ H6 .int 0x5BE0CD19 @ H7 /* array 64 constantes Kt */ tbConstKt: .int 0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5 .int 0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3, 0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174 .int 0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc, 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da .int 0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7, 0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967 .int 0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13, 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85 .int 0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3, 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070 .int 0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5, 0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3 .int 0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208, 0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2   /*********************************/ /* UnInitialized data */ /*********************************/ .bss .align 4 iNbBlocs: .skip 4 sZoneConv: .skip 24 sZoneTrav: .skip 1000 .align 8 tbH: .skip 4 * 8 @ 8 variables H tbabcdefgh: .skip 4 * 8 tbW: .skip 4 * 64 @ 64 words W /*********************************/ /* code section */ /*********************************/ .text .global main main: @ entry of program   ldr r0,iAdrszMessRosetta //ldr r0,iAdrszMessTest1 //ldr r0,iAdrszMessTest2 //ldr r0,iAdrszMessSup64 bl computeSHA256 @ call routine SHA1   ldr r0,iAdrszMessResult bl affichageMess @ display message   ldr r0, iAdrtbH bl displaySHA1   ldr r0,iAdrszMessFinPgm bl affichageMess @ display message     100: @ standard end of the program mov r0, #0 @ return code mov r7, #EXIT @ request to exit program svc #0 @ perform the system call   iAdrszCarriageReturn: .int szCarriageReturn iAdrszMessResult: .int szMessResult iAdrszMessRosetta: .int szMessRosetta iAdrszMessTest1: .int szMessTest1 iAdrszMessTest2: .int szMessTest2 iAdrsZoneTrav: .int sZoneTrav iAdrsZoneConv: .int sZoneConv iAdrszMessFinPgm: .int szMessFinPgm iAdrszMessSup64: .int szMessSup64 /******************************************************************/ /* compute SHA1 */ /******************************************************************/ /* r0 contains the address of the message */ computeSHA256: push {r1-r12,lr} @ save registres ldr r1,iAdrsZoneTrav mov r2,#0 @ counter length debCopy: @ copy string in work area ldrb r3,[r0,r2] strb r3,[r1,r2] cmp r3,#0 addne r2,r2,#1 bne debCopy lsl r6,r2,#3 @ initial message length in bits mov r3,#0b10000000 @ add bit 1 at end of string strb r3,[r1,r2] add r2,r2,#1 @ length in bytes lsl r4,r2,#3 @ length in bits mov r3,#0 addZeroes: lsr r5,r2,#6 lsl r5,r5,#6 sub r5,r2,r5 cmp r5,#56 beq storeLength @ yes -> end add strb r3,[r1,r2] @ add zero at message end add r2,#1 @ increment lenght bytes add r4,#8 @ increment length in bits b addZeroes storeLength: add r2,#4 @ add four bytes rev r6,r6 @ inversion bits initials message length str r6,[r1,r2] @ and store at end   ldr r7,iAdrtbConstHi @ constantes H address ldr r4,iAdrtbH @ start area H mov r5,#0 loopConst: @ init array H with start constantes ldr r6,[r7,r5,lsl #2] @ load constante str r6,[r4,r5,lsl #2] @ and store add r5,r5,#1 cmp r5,#8 blt loopConst @ split into block of 64 bytes add r2,#4 @ TODO : à revoir lsr r4,r2,#6 @ blocks number ldr r0,iAdriNbBlocs str r4,[r0] @ save block maxi mov r7,#0 @ n° de block et r1 contient l adresse zone de travail loopBlock: @ begin loop of each block of 64 bytes mov r0,r7 bl inversion @ inversion each word because little indian ldr r3,iAdrtbW @ working area W address mov r6,#0 @ indice t /* r2 address begin each block */ ldr r1,iAdrsZoneTrav add r2,r1,r7,lsl #6 @ compute block begin indice * 4 * 16 //vidregtit avantloop //mov r0,r2 //vidmemtit verifBloc r0 10 loopPrep: @ loop for expand 80 words cmp r6,#15 @ bgt expand1 ldr r0,[r2,r6,lsl #2] @ load byte message str r0,[r3,r6,lsl #2] @ store in first 16 block b expandEnd   expand1: sub r8,r6,#2 ldr r9,[r3,r8,lsl #2] ror r10,r9,#17 @ fonction e1 (256) ror r11,r9,#19 eor r10,r10,r11 lsr r11,r9,#10 eor r10,r10,r11 sub r8,r6,#7 ldr r9,[r3,r8,lsl #2] add r9,r9,r10 @ + w - 7 sub r8,r6,#15 ldr r10,[r3,r8,lsl #2] ror r11,r10,#7 @ fonction e0 (256) ror r12,r10,#18 eor r11,r12 lsr r12,r10,#3 eor r10,r11,r12 add r9,r9,r10 sub r8,r6,#16 ldr r11,[r3,r8,lsl #2] add r9,r9,r11   str r9,[r3,r6,lsl #2] expandEnd: add r6,r6,#1 cmp r6,#64 @ 64 words ? blt loopPrep @ and loop     /* COMPUTING THE MESSAGE DIGEST */ /* r1 area H constantes address */ /* r3 working area W address */ /* r5 address constantes K */ /* r6 counter t */ /* r7 block counter */ /* r8 addresse variables a b c d e f g h */ //ldr r0,iAdrtbW //vidmemtit verifW80 r0 20 @ init variable a b c d e f g h ldr r0,iAdrtbH ldr r8,iAdrtbabcdefgh mov r1,#0 loopInita: ldr r9,[r0,r1,lsl #2] str r9,[r8,r1,lsl #2] add r1,r1,#1 cmp r1,#8 blt loopInita     ldr r1,iAdrtbConstHi ldr r5,iAdrtbConstKt mov r6,#0 loop64T: @ begin loop 64 t ldr r9,[r8,#var_h] ldr r10,[r8,#var_e] @ calcul T1 ror r11,r10,#6 @ fonction sigma 1 ror r12,r10,#11 eor r11,r12 ror r12,r10,#25 eor r11,r12 add r9,r9,r11 @ h + sigma1 (e) ldr r0,[r8,#var_f] @ fonction ch x and y xor (non x and z) ldr r4,[r8,#var_g] and r11,r10,r0 mvn r12,r10 and r12,r12,r4 eor r11,r12 add r9,r9,r11 @ h + sigma1 (e) + ch (e,f,g) ldr r0,[r5,r6,lsl #2] @ load constantes k0 add r9,r9,r0 ldr r0,[r3,r6,lsl #2] @ Wt add r9,r9,r0 @ calcul T2 ldr r10,[r8,#var_a] @ fonction sigma 0 ror r11,r10,#2 ror r12,r10,#13 eor r11,r11,r12 ror r12,r10,#22 eor r11,r11,r12 ldr r2,[r8,#var_b] ldr r4,[r8,#var_c] @ fonction maj x and y xor x and z xor y and z and r12,r10,r2 and r0,r10,r4 eor r12,r12,r0 and r0,r2,r4 eor r12,r12,r0 @ add r12,r12,r11 @ T2 @ compute variables ldr r4,[r8,#var_g] str r4,[r8,#var_h] ldr r4,[r8,#var_f] str r4,[r8,#var_g] ldr r4,[r8,#var_e] str r4,[r8,#var_f] ldr r4,[r8,#var_d] add r4,r4,r9 @ add T1 str r4,[r8,#var_e] ldr r4,[r8,#var_c] str r4,[r8,#var_d] ldr r4,[r8,#var_b] str r4,[r8,#var_c] ldr r4,[r8,#var_a] str r4,[r8,#var_b] add r4,r9,r12 @ add T1 T2 str r4,[r8,#var_a] mov r0,r8   add r6,r6,#1 @ increment t cmp r6,#64 blt loop64T @ End block ldr r0,iAdrtbH @ start area H mov r10,#0 loopStoreH: ldr r9,[r8,r10,lsl #2] ldr r3,[r0,r10,lsl #2] add r3,r9 str r3,[r0,r10,lsl #2] @ store variables in H0 add r10,r10,#1 cmp r10,#8 blt loopStoreH @ other bloc add r7,#1 @ increment block ldr r0,iAdriNbBlocs ldr r4,[r0] @ restaur maxi block cmp r7,r4 @ maxi ?   blt loopBlock @ loop other block   mov r0,#0 @ routine OK 100: pop {r1-r12,lr} @ restaur registers bx lr @ return iAdrtbConstHi: .int tbConstHi iAdrtbConstKt: .int tbConstKt iAdrtbH: .int tbH iAdrtbW: .int tbW iAdrtbabcdefgh: .int tbabcdefgh iAdriNbBlocs: .int iNbBlocs /******************************************************************/ /* inversion des mots de 32 bits d un bloc */ /******************************************************************/ /* r0 contains N° block */ inversion: push {r1-r3,lr} @ save registers ldr r1,iAdrsZoneTrav add r1,r0,lsl #6 @ debut du bloc mov r2,#0 1: @ start loop ldr r3,[r1,r2,lsl #2] rev r3,r3 str r3,[r1,r2,lsl #2] add r2,r2,#1 cmp r2,#16 blt 1b 100: pop {r1-r3,lr} @ restaur registres bx lr @return /******************************************************************/ /* display hash SHA1 */ /******************************************************************/ /* r0 contains the address of hash */ displaySHA1: push {r1-r3,lr} @ save registres mov r3,r0 mov r2,#0 1: ldr r0,[r3,r2,lsl #2] @ load 4 bytes //rev r0,r0 @ reverse bytes ldr r1,iAdrsZoneConv bl conversion16 @ conversion hexa ldr r0,iAdrsZoneConv bl affichageMess add r2,r2,#1 cmp r2,#LGHASH / 4 blt 1b @ and loop ldr r0,iAdrszCarriageReturn bl affichageMess @ display message 100: pop {r1-r3,lr} @ restaur registers bx lr @ return /***************************************************/ /* ROUTINES INCLUDE */ /***************************************************/ .include "../affichage.inc"  
http://rosettacode.org/wiki/SHA-1
SHA-1
SHA-1 or SHA1 is a one-way hash function; it computes a 160-bit message digest. SHA-1 often appears in security protocols; for example, many HTTPS websites use RSA with SHA-1 to secure their connections. BitTorrent uses SHA-1 to verify downloads. Git and Mercurial use SHA-1 digests to identify commits. A US government standard, FIPS 180-1, defines SHA-1. Find the SHA-1 message digest for a string of octets. You may either call a SHA-1 library, or implement SHA-1 in your language. Both approaches interest Rosetta Code. Warning: SHA-1 has known weaknesses. Theoretical attacks may find a collision after 252 operations, or perhaps fewer. This is much faster than a brute force attack of 280 operations. USgovernment deprecated SHA-1. For production-grade cryptography, users may consider a stronger alternative, such as SHA-256 (from the SHA-2 family) or the upcoming SHA-3.
#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 ====================================================================== CalcAddrHash(addr, length, algid, byref hash = 0, byref hashlength = 0) { static h := [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, "A", "B", "C", "D", "E", "F"] static b := h.minIndex() o := "" if (DllCall("advapi32\CryptAcquireContext", "Ptr*", hProv, "Ptr", 0, "Ptr", 0, "UInt", 24, "UInt", 0xF0000000)) { if (DllCall("advapi32\CryptCreateHash", "Ptr", hProv, "UInt", algid, "UInt", 0, "UInt", 0, "Ptr*", hHash)) { if (DllCall("advapi32\CryptHashData", "Ptr", hHash, "Ptr", addr, "UInt", length, "UInt", 0)) { if (DllCall("advapi32\CryptGetHashParam", "Ptr", hHash, "UInt", 2, "Ptr", 0, "UInt*", hashlength, "UInt", 0)) { VarSetCapacity(hash, hashlength, 0) if (DllCall("advapi32\CryptGetHashParam", "Ptr", hHash, "UInt", 2, "Ptr", &hash, "UInt*", hashlength, "UInt", 0)) { loop, % hashlength { v := NumGet(hash, A_Index - 1, "UChar") o .= h[(v >> 4) + b] h[(v & 0xf) + b] } } } } DllCall("advapi32\CryptDestroyHash", "Ptr", hHash) } DllCall("advapi32\CryPtreleaseContext", "Ptr", hProv, "UInt", 0) } return o }   ; CalcStringHash ==================================================================== CalcStringHash(string, algid, encoding = "utf-8", byref hash = 0, byref hashlength = 0) { chrlength := (encoding = "cp1200" || encoding = "utf-16") ? 2 : 1 length := (StrPut(string, encoding) - 1) * chrlength VarSetCapacity(data, length, 0) StrPut(string, &data, floor(length / chrlength), encoding) return CalcAddrHash(&data, length, algid, hash, hashlength) }
http://rosettacode.org/wiki/Sexy_primes
Sexy primes
This page uses content from Wikipedia. The original article was at Sexy_prime. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance) In mathematics, sexy primes are prime numbers that differ from each other by six. For example, the numbers 5 and 11 are both sexy primes, because 11 minus 6 is 5. The term "sexy prime" is a pun stemming from the Latin word for six: sex. Sexy prime pairs: Sexy prime pairs are groups of two primes that differ by 6. e.g. (5 11), (7 13), (11 17) See sequences: OEIS:A023201 and OEIS:A046117 Sexy prime triplets: Sexy prime triplets are groups of three primes where each differs from the next by 6. e.g. (5 11 17), (7 13 19), (17 23 29) See sequences: OEIS:A046118, OEIS:A046119 and OEIS:A046120 Sexy prime quadruplets: Sexy prime quadruplets are groups of four primes where each differs from the next by 6. e.g. (5 11 17 23), (11 17 23 29) See sequences: OEIS:A023271, OEIS:A046122, OEIS:A046123 and OEIS:A046124 Sexy prime quintuplets: Sexy prime quintuplets are groups of five primes with a common difference of 6. One of the terms must be divisible by 5, because 5 and 6 are relatively prime. Thus, the only possible sexy prime quintuplet is (5 11 17 23 29) Task For each of pairs, triplets, quadruplets and quintuplets, Find and display the count of each group type of sexy primes less than one million thirty-five (1,000,035). Display at most the last 5, less than one million thirty-five, of each sexy prime group type. Find and display the count of the unsexy primes less than one million thirty-five. Find and display the last 10 unsexy primes less than one million thirty-five. Note that 1000033 SHOULD NOT be counted in the pair count. It is sexy, but not in a pair within the limit. However, it also SHOULD NOT be listed in the unsexy primes since it is sexy.
#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 "%d " n); printfn "" let ni=pCache |> Seq.takeWhile(fun n->n<1000035) |> Seq.filter(fun n->isPrime(n-6)) |> Array.ofSeq printfn "There are %d sexy prime pairs all components of which are less than 1,000,035. The last 5 are:" ni.Length Array.skip (ni.Length-5) ni |> Array.iter(fun n->printf "(%d,%d) " (n-6) n); printfn "" let nig=ni |> Array.filter(fun n->isPrime(n-12)) printfn "There are %d sexy prime triplets all components of which are less than 1,000,035. The last 5 are:" nig.Length Array.skip (nig.Length-5) nig |> Array.iter(fun n->printf "(%d,%d,%d) " (n-12) (n-6) n); printfn "" let nige=nig |> Array.filter(fun n->isPrime(n-18)) printfn "There are %d sexy prime quadruplets all components of which are less than 1,000,035. The last 5 are:" nige.Length Array.skip (nige.Length-5) nige |> Array.iter(fun n->printf "(%d,%d,%d,%d) " (n-18) (n-12) (n-6) n); printfn "" let nigel=nige |> Array.filter(fun n->isPrime(n-24)) printfn "There are %d sexy prime quintuplets all components of which are less than 1,000,035. The last 5 are:" nigel.Length Array.skip (nigel.Length-5) nigel |> Array.iter(fun n->printf "(%d,%d,%d,%d,%d) " (n-24) (n-18) (n-12) (n-6) n); printfn ""  
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 a nibble gets changed: n = 2; Width e = 4: Input b: 1000 Result: 1110 Input b: 0100 Result: 0111 Input b: 0010 Result: 0011 Input b: 0000 Result: 0000 Set of examples with the same input with set bits of varying distance apart: n = 0; Width e = 66: Input b: 010000000000100000000010000000010000000100000010000010000100010010 Result: 010000000000100000000010000000010000000100000010000010000100010010 n = 1; Width e = 66: Input b: 010000000000100000000010000000010000000100000010000010000100010010 Result: 011000000000110000000011000000011000000110000011000011000110011011 n = 2; Width e = 66: Input b: 010000000000100000000010000000010000000100000010000010000100010010 Result: 011100000000111000000011100000011100000111000011100011100111011111 n = 3; Width e = 66: Input b: 010000000000100000000010000000010000000100000010000010000100010010 Result: 011110000000111100000011110000011110000111100011110011110111111111 Task: Implement a routine to perform the setting of right-adjacent bits on representations of bits that will scale over the given range of input width e. Use it to show, here, the results for the input examples above. Print the output aligned in a way that allows easy checking by eye of the binary input vs output.
#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 setrightadj("0100", 2) @show setrightadj("0010", 2) @show setrightadj("0000", 2)   @show setrightadj("010000000000100000000010000000010000000100000010000010000100010010", 0) @show setrightadj("010000000000100000000010000000010000000100000010000010000100010010", 1) @show setrightadj("010000000000100000000010000000010000000100000010000010000100010010", 2) @show setrightadj("010000000000100000000010000000010000000100000010000010000100010010", 3)  
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 a nibble gets changed: n = 2; Width e = 4: Input b: 1000 Result: 1110 Input b: 0100 Result: 0111 Input b: 0010 Result: 0011 Input b: 0000 Result: 0000 Set of examples with the same input with set bits of varying distance apart: n = 0; Width e = 66: Input b: 010000000000100000000010000000010000000100000010000010000100010010 Result: 010000000000100000000010000000010000000100000010000010000100010010 n = 1; Width e = 66: Input b: 010000000000100000000010000000010000000100000010000010000100010010 Result: 011000000000110000000011000000011000000110000011000011000110011011 n = 2; Width e = 66: Input b: 010000000000100000000010000000010000000100000010000010000100010010 Result: 011100000000111000000011100000011100000111000011100011100111011111 n = 3; Width e = 66: Input b: 010000000000100000000010000000010000000100000010000010000100010010 Result: 011110000000111100000011110000011110000111100011110011110111111111 Task: Implement a routine to perform the setting of right-adjacent bits on representations of bits that will scale over the given range of input width e. Use it to show, here, the results for the input examples above. Print the output aligned in a way that allows easy checking by eye of the binary input vs output.
#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\n"; }   __DATA__ 2 1000 2 0100 2 0011 2 0000 0 010000000000100000000010000000010000000100000010000010000100010010 1 010000000000100000000010000000010000000100000010000010000100010010 2 010000000000100000000010000000010000000100000010000010000100010010 3 010000000000100000000010000000010000000100000010000010000100010010
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 a nibble gets changed: n = 2; Width e = 4: Input b: 1000 Result: 1110 Input b: 0100 Result: 0111 Input b: 0010 Result: 0011 Input b: 0000 Result: 0000 Set of examples with the same input with set bits of varying distance apart: n = 0; Width e = 66: Input b: 010000000000100000000010000000010000000100000010000010000100010010 Result: 010000000000100000000010000000010000000100000010000010000100010010 n = 1; Width e = 66: Input b: 010000000000100000000010000000010000000100000010000010000100010010 Result: 011000000000110000000011000000011000000110000011000011000110011011 n = 2; Width e = 66: Input b: 010000000000100000000010000000010000000100000010000010000100010010 Result: 011100000000111000000011100000011100000111000011100011100111011111 n = 3; Width e = 66: Input b: 010000000000100000000010000000010000000100000010000010000100010010 Result: 011110000000111100000011110000011110000111100011110011110111111111 Task: Implement a routine to perform the setting of right-adjacent bits on representations of bits that will scale over the given range of input width e. Use it to show, here, the results for the input examples above. Print the output aligned in a way that allows easy checking by eye of the binary input vs output.
#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]):0)-bit if count and not bit then res[i] = '1' end if k -= 1 end for assert(count=0) return res end function constant tests = {{"1000",2,2},{"0100",2,2},{"0010",2,2},{"0000",2,2}, {"010000000000100000000010000000010000000100000010000010000100010010",0,3}} for i=1 to length(tests) do {string input, integer l, integer m} = tests[i] printf(1,"input: %s (width %d)\n",{input,length(input)}) for n=l to m do printf(1,"n = %d: %s\n",{n,str_srb(input,n)}) end for end 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 paired up and concatenated together, and a new hash is computed from each concatenation. Then these are paired up and concatenated and hashed, and the process continues until there is only one hash left, which is the final checksum. The hexadecimal representation of this checksum is the value that must be included with the AWS API call to upload the object (or complete a multipart upload). Implement this algorithm in your language; you can use the code from the SHA-256 task for the actual hash computations. For better manageability and portability, build the tree using a smaller block size of only 1024 bytes, and demonstrate it on the RosettaCode title image with that block size. The final result should be the hexadecimal digest value a4f902cf9d51fe51eda156a6792e1445dff65edf3a217a1f3334cc9cf1495c2c.
#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 BufferedInputStream(new FileInputStream(args[0]))) { byte[] digest = sha256MerkleTree(in, 1024); if (digest != null) System.out.println(digestToString(digest)); } catch (Exception e) { e.printStackTrace(); } }   private static String digestToString(byte[] digest) { StringBuilder result = new StringBuilder(); for (int i = 0; i < digest.length; ++i) result.append(String.format("%02x", digest[i])); return result.toString(); }   private static byte[] sha256MerkleTree(InputStream in, int blockSize) throws Exception { byte[] buffer = new byte[blockSize]; int bytes; MessageDigest md = MessageDigest.getInstance("SHA-256"); List<byte[]> digests = new ArrayList<>(); while ((bytes = in.read(buffer)) > 0) { md.reset(); md.update(buffer, 0, bytes); digests.add(md.digest()); } int length = digests.size(); if (length == 0) return null; while (length > 1) { int j = 0; for (int i = 0; i < length; i += 2, ++j) { byte[] digest1 = digests.get(i); if (i + 1 < length) { byte[] digest2 = digests.get(i + 1); md.reset(); md.update(digest1); md.update(digest2); digests.set(j, md.digest()); } else { digests.set(j, digest1); } } length = j; } return digests.get(0); } }
http://rosettacode.org/wiki/Show_ASCII_table
Show ASCII table
Task Show  the ASCII character set  from values   32   to   127   (decimal)   in a table format. Other tasks related to string operations: Metrics Array length String length Copy a string Empty string  (assignment) Counting Word frequency Letter frequency Jewels and stones I before E except after C Bioinformatics/base count Count occurrences of a substring Count how many vowels and consonants occur in a string Remove/replace XXXX redacted Conjugate a Latin verb Remove vowels from a string String interpolation (included) Strip block comments Strip comments from a string Strip a set of characters from a string Strip whitespace from a string -- top and tail Strip control codes and extended characters from a string Anagrams/Derangements/shuffling Word wheel ABC problem Sattolo cycle Knuth shuffle Ordered words Superpermutation minimisation Textonyms (using a phone text pad) Anagrams Anagrams/Deranged anagrams Permutations/Derangements Find/Search/Determine ABC words Odd words Word ladder Semordnilap Word search Wordiff  (game) String matching Tea cup rim text Alternade words Changeable words State name puzzle String comparison Unique characters Unique characters in each string Extract file extension Levenshtein distance Palindrome detection Common list elements Longest common suffix Longest common prefix Compare a list of strings Longest common substring Find common directory path Words from neighbour ones Change e letters to i in words Non-continuous subsequences Longest common subsequence Longest palindromic substrings Longest increasing subsequence Words containing "the" substring Sum of the digits of n is substring of n Determine if a string is numeric Determine if a string is collapsible Determine if a string is squeezable Determine if a string has all unique characters Determine if a string has all the same characters Longest substrings without repeating characters Find words which contains all the vowels Find words which contains most consonants Find words which contains more than 3 vowels Find words which first and last three letters are equals Find words which odd letters are consonants and even letters are vowels or vice_versa Formatting Substring Rep-string Word wrap String case Align columns Literals/String Repeat a string Brace expansion Brace expansion using ranges Reverse a string Phrase reversals Comma quibbling Special characters String concatenation Substring/Top and tail Commatizing numbers Reverse words in a string Suffixation of decimal numbers Long literals, with continuations Numerical and alphabetical suffixes Abbreviations, easy Abbreviations, simple Abbreviations, automatic Song lyrics/poems/Mad Libs/phrases Mad Libs Magic 8-ball 99 Bottles of Beer The Name Game (a song) The Old lady swallowed a fly The Twelve Days of Christmas Tokenize Text between Tokenize a string Word break problem Tokenize a string with escaping Split a character string based on change of character Sequences Show ASCII table De Bruijn sequences Self-referential sequences Generate lower case ASCII alphabet
#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: return "Spc"; case DELETE: return "Del"; default: return std::string(1,char(ascii)); } }   int main(void) {   for(int row = 0; row < HEIGHT; ++row) { for(int col = 0; col < WIDTH; ++col) { int ascii = ASCII_START + row + col*HEIGHT; std::cout << std::right << std::setw(3) << ascii << " : " \ << std::left << std::setw(6) << displayAscii(ascii); } std::cout << std::endl; } }
http://rosettacode.org/wiki/Sierpinski_triangle
Sierpinski triangle
Task Produce an ASCII representation of a Sierpinski triangle of order   N. Example The Sierpinski triangle of order   4   should look like this: * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * Related tasks Sierpinski triangle/Graphical for graphics images of this pattern. Sierpinski carpet
#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); String [] split = s.split("\n"); int length = split.length;   // Top triangle StringBuilder sb = new StringBuilder(); String top = buildSpace((int)Math.pow(2, n-1)); for ( int i = 0 ; i < length ;i++ ) { sb.append(top); sb.append(split[i]); sb.append("\n"); }   // Two triangles side by side for ( int i = 0 ; i < length ;i++ ) { sb.append(split[i]); sb.append(buildSpace(length-i)); sb.append(split[i]); sb.append("\n"); } return sb.toString(); }   private static String buildSpace(int n) { StringBuilder sb = new StringBuilder(); while ( n > 0 ) { sb.append(" "); n--; } return sb.toString(); }   }  
http://rosettacode.org/wiki/Sierpinski_carpet
Sierpinski carpet
Task Produce a graphical or ASCII-art representation of a Sierpinski carpet of order   N. For example, the Sierpinski carpet of order   3   should look like this: ########################### # ## ## ## ## ## ## ## ## # ########################### ### ###### ###### ### # # # ## # # ## # # # ### ###### ###### ### ########################### # ## ## ## ## ## ## ## ## # ########################### ######### ######### # ## ## # # ## ## # ######### ######### ### ### ### ### # # # # # # # # ### ### ### ### ######### ######### # ## ## # # ## ## # ######### ######### ########################### # ## ## ## ## ## ## ## ## # ########################### ### ###### ###### ### # # # ## # # ## # # # ### ###### ###### ### ########################### # ## ## ## ## ## ## ## ## # ########################### The use of the   #   character is not rigidly required for ASCII art. The important requirement is the placement of whitespace and non-whitespace characters. Related task   Sierpinski triangle
#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 ; Y=:=0 -> io:format("*"); (X rem 3)=:=1, (Y rem 3) =:=1 -> io:format(" "); true -> carpet(X div 3, Y div 3) 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 a function/method/routine to use the the Shoelace formula to calculate the area of the polygon described by the ordered points: (3,4), (5,11), (12,8), (9,5), and (5,6) Show the answer here, on this page.
#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 sum = sum + p[i][1] * p[1][2] sum = sum - p[1][1] * p[i][2] return fabs(sum) / 2  
http://rosettacode.org/wiki/Shoelace_formula_for_polygonal_area
Shoelace formula for polygonal area
Given the n + 1 vertices x[0], y[0] .. x[N], y[N] of a simple polygon described in a clockwise direction, then the polygon's area can be calculated by: abs( (sum(x[0]*y[1] + ... x[n-1]*y[n]) + x[N]*y[0]) - (sum(x[1]*y[0] + ... x[n]*y[n-1]) + x[0]*y[N]) ) / 2 (Where abs returns the absolute value) Task Write a function/method/routine to use the the Shoelace formula to calculate the area of the polygon described by the ordered points: (3,4), (5,11), (12,8), (9,5), and (5,6) Show the answer here, on this page.
#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   end   puts Polygon.new([3,4], [5,11], [12,8], [9,5], [5,6]).area # => 30.0  
http://rosettacode.org/wiki/Shell_one-liner
Shell one-liner
Task Show how to specify and execute a short program in the language from a command shell, where the input to the command shell is only one line in length. Avoid depending on the particular shell or operating system used as much as is reasonable; if the language has notable implementations which have different command argument syntax, or the systems those implementations run on have different styles of shells, it would be good to show multiple examples.
#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 command argument syntax, or the systems those implementations run on have different styles of shells, it would be good to show multiple examples.
#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, and is to be minimized. If we needed to compute the conjunction   (and): x = a() and b() Then it would be best to not compute the value of   b()   if the value of   a()   is computed as   false,   as the value of   x   can then only ever be   false. Similarly, if we needed to compute the disjunction (or): y = a() or b() Then it would be best to not compute the value of   b()   if the value of   a()   is computed as   true,   as the value of   y   can then only ever be   true. Some languages will stop further computation of boolean equations as soon as the result is known, so-called   short-circuit evaluation   of boolean expressions Task Create two functions named   a   and   b,   that take and return the same boolean value. The functions should also print their name whenever they are called. Calculate and assign the values of the following equations to a variable in such a way that function   b   is only called when necessary: x = a(i) and b(j) y = a(i) or b(j) If the language does not have short-circuit evaluation, this might be achieved with nested     if     statements.
#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) { console.printLine(i," and ",j," = ",a(i) && b(j));   console.writeLine(); console.printLine(i," or ",j," = ",a(i) || b(j)); console.writeLine() } } }
http://rosettacode.org/wiki/Short-circuit_evaluation
Short-circuit evaluation
Control Structures These are examples of control structures. You may also be interested in: Conditional structures Exceptions Flow-control structures Loops Assume functions   a   and   b   return boolean values,   and further, the execution of function   b   takes considerable resources without side effects, and is to be minimized. If we needed to compute the conjunction   (and): x = a() and b() Then it would be best to not compute the value of   b()   if the value of   a()   is computed as   false,   as the value of   x   can then only ever be   false. Similarly, if we needed to compute the disjunction (or): y = a() or b() Then it would be best to not compute the value of   b()   if the value of   a()   is computed as   true,   as the value of   y   can then only ever be   true. Some languages will stop further computation of boolean equations as soon as the result is known, so-called   short-circuit evaluation   of boolean expressions Task Create two functions named   a   and   b,   that take and return the same boolean value. The functions should also print their name whenever they are called. Calculate and assign the values of the following equations to a variable in such a way that function   b   is only called when necessary: x = a(i) and b(j) y = a(i) or b(j) If the language does not have short-circuit evaluation, this might be achieved with nested     if     statements.
#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" IO.puts "a( #{i} ) or b( #{j} ) is #{a(i) or b(j)}.\n" end) end) end end   Short_circuit.task
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 ====================================================================== CalcAddrHash(addr, length, algid, byref hash = 0, byref hashlength = 0) { static h := [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, "A", "B", "C", "D", "E", "F"] static b := h.minIndex() o := "" if (DllCall("advapi32\CryptAcquireContext", "Ptr*", hProv, "Ptr", 0, "Ptr", 0, "UInt", 24, "UInt", 0xF0000000)) { if (DllCall("advapi32\CryptCreateHash", "Ptr", hProv, "UInt", algid, "UInt", 0, "UInt", 0, "Ptr*", hHash)) { if (DllCall("advapi32\CryptHashData", "Ptr", hHash, "Ptr", addr, "UInt", length, "UInt", 0)) { if (DllCall("advapi32\CryptGetHashParam", "Ptr", hHash, "UInt", 2, "Ptr", 0, "UInt*", hashlength, "UInt", 0)) { VarSetCapacity(hash, hashlength, 0) if (DllCall("advapi32\CryptGetHashParam", "Ptr", hHash, "UInt", 2, "Ptr", &hash, "UInt*", hashlength, "UInt", 0)) { loop, % hashlength { v := NumGet(hash, A_Index - 1, "UChar") o .= h[(v >> 4) + b] h[(v & 0xf) + b] } } } } DllCall("advapi32\CryptDestroyHash", "Ptr", hHash) } DllCall("advapi32\CryPtreleaseContext", "Ptr", hProv, "UInt", 0) } return o }   ; CalcStringHash ==================================================================== CalcStringHash(string, algid, encoding = "utf-8", byref hash = 0, byref hashlength = 0) { chrlength := (encoding = "cp1200" || encoding = "utf-16") ? 2 : 1 length := (StrPut(string, encoding) - 1) * chrlength VarSetCapacity(data, length, 0) StrPut(string, &data, floor(length / chrlength), encoding) return CalcAddrHash(&data, length, algid, hash, hashlength) }
http://rosettacode.org/wiki/SHA-1
SHA-1
SHA-1 or SHA1 is a one-way hash function; it computes a 160-bit message digest. SHA-1 often appears in security protocols; for example, many HTTPS websites use RSA with SHA-1 to secure their connections. BitTorrent uses SHA-1 to verify downloads. Git and Mercurial use SHA-1 digests to identify commits. A US government standard, FIPS 180-1, defines SHA-1. Find the SHA-1 message digest for a string of octets. You may either call a SHA-1 library, or implement SHA-1 in your language. Both approaches interest Rosetta Code. Warning: SHA-1 has known weaknesses. Theoretical attacks may find a collision after 252 operations, or perhaps fewer. This is much faster than a brute force attack of 280 operations. USgovernment deprecated SHA-1. For production-grade cryptography, users may consider a stronger alternative, such as SHA-256 (from the SHA-2 family) or the upcoming SHA-3.
#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", ^hprov%, 0, 0, PROV_RSA_FULL, CRYPT_VERIFYCONTEXT SYS "CryptCreateHash", hprov%, CALG_SHA1, 0, 0, ^hhash% SYS "CryptHashData", hhash%, message$, LEN(message$), 0 SYS "CryptGetHashParam", hhash%, HP_HASHVAL, buffer%, ^buflen%, 0 SYS "CryptDestroyHash", hhash% SYS "CryptReleaseContext", hprov% FOR i% = 0 TO buflen%-1 hash$ += RIGHT$("0" + STR$~buffer%?i%, 2) NEXT = hash$
http://rosettacode.org/wiki/SHA-1
SHA-1
SHA-1 or SHA1 is a one-way hash function; it computes a 160-bit message digest. SHA-1 often appears in security protocols; for example, many HTTPS websites use RSA with SHA-1 to secure their connections. BitTorrent uses SHA-1 to verify downloads. Git and Mercurial use SHA-1 digests to identify commits. A US government standard, FIPS 180-1, defines SHA-1. Find the SHA-1 message digest for a string of octets. You may either call a SHA-1 library, or implement SHA-1 in your language. Both approaches interest Rosetta Code. Warning: SHA-1 has known weaknesses. Theoretical attacks may find a collision after 252 operations, or perhaps fewer. This is much faster than a brute force attack of 280 operations. USgovernment deprecated SHA-1. For production-grade cryptography, users may consider a stronger alternative, such as SHA-256 (from the SHA-2 family) or the upcoming SHA-3.
#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_DIGEST_LENGTH-1) ? ' ' : '\n');   return EXIT_SUCCESS; }
http://rosettacode.org/wiki/Seven-sided_dice_from_five-sided_dice
Seven-sided dice from five-sided dice
Task (Given an equal-probability generator of one of the integers 1 to 5 as dice5),   create dice7 that generates a pseudo-random integer from 1 to 7 in equal probability using only dice5 as a source of random numbers,   and check the distribution for at least one million calls using the function created in   Simple Random Distribution Checker. Implementation suggestion: dice7 might call dice5 twice, re-call if four of the 25 combinations are given, otherwise split the other 21 combinations into 7 groups of three, and return the group index from the rolls. (Task adapted from an answer here)
#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(bin.values().map(count -> abs(@target - count) < @deltacount)), ‘Bin distribution skewed from #. +/- #.: #.’.format(target, deltacount, sorted(bin.items()).map((key, count) -> (key, @target - count)))) print(bin)   distcheck(dice5, 1000000, 1) distcheck(dice7, 1000000, 1)
http://rosettacode.org/wiki/Sexy_primes
Sexy primes
This page uses content from Wikipedia. The original article was at Sexy_prime. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance) In mathematics, sexy primes are prime numbers that differ from each other by six. For example, the numbers 5 and 11 are both sexy primes, because 11 minus 6 is 5. The term "sexy prime" is a pun stemming from the Latin word for six: sex. Sexy prime pairs: Sexy prime pairs are groups of two primes that differ by 6. e.g. (5 11), (7 13), (11 17) See sequences: OEIS:A023201 and OEIS:A046117 Sexy prime triplets: Sexy prime triplets are groups of three primes where each differs from the next by 6. e.g. (5 11 17), (7 13 19), (17 23 29) See sequences: OEIS:A046118, OEIS:A046119 and OEIS:A046120 Sexy prime quadruplets: Sexy prime quadruplets are groups of four primes where each differs from the next by 6. e.g. (5 11 17 23), (11 17 23 29) See sequences: OEIS:A023271, OEIS:A046122, OEIS:A046123 and OEIS:A046124 Sexy prime quintuplets: Sexy prime quintuplets are groups of five primes with a common difference of 6. One of the terms must be divisible by 5, because 5 and 6 are relatively prime. Thus, the only possible sexy prime quintuplet is (5 11 17 23 29) Task For each of pairs, triplets, quadruplets and quintuplets, Find and display the count of each group type of sexy primes less than one million thirty-five (1,000,035). Display at most the last 5, less than one million thirty-five, of each sexy prime group type. Find and display the count of the unsexy primes less than one million thirty-five. Find and display the last 10 unsexy primes less than one million thirty-five. Note that 1000033 SHOULD NOT be counted in the pair count. It is sexy, but not in a pair within the limit. However, it also SHOULD NOT be listed in the unsexy primes since it is sexy.
#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 "%d " n); printfn "" let ni=pCache |> Seq.takeWhile(fun n->n<1000035) |> Seq.filter(fun n->isPrime(n-6)) |> Array.ofSeq printfn "There are %d sexy prime pairs all components of which are less than 1,000,035. The last 5 are:" ni.Length Array.skip (ni.Length-5) ni |> Array.iter(fun n->printf "(%d,%d) " (n-6) n); printfn "" let nig=ni |> Array.filter(fun n->isPrime(n-12)) printfn "There are %d sexy prime triplets all components of which are less than 1,000,035. The last 5 are:" nig.Length Array.skip (nig.Length-5) nig |> Array.iter(fun n->printf "(%d,%d,%d) " (n-12) (n-6) n); printfn "" let nige=nig |> Array.filter(fun n->isPrime(n-18)) printfn "There are %d sexy prime quadruplets all components of which are less than 1,000,035. The last 5 are:" nige.Length Array.skip (nige.Length-5) nige |> Array.iter(fun n->printf "(%d,%d,%d,%d) " (n-18) (n-12) (n-6) n); printfn "" let nigel=nige |> Array.filter(fun n->isPrime(n-24)) printfn "There are %d sexy prime quintuplets all components of which are less than 1,000,035. The last 5 are:" nigel.Length Array.skip (nigel.Length-5) nigel |> Array.iter(fun n->printf "(%d,%d,%d,%d,%d) " (n-24) (n-18) (n-12) (n-6) n); printfn ""  
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 a nibble gets changed: n = 2; Width e = 4: Input b: 1000 Result: 1110 Input b: 0100 Result: 0111 Input b: 0010 Result: 0011 Input b: 0000 Result: 0000 Set of examples with the same input with set bits of varying distance apart: n = 0; Width e = 66: Input b: 010000000000100000000010000000010000000100000010000010000100010010 Result: 010000000000100000000010000000010000000100000010000010000100010010 n = 1; Width e = 66: Input b: 010000000000100000000010000000010000000100000010000010000100010010 Result: 011000000000110000000011000000011000000110000011000011000110011011 n = 2; Width e = 66: Input b: 010000000000100000000010000000010000000100000010000010000100010010 Result: 011100000000111000000011100000011100000111000011100011100111011111 n = 3; Width e = 66: Input b: 010000000000100000000010000000010000000100000010000010000100010010 Result: 011110000000111100000011110000011110000111100011110011110111111111 Task: Implement a routine to perform the setting of right-adjacent bits on representations of bits that will scale over the given range of input width e. Use it to show, here, the results for the input examples above. Print the output aligned in a way that allows easy checking by eye of the binary input vs output.
#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" first = True for b_str in bits.split(): b = int(b_str, 2) e = len(b_str) if first: first = False print(f"n = {n}; Width e = {e}:\n") result = set_right_adjacent_bits(n, b) print(f" Input b: {b:0{e}b}") print(f" Result: {result:0{e}b}\n")   print("SAME Input & Width.\n") #bits = "01000010001001010110" bits = '01' + '1'.join('0'*x for x in range(10, 0, -1)) for n in range(4): first = True for b_str in bits.split(): b = int(b_str, 2) e = len(b_str) if first: first = False print(f"n = {n}; Width e = {e}:\n") result = set_right_adjacent_bits(n, b) print(f" Input b: {b:0{e}b}") print(f" Result: {result:0{e}b}\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 a nibble gets changed: n = 2; Width e = 4: Input b: 1000 Result: 1110 Input b: 0100 Result: 0111 Input b: 0010 Result: 0011 Input b: 0000 Result: 0000 Set of examples with the same input with set bits of varying distance apart: n = 0; Width e = 66: Input b: 010000000000100000000010000000010000000100000010000010000100010010 Result: 010000000000100000000010000000010000000100000010000010000100010010 n = 1; Width e = 66: Input b: 010000000000100000000010000000010000000100000010000010000100010010 Result: 011000000000110000000011000000011000000110000011000011000110011011 n = 2; Width e = 66: Input b: 010000000000100000000010000000010000000100000010000010000100010010 Result: 011100000000111000000011100000011100000111000011100011100111011111 n = 3; Width e = 66: Input b: 010000000000100000000010000000010000000100000010000010000100010010 Result: 011110000000111100000011110000011110000111100011110011110111111111 Task: Implement a routine to perform the setting of right-adjacent bits on representations of bits that will scale over the given range of input width e. Use it to show, here, the results for the input examples above. Print the output aligned in a way that allows easy checking by eye of the binary input vs output.
#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,4, 18455760086304825618,5, 5444684034376312377319904082902529876242,15 -> $integer, $bits {   say "\nInteger: $integer - Right-adjacent-bits: up to $bits";   .say for ^$bits .map: -> $b { $integer.&rab($b).base: 2 };   say "\nInteger: $integer - Left-adjacent-bits: up to $bits";   .say for ^$bits .map: -> $b { $integer.&lab($b).fmt("%{0~$bits+$integer.msb}b") };   }
http://rosettacode.org/wiki/SHA-256_Merkle_tree
SHA-256 Merkle tree
As described in its documentation, Amazon S3 Glacier requires that all uploaded files come with a checksum computed as a Merkle Tree using SHA-256. Specifically, the SHA-256 hash is computed for each 1MiB block of the file. And then, starting from the beginning of the file, the raw hashes of consecutive blocks are paired up and concatenated together, and a new hash is computed from each concatenation. Then these are paired up and concatenated and hashed, and the process continues until there is only one hash left, which is the final checksum. The hexadecimal representation of this checksum is the value that must be included with the AWS API call to upload the object (or complete a multipart upload). Implement this algorithm in your language; you can use the code from the SHA-256 task for the actual hash computations. For better manageability and portability, build the tree using a smaller block size of only 1024 bytes, and demonstrate it on the RosettaCode title image with that block size. The final result should be the hexadecimal digest value a4f902cf9d51fe51eda156a6792e1445dff65edf3a217a1f3334cc9cf1495c2c.
#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 + 1])) for i in 1:2:len] len = length(hsh) end return bytes2hex(hsh[1]) end   println(merkletree())  
http://rosettacode.org/wiki/SHA-256_Merkle_tree
SHA-256 Merkle tree
As described in its documentation, Amazon S3 Glacier requires that all uploaded files come with a checksum computed as a Merkle Tree using SHA-256. Specifically, the SHA-256 hash is computed for each 1MiB block of the file. And then, starting from the beginning of the file, the raw hashes of consecutive blocks are paired up and concatenated together, and a new hash is computed from each concatenation. Then these are paired up and concatenated and hashed, and the process continues until there is only one hash left, which is the final checksum. The hexadecimal representation of this checksum is the value that must be included with the AWS API call to upload the object (or complete a multipart upload). Implement this algorithm in your language; you can use the code from the SHA-256 task for the actual hash computations. For better manageability and portability, build the tree using a smaller block size of only 1024 bytes, and demonstrate it on the RosettaCode title image with that block size. The final result should be the hexadecimal digest value a4f902cf9d51fe51eda156a6792e1445dff65edf3a217a1f3334cc9cf1495c2c.
#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 Bioinformatics/base count Count occurrences of a substring Count how many vowels and consonants occur in a string Remove/replace XXXX redacted Conjugate a Latin verb Remove vowels from a string String interpolation (included) Strip block comments Strip comments from a string Strip a set of characters from a string Strip whitespace from a string -- top and tail Strip control codes and extended characters from a string Anagrams/Derangements/shuffling Word wheel ABC problem Sattolo cycle Knuth shuffle Ordered words Superpermutation minimisation Textonyms (using a phone text pad) Anagrams Anagrams/Deranged anagrams Permutations/Derangements Find/Search/Determine ABC words Odd words Word ladder Semordnilap Word search Wordiff  (game) String matching Tea cup rim text Alternade words Changeable words State name puzzle String comparison Unique characters Unique characters in each string Extract file extension Levenshtein distance Palindrome detection Common list elements Longest common suffix Longest common prefix Compare a list of strings Longest common substring Find common directory path Words from neighbour ones Change e letters to i in words Non-continuous subsequences Longest common subsequence Longest palindromic substrings Longest increasing subsequence Words containing "the" substring Sum of the digits of n is substring of n Determine if a string is numeric Determine if a string is collapsible Determine if a string is squeezable Determine if a string has all unique characters Determine if a string has all the same characters Longest substrings without repeating characters Find words which contains all the vowels Find words which contains most consonants Find words which contains more than 3 vowels Find words which first and last three letters are equals Find words which odd letters are consonants and even letters are vowels or vice_versa Formatting Substring Rep-string Word wrap String case Align columns Literals/String Repeat a string Brace expansion Brace expansion using ranges Reverse a string Phrase reversals Comma quibbling Special characters String concatenation Substring/Top and tail Commatizing numbers Reverse words in a string Suffixation of decimal numbers Long literals, with continuations Numerical and alphabetical suffixes Abbreviations, easy Abbreviations, simple Abbreviations, automatic Song lyrics/poems/Mad Libs/phrases Mad Libs Magic 8-ball 99 Bottles of Beer The Name Game (a song) The Old lady swallowed a fly The Twelve Days of Christmas Tokenize Text between Tokenize a string Word break problem Tokenize a string with escaping Split a character string based on change of character Sequences Show ASCII table De Bruijn sequences Self-referential sequences Generate lower case ASCII alphabet
#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 Text(int index) => index == 32 ? "Sp" : index == 127 ? "Del" : (char)index + ""; } }
http://rosettacode.org/wiki/Sierpinski_triangle
Sierpinski triangle
Task Produce an ASCII representation of a Sierpinski triangle of order   N. Example The Sierpinski triangle of order   4   should look like this: * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * Related tasks Sierpinski triangle/Graphical for graphics images of this pattern. Sierpinski carpet
#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: ########################### # ## ## ## ## ## ## ## ## # ########################### ### ###### ###### ### # # # ## # # ## # # # ### ###### ###### ### ########################### # ## ## ## ## ## ## ## ## # ########################### ######### ######### # ## ## # # ## ## # ######### ######### ### ### ### ### # # # # # # # # ### ### ### ### ######### ######### # ## ## # # ## ## # ######### ######### ########################### # ## ## ## ## ## ## ## ## # ########################### ### ###### ###### ### # # # ## # # ## # # # ### ###### ###### ### ########################### # ## ## ## ## ## ## ## ## # ########################### The use of the   #   character is not rigidly required for ASCII art. The important requirement is the placement of whitespace and non-whitespace characters. Related task   Sierpinski triangle
#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 D=1) D=D DIV 3 UNTIL NOT(D>0) IF D>0 THEN PRINT(#1," ";) ELSE PRINT(#1,"##";) END IF END FOR PRINT(#1,) END FOR  ! PRINT(#1,CHR$(12);) for printer only! CLOSE(1) END PROGRAM  
http://rosettacode.org/wiki/Shoelace_formula_for_polygonal_area
Shoelace formula for polygonal area
Given the n + 1 vertices x[0], y[0] .. x[N], y[N] of a simple polygon described in a clockwise direction, then the polygon's area can be calculated by: abs( (sum(x[0]*y[1] + ... x[n-1]*y[n]) + x[N]*y[0]) - (sum(x[1]*y[0] + ... x[n]*y[n-1]) + x[0]*y[N]) ) / 2 (Where abs returns the absolute value) Task Write a function/method/routine to use the the Shoelace formula to calculate the area of the polygon described by the ordered points: (3,4), (5,11), (12,8), (9,5), and (5,6) Show the answer here, on this page.
#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 Shoelace Formula val xx = pp.map( p => p.x ) val yy = pp.map( p => p.y ) val overlace = xx zip yy.drop(1)++yy.take(1) val underlace = yy zip xx.drop(1)++xx.take(1)   (overlace.map( t => t._1 * t._2 ).sum - underlace.map( t => t._1 * t._2 ).sum).abs / 2.0 } }   // A little test... { val p = Polygon( List( Point(3,4), Point(5,11), Point(12,8), Point(9,5), Point(5,6) ) )   assert( p.area == 30.0 )   println( "Area of " + p + " = " + p.area ) }  
http://rosettacode.org/wiki/Shoelace_formula_for_polygonal_area
Shoelace formula for polygonal area
Given the n + 1 vertices x[0], y[0] .. x[N], y[N] of a simple polygon described in a clockwise direction, then the polygon's area can be calculated by: abs( (sum(x[0]*y[1] + ... x[n-1]*y[n]) + x[N]*y[0]) - (sum(x[1]*y[0] + ... x[n]*y[n-1]) + x[0]*y[N]) ) / 2 (Where abs returns the absolute value) Task Write a function/method/routine to use the the Shoelace formula to calculate the area of the polygon described by the ordered points: (3,4), (5,11), (12,8), (9,5), and (5,6) Show the answer here, on this page.
#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 command argument syntax, or the systems those implementations run on have different styles of shells, it would be good to show multiple examples.
#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 command argument syntax, or the systems those implementations run on have different styles of shells, it would be good to show multiple examples.
#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 command argument syntax, or the systems those implementations run on have different styles of shells, it would be good to show multiple examples.
#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 command argument syntax, or the systems those implementations run on have different styles of shells, it would be good to show multiple examples.
#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, and is to be minimized. If we needed to compute the conjunction   (and): x = a() and b() Then it would be best to not compute the value of   b()   if the value of   a()   is computed as   false,   as the value of   x   can then only ever be   false. Similarly, if we needed to compute the disjunction (or): y = a() or b() Then it would be best to not compute the value of   b()   if the value of   a()   is computed as   true,   as the value of   y   can then only ever be   true. Some languages will stop further computation of boolean equations as soon as the result is known, so-called   short-circuit evaluation   of boolean expressions Task Create two functions named   a   and   b,   that take and return the same boolean value. The functions should also print their name whenever they are called. Calculate and assign the values of the following equations to a variable in such a way that function   b   is only called when necessary: x = a(i) and b(j) y = a(i) or b(j) If the language does not have short-circuit evaluation, this might be achieved with nested     if     statements.
#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( "~p andalso ~p~n", [Boolean1, Boolean2] ), io:fwrite( "=> ~p~n", [a(Boolean1) andalso b(Boolean2)] ), io:fwrite( "~p orelse ~p~n", [Boolean1, Boolean2] ), io:fwrite( "=> ~p~n", [a(Boolean1) orelse b(Boolean2)] ).  
http://rosettacode.org/wiki/Set_puzzle
Set puzzle
Set Puzzles are created with a deck of cards from the Set Game™. The object of the puzzle is to find sets of 3 cards in a rectangle of cards that have been dealt face up. There are 81 cards in a deck. Each card contains a unique variation of the following four features: color, symbol, number and shading. there are three colors:    red, green, purple there are three symbols:    oval, squiggle, diamond there is a number of symbols on the card:    one, two, three there are three shadings:    solid, open, striped Three cards form a set if each feature is either the same on each card, or is different on each card. For instance: all 3 cards are red, all 3 cards have a different symbol, all 3 cards have a different number of symbols, all 3 cards are striped. There are two degrees of difficulty: basic and advanced. The basic mode deals 9 cards, that contain exactly 4 sets; the advanced mode deals 12 cards that contain exactly 6 sets. When creating sets you may use the same card more than once. Task Write code that deals the cards (9 or 12, depending on selected mode) from a shuffled deck in which the total number of sets that could be found is 4 (or 6, respectively); and print the contents of the cards and the sets. For instance: DEALT 9 CARDS: green, one, oval, striped green, one, diamond, open green, one, diamond, striped green, one, diamond, solid purple, one, diamond, open purple, two, squiggle, open purple, three, oval, open red, three, oval, open red, three, diamond, solid CONTAINING 4 SETS: green, one, oval, striped purple, two, squiggle, open red, three, diamond, solid green, one, diamond, open green, one, diamond, striped green, one, diamond, solid green, one, diamond, open purple, two, squiggle, open red, three, oval, open purple, one, diamond, open purple, two, squiggle, open purple, three, oval, open
#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 String;   generic with procedure Do_something(C: Cards; S: Set); procedure Find_Sets(Given: Cards); -- calls Do_Something once for each set it finds.   end Set_Puzzle;
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 standard, FIPS 180-1, defines SHA-1. Find the SHA-1 message digest for a string of octets. You may either call a SHA-1 library, or implement SHA-1 in your language. Both approaches interest Rosetta Code. Warning: SHA-1 has known weaknesses. Theoretical attacks may find a collision after 252 operations, or perhaps fewer. This is much faster than a brute force attack of 280 operations. USgovernment deprecated SHA-1. For production-grade cryptography, users may consider a stronger alternative, such as SHA-256 (from the SHA-2 family) or the upcoming SHA-3.
#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 UTF8Encoding().GetBytes("Rosetta Code"); var output = new SHA1CryptoServiceProvider().ComputeHash(input); Assert.AreEqual( "48-C9-8F-7E-5A-6E-73-6D-79-0A-B7-40-DF-C3-F5-1A-61-AB-E2-B5", BitConverter.ToString(output)); } } }
http://rosettacode.org/wiki/Seven-sided_dice_from_five-sided_dice
Seven-sided dice from five-sided dice
Task (Given an equal-probability generator of one of the integers 1 to 5 as dice5),   create dice7 that generates a pseudo-random integer from 1 to 7 in equal probability using only dice5 as a source of random numbers,   and check the distribution for at least one million calls using the function created in   Simple Random Distribution Checker. Implementation suggestion: dice7 might call dice5 twice, re-call if four of the 25 combinations are given, otherwise split the other 21 combinations into 7 groups of three, and return the group index from the rolls. (Task adapted from an answer here)
#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 Random Distribution Checker. Implementation suggestion: dice7 might call dice5 twice, re-call if four of the 25 combinations are given, otherwise split the other 21 combinations into 7 groups of three, and return the group index from the rolls. (Task adapted from an answer here)
#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 SKIP OD;   m := 1; WHILE d55>0 DO d55 +:= m; m := ABS (BIN d55 AND 2r111); # modulas by 8 # d55 := ABS (BIN d55 SHR 3) # divide by 8 # OD; m );   PROC distcheck = (PROC INT dice, INT count, upb)VOID: ( [upb]INT sum; FOR i TO UPB sum DO sum[i] := 0 OD; FOR i TO count DO sum[dice]+:=1 OD; FOR i TO UPB sum WHILE print(whole(sum[i],0)); i /= UPB sum DO print(", ") OD; print(new line) );   main: ( distcheck(dice5, 1000000, 5); distcheck(dice7, 1000000, 7) )
http://rosettacode.org/wiki/Sexy_primes
Sexy primes
This page uses content from Wikipedia. The original article was at Sexy_prime. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance) In mathematics, sexy primes are prime numbers that differ from each other by six. For example, the numbers 5 and 11 are both sexy primes, because 11 minus 6 is 5. The term "sexy prime" is a pun stemming from the Latin word for six: sex. Sexy prime pairs: Sexy prime pairs are groups of two primes that differ by 6. e.g. (5 11), (7 13), (11 17) See sequences: OEIS:A023201 and OEIS:A046117 Sexy prime triplets: Sexy prime triplets are groups of three primes where each differs from the next by 6. e.g. (5 11 17), (7 13 19), (17 23 29) See sequences: OEIS:A046118, OEIS:A046119 and OEIS:A046120 Sexy prime quadruplets: Sexy prime quadruplets are groups of four primes where each differs from the next by 6. e.g. (5 11 17 23), (11 17 23 29) See sequences: OEIS:A023271, OEIS:A046122, OEIS:A046123 and OEIS:A046124 Sexy prime quintuplets: Sexy prime quintuplets are groups of five primes with a common difference of 6. One of the terms must be divisible by 5, because 5 and 6 are relatively prime. Thus, the only possible sexy prime quintuplet is (5 11 17 23 29) Task For each of pairs, triplets, quadruplets and quintuplets, Find and display the count of each group type of sexy primes less than one million thirty-five (1,000,035). Display at most the last 5, less than one million thirty-five, of each sexy prime group type. Find and display the count of the unsexy primes less than one million thirty-five. Find and display the last 10 unsexy primes less than one million thirty-five. Note that 1000033 SHOULD NOT be counted in the pair count. It is sexy, but not in a pair within the limit. However, it also SHOULD NOT be listed in the unsexy primes since it is sexy.
#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 }   : tuplet ( m n -- seq ) dupd 1 - 6 * + 6 <range> ;   : viable-tuplet? ( seq -- ? ) [ [ prime? ] [ limit < ] bi and ] all? ;   : sexy-tuplets ( n -- seq ) [ primes ] dip '[ [ _ tuplet dup viable-tuplet? [ , ] [ drop ] if ] each ] { } make ;   : ?last5 ( seq -- seq' ) 5 short tail* ;   : last5 ( seq -- str )  ?last5 [ { } like unparse ] map " " join ;   :: tuplet-info ( n -- last5 l5-len num-tup limit tuplet-name ) n sexy-tuplets :> tup tup last5 tup ?last5 length tup length commas limit commas n 2 - tuplet-names nth ;   : show-tuplets ( n -- ) tuplet-info [I Number of sexy prime ${0}s < ${1}: ${2}I] nl [I Last ${0}: ${1}I] nl nl ;   : unsexy-primes ( -- seq ) primes [ { [ 6 + prime? not ] [ 6 - prime? not ] } 1&& ] filter ;   : show-unsexy ( -- ) unsexy-primes dup length commas limit commas [I Number of unsexy primes < ${0}: ${1}I] nl "Last 10: " write 10 short tail* [ pprint bl ] each nl ;   : main ( -- ) 2 5 [a,b] [ show-tuplets ] each show-unsexy ;   MAIN: main
http://rosettacode.org/wiki/Sexy_primes
Sexy primes
This page uses content from Wikipedia. The original article was at Sexy_prime. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance) In mathematics, sexy primes are prime numbers that differ from each other by six. For example, the numbers 5 and 11 are both sexy primes, because 11 minus 6 is 5. The term "sexy prime" is a pun stemming from the Latin word for six: sex. Sexy prime pairs: Sexy prime pairs are groups of two primes that differ by 6. e.g. (5 11), (7 13), (11 17) See sequences: OEIS:A023201 and OEIS:A046117 Sexy prime triplets: Sexy prime triplets are groups of three primes where each differs from the next by 6. e.g. (5 11 17), (7 13 19), (17 23 29) See sequences: OEIS:A046118, OEIS:A046119 and OEIS:A046120 Sexy prime quadruplets: Sexy prime quadruplets are groups of four primes where each differs from the next by 6. e.g. (5 11 17 23), (11 17 23 29) See sequences: OEIS:A023271, OEIS:A046122, OEIS:A046123 and OEIS:A046124 Sexy prime quintuplets: Sexy prime quintuplets are groups of five primes with a common difference of 6. One of the terms must be divisible by 5, because 5 and 6 are relatively prime. Thus, the only possible sexy prime quintuplet is (5 11 17 23 29) Task For each of pairs, triplets, quadruplets and quintuplets, Find and display the count of each group type of sexy primes less than one million thirty-five (1,000,035). Display at most the last 5, less than one million thirty-five, of each sexy prime group type. Find and display the count of the unsexy primes less than one million thirty-five. Find and display the last 10 unsexy primes less than one million thirty-five. Note that 1000033 SHOULD NOT be counted in the pair count. It is sexy, but not in a pair within the limit. However, it also SHOULD NOT be listed in the unsexy primes since it is sexy.
#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 If ValorEval Mod d = 0 Then Return False Else d += 4 Wend Return True End Function   #define maxi 1000035 Dim As Integer CU = 0, C2 = 0, C3 = 0, C4 = 0, C5 = 0, N, I, P = 0 Dim As Integer Unsexy(10), Pairs(5), Trips(5), Quads(5), Quins(5)   For N = maxi To 2 Step -1 If isPrime(N) Then P += 1 If Not isPrime(N-6) And Not isPrime(N+6) Then If CU < 10 Then Unsexy(CU) = N CU += 1 End If If isPrime(N-6) Then If C2 < 5 Then Pairs(C2) = N C2 += 1 If isPrime(N-12) Then If C3 < 5 Then Trips(C3) = N C3 += 1 If isPrime(N-18) Then If C4 < 5 Then Quads(C4) = N C4 += 1 If isPrime(N-24) Then If C5 < 5 Then Quins(C5) = N C5 += 1 End If End If End If End If End If Next N   Print P; " primes less than"; maxi   Print Chr(10); C2; " pairs ending with:" For I = 4 To 0 Step -1 Print " [" & Pairs(I)-6 & ", "& Pairs(I) & "]" Next I   Print Chr(10); C3; " triplets ending with:" For I = 4 To 0 Step -1 Print " [" & Trips(I)-12 & ", "& Trips(I)-6 & ", "& Trips(I) & "]" Next I   Print Chr(10); C4; " quadruplets ending with:" For I = 4 To 0 Step -1 Print " [" & Quads(I)-18 & ", "& Quads(I)-12 & ", "& Quads(I)-6 & ", "& Quads(I) & "]" Next I   Print Chr(10); C5; " quintuplet(s) ending with:" I = Iif(C5 > 5, 5, C5) For I = I-1 To 0 Step -1 Print " [" & Quins(I)-24 & ", "& Quins(I)-18 & ", "& Quins(I)-12 & ", "& Quins(I)-6 & ", "& Quins(I) & "]" Next I   Print Chr(10); CU; " unsexy primes ending with:" For I = 9 To 0 Step -1 Print Unsexy(I); ","; Next I Print Chr(8); " " Sleep
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 a nibble gets changed: n = 2; Width e = 4: Input b: 1000 Result: 1110 Input b: 0100 Result: 0111 Input b: 0010 Result: 0011 Input b: 0000 Result: 0000 Set of examples with the same input with set bits of varying distance apart: n = 0; Width e = 66: Input b: 010000000000100000000010000000010000000100000010000010000100010010 Result: 010000000000100000000010000000010000000100000010000010000100010010 n = 1; Width e = 66: Input b: 010000000000100000000010000000010000000100000010000010000100010010 Result: 011000000000110000000011000000011000000110000011000011000110011011 n = 2; Width e = 66: Input b: 010000000000100000000010000000010000000100000010000010000100010010 Result: 011100000000111000000011100000011100000111000011100011100111011111 n = 3; Width e = 66: Input b: 010000000000100000000010000000010000000100000010000010000100010010 Result: 011110000000111100000011110000011110000111100011110011110111111111 Task: Implement a routine to perform the setting of right-adjacent bits on representations of bits that will scale over the given range of input width e. Use it to show, here, the results for the input examples above. Print the output aligned in a way that allows easy checking by eye of the binary input vs output.
#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() { let n: usize = $n; let e: usize = $e; let b_original: $g = $b; let mut b = b_original.clone(); set_right_adjacent_bits(&mut b, n); println!("n = {n}; e = {e}:"); println!(" b = {:0>e$b}", b_original); println!(" output = {:0>e$b}", b); assert_eq!(b, $c); } }; }   test!(test_a1, 2, 4, u8, 0b1000, 0b1110); test!(test_a2, 2, 4, u8, 0b0100, 0b0111); test!(test_a3, 2, 4, u8, 0b0010, 0b0011); test!(test_a4, 2, 4, u8, 0b0000, 0b0000); test!( test_b1, 0, 66, u128, 0b010000000000100000000010000000010000000100000010000010000100010010, 0b010000000000100000000010000000010000000100000010000010000100010010, ); test!( test_b2, 1, 66, u128, 0b010000000000100000000010000000010000000100000010000010000100010010, 0b011000000000110000000011000000011000000110000011000011000110011011, ); test!( test_b3, 2, 66, u128, 0b010000000000100000000010000000010000000100000010000010000100010010, 0b011100000000111000000011100000011100000111000011100011100111011111, ); test!( test_b4, 3, 66, u128, 0b010000000000100000000010000000010000000100000010000010000100010010, 0b011110000000111100000011110000011110000111100011110011110111111111, );
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 a nibble gets changed: n = 2; Width e = 4: Input b: 1000 Result: 1110 Input b: 0100 Result: 0111 Input b: 0010 Result: 0011 Input b: 0000 Result: 0000 Set of examples with the same input with set bits of varying distance apart: n = 0; Width e = 66: Input b: 010000000000100000000010000000010000000100000010000010000100010010 Result: 010000000000100000000010000000010000000100000010000010000100010010 n = 1; Width e = 66: Input b: 010000000000100000000010000000010000000100000010000010000100010010 Result: 011000000000110000000011000000011000000110000011000011000110011011 n = 2; Width e = 66: Input b: 010000000000100000000010000000010000000100000010000010000100010010 Result: 011100000000111000000011100000011100000111000011100011100111011111 n = 3; Width e = 66: Input b: 010000000000100000000010000000010000000100000010000010000100010010 Result: 011110000000111100000011110000011110000111100011110011110111111111 Task: Implement a routine to perform the setting of right-adjacent bits on representations of bits that will scale over the given range of input width e. Use it to show, here, the results for the input examples above. Print the output aligned in a way that allows easy checking by eye of the binary input vs output.
#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 } } } return bits2 }   var b = "010000000000100000000010000000010000000100000010000010000100010010" var tests = [["1000", 2], ["0100", 2], ["0010", 2], ["0000", 2], [b, 0], [b, 1], [b, 2], [b, 3]] for (test in tests) { var bits = test[0] var e = bits.count var n = test[1] System.print("n = %(n); Width e = %(e):") System.print(" Input b: %(bits)") bits = bits.map { |c| c.bytes[0] - 48 }.toList bits = setRightBits.call(bits, e, n) System.print(" Result: %(bits.join())\n") }
http://rosettacode.org/wiki/SHA-256_Merkle_tree
SHA-256 Merkle tree
As described in its documentation, Amazon S3 Glacier requires that all uploaded files come with a checksum computed as a Merkle Tree using SHA-256. Specifically, the SHA-256 hash is computed for each 1MiB block of the file. And then, starting from the beginning of the file, the raw hashes of consecutive blocks are paired up and concatenated together, and a new hash is computed from each concatenation. Then these are paired up and concatenated and hashed, and the process continues until there is only one hash left, which is the final checksum. The hexadecimal representation of this checksum is the value that must be included with the AWS API call to upload the object (or complete a multipart upload). Implement this algorithm in your language; you can use the code from the SHA-256 task for the actual hash computations. For better manageability and portability, build the tree using a smaller block size of only 1024 bytes, and demonstrate it on the RosettaCode title image with that block size. The final result should be the hexadecimal digest value a4f902cf9d51fe51eda156a6792e1445dff65edf3a217a1f3334cc9cf1495c2c.
#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: var newHashes: seq[MDigest[256]] for i in countup(0, hashes.high, 2): if i < hashes.high: ctx.init() ctx.update(hashes[i].data) ctx.update(hashes[i + 1].data) newHashes.add ctx.finish() ctx.clear() else: newHashes.add hashes[i] hashes= newHashes   echo hashes[0]
http://rosettacode.org/wiki/SHA-256_Merkle_tree
SHA-256 Merkle tree
As described in its documentation, Amazon S3 Glacier requires that all uploaded files come with a checksum computed as a Merkle Tree using SHA-256. Specifically, the SHA-256 hash is computed for each 1MiB block of the file. And then, starting from the beginning of the file, the raw hashes of consecutive blocks are paired up and concatenated together, and a new hash is computed from each concatenation. Then these are paired up and concatenated and hashed, and the process continues until there is only one hash left, which is the final checksum. The hexadecimal representation of this checksum is the value that must be included with the AWS API call to upload the object (or complete a multipart upload). Implement this algorithm in your language; you can use the code from the SHA-256 task for the actual hash computations. For better manageability and portability, build the tree using a smaller block size of only 1024 bytes, and demonstrate it on the RosettaCode title image with that block size. The final result should be the hexadecimal digest value a4f902cf9d51fe51eda156a6792e1445dff65edf3a217a1f3334cc9cf1495c2c.
#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 TmyByte = array of byte; TmyHashes = array of TmyByte; {$ENDIF}   function SHA256(const Input: TmyByte; Len: Integer = -1): TmyByte; var Hasher: TDCP_sha256; l: Integer; begin if Len < 0 then l := length(Input) else l := Len; Hasher := TDCP_sha256.Create(nil); try Hasher.Init; Hasher.Update(Input[0], l); SetLength(Result, Hasher.HashSize div 8); Hasher.final(Result[0]); finally Hasher.Free; end; end;   function Merkle_tree(FileName: TFileName): string; const blockSize = 1024; var f: TMemoryStream; hashes, hashes2: TmyHashes; bytesRead: Cardinal; buffer: TmyByte; i, index: Integer; b: byte; begin Result := ''; if not FileExists(FileName) then exit;   SetLength(buffer, blockSize); FillChar(buffer[0], blockSize, #0); f := TMemoryStream.Create; f.LoadFromFile(FileName); index := 0; repeat //freepascal needs buffer[0] instead buffer bytesRead := f.Read(buffer[0], blockSize); if bytesRead= 0 then BREAK; Insert(SHA256(buffer, bytesRead), hashes, index); inc(index); until bytesRead<blockSize; f.Free;   SetLength(buffer, 64); while Length(hashes) > 1 do begin //first clear old hashes2 setlength(hashes2,0); index := 0; i := 0; while i < length(hashes) do begin if i < length(hashes) - 1 then begin buffer := copy(hashes[i], 0, length(hashes[i])); buffer := concat(buffer,copy(hashes[i + 1], 0, length(hashes[i]))); Insert(SHA256(buffer), hashes2, index); inc(index); end else begin Insert(hashes[i], hashes2, index); inc(index); end; inc(i, 2); end; hashes := hashes2; end;   Result := ''; for b in hashes[0] do begin Result := Result + b.ToHexString(2); end; end;   begin writeln(Merkle_tree('title.png')); {$IFDEF WINDOWS} readln; {$ENDIF} end.
http://rosettacode.org/wiki/Show_ASCII_table
Show ASCII table
Task Show  the ASCII character set  from values   32   to   127   (decimal)   in a table format. Other tasks related to string operations: Metrics Array length String length Copy a string Empty string  (assignment) Counting Word frequency Letter frequency Jewels and stones I before E except after C Bioinformatics/base count Count occurrences of a substring Count how many vowels and consonants occur in a string Remove/replace XXXX redacted Conjugate a Latin verb Remove vowels from a string String interpolation (included) Strip block comments Strip comments from a string Strip a set of characters from a string Strip whitespace from a string -- top and tail Strip control codes and extended characters from a string Anagrams/Derangements/shuffling Word wheel ABC problem Sattolo cycle Knuth shuffle Ordered words Superpermutation minimisation Textonyms (using a phone text pad) Anagrams Anagrams/Deranged anagrams Permutations/Derangements Find/Search/Determine ABC words Odd words Word ladder Semordnilap Word search Wordiff  (game) String matching Tea cup rim text Alternade words Changeable words State name puzzle String comparison Unique characters Unique characters in each string Extract file extension Levenshtein distance Palindrome detection Common list elements Longest common suffix Longest common prefix Compare a list of strings Longest common substring Find common directory path Words from neighbour ones Change e letters to i in words Non-continuous subsequences Longest common subsequence Longest palindromic substrings Longest increasing subsequence Words containing "the" substring Sum of the digits of n is substring of n Determine if a string is numeric Determine if a string is collapsible Determine if a string is squeezable Determine if a string has all unique characters Determine if a string has all the same characters Longest substrings without repeating characters Find words which contains all the vowels Find words which contains most consonants Find words which contains more than 3 vowels Find words which first and last three letters are equals Find words which odd letters are consonants and even letters are vowels or vice_versa Formatting Substring Rep-string Word wrap String case Align columns Literals/String Repeat a string Brace expansion Brace expansion using ranges Reverse a string Phrase reversals Comma quibbling Special characters String concatenation Substring/Top and tail Commatizing numbers Reverse words in a string Suffixation of decimal numbers Long literals, with continuations Numerical and alphabetical suffixes Abbreviations, easy Abbreviations, simple Abbreviations, automatic Song lyrics/poems/Mad Libs/phrases Mad Libs Magic 8-ball 99 Bottles of Beer The Name Game (a song) The Old lady swallowed a fly The Twelve Days of Christmas Tokenize Text between Tokenize a string Word break problem Tokenize a string with escaping Split a character string based on change of character Sequences Show ASCII table De Bruijn sequences Self-referential sequences Generate lower case ASCII alphabet
#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 = $case(i,32:"Spc",127:"Del",:$char(i)) write ?x,$justify(i,3)_": "_wrtchr }   quit
http://rosettacode.org/wiki/Sierpinski_triangle
Sierpinski triangle
Task Produce an ASCII representation of a Sierpinski triangle of order   N. Example The Sierpinski triangle of order   4   should look like this: * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * Related tasks Sierpinski triangle/Graphical for graphics images of this pattern. Sierpinski carpet
#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) .reduce(function (lstRows) { var lstPrevRow = lstRows.slice(-1)[0];   // Each new row is a function of the previous row return lstRows.concat([zipWith(function (left, right) { // The composition ( asciiBinary . mod 2 . add ) // reduces to a rule from 2 parent characters // to a single child character   // Rule 90 also reduces to the same XOR // relationship between left and right neighbours   return left === right ? " " : "▲"; }, [' '].concat(lstPrevRow), lstPrevRow.concat(' '))]); }, [ ["▲"] // Tip of triangle ]); }(Math.pow(2, intOrder))   // As centred lines, from bottom (0 indent) up (indent below + 1) .reduceRight(function (sofar, lstLine) { return { triangle: sofar.indent + lstLine.join(" ") + "\n" + sofar.triangle, indent: sofar.indent + " " }; }, { triangle: "", indent: "" }).triangle; };   var zipWith = function (f, xs, ys) { return xs.length === ys.length ? xs .map(function (x, i) { return f(x, ys[i]); }) : undefined; }, range = function (m, n) { return Array.apply(null, Array(n - m + 1)) .map(function (x, i) { return m + i; }); };   // TEST return sierpinski(order);   })(4);  
http://rosettacode.org/wiki/Sierpinski_carpet
Sierpinski carpet
Task Produce a graphical or ASCII-art representation of a Sierpinski carpet of order   N. For example, the Sierpinski carpet of order   3   should look like this: ########################### # ## ## ## ## ## ## ## ## # ########################### ### ###### ###### ### # # # ## # # ## # # # ### ###### ###### ### ########################### # ## ## ## ## ## ## ## ## # ########################### ######### ######### # ## ## # # ## ## # ######### ######### ### ### ### ### # # # # # # # # ### ### ### ### ######### ######### # ## ## # # ## ## # ######### ######### ########################### # ## ## ## ## ## ## ## ## # ########################### ### ###### ###### ### # # # ## # # ## # # # ### ###### ###### ### ########################### # ## ## ## ## ## ## ## ## # ########################### The use of the   #   character is not rigidly required for ASCII art. The important requirement is the placement of whitespace and non-whitespace characters. Related task   Sierpinski triangle
#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 InCarpet(i,j) = 1 then puts(1,"#") else puts(1," ") end if end for puts(1,'\n') end for  
http://rosettacode.org/wiki/Shoelace_formula_for_polygonal_area
Shoelace formula for polygonal area
Given the n + 1 vertices x[0], y[0] .. x[N], y[N] of a simple polygon described in a clockwise direction, then the polygon's area can be calculated by: abs( (sum(x[0]*y[1] + ... x[n-1]*y[n]) + x[N]*y[0]) - (sum(x[1]*y[0] + ... x[n]*y[n-1]) + x[0]*y[N]) ) / 2 (Where abs returns the absolute value) Task Write a function/method/routine to use the the Shoelace formula to calculate the area of the polygon described by the ordered points: (3,4), (5,11), (12,8), (9,5), and (5,6) Show the answer here, on this page.
#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 }) let overlace = zip(xx, yy.dropFirst() + yy.prefix(1)).map({ $0.0 * $0.1 }).reduce(0, +) let underlace = zip(yy, xx.dropFirst() + xx.prefix(1)).map({ $0.0 * $0.1 }).reduce(0, +)   return abs(overlace - underlace) / 2 }   init(points: [Point]) { self.points = points }   init(points: [(Double, Double)]) { self.init(points: points.map({ Point(x: $0.0, y: $0.1) })) } }   let poly = Polygon(points: [ (3,4), (5,11), (12,8), (9,5), (5,6) ])   print("\(poly) area = \(poly.area)")
http://rosettacode.org/wiki/Shoelace_formula_for_polygonal_area
Shoelace formula for polygonal area
Given the n + 1 vertices x[0], y[0] .. x[N], y[N] of a simple polygon described in a clockwise direction, then the polygon's area can be calculated by: abs( (sum(x[0]*y[1] + ... x[n-1]*y[n]) + x[N]*y[0]) - (sum(x[1]*y[0] + ... x[n]*y[n-1]) + x[0]*y[N]) ) / 2 (Where abs returns the absolute value) Task Write a function/method/routine to use the the Shoelace formula to calculate the area of the polygon described by the ordered points: (3,4), (5,11), (12,8), (9,5), and (5,6) Show the answer here, on this page.
#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 a function/method/routine to use the the Shoelace formula to calculate the area of the polygon described by the ordered points: (3,4), (5,11), (12,8), (9,5), and (5,6) Show the answer here, on this page.
#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) / 2 End Function   Public Sub polygonal_area() Dim task() As Variant task = [{3,4;5,11;12,8;9,5;5,6}] Dim tcol As New Collection For i = 1 To UBound(task) tcol.Add Array(task(i, u), task(i, v)) Next i Debug.Print shoelace(tcol) End Sub
http://rosettacode.org/wiki/Shell_one-liner
Shell one-liner
Task Show how to specify and execute a short program in the language from a command shell, where the input to the command shell is only one line in length. Avoid depending on the particular shell or operating system used as much as is reasonable; if the language has notable implementations which have different command argument syntax, or the systems those implementations run on have different styles of shells, it would be good to show multiple examples.
#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 command argument syntax, or the systems those implementations run on have different styles of shells, it would be good to show multiple examples.
#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 command argument syntax, or the systems those implementations run on have different styles of shells, it would be good to show multiple examples.
#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, and is to be minimized. If we needed to compute the conjunction   (and): x = a() and b() Then it would be best to not compute the value of   b()   if the value of   a()   is computed as   false,   as the value of   x   can then only ever be   false. Similarly, if we needed to compute the disjunction (or): y = a() or b() Then it would be best to not compute the value of   b()   if the value of   a()   is computed as   true,   as the value of   y   can then only ever be   true. Some languages will stop further computation of boolean equations as soon as the result is known, so-called   short-circuit evaluation   of boolean expressions Task Create two functions named   a   and   b,   that take and return the same boolean value. The functions should also print their name whenever they are called. Calculate and assign the values of the following equations to a variable in such a way that function   b   is only called when necessary: x = a(i) and b(j) y = a(i) or b(j) If the language does not have short-circuit evaluation, this might be achieved with nested     if     statements.
#F.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 three colors:    red, green, purple there are three symbols:    oval, squiggle, diamond there is a number of symbols on the card:    one, two, three there are three shadings:    solid, open, striped Three cards form a set if each feature is either the same on each card, or is different on each card. For instance: all 3 cards are red, all 3 cards have a different symbol, all 3 cards have a different number of symbols, all 3 cards are striped. There are two degrees of difficulty: basic and advanced. The basic mode deals 9 cards, that contain exactly 4 sets; the advanced mode deals 12 cards that contain exactly 6 sets. When creating sets you may use the same card more than once. Task Write code that deals the cards (9 or 12, depending on selected mode) from a shuffled deck in which the total number of sets that could be found is 4 (or 6, respectively); and print the contents of the cards and the sets. For instance: DEALT 9 CARDS: green, one, oval, striped green, one, diamond, open green, one, diamond, striped green, one, diamond, solid purple, one, diamond, open purple, two, squiggle, open purple, three, oval, open red, three, oval, open red, three, diamond, solid CONTAINING 4 SETS: green, one, oval, striped purple, two, squiggle, open red, three, diamond, solid green, one, diamond, open green, one, diamond, striped green, one, diamond, solid green, one, diamond, open purple, two, squiggle, open red, three, oval, open purple, one, diamond, open purple, two, squiggle, open purple, three, oval, open
#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) { Color1:="red",Color2:="green",Color4:="purple" ,Symbl1:="oval",Symbl2:="squiggle",Symbl4:="diamond" ,Numbr1:="one",Numbr2:="two",Numbr4:="three" ,Shape1:="solid",Shape2:="open",Shape4:="striped" Loop, Parse, hand, `, { StringSplit, i, A_LoopField s .= "`t" Color%i1% "`t" Symbl%i2% "`t" Numbr%i3% "`t" Shape%i4% "`n" } Return s }   ; Get all unique valid sets of three cards in a hand. allValidSets(n, m, deck) { While j != m { j := 0 ,hand := draw(n, deck) ,s := "Dealt " n " cards:`n" . prettyhand(hand) StringSplit, set, hand, `, comb := comb(n,3) Loop, Parse, comb, `n { StringSplit, i, A_LoopField, %A_Space% If isValidSet(set%i1%, set%i2%, set%i3%) s .= "`nSet " ++j ":`n" . prettyhand(set%i1% "," set%i2% "," set%i3%) } } Return s }   ; Convert n to arbitrary base using recursion toBase(n,b) { ; n >= 0, 1 < b < StrLen(t), t = digits Static t := "0123456789ABCDEF" Return (n < b ? "" : ToBase(n//b,b)) . SubStr(t,mod(n,b)+1,1) }   ; Knuth shuffle from http://rosettacode.org/wiki/Knuth_Shuffle#AutoHotkey shuffle(list) { ; shuffle comma separated list, converted to array StringSplit a, list, `, ; make array (length = a0) Loop % a0-1 { Random i, A_Index, a0 ; swap item 1,2... with a random item to the right of it t := a%i%, a%i% := a%A_Index%, a%A_Index% := t } Loop % a0 ; construct string from sorted array s .= "," . a%A_Index% Return SubStr(s,2) ; drop leading comma }   ; Randomly pick a hand of cards from the deck draw(n, deck) { Loop, % n { Random, i, 1, 81 cards := deck Loop, Parse, cards, `, (A_Index = i) ? (hand .= A_LoopField ",") : (cards .= A_LoopField ",") deck := cards } Return SubStr(hand, 1, -1) }   ; Test if a particular group of three cards is a valid set isValidSet(a, b, c) { StringSplit, a, a StringSplit, b, b StringSplit, c, c Return !((a1|b1|c1 ~= "[3,5,6]") + (a2|b2|c2 ~= "[3,5,6]") + (a3|b3|c3 ~= "[3,5,6]") + (a4|b4|c4 ~= "[3,5,6]")) }   ; Get all combinations, from http://rosettacode.org/wiki/Combinations#AutoHotkey comb(n,t) { ; Generate all n choose t combinations of 1..n, lexicographically IfLess n,%t%, Return Loop %t% c%A_Index% := A_Index i := t+1, c%i% := n+1   Loop { Loop %t% i := t+1-A_Index, c .= c%i% " " c .= "`n" ; combinations in new lines j := 1, i := 2 Loop If (c%j%+1 = c%i%) c%j% := j, ++j, ++i Else Break If (j > t) Return c c%j% += 1 } }
http://rosettacode.org/wiki/SHA-256
SHA-256
SHA-256 is the recommended stronger alternative to SHA-1. See FIPS PUB 180-4 for implementation details. Either by using a dedicated library or implementing the algorithm in your language, show that the SHA-256 digest of the string "Rosetta code" is: 764faf5c61ac315f1497f9dfa542713965b785e5cc2f707d6468d7d1124cdfcf
#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 "CryptAcquireContext", ^hcont%, 0, \ \ "Microsoft Enhanced RSA and AES Cryptographic Provider", \ \ PROV_RSA_AES, CRYPT_NEWKEYSET SYS "CryptAcquireContext", ^hprov%, 0, 0, PROV_RSA_AES, 0 SYS "CryptCreateHash", hprov%, CALG_SHA_256, 0, 0, ^hhash% SYS "CryptHashData", hhash%, message$, LEN(message$), 0 SYS "CryptGetHashParam", hhash%, HP_HASHVAL, buffer%, ^buflen%, 0 SYS "CryptDestroyHash", hhash% SYS "CryptReleaseContext", hprov% SYS "CryptReleaseContext", hcont% FOR i% = 0 TO buflen%-1 hash$ += RIGHT$("0" + STR$~buffer%?i%, 2) NEXT = hash$
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 standard, FIPS 180-1, defines SHA-1. Find the SHA-1 message digest for a string of octets. You may either call a SHA-1 library, or implement SHA-1 in your language. Both approaches interest Rosetta Code. Warning: SHA-1 has known weaknesses. Theoretical attacks may find a collision after 252 operations, or perhaps fewer. This is much faster than a brute force attack of 280 operations. USgovernment deprecated SHA-1. For production-grade cryptography, users may consider a stronger alternative, such as SHA-256 (from the SHA-2 family) or the upcoming SHA-3.
#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 << myphrase ; outstr.flush( ) ; //to pass everything to the digest engine const DigestEngine::Digest& digest = sha1.digest( ) ; std::cout << myphrase << " as a sha1 digest :" << DigestEngine::digestToHex( digest ) << " !" << std::endl ; return 0 ; }
http://rosettacode.org/wiki/Seven-sided_dice_from_five-sided_dice
Seven-sided dice from five-sided dice
Task (Given an equal-probability generator of one of the integers 1 to 5 as dice5),   create dice7 that generates a pseudo-random integer from 1 to 7 in equal probability using only dice5 as a source of random numbers,   and check the distribution for at least one million calls using the function created in   Simple Random Distribution Checker. Implementation suggestion: dice7 might call dice5 twice, re-call if four of the 25 combinations are given, otherwise split the other 21 combinations into 7 groups of three, and return the group index from the rolls. (Task adapted from an answer here)
#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 Random Distribution Checker. Implementation suggestion: dice7 might call dice5 twice, re-call if four of the 25 combinations are given, otherwise split the other 21 combinations into 7 groups of three, and return the group index from the rolls. (Task adapted from an answer here)
#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 END   DEF FNdice7 LOCAL x% : x% = FNdice5 + 5*FNdice5 IF x%>26 THEN = FNdice7 ELSE = (x%+1) MOD 7 + 1   DEF FNdice5 = RND(5)   DEF FNdistcheck(RETURN func%, repet%, delta) LOCAL i%, m%, r%, s%, bins%() DIM bins%(MAXRND) FOR i% = 1 TO repet% r% = FN(^func%) bins%(r%) += 1 IF r%>m% m% = r% NEXT FOR i% = 1 TO m% IF bins%(i%)/(repet%/m%) > 1+delta s% += 1 IF bins%(i%)/(repet%/m%) < 1-delta s% += 1 NEXT = 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 other by six. For example, the numbers 5 and 11 are both sexy primes, because 11 minus 6 is 5. The term "sexy prime" is a pun stemming from the Latin word for six: sex. Sexy prime pairs: Sexy prime pairs are groups of two primes that differ by 6. e.g. (5 11), (7 13), (11 17) See sequences: OEIS:A023201 and OEIS:A046117 Sexy prime triplets: Sexy prime triplets are groups of three primes where each differs from the next by 6. e.g. (5 11 17), (7 13 19), (17 23 29) See sequences: OEIS:A046118, OEIS:A046119 and OEIS:A046120 Sexy prime quadruplets: Sexy prime quadruplets are groups of four primes where each differs from the next by 6. e.g. (5 11 17 23), (11 17 23 29) See sequences: OEIS:A023271, OEIS:A046122, OEIS:A046123 and OEIS:A046124 Sexy prime quintuplets: Sexy prime quintuplets are groups of five primes with a common difference of 6. One of the terms must be divisible by 5, because 5 and 6 are relatively prime. Thus, the only possible sexy prime quintuplet is (5 11 17 23 29) Task For each of pairs, triplets, quadruplets and quintuplets, Find and display the count of each group type of sexy primes less than one million thirty-five (1,000,035). Display at most the last 5, less than one million thirty-five, of each sexy prime group type. Find and display the count of the unsexy primes less than one million thirty-five. Find and display the last 10 unsexy primes less than one million thirty-five. Note that 1000033 SHOULD NOT be counted in the pair count. It is sexy, but not in a pair within the limit. However, it also SHOULD NOT be listed in the unsexy primes since it is sexy.
#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 { p2 := p * p if p2 >= limit { break } for i := p2; i < limit; i += 2 * p { c[i] = true } for { p += 2 if !c[p] { break } } } return c }   func commatize(n int) string { s := fmt.Sprintf("%d", n) if n < 0 { s = s[1:] } le := len(s) for i := le - 3; i >= 1; i -= 3 { s = s[0:i] + "," + s[i:] } if n >= 0 { return s } return "-" + s }   func printHelper(cat string, le, lim, max int) (int, int, string) { cle, clim := commatize(le), commatize(lim) if cat != "unsexy primes" { cat = "sexy prime " + cat } fmt.Printf("Number of %s less than %s = %s\n", cat, clim, cle) last := max if le < last { last = le } verb := "are" if last == 1 { verb = "is" } return le, last, verb }   func main() { lim := 1000035 sv := sieve(lim - 1) var pairs [][2]int var trips [][3]int var quads [][4]int var quins [][5]int var unsexy = []int{2, 3} for i := 3; i < lim; i += 2 { if i > 5 && i < lim-6 && !sv[i] && sv[i-6] && sv[i+6] { unsexy = append(unsexy, i) continue } if i < lim-6 && !sv[i] && !sv[i+6] { pair := [2]int{i, i + 6} pairs = append(pairs, pair) } else { continue } if i < lim-12 && !sv[i+12] { trip := [3]int{i, i + 6, i + 12} trips = append(trips, trip) } else { continue } if i < lim-18 && !sv[i+18] { quad := [4]int{i, i + 6, i + 12, i + 18} quads = append(quads, quad) } else { continue } if i < lim-24 && !sv[i+24] { quin := [5]int{i, i + 6, i + 12, i + 18, i + 24} quins = append(quins, quin) } } le, n, verb := printHelper("pairs", len(pairs), lim, 5) fmt.Printf("The last %d %s:\n  %v\n\n", n, verb, pairs[le-n:])   le, n, verb = printHelper("triplets", len(trips), lim, 5) fmt.Printf("The last %d %s:\n  %v\n\n", n, verb, trips[le-n:])   le, n, verb = printHelper("quadruplets", len(quads), lim, 5) fmt.Printf("The last %d %s:\n  %v\n\n", n, verb, quads[le-n:])   le, n, verb = printHelper("quintuplets", len(quins), lim, 5) fmt.Printf("The last %d %s:\n  %v\n\n", n, verb, quins[le-n:])   le, n, verb = printHelper("unsexy primes", len(unsexy), lim, 10) fmt.Printf("The last %d %s:\n  %v\n\n", n, verb, unsexy[le-n:]) }
http://rosettacode.org/wiki/SHA-256_Merkle_tree
SHA-256 Merkle tree
As described in its documentation, Amazon S3 Glacier requires that all uploaded files come with a checksum computed as a Merkle Tree using SHA-256. Specifically, the SHA-256 hash is computed for each 1MiB block of the file. And then, starting from the beginning of the file, the raw hashes of consecutive blocks are paired up and concatenated together, and a new hash is computed from each concatenation. Then these are paired up and concatenated and hashed, and the process continues until there is only one hash left, which is the final checksum. The hexadecimal representation of this checksum is the value that must be included with the AWS API call to upload the object (or complete a multipart upload). Implement this algorithm in your language; you can use the code from the SHA-256 task for the actual hash computations. For better manageability and portability, build the tree using a smaller block size of only 1024 bytes, and demonstrate it on the RosettaCode title image with that block size. The final result should be the hexadecimal digest value a4f902cf9d51fe51eda156a6792e1445dff65edf3a217a1f3334cc9cf1495c2c.
#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 ( @_ = splice @clone, 0, 2 ) { push @blocks, scalar @_ == 1 ? $_[0] : sha256 $_[0].$_[1] } }   print unpack ( 'H*', $blocks[0] ) , "\n";
http://rosettacode.org/wiki/Show_ASCII_table
Show ASCII table
Task Show  the ASCII character set  from values   32   to   127   (decimal)   in a table format. Other tasks related to string operations: Metrics Array length String length Copy a string Empty string  (assignment) Counting Word frequency Letter frequency Jewels and stones I before E except after C Bioinformatics/base count Count occurrences of a substring Count how many vowels and consonants occur in a string Remove/replace XXXX redacted Conjugate a Latin verb Remove vowels from a string String interpolation (included) Strip block comments Strip comments from a string Strip a set of characters from a string Strip whitespace from a string -- top and tail Strip control codes and extended characters from a string Anagrams/Derangements/shuffling Word wheel ABC problem Sattolo cycle Knuth shuffle Ordered words Superpermutation minimisation Textonyms (using a phone text pad) Anagrams Anagrams/Deranged anagrams Permutations/Derangements Find/Search/Determine ABC words Odd words Word ladder Semordnilap Word search Wordiff  (game) String matching Tea cup rim text Alternade words Changeable words State name puzzle String comparison Unique characters Unique characters in each string Extract file extension Levenshtein distance Palindrome detection Common list elements Longest common suffix Longest common prefix Compare a list of strings Longest common substring Find common directory path Words from neighbour ones Change e letters to i in words Non-continuous subsequences Longest common subsequence Longest palindromic substrings Longest increasing subsequence Words containing "the" substring Sum of the digits of n is substring of n Determine if a string is numeric Determine if a string is collapsible Determine if a string is squeezable Determine if a string has all unique characters Determine if a string has all the same characters Longest substrings without repeating characters Find words which contains all the vowels Find words which contains most consonants Find words which contains more than 3 vowels Find words which first and last three letters are equals Find words which odd letters are consonants and even letters are vowels or vice_versa Formatting Substring Rep-string Word wrap String case Align columns Literals/String Repeat a string Brace expansion Brace expansion using ranges Reverse a string Phrase reversals Comma quibbling Special characters String concatenation Substring/Top and tail Commatizing numbers Reverse words in a string Suffixation of decimal numbers Long literals, with continuations Numerical and alphabetical suffixes Abbreviations, easy Abbreviations, simple Abbreviations, automatic Song lyrics/poems/Mad Libs/phrases Mad Libs Magic 8-ball 99 Bottles of Beer The Name Game (a song) The Old lady swallowed a fly The Twelve Days of Christmas Tokenize Text between Tokenize a string Word break problem Tokenize a string with escaping Split a character string based on change of character Sequences Show ASCII table De Bruijn sequences Self-referential sequences Generate lower case ASCII alphabet
#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] (clojure.string/join " " (map #(cell (code r %)) (range n-cols))))] (->> (for [r (range n-rows)] (row-str r)) (clojure.string/join "\n"))))   (defn pr-ascii-table [n-cols st-code end-code] (println (ascii-table n-cols st-code end-code)))  
http://rosettacode.org/wiki/Sierpinski_triangle
Sierpinski triangle
Task Produce an ASCII representation of a Sierpinski triangle of order   N. Example The Sierpinski triangle of order   4   should look like this: * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * Related tasks Sierpinski triangle/Graphical for graphics images of this pattern. Sierpinski carpet
#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}; .ans += ($c * .power) | .power *= 2 ) | .ans;   if any(.==0) then 0 else map([stream]) | (map(length) | min) as $min | map( .[:$min] ) | elementwise(min) | toi end;
http://rosettacode.org/wiki/Sierpinski_carpet
Sierpinski carpet
Task Produce a graphical or ASCII-art representation of a Sierpinski carpet of order   N. For example, the Sierpinski carpet of order   3   should look like this: ########################### # ## ## ## ## ## ## ## ## # ########################### ### ###### ###### ### # # # ## # # ## # # # ### ###### ###### ### ########################### # ## ## ## ## ## ## ## ## # ########################### ######### ######### # ## ## # # ## ## # ######### ######### ### ### ### ### # # # # # # # # ### ### ### ### ######### ######### # ## ## # # ## ## # ######### ######### ########################### # ## ## ## ## ## ## ## ## # ########################### ### ###### ###### ### # # # ## # # ## # # # ### ###### ###### ### ########################### # ## ## ## ## ## ## ## ## # ########################### The use of the   #   character is not rigidly required for ASCII art. The important requirement is the placement of whitespace and non-whitespace characters. Related task   Sierpinski triangle
#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),   APPENDROWS( APPENDROWS(triple)(middle) )(triple) ) )
http://rosettacode.org/wiki/Shoelace_formula_for_polygonal_area
Shoelace formula for polygonal area
Given the n + 1 vertices x[0], y[0] .. x[N], y[N] of a simple polygon described in a clockwise direction, then the polygon's area can be calculated by: abs( (sum(x[0]*y[1] + ... x[n-1]*y[n]) + x[N]*y[0]) - (sum(x[1]*y[0] + ... x[n]*y[n-1]) + x[0]*y[N]) ) / 2 (Where abs returns the absolute value) Task Write a function/method/routine to use the the Shoelace formula to calculate the area of the polygon described by the ordered points: (3,4), (5,11), (12,8), (9,5), and (5,6) Show the answer here, on this page.
#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 = 1 To n area = area + x(i)*y(i+1) - x(i+1)*y(i) Next 'i area = Abs(area)/2 msgbox area,,"Shoelace formula"
http://rosettacode.org/wiki/Shoelace_formula_for_polygonal_area
Shoelace formula for polygonal area
Given the n + 1 vertices x[0], y[0] .. x[N], y[N] of a simple polygon described in a clockwise direction, then the polygon's area can be calculated by: abs( (sum(x[0]*y[1] + ... x[n-1]*y[n]) + x[N]*y[0]) - (sum(x[1]*y[0] + ... x[n]*y[n-1]) + x[0]*y[N]) ) / 2 (Where abs returns the absolute value) Task Write a function/method/routine to use the the Shoelace formula to calculate the area of the polygon described by the ordered points: (3,4), (5,11), (12,8), (9,5), and (5,6) Show the answer here, on this page.
#Visual_Basic
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 Variant Dim n As Long, i As Long, j As Long v = Array(3, 4, 5, 11, 12, 8, 9, 5, 5, 6) n = (UBound(v) - LBound(v) + 1) \ 2 - 1 ReDim x(0 To n) As Double, y(0 To n) As Double j = 0 For i = 0 To n x(i) = v(j) y(i) = v(j + 1) j = j + 2 Next i Debug.Print ShoelaceArea(x(), y()) End Sub
http://rosettacode.org/wiki/Shell_one-liner
Shell one-liner
Task Show how to specify and execute a short program in the language from a command shell, where the input to the command shell is only one line in length. Avoid depending on the particular shell or operating system used as much as is reasonable; if the language has notable implementations which have different command argument syntax, or the systems those implementations run on have different styles of shells, it would be good to show multiple examples.
#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 command argument syntax, or the systems those implementations run on have different styles of shells, it would be good to show multiple examples.
#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 command argument syntax, or the systems those implementations run on have different styles of shells, it would be good to show multiple examples.
#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, and is to be minimized. If we needed to compute the conjunction   (and): x = a() and b() Then it would be best to not compute the value of   b()   if the value of   a()   is computed as   false,   as the value of   x   can then only ever be   false. Similarly, if we needed to compute the disjunction (or): y = a() or b() Then it would be best to not compute the value of   b()   if the value of   a()   is computed as   true,   as the value of   y   can then only ever be   true. Some languages will stop further computation of boolean equations as soon as the result is known, so-called   short-circuit evaluation   of boolean expressions Task Create two functions named   a   and   b,   that take and return the same boolean value. The functions should also print their name whenever they are called. Calculate and assign the values of the following equations to a variable in such a way that function   b   is only called when necessary: x = a(i) and b(j) y = a(i) or b(j) If the language does not have short-circuit evaluation, this might be achieved with nested     if     statements.
#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 ] } || . "t && f = " write { [ t a ] [ f b ] } && . "t || f = " write { [ t a ] [ f b ] } || . "t && t = " write { [ t a ] [ t b ] } && . "t || t = " write { [ t a ] [ t b ] } || .