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/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
#Kotlin
Kotlin
// version 1.0.6   import java.security.MessageDigest   fun main(args: Array<String>) { val text = "Rosetta code" val bytes = text.toByteArray() val md = MessageDigest.getInstance("SHA-256") val digest = md.digest(bytes) for (byte in digest) print("%02x".format(byte)) println() }
http://rosettacode.org/wiki/Sequence:_smallest_number_greater_than_previous_term_with_exactly_n_divisors
Sequence: smallest number greater than previous term with exactly n divisors
Calculate the sequence where each term an is the smallest natural number greater than the previous term, that has exactly n divisors. Task Show here, on this page, at least the first 15 terms of the sequence. See also OEIS:A069654 Related tasks Sequence: smallest number with exactly n divisors Sequence: nth number with exactly n divisors‎‎
#Go
Go
package main   import "fmt"   func countDivisors(n int) int { count := 0 for i := 1; i*i <= n; i++ { if n%i == 0 { if i == n/i { count++ } else { count += 2 } } } return count }   func main() { const max = 15 fmt.Println("The first", max, "terms of the sequence are:") for i, next := 1, 1; next <= max; i++ { if next == countDivisors(i) { fmt.Printf("%d ", i) next++ } } fmt.Println() }
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.
#Lua
Lua
#!/usr/bin/lua   local sha1 = require "sha1"   for i, str in ipairs{"Rosetta code", "Rosetta Code"} do print(string.format("SHA-1(%q) = %s", str, sha1(str))) end
http://rosettacode.org/wiki/Seven-sided_dice_from_five-sided_dice
Seven-sided dice from five-sided dice
Task (Given an equal-probability generator of one of the integers 1 to 5 as dice5),   create dice7 that generates a pseudo-random integer from 1 to 7 in equal probability using only dice5 as a source of random numbers,   and check the distribution for at least one million calls using the function created in   Simple Random Distribution Checker. Implementation suggestion: dice7 might call dice5 twice, re-call if four of the 25 combinations are given, otherwise split the other 21 combinations into 7 groups of three, and return the group index from the rolls. (Task adapted from an answer here)
#PicoLisp
PicoLisp
(de dice5 () (rand 1 5) )   (de dice7 () (use R (until (> 21 (setq R (+ (* 5 (dice5)) (dice5) -6)))) (inc (% R 7)) ) )
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)
#PureBasic
PureBasic
Procedure dice5() ProcedureReturn Random(4) + 1 EndProcedure   Procedure dice7() Protected x   x = dice5() * 5 + dice5() - 6 If x > 20 ProcedureReturn dice7() EndIf   ProcedureReturn x % 7 + 1 EndProcedure
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.
#XPL0
XPL0
func IsPrime(N); \Return 'true' if N is prime int N, I; [if N <= 2 then return N = 2; if (N&1) = 0 then \even >2\ return false; for I:= 3 to sqrt(N) do [if rem(N/I) = 0 then return false; I:= I+1; ]; return true; ];   int CU, C2, C3, C4, C5, N, I; int Unsexy(10), Pairs(5), Trips(5), Quads(5), Quins(5); [CU:= 0; C2:= 0; C3:= 0; C4:= 0; C5:= 0; for N:= 1000035 downto 2 do [if IsPrime(N) then [if IsPrime(N-6) then [if C2 < 5 then Pairs(C2):= N; C2:= C2+1; if IsPrime(N-12) then [if C3 < 5 then Trips(C3):= N; C3:= C3+1; if IsPrime(N-18) then [if C4 < 5 then Quads(C4):= N; C4:= C4+1; if IsPrime(N-24) then [if C5 < 5 then Quins(C5):= N; C5:= C5+1; ]; ]; ]; ] else if not IsPrime(N+6) then [if CU < 10 then Unsexy(CU):= N; CU:= CU+1; ]; ]; ]; IntOut(0, C2); Text(0, " pairs ending with:^m^j"); for I:= 4 downto 0 do [Text(0, " ["); IntOut(0, Pairs(I)-6); Text(0, ", "); IntOut(0, Pairs(I)); Text(0, "]^m^j"); ]; IntOut(0, C3); Text(0, " triplets ending with:^m^j"); for I:= 4 downto 0 do [Text(0, " ["); IntOut(0, Trips(I)-12); Text(0, ", "); IntOut(0, Trips(I)-6); Text(0, ", "); IntOut(0, Trips(I)); Text(0, "]^m^j"); ]; IntOut(0, C4); Text(0, " quadruplets ending with:^m^j"); for I:= 4 downto 0 do [Text(0, " ["); IntOut(0, Quads(I)-18); Text(0, ", "); IntOut(0, Quads(I)-12); Text(0, ", "); IntOut(0, Quads(I)-6); Text(0, ", "); IntOut(0, Quads(I)); Text(0, "]^m^j"); ]; IntOut(0, C5); Text(0, " quintuplet(s) ending with:^m^j"); I:= if C5 > 5 then 5 else C5; for I:= I-1 downto 0 do [Text(0, " ["); IntOut(0, Quins(I)-24); Text(0, ", "); IntOut(0, Quins(I)-18); Text(0, ", "); IntOut(0, Quins(I)-12); Text(0, ", "); IntOut(0, Quins(I)-6); Text(0, ", "); IntOut(0, Quins(I)); Text(0, "]^m^j"); ]; IntOut(0, CU); Text(0, " unsexy primes ending with:^m^j"); for I:= 9 downto 0 do [IntOut(0, Unsexy(I)); if I then Text(0, ", ")]; CrLf(0); ]
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.
#zkl
zkl
var [const] BI=Import("zklBigNum"); // libGMP const N=1_000_035, M=N+24; // M allows prime group to span N, eg N=100, (97,103) const OVR=6; // 6 if prime group can NOT span N, else 0 ps,p := Data(M+50).fill(0), BI(1); // slop at the end (for reverse wrap around) while(p.nextPrime()<=M){ ps[p]=1 } // bitmap of primes   ns:=(N-OVR).filter('wrap(n){ 2==(ps[n] + ps[n+6]) }); # know 2 isn't, check anyway msg(N,"sexy prime pairs",ns,5,1);   ns:=[3..N-(6+OVR),2].filter('wrap(n){ 3==(ps[n] + ps[n+6] + ps[n+12]) }); # can't be even msg(N,"sexy triplet primes",ns,5,2);   ns:=[3..N-(12+OVR),2].filter('wrap(n){ 4==(ps[n] + ps[n+6] + ps[n+12] + ps[n+18]) }); # no evens msg(N,"sexy quadruplet primes",ns,5,3);   ns:=[3..N-(18+OVR),2].filter('wrap(n){ 5==(ps[n] + ps[n+6] + ps[n+12] + ps[n+18] + ps[n+24]) }); msg(N,"sexy quintuplet primes",ns,1,4);   ns:=(N-OVR).filter('wrap(n){ ps[n] and 0==(ps[n-6] + ps[n+6]) }); // include 2 msg(N,"unsexy primes",ns,10,0);   fcn msg(N,s,ps,n,g){ n=n.min(ps.len()); // if the number of primes is less than n gs:=ps[-n,*].apply('wrap(n){ [0..g*6,6].apply('+(n)) }) .pump(String,T("concat", ","),"(%s) ".fmt); println("Number of %s less than %,d is %,d".fmt(s,N,ps.len())); println("The last %d %s:\n  %s\n".fmt(n, (n>1 and "are" or "is"), gs)); }
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
#Groovy
Groovy
class ShowAsciiTable { static void main(String[] args) { for (int i = 32; i <= 127; i++) { if (i == 32 || i == 127) { String s = i == 32 ? "Spc" : "Del" printf("%3d: %s ", i, s) } else { printf("%3d: %c ", i, i) } if ((i - 1) % 6 == 0) { println() } } } }
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
#PHP
PHP
<?php   function sierpinskiTriangle($order) { $char = '#'; $n = 1 << $order; $line = array(); for ($i = 0 ; $i <= 2 * $n ; $i++) { $line[$i] = ' '; } $line[$n] = $char; for ($i = 0 ; $i < $n ; $i++) { echo implode('', $line), PHP_EOL; $u = $char; for ($j = $n - $i ; $j < $n + $i + 1 ; $j++) { $t = ($line[$j - 1] == $line[$j + 1] ? ' ' : $char); $line[$j - 1] = $u; $u = $t; } $line[$n + $i] = $t; $line[$n + $i + 1] = $char; } }   sierpinskiTriangle(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
#Kotlin
Kotlin
// version 1.1.2   fun inCarpet(x: Int, y: Int): Boolean { var xx = x var yy = y while (xx != 0 && yy != 0) { if (xx % 3 == 1 && yy % 3 == 1) return false xx /= 3 yy /= 3 } return true }   fun carpet(n: Int) { val power = Math.pow(3.0, n.toDouble()).toInt() for(i in 0 until power) { for(j in 0 until power) print(if (inCarpet(i, j)) "*" else " ") println() } }   fun main(args: Array<String>) = carpet(3)
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.
#Nim
Nim
proc a(x): bool = echo "a called" result = x   proc b(x): bool = echo "b called" result = x   let x = a(false) and b(true) # echoes "a called" let y = a(true) or b(true) # echoes "a called"
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.
#Objeck
Objeck
class ShortCircuit { function : a(a : Bool) ~ Bool { "a"->PrintLine(); return a; }   function : b(b : Bool) ~ Bool { "b"->PrintLine(); return b; }   function : Main(args : String[]) ~ Nil { result := a(false) & b(false); "F and F = {$result}"->PrintLine(); result := a(false) | b(false); "F or F = {$result}"->PrintLine();   result := a(false) & b(true); "F and T = {$result}"->PrintLine(); result := a(false) | b(true); "F or T = {$result}"->PrintLine();   result := a(true) & b(false); "T and F = {$result}"->PrintLine(); result := a(true) | b(false); "T or F = {$result}"->PrintLine();   result := a(true) & b(true); "T and T = {$result}"->PrintLine(); result := a(true) | b(true); "T or T = {$result}"->PrintLine(); } }
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
#Ruby
Ruby
COLORS = %i(red green purple) #use [:red, :green, :purple] in Ruby < 2.0 SYMBOLS = %i(oval squiggle diamond) NUMBERS = %i(one two three) SHADINGS = %i(solid open striped) DECK = COLORS.product(SYMBOLS, NUMBERS, SHADINGS)   def get_all_sets(hand) hand.combination(3).select do |candidate| grouped_features = candidate.flatten.group_by{|f| f} grouped_features.values.none?{|v| v.size == 2} end end   def get_puzzle_and_answer(hand_size, num_sets_goal) begin hand = DECK.sample(hand_size) sets = get_all_sets(hand) end until sets.size == num_sets_goal [hand, sets] end   def print_cards(cards) puts cards.map{|card| "  %-8s" * 4 % card} puts end   def set_puzzle(deal, goal=deal/2) puzzle, sets = get_puzzle_and_answer(deal, goal) puts "Dealt #{puzzle.size} cards:" print_cards(puzzle) puts "Containing #{sets.size} sets:" sets.each{|set| print_cards(set)} end   set_puzzle(9) set_puzzle(12)
http://rosettacode.org/wiki/Set_of_real_numbers
Set of real numbers
All real numbers form the uncountable set ℝ. Among its subsets, relatively simple are the convex sets, each expressed as a range between two real numbers a and b where a ≤ b. There are actually four cases for the meaning of "between", depending on open or closed boundary: [a, b]: {x | a ≤ x and x ≤ b } (a, b): {x | a < x and x < b } [a, b): {x | a ≤ x and x < b } (a, b]: {x | a < x and x ≤ b } Note that if a = b, of the four only [a, a] would be non-empty. Task Devise a way to represent any set of real numbers, for the definition of 'any' in the implementation notes below. Provide methods for these common set operations (x is a real number; A and B are sets): x ∈ A: determine if x is an element of A example: 1 is in [1, 2), while 2, 3, ... are not. A ∪ B: union of A and B, i.e. {x | x ∈ A or x ∈ B} example: [0, 2) ∪ (1, 3) = [0, 3); [0, 1) ∪ (2, 3] = well, [0, 1) ∪ (2, 3] A ∩ B: intersection of A and B, i.e. {x | x ∈ A and x ∈ B} example: [0, 2) ∩ (1, 3) = (1, 2); [0, 1) ∩ (2, 3] = empty set A - B: difference between A and B, also written as A \ B, i.e. {x | x ∈ A and x ∉ B} example: [0, 2) − (1, 3) = [0, 1] Test your implementation by checking if numbers 0, 1, and 2 are in any of the following sets: (0, 1] ∪ [0, 2) [0, 2) ∩ (1, 2] [0, 3) − (0, 1) [0, 3) − [0, 1] Implementation notes 'Any' real set means 'sets that can be expressed as the union of a finite number of convex real sets'. Cantor's set needs not apply. Infinities should be handled gracefully; indeterminate numbers (NaN) can be ignored. You can use your machine's native real number representation, which is probably IEEE floating point, and assume it's good enough (it usually is). Optional work Create a function to determine if a given set is empty (contains no element). Define A = {x | 0 < x < 10 and |sin(π x²)| > 1/2 }, B = {x | 0 < x < 10 and |sin(π x)| > 1/2}, calculate the length of the real axis covered by the set A − B. Note that |sin(π x)| > 1/2 is the same as n + 1/6 < x < n + 5/6 for all integers n; your program does not need to derive this by itself.
#C
C
#include <math.h> #include <stdbool.h> #include <stdio.h> #include <stdlib.h>   struct RealSet { bool(*contains)(struct RealSet*, struct RealSet*, double); struct RealSet *left; struct RealSet *right; double low, high; };   typedef enum { CLOSED, LEFT_OPEN, RIGHT_OPEN, BOTH_OPEN, } RangeType;   double length(struct RealSet *self) { const double interval = 0.00001; double p = self->low; int count = 0;   if (isinf(self->low) || isinf(self->high)) return -1.0; if (self->high <= self->low) return 0.0;   do { if (self->contains(self, NULL, p)) count++; p += interval; } while (p < self->high); return count * interval; }   bool empty(struct RealSet *self) { if (self->low == self->high) { return !self->contains(self, NULL, self->low); } return length(self) == 0.0; }   static bool contains_closed(struct RealSet *self, struct RealSet *_, double d) { return self->low <= d && d <= self->high; }   static bool contains_left_open(struct RealSet *self, struct RealSet *_, double d) { return self->low < d && d <= self->high; }   static bool contains_right_open(struct RealSet *self, struct RealSet *_, double d) { return self->low <= d && d < self->high; }   static bool contains_both_open(struct RealSet *self, struct RealSet *_, double d) { return self->low < d && d < self->high; }   static bool contains_intersect(struct RealSet *self, struct RealSet *_, double d) { return self->left->contains(self->left, NULL, d) && self->right->contains(self->right, NULL, d); }   static bool contains_union(struct RealSet *self, struct RealSet *_, double d) { return self->left->contains(self->left, NULL, d) || self->right->contains(self->right, NULL, d); }   static bool contains_subtract(struct RealSet *self, struct RealSet *_, double d) { return self->left->contains(self->left, NULL, d) && !self->right->contains(self->right, NULL, d); }   struct RealSet* makeSet(double low, double high, RangeType type) { bool(*contains)(struct RealSet*, struct RealSet*, double); struct RealSet *rs;   switch (type) { case CLOSED: contains = contains_closed; break; case LEFT_OPEN: contains = contains_left_open; break; case RIGHT_OPEN: contains = contains_right_open; break; case BOTH_OPEN: contains = contains_both_open; break; default: return NULL; }   rs = malloc(sizeof(struct RealSet)); rs->contains = contains; rs->left = NULL; rs->right = NULL; rs->low = low; rs->high = high; return rs; }   struct RealSet* makeIntersect(struct RealSet *left, struct RealSet *right) { struct RealSet *rs = malloc(sizeof(struct RealSet)); rs->contains = contains_intersect; rs->left = left; rs->right = right; rs->low = fmin(left->low, right->low); rs->high = fmin(left->high, right->high); return rs; }   struct RealSet* makeUnion(struct RealSet *left, struct RealSet *right) { struct RealSet *rs = malloc(sizeof(struct RealSet)); rs->contains = contains_union; rs->left = left; rs->right = right; rs->low = fmin(left->low, right->low); rs->high = fmin(left->high, right->high); return rs; }   struct RealSet* makeSubtract(struct RealSet *left, struct RealSet *right) { struct RealSet *rs = malloc(sizeof(struct RealSet)); rs->contains = contains_subtract; rs->left = left; rs->right = right; rs->low = left->low; rs->high = left->high; return rs; }   int main() { struct RealSet *a = makeSet(0.0, 1.0, LEFT_OPEN); struct RealSet *b = makeSet(0.0, 2.0, RIGHT_OPEN); struct RealSet *c = makeSet(1.0, 2.0, LEFT_OPEN); struct RealSet *d = makeSet(0.0, 3.0, RIGHT_OPEN); struct RealSet *e = makeSet(0.0, 1.0, BOTH_OPEN); struct RealSet *f = makeSet(0.0, 1.0, CLOSED); struct RealSet *g = makeSet(0.0, 0.0, CLOSED); int i;   for (i = 0; i < 3; ++i) { struct RealSet *t;   t = makeUnion(a, b); printf("(0, 1] union [0, 2) contains %d is %d\n", i, t->contains(t, NULL, i)); free(t);   t = makeIntersect(b, c); printf("[0, 2) intersect (1, 2] contains %d is %d\n", i, t->contains(t, NULL, i)); free(t);   t = makeSubtract(d, e); printf("[0, 3) - (0, 1) contains %d is %d\n", i, t->contains(t, NULL, i)); free(t);   t = makeSubtract(d, f); printf("[0, 3) - [0, 1] contains %d is %d\n", i, t->contains(t, NULL, i)); free(t);   printf("\n"); }   printf("[0, 0] is empty %d\n", empty(g));   free(a); free(b); free(c); free(d); free(e); free(f); free(g);   return 0; }
http://rosettacode.org/wiki/Sieve_of_Eratosthenes
Sieve of Eratosthenes
This task has been clarified. Its programming examples are in need of review to ensure that they still fit the requirements of the task. The Sieve of Eratosthenes is a simple algorithm that finds the prime numbers up to a given integer. Task Implement the   Sieve of Eratosthenes   algorithm, with the only allowed optimization that the outer loop can stop at the square root of the limit, and the inner loop may start at the square of the prime just found. That means especially that you shouldn't optimize by using pre-computed wheels, i.e. don't assume you need only to cross out odd numbers (wheel based on 2), numbers equal to 1 or 5 modulo 6 (wheel based on 2 and 3), or similar wheels based on low primes. If there's an easy way to add such a wheel based optimization, implement it as an alternative version. Note It is important that the sieve algorithm be the actual algorithm used to find prime numbers for the task. Related tasks   Emirp primes   count in factors   prime decomposition   factors of an integer   extensible prime generator   primality by trial division   factors of a Mersenne number   trial factoring of a Mersenne number   partition an integer X into N primes   sequence of primes by Trial Division
#6502_Assembly
6502 Assembly
ERATOS: STA $D0  ; value of n LDA #$00 LDX #$00 SETUP: STA $1000,X  ; populate array ADC #$01 INX CPX $D0 BPL SET JMP SETUP SET: LDX #$02 SIEVE: LDA $1000,X  ; find non-zero INX CPX $D0 BPL SIEVED CMP #$00 BEQ SIEVE STA $D1  ; current prime MARK: CLC ADC $D1 TAY LDA #$00 STA $1000,Y TYA CMP $D0 BPL SIEVE JMP MARK SIEVED: LDX #$01 LDY #$00 COPY: INX CPX $D0 BPL COPIED LDA $1000,X CMP #$00 BEQ COPY STA $2000,Y INY JMP COPY COPIED: TYA  ; how many found RTS
http://rosettacode.org/wiki/Sequence_of_primorial_primes
Sequence of primorial primes
The sequence of primorial primes is given as the increasing values of n where primorial(n) ± 1 is prime. Noting that the n'th primorial is defined as the multiplication of the smallest n primes, the sequence is of the number of primes, in order that when multiplied together is one-off being a prime number itself. Task Generate and show here the first ten values of the sequence. Optional extended task Show the first twenty members of the series. Notes This task asks for the primorial indices that create the final primorial prime numbers, so there should be no ten-or-more digit numbers in the program output (although extended precision integers will be needed for intermediate results). There is some confusion in the references, but for the purposes of this task the sequence begins with n = 1. Probabilistic primality tests are allowed, as long as they are good enough such that the output shown is correct. Related tasks Primorial numbers Factorial See also Primorial prime Wikipedia. Primorial prime from The Prime Glossary. Sequence A088411 from The On-Line Encyclopedia of Integer Sequences
#C.2B.2B
C++
#include <cstdint> #include <iostream> #include <sstream> #include <gmpxx.h>   typedef mpz_class integer;   bool is_probably_prime(const integer& n) { return mpz_probab_prime_p(n.get_mpz_t(), 25) != 0; }   bool is_prime(unsigned int n) { if (n < 2) return false; if (n % 2 == 0) return n == 2; if (n % 3 == 0) return n == 3; for (unsigned int p = 5; p * p <= n; p += 4) { if (n % p == 0) return false; p += 2; if (n % p == 0) return false; } return true; }   int main() { const unsigned int max = 20; integer primorial = 1; for (unsigned int p = 0, count = 0, index = 0; count < max; ++p) { if (!is_prime(p)) continue; primorial *= p; ++index; if (is_probably_prime(primorial - 1) || is_probably_prime(primorial + 1)) { if (count > 0) std::cout << ' '; std::cout << index; ++count; } } std::cout << '\n'; return 0; }
http://rosettacode.org/wiki/Sequence:_nth_number_with_exactly_n_divisors
Sequence: nth number with exactly n divisors
Calculate the sequence where each term an is the nth that has n divisors. Task Show here, on this page, at least the first 15 terms of the sequence. See also OEIS:A073916 Related tasks Sequence: smallest number greater than previous term with exactly n divisors Sequence: smallest number with exactly n divisors
#Go
Go
package main   import ( "fmt" "math" "math/big" )   var bi = new(big.Int)   func isPrime(n int) bool { bi.SetUint64(uint64(n)) return bi.ProbablyPrime(0) }   func generateSmallPrimes(n int) []int { primes := make([]int, n) primes[0] = 2 for i, count := 3, 1; count < n; i += 2 { if isPrime(i) { primes[count] = i count++ } } return primes }   func countDivisors(n int) int { count := 1 for n%2 == 0 { n >>= 1 count++ } for d := 3; d*d <= n; d += 2 { q, r := n/d, n%d if r == 0 { dc := 0 for r == 0 { dc += count n = q q, r = n/d, n%d } count += dc } } if n != 1 { count *= 2 } return count }   func main() { const max = 33 primes := generateSmallPrimes(max) z := new(big.Int) p := new(big.Int) fmt.Println("The first", max, "terms in the sequence are:") for i := 1; i <= max; i++ { if isPrime(i) { z.SetUint64(uint64(primes[i-1])) p.SetUint64(uint64(i - 1)) z.Exp(z, p, nil) fmt.Printf("%2d : %d\n", i, z) } else { count := 0 for j := 1; ; j++ { if i%2 == 1 { sq := int(math.Sqrt(float64(j))) if sq*sq != j { continue } } if countDivisors(j) == i { count++ if count == i { fmt.Printf("%2d : %d\n", i, j) break } } } } } }
http://rosettacode.org/wiki/Set_consolidation
Set consolidation
Given two sets of items then if any item is common to any set then the result of applying consolidation to those sets is a set of sets whose contents is: The two input sets if no common item exists between the two input sets of items. The single set that is the union of the two input sets if they share a common item. Given N sets of items where N>2 then the result is the same as repeatedly replacing all combinations of two sets by their consolidation until no further consolidation between set pairs is possible. If N<2 then consolidation has no strict meaning and the input can be returned. Example 1: Given the two sets {A,B} and {C,D} then there is no common element between the sets and the result is the same as the input. Example 2: Given the two sets {A,B} and {B,D} then there is a common element B between the sets and the result is the single set {B,D,A}. (Note that order of items in a set is immaterial: {A,B,D} is the same as {B,D,A} and {D,A,B}, etc). Example 3: Given the three sets {A,B} and {C,D} and {D,B} then there is no common element between the sets {A,B} and {C,D} but the sets {A,B} and {D,B} do share a common element that consolidates to produce the result {B,D,A}. On examining this result with the remaining set, {C,D}, they share a common element and so consolidate to the final output of the single set {A,B,C,D} Example 4: The consolidation of the five sets: {H,I,K}, {A,B}, {C,D}, {D,B}, and {F,G,H} Is the two sets: {A, C, B, D}, and {G, F, I, H, K} See also Connected component (graph theory) Range consolidation
#D
D
import std.stdio, std.algorithm, std.array;   dchar[][] consolidate(dchar[][] sets) @safe { foreach (set; sets) set.sort();   foreach (i, ref si; sets[0 .. $ - 1]) { if (si.empty) continue; foreach (ref sj; sets[i + 1 .. $]) if (!sj.empty && !si.setIntersection(sj).empty) { sj = si.setUnion(sj).uniq.array; si = null; } }   return sets.filter!"!a.empty".array; }   void main() @safe { [['A', 'B'], ['C','D']].consolidate.writeln;   [['A','B'], ['B','D']].consolidate.writeln;   [['A','B'], ['C','D'], ['D','B']].consolidate.writeln;   [['H','I','K'], ['A','B'], ['C','D'], ['D','B'], ['F','G','H']].consolidate.writeln; }
http://rosettacode.org/wiki/Sequence:_smallest_number_with_exactly_n_divisors
Sequence: smallest number with exactly n divisors
Calculate the sequence where each term   an   is the smallest natural number that has exactly   n   divisors. Task Show here, on this page, at least the first  15  terms of the sequence. Related tasks Sequence: smallest number greater than previous term with exactly n divisors Sequence: nth number with exactly n divisors‎‎ See also OEIS:A005179
#Factor
Factor
USING: fry kernel lists lists.lazy math math.primes.factors prettyprint sequences ;   : A005179 ( -- list ) 1 lfrom [ 1 swap '[ dup divisors length _ = ] [ 1 + ] until ] lmap-lazy ;   15 A005179 ltake list>array .
http://rosettacode.org/wiki/Sequence:_smallest_number_with_exactly_n_divisors
Sequence: smallest number with exactly n divisors
Calculate the sequence where each term   an   is the smallest natural number that has exactly   n   divisors. Task Show here, on this page, at least the first  15  terms of the sequence. Related tasks Sequence: smallest number greater than previous term with exactly n divisors Sequence: nth number with exactly n divisors‎‎ See also OEIS:A005179
#FreeBASIC
FreeBASIC
#define UPTO 15   function divisors(byval n as ulongint) as uinteger 'find the number of divisors of an integer dim as integer r = 2, i for i = 2 to n\2 if n mod i = 0 then r += 1 next i return r end function   dim as ulongint i = 2 dim as integer n, nfound = 1, sfound(UPTO) = {1}   while nfound < UPTO n = divisors(i) if n<=UPTO andalso sfound(n)=0 then nfound += 1 sfound(n) = i end if i+=1 wend   print 1;" "; 'special case for i = 2 to UPTO print sfound(i);" "; next i print 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
#Lasso
Lasso
// The following will return a list of all the cipher // algorithms supported by the installation of Lasso cipher_list   // With a -digest parameter the method will limit the returned list // to all of the digest algorithms supported by the installation of Lasso cipher_list(-digest)   // return the SHA-256 digest. Dependant on SHA-256 being an available digest method cipher_digest('Rosetta Code', -digest='SHA-256',-hex=true)  
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
#Lua
Lua
#!/usr/bin/lua   require "sha2"   print(sha2.sha256hex("Rosetta code"))
http://rosettacode.org/wiki/Sequence:_smallest_number_greater_than_previous_term_with_exactly_n_divisors
Sequence: smallest number greater than previous term with exactly n divisors
Calculate the sequence where each term an is the smallest natural number greater than the previous term, that has exactly n divisors. Task Show here, on this page, at least the first 15 terms of the sequence. See also OEIS:A069654 Related tasks Sequence: smallest number with exactly n divisors Sequence: nth number with exactly n divisors‎‎
#Haskell
Haskell
import Text.Printf (printf)   sequence_A069654 :: [(Int,Int)] sequence_A069654 = go 1 $ (,) <*> countDivisors <$> [1..] where go t ((n,c):xs) | c == t = (t,n):go (succ t) xs | otherwise = go t xs countDivisors n = foldr f 0 [1..floor $ sqrt $ realToFrac n] where f x r | n `mod` x == 0 = if n `div` x == x then r+1 else r+2 | otherwise = r   main :: IO () main = mapM_ (uncurry $ printf "a(%2d)=%5d\n") $ take 15 sequence_A069654
http://rosettacode.org/wiki/Sequence:_smallest_number_greater_than_previous_term_with_exactly_n_divisors
Sequence: smallest number greater than previous term with exactly n divisors
Calculate the sequence where each term an is the smallest natural number greater than the previous term, that has exactly n divisors. Task Show here, on this page, at least the first 15 terms of the sequence. See also OEIS:A069654 Related tasks Sequence: smallest number with exactly n divisors Sequence: nth number with exactly n divisors‎‎
#J
J
  sieve=: 3 :0 NB. sieve y returns a vector of y boxes. NB. In each box is an array of 2 columns. NB. The first column is the factor tally NB. and the second column is a number with NB. that many factors. NB. Rather than factoring, the algorithm NB. counts prime seive cell hits. NB. The boxes are not ordered by factor tally. range=. <. + i.@:|@:- tally=. y#0 for_i.#\tally do. j=. }:^:(y<:{:)i * 1 range >: <. y % i tally=. j >:@:{`[`]} tally end. (</.~ {."1) (,. i.@:#)tally )  
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.
#Maple
Maple
with(StringTools): Hash("Ars longa, vita brevis",method="SHA1");   # "e640d285242886eb96ab80cbf858389b3df52f43"
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.
#Mathematica.2FWolfram_Language
Mathematica/Wolfram Language
Hash["Rosetta code","SHA1","HexString"]
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)
#Python
Python
from random import randint   def dice5(): return randint(1, 5)   def dice7(): r = dice5() + dice5() * 5 - 6 return (r % 7) + 1 if r < 21 else dice7()
http://rosettacode.org/wiki/Seven-sided_dice_from_five-sided_dice
Seven-sided dice from five-sided dice
Task (Given an equal-probability generator of one of the integers 1 to 5 as dice5),   create dice7 that generates a pseudo-random integer from 1 to 7 in equal probability using only dice5 as a source of random numbers,   and check the distribution for at least one million calls using the function created in   Simple Random Distribution Checker. Implementation suggestion: dice7 might call dice5 twice, re-call if four of the 25 combinations are given, otherwise split the other 21 combinations into 7 groups of three, and return the group index from the rolls. (Task adapted from an answer here)
#Quackery
Quackery
[ 5 random 1+ ] is dice5 ( --> n )   [ dice5 5 * dice5 + 6 - [ table 0 0 0 0 1 1 1 2 2 2 3 3 3 4 4 4 5 5 5 6 6 6 7 7 7 ] dup 0 = iff drop again ] is dice7 ( --> n )
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)
#R
R
dice5 <- function(n=1) sample(5, n, replace=TRUE)
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
#Haskell
Haskell
import Data.Char (chr) import Data.List (transpose) import Data.List.Split (chunksOf) import Text.Printf (printf)   ----------------------- ASCII TABLE ----------------------   asciiTable :: String asciiTable = unlines $ (printf "%-12s" =<<) <$> transpose (chunksOf 16 $ asciiEntry <$> [32 .. 127])   asciiEntry :: Int -> String asciiEntry n | null k = k | otherwise = concat [printf "%3d" n, " : ", k] where k = asciiName n   asciiName :: Int -> String asciiName n | 32 > n = [] | 127 < n = [] | 32 == n = "Spc" | 127 == n = "Del" | otherwise = [chr n]     --------------------------- TEST ------------------------- main :: IO () main = putStrLn asciiTable
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
#Picat
Picat
go => foreach(N in 1..4) sierpinski(N), nl end, nl.   sierpinski(N) => Size = 2**N, foreach(Y in Size-1..-1..0) printf("%s", [' ' : _I in 1..Y]), foreach(X in 0..Size-Y-1) printf("%s ", cond(X /\ Y == 0, "*", " ")) end, nl 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
#Lua
Lua
local function carpet(n, f) print("n = " .. n) local function S(x, y) if x==0 or y==0 then return true elseif x%3==1 and y%3==1 then return false end return S(x//3, y//3) end for y = 0, 3^n-1 do for x = 0, 3^n-1 do io.write(f(S(x, y))) end print() end print() end   for n = 0, 4 do carpet(n, function(b) return b and "■ " or " " end) end
http://rosettacode.org/wiki/Short-circuit_evaluation
Short-circuit evaluation
Control Structures These are examples of control structures. You may also be interested in: Conditional structures Exceptions Flow-control structures Loops Assume functions   a   and   b   return boolean values,   and further, the execution of function   b   takes considerable resources without side effects, and is to be minimized. If we needed to compute the conjunction   (and): x = a() and b() Then it would be best to not compute the value of   b()   if the value of   a()   is computed as   false,   as the value of   x   can then only ever be   false. Similarly, if we needed to compute the disjunction (or): y = a() or b() Then it would be best to not compute the value of   b()   if the value of   a()   is computed as   true,   as the value of   y   can then only ever be   true. Some languages will stop further computation of boolean equations as soon as the result is known, so-called   short-circuit evaluation   of boolean expressions Task Create two functions named   a   and   b,   that take and return the same boolean value. The functions should also print their name whenever they are called. Calculate and assign the values of the following equations to a variable in such a way that function   b   is only called when necessary: x = a(i) and b(j) y = a(i) or b(j) If the language does not have short-circuit evaluation, this might be achieved with nested     if     statements.
#OCaml
OCaml
let a r = print_endline " > function a called"; r let b r = print_endline " > function b called"; r   let test_and b1 b2 = Printf.printf "# testing (%b && %b)\n" b1 b2; ignore (a b1 && b b2)   let test_or b1 b2 = Printf.printf "# testing (%b || %b)\n" b1 b2; ignore (a b1 || b b2)   let test_this test = test true true; test true false; test false true; test false false; ;;   let () = print_endline "==== Testing and ===="; test_this test_and; print_endline "==== Testing or ===="; test_this test_or; ;;
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
#Rust
Rust
  use itertools::Itertools; use rand::Rng;   const DECK_SIZE: usize = 81; const NUM_ATTRIBUTES: usize = 4; const ATTRIBUTES: [&[&str]; NUM_ATTRIBUTES] = [ &["red", "green", "purple"], &["one", "two", "three"], &["oval", "squiggle", "diamond"], &["solid", "open", "striped"], ];   fn get_random_card_indexes(num_of_cards: usize) -> Vec<usize> { let mut selected_cards: Vec<usize> = Vec::with_capacity(num_of_cards); let mut rng = rand::thread_rng(); loop { let idx = rng.gen_range(0..DECK_SIZE); if !selected_cards.contains(&idx) { selected_cards.push(idx); } if selected_cards.len() == num_of_cards { break; } }   selected_cards }   fn run_game(num_of_cards: usize, minimum_number_of_sets: usize) { println!( "\nGAME: # of cards: {} # of sets: {}", num_of_cards, minimum_number_of_sets );   // generate the deck with 81 unique cards let deck = (0..NUM_ATTRIBUTES) .map(|_| (0..=2_usize)) .multi_cartesian_product() .collect::<Vec<_>>();   // closure to return true if the three attributes are the same, or each of them is different let valid_attribute = |a: usize, b: usize, c: usize| -> bool { a == b && b == c || (a != b && b != c && a != c) };   // closure to test all attributes, each of them should be true to have a valid set let valid_set = |t: &Vec<&Vec<usize>>| -> bool { for attr in 0..NUM_ATTRIBUTES { if !valid_attribute(t[0][attr], t[1][attr], t[2][attr]) { return false; } } true };   loop { // select the required # of cards from the deck randomly let selected_cards = get_random_card_indexes(num_of_cards) .iter() .map(|idx| deck[*idx].clone()) .collect::<Vec<_>>();   // generate all combinations, and filter/keep only which are valid sets let valid_sets = selected_cards .iter() .combinations(3) .filter(|triplet| valid_set(triplet)) .collect::<Vec<_>>();   // if the # of the sets is matching the requirement, print it and finish if valid_sets.len() == minimum_number_of_sets { print!("SELECTED CARDS:"); for card in &selected_cards { print!("\ncard: "); for attr in 0..NUM_ATTRIBUTES { print!("{}, ", ATTRIBUTES[attr][card[attr]]); } }   print!("\nSets:"); for triplet in &valid_sets { print!("\nSet: "); for card in triplet { for attr in 0..NUM_ATTRIBUTES { print!("{}, ", ATTRIBUTES[attr][card[attr]]); } print!(" | "); } }   break; }   //otherwise generate again } } fn main() { run_game(9, 4); run_game(12, 6); }    
http://rosettacode.org/wiki/Set_puzzle
Set puzzle
Set Puzzles are created with a deck of cards from the Set Game™. The object of the puzzle is to find sets of 3 cards in a rectangle of cards that have been dealt face up. There are 81 cards in a deck. Each card contains a unique variation of the following four features: color, symbol, number and shading. there are three colors:    red, green, purple there are three symbols:    oval, squiggle, diamond there is a number of symbols on the card:    one, two, three there are three shadings:    solid, open, striped Three cards form a set if each feature is either the same on each card, or is different on each card. For instance: all 3 cards are red, all 3 cards have a different symbol, all 3 cards have a different number of symbols, all 3 cards are striped. There are two degrees of difficulty: basic and advanced. The basic mode deals 9 cards, that contain exactly 4 sets; the advanced mode deals 12 cards that contain exactly 6 sets. When creating sets you may use the same card more than once. Task Write code that deals the cards (9 or 12, depending on selected mode) from a shuffled deck in which the total number of sets that could be found is 4 (or 6, respectively); and print the contents of the cards and the sets. For instance: DEALT 9 CARDS: green, one, oval, striped green, one, diamond, open green, one, diamond, striped green, one, diamond, solid purple, one, diamond, open purple, two, squiggle, open purple, three, oval, open red, three, oval, open red, three, diamond, solid CONTAINING 4 SETS: green, one, oval, striped purple, two, squiggle, open red, three, diamond, solid green, one, diamond, open green, one, diamond, striped green, one, diamond, solid green, one, diamond, open purple, two, squiggle, open red, three, oval, open purple, one, diamond, open purple, two, squiggle, open purple, three, oval, open
#Tailspin
Tailspin
  def deck: [ { by 1..3 -> (colour: $), by 1..3 -> (symbol: $), by 1..3 -> (number: $), by 1..3 -> (shading: $)} ];   templates deal @: $deck; [ 1..$ -> \($@deal::length -> SYS::randomInt -> ^@deal($ + 1) !\)] ! end deal   templates isSet def set : $; [ $(1).colour::raw + $(2).colour::raw + $(3).colour::raw, $(1).symbol::raw + $(2).symbol::raw + $(3).symbol::raw, $(1).number::raw + $(2).number::raw + $(3).number::raw, $(1).shading::raw + $(2).shading::raw + $(3).shading::raw ] -> # // if it is an array where all elements of 3, 6 or 9, it is a set when <[<=3|=6|=9>+ VOID]> do $set ! end isSet   templates findSets def hand: $; [ 1..$hand::length - 2 -> \(def a: $; $a+1..$hand::length - 1 -> \(def b: $; $b+1..$hand::length -> $hand([$a, $b, $]) ! \) ! \) -> isSet ] ! end findSets   templates setPuzzle def nCards: $(1); def nSets: $(2); {} -> # when <{sets: <[]($nSets..)>}> do $ ! otherwise def hand: $nCards -> deal; {hand: $hand, sets: $hand -> findSets} -> # end setPuzzle   templates formatCard def colours: ['red', 'green', 'purple']; def symbols: ['oval', 'squiggle', 'diamond']; def numbers: ['one', 'two', 'three']; def shadings: ['solid', 'open', 'striped']; $ -> '$colours($.colour);-$symbols($.symbol);-$numbers($.number);-$shadings($.shading);' ! end formatCard   templates formatSets $ -> 'hand: $.hand... -> '$ -> formatCard; '; sets: $.sets... -> '[$... -> ' $ -> formatCard; ';] ';' ! end formatSets   [9,4] -> setPuzzle -> formatSets -> !OUT::write  
http://rosettacode.org/wiki/Set_of_real_numbers
Set of real numbers
All real numbers form the uncountable set ℝ. Among its subsets, relatively simple are the convex sets, each expressed as a range between two real numbers a and b where a ≤ b. There are actually four cases for the meaning of "between", depending on open or closed boundary: [a, b]: {x | a ≤ x and x ≤ b } (a, b): {x | a < x and x < b } [a, b): {x | a ≤ x and x < b } (a, b]: {x | a < x and x ≤ b } Note that if a = b, of the four only [a, a] would be non-empty. Task Devise a way to represent any set of real numbers, for the definition of 'any' in the implementation notes below. Provide methods for these common set operations (x is a real number; A and B are sets): x ∈ A: determine if x is an element of A example: 1 is in [1, 2), while 2, 3, ... are not. A ∪ B: union of A and B, i.e. {x | x ∈ A or x ∈ B} example: [0, 2) ∪ (1, 3) = [0, 3); [0, 1) ∪ (2, 3] = well, [0, 1) ∪ (2, 3] A ∩ B: intersection of A and B, i.e. {x | x ∈ A and x ∈ B} example: [0, 2) ∩ (1, 3) = (1, 2); [0, 1) ∩ (2, 3] = empty set A - B: difference between A and B, also written as A \ B, i.e. {x | x ∈ A and x ∉ B} example: [0, 2) − (1, 3) = [0, 1] Test your implementation by checking if numbers 0, 1, and 2 are in any of the following sets: (0, 1] ∪ [0, 2) [0, 2) ∩ (1, 2] [0, 3) − (0, 1) [0, 3) − [0, 1] Implementation notes 'Any' real set means 'sets that can be expressed as the union of a finite number of convex real sets'. Cantor's set needs not apply. Infinities should be handled gracefully; indeterminate numbers (NaN) can be ignored. You can use your machine's native real number representation, which is probably IEEE floating point, and assume it's good enough (it usually is). Optional work Create a function to determine if a given set is empty (contains no element). Define A = {x | 0 < x < 10 and |sin(π x²)| > 1/2 }, B = {x | 0 < x < 10 and |sin(π x)| > 1/2}, calculate the length of the real axis covered by the set A − B. Note that |sin(π x)| > 1/2 is the same as n + 1/6 < x < n + 5/6 for all integers n; your program does not need to derive this by itself.
#C.23
C#
using System;   namespace RosettaCode.SetOfRealNumbers { public class Set<TValue> { public Set(Predicate<TValue> contains) { Contains = contains; }   public Predicate<TValue> Contains { get; private set; }   public Set<TValue> Union(Set<TValue> set) { return new Set<TValue>(value => Contains(value) || set.Contains(value)); }   public Set<TValue> Intersection(Set<TValue> set) { return new Set<TValue>(value => Contains(value) && set.Contains(value)); }   public Set<TValue> Difference(Set<TValue> set) { return new Set<TValue>(value => Contains(value) && !set.Contains(value)); } } }
http://rosettacode.org/wiki/Sieve_of_Eratosthenes
Sieve of Eratosthenes
This task has been clarified. Its programming examples are in need of review to ensure that they still fit the requirements of the task. The Sieve of Eratosthenes is a simple algorithm that finds the prime numbers up to a given integer. Task Implement the   Sieve of Eratosthenes   algorithm, with the only allowed optimization that the outer loop can stop at the square root of the limit, and the inner loop may start at the square of the prime just found. That means especially that you shouldn't optimize by using pre-computed wheels, i.e. don't assume you need only to cross out odd numbers (wheel based on 2), numbers equal to 1 or 5 modulo 6 (wheel based on 2 and 3), or similar wheels based on low primes. If there's an easy way to add such a wheel based optimization, implement it as an alternative version. Note It is important that the sieve algorithm be the actual algorithm used to find prime numbers for the task. Related tasks   Emirp primes   count in factors   prime decomposition   factors of an integer   extensible prime generator   primality by trial division   factors of a Mersenne number   trial factoring of a Mersenne number   partition an integer X into N primes   sequence of primes by Trial Division
#68000_Assembly
68000 Assembly
*----------------------------------------------------------- * Title  : BitSieve * Written by : G. A. Tippery * Date  : 2014-Feb-24, 2013-Dec-22 * Description: Prime number sieve *----------------------------------------------------------- ORG $1000   ** ---- Generic macros ---- ** PUSH MACRO MOVE.L \1,-(SP) ENDM   POP MACRO MOVE.L (SP)+,\1 ENDM   DROP MACRO ADDQ #4,SP ENDM   PUTS MACRO ** Print a null-terminated string w/o CRLF ** ** Usage: PUTS stringaddress ** Returns with D0, A1 modified MOVEQ #14,D0 ; task number 14 (display null string) LEA \1,A1 ; address of string TRAP #15 ; display it ENDM   GETN MACRO MOVEQ #4,D0 ; Read a number from the keyboard into D1.L. TRAP #15 ENDM   ** ---- Application-specific macros ---- **   val MACRO ; Used by bit sieve. Converts bit address to the number it represents. ADD.L \1,\1 ; double it because odd numbers are omitted ADDQ #3,\1 ; add offset because initial primes (1, 2) are omitted ENDM   * ** ================================================================================ ** * ** Integer square root routine, bisection method ** * ** IN: D0, should be 0<D0<$10000 (65536) -- higher values MAY work, no guarantee * ** OUT: D1 * SquareRoot: * MOVEM.L D2-D4,-(SP) ; save registers needed for local variables * DO == n * D1 == a * D2 == b * D3 == guess * D4 == temp * * a = 1; * b = n; MOVEQ #1,D1 MOVE.L D0,D2 * do { REPEAT * guess = (a+b)/2; MOVE.L D1,D3 ADD.L D2,D3 LSR.L #1,D3 * if (guess*guess > n) { // inverse function of sqrt is square MOVE.L D3,D4 MULU D4,D4 ; guess^2 CMP.L D0,D4 BLS .else * b = guess; MOVE.L D3,D2 BRA .endif * } else { .else: * a = guess; MOVE.L D3,D1 * } //if .endif: * } while ((b-a) > 1); ; Same as until (b-a)<=1 or until (a-b)>=1 MOVE.L D2,D4 SUB.L D1,D4 ; b-a UNTIL.L D4 <LE> #1 DO.S * return (a) ; Result is in D1 * } //LongSqrt() MOVEM.L (SP)+,D2-D4 ; restore saved registers RTS * * ** ================================================================================ **     ** ======================================================================= ** * ** Prime-number Sieve of Eratosthenes routine using a big bit field for flags ** * Enter with D0 = size of sieve (bit array) * Prints found primes 10 per line * Returns # prime found in D6 * * Register usage: * * D0 == n * D1 == prime * D2 == sqroot * D3 == PIndex * D4 == CIndex * D5 == MaxIndex * D6 == PCount * * A0 == PMtx[0] * * On return, all registers above except D0 are modified. Could add MOVEMs to save and restore D2-D6/A0. *   ** ------------------------ **   GetBit: ** sub-part of Sieve subroutine ** ** Entry: bit # is on TOS ** Exit: A6 holds the byte number, D7 holds the bit number within the byte ** Note: Input param is still on TOS after return. Could have passed via a register, but ** wanted to practice with stack. :) * MOVE.L (4,SP),D7 ; get value from (pre-call) TOS ASR.L #3,D7 ; /8 MOVEA D7,A6 ; byte # MOVE.L (4,SP),D7 ; get value from (pre-call) TOS AND.L #$7,D7 ; bit # RTS   ** ------------------------ **   Sieve: MOVE D0,D5 SUBQ #1,D5 JSR SquareRoot ; sqrt D0 => D1 MOVE.L D1,D2 LEA PArray,A0 CLR.L D3 * PrimeLoop: MOVE.L D3,D1 val D1 MOVE.L D3,D4 ADD.L D1,D4 * CxLoop: ; Goes through array marking multiples of d1 as composite numbers CMP.L D5,D4 BHI ExitCx PUSH D4 ; set D7 as bit # and A6 as byte pointer for D4'th bit of array JSR GetBit DROP BSET D7,0(A0,A6.L) ; set bit to mark as composite number ADD.L D1,D4 ; next number to mark BRA CxLoop ExitCx: CLR.L D1 ; Clear new-prime-found flag ADDQ #1,D3 ; Start just past last prime found PxLoop: ; Searches for next unmarked (not composite) number CMP.L D2,D3 ; no point searching past where first unmarked multiple would be past end of array BHI ExitPx ; if past end of array TST.L D1 BNE ExitPx ; if flag set, new prime found PUSH D3 ; check D3'th bit flag JSR GetBit ; sets D7 as bit # and A6 as byte pointer DROP ; drop TOS BTST D7,0(A0,A6.L) ; read bit flag BNE IsSet ; If already tagged as composite MOVEQ #-1,D1 ; Set flag that we've found a new prime IsSet: ADDQ #1,D3 ; next PIndex BRA PxLoop ExitPx: SUBQ #1,D3 ; back up PIndex TST.L D1 ; Did we find a new prime #? BNE PrimeLoop ; If another prime # found, go process it * ; fall through to print routine   ** ------------------------ **   * Print primes found * * D4 == Column count * * Print header and assumed primes (#1, #2) PUTS Header ; Print string @ Header, no CR/LF MOVEQ #2,D6 ; Start counter at 2 because #1 and #2 are assumed primes MOVEQ #2,D4 * MOVEQ #0,D3 PrintLoop: CMP.L D5,D3 BHS ExitPL PUSH D3 JSR GetBit ; sets D7 as bit # and A6 as byte pointer DROP ; drop TOS BTST D7,0(A0,A6.L) BNE NotPrime * printf(" %6d", val(PIndex) MOVE.L D3,D1 val D1 AND.L #$0000FFFF,D1 MOVEQ #6,D2 MOVEQ #20,D0 ; display signed RJ TRAP #15 ADDQ #1,D4 ADDQ #1,D6 * *** Display formatting *** * if((PCount % 10) == 0) printf("\n"); CMP #10,D4 BLO NoLF PUTS CRLF MOVEQ #0,D4 NoLF: NotPrime: ADDQ #1,D3 BRA PrintLoop ExitPL: RTS   ** ======================================================================= **   N EQU 5000 ; *** Size of boolean (bit) array *** SizeInBytes EQU (N+7)/8 * START: ; first instruction of program MOVE.L #N,D0 ; # to test JSR Sieve * printf("\n %d prime numbers found.\n", D6); *** PUTS Summary1,A1 MOVE #3,D0 ; Display signed number in D1.L in decimal in smallest field. MOVE.W D6,D1 TRAP #15 PUTS Summary2,A1   SIMHALT ; halt simulator   ** ======================================================================= **   * Variables and constants here   ORG $2000 CR EQU 13 LF EQU 10 CRLF DC.B CR,LF,$00   PArray: DCB.B SizeInBytes,0   Header: DC.B CR,LF,LF,' Primes',CR,LF,' ======',CR,LF DC.B ' 1 2',$00   Summary1: DC.B CR,LF,' ',$00 Summary2: DC.B ' prime numbers found.',CR,LF,$00   END START ; last line of source
http://rosettacode.org/wiki/Sequence_of_primorial_primes
Sequence of primorial primes
The sequence of primorial primes is given as the increasing values of n where primorial(n) ± 1 is prime. Noting that the n'th primorial is defined as the multiplication of the smallest n primes, the sequence is of the number of primes, in order that when multiplied together is one-off being a prime number itself. Task Generate and show here the first ten values of the sequence. Optional extended task Show the first twenty members of the series. Notes This task asks for the primorial indices that create the final primorial prime numbers, so there should be no ten-or-more digit numbers in the program output (although extended precision integers will be needed for intermediate results). There is some confusion in the references, but for the purposes of this task the sequence begins with n = 1. Probabilistic primality tests are allowed, as long as they are good enough such that the output shown is correct. Related tasks Primorial numbers Factorial See also Primorial prime Wikipedia. Primorial prime from The Prime Glossary. Sequence A088411 from The On-Line Encyclopedia of Integer Sequences
#Clojure
Clojure
  (ns example (:gen-class))   ; Lazy Sequence of primes (starting with number 2) (def primes (iterate #(.nextProbablePrime %) (biginteger 2)))   (defn primorial-prime? [v] " Test if value is a primorial prime " (let [a (biginteger (inc v)) b (biginteger (dec v))] (or (.isProbablePrime a 16) (.isProbablePrime b 16))))   ; Generate indexes for first 20 primorial primes (println (take 20 (keep-indexed ; take the first 20 #(if (primorial-prime? %2) (inc %1)) ; filters out non-primorials, passing on the index + 1 (since sequence begins with 1 (not 0) (reductions *' primes)))) ; computes the lazy sequence of product of 1 prime, 2 primes, 3 primes, etc.    
http://rosettacode.org/wiki/Sequence:_nth_number_with_exactly_n_divisors
Sequence: nth number with exactly n divisors
Calculate the sequence where each term an is the nth that has n divisors. Task Show here, on this page, at least the first 15 terms of the sequence. See also OEIS:A073916 Related tasks Sequence: smallest number greater than previous term with exactly n divisors Sequence: smallest number with exactly n divisors
#Haskell
Haskell
import Control.Monad (guard) import Math.NumberTheory.ArithmeticFunctions (divisorCount) import Math.NumberTheory.Primes (Prime, unPrime) import Math.NumberTheory.Primes.Testing (isPrime)   calc :: Integer -> [(Integer, Integer)] calc n = do x <- [1..] guard (even n || odd n && f x == x) [(x, divisorCount x)] where f n = floor (sqrt $ realToFrac n) ^ 2   havingNthDivisors :: Integer -> [(Integer, Integer)] havingNthDivisors n = filter ((==n) . snd) $ calc n   nths :: [(Integer, Integer)] nths = do n <- [1..35] :: [Integer] if isPrime n then pure (n, nthPrime (fromIntegral n) ^ pred n) else pure (n, f n) where f n = fst (havingNthDivisors n !! pred (fromIntegral n)) nthPrime n = unPrime (toEnum n :: Prime Integer)   main :: IO () main = mapM_ print nths
http://rosettacode.org/wiki/Set_consolidation
Set consolidation
Given two sets of items then if any item is common to any set then the result of applying consolidation to those sets is a set of sets whose contents is: The two input sets if no common item exists between the two input sets of items. The single set that is the union of the two input sets if they share a common item. Given N sets of items where N>2 then the result is the same as repeatedly replacing all combinations of two sets by their consolidation until no further consolidation between set pairs is possible. If N<2 then consolidation has no strict meaning and the input can be returned. Example 1: Given the two sets {A,B} and {C,D} then there is no common element between the sets and the result is the same as the input. Example 2: Given the two sets {A,B} and {B,D} then there is a common element B between the sets and the result is the single set {B,D,A}. (Note that order of items in a set is immaterial: {A,B,D} is the same as {B,D,A} and {D,A,B}, etc). Example 3: Given the three sets {A,B} and {C,D} and {D,B} then there is no common element between the sets {A,B} and {C,D} but the sets {A,B} and {D,B} do share a common element that consolidates to produce the result {B,D,A}. On examining this result with the remaining set, {C,D}, they share a common element and so consolidate to the final output of the single set {A,B,C,D} Example 4: The consolidation of the five sets: {H,I,K}, {A,B}, {C,D}, {D,B}, and {F,G,H} Is the two sets: {A, C, B, D}, and {G, F, I, H, K} See also Connected component (graph theory) Range consolidation
#EchoLisp
EchoLisp
  ;; utility : make a set of sets from a list (define (make-set* s) (or (when (list? s) (make-set (map make-set* s))) s))   ;; union of all sets which intersect - O(n^2) (define (make-big ss) (make-set (for/list ((u ss)) (for/fold (big u) ((v ss)) #:when (set-intersect? big v) (set-union big v)))))   ;; remove sets which are subset of another one - O(n^2) (define (remove-small ss) (for/list ((keep ss)) #:when (for/and ((v ss)) #:continue (set-equal? keep v) (not (set-subset? v keep))) keep))   (define (consolidate ss) (make-set (remove-small (make-big ss))))   (define S (make-set* ' ((h i k) ( a b) ( b c) (c d) ( f g h)))) → { { a b } { b c } { c d } { f g h } { h i k } }   (consolidate S) → { { a b c d } { f g h i k } }    
http://rosettacode.org/wiki/Sequence:_smallest_number_with_exactly_n_divisors
Sequence: smallest number with exactly n divisors
Calculate the sequence where each term   an   is the smallest natural number that has exactly   n   divisors. Task Show here, on this page, at least the first  15  terms of the sequence. Related tasks Sequence: smallest number greater than previous term with exactly n divisors Sequence: nth number with exactly n divisors‎‎ See also OEIS:A005179
#Go
Go
package main   import "fmt"   func countDivisors(n int) int { count := 0 for i := 1; i*i <= n; i++ { if n%i == 0 { if i == n/i { count++ } else { count += 2 } } } return count }   func main() { const max = 15 seq := make([]int, max) fmt.Println("The first", max, "terms of the sequence are:") for i, n := 1, 0; n < max; i++ { if k := countDivisors(i); k <= max && seq[k-1] == 0 { seq[k-1] = i n++ } } fmt.Println(seq) }
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
#Mathematica.2FWolfram_Language
Mathematica/Wolfram Language
Hash["Rosetta code","SHA256","HexString"]
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
#min
min
"Rosetta code" sha256 puts!
http://rosettacode.org/wiki/Sequence:_smallest_number_greater_than_previous_term_with_exactly_n_divisors
Sequence: smallest number greater than previous term with exactly n divisors
Calculate the sequence where each term an is the smallest natural number greater than the previous term, that has exactly n divisors. Task Show here, on this page, at least the first 15 terms of the sequence. See also OEIS:A069654 Related tasks Sequence: smallest number with exactly n divisors Sequence: nth number with exactly n divisors‎‎
#Java
Java
public class AntiPrimesPlus {   static int count_divisors(int n) { int count = 0; for (int i = 1; i * i <= n; ++i) { if (n % i == 0) { if (i == n / i) count++; else count += 2; } } return count; }   public static void main(String[] args) { final int max = 15; System.out.printf("The first %d terms of the sequence are:\n", max); for (int i = 1, next = 1; next <= max; ++i) { if (next == count_divisors(i)) { System.out.printf("%d ", i); next++; } } System.out.println(); } }
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.
#min
min
"Rosetta Code" sha1 puts!
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.
#Neko
Neko
/** SHA-1 in Neko Tectonics: nekoc SHA-1.neko neko SHA-1 */   var SHA1 = $loader.loadprim("std@make_sha1", 3); var base_encode = $loader.loadprim("std@base_encode", 2);   var msg = "Rosetta Code"; var result = SHA1(msg, 0, $ssize(msg));   /* Output in lowercase hex */ $print(base_encode(result, "0123456789abcdef"));
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)
#Racket
Racket
  #lang racket (define (dice5) (add1 (random 5)))   (define (dice7) (define res (+ (* 5 (dice5)) (dice5) -6)) (if (< res 21) (+ 1 (modulo res 7)) (dice7)))  
http://rosettacode.org/wiki/Seven-sided_dice_from_five-sided_dice
Seven-sided dice from five-sided dice
Task (Given an equal-probability generator of one of the integers 1 to 5 as dice5),   create dice7 that generates a pseudo-random integer from 1 to 7 in equal probability using only dice5 as a source of random numbers,   and check the distribution for at least one million calls using the function created in   Simple Random Distribution Checker. Implementation suggestion: dice7 might call dice5 twice, re-call if four of the 25 combinations are given, otherwise split the other 21 combinations into 7 groups of three, and return the group index from the rolls. (Task adapted from an answer here)
#Raku
Raku
my $d5 = 1..5; sub d5() { $d5.roll; } # 1d5   sub d7() { my $flat = 21; $flat = 5 * d5() - d5() until $flat < 21; $flat % 7 + 1; }   # Testing my @dist; my $n = 1_000_000; my $expect = $n / 7;   loop ($_ = $n; $n; --$n) { @dist[d7()]++; }   say "Expect\t",$expect.fmt("%.3f"); for @dist.kv -> $i, $v { say "$i\t$v\t" ~ (($v - $expect)/$expect*100).fmt("%+.2f%%") if $v; }
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
#IS-BASIC
IS-BASIC
100 TEXT 80 110 FOR R=0 TO 15 120 FOR C=32+R TO 112+R STEP 16 130 PRINT USING "###":C;:PRINT ": ";CHR$(C), 140 NEXT 150 PRINT 160 NEXT
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
#PicoLisp
PicoLisp
(de sierpinski (N) (let (D '("*") S " ") (do N (setq D (conc (mapcar '((X) (pack S X S)) D) (mapcar '((X) (pack X " " X)) D) ) S (pack S S) ) ) D ) )   (mapc prinl (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
#Liberty_BASIC
Liberty BASIC
NoMainWin WindowWidth = 508 WindowHeight = 575 Open "Sierpinski Carpets" For Graphics_nsb_nf As #g #g "Down; TrapClose [halt]"   'labels #g "Place 90 15;\Order 0" #g "Place 340 15;\Order 1" #g "Place 90 286;\Order 2" #g "Place 340 286;\Order 3" 'carpets Call carpet 5, 20, 243, 0 Call carpet 253, 20, 243, 1 Call carpet 5, 293, 243, 2 Call carpet 253, 293, 243, 3 #g "Flush" Wait   [halt] Close #g End   Sub carpet x, y, size, order #g "Color 0 0 128; BackColor 0 0 128" #g "Place ";x;" ";y #g "BoxFilled ";x+size-1;" ";y+size-1 #g "Color white; BackColor white" side = Int(size/3) newX = x+side newY = y+side #g "Place ";newX;" ";newY #g "BoxFilled ";newX+side-1;" ";newY+side-1 order = order - 1 If order > -1 Then Call carpet newX-side, newY-side+1, side, order Call carpet newX, newY-side+1, side, order Call carpet newX+side, newY-side+1, side, order Call carpet newX+side, newY, side, order Call carpet newX+side, newY+side, side, order Call carpet newX, newY+side, side, order Call carpet newX-side, newY+side, side, order Call carpet newX-side, newY, side, order End If End Sub
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.
#Ol
Ol
  (define (a x) (print " (a) => " x) x)   (define (b x) (print " (b) => " x) x)   ; and (print " -- and -- ") (for-each (lambda (x y) (print "let's evaluate '(a as " x ") and (b as " y ")':") (let ((out (and (a x) (b y)))) (print " result is " out))) '(#t #t #f #f) '(#t #f #t #f))   ; or (print " -- or -- ") (for-each (lambda (x y) (print "let's evaluate '(a as " x ") or (b as " y ")':") (let ((out (or (a x) (b y)))) (print " result is " out))) '(#t #t #f #f) '(#t #f #t #f))  
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
#Tcl
Tcl
# Generate random integer uniformly on range [0..$n-1] proc random n {expr {int(rand() * $n)}}   # Generate a shuffled deck of all cards; the card encoding was stolen from the # Perl6 solution. This is done once and then used as a constant. Note that the # rest of the code assumes that all cards in the deck are unique. set ::AllCards [apply {{} { set cards {} foreach color {1 2 4} { foreach symbol {1 2 4} { foreach number {1 2 4} { foreach shading {1 2 4} { lappend cards [list $color $symbol $number $shading] } } } } # Knuth-Morris-Pratt shuffle (not that it matters) for {set i [llength $cards]} {$i > 0} {} { set j [random $i] set tmp [lindex $cards [incr i -1]] lset cards $i [lindex $cards $j] lset cards $j $tmp } return $cards }}]   # Randomly pick a hand of cards from the deck (itself in a global for # convenience). proc drawCards n { set cards $::AllCards; # Copies... for {set i 0} {$i < $n} {incr i} { set idx [random [llength $cards]] lappend hand [lindex $cards $idx] set cards [lreplace $cards $idx $idx] } return $hand }   # Test if a particular group of three cards is a valid set proc isValidSet {a b c} { expr { ([lindex $a 0]|[lindex $b 0]|[lindex $c 0]) in {1 2 4 7} && ([lindex $a 1]|[lindex $b 1]|[lindex $c 1]) in {1 2 4 7} && ([lindex $a 2]|[lindex $b 2]|[lindex $c 2]) in {1 2 4 7} && ([lindex $a 3]|[lindex $b 3]|[lindex $c 3]) in {1 2 4 7} } }   # Get all unique valid sets of three cards in a hand. proc allValidSets {hand} { set sets {} for {set i 0} {$i < [llength $hand]} {incr i} { set a [lindex $hand $i] set hand [set cards2 [lreplace $hand $i $i]] for {set j 0} {$j < [llength $cards2]} {incr j} { set b [lindex $cards2 $j] set cards2 [set cards3 [lreplace $cards2 $j $j]] foreach c $cards3 { if {[isValidSet $a $b $c]} { lappend sets [list $a $b $c] } } } } return $sets }   # Solve a particular version of the set puzzle, by picking random hands until # one is found that satisfies the constraints. This is usually much faster # than a systematic search. On success, returns the hand found and the card # sets within that hand. proc SetPuzzle {numCards numSets} { while 1 { set hand [drawCards $numCards] set sets [allValidSets $hand] if {[llength $sets] == $numSets} { break } } return [list $hand $sets] }
http://rosettacode.org/wiki/Set_of_real_numbers
Set of real numbers
All real numbers form the uncountable set ℝ. Among its subsets, relatively simple are the convex sets, each expressed as a range between two real numbers a and b where a ≤ b. There are actually four cases for the meaning of "between", depending on open or closed boundary: [a, b]: {x | a ≤ x and x ≤ b } (a, b): {x | a < x and x < b } [a, b): {x | a ≤ x and x < b } (a, b]: {x | a < x and x ≤ b } Note that if a = b, of the four only [a, a] would be non-empty. Task Devise a way to represent any set of real numbers, for the definition of 'any' in the implementation notes below. Provide methods for these common set operations (x is a real number; A and B are sets): x ∈ A: determine if x is an element of A example: 1 is in [1, 2), while 2, 3, ... are not. A ∪ B: union of A and B, i.e. {x | x ∈ A or x ∈ B} example: [0, 2) ∪ (1, 3) = [0, 3); [0, 1) ∪ (2, 3] = well, [0, 1) ∪ (2, 3] A ∩ B: intersection of A and B, i.e. {x | x ∈ A and x ∈ B} example: [0, 2) ∩ (1, 3) = (1, 2); [0, 1) ∩ (2, 3] = empty set A - B: difference between A and B, also written as A \ B, i.e. {x | x ∈ A and x ∉ B} example: [0, 2) − (1, 3) = [0, 1] Test your implementation by checking if numbers 0, 1, and 2 are in any of the following sets: (0, 1] ∪ [0, 2) [0, 2) ∩ (1, 2] [0, 3) − (0, 1) [0, 3) − [0, 1] Implementation notes 'Any' real set means 'sets that can be expressed as the union of a finite number of convex real sets'. Cantor's set needs not apply. Infinities should be handled gracefully; indeterminate numbers (NaN) can be ignored. You can use your machine's native real number representation, which is probably IEEE floating point, and assume it's good enough (it usually is). Optional work Create a function to determine if a given set is empty (contains no element). Define A = {x | 0 < x < 10 and |sin(π x²)| > 1/2 }, B = {x | 0 < x < 10 and |sin(π x)| > 1/2}, calculate the length of the real axis covered by the set A − B. Note that |sin(π x)| > 1/2 is the same as n + 1/6 < x < n + 5/6 for all integers n; your program does not need to derive this by itself.
#C.2B.2B
C++
#include <cassert> #include <functional> #include <iostream>   #define _USE_MATH_DEFINES #include <math.h>   enum RangeType { CLOSED, BOTH_OPEN, LEFT_OPEN, RIGHT_OPEN };   class RealSet { private: double low, high; double interval = 0.00001; std::function<bool(double)> predicate;   public: RealSet(double low, double high, const std::function<bool(double)>& predicate) { this->low = low; this->high = high; this->predicate = predicate; }   RealSet(double start, double end, RangeType rangeType) { low = start; high = end;   switch (rangeType) { case CLOSED: predicate = [start, end](double d) { return start <= d && d <= end; }; break; case BOTH_OPEN: predicate = [start, end](double d) { return start < d && d < end; }; break; case LEFT_OPEN: predicate = [start, end](double d) { return start < d && d <= end; }; break; case RIGHT_OPEN: predicate = [start, end](double d) { return start <= d && d < end; }; break; default: assert(!"Unexpected range type encountered."); } }   bool contains(double d) const { return predicate(d); }   RealSet unionSet(const RealSet& rhs) const { double low2 = fmin(low, rhs.low); double high2 = fmax(high, rhs.high); return RealSet( low2, high2, [this, &rhs](double d) { return predicate(d) || rhs.predicate(d); } ); }   RealSet intersect(const RealSet& rhs) const { double low2 = fmin(low, rhs.low); double high2 = fmax(high, rhs.high); return RealSet( low2, high2, [this, &rhs](double d) { return predicate(d) && rhs.predicate(d); } ); }   RealSet subtract(const RealSet& rhs) const { return RealSet( low, high, [this, &rhs](double d) { return predicate(d) && !rhs.predicate(d); } ); }   double length() const { if (isinf(low) || isinf(high)) return -1.0; // error value if (high <= low) return 0.0;   double p = low; int count = 0; do { if (predicate(p)) count++; p += interval; } while (p < high); return count * interval; }   bool empty() const { if (high == low) { return !predicate(low); } return length() == 0.0; } };   int main() { using namespace std;   RealSet a(0.0, 1.0, LEFT_OPEN); RealSet b(0.0, 2.0, RIGHT_OPEN); RealSet c(1.0, 2.0, LEFT_OPEN); RealSet d(0.0, 3.0, RIGHT_OPEN); RealSet e(0.0, 1.0, BOTH_OPEN); RealSet f(0.0, 1.0, CLOSED); RealSet g(0.0, 0.0, CLOSED);   for (int i = 0; i <= 2; ++i) { cout << "(0, 1] ∪ [0, 2) contains " << i << " is " << boolalpha << a.unionSet(b).contains(i) << "\n"; cout << "[0, 2) ∩ (1, 2] contains " << i << " is " << boolalpha << b.intersect(c).contains(i) << "\n"; cout << "[0, 3) - (0, 1) contains " << i << " is " << boolalpha << d.subtract(e).contains(i) << "\n"; cout << "[0, 3) - [0, 1] contains " << i << " is " << boolalpha << d.subtract(f).contains(i) << "\n"; cout << endl; }   cout << "[0, 0] is empty is " << boolalpha << g.empty() << "\n"; cout << endl;   RealSet aa( 0.0, 10.0, [](double x) { return (0.0 < x && x < 10.0) && abs(sin(M_PI * x * x)) > 0.5; } ); RealSet bb( 0.0, 10.0, [](double x) { return (0.0 < x && x < 10.0) && abs(sin(M_PI * x)) > 0.5; } ); auto cc = aa.subtract(bb); cout << "Approximate length of A - B is " << cc.length() << endl;   return 0; }
http://rosettacode.org/wiki/Sieve_of_Eratosthenes
Sieve of Eratosthenes
This task has been clarified. Its programming examples are in need of review to ensure that they still fit the requirements of the task. The Sieve of Eratosthenes is a simple algorithm that finds the prime numbers up to a given integer. Task Implement the   Sieve of Eratosthenes   algorithm, with the only allowed optimization that the outer loop can stop at the square root of the limit, and the inner loop may start at the square of the prime just found. That means especially that you shouldn't optimize by using pre-computed wheels, i.e. don't assume you need only to cross out odd numbers (wheel based on 2), numbers equal to 1 or 5 modulo 6 (wheel based on 2 and 3), or similar wheels based on low primes. If there's an easy way to add such a wheel based optimization, implement it as an alternative version. Note It is important that the sieve algorithm be the actual algorithm used to find prime numbers for the task. Related tasks   Emirp primes   count in factors   prime decomposition   factors of an integer   extensible prime generator   primality by trial division   factors of a Mersenne number   trial factoring of a Mersenne number   partition an integer X into N primes   sequence of primes by Trial Division
#8086_Assembly
8086 Assembly
MAXPRM: equ 5000 ; Change this value for more primes cpu 8086 bits 16 org 100h section .text erato: mov cx,MAXPRM ; Initialize array (set all items to prime) mov bp,cx ; Keep a copy in BP mov di,sieve mov al,1 rep stosb ;;; Sieve mov bx,sieve ; Set base register to array inc cx ; CX=1 (CH=0, CL=1); CX was 0 before mov si,cx ; Start at number 2 (1+1) .next: inc si ; Next number cmp cl,[bx+si] ; Is this number marked as prime? jne .next ; If not, try next number mov ax,si ; Otherwise, calculate square, mul si mov di,ax ; and put it in DI cmp di,bp ; Check array bounds ja output ; We're done when SI*SI>MAXPRM .mark: mov [bx+di],ch ; Mark byte as composite add di,si ; Next composite cmp di,bp ; While maximum not reached jbe .mark jmp .next ;;; Output output: mov si,2 ; Start at 2 .test: dec byte [bx+si] ; Prime? jnz .next ; If not, try next number mov ax,si ; Otherwise, print number call prax .next: inc si cmp si,MAXPRM jbe .test ret ;;; Write number in AX to standard output (using MS-DOS) prax: push bx ; Save BX mov bx,numbuf mov bp,10 ; Divisor .loop: xor dx,dx ; Divide AX by 10, modulus in DX div bp add dl,'0' ; ASCII digit dec bx mov [bx],dl ; Store ASCII digit test ax,ax ; More digits? jnz .loop mov dx,bx ; Print number mov ah,9 ; 9 = MS-DOS syscall to print string int 21h pop bx ; Restore BX ret section .data db '*****' ; Room for number numbuf: db 13,10,'$' section .bss sieve: resb MAXPRM
http://rosettacode.org/wiki/Sequence_of_primorial_primes
Sequence of primorial primes
The sequence of primorial primes is given as the increasing values of n where primorial(n) ± 1 is prime. Noting that the n'th primorial is defined as the multiplication of the smallest n primes, the sequence is of the number of primes, in order that when multiplied together is one-off being a prime number itself. Task Generate and show here the first ten values of the sequence. Optional extended task Show the first twenty members of the series. Notes This task asks for the primorial indices that create the final primorial prime numbers, so there should be no ten-or-more digit numbers in the program output (although extended precision integers will be needed for intermediate results). There is some confusion in the references, but for the purposes of this task the sequence begins with n = 1. Probabilistic primality tests are allowed, as long as they are good enough such that the output shown is correct. Related tasks Primorial numbers Factorial See also Primorial prime Wikipedia. Primorial prime from The Prime Glossary. Sequence A088411 from The On-Line Encyclopedia of Integer Sequences
#EchoLisp
EchoLisp
  (lib 'timer) ;; for (every (proc t) interval) (lib 'bigint)   ;; memoize primorial (define p1000 (cons 1 (primes 1000))) ; remember first 1000 primes (define (primorial n) (if(zero? n) 1 (* (list-ref p1000 n) (primorial (1- n))))) (remember 'primorial)   (define N 0)   ;; search one at a time (define (search t) ;; time parameter, set by (every), not used (set! N (1+ N)) (if (or (prime? (1+ (primorial N))) (prime? (1- (primorial N)))) (writeln 'HIT N ) (writeln N (date->time-string (current-date )))))  
http://rosettacode.org/wiki/Sequence_of_primorial_primes
Sequence of primorial primes
The sequence of primorial primes is given as the increasing values of n where primorial(n) ± 1 is prime. Noting that the n'th primorial is defined as the multiplication of the smallest n primes, the sequence is of the number of primes, in order that when multiplied together is one-off being a prime number itself. Task Generate and show here the first ten values of the sequence. Optional extended task Show the first twenty members of the series. Notes This task asks for the primorial indices that create the final primorial prime numbers, so there should be no ten-or-more digit numbers in the program output (although extended precision integers will be needed for intermediate results). There is some confusion in the references, but for the purposes of this task the sequence begins with n = 1. Probabilistic primality tests are allowed, as long as they are good enough such that the output shown is correct. Related tasks Primorial numbers Factorial See also Primorial prime Wikipedia. Primorial prime from The Prime Glossary. Sequence A088411 from The On-Line Encyclopedia of Integer Sequences
#Factor
Factor
USING: kernel lists lists.lazy math math.primes prettyprint sequences ;   : pprime? ( n -- ? ) nprimes product [ 1 + ] [ 1 - ] bi [ prime? ] either? ;   10 1 lfrom [ pprime? ] <lazy-filter> ltake list>array .
http://rosettacode.org/wiki/Sequence:_nth_number_with_exactly_n_divisors
Sequence: nth number with exactly n divisors
Calculate the sequence where each term an is the nth that has n divisors. Task Show here, on this page, at least the first 15 terms of the sequence. See also OEIS:A073916 Related tasks Sequence: smallest number greater than previous term with exactly n divisors Sequence: smallest number with exactly n divisors
#J
J
  A073916=: {{ if.1 p: y do. (p:^x:)y-1 return. elseif.1|y do. f= *: else. f=. ] end. r=.i.0 off=. 1 while. y>#r do. r=. r,f off+I.y=*/|:1+_ q:f off+i.y off=. off+y end. (y-1){r }}"0  
http://rosettacode.org/wiki/Sequence:_nth_number_with_exactly_n_divisors
Sequence: nth number with exactly n divisors
Calculate the sequence where each term an is the nth that has n divisors. Task Show here, on this page, at least the first 15 terms of the sequence. See also OEIS:A073916 Related tasks Sequence: smallest number greater than previous term with exactly n divisors Sequence: smallest number with exactly n divisors
#Java
Java
  import java.math.BigInteger; import java.util.ArrayList; import java.util.List;   public class SequenceNthNumberWithExactlyNDivisors {   public static void main(String[] args) { int max = 45; smallPrimes(max); for ( int n = 1; n <= max ; n++ ) { System.out.printf("A073916(%d) = %s%n", n, OEISA073916(n)); } }   private static List<Integer> smallPrimes = new ArrayList<>();   private static void smallPrimes(int numPrimes) { smallPrimes.add(2); for ( int n = 3, count = 0 ; count < numPrimes ; n += 2 ) { if ( isPrime(n) ) { smallPrimes.add(n); count++; } } }   private static final boolean isPrime(long test) { if ( test == 2 ) { return true; } if ( test % 2 == 0 ) { return false; } for ( long d = 3 ; d*d <= test ; d += 2 ) { if ( test % d == 0 ) { return false; } } return true; }   private static int getDivisorCount(long n) { int count = 1; while ( n % 2 == 0 ) { n /= 2; count += 1; } for ( long d = 3 ; d*d <= n ; d += 2 ) { long q = n / d; long r = n % d; int dc = 0; while ( r == 0 ) { dc += count; n = q; q = n / d; r = n % d; } count += dc; } if ( n != 1 ) { count *= 2; } return count; }   private static BigInteger OEISA073916(int n) { if ( isPrime(n) ) { return BigInteger.valueOf(smallPrimes.get(n-1)).pow(n - 1); } int count = 0; int result = 0; for ( int i = 1 ; count < n ; i++ ) { if ( n % 2 == 1 ) { // The solution for an odd (non-prime) term is always a square number int sqrt = (int) Math.sqrt(i); if ( sqrt*sqrt != i ) { continue; } } if ( getDivisorCount(i) == n ) { count++; result = i; } } return BigInteger.valueOf(result); }   }  
http://rosettacode.org/wiki/Set_consolidation
Set consolidation
Given two sets of items then if any item is common to any set then the result of applying consolidation to those sets is a set of sets whose contents is: The two input sets if no common item exists between the two input sets of items. The single set that is the union of the two input sets if they share a common item. Given N sets of items where N>2 then the result is the same as repeatedly replacing all combinations of two sets by their consolidation until no further consolidation between set pairs is possible. If N<2 then consolidation has no strict meaning and the input can be returned. Example 1: Given the two sets {A,B} and {C,D} then there is no common element between the sets and the result is the same as the input. Example 2: Given the two sets {A,B} and {B,D} then there is a common element B between the sets and the result is the single set {B,D,A}. (Note that order of items in a set is immaterial: {A,B,D} is the same as {B,D,A} and {D,A,B}, etc). Example 3: Given the three sets {A,B} and {C,D} and {D,B} then there is no common element between the sets {A,B} and {C,D} but the sets {A,B} and {D,B} do share a common element that consolidates to produce the result {B,D,A}. On examining this result with the remaining set, {C,D}, they share a common element and so consolidate to the final output of the single set {A,B,C,D} Example 4: The consolidation of the five sets: {H,I,K}, {A,B}, {C,D}, {D,B}, and {F,G,H} Is the two sets: {A, C, B, D}, and {G, F, I, H, K} See also Connected component (graph theory) Range consolidation
#Egison
Egison
  (define $consolidate (lambda [$xss] (match xss (multiset (set char)) {[<cons <cons $m $xs> <cons <cons ,m $ys> $rss>> (consolidate {(unique/m char {m @xs @ys}) @rss})] [_ xss]})))   (test (consolidate {{'H' 'I' 'K'} {'A' 'B'} {'C' 'D'} {'D' 'B'} {'F' 'G' 'H'}}))  
http://rosettacode.org/wiki/Set_consolidation
Set consolidation
Given two sets of items then if any item is common to any set then the result of applying consolidation to those sets is a set of sets whose contents is: The two input sets if no common item exists between the two input sets of items. The single set that is the union of the two input sets if they share a common item. Given N sets of items where N>2 then the result is the same as repeatedly replacing all combinations of two sets by their consolidation until no further consolidation between set pairs is possible. If N<2 then consolidation has no strict meaning and the input can be returned. Example 1: Given the two sets {A,B} and {C,D} then there is no common element between the sets and the result is the same as the input. Example 2: Given the two sets {A,B} and {B,D} then there is a common element B between the sets and the result is the single set {B,D,A}. (Note that order of items in a set is immaterial: {A,B,D} is the same as {B,D,A} and {D,A,B}, etc). Example 3: Given the three sets {A,B} and {C,D} and {D,B} then there is no common element between the sets {A,B} and {C,D} but the sets {A,B} and {D,B} do share a common element that consolidates to produce the result {B,D,A}. On examining this result with the remaining set, {C,D}, they share a common element and so consolidate to the final output of the single set {A,B,C,D} Example 4: The consolidation of the five sets: {H,I,K}, {A,B}, {C,D}, {D,B}, and {F,G,H} Is the two sets: {A, C, B, D}, and {G, F, I, H, K} See also Connected component (graph theory) Range consolidation
#Ela
Ela
open list   merge [] ys = ys merge (x::xs) ys | x `elem` ys = merge xs ys | else = merge xs (x::ys)   consolidate (_::[])@xs = xs consolidate (x::xs) = conso [x] (consolidate xs) where conso xs [] = xs conso (x::xs)@r (y::ys) | intersect x y <> [] = conso ((merge x y)::xs) ys | else = conso (r ++ [y]) ys
http://rosettacode.org/wiki/Sequence:_smallest_number_with_exactly_n_divisors
Sequence: smallest number with exactly n divisors
Calculate the sequence where each term   an   is the smallest natural number that has exactly   n   divisors. Task Show here, on this page, at least the first  15  terms of the sequence. Related tasks Sequence: smallest number greater than previous term with exactly n divisors Sequence: nth number with exactly n divisors‎‎ See also OEIS:A005179
#Haskell
Haskell
import Data.List (find, group, sort) import Data.Maybe (mapMaybe) import Data.Numbers.Primes (primeFactors)   ------------------------- A005179 ------------------------   a005179 :: [Int] a005179 = mapMaybe ( \n -> find ((n ==) . succ . length . properDivisors) [1 ..] ) [1 ..]   --------------------------- TEST ------------------------- main :: IO () main = print $ take 15 a005179   ------------------------- GENERIC ------------------------   properDivisors :: Int -> [Int] properDivisors = init . sort . foldr (flip ((<*>) . fmap (*)) . scanl (*) 1) [1] . group . primeFactors
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
#NetRexx
NetRexx
/* NetRexx */ options replace format comments java crossref savelog symbols binary   import java.security.MessageDigest   SHA256('Rosetta code', '764faf5c61ac315f1497f9dfa542713965b785e5cc2f707d6468d7d1124cdfcf')   return   -- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ method SHA256(messageText, verifyCheck) public static   algorithm = 'SHA-256' digestSum = getDigest(messageText, algorithm)   say '<Message>'messageText'</Message>' say Rexx('<'algorithm'>').right(12) || digestSum'</'algorithm'>' say Rexx('<Verify>').right(12) || verifyCheck'</Verify>' if digestSum == verifyCheck then say algorithm 'Confirmed' else say algorithm 'Failed'   return   -- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ method getDigest(messageText = Rexx, algorithm = Rexx 'MD5', encoding = Rexx 'UTF-8', lowercase = boolean 1) public static returns Rexx   algorithm = algorithm.upper encoding = encoding.upper   message = String(messageText) messageBytes = byte[] digestBytes = byte[] digestSum = Rexx ''   do messageBytes = message.getBytes(encoding) md = MessageDigest.getInstance(algorithm) md.update(messageBytes) digestBytes = md.digest   loop b_ = 0 to digestBytes.length - 1 bb = Rexx(digestBytes[b_]).d2x(2) if lowercase then digestSum = digestSum || bb.lower else digestSum = digestSum || bb.upper end b_ catch ex = Exception ex.printStackTrace end   return digestSum  
http://rosettacode.org/wiki/Sequence:_smallest_number_greater_than_previous_term_with_exactly_n_divisors
Sequence: smallest number greater than previous term with exactly n divisors
Calculate the sequence where each term an is the smallest natural number greater than the previous term, that has exactly n divisors. Task Show here, on this page, at least the first 15 terms of the sequence. See also OEIS:A069654 Related tasks Sequence: smallest number with exactly n divisors Sequence: nth number with exactly n divisors‎‎
#jq
jq
  # The number of prime factors (as in prime factorization) def numfactors: . as $num | reduce range(1; 1 + sqrt|floor) as $i (null; if ($num % $i) == 0 then ($num / $i) as $r | if $i == $r then .+1 else .+2 end else . end );   # Output: a stream def A06954: foreach range(1; infinite) as $i ({k: 0}; .j = .k + 1 | until( $i == (.j | numfactors); .j += 1) | .k = .j ; .j ) ;   "First 15 terms of OEIS sequence A069654: ", [limit(15; A06954)]
http://rosettacode.org/wiki/Sequence:_smallest_number_greater_than_previous_term_with_exactly_n_divisors
Sequence: smallest number greater than previous term with exactly n divisors
Calculate the sequence where each term an is the smallest natural number greater than the previous term, that has exactly n divisors. Task Show here, on this page, at least the first 15 terms of the sequence. See also OEIS:A069654 Related tasks Sequence: smallest number with exactly n divisors Sequence: nth number with exactly n divisors‎‎
#Julia
Julia
using Primes   function numfactors(n) f = [one(n)] for (p,e) in factor(n) f = reduce(vcat, [f*p^j for j in 1:e], init=f) end length(f) end   function A06954(N) println("First $N terms of OEIS sequence A069654: ") k = 0 for i in 1:N j = k while (j += 1) > 0 if i == numfactors(j) print("$j ") k = j break end end end end   A06954(15)  
http://rosettacode.org/wiki/Sequence:_smallest_number_greater_than_previous_term_with_exactly_n_divisors
Sequence: smallest number greater than previous term with exactly n divisors
Calculate the sequence where each term an is the smallest natural number greater than the previous term, that has exactly n divisors. Task Show here, on this page, at least the first 15 terms of the sequence. See also OEIS:A069654 Related tasks Sequence: smallest number with exactly n divisors Sequence: nth number with exactly n divisors‎‎
#Kotlin
Kotlin
// Version 1.3.21   const val MAX = 15   fun countDivisors(n: Int): Int { var count = 0 var i = 1 while (i * i <= n) { if (n % i == 0) { count += if (i == n / i) 1 else 2 } i++ } return count }   fun main() { println("The first $MAX terms of the sequence are:") var i = 1 var next = 1 while (next <= MAX) { if (next == countDivisors(i)) { print("$i ") next++ } i++ } println() }
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.
#NetRexx
NetRexx
/* NetRexx */ options replace format comments java crossref savelog symbols binary   import java.security.MessageDigest   SHA1('Rosetta Code', '48c98f7e5a6e736d790ab740dfc3f51a61abe2b5')   return   -- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ method SHA1(messageText, verifyCheck) public static   algorithm = 'SHA-1' digestSum = getDigest(messageText, algorithm)   say '<Message>'messageText'</Message>' say Rexx('<'algorithm'>').right(12) || digestSum'</'algorithm'>' say Rexx('<Verify>').right(12) || verifyCheck'</Verify>' if digestSum == verifyCheck then say algorithm 'Confirmed' else say algorithm 'Failed'   return   -- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ method getDigest(messageText = Rexx, algorithm = Rexx 'MD5', encoding = Rexx 'UTF-8', lowercase = boolean 1) public static returns Rexx   algorithm = algorithm.upper encoding = encoding.upper   message = String(messageText) messageBytes = byte[] digestBytes = byte[] digestSum = Rexx ''   do messageBytes = message.getBytes(encoding) md = MessageDigest.getInstance(algorithm) md.update(messageBytes) digestBytes = md.digest   loop b_ = 0 to digestBytes.length - 1 bb = Rexx(digestBytes[b_]).d2x(2) if lowercase then digestSum = digestSum || bb.lower else digestSum = digestSum || bb.upper end b_ catch ex = Exception ex.printStackTrace end   return digestSum  
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)
#REXX
REXX
/*REXX program simulates a 7─sided die based on a 5─sided throw for a number of trials. */ parse arg trials sample seed . /*obtain optional arguments from the CL*/ if trials=='' | trials="," then trials= 1 /*Not specified? Then use the default.*/ if sample=='' | sample="," then sample= 1000000 /* " " " " " " */ if datatype(seed, 'W') then call random ,,seed /*Integer? Then use it as a RAND seed.*/ L= length(trials) /* [↑] one million samples to be used.*/   do #=1 for trials; die.= 0 /*performs the number of desired trials*/ k= 0 do until k==sample; r= 5 * random(1, 5) + random(1, 5) - 6 if r>20 then iterate k= k + 1; r= r // 7 + 1; die.r= die.r + 1 end /*until*/ say expect= sample % 7 say center('trial:' right(#, L) " " sample 'samples, expect' expect, 80, "─")   do j=1 for 7 say ' side' j "had " die.j ' occurrences', ' difference from expected:'right(die.j - expect, length(sample) ) end /*j*/ end /*#*/ /*stick a fork in it, we're all done. */
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)
#Ring
Ring
  # Project : Seven-sided dice from five-sided dice   for n = 1 to 20 d = dice7() see "" + d + " " next see nl   func dice7() x = dice5() * 5 + dice5() - 6 if x > 20 return dice7() ok dc = x % 7 + 1 return dc   func dice5() rnd = random(4) + 1 return rnd  
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
#J
J
32}._129}.a. !"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~ NB. A are the decimal ASCII values [A =: 10 |."1 ] 12 ": |: _16 [\ 32 }. i. 128 32 48 64 80 96 112 33 49 65 81 97 113 34 50 66 82 98 114 35 51 67 83 99 115 36 52 68 84 100 116 37 53 69 85 101 117 38 54 70 86 102 118 39 55 71 87 103 119 40 56 72 88 104 120 41 57 73 89 105 121 42 58 74 90 106 122 43 59 75 91 107 123 44 60 76 92 108 124 45 61 77 93 109 125 46 62 78 94 110 126 47 63 79 95 111 127 NB. B are the corresponding ASCII characters [B =: |:_16[\32}._128}.a. 0@P`p !1AQaq "2BRbr #3CScs $4DTdt %5EUeu &6FVfv '7GWgw (8HXhx )9IYiy *:JZjz +;K[k{ ,<L\l| -=M]m} .>N^n~ /?O_o� NB. stuff the characters into the text array of numbers B [`((4 12 p. i. 6)"_)`]}"1 A 32 48 0 64 @ 80 P 96 ` 112 p 33  ! 49 1 65 A 81 Q 97 a 113 q 34 " 50 2 66 B 82 R 98 b 114 r 35 # 51 3 67 C 83 S 99 c 115 s 36 $ 52 4 68 D 84 T 100 d 116 t 37  % 53 5 69 E 85 U 101 e 117 u 38 & 54 6 70 F 86 V 102 f 118 v 39 ' 55 7 71 G 87 W 103 g 119 w 40 ( 56 8 72 H 88 X 104 h 120 x 41 ) 57 9 73 I 89 Y 105 i 121 y 42 * 58  : 74 J 90 Z 106 j 122 z 43 + 59  ; 75 K 91 [ 107 k 123 { 44 , 60 < 76 L 92 \ 108 l 124 | 45 - 61 = 77 M 93 ] 109 m 125 } 46 . 62 > 78 N 94 ^ 110 n 126 ~ 47 / 63  ? 79 O 95 _ 111 o 127 �
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
#PL.2FI
PL/I
sierpinski: procedure options (main); /* 2010-03-30 */ declare t (79,79) char (1); declare (i, j, k) fixed binary; declare (y, xs, ys, xll, xrr, ixrr, limit) fixed binary;   t = ' '; xs = 40; ys = 1; /* Make initial triangle */ call make_triangle (xs, ys); y = ys + 4; xll = xs-4; xrr = xs+4; do k = 1 to 3; limit = 0; do forever; ixrr = xrr; do i = xll to xll+limit by 8; if t(y-1, i) = ' ' then do; call make_triangle (i, y); if t(y+3,i-5) = '*' then t(y+3,i-4), t(y+3,ixrr+4) = '*'; call make_triangle (ixrr, y); end; ixrr = ixrr - 8; end; xll = xll - 4; xrr = xrr + 4; y = y + 4; limit = limit + 8; if xll+limit > xs-1 then leave; end; t(y-1,xs) = '*'; end;   /* Finished generation; now print the Sierpinski triangle. */ put edit (t) (skip, (hbound(t,2)) a);   make_triangle: procedure (x, y); declare (x, y) fixed binary; declare i fixed binary;   do i = 0 to 3; t(y+i, x-i), t(y+i, x+i) = '*'; end; do i = x-2 to x+2; /* The base of the triangle. */ t(y+3, i) = '*'; end; end make_triangle;   end sierpinski;
http://rosettacode.org/wiki/Sierpinski_carpet
Sierpinski carpet
Task Produce a graphical or ASCII-art representation of a Sierpinski carpet of order   N. For example, the Sierpinski carpet of order   3   should look like this: ########################### # ## ## ## ## ## ## ## ## # ########################### ### ###### ###### ### # # # ## # # ## # # # ### ###### ###### ### ########################### # ## ## ## ## ## ## ## ## # ########################### ######### ######### # ## ## # # ## ## # ######### ######### ### ### ### ### # # # # # # # # ### ### ### ### ######### ######### # ## ## # # ## ## # ######### ######### ########################### # ## ## ## ## ## ## ## ## # ########################### ### ###### ###### ### # # # ## # # ## # # # ### ###### ###### ### ########################### # ## ## ## ## ## ## ## ## # ########################### 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
#Mathematica.2FWolfram_Language
Mathematica/Wolfram Language
full={{1,1,1},{1,0,1},{1,1,1}} empty={{0,0,0},{0,0,0},{0,0,0}} n=3; Grid[Nest[ArrayFlatten[#/.{0->empty,1->full}]&,{{1}},n]//.{0->" ",1->"#"}]
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.
#ooRexx
ooRexx
Parse Version v Say 'Version='v If a() | b() Then Say 'a and b are true' If \a() | b() Then Say 'Surprise' Else Say 'ok' If a(), b() Then Say 'a is true' If \a(), b() Then Say 'Surprise' Else Say 'ok: \a() is false' Select When \a(), b() Then Say 'Surprise' Otherwise Say 'ok: \a() is false (Select)' End Exit a: Say 'a returns .true'; Return .true b: Say 'b returns 1'; Return 1  
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
#Wren
Wren
import "/dynamic" for Enum import "/trait" for Comparable import "/fmt" for Fmt import "/str" for Str import "/math" for Nums import "/sort" for Sort import "random" for Random   var Color = Enum.create("Color", ["RED", "GREEN", "PURPLE"]) var Symbol = Enum.create("Symbol", ["OVAL", "SQUIGGLE", "DIAMOND"]) var Number = Enum.create("Number", ["ONE", "TWO", "THREE"]) var Shading = Enum.create("Shading", ["SOLID", "OPEN", "STRIPED"]) var Degree = Enum.create("Degree", ["BASIC", "ADVANCED"])   class Card is Comparable { static zero { Card.new(Color.RED, Symbol.OVAL, Number.ONE, Shading.SOLID) }   construct new(color, symbol, number, shading) { _color = color _symbol = symbol _number = number _shading = shading _value = color * 27 + symbol * 9 + number * 3 + shading }   color { _color } symbol { _symbol } number { _number } shading { _shading } value { _value }   compare(other) { (_value - other.value).sign }   toString { return Str.lower(Fmt.swrite("$-8s$-10s$-7s$-7s", Color.members [_color], Symbol.members [_symbol], Number.members [_number], Shading.members[_shading] )) } }   var createDeck = Fn.new { var deck = List.filled(81, null) for (i in 0...81) { var col = (i/27).floor var sym = (i/ 9).floor % 3 var num = (i/ 3).floor % 3 var shd = i % 3 deck[i] = Card.new(col, sym, num, shd) } return deck }   var rand = Random.new()   var isSet = Fn.new { |trio| var r1 = Nums.sum(trio.map { |c| c.color }) % 3 var r2 = Nums.sum(trio.map { |c| c.symbol }) % 3 var r3 = Nums.sum(trio.map { |c| c.number }) % 3 var r4 = Nums.sum(trio.map { |c| c.shading }) % 3 return r1 + r2 + r3 + r4 == 0 }   var playGame = Fn.new { |degree| var deck = createDeck.call() var nCards = (degree == Degree.BASIC) ? 9 : 12 var nSets = (nCards/2).floor var sets = List.filled(nSets, null) for (i in 0...nSets) sets[i] = [Card.zero, Card.zero, Card.zero] var hand = [] while (true) { rand.shuffle(deck) hand = deck.take(nCards).toList var count = 0 var hSize = hand.count var outer = false for (i in 0...hSize-2) { for (j in i+1...hSize-1) { for (k in j+1...hSize) { var trio = [hand[i], hand[j], hand[k]] if (isSet.call(trio)) { sets[count] = trio count = count + 1 if (count == nSets) { outer = true break } } } if (outer) break } if (outer) break } if (outer) break } Sort.quick(hand) System.print("DEALT %(nCards) CARDS:\n") System.print(hand.join("\n")) System.print("\nCONTAINING %(nSets) SETS:\n") for (s in sets) { Sort.quick(s) System.print(s.join("\n")) System.print() } }   playGame.call(Degree.BASIC) System.print() playGame.call(Degree.ADVANCED)
http://rosettacode.org/wiki/Set_of_real_numbers
Set of real numbers
All real numbers form the uncountable set ℝ. Among its subsets, relatively simple are the convex sets, each expressed as a range between two real numbers a and b where a ≤ b. There are actually four cases for the meaning of "between", depending on open or closed boundary: [a, b]: {x | a ≤ x and x ≤ b } (a, b): {x | a < x and x < b } [a, b): {x | a ≤ x and x < b } (a, b]: {x | a < x and x ≤ b } Note that if a = b, of the four only [a, a] would be non-empty. Task Devise a way to represent any set of real numbers, for the definition of 'any' in the implementation notes below. Provide methods for these common set operations (x is a real number; A and B are sets): x ∈ A: determine if x is an element of A example: 1 is in [1, 2), while 2, 3, ... are not. A ∪ B: union of A and B, i.e. {x | x ∈ A or x ∈ B} example: [0, 2) ∪ (1, 3) = [0, 3); [0, 1) ∪ (2, 3] = well, [0, 1) ∪ (2, 3] A ∩ B: intersection of A and B, i.e. {x | x ∈ A and x ∈ B} example: [0, 2) ∩ (1, 3) = (1, 2); [0, 1) ∩ (2, 3] = empty set A - B: difference between A and B, also written as A \ B, i.e. {x | x ∈ A and x ∉ B} example: [0, 2) − (1, 3) = [0, 1] Test your implementation by checking if numbers 0, 1, and 2 are in any of the following sets: (0, 1] ∪ [0, 2) [0, 2) ∩ (1, 2] [0, 3) − (0, 1) [0, 3) − [0, 1] Implementation notes 'Any' real set means 'sets that can be expressed as the union of a finite number of convex real sets'. Cantor's set needs not apply. Infinities should be handled gracefully; indeterminate numbers (NaN) can be ignored. You can use your machine's native real number representation, which is probably IEEE floating point, and assume it's good enough (it usually is). Optional work Create a function to determine if a given set is empty (contains no element). Define A = {x | 0 < x < 10 and |sin(π x²)| > 1/2 }, B = {x | 0 < x < 10 and |sin(π x)| > 1/2}, calculate the length of the real axis covered by the set A − B. Note that |sin(π x)| > 1/2 is the same as n + 1/6 < x < n + 5/6 for all integers n; your program does not need to derive this by itself.
#Clojure
Clojure
(ns rosettacode.real-set)   (defn >=|<= [lo hi] #(<= lo % hi))   (defn >|< [lo hi] #(< lo % hi))   (defn >=|< [lo hi] #(and (<= lo %) (< % hi)))   (defn >|<= [lo hi] #(and (< lo %) (<= % hi)))   (def ⋃ some-fn) (def ⋂ every-pred) (defn ∖ ([s1] s1) ([s1 s2] #(and (s1 %) (not (s2 %)))) ([s1 s2 s3] #(and (s1 %) (not (s2 %)) (not (s3 %)))) ([s1 s2 s3 & ss] (fn [x] (every? #(not (% x)) (list* s1 s2 s3 ss)))))   (clojure.pprint/pprint (map #(map % [0 1 2]) [(⋃ (>|<= 0 1) (>=|< 0 2)) (⋂ (>=|< 0 2) (>|<= 1 2)) (∖ (>=|< 0 3) (>|< 0 1)) (∖ (>=|< 0 3) (>=|<= 0 1))])   (def ∅ (constantly false)) (def R (constantly true)) (def Z integer?) (def Q ratio?) (def I #(∖ R Z Q)) (def N #(∖ Z neg?))
http://rosettacode.org/wiki/Set
Set
Data Structure This illustrates a data structure, a means of storing data within a program. You may see other such structures in the Data Structures category. A   set  is a collection of elements, without duplicates and without order. Task Show each of these set operations: Set creation Test m ∈ S -- "m is an element in set S" A ∪ B -- union; a set of all elements either in set A or in set B. A ∩ B -- intersection; a set of all elements in both set A and set B. A ∖ B -- difference; a set of all elements in set A, except those in set B. A ⊆ B -- subset; true if every element in set A is also in set B. A = B -- equality; true if every element of set A is in set B and vice versa. As an option, show some other set operations. (If A ⊆ B, but A ≠ B, then A is called a true or proper subset of B, written A ⊂ B or A ⊊ B.) As another option, show how to modify a mutable set. One might implement a set using an associative array (with set elements as array keys and some dummy value as the values). One might also implement a set with a binary search tree, or with a hash table, or with an ordered array of binary bits (operated on with bit-wise binary operators). The basic test, m ∈ S, is O(n) with a sequential list of elements, O(log n) with a balanced binary search tree, or (O(1) average-case, O(n) worst case) with a hash table. See also Array Associative array: Creation, Iteration Collections Compound data type Doubly-linked list: Definition, Element definition, Element insertion, List Traversal, Element Removal Linked list Queue: Definition, Usage Set Singly-linked list: Element definition, Element insertion, List Traversal, Element Removal Stack
#11l
11l
V s1 = Set([1, 2, 3, 4]) V s2 = Set([3, 4, 5, 6]) print(s1.union(s2)) print(s1.intersection(s2)) print(s1.difference(s2)) print(s1 < s1) print(Set([3, 1]) < s1) print(s1 <= s1) print(Set([3, 1]) <= s1) print(Set([3, 2, 4, 1]) == s1) print(s1 == s2) print(2 C s1) print(10 !C s1) print(Set([1, 2, 3, 4, 5]) > s1) print(Set([1, 2, 3, 4]) > s1) print(Set([1, 2, 3, 4]) >= s1) print(s1.symmetric_difference(s2)) print(s1.len) s1.add(99) print(s1) s1.discard(99) print(s1)
http://rosettacode.org/wiki/Send_an_unknown_method_call
Send an unknown method call
Task Invoke an object method where the name of the method to be invoked can be generated at run time. Related tasks Respond to an unknown method call. Runtime evaluation
#AutoHotkey
AutoHotkey
obj := {mA: Func("mA"), mB: Func("mB"), mC: Func("mC")} InputBox, methodToCall, , Which method should I call? obj[methodToCall].()   mA(){ MsgBox Method A } mB(){ MsgBox Method B } mC(){ MsgBox Method C }  
http://rosettacode.org/wiki/Sieve_of_Eratosthenes
Sieve of Eratosthenes
This task has been clarified. Its programming examples are in need of review to ensure that they still fit the requirements of the task. The Sieve of Eratosthenes is a simple algorithm that finds the prime numbers up to a given integer. Task Implement the   Sieve of Eratosthenes   algorithm, with the only allowed optimization that the outer loop can stop at the square root of the limit, and the inner loop may start at the square of the prime just found. That means especially that you shouldn't optimize by using pre-computed wheels, i.e. don't assume you need only to cross out odd numbers (wheel based on 2), numbers equal to 1 or 5 modulo 6 (wheel based on 2 and 3), or similar wheels based on low primes. If there's an easy way to add such a wheel based optimization, implement it as an alternative version. Note It is important that the sieve algorithm be the actual algorithm used to find prime numbers for the task. Related tasks   Emirp primes   count in factors   prime decomposition   factors of an integer   extensible prime generator   primality by trial division   factors of a Mersenne number   trial factoring of a Mersenne number   partition an integer X into N primes   sequence of primes by Trial Division
#8th
8th
  with: n   \ create a new buffer which will function as a bit vector : bit-vec SED: n -- b dup 3 shr swap 7 band if 1+ then b:new b:clear ;   \ given a buffer, sieving prime, and limit, cross off multiples \ of the sieving prime. : +composites SED: b n n -- b >r dup sqr rot \ want: -- n index b repeat over 1- true b:bit! >r over + r> over r@ > until! rdrop nip nip ;   \ SoE algorithm proper : make-sieve SED: n -- b dup>r bit-vec 2 repeat tuck 1- b:bit@ not if over r@ +composites then swap 1+ dup sqr r@ < while! rdrop drop ;   \ traverse the final buffer, creating an array of primes : sieve>a SED: b n -- a >r a:new swap ( 1- b:bit@ not if >r I a:push r> then ) 2 r> loop drop ;   ;with   : sieve SED: n -- a dup make-sieve swap sieve>a ;  
http://rosettacode.org/wiki/Sequence_of_primorial_primes
Sequence of primorial primes
The sequence of primorial primes is given as the increasing values of n where primorial(n) ± 1 is prime. Noting that the n'th primorial is defined as the multiplication of the smallest n primes, the sequence is of the number of primes, in order that when multiplied together is one-off being a prime number itself. Task Generate and show here the first ten values of the sequence. Optional extended task Show the first twenty members of the series. Notes This task asks for the primorial indices that create the final primorial prime numbers, so there should be no ten-or-more digit numbers in the program output (although extended precision integers will be needed for intermediate results). There is some confusion in the references, but for the purposes of this task the sequence begins with n = 1. Probabilistic primality tests are allowed, as long as they are good enough such that the output shown is correct. Related tasks Primorial numbers Factorial See also Primorial prime Wikipedia. Primorial prime from The Prime Glossary. Sequence A088411 from The On-Line Encyclopedia of Integer Sequences
#Fortran
Fortran
PROGRAM PRIMORIALP !Simple enough, with some assistants. USE PRIMEBAG !Some prime numbers are wanted. USE BIGNUMBERS !Just so. TYPE(BIGNUM) B !I'll have one. INTEGER MAXF !Largest factor to consider by direct division. PARAMETER (MAXF = 18000000) !Some determination. INTEGER I !Step stuff. INTEGER FU,FD !Found factors. INTEGER NHIT,HIT(666) !A little list. CHARACTER*4 WOT !A remark. CHARACTER*66 ALINE !A scratchpad. REAL T0,T1 !In memory of lost time. MSG = 6 !Standard output. WRITE (MSG,1) BIGLIMIT,BIGBASE,HUGE(I) !Announce. 1 FORMAT ('Calculates primorial "primes"',/, 1 "A primorial prime is a value N such that",/, 2 " Primorial(N) - 1 is prime, OR",/, 3 " Primorial(N) + 1 is prime, or both.",/, 4 "and Primorial(N) is the product of the first N prime numbers.",/ 5 "Working with up to ",I0," digits in base ",I0,"."/ 6 "The integer limit is ",I0,/)   c CALL PREPARE PRIMES !First, catch your rabbit. Via ERATOSTHENES. IF (.NOT.GRASPPRIMEBAG(66)) STOP "Gan't grab my file!" !Attempt in hope. WRITE (MSG,2) 2 FORMAT ("Primorial#",3X,"Approx.",8X," -1 Factor +1 Factor Hit")   Commence prime mashing. 100 NHIT = 0 !My list is empty. B.LAST = 1 !Begin at the beginning. B.DIGIT(1) = 1 !With one. The same, whatever BIGBASE. CALL CPU_TIME(T0) !Start the timing. DO I = 1,30 !69 !Step along the primorials. CALL BIGMULTN(B,PRIME(I)) !Multiply by the next prime. c WRITE (MSG,101) I,PRIME(I),I,B.DIGIT(B.LAST:1:-1) !Digits in Arabic/Hindu order. 101 FORMAT ("Prime(",I0,") = ",I0,", Primorial(",I0,") = ", !For a possibly multi-BIGBASE sequence. 1 I0,9I<BIGORDER>.<BIGORDER>,/,(10I<BIGORDER>.<BIGORDER>)) !The first without leading zero digits. FU = -1 !No factor for up one. FD = -1 !No factor for down one. CALL BIGADDN(B,+1) !Go up one. FU = BIGFACTOR(B,MAXF) !Find a factor, maybe. CALL BIGADDN(B,-2) !Now test down one. IF (FU.NE.1) FD = BIGFACTOR(B,MAXF) !But only if FU didn't report "prime". IF (FU.EQ.1 .OR. FD.EQ.1) THEN !Since if either candidate is a prime, WOT = "Yes!" !Then a hit. NHIT = NHIT + 1 !So count up a success. HIT(NHIT) = I !And append to my list. ELSE IF (FU.GT.1 .AND. FD.GT.1) THEN !But if both have factors, WOT = "No." !Then definitely not a hit. ELSE !Otherwise, WOT = "?" !I can't decide. END IF !So much for that candidate. CALL BIGADDN(B,1) !Recover the original primorial value. WRITE (ALINE,102) I,BIGVALUE(B),FD,FU,WOT !Prepare a report. 102 FORMAT (I10,1PE18.10,I10,I10,1X,A) !A table. IF (FD.EQ.-1) ALINE(37:38) = "" !Wasn't looked for, so no remark. IF (FD.EQ. 0) ALINE(38:38) = "?" !Recode a zero. IF (FU.EQ. 0) ALINE(48:48) = "?" !Since it represents "Don't know". WRITE (MSG,"(A)") ALINE !Show the report. END DO !On to the next prime. CALL CPU_TIME(T1) !Completed the run.   Cast forth some pearls. WRITE (MSG,201) HIT(1:NHIT) !The list. 201 FORMAT (/,"Hit list: ",I0,666(",",I0:)) !Don't actually expect so many. WRITE (MSG,*) "CPU time:",T1 - T0 !The cost. END !So much for that.  
http://rosettacode.org/wiki/Sequence:_nth_number_with_exactly_n_divisors
Sequence: nth number with exactly n divisors
Calculate the sequence where each term an is the nth that has n divisors. Task Show here, on this page, at least the first 15 terms of the sequence. See also OEIS:A073916 Related tasks Sequence: smallest number greater than previous term with exactly n divisors Sequence: smallest number with exactly n divisors
#jq
jq
def count(stream): reduce stream as $i (0; .+1);   # To maintain precision: def power($b): . as $in | reduce range(0;$b) as $i (1; . * $in);   def primes: 2, (range(3; infinite; 2) | select(is_prime));   # divisors as an unsorted stream def divisors: if . == 1 then 1 else . as $n | label $out | range(1; $n) as $i | ($i * $i) as $i2 | if $i2 > $n then break $out else if $i2 == $n then $i elif ($n % $i) == 0 then $i, ($n/$i) else empty end end end;  
http://rosettacode.org/wiki/Sequence:_nth_number_with_exactly_n_divisors
Sequence: nth number with exactly n divisors
Calculate the sequence where each term an is the nth that has n divisors. Task Show here, on this page, at least the first 15 terms of the sequence. See also OEIS:A073916 Related tasks Sequence: smallest number greater than previous term with exactly n divisors Sequence: smallest number with exactly n divisors
#Julia
Julia
using Primes   function countdivisors(n) f = [one(n)] for (p, e) in factor(n) f = reduce(vcat, [f * p ^ j for j in 1:e], init = f) end length(f) end   function nthwithndivisors(N) parray = findall(primesmask(100 * N)) for i = 1:N if isprime(i) println("$i : ", BigInt(parray[i])^(i-1)) else k = 0 for j in 1:100000000000 if (iseven(i) || Int(floor(sqrt(j)))^2 == j) && i == countdivisors(j) && (k += 1) == i println("$i : $j") break end end end end end   nthwithndivisors(35)  
http://rosettacode.org/wiki/Sequence:_nth_number_with_exactly_n_divisors
Sequence: nth number with exactly n divisors
Calculate the sequence where each term an is the nth that has n divisors. Task Show here, on this page, at least the first 15 terms of the sequence. See also OEIS:A073916 Related tasks Sequence: smallest number greater than previous term with exactly n divisors Sequence: smallest number with exactly n divisors
#Kotlin
Kotlin
// Version 1.3.21   import java.math.BigInteger import kotlin.math.sqrt   const val MAX = 33   fun isPrime(n: Int) = BigInteger.valueOf(n.toLong()).isProbablePrime(10)   fun generateSmallPrimes(n: Int): List<Int> { val primes = mutableListOf<Int>() primes.add(2) var i = 3 while (primes.size < n) { if (isPrime(i)) { primes.add(i) } i += 2 } return primes }   fun countDivisors(n: Int): Int { var nn = n var count = 1 while (nn % 2 == 0) { nn = nn shr 1 count++ } var d = 3 while (d * d <= nn) { var q = nn / d var r = nn % d if (r == 0) { var dc = 0 while (r == 0) { dc += count nn = q q = nn / d r = nn % d } count += dc } d += 2 } if (nn != 1) count *= 2 return count }   fun main() { var primes = generateSmallPrimes(MAX) println("The first $MAX terms in the sequence are:") for (i in 1..MAX) { if (isPrime(i)) { var z = BigInteger.valueOf(primes[i - 1].toLong()) z = z.pow(i - 1) System.out.printf("%2d : %d\n", i, z) } else { var count = 0 var j = 1 while (true) { if (i % 2 == 1) { val sq = sqrt(j.toDouble()).toInt() if (sq * sq != j) { j++ continue } } if (countDivisors(j) == i) { if (++count == i) { System.out.printf("%2d : %d\n", i, j) break } } j++ } } } }
http://rosettacode.org/wiki/Set_consolidation
Set consolidation
Given two sets of items then if any item is common to any set then the result of applying consolidation to those sets is a set of sets whose contents is: The two input sets if no common item exists between the two input sets of items. The single set that is the union of the two input sets if they share a common item. Given N sets of items where N>2 then the result is the same as repeatedly replacing all combinations of two sets by their consolidation until no further consolidation between set pairs is possible. If N<2 then consolidation has no strict meaning and the input can be returned. Example 1: Given the two sets {A,B} and {C,D} then there is no common element between the sets and the result is the same as the input. Example 2: Given the two sets {A,B} and {B,D} then there is a common element B between the sets and the result is the single set {B,D,A}. (Note that order of items in a set is immaterial: {A,B,D} is the same as {B,D,A} and {D,A,B}, etc). Example 3: Given the three sets {A,B} and {C,D} and {D,B} then there is no common element between the sets {A,B} and {C,D} but the sets {A,B} and {D,B} do share a common element that consolidates to produce the result {B,D,A}. On examining this result with the remaining set, {C,D}, they share a common element and so consolidate to the final output of the single set {A,B,C,D} Example 4: The consolidation of the five sets: {H,I,K}, {A,B}, {C,D}, {D,B}, and {F,G,H} Is the two sets: {A, C, B, D}, and {G, F, I, H, K} See also Connected component (graph theory) Range consolidation
#Elixir
Elixir
defmodule RC do def set_consolidate(sets, result\\[]) def set_consolidate([], result), do: result def set_consolidate([h|t], result) do case Enum.find(t, fn set -> not MapSet.disjoint?(h, set) end) do nil -> set_consolidate(t, [h | result]) set -> set_consolidate([MapSet.union(h, set) | t -- [set]], result) end end end   examples = [[[:A,:B], [:C,:D]], [[:A,:B], [:B,:D]], [[:A,:B], [:C,:D], [:D,:B]], [[:H,:I,:K], [:A,:B], [:C,:D], [:D,:B], [:F,:G,:H]]] |> Enum.map(fn sets -> Enum.map(sets, fn set -> MapSet.new(set) end) end)   Enum.each(examples, fn sets -> IO.write "#{inspect sets} =>\n\t" IO.inspect RC.set_consolidate(sets) end)
http://rosettacode.org/wiki/Sequence:_smallest_number_with_exactly_n_divisors
Sequence: smallest number with exactly n divisors
Calculate the sequence where each term   an   is the smallest natural number that has exactly   n   divisors. Task Show here, on this page, at least the first  15  terms of the sequence. Related tasks Sequence: smallest number greater than previous term with exactly n divisors Sequence: nth number with exactly n divisors‎‎ See also OEIS:A005179
#JavaScript
JavaScript
(() => { 'use strict';   // a005179 :: () -> [Int] const a005179 = () => fmapGen( n => find( compose( eq(n), succ, length, properDivisors ) )(enumFrom(1)).Just )(enumFrom(1));     // ------------------------TEST------------------------ // main :: IO () const main = () => console.log( take(15)( a005179() ) );   // [1,2,4,6,16,12,64,24,36,48,1024,60,4096,192,144]     // -----------------GENERIC FUNCTIONS------------------   // Just :: a -> Maybe a const Just = x => ({ type: 'Maybe', Nothing: false, Just: x });   // Nothing :: Maybe a const Nothing = () => ({ type: 'Maybe', Nothing: true, });   // Tuple (,) :: a -> b -> (a, b) const Tuple = a => b => ({ type: 'Tuple', '0': a, '1': b, length: 2 });   // compose (<<<) :: (b -> c) -> (a -> b) -> a -> c const compose = (...fs) => fs.reduce( (f, g) => x => f(g(x)), x => x );   // enumFrom :: Enum a => a -> [a] function* enumFrom(x) { // A non-finite succession of enumerable // values, starting with the value x. let v = x; while (true) { yield v; v = succ(v); } };   // eq (==) :: Eq a => a -> a -> Bool const eq = a => // True when a and b are equivalent in the terms // defined below for their shared data type. b => a === b;   // find :: (a -> Bool) -> Gen [a] -> Maybe a const find = p => xs => { const mb = until(tpl => { const nxt = tpl[0]; return nxt.done || p(nxt.value); })( tpl => Tuple(tpl[1].next())( tpl[1] ) )(Tuple(xs.next())(xs))[0]; return mb.done ? ( Nothing() ) : Just(mb.value); }   // fmapGen <$> :: (a -> b) -> Gen [a] -> Gen [b] const fmapGen = f => function*(gen) { let v = take(1)(gen); while (0 < v.length) { yield(f(v[0])) v = take(1)(gen) } };   // group :: [a] -> [[a]] const group = xs => { // A list of lists, each containing only equal elements, // such that the concatenation of these lists is xs. const go = xs => 0 < xs.length ? (() => { const h = xs[0], i = xs.findIndex(x => h !== x); return i !== -1 ? ( [xs.slice(0, i)].concat(go(xs.slice(i))) ) : [xs]; })() : []; return go(xs); };   // length :: [a] -> Int const length = xs => // Returns Infinity over objects without finite // length. This enables zip and zipWith to choose // the shorter argument when one is non-finite, // like cycle, repeat etc (Array.isArray(xs) || 'string' === typeof xs) ? ( xs.length ) : Infinity;   // liftA2List :: (a -> b -> c) -> [a] -> [b] -> [c] const liftA2List = f => xs => ys => // The binary operator f lifted to a function over two // lists. f applied to each pair of arguments in the // cartesian product of xs and ys. xs.flatMap( x => ys.map(f(x)) );   // mul (*) :: Num a => a -> a -> a const mul = a => b => a * b;   // properDivisors :: Int -> [Int] const properDivisors = n => // The ordered divisors of n, // excluding n itself. 1 < n ? ( sort(group(primeFactors(n)).reduce( (a, g) => liftA2List(mul)(a)( scanl(mul)([1])(g) ), [1] )).slice(0, -1) ) : [];   // primeFactors :: Int -> [Int] const primeFactors = n => { // A list of the prime factors of n. const go = x => { const root = Math.floor(Math.sqrt(x)), m = until( ([q, _]) => (root < q) || (0 === (x % q)) )( ([_, r]) => [step(r), 1 + r] )( [0 === x % 2 ? 2 : 3, 1] )[0]; return m > root ? ( [x] ) : ([m].concat(go(Math.floor(x / m)))); }, step = x => 1 + (x << 2) - ((x >> 1) << 1); return go(n); };   // scanl :: (b -> a -> b) -> b -> [a] -> [b] const scanl = f => startValue => xs => xs.reduce((a, x) => { const v = f(a[0])(x); return Tuple(v)(a[1].concat(v)); }, Tuple(startValue)([startValue]))[1];   // sort :: Ord a => [a] -> [a] const sort = xs => xs.slice() .sort((a, b) => a < b ? -1 : (a > b ? 1 : 0));   // succ :: Enum a => a -> a const succ = x => 1 + x;   // take :: Int -> [a] -> [a] // take :: Int -> String -> String const take = n => // The first n elements of a list, // string of characters, or stream. xs => 'GeneratorFunction' !== xs .constructor.constructor.name ? ( xs.slice(0, n) ) : [].concat.apply([], Array.from({ length: n }, () => { const x = xs.next(); return x.done ? [] : [x.value]; }));   // until :: (a -> Bool) -> (a -> a) -> a -> a const until = p => f => x => { let v = x; while (!p(v)) v = f(v); return v; };   // MAIN --- return main(); })();
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
#NewLISP
NewLISP
;; using the crypto module from http://www.newlisp.org/code/modules/crypto.lsp.html ;; (import native functions from the crypto library, provided by OpenSSL) (module "crypto.lsp") (crypto:sha256 "Rosetta Code")
http://rosettacode.org/wiki/SHA-256
SHA-256
SHA-256 is the recommended stronger alternative to SHA-1. See FIPS PUB 180-4 for implementation details. Either by using a dedicated library or implementing the algorithm in your language, show that the SHA-256 digest of the string "Rosetta code" is: 764faf5c61ac315f1497f9dfa542713965b785e5cc2f707d6468d7d1124cdfcf
#Nim
Nim
import nimcrypto   echo sha256.digest("Rosetta code")
http://rosettacode.org/wiki/Sequence:_smallest_number_greater_than_previous_term_with_exactly_n_divisors
Sequence: smallest number greater than previous term with exactly n divisors
Calculate the sequence where each term an is the smallest natural number greater than the previous term, that has exactly n divisors. Task Show here, on this page, at least the first 15 terms of the sequence. See also OEIS:A069654 Related tasks Sequence: smallest number with exactly n divisors Sequence: nth number with exactly n divisors‎‎
#Mathematica_.2F_Wolfram_Language
Mathematica / Wolfram Language
res = {#, DivisorSigma[0, #]} & /@ Range[100000]; highest = 0; filter = {}; Do[ If[r[[2]] == highest + 1, AppendTo[filter, r[[1]]]; highest = r[[2]] ] , {r, res} ] Take[filter, 15]
http://rosettacode.org/wiki/Sequence:_smallest_number_greater_than_previous_term_with_exactly_n_divisors
Sequence: smallest number greater than previous term with exactly n divisors
Calculate the sequence where each term an is the smallest natural number greater than the previous term, that has exactly n divisors. Task Show here, on this page, at least the first 15 terms of the sequence. See also OEIS:A069654 Related tasks Sequence: smallest number with exactly n divisors Sequence: nth number with exactly n divisors‎‎
#Nim
Nim
import strformat   const MAX = 15   func countDivisors(n: int): int = var i = 1 var count = 0 while i * i <= n: if n mod i == 0: if i == n div i: inc count else: inc count, 2 inc i count   var i, next = 1 echo fmt"The first {MAX} terms of the sequence are:" while next <= MAX: if next == countDivisors(i): write(stdout, fmt"{i} ") inc next inc i write(stdout, "\n")
http://rosettacode.org/wiki/Sequence:_smallest_number_greater_than_previous_term_with_exactly_n_divisors
Sequence: smallest number greater than previous term with exactly n divisors
Calculate the sequence where each term an is the smallest natural number greater than the previous term, that has exactly n divisors. Task Show here, on this page, at least the first 15 terms of the sequence. See also OEIS:A069654 Related tasks Sequence: smallest number with exactly n divisors Sequence: nth number with exactly n divisors‎‎
#Pascal
Pascal
program AntiPrimesPlus; {$IFDEF FPC} {$MODE Delphi} {$ELSE} {$APPTYPE CONSOLE} // delphi {$ENDIF} uses sysutils,math; const MAX =32;   function getDividersCnt(n:Uint32):Uint32; // getDividersCnt by dividing n into its prime factors // aka n = 2250 = 2^1*3^2*5^3 has (1+1)*(2+1)*(3+1)= 24 dividers var divi,quot,deltaRes,rest : Uint32; begin result := 1;   //divi  := 2; //separat without division while Not(Odd(n)) do Begin n := n SHR 1; inc(result); end;   //from now on only odd numbers divi := 3; while (sqr(divi)<=n) do Begin DivMod(n,divi,quot,rest); if rest = 0 then Begin deltaRes := 0; repeat inc(deltaRes,result); n := quot; DivMod(n,divi,quot,rest); until rest <> 0; inc(result,deltaRes); end; inc(divi,2); end; //if last factor of n is prime IF n <> 1 then result := result*2; end;   var T0 : Int64; i,next,DivCnt: Uint32; begin writeln('The first ',MAX,' anti-primes plus are:'); T0:= GetTickCount64; i := 1; next := 1; repeat DivCnt := getDividersCnt(i); IF DivCnt= next then Begin write(i,' '); inc(next); //if next is prime then only prime( => mostly 2 )^(next-1) is solution IF (next > 4) AND (getDividersCnt(next) = 2) then i := 1 shl (next-1) -1;// i is incremented afterwards end; inc(i); until Next > MAX; writeln; writeln(GetTickCount64-T0,' ms'); end.
http://rosettacode.org/wiki/SHA-1
SHA-1
SHA-1 or SHA1 is a one-way hash function; it computes a 160-bit message digest. SHA-1 often appears in security protocols; for example, many HTTPS websites use RSA with SHA-1 to secure their connections. BitTorrent uses SHA-1 to verify downloads. Git and Mercurial use SHA-1 digests to identify commits. A US government standard, FIPS 180-1, defines SHA-1. Find the SHA-1 message digest for a string of octets. You may either call a SHA-1 library, or implement SHA-1 in your language. Both approaches interest Rosetta Code. Warning: SHA-1 has known weaknesses. Theoretical attacks may find a collision after 252 operations, or perhaps fewer. This is much faster than a brute force attack of 280 operations. USgovernment deprecated SHA-1. For production-grade cryptography, users may consider a stronger alternative, such as SHA-256 (from the SHA-2 family) or the upcoming SHA-3.
#NewLISP
NewLISP
;; using the crypto module from http://www.newlisp.org/code/modules/crypto.lsp.html ;; (import native functions from the crypto library, provided by OpenSSL) (module "crypto.lsp") (crypto:sha1 "Rosetta Code")
http://rosettacode.org/wiki/SHA-1
SHA-1
SHA-1 or SHA1 is a one-way hash function; it computes a 160-bit message digest. SHA-1 often appears in security protocols; for example, many HTTPS websites use RSA with SHA-1 to secure their connections. BitTorrent uses SHA-1 to verify downloads. Git and Mercurial use SHA-1 digests to identify commits. A US government standard, FIPS 180-1, defines SHA-1. Find the SHA-1 message digest for a string of octets. You may either call a SHA-1 library, or implement SHA-1 in your language. Both approaches interest Rosetta Code. Warning: SHA-1 has known weaknesses. Theoretical attacks may find a collision after 252 operations, or perhaps fewer. This is much faster than a brute force attack of 280 operations. USgovernment deprecated SHA-1. For production-grade cryptography, users may consider a stronger alternative, such as SHA-256 (from the SHA-2 family) or the upcoming SHA-3.
#Nim
Nim
import std/sha1   echo secureHash("Rosetta Code")
http://rosettacode.org/wiki/Seven-sided_dice_from_five-sided_dice
Seven-sided dice from five-sided dice
Task (Given an equal-probability generator of one of the integers 1 to 5 as dice5),   create dice7 that generates a pseudo-random integer from 1 to 7 in equal probability using only dice5 as a source of random numbers,   and check the distribution for at least one million calls using the function created in   Simple Random Distribution Checker. Implementation suggestion: dice7 might call dice5 twice, re-call if four of the 25 combinations are given, otherwise split the other 21 combinations into 7 groups of three, and return the group index from the rolls. (Task adapted from an answer here)
#Ruby
Ruby
require './distcheck.rb'   def d5 1 + rand(5) end   def d7 loop do d55 = 5*d5 + d5 - 6 return (d55 % 7 + 1) if d55 < 21 end end   distcheck(1_000_000) {d5} distcheck(1_000_000) {d7}
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)
#Scala
Scala
import scala.util.Random   object SevenSidedDice extends App { private val rnd = new Random   private def seven = { var v = 21   def five = 1 + rnd.nextInt(5)   while (v > 20) v = five + five * 5 - 6 1 + v % 7 }   println("Random number from 1 to 7: " + seven)   }
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
#Java
Java
  public class ShowAsciiTable {   public static void main(String[] args) { for ( int i = 32 ; i <= 127 ; i++ ) { if ( i == 32 || i == 127 ) { String s = i == 32 ? "Spc" : "Del"; System.out.printf("%3d: %s ", i, s); } else { System.out.printf("%3d: %c ", i, i); } if ( (i-1) % 6 == 0 ) { System.out.println(); } } }   }  
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
#PL.2FM
PL/M
100H:   DECLARE ORDER LITERALLY '4';   /* CP/M BDOS CALL */ BDOS: PROCEDURE (FN, ARG); DECLARE FN BYTE, ARG ADDRESS; GO TO 5; END BDOS;   PUT$CHAR: PROCEDURE (CHAR); DECLARE CHAR BYTE; CALL BDOS(2, CHAR); END PUT$CHAR;   /* PRINT SIERPINSKI TRIANGLE */ DECLARE (X, Y, SIZE) BYTE; SIZE = SHL(1, ORDER);   Y = SIZE - 1; DO WHILE Y <> -1; DO X = 0 TO Y; CALL PUT$CHAR(' '); END; DO X = 0 TO SIZE-Y-1; IF (X AND Y) = 0 THEN CALL PUT$CHAR('*'); ELSE CALL PUT$CHAR(' '); CALL PUT$CHAR(' '); END; Y = Y - 1; CALL PUT$CHAR(13); CALL PUT$CHAR(10); END;   CALL BDOS(0,0); EOF
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
#MATLAB
MATLAB
n = 3; c = string('#'); for k = 1 : n c = [c + c + c, c + c.replace('#', ' ') + c, c + c + c]; end disp(c.join(char(10)))
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.
#Oz
Oz
declare fun {A Answer} AnswerS = {Value.toVirtualString Answer 1 1} in {System.showInfo "  % Called function {A "#AnswerS#"} -> "#AnswerS} Answer end   fun {B Answer} AnswerS = {Value.toVirtualString Answer 1 1} in {System.showInfo "  % Called function {B "#AnswerS#"} -> "#AnswerS} Answer end in for I in [false true] do for J in [false true] do X Y in {System.showInfo "\nCalculating: X = {A I} andthen {B J}"} X = {A I} andthen {B J} {System.showInfo "Calculating: Y = {A I} orelse {B J}"} Y = {A I} orelse {B J} end end
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
#zkl
zkl
const nDraw=9, nGoal=(nDraw/2); // Basic var [const] UH=Utils.Helpers; // baked in stash of goodies deck:=Walker.cproduct("red green purple".split(), // Cartesian product of 4 lists of lists "one two three".split(), // T(1,2,3) (ie numbers) also works "oval squiggle diamond".split(), "solid open striped".split()).walk(); reg draw,sets,N=0; do{ N+=1; draw=deck.shuffle()[0,nDraw]; // one draw per shuffle sets=UH.pickNFrom(3,draw) // 84 sets of 3 cards (each with 4 features) .filter(fcn(set){ // list of 12 items (== 3 cards) set[0,4].zip(set[4,4],set[8,4]) // -->4 tuples of 3 features .pump(List,UH.listUnique,"len", // 1,3 (good) or 2 (bad) '==(2)) // (F,F,F,F)==good .sum(0) == 0 // all 4 feature sets good }); }while(sets.len()!=nGoal);   println("Dealt %d cards %d times:".fmt(draw.len(),N)); draw.pump(Void,fcn(card){ println(("%8s "*4).fmt(card.xplode())) }); println("\nContaining:"); sets.pump(Void,fcn(card){ println((("%8s "*4 + "\n")*3).fmt(card.xplode())) });
http://rosettacode.org/wiki/Send_email
Send email
Task Write a function to send an email. The function should have parameters for setting From, To and Cc addresses; the Subject, and the message text, and optionally fields for the server name and login details. If appropriate, explain what notifications of problems/success are given. Solutions using libraries or functions from the language are preferred, but failing that, external programs can be used with an explanation. Note how portable the solution given is between operating systems when multi-OS languages are used. (Remember to obfuscate any sensitive data used in examples)
#Ada
Ada
with AWS.SMTP, AWS.SMTP.Client, AWS.SMTP.Authentication.Plain; with Ada.Text_IO; use Ada, AWS;   procedure Sendmail is Status : SMTP.Status; Auth : aliased constant SMTP.Authentication.Plain.Credential := SMTP.Authentication.Plain.Initialize ("id", "password"); Isp : SMTP.Receiver; begin Isp := SMTP.Client.Initialize ("smtp.mail.com", Port => 5025, Credential => Auth'Unchecked_Access); SMTP.Client.Send (Isp, From => SMTP.E_Mail ("Me", "[email protected]"), To => SMTP.E_Mail ("You", "[email protected]"), Subject => "subject", Message => "Here is the text", Status => Status); if not SMTP.Is_Ok (Status) then Text_IO.Put_Line ("Can't send message :" & SMTP.Status_Message (Status)); end if; end Sendmail;  
http://rosettacode.org/wiki/Set_of_real_numbers
Set of real numbers
All real numbers form the uncountable set ℝ. Among its subsets, relatively simple are the convex sets, each expressed as a range between two real numbers a and b where a ≤ b. There are actually four cases for the meaning of "between", depending on open or closed boundary: [a, b]: {x | a ≤ x and x ≤ b } (a, b): {x | a < x and x < b } [a, b): {x | a ≤ x and x < b } (a, b]: {x | a < x and x ≤ b } Note that if a = b, of the four only [a, a] would be non-empty. Task Devise a way to represent any set of real numbers, for the definition of 'any' in the implementation notes below. Provide methods for these common set operations (x is a real number; A and B are sets): x ∈ A: determine if x is an element of A example: 1 is in [1, 2), while 2, 3, ... are not. A ∪ B: union of A and B, i.e. {x | x ∈ A or x ∈ B} example: [0, 2) ∪ (1, 3) = [0, 3); [0, 1) ∪ (2, 3] = well, [0, 1) ∪ (2, 3] A ∩ B: intersection of A and B, i.e. {x | x ∈ A and x ∈ B} example: [0, 2) ∩ (1, 3) = (1, 2); [0, 1) ∩ (2, 3] = empty set A - B: difference between A and B, also written as A \ B, i.e. {x | x ∈ A and x ∉ B} example: [0, 2) − (1, 3) = [0, 1] Test your implementation by checking if numbers 0, 1, and 2 are in any of the following sets: (0, 1] ∪ [0, 2) [0, 2) ∩ (1, 2] [0, 3) − (0, 1) [0, 3) − [0, 1] Implementation notes 'Any' real set means 'sets that can be expressed as the union of a finite number of convex real sets'. Cantor's set needs not apply. Infinities should be handled gracefully; indeterminate numbers (NaN) can be ignored. You can use your machine's native real number representation, which is probably IEEE floating point, and assume it's good enough (it usually is). Optional work Create a function to determine if a given set is empty (contains no element). Define A = {x | 0 < x < 10 and |sin(π x²)| > 1/2 }, B = {x | 0 < x < 10 and |sin(π x)| > 1/2}, calculate the length of the real axis covered by the set A − B. Note that |sin(π x)| > 1/2 is the same as n + 1/6 < x < n + 5/6 for all integers n; your program does not need to derive this by itself.
#Common_Lisp
Common Lisp
(deftype set== (a b) `(real ,a ,b)) (deftype set<> (a b) `(real (,a) (,b))) (deftype set=> (a b) `(real ,a (,b))) (deftype set<= (a b) `(real (,a) ,b))   (deftype set-union (s1 s2) `(or ,s1 ,s2)) (deftype set-intersection (s1 s2) `(and ,s1 ,s2)) (deftype set-diff (s1 s2) `(and ,s1 (not ,s2)))   (defun in-set-p (x set) (typep x set))   (defun test () (let ((set '(set-union (set<= 0 1) (set=> 0 2)))) (assert (in-set-p 0 set)) (assert (in-set-p 1 set)) (assert (not (in-set-p 2 set)))) (let ((set '(set-intersection (set=> 0 2) (set<= 1 2)))) (assert (not (in-set-p 0 set))) (assert (not (in-set-p 1 set))) (assert (not (in-set-p 2 set)))) (let ((set '(set-diff (set=> 0 3) (set<> 0 1)))) (assert (in-set-p 0 set)) (assert (in-set-p 1 set)) (assert (in-set-p 2 set))) (let ((set '(set-diff (set<= 0 3) (set== 0 1)))) (assert (not (in-set-p 0 set))) (assert (not (in-set-p 1 set))) (assert (in-set-p 2 set))))