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 ...
#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 ...
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...
#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...
#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 d...
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 R...
#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, nRe...
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 Bioin...
#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: * * * * * * * * * * * * * * * ...
#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: ########################### # ## ## ## ## ## ## ## ## # ########################### ### ###### ###### ### # # # ## # # ## # # # ### ###### ...
#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) ~...
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 ...
#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, an...
#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(...
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...
#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.fin...
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 f...
#Clojure
Clojure
(require '[postal.core :refer [send-message]])   (send-message {:host "smtp.gmail.com"  :ssl true  :user your_username  :pass your_password} {:from "you@yourdomain.com"  :to ["your_friend@example.com"]  :cc ["bob@builder.com" "dora@expl...
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 f...
#D
D
void main() { import std.net.curl;   auto s = SMTP("smtps://smtp.gmail.com"); s.setAuthentication("someuser@gmail.com", "somepassword"); s.mailTo = ["<friend@example.com>"]; s.mailFrom = "<someuser@gmail.com>"; 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 Arecib...
#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; ...
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 | ...
#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 <=...
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 | ...
#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) asse...
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...
#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 va...
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...
#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]; ...
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 "...
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...
#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'};   //Initia...
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(...
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...
#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...
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. T...
#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) || isp...
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. T...
#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 ...
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 ...
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...
#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))) ...
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...
#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(cou...
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" "5C...
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 ...
#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 = previou...
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 ...
#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 di...
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...
#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...
#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 (- ...
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 R...
#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 ",10...
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 Bioin...
#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) ...
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: * * * * * * * * * * * * * * * ...
#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, ...
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: ########################### # ## ## ## ## ## ## ## ## # ########################### ### ###### ###### ### # # # ## # # ## # # # ### ###### ...
#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...
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 ...
#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 ...
#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 ...
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, an...
#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, an...
#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...
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...
#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-n...
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...
#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) = Mi...
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...
#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 = st...
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 f...
#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 w...
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 Arecib...
#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...
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 ...
#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 d...
#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 :...
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 | ...
#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) } } f...
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...
#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...
#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 fo...
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!" els...
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...
#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...
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...
#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 :...
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. T...
#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. T...
#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 =...
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 ...
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 < num...
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...
#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...
#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) ...
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...
#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 ...
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...
#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:" v...
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 ...
#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]...
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 ...
#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...
#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...
#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) [Syst...
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 Bioin...
#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 Bioin...
#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: * * * * * * * * * * * * * * * ...
#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 t...
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: ########################### # ## ## ## ## ## ## ## ## # ########################### ### ###### ###### ### # # # ## # # ## # # # ### ###### ...
#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 ] pr...
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 ...
#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 ...
#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;...
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, an...
#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 (b...
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...
#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...
#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) ?...
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...
#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...
#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 f...
#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) ...
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 f...
#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 "from@example.com" "to...
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 Arecib...
#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 Arecib...
#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)...
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 ...
#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...
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 ...
#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,...
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 d...
#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 followe...
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 | ...
#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 ::...
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...
#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" ...
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...
#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...
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 squar...
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...
#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 supers...
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"]]