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/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
|
#Perl
|
Perl
|
use strict;
use English;
use Smart::Comments;
my @ex1 = consolidate( (['A', 'B'], ['C', 'D']) );
### Example 1: @ex1
my @ex2 = consolidate( (['A', 'B'], ['B', 'D']) );
### Example 2: @ex2
my @ex3 = consolidate( (['A', 'B'], ['C', 'D'], ['D', 'B']) );
### Example 3: @ex3
my @ex4 = consolidate( (['H', 'I', 'K'], ['A', 'B'], ['C', 'D'], ['D', 'B'], ['F', 'G', 'H']) );
### Example 4: @ex4
exit 0;
sub consolidate {
scalar(@ARG) >= 2 or return @ARG;
my @result = ( shift(@ARG) );
my @recursion = consolidate(@ARG);
foreach my $r (@recursion) {
if (set_intersection($result[0], $r)) {
$result[0] = [ set_union($result[0], $r) ];
}
else {
push @result, $r;
}
}
return @result;
}
sub set_union {
my ($a, $b) = @ARG;
my %union;
foreach my $a_elt (@{$a}) { $union{$a_elt}++; }
foreach my $b_elt (@{$b}) { $union{$b_elt}++; }
return keys(%union);
}
sub set_intersection {
my ($a, $b) = @ARG;
my %a_hash;
foreach my $a_elt (@{$a}) { $a_hash{$a_elt}++; }
my @result;
foreach my $b_elt (@{$b}) {
push(@result, $b_elt) if exists($a_hash{$b_elt});
}
return @result;
}
|
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
|
#Swift
|
Swift
|
// See https://en.wikipedia.org/wiki/Divisor_function
func divisorCount(number: Int) -> Int {
var n = number
var total = 1
// Deal with powers of 2 first
while n % 2 == 0 {
total += 1
n /= 2
}
// Odd prime factors up to the square root
var p = 3
while p * p <= n {
var count = 1
while n % p == 0 {
count += 1
n /= p
}
total *= count
p += 2
}
// If n > 1 then it's prime
if n > 1 {
total *= 2
}
return total
}
let limit = 15
var sequence = Array(repeating: 0, count: limit)
var count = 0
var n = 1
while count < limit {
let divisors = divisorCount(number: n)
if divisors <= limit && sequence[divisors - 1] == 0 {
sequence[divisors - 1] = n
count += 1
}
n += 1
}
for n in sequence {
print(n, terminator: " ")
}
print()
|
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
|
#Tcl
|
Tcl
|
proc divCount {n} {
set cnt 0
for {set d 1} {($d * $d) <= $n} {incr d} {
if {0 == ($n % $d)} {
incr cnt
if {$d < ($n / $d)} {
incr cnt
}
}
}
return $cnt
}
proc A005179 {n} {
if {$n >= 1} {
for {set k 1} {1} {incr k} {
if {$n == [divCount $k]} {
return $k
}
}
}
return 0
}
proc show {func lo hi} {
puts "${func}($lo..$hi) ="
for {set n $lo} {$n <= $hi} {incr n} {
puts -nonewline " [$func $n]"
}
puts ""
}
show A005179 1 15
|
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
|
#Smalltalk
|
Smalltalk
|
(SHA256 new hashStream: 'Rosetta code' readStream) hex.
|
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
|
#Tcl
|
Tcl
|
package require sha256
puts [sha2::sha256 -hex "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.
|
#Scheme
|
Scheme
|
; band - binary AND operation
; bor - binary OR operation
; bxor - binary XOR operation
; >>, << - binary shift operations
; runes->string - convert byte list to string /(runes->string '(65 66 67 65)) => "ABCA"/
(define (sha1-padding-size n)
(let ((x (mod (- 56 (rem n 64)) 64)))
(if (= x 0) 64 x)))
(define (sha1-pad-message message)
(let*((message-len (string-length message))
(message-len-in-bits (* message-len 8))
(buffer-len (+ message-len 8 (sha1-padding-size message-len)))
(message (string-append message (runes->string '(#b10000000))))
(zeroes-len (- buffer-len message-len 1 4)) ; for ending length encoded value
(message (string-append message (make-string zeroes-len 0)))
(message (string-append message (runes->string (list
(band (>> message-len-in-bits 24) #xFF)
(band (>> message-len-in-bits 16) #xFF)
(band (>> message-len-in-bits 8) #xFF)
(band (>> message-len-in-bits 0) #xFF))))))
; (print "message-len: " message-len)
; (print "message-len-in-bits: " message-len-in-bits)
; (print "buffer-len: " buffer-len)
; (print "zeroes-len: " zeroes-len)
; (print "message: " message)
; (print "length(message): " (string-length message))
message))
(define XOR (lambda args (fold bxor 0 args))) ; bxor more than 2 arguments
(define OR (lambda args (fold bor 0 args))) ; bor more than 2 arguments
(define NOT (lambda (arg) (bxor arg #xFFFFFFFF))) ; binary not operation
; to 32-bit number
(define (->32 i)
(band i #xFFFFFFFF))
; binary cycle rotate left
(define (rol bits x)
(->32
(bor
(<< x bits)
(>> x (- 32 bits)))))
(define (word->list x)
(list
(band (>> x 24) #xFF)
(band (>> x 16) #xFF)
(band (>> x 8) #xFF)
(band (>> x 0) #xFF)))
(define (message->words message)
(let cycle ((W
(let loop ((t (iota 0 1 16)))
(if (null? t)
null
(let*((p (* (car t) 4)))
(cons (OR
(<< (string-ref message (+ p 0)) 24)
(<< (string-ref message (+ p 1)) 16)
(<< (string-ref message (+ p 2)) 8)
(<< (string-ref message (+ p 3)) 0))
(loop (cdr t)))))))
(t 16))
(if (eq? t 80)
W
(cycle (append W (list
(XOR
(rol 1 (list-ref W (- t 3)))
(rol 1 (list-ref W (- t 8)))
(rol 1 (list-ref W (- t 14)))
(rol 1 (list-ref W (- t 16))))))
(+ t 1)))))
(define (sha1:digest message)
(let*((h0 #x67452301)
(h1 #xEFCDAB89)
(h2 #x98BADCFE)
(h3 #x10325476)
(h4 #xC3D2E1F0)
(K '(#x5A827999 #x6ED9EBA1 #x8F1BBCDC #xCA62C1D6))
(padded-message (sha1-pad-message message))
(n (/ (string-length padded-message) 64)))
(let main ((i 0)
(A h0) (B h1) (C h2) (D h3) (E h4))
(if (= i n)
(fold append null
(list (word->list A) (word->list B) (word->list C) (word->list D) (word->list E)))
(let*((message (substring padded-message (* i 64) (+ (* i 64) 64)))
(W (message->words message)))
(let*((a b c d e ; round 1
(let loop ((a A) (b B) (c C) (d D) (e E) (t 0))
(if (< t 20)
(loop (->32
(+ (rol 5 a)
(OR (band b c) (band (NOT b) d))
e
(list-ref W t)
(list-ref K 0)))
a
(rol 30 b)
c
d
(+ t 1))
(values a b c d e))))
(a b c d e ; round 2
(let loop ((a a) (b b) (c c) (d d) (e e) (t 20))
(if (< t 40)
(loop (->32
(+ (rol 5 a)
(XOR b c d)
e
(list-ref W t)
(list-ref K 1)))
a
(rol 30 b)
c
d
(+ t 1))
(values a b c d e))))
(a b c d e ; round 3
(let loop ((a a) (b b) (c c) (d d) (e e) (t 40))
(if (< t 60)
(loop (->32
(+ (rol 5 a)
(OR (band b c) (band b d) (band c d))
e
(list-ref W t)
(list-ref K 2)))
a
(rol 30 b)
c
d
(+ t 1))
(values a b c d e))))
(a b c d e ; round 4
(let loop ((a a) (b b) (c c) (d d) (e e) (t 60))
(if (< t 80)
(loop (->32
(+ (rol 5 a)
(XOR b c d)
e
(list-ref W t)
(list-ref K 3)))
a
(rol 30 b)
c
d
(+ t 1))
(values a b c d e)))))
(main (+ i 1)
(->32 (+ A a))
(->32 (+ B b))
(->32 (+ C c))
(->32 (+ D d))
(->32 (+ E e)))))))))
|
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
|
#OxygenBasic
|
OxygenBasic
|
uses console
int i,j
string c
for i=32 to 127
select case i
case 32 : c="spc"
case 127: c="del"
case else c=chr i
end select
print i ": " c tab
j++
if j = 8 'columns
print cr
j=0
endif
next
pause
|
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
|
#Ring
|
Ring
|
# Project : Sierpinski triangle
norder=4
xy = list(40)
for i = 1 to 40
xy[i] = " "
next
triangle(1, 1, norder)
for i = 1 to 36
see xy[i] + nl
next
func triangle(x, y, n)
if n = 0
xy[y] = left(xy[y],x-1) + "*" + substr(xy[y],x+1)
else
n=n-1
length=pow(2,n)
triangle(x, y+length, n)
triangle(x+length, y, n)
triangle(x+length*2, y+length, n)
ok
|
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
|
#PHP
|
PHP
|
<?php
function isSierpinskiCarpetPixelFilled($x, $y) {
while (($x > 0) or ($y > 0)) {
if (($x % 3 == 1) and ($y % 3 == 1)) {
return false;
}
$x /= 3;
$y /= 3;
}
return true;
}
function sierpinskiCarpet($order) {
$size = pow(3, $order);
for ($y = 0 ; $y < $size ; $y++) {
for ($x = 0 ; $x < $size ; $x++) {
echo isSierpinskiCarpetPixelFilled($x, $y) ? '#' : ' ';
}
echo PHP_EOL;
}
}
for ($order = 0 ; $order <= 3 ; $order++) {
echo 'N=', $order, PHP_EOL;
sierpinskiCarpet($order);
echo PHP_EOL;
}
|
http://rosettacode.org/wiki/Semordnilap
|
Semordnilap
|
A semordnilap is a word (or phrase) that spells a different word (or phrase) backward. "Semordnilap" is a word that itself is a semordnilap.
Example: lager and regal
Task
This task does not consider semordnilap phrases, only single words.
Using only words from this list, report the total number of unique semordnilap pairs, and print 5 examples.
Two matching semordnilaps, such as lager and regal, should be counted as one unique pair.
(Note that the word "semordnilap" is not in the above dictionary.)
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
|
#Clojure
|
Clojure
|
(ns rosettacode.semordnilaps
(:require [clojure.string :as str])
[clojure.java.io :as io ]))
(def dict-file
(or (first *command-line-args*) "unixdict.txt"))
(def dict (-> dict-file io/reader line-seq set))
(defn semordnilap? [word]
(let [rev (str/reverse word)]
(and (not= word rev) (dict rev))))
(def semordnilaps
(->> dict
(filter semordnilap?)
(map #([% (str/reverse %)]))
(filter (fn [[x y]] (<= (compare x y) 0)))))
(printf "There are %d semordnilaps in %s. Here are 5:\n"
(count semordnilaps)
dict-file)
(dorun (->> semordnilaps shuffle (take 5) sort (map println)))
|
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.
|
#Ring
|
Ring
|
# Project : Short-circuit evaluation
for k = 1 to 2
word = ["AND","OR"]
see "========= " + word[k] + " ==============" + nl
for i = 0 to 1
for j = 0 to 1
see "a(" + i + ") " + word[k] +" b(" + j + ")" + nl
res =a(i)
if word[k] = "AND" and res != 0
res = b(j)
ok
if word[k] = "OR" and res = 0
res = b(j)
ok
next
next
next
func a(t)
see char(9) + "calls func a" + nl
a = t
return a
func b(t)
see char(9) + "calls func b" + nl
b = t
return b
|
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.
|
#Ruby
|
Ruby
|
def a( bool )
puts "a( #{bool} ) called"
bool
end
def b( bool )
puts "b( #{bool} ) called"
bool
end
[true, false].each do |a_val|
[true, false].each do |b_val|
puts "a( #{a_val} ) and b( #{b_val} ) is #{a( a_val ) and b( b_val )}."
puts
puts "a( #{a_val} ) or b( #{b_val} ) is #{a( a_val) or b( b_val )}."
puts
end
end
|
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)
|
#Lasso
|
Lasso
|
// with a lot of unneeded params.
// sends plain text and html in same email
// simple usage is below
email_send(
-host = 'mail.example.com',
-port = 25,
-timeout = 100,
-username = 'user.name',
-password = 'secure_password',
-priority = 'immediate',
-to = '[email protected]',
-cc = '[email protected]',
-bcc = '[email protected]',
-from = '[email protected]',
-replyto = '[email protected]',
-sender = '[email protected]',
-subject = 'Lasso is awesome',
-body = 'Lasso is awesome, you should try it!',
-html = '<p>Lasso is <b>awesome</b>, you should try it!</p>',
-attachments = '/path/to/myFile.txt'
)
// simple usage
// sends plan text email
email_send(
-host = 'mail.example.com',
-username = 'user.name',
-password = 'secure_password',
-to = '[email protected]',
-from = '[email protected]',
-subject = 'Lasso is awesome',
-body = 'Lasso is awesome, you should try it!'
)
|
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)
|
#Liberty_BASIC
|
Liberty BASIC
|
text$ = "This is a simple text message."
from$ = "[email protected]"
username$ = "[email protected]"
'password$ = "***********"
recipient$ = "[email protected]"
server$ = "auth.smtp.1and1.co.uk:25"
subject$ = chr$( 34) +text$ +chr$( 34) ' Use quotes to allow spaces in text.
message$ = chr$( 34) +"Hello world." +chr$( 34)
attach$ = "a.txt"
logfile$ = "sendemail.log"
cmd$ = " -f "; from$;_ 'from
" -t "; recipient$;_ 'to
" -u "; subject$;_ 'subject
" -s "; server$;_ 'server
" -m "; message$;_ 'message
" -a "; attach$;_ 'file to attach
" -l "; logfile$;_ 'file to log result in
" -xu "; username$ 'smtp user name
'" -xp "; password$ 'smtp password not given so will ask in a CMD window
run "sendEmail.exe "; cmd$, HIDE
end
|
http://rosettacode.org/wiki/Semiprime
|
Semiprime
|
Semiprime numbers are natural numbers that are products of exactly two (possibly equal) prime numbers.
Semiprimes are also known as:
semi-primes
biprimes
bi-primes
2-almost primes
or simply: P2
Example
1679 = 23 × 73
(This particular number was chosen as the length of the Arecibo message).
Task
Write a function determining whether a given number is semiprime.
See also
The Wikipedia article: semiprime.
The Wikipedia article: almost prime.
The OEIS sequence: A001358: semiprimes which has a shorter definition: the product of two primes.
|
#Common_Lisp
|
Common Lisp
|
(defun semiprimep (n &optional (a 2))
(cond ((> a (isqrt n)) nil)
((zerop (rem n a)) (and (primep a) (primep (/ n a))))
(t (semiprimep n (+ a 1)))))
(defun primep (n &optional (a 2))
(cond ((> a (isqrt n)) t)
((zerop (rem n a)) nil)
(t (primep n (+ a 1)))))
|
http://rosettacode.org/wiki/Semiprime
|
Semiprime
|
Semiprime numbers are natural numbers that are products of exactly two (possibly equal) prime numbers.
Semiprimes are also known as:
semi-primes
biprimes
bi-primes
2-almost primes
or simply: P2
Example
1679 = 23 × 73
(This particular number was chosen as the length of the Arecibo message).
Task
Write a function determining whether a given number is semiprime.
See also
The Wikipedia article: semiprime.
The Wikipedia article: almost prime.
The OEIS sequence: A001358: semiprimes which has a shorter definition: the product of two primes.
|
#Crystal
|
Crystal
|
def semiprime(n)
nf = 0
(2..n).each do |i|
while n % i == 0
return false if nf == 2
nf += 1
n /= i
end
end
nf == 2
end
(1675..1681).each { |n| puts "#{n} -> #{semiprime(n)}" }
|
http://rosettacode.org/wiki/SEDOLs
|
SEDOLs
|
Task
For each number list of 6-digit SEDOLs, calculate and append the checksum digit.
That is, given this input:
710889
B0YBKJ
406566
B0YBLH
228276
B0YBKL
557910
B0YBKR
585284
B0YBKT
B00030
Produce this output:
7108899
B0YBKJ7
4065663
B0YBLH2
2282765
B0YBKL9
5579107
B0YBKR5
5852842
B0YBKT7
B000300
Extra credit
Check each input is correctly formed, especially with respect to valid characters allowed in a SEDOL string.
Related tasks
Luhn test
ISIN
|
#ALGOL_68
|
ALGOL 68
|
[]INT sedol weights = (1, 3, 1, 7, 3, 9);
STRING reject = "AEIOUaeiou";
PROC strcspn = (STRING s,reject)INT: (
INT out:=0;
FOR i TO UPB s DO
IF char in string(s[i], LOC INT, reject) THEN
return out
FI;
out:=i
OD;
return out: out
);
PROC sedol checksum = (REF STRING sedol6)INT:
(
INT out;
INT len := UPB sedol6;
INT sum := 0;
IF sedol6[len-1] = REPR 10 THEN len-:=1; sedol6[len]:=null char FI;
IF len = 7 THEN
putf(stand error, ($"SEDOL code already checksummed? ("g")"l$, sedol6));
out := ABS ( BIN ABS sedol6[6] AND 16r7f); return out
FI;
IF len > 7 OR len < 6 OR strcspn(sedol6, reject) /= 6 THEN
putf(stand error, ($"not a SEDOL code? ("g")"l$, sedol6));
out := -1; return out
FI;
FOR i TO UPB sedol6 DO
sum+:=sedol weights[i]*
IF is digit(sedol6[i]) THEN
ABS sedol6[i]- ABS "0"
ELIF is alpha(sedol6[i]) THEN
(ABS to upper(sedol6[i])-ABS "A") + 10
ELSE
putf(stand error, $"SEDOL with not alphanumeric digit"l$);
out:=-1; return out
FI
OD;
out := (10 - (sum MOD 10)) MOD 10 + ABS "0";
return out: out
);
main:
(
STRING line;
on logical file end(stand in, (REF FILE f)BOOL: done);
DO getf(stand in, ($gl$,line));
INT sr := sedol checksum(line);
IF sr > 0 THEN
printf(($ggl$, line, REPR sedol checksum(line)))
FI
OD;
done: SKIP
)
|
http://rosettacode.org/wiki/Self-describing_numbers
|
Self-describing numbers
|
Self-describing numbers
You are encouraged to solve this task according to the task description, using any language you may know.
There are several so-called "self-describing" or "self-descriptive" integers.
An integer is said to be "self-describing" if it has the property that, when digit positions are labeled 0 to N-1, the digit in each position is equal to the number of times that that digit appears in the number.
For example, 2020 is a four-digit self describing number:
position 0 has value 2 and there are two 0s in the number;
position 1 has value 0 and there are no 1s in the number;
position 2 has value 2 and there are two 2s;
position 3 has value 0 and there are zero 3s.
Self-describing numbers < 100.000.000 are: 1210, 2020, 21200, 3211000, 42101000.
Task Description
Write a function/routine/method/... that will check whether a given positive integer is self-describing.
As an optional stretch goal - generate and display the set of self-describing numbers.
Related tasks
Fours is the number of letters in the ...
Look-and-say sequence
Number names
Self-referential sequence
Spelling of ordinal numbers
|
#C.2B.2B
|
C++
|
#include <iostream>
//--------------------------------------------------------------------------------------------------
typedef unsigned long long bigint;
//--------------------------------------------------------------------------------------------------
using namespace std;
//--------------------------------------------------------------------------------------------------
class sdn
{
public:
bool check( bigint n )
{
int cc = digitsCount( n );
return compare( n, cc );
}
void displayAll( bigint s )
{
for( bigint y = 1; y < s; y++ )
if( check( y ) )
cout << y << " is a Self-Describing Number." << endl;
}
private:
bool compare( bigint n, int cc )
{
bigint a;
while( cc )
{
cc--; a = n % 10;
if( dig[cc] != a ) return false;
n -= a; n /= 10;
}
return true;
}
int digitsCount( bigint n )
{
int cc = 0; bigint a;
memset( dig, 0, sizeof( dig ) );
while( n )
{
a = n % 10; dig[a]++;
cc++ ; n -= a; n /= 10;
}
return cc;
}
int dig[10];
};
//--------------------------------------------------------------------------------------------------
int main( int argc, char* argv[] )
{
sdn s;
s. displayAll( 1000000000000 );
cout << endl << endl; system( "pause" );
bigint n;
while( true )
{
system( "cls" );
cout << "Enter a positive whole number ( 0 to QUIT ): "; cin >> n;
if( !n ) return 0;
if( s.check( n ) ) cout << n << " is";
else cout << n << " is NOT";
cout << " a Self-Describing Number!" << endl << endl;
system( "pause" );
}
return 0;
}
|
http://rosettacode.org/wiki/Self_numbers
|
Self numbers
|
A number n is a self number if there is no number g such that g + the sum of g's digits = n. So 18 is not a self number because 9+9=18, 43 is not a self number because 35+5+3=43.
The task is:
Display the first 50 self numbers;
I believe that the 100000000th self number is 1022727208. You should either confirm or dispute my conjecture.
224036583-1 is a Mersenne prime, claimed to also be a self number. Extra credit to anyone proving it.
See also
OEIS: A003052 - Self numbers or Colombian numbers
Wikipedia: Self numbers
|
#Go
|
Go
|
package main
import (
"fmt"
"time"
)
func sumDigits(n int) int {
sum := 0
for n > 0 {
sum += n % 10
n /= 10
}
return sum
}
func max(x, y int) int {
if x > y {
return x
}
return y
}
func main() {
st := time.Now()
count := 0
var selfs []int
i := 1
pow := 10
digits := 1
offset := 9
lastSelf := 0
for count < 1e8 {
isSelf := true
start := max(i-offset, 0)
sum := sumDigits(start)
for j := start; j < i; j++ {
if j+sum == i {
isSelf = false
break
}
if (j+1)%10 != 0 {
sum++
} else {
sum = sumDigits(j + 1)
}
}
if isSelf {
count++
lastSelf = i
if count <= 50 {
selfs = append(selfs, i)
if count == 50 {
fmt.Println("The first 50 self numbers are:")
fmt.Println(selfs)
}
}
}
i++
if i%pow == 0 {
pow *= 10
digits++
offset = digits * 9
}
}
fmt.Println("\nThe 100 millionth self number is", lastSelf)
fmt.Println("Took", time.Since(st))
}
|
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.
|
#Mathematica.2FWolfram_Language
|
Mathematica/Wolfram Language
|
(* defining functions *)
setcc[a_, b_] := a <= x <= b
setoo[a_, b_] := a < x < b
setco[a_, b_] := a <= x < b
setoc[a_, b_] := a < x <= b
setSubtract[s1_, s2_] := s1 && Not[s2]; (* new function; subtraction not built in *)
inSetQ[y_, set_] := set /. x -> y
(* testing sets *)
set1 = setoc[0, 1] || setco[0, 2] (* union built in as || shortcut (OR) *);
Print[set1]
Print["First trial set, (0, 1] ∪ [0, 2) , testing for {0,1,2}:"]
Print[inSetQ[#, set1] & /@ {0, 1, 2}]
set2 = setco[0, 2] && setoc[1, 2]; (* intersection built in as && shortcut (AND) *)
Print[]
Print[set2]
Print["Second trial set, [0, 2) ∩ (1, 2], testing for {0,1,2}:"]
Print[inSetQ[#, set2] & /@ {0, 1, 2}]
Print[]
set3 = setSubtract[setco[0, 3], setoo[0, 1]];
Print[set3]
Print["Third trial set, [0, 3) \[Minus] (0, 1), testing for {0,1,2}"]
Print[inSetQ[#, set3] & /@ {0, 1, 2}]
Print[]
set4 = setSubtract[setco[0, 3], setcc[0, 1]];
Print[set4]
Print["Fourth trial set, [0,3)\[Minus][0,1], testing for {0,1,2}:"]
Print[inSetQ[#, set4] & /@ {0, 1, 2}]
|
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.
|
#Nim
|
Nim
|
import math, strformat, sugar
type
RealPredicate = (float) -> bool
RangeType {.pure} = enum Closed, BothOpen, LeftOpen, RightOpen
RealSet = object
low, high: float
predicate: RealPredicate
proc initRealSet(slice: Slice[float]; rangeType: RangeType): RealSet =
result = RealSet(low: slice.a, high: slice.b)
result.predicate = case rangeType
of Closed: (x: float) => x in slice
of BothOpen: (x: float) => slice.a < x and x < slice.b
of LeftOpen: (x: float) => slice.a < x and x <= slice.b
of RightOpen: (x: float) => slice.a <= x and x < slice.b
proc contains(s: RealSet; val: float): bool =
## Defining "contains" makes operator "in" available.
s.predicate(val)
proc `+`(s1, s2: RealSet): RealSet =
RealSet(low: min(s1.low, s2.low), high: max(s1.high, s2.high),
predicate: (x:float) => s1.predicate(x) or s2.predicate(x))
proc `*`(s1, s2: RealSet): RealSet =
RealSet(low: max(s1.low, s2.low), high: min(s1.high, s2.high),
predicate: (x:float) => s1.predicate(x) and s2.predicate(x))
proc `-`(s1, s2: RealSet): RealSet =
RealSet(low: s1.low, high: s1.high,
predicate: (x:float) => s1.predicate(x) and not s2.predicate(x))
const Interval = 0.00001
proc length(s: RealSet): float =
if s.low.classify() in {fcInf, fcNegInf} or s.high.classify() in {fcInf, fcNegInf}: return Inf
if s.high <= s.low: return 0
var p = s.low
var count = 0.0
while p < s.high:
if s.predicate(p): count += 1
p += Interval
result = count * Interval
proc isEmpty(s: RealSet): bool =
if s.high == s.low: not s.predicate(s.low)
else: s.length == 0
when isMainModule:
let
a = initRealSet(0.0..1.0, LeftOpen)
b = initRealSet(0.0..2.0, RightOpen)
c = initRealSet(1.0..2.0, LeftOpen)
d = initRealSet(0.0..3.0, RightOpen)
e = initRealSet(0.0..1.0, BothOpen)
f = initRealSet(0.0..1.0, Closed)
g = initRealSet(0.0..0.0, Closed)
for n in 0..2:
let x = n.toFloat
echo &"{n} ∊ (0, 1] ∪ [0, 2) is {x in (a + b)}"
echo &"{n} ∊ [0, 2) ∩ (1, 2] is {x in (b * c)}"
echo &"{n} ∊ [0, 3) − (0, 1) is {x in (d - e)}"
echo &"{n} ∊ [0, 3) − [0, 1] is {x in (d - f)}\n"
echo &"[0, 0] is empty is {g.isEmpty()}.\n"
let
aa = RealSet(low: 0, high: 10,
predicate: (x: float) => 0 < x and x < 10 and abs(sin(PI * x * x)) > 0.5)
bb = RealSet(low: 0, high: 10,
predicate: (x: float) => 0 < x and x < 10 and abs(sin(PI * x)) > 0.5)
cc = aa - bb
echo &"Approximative length of A - B is {cc.length}."
|
http://rosettacode.org/wiki/Sequence_of_primes_by_trial_division
|
Sequence of primes by trial division
|
Sequence of primes by trial division
You are encouraged to solve this task according to the task description, using any language you may know.
Task
Generate a sequence of primes by means of trial division.
Trial division is an algorithm where a candidate number is tested for being a prime by trying to divide it by other numbers.
You may use primes, or any numbers of your choosing, as long as the result is indeed a sequence of primes.
The sequence may be bounded (i.e. up to some limit), unbounded, starting from the start (i.e. 2) or above some given value.
Organize your function as you wish, in particular, it might resemble a filtering operation, or a sieving operation.
If you want to use a ready-made is_prime function, use one from the Primality by trial division page (i.e., add yours there if it isn't there already).
Related tasks
count in factors
prime decomposition
factors of an integer
Sieve of Eratosthenes
primality by trial division
factors of a Mersenne number
trial factoring of a Mersenne number
partition an integer X into N primes
|
#Delphi
|
Delphi
|
(lib 'sequences)
(define (is-prime? p)
(cond
[(< p 2) #f]
[(zero? (modulo p 2)) (= p 2)]
[else
(for/and ((d [3 5 .. (1+ (sqrt p))] )) (!zero? (modulo p d)))]))
(is-prime? 101) → #t
|
http://rosettacode.org/wiki/Sequence_of_primes_by_trial_division
|
Sequence of primes by trial division
|
Sequence of primes by trial division
You are encouraged to solve this task according to the task description, using any language you may know.
Task
Generate a sequence of primes by means of trial division.
Trial division is an algorithm where a candidate number is tested for being a prime by trying to divide it by other numbers.
You may use primes, or any numbers of your choosing, as long as the result is indeed a sequence of primes.
The sequence may be bounded (i.e. up to some limit), unbounded, starting from the start (i.e. 2) or above some given value.
Organize your function as you wish, in particular, it might resemble a filtering operation, or a sieving operation.
If you want to use a ready-made is_prime function, use one from the Primality by trial division page (i.e., add yours there if it isn't there already).
Related tasks
count in factors
prime decomposition
factors of an integer
Sieve of Eratosthenes
primality by trial division
factors of a Mersenne number
trial factoring of a Mersenne number
partition an integer X into N primes
|
#EchoLisp
|
EchoLisp
|
(lib 'sequences)
(define (is-prime? p)
(cond
[(< p 2) #f]
[(zero? (modulo p 2)) (= p 2)]
[else
(for/and ((d [3 5 .. (1+ (sqrt p))] )) (!zero? (modulo p d)))]))
(is-prime? 101) → #t
|
http://rosettacode.org/wiki/Sequence_of_non-squares
|
Sequence of non-squares
|
Task
Show that the following remarkable formula gives the sequence of non-square natural numbers:
n + floor(1/2 + sqrt(n))
Print out the values for n in the range 1 to 22
Show that no squares occur for n less than one million
This is sequence A000037 in the OEIS database.
|
#C.2B.2B
|
C++
|
#include <iostream>
#include <algorithm>
#include <vector>
#include <cmath>
#include <boost/bind.hpp>
#include <iterator>
double nextNumber( double number ) {
return number + floor( 0.5 + sqrt( number ) ) ;
}
int main( ) {
std::vector<double> non_squares ;
typedef std::vector<double>::iterator SVI ;
non_squares.reserve( 1000000 ) ;
//create a vector with a million sequence numbers
for ( double i = 1.0 ; i < 100001.0 ; i += 1 )
non_squares.push_back( nextNumber( i ) ) ;
//copy the first numbers to standard out
std::copy( non_squares.begin( ) , non_squares.begin( ) + 22 ,
std::ostream_iterator<double>(std::cout, " " ) ) ;
std::cout << '\n' ;
//find if floor of square root equals square root( i. e. it's a square number )
SVI found = std::find_if ( non_squares.begin( ) , non_squares.end( ) ,
boost::bind( &floor, boost::bind( &sqrt, _1 ) ) == boost::bind( &sqrt, _1 ) ) ;
if ( found != non_squares.end( ) ) {
std::cout << "Found a square number in the sequence!\n" ;
std::cout << "It is " << *found << " !\n" ;
}
else {
std::cout << "Up to 1000000, found no square number in the sequence!\n" ;
}
return 0 ;
}
|
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
|
#C.2B.2B
|
C++
|
#include <set>
#include <iostream>
#include <iterator>
#include <algorithm>
namespace set_display {
template <class T>
std::ostream& operator<<(std::ostream& os, const std::set<T>& set)
{
os << '[';
if (!set.empty()) {
std::copy(set.begin(), --set.end(), std::ostream_iterator<T>(os, ", "));
os << *--set.end();
}
return os << ']';
}
}
template <class T>
bool contains(const std::set<T>& set, const T& key)
{
return set.count(key) != 0;
}
template <class T>
std::set<T> set_union(const std::set<T>& a, const std::set<T>& b)
{
std::set<T> result;
std::set_union(a.begin(), a.end(), b.begin(), b.end(), std::inserter(result, result.end()));
return result;
}
template <class T>
std::set<T> set_intersection(const std::set<T>& a, const std::set<T>& b)
{
std::set<T> result;
std::set_intersection(a.begin(), a.end(), b.begin(), b.end(), std::inserter(result, result.end()));
return result;
}
template <class T>
std::set<T> set_difference(const std::set<T>& a, const std::set<T>& b)
{
std::set<T> result;
std::set_difference(a.begin(), a.end(), b.begin(), b.end(), std::inserter(result, result.end()));
return result;
}
template <class T>
bool is_subset(const std::set<T>& set, const std::set<T>& subset)
{
return std::includes(set.begin(), set.end(), subset.begin(), subset.end());
}
int main()
{
using namespace set_display;
std::set<int> a{2, 5, 7, 5, 9, 2}; //C++11 initialization syntax
std::set<int> b{1, 5, 9, 7, 4 };
std::cout << "a = " << a << '\n';
std::cout << "b = " << b << '\n';
int value1 = 8, value2 = 5;
std::cout << "Set a " << (contains(a, value1) ? "contains " : "does not contain ") << value1 << '\n';
std::cout << "Set a " << (contains(a, value2) ? "contains " : "does not contain ") << value2 << '\n';
std::cout << "Union of a and b: " << set_union(a, b) << '\n';
std::cout << "Intersection of a and b: " << set_intersection(a, b) << '\n';
std::cout << "Difference of a and b: " << set_difference(a, b) << '\n';
std::set<int> sub{5, 9};
std::cout << "Set b " << (is_subset(a, b) ? "is" : "is not") << " a subset of a\n";
std::cout << "Set " << sub << ' ' << (is_subset(a, sub) ? "is" : "is not") << " a subset of a\n";
std::set<int> copy = a;
std::cout << "a " << (a == copy ? "equals " : "does not equal ") << copy << '\n';
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
|
#AppleScript
|
AppleScript
|
on sieveOfEratosthenes(limit)
script o
property numberList : {missing value}
end script
repeat with n from 2 to limit
set end of o's numberList to n
end repeat
repeat with n from 2 to (limit ^ 0.5 div 1)
if (item n of o's numberList is n) then
repeat with multiple from (n * n) to limit by n
set item multiple of o's numberList to missing value
end repeat
end if
end repeat
return o's numberList's numbers
end sieveOfEratosthenes
sieveOfEratosthenes(1000)
|
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
|
#Phix
|
Phix
|
with javascript_semantics
function has_intersection(sequence set1, set2)
for i=1 to length(set1) do
if find(set1[i],set2) then
return true
end if
end for
return false
end function
function get_union(sequence set1, set2)
for i=1 to length(set2) do
if not find(set2[i],set1) then
set1 = append(set1,set2[i])
end if
end for
return set1
end function
function consolidate(sequence sets)
for i=length(sets) to 1 by -1 do
for j=length(sets) to i+1 by -1 do
if has_intersection(sets[i],sets[j]) then
sets[i] = get_union(sets[i],sets[j])
sets[j..j] = {}
end if
end for
end for
return sets
end function
?consolidate({"AB","CD"})
?consolidate({"AB","BD"})
?consolidate({"AB","CD","DB"})
?consolidate({"HIK","AB","CD","DB","FGH"})
|
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
|
#Wren
|
Wren
|
import "/math" for Int
var limit = 22
var numbers = List.filled(limit, 0)
var i = 1
while (true) {
var nd = Int.divisors(i).count
if (nd <= limit && numbers[nd-1] == 0) {
numbers[nd-1] = i
if (numbers.all { |n| n > 0 }) break
}
i = i + 1
}
System.print("The first %(limit) terms are:")
System.print(numbers)
|
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
|
#Vlang
|
Vlang
|
import crypto.sha256
fn main() {
println("${sha256.hexhash('Rosetta code')}")
mut h := sha256.new()
h.write('Rosetta code'.bytes()) ?
println('${h.checksum().map(it.hex()).join('')}')
}
|
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
|
#Wren
|
Wren
|
import "/crypto" for Sha256
import "/fmt" for Fmt
var strings = [
"",
"a",
"abc",
"message digest",
"abcdefghijklmnopqrstuvwxyz",
"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789",
"12345678901234567890123456789012345678901234567890123456789012345678901234567890",
"The quick brown fox jumps over the lazy dog",
"The quick brown fox jumps over the lazy cog",
"Rosetta code"
]
for (s in strings) {
var hash = Sha256.digest(s)
Fmt.print("$s <== '$0s'", hash, s)
}
|
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.
|
#Seed7
|
Seed7
|
$ include "seed7_05.s7i";
include "msgdigest.s7i";
const proc: main is func
begin
writeln(hex(sha1("Rosetta Code")));
end func;
|
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.
|
#Sidef
|
Sidef
|
var sha = frequire('Digest::SHA');
say sha.sha1_hex('Rosetta Code');
|
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
|
#Perl
|
Perl
|
use charnames ':full';
binmode STDOUT, ':utf8';
sub glyph {
my($n) = @_;
if ($n < 33) { chr 0x2400 + $n } # display symbol names for invisible glyphs
elsif ($n==124) { '<nowiki>|</nowiki>' }
elsif ($n==127) { 'DEL' }
else { chr $n }
}
print qq[{|class="wikitable" style="text-align:center;background-color:hsl(39, 90%, 95%)"\n];
for (0..127) {
print qq[|-\n] unless $_ % 16;;
printf qq[|%d<br>0x%02X<br><big><big title="%s">%s</big></big>\n],
$_, $_, charnames::viacode($_), glyph($_);
}
}
print qq[|}\n];
|
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
|
#Ruby
|
Ruby
|
ruby -le'16.times{|y|print" "*(15-y),*(0..y).map{|x|~y&x>0?" ":" *"}}'
|
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
|
#Picat
|
Picat
|
in_carpet(X, Y) =>
while (X != 0, Y != 0)
if (X mod 3 == 1, Y mod 3 == 1) then
false
end,
X := X div 3,
Y := Y div 3
end.
in_carpet(_, _) =>
true.
main(Args) =>
N = to_int(Args[1]),
Power1 = 3 ** N - 1,
foreach (I in 0..Power1)
foreach (J in 0..Power1)
printf("%w", cond(in_carpet(I, J), "*", " "))
end,
nl
end.
|
http://rosettacode.org/wiki/Semordnilap
|
Semordnilap
|
A semordnilap is a word (or phrase) that spells a different word (or phrase) backward. "Semordnilap" is a word that itself is a semordnilap.
Example: lager and regal
Task
This task does not consider semordnilap phrases, only single words.
Using only words from this list, report the total number of unique semordnilap pairs, and print 5 examples.
Two matching semordnilaps, such as lager and regal, should be counted as one unique pair.
(Note that the word "semordnilap" is not in the above dictionary.)
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
|
#Common_Lisp
|
Common Lisp
|
(defun semordnilaps (word-list)
(let ((word-map (make-hash-table :test 'equal)))
(loop for word in word-list do
(setf (gethash word word-map) t))
(loop for word in word-list
for rword = (reverse word)
when (and (string< word rword) (gethash rword word-map))
collect (cons word rword))))
(defun main ()
(let ((words
(semordnilaps
(with-open-file (s "unixdict.txt")
(loop for line = (read-line s nil nil)
until (null line)
collect (string-right-trim #(#\space #\return #\newline) line))))))
(format t "Found pairs: ~D" (length words))
(loop for x from 1 to 5
for word in words
do (print word)))
(values))
|
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.
|
#Run_BASIC
|
Run BASIC
|
for k = 1 to 2
ao$ = word$("AND,OR",k,",")
print "========= ";ao$;" =============="
for i = 0 to 1
for j = 0 to 1
print "a("; i; ") ";ao$;" b("; j; ")"
res =a(i) 'call always
'print res;"<===="
if ao$ = "AND" and res <> 0 then res = b(j)
if ao$ = "OR" and res = 0 then res = b(j)
next
next
next k
end
function a( t)
print chr$(9);"calls func a"
a = t
end function
function b( t)
print chr$(9);"calls func b"
b = t
end function
|
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.
|
#Rust
|
Rust
|
fn a(foo: bool) -> bool {
println!("a");
foo
}
fn b(foo: bool) -> bool {
println!("b");
foo
}
fn main() {
for i in vec![true, false] {
for j in vec![true, false] {
println!("{} and {} == {}", i, j, a(i) && b(j));
println!("{} or {} == {}", i, j, a(i) || b(j));
println!();
}
}
}
|
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)
|
#Lingo
|
Lingo
|
----------------------------------------
-- Sends email via SMTP using senditquiet.exe (15 KB)
-- @param {string} fromAddr
-- @param {string} toAddr - multiple addresses separated with ;
-- @param {string} subject
-- @param {string} message - use "\n" for line breaks
-- @param {string} [cc=VOID] - optional; multiple addresses separated with ;
-- @param {string} [bcc=VOID] - optional; multiple addresses separated with ;
-- @param {propList} [serverProps=VOID] - optional; allows to overwrite default settings
-- @return {bool} success
----------------------------------------
on sendEmail (fromAddr, toAddr, subject, message, cc, bcc, serverProps)
sx = xtra("Shell").new()
-- senditquiet.exe in folder "bin" relative to current movie
sx.shell_setcurrentdir(_movie.path&"bin")
-- defaults
host = "smtp.gmail.com"
protocol = "ssl"
port = 587
user = "johndoe"
pass = "foobar"
-- if propList 'serverProps' was passed, overwrite defaults
if ilk(serverProps)=#propList then
repeat with i = 1 to serverProps.count
do(serverProps.getPropAt(i)&"=""E&serverProps[i]"E)
end repeat
end if
cmd = "senditquiet"
put " -s "&host after cmd
put " -protocol "&protocol after cmd
put " -port "&port after cmd
put " -u "&user after cmd
put " -p "&pass after cmd
put " -f ""E&fromAddr"E after cmd
put " -t ""E&toAddr"E after cmd
put " -subject ""E&subject"E after cmd
put " -body ""E&message"E after cmd
-- optional args
if not voidP(cc) then put " -cc ""E&cc"E after cmd
if not voidP(bcc) then put " -bcc ""E&bcc"E after cmd
put " 1>nul 2>nul & if errorlevel 1 echo ERROR" after cmd
res = sx.shell_cmd(cmd)
return not(res contains "ERROR")
end
|
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)
|
#LiveCode
|
LiveCode
|
revMail "[email protected]",,"Help!",field "Message"
|
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)
|
#LotusScript
|
LotusScript
|
Dim session As New NotesSession
Dim db As NotesDatabase
Dim doc As NotesDocument
Set db = session.CurrentDatabase
Set doc = New NotesDocument( db )
doc.Form = "Memo"
doc.SendTo = "John Doe"
doc.Subject = "Subject of this mail"
Call doc.Send( False )
|
http://rosettacode.org/wiki/Semiprime
|
Semiprime
|
Semiprime numbers are natural numbers that are products of exactly two (possibly equal) prime numbers.
Semiprimes are also known as:
semi-primes
biprimes
bi-primes
2-almost primes
or simply: P2
Example
1679 = 23 × 73
(This particular number was chosen as the length of the Arecibo message).
Task
Write a function determining whether a given number is semiprime.
See also
The Wikipedia article: semiprime.
The Wikipedia article: almost prime.
The OEIS sequence: A001358: semiprimes which has a shorter definition: the product of two primes.
|
#D
|
D
|
bool semiprime(long n) pure nothrow @safe @nogc {
auto nf = 0;
foreach (immutable i; 2 .. n + 1) {
while (n % i == 0) {
if (nf == 2)
return false;
nf++;
n /= i;
}
}
return nf == 2;
}
void main() {
import std.stdio;
foreach (immutable n; 1675 .. 1681)
writeln(n, " -> ", n.semiprime);
}
|
http://rosettacode.org/wiki/SEDOLs
|
SEDOLs
|
Task
For each number list of 6-digit SEDOLs, calculate and append the checksum digit.
That is, given this input:
710889
B0YBKJ
406566
B0YBLH
228276
B0YBKL
557910
B0YBKR
585284
B0YBKT
B00030
Produce this output:
7108899
B0YBKJ7
4065663
B0YBLH2
2282765
B0YBKL9
5579107
B0YBKR5
5852842
B0YBKT7
B000300
Extra credit
Check each input is correctly formed, especially with respect to valid characters allowed in a SEDOL string.
Related tasks
Luhn test
ISIN
|
#ALGOL_W
|
ALGOL W
|
begin
% returns the check digit for the specified SEDOL %
string(1) procedure sedolCheckDigit ( string(6) value sedol ) ;
begin
integer checkSum, checkDigit;
checkSum := 0;
for cPos := 0 until 5 do begin
string(1) c;
integer digit;
c := sedol( cPos // 1 );
if c >= "0" and c <= "9"
then digit := decode( c ) - decode( "0" )
else digit := 10 + ( decode( c ) - decode( "A" ) );
checkSum := checkSum + ( ( case cPos + 1 of ( 1, 3, 1, 7, 3, 9 ) ) * digit )
end for_cPos ;
checkDigit := ( 10 - ( checkSum rem 10 ) ) rem 10;
if checkDigit < 10
then code( decode( "0" ) + checkDigit )
else code( decode( "A" ) + ( checkDigit - 10 ) )
end sedolCheckDigit ;
% task test cases %
procedure testCheckDigit ( string(6) value sedol; string(1) value expectedCheckDigit ) ;
begin
string(1) checkDigit;
checkDigit := sedolCheckDigit( sedol );
write( s_w := 0, sedol, checkDigit );
if checkDigit not = expectedCheckDigit then writeon( " ?? expected: ", expectedCheckDigit )
end testCheckDigit ;
testCheckDigit( "710889", "9" );
testCheckDigit( "B0YBKJ", "7" );
testCheckDigit( "406566", "3" );
testCheckDigit( "B0YBLH", "2" );
testCheckDigit( "228276", "5" );
testCheckDigit( "B0YBKL", "9" );
testCheckDigit( "557910", "7" );
testCheckDigit( "B0YBKR", "5" );
testCheckDigit( "585284", "2" );
testCheckDigit( "B0YBKT", "7" );
testCheckDigit( "B00030", "0" )
end.
|
http://rosettacode.org/wiki/Self-describing_numbers
|
Self-describing numbers
|
Self-describing numbers
You are encouraged to solve this task according to the task description, using any language you may know.
There are several so-called "self-describing" or "self-descriptive" integers.
An integer is said to be "self-describing" if it has the property that, when digit positions are labeled 0 to N-1, the digit in each position is equal to the number of times that that digit appears in the number.
For example, 2020 is a four-digit self describing number:
position 0 has value 2 and there are two 0s in the number;
position 1 has value 0 and there are no 1s in the number;
position 2 has value 2 and there are two 2s;
position 3 has value 0 and there are zero 3s.
Self-describing numbers < 100.000.000 are: 1210, 2020, 21200, 3211000, 42101000.
Task Description
Write a function/routine/method/... that will check whether a given positive integer is self-describing.
As an optional stretch goal - generate and display the set of self-describing numbers.
Related tasks
Fours is the number of letters in the ...
Look-and-say sequence
Number names
Self-referential sequence
Spelling of ordinal numbers
|
#Common_Lisp
|
Common Lisp
|
(defun to-ascii (str) (mapcar #'char-code (coerce str 'list)))
(defun to-digits (n)
(mapcar #'(lambda(v) (- v 48)) (to-ascii (princ-to-string n))))
(defun count-digits (n)
(do
((counts (make-array '(10) :initial-contents '(0 0 0 0 0 0 0 0 0 0)))
(curlist (to-digits n) (cdr curlist)))
((null curlist) counts)
(setf (aref counts (car curlist)) (+ 1 (aref counts (car curlist)))))))
(defun self-described-p (n)
(if (not (numberp n))
nil
(do ((counts (count-digits n))
(ipos 0 (+ 1 ipos))
(digits (to-digits n) (cdr digits)))
((null digits) t)
(if (not (eql (car digits) (aref counts ipos))) (return nil)))))
|
http://rosettacode.org/wiki/Self_numbers
|
Self numbers
|
A number n is a self number if there is no number g such that g + the sum of g's digits = n. So 18 is not a self number because 9+9=18, 43 is not a self number because 35+5+3=43.
The task is:
Display the first 50 self numbers;
I believe that the 100000000th self number is 1022727208. You should either confirm or dispute my conjecture.
224036583-1 is a Mersenne prime, claimed to also be a self number. Extra credit to anyone proving it.
See also
OEIS: A003052 - Self numbers or Colombian numbers
Wikipedia: Self numbers
|
#Haskell
|
Haskell
|
import Control.Monad (forM_)
import Text.Printf
selfs :: [Integer]
selfs = sieve (sumFs [0..]) [0..]
where
sumFs = zipWith (+) [ a+b+c+d+e+f+g+h+i+j
| a <- [0..9] , b <- [0..9]
, c <- [0..9] , d <- [0..9]
, e <- [0..9] , f <- [0..9]
, g <- [0..9] , h <- [0..9]
, i <- [0..9] , j <- [0..9] ]
-- More idiomatic list generator is about three times slower
-- sumFs = zipWith (+) $ sum <$> replicateM 10 [0..9]
sieve (f:fs) (n:ns)
| n > f = sieve fs (n:ns)
| n `notElem` take 81 (f:fs) = n : sieve (f:fs) ns
| otherwise = sieve (f:fs) ns
main = do
print $ take 50 selfs
forM_ [1..8] $ \i ->
printf "1e%v\t%v\n" (i :: Int) (selfs !! (10^i-1))
|
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.
|
#PARI.2FGP
|
PARI/GP
|
set11(x,a,b)=select(x -> a <= x && x <= b, x);
set01(x,a,b)=select(x -> a < x && x <= b, x);
set10(x,a,b)=select(x -> a <= x && x < b, x);
set00(x,a,b)=select(x -> a < x && x < b, x);
V = [0, 1, 2];
setunion(set01(V, 0, 1), set10(V, 0, 2))
setintersect(set10(V, 0, 2), set01(V, 1, 2))
setminus(set10(V, 0, 3), set00(V, 0, 1))
setminus(set10(V, 0, 3), set11(V, 0, 1))
|
http://rosettacode.org/wiki/Sequence_of_primes_by_trial_division
|
Sequence of primes by trial division
|
Sequence of primes by trial division
You are encouraged to solve this task according to the task description, using any language you may know.
Task
Generate a sequence of primes by means of trial division.
Trial division is an algorithm where a candidate number is tested for being a prime by trying to divide it by other numbers.
You may use primes, or any numbers of your choosing, as long as the result is indeed a sequence of primes.
The sequence may be bounded (i.e. up to some limit), unbounded, starting from the start (i.e. 2) or above some given value.
Organize your function as you wish, in particular, it might resemble a filtering operation, or a sieving operation.
If you want to use a ready-made is_prime function, use one from the Primality by trial division page (i.e., add yours there if it isn't there already).
Related tasks
count in factors
prime decomposition
factors of an integer
Sieve of Eratosthenes
primality by trial division
factors of a Mersenne number
trial factoring of a Mersenne number
partition an integer X into N primes
|
#EDSAC_order_code
|
EDSAC order code
|
[List of primes by trial division, for Rosetta Code website.]
[EDSAC program, Initial Orders 2.]
[Division is done implicitly by the use of wheels.
One wheel for each possible prime divisor, up to an editable limit.]
T51K [G parameter: print subroutine, 54 locations.]
P56F [must be even address]
T47K [M parameter: main routine.]
P110F [must be even address]
[============================= M parameter ===============================]
E25KTM
GK
[35-bit values. First clear them completely.
This is done to ensure that the middle bit ("sandwich digit") is zero.]
T#ZPF T2#ZPF T4#ZPF T6#ZPF T8#ZPF
[Back to normal loading]
TZ
[0] PDPF [number under test; initially to 1, pre-inc'd to 5]
[2] P1FPF [increment, alternately 2 and 4]
[4] P12DPF ['milestone', square of prime; initially 25]
[6] PDPF [constant 1]
[8] P3FPF [constant 6]
[17-bit values]
[10] P30F [*EDIT HERE* Number of primes to store (in address field)]
[11] PF [flag < 0 if number is prime; 0 if factor is found]
[12] #F [figure shift]
[13] @F [carriage return]
[14] &F [line feed]
[15] K4096F [null char]
[16] A112@ [A order for list{0}]
[17] T112@ [T order for list{0}]
[18] AF [limit of A order for testing primes]
[19] AF [limit of A order for loading wheels]
[20] TF [limit of T order for storing primes]
[21] O1F [subtract from T order to make A order for previous address]
[22] W1F [add to T order to make U order for next address]
[23] OF [add to A order to make T order for same address]
[24] P2F [to inc an address by 2]
[Enter with acc = 0]
[25] O12@ [set teleprinter to figures]
[Set limits for list of trial prime divisors.
The list contains wheels and negatives of primes, thus:
wheel for 5; -5; wheel for 7; -7; wheel for 11; -11; etc]
A10@ [number of items in prime list]
LD [times 2 words per item (wheel + prime)]
A17@ [add T order for list{0}]
U20@ [store T order for exclusive end of wheels]
S21@ [make A order for inclusive end of primes]
T19@ [store it]
A16@ [load A order for start of lise]
U18@ [store as exclusive end of active wheels]
A2F [inc address, exclusive end of active primes]
T100@ [plant in code]
A17@ [load T order to store first wheel]
T89@ [plant in code]
[Main loop: update increment, alternately 2 and 4]
[Assume acc = 0;]
[38] A8#@ [load 6]
S2#@ [subtract incremet]
T2#@ [store new increment]
[First priority: keep the wheels turning]
A16@ [load order that loads first wheel]
U11@ [set prime flag (any negative value will do)]
[43] U49@ [plant order in code]
S18@ [more wheels to test?]
E66@ [if not, jump with acc = 0]
A18@ [restore after test]
A23@ [make order to store wheel]
T62@ [plant in code]
[49] AF [load wheel]
A2@ [apply current inc as 17-bit 2 or 4]
G62@ [if wheel still < 0, just store updated value]
T1F [wheel >= 0, save in 1F]
S1F [wheel = 0?]
G56@ [no, skip next order]
T11@ [yes, so prime flag := 0]
[56] TF [clear acc]
A49@ [make A order for negative of prime]
A2F
T61@ [plant in code]
A1F [load wheel again]
[61] AF [add negative of prime to set wheel < 0]
[62] TF [store updated wheel]
A49@ [on to next wheel]
A24@
G43@ [always jump, since A < 0]
[Update the number under test. Assume acc = 0.]
[66] A#@ [add incrememnt to number under test]
A2#@
U#@ [store new number]
[Test whether we've reached the "milestone", i.e. number = p^2.]
S4#@ [subtract milestone]
E94@ [if reached milestone, jump with acc = 0]
TF [clear acc]
A11@ [acc < 0 if number is prime, 0 if composite]
E38@ [if composite, loop for next number with acc = 0]
[Here when number is found to be prime.]
TF [clear acc]
A#@ [load number]
TD [copy number 0D for printing]
[77] A77@
GG [call print routine, clears acc]
O13@O14@ [print CR, LF]
[If list of primes isn't yet full, store the prime just found.
It's slightly more convenient to store the negative of the prime.
Also, the wheel is initialized to the negative of the prime.]
A89@ [load T order to store ]
S20@ [compare with end of list]
E38@ [if list is full, loop with acc = 0]
A20@ [restore acc after test]
A22@ [make U order for wheel + 1, i.e. for prime]
T88@ [plant in code]
S@ [load negative of latest prime]
[88] UF [store in list]
[89] TF [initialize wheel for this prime]
A89@ [inc address by 2 for next time]
A24@
T89@
E38@ [loop with acc = 0]
[Here when number tested equals the "milestone" p^2 (p prime).
We need to activate the wheel for the prime p,
and update the milestone to the next prime after p.]
[Assume acc = 0.]
[94] A100@ [load A order below]
S19@ [test against A order for end of list]
E110@ [if reached end of list, exit]
A19@ [restore acc after test]
A24@ [inc address in A order]
T100@ [plant in next order]
[100] AF [load negative of prime from list]
TF [to 0F]
HF [to mult reg]
VF [acc := square of prime scaled by 2^(-32)]
R1F [scale by 2^(-34) for 35-bit value]
T4#@ [update]
A18@ [start testing next prime wheel]
A24@
T18@
E38@ [loop with acc = 0]
[Here on exit from program]
[110] O15@ [print null to flush printer buffer]
[111] ZF [stop]
[Array of wheels and primes, immediately after program code]
[112]
[============================ G parameter ==================================]
[Modified library subroutine P7.]
[Prints signed integer; up to 10 digits, left-justified.]
[Input: 0D = integer,]
[54 locations. Load at even address. Workspace 4D.]
E25KTG
GKA3FT42@A49@T31@ADE10@T31@A48@T31@SDTDH44#@NDYFLDT4DS43@
TFH17@S17@A43@G23@UFS43@T1FV4DAFG50@SFLDUFXFOFFFSFL4FT4D
A49@T31@A1FA43@G20@XFP1024FP610D@524D!FO46@O26@XFSFL8FT4DE39@
[========================= M parameter again ===============================]
E25KTM
GK
E25Z [define entry point]
PF [acc = 0 on entry]
|
http://rosettacode.org/wiki/Sequence_of_primes_by_trial_division
|
Sequence of primes by trial division
|
Sequence of primes by trial division
You are encouraged to solve this task according to the task description, using any language you may know.
Task
Generate a sequence of primes by means of trial division.
Trial division is an algorithm where a candidate number is tested for being a prime by trying to divide it by other numbers.
You may use primes, or any numbers of your choosing, as long as the result is indeed a sequence of primes.
The sequence may be bounded (i.e. up to some limit), unbounded, starting from the start (i.e. 2) or above some given value.
Organize your function as you wish, in particular, it might resemble a filtering operation, or a sieving operation.
If you want to use a ready-made is_prime function, use one from the Primality by trial division page (i.e., add yours there if it isn't there already).
Related tasks
count in factors
prime decomposition
factors of an integer
Sieve of Eratosthenes
primality by trial division
factors of a Mersenne number
trial factoring of a Mersenne number
partition an integer X into N primes
|
#Eiffel
|
Eiffel
|
class
APPLICATION
create
make
feature
make
do
sequence (1, 27)
end
sequence (lower, upper: INTEGER)
-- Sequence of primes from 'lower' to 'upper'.
require
lower_positive: lower > 0
upper_positive: upper > 0
lower_smaller: lower < upper
local
i: INTEGER
do
io.put_string ("Sequence of primes from " + lower.out + " up to " + upper.out + ".%N")
i := lower
if i \\ 2 = 0 then
i := i + 1
end
from
until
i > upper
loop
if is_prime (i) then
io.put_integer (i)
io.put_new_line
end
i := i + 2
end
end
feature {NONE}
is_prime (n: INTEGER): BOOLEAN
-- Is 'n' a prime number?
require
positiv_input: n > 0
local
i: INTEGER
max: REAL_64
math: DOUBLE_MATH
do
create math
if n = 2 then
Result := True
elseif n <= 1 or n \\ 2 = 0 then
Result := False
else
Result := True
max := math.sqrt (n)
from
i := 3
until
i > max
loop
if n \\ i = 0 then
Result := False
end
i := i + 2
end
end
end
end
|
http://rosettacode.org/wiki/Sequence_of_non-squares
|
Sequence of non-squares
|
Task
Show that the following remarkable formula gives the sequence of non-square natural numbers:
n + floor(1/2 + sqrt(n))
Print out the values for n in the range 1 to 22
Show that no squares occur for n less than one million
This is sequence A000037 in the OEIS database.
|
#Clojure
|
Clojure
|
;; provides floor and sqrt, but we use Java's sqrt as it's faster
;; (Clojure's is more exact)
(use 'clojure.contrib.math)
(defn nonsqr [#^Integer n] (+ n (floor (+ 0.5 (Math/sqrt n)))))
(defn square? [#^Double n]
(let [r (floor (Math/sqrt n))]
(= (* r r) n)))
(doseq [n (range 1 23)] (printf "%s -> %s\n" n (nonsqr n)))
(defn verify [] (not-any? square? (map nonsqr (range 1 1000000))) )
|
http://rosettacode.org/wiki/Sequence_of_non-squares
|
Sequence of non-squares
|
Task
Show that the following remarkable formula gives the sequence of non-square natural numbers:
n + floor(1/2 + sqrt(n))
Print out the values for n in the range 1 to 22
Show that no squares occur for n less than one million
This is sequence A000037 in the OEIS database.
|
#CLU
|
CLU
|
non_square = proc (n: int) returns (int)
return(n + real$r2i(0.5 + real$i2r(n)**0.5))
end non_square
is_square = proc (n: int) returns (bool)
return(n = real$r2i(real$i2r(n)**0.5))
end is_square
start_up = proc()
po: stream := stream$primary_output()
for n: int in int$from_to(1, 22) do
stream$puts(po, int$unparse(non_square(n)) || " ")
end
stream$putl(po, "")
begin
for n: int in int$from_to(1, 1000000) do
if is_square(non_square(n)) then exit square(n) end
end
stream$putl(po, "No squares found up to 1000000.")
end
except when square(n: int):
stream$putl(po, "Found square " || int$unparse(non_square(n))
|| " at n = " || int$unparse(n))
end
end start_up
|
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
|
#Ceylon
|
Ceylon
|
shared void run() {
value a = set {1, 2, 3};
value b = set {3, 4, 5};
value union = a | b;
value intersection = a & b;
value difference = a ~ b;
value subset = a.subset(b);
value equality = a == b;
print("set a: ``a``
set b: ``b``
1 in a? ``1 in a``
a | b: ``union``
a & b: ``intersection``
a ~ b: ``difference``
a subset of b? ``subset``
a == b? ``equality``");
}
|
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
|
#ARM_Assembly
|
ARM Assembly
|
/* ARM assembly Raspberry PI */
/* program cribleEras.s */
/* REMARK 1 : this program use routines in a include file
see task Include a file language arm assembly
for the routine affichageMess conversion10
see at end of this program the instruction include */
/* for constantes see task include a file in arm assembly */
/************************************/
/* Constantes */
/************************************/
.include "../constantes.inc"
.equ MAXI, 101
/*********************************/
/* Initialized data */
/*********************************/
.data
sMessResult: .asciz "Prime : @ \n"
szCarriageReturn: .asciz "\n"
/*********************************/
/* UnInitialized data */
/*********************************/
.bss
sZoneConv: .skip 24
TablePrime: .skip 4 * MAXI
/*********************************/
/* code section */
/*********************************/
.text
.global main
main: @ entry of program
ldr r4,iAdrTablePrime @ address prime table
mov r0,#2 @ prime 2
bl displayPrime
mov r1,#2
mov r2,#1
1: @ loop for multiple of 2
str r2,[r4,r1,lsl #2] @ mark multiple of 2
add r1,#2
cmp r1,#MAXI @ end ?
ble 1b @ no loop
mov r1,#3 @ begin indice
mov r3,#1
2:
ldr r2,[r4,r1,lsl #2] @ load table élément
cmp r2,#1 @ is prime ?
beq 4f
mov r0,r1 @ yes -> display
bl displayPrime
mov r2,r1
3: @ and loop to mark multiples of this prime
str r3,[r4,r2,lsl #2]
add r2,r1 @ add the prime
cmp r2,#MAXI @ end ?
ble 3b @ no -> loop
4:
add r1,#2 @ other prime in table
cmp r1,#MAXI @ end table ?
ble 2b @ no -> loop
100: @ standard end of the program
mov r0, #0 @ return code
mov r7, #EXIT @ request to exit program
svc #0 @ perform the system call
iAdrszCarriageReturn: .int szCarriageReturn
iAdrsMessResult: .int sMessResult
iAdrTablePrime: .int TablePrime
/******************************************************************/
/* Display prime table elements */
/******************************************************************/
/* r0 contains the prime */
displayPrime:
push {r1,lr} @ save registers
ldr r1,iAdrsZoneConv
bl conversion10 @ call décimal conversion
ldr r0,iAdrsMessResult
ldr r1,iAdrsZoneConv @ insert conversion in message
bl strInsertAtCharInc
bl affichageMess @ display message
100:
pop {r1,lr}
bx lr
iAdrsZoneConv: .int sZoneConv
/***************************************************/
/* ROUTINES INCLUDE */
/***************************************************/
.include "../affichage.inc"
|
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
|
#PicoLisp
|
PicoLisp
|
(de consolidate (S)
(when S
(let R (cons (car S))
(for X (consolidate (cdr S))
(if (mmeq X (car R))
(set R (uniq (conc X (car R))))
(conc R (cons X)) ) )
R ) ) )
|
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
|
#PL.2FI
|
PL/I
|
Set: procedure options (main); /* 13 November 2013 */
declare set(20) character (200) varying;
declare e character (1);
declare (i, n) fixed binary;
set = '';
n = 1;
do until (e = ']');
get edit (e) (a(1)); put edit (e) (a(1));
if e = '}' then n = n + 1; /* end of set. */
if e ^= '{' & e ^= ',' & e ^= '}' & e ^= ' ' then
set(n) = set(n) || e; /* Build set */
end;
/* We have read in all sets. */
n = n - 1; /* we have n sets */
/* Display the sets: */
put skip list ('The original sets:');
do i = 1 to n;
call print(i);
end;
/* Look for sets to combine: */
do i = 2 to n;
if length(set(i)) > 0 then
if search(set(1), set(i)) > 0 then
/* there's at least one common element */
do; call combine (1, i); set(i) = ''; end;
end;
put skip (2) list ('Results:');
do i = 1 to n;
if length(set(i)) > 0 then call print (i);
end;
combine: procedure (p, q);
declare (p, q) fixed binary;
declare e character (1);
declare i fixed binary;
do i = 1 to length(set(q));
e = substr(set(q), i, 1);
if index(set(p), e) = 0 then set(p) = set(p) || e;
end;
end combine;
print: procedure(k);
declare k fixed binary;
declare i fixed binary;
put edit ('{') (a);
do i = 1 to length(set(k));
put edit (substr(set(k), i, 1)) (a);
if i < length(set(k)) then put edit (',') (a);
end;
put edit ('} ') (a);
end print;
end Set;
|
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
|
#XPL0
|
XPL0
|
func Divisors(N); \Return number of divisors of N
int N, Count, D;
[Count:= 0;
for D:= 1 to N do
if rem(N/D) = 0 then Count:= Count+1;
return Count;
];
int N, AN;
[for N:= 1 to 15 do
[AN:= 0;
repeat AN:= AN+1 until Divisors(AN) = N;
IntOut(0, AN); ChOut(0, ^ );
];
]
|
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
|
#zkl
|
zkl
|
fcn countDivisors(n)
{ [1.. n.toFloat().sqrt()].reduce('wrap(s,i){ s + (if(0==n%i) 1 + (i!=n/i)) },0) }
A005179w:=(1).walker(*).tweak(fcn(n){
var N=0,cache=Dictionary();
if(cache.find(n)) return(cache.pop(n)); // prune
while(1){
if(n == (d:=countDivisors(N+=1))) return(N);
if(n<d and not cache.find(d)) cache[d]=N;
}
});
|
http://rosettacode.org/wiki/SHA-256
|
SHA-256
|
SHA-256 is the recommended stronger alternative to SHA-1. See FIPS PUB 180-4 for implementation details.
Either by using a dedicated library or implementing the algorithm in your language, show that the SHA-256 digest of the string "Rosetta code" is: 764faf5c61ac315f1497f9dfa542713965b785e5cc2f707d6468d7d1124cdfcf
|
#zkl
|
zkl
|
var MsgHash=Import("zklMsgHash");
MsgHash.SHA256("Rosetta code")=="764faf5c61ac315f1497f9dfa542713965b785e5cc2f707d6468d7d1124cdfcf"
|
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.
|
#Smalltalk
|
Smalltalk
|
PackageLoader fileInPackage: 'Digest'.
(SHA1 hexDigestOf: 'Rosetta Code') displayNl.
|
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.
|
#Tcl
|
Tcl
|
package require sha1
puts [sha1::sha1 "Rosetta Code"]
|
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
|
#Phix
|
Phix
|
with javascript_semantics
sequence ascii = {}
for ch=32 to 127 do
ascii = append(ascii,sprintf("%4d (#%02x): %c ",ch))
end for
puts(1,substitute(join_by(ascii,16,6),"\x7F","del"))
|
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
|
#Run_BASIC
|
Run BASIC
|
nOrder=4
dim xy$(40)
for i = 1 to 40
xy$(i) = " "
next i
call triangle 1, 1, nOrder
for i = 1 to 36
print xy$(i)
next i
end
SUB triangle x, y, n
IF n = 0 THEN
xy$(y) = left$(xy$(y),x-1) + "*" + mid$(xy$(y),x+1)
ELSE
n=n-1
length=2^n
call triangle x, y+length, n
call triangle x+length, y, n
call triangle x+length*2, y+length, n
END IF
END SUB
|
http://rosettacode.org/wiki/Sierpinski_carpet
|
Sierpinski carpet
|
Task
Produce a graphical or ASCII-art representation of a Sierpinski carpet of order N.
For example, the Sierpinski carpet of order 3 should look like this:
###########################
# ## ## ## ## ## ## ## ## #
###########################
### ###### ###### ###
# # # ## # # ## # # #
### ###### ###### ###
###########################
# ## ## ## ## ## ## ## ## #
###########################
######### #########
# ## ## # # ## ## #
######### #########
### ### ### ###
# # # # # # # #
### ### ### ###
######### #########
# ## ## # # ## ## #
######### #########
###########################
# ## ## ## ## ## ## ## ## #
###########################
### ###### ###### ###
# # # ## # # ## # # #
### ###### ###### ###
###########################
# ## ## ## ## ## ## ## ## #
###########################
The use of the # character is not rigidly required for ASCII art.
The important requirement is the placement of whitespace and non-whitespace characters.
Related task
Sierpinski triangle
|
#PicoLisp
|
PicoLisp
|
(de carpet (N)
(let Carpet '("#")
(do N
(setq Carpet
(conc
(mapcar '((S) (pack S S S)) Carpet)
(mapcar
'((S) (pack S (replace (chop S) "#" " ") S))
Carpet )
(mapcar '((S) (pack S S S)) Carpet) ) ) ) ) )
(mapc prinl (carpet 3))
|
http://rosettacode.org/wiki/Semordnilap
|
Semordnilap
|
A semordnilap is a word (or phrase) that spells a different word (or phrase) backward. "Semordnilap" is a word that itself is a semordnilap.
Example: lager and regal
Task
This task does not consider semordnilap phrases, only single words.
Using only words from this list, report the total number of unique semordnilap pairs, and print 5 examples.
Two matching semordnilaps, such as lager and regal, should be counted as one unique pair.
(Note that the word "semordnilap" is not in the above dictionary.)
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
|
#Crystal
|
Crystal
|
require "set"
UNIXDICT = File.read("unixdict.txt").lines
def word?(word : String)
UNIXDICT.includes?(word)
end
# is it a word and is it a word backwards?
semordnilap = UNIXDICT.select { |word| word?(word) && word?(word.reverse) }
# consolidate pairs like [bad, dab] == [dab, bad]
final_results = semordnilap.map { |word| [word, word.reverse].to_set }.uniq
# sets of N=1 mean the word is identical backwards
# print out the size, and 5 random pairs
puts final_results.size, final_results.sample(5)
|
http://rosettacode.org/wiki/Semordnilap
|
Semordnilap
|
A semordnilap is a word (or phrase) that spells a different word (or phrase) backward. "Semordnilap" is a word that itself is a semordnilap.
Example: lager and regal
Task
This task does not consider semordnilap phrases, only single words.
Using only words from this list, report the total number of unique semordnilap pairs, and print 5 examples.
Two matching semordnilaps, such as lager and regal, should be counted as one unique pair.
(Note that the word "semordnilap" is not in the above dictionary.)
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
|
#D
|
D
|
void main() {
import std.stdio, std.file, std.string, std.algorithm;
bool[string] seenWords;
size_t pairCount = 0;
foreach (const word; "unixdict.txt".readText.toLower.splitter) {
//const drow = word.dup.reverse();
auto drow = word.dup;
drow.reverse();
if (drow in seenWords) {
if (pairCount++ < 5)
writeln(word, " ", drow);
} else
seenWords[word] = true;
}
writeln("\nSemordnilap pairs: ", pairCount);
}
|
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.
|
#Sather
|
Sather
|
class MAIN is
a(v:BOOL):BOOL is
#OUT + "executing a\n";
return v;
end;
b(v:BOOL):BOOL is
#OUT + "executing b\n";
return v;
end;
main is
x:BOOL;
x := a(false) and b(true);
#OUT + "F and T = " + x + "\n\n";
x := a(true) or b(true);
#OUT + "T or T = " + x + "\n\n";
x := a(true) and b(false);
#OUT + "T and T = " + x + "\n\n";
x := a(false) or b(true);
#OUT + "F or T = " + x + "\n\n";
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.
|
#Scala
|
Scala
|
object ShortCircuit {
def a(b:Boolean)={print("Called A=%5b".format(b));b}
def b(b:Boolean)={print(" -> B=%5b".format(b));b}
def main(args: Array[String]): Unit = {
val boolVals=List(false,true)
for(aa<-boolVals; bb<-boolVals){
print("\nTesting A=%5b AND B=%5b -> ".format(aa, bb))
a(aa) && b(bb)
}
for(aa<-boolVals; bb<-boolVals){
print("\nTesting A=%5b OR B=%5b -> ".format(aa, bb))
a(aa) || b(bb)
}
println
}
}
|
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)
|
#Lua
|
Lua
|
-- load the smtp support
local smtp = require("socket.smtp")
-- Connects to server "localhost" and sends a message to users
-- "[email protected]", "[email protected]",
-- and "[email protected]".
-- Note that "fulano" is the primary recipient, "beltrano" receives a
-- carbon copy and neither of them knows that "sicrano" received a blind
-- carbon copy of the message.
from = "<[email protected]>"
rcpt = {
"<[email protected]>",
"<[email protected]>",
"<[email protected]>"
}
mesgt = {
headers = {
to = "Fulano da Silva <[email protected]>",
cc = '"Beltrano F. Nunes" <[email protected]>',
subject = "My first message"
},
body = "I hope this works. If it does, I can send you another 1000 copies."
}
r, e = smtp.send{
from = from,
rcpt = rcpt,
source = smtp.message(mesgt)
}
|
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)
|
#Mathematica.2FWolfram_Language
|
Mathematica/Wolfram Language
|
SendMail["From" -> "[email protected]", "To" -> "[email protected]",
"Subject" -> "Sending Email from Mathematica", "Body" -> "Hello world!",
"Server" -> "smtp.email.com"]
|
http://rosettacode.org/wiki/Semiprime
|
Semiprime
|
Semiprime numbers are natural numbers that are products of exactly two (possibly equal) prime numbers.
Semiprimes are also known as:
semi-primes
biprimes
bi-primes
2-almost primes
or simply: P2
Example
1679 = 23 × 73
(This particular number was chosen as the length of the Arecibo message).
Task
Write a function determining whether a given number is semiprime.
See also
The Wikipedia article: semiprime.
The Wikipedia article: almost prime.
The OEIS sequence: A001358: semiprimes which has a shorter definition: the product of two primes.
|
#DCL
|
DCL
|
$ p1 = f$integer( p1 )
$ if p1 .lt. 2
$ then
$ write sys$output "out of range 2 thru 2^31-1"
$ exit
$ endif
$
$ close /nolog primes
$ on control_y then $ goto clean
$ open primes primes.txt
$
$ loop1:
$ read /end_of_file = prime primes prime
$ prime = f$integer( prime )
$ loop2:
$ t = p1 / prime
$ if t * prime .eq. p1
$ then
$ if f$type( factorization ) .eqs. ""
$ then
$ factorization = f$string( prime )
$ else
$ factorization = factorization + "*" + f$string( prime )
$ endif
$ if t .eq. 1 then $ goto done
$ p1 = t
$ goto loop2
$ else
$ goto loop1
$ endif
$ prime:
$ if f$type( factorization ) .eqs. ""
$ then
$ factorization = f$string( p1 )
$ else
$ factorization = factorization + "*" + f$string( p1 )
$ endif
$ done:
$ show symbol factorization
$ if f$locate( "*", factorization ) .eq. f$length( factorization )
$ then
$ write sys$output "so, it is prime"
$ else
$ if f$element( 2, "*", factorization ) .eqs. "*" then $ write sys$output "so, it is semiprime"
$ endif
$
$ clean:
$ close primes
|
http://rosettacode.org/wiki/SEDOLs
|
SEDOLs
|
Task
For each number list of 6-digit SEDOLs, calculate and append the checksum digit.
That is, given this input:
710889
B0YBKJ
406566
B0YBLH
228276
B0YBKL
557910
B0YBKR
585284
B0YBKT
B00030
Produce this output:
7108899
B0YBKJ7
4065663
B0YBLH2
2282765
B0YBKL9
5579107
B0YBKR5
5852842
B0YBKT7
B000300
Extra credit
Check each input is correctly formed, especially with respect to valid characters allowed in a SEDOL string.
Related tasks
Luhn test
ISIN
|
#AppleScript
|
AppleScript
|
on appendCheckDigitToSEDOL(sedol)
if ((count sedol) is not 6) then ¬
return {false, "Error in appendCheckDigitToSEDOL handler: " & sedol & " doesn't have 6 characters."}
set chars to "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"
set vowels to "AEIOU"
set weights to {1, 3, 1, 7, 3, 9}
set s to 0
considering diacriticals but ignoring case -- In case these are set otherwise when this handler's called.
repeat with i from 1 to 6
set thisCharacter to character i of sedol
set o to (offset of thisCharacter in chars)
if ((o is 0) or (thisCharacter is in vowels)) then ¬
return {false, "Error in appendCheckDigitToSEDOL handler: " & sedol & " contains invalid character(s)."}
set s to s + (o - 1) * (item i of weights)
end repeat
end considering
return {true, sedol & ((10 - (s mod 10)) mod 10)}
end appendCheckDigitToSEDOL
-- Test code:
set input to "710889
B0YBKJ
406566
B0YBLH
228276
B0YBKL
557910
B0YBKR
585284
B0YBKT
B00030"
set output to {}
repeat with thisSEDOL in paragraphs of input
set {valid, theResult} to appendCheckDigitToSEDOL(thisSEDOL)
set end of output to theResult
end repeat
set astid to AppleScript's text item delimiters
set AppleScript's text item delimiters to linefeed
set output to output as text
set AppleScript's text item delimiters to astid
return output
|
http://rosettacode.org/wiki/Self-describing_numbers
|
Self-describing numbers
|
Self-describing numbers
You are encouraged to solve this task according to the task description, using any language you may know.
There are several so-called "self-describing" or "self-descriptive" integers.
An integer is said to be "self-describing" if it has the property that, when digit positions are labeled 0 to N-1, the digit in each position is equal to the number of times that that digit appears in the number.
For example, 2020 is a four-digit self describing number:
position 0 has value 2 and there are two 0s in the number;
position 1 has value 0 and there are no 1s in the number;
position 2 has value 2 and there are two 2s;
position 3 has value 0 and there are zero 3s.
Self-describing numbers < 100.000.000 are: 1210, 2020, 21200, 3211000, 42101000.
Task Description
Write a function/routine/method/... that will check whether a given positive integer is self-describing.
As an optional stretch goal - generate and display the set of self-describing numbers.
Related tasks
Fours is the number of letters in the ...
Look-and-say sequence
Number names
Self-referential sequence
Spelling of ordinal numbers
|
#Crystal
|
Crystal
|
def self_describing?(n)
digits = n.to_s.chars.map(&.to_i) # 12345 => [1, 2, 3, 4, 5]
digits.each_with_index.all? { |digit, idx| digits.count(idx) == digit }
end
t = Time.monotonic
600_000_000.times { |n| (puts "#{n} in #{(Time.monotonic - t).total_seconds} secs";\
t = Time.monotonic) if self_describing?(n) }
|
http://rosettacode.org/wiki/Self-describing_numbers
|
Self-describing numbers
|
Self-describing numbers
You are encouraged to solve this task according to the task description, using any language you may know.
There are several so-called "self-describing" or "self-descriptive" integers.
An integer is said to be "self-describing" if it has the property that, when digit positions are labeled 0 to N-1, the digit in each position is equal to the number of times that that digit appears in the number.
For example, 2020 is a four-digit self describing number:
position 0 has value 2 and there are two 0s in the number;
position 1 has value 0 and there are no 1s in the number;
position 2 has value 2 and there are two 2s;
position 3 has value 0 and there are zero 3s.
Self-describing numbers < 100.000.000 are: 1210, 2020, 21200, 3211000, 42101000.
Task Description
Write a function/routine/method/... that will check whether a given positive integer is self-describing.
As an optional stretch goal - generate and display the set of self-describing numbers.
Related tasks
Fours is the number of letters in the ...
Look-and-say sequence
Number names
Self-referential sequence
Spelling of ordinal numbers
|
#D
|
D
|
import std.stdio, std.algorithm, std.range, std.conv, std.string;
bool isSelfDescribing(in long n) pure nothrow @safe {
auto nu = n.text.representation.map!q{ a - '0' };
return nu.length.iota.map!(a => nu.count(a)).equal(nu);
}
void main() {
4_000_000.iota.filter!isSelfDescribing.writeln;
}
|
http://rosettacode.org/wiki/Self_numbers
|
Self numbers
|
A number n is a self number if there is no number g such that g + the sum of g's digits = n. So 18 is not a self number because 9+9=18, 43 is not a self number because 35+5+3=43.
The task is:
Display the first 50 self numbers;
I believe that the 100000000th self number is 1022727208. You should either confirm or dispute my conjecture.
224036583-1 is a Mersenne prime, claimed to also be a self number. Extra credit to anyone proving it.
See also
OEIS: A003052 - Self numbers or Colombian numbers
Wikipedia: Self numbers
|
#Java
|
Java
|
public class SelfNumbers {
private static final int MC = 103 * 1000 * 10000 + 11 * 9 + 1;
private static final boolean[] SV = new boolean[MC + 1];
private static void sieve() {
int[] dS = new int[10_000];
for (int a = 9, i = 9999; a >= 0; a--) {
for (int b = 9; b >= 0; b--) {
for (int c = 9, s = a + b; c >= 0; c--) {
for (int d = 9, t = s + c; d >= 0; d--) {
dS[i--] = t + d;
}
}
}
}
for (int a = 0, n = 0; a < 103; a++) {
for (int b = 0, d = dS[a]; b < 1000; b++, n += 10000) {
for (int c = 0, s = d + dS[b] + n; c < 10000; c++) {
SV[dS[c] + s++] = true;
}
}
}
}
public static void main(String[] args) {
sieve();
System.out.println("The first 50 self numbers are:");
for (int i = 0, count = 0; count <= 50; i++) {
if (!SV[i]) {
count++;
if (count <= 50) {
System.out.printf("%d ", i);
} else {
System.out.printf("%n%n Index Self number%n");
}
}
}
for (int i = 0, limit = 1, count = 0; i < MC; i++) {
if (!SV[i]) {
if (++count == limit) {
System.out.printf("%,12d %,13d%n", count, i);
limit *= 10;
}
}
}
}
}
|
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.
|
#Perl
|
Perl
|
use utf8;
# numbers used as boundaries to real sets. Each has 3 components:
# the real value x;
# a +/-1 indicating if it's x + ϵ or x - ϵ
# a 0/1 indicating if it's the left border or right border
# e.g. "[1.5, ..." is written "1.5, -1, 0", while "..., 2)" is "2, -1, 1"
package BNum;
use overload (
'""' => \&_str,
'<=>' => \&_cmp,
);
sub new {
my $self = shift;
bless [@_], ref $self || $self
}
sub flip {
my @a = @{+shift};
$a[2] = !$a[2];
bless \@a
}
my $brackets = qw/ [ ( ) ] /;
sub _str {
my $v = sprintf "%.2f", $_[0][0];
$_[0][2]
? $v . ($_[0][1] == 1 ? "]" : ")")
: ($_[0][1] == 1 ? "(" : "[" ) . $v;
}
sub _cmp {
my ($a, $b, $swap) = @_;
# if one of the argument is a normal number
if ($swap) { return -_ncmp($a, $b) }
if (!ref $b || !$b->isa(__PACKAGE__)) { return _ncmp($a, $b) }
$a->[0] <=> $b->[0] || $a->[1] <=> $b->[1]
}
sub _ncmp {
# $a is a BNum, $b is something comparable to a real
my ($a, $b) = @_;
$a->[0] <=> $b || $a->[1] <=> 0
}
package RealSet;
use Carp;
use overload (
'""' => \&_str,
'|' => \&_or,
'&' => \&_and,
'~' => \&_neg,
'-' => \&_diff,
'bool' => \¬_empty, # set is true if not empty
);
my %pm = qw/ [ -1 ( 1 ) -1 ] 1 /;
sub range {
my ($cls, $a, $b, $spec) = @_;
$spec =~ /^( \[ | \( )( \) | \] )$/x or croak "bad spec $spec";
$a = BNum->new($a, $pm{$1}, 0);
$b = BNum->new($b, $pm{$2}, 1);
normalize($a < $b ? [$a, $b] : [])
}
sub normalize {
my @a = @{+shift};
# remove invalid or duplicate borders, such as "[2, 1]" or "3) [3"
# note that "(a" == "a]" and "a)" == "[a", but "a)" < "(a" and
# "[a" < "a]"
for (my $i = $#a; $i > 0; $i --) {
splice @a, $i - 1, 2
if $a[$i] <= $a[$i - 1]
}
bless \@a
}
sub not_empty { scalar @{ normalize shift } }
sub _str {
my (@a, @s) = @{+shift} or return '()';
join " ∪ ", map { shift(@a).", ".shift(@a) } 0 .. $#a/2
}
sub _or {
# we may have nested ranges now; let only outmost ones survive
my $d = 0;
normalize [
map { $_->[2] ? --$d ? () : ($_)
: $d++ ? () : ($_) }
sort{ $a <=> $b } @{+shift}, @{+shift}
];
}
sub _neg {
normalize [
BNum->new('-inf', 1, 0),
map($_->flip, @{+shift}),
BNum->new('inf', -1, 1),
]
}
sub _and {
my $d = 0;
normalize [
map { $_->[2] ? --$d ? ($_) : ()
: $d++ ? ($_) : () }
sort{ $a <=> $b } @{+shift}, @{+shift}
];
}
sub _diff { shift() & ~shift() }
sub has {
my ($a, $b) = @_;
for (my $i = 0; $i < $#$a; $i += 2) {
return 1 if $a->[$i] <= $b && $b <= $a->[$i + 1]
}
return 0
}
sub len {
my ($a, $l) = shift;
for (my $i = 0; $i < $#$a; $i += 2) {
$l += $a->[$i+1][0] - $a->[$i][0]
}
return $l
}
package main;
use List::Util 'reduce';
sub rng { RealSet->range(@_) }
my @sets = (
rng(0, 1, '(]') | rng(0, 2, '[)'),
rng(0, 2, '[)') & rng(0, 2, '(]'),
rng(0, 3, '[)') - rng(0, 1, '()'),
rng(0, 3, '[)') - rng(0, 1, '[]'),
);
for my $i (0 .. $#sets) {
print "Set $i = ", $sets[$i], ": ";
for (0 .. 2) {
print "has $_; " if $sets[$i]->has($_);
}
print "\n";
}
# optional task
print "\n####\n";
sub brev { # show only head and tail if string too long
my $x = shift;
return $x if length $x < 60;
substr($x, 0, 30)." ... ".substr($x, -30, 30)
}
# "|sin(x)| > 1/2" means (n + 1/6) pi < x < (n + 5/6) pi
my $x = reduce { $a | $b }
map(rng(sqrt($_ + 1./6), sqrt($_ + 5./6), '()'), 0 .. 101);
$x &= rng(0, 10, '()');
print "A\t", '= {x | 0 < x < 10 and |sin(π x²)| > 1/2 }',
"\n\t= ", brev($x), "\n";
my $y = reduce { $a | $b }
map { rng($_ + 1./6, $_ + 5./6, '()') } 0 .. 11;
$y &= rng(0, 10, '()');
print "B\t", '= {x | 0 < x < 10 and |sin(π x)| > 1/2 }',
"\n\t= ", brev($y), "\n";
my $z = $x - $y;
print "A - B\t= ", brev($z), "\n\tlength = ", $z->len, "\n";
print $z ? "not empty\n" : "empty\n";
|
http://rosettacode.org/wiki/Sequence_of_primes_by_trial_division
|
Sequence of primes by trial division
|
Sequence of primes by trial division
You are encouraged to solve this task according to the task description, using any language you may know.
Task
Generate a sequence of primes by means of trial division.
Trial division is an algorithm where a candidate number is tested for being a prime by trying to divide it by other numbers.
You may use primes, or any numbers of your choosing, as long as the result is indeed a sequence of primes.
The sequence may be bounded (i.e. up to some limit), unbounded, starting from the start (i.e. 2) or above some given value.
Organize your function as you wish, in particular, it might resemble a filtering operation, or a sieving operation.
If you want to use a ready-made is_prime function, use one from the Primality by trial division page (i.e., add yours there if it isn't there already).
Related tasks
count in factors
prime decomposition
factors of an integer
Sieve of Eratosthenes
primality by trial division
factors of a Mersenne number
trial factoring of a Mersenne number
partition an integer X into N primes
|
#Elena
|
Elena
|
import extensions;
import system'routines;
import system'math;
isPrime =
(n => new Range(2,(n.sqrt() - 1).RoundedInt).allMatchedBy:(i => n.mod:i != 0));
Primes =
(n => new Range(2, n - 2).filterBy:isPrime);
public program()
{
console.printLine(Primes(100))
}
|
http://rosettacode.org/wiki/Sequence_of_primes_by_trial_division
|
Sequence of primes by trial division
|
Sequence of primes by trial division
You are encouraged to solve this task according to the task description, using any language you may know.
Task
Generate a sequence of primes by means of trial division.
Trial division is an algorithm where a candidate number is tested for being a prime by trying to divide it by other numbers.
You may use primes, or any numbers of your choosing, as long as the result is indeed a sequence of primes.
The sequence may be bounded (i.e. up to some limit), unbounded, starting from the start (i.e. 2) or above some given value.
Organize your function as you wish, in particular, it might resemble a filtering operation, or a sieving operation.
If you want to use a ready-made is_prime function, use one from the Primality by trial division page (i.e., add yours there if it isn't there already).
Related tasks
count in factors
prime decomposition
factors of an integer
Sieve of Eratosthenes
primality by trial division
factors of a Mersenne number
trial factoring of a Mersenne number
partition an integer X into N primes
|
#Elixir
|
Elixir
|
defmodule Prime do
def sequence do
Stream.iterate(2, &(&1+1)) |> Stream.filter(&is_prime/1)
end
def is_prime(2), do: true
def is_prime(n) when n<2 or rem(n,2)==0, do: false
def is_prime(n), do: is_prime(n,3)
defp is_prime(n,k) when n<k*k, do: true
defp is_prime(n,k) when rem(n,k)==0, do: false
defp is_prime(n,k), do: is_prime(n,k+2)
end
IO.inspect Prime.sequence |> Enum.take(20)
|
http://rosettacode.org/wiki/Sequence_of_non-squares
|
Sequence of non-squares
|
Task
Show that the following remarkable formula gives the sequence of non-square natural numbers:
n + floor(1/2 + sqrt(n))
Print out the values for n in the range 1 to 22
Show that no squares occur for n less than one million
This is sequence A000037 in the OEIS database.
|
#COBOL
|
COBOL
|
IDENTIFICATION DIVISION.
PROGRAM-ID. NONSQR.
DATA DIVISION.
WORKING-STORAGE SECTION.
01 NEWTON.
03 SQR-INP PIC 9(7)V9(5).
03 SQUARE-ROOT PIC 9(7)V9(5).
03 FILLER REDEFINES SQUARE-ROOT.
05 FILLER PIC 9(7).
05 FILLER PIC 9(5).
88 SQUARE VALUE ZERO.
03 SQR-TEMP PIC 9(7)V9(5).
01 SEQUENCE-VARS.
03 N PIC 9(7).
03 SEQ PIC 9(7).
01 SMALL-FMT.
03 N-O PIC Z9.
03 FILLER PIC XX VALUE ": ".
03 SEQ-O PIC Z9.
PROCEDURE DIVISION.
BEGIN.
DISPLAY "Sequence of non-squares from 1 to 22:"
PERFORM SMALL-NUMS VARYING N FROM 1 BY 1
UNTIL N IS GREATER THAN 22.
DISPLAY SPACES.
DISPLAY "Checking items up to 1 million..."
PERFORM CHECK-NONSQUARE VARYING N FROM 1 BY 1
UNTIL SQUARE OR N IS GREATER THAN 1000000.
IF SQUARE, DISPLAY "Square found at N = " N,
ELSE, DISPLAY "No squares found up to 1 million.".
STOP RUN.
SMALL-NUMS.
PERFORM NONSQUARE.
MOVE N TO N-O.
MOVE SEQ TO SEQ-O.
DISPLAY SMALL-FMT.
CHECK-NONSQUARE.
PERFORM NONSQUARE.
MOVE SEQ TO SQR-INP.
PERFORM SQRT.
NONSQUARE.
MOVE N TO SQR-INP.
PERFORM SQRT.
ADD 0.5, SQUARE-ROOT GIVING SEQ.
ADD N TO SEQ.
SQRT.
MOVE SQR-INP TO SQUARE-ROOT.
COMPUTE SQR-TEMP =
(SQUARE-ROOT + SQR-INP / SQUARE-ROOT) / 2.
PERFORM SQRT-LOOP UNTIL SQUARE-ROOT IS EQUAL TO SQR-TEMP.
SQRT-LOOP.
MOVE SQR-TEMP TO SQUARE-ROOT.
COMPUTE SQR-TEMP =
(SQUARE-ROOT + SQR-INP / SQUARE-ROOT) / 2.
|
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
|
#Clojure
|
Clojure
|
(require 'clojure.set)
; sets can be created using the set method or set literal syntax
(def a (set [1 2 3 4]))
(def b #{4 5 6 7})
(a 10) ; returns the element if it's contained in the set, otherwise nil
(clojure.set/union a b)
(clojure.set/intersection a b)
(clojure.set/difference a b)
(clojure.set/subset? a b)
|
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
|
#Arturo
|
Arturo
|
sieve: function [upto][
composites: array.of: inc upto false
loop 2..to :integer sqrt upto 'x [
if not? composites\[x][
loop range.step: x x^2 upto 'c [
composites\[c]: true
]
]
]
result: new []
loop.with:'i composites 'c [
unless c -> 'result ++ i
]
return result -- [0,1]
]
print sieve 100
|
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
|
#Python
|
Python
|
def consolidate(sets):
setlist = [s for s in sets if s]
for i, s1 in enumerate(setlist):
if s1:
for s2 in setlist[i+1:]:
intersection = s1.intersection(s2)
if intersection:
s2.update(s1)
s1.clear()
s1 = s2
return [s for s in setlist if s]
|
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.
|
#UNIX_Shell
|
UNIX Shell
|
$ echo -n 'ASCII string' | sha1
9e9aeefe5563845ec5c42c5630842048c0fc261b
|
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.
|
#Vlang
|
Vlang
|
import crypto.sha1
fn main() {
println("${sha1.hexhash('Rosetta Code')}")//Rosetta code
mut h := sha1.new()
h.write('Rosetta Code'.bytes()) ?
println('${h.checksum().map(it.hex()).join('')}')
}
|
http://rosettacode.org/wiki/Show_ASCII_table
|
Show ASCII table
|
Task
Show the ASCII character set from values 32 to 127 (decimal) in a table format.
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
|
#PHP
|
PHP
|
<?php
echo '+' . str_repeat('----------+', 6), PHP_EOL;
for ($j = 0 ; $j < 16 ; $j++) {
for ($i = 0 ; $i < 6 ; $i++) {
$val = 32 + $i * 16 + $j;
switch ($val) {
case 32: $chr = 'Spc'; break;
case 127: $chr = 'Del'; break;
default: $chr = chr($val) ; break;
}
echo sprintf('| %3d: %3s ', $val, $chr);
}
echo '|', PHP_EOL;
}
echo '+' . str_repeat('----------+', 6), PHP_EOL;
|
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
|
#Rust
|
Rust
|
use std::iter::repeat;
fn sierpinski(order: usize) {
let mut triangle = vec!["*".to_string()];
for i in 0..order {
let space = repeat(' ').take(2_usize.pow(i as u32)).collect::<String>();
// save original state
let mut d = triangle.clone();
// extend existing lines
d.iter_mut().for_each(|r| {
let new_row = format!("{}{}{}", space, r, space);
*r = new_row;
});
// add new lines
triangle.iter().for_each(|r| {
let new_row = format!("{}{}{}", r, " ", r);
d.push(new_row);
});
triangle = d;
}
triangle.iter().for_each(|r| println!("{}", r));
}
fn main() {
let order = std::env::args()
.nth(1)
.unwrap_or_else(|| "4".to_string())
.parse::<usize>()
.unwrap();
sierpinski(order);
}
|
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
|
#PL.2FI
|
PL/I
|
/* Sierpinski carpet */
Sierpinski_carpet: procedure options (main); /* 28 January 2013 */
call carpet(3);
In_carpet: procedure (a, b) returns (bit(1));
declare (a, b) fixed binary nonassignable;
declare (x, y) fixed binary;
declare (true value ('1'b), false value ('0'b)) bit (1);
x = a ; y = b;
do forever;
if x = 0 | y = 0 then
return (true);
else if mod(x, 3) = 1 & mod(y, 3) = 1 then
return (false);
x = x / 3;
y = y / 3;
end;
end in_carpet;
Carpet: procedure (n);
declare n fixed binary nonassignable;
declare (i, j) fixed binary;
do i = 0 to 3**n - 1;
do j = 0 to 3**n - 1;
if In_carpet(i, j) then
put edit ('#') (a);
else
put edit (' ') (a);
end;
put skip;
end;
end Carpet;
end Sierpinski_carpet;
|
http://rosettacode.org/wiki/Semordnilap
|
Semordnilap
|
A semordnilap is a word (or phrase) that spells a different word (or phrase) backward. "Semordnilap" is a word that itself is a semordnilap.
Example: lager and regal
Task
This task does not consider semordnilap phrases, only single words.
Using only words from this list, report the total number of unique semordnilap pairs, and print 5 examples.
Two matching semordnilaps, such as lager and regal, should be counted as one unique pair.
(Note that the word "semordnilap" is not in the above dictionary.)
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
|
#Delphi
|
Delphi
|
program Semordnilap;
{$APPTYPE CONSOLE}
{$R *.res}
uses
System.SysUtils,
System.Classes,
System.StrUtils,
System.Diagnostics;
function Sort(s: string): string;
var
c: Char;
i, j, aLength: Integer;
begin
aLength := s.Length;
if aLength = 0 then
exit('');
Result := s;
for i := 1 to aLength - 1 do
for j := i + 1 to aLength do
if result[i] > result[j] then
begin
c := result[i];
result[i] := result[j];
result[j] := c;
end;
end;
function IsAnagram(s1, s2: string): Boolean;
begin
if s1.Length <> s2.Length then
exit(False);
Result := Sort(s1) = Sort(s2);
end;
function CompareLength(List: TStringList; Index1, Index2: Integer): Integer;
begin
result := List[Index1].Length - List[Index2].Length;
if Result = 0 then
Result := CompareText(Sort(List[Index2]), Sort(List[Index1]));
end;
function IsSemordnilap(word1, word2: string): Boolean;
begin
Result := SameText(word1, ReverseString(word2));
end;
var
SemordnilapDict, Dict: TStringList;
Count, Index, i, j: Integer;
words: string;
StopWatch: TStopwatch;
begin
Randomize;
StopWatch := TStopwatch.Create;
StopWatch.Start;
Dict := TStringList.Create();
Dict.LoadFromFile('unixdict.txt');
SemordnilapDict := TStringList.Create;
Dict.CustomSort(CompareLength);
Index := Dict.Count - 1;
words := '';
Count := 1;
while Index - Count >= 0 do
begin
if IsAnagram(Dict[Index], Dict[Index - Count]) then
begin
if IsSemordnilap(Dict[Index], Dict[Index - Count]) then
begin
words := Dict[Index] + ' - ' + Dict[Index - Count];
SemordnilapDict.Add(words);
end;
Inc(Count);
end
else
begin
if Count > 2 then
for i := 1 to Count - 2 do
for j := i + 1 to Count - 1 do
begin
if IsSemordnilap(Dict[Index - i], Dict[Index - j]) then
begin
words := Dict[Index - i] + ' - ' + Dict[Index - j];
SemordnilapDict.Add(words);
end;
end;
Dec(Index, Count);
Count := 1;
end;
end;
StopWatch.Stop;
Writeln(Format('Time pass: %d ms [i7-4500U Windows 7]', [StopWatch.ElapsedMilliseconds]));
writeln(#10'Semordnilap found: ', SemordnilapDict.Count);
writeln(#10'Five random samples:'#10);
for Index := 0 to 4 do
writeln(' ', SemordnilapDict[Random(SemordnilapDict.Count)]);
SemordnilapDict.SaveToFile('Semordnilap.txt');
SemordnilapDict.Free;
Dict.Free;
Readln;
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.
|
#Scheme
|
Scheme
|
>(define (a x)
(display "a\n")
x)
>(define (b x)
(display "b\n")
x)
>(for-each (lambda (i)
(for-each (lambda (j)
(display i) (display " and ") (display j) (newline)
(and (a i) (b j))
(display i) (display " or ") (display j) (newline)
(or (a i) (b j))
) '(#t #f))
) '(#t #f))
#t and #t
a
b
#t or #t
a
#t and #f
a
b
#t or #f
a
#f and #t
a
#f or #t
a
b
#f and #f
a
#f or #f
a
b
|
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)
|
#NewLISP
|
NewLISP
|
(module "smtp.lsp")
(SMTP:send-mail "[email protected]" "[email protected]" "Greetings" "How are you today? - john doe -" "smtp.asite.com" "user" "password")
|
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)
|
#Nim
|
Nim
|
import smtp
proc sendMail(fromAddr: string; toAddrs, ccAddrs: seq[string];
subject, message, login, password: string;
server = "smtp.gmail.com"; port = Port 465; ssl = true) =
let msg = createMessage(subject, message, toAddrs, ccAddrs)
let session = newSmtp(useSsl = ssl, debug = true)
session.connect(server, port)
session.auth(login, password)
session.sendMail(fromAddr, toAddrs, $msg)
sendMail(fromAddr = "[email protected]",
toAddrs = @["[email protected]"],
ccAddrs = @[],
subject = "Hi from Nim",
message = "Nim says hi!\nAnd bye again!",
login = "[email protected]",
password = "XXXXXX")
|
http://rosettacode.org/wiki/Semiprime
|
Semiprime
|
Semiprime numbers are natural numbers that are products of exactly two (possibly equal) prime numbers.
Semiprimes are also known as:
semi-primes
biprimes
bi-primes
2-almost primes
or simply: P2
Example
1679 = 23 × 73
(This particular number was chosen as the length of the Arecibo message).
Task
Write a function determining whether a given number is semiprime.
See also
The Wikipedia article: semiprime.
The Wikipedia article: almost prime.
The OEIS sequence: A001358: semiprimes which has a shorter definition: the product of two primes.
|
#EchoLisp
|
EchoLisp
|
(lib 'math)
(define (semi-prime? n)
(= (length (prime-factors n)) 2))
(for ((i 100))
(when (semi-prime? i) (write i)))
4 6 9 10 14 15 21 22 25 26 33 34 35 38 39 46 49 51 55 57 58 62 65 69 74 77 82 85 86 87 91 93 94 95
(lib 'bigint)
(define N (* (random-prime 10000000) (random-prime 10000000)))
→ 6764578882969
(semi-prime? N)
→ #t
;; a pair n,n+1 of semi-primes
(prime-factors 100000000041)
→ (3 33333333347)
(prime-factors 100000000042)
→ (2 50000000021)
|
http://rosettacode.org/wiki/SEDOLs
|
SEDOLs
|
Task
For each number list of 6-digit SEDOLs, calculate and append the checksum digit.
That is, given this input:
710889
B0YBKJ
406566
B0YBLH
228276
B0YBKL
557910
B0YBKR
585284
B0YBKT
B00030
Produce this output:
7108899
B0YBKJ7
4065663
B0YBLH2
2282765
B0YBKL9
5579107
B0YBKR5
5852842
B0YBKT7
B000300
Extra credit
Check each input is correctly formed, especially with respect to valid characters allowed in a SEDOL string.
Related tasks
Luhn test
ISIN
|
#Arturo
|
Arturo
|
ord0: to :integer `0`
ord7: to :integer `7`
c2v: function [c][
ordC: to :integer c
if? c < `A` -> return ordC - ord0
else -> return ordC - ord7
]
weight: [1 3 1 7 3 9]
checksum: function [sedol][
val: new 0
loop .with:'i sedol 'ch ->
'val + weight\[i] * c2v ch
return to :char ord0 + (10 - val % 10) % 10
]
sedols: [
"710889" "B0YBKJ" "406566" "B0YBLH"
"228276" "B0YBKL" "557910" "B0YBKR"
"585284" "B0YBKT" "B00030"
]
loop sedols 'sed ->
print [sed "->" sed ++ checksum sed]
|
http://rosettacode.org/wiki/Self-describing_numbers
|
Self-describing numbers
|
Self-describing numbers
You are encouraged to solve this task according to the task description, using any language you may know.
There are several so-called "self-describing" or "self-descriptive" integers.
An integer is said to be "self-describing" if it has the property that, when digit positions are labeled 0 to N-1, the digit in each position is equal to the number of times that that digit appears in the number.
For example, 2020 is a four-digit self describing number:
position 0 has value 2 and there are two 0s in the number;
position 1 has value 0 and there are no 1s in the number;
position 2 has value 2 and there are two 2s;
position 3 has value 0 and there are zero 3s.
Self-describing numbers < 100.000.000 are: 1210, 2020, 21200, 3211000, 42101000.
Task Description
Write a function/routine/method/... that will check whether a given positive integer is self-describing.
As an optional stretch goal - generate and display the set of self-describing numbers.
Related tasks
Fours is the number of letters in the ...
Look-and-say sequence
Number names
Self-referential sequence
Spelling of ordinal numbers
|
#Elixir
|
Elixir
|
defmodule Self_describing do
def number(n) do
digits = Integer.digits(n)
Enum.map(0..length(digits)-1, fn s ->
length(Enum.filter(digits, fn c -> c==s end))
end) == digits
end
end
m = 3300000
Enum.filter(0..m, fn n -> Self_describing.number(n) end)
|
http://rosettacode.org/wiki/Self-describing_numbers
|
Self-describing numbers
|
Self-describing numbers
You are encouraged to solve this task according to the task description, using any language you may know.
There are several so-called "self-describing" or "self-descriptive" integers.
An integer is said to be "self-describing" if it has the property that, when digit positions are labeled 0 to N-1, the digit in each position is equal to the number of times that that digit appears in the number.
For example, 2020 is a four-digit self describing number:
position 0 has value 2 and there are two 0s in the number;
position 1 has value 0 and there are no 1s in the number;
position 2 has value 2 and there are two 2s;
position 3 has value 0 and there are zero 3s.
Self-describing numbers < 100.000.000 are: 1210, 2020, 21200, 3211000, 42101000.
Task Description
Write a function/routine/method/... that will check whether a given positive integer is self-describing.
As an optional stretch goal - generate and display the set of self-describing numbers.
Related tasks
Fours is the number of letters in the ...
Look-and-say sequence
Number names
Self-referential sequence
Spelling of ordinal numbers
|
#Erlang
|
Erlang
|
sdn(N) -> lists:map(fun(S)->length(lists:filter(fun(C)->C-$0==S end,N))+$0 end,lists:seq(0,length(N)-1))==N.
gen(M) -> lists:filter(fun(N)->sdn(integer_to_list(N)) end,lists:seq(0,M)).
|
http://rosettacode.org/wiki/Self_numbers
|
Self numbers
|
A number n is a self number if there is no number g such that g + the sum of g's digits = n. So 18 is not a self number because 9+9=18, 43 is not a self number because 35+5+3=43.
The task is:
Display the first 50 self numbers;
I believe that the 100000000th self number is 1022727208. You should either confirm or dispute my conjecture.
224036583-1 is a Mersenne prime, claimed to also be a self number. Extra credit to anyone proving it.
See also
OEIS: A003052 - Self numbers or Colombian numbers
Wikipedia: Self numbers
|
#jq
|
jq
|
def sumdigits: tostring | explode | map([.]|implode|tonumber) | add;
def gsum: . + sumdigits;
def isnonself:
def ndigits: tostring|length;
. as $i
| ($i - ($i|ndigits)*9) as $n
| any( range($i-1; [0,$n]|max; -1);
gsum == $i);
# an array
def last81:
[limit(81; range(1; infinite) | select(isnonself))];
# output an unbounded stream
def selfnumbers:
foreach range(1; infinite) as $i ( [0, last81];
.[0] = false
| .[1] as $last81
| if $last81 | bsearch($i) < 0
then .[0] = $i
| if $i > $last81[-1] then .[1] = $last81[1:] + [$i | gsum ] else . end
else .
end;
.[0] | select(.) );
"The first 50 self numbers are:", last81[:50],
"",
(nth(100000000 - 1; selfnumbers)
| if . == 1022727208
then "Yes, \(.) is the 100,000,000th self number."
else "No, \(.i) is actually the 100,000,000th self number."
end)
|
http://rosettacode.org/wiki/Self_numbers
|
Self numbers
|
A number n is a self number if there is no number g such that g + the sum of g's digits = n. So 18 is not a self number because 9+9=18, 43 is not a self number because 35+5+3=43.
The task is:
Display the first 50 self numbers;
I believe that the 100000000th self number is 1022727208. You should either confirm or dispute my conjecture.
224036583-1 is a Mersenne prime, claimed to also be a self number. Extra credit to anyone proving it.
See also
OEIS: A003052 - Self numbers or Colombian numbers
Wikipedia: Self numbers
|
#Julia
|
Julia
|
gsum(i) = sum(digits(i)) + i
isnonself(i) = any(x -> gsum(x) == i, i-1:-1:i-max(1, ndigits(i)*9))
const last81 = filter(isnonself, 1:5000)[1:81]
function checkselfnumbers()
i, selfcount = 1, 0
while selfcount <= 100_000_000 && i <= 1022727208
if !(i in last81)
selfcount += 1
if selfcount < 51
print(i, " ")
elseif selfcount == 51
println()
elseif selfcount == 100_000_000
println(i == 1022727208 ?
"Yes, $i is the 100,000,000th self number." :
"No, instead $i is the 100,000,000th self number.")
end
end
popfirst!(last81)
push!(last81, gsum(i))
i += 1
end
end
checkselfnumbers()
|
http://rosettacode.org/wiki/Self_numbers
|
Self numbers
|
A number n is a self number if there is no number g such that g + the sum of g's digits = n. So 18 is not a self number because 9+9=18, 43 is not a self number because 35+5+3=43.
The task is:
Display the first 50 self numbers;
I believe that the 100000000th self number is 1022727208. You should either confirm or dispute my conjecture.
224036583-1 is a Mersenne prime, claimed to also be a self number. Extra credit to anyone proving it.
See also
OEIS: A003052 - Self numbers or Colombian numbers
Wikipedia: Self numbers
|
#Kotlin
|
Kotlin
|
private const val MC = 103 * 1000 * 10000 + 11 * 9 + 1
private val SV = BooleanArray(MC + 1)
private fun sieve() {
val dS = IntArray(10000)
run {
var a = 9
var i = 9999
while (a >= 0) {
for (b in 9 downTo 0) {
var c = 9
val s = a + b
while (c >= 0) {
var d = 9
val t = s + c
while (d >= 0) {
dS[i--] = t + d
d--
}
c--
}
}
a--
}
}
var a = 0
var n = 0
while (a < 103) {
var b = 0
val d = dS[a]
while (b < 1000) {
var c = 0
var s = d + dS[b] + n
while (c < 10000) {
SV[dS[c] + s++] = true
c++
}
b++
n += 10000
}
a++
}
}
fun main() {
sieve()
println("The first 50 self numbers are:")
run {
var i = 0
var count = 0
while (count <= 50) {
if (!SV[i]) {
count++
if (count <= 50) {
print("$i ")
} else {
println()
println()
println(" Index Self number")
}
}
i++
}
}
var i = 0
var limit = 1
var count = 0
while (i < MC) {
if (!SV[i]) {
if (++count == limit) {
println("%,12d %,13d".format(count, i))
limit *= 10
}
}
i++
}
}
|
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.
|
#Phix
|
Phix
|
with javascript_semantics
enum ID,ARGS
function cf(sequence f, atom x) return call_func(f[ID],deep_copy(f[ARGS])&x) end function
function Union(sequence a, b, atom x) return cf(a,x) or cf(b,x) end function
function Inter(sequence a, b, atom x) return cf(a,x) and cf(b,x) end function
function Diffr(sequence a, b, atom x) return cf(a,x) and not cf(b,x) end function
function OpOp(atom a, b, x) return a < x and x < b end function
function ClCl(atom a, b, x) return a <= x and x <= b end function
function OpCl(atom a, b, x) return a < x and x <= b end function
function ClOp(atom a, b, x) return a <= x and x < b end function
-- expected
-- ---- desc ----, 0 1 2, --------------- set method ---------------
constant s = {{"(0,1] u [0,2)", {1,1,0}, {Union,{{OpCl,{0,1}},{ClOp,{0,2}}}}},
{"[0,2) n (1,2]", {0,0,0}, {Inter,{{ClOp,{0,2}},{OpCl,{1,2}}}}},
{"[0,3) - (0,1)", {1,1,1}, {Diffr,{{ClOp,{0,3}},{OpOp,{0,1}}}}},
{"[0,3) - [0,1]", {0,0,1}, {Diffr,{{ClOp,{0,3}},{ClCl,{0,1}}}}}}
for i=1 to length(s) do
sequence {desc, expect, method} = s[i]
for x=0 to 2 do
bool r = cf(method,x)
string error = iff(r!=expect[x+1]?"error":"")
printf(1,"%d in %s : %t %s\n", {x, desc, r, error})
end for
printf(1,"\n")
end for
|
http://rosettacode.org/wiki/Sequence_of_primes_by_trial_division
|
Sequence of primes by trial division
|
Sequence of primes by trial division
You are encouraged to solve this task according to the task description, using any language you may know.
Task
Generate a sequence of primes by means of trial division.
Trial division is an algorithm where a candidate number is tested for being a prime by trying to divide it by other numbers.
You may use primes, or any numbers of your choosing, as long as the result is indeed a sequence of primes.
The sequence may be bounded (i.e. up to some limit), unbounded, starting from the start (i.e. 2) or above some given value.
Organize your function as you wish, in particular, it might resemble a filtering operation, or a sieving operation.
If you want to use a ready-made is_prime function, use one from the Primality by trial division page (i.e., add yours there if it isn't there already).
Related tasks
count in factors
prime decomposition
factors of an integer
Sieve of Eratosthenes
primality by trial division
factors of a Mersenne number
trial factoring of a Mersenne number
partition an integer X into N primes
|
#ERRE
|
ERRE
|
PROGRAM PRIME_GENERATOR
!$DOUBLE
BEGIN
PRINT(CHR$(12);) !CLS
N=1
LOOP
N+=1
FOR F=2 TO N DO
IF F=N THEN PRINT(N;) EXIT END IF
EXIT IF N=F*INT(N/F)
END FOR
END LOOP
END PROGRAM
|
http://rosettacode.org/wiki/Sequence_of_primes_by_trial_division
|
Sequence of primes by trial division
|
Sequence of primes by trial division
You are encouraged to solve this task according to the task description, using any language you may know.
Task
Generate a sequence of primes by means of trial division.
Trial division is an algorithm where a candidate number is tested for being a prime by trying to divide it by other numbers.
You may use primes, or any numbers of your choosing, as long as the result is indeed a sequence of primes.
The sequence may be bounded (i.e. up to some limit), unbounded, starting from the start (i.e. 2) or above some given value.
Organize your function as you wish, in particular, it might resemble a filtering operation, or a sieving operation.
If you want to use a ready-made is_prime function, use one from the Primality by trial division page (i.e., add yours there if it isn't there already).
Related tasks
count in factors
prime decomposition
factors of an integer
Sieve of Eratosthenes
primality by trial division
factors of a Mersenne number
trial factoring of a Mersenne number
partition an integer X into N primes
|
#F.23
|
F#
|
(*
Nigel Galloway April 7th., 2017.
*)
let SofE =
let rec fg ng = seq{
let n = Seq.item 0 ng
yield n; yield! fg (Seq.cache(Seq.filter (fun g->g%n<>0) (Seq.skip 1 ng)))}
fg (Seq.initInfinite(id)|>Seq.skip 2)
|
http://rosettacode.org/wiki/Sequence_of_non-squares
|
Sequence of non-squares
|
Task
Show that the following remarkable formula gives the sequence of non-square natural numbers:
n + floor(1/2 + sqrt(n))
Print out the values for n in the range 1 to 22
Show that no squares occur for n less than one million
This is sequence A000037 in the OEIS database.
|
#CoffeeScript
|
CoffeeScript
|
non_square = (n) -> n + Math.floor(1/2 + Math.sqrt(n))
is_square = (n) ->
r = Math.floor(Math.sqrt(n))
r * r is n
do ->
first_22_non_squares = (non_square i for i in [1..22])
console.log first_22_non_squares
# test is_square has no false negatives:
for i in [1..10000]
throw Error("is_square broken") unless is_square i*i
# test non_square is valid for first million values of n
for i in [1..1000000]
throw Error("non_square broken") if is_square non_square(i)
console.log "success"
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.