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/Sequence:_smallest_number_greater_than_previous_term_with_exactly_n_divisors
|
Sequence: smallest number greater than previous term with exactly n divisors
|
Calculate the sequence where each term an is the smallest natural number greater than the previous term, that has exactly n divisors.
Task
Show here, on this page, at least the first 15 terms of the sequence.
See also
OEIS:A069654
Related tasks
Sequence: smallest number with exactly n divisors
Sequence: nth number with exactly n divisors
|
#Polyglot:PL.2FI_and_PL.2FM
|
Polyglot:PL/I and PL/M
|
/* FIND THE SMALLEST NUMBER > THE PREVIOUS ONE WITH EXACTLY N DIVISORS */
sequence_100H: procedure options (main);
/* PROGRAM-SPECIFIC %REPLACE STATEMENTS MUST APPEAR BEFORE THE %INCLUDE AS */
/* E.G. THE CP/M PL/I COMPILER DOESN'T LIKE THEM TO FOLLOW PROCEDURES */
/* PL/I */
%replace maxnumber by 15;
/* PL/M */ /*
DECLARE MAXNUMBER LITERALLY '15';
/* */
/* PL/I DEFINITIONS */
%include 'pg.inc';
/* PL/M DEFINITIONS: CP/M BDOS SYSTEM CALL AND CONSOLE I/O ROUTINES, ETC. */ /*
DECLARE BINARY LITERALLY 'ADDRESS', CHARACTER LITERALLY 'BYTE';
DECLARE FIXED LITERALLY ' ', BIT LITERALLY 'BYTE';
DECLARE STATIC LITERALLY ' ', RETURNS LITERALLY ' ';
DECLARE FALSE LITERALLY '0', TRUE LITERALLY '1';
DECLARE HBOUND LITERALLY 'LAST', SADDR LITERALLY '.';
BDOSF: PROCEDURE( FN, ARG )BYTE;
DECLARE FN BYTE, ARG ADDRESS; GOTO 5; END;
BDOS: PROCEDURE( FN, ARG ); DECLARE FN BYTE, ARG ADDRESS; GOTO 5; END;
PRCHAR: PROCEDURE( C ); DECLARE C BYTE; CALL BDOS( 2, C ); END;
PRSTRING: PROCEDURE( S ); DECLARE S ADDRESS; CALL BDOS( 9, S ); END;
PRNL: PROCEDURE; CALL PRCHAR( 0DH ); CALL PRCHAR( 0AH ); END;
PRNUMBER: PROCEDURE( N );
DECLARE N ADDRESS;
DECLARE V ADDRESS, N$STR( 6 ) BYTE, W BYTE;
N$STR( W := LAST( N$STR ) ) = '$';
N$STR( W := W - 1 ) = '0' + ( ( V := N ) MOD 10 );
DO WHILE( ( V := V / 10 ) > 0 );
N$STR( W := W - 1 ) = '0' + ( V MOD 10 );
END;
CALL BDOS( 9, .N$STR( W ) );
END PRNUMBER;
MODF: PROCEDURE( A, B )ADDRESS;
DECLARE ( A, B )ADDRESS;
RETURN( A MOD B );
END MODF;
MIN: PROCEDURE( A, B ) ADDRESS;
DECLARE ( A, B ) ADDRESS;
IF A < B THEN RETURN( A ); ELSE RETURN( B );
END MIN;
/* END LANGUAGE DEFINITIONS */
/* TASK */
COUNTDIVISORS: PROCEDURE( N )RETURNS /* THE DIVISOR COUNT OF N */ (
FIXED BINARY )
;
DECLARE N FIXED BINARY;
DECLARE ( I, I2, COUNT ) FIXED BINARY;
COUNT = 0;
I = 1;
I2 = 1;
DO WHILE( I2 < N );
IF MODF( N, I ) = 0 THEN COUNT = COUNT + 2;
I = I + 1;
I2 = I * I;
END;
IF I2 = N THEN RETURN ( COUNT + 1 ); ELSE RETURN ( COUNT );
END COUNTDIVISORS ;
DECLARE ( I, NEXT ) FIXED BINARY;
CALL PRSTRING( SADDR( 'THE FIRST $' ) );
CALL PRNUMBER( MAXNUMBER );
CALL PRSTRING( SADDR( ' TERMS OF THE SEQUENCE ARE:$' ) );
NEXT = 1;
I = 1;
DO WHILE( NEXT <= MAXNUMBER );
IF NEXT = COUNTDIVISORS( I ) THEN DO;
CALL PRCHAR( ' ' );
CALL PRNUMBER( I );
NEXT = NEXT + 1;
END;
I = I + 1;
END;
EOF: end sequence_100H;
|
http://rosettacode.org/wiki/SHA-1
|
SHA-1
|
SHA-1 or SHA1 is a one-way hash function;
it computes a 160-bit message digest.
SHA-1 often appears in security protocols; for example,
many HTTPS websites use RSA with SHA-1 to secure their connections.
BitTorrent uses SHA-1 to verify downloads.
Git and Mercurial use SHA-1 digests to identify commits.
A US government standard, FIPS 180-1, defines SHA-1.
Find the SHA-1 message digest for a string of octets. You may either call a SHA-1 library, or implement SHA-1 in your language. Both approaches interest Rosetta Code.
Warning: SHA-1 has known weaknesses. Theoretical attacks may find a collision after 252 operations, or perhaps fewer.
This is much faster than a brute force attack of 280 operations. USgovernment deprecated SHA-1.
For production-grade cryptography, users may consider a stronger alternative, such as SHA-256 (from the SHA-2 family) or the upcoming SHA-3.
|
#Perl
|
Perl
|
use Digest::SHA qw(sha1_hex);
print sha1_hex('Rosetta Code'), "\n";
|
http://rosettacode.org/wiki/SHA-1
|
SHA-1
|
SHA-1 or SHA1 is a one-way hash function;
it computes a 160-bit message digest.
SHA-1 often appears in security protocols; for example,
many HTTPS websites use RSA with SHA-1 to secure their connections.
BitTorrent uses SHA-1 to verify downloads.
Git and Mercurial use SHA-1 digests to identify commits.
A US government standard, FIPS 180-1, defines SHA-1.
Find the SHA-1 message digest for a string of octets. You may either call a SHA-1 library, or implement SHA-1 in your language. Both approaches interest Rosetta Code.
Warning: SHA-1 has known weaknesses. Theoretical attacks may find a collision after 252 operations, or perhaps fewer.
This is much faster than a brute force attack of 280 operations. USgovernment deprecated SHA-1.
For production-grade cryptography, users may consider a stronger alternative, such as SHA-256 (from the SHA-2 family) or the upcoming SHA-3.
|
#Phix
|
Phix
|
--
-- demo\rosetta\sha1.exw
-- =====================
--
-- NB no longer considered secure. Non-optimised.
--
function uint32(atom v)
return and_bitsu(v,#FFFFFFFF)
end function
function sq_uint32(sequence s)
for i=1 to length(s) do
s[i] = uint32(s[i])
end for
return s
end function
function dword(string msg, integer i)
-- get dword as big-endian
return msg[i]*#1000000+msg[i+1]*#10000+msg[i+2]*#100+msg[i+3]
end function
function xor_all(sequence s)
atom result = 0
for i=1 to length(s) do
result = xor_bits(result, s[i])
end for
result = uint32(result)
return result
end function
function rol(atom word, integer bits)
-- left rotate the bits of a 32-bit number by the specified number of bits
return uint32(word*power(2,bits))+floor(word/power(2,32-bits))
end function
function sha1(string msg)
atom a,b,c,d,e,temp,k
sequence w = repeat(0,80)
atom h0 = 0x67452301,
h1 = 0xefcdab89,
h2 = 0x98badcfe,
h3 = 0x10325476,
h4 = 0xc3d2e1f0
integer bits = length(msg)*8
msg &= #80
while mod(length(msg),64)!=56 do msg &= '\0' end while
msg &= reverse(int_to_bytes(bits,8))
for chunk=1 to length(msg) by 64 do
for i=1 to 16 do
w[i] = dword(msg,chunk+(i-1)*4)
end for
for i=17 to 80 do
w[i] = rol(xor_all({w[i-3],w[i-8],w[i-14],w[i-16]}),1)
end for
{a,b,c,d,e} = {h0,h1,h2,h3,h4}
for i=1 to 80 do
if i<=20 then
temp = or_bits(and_bits(b,c),and_bits(not_bits(b),d))
k = #5A827999
elsif i<=40 then
temp = xor_bits(xor_bits(b,c),d)
k = #6ED9EBA1
elsif i<=60 then
temp = or_bits(or_bits(and_bits(b,c),and_bits(b,d)),and_bits(c,d))
k = #8F1BBCDC
else -- i<=80
temp = xor_bits(xor_bits(b,c),d)
k = #CA62C1D6
end if
{a,b,c,d,e} = {uint32(rol(a,5)+temp+e+k+w[i]),a,rol(b,30),c,d}
end for
{h0,h1,h2,h3,h4} = sq_uint32(sq_add({h0,h1,h2,h3,h4},{a,b,c,d,e}))
end for
sequence res = {h0, h1, h2, h3, h4}
for i=1 to length(res) do
res[i] = sprintf("%08X",res[i])
end for
return join(res)
end function
?sha1("Rosetta Code")
|
http://rosettacode.org/wiki/Seven-sided_dice_from_five-sided_dice
|
Seven-sided dice from five-sided dice
|
Task
(Given an equal-probability generator of one of the integers 1 to 5
as dice5), create dice7 that generates a pseudo-random integer from
1 to 7 in equal probability using only dice5 as a source of random
numbers, and check the distribution for at least one million calls using the function created in Simple Random Distribution Checker.
Implementation suggestion:
dice7 might call dice5 twice, re-call if four of the 25
combinations are given, otherwise split the other 21 combinations
into 7 groups of three, and return the group index from the rolls.
(Task adapted from an answer here)
|
#Wren
|
Wren
|
import "random" for Random
import "/sort" for Sort
import "/fmt" for Fmt
var r = Random.new()
var dice5 = Fn.new { r.int(1, 6) }
var dice7 = Fn.new {
while (true) {
var t = (dice5.call() - 1) * 5 + dice5.call() - 1
if (t < 21) return 1 + (t/3).floor
}
}
var checkDist = Fn.new { |gen, nRepeats, tolerance|
var occurs = {}
for (i in 1..nRepeats) {
var d = gen.call()
occurs[d] = occurs.containsKey(d) ? occurs[d] + 1 : 1
}
var expected = (nRepeats/occurs.count).floor
var maxError = (expected * tolerance / 100).floor
System.print("Repetitions = %(nRepeats), Expected = %(expected)")
System.print("Tolerance = %(tolerance)\%, Max Error = %(maxError)\n")
System.print("Integer Occurrences Error Acceptable")
var f = " $d $5d $5d $s"
var allAcceptable = true
var cmp = Fn.new { |me1, me2| (me1.key - me2.key).sign }
occurs = occurs.toList
Sort.insertion(occurs, cmp)
for (me in occurs) {
var k = me.key
var v = me.value
var error = (v - expected).abs
var acceptable = (error <= maxError) ? "Yes" : "No"
if (acceptable == "No") allAcceptable = false
Fmt.print(f, k, v, error, acceptable)
}
System.print("\nAcceptable overall: %(allAcceptable ? "Yes" : "No")")
}
checkDist.call(dice7, 1400000, 0.5)
|
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
|
#Julia
|
Julia
|
for i in 32:127
c= i== 0 ? "NUL" : i== 7 ? "BEL" : i== 8 ? "BKS" : i== 9 ? "TAB" :
i==10 ? "LF " : i==13 ? "CR " : i==27 ? "ESC" : i==155 ? "CSI" : "|$(Char(i))|"
print("$(lpad(i,3)) $(string(i,base=16,pad=2)) $c")
(i&7)==7 ? println() : print(" ")
end
|
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
|
#Processing
|
Processing
|
void setup() {
size(410, 230);
background(255);
fill(0);
sTriangle (10, 25, 100, 5);
}
void sTriangle(int x, int y, int l, int n) {
if( n == 0) text("*", x, y);
else {
sTriangle(x, y+l, l/2, n-1);
sTriangle(x+l, y, l/2, n-1);
sTriangle(x+l*2, y+l, l/2, n-1);
}
}
|
http://rosettacode.org/wiki/Sierpinski_carpet
|
Sierpinski carpet
|
Task
Produce a graphical or ASCII-art representation of a Sierpinski carpet of order N.
For example, the Sierpinski carpet of order 3 should look like this:
###########################
# ## ## ## ## ## ## ## ## #
###########################
### ###### ###### ###
# # # ## # # ## # # #
### ###### ###### ###
###########################
# ## ## ## ## ## ## ## ## #
###########################
######### #########
# ## ## # # ## ## #
######### #########
### ### ### ###
# # # # # # # #
### ### ### ###
######### #########
# ## ## # # ## ## #
######### #########
###########################
# ## ## ## ## ## ## ## ## #
###########################
### ###### ###### ###
# # # ## # # ## # # #
### ###### ###### ###
###########################
# ## ## ## ## ## ## ## ## #
###########################
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
|
#Objeck
|
Objeck
|
class SierpinskiCarpet {
function : Main(args : String[]) ~ Nil {
Carpet(3);
}
function : InCarpet(x : Int, y : Int) ~ Bool {
while(x<>0 & y<>0) {
if(x % 3 = 1 & y % 3 = 1) {
return false;
};
x /= 3;
y /= 3;
};
return true;
}
function : Carpet(n : Int) ~ Nil {
power := 3.0->Power(n->As(Float));
for(i := 0; i < power; i+=1;) {
for(j := 0; j < power; j+=1;) {
c := InCarpet(i, j) ? '*' : ' ';
c->Print();
};
IO.Console->PrintLine();
};
}
}
|
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
|
#11l
|
11l
|
V wordset = Set(File(‘unixdict.txt’).read().split("\n"))
V revlist = wordset.map(word -> reversed(word))
V pairs = Set(zip(wordset, revlist).filter((wrd, rev) -> wrd < rev & rev C :wordset))
print(pairs.len)
print(sorted(Array(pairs), key' p -> (p[0].len, p))[(len)-5..])
|
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.
|
#Phix
|
Phix
|
with javascript_semantics
function a(integer i)
printf(1,"a ")
return i
end function
function b(integer i)
printf(1,"b ")
return i
end function
for z=0 to 1 do
for i=0 to 1 do
for j=0 to 1 do
if z then
printf(1,"a(%d) and b(%d) ",{i,j})
printf(1," => %d\n",a(i) and b(j))
else
printf(1,"a(%d) or b(%d) ",{i,j})
printf(1," => %d\n",a(i) or b(j))
end if
end for
end for
end for
|
http://rosettacode.org/wiki/Selectively_replace_multiple_instances_of_a_character_within_a_string
|
Selectively replace multiple instances of a character within a string
|
Task
This is admittedly a trivial task but I thought it would be interesting to see how succinctly (or otherwise) different languages can handle it.
Given the string: "abracadabra", replace programatically:
the first 'a' with 'A'
the second 'a' with 'B'
the fourth 'a' with 'C'
the fifth 'a' with 'D'
the first 'b' with 'E'
the second 'r' with 'F'
Note that there is no replacement for the third 'a', second 'b' or first 'r'.
The answer should, of course, be : "AErBcadCbFD".
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
|
#C.2B.2B
|
C++
|
#include <map>
#include <iostream>
#include <string>
int main()
{
std::map<char, std::string> rep =
{{'a', "DCaBA"}, // replacement string is reversed
{'b', "E"},
{'r', "Fr"}};
std::string magic = "abracadabra";
for(auto it = magic.begin(); it != magic.end(); ++it)
{
if(auto f = rep.find(*it); f != rep.end() && !f->second.empty())
{
*it = f->second.back();
f->second.pop_back();
}
}
std::cout << magic << "\n";
}
|
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)
|
#Clojure
|
Clojure
|
(require '[postal.core :refer [send-message]])
(send-message {:host "smtp.gmail.com"
:ssl true
:user your_username
:pass your_password}
{:from "[email protected]"
:to ["[email protected]"]
:cc ["[email protected]" "[email protected]"]
:subject "Yo"
:body "Testing."})
|
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)
|
#D
|
D
|
void main() {
import std.net.curl;
auto s = SMTP("smtps://smtp.gmail.com");
s.setAuthentication("[email protected]", "somepassword");
s.mailTo = ["<[email protected]>"];
s.mailFrom = "<[email protected]>";
s.message = "Subject:test\n\nExample Message";
s.perform;
}
|
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.
|
#Ada
|
Ada
|
with Prime_Numbers, Ada.Text_IO;
procedure Test_Semiprime is
package Integer_Numbers is new
Prime_Numbers (Natural, 0, 1, 2);
use Integer_Numbers;
begin
for N in 1 .. 100 loop
if Decompose(N)'Length = 2 then -- N is a semiprime;
Ada.Text_IO.Put(Integer'Image(Integer(N)));
end if;
end loop;
Ada.Text_IO.New_Line;
for N in 1675 .. 1680 loop
if Decompose(N)'Length = 2 then -- N is a semiprime;
Ada.Text_IO.Put(Integer'Image(Integer(N)));
end if;
end loop;
end Test_Semiprime;
|
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.
|
#Elena
|
Elena
|
import extensions;
extension setOp
{
union(func)
= (val => self(val) || func(val) );
intersection(func)
= (val => self(val) && func(val) );
difference(func)
= (val => self(val) && (func(val)).Inverted );
}
public program()
{
// union
var set := (x => x >= 0.0r && x <= 1.0r ).union:(x => x >= 0.0r && x < 2.0r );
set(0.0r).assertTrue();
set(1.0r).assertTrue();
set(2.0r).assertFalse();
// intersection
var set2 := (x => x >= 0.0r && x < 2.0r ).intersection:(x => x >= 1.0r && x <= 2.0r );
set2(0.0r).assertFalse();
set2(1.0r).assertTrue();
set2(2.0r).assertFalse();
// difference
var set3 := (x => x >= 0.0r && x < 3.0r ).difference:(x => x >= 0.0r && x <= 1.0r );
set3(0.0r).assertFalse();
set3(1.0r).assertFalse();
set3(2.0r).assertTrue();
}
|
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.
|
#F.23
|
F#
|
open System
let union s1 s2 =
fun x -> (s1 x) || (s2 x);
let difference s1 s2 =
fun x -> (s1 x) && not (s2 x)
let intersection s1 s2 =
fun x -> (s1 x) && (s2 x)
[<EntryPoint>]
let main _ =
//test set union
let u1 = union (fun x -> 0.0 < x && x <= 1.0) (fun x -> 0.0 <= x && x < 2.0)
assert (u1 0.0)
assert (u1 1.0)
assert (not (u1 2.0))
//test set difference
let d1 = difference (fun x -> 0.0 <= x && x < 3.0) (fun x -> 0.0 < x && x < 1.0)
assert (d1 0.0)
assert (not (d1 0.5))
assert (d1 1.0)
assert (d1 2.0)
let d2 = difference (fun x -> 0.0 <= x && x < 3.0) (fun x -> 0.0 <= x && x <= 1.0)
assert (not (d2 0.0))
assert (not (d2 1.0))
assert (d2 2.0)
let d3 = difference (fun x -> 0.0 <= x && x <= Double.PositiveInfinity) (fun x -> 1.0 <= x && x <= 2.0)
assert (d3 0.0)
assert (not (d3 1.5))
assert (d3 3.0)
//test set intersection
let i1 = intersection (fun x -> 0.0 <= x && x < 2.0) (fun x -> 1.0 < x && x <= 2.0)
assert (not (i1 0.0))
assert (not (i1 1.0))
assert (not (i1 2.0))
0 // return an integer exit code
|
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
|
#ALGOL_W
|
ALGOL W
|
begin
% use the isPrime procedure from the Primality by Trial Division task %
logical procedure isPrime ( integer value n ) ; algol "isPrime" ;
% sets the elements of p to the first n primes. p must have bounds 1 :: n %
procedure getPrimes ( integer array p ( * )
; integer value n
) ;
if n > 0 then begin
% have room for at least oe prime %
integer pPos, possiblePrime;
p( 1 ) := 2;
pPos := 2;
possiblePrime := 3;
while pPos <= n do begin
if isPrime( possiblePrime ) then begin
p( pPos ) := possiblePrime;
pPos := pPos + 1;
end;
possiblePrime := possiblePrime + 1
end
end getPrimes ;
begin % test getPrimes %
integer array p( 1 :: 100 );
getPrimes( p, 100 );
for i := 1 until 100 do begin
if i rem 20 = 1 then write( i_w := 4, s_w := 1, p( i ) )
else writeon( i_w := 4, s_w := 1, p( i ) )
end for_i
end
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
|
#ALGOL-M
|
ALGOL-M
|
BEGIN
INTEGER I, K, M, N, S, NPRIMES, DIVISIBLE, FALSE, TRUE;
COMMENT COMPUTE P MOD Q;
INTEGER FUNCTION MOD (P, Q);
INTEGER P, Q;
BEGIN
MOD := P - Q * (P / Q);
END;
COMMENT MAIN PROGRAM BEGINS HERE;
WRITE ("HOW MANY PRIMES DO YOU WANT TO GENERATE?");
READ (NPRIMES);
BEGIN
INTEGER ARRAY P[1:NPRIMES];
FALSE := 0;
TRUE := -1;
% INITIALIZE P WITH FIRST (AND ONLY EVEN) PRIME NUMBER %
P[1] := 2;
WRITE (1, ":", P[1]);
I := 1; % COUNT OF PRIME NUMBERS FOUND SO FAR %
K := 1; % INDEX OF LARGEST PRIME <= SQRT OF N %
N := 3; % CURRENT NUMBER BEING CHECKED %
WHILE I < NPRIMES DO
BEGIN
S := P[K] * P[K];
IF S <= N THEN K := K + 1;
DIVISIBLE := FALSE;
M := 2; % INDEX OF POSSIBLE DIVISORS (EXCLUDING 2) %
WHILE M <= K AND DIVISIBLE = FALSE DO
BEGIN
IF MOD(N, P[M]) = 0 THEN DIVISIBLE := TRUE;
M := M + 1;
END;
IF DIVISIBLE = FALSE THEN
BEGIN
I := I + 1;
P[I] := N;
WRITE (I, ":", N);
END;
N := N + 2;
END;
END;
END
|
http://rosettacode.org/wiki/Sequence_of_non-squares
|
Sequence of non-squares
|
Task
Show that the following remarkable formula gives the sequence of non-square natural numbers:
n + floor(1/2 + sqrt(n))
Print out the values for n in the range 1 to 22
Show that no squares occur for n less than one million
This is sequence A000037 in the OEIS database.
|
#APL
|
APL
|
NONSQUARE←{(⍳⍵)+⌊0.5+(⍳⍵)*0.5}
NONSQUARE 22
2 3 5 6 7 8 10 11 12 13 14 15 17 18 19 20 21 22 23 24 26 27
|
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.
|
#AppleScript
|
AppleScript
|
on task()
set values to {}
set squareCount to 0
repeat with n from 1 to (1000000 - 1)
set v to n + (0.5 + n ^ 0.5) div 1
if (n ≤ 22) then set end of values to v
set sqrt to v ^ 0.5
if (sqrt = sqrt as integer) then set squareCount to squareCount + 1
end repeat
return "Values (n = 1 to 22): " & join(values, ", ") & (linefeed & ¬
"Number of squares (n < 1000000): " & squareCount)
end task
on join(lst, delim)
set astid to AppleScript's text item delimiters
set AppleScript's text item delimiters to delim
set txt to lst as text
set AppleScript's text item delimiters to astid
return txt
end join
task()
|
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
|
#Apex
|
Apex
|
public class MySetController{
public Set<String> strSet {get; private set; }
public Set<Id> idSet {get; private set; }
public MySetController(){
//Initialize to an already known collection. Results in a set of abc,def.
this.strSet = new Set<String>{'abc','abc','def'};
//Initialize to empty set and add in entries.
this.strSet = new Set<String>();
this.strSet.add('abc');
this.strSet.add('def');
this.strSet.add('abc');
//Results in {'abc','def'}
//You can also get a set from a map in Apex. In this case, the account ids are fetched from a SOQL query.
Map<Id,Account> accountMap = new Map<Id,Account>([Select Id,Name From Account Limit 10]);
Set<Id> accountIds = accountMap.keySet();
//If you have a set, you can also use it with the bind variable syntax in SOQL:
List<Account> accounts = [Select Name From Account Where Id in :accountIds];
//Like other collections in Apex, you can use a for loop to iterate over sets:
for(Id accountId : accountIds){
Account a = accountMap.get(accountId);
//Do account stuffs here.
}
}
}
|
http://rosettacode.org/wiki/Send_an_unknown_method_call
|
Send an unknown method call
|
Task
Invoke an object method where the name of the method to be invoked can be generated at run time.
Related tasks
Respond to an unknown method call.
Runtime evaluation
|
#Java
|
Java
|
import java.lang.reflect.Method;
class Example {
public int foo(int x) {
return 42 + x;
}
}
public class Main {
public static void main(String[] args) throws Exception {
Object example = new Example();
String name = "foo";
Class<?> clazz = example.getClass();
Method meth = clazz.getMethod(name, int.class);
Object result = meth.invoke(example, 5); // result is int wrapped in an object (Integer)
System.out.println(result); // prints "47"
}
}
|
http://rosettacode.org/wiki/Send_an_unknown_method_call
|
Send an unknown method call
|
Task
Invoke an object method where the name of the method to be invoked can be generated at run time.
Related tasks
Respond to an unknown method call.
Runtime evaluation
|
#JavaScript
|
JavaScript
|
example = new Object;
example.foo = function(x) {
return 42 + x;
};
name = "foo";
example[name](5) # => 47
|
http://rosettacode.org/wiki/Send_an_unknown_method_call
|
Send an unknown method call
|
Task
Invoke an object method where the name of the method to be invoked can be generated at run time.
Related tasks
Respond to an unknown method call.
Runtime evaluation
|
#Julia
|
Julia
|
const functions = Dict{String,Function}(
"foo" => x -> 42 + x,
"bar" => x -> 42 * x)
@show functions["foo"](3)
@show functions["bar"](3)
|
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
|
#ActionScript
|
ActionScript
|
function eratosthenes(limit:int):Array
{
var primes:Array = new Array();
if (limit >= 2) {
var sqrtlmt:int = int(Math.sqrt(limit) - 2);
var nums:Array = new Array(); // start with an empty Array...
for (var i:int = 2; i <= limit; i++) // and
nums.push(i); // only initialize the Array once...
for (var j:int = 0; j <= sqrtlmt; j++) {
var p:int = nums[j]
if (p)
for (var t:int = p * p - 2; t < nums.length; t += p)
nums[t] = 0;
}
for (var m:int = 0; m < nums.length; m++) {
var r:int = nums[m];
if (r)
primes.push(r);
}
}
return primes;
}
var e:Array = eratosthenes(1000);
trace(e);
|
http://rosettacode.org/wiki/Sequence_of_primorial_primes
|
Sequence of primorial primes
|
The sequence of primorial primes is given as the increasing values of n where primorial(n) ± 1 is prime.
Noting that the n'th primorial is defined as the multiplication of the smallest n primes, the sequence is of the number of primes, in order that when multiplied together is one-off being a prime number itself.
Task
Generate and show here the first ten values of the sequence.
Optional extended task
Show the first twenty members of the series.
Notes
This task asks for the primorial indices that create the final primorial prime numbers, so there should be no ten-or-more digit numbers in the program output (although extended precision integers will be needed for intermediate results).
There is some confusion in the references, but for the purposes of this task the sequence begins with n = 1.
Probabilistic primality tests are allowed, as long as they are good enough such that the output shown is correct.
Related tasks
Primorial numbers
Factorial
See also
Primorial prime Wikipedia.
Primorial prime from The Prime Glossary.
Sequence A088411 from The On-Line Encyclopedia of Integer Sequences
|
#Julia
|
Julia
|
using Primes
function primordials(N)
print("The first $N primorial indices sequentially producing primorial primes are: 1 ")
primorial = 1
count = 1
p = 3
prod = BigInt(2)
while true
if isprime(p)
prod *= p
primorial += 1
if isprime(prod + 1) || isprime(prod - 1)
print("$primorial ")
count += 1
if count == N
break
end
end
end
p += 2
end
end
primordials(20)
|
http://rosettacode.org/wiki/Sequence_of_primorial_primes
|
Sequence of primorial primes
|
The sequence of primorial primes is given as the increasing values of n where primorial(n) ± 1 is prime.
Noting that the n'th primorial is defined as the multiplication of the smallest n primes, the sequence is of the number of primes, in order that when multiplied together is one-off being a prime number itself.
Task
Generate and show here the first ten values of the sequence.
Optional extended task
Show the first twenty members of the series.
Notes
This task asks for the primorial indices that create the final primorial prime numbers, so there should be no ten-or-more digit numbers in the program output (although extended precision integers will be needed for intermediate results).
There is some confusion in the references, but for the purposes of this task the sequence begins with n = 1.
Probabilistic primality tests are allowed, as long as they are good enough such that the output shown is correct.
Related tasks
Primorial numbers
Factorial
See also
Primorial prime Wikipedia.
Primorial prime from The Prime Glossary.
Sequence A088411 from The On-Line Encyclopedia of Integer Sequences
|
#Kotlin
|
Kotlin
|
// version 1.0.6
import java.math.BigInteger
const val LIMIT = 20 // expect a run time of about 2 minutes on a typical laptop
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>) {
println("The first $LIMIT primorial indices in the sequence are:")
print("1 ")
var primorial = 1
var count = 1
var p = 3
var prod = BigInteger.valueOf(2L)
while(true) {
if (isPrime(p)) {
prod *= BigInteger.valueOf(p.toLong())
primorial++
if ((prod + BigInteger.ONE).isProbablePrime(1) || (prod - BigInteger.ONE).isProbablePrime(1)) {
print("$primorial ")
count++
if (count == LIMIT) {
println()
break
}
}
}
p += 2
}
}
|
http://rosettacode.org/wiki/Sequence:_nth_number_with_exactly_n_divisors
|
Sequence: nth number with exactly n divisors
|
Calculate the sequence where each term an is the nth that has n divisors.
Task
Show here, on this page, at least the first 15 terms of the sequence.
See also
OEIS:A073916
Related tasks
Sequence: smallest number greater than previous term with exactly n divisors
Sequence: smallest number with exactly n divisors
|
#REXX
|
REXX
|
/*REXX program finds and displays the Nth number with exactly N divisors. */
parse arg N . /*obtain optional argument from the CL.*/
if N=='' | N=="," then N= 15 /*Not specified? Then use the default.*/
if N>=50 then numeric digits 10 /*use more decimal digits for large N. */
w= 50 /*W: width of the 2nd column of output*/
say '─divisors─' center("the Nth number with exactly N divisors", w, '─') /*title.*/
@.1= 2; Ps= 1 /*1st prime; number of primes (so far)*/
do p=3 until Ps==N /* [↓] gen N primes, store in @ array.*/
if \isPrime(p) then iterate; Ps= Ps + 1; @.Ps= p
end /*gp*/
!.= /*the ! array is used for memoization*/
do i=1 for N; odd= i//2 /*step through a number of divisors. */
if odd then if isPrime(i) then do; _= pPow(); w= max(w, length(_) )
call tell commas(_); iterate
end
#= 0; even= \odd /*the number of occurrences for #div. */
do j=1; jj= j /*now, search for a number that ≡ #divs*/
if odd then jj= j*j /*Odd and non-prime? Calculate square.*/
if !.jj==. then iterate /*has this number already been found? */
d= #divs(jj) /*get # divisors; Is not equal? Skip.*/
if even then if d<i then do; !.j=.; iterate; end /*Too low? Flag it.*/
if d\==i then iterate /*Is not equal? Then skip this number.*/
#= # + 1 /*bump number of occurrences for #div. */
if #\==i then iterate /*Not correct occurrence? Keep looking.*/
call tell commas(jj) /*display Nth number with #divs*/
leave /*found a number, so now get the next I*/
end /*j*/
end /*i*/
exit /*stick a fork in it, we're all done. */
/*──────────────────────────────────────────────────────────────────────────────────────*/
commas: parse arg _; do j=length(_)-3 to 1 by -3; _=insert(',', _, j); end; return _
pPow: numeric digits 1000; return @.i**(i-1) /*temporarily increase decimal digits. */
tell: parse arg _; say center(i,10) right(_,max(w,length(_))); if i//5==0 then say; return
/*──────────────────────────────────────────────────────────────────────────────────────*/
#divs: procedure; parse arg x 1 y /*X and Y: both set from 1st argument.*/
if x<7 then do /*handle special cases for numbers < 7.*/
if x<3 then return x /* " " " " one and two.*/
if x<5 then return x - 1 /* " " " " three & four*/
if x==5 then return 2 /* " " " " five. */
if x==6 then return 4 /* " " " " six. */
end
odd= x // 2 /*check if X is odd or not. */
if odd then do; #= 1; end /*Odd? Assume Pdivisors count of 1.*/
else do; #= 3; y= x%2; end /*Even? " " " " 3.*/
/* [↑] start with known num of Pdivs.*/
do k=3 by 1+odd while k<y /*when doing odd numbers, skip evens. */
if x//k==0 then do /*if no remainder, then found a divisor*/
#=#+2; y=x%k /*bump # Pdivs, calculate limit Y. */
if k>=y then do; #= #-1; leave; end /*limit?*/
end /* ___ */
else if k*k>x then leave /*only divide up to √ x */
end /*k*/ /* [↑] this form of DO loop is faster.*/
return #+1 /*bump "proper divisors" to "divisors".*/
/*──────────────────────────────────────────────────────────────────────────────────────*/
isPrime: procedure; parse arg #; if wordpos(#, '2 3 5 7 11 13')\==0 then return 1
if #<2 then return 0; if #//2==0 | #//3==0 | #//5==0 | #//7==0 then return 0
if # // 2==0 | # // 3 ==0 then return 0
do j=11 by 6 until j*j>#; if # // j==0 | # // (J+2)==0 then return 0
end /*j*/ /* ___ */
return 1 /*Exceeded √ # ? Then # is prime. */
|
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
|
#JavaScript
|
JavaScript
|
(() => {
'use strict';
// consolidated :: Ord a => [Set a] -> [Set a]
const consolidated = xs => {
const go = (s, xs) =>
0 !== xs.length ? (() => {
const h = xs[0];
return 0 === intersection(h, s).size ? (
[h].concat(go(s, tail(xs)))
) : go(union(h, s), tail(xs));
})() : [s];
return foldr(go, [], xs);
};
// TESTS ----------------------------------------------
const main = () =>
map(xs => intercalate(
', and ',
map(showSet, consolidated(xs))
),
map(x => map(
s => new Set(chars(s)),
x
),
[
['ab', 'cd'],
['ab', 'bd'],
['ab', 'cd', 'db'],
['hik', 'ab', 'cd', 'db', 'fgh']
]
)
).join('\n');
// GENERIC FUNCTIONS ----------------------------------
// chars :: String -> [Char]
const chars = s => s.split('');
// concat :: [[a]] -> [a]
// concat :: [String] -> String
const concat = xs =>
0 < xs.length ? (() => {
const unit = 'string' !== typeof xs[0] ? (
[]
) : '';
return unit.concat.apply(unit, xs);
})() : [];
// elems :: Dict -> [a]
// elems :: Set -> [a]
const elems = x =>
'Set' !== x.constructor.name ? (
Object.values(x)
) : Array.from(x.values());
// flip :: (a -> b -> c) -> b -> a -> c
const flip = f =>
1 < f.length ? (
(a, b) => f(b, a)
) : (x => y => f(y)(x));
// Note that that the Haskell signature of foldr differs from that of
// foldl - the positions of accumulator and current value are reversed
// foldr :: (a -> b -> b) -> b -> [a] -> b
const foldr = (f, a, xs) => xs.reduceRight(flip(f), a);
// intercalate :: [a] -> [[a]] -> [a]
// intercalate :: String -> [String] -> String
const intercalate = (sep, xs) =>
0 < xs.length && 'string' === typeof sep &&
'string' === typeof xs[0] ? (
xs.join(sep)
) : concat(intersperse(sep, xs));
// intersection :: Ord a => Set a -> Set a -> Set a
const intersection = (s, s1) =>
new Set([...s].filter(x => s1.has(x)));
// intersperse :: a -> [a] -> [a]
// intersperse :: Char -> String -> String
const intersperse = (sep, xs) => {
const bln = 'string' === typeof xs;
return xs.length > 1 ? (
(bln ? concat : x => x)(
(bln ? (
xs.split('')
) : xs)
.slice(1)
.reduce((a, x) => a.concat([sep, x]), [xs[0]])
)) : xs;
};
// map :: (a -> b) -> [a] -> [b]
const map = (f, xs) => xs.map(f);
// showSet :: Set -> String
const showSet = s =>
intercalate(elems(s), ['{', '}']);
// sort :: Ord a => [a] -> [a]
const sort = xs => xs.slice()
.sort((a, b) => a < b ? -1 : (a > b ? 1 : 0));
// tail :: [a] -> [a]
const tail = xs => 0 < xs.length ? xs.slice(1) : [];
// union :: Ord a => Set a -> Set a -> Set a
const union = (s, s1) =>
Array.from(s1.values())
.reduce(
(a, x) => (a.add(x), a),
new Set(s)
);
// MAIN ---
return main();
})();
|
http://rosettacode.org/wiki/Sequence:_smallest_number_with_exactly_n_divisors
|
Sequence: smallest number with exactly n divisors
|
Calculate the sequence where each term an is the smallest natural number that has exactly n divisors.
Task
Show here, on this page, at least the first 15 terms of the sequence.
Related tasks
Sequence: smallest number greater than previous term with exactly n divisors
Sequence: nth number with exactly n divisors
See also
OEIS:A005179
|
#Modula-2
|
Modula-2
|
MODULE A005179;
FROM InOut IMPORT WriteCard, WriteLn;
CONST Amount = 15;
VAR found, i, ndivs: CARDINAL;
A: ARRAY [1..Amount] OF CARDINAL;
PROCEDURE divisors(n: CARDINAL): CARDINAL;
VAR count, i: CARDINAL;
BEGIN
count := 0;
i := 1;
WHILE i*i <= n DO
IF n MOD i = 0 THEN
INC(count);
IF n DIV i # i THEN
INC(count);
END;
END;
INC(i);
END;
RETURN count;
END divisors;
BEGIN
FOR i := 1 TO Amount DO A[i] := 0; END;
found := 0;
i := 1;
WHILE found < Amount DO
ndivs := divisors(i);
IF (ndivs <= Amount) AND (A[ndivs] = 0) THEN
INC(found);
A[ndivs] := i;
END;
INC(i);
END;
FOR i := 1 TO Amount DO
WriteCard(A[i], 4);
WriteLn;
END;
END A005179.
|
http://rosettacode.org/wiki/SHA-256
|
SHA-256
|
SHA-256 is the recommended stronger alternative to SHA-1. See FIPS PUB 180-4 for implementation details.
Either by using a dedicated library or implementing the algorithm in your language, show that the SHA-256 digest of the string "Rosetta code" is: 764faf5c61ac315f1497f9dfa542713965b785e5cc2f707d6468d7d1124cdfcf
|
#PHP
|
PHP
|
<?php
echo hash('sha256', 'Rosetta code');
|
http://rosettacode.org/wiki/SHA-256
|
SHA-256
|
SHA-256 is the recommended stronger alternative to SHA-1. See FIPS PUB 180-4 for implementation details.
Either by using a dedicated library or implementing the algorithm in your language, show that the SHA-256 digest of the string "Rosetta code" is: 764faf5c61ac315f1497f9dfa542713965b785e5cc2f707d6468d7d1124cdfcf
|
#PicoLisp
|
PicoLisp
|
(setq *Sha256-K
(mapcar hex
'("428A2F98" "71374491" "B5C0FBCF" "E9B5DBA5" "3956C25B"
"59F111F1" "923F82A4" "AB1C5ED5" "D807AA98" "12835B01"
"243185BE" "550C7DC3" "72BE5D74" "80DEB1FE" "9BDC06A7"
"C19BF174" "E49B69C1" "EFBE4786" "0FC19DC6" "240CA1CC"
"2DE92C6F" "4A7484AA" "5CB0A9DC" "76F988DA" "983E5152"
"A831C66D" "B00327C8" "BF597FC7" "C6E00BF3" "D5A79147"
"06CA6351" "14292967" "27B70A85" "2E1B2138" "4D2C6DFC"
"53380D13" "650A7354" "766A0ABB" "81C2C92E" "92722C85"
"A2BFE8A1" "A81A664B" "C24B8B70" "C76C51A3" "D192E819"
"D6990624" "F40E3585" "106AA070" "19A4C116" "1E376C08"
"2748774C" "34B0BCB5" "391C0CB3" "4ED8AA4A" "5B9CCA4F"
"682E6FF3" "748F82EE" "78A5636F" "84C87814" "8CC70208"
"90BEFFFA" "A4506CEB" "BEF9A3F7" "C67178F2") ) )
(de rightRotate (X C)
(| (mod32 (>> C X)) (mod32 (>> (- C 32) X))) )
(de mod32 (N)
(& N `(hex "FFFFFFFF")) )
(de not32 (N)
(x| N `(hex "FFFFFFFF")) )
(de add32 @
(mod32 (pass +)) )
(de sha256 (Str)
(let Len (length Str)
(setq Str
(conc
(need
(-
8
(* 64 (/ (+ Len 1 8 63) 64)) )
(conc (mapcar char (chop Str)) (cons `(hex "80")))
0 )
(flip
(make
(setq Len (* 8 Len))
(do 8
(link (& Len 255))
(setq Len (>> 8 Len )) ) ) ) ) ) )
(let
(H0 `(hex "6A09E667")
H1 `(hex "BB67AE85")
H2 `(hex "3C6EF372")
H3 `(hex "A54FF53A")
H4 `(hex "510E527F")
H5 `(hex "9B05688C")
H6 `(hex "1F83D9AB")
H7 `(hex "5BE0CD19") )
(while Str
(let
(A H0
B H1
C H2
D H3
E H4
F H5
G H6
H H7
W
(conc
(make
(do 16
(link
(apply
|
(mapcar >> (-24 -16 -8 0) (cut 4 'Str)) ) ) ) )
(need 48 0) ) )
(for (I 17 (>= 64 I) (inc I))
(let
(Wi15 (get W (- I 15))
Wi2 (get W (- I 2))
S0
(x|
(rightRotate Wi15 7)
(rightRotate Wi15 18)
(>> 3 Wi15) )
S1
(x|
(rightRotate Wi2 17)
(rightRotate Wi2 19)
(>> 10 Wi2) ) )
(set (nth W I)
(add32
(get W (- I 16))
S0
(get W (- I 7))
S1 ) ) ) )
(use (Tmp1 Tmp2)
(for I 64
(setq
Tmp1
(add32
H
(x|
(rightRotate E 6)
(rightRotate E 11)
(rightRotate E 25) )
(x| (& E F) (& (not32 E) G))
(get *Sha256-K I)
(get W I) )
Tmp2
(add32
(x|
(rightRotate A 2)
(rightRotate A 13)
(rightRotate A 22) )
(x|
(& A B)
(& A C)
(& B C) ) )
H G
G F
F E
E (add32 D Tmp1)
D C
C B
B A
A (add32 Tmp1 Tmp2) ) ) )
(setq
H0 (add32 H0 A)
H1 (add32 H1 B)
H2 (add32 H2 C)
H3 (add32 H3 D)
H4 (add32 H4 E)
H5 (add32 H5 F)
H6 (add32 H6 G)
H7 (add32 H7 H) ) ) )
(mapcan
'((N)
(flip
(make
(do 4
(link (& 255 N))
(setq N (>> 8 N)) ) ) ) )
(list H0 H1 H2 H3 H4 H5 H6 H7) ) ) )
(let Str "Rosetta code"
(println
(pack
(mapcar
'((B) (pad 2 (hex B)))
(sha256 Str) ) ) )
(println
(pack
(mapcar
'((B) (pad 2 (hex B)))
(native
"libcrypto.so"
"SHA256"
'(B . 32)
Str
(length Str)
'(NIL (32)) ) ) ) ) )
(bye)
|
http://rosettacode.org/wiki/Sequence:_smallest_number_greater_than_previous_term_with_exactly_n_divisors
|
Sequence: smallest number greater than previous term with exactly n divisors
|
Calculate the sequence where each term an is the smallest natural number greater than the previous term, that has exactly n divisors.
Task
Show here, on this page, at least the first 15 terms of the sequence.
See also
OEIS:A069654
Related tasks
Sequence: smallest number with exactly n divisors
Sequence: nth number with exactly n divisors
|
#Python
|
Python
|
def divisors(n):
divs = [1]
for ii in range(2, int(n ** 0.5) + 3):
if n % ii == 0:
divs.append(ii)
divs.append(int(n / ii))
divs.append(n)
return list(set(divs))
def sequence(max_n=None):
previous = 0
n = 0
while True:
n += 1
ii = previous
if max_n is not None:
if n > max_n:
break
while True:
ii += 1
if len(divisors(ii)) == n:
yield ii
previous = ii
break
if __name__ == '__main__':
for item in sequence(15):
print(item)
|
http://rosettacode.org/wiki/Sequence:_smallest_number_greater_than_previous_term_with_exactly_n_divisors
|
Sequence: smallest number greater than previous term with exactly n divisors
|
Calculate the sequence where each term an is the smallest natural number greater than the previous term, that has exactly n divisors.
Task
Show here, on this page, at least the first 15 terms of the sequence.
See also
OEIS:A069654
Related tasks
Sequence: smallest number with exactly n divisors
Sequence: nth number with exactly n divisors
|
#Quackery
|
Quackery
|
[ stack ] is terms ( --> s )
[ temp put
[] terms put
0 1
[ dip 1+
over factors size
over = if
[ over
terms take
swap join
terms put
1+ ]
terms share size
temp share = until ]
terms take
temp release
dip 2drop ] is task ( n --> [ )
15 task echo
|
http://rosettacode.org/wiki/SHA-1
|
SHA-1
|
SHA-1 or SHA1 is a one-way hash function;
it computes a 160-bit message digest.
SHA-1 often appears in security protocols; for example,
many HTTPS websites use RSA with SHA-1 to secure their connections.
BitTorrent uses SHA-1 to verify downloads.
Git and Mercurial use SHA-1 digests to identify commits.
A US government standard, FIPS 180-1, defines SHA-1.
Find the SHA-1 message digest for a string of octets. You may either call a SHA-1 library, or implement SHA-1 in your language. Both approaches interest Rosetta Code.
Warning: SHA-1 has known weaknesses. Theoretical attacks may find a collision after 252 operations, or perhaps fewer.
This is much faster than a brute force attack of 280 operations. USgovernment deprecated SHA-1.
For production-grade cryptography, users may consider a stronger alternative, such as SHA-256 (from the SHA-2 family) or the upcoming SHA-3.
|
#PHP
|
PHP
|
<?php
$string = 'Rosetta Code';
echo sha1( $string ), "\n";
?>
|
http://rosettacode.org/wiki/SHA-1
|
SHA-1
|
SHA-1 or SHA1 is a one-way hash function;
it computes a 160-bit message digest.
SHA-1 often appears in security protocols; for example,
many HTTPS websites use RSA with SHA-1 to secure their connections.
BitTorrent uses SHA-1 to verify downloads.
Git and Mercurial use SHA-1 digests to identify commits.
A US government standard, FIPS 180-1, defines SHA-1.
Find the SHA-1 message digest for a string of octets. You may either call a SHA-1 library, or implement SHA-1 in your language. Both approaches interest Rosetta Code.
Warning: SHA-1 has known weaknesses. Theoretical attacks may find a collision after 252 operations, or perhaps fewer.
This is much faster than a brute force attack of 280 operations. USgovernment deprecated SHA-1.
For production-grade cryptography, users may consider a stronger alternative, such as SHA-256 (from the SHA-2 family) or the upcoming SHA-3.
|
#PicoLisp
|
PicoLisp
|
(de leftRotate (X C)
(| (mod32 (>> (- C) X)) (>> (- 32 C) X)) )
(de mod32 (N)
(& N `(hex "FFFFFFFF")) )
(de not32 (N)
(x| N `(hex "FFFFFFFF")) )
(de add32 @
(mod32 (pass +)) )
(de sha1 (Str)
(let Len (length Str)
(setq Str
(conc
(need
(-
8
(* 64 (/ (+ Len 1 8 63) 64)) )
(conc
(mapcar char (chop Str))
(cons `(hex "80")) )
0 )
(flip
(make
(setq Len (* 8 Len))
(do 8
(link (& Len 255))
(setq Len (>> 8 Len )) ) ) ) ) ) )
(let
(H0 `(hex "67452301")
H1 `(hex "EFCDAB89")
H2 `(hex "98BADCFE")
H3 `(hex "10325476")
H4 `(hex "C3D2E1F0") )
(while Str
(let
(A H0 B H1 C H2 D H3 E H4
W (conc
(make
(do 16
(link
(apply
|
(mapcar >> (-24 -16 -8 0) (cut 4 'Str)) ) ) ) )
(need 64 0) ) )
(for (I 17 (>= 80 I) (inc I))
(set (nth W I)
(leftRotate
(x|
(get W (- I 3))
(get W (- I 8))
(get W (- I 14))
(get W (- I 16)) )
1 ) ) )
(use (Tmp F K)
(for I 80
(cond
((>= 20 I)
(setq
F (| (& B C) (& (not32 B) D))
K `(hex "5A827999") ) )
((>= 40 I)
(setq
F (x| B C D)
K `(hex "6ED9EBA1") ) )
((>= 60 I)
(setq
F (| (& B C) (& B D) (& C D))
K `(hex "8F1BBCDC") ) )
(T
(setq
F (x| B C D)
K `(hex "CA62C1D6") ) ) )
(setq
Tmp (add32 (leftRotate A 5) F E K (get W I) )
E D
D C
C (leftRotate B 30)
B A
A Tmp ) ) )
(setq
H0 (add32 H0 A)
H1 (add32 H1 B)
H2 (add32 H2 C)
H3 (add32 H3 D)
H4 (add32 H4 E) ) ) )
(mapcan
'((N)
(flip
(make
(do 4
(link (& 255 N))
(setq N (>> 8 N)) ) ) ) )
(list H0 H1 H2 H3 H4) ) ) )
(let Str "Rosetta Code"
(println
(pack
(mapcar
'((B) (pad 2 (hex B)))
(sha1 Str) ) ) )
(println
(pack
(mapcar
'((B) (pad 2 (hex B)))
(native
"libcrypto.so"
"SHA1"
'(B . 20)
Str
(length Str)
'(NIL (20)) ) ) ) ) )
(bye)
|
http://rosettacode.org/wiki/Seven-sided_dice_from_five-sided_dice
|
Seven-sided dice from five-sided dice
|
Task
(Given an equal-probability generator of one of the integers 1 to 5
as dice5), create dice7 that generates a pseudo-random integer from
1 to 7 in equal probability using only dice5 as a source of random
numbers, and check the distribution for at least one million calls using the function created in Simple Random Distribution Checker.
Implementation suggestion:
dice7 might call dice5 twice, re-call if four of the 25
combinations are given, otherwise split the other 21 combinations
into 7 groups of three, and return the group index from the rolls.
(Task adapted from an answer here)
|
#zkl
|
zkl
|
var die5=(1).random.fp(6); // [1..5]
fcn die7{ while((r:=5*die5() + die5())>=27){} r/3-1 }
fcn rtest(N){ //test spread over [0..9]
dist:=L(0,0,0,0,0,0,0,0,0,0);
do(N){ dist[die7()]+=1 }
sum:=dist.sum();
dist=dist.apply('wrap(n){ "%.2f%%".fmt(n.toFloat()/sum*100) }).println();
}
println("Looking for ",100.0/7,"%");
rtest(0d1_000_000);
|
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
|
#Kotlin
|
Kotlin
|
// Version 1.2.60
fun main(args: Array<String>) {
for (i in 0..15) {
for (j in 32 + i..127 step 16) {
val k = when (j) {
32 -> "Spc"
127 -> "Del"
else -> j.toChar().toString()
}
System.out.printf("%3d : %-3s ", j, k)
}
println()
}
}
|
http://rosettacode.org/wiki/Sierpinski_triangle
|
Sierpinski triangle
|
Task
Produce an ASCII representation of a Sierpinski triangle of order N.
Example
The Sierpinski triangle of order 4 should look like this:
*
* *
* *
* * * *
* *
* * * *
* * * *
* * * * * * * *
* *
* * * *
* * * *
* * * * * * * *
* * * *
* * * * * * * *
* * * * * * * *
* * * * * * * * * * * * * * * *
Related tasks
Sierpinski triangle/Graphical for graphics images of this pattern.
Sierpinski carpet
|
#Prolog
|
Prolog
|
sierpinski_triangle(N) :-
Len is 2 ** (N+1) - 1,
length(L, Len),
numlist(1, Len, LN),
maplist(init(N), L, LN),
atomic_list_concat(L, Line),
writeln(Line),
NbTours is 2**N - 1,
loop(NbTours, LN, Len, L).
init(N, Cell, Num) :-
( Num is 2 ** N + 1 -> Cell = *; Cell = ' ').
loop(0, _, _, _) :- !.
loop(N, LN, Len, L) :-
maplist(compute_next_line(Len, L), LN, L1),
atomic_list_concat(L1, Line),
writeln(Line),
N1 is N - 1,
loop(N1, LN, Len, L1).
compute_next_line(Len, L, I, V) :-
I1 is I - 1,
I2 is I+1,
( I = 1 -> V0 = ' '; nth1(I1, L, V0)),
nth1(I, L, V1),
( I = Len -> V2 = ' '; nth1(I2, L, V2)),
rule_90(V0, V1, V2, V).
rule_90('*','*','*', ' ').
rule_90('*','*',' ', '*').
rule_90('*',' ','*', ' ').
rule_90('*',' ',' ', '*').
rule_90(' ','*','*', '*').
rule_90(' ','*',' ', ' ').
rule_90(' ',' ','*', '*').
rule_90(' ',' ',' ', ' ').
|
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
|
#OCaml
|
OCaml
|
let rec in_carpet x y =
if x = 0 || y = 0 then true
else if x mod 3 = 1 && y mod 3 = 1 then false
else in_carpet (x / 3) (y / 3)
(* I define my own operator for integer exponentiation *)
let rec (^:) a b =
if b = 0 then 1
else if b mod 2 = 0 then let x = a ^: (b / 2) in x * x
else a * (a ^: (b - 1))
let carpet n =
for i = 0 to (3 ^: n) - 1 do
for j = 0 to (3 ^: n) - 1 do
print_char (if in_carpet i j then '*' else ' ')
done;
print_newline ()
done
|
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
|
#8th
|
8th
|
[] var, results
: processline \ m s --
clone nip
tuck s:rev
m:exists? if
results @ rot a:push drop
else
swap true m:!
then ;
{} "unixdict.txt" app:asset >s
' processline s:eachline
results @ dup a:len . " pairs" . cr
a:shuffle
( a:shift dup . " is the reverse of " . s:rev . cr ) 5 times bye
|
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
|
#Ada
|
Ada
|
with Ada.Containers.Indefinite_Vectors, Ada.Text_IO;
package String_Vectors is
package String_Vec is new Ada.Containers.Indefinite_Vectors
(Index_Type => Positive, Element_Type => String);
type Vec is new String_Vec.Vector with null record;
function Read(Filename: String) return Vec;
-- uses Ada.Text_IO to read words from the given file into a Vec
-- requirement: each word is written in a single line
function Is_In(List: Vec;
Word: String;
Start: Positive; Stop: Natural) return Boolean;
-- checks if Word is in List(Start .. Stop);
-- requirement: the words in List are sorted alphabetically
end String_Vectors;
|
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.
|
#PicoLisp
|
PicoLisp
|
(de a (F)
(msg 'a)
F )
(de b (F)
(msg 'b)
F )
(mapc
'((I J)
(for Op '(and or)
(println I Op J '-> (Op (a I) (b J))) ) )
'(NIL NIL T T)
'(NIL T NIL T) )
|
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.
|
#Pike
|
Pike
|
int(0..1) a(int(0..1) i)
{
write(" a\n");
return i;
}
int(0..1) b(int(0..1) i)
{
write(" b\n");
return i;
}
foreach(({ ({ false, false }), ({ false, true }), ({ true, true }), ({ true, false }) });; array(int) args)
{
write(" %d && %d\n", @args);
a(args[0]) && b(args[1]);
write(" %d || %d\n", @args);
a(args[0]) || b(args[1]);
}
|
http://rosettacode.org/wiki/Selectively_replace_multiple_instances_of_a_character_within_a_string
|
Selectively replace multiple instances of a character within a string
|
Task
This is admittedly a trivial task but I thought it would be interesting to see how succinctly (or otherwise) different languages can handle it.
Given the string: "abracadabra", replace programatically:
the first 'a' with 'A'
the second 'a' with 'B'
the fourth 'a' with 'C'
the fifth 'a' with 'D'
the first 'b' with 'E'
the second 'r' with 'F'
Note that there is no replacement for the third 'a', second 'b' or first 'r'.
The answer should, of course, be : "AErBcadCbFD".
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
|
#Factor
|
Factor
|
USING: assocs formatting grouping kernel random sequences ;
CONSTANT: instrs {
CHAR: a 1 CHAR: A
CHAR: a 2 CHAR: B
CHAR: a 4 CHAR: C
CHAR: a 5 CHAR: D
CHAR: b 1 CHAR: E
CHAR: r 2 CHAR: F
}
: counts ( seq -- assoc )
H{ } clone swap [ 2dup swap inc-at dupd of ] zip-with nip ;
: replace-nths ( seq instrs -- seq' )
[ counts ] dip 3 group [ f suffix 2 group ] map substitute keys ;
: test ( str -- )
dup instrs replace-nths "" like "%s -> %s\n" printf ;
"abracadabra" test
"abracadabra" randomize test
|
http://rosettacode.org/wiki/Selectively_replace_multiple_instances_of_a_character_within_a_string
|
Selectively replace multiple instances of a character within a string
|
Task
This is admittedly a trivial task but I thought it would be interesting to see how succinctly (or otherwise) different languages can handle it.
Given the string: "abracadabra", replace programatically:
the first 'a' with 'A'
the second 'a' with 'B'
the fourth 'a' with 'C'
the fifth 'a' with 'D'
the first 'b' with 'E'
the second 'r' with 'F'
Note that there is no replacement for the third 'a', second 'b' or first 'r'.
The answer should, of course, be : "AErBcadCbFD".
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
|
Function replaceChar(Byref S As String) As String
Dim As String A = "ABaCD", B = "Eb", R = "rF"
Dim As Byte pA = 1, pB = 1, pR = 1
For i As Byte = 0 To Len(S)
Select Case Mid(S,i,1)
Case "a"
Mid(S,i,1) = Mid(A,pA,1)
pA += 1
Case "b"
Mid(S,i,1) = Mid(B,pB,1)
pB += 1
Case "r"
Mid(S,i,1) = Mid(R,pR,1)
pR += 1
End Select
Next i
Return S
End Function
Dim As String S
S = "abracadabra"
Print S; " -> "; replaceChar(S)
S = "caarabadrab"
Print S; " -> "; replaceChar(S)
Sleep
|
http://rosettacode.org/wiki/Selectively_replace_multiple_instances_of_a_character_within_a_string
|
Selectively replace multiple instances of a character within a string
|
Task
This is admittedly a trivial task but I thought it would be interesting to see how succinctly (or otherwise) different languages can handle it.
Given the string: "abracadabra", replace programatically:
the first 'a' with 'A'
the second 'a' with 'B'
the fourth 'a' with 'C'
the fifth 'a' with 'D'
the first 'b' with 'E'
the second 'r' with 'F'
Note that there is no replacement for the third 'a', second 'b' or first 'r'.
The answer should, of course, be : "AErBcadCbFD".
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"
"strings"
)
func main() {
s := "abracadabra"
ss := []byte(s)
var ixs []int
for ix, c := range s {
if c == 'a' {
ixs = append(ixs, ix)
}
}
repl := "ABaCD"
for i := 0; i < 5; i++ {
ss[ixs[i]] = repl[i]
}
s = string(ss)
s = strings.Replace(s, "b", "E", 1)
s = strings.Replace(s, "r", "F", 2)
s = strings.Replace(s, "F", "r", 1)
fmt.Println(s)
}
|
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)
|
#Delphi
|
Delphi
|
procedure SendEmail;
var
msg: TIdMessage;
smtp: TIdSMTP;
begin
smtp := TIdSMTP.Create;
try
smtp.Host := 'smtp.server.com';
smtp.Port := 587;
smtp.Username := 'login';
smtp.Password := 'password';
smtp.AuthType := satNone;
smtp.Connect;
msg := TIdMessage.Create(nil);
try
with msg.Recipients.Add do begin
Address := '[email protected]';
Name := 'Doug';
end;
with msg.Sender do begin
Address := '[email protected]';
Name := 'Fred';
end;
msg.Subject := 'subj';
msg.Body.Text := 'here goes email message';
smtp.Send(msg);
finally
msg.Free;
end;
finally
smtp.Free;
end;
end;
|
http://rosettacode.org/wiki/Semiprime
|
Semiprime
|
Semiprime numbers are natural numbers that are products of exactly two (possibly equal) prime numbers.
Semiprimes are also known as:
semi-primes
biprimes
bi-primes
2-almost primes
or simply: P2
Example
1679 = 23 × 73
(This particular number was chosen as the length of the Arecibo message).
Task
Write a function determining whether a given number is semiprime.
See also
The Wikipedia article: semiprime.
The Wikipedia article: almost prime.
The OEIS sequence: A001358: semiprimes which has a shorter definition: the product of two primes.
|
#ALGOL_68
|
ALGOL 68
|
# returns TRUE if n is semi-prime, FALSE otherwise #
# n is semi prime if it has exactly two prime factors #
PROC is semiprime = ( INT n )BOOL:
BEGIN
# We only need to consider factors between 2 and #
# sqrt( n ) inclusive. If there is only one of these #
# then it must be a prime factor and so the number #
# is semi prime #
INT factor count := 0;
FOR factor FROM 2 TO ENTIER sqrt( ABS n )
WHILE IF n MOD factor = 0 THEN
factor count +:= 1;
# check the factor isn't a repeated factor #
IF n /= factor * factor THEN
# the factor isn't the square root #
INT other factor = n OVER factor;
IF other factor MOD factor = 0 THEN
# have a repeated factor #
factor count +:= 1
FI
FI
FI;
factor count < 2
DO SKIP OD;
factor count = 1
END # is semiprime # ;
# determine the first few semi primes #
print( ( "semi primes below 100: " ) );
FOR i TO 99 DO
IF is semi prime( i ) THEN print( ( whole( i, 0 ), " " ) ) FI
OD;
print( ( newline ) );
print( ( "semi primes below between 1670 and 1690: " ) );
FOR i FROM 1670 TO 1690 DO
IF is semi prime( i ) THEN print( ( whole( i, 0 ), " " ) ) FI
OD;
print( ( newline ) )
|
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
|
#11l
|
11l
|
F is_self_describing(n)
V s = String(n)
R all(enumerate(Array(s)).map((i, ch) -> @s.count(String(i)) == Int(ch)))
print((0.<4000000).filter(x -> is_self_describing(x)))
|
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
|
#ALGOL_68
|
ALGOL 68
|
BEGIN # find some self numbers numbers n such that there is no g such that g + sum of g's digits = n #
INT max number = 1 999 999 999 + 82; # maximum n plus g we will condifer #
# sieve the self numbers up to 1 999 999 999 #
[ 0 : max number ]BOOL self; FOR i TO UPB self DO self[ i ] := TRUE OD;
INT n := 0;
FOR s0 FROM 0 TO 1 DO
FOR d1 FROM 0 TO 9 DO
INT s1 = s0 + d1;
FOR d2 FROM 0 TO 9 DO
INT s2 = s1 + d2;
FOR d3 FROM 0 TO 9 DO
INT s3 = s2 + d3;
FOR d4 FROM 0 TO 9 DO
INT s4 = s3 + d4;
FOR d5 FROM 0 TO 9 DO
INT s5 = s4 + d5;
FOR d6 FROM 0 TO 9 DO
INT s6 = s5 + d6;
FOR d7 FROM 0 TO 9 DO
INT s7 = s6 + d7;
FOR d8 FROM 0 TO 9 DO
INT s8 = s7 + d8;
FOR d9 FROM 0 TO 9 DO
INT s9 = s8 + d9;
self[ s9 + n ] := FALSE;
n +:= 1
OD
OD
OD
OD
OD
OD
OD
OD
OD
OD;
# show the first 50 self numbers #
INT s count := 0;
FOR i TO UPB self WHILE s count < 50 DO
IF self[ i ] THEN
print( ( " ", whole( i, -3 ) ) );
IF ( s count +:= 1 ) MOD 18 = 0 THEN print( ( newline ) ) FI
FI
OD;
print( ( newline ) );
# show the self numbers with power-of-10 indxes #
INT s show := 1;
s count := 0;
print( ( " nth self", newline ) );
print( ( " n number", newline ) );
FOR i TO UPB self DO
IF self[ i ] THEN
s count +:= 1;
IF s count = s show THEN
print( ( whole( s show, -9 ), " ", whole( i, -11 ), newline ) );
s show *:= 10
FI
FI
OD
END
|
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.
|
#Go
|
Go
|
package main
import "fmt"
type Set func(float64) bool
func Union(a, b Set) Set { return func(x float64) bool { return a(x) || b(x) } }
func Inter(a, b Set) Set { return func(x float64) bool { return a(x) && b(x) } }
func Diff(a, b Set) Set { return func(x float64) bool { return a(x) && !b(x) } }
func open(a, b float64) Set { return func(x float64) bool { return a < x && x < b } }
func closed(a, b float64) Set { return func(x float64) bool { return a <= x && x <= b } }
func opCl(a, b float64) Set { return func(x float64) bool { return a < x && x <= b } }
func clOp(a, b float64) Set { return func(x float64) bool { return a <= x && x < b } }
func main() {
s := make([]Set, 4)
s[0] = Union(opCl(0, 1), clOp(0, 2)) // (0,1] ∪ [0,2)
s[1] = Inter(clOp(0, 2), opCl(1, 2)) // [0,2) ∩ (1,2]
s[2] = Diff(clOp(0, 3), open(0, 1)) // [0,3) − (0,1)
s[3] = Diff(clOp(0, 3), closed(0, 1)) // [0,3) − [0,1]
for i := range s {
for x := float64(0); x < 3; x++ {
fmt.Printf("%v ∈ s%d: %t\n", x, i, s[i](x))
}
fmt.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
|
#Arturo
|
Arturo
|
getPrimes: function [upto][
result: new [2]
loop range.step:2 3 upto 'x [
divisible: false
loop 2..inc x/2 'z [
if zero? x%z ->
divisible: true
]
if not? divisible ->
'result ++ x
]
return result
]
print getPrimes 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
|
#AsciiDots
|
AsciiDots
|
``warps
%$ABCPR
``outputs all primes up to and including the input
.-#?-A
B-P/$_#$_" "
R-*~
\/
``primality test
/---------------*-\
//-----------{*}*~-+\
///--#1--\ /#1>/ \/ ||
\\*/#2>*-\-~#0*>R ||
/*>*+--++{%}/ \+>C || ``signal to C triggers next number
|\--/>-/| || || ``to be input from for loop
| /-~*--+-------^| ||
| |[<]\ | */ ||
| \-* | | | /--+/
|/-[+]|[*]------+-<1#*
|\1#* \-+-------+----/
| ~---* ^--\
| \---/ | |
\------\ | |
/-----~\ /-----~#0/
P*#2{<}/\-*#2{=}/ ``hardcode <=1 and 2
\---/ \---/
``for loop
``only outputs next number once C receives any input
.-\C#1-*--\ /--B
# /-{+}-+-*--\
1 | /---+----~
*->-*\ \---\|
A{+}>*{-}*-{>}+/
//| \#0/ |
\{*}-------/
|
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.
|
#Arturo
|
Arturo
|
f: function [n]->
n + floor 0.5 + sqrt n
loop 1..22 'i ->
print [i "->" f i]
i: new 1, nonSquares: new []
while [i<1000000][ 'nonSquares ++ f i, inc 'i]
squares: map 1..1001 'x -> x ^ 2
if? empty? intersection squares nonSquares -> print "Didn't find any squares!"
else -> print "Ooops! Something went wrong!"
|
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.
|
#AutoHotkey
|
AutoHotkey
|
Loop 22
t .= (A_Index + floor(0.5 + sqrt(A_Index))) " "
MsgBox %t%
s := 0
Loop 1000000
x := A_Index + floor(0.5 + sqrt(A_Index)), s += x = round(sqrt(x))**2
Msgbox Number of bad squares = %s% ; 0
|
http://rosettacode.org/wiki/Set
|
Set
|
Data Structure
This illustrates a data structure, a means of storing data within a program.
You may see other such structures in the Data Structures category.
A set is a collection of elements, without duplicates and without order.
Task
Show each of these set operations:
Set creation
Test m ∈ S -- "m is an element in set S"
A ∪ B -- union; a set of all elements either in set A or in set B.
A ∩ B -- intersection; a set of all elements in both set A and set B.
A ∖ B -- difference; a set of all elements in set A, except those in set B.
A ⊆ B -- subset; true if every element in set A is also in set B.
A = B -- equality; true if every element of set A is in set B and vice versa.
As an option, show some other set operations.
(If A ⊆ B, but A ≠ B, then A is called a true or proper subset of B, written A ⊂ B or A ⊊ B.)
As another option, show how to modify a mutable set.
One might implement a set using an associative array (with set elements as array keys and some dummy value as the values).
One might also implement a set with a binary search tree, or with a hash table, or with an ordered array of binary bits (operated on with bit-wise binary operators).
The basic test, m ∈ S, is O(n) with a sequential list of elements, O(log n) with a balanced binary search tree, or (O(1) average-case, O(n) worst case) with a hash table.
See also
Array
Associative array: Creation, Iteration
Collections
Compound data type
Doubly-linked list: Definition, Element definition, Element insertion, List Traversal, Element Removal
Linked list
Queue: Definition, Usage
Set
Singly-linked list: Element definition, Element insertion, List Traversal, Element Removal
Stack
|
#AppleScript
|
AppleScript
|
use AppleScript version "2.4" -- OS X 10.10 (Yosemite) or later
use framework "Foundation"
--use scripting additions
on doSetTask()
-- 'set' at the beginnings of lines is an AppleScript command; nothing to do with sets.
set output to {}
set astid to AppleScript's text item delimiters
set AppleScript's text item delimiters to ", "
set S to current application's class "NSSet"'s setWithArray:({1, 2, 3, 6, 7, 8, 9, 0})
set end of output to "Set S: " & (S's allObjects() as list)
set end of output to "\"aardvark\" is a member of S: " & ((S's containsObject:("aardvark")) as boolean)
set end of output to "3 is a member of S: " & ((S's containsObject:(3)) as boolean)
set A to S's |copy|() -- or: set A to current application's class "NSSet"'s setWithArray:({1, 2, 3, 6, 7, 8, 9, 0})
set end of output to linefeed & "Set A: " & (A's allObjects() as list)
set B to current application's class "NSSet"'s setWithArray:({2, 2, 2, 3, 4, 5, 6, 7, 7, 7, 8})
set end of output to "Set B: " & (B's allObjects() as list)
set union to A's setByAddingObjectsFromSet:(B)
-- Or:
-- set union to A's mutableCopy()
-- tell union to unionSet:(B)
set end of output to "Union of A and B: " & (union's allObjects() as list)
set intersection to A's mutableCopy()
tell intersection to intersectSet:(B)
set end of output to "Intersection of A and B: " & (intersection's allObjects() as list)
set difference to A's mutableCopy()
tell difference to minusSet:(B)
set end of output to "Difference of A and B: " & (difference's allObjects() as list)
set end of output to "A is a subset of B: " & ((A's isSubsetOfSet:(B)) as boolean)
set end of output to "A is a subset of S: " & ((A's isSubsetOfSet:(S)) as boolean)
set end of output to "A is equal to B: " & ((A's isEqualToSet:(B)) as boolean)
set end of output to "A is equal to S: " & ((A's isEqualToSet:(S)) as boolean)
set AppleScript's text item delimiters to linefeed
set output to output as text
set AppleScript's text item delimiters to astid
return output
end doSetTask
doSetTask()
|
http://rosettacode.org/wiki/Send_an_unknown_method_call
|
Send an unknown method call
|
Task
Invoke an object method where the name of the method to be invoked can be generated at run time.
Related tasks
Respond to an unknown method call.
Runtime evaluation
|
#Kotlin
|
Kotlin
|
// Kotlin JS version 1.1.4-3
class C {
fun foo() {
println("foo called")
}
}
fun main(args: Array<String>) {
val c = C()
val f = "c.foo"
js(f)() // invokes c.foo dynamically
}
|
http://rosettacode.org/wiki/Send_an_unknown_method_call
|
Send an unknown method call
|
Task
Invoke an object method where the name of the method to be invoked can be generated at run time.
Related tasks
Respond to an unknown method call.
Runtime evaluation
|
#Lasso
|
Lasso
|
define mytype => type {
public foo() => {
return 'foo was called'
}
public bar() => {
return 'this time is was bar'
}
}
local(obj = mytype, methodname = tag('foo'), methodname2 = tag('bar'))
#obj->\#methodname->invoke
#obj->\#methodname2->invoke
|
http://rosettacode.org/wiki/Send_an_unknown_method_call
|
Send an unknown method call
|
Task
Invoke an object method where the name of the method to be invoked can be generated at run time.
Related tasks
Respond to an unknown method call.
Runtime evaluation
|
#Lingo
|
Lingo
|
obj = script("MyClass").new()
-- ...
method = #foo
arg1 = 23
res = call(method, obj, arg1)
|
http://rosettacode.org/wiki/Send_an_unknown_method_call
|
Send an unknown method call
|
Task
Invoke an object method where the name of the method to be invoked can be generated at run time.
Related tasks
Respond to an unknown method call.
Runtime evaluation
|
#Logtalk
|
Logtalk
|
:- object(foo).
:- public(bar/1).
bar(42).
:- end_object.
|
http://rosettacode.org/wiki/Send_an_unknown_method_call
|
Send an unknown method call
|
Task
Invoke an object method where the name of the method to be invoked can be generated at run time.
Related tasks
Respond to an unknown method call.
Runtime evaluation
|
#Lua
|
Lua
|
local example = { }
function example:foo (x) return 42 + x end
local name = "foo"
example[name](example, 5) --> 47
|
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
|
#Ada
|
Ada
|
with Ada.Text_IO, Ada.Command_Line;
procedure Eratos is
Last: Positive := Positive'Value(Ada.Command_Line.Argument(1));
Prime: array(1 .. Last) of Boolean := (1 => False, others => True);
Base: Positive := 2;
Cnt: Positive;
begin
while Base * Base <= Last loop
if Prime(Base) then
Cnt := Base + Base;
while Cnt <= Last loop
Prime(Cnt) := False;
Cnt := Cnt + Base;
end loop;
end if;
Base := Base + 1;
end loop;
Ada.Text_IO.Put("Primes less or equal" & Positive'Image(Last) &" are:");
for Number in Prime'Range loop
if Prime(Number) then
Ada.Text_IO.Put(Positive'Image(Number));
end if;
end loop;
end Eratos;
|
http://rosettacode.org/wiki/Sequence_of_primorial_primes
|
Sequence of primorial primes
|
The sequence of primorial primes is given as the increasing values of n where primorial(n) ± 1 is prime.
Noting that the n'th primorial is defined as the multiplication of the smallest n primes, the sequence is of the number of primes, in order that when multiplied together is one-off being a prime number itself.
Task
Generate and show here the first ten values of the sequence.
Optional extended task
Show the first twenty members of the series.
Notes
This task asks for the primorial indices that create the final primorial prime numbers, so there should be no ten-or-more digit numbers in the program output (although extended precision integers will be needed for intermediate results).
There is some confusion in the references, but for the purposes of this task the sequence begins with n = 1.
Probabilistic primality tests are allowed, as long as they are good enough such that the output shown is correct.
Related tasks
Primorial numbers
Factorial
See also
Primorial prime Wikipedia.
Primorial prime from The Prime Glossary.
Sequence A088411 from The On-Line Encyclopedia of Integer Sequences
|
#Mathematica_.2F_Wolfram_Language
|
Mathematica / Wolfram Language
|
primorials = Rest@FoldList[Times, 1, Prime[Range[500]]];
primorials = MapIndexed[{{First[#2], #1 - 1}, {First[#2], #1 + 1}} &, primorials];
Select[primorials, AnyTrue[#[[All, 2]], PrimeQ] &][[All, 1, 1]]
|
http://rosettacode.org/wiki/Sequence_of_primorial_primes
|
Sequence of primorial primes
|
The sequence of primorial primes is given as the increasing values of n where primorial(n) ± 1 is prime.
Noting that the n'th primorial is defined as the multiplication of the smallest n primes, the sequence is of the number of primes, in order that when multiplied together is one-off being a prime number itself.
Task
Generate and show here the first ten values of the sequence.
Optional extended task
Show the first twenty members of the series.
Notes
This task asks for the primorial indices that create the final primorial prime numbers, so there should be no ten-or-more digit numbers in the program output (although extended precision integers will be needed for intermediate results).
There is some confusion in the references, but for the purposes of this task the sequence begins with n = 1.
Probabilistic primality tests are allowed, as long as they are good enough such that the output shown is correct.
Related tasks
Primorial numbers
Factorial
See also
Primorial prime Wikipedia.
Primorial prime from The Prime Glossary.
Sequence A088411 from The On-Line Encyclopedia of Integer Sequences
|
#Nim
|
Nim
|
import strutils, sugar
import bignum
## Run a sieve of Erathostenes.
const N = 4000
var isComposite: array[2..N, bool] # False (default) means "is prime".
for n in 2..isComposite.high:
if not isComposite[n]:
for k in countup(n * n, N, n):
isComposite[k] = true
# Collect the list of primes.
let primes = collect(newSeq):
for n, comp in isComposite:
if not comp:
n
iterator primorials(): Int =
## Yield the successive primorial numbers.
var result = newInt(1)
for prime in primes:
result *= prime
yield result
template isPrime(n: Int): bool =
## Return true if "n" is certainly or probably prime.
## Use the probabilistic test provided by "bignum" (i.e. "gmp" probabilistic test).
probablyPrime(n, 25) != 0
func isPrimorialPrime(n: Int): bool =
## Return true if "n" is a primorial prime.
(n - 1).isPrime or (n + 1).isPrime
const Lim = 20 # Number of indices to keep.
var idx = 0 # Primorial index.
var indices = newSeqOfCap[int](Lim) # List of indices.
for p in primorials():
inc idx
if p.isPrimorialPrime():
indices.add idx
if indices.len == LIM: break
echo indices.join(" ")
|
http://rosettacode.org/wiki/Sequence:_nth_number_with_exactly_n_divisors
|
Sequence: nth number with exactly n divisors
|
Calculate the sequence where each term an is the nth that has n divisors.
Task
Show here, on this page, at least the first 15 terms of the sequence.
See also
OEIS:A073916
Related tasks
Sequence: smallest number greater than previous term with exactly n divisors
Sequence: smallest number with exactly n divisors
|
#Ring
|
Ring
|
load "stdlib.ring"
num = 0
limit = 22563490300366186081
see "working..." + nl
see "the first 15 terms of the sequence are:" + nl
for n = 1 to 15
num = 0
for m = 1 to limit
pnum = 0
for p = 1 to limit
if (m % p = 0)
pnum = pnum + 1
ok
next
if pnum = n
num = num + 1
if num = n
see "" + n + ": " + m + " " + nl
exit
ok
ok
next
next
see nl + "done..." + nl
|
http://rosettacode.org/wiki/Sequence:_nth_number_with_exactly_n_divisors
|
Sequence: nth number with exactly n divisors
|
Calculate the sequence where each term an is the nth that has n divisors.
Task
Show here, on this page, at least the first 15 terms of the sequence.
See also
OEIS:A073916
Related tasks
Sequence: smallest number greater than previous term with exactly n divisors
Sequence: smallest number with exactly n divisors
|
#Ruby
|
Ruby
|
def isPrime(n)
return false if n < 2
return n == 2 if n % 2 == 0
return n == 3 if n % 3 == 0
k = 5
while k * k <= n
return false if n % k == 0
k = k + 2
end
return true
end
def getSmallPrimes(numPrimes)
smallPrimes = [2]
count = 0
n = 3
while count < numPrimes
if isPrime(n) then
smallPrimes << n
count = count + 1
end
n = n + 2
end
return smallPrimes
end
def getDivisorCount(n)
count = 1
while n % 2 == 0
n = (n / 2).floor
count = count + 1
end
d = 3
while d * d <= n
q = (n / d).floor
r = n % d
dc = 0
while r == 0
dc = dc + count
n = q
q = (n / d).floor
r = n % d
end
count = count + dc
d = d + 2
end
if n != 1 then
count = 2 * count
end
return count
end
MAX = 15
@smallPrimes = getSmallPrimes(MAX)
def OEISA073916(n)
if isPrime(n) then
return @smallPrimes[n - 1] ** (n - 1)
end
count = 0
result = 0
i = 1
while count < n
if n % 2 == 1 then
# The solution for an odd (non-prime) term is always a square number
root = Math.sqrt(i)
if root * root != i then
i = i + 1
next
end
end
if getDivisorCount(i) == n then
count = count + 1
result = i
end
i = i + 1
end
return result
end
n = 1
while n <= MAX
print "A073916(", n, ") = ", OEISA073916(n), "\n"
n = n + 1
end
|
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
|
#jq
|
jq
|
def to_set: unique;
def union(A; B): (A + B) | unique;
# boolean
def intersect(A;B):
reduce A[] as $x (false; if . then . else (B|index($x)) end) | not | not;
|
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
|
#Julia
|
Julia
|
function consolidate{T}(a::Array{Set{T},1})
1 < length(a) || return a
b = copy(a)
c = Set{T}[]
while 1 < length(b)
x = shift!(b)
cme = true
for (i, y) in enumerate(b)
!isempty(intersect(x, y)) || continue
cme = false
b[i] = union(x, y)
break
end
!cme || push!(c, x)
end
push!(c, b[1])
return c
end
|
http://rosettacode.org/wiki/Sequence:_smallest_number_with_exactly_n_divisors
|
Sequence: smallest number with exactly n divisors
|
Calculate the sequence where each term an is the smallest natural number that has exactly n divisors.
Task
Show here, on this page, at least the first 15 terms of the sequence.
Related tasks
Sequence: smallest number greater than previous term with exactly n divisors
Sequence: nth number with exactly n divisors
See also
OEIS:A005179
|
#Nanoquery
|
Nanoquery
|
def count_divisors(n)
count = 0
for (i = 1) ((i * i) <= n) (i += 1)
if (n % i) = 0
if i = (n / i)
count += 1
else
count += 2
end
end
end
return count
end
max = 15
seq = {0} * max
print format("The first %d terms of the sequence are:\n", max)
i = 1
for (n = 0) (n < max) (i += 1)
k = count_divisors(i)
if (k <= max)
if seq[k - 1] = 0
seq[k - 1] = i
n += 1
end
end
end
println seq
|
http://rosettacode.org/wiki/Sequence:_smallest_number_with_exactly_n_divisors
|
Sequence: smallest number with exactly n divisors
|
Calculate the sequence where each term an is the smallest natural number that has exactly n divisors.
Task
Show here, on this page, at least the first 15 terms of the sequence.
Related tasks
Sequence: smallest number greater than previous term with exactly n divisors
Sequence: nth number with exactly n divisors
See also
OEIS:A005179
|
#Nim
|
Nim
|
import strformat
const MAX = 15
func countDivisors(n: int): int =
var count = 0
var i = 1
while i * i <= n:
if n mod i == 0:
if i == n div i:
inc count, 1
else:
inc count, 2
inc i
count
var sequence: array[MAX, int]
echo fmt"The first {MAX} terms of the sequence are:"
var i = 1
var n = 0
while n < MAX:
var k = countDivisors(i)
if k <= MAX and sequence[k - 1] == 0:
sequence[k - 1] = i
inc n
inc i
echo sequence
|
http://rosettacode.org/wiki/SHA-256
|
SHA-256
|
SHA-256 is the recommended stronger alternative to SHA-1. See FIPS PUB 180-4 for implementation details.
Either by using a dedicated library or implementing the algorithm in your language, show that the SHA-256 digest of the string "Rosetta code" is: 764faf5c61ac315f1497f9dfa542713965b785e5cc2f707d6468d7d1124cdfcf
|
#Pike
|
Pike
|
string input = "Rosetta code";
string out = Crypto.SHA256.hash(input);
write( String.string2hex(out) +"\n");
|
http://rosettacode.org/wiki/SHA-256
|
SHA-256
|
SHA-256 is the recommended stronger alternative to SHA-1. See FIPS PUB 180-4 for implementation details.
Either by using a dedicated library or implementing the algorithm in your language, show that the SHA-256 digest of the string "Rosetta code" is: 764faf5c61ac315f1497f9dfa542713965b785e5cc2f707d6468d7d1124cdfcf
|
#PowerShell
|
PowerShell
|
Set-Content -Value "Rosetta code" -Path C:\Colors\blue.txt -NoNewline -Force
Get-FileHash -Path C:\Colors\blue.txt -Algorithm SHA256
|
http://rosettacode.org/wiki/Sequence:_smallest_number_greater_than_previous_term_with_exactly_n_divisors
|
Sequence: smallest number greater than previous term with exactly n divisors
|
Calculate the sequence where each term an is the smallest natural number greater than the previous term, that has exactly n divisors.
Task
Show here, on this page, at least the first 15 terms of the sequence.
See also
OEIS:A069654
Related tasks
Sequence: smallest number with exactly n divisors
Sequence: nth number with exactly n divisors
|
#R
|
R
|
#Need to add 1 to account for skipping n. Not the most efficient way to count divisors, but quite clear.
divisorCount <- function(n) length(Filter(function(x) n %% x == 0, seq_len(n %/% 2))) + 1
A06954 <- function(terms)
{
out <- 1
while((resultCount <- length(out)) != terms)
{
n <- resultCount + 1
out[n] <- out[resultCount]
while(divisorCount(out[n]) != n) out[n] <- out[n] + 1
}
out
}
print(A06954(15))
|
http://rosettacode.org/wiki/Sequence:_smallest_number_greater_than_previous_term_with_exactly_n_divisors
|
Sequence: smallest number greater than previous term with exactly n divisors
|
Calculate the sequence where each term an is the smallest natural number greater than the previous term, that has exactly n divisors.
Task
Show here, on this page, at least the first 15 terms of the sequence.
See also
OEIS:A069654
Related tasks
Sequence: smallest number with exactly n divisors
Sequence: nth number with exactly n divisors
|
#Raku
|
Raku
|
sub div-count (\x) {
return 2 if x.is-prime;
+flat (1 .. x.sqrt.floor).map: -> \d {
unless x % d { my \y = x div d; y == d ?? y !! (y, d) }
}
}
my $limit = 15;
my $m = 1;
put "First $limit terms of OEIS:A069654";
put (1..$limit).map: -> $n { my $ = $m = first { $n == .&div-count }, $m..Inf };
|
http://rosettacode.org/wiki/SHA-1
|
SHA-1
|
SHA-1 or SHA1 is a one-way hash function;
it computes a 160-bit message digest.
SHA-1 often appears in security protocols; for example,
many HTTPS websites use RSA with SHA-1 to secure their connections.
BitTorrent uses SHA-1 to verify downloads.
Git and Mercurial use SHA-1 digests to identify commits.
A US government standard, FIPS 180-1, defines SHA-1.
Find the SHA-1 message digest for a string of octets. You may either call a SHA-1 library, or implement SHA-1 in your language. Both approaches interest Rosetta Code.
Warning: SHA-1 has known weaknesses. Theoretical attacks may find a collision after 252 operations, or perhaps fewer.
This is much faster than a brute force attack of 280 operations. USgovernment deprecated SHA-1.
For production-grade cryptography, users may consider a stronger alternative, such as SHA-256 (from the SHA-2 family) or the upcoming SHA-3.
|
#Pike
|
Pike
|
string input = "Rosetta Code";
string out = Crypto.SHA1.hash(input);
write( String.string2hex(out) +"\n");
|
http://rosettacode.org/wiki/SHA-1
|
SHA-1
|
SHA-1 or SHA1 is a one-way hash function;
it computes a 160-bit message digest.
SHA-1 often appears in security protocols; for example,
many HTTPS websites use RSA with SHA-1 to secure their connections.
BitTorrent uses SHA-1 to verify downloads.
Git and Mercurial use SHA-1 digests to identify commits.
A US government standard, FIPS 180-1, defines SHA-1.
Find the SHA-1 message digest for a string of octets. You may either call a SHA-1 library, or implement SHA-1 in your language. Both approaches interest Rosetta Code.
Warning: SHA-1 has known weaknesses. Theoretical attacks may find a collision after 252 operations, or perhaps fewer.
This is much faster than a brute force attack of 280 operations. USgovernment deprecated SHA-1.
For production-grade cryptography, users may consider a stronger alternative, such as SHA-256 (from the SHA-2 family) or the upcoming SHA-3.
|
#PowerShell
|
PowerShell
|
Function Calculate-SHA1( $String ){
$Enc = [system.Text.Encoding]::UTF8
$Data = $enc.GetBytes($String)
# Create a New SHA1 Crypto Provider
$Sha = New-Object System.Security.Cryptography.SHA1CryptoServiceProvider
# Now hash and display results
$Result = $sha.ComputeHash($Data)
[System.Convert]::ToBase64String($Result)
}
|
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
|
#langur
|
langur
|
for .i of 16 {
for .j = 31 + .i ; .j < 128 ; .j += 16 {
val .L = given(.j; 32: "spc"; 127: "del"; cp2s .j)
write $"\.j:3; : \.L:-4;"
}
writeln()
}
|
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
|
#Locomotive_Basic
|
Locomotive Basic
|
10 mode 1:defint a-z
20 for x=1 to 6
30 for y=1 to 16
40 n=16*(x-1)+y+31
50 locate 6*(x-1)+1,y
60 print using "###";n;
70 print " ";chr$(n);
80 next
90 next
|
http://rosettacode.org/wiki/Sierpinski_triangle
|
Sierpinski triangle
|
Task
Produce an ASCII representation of a Sierpinski triangle of order N.
Example
The Sierpinski triangle of order 4 should look like this:
*
* *
* *
* * * *
* *
* * * *
* * * *
* * * * * * * *
* *
* * * *
* * * *
* * * * * * * *
* * * *
* * * * * * * *
* * * * * * * *
* * * * * * * * * * * * * * * *
Related tasks
Sierpinski triangle/Graphical for graphics images of this pattern.
Sierpinski carpet
|
#PureBasic
|
PureBasic
|
Procedure Triangle (X,Y, Length, N)
If N = 0
DrawText( Y,X, "*",#Blue)
Else
Triangle (X+Length, Y, Length/2, N-1)
Triangle (X, Y+Length, Length/2, N-1)
Triangle (X+Length, Y+Length*2, Length/2, N-1)
EndIf
EndProcedure
OpenWindow(0, 100, 100,700,500 ,"Sierpinski triangle", #PB_Window_SystemMenu |1)
StartDrawing(WindowOutput(0))
DrawingMode(#PB_2DDrawing_Transparent )
Triangle(10,10,120,5)
StopDrawing()
Repeat
Until WaitWindowEvent()=#PB_Event_CloseWindow
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
|
#Oforth
|
Oforth
|
: carpet(n)
| dim i j k |
3 n pow ->dim
0 dim 1 - for: i [
0 dim 1 - for: j [
dim 3 / ->k
while(k) [
i k 3 * mod k / 1 == j k 3 * mod k / 1 == and ifTrue: [ break ]
k 3 / ->k
]
k ifTrue: [ " " ] else: [ "#" ] print
]
printcr
] ;
|
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
|
#Aime
|
Aime
|
integer p, z;
record r;
file f;
text s, t;
f.affix("unixdict.txt");
p = 0;
while (f.line(s) != -1) {
if (r_o_integer(z, r, t = b_reverse(s))) {
p += 1;
if (p <= 5) {
o_(s, " ", t, "\n");
}
}
r[s] = 0;
}
o_form("Semordnilap pairs: ~\n", p);
|
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
|
#ALGOL_68
|
ALGOL 68
|
# find the semordnilaps in a list of words #
# use the associative array in the Associate array/iteration task #
PR read "aArray.a68" PR
# returns text with the characters reversed #
OP REVERSE = ( STRING text )STRING:
BEGIN
STRING reversed := text;
INT start pos := LWB text;
FOR end pos FROM UPB reversed BY -1 TO LWB reversed
DO
reversed[ end pos ] := text[ start pos ];
start pos +:= 1
OD;
reversed
END # REVERSE # ;
# read the list of words and store the words in an associative array #
# check for semordnilaps #
IF FILE input file;
STRING file name = "unixdict.txt";
open( input file, file name, stand in channel ) /= 0
THEN
# failed to open the file #
print( ( "Unable to open """ + file name + """", newline ) )
ELSE
# file opened OK #
BOOL at eof := FALSE;
# set the EOF handler for the file #
on logical file end( input file, ( REF FILE f )BOOL:
BEGIN
# note that we reached EOF on the #
# latest read #
at eof := TRUE;
# return TRUE so processing can continue #
TRUE
END
);
REF AARRAY words := INIT LOC AARRAY;
STRING word;
INT semordnilap count := 0;
WHILE NOT at eof
DO
STRING word;
get( input file, ( word, newline ) );
STRING reversed word = REVERSE word;
IF ( words // reversed word ) = ""
THEN
# the reversed word isn't in the array #
words // word := reversed word
ELSE
# we already have this reversed - we have a semordnilap #
semordnilap count +:= 1;
IF semordnilap count <= 5
THEN
print( ( reversed word, " & ", word, newline ) )
FI
FI
OD;
close( input file );
print( ( whole( semordnilap count, 0 ), " semordnilaps found", newline ) )
FI
|
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.
|
#PL.2FI
|
PL/I
|
short_circuit_evaluation:
procedure options (main);
declare (true initial ('1'b), false initial ('0'b) ) bit (1);
declare (i, j, x, y) bit (1);
a: procedure (bv) returns (bit(1));
declare bv bit(1);
put ('Procedure ' || procedurename() || ' called.');
return (bv);
end a;
b: procedure (bv) returns (bit(1));
declare bv bit(1);
put ('Procedure ' || procedurename() || ' called.');
return (bv);
end b;
do i = true, false;
do j = true, false;
put skip(2) list ('Evaluating x with <a> with ' || i || ' and <b> with ' || j);
put skip;
if a(i) then
x = b(j);
else
x = false;
put skip data (x);
put skip(2) list ('Evaluating y with <a> with ' || i || ' and <b> with ' || j);
put skip;
if a(i) then
y = true;
else
y = b(j);
put skip data (y);
end;
end;
end short_circuit_evaluation;
|
http://rosettacode.org/wiki/Selectively_replace_multiple_instances_of_a_character_within_a_string
|
Selectively replace multiple instances of a character within a string
|
Task
This is admittedly a trivial task but I thought it would be interesting to see how succinctly (or otherwise) different languages can handle it.
Given the string: "abracadabra", replace programatically:
the first 'a' with 'A'
the second 'a' with 'B'
the fourth 'a' with 'C'
the fifth 'a' with 'D'
the first 'b' with 'E'
the second 'r' with 'F'
Note that there is no replacement for the third 'a', second 'b' or first 'r'.
The answer should, of course, be : "AErBcadCbFD".
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
|
#J
|
J
|
upd=: {{ x (n{I.y=m)} y }}
'ABCD' 'a' upd 0 1 3 4 'E' 'b' upd 0 'F' 'r' upd 1 'abracadabra'
AErBcadCbFD
|
http://rosettacode.org/wiki/Selectively_replace_multiple_instances_of_a_character_within_a_string
|
Selectively replace multiple instances of a character within a string
|
Task
This is admittedly a trivial task but I thought it would be interesting to see how succinctly (or otherwise) different languages can handle it.
Given the string: "abracadabra", replace programatically:
the first 'a' with 'A'
the second 'a' with 'B'
the fourth 'a' with 'C'
the fifth 'a' with 'D'
the first 'b' with 'E'
the second 'r' with 'F'
Note that there is no replacement for the third 'a', second 'b' or first 'r'.
The answer should, of course, be : "AErBcadCbFD".
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
|
#Julia
|
Julia
|
rep = Dict('a' => Dict(1 => 'A', 2 => 'B', 4 => 'C', 5 => 'D'), 'b' => Dict(1 => 'E'), 'r' => Dict(2 => 'F'))
function trstring(oldstring, repdict)
seen, newchars = Dict{Char, Int}(), Char[]
for c in oldstring
i = get!(seen, c, 1)
push!(newchars, haskey(repdict, c) && haskey(repdict[c], i) ? repdict[c][i] : c)
seen[c] += 1
end
return String(newchars)
end
println("abracadabra -> ", trstring("abracadabra", rep))
|
http://rosettacode.org/wiki/Selectively_replace_multiple_instances_of_a_character_within_a_string
|
Selectively replace multiple instances of a character within a string
|
Task
This is admittedly a trivial task but I thought it would be interesting to see how succinctly (or otherwise) different languages can handle it.
Given the string: "abracadabra", replace programatically:
the first 'a' with 'A'
the second 'a' with 'B'
the fourth 'a' with 'C'
the fifth 'a' with 'D'
the first 'b' with 'E'
the second 'r' with 'F'
Note that there is no replacement for the third 'a', second 'b' or first 'r'.
The answer should, of course, be : "AErBcadCbFD".
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
|
#Lambdatalk
|
Lambdatalk
|
the first 'a' with 'A' -> aA1
...and so on
|
http://rosettacode.org/wiki/Selectively_replace_multiple_instances_of_a_character_within_a_string
|
Selectively replace multiple instances of a character within a string
|
Task
This is admittedly a trivial task but I thought it would be interesting to see how succinctly (or otherwise) different languages can handle it.
Given the string: "abracadabra", replace programatically:
the first 'a' with 'A'
the second 'a' with 'B'
the fourth 'a' with 'C'
the fifth 'a' with 'D'
the first 'b' with 'E'
the second 'r' with 'F'
Note that there is no replacement for the third 'a', second 'b' or first 'r'.
The answer should, of course, be : "AErBcadCbFD".
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
|
#Perl
|
Perl
|
use strict;
use warnings;
use feature 'say';
sub transmogrify {
my($str, %sub) = @_;
for my $l (keys %sub) {
$str =~ s/$l/$_/ for split '', $sub{$l};
$str =~ s/_/$l/g;
}
$str
}
my $word = 'abracadabra';
say "$word -> " . transmogrify $word, 'a' => 'AB_CD', 'r' => '_F', 'b' => 'E';
|
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)
|
#Diego
|
Diego
|
begin_instruct(Send email)_param({str} from, to, cc, subject, msg, {html}, htmlmsg)_opt({cred}, login)_ns(rosettacode);
set_thread(linger);
find_thing()_first()_email()
? with_found()_label(emailer);
: exit_instruct[]_err(Sorry, no one can send emails!);
;
with_[emailer]_format(html)
? with_[emailer]_cred[login]_email[htmlmsg]_from[from]_to[to]_cc[cc]_subject[subject];
: exit_instruct[]_err(Something went wrong with the email);
: with_[emailer]_cred[login]_email[msg]_from[from]_to[to]_cc[cc]_subject[subject];
: exit_instruct[]_err(Something went wrong with the email);
;
reset_thread();
end_instruct[];
set_namespace(rosettacode);
// Set up credentials
add_var({cred}, mycred)_server(esvr1)_username(bob)_password(p@$$w0rd); // Other credentials can be added here
// Send email:
exec_instruct(Send email)_param()
_from([email protected]) // It is at the discretion of the caller to use this from address
_to([email protected])
_cc([email protected])
_subject(Rosettacode wants me to send an email!)
_msg(This is the body of my email.)
_htmlmsg(<b>This is the body of my email, in bold</b>)
_login[mycred]
_me();
reset_namespace();
|
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)
|
#Emacs_Lisp
|
Emacs Lisp
|
(defun my-send-email (from to cc subject text)
(with-temp-buffer
(insert "From: " from "\n"
"To: " to "\n"
"Cc: " cc "\n"
"Subject: " subject "\n"
mail-header-separator "\n"
text)
(funcall send-mail-function)))
(my-send-email "[email protected]" "[email protected]" ""
"very important"
"body\ntext\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.
|
#Arturo
|
Arturo
|
semiPrime?: function [x][
2 = size factors.prime x
]
print select 1..100 => semiPrime?
|
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.
|
#AutoHotkey
|
AutoHotkey
|
SetBatchLines -1
k := 1
loop, 100
{
m := semiprime(k)
StringSplit, m_m, m, -
if ( m_m1 = "yes" )
list .= k . " "
k++
}
MsgBox % list
list :=
;===================================================================================================================================
k := 1675
loop, 5
{
m := semiprime(k)
StringSplit, m_m, m, -
if ( m_m1 = "yes" )
list1 .= semiprime(k) . "`n"
else
list1 .= semiprime(k) . "`n"
k++
}
MsgBox % list1
list1 :=
;===================================================================================================================================
; The function==========================================================================================================================
semiprime(k)
{
start := floor(sqrt(k))
loop, % floor(sqrt(k)) - 1
{
if ( mod(k, start) = 0 )
new .= floor(start) . "*" . floor(k//start) . ","
start--
}
StringSplit, index, new, `,
if ( index0 = 2 )
{
StringTrimRight, new, new, 1
StringSplit, 2_ind, new, *
if (mod(2_ind2, 2_ind1) = 0) && ( 2_ind1 != 2_ind2 )
new := "N0- " . k . " - " . new
else
new := "yes- " . k . " - " . new
}
else
new := "N0- " . k . " - " . new
return new
}
;=================================================================================================================================================
esc::Exitapp
|
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
|
#360_Assembly
|
360 Assembly
|
* Self-describing numbers 26/04/2020
SELFDESC CSECT
USING SELFDESC,R13 base register
B 72(R15) skip savearea
DC 17F'0' savearea
SAVE (14,12) save previous context
ST R13,4(R15) link backward
ST R15,8(R13) link forward
LR R13,R15 set addressability
LA R8,1 k=1
DO WHILE=(C,R8,LE,=A(NN)) do k=1 to nn
CVD R8,DBLK binary to packed decimal (PL8)
MVC CK,MAK load mask
EDMK CK,DBLK+2 packed dec (PL5) to char (CL10)
S R1,=A(CK) number of blanks
LR R3,R1 "
LA R9,L'CK length(ck)
SR R9,R1 length of the number
LA R6,1 i=1
DO WHILE=(CR,R6,LE,R9) do i=1 to l
LA R10,0 n=0
LA R7,1 j=1
DO WHILE=(CR,R7,LE,R9) do j=1 to l
LA R1,CK-1 @ck
AR R1,R3 +space(k)
AR R1,R7 +j
MVC CJ,0(R1) substr(k,j,1)
IC R1,CJ ~
SLL R1,28 shift left 28
SRL R1,28 shift right 28
LR R2,R6 i
BCTR R2,0 i-1
IF CR,R1,EQ,R2 THEN if substr(k,j,1)=i-1 then
LA R10,1(R10) n++
ENDIF , endif
LA R7,1(R7) j++
ENDDO , enddo j
LA R1,CK-1 @ck
AR R1,R3 +space(k)
AR R1,R6 +i
MVC CI,0(R1) substr(k,i,1)
IC R1,CI ~
SLL R1,28 shift left 28
SRL R1,28 shift right 28
IF CR,R1,NE,R10 THEN if substr(k,i,1)<>n then
B ITERK iterate k
ENDIF , endif
LA R6,1(R6) i++
ENDDO , enddo i
XPRNT CK,L'CK print ck
ITERK LA R8,1(R8) k++
ENDDO , enddo k
L R13,4(0,R13) restore previous savearea pointer
RETURN (14,12),RC=0 restore registers from calling save
NN EQU 5000000 nn
DBLK DS PL8 double word 15num
MAK DC X'402020202020202020202020' mask CL12 11num
CK DS CL12 ck 12num
CI DS C ci
CJ DS C cj
PG DS CL80 buffer
XDEC DS CL12 temp fo xdeco
REGEQU
END SELFDESC
|
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
|
#Ada
|
Ada
|
with Ada.Text_IO; use Ada.Text_IO;
procedure SelfDesc is
subtype Desc_Int is Long_Integer range 0 .. 10**10-1;
function isDesc (innum : Desc_Int) return Boolean is
subtype S_Int is Natural range 0 .. 10;
type S_Int_Arr is array (0 .. 9) of S_Int;
ref, cnt : S_Int_Arr := (others => 0);
n, digit : S_Int := 0; num : Desc_Int := innum;
begin
loop
digit := S_Int (num mod 10);
ref (9 - n) := digit; cnt (digit) := cnt (digit) + 1;
num := num / 10; exit when num = 0; n := n + 1;
end loop;
return ref (9 - n .. 9) = cnt (0 .. n);
end isDesc;
begin
for i in Desc_Int range 1 .. 100_000_000 loop
if isDesc (i) then
Put_Line (Desc_Int'Image (i));
end if;
end loop;
end SelfDesc;
|
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
|
#AppleScript
|
AppleScript
|
(*
Base-10 self numbers by index (single or range).
Follows an observed sequence pattern whereby, after the initial single-digit odd numbers, self numbers are
grouped in runs whose members occur at numeric intervals of 11. Runs after the first one come in blocks of
ten: eight runs of ten numbers followed by two shorter runs. The numeric interval between runs is usually 2,
but that between shorter runs, and their length, depend on the highest-order digit change occurring in them.
This connection with significant digit change means every ten blocks form a higher-order block, every ten
of these a higher-order-still block, and so on.
The code below appears to be good up to the last self number before 10^12 — ie. 999,999,999,997, which is
returned as the 97,777,777,792nd such number. After this, instead of zero-length shorter runs, the actual
pattern apparently starts again with a single run of 10, like the one at the beginning.
*)
on selfNumbers(indexRange)
set indexRange to indexRange as list
-- Script object with subhandlers and associated properties.
script |subscript|
property startIndex : beginning of indexRange
property endIndex : end of indexRange
property counter : 0
property currentSelf : -1
property output : {}
-- Advance to the next self number in the sequence, append it to the output if required, indicate if finished.
on doneAfterAdding(interval)
set currentSelf to currentSelf + interval
set counter to counter + 1
if (counter < startIndex) then return false
set end of my output to currentSelf
return (counter = endIndex)
end doneAfterAdding
-- If necessary, fast forward to the last self number before the lowest-order block containing the first number required.
on fastForward()
if (counter ≥ startIndex) then return
-- The highest-order blocks whose ends this script handles correctly contain 9,777,777,778 self numbers.
-- The difference between equivalently positioned numbers in these blocks is 100,000,000,001.
-- The figures for successively lower-order blocks have successively fewer 7s and 0s!
set indexDiff to 9.777777778E+9
set numericDiff to 1.00000000001E+11
repeat until ((indexDiff < 98) or (counter = startIndex))
set test to counter + indexDiff
if (test < startIndex) then
set counter to test
set currentSelf to (currentSelf + numericDiff)
else
set indexDiff to (indexDiff + 2) div 10
set numericDiff to numericDiff div 10 + 1
end if
end repeat
end fastForward
-- Work out a shorter run length based on the most significant digit change about to happen.
on getShorterRunLength()
set shorterRunLength to 9
set temp to (|subscript|'s currentSelf) div 1000
repeat while (temp mod 10 is 9)
set shorterRunLength to shorterRunLength - 1
set temp to temp div 10
end repeat
return shorterRunLength
end getShorterRunLength
end script
-- Main process. Start with the single-digit odd numbers and first run.
repeat 5 times
if (|subscript|'s doneAfterAdding(2)) then return |subscript|'s output
end repeat
repeat 9 times
if (|subscript|'s doneAfterAdding(11)) then return |subscript|'s output
end repeat
-- Fast forward if the start index hasn't yet been reached.
tell |subscript| to fastForward()
-- Sequencing loop, per lowest-order block.
repeat
-- Eight ten-number runs, each at a numeric interval of 2 from the end of the previous one.
repeat 8 times
if (|subscript|'s doneAfterAdding(2)) then return |subscript|'s output
repeat 9 times
if (|subscript|'s doneAfterAdding(11)) then return |subscript|'s output
end repeat
end repeat
-- Two shorter runs, the second at an interval inversely related to their length.
set shorterRunLength to |subscript|'s getShorterRunLength()
repeat with interval in {2, 2 + (10 - shorterRunLength) * 13}
if (|subscript|'s doneAfterAdding(interval)) then return |subscript|'s output
repeat (shorterRunLength - 1) times
if (|subscript|'s doneAfterAdding(11)) then return |subscript|'s output
end repeat
end repeat
end repeat
end selfNumbers
-- Demo calls:
-- First to fiftieth self numbers.
selfNumbers({1, 50})
--> {1, 3, 5, 7, 9, 20, 31, 42, 53, 64, 75, 86, 97, 108, 110, 121, 132, 143, 154, 165, 176, 187, 198, 209, 211, 222, 233, 244, 255, 266, 277, 288, 299, 310, 312, 323, 334, 345, 356, 367, 378, 389, 400, 411, 413, 424, 435, 446, 457, 468}
-- One hundred millionth:
selfNumbers(100000000)
--> {1.022727208E+9}
-- 97,777,777,792nd:
selfNumbers(9.7777777792E+10)
--> {9.99999999997E+11}
|
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.
|
#Haskell
|
Haskell
|
{- Not so functional representation of R sets (with IEEE Double), in a strange way -}
import Data.List
import Data.Maybe
data BracketType = OpenSub | ClosedSub
deriving (Show, Enum, Eq, Ord)
data RealInterval = RealInterval {left :: BracketType, right :: BracketType,
lowerBound :: Double, upperBound :: Double}
deriving (Eq)
type RealSet = [RealInterval]
posInf = 1.0/0.0 :: Double -- IEEE tricks
negInf = (-1.0/0.0) :: Double
set_R = RealInterval ClosedSub ClosedSub negInf posInf :: RealInterval
emptySet = [] :: [RealInterval]
instance Show RealInterval where
show x@(RealInterval _ _ y y')
| y == y' && (left x == right x) && (left x == ClosedSub) = "{" ++ (show y) ++ "}"
| otherwise = [['(', '[']!!(fromEnum $ left x)] ++ (show $ lowerBound x) ++
"," ++ (show $ upperBound x) ++ [[')', ']']!!(fromEnum $ right x)]
showList [x] = shows x
showList (h:t) = shows h . (" U " ++) . showList t
showList [] = (++ "(/)") -- empty set
construct_interval :: Char -> Double -> Double -> Char -> RealInterval
construct_interval '(' x y ')' = RealInterval OpenSub OpenSub x y
construct_interval '(' x y ']' = RealInterval OpenSub ClosedSub x y
construct_interval '[' x y ')' = RealInterval ClosedSub OpenSub x y
construct_interval _ x y _ = RealInterval ClosedSub ClosedSub x y
set_is_empty :: RealSet -> Bool
set_is_empty rs = (rs == emptySet)
set_in :: Double -> RealSet -> Bool
set_in x [] = False
set_in x rs =
isJust (find (\s ->
((lowerBound s < x) && (x < upperBound s)) ||
(x == lowerBound s && left s == ClosedSub) ||
(x == upperBound s && right s == ClosedSub))
rs)
-- max, min for pairs (double, bracket)
max_p :: (Double, BracketType) -> (Double, BracketType) -> (Double, BracketType)
min_p :: (Double, BracketType) -> (Double, BracketType) -> (Double, BracketType)
max_p p1@(x, y) p2@(x', y')
| x == x' = (x, max y y') -- closed is stronger than open
| x < x' = p2
| otherwise = p1
min_p p1@(x, y) p2@(x', y')
| x == x' = (x, min y y')
| x < x' = p1
| otherwise = p2
simple_intersection :: RealInterval -> RealInterval -> [RealInterval]
simple_intersection ri1@(RealInterval l_ri1 r_ri1 x1 y1) ri2@(RealInterval l_ri2 r_ri2 x2 y2)
| (y1 < x2) || (y2 < x1) = emptySet
| (y1 == x2) && ((fromEnum r_ri1) + (fromEnum l_ri2) /= 2) = emptySet
| (y2 == x1) && ((fromEnum r_ri2) + (fromEnum l_ri1) /= 2) = emptySet
| otherwise = let lb = if x1 == x2 then (x1, min l_ri1 l_ri2) else max_p (x1, l_ri1) (x2, l_ri2) in
let rb = min_p (y1, right ri1) (y2, right ri2) in
[RealInterval (snd lb) (snd rb) (fst lb) (fst rb)]
simple_union :: RealInterval -> RealInterval -> [RealInterval]
simple_union ri1@(RealInterval l_ri1 r_ri1 x1 y1) ri2@(RealInterval l_ri2 r_ri2 x2 y2)
| (y1 < x2) || (y2 < x1) = [ri2, ri1]
| (y1 == x2) && ((fromEnum r_ri1) + (fromEnum l_ri2) /= 2) = [ri1, ri2]
| (y2 == x1) && ((fromEnum r_ri2) + (fromEnum l_ri1) /= 2) = [ri1, ri2]
| otherwise = let lb = if x1 == x2 then (x1, max l_ri1 l_ri2) else min_p (x1, l_ri1) (x2, l_ri2) in
let rb = max_p (y1, right ri1) (y2, right ri2) in
[RealInterval (snd lb) (snd rb) (fst lb) (fst rb)]
simple_complement :: RealInterval -> [RealInterval]
simple_complement ri1@(RealInterval l_ri1 r_ri1 x1 y1) =
[(RealInterval ClosedSub (inv l_ri1) negInf x1), (RealInterval (inv r_ri1) ClosedSub y1 posInf)]
where
inv OpenSub = ClosedSub
inv ClosedSub = OpenSub
set_sort :: RealSet -> RealSet
set_sort rs =
sortBy
(\s1 s2 ->
let (lp, rp) = ((lowerBound s1, left s1), (lowerBound s2, left s2)) in
if max_p lp rp == lp then GT else LT)
rs
set_simplify :: RealSet -> RealSet
set_simplify [] = emptySet
set_simplify rs =
concat (map make_empty (set_sort (foldl
(\acc ri1 -> (simple_union (head acc) ri1) ++ (tail acc))
[head sorted_rs]
sorted_rs)))
where
sorted_rs = set_sort rs
make_empty ri@(RealInterval lb rb x y)
| x >= y && (lb /= rb || rb /= ClosedSub) = emptySet
| otherwise = [ri]
-- set operations
set_complement :: RealSet -> RealSet
set_union :: RealSet -> RealSet -> RealSet
set_intersection :: RealSet -> RealSet -> RealSet
set_difference :: RealSet -> RealSet -> RealSet
set_measure :: RealSet -> Double
set_complement rs =
foldl set_intersection [set_R] (map simple_complement rs)
set_union rs1 rs2 =
set_simplify (rs1 ++ rs2)
set_intersection rs1 rs2 =
set_simplify $ concat [simple_intersection s1 s2 | s1 <- rs1, s2 <- rs2]
set_difference rs1 rs2 =
set_intersection (set_complement rs2) rs1
set_measure rs =
foldl (\acc x -> acc + (upperBound x) - (lowerBound x)) 0.0 rs
-- test
test = map (\x -> [x]) [construct_interval '(' 0 1 ']', construct_interval '[' 0 2 ')',
construct_interval '[' 0 2 ')', construct_interval '(' 1 2 ']',
construct_interval '[' 0 3 ')', construct_interval '(' 0 1 ')',
construct_interval '[' 0 3 ')', construct_interval '[' 0 1 ']']
restest = [set_union (test!!0) (test!!1), set_intersection (test!!2) (test!!3),
set_difference (test!!4) (test!!5), set_difference (test!!6) (test!!7)]
isintest s =
mapM_
(\x -> putStrLn ((show x) ++ " is in " ++ (show s) ++ " : " ++ (show (set_in x s))))
[0, 1, 2]
testA = [construct_interval '(' (sqrt (n + (1.0/6))) (sqrt (n + (5.0/6))) ')' | n <- [0..99]]
testB = [construct_interval '(' (n + (1.0/6)) (n + (5.0/6)) ')' | n <- [0..9]]
main =
putStrLn ("union " ++ (show (test!!0)) ++ " " ++ (show (test!!1)) ++ " = " ++ (show (restest!!0))) >>
putStrLn ("inter " ++ (show (test!!2)) ++ " " ++ (show (test!!3)) ++ " = " ++ (show (restest!!1))) >>
putStrLn ("diff " ++ (show (test!!4)) ++ " " ++ (show (test!!5)) ++ " = " ++ (show (restest!!2))) >>
putStrLn ("diff " ++ (show (test!!6)) ++ " " ++ (show (test!!7)) ++ " = " ++ (show (restest!!3))) >>
mapM_ isintest restest >>
putStrLn ("measure: " ++ (show (set_measure (set_difference testA testB))))
|
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
|
#ATS
|
ATS
|
(*
// Lazy-evaluation:
// sieve for primes
*)
(* ****** ****** *)
//
// How to compile:
// with no GC:
// patscc -D_GNU_SOURCE -DATS_MEMALLOC_LIBC -o sieve sieve.dats
// with Boehm-GC:
// patscc -D_GNU_SOURCE -DATS_MEMALLOC_GCBDW -o sieve sieve.dats -lgc
//
(* ****** ****** *)
//
#include
"share/atspre_staload.hats"
//
(* ****** ****** *)
#define :: stream_cons
#define cons stream_cons
#define nil stream_nil
(* ****** ****** *)
//
fun
from{n:int} (n: int n)
:<!laz> stream (intGte(n)) = $delay (cons{intGte(n)}(n, from (n+1)))
//
(* ****** ****** *)
typedef N2 = intGte(2)
(* ****** ****** *)
fun sieve
(
ns: stream N2
) :<!laz>
stream (N2) = $delay
(
let
val-cons(n, ns) = !ns
in
cons{N2}(n, sieve (stream_filter_cloref<N2> (ns, lam x => g1int_nmod(x, n) > 0)))
end : stream_con (N2)
) // end of [sieve]
//
val primes: stream (N2) = sieve (from(2))
//
macdef prime_get (n) = stream_nth_exn (primes, ,(n))
//
implement
main0 () = begin
//
println! ("prime 1000 = ", prime_get (1000)) ; // = 7927
(*
println! ("prime 5000 = ", prime_get (5000)) ; // = 48619
println! ("prime 10000 = ", prime_get (10000)) ; // = 104743
*)
//
end // end of [main0]
(* ****** ****** *)
|
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
|
#AWK
|
AWK
|
# syntax: GAWK -f SEQUENCE_OF_PRIMES_BY_TRIAL_DIVISION.AWK
BEGIN {
low = 1
high = 100
for (i=low; i<=high; i++) {
if (is_prime(i) == 1) {
printf("%d ",i)
count++
}
}
printf("\n%d prime numbers found in range %d-%d\n",count,low,high)
exit(0)
}
function is_prime(x, i) {
if (x <= 1) {
return(0)
}
for (i=2; i<=int(sqrt(x)); i++) {
if (x % i == 0) {
return(0)
}
}
return(1)
}
|
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.
|
#AWK
|
AWK
|
$ awk 'func f(n){return(n+int(.5+sqrt(n)))}BEGIN{for(i=1;i<=22;i++)print i,f(i)}'
1 2
2 3
3 5
4 6
5 7
6 8
7 10
8 11
9 12
10 13
11 14
12 15
13 17
14 18
15 19
16 20
17 21
18 22
19 23
20 24
21 26
22 27
$ awk 'func f(n){return(n+int(.5+sqrt(n)))}BEGIN{for(i=1;i<100000;i++){n=f(i);r=int(sqrt(n));if(r*r==n)print n"is square"}}'
$
|
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
|
#Arturo
|
Arturo
|
a: [1 2 3 4]
b: [3 4 5 6]
print in? 3 a
print contains? b 3
print union a b
print intersection a b
print difference a b
print difference.symmetric a b
print a = b
print subset? [1 3] a
print subset?.proper [1 3] a
print subset? [1 3] [1 3]
print subset?.proper [1 3] [1 3]
print superset? a [1 3]
print superset?.proper a [1 3]
print superset? [1 3] [1 3]
print superset?.proper [1 3] [1 3]
|
http://rosettacode.org/wiki/Send_an_unknown_method_call
|
Send an unknown method call
|
Task
Invoke an object method where the name of the method to be invoked can be generated at run time.
Related tasks
Respond to an unknown method call.
Runtime evaluation
|
#Mathematica.2FWolfram_Language
|
Mathematica/Wolfram Language
|
ToExpression[Input["function? E.g. Sin",]][Input["value? E.g. 0.4123"]]
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.