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/The_Twelve_Days_of_Christmas
The Twelve Days of Christmas
Task Write a program that outputs the lyrics of the Christmas carol The Twelve Days of Christmas. The lyrics can be found here. (You must reproduce the words in the correct order, but case, format, and punctuation are left to your discretion.) Other tasks related to string operations: Metrics Array length Stri...
#Go
Go
package main   import ( "fmt" )   func main() { days := []string{"first", "second", "third", "fourth", "fifth", "sixth", "seventh", "eighth", "ninth", "tenth", "eleventh", "twelfth"}   gifts := []string{"A Partridge in a Pear Tree", "Two Turtle Doves and", "Three French Hens", "Four Calling Birds", "Five Gold Ri...
http://rosettacode.org/wiki/Terminal_control/Coloured_text
Terminal control/Coloured text
Task Display a word in various colours on the terminal. The system palette, or colours such as Red, Green, Blue, Magenta, Cyan, and Yellow can be used. Optionally demonstrate: How the system should determine if the terminal supports colour Setting of the background colour How to cause blinking or flashing (if ...
#Lua
Lua
print("Normal \027[1mBold\027[0m \027[4mUnderline\027[0m \027[7mInverse\027[0m") colors = { 30,31,32,33,34,35,36,37,90,91,92,93,94,95,96,97 } for _,bg in ipairs(colors) do for _,fg in ipairs(colors) do io.write("\027["..fg..";"..(bg+10).."mX") end print("\027[0m") -- be nice, reset end
http://rosettacode.org/wiki/Synchronous_concurrency
Synchronous concurrency
The goal of this task is to create two concurrent activities ("Threads" or "Tasks", not processes.) that share data synchronously. Your language may provide syntax or libraries to perform concurrency. Different languages provide different implementations of concurrency, often with different names. Some languages use th...
#Aikido
Aikido
  monitor Queue { var items = [] public function put (item) { items.append (item) notify() }   public function get() { while (items.size() == 0) { wait() } var item = items[0] items <<= 1 return item }   public function close { ...
http://rosettacode.org/wiki/Synchronous_concurrency
Synchronous concurrency
The goal of this task is to create two concurrent activities ("Threads" or "Tasks", not processes.) that share data synchronously. Your language may provide syntax or libraries to perform concurrency. Different languages provide different implementations of concurrency, often with different names. Some languages use th...
#ALGOL_68
ALGOL 68
( STRING line; INT count := 0, errno; BOOL input complete := FALSE; SEMA output throttle = LEVEL 0, input throttle = LEVEL 1;   FILE input txt; errno := open(input txt, "input.txt", stand in channel);   PROC call back done = (REF FILE f) BOOL: ( input complete := TRUE ); on logical file end(input txt, c...
http://rosettacode.org/wiki/Table_creation/Postal_addresses
Table creation/Postal addresses
Task Create a table to store addresses. You may assume that all the addresses to be stored will be located in the USA.   As such, you will need (in addition to a field holding a unique identifier) a field holding the street address, a field holding the city, a field holding the state code, and a field holding the zip...
#FunL
FunL
import db.* import util.*   Class.forName( 'org.h2.Driver' ) conn = DriverManager.getConnection( 'jdbc:h2:mem:test', 'sa', '' ) statement = conn.createStatement()   statement.execute( ''' CREATE TABLE `user_data` ( `id` identity, `name` varchar(255) NOT NULL, `street` varchar(255) NOT NULL, `city` var...
http://rosettacode.org/wiki/Table_creation/Postal_addresses
Table creation/Postal addresses
Task Create a table to store addresses. You may assume that all the addresses to be stored will be located in the USA.   As such, you will need (in addition to a field holding a unique identifier) a field holding the street address, a field holding the city, a field holding the state code, and a field holding the zip...
#Go
Go
package main   import ( "database/sql" "fmt" "log"   _ "github.com/mattn/go-sqlite3" )   func main() { // task req: show database connection db, err := sql.Open("sqlite3", "rc.db") if err != nil { log.Print(err) return } defer db.Close() // task req: create table ...
http://rosettacode.org/wiki/Take_notes_on_the_command_line
Take notes on the command line
Take notes on the command line is part of Short Circuit's Console Program Basics selection. Invoking NOTES without commandline arguments displays the current contents of the local NOTES.TXT if it exists. If NOTES has arguments, the current date and time are appended to the local NOTES.TXT followed by a newline. Then al...
#BASIC
BASIC
IF LEN(COMMAND$) THEN OPEN "notes.txt" FOR APPEND AS 1 PRINT #1, DATE$, TIME$ PRINT #1, CHR$(9); COMMAND$ CLOSE ELSE d$ = DIR$("notes.txt") IF LEN(d$) THEN OPEN d$ FOR INPUT AS 1 WHILE NOT EOF(1) LINE INPUT #1, i$ PRINT i$ WEND CLOSE EN...
http://rosettacode.org/wiki/Take_notes_on_the_command_line
Take notes on the command line
Take notes on the command line is part of Short Circuit's Console Program Basics selection. Invoking NOTES without commandline arguments displays the current contents of the local NOTES.TXT if it exists. If NOTES has arguments, the current date and time are appended to the local NOTES.TXT followed by a newline. Then al...
#Batch_File
Batch File
@echo off if %1@==@ ( if exist notes.txt more notes.txt goto :eof ) echo %date% %time%:>>notes.txt echo %*>>notes.txt
http://rosettacode.org/wiki/Taxicab_numbers
Taxicab numbers
A   taxicab number   (the definition that is being used here)   is a positive integer that can be expressed as the sum of two positive cubes in more than one way. The first taxicab number is   1729,   which is: 13   +   123       and also 93   +   103. Taxicab numbers are also known as:   taxi numbers   tax...
#EchoLisp
EchoLisp
  (require '(heap compile))   (define (scube a b) (+ (* a a a) (* b b b))) (compile 'scube "-f") ; "-f" means : no bigint, no rational used   ;; is n - a^3 a cube b^3? ;; if yes return b, else #f (define (taxi? n a (b 0)) (set! b (cbrt (- n (* a a a)))) ;; cbrt is ∛ (when (and (< b a) (integer? b)) b)) (compile 'tax...
http://rosettacode.org/wiki/Superpermutation_minimisation
Superpermutation minimisation
A superpermutation of N different characters is a string consisting of an arrangement of multiple copies of those N different characters in which every permutation of those characters can be found as a substring. For example, representing the characters as A..Z, using N=2 we choose to use the first two characters 'AB'...
#11l
11l
-V MAX = 12   [Char] sp V count = [0] * MAX V pos = 0   F factSum(n) V s = 0 V x = 0 V f = 1 L x < n f *= ++x s += f R s   F r(n) I n == 0 R 0B V c = :sp[:pos - n] I --:count[n] == 0  :count[n] = n I !r(n - 1) R 0B  :sp[:pos++] = c R 1B   F superPerm(n)...
http://rosettacode.org/wiki/Tau_number
Tau number
A Tau number is a positive integer divisible by the count of its positive divisors. Task Show the first   100   Tau numbers. The numbers shall be generated during run-time (i.e. the code may not contain string literals, sets/arrays of integers, or alike). Related task  Tau function
#Haskell
Haskell
tau :: Integral a => a -> a tau n | n <= 0 = error "Not a positive integer" tau n = go 0 (1, 1) where yo i = (i, i * i) go r (i, ii) | n < ii = r | n == ii = r + 1 | 0 == mod n i = go (r + 2) (yo $ i + 1) | otherwise = go r (yo $ i + 1)   isTau :: Integral a => a -> Bool isTa...
http://rosettacode.org/wiki/Tau_number
Tau number
A Tau number is a positive integer divisible by the count of its positive divisors. Task Show the first   100   Tau numbers. The numbers shall be generated during run-time (i.e. the code may not contain string literals, sets/arrays of integers, or alike). Related task  Tau function
#J
J
  tau_number=: 0 = (|~ tally_factors@>) tally_factors=: [: */ 1 + _&q:  
http://rosettacode.org/wiki/Tarjan
Tarjan
This page uses content from Wikipedia. The original article was at Graph. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance) Tarjan's algorithm is an algorithm in graph theory for finding the strongly...
#Python
Python
from collections import defaultdict   def from_edges(edges): '''translate list of edges to list of nodes'''   class Node: def __init__(self): # root is one of: # None: not yet visited # -1: already processed # non-negative integer: what Wikipedia pse...
http://rosettacode.org/wiki/Teacup_rim_text
Teacup rim text
On a set of coasters we have, there's a picture of a teacup.   On the rim of the teacup the word   TEA   appears a number of times separated by bullet characters   (•). It occurred to me that if the bullet were removed and the words run together,   you could start at any letter and still end up with a meaningful three...
#Perl
Perl
use strict; use warnings; use feature 'say'; use List::Util qw(uniqstr any);   my(%words,@teacups,%seen);   open my $fh, '<', 'ref/wordlist.10000'; while (<$fh>) { chomp(my $w = uc $_); next if length $w < 3; push @{$words{join '', sort split //, $w}}, $w;}   for my $these (values %words) { next if @$th...
http://rosettacode.org/wiki/Temperature_conversion
Temperature conversion
There are quite a number of temperature scales. For this task we will concentrate on four of the perhaps best-known ones: Kelvin, Celsius, Fahrenheit, and Rankine. The Celsius and Kelvin scales have the same magnitude, but different null points. 0 degrees Celsius corresponds to 273.15 kelvin. 0 kelvin is absolute z...
#AppleScript
AppleScript
use framework "Foundation" -- Yosemite onwards, for the toLowerCase() function   -- KELVIN TO OTHER SCALE -----------------------------------------------------   -- kelvinAs :: ScaleName -> Num -> Num on kelvinAs(strOtherScale, n) heatBabel(n, "Kelvin", strOtherScale) end kelvinAs   -- MORE GENERAL CONVERSION -----...
http://rosettacode.org/wiki/Tau_function
Tau function
Given a positive integer, count the number of its positive divisors. Task Show the result for the first   100   positive integers. Related task  Tau number
#Cowgol
Cowgol
include "cowgol.coh";   typedef N is uint8; sub tau(n: N): (total: N) is total := 1; while n & 1 == 0 loop total := total + 1; n := n >> 1; end loop; var p: N := 3; while p*p <= n loop var count: N := 1; while n%p == 0 loop count := count + 1; ...
http://rosettacode.org/wiki/Tau_function
Tau function
Given a positive integer, count the number of its positive divisors. Task Show the result for the first   100   positive integers. Related task  Tau number
#D
D
import std.stdio;   // See https://en.wikipedia.org/wiki/Divisor_function uint divisor_count(uint n) { uint total = 1; // Deal with powers of 2 first for (; (n & 1) == 0; n >>= 1) { ++total; } // Odd prime factors up to the square root for (uint p = 3; p * p <= n; p += 2) { uint ...
http://rosettacode.org/wiki/Terminal_control/Clear_the_screen
Terminal control/Clear the screen
Task Clear the terminal window.
#Fortran
Fortran
program clear character(len=:), allocatable :: clear_command clear_command = "clear" !"cls" on Windows, "clear" on Linux and alike call execute_command_line(clear_command) end program
http://rosettacode.org/wiki/Terminal_control/Clear_the_screen
Terminal control/Clear the screen
Task Clear the terminal window.
#FreeBASIC
FreeBASIC
' FB 1.05.0 Win64   ' FreeBASIC has a built in Cls command which clears the console on Windows ' but it may still be possible to scroll the console to view its ' previous contents. The following command prevents this.   Shell("Cls") Sleep
http://rosettacode.org/wiki/Terminal_control/Clear_the_screen
Terminal control/Clear the screen
Task Clear the terminal window.
#Furor
Furor
  cls  
http://rosettacode.org/wiki/Ternary_logic
Ternary logic
This page uses content from Wikipedia. The original article was at Ternary logic. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance) In logic, a three-valued logic (also trivalent, ternary, or trinary...
#J
J
not=: -. and=: <. or =: >. if =: (>. -.)"0~ eq =: (<.&-. >. <.)"0
http://rosettacode.org/wiki/Text_processing/1
Text processing/1
This task has been flagged for clarification. Code on this page in its current state may be flagged incorrect once this task has been clarified. See this page's Talk page for discussion. Often data is produced by one program, in the wrong format for later use by another program or person. In these situations another pr...
#Lua
Lua
filename = "readings.txt" io.input( filename )   file_sum, file_cnt_data, file_lines = 0, 0, 0 max_rejected, n_rejected = 0, 0 max_rejected_date, rejected_date = "", ""   while true do data = io.read("*line") if data == nil then break end   date = string.match( data, "%d+%-%d+%-%d+" ) if date == nil the...
http://rosettacode.org/wiki/Test_a_function
Test a function
Task Using a well-known testing-specific library/module/suite for your language, write some tests for your language's entry in Palindrome. If your language does not have a testing specific library well known to the language's community then state this or omit the language.
#UNIX_Shell
UNIX Shell
#!/bin/bash   is_palindrome() { local s1=$1 local s2=$(echo $1 | tr -d "[ ,!:;.'\"]" | tr '[A-Z]' '[a-z]')   if [[ $s2 = $(echo $s2 | rev) ]] then echo "[$s1] is a palindrome" else echo "[$s1] is NOT a palindrome" fi }  
http://rosettacode.org/wiki/Test_a_function
Test a function
Task Using a well-known testing-specific library/module/suite for your language, write some tests for your language's entry in Palindrome. If your language does not have a testing specific library well known to the language's community then state this or omit the language.
#VBA
VBA
  Option Explicit   Sub Test_a_function() Dim a, i& a = Array("abba", "mom", "dennis sinned", "Un roc lamina l animal cornu", "palindrome", "ba _ ab", "racecars", "racecar", "wombat", "in girum imus nocte et consumimur igni") For i = 0 To UBound(a) Debug.Print a(i) & " is a palidrome ? " & IsPalindrome(...
http://rosettacode.org/wiki/The_Twelve_Days_of_Christmas
The Twelve Days of Christmas
Task Write a program that outputs the lyrics of the Christmas carol The Twelve Days of Christmas. The lyrics can be found here. (You must reproduce the words in the correct order, but case, format, and punctuation are left to your discretion.) Other tasks related to string operations: Metrics Array length Stri...
#Groovy
Groovy
def presents = ['A partridge in a pear tree.', 'Two turtle doves', 'Three french hens', 'Four calling birds', 'Five golden rings', 'Six geese a-laying', 'Seven swans a-swimming', 'Eight maids a-milking', 'Nine ladies dancing', 'Ten lords a-leaping', 'Eleven pipers piping', 'Twelve drummers drumming'] ['...
http://rosettacode.org/wiki/Terminal_control/Coloured_text
Terminal control/Coloured text
Task Display a word in various colours on the terminal. The system palette, or colours such as Red, Green, Blue, Magenta, Cyan, and Yellow can be used. Optionally demonstrate: How the system should determine if the terminal supports colour Setting of the background colour How to cause blinking or flashing (if ...
#Mathematica.2FWolfram_Language
Mathematica/Wolfram Language
Run["tput setaf 1"]; Print["Coloured Text"]; Run["tput setaf 2"]; Print["Coloured Text"]; Run["tput setaf 3"]; Print["Coloured Text"]
http://rosettacode.org/wiki/Terminal_control/Coloured_text
Terminal control/Coloured text
Task Display a word in various colours on the terminal. The system palette, or colours such as Red, Green, Blue, Magenta, Cyan, and Yellow can be used. Optionally demonstrate: How the system should determine if the terminal supports colour Setting of the background colour How to cause blinking or flashing (if ...
#Nim
Nim
import Terminal setForegroundColor(fgRed) echo "FATAL ERROR! Cannot write to /boot/vmlinuz-3.2.0-33-generic"   setBackgroundColor(bgBlue) setForegroundColor(fgYellow) stdout.write "This is an " writeStyled "important" stdout.write " word" resetAttributes() stdout.write "\n"   setForegroundColor(fgYellow) echo "Rosetta...
http://rosettacode.org/wiki/Terminal_control/Coloured_text
Terminal control/Coloured text
Task Display a word in various colours on the terminal. The system palette, or colours such as Red, Green, Blue, Magenta, Cyan, and Yellow can be used. Optionally demonstrate: How the system should determine if the terminal supports colour Setting of the background colour How to cause blinking or flashing (if ...
#OCaml
OCaml
$ ocaml unix.cma -I +ANSITerminal ANSITerminal.cma   # open ANSITerminal ;; # print_string [cyan; on_blue] "Hello\n" ;; Hello - : unit = ()
http://rosettacode.org/wiki/Synchronous_concurrency
Synchronous concurrency
The goal of this task is to create two concurrent activities ("Threads" or "Tasks", not processes.) that share data synchronously. Your language may provide syntax or libraries to perform concurrency. Different languages provide different implementations of concurrency, often with different names. Some languages use th...
#BCPL
BCPL
// This is a BCPL implementation of the Rosettacode synchronous // concurrency test using BCPL coroutines and a coroutine implementation // of a Occum-style channels. // BCPL is freely available from www.cl.cam.ac.uk/users/mr10   SECTION "coinout"   GET "libhdr.h"   GLOBAL { tracing: ug }   LET start() = VALOF { LET ...
http://rosettacode.org/wiki/Synchronous_concurrency
Synchronous concurrency
The goal of this task is to create two concurrent activities ("Threads" or "Tasks", not processes.) that share data synchronously. Your language may provide syntax or libraries to perform concurrency. Different languages provide different implementations of concurrency, often with different names. Some languages use th...
#C
C
#include <stdlib.h> /* malloc(), realloc(), free() */ #include <stdio.h> /* fopen(), fgetc(), fwrite(), printf() */   #include <libco.h> /* co_create(), co_switch() */   void fail(const char *message) { perror(message); exit(1); }   /* * These are global variables of this process. All cothreads of this * process wi...
http://rosettacode.org/wiki/Table_creation/Postal_addresses
Table creation/Postal addresses
Task Create a table to store addresses. You may assume that all the addresses to be stored will be located in the USA.   As such, you will need (in addition to a field holding a unique identifier) a field holding the street address, a field holding the city, a field holding the state code, and a field holding the zip...
#Haskell
Haskell
{-# LANGUAGE OverloadedStrings #-}   import Database.SQLite.Simple   main = do db <- open "postal.db" execute_ db "\ \CREATE TABLE address (\ \addrID INTEGER PRIMARY KEY AUTOINCREMENT, \ \addrStreet TEXT NOT NULL, \ \addrCity TEXT NOT NULL, \ \addrState TEXT NOT NU...
http://rosettacode.org/wiki/Table_creation/Postal_addresses
Table creation/Postal addresses
Task Create a table to store addresses. You may assume that all the addresses to be stored will be located in the USA.   As such, you will need (in addition to a field holding a unique identifier) a field holding the street address, a field holding the city, a field holding the state code, and a field holding the zip...
#J
J
Create__hd 'Address';noun define addrID autoid; addrStreet varchar addrCity varchar addrState char addrZip char )
http://rosettacode.org/wiki/Table_creation/Postal_addresses
Table creation/Postal addresses
Task Create a table to store addresses. You may assume that all the addresses to be stored will be located in the USA.   As such, you will need (in addition to a field holding a unique identifier) a field holding the street address, a field holding the city, a field holding the state code, and a field holding the zip...
#Julia
Julia
using SQLite   db = SQLite.DB() SQLite.execute!(db, """\ CREATE TABLE address ( addrID INTEGER PRIMARY KEY AUTOINCREMENT, addrStreet TEXT NOT NULL, addrCity TEXT NOT NULL, addrState TEXT NOT NULL, addrZIP TEXT NOT NULL) """)
http://rosettacode.org/wiki/Table_creation/Postal_addresses
Table creation/Postal addresses
Task Create a table to store addresses. You may assume that all the addresses to be stored will be located in the USA.   As such, you will need (in addition to a field holding a unique identifier) a field holding the street address, a field holding the city, a field holding the state code, and a field holding the zip...
#Kotlin
Kotlin
// Version 1.2.41   import java.io.File import java.io.RandomAccessFile   fun String.toFixedLength(len: Int) = this.padEnd(len).substring(0, len)   class Address( var name: String, var street: String = "", var city: String = "", var state: String = "", var zipCode: String = "", val autoId: Boole...
http://rosettacode.org/wiki/Take_notes_on_the_command_line
Take notes on the command line
Take notes on the command line is part of Short Circuit's Console Program Basics selection. Invoking NOTES without commandline arguments displays the current contents of the local NOTES.TXT if it exists. If NOTES has arguments, the current date and time are appended to the local NOTES.TXT followed by a newline. Then al...
#BBC_BASIC
BBC BASIC
REM!Exefile C:\NOTES.EXE, encrypt, console REM!Embed LF = 10   SYS "GetStdHandle", -10 TO @hfile%(1) SYS "GetStdHandle", -11 TO @hfile%(2) SYS "SetConsoleMode", @hfile%(1), 0 *INPUT 13 *OUTPUT 14 ON ERROR PRINT REPORT$ : QUIT ERR   notes% = OPENUP(@dir$ + "NOT...
http://rosettacode.org/wiki/Take_notes_on_the_command_line
Take notes on the command line
Take notes on the command line is part of Short Circuit's Console Program Basics selection. Invoking NOTES without commandline arguments displays the current contents of the local NOTES.TXT if it exists. If NOTES has arguments, the current date and time are appended to the local NOTES.TXT followed by a newline. Then al...
#C
C
#include <stdio.h> #include <time.h>   #define note_file "NOTES.TXT"   int main(int argc, char**argv) { FILE *note = 0; time_t tm; int i; char *p;   if (argc < 2) { if ((note = fopen(note_file, "r"))) while ((i = fgetc(note)) != EOF) putchar(i);   } else if ((note = fopen(note_file, "a"))) { tm = time(...
http://rosettacode.org/wiki/Taxicab_numbers
Taxicab numbers
A   taxicab number   (the definition that is being used here)   is a positive integer that can be expressed as the sum of two positive cubes in more than one way. The first taxicab number is   1729,   which is: 13   +   123       and also 93   +   103. Taxicab numbers are also known as:   taxi numbers   tax...
#Elixir
Elixir
defmodule Taxicab do def numbers(n \\ 1200) do (for i <- 1..n, j <- i..n, do: {i,j}) |> Enum.group_by(fn {i,j} -> i*i*i + j*j*j end) |> Enum.filter(fn {_,v} -> length(v)>1 end) |> Enum.sort end end   nums = Taxicab.numbers |> Enum.with_index Enum.each(nums, fn {x,i} -> if i in 0..24 or i in 1999.....
http://rosettacode.org/wiki/Taxicab_numbers
Taxicab numbers
A   taxicab number   (the definition that is being used here)   is a positive integer that can be expressed as the sum of two positive cubes in more than one way. The first taxicab number is   1729,   which is: 13   +   123       and also 93   +   103. Taxicab numbers are also known as:   taxi numbers   tax...
#Forth
Forth
variable taxicablist variable searched-cubessum 73 constant max-constituent \ uses magic numbers   : cube dup dup * * ; : cubessum cube swap cube + ;   : ?taxicab ( a b -- c d true | false ) \ does exist an (c, d) such that c^3+d^3 = a^3+b^3 ? 2dup cubessum searched-cubessum ! dup 1- rot 1+ do \ c is possibly in ...
http://rosettacode.org/wiki/Superpermutation_minimisation
Superpermutation minimisation
A superpermutation of N different characters is a string consisting of an arrangement of multiple copies of those N different characters in which every permutation of those characters can be found as a substring. For example, representing the characters as A..Z, using N=2 we choose to use the first two characters 'AB'...
#AWK
AWK
  # syntax: GAWK -f SUPERPERMUTATION_MINIMISATION.AWK # converted from C BEGIN { arr[0] # prevents fatal: attempt to use scalar 'arr' as an array limit = 11 for (n=0; n<=limit; n++) { leng = super_perm(n) printf("%2d %d ",n,leng) # for (i=0; i<length(arr); i++) { printf(arr[i]) } # un-commen...
http://rosettacode.org/wiki/Tau_number
Tau number
A Tau number is a positive integer divisible by the count of its positive divisors. Task Show the first   100   Tau numbers. The numbers shall be generated during run-time (i.e. the code may not contain string literals, sets/arrays of integers, or alike). Related task  Tau function
#Java
Java
public class Tau { private static long divisorCount(long n) { long total = 1; // Deal with powers of 2 first for (; (n & 1) == 0; n >>= 1) { ++total; } // Odd prime factors up to the square root for (long p = 3; p * p <= n; p += 2) { long count...
http://rosettacode.org/wiki/Tarjan
Tarjan
This page uses content from Wikipedia. The original article was at Graph. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance) Tarjan's algorithm is an algorithm in graph theory for finding the strongly...
#Racket
Racket
#lang racket   (require syntax/parse/define fancy-app (for-syntax racket/syntax))   (struct node (name index low-link on?) #:transparent #:mutable #:methods gen:custom-write [(define (write-proc v port mode) (fprintf port "~a" (node-name v)))])   (define-syntax-parser change! [(_ x:id f) #'(set!...
http://rosettacode.org/wiki/Tarjan
Tarjan
This page uses content from Wikipedia. The original article was at Graph. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance) Tarjan's algorithm is an algorithm in graph theory for finding the strongly...
#Raku
Raku
sub tarjan (%k) { my %onstack; my %index; my %lowlink; my @stack; my @connected;   sub strong-connect ($vertex) { state $index = 0; %index{$vertex} = $index; %lowlink{$vertex} = $index++; %onstack{$vertex} = True; @stack.push: $vertex; ...
http://rosettacode.org/wiki/Teacup_rim_text
Teacup rim text
On a set of coasters we have, there's a picture of a teacup.   On the rim of the teacup the word   TEA   appears a number of times separated by bullet characters   (•). It occurred to me that if the bullet were removed and the words run together,   you could start at any letter and still end up with a meaningful three...
#Phix
Phix
procedure filter_set(sequence anagrams) -- anagrams is a (small) set of words that are all anagrams of each other -- for example: {"angel","angle","galen","glean","lange"} -- print any set(s) for which every rotation is also present (marking as -- you go to prevent the same set appearing with each word...
http://rosettacode.org/wiki/Temperature_conversion
Temperature conversion
There are quite a number of temperature scales. For this task we will concentrate on four of the perhaps best-known ones: Kelvin, Celsius, Fahrenheit, and Rankine. The Celsius and Kelvin scales have the same magnitude, but different null points. 0 degrees Celsius corresponds to 273.15 kelvin. 0 kelvin is absolute z...
#Arturo
Arturo
convertKelvins: function [k][ #[ celcius: k - 273.15 fahrenheit: (k * 9/5.0)-459.67 rankine: k * 9/5.0 ] ]   print convertKelvins 100
http://rosettacode.org/wiki/Tau_function
Tau function
Given a positive integer, count the number of its positive divisors. Task Show the result for the first   100   positive integers. Related task  Tau number
#Delphi
Delphi
  program Tau_function;   {$APPTYPE CONSOLE}   uses System.SysUtils;   function CountDivisors(n: Integer): Integer; begin Result := 0; var i := 1; var k := 2; if (n mod 2) = 0 then k := 1;   while i * i <= n do begin if (n mod i) = 0 then begin inc(Result); var j := n div i; ...
http://rosettacode.org/wiki/Tau_function
Tau function
Given a positive integer, count the number of its positive divisors. Task Show the result for the first   100   positive integers. Related task  Tau number
#Draco
Draco
proc nonrec tau(word n) word: word count, total, p; total := 1; while n & 1 = 0 do total := total + 1; n := n >> 1 od; p := 3; while p*p <= n do count := 1; while n % p = 0 do count := count + 1; n := n / p od; total := tota...
http://rosettacode.org/wiki/Terminal_control/Clear_the_screen
Terminal control/Clear the screen
Task Clear the terminal window.
#Go
Go
package main   import ( "os" "os/exec" )   func main() { c := exec.Command("clear") c.Stdout = os.Stdout c.Run() }
http://rosettacode.org/wiki/Terminal_control/Clear_the_screen
Terminal control/Clear the screen
Task Clear the terminal window.
#GUISS
GUISS
Window:Terminal,Type:clear[enter]
http://rosettacode.org/wiki/Terminal_control/Clear_the_screen
Terminal control/Clear the screen
Task Clear the terminal window.
#Haskell
Haskell
  import System.Console.ANSI   main = clearScreen  
http://rosettacode.org/wiki/Ternary_logic
Ternary logic
This page uses content from Wikipedia. The original article was at Ternary logic. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance) In logic, a three-valued logic (also trivalent, ternary, or trinary...
#Java
Java
public class Logic{ public static enum Trit{ TRUE, MAYBE, FALSE;   public Trit and(Trit other){ if(this == TRUE){ return other; }else if(this == MAYBE){ return (other == FALSE) ? FALSE : MAYBE; }else{ return FALSE; } }   public Trit or(Trit other){ if(this == TRUE){ return TRUE; ...
http://rosettacode.org/wiki/Text_processing/1
Text processing/1
This task has been flagged for clarification. Code on this page in its current state may be flagged incorrect once this task has been clarified. See this page's Talk page for discussion. Often data is produced by one program, in the wrong format for later use by another program or person. In these situations another pr...
#Mathematica.2FWolfram_Language
Mathematica/Wolfram Language
FileName = "Readings.txt"; data = Import[FileName,"TSV"]; Scan[(a=Position[#[[3;;All;;2]],1]; Print["Line:",#[[1]] ,"\tReject:", 24 - Length[a], "\t Accept:", Length[a], "\tLine_tot:", Total@Part[#, Flatten[2*a]] , "\tLine_avg:", Total@Part[#, Flatten[2*a]]/Length[a]])&, data]   GlobalSum = Nb = Running = MaxRunRecorde...
http://rosettacode.org/wiki/Test_a_function
Test a function
Task Using a well-known testing-specific library/module/suite for your language, write some tests for your language's entry in Palindrome. If your language does not have a testing specific library well known to the language's community then state this or omit the language.
#Wren
Wren
import "/module" for Expect, Suite, ConsoleReporter   var isPal = Fn.new { |word| word == ((word.count > 0) ? word[-1..0] : "") }   var words = ["rotor", "rosetta", "step on no pets", "été", "wren", "🦊😀🦊"] var expected = [true, false, true, true, false, true]   var TestPal = Suite.new("Pal") { |it| it.suite("'is...
http://rosettacode.org/wiki/Test_a_function
Test a function
Task Using a well-known testing-specific library/module/suite for your language, write some tests for your language's entry in Palindrome. If your language does not have a testing specific library well known to the language's community then state this or omit the language.
#zkl
zkl
fcn pali(text){ if (text.len()<2) return(False); text==text.reverse(); }
http://rosettacode.org/wiki/The_Twelve_Days_of_Christmas
The Twelve Days of Christmas
Task Write a program that outputs the lyrics of the Christmas carol The Twelve Days of Christmas. The lyrics can be found here. (You must reproduce the words in the correct order, but case, format, and punctuation are left to your discretion.) Other tasks related to string operations: Metrics Array length Stri...
#Haskell
Haskell
gifts :: [String] gifts = [ "And a partridge in a pear tree!", "Two turtle doves,", "Three french hens,", "Four calling birds,", "FIVE GOLDEN RINGS,", "Six geese a-laying,", "Seven swans a-swimming,", "Eight maids a-milking,", "Nine ladies dancing,", "Ten lords a-leaping,", "El...
http://rosettacode.org/wiki/Terminal_control/Coloured_text
Terminal control/Coloured text
Task Display a word in various colours on the terminal. The system palette, or colours such as Red, Green, Blue, Magenta, Cyan, and Yellow can be used. Optionally demonstrate: How the system should determine if the terminal supports colour Setting of the background colour How to cause blinking or flashing (if ...
#ooRexx
ooRexx
  #!/usr/bin/rexx /*.----------------------------------------------------------------------.*/ /*|bashcolours: Display a table showing all of the possible colours that |*/ /*| can be generated using ANSI escapes in bash in an xterm |*/ /*| terminal session. ...
http://rosettacode.org/wiki/Synchronous_concurrency
Synchronous concurrency
The goal of this task is to create two concurrent activities ("Threads" or "Tasks", not processes.) that share data synchronously. Your language may provide syntax or libraries to perform concurrency. Different languages provide different implementations of concurrency, often with different names. Some languages use th...
#C.23
C#
using System; using System.Threading.Tasks; using System.Collections.Concurrent; using System.IO;   namespace SynchronousConcurrency { class Program { static void Main(string[] args) { BlockingCollection<string> toWriterTask = new BlockingCollection<string>(); BlockingCol...
http://rosettacode.org/wiki/Table_creation/Postal_addresses
Table creation/Postal addresses
Task Create a table to store addresses. You may assume that all the addresses to be stored will be located in the USA.   As such, you will need (in addition to a field holding a unique identifier) a field holding the street address, a field holding the city, a field holding the state code, and a field holding the zip...
#Lasso
Lasso
// connect to a Mysql database inline(-database = 'rosettatest', -sql = "CREATE TABLE `address` ( `id` int(11) NOT NULL auto_increment, `street` varchar(50) NOT NULL default '', `city` varchar(25) NOT NULL default '', `state` char(2) NOT NULL default '', `zip` cha...
http://rosettacode.org/wiki/Table_creation/Postal_addresses
Table creation/Postal addresses
Task Create a table to store addresses. You may assume that all the addresses to be stored will be located in the USA.   As such, you will need (in addition to a field holding a unique identifier) a field holding the street address, a field holding the city, a field holding the state code, and a field holding the zip...
#Lua
Lua
-- Import module local sql = require("ljsqlite3")   -- Open connection to database file local conn = sql.open("address.sqlite")   -- Create address table unless it already exists conn:exec[[ CREATE TABLE IF NOT EXISTS address( id INTEGER PRIMARY KEY AUTOINCREMENT, street TEXT NOT NULL, city TEXT NOT NULL, sta...
http://rosettacode.org/wiki/Table_creation/Postal_addresses
Table creation/Postal addresses
Task Create a table to store addresses. You may assume that all the addresses to be stored will be located in the USA.   As such, you will need (in addition to a field holding a unique identifier) a field holding the street address, a field holding the city, a field holding the state code, and a field holding the zip...
#Mathematica.2FWolfram_Language
Mathematica/Wolfram Language
TableCreation="CREATE TABLE address ( addrID INTEGER PRIMARY KEY AUTOINCREMENT, addrStreet TEXT NOT NULL, addrCity TEXT NOT NULL, addrState TEXT NOT NULL, addrZIP TEXT NOT NULL )"; Needs["DatabaseLink`"] conn=OpenSQLConnection[ JDBC[ "mysql","databases:1234/conn_test"], "Username" -> "test"] SQLExecute[ conn, Tab...
http://rosettacode.org/wiki/Table_creation/Postal_addresses
Table creation/Postal addresses
Task Create a table to store addresses. You may assume that all the addresses to be stored will be located in the USA.   As such, you will need (in addition to a field holding a unique identifier) a field holding the street address, a field holding the city, a field holding the state code, and a field holding the zip...
#MySQL
MySQL
CREATE TABLE `Address` ( `addrID` int(11) NOT NULL auto_increment, `addrStreet` varchar(50) NOT NULL default '', `addrCity` varchar(25) NOT NULL default '', `addrState` char(2) NOT NULL default '', `addrZIP` char(10) NOT NULL default '', PRIMARY KEY (`add...
http://rosettacode.org/wiki/Take_notes_on_the_command_line
Take notes on the command line
Take notes on the command line is part of Short Circuit's Console Program Basics selection. Invoking NOTES without commandline arguments displays the current contents of the local NOTES.TXT if it exists. If NOTES has arguments, the current date and time are appended to the local NOTES.TXT followed by a newline. Then al...
#C.23
C#
using System; using System.IO; using System.Text;   namespace RosettaCode { internal class Program { private const string FileName = "NOTES.TXT";   private static void Main(string[] args) { if (args.Length==0) { string txt = File.ReadAllText(FileName); Console.WriteLine(txt);...
http://rosettacode.org/wiki/Take_notes_on_the_command_line
Take notes on the command line
Take notes on the command line is part of Short Circuit's Console Program Basics selection. Invoking NOTES without commandline arguments displays the current contents of the local NOTES.TXT if it exists. If NOTES has arguments, the current date and time are appended to the local NOTES.TXT followed by a newline. Then al...
#C.2B.2B
C++
#include <fstream> #include <iostream> #include <ctime> using namespace std;   #define note_file "NOTES.TXT"   int main(int argc, char **argv) { if(argc>1) { ofstream Notes(note_file, ios::app); time_t timer = time(NULL); if(Notes.is_open()) { Notes << asctime(localtime(&timer)) << '\t'; for(int i=1;i<a...
http://rosettacode.org/wiki/Sylvester%27s_sequence
Sylvester's sequence
This page uses content from Wikipedia. The original article was at Sylvester's sequence. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance) In number theory, Sylvester's sequence is an integer sequenc...
#11l
11l
F sylverster(lim) V result = [BigInt(2)] L 2..lim result.append(product(result) + 1) R result   V l = sylverster(10) print(‘First 10 terms of the Sylvester sequence:’) L(item) l print(item)   V s = 0.0 L(item) l s += 1 / Float(item) print("\nSum of the reciprocals of the first 10 terms: #.17".forma...
http://rosettacode.org/wiki/Taxicab_numbers
Taxicab numbers
A   taxicab number   (the definition that is being used here)   is a positive integer that can be expressed as the sum of two positive cubes in more than one way. The first taxicab number is   1729,   which is: 13   +   123       and also 93   +   103. Taxicab numbers are also known as:   taxi numbers   tax...
#Fortran
Fortran
  ! A non-bruteforce approach PROGRAM POOKA IMPLICIT NONE ! ! PARAMETER definitions ! INTEGER , PARAMETER :: NVARS = 25 ! ! Local variables ! REAL :: f1 REAL :: f2 INTEGER :: hits INTEGER :: s INTEGER :: TAXICAB   hits = 0 s = 0 f1 = SECOND() ...
http://rosettacode.org/wiki/Superpermutation_minimisation
Superpermutation minimisation
A superpermutation of N different characters is a string consisting of an arrangement of multiple copies of those N different characters in which every permutation of those characters can be found as a substring. For example, representing the characters as A..Z, using N=2 we choose to use the first two characters 'AB'...
#C
C
#include <stdio.h> #include <stdlib.h> #include <string.h>   #define MAX 12 char *super = 0; int pos, cnt[MAX];   // 1! + 2! + ... + n! int fact_sum(int n) { int s, x, f; for (s = 0, x = 0, f = 1; x < n; f *= ++x, s += f); return s; }   int r(int n) { if (!n) return 0;   char c = super[pos - n]; if (!--cnt[n]) { ...
http://rosettacode.org/wiki/Tau_number
Tau number
A Tau number is a positive integer divisible by the count of its positive divisors. Task Show the first   100   Tau numbers. The numbers shall be generated during run-time (i.e. the code may not contain string literals, sets/arrays of integers, or alike). Related task  Tau function
#jq
jq
def count(s): reduce s as $x (0; .+1);   # For pretty-printing def nwise($n): def n: if length <= $n then . else .[0:$n] , (.[$n:] | n) end; n;   def lpad($len): tostring | ($len - length) as $l | (" " * $l)[:$l] + .;
http://rosettacode.org/wiki/Tau_number
Tau number
A Tau number is a positive integer divisible by the count of its positive divisors. Task Show the first   100   Tau numbers. The numbers shall be generated during run-time (i.e. the code may not contain string literals, sets/arrays of integers, or alike). Related task  Tau function
#Julia
Julia
using Primes   function numfactors(n) f = [one(n)] for (p, e) in factor(n) f = reduce(vcat, [f * p^j for j in 1:e], init = f) end length(f) end   function taunumbers(toget = 100) n = 0 for i in 1:100000000 if i % numfactors(i) == 0 n += 1 print(rpad(i, 5),...
http://rosettacode.org/wiki/Tau_number
Tau number
A Tau number is a positive integer divisible by the count of its positive divisors. Task Show the first   100   Tau numbers. The numbers shall be generated during run-time (i.e. the code may not contain string literals, sets/arrays of integers, or alike). Related task  Tau function
#Lua
Lua
function divisor_count(n) local total = 1   -- Deal with powers of 2 first while (n & 1) == 0 do total = total + 1 n = n >> 1 end -- Odd prime factors up to the square root local p = 3 while p * p <= n do local count = 1 while n % p == 0 do count =...
http://rosettacode.org/wiki/Tarjan
Tarjan
This page uses content from Wikipedia. The original article was at Graph. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance) Tarjan's algorithm is an algorithm in graph theory for finding the strongly...
#REXX
REXX
/* REXX - Tarjan's Algorithm */ /* Vertices are numbered 1 to 8 (instead of 0 to 7) */ g='[2] [3] [1] [2 3 5] [4 6] [3 7] [6] [5 7 8]' gg=g Do i=1 By 1 While gg>'' Parse Var gg '[' g.i ']' gg name.i=i-1 End g.0=i-1 index.=0 lowlink.=0 stacked.=0 stack.=0 x=1 Do n=1 To g.0 If index.n=0 The...
http://rosettacode.org/wiki/Teacup_rim_text
Teacup rim text
On a set of coasters we have, there's a picture of a teacup.   On the rim of the teacup the word   TEA   appears a number of times separated by bullet characters   (•). It occurred to me that if the bullet were removed and the words run together,   you could start at any letter and still end up with a meaningful three...
#PicoLisp
PicoLisp
(de rotw (W) (let W (chop W) (unless (or (apply = W) (not (cddr W))) (make (do (length W) (link (pack (copy W))) (rot W) ) ) ) ) ) (off D) (put 'D 'v (cons)) (mapc '((W) (idx 'D (cons (hash W) W) T) ) (setq Words (make (in "wordlist.10000" (w...
http://rosettacode.org/wiki/Teacup_rim_text
Teacup rim text
On a set of coasters we have, there's a picture of a teacup.   On the rim of the teacup the word   TEA   appears a number of times separated by bullet characters   (•). It occurred to me that if the bullet were removed and the words run together,   you could start at any letter and still end up with a meaningful three...
#PureBasic
PureBasic
DataSection dname: Data.s "./Data/unixdict.txt" Data.s "./Data/wordlist.10000.txt" Data.s "" EndDataSection   EnableExplicit Dim c.s{1}(2) Define.s txt, bset, res, dn Define.i i,q, cw Restore dname : Read.s dn While OpenConsole() And ReadFile(0,dn) While Not Eof(0) cw+1 txt=ReadString(0) If Le...
http://rosettacode.org/wiki/Temperature_conversion
Temperature conversion
There are quite a number of temperature scales. For this task we will concentrate on four of the perhaps best-known ones: Kelvin, Celsius, Fahrenheit, and Rankine. The Celsius and Kelvin scales have the same magnitude, but different null points. 0 degrees Celsius corresponds to 273.15 kelvin. 0 kelvin is absolute z...
#AutoHotkey
AutoHotkey
MsgBox, % "Kelvin:`t`t 21.00 K`n" . "Celsius:`t`t" kelvinToCelsius(21) " C`n" . "Fahrenheit:`t" kelvinToFahrenheit(21) " F`n" . "Rankine:`t`t" kelvinToRankine(21) " R`n"   kelvinToCelsius(k) { return, round(k - 273.15, 2) } kelvinToFahrenheit(k) { return, round(k * 1.8 - 459.67, 2) } kel...
http://rosettacode.org/wiki/Tau_function
Tau function
Given a positive integer, count the number of its positive divisors. Task Show the result for the first   100   positive integers. Related task  Tau number
#Dyalect
Dyalect
func divisorCount(number) { var n = number var total = 1   while (n &&& 1) == 0 { total += 1 n >>>= 1 }   var p = 3 while p * p <= n { var count = 1 while n % p == 0 { count += 1 n /= p } total *= count p += 2 } ...
http://rosettacode.org/wiki/Tau_function
Tau function
Given a positive integer, count the number of its positive divisors. Task Show the result for the first   100   positive integers. Related task  Tau number
#F.23
F#
  // Tau function. Nigel Galloway: March 10th., 2021 let tau u=let P=primes32() let rec fN g=match u%g with 0->g |_->fN(Seq.head P) let rec fG n i g e l=match n=u,u%l with (true,_)->e |(_,0)->fG (n*i) i g (e+g)(l*i) |_->let q=fN(Seq.head P) in fG (n*q) q e (e+e) (q*q) let n=Seq.head P in f...
http://rosettacode.org/wiki/Terminal_control/Clear_the_screen
Terminal control/Clear the screen
Task Clear the terminal window.
#Icon_and_Unicon
Icon and Unicon
procedure main () if &features == "MS Windows" then system("cls") # Windows else if &features == "UNIX" then system("clear") # Unix end
http://rosettacode.org/wiki/Terminal_control/Clear_the_screen
Terminal control/Clear the screen
Task Clear the terminal window.
#J
J
smwrite_jijs_ ''
http://rosettacode.org/wiki/Terminal_control/Clear_the_screen
Terminal control/Clear the screen
Task Clear the terminal window.
#Java
Java
public class Clear { public static void main (String[] args) { System.out.print("\033[2J"); } }
http://rosettacode.org/wiki/Ternary_logic
Ternary logic
This page uses content from Wikipedia. The original article was at Ternary logic. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance) In logic, a three-valued logic (also trivalent, ternary, or trinary...
#JavaScript
JavaScript
var L3 = new Object();   L3.not = function(a) { if (typeof a == "boolean") return !a; if (a == undefined) return undefined; throw("Invalid Ternary Expression."); }   L3.and = function(a, b) { if (typeof a == "boolean" && typeof b == "boolean") return a && b; if ((a == true && b == undefined) || (a == undefine...
http://rosettacode.org/wiki/Text_processing/1
Text processing/1
This task has been flagged for clarification. Code on this page in its current state may be flagged incorrect once this task has been clarified. See this page's Talk page for discussion. Often data is produced by one program, in the wrong format for later use by another program or person. In these situations another pr...
#Nim
Nim
import os, sequtils, strutils, strformat   var nodata = 0 nodataMax = -1 nodataMaxLine: seq[string]   totFile = 0.0 numFile = 0   for filename in commandLineParams(): for line in filename.lines: var totLine = 0.0 numLine = 0 data: seq[float] flags: seq[int]   let fields = lin...
http://rosettacode.org/wiki/The_Twelve_Days_of_Christmas
The Twelve Days of Christmas
Task Write a program that outputs the lyrics of the Christmas carol The Twelve Days of Christmas. The lyrics can be found here. (You must reproduce the words in the correct order, but case, format, and punctuation are left to your discretion.) Other tasks related to string operations: Metrics Array length Stri...
#Icon_and_Unicon
Icon and Unicon
procedure main() days := ["first","second","third","fourth","fifth","sixth","seventh", "eighth","ninth","tenth","eleventh","twelveth"] gifts := ["A partridge in a pear tree.", "Two turtle doves and", "Three french hens,", "Four calling birds,", "Five golden rings,", "Six...
http://rosettacode.org/wiki/Terminal_control/Coloured_text
Terminal control/Coloured text
Task Display a word in various colours on the terminal. The system palette, or colours such as Red, Green, Blue, Magenta, Cyan, and Yellow can be used. Optionally demonstrate: How the system should determine if the terminal supports colour Setting of the background colour How to cause blinking or flashing (if ...
#PARI.2FGP
PARI/GP
for(b=40, 47, for(c=30, 37, printf("\e[%d;%d;1mRosetta Code\e[0m\n", c, b)))
http://rosettacode.org/wiki/Terminal_control/Coloured_text
Terminal control/Coloured text
Task Display a word in various colours on the terminal. The system palette, or colours such as Red, Green, Blue, Magenta, Cyan, and Yellow can be used. Optionally demonstrate: How the system should determine if the terminal supports colour Setting of the background colour How to cause blinking or flashing (if ...
#Pascal
Pascal
program Colorizer;   uses CRT;   const SampleText = 'Lorem ipsum dolor sit amet';   var fg, bg: 0..15;   begin ClrScr; for fg := 0 to 7 do begin bg := 15 - fg; TextBackground(bg); TextColor(fg); writeln(SampleText) end; TextBackground(White); TextColor(Black); end.
http://rosettacode.org/wiki/Synchronous_concurrency
Synchronous concurrency
The goal of this task is to create two concurrent activities ("Threads" or "Tasks", not processes.) that share data synchronously. Your language may provide syntax or libraries to perform concurrency. Different languages provide different implementations of concurrency, often with different names. Some languages use th...
#C.2B.2B
C++
#include <future> #include <iostream> #include <fstream> #include <mutex> #include <queue> #include <string> #include <thread>   struct lock_queue { std::queue<std::string> q; std::mutex mutex; };   void reader(std::string filename, std::future<size_t> lines, lock_queue& out) { std::string line; std::if...
http://rosettacode.org/wiki/Table_creation/Postal_addresses
Table creation/Postal addresses
Task Create a table to store addresses. You may assume that all the addresses to be stored will be located in the USA.   As such, you will need (in addition to a field holding a unique identifier) a field holding the street address, a field holding the city, a field holding the state code, and a field holding the zip...
#NetRexx
NetRexx
/* NetRexx */ options replace format comments java crossref symbols binary   import java.sql.Connection import java.sql.Statement import java.sql.SQLException import java.sql.DriverManager   class RTableCreate01 public properties private constant addressDDL = String '' - ' create table Address' - ' (' - ...
http://rosettacode.org/wiki/Table_creation/Postal_addresses
Table creation/Postal addresses
Task Create a table to store addresses. You may assume that all the addresses to be stored will be located in the USA.   As such, you will need (in addition to a field holding a unique identifier) a field holding the street address, a field holding the city, a field holding the state code, and a field holding the zip...
#Nim
Nim
import db_sqlite as db #import db_mysql as db #import db_postgres as db   const connection = ":memory:" user = "foo" pass = "bar" database = "db"   var c = open(connection, user, pass, database) c.exec sql"""CREATE TABLE address ( addrID INTEGER PRIMARY KEY AUTOINCREMENT, addrStreet TEXT NOT NULL, add...
http://rosettacode.org/wiki/Sutherland-Hodgman_polygon_clipping
Sutherland-Hodgman polygon clipping
The   Sutherland-Hodgman clipping algorithm   finds the polygon that is the intersection between an arbitrary polygon (the “subject polygon”) and a convex polygon (the “clip polygon”). It is used in computer graphics (especially 2D graphics) to reduce the complexity of a scene being displayed by eliminating parts of a...
#11l
11l
F clip(subjectPolygon, clipPolygon) F inside(p, cp1, cp2) R (cp2.x - cp1.x) * (p.y - cp1.y) > (cp2.y - cp1.y) * (p.x - cp1.x)   F computeIntersection(s, e, cp1, cp2) V dc = cp1 - cp2 V dp = s - e V n1 = cp1.x * cp2.y - cp1.y * cp2.x V n2 = s.x * e.y - s.y * e.x V n3 = 1.0 / (dc...
http://rosettacode.org/wiki/Symmetric_difference
Symmetric difference
Task Given two sets A and B, compute ( A ∖ B ) ∪ ( B ∖ A ) . {\displaystyle (A\setminus B)\cup (B\setminus A).} That is, enumerate the items that are in A or B but not both. This set is called the symmetric difference of A and B. In other words: ( A ∪ B ) ∖ ( A ∩ B ) {\displaystyle (A\cup B)\setminus (A...
#11l
11l
V setA = Set([‘John’, ‘Bob’, ‘Mary’, ‘Serena’]) V setB = Set([‘Jim’, ‘Mary’, ‘John’, ‘Bob’]) print(setA.symmetric_difference(setB)) print(setA - setB) print(setB - setA)
http://rosettacode.org/wiki/Super-d_numbers
Super-d numbers
A super-d number is a positive, decimal (base ten) integer   n   such that   d × nd   has at least   d   consecutive digits   d   where 2 ≤ d ≤ 9 For instance, 753 is a super-3 number because 3 × 7533 = 1280873331. Super-d   numbers are also shown on   MathWorld™   as   super-d   or   super-d. Task Write a...
#11l
11l
V rd = [‘22’, ‘333’, ‘4444’, ‘55555’, ‘666666’, ‘7777777’, ‘88888888’, ‘999999999’]   L(ii) 2..7 print(‘First 10 super-#. numbers:’.format(ii)) V count = 0   BigInt j = 3 L V k = ii * j^ii I rd[ii - 2] C String(k) count++ print(j, end' ‘ ’) I count == 10 pr...
http://rosettacode.org/wiki/Take_notes_on_the_command_line
Take notes on the command line
Take notes on the command line is part of Short Circuit's Console Program Basics selection. Invoking NOTES without commandline arguments displays the current contents of the local NOTES.TXT if it exists. If NOTES has arguments, the current date and time are appended to the local NOTES.TXT followed by a newline. Then al...
#Clojure
Clojure
(ns rosettacode.notes (:use [clojure.string :only [join]]))   (defn notes [notes] (if (seq notes) (spit "NOTES.txt" (str (java.util.Date.) "\n" "\t" (join " " notes) "\n")  :append true) (println (slurp "NOTES.txt"))))   (notes *command-line-args*)
http://rosettacode.org/wiki/Take_notes_on_the_command_line
Take notes on the command line
Take notes on the command line is part of Short Circuit's Console Program Basics selection. Invoking NOTES without commandline arguments displays the current contents of the local NOTES.TXT if it exists. If NOTES has arguments, the current date and time are appended to the local NOTES.TXT followed by a newline. Then al...
#CLU
CLU
% This program uses the "get_argv" function that is supplied iwth % PCLU in "useful.lib".   NOTEFILE = "notes.txt"   % Format the date and time as MM/DD/YYYY HH:MM:SS [AM|PM] format_date = proc (d: date) returns (string) ds: stream := stream$create_output() stream$putzero(ds, int$unparse(d.month), 2) stream...
http://rosettacode.org/wiki/Sylvester%27s_sequence
Sylvester's sequence
This page uses content from Wikipedia. The original article was at Sylvester's sequence. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance) In number theory, Sylvester's sequence is an integer sequenc...
#ALGOL_68
ALGOL 68
BEGIN # calculate elements of Sylvestor's Sequence # PR precision 200 PR # set the number of digits for LONG LONG modes # # returns an array set to the forst n elements of Sylvestor's Sequence # # starting from 2, the elements are the product of the previous # # ...
http://rosettacode.org/wiki/Sylvester%27s_sequence
Sylvester's sequence
This page uses content from Wikipedia. The original article was at Sylvester's sequence. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance) In number theory, Sylvester's sequence is an integer sequenc...
#Arturo
Arturo
sylvester: function [lim][ result: new [2] loop 2..lim 'x [ 'result ++ inc fold result .seed:1 [a b][a * b] ] return result ] lst: sylvester 10   print "First 10 terms of the Sylvester sequence:" print lst print ""   sumRep: round sum map lst => [1 // &]   print "Sum of the reciprocals of the fi...
http://rosettacode.org/wiki/Taxicab_numbers
Taxicab numbers
A   taxicab number   (the definition that is being used here)   is a positive integer that can be expressed as the sum of two positive cubes in more than one way. The first taxicab number is   1729,   which is: 13   +   123       and also 93   +   103. Taxicab numbers are also known as:   taxi numbers   tax...
#FreeBASIC
FreeBASIC
' version 11-10-2016 ' compile with: fbc -s console   ' Brute force   ' adopted from "Sorting algorithms/Shell" sort Task Sub shellsort(s() As String) ' sort from lower bound to the highter bound Dim As UInteger lb = LBound(s) Dim As UInteger ub = UBound(s) Dim As Integer done, i, inc = ub - lb   Do inc =...
http://rosettacode.org/wiki/Superpermutation_minimisation
Superpermutation minimisation
A superpermutation of N different characters is a string consisting of an arrangement of multiple copies of those N different characters in which every permutation of those characters can be found as a substring. For example, representing the characters as A..Z, using N=2 we choose to use the first two characters 'AB'...
#C.2B.2B
C++
#include <array> #include <iostream> #include <vector>   constexpr int MAX = 12;   static std::vector<char> sp; static std::array<int, MAX> count; static int pos = 0;   int factSum(int n) { int s = 0; int x = 0; int f = 1; while (x < n) { f *= ++x; s += f; } return s; }   bool r(...
http://rosettacode.org/wiki/Tau_number
Tau number
A Tau number is a positive integer divisible by the count of its positive divisors. Task Show the first   100   Tau numbers. The numbers shall be generated during run-time (i.e. the code may not contain string literals, sets/arrays of integers, or alike). Related task  Tau function
#MAD
MAD
NORMAL MODE IS INTEGER   INTERNAL FUNCTION(N) ENTRY TO POSDIV. COUNT = 1 THROUGH DIV, FOR I=2, 1, I.G.N DIV WHENEVER N/I*I.E.N, COUNT = COUNT+1 FUNCTION RETURN COUNT END OF FUNCTION   SEEN=0 ...
http://rosettacode.org/wiki/Tau_number
Tau number
A Tau number is a positive integer divisible by the count of its positive divisors. Task Show the first   100   Tau numbers. The numbers shall be generated during run-time (i.e. the code may not contain string literals, sets/arrays of integers, or alike). Related task  Tau function
#Mathematica.2FWolfram_Language
Mathematica/Wolfram Language
Take[Select[Range[10000], Divisible[#, Length[Divisors[#]]] &], 100]
http://rosettacode.org/wiki/Tau_number
Tau number
A Tau number is a positive integer divisible by the count of its positive divisors. Task Show the first   100   Tau numbers. The numbers shall be generated during run-time (i.e. the code may not contain string literals, sets/arrays of integers, or alike). Related task  Tau function
#Modula-2
Modula-2
MODULE TauNumbers; FROM InOut IMPORT WriteCard, WriteLn;   CONST MaxNum = 1100; (* enough to generate 100 Tau numbers *) NumTau = 100; (* how many Tau numbers to generate *)   VAR DivCount: ARRAY [1..MaxNum] OF CARDINAL; seen, n: CARDINAL;   (* Find the amount of divisors for each number beforehand *) PRO...
http://rosettacode.org/wiki/Tarjan
Tarjan
This page uses content from Wikipedia. The original article was at Graph. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance) Tarjan's algorithm is an algorithm in graph theory for finding the strongly...
#Rust
Rust
use std::collections::{BTreeMap, BTreeSet};   // Using a naked BTreeMap would not be very nice, so let's make a simple graph representation #[derive(Clone, Debug)] pub struct Graph { neighbors: BTreeMap<usize, BTreeSet<usize>>, }   impl Graph { pub fn new(size: usize) -> Self { Self { neighb...
http://rosettacode.org/wiki/Tarjan
Tarjan
This page uses content from Wikipedia. The original article was at Graph. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance) Tarjan's algorithm is an algorithm in graph theory for finding the strongly...
#Sidef
Sidef
func tarjan (k) {   var(:onstack, :index, :lowlink, *stack, *connected)   func strong_connect (vertex, i=0) {   index{vertex} = i lowlink{vertex} = i+1 onstack{vertex} = true stack << vertex   for connection in (k{vertex}) { if (index{connection} == ni...
http://rosettacode.org/wiki/Teacup_rim_text
Teacup rim text
On a set of coasters we have, there's a picture of a teacup.   On the rim of the teacup the word   TEA   appears a number of times separated by bullet characters   (•). It occurred to me that if the bullet were removed and the words run together,   you could start at any letter and still end up with a meaningful three...
#Python
Python
'''Teacup rim text'''   from itertools import chain, groupby from os.path import expanduser from functools import reduce     # main :: IO () def main(): '''Circular anagram groups, of more than one word, and containing words of length > 2, found in: https://www.mit.edu/~ecprice/wordlist.10000 ''' ...