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/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
|
#Forth
|
Forth
|
wordlist constant dict
: load-dict ( c-addr u -- )
r/o open-file throw >r
begin
pad 1024 r@ read-line throw while
pad swap ['] create execute-parsing
repeat
drop r> close-file throw ;
: xreverse {: c-addr u -- c-addr2 u :}
u allocate throw u + c-addr swap over u + >r begin ( from to r:end)
over r@ u< while
over r@ over - x-size dup >r - 2dup r@ cmove
swap r> + swap repeat
r> drop nip u ;
: .example ( c-addr u u1 -- )
5 < if
cr 2dup type space 2dup xreverse 2dup type drop free throw then
2drop ;
: nt-semicheck ( u1 nt -- u2 f )
dup >r name>string xreverse 2dup dict find-name-in dup if ( u1 c-addr u nt2)
r@ < if ( u1 c-addr u ) \ count pairs only once and not palindromes
2dup 4 pick .example
rot 1+ -rot then
else
drop then
drop free throw r> drop true ;
get-current dict set-current s" unixdict.txt" load-dict set-current
0 ' nt-semicheck dict traverse-wordlist cr .
cr bye
|
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.
|
#Tcl
|
Tcl
|
package require Tcl 8.5
proc tcl::mathfunc::a boolean {
puts "a($boolean) called"
return $boolean
}
proc tcl::mathfunc::b boolean {
puts "b($boolean) called"
return $boolean
}
foreach i {false true} {
foreach j {false true} {
set x [expr {a($i) && b($j)}]
puts "x = a($i) && b($j) = $x"
set y [expr {a($i) || b($j)}]
puts "y = a($i) || b($j) = $y"
puts ""; # Blank line for clarity
}
}
|
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.
|
#TXR
|
TXR
|
@(define a (x out))
@ (output)
a (@x) called
@ (end)
@ (bind out x)
@(end)
@(define b (x out))
@ (output)
b (@x) called
@ (end)
@ (bind out x)
@(end)
@(define short_circuit_demo (i j))
@ (output)
a(@i) and b(@j):
@ (end)
@ (maybe)
@ (a i "1")
@ (b j "1")
@ (end)
@ (output)
a(@i) or b(@j):
@ (end)
@ (cases)
@ (a i "1")
@ (or)
@ (b j "1")
@ (or)
@ (accept)
@ (end)
@(end)
@(short_circuit_demo "0" "0")
@(short_circuit_demo "0" "1")
@(short_circuit_demo "1" "0")
@(short_circuit_demo "1" "1")
|
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)
|
#Python
|
Python
|
import smtplib
def sendemail(from_addr, to_addr_list, cc_addr_list,
subject, message,
login, password,
smtpserver='smtp.gmail.com:587'):
header = 'From: %s\n' % from_addr
header += 'To: %s\n' % ','.join(to_addr_list)
header += 'Cc: %s\n' % ','.join(cc_addr_list)
header += 'Subject: %s\n\n' % subject
message = header + message
server = smtplib.SMTP(smtpserver)
server.starttls()
server.login(login,password)
problems = server.sendmail(from_addr, to_addr_list, message)
server.quit()
return problems
|
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)
|
#R
|
R
|
library(RDCOMClient)
send.mail <- function(to, title, body) {
olMailItem <- 0
ol <- COMCreate("Outlook.Application")
msg <- ol$CreateItem(olMailItem)
msg[["To"]] <- to
msg[["Subject"]] <- title
msg[["Body"]] <- body
msg$Send()
ol$Quit()
}
send.mail("somebody@somewhere", "Title", "Hello")
|
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.
|
#Haskell
|
Haskell
|
isSemiprime :: Int -> Bool
isSemiprime n = (length factors) == 2 && (product factors) == n ||
(length factors) == 1 && (head factors) ^ 2 == n
where factors = primeFactors n
|
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.
|
#Icon_and_Unicon
|
Icon and Unicon
|
link "factors"
procedure main(A)
every nf := semiprime(n := !A) do write(n," = ",nf[1]," * ",nf[2])
end
procedure semiprime(n) # Succeeds and produces the factors only if n is semiprime.
return (2 = *(nf := factors(n)), nf)
end
|
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
|
#C.23
|
C#
|
static int[] sedol_weights = { 1, 3, 1, 7, 3, 9 };
static int sedolChecksum(string sedol)
{
int len = sedol.Length;
int sum = 0;
if (len == 7) //SEDOL code already checksummed?
return (int)sedol[6];
if ((len > 7) || (len < 6) || System.Text.RegularExpressions.Regex.IsMatch(sedol, "[AEIOUaeiou]+")) //invalid SEDOL
return -1;
for (int i = 0; i < 6; i++)
{
if (Char.IsDigit(sedol[i]))
sum += (((int)sedol[i] - 48) * sedol_weights[i]);
else if (Char.IsLetter(sedol[i]))
sum += (((int)Char.ToUpper(sedol[i]) - 55) * sedol_weights[i]);
else
return -1;
}
return (10 - (sum % 10)) % 10;
}
|
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
|
#J
|
J
|
digits =: 10&#.^:_1
counts =: _1 + [: #/.~ i.@:# , ]
selfdesc =: = counts&.digits"0 NB. Note use of "under"
|
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
|
#Java
|
Java
|
public class SelfDescribingNumbers{
public static boolean isSelfDescribing(int a){
String s = Integer.toString(a);
for(int i = 0; i < s.length(); i++){
String s0 = s.charAt(i) + "";
int b = Integer.parseInt(s0); // number of times i-th digit must occur for it to be a self describing number
int count = 0;
for(int j = 0; j < s.length(); j++){
int temp = Integer.parseInt(s.charAt(j) + "");
if(temp == i){
count++;
}
if (count > b) return false;
}
if(count != b) return false;
}
return true;
}
public static void main(String[] args){
for(int i = 0; i < 100000000; i++){
if(isSelfDescribing(i)){
System.out.println(i);
}
}
}
}
|
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
|
#REXX
|
REXX
|
/*REXX program displays N self numbers (aka Colombian or Devlali numbers). OEIS A3052.*/
parse arg n . /*obtain optional argument from the CL.*/
if n=='' | n=="," then n= 50 /*Not specified? Then use the default.*/
tell = n>0; n= abs(n) /*TELL: show the self numbers if N>0 */
@.= . /*initialize the array of self numbers.*/
do j=1 for n*10 /*scan through ten times the #s wanted.*/
$= j /*1st part of sum is the number itself.*/
do k=1 for length(j) /*sum the decimal digits in the number.*/
$= $ + substr(j, k, 1) /*add a particular digit to the sum. */
end /*k*/
@.$= /*mark J as not being a self number. */
end /*j*/ /* ─── */
list= 1 /*initialize the list to the 1st number*/
#= 1 /*the count of self numbers (so far). */
do i=3 until #==n; if @.i=='' then iterate /*Not a self number? Then skip it. */
#= # + 1; list= list i /*bump counter of self #'s; add to list*/
end /*i*/
/*stick a fork in it, we're all done. */
say n " self numbers were found." /*display the title for the output list*/
if tell then say list /*display list of self numbers ──►term.*/
|
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
|
#Ring
|
Ring
|
load "stdlib.ring"
see "working..." + nl
see "The first 50 self numbers are:" + nl
n = 0
num = 0
limit = 51
limit2 = 10000000
while true
n = n + 1
for m = 1 to n
flag = 1
sum = 0
strnum = string(m)
for p = 1 to len(strnum)
sum = sum + number(strnum[p])
next
sum2 = m + sum
if sum2 = n
flag = 0
exit
else
flag = 1
ok
next
if flag = 1
num = num + 1
if num < limit
see "" + num + ". " + n + nl
ok
if num = limit2
see "The " + limit2 + "th self number is: " + n + nl
ok
if num > limit2
exit
ok
ok
end
see "done..." + nl
|
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.
|
#Rust
|
Rust
|
#[derive(Debug)]
enum SetOperation {
Union,
Intersection,
Difference,
}
#[derive(Debug, PartialEq)]
enum RangeType {
Inclusive,
Exclusive,
}
#[derive(Debug)]
struct CompositeSet<'a> {
operation: SetOperation,
a: &'a RealSet<'a>,
b: &'a RealSet<'a>,
}
#[derive(Debug)]
struct RangeSet {
range_types: (RangeType, RangeType),
start: f64,
end: f64,
}
#[derive(Debug)]
enum RealSet<'a> {
RangeSet(RangeSet),
CompositeSet(CompositeSet<'a>),
}
impl RangeSet {
fn compare_start(&self, n: f64) -> bool {
if self.range_types.0 == RangeType::Inclusive {
self.start <= n
} else {
self.start < n
}
}
fn compare_end(&self, n: f64) -> bool {
if self.range_types.1 == RangeType::Inclusive {
n <= self.end
} else {
n < self.end
}
}
}
impl<'a> RealSet<'a> {
fn new(start_type: RangeType, start: f64, end: f64, end_type: RangeType) -> Self {
RealSet::RangeSet(RangeSet {
range_types: (start_type, end_type),
start,
end,
})
}
fn operation(&'a self, other: &'a Self, operation: SetOperation) -> Self {
RealSet::CompositeSet(CompositeSet {
operation,
a: self,
b: other,
})
}
fn union(&'a self, other: &'a Self) -> Self {
self.operation(other, SetOperation::Union)
}
fn intersection(&'a self, other: &'a Self) -> Self {
self.operation(other, SetOperation::Intersection)
}
fn difference(&'a self, other: &'a Self) -> Self {
self.operation(other, SetOperation::Difference)
}
fn contains(&self, n: f64) -> bool {
if let RealSet::RangeSet(range) = self {
range.compare_start(n) && range.compare_end(n)
} else if let RealSet::CompositeSet(range) = self {
match range.operation {
SetOperation::Union => range.a.contains(n) || range.b.contains(n),
SetOperation::Intersection => range.a.contains(n) && range.b.contains(n),
SetOperation::Difference => range.a.contains(n) && !range.b.contains(n),
}
} else {
unimplemented!();
}
}
}
fn make_contains_phrase(does_contain: bool) -> &'static str {
if does_contain {
"contains"
} else {
"does not contain"
}
}
use RangeType::*;
fn main() {
for (set_name, set) in [
(
"(0, 1] ∪ [0, 2)",
RealSet::new(Exclusive, 0.0, 1.0, Inclusive)
.union(&RealSet::new(Inclusive, 0.0, 2.0, Exclusive)),
),
(
"[0, 2) ∩ (1, 2]",
RealSet::new(Inclusive, 0.0, 2.0, Exclusive)
.intersection(&RealSet::new(Exclusive, 1.0, 2.0, Inclusive)),
),
(
"[0, 3) − (0, 1)",
RealSet::new(Inclusive, 0.0, 3.0, Exclusive)
.difference(&RealSet::new(Exclusive, 0.0, 1.0, Exclusive)),
),
(
"[0, 3) − [0, 1]",
RealSet::new(Inclusive, 0.0, 3.0, Exclusive)
.difference(&RealSet::new(Inclusive, 0.0, 1.0, Inclusive)),
),
] {
println!("Set {}", set_name);
for i in [0.0, 1.0, 2.0] {
println!("- {} {}", make_contains_phrase(set.contains(i)), 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.
|
#Tcl
|
Tcl
|
package require Tcl 8.5
proc inRange {x range} {
lassign $range a aClosed b bClosed
expr {($aClosed ? $a<=$x : $a<$x) && ($bClosed ? $x<=$b : $x<$b)}
}
proc normalize {A} {
set A [lsort -index 0 -real [lsort -index 1 -integer -decreasing $A]]
for {set i 0} {$i < [llength $A]} {incr i} {
lassign [lindex $A $i] a aClosed b bClosed
if {$b < $a || ($a == $b && !($aClosed && $bClosed))} {
set A [lreplace $A $i $i]
incr i -1
}
}
for {set i 0} {$i < [llength $A]} {incr i} {
for {set j [expr {$i+1}]} {$j < [llength $A]} {incr j} {
set R [lindex $A $i]
lassign [lindex $A $j] a aClosed b bClosed
if {[inRange $a $R]} {
if {![inRange $b $R]} {
lset A $i 2 $b
lset A $i 3 $bClosed
}
set A [lreplace $A $j $j]
incr j -1
}
}
}
return $A
}
proc realset {args} {
set RE {^\s*([\[(])\s*([-\d.e]+|-inf)\s*,\s*([-\d.e]+|inf)\s*([\])])\s*$}
set result {}
foreach s $args {
if {
[regexp $RE $s --> left a b right] &&
[string is double $a] && [string is double $b]
} then {
lappend result [list \
$a [expr {$left eq "\["}] $b [expr {$right eq "\]"}]]
} else {
error "bad range descriptor"
}
}
return $result
}
proc elementOf {x A} {
foreach range $A {
if {[inRange $x $range]} {return 1}
}
return 0
}
proc union {A B} {
return [normalize [concat $A $B]]
}
proc intersection {A B} {
set B [normalize $B]
set C {}
foreach RA [normalize $A] {
lassign $RA Aa AaClosed Ab AbClosed
foreach RB $B {
lassign $RB Ba BaClosed Bb BbClosed
if {$Aa > $Bb || $Ba > $Ab} continue
set RC {}
lappend RC [expr {max($Aa,$Ba)}]
if {$Aa==$Ba} {
lappend RC [expr {min($AaClosed,$BaClosed)}]
} else {
lappend RC [expr {$Aa>$Ba ? $AaClosed : $BaClosed}]
}
lappend RC [expr {min($Ab,$Bb)}]
if {$Ab==$Bb} {
lappend RC [expr {min($AbClosed,$BbClosed)}]
} else {
lappend RC [expr {$Ab<$Bb ? $AbClosed : $BbClosed}]
}
lappend C $RC
}
}
return [normalize $C]
}
proc difference {A B} {
set C {}
set B [normalize $B]
foreach arange [normalize $A] {
if {[isEmpty [intersection [list $arange] $B]]} {
lappend C $arange
continue
}
lassign $arange Aa AaClosed Ab AbClosed
foreach brange $B {
lassign $brange Ba BaClosed Bb BbClosed
if {$Bb < $Aa || ($Bb==$Aa && !($AaClosed && $BbClosed))} {
continue
}
if {$Ab < $Ba || ($Ab==$Ba && !($BaClosed && $AbClosed))} {
lappend C [list $Aa $AaClosed $Ab $AbClosed]
unset arange
break
}
if {$Aa==$Bb} {
set AaClosed 0
continue
} elseif {$Ab==$Ba} {
set AbClosed 0
lappend C [list $Aa $AaClosed $Ab $AbClosed]
unset arange
continue
}
if {$Aa<$Ba} {
lappend C [list $Aa $AaClosed $Ba [expr {!$BaClosed}]]
if {$Ab>$Bb} {
set Aa $Bb
set AaClosed [expr {!$BbClosed}]
} else {
unset arange
break
}
} elseif {$Aa==$Ba} {
lappend C [list $Aa $AaClosed $Ba [expr {!$BaClosed}]]
set Aa $Bb
set AaClosed [expr {!$BbClosed}]
} else {
set Aa $Bb
set AaClosed [expr {!$BbClosed}]
}
}
if {[info exist arange]} {
lappend C [list $Aa $AaClosed $Ab $AbClosed]
}
}
return [normalize $C]
}
proc isEmpty A {
expr {![llength [normalize $A]]}
}
proc length A {
set len 0.0
foreach range [normalize $A] {
lassign $range a _ b _
set len [expr {$len + ($b-$a)}]
}
return $len
}
|
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
|
#Haskell
|
Haskell
|
[n | n <- [2..], []==[i | i <- [2..n-1], rem n i == 0]]
|
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
|
#J
|
J
|
primTrial=:3 :0
try=. i.&.(p:inv) %: >./ y
candidate=. (y>1)*y=<.y
y #~ candidate*(y e.try) = +/ 0= try|/ y
)
|
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.
|
#Euphoria
|
Euphoria
|
function nonsqr( atom n)
return n + floor( 0.5 + sqrt( n ) )
end function
puts( 1, " n r(n)\n" )
puts( 1, "--- ---\n" )
for i = 1 to 22 do
printf( 1, "%3d %3d\n", { i, nonsqr(i) } )
end for
atom j
atom found
found = 0
for i = 1 to 1000000 do
j = sqrt(nonsqr(i))
if integer(j) then
found = 1
printf( 1, "Found square: %d\n", i )
exit
end if
end for
if found = 0 then
puts( 1, "No squares found\n" )
end if
|
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
|
#EchoLisp
|
EchoLisp
|
; use { } to read a set
(define A { 1 2 3 4 3 5 5}) → { 1 2 3 4 5 } ; duplicates are removed from a set
; or use make-set to make a set from a list
(define B (make-set ' ( 3 4 5 6 7 8 8))) → { 3 4 5 6 7 8 }
(set-intersect A B) → { 3 4 5 }
(set-intersect? A B) → #t ; predicate
(set-union A B) → { 1 2 3 4 5 6 7 8 }
(set-substract A B) → { 1 2 }
(set-sym-diff A B) → { 1 2 6 7 8 } ; ∆ symmetric difference
(set-equal? A B) → #f
(set-equal? { a b c} { c b a}) → #t ; order is unimportant
(set-subset? A B) → #f ; B in A or B = A
(set-subset? A { 3 4 }) → #t
(member 4 A) → (4 5) ; same as #t : true
(member 9 A) → #f
; check basic equalities
(set-equal? A (set-union (set-intersect A B) (set-substract A B))) → #t
(set-equal? (set-union A B) (set-union (set-sym-diff A B) (set-intersect A B))) → #t
; × : cartesian product of two sets : all pairs (a . b) , a in A, b in B
; returns a list (not a set)
(define A { albert simon})
(define B { antoinette ornella marylin})
(set-product A B)
→ ((albert . antoinette) (albert . marylin) (albert . ornella) (simon . antoinette) (simon . marylin) (simon . ornella))
; sets elements may be sets
{ { a b c} {c b a } { a b d}} → { { a b c } { a b d } } ; duplicate removed
; A few functions return sets :
(primes 10) → { 2 3 5 7 11 13 17 19 23 29 }
|
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
|
#Batch_File
|
Batch File
|
:: Sieve of Eratosthenes for Rosetta Code - PG
@echo off
setlocal ENABLEDELAYEDEXPANSION
setlocal ENABLEEXTENSIONS
rem echo on
set /p n=limit:
rem set n=100
for /L %%i in (1,1,%n%) do set crible.%%i=1
for /L %%i in (2,1,%n%) do (
if !crible.%%i! EQU 1 (
set /A w = %%i * 2
for /L %%j in (!w!,%%i,%n%) do (
set crible.%%j=0
)
)
)
for /L %%i in (2,1,%n%) do (
if !crible.%%i! EQU 1 echo %%i
)
pause
|
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
|
#Tcl
|
Tcl
|
package require struct::set
proc consolidate {sets} {
if {[llength $sets] < 2} {
return $sets
}
set r [list {}]
set r0 [lindex $sets 0]
foreach x [consolidate [lrange $sets 1 end]] {
if {[struct::set size [struct::set intersect $x $r0]]} {
struct::set add r0 $x
} else {
lappend r $x
}
}
return [lset r 0 $r0]
}
|
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
|
#Quackery
|
Quackery
|
[ dup 32 = iff
[ drop say 'spc' ] done
dup 127 = iff
[ drop say 'del' ] done
emit sp sp ] is echoascii ( n --> )
[ dup echo say ': '
dup echoascii
84 < 3 + times sp ] is echoelt ( n --> )
[ sp 81 times
[ dup i^ + echoelt 16 step ]
drop cr ] is echorow ( n --> )
[ 16 times [ i^ 32 + echorow ] ] is echotable ( --> )
echotable
|
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
|
#Tcl
|
Tcl
|
package require Tcl 8.5
proc map {lambda list} {
foreach elem $list {
lappend result [apply $lambda $elem]
}
return $result
}
proc sierpinski_triangle n {
set down [list *]
set space " "
for {set i 1} {$i <= $n} {incr i} {
set down [concat \
[map [subst -nocommands {x {expr {"$space[set x]$space"}}}] $down] \
[map {x {expr {"$x $x"}}} $down] \
]
append space $space
}
return [join $down \n]
}
puts [sierpinski_triangle 4]
|
http://rosettacode.org/wiki/Sierpinski_carpet
|
Sierpinski carpet
|
Task
Produce a graphical or ASCII-art representation of a Sierpinski carpet of order N.
For example, the Sierpinski carpet of order 3 should look like this:
###########################
# ## ## ## ## ## ## ## ## #
###########################
### ###### ###### ###
# # # ## # # ## # # #
### ###### ###### ###
###########################
# ## ## ## ## ## ## ## ## #
###########################
######### #########
# ## ## # # ## ## #
######### #########
### ### ### ###
# # # # # # # #
### ### ### ###
######### #########
# ## ## # # ## ## #
######### #########
###########################
# ## ## ## ## ## ## ## ## #
###########################
### ###### ###### ###
# # # ## # # ## # # #
### ###### ###### ###
###########################
# ## ## ## ## ## ## ## ## #
###########################
The use of the # character is not rigidly required for ASCII art.
The important requirement is the placement of whitespace and non-whitespace characters.
Related task
Sierpinski triangle
|
#Python
|
Python
|
def in_carpet(x, y):
while True:
if x == 0 or y == 0:
return True
elif x % 3 == 1 and y % 3 == 1:
return False
x /= 3
y /= 3
def carpet(n):
for i in xrange(3 ** n):
for j in xrange(3 ** n):
if in_carpet(i, j):
print '*',
else:
print ' ',
print
|
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
|
#Fortran
|
Fortran
|
!-*- mode: compilation; default-directory: "/tmp/" -*-
!Compilation started at Sun May 19 21:50:08
!
!a=./F && make $a && $a < unixdict.txt
!f95 -Wall -ffree-form F.F -o F
! 5 of 158 semordnilaps
!yaw
!room
!xi
!tim
!nova
!
!
!Compilation finished at Sun May 19 21:50:08
!
!
!
!
! unixdict.txt information
! wc -l unixdict.txt #--> 25104 25 thousand entries
! gawk 'length(a)<length($0){a=$0}END{print a}' unixdict.txt #--> electroencephalography longest word has 22 characters
! gawk '/[A-Z]/{++a}END{print a}' unixdict.txt #--> <empty> the dictionary is lower case
! sort unixdict.txt | cmp - unixdict.txt #--> - unixdict.txt differ: byte 45, line 12
! the dictionary is unsorted
! mmmmm the dictionary is sorted, according to subroutine bs. There's something about the ampersands within unixdict.txt I misunderstand.
program Semordnilap
implicit none
integer :: i, ios, words, swords
character(len=24), dimension(32768) :: dictionary, backword
real, dimension(5) :: harvest
! read the dictionary
open(7,file='unixdict.txt')
do words = 1, 32768
read(7, '(a)', iostat = ios) dictionary(words)
if (ios .ne. 0) exit
enddo
close(7)
if (iachar(dictionary(words)(1:1)) .eq. 0) words = words-1
! sort the dictionary
call bs(dictionary, words)
!do i = 1, words
! write(6,*) dictionary(i)(1:len_trim(dictionary(i))) ! with which we determine the dictionary was ordered
!enddo
swords = 0
do i = 1, words
call reverse(dictionary(i), backword(swords+1))
if ((binary_search(dictionary, words, backword(swords+1))) & ! the reversed word is in the dictionary
.and. (.not. binary_search(backword, swords, dictionary(i))) & ! and it's new
.and. (dictionary(i) .ne. backword(swords+1))) then ! and it's not a palindrome
swords = swords + 1
call bs(backword, swords)
endif
enddo
call random_number(harvest)
call reverse('spalindromes', backword(swords+1))
write(6, *) '5 of ', swords, backword(swords+1)
write(6,'(5(a/))') (backword(1+int(harvest(i)*(swords-2))), i=1,5)
contains
subroutine reverse(inp, outp)
character(len=*), intent(in) :: inp
character(len=*), intent(inout) :: outp
integer :: k, L
L = len_trim(inp)
do k = 1, L
outp(L+1-k:L+1-k) = inp(k:k)
enddo
do k = L+1, len(outp)
outp(k:k) = ' '
enddo
end subroutine reverse
subroutine bs(a, n) ! ok, despite having claimed that bubble sort should be unceremoniously buried, I'll use it anyway because I expect the dictionary is nearly ordered. It's also not a terrible sort for less than 5 items.
! Please note, I tested bs using unixdict.txt randomized with sort --random .
character(len=*),dimension(*),intent(inout) :: a
integer, intent(in) :: n
integer :: i, j, k
logical :: done
character(len=1) :: t
do i=n-1, 1, -1
done = .true.
do j=1, i
if (a(j+1) .lt. a(j)) then
done = .false.
do k = 1, max(len_trim(a(j+1)), len_trim(a(j)))
t = a(j+1)(k:k)
a(j+1)(k:k) = a(j)(k:k)
a(j)(k:k) = t(1:1)
enddo
endif
enddo
if (done) return
enddo
end subroutine bs
logical function binary_search(source, n, target)
character(len=*),dimension(*),intent(in) :: source
character(len=*),intent(in) :: target
integer, intent(in) :: n
integer :: a,m,z
a = 1
z = n
do while (a .lt. z)
m = a + (z - a) / 2
if (target .lt. source(m)) then
z = m-1
else
if (m .eq. a) exit
a = m
endif
enddo
binary_search = (target .eq. source(a)) .or. (target .eq. source(z))
end function binary_search
end program Semordnilap
|
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.
|
#UNIX_Shell
|
UNIX Shell
|
a() {
echo "Called a $1"
"$1"
}
b() {
echo "Called b $1"
"$1"
}
for i in false true; do
for j in false true; do
a $i && b $j && x=true || x=false
echo " $i && $j is $x"
a $i || b $j && y=true || y=false
echo " $i || $j is $y"
done
done
|
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)
|
#Racket
|
Racket
|
#lang racket
;; using sendmail:
(require net/sendmail)
(send-mail-message
"[email protected]" "Some Subject"
'("[email protected]" "[email protected]")
'("[email protected]")
'("[email protected]")
(list "Some lines of text" "go here."))
;; and using smtp (and adding more headers here):
(require net/head net/smtp)
(smtp-send-message
"192.168.0.1"
"Sender <[email protected]>"
'("Recipient <[email protected]>")
(standard-message-header
"Sender <[email protected]>"
'("Recipient <[email protected]>")
'() ; CC
'() ; BCC
"Subject")
'("Hello World!"))
|
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)
|
#Raku
|
Raku
|
use Email::Simple;
my $to = '[email protected]';
my $from = '[email protected]';
my $subject = 'test';
my $body = 'This is a test.';
my $email = Email::Simple.create(
:header[['To', $to], ['From', $from], ['Subject', $subject]],
:body($body)
);
say ~$email;
# Note that the following will fail without an actual smtp server that
# will accept anonymous emails on port 25 (Not very common anymore).
# Most public email servers now require authentication and encryption.
my $smtp-server = 'smtp.example.com';
my $smtp-port = 25;
await IO::Socket::Async.connect($smtp-server, $smtp-port).then(
-> $smtp {
if $smtp.status {
given $smtp.result {
react {
whenever .Supply() -> $response {
if $response ~~ /^220/ {
.print( join "\r\n",
"EHLO $smtp-server",
"MAIL FROM:<{$email.from}>",
"RCPT TO:<{$email.to}>",
"DATA", $email.body,
'.', ''
)
}
elsif $response ~~ /^250/ {
.print("QUIT\r\n");
done
}
else {
say "Send email failed with: $response";
done
}
}
.close
}
}
}
}
)
|
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.
|
#J
|
J
|
isSemiPrime=: 2 = #@q: ::0:"0
|
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.
|
#Java
|
Java
|
import java.math.BigInteger;
import java.util.ArrayList;
import java.util.List;
public class SemiPrime{
private static final BigInteger TWO = BigInteger.valueOf(2);
public static List<BigInteger> primeDecomp(BigInteger a){
// impossible for values lower than 2
if(a.compareTo(TWO) < 0){
return null;
}
//quickly handle even values
List<BigInteger> result = new ArrayList<BigInteger>();
while(a.and(BigInteger.ONE).equals(BigInteger.ZERO)){
a = a.shiftRight(1);
result.add(TWO);
}
//left with odd values
if(!a.equals(BigInteger.ONE)){
BigInteger b = BigInteger.valueOf(3);
while(b.compareTo(a) < 0){
if(b.isProbablePrime(10)){
BigInteger[] dr = a.divideAndRemainder(b);
if(dr[1].equals(BigInteger.ZERO)){
result.add(b);
a = dr[0];
}
}
b = b.add(TWO);
}
result.add(b); //b will always be prime here...
}
return result;
}
public static boolean isSemi(BigInteger x){
List<BigInteger> decomp = primeDecomp(x);
return decomp != null && decomp.size() == 2;
}
public static void main(String[] args){
for(int i = 2; i <= 100; i++){
if(isSemi(BigInteger.valueOf(i))){
System.out.print(i + " ");
}
}
System.out.println();
for(int i = 1675; i <= 1680; i++){
if(isSemi(BigInteger.valueOf(i))){
System.out.print(i + " ");
}
}
}
}
|
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
|
#C.2B.2B
|
C++
|
#include <numeric>
#include <cctype>
#include <iostream>
#include <string>
template<typename result_sink_t>
auto sedol_checksum(std::string const& sedol, result_sink_t result_sink)
{
if(sedol.size() != 6)
return result_sink(0, "length of sedol string != 6");
const char * valid_chars = "BCDFGHJKLMNPQRSTVWXYZ0123456789";
if(sedol.find_first_not_of(valid_chars) != std::string::npos)
return result_sink(0, "sedol string contains disallowed characters");
const int weights[] = {1,3,1,7,3,9};
auto weighted_sum = std::inner_product(sedol.begin(), sedol.end(), weights, 0
, [](int acc, int prod){ return acc + prod; }
, [](char c, int weight){ return (std::isalpha(c) ? c -'A' + 10 : c - '0') * weight; }
);
return result_sink((10 - (weighted_sum % 10)) % 10, nullptr);
}
int main()
{
using namespace std;
string inputs[] = {
"710889", "B0YBKJ", "406566", "B0YBLH", "228276", "B0YBKL",
"557910", "B0YBKR", "585284", "B0YBKT", "B00030"
};
for(auto const & sedol : inputs)
{
sedol_checksum(sedol, [&](auto sum, char const * errorMessage)
{
if(errorMessage)
cout << "error for sedol: " << sedol << " message: " << errorMessage << "\n";
else
cout << sedol << sum << "\n";
});
}
return 0;
}
|
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
|
#JavaScript
|
JavaScript
|
function is_self_describing(n) {
var digits = Number(n).toString().split("").map(function(elem) {return Number(elem)});
var len = digits.length;
var count = digits.map(function(x){return 0});
digits.forEach(function(digit, idx, ary) {
if (digit >= count.length)
return false
count[digit] ++;
});
return digits.equals(count);
}
Array.prototype.equals = function(other) {
if (this === other)
return true; // same object
if (this.length != other.length)
return false;
for (idx in this)
if (this[idx] !== other[idx])
return false;
return true;
}
for (var i=1; i<=3300000; i++)
if (is_self_describing(i))
print(i);
|
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
|
#Sidef
|
Sidef
|
func is_self_number(n) {
if (n < 30) {
return (((n < 10) && (n.is_odd)) || (n == 20))
}
var qd = (1 + n.ilog10)
var r = (1 + (n-1)%9)
var h = (r + 9*(r%2))/2
var ld = 10
while (h + 9*qd >= n%ld) {
ld *= 10
}
var vs = idiv(n, ld).sumdigits
n %= ld
0..qd -> none { |i|
vs + sumdigits(n - h - 9*i) == (h + 9*i)
}
}
say is_self_number.first(50).join(' ')
|
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.
|
#Wren
|
Wren
|
import "/dynamic" for Enum
var RangeType = Enum.create("RangeType", ["CLOSED", "BOTH_OPEN", "LEFT_OPEN", "RIGHT_OPEN"])
class RealSet {
construct new(start, end, pred) {
_low = start
_high = end
_pred = (pred == RangeType.CLOSED) ? Fn.new { |d| d >= _low && d <= _high } :
(pred == RangeType.BOTH_OPEN) ? Fn.new { |d| d > _low && d < _high } :
(pred == RangeType.LEFT_OPEN) ? Fn.new { |d| d > _low && d <= _high } :
(pred == RangeType.RIGHT_OPEN) ? Fn.new { |d| d >= _low && d < _high } : pred
}
low { _low }
high { _high }
pred { _pred }
contains(d) { _pred.call(d) }
union(other) {
if (!other.type == RealSet) Fiber.abort("Argument must be a RealSet")
var low2 = _low.min(other.low)
var high2 = _high.max(other.high)
return RealSet.new(low2, high2) { |d| _pred.call(d) || other.pred.call(d) }
}
intersect(other) {
if (!other.type == RealSet) Fiber.abort("Argument must be a RealSet")
var low2 = _low.max(other.low)
var high2 = _high.min(other.high)
return RealSet.new(low2, high2) { |d| _pred.call(d) && other.pred.call(d) }
}
subtract(other) {
if (!other.type == RealSet) Fiber.abort("Argument must be a RealSet")
return RealSet.new(_low, _high) { |d| _pred.call(d) && !other.pred.call(d) }
}
length {
if (_low.isInfinity || _high.isInfinity) return -1 // error value
if (_high <= _low) return 0
var p = _low
var count = 0
var interval = 0.00001
while (true) {
if (_pred.call(p)) count = count + 1
p = p + interval
if (p >= _high) break
}
return count * interval
}
isEmpty { (_high == _low) ? !_pred.call(_low) : length == 0 }
}
var a = RealSet.new(0, 1, RangeType.LEFT_OPEN)
var b = RealSet.new(0, 2, RangeType.RIGHT_OPEN)
var c = RealSet.new(1, 2, RangeType.LEFT_OPEN)
var d = RealSet.new(0, 3, RangeType.RIGHT_OPEN)
var e = RealSet.new(0, 1, RangeType.BOTH_OPEN)
var f = RealSet.new(0, 1, RangeType.CLOSED)
var g = RealSet.new(0, 0, RangeType.CLOSED)
for (i in 0..2) {
System.print("(0, 1] ∪ [0, 2) contains %(i) is %(a.union(b).contains(i))")
System.print("[0, 2) ∩ (1, 2] contains %(i) is %(b.intersect(c).contains(i))")
System.print("[0, 3) − (0, 1) contains %(i) is %(d.subtract(e).contains(i))")
System.print("[0, 3) − [0, 1] contains %(i) is %(d.subtract(f).contains(i))\n")
}
System.print("[0, 0] is empty is %(g.isEmpty)\n")
var aa = RealSet.new(0, 10) { |x| (0 < x && x < 10) && ((Num.pi * x * x).sin.abs > 0.5) }
var bb = RealSet.new(0, 10) { |x| (0 < x && x < 10) && ((Num.pi * x).sin.abs > 0.5) }
var cc = aa.subtract(bb)
System.print("Approx 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
|
#Java
|
Java
|
import java.util.stream.IntStream;
public class Test {
static IntStream getPrimes(int start, int end) {
return IntStream.rangeClosed(start, end).filter(n -> isPrime(n));
}
public static boolean isPrime(long x) {
if (x < 3 || x % 2 == 0)
return x == 2;
long max = (long) Math.sqrt(x);
for (long n = 3; n <= max; n += 2) {
if (x % n == 0) {
return false;
}
}
return true;
}
public static void main(String[] args) {
getPrimes(0, 100).forEach(p -> System.out.printf("%d, ", p));
}
}
|
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
|
#jq
|
jq
|
# Produce a (possibly empty) stream of primes in the range [m,n], i.e. m <= p <= n
def primes(m; n):
([m,2] | max) as $m
| if $m > n then empty
elif $m == 2 then 2, primes(3;n)
else (1 + (2 * range($m/2 | floor; (n + 1) /2 | floor))) | select( is_prime )
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.
|
#F.23
|
F#
|
open System
let SequenceOfNonSquares =
let nonsqr n = n+(int(0.5+Math.Sqrt(float (n))))
let isqrt n = int(Math.Sqrt(float(n)))
let IsSquare n = n = (isqrt n)*(isqrt n)
{1 .. 999999}
|> Seq.map(fun f -> (f, nonsqr f))
|> Seq.filter(fun f -> IsSquare(snd f))
;;
|
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.
|
#Factor
|
Factor
|
USING: kernel math math.functions math.ranges prettyprint
sequences ;
: non-sq ( n -- m ) dup sqrt 1/2 + floor + >integer ;
: print-first22 ( -- ) 22 [1,b] [ non-sq ] map . ;
: check-for-sq ( -- ) 1,000,000 [1,b)
[ non-sq sqrt dup floor = [ "Square found." throw ] when ]
each ;
print-first22 check-for-sq
|
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
|
#Elixir
|
Elixir
|
iex(1)> s = MapSet.new
#MapSet<[]>
iex(2)> sa = MapSet.put(s, :a)
#MapSet<[:a]>
iex(3)> sab = MapSet.put(sa, :b)
#MapSet<[:a, :b]>
iex(4)> sbc = Enum.into([:b, :c], MapSet.new)
#MapSet<[:b, :c]>
iex(5)> MapSet.member?(sab, :a)
true
iex(6)> MapSet.member?(sab, :c)
false
iex(7)> :a in sab
true
iex(8)> MapSet.union(sab, sbc)
#MapSet<[:a, :b, :c]>
iex(9)> MapSet.intersection(sab, sbc)
#MapSet<[:b]>
iex(10)> MapSet.difference(sab, sbc)
#MapSet<[:a]>
iex(11)> MapSet.disjoint?(sab, sbc)
false
iex(12)> MapSet.subset?(sa, sab)
true
iex(13)> MapSet.subset?(sab, sa)
false
iex(14)> sa == sab
false
|
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
|
#BBC_BASIC
|
BBC BASIC
|
limit% = 100000
DIM sieve% limit%
prime% = 2
WHILE prime%^2 < limit%
FOR I% = prime%*2 TO limit% STEP prime%
sieve%?I% = 1
NEXT
REPEAT prime% += 1 : UNTIL sieve%?prime%=0
ENDWHILE
REM Display the primes:
FOR I% = 1 TO limit%
IF sieve%?I% = 0 PRINT I%;
NEXT
|
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
|
#TXR
|
TXR
|
(defun mkset (p x) (set [p x] (or [p x] x)))
(defun fnd (p x) (if (eq [p x] x) x (fnd p [p x])))
(defun uni (p x y)
(let ((xr (fnd p x)) (yr (fnd p y)))
(set [p xr] yr)))
(defun consoli (sets)
(let ((p (hash)))
(each ((s sets))
(each ((e s))
(mkset p e)
(uni p e (car s))))
(hash-values
[group-by (op fnd p) (hash-keys
[group-by identity (flatten sets)])])))
;; tests
(each ((test '(((a b) (c d))
((a b) (b d))
((a b) (c d) (d b))
((h i k) (a b) (c d) (d b) (f g h)))))
(format t "~s -> ~s\n" test (consoli test)))
|
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
|
#VBA
|
VBA
|
Private Function has_intersection(set1 As Collection, set2 As Collection) As Boolean
For Each element In set1
On Error Resume Next
tmp = set2(element)
If tmp = element Then
has_intersection = True
Exit Function
End If
Next element
End Function
Private Sub union(set1 As Collection, set2 As Collection)
For Each element In set2
On Error Resume Next
tmp = set1(element)
If tmp <> element Then
set1.Add element, element
End If
Next element
End Sub
Private Function consolidate(sets As Collection) As Collection
For i = sets.Count To 1 Step -1
For j = sets.Count To i + 1 Step -1
If has_intersection(sets(i), sets(j)) Then
union sets(i), sets(j)
sets.Remove j
End If
Next j
Next i
Set consolidate = sets
End Function
Private Function mc(s As Variant) As Collection
Dim res As New Collection
For i = 1 To Len(s)
res.Add Mid(s, i, 1), Mid(s, i, 1)
Next i
Set mc = res
End Function
Private Function ms(t As Variant) As Collection
Dim res As New Collection
Dim element As Collection
For i = LBound(t) To UBound(t)
Set element = t(i)
res.Add t(i)
Next i
Set ms = res
End Function
Private Sub show(x As Collection)
Dim t() As String
Dim u() As String
ReDim t(1 To x.Count)
For i = 1 To x.Count
ReDim u(1 To x(i).Count)
For j = 1 To x(i).Count
u(j) = x(i)(j)
Next j
t(i) = "{" & Join(u, ", ") & "}"
Next i
Debug.Print "{" & Join(t, ", ") & "}"
End Sub
Public Sub main()
show consolidate(ms(Array(mc("AB"), mc("CD"))))
show consolidate(ms(Array(mc("AB"), mc("BD"))))
show consolidate(ms(Array(mc("AB"), mc("CD"), mc("DB"))))
show consolidate(ms(Array(mc("HIK"), mc("AB"), mc("CD"), mc("DB"), mc("FGH"))))
End Sub
|
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
|
#R
|
R
|
chr <- function(n) {
rawToChar(as.raw(n))
}
idx <- 32
while (idx < 128) {
for (i in 0:5) {
num <- idx + i
if (num<100) cat(" ")
cat(num,": ")
if (num == 32) { cat("Spc "); next }
if (num == 127) { cat("Del "); next }
cat(chr(num)," ")
}
idx <- idx + 6
cat("\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
|
#TI-83_BASIC
|
TI-83 BASIC
|
PROGRAM:SIRPNSKI
:ClrHome
:Output(1,8,"^")
:{0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0}→L1
:{0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0}→L2
:L2→L3
:For(X,2,8,1)
:For(Y,2,17,1)
:If L1(Y-1)
:Then
:4→N
:End
:If L1(Y)
:Then
:N+2→N
:End
:If L1(Y+1)
:Then
:N+1→N
:End
:If N=1 or N=3 or N=4 or N=6
:Then
:1→L2(Y)
:Output(X,Y-1,"^")
:End
:0→N
:End
:L2→L1
:L3→L2
:End
|
http://rosettacode.org/wiki/Sierpinski_carpet
|
Sierpinski carpet
|
Task
Produce a graphical or ASCII-art representation of a Sierpinski carpet of order N.
For example, the Sierpinski carpet of order 3 should look like this:
###########################
# ## ## ## ## ## ## ## ## #
###########################
### ###### ###### ###
# # # ## # # ## # # #
### ###### ###### ###
###########################
# ## ## ## ## ## ## ## ## #
###########################
######### #########
# ## ## # # ## ## #
######### #########
### ### ### ###
# # # # # # # #
### ### ### ###
######### #########
# ## ## # # ## ## #
######### #########
###########################
# ## ## ## ## ## ## ## ## #
###########################
### ###### ###### ###
# # # ## # # ## # # #
### ###### ###### ###
###########################
# ## ## ## ## ## ## ## ## #
###########################
The use of the # character is not rigidly required for ASCII art.
The important requirement is the placement of whitespace and non-whitespace characters.
Related task
Sierpinski triangle
|
#QB64
|
QB64
|
_Title "Sierpinski Carpet"
Screen _NewImage(500, 545, 8)
Cls , 15: Color 1, 15
'labels
_PrintString (96, 8), "Order 0"
_PrintString (345, 8), "Order 1"
_PrintString (96, 280), "Order 3"
_PrintString (345, 280), "Order 4"
'carpets
Call carpet(5, 20, 243, 0)
Call carpet(253, 20, 243, 1)
Call carpet(5, 293, 243, 2)
Call carpet(253, 293, 243, 3)
Sleep
System
Sub carpet (x As Integer, y As Integer, size As Integer, order As Integer)
Dim As Integer ix, iy, isize, iorder, side, newX, newY
ix = x: iy = y: isize = size: iorder = order
Line (ix, iy)-(ix + isize - 1, iy + isize - 1), 1, BF
side = Int(isize / 3)
newX = ix + side
newY = iy + side
Line (newX, newY)-(newX + side - 1, newY + side - 1), 15, BF
iorder = iorder - 1
If iorder >= 0 Then
Call carpet(newX - side, newY - side + 1, side, iorder)
Call carpet(newX, newY - side + 1, side, iorder)
Call carpet(newX + side, newY - side + 1, side, iorder)
Call carpet(newX + side, newY, side, iorder)
Call carpet(newX + side, newY + side, side, iorder)
Call carpet(newX, newY + side, side, iorder)
Call carpet(newX - side, newY + side, side, iorder)
Call carpet(newX - side, newY, side, iorder)
End If
End Sub
|
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
|
#FreeBASIC
|
FreeBASIC
|
' version 20-06-2015
' compile with: fbc -s console
Function reverse(norm As String) As String
Dim As String rev
Dim As Integer i, l = Len(norm) -1
rev = norm
For i = 0 To l
rev[l-i] = norm[i]
Next
Return rev
End Function
' ------=< MAIN >=------
Dim As Integer i, j, count, amount, ff = FreeFile
Dim As String in_str, rev, big = " " ' big needs to start with a space
Dim As String norm(27000), result(270, 2)
Print
Print "Start reading unixdict.txt";
Open "unixdict.txt" For Input As #ff
While Not Eof(ff) ' read to end of file
Line Input #ff, in_str ' get line = word
in_str = Trim(in_str) ' we don't want spaces
If Len(in_str) > 1 Then ' if length > 1 then reverse
rev = reverse(in_str)
If in_str <> rev Then ' if in_str is not a palingdrome
count = count + 1 ' increase counter
norm(count) = in_str ' store in the array
big = big + rev + " " ' create big string with reversed words
End If
End If
Wend
Close #ff
Print " ... Done"
Print : Print "Start looking for semordnilap"
For i = 1 To count
For j = 1 To amount ' check to avoid the double
If result(j, 2) = norm(i) Then Continue For, For
Next
j = InStr(big, " " + norm(i) + " ")
If j <> 0 Then ' found one
amount = amount + 1 ' increase counter
result(amount,1) = norm(i) ' store normal word
result(amount,2) = reverse(norm(i)) ' store reverse word
End If
Next
Print : Print "Found"; amount; " unique semordnilap pairs"
Print : Print "Display 5 semordnilap pairs"
Print
count = 0
For i = 1 To amount
If Len(result(i,1)) >= 5 Then
count = count + 1
Print result(i, 1), result(i, 2)
If count >= 5 Then Exit For
EndIf
Next
Print
' empty keyboard buffer
While InKey <> "" : Wend
Print : Print "Hit any key to end program"
Sleep
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.
|
#VBA
|
VBA
|
Private Function a(i As Variant) As Boolean
Debug.Print "a: "; i = 1,
a = i
End Function
Private Function b(j As Variant) As Boolean
Debug.Print "b: "; j = 1;
b = j
End Function
Public Sub short_circuit()
Dim x As Boolean, y As Boolean
'Dim p As Boolean, q As Boolean
Debug.Print "=====AND=====" & vbCrLf
For p = 0 To 1
For q = 0 To 1
If a(p) Then
x = b(q)
End If
Debug.Print " = x"
Next q
Debug.Print
Next p
Debug.Print "======OR=====" & vbCrLf
For p = 0 To 1
For q = 0 To 1
If Not a(p) Then
x = b(q)
End If
Debug.Print " = x"
Next q
Debug.Print
Next p
Debug.Print
End Sub
|
http://rosettacode.org/wiki/Short-circuit_evaluation
|
Short-circuit evaluation
|
Control Structures
These are examples of control structures. You may also be interested in:
Conditional structures
Exceptions
Flow-control structures
Loops
Assume functions a and b return boolean values, and further, the execution of function b takes considerable resources without side effects, and is to be minimized.
If we needed to compute the conjunction (and):
x = a() and b()
Then it would be best to not compute the value of b() if the value of a() is computed as false, as the value of x can then only ever be false.
Similarly, if we needed to compute the disjunction (or):
y = a() or b()
Then it would be best to not compute the value of b() if the value of a() is computed as true, as the value of y can then only ever be true.
Some languages will stop further computation of boolean equations as soon as the result is known, so-called short-circuit evaluation of boolean expressions
Task
Create two functions named a and b, that take and return the same boolean value.
The functions should also print their name whenever they are called.
Calculate and assign the values of the following equations to a variable in such a way that function b is only called when necessary:
x = a(i) and b(j)
y = a(i) or b(j)
If the language does not have short-circuit evaluation, this might be achieved with nested if statements.
|
#Visual_Basic_.NET
|
Visual Basic .NET
|
Module Module1
Function A(v As Boolean) As Boolean
Console.WriteLine("a")
Return v
End Function
Function B(v As Boolean) As Boolean
Console.WriteLine("b")
Return v
End Function
Sub Test(i As Boolean, j As Boolean)
Console.WriteLine("{0} and {1} = {2} (eager evaluation)", i, j, A(i) And B(j))
Console.WriteLine("{0} or {1} = {2} (eager evaluation)", i, j, A(i) Or B(j))
Console.WriteLine("{0} and {1} = {2} (lazy evaluation)", i, j, A(i) AndAlso B(j))
Console.WriteLine("{0} or {1} = {2} (lazy evaluation)", i, j, A(i) OrElse B(j))
Console.WriteLine()
End Sub
Sub Main()
Test(False, False)
Test(False, True)
Test(True, False)
Test(True, True)
End Sub
End Module
|
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)
|
#REBOL
|
REBOL
|
send [email protected] "My 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)
|
#REXX
|
REXX
|
load "stdlib.ring"
See "Send email..." + nl
sendemail("smtp://smtp.gmail.com",
"[email protected]",
"password",
"[email protected]",
"[email protected]",
"[email protected]",
"Sending email from Ring",
"Hello
How are you?
Are you fine?
Thank you!
Greetings,
CalmoSoft")
see "Done.." + nl
|
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)
|
#Ring
|
Ring
|
load "stdlib.ring"
See "Send email..." + nl
sendemail("smtp://smtp.gmail.com",
"[email protected]",
"password",
"[email protected]",
"[email protected]",
"[email protected]",
"Sending email from Ring",
"Hello
How are you?
Are you fine?
Thank you!
Greetings,
CalmoSoft")
see "Done.." + nl
|
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.
|
#jq
|
jq
|
# Output: a stream of proper factors (probably unsorted)
def proper_factors:
range(2; 1 + sqrt|floor) as $i
| if (. % $i) == 0
then (. / $i) as $r
| if $i == $r then $i else $i, $r end
else empty
end;
def is_semiprime:
. as $n
| any(proper_factors;
is_prime and (($n / .) | (. == $n or is_prime) );
|
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.
|
#Julia
|
Julia
|
using Primes
issemiprime(n::Integer) = sum(values(factor(n))) == 2
@show filter(issemiprime, 1:100)
|
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
|
#Cach.C3.A9_ObjectScript
|
Caché ObjectScript
|
Class Utils.Check [ Abstract ]
{
ClassMethod SEDOL(x As %String) As %Boolean
{
// https://en.wikipedia.org/wiki/SEDOL
IF x'?1(7N,1U5UN1N) QUIT 0
IF x'=$TRANSLATE(x,"AEIOU") QUIT 0
SET cd=$EXTRACT(x,*), x=$EXTRACT(x,1,*-1)
SET wgt="1317391", t=0
FOR i=1:1:$LENGTH(x) {
SET n=$EXTRACT(x,i)
IF n'=+n SET n=$ASCII(n)-55
SET t=t+(n*$EXTRACT(wgt,i))
}
QUIT cd=((10-(t#10))#10)
}
}
|
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
|
#Clojure
|
Clojure
|
(defn sedols [xs]
(letfn [(sedol [ys] (let [weights [1 3 1 7 3 9]
convtonum (map #(Character/getNumericValue %) ys)
check (-> (reduce + (map * weights convtonum)) (rem 10) (->> (- 10)) (rem 10))]
(str ys check)))]
(map #(sedol %) xs)))
|
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
|
#jq
|
jq
|
# If your jq includes all/2 then comment out the following definition,
# which is slightly less efficient:
def all(generator; condition):
reduce generator as $i (true; if . then $i | condition else . 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
|
#Julia
|
Julia
|
function selfie(x::Integer)
ds = reverse(digits(x))
if sum(ds) != length(ds) return false end
for (i, d) in enumerate(ds)
if d != sum(ds .== i - 1) return false end
end
return true
end
@show selfie(2020)
@show selfie(2021)
selfies(x) = for i in 1:x selfie(i) && println(i) end
@time selfies(4000000)
|
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
|
#Standard_ML
|
Standard ML
|
open List;
val rec selfNumberNr = fn NR =>
let
val rec sumdgt = fn 0 => 0 | n => Int.rem (n, 10) + sumdgt (Int.quot(n ,10));
val rec isSelf = fn ([],l1,l2) => []
| (x::tt,l1,l2) => if exists (fn i=>i=x) l1 orelse exists (fn i=>i=x) l2
then ( isSelf (tt,l1,l2)) else x::isSelf (tt,l1,l2) ;
val rec partcount = fn (n, listIn , count , selfs) =>
if count >= NR then nth (selfs, length selfs + NR - count -1)
else
let
val range = tabulate (81 , fn i => 81*n +i+1) ;
val listOut = map (fn i => i + sumdgt i ) range ;
val selfs = isSelf (range,listIn,listOut)
in
partcount ( n+1 , listOut , count+length (selfs) , selfs )
end;
in
partcount (0,[],0,[])
end;
app ((fn s => print (s ^ " ")) o Int.toString o selfNumberNr) (tabulate (50,fn i=>i+1)) ;
selfNumberNr 100000000 ;
|
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
|
#Wren
|
Wren
|
var sieve = Fn.new {
var sv = List.filled(2*1e9+9*9+1, false)
var n = 0
var s = [0] * 8
for (a in 0..1) {
for (b in 0..9) {
s[0] = a + b
for (c in 0..9) {
s[1] = s[0] + c
for (d in 0..9) {
s[2] = s[1] + d
for (e in 0..9) {
s[3] = s[2] + e
for (f in 0..9) {
s[4] = s[3] + f
for (g in 0..9) {
s[5] = s[4] + g
for (h in 0..9) {
s[6] = s[5] + h
for (i in 0..9) {
s[7] = s[6] + i
for (j in 0..9) {
sv[s[7] + j + n] = true
n = n + 1
}
}
}
}
}
}
}
}
}
}
return sv
}
var st = System.clock
var sv = sieve.call()
var count = 0
System.print("The first 50 self numbers are:")
for (i in 0...sv.count) {
if (!sv[i]) {
count = count + 1
if (count <= 50) System.write("%(i) ")
if (count == 1e8) {
System.print("\n\nThe 100 millionth self number is %(i)")
break
}
}
}
System.print("Took %(System.clock-st) seconds.")
|
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.
|
#zkl
|
zkl
|
class RealSet{
fcn init(fx){ var [const] contains=fx; }
fcn holds(x){ contains(x) }
fcn __opAdd(rs){ RealSet('wrap(x){ contains(x) or rs.contains(x) }) }
fcn __opSub(rs){ RealSet('wrap(x){ contains(x) and not rs.contains(x) }) }
fcn intersection(rs) { RealSet('wrap(x){ contains(x) and rs.contains(x) }) }
}
|
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
|
#Julia
|
Julia
|
struct TDPrimes{T<:Integer}
uplim::T
end
Base.start{T<:Integer}(pl::TDPrimes{T}) = 2ones(T, 1)
Base.done{T<:Integer}(pl::TDPrimes{T}, p::Vector{T}) = p[end] > pl.uplim
function Base.next{T<:Integer}(pl::TDPrimes{T}, p::Vector{T})
pr = npr = p[end]
ispr = false
while !ispr
npr += 1
ispr = all(npr % d != 0 for d in p)
end
push!(p, npr)
return pr, p
end
println("Primes ≤ 100: ", join((p for p in TDPrimes(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
|
#Kotlin
|
Kotlin
|
// version 1.0.6
fun isPrime(n: Int): Boolean {
if (n < 2) return false
if (n % 2 == 0) return n == 2
if (n % 3 == 0) return n == 3
var d : Int = 5
while (d * d <= n) {
if (n % d == 0) return false
d += 2
if (n % d == 0) return false
d += 4
}
return true
}
fun main(args: Array<String>) {
// print all primes below 2000 say
var count = 1
print(" 2")
for (i in 3..1999 step 2)
if (isPrime(i)) {
count++
print("%5d".format(i))
if (count % 15 == 0) println()
}
}
|
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.
|
#Fantom
|
Fantom
|
class Main
{
static Float fn (Int n)
{
n + (0.5f + (n * 1.0f).sqrt).floor
}
static Bool isSquare (Float n)
{
n.sqrt.floor == n.sqrt
}
public static Void main ()
{
(1..22).each |n|
{
echo ("$n is ${fn(n)}")
}
echo ((1..1000000).toList.any |n| { isSquare (fn(n)) } )
}
}
|
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.
|
#Forth
|
Forth
|
: u>f 0 d>f ;
: f>u f>d drop ;
: fn ( n -- n ) dup u>f fsqrt fround f>u + ;
: test ( n -- ) 1 do i fn . loop ;
23 test \ 2 3 5 6 7 8 10 11 12 13 14 15 17 18 19 20 21 22 23 24 26 27 ok
: square? ( n -- ? ) u>f fsqrt fdup fround f- f0= ;
: test ( n -- ) 1 do i fn square? if cr i . ." fn was square" then loop ;
1000000 test \ ok
|
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
|
#Erlang
|
Erlang
|
2> S = sets:new().
3> Sa = sets:add_element(a, S).
4> Sab = sets:from_list([a, b]).
5> sets:is_element(a, Sa).
true
6> Union = sets:union(Sa, Sab).
7> sets:to_list(Union).
[a,b]
8> Intersection = sets:intersection(Sa, Sab).
9> sets:to_list(Intersection).
[a]
10> Subtract = sets:subtract(Sab, Sa).
11> sets:to_list(Subtract).
[b]
12> sets:is_subset(Sa, Sab).
true
13> Sa =:= Sab.
false
|
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
|
#BCPL
|
BCPL
|
get "libhdr"
manifest $( LIMIT = 1000 $)
let sieve(prime,max) be
$( let i = 2
0!prime := false
1!prime := false
for i = 2 to max do i!prime := true
while i*i <= max do
$( if i!prime do
$( let j = i*i
while j <= max do
$( j!prime := false
j := j + i
$)
$)
i := i + 1
$)
$)
let start() be
$( let prime = vec LIMIT
let col = 0
sieve(prime, LIMIT)
for i = 2 to LIMIT do
if i!prime do
$( writef("%I4",i)
col := col + 1
if col rem 20 = 0 then wrch('*N')
$)
wrch('*N')
$)
|
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
|
#VBScript
|
VBScript
|
Function consolidate(s)
sets = Split(s,",")
n = UBound(sets)
For i = 1 To n
p = i
ts = ""
For j = i To 1 Step -1
If ts = "" Then
p = j
End If
ts = ""
For k = 1 To Len(sets(p))
If InStr(1,sets(j-1),Mid(sets(p),k,1)) = 0 Then
ts = ts & Mid(sets(p),k,1)
End If
Next
If Len(ts) < Len(sets(p)) Then
sets(j-1) = sets(j-1) & ts
sets(p) = "-"
ts = ""
Else
p = i
End If
Next
Next
consolidate = s & " = " & Join(sets," , ")
End Function
'testing
test = Array("AB","AB,CD","AB,CD,DB","HIK,AB,CD,DB,FGH")
For Each t In test
WScript.StdOut.WriteLine consolidate(t)
Next
|
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
|
#Wren
|
Wren
|
import "/set" for Set
var consolidateSets = Fn.new { |sets|
var size = sets.count
var consolidated = List.filled(size, false)
var i = 0
while (i < size - 1) {
if (!consolidated[i]) {
while (true) {
var intersects = 0
for (j in i+1...size) {
if (!consolidated[j]) {
if (!sets[i].intersect(sets[j]).isEmpty) {
sets[i].addAll(sets[j])
consolidated[j] = true
intersects = intersects + 1
}
}
}
if (intersects == 0) break
}
}
i = i + 1
}
return (0...size).where { |i| !consolidated[i] }.map { |i| sets[i] }.toList
}
var unconsolidatedSets = [
[Set.new(["A", "B"]), Set.new(["C", "D"])],
[Set.new(["A", "B"]), Set.new(["B", "D"])],
[Set.new(["A", "B"]), Set.new(["C", "D"]), Set.new(["D", "B"])],
[Set.new(["H", "I", "K"]), Set.new(["A", "B"]), Set.new(["C", "D"]),
Set.new(["D", "B"]), Set.new(["F", "G", "H"])]
]
for (sets in unconsolidatedSets) {
System.print("Unconsolidated: %(sets)")
System.print("Cosolidated : %(consolidateSets.call(sets))\n")
}
|
http://rosettacode.org/wiki/Show_ASCII_table
|
Show ASCII table
|
Task
Show the ASCII character set from values 32 to 127 (decimal) in a table format.
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
|
#Racket
|
Racket
|
#lang racket
(for ([i (in-range 16)])
(for ([j (in-range 6)])
(define n (+ 32 (* j 16) i))
(printf "~a : ~a"
(~a n #:align 'right #:min-width 3)
(~a (match n
[32 "SPC"]
[127 "DEL"]
[_ (integer->char n)]) #:min-width 5)))
(newline))
|
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
|
#uBasic.2F4tH
|
uBasic/4tH
|
Input "Triangle order: ";n
n = 2^n
For y = n - 1 To 0 Step -1
For i = 0 To y
Print " ";
Next
x = 0
For x = 0 Step 1 While ((x + y) < n)
If AND (x,y) Then
Print " ";
Else
Print "* ";
EndIf
Next
Print
Next
End
|
http://rosettacode.org/wiki/Sierpinski_carpet
|
Sierpinski carpet
|
Task
Produce a graphical or ASCII-art representation of a Sierpinski carpet of order N.
For example, the Sierpinski carpet of order 3 should look like this:
###########################
# ## ## ## ## ## ## ## ## #
###########################
### ###### ###### ###
# # # ## # # ## # # #
### ###### ###### ###
###########################
# ## ## ## ## ## ## ## ## #
###########################
######### #########
# ## ## # # ## ## #
######### #########
### ### ### ###
# # # # # # # #
### ### ### ###
######### #########
# ## ## # # ## ## #
######### #########
###########################
# ## ## ## ## ## ## ## ## #
###########################
### ###### ###### ###
# # # ## # # ## # # #
### ###### ###### ###
###########################
# ## ## ## ## ## ## ## ## #
###########################
The use of the # character is not rigidly required for ASCII art.
The important requirement is the placement of whitespace and non-whitespace characters.
Related task
Sierpinski triangle
|
#Quackery
|
Quackery
|
[ over 3 mod 1 = ] is 1? ( n1 n2 --> n1 n2 f )
[ 3 / swap ] is 3/ ( n1 n2 --> n2/3 n1 )
[ true unrot
[ 2dup or while
1? 1? and iff
[ rot not unrot ] done
3/ 3/ again ]
2drop ] is incarpet ( n --> )
[ 1 swap times [ 3 * ]
dup times
[ i^ over times
[ i^ over incarpet iff
[ say "[]" ]
else
[ say " " ] ]
drop cr ]
drop ] is carpet ( n --> )
4 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
|
#Go
|
Go
|
package main
import (
"fmt"
"io/ioutil"
"log"
"strings"
)
func main() {
// read file into memory as one big block
data, err := ioutil.ReadFile("unixdict.txt")
if err != nil {
log.Fatal(err)
}
// copy the block, split it up into words
words := strings.Split(string(data), "\n")
// optional, free the first block for garbage collection
data = nil
// put words in a map, also determine length of longest word
m := make(map[string]bool)
longest := 0
for _, w := range words {
m[string(w)] = true
if len(w) > longest {
longest = len(w)
}
}
// allocate a buffer for reversing words
r := make([]byte, longest)
// iterate over word list
sem := 0
var five []string
for _, w := range words {
// first, delete from map. this prevents a palindrome from matching
// itself, and also prevents it's reversal from matching later.
delete(m, w)
// use buffer to reverse word
last := len(w) - 1
for i := 0; i < len(w); i++ {
r[i] = w[last-i]
}
rs := string(r[:len(w)])
// see if reversed word is in map, accumulate results
if m[rs] {
sem++
if len(five) < 5 {
five = append(five, w+"/"+rs)
}
}
}
// print results
fmt.Println(sem, "pairs")
fmt.Println("examples:")
for _, e := range five {
fmt.Println(" ", e)
}
}
|
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.
|
#Visual_FoxPro
|
Visual FoxPro
|
*!* Visual FoxPro natively supports short circuit evaluation
CLEAR
CREATE CURSOR funceval(arg1 L, arg2 L, operation V(3), result L, calls V(10))
*!* Conjunction
INSERT INTO funceval (arg1, arg2, operation) VALUES (.F., .F., "AND")
REPLACE result WITH (a(arg1) AND b(arg2))
INSERT INTO funceval (arg1, arg2, operation) VALUES (.F., .T., "AND")
REPLACE result WITH (a(arg1) AND b(arg2))
INSERT INTO funceval (arg1, arg2, operation) VALUES (.T., .F., "AND")
REPLACE result WITH (a(arg1) AND b(arg2))
INSERT INTO funceval (arg1, arg2, operation) VALUES (.T., .T., "AND")
REPLACE result WITH (a(arg1) AND b(arg2))
*!* Disjunction
INSERT INTO funceval (arg1, arg2, operation) VALUES (.F., .F., "OR")
REPLACE result WITH (a(arg1) OR b(arg2))
INSERT INTO funceval (arg1, arg2, operation) VALUES (.F., .T., "OR")
REPLACE result WITH (a(arg1) OR b(arg2))
INSERT INTO funceval (arg1, arg2, operation) VALUES (.T., .F., "OR")
REPLACE result WITH (a(arg1) OR b(arg2))
INSERT INTO funceval (arg1, arg2, operation) VALUES (.T., .T., "OR")
REPLACE result WITH (a(arg1) OR b(arg2))
GO TOP
_VFP.DataToClip("funceval", 8, 3)
FUNCTION a(v As Boolean) As Boolean
REPLACE calls WITH "a()"
RETURN v
ENDFUNC
FUNCTION b(v As Boolean) As Boolean
REPLACE calls WITH calls + ", b()"
RETURN v
ENDFUNC
|
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.
|
#Wren
|
Wren
|
var a = Fn.new { |bool|
System.print(" a called")
return bool
}
var b = Fn.new { |bool|
System.print(" b called")
return bool
}
var bools = [ [true, true], [true, false], [false, true], [false, false] ]
for (bool in bools) {
System.print("a = %(bool[0]), b = %(bool[1]), op = && :")
a.call(bool[0]) && b.call(bool[1])
System.print()
}
for (bool in bools) {
System.print("a = %(bool[0]), b = %(bool[1]), op = || :")
a.call(bool[0]) || b.call(bool[1])
System.print()
}
|
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)
|
#Ruby
|
Ruby
|
require 'base64'
require 'net/smtp'
require 'tmail'
require 'mime/types'
class Email
def initialize(from, to, subject, body, options={})
@opts = {:attachments => [], :server => 'localhost'}.update(options)
@msg = TMail::Mail.new
@msg.from = from
@msg.to = to
@msg.subject = subject
@msg.cc = @opts[:cc] if @opts[:cc]
@msg.bcc = @opts[:bcc] if @opts[:bcc]
if @opts[:attachments].empty?
# just specify the body
@msg.body = body
else
# attach attachments, including the body
@msg.body = "This is a multi-part message in MIME format.\n"
msg_body = TMail::Mail.new
msg_body.body = body
msg_body.set_content_type("text","plain", {:charset => "ISO-8859-1"})
@msg.parts << msg_body
octet_stream = MIME::Types['application/octet-stream'].first
@opts[:attachments].select {|file| File.readable?(file)}.each do |file|
mime_type = MIME::Types.type_for(file).first || octet_stream
@msg.parts << create_attachment(file, mime_type)
end
end
end
attr_reader :msg
def create_attachment(file, mime_type)
attach = TMail::Mail.new
if mime_type.binary?
attach.body = Base64.encode64(File.read(file))
attach.transfer_encoding = 'base64'
else
attach.body = File.read(file)
end
attach.set_disposition("attachment", {:filename => file})
attach.set_content_type(mime_type.media_type, mime_type.sub_type, {:name=>file})
attach
end
# instance method to send an Email object
def send
args = @opts.values_at(:server, :port, :helo, :username, :password, :authtype)
Net::SMTP.start(*args) do |smtp|
smtp.send_message(@msg.to_s, @msg.from[0], @msg.to)
end
end
# class method to construct an Email object and send it
def self.send(*args)
self.new(*args).send
end
end
Email.send(
'[email protected]',
%w{ [email protected] [email protected] },
'the subject',
"the body\nhas lines",
{
:attachments => %w{ file1 file2 file3 },
:server => 'mail.example.com',
:helo => 'sender.invalid',
:username => 'user',
:password => 'secret'
}
)
|
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.
|
#Kotlin
|
Kotlin
|
// version 1.1.2
fun isSemiPrime(n: Int): Boolean {
var nf = 0
var nn = n
for (i in 2..nn)
while (nn % i == 0) {
if (nf == 2) return false
nf++
nn /= i
}
return nf == 2
}
fun main(args: Array<String>) {
for (v in 1675..1680)
println("$v ${if (isSemiPrime(v)) "is" else "isn't"} semi-prime")
}
|
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
|
#COBOL
|
COBOL
|
>>SOURCE FREE
IDENTIFICATION DIVISION.
PROGRAM-ID. sedol.
ENVIRONMENT DIVISION.
INPUT-OUTPUT SECTION.
FILE-CONTROL.
SELECT sedol-file ASSIGN "sedol.txt"
ORGANIZATION LINE SEQUENTIAL
FILE STATUS sedol-file-status.
DATA DIVISION.
FILE SECTION.
FD sedol-file.
01 sedol PIC X(6).
WORKING-STORAGE SECTION.
01 sedol-file-status PIC XX.
88 sedol-file-ok VALUE "00".
01 digit-num PIC 9 COMP.
01 digit-weights-area VALUE "1317391".
03 digit-weights PIC 9 OCCURS 7 TIMES.
01 weighted-sum-parts-area.
03 weighted-sum-parts PIC 9(3) COMP OCCURS 6 TIMES.
01 weighted-sum PIC 9(3) COMP.
01 check-digit PIC 9.
PROCEDURE DIVISION.
OPEN INPUT sedol-file
PERFORM UNTIL NOT sedol-file-ok
READ sedol-file
AT END
EXIT PERFORM
END-READ
MOVE FUNCTION UPPER-CASE(sedol) TO sedol
PERFORM VARYING digit-num FROM 1 BY 1 UNTIL digit-num > 6
EVALUATE TRUE
WHEN sedol (digit-num:1) IS ALPHABETIC-UPPER
IF sedol (digit-num:1) = "A" OR "E" OR "I" OR "O" OR "U"
DISPLAY "Invalid SEDOL: " sedol
EXIT PERFORM CYCLE
END-IF
COMPUTE weighted-sum-parts (digit-num) =
(FUNCTION ORD(sedol (digit-num:1)) - FUNCTION ORD("A")
+ 10) * digit-weights (digit-num)
WHEN sedol (digit-num:1) IS NUMERIC
MULTIPLY FUNCTION NUMVAL(sedol (digit-num:1))
BY digit-weights (digit-num)
GIVING weighted-sum-parts (digit-num)
WHEN OTHER
DISPLAY "Invalid SEDOL: " sedol
EXIT PERFORM CYCLE
END-EVALUATE
END-PERFORM
INITIALIZE weighted-sum
PERFORM VARYING digit-num FROM 1 BY 1 UNTIL digit-num > 6
ADD weighted-sum-parts (digit-num) TO weighted-sum
END-PERFORM
COMPUTE check-digit =
FUNCTION MOD(10 - FUNCTION MOD(weighted-sum, 10), 10)
DISPLAY sedol check-digit
END-PERFORM
CLOSE sedol-file
.
END PROGRAM sedol.
|
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
|
#K
|
K
|
sdn: {n~+/'n=/:!#n:0$'$x}'
sdn 1210 2020 2121 21200 3211000 42101000
1 1 0 1 1 1
&sdn@!:1e6
1210 2020 21200
|
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
|
#Kotlin
|
Kotlin
|
// version 1.0.6
fun selfDescribing(n: Int): Boolean {
if (n <= 0) return false
val ns = n.toString()
val count = IntArray(10)
var nn = n
while (nn > 0) {
count[nn % 10] += 1
nn /= 10
}
for (i in 0 until ns.length)
if( ns[i] - '0' != count[i]) return false
return true
}
fun main(args: Array<String>) {
println("The self-describing numbers less than 100 million are:")
for (i in 0..99999999) if (selfDescribing(i)) print("$i ")
println()
}
|
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
|
#Lambdatalk
|
Lambdatalk
|
{def prime
{def prime.rec
{lambda {:m :n}
{if {> {* :m :m} :n}
then :n
else {if {= {% :n :m} 0}
then
else {prime.rec {+ :m 1} :n} }}}}
{lambda {:n}
{prime.rec 2 :n} }}
{map prime {serie 3 100 2}}
-> 3 5 7 11 13 17 19 23 29 31 37 41 43 47 53 59 61 67 71 73 79 83 89 97
{map prime {serie 9901 10000 2}}
-> 9901 9907 9923 9929 9931 9941 9949 9967 9973
|
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.
|
#Fortran
|
Fortran
|
PROGRAM NONSQUARES
IMPLICIT NONE
INTEGER :: m, n, nonsqr
DO n = 1, 22
nonsqr = n + FLOOR(0.5 + SQRT(REAL(n))) ! or could use NINT(SQRT(REAL(n)))
WRITE(*,*) nonsqr
END DO
DO n = 1, 1000000
nonsqr = n + FLOOR(0.5 + SQRT(REAL(n)))
m = INT(SQRT(REAL(nonsqr)))
IF (m*m == nonsqr) THEN
WRITE(*,*) "Square found, n=", n
END IF
END DO
END PROGRAM NONSQUARES
|
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
|
#F.23
|
F#
|
[<EntryPoint>]
let main args =
// Create some sets (of int):
let s1 = Set.ofList [1;2;3;4;3]
let s2 = Set.ofArray [|3;4;5;6|]
printfn "Some sets (of int):"
printfn "s1 = %A" s1
printfn "s2 = %A" s2
printfn "Set operations:"
printfn "2 ∈ s1? %A" (s1.Contains 2)
printfn "10 ∈ s1? %A" (s1.Contains 10)
printfn "s1 ∪ s2 = %A" (Set.union s1 s2)
printfn "s1 ∩ s2 = %A" (Set.intersect s1 s2)
printfn "s1 ∖ s2 = %A" (Set.difference s1 s2)
printfn "s1 ⊆ s2? %A" (Set.isSubset s1 s1)
printfn "{3, 1} ⊆ s1? %A" (Set.isSubset (Set.ofList [3;1]) s1)
printfn "{3, 2, 4, 1} = s1? %A" ((Set.ofList [3;2;4;1]) = s1)
printfn "s1 = s2? %A" (s1 = s2)
printfn "More set operations:"
printfn "#s1 = %A" s1.Count
printfn "s1 ∪ {99} = %A" (s1.Add 99)
printfn "s1 ∖ {3} = %A" (s1.Remove 3)
printfn "s1 ⊂ s1? %A" (Set.isProperSubset s1 s1)
printfn "s1 ⊂ s2? %A" (Set.isProperSubset s1 s2)
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
|
#Befunge
|
Befunge
|
2>:3g" "-!v\ g30 <
|!`"O":+1_:.:03p>03g+:"O"`|
@ ^ p3\" ":<
2 234567890123456789012345678901234567890123456789012345678901234567890123456789
|
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
|
#zkl
|
zkl
|
fcn consolidate(sets){ // set are munged if they are read/write
if(sets.len()<2) return(sets);
r,r0 := List(List()),sets[0];
foreach x in (consolidate(sets[1,*])){
i,ni:=x.filter22(r0.holds); //-->(intersection, !intersection)
if(i) r0=r0.extend(ni);
else r.append(x);
}
r[0]=r0;
r
}
|
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
|
#Raku
|
Raku
|
sub glyph ($_) {
when * < 33 { (0x2400 + $_).chr } # display symbol names for invisible glyphs
when 127 { '␡' }
default { .chr }
}
say '{|class="wikitable" style="text-align:center;background-color:hsl(39, 90%, 95%)"';
for (^128).rotor(16) -> @row {
say '|-';
printf(q[|%d<br>0x%02X<br><big><big title="%s">%s</big></big>] ~ "\n",
$_, $_, .&glyph.uniname.subst('SYMBOL FOR ', ''),
.&glyph.subst('|', '<nowiki>|</nowiki>')) for @row;
}
say '|}';
|
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
|
#Unlambda
|
Unlambda
|
```ci``s``s`ks``s`k`s``s`kc``s``s``si`kr`k. `k.*k
`k``s``s``s``s`s`k`s``s`ksk`k``s``si`kk`k``s`kkk
`k``s`k`s``si`kk``s`kk``s``s``s``si`kk`k`s`k`s``s`ksk`k`s`k`s`k`si``si`k`ki
`k``s`k`s``si`k`ki``s`kk``s``s``s``si`kk`k`s`k`s`k`si`k`s`k`s``s`ksk``si`k`ki
`k`ki``s`k`s`k`si``s`kkk
|
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
|
#R
|
R
|
## Are x,y inside Sierpinski carpet (and where)? (1-yes, 0-no)
inSC <- function(x, y) {
while(TRUE) {
if(!x||!y) {return(1)}
if(x%%3==1&&y%%3==1) {return(0)}
x=x%/%3; y=y%/%3;
} return(0);
}
## Plotting Sierpinski carpet fractal. aev 4/1/17
## ord - order, fn - file name, ttl - plot title, clr - color
pSierpinskiC <- function(ord, fn="", ttl="", clr="navy") {
m=640; abbr="SCR"; dftt="Sierpinski carpet fractal";
n=3^ord-1; M <- matrix(c(0), ncol=n, nrow=n, byrow=TRUE);
cat(" *** START", abbr, date(), "\n");
if(fn=="") {pf=paste0(abbr,"o", ord)} else {pf=paste0(fn, ".png")};
if(ttl!="") {dftt=ttl}; ttl=paste0(dftt,", order ", ord);
cat(" *** Plot file:", pf,".png", "title:", ttl, "\n");
for(i in 0:n) {
for(j in 0:n) {if(inSC(i,j)) {M[i,j]=1}
}}
plotmat(M, pf, clr, ttl);
cat(" *** END", abbr, date(), "\n");
}
## Executing:
pSierpinskiC(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
|
#Groovy
|
Groovy
|
def semordnilapWords(source) {
def words = [] as Set
def semordnilaps = []
source.eachLine { word ->
if (words.contains(word.reverse())) semordnilaps << word
words << word
}
semordnilaps
}
|
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.
|
#zkl
|
zkl
|
fcn a(b){self.fcn.println(b); b}
fcn b(b){self.fcn.println(b); 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)
|
#SAS
|
SAS
|
filename msg email
to="[email protected]"
cc="[email protected]"
subject="Important message"
;
data _null_;
file msg;
put "Hello, Connected World!";
run;
|
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)
|
#Scala
|
Scala
|
import java.util.Properties
import javax.mail.internet.{ InternetAddress, MimeMessage }
import javax.mail.Message.RecipientType
import javax.mail.{ Session, Transport }
/** Mail constructor.
* @constructor Mail
* @param host Host
*/
class Mail(host: String) {
val session = Session.getDefaultInstance(new Properties() { put("mail.smtp.host", host) })
/** Send email message.
*
* @param from From
* @param tos Recipients
* @param ccs CC Recipients
* @param subject Subject
* @param text Text
* @throws MessagingException
*/
def send(from: String, tos: List[String], ccs: List[String], subject: String, text: String) {
val message = new MimeMessage(session)
message.setFrom(new InternetAddress(from))
for (to <- tos)
message.addRecipient(RecipientType.TO, new InternetAddress(to))
for (cc <- ccs)
message.addRecipient(RecipientType.TO, new InternetAddress(cc))
message.setSubject(subject)
message.setText(text)
Transport.send(message)
}
}
|
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.
|
#Ksh
|
Ksh
|
#!/bin/ksh
# Semiprime - As translated from C
# # Variables:
#
# # Functions:
#
# Function _issemiprime(p2) - return 1 if p2 semiprime, 0 if not
#
function _issemiprime {
typeset _p2 ; integer _p2=$1
typeset _p _f ; integer _p _f=0
for ((_p=2; (_f<2 && _p*_p<=_p2); _p++)); do
while (( _p2 % _p == 0 )); do
(( _p2 /= _p ))
(( _f++ ))
done
done
return $(( _f + (_p2 > 1) == 2 ))
}
######
# main #
######
integer i
for ((i=2; i<100; i++)); do
_issemiprime ${i}
(( $? )) && printf " %d" ${i}
done
echo
|
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.
|
#Lingo
|
Lingo
|
on isSemiPrime (n)
div = 2
cnt = 0
repeat while cnt < 3 and n <> 1
if n mod div = 0 then
n = n / div
cnt = cnt + 1
else
div = div + 1
end if
end repeat
return cnt=2
end
|
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
|
#Common_Lisp
|
Common Lisp
|
(defun append-sedol-check-digit (sedol &key (start 0) (end (+ start 6)))
(assert (<= 0 start end (length sedol)))
(assert (= (- end start) 6))
(loop
:with checksum = 0
:for weight :in '(1 3 1 7 3 9)
:for index :upfrom start
:do (incf checksum (* weight (digit-char-p (char sedol index) 36)))
:finally (let* ((posn (- 10 (mod checksum 10)))
(head (subseq sedol start end))
(tail (digit-char posn)))
(return (concatenate 'string head (list tail))))))
|
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
|
#Liberty_BASIC
|
Liberty BASIC
|
'adapted from BASIC solution
FOR x = 1 TO 5000000
a$ = TRIM$(STR$(x))
b = LEN(a$)
FOR c = 1 TO b
d$ = MID$(a$, c, 1)
v(VAL(d$)) = v(VAL(d$)) + 1
w(c - 1) = VAL(d$)
NEXT c
r = 0
FOR n = 0 TO 10
IF v(n) = w(n) THEN r = r + 1
v(n) = 0
w(n) = 0
NEXT n
IF r = 11 THEN PRINT x; " is a self-describing number"
NEXT x
PRINT
PRINT "End"
|
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
|
#Liberty_BASIC
|
Liberty BASIC
|
print "Rosetta Code - Sequence of primes by trial division"
print: print "Prime numbers between 1 and 50"
for x=1 to 50
if isPrime(x) then print x
next x
[start]
input "Enter an integer: "; x
if x=0 then print "Program complete.": end
if isPrime(x) then print x; " is prime" else print x; " is not prime"
goto [start]
function isPrime(p)
p=int(abs(p))
if p=2 or then isPrime=1: exit function 'prime
if p=0 or p=1 or (p mod 2)=0 then exit function 'not prime
for i=3 to sqr(p) step 2
if (p mod i)=0 then exit function 'not prime
next i
isPrime=1
end function
|
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
|
#Lua
|
Lua
|
-- Returns true if x is prime, and false otherwise
function isprime (x)
if x < 2 then return false end
if x < 4 then return true end
if x % 2 == 0 then return false end
for d = 3, math.sqrt(x), 2 do
if x % d == 0 then return false end
end
return true
end
-- Returns table of prime numbers (from lo, if specified) up to hi
function primes (lo, hi)
local t = {}
if not hi then
hi = lo
lo = 2
end
for n = lo, hi do
if isprime(n) then table.insert(t, n) end
end
return t
end
-- Show all the values of a table in one line
function show (x)
for _, v in pairs(x) do io.write(v .. " ") end
print()
end
-- Main procedure
show(primes(100))
show(primes(50, 150))
|
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.
|
#FreeBASIC
|
FreeBASIC
|
' FB 1.05.0 Win64
Function nonSquare (n As UInteger) As UInteger
Return CUInt(n + Int(0.5 + Sqr(n)))
End Function
Function isSquare (n As UInteger) As Boolean
Dim As UInteger r = CUInt(Sqr(n))
Return n = r * r
End Function
Print "The first 22 numbers generated by the sequence are :"
For i As Integer = 1 To 22
Print nonSquare(i); " ";
Next
Print : Print
' Test numbers generated for n less than a million to see if they're squares
For i As UInteger = 1 To 999999
If isSquare(nonSquare(i)) Then
Print "The number generated by the sequence for n ="; i; " is square!"
Goto finish
End If
Next
Print "None of the numbers generated by the sequence for n < 1000000 are square"
finish:
Print
Print "Press any key to quit"
Sleep
|
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
|
#Factor
|
Factor
|
( scratchpad ) USE: sets
( scratchpad ) HS{ 2 5 4 3 } HS{ 5 6 7 } union .
HS{ 2 3 4 5 6 7 }
( scratchpad ) HS{ 2 5 4 3 } HS{ 5 6 7 } intersect .
HS{ 5 }
( scratchpad ) HS{ 2 5 4 3 } HS{ 5 6 7 } diff .
HS{ 2 3 4 }
( scratchpad ) HS{ 2 5 4 3 } HS{ 5 6 7 } subset? .
f
( scratchpad ) HS{ 5 6 } HS{ 5 6 7 } subset? .
t
( scratchpad ) HS{ 5 6 } HS{ 5 6 7 } set= .
f
( scratchpad ) HS{ 6 5 7 } HS{ 5 6 7 } set= .
t
|
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
|
#BQN
|
BQN
|
Primes ← {
𝕩≤2 ? ↕0 ; # No primes below 2
p ← 𝕊⌈√n←𝕩 # Initial primes by recursion
b ← 2≤↕n # Initial sieve: no 0 or 1
E ← {↕∘⌈⌾((𝕩×𝕩+⊢)⁼)n} # Multiples of 𝕩 under n, starting at 𝕩×𝕩
/ b E⊸{0¨⌾(𝕨⊸⊏)𝕩}´ p # Cross them out
}
|
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
|
#Red
|
Red
|
Red ["ASCII table"]
repeat i 16 [
repeat j 6 [
n: j - 1 * 16 + i + 31
prin append pad/left n 3 ": "
prin pad switch/default n [
32 ["spc"]
127 ["del"]
] [to-char n] 4
]
prin newline
]
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.