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/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 ...
#GW-BASIC
GW-BASIC
10 FOR I = 0 TO 31 20 COLOR I, 7 - (I MOD 8) 30 PRINT I; 40 IF I MOD 4 = 3 THEN COLOR 7, 0 : PRINT 50 NEXT I
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 ...
#Haskell
Haskell
#!/usr/bin/runhaskell   import System.Console.ANSI   colorStrLn :: ColorIntensity -> Color -> ColorIntensity -> Color -> String -> IO () colorStrLn fgi fg bgi bg str = do setSGR [SetColor Foreground fgi fg, SetColor Background bgi bg] putStr str setSGR [] putStrLn ""   main = do colorStrLn Vivid White Vivid R...
http://rosettacode.org/wiki/Terminal_control/Cursor_movement
Terminal control/Cursor movement
Task Demonstrate how to achieve movement of the terminal cursor: how to move the cursor one position to the left how to move the cursor one position to the right how to move the cursor up one line (without affecting its horizontal position) how to move the cursor down one line (without affecting its horizontal po...
#Scala
Scala
object CursorMovement extends App { val ESC = "\u001B" // escape code   print(s"$ESC[2J$ESC[10;10H") // clear terminal first, move cursor to (10, 10) say val aecs = Seq( "[1D", // left "[1C", // right "[1A", // up "[1B", // down "[9D", // line start "[H", // top left "[24;79H" // botto...
http://rosettacode.org/wiki/Terminal_control/Cursor_movement
Terminal control/Cursor movement
Task Demonstrate how to achieve movement of the terminal cursor: how to move the cursor one position to the left how to move the cursor one position to the right how to move the cursor up one line (without affecting its horizontal position) how to move the cursor down one line (without affecting its horizontal po...
#Tcl
Tcl
# Simplification wrapper for when we're actually affecting the terminal proc tput args { exec tput {*}$args >@stdout <@stdin }   tput cub1; # one position to the left tput cuf1; # one position to the right tput cuu1; # up one line tput cud1; # down one...
http://rosettacode.org/wiki/Terminal_control/Cursor_movement
Terminal control/Cursor movement
Task Demonstrate how to achieve movement of the terminal cursor: how to move the cursor one position to the left how to move the cursor one position to the right how to move the cursor up one line (without affecting its horizontal position) how to move the cursor down one line (without affecting its horizontal po...
#UNIX_Shell
UNIX Shell
tput cub1 # one position to the left tput cuf1 # one position to the right tput cuu1 # up one line tput cud1 # down one line tput cr # beginning of line tput home # top left corner   # For line ends and bottom, we ne...
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...
#Apache_Derby
Apache Derby
CREATE TABLE Address ( addrID INTEGER PRIMARY KEY generated BY DEFAULT AS IDENTITY, addrStreet VARCHAR(50) NOT NULL, addrCity VARCHAR(50) NOT NULL, addrState CHAR(2) NOT NULL, addrZip CHAR(10) 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...
#Arturo
Arturo
db: open.sqlite "addresses.db"   query db {!sql CREATE TABLE address ( addrID INTEGER PRIMARY KEY AUTOINCREMENT, addrStreet TEXT NOT NULL, addrCity TEXT NOT NULL, addrState TEXT NOT NULL, addrZIP TEXT NOT NULL ) }   close db
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...
#Aime
Aime
#! /usr/local/bin/aime -a   if (argc() == 1) { file f; text s;   f.affix("NOTES.TXT");   while (~f.line(s)) { o_(s, "\n"); } } else { date d; file f;   f.open("NOTES.TXT", OPEN_APPEND | OPEN_CREATE | OPEN_WRITEONLY, 0644);   d.now;   f.form("/f4/-/f2/-/f2/ /f2/:/f2/:/f2/\...
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...
#APL
APL
#!/usr/local/bin/apl -s --   ∇r←ch Join ls ⍝ Join list of strings with character r←1↓∊ch,¨ls ∇   ∇d←Date ⍝ Get system date as formatted string d←'/'Join ⍕¨1⌽3↑⎕TS ∇   ∇t←Time;t24 ⍝ Get system time as formatted string ...
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...
#Clojure
Clojure
(ns test-project-intellij.core (:gen-class))   (defn cube [x] "Cube a number through triple multiplication" (* x x x))   (defn sum3 [[i j]] " [i j] -> i^3 + j^3" (+ (cube i) (cube j)))   (defn next-pair [[i j]] " Generate next [i j] pair of sequence (producing lower triangle pairs) " (if (< j i) [i ...
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
#Delphi
Delphi
  program Tau_number;   {$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; if...
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
#Draco
Draco
/* Generate a table of the amount of divisors for each number */ proc nonrec div_count([*]word divs) void: word max, i, j; max := dim(divs,1)-1; divs[0] := 0; for i from 1 upto max do divs[i] := 1 od; for i from 2 upto max do for j from i by i upto max do divs[j] := divs[j] + 1 ...
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...
#Go
Go
package main   import ( "fmt" "math/big" )   // (same data as zkl example) var g = [][]int{ 0: {1}, 2: {0}, 5: {2, 6}, 6: {5}, 1: {2}, 3: {1, 2, 4}, 4: {5, 3}, 7: {4, 7, 6}, }   func main() { tarjan(g, func(c []int) { fmt.Println(c) }) }   // the function calls the emit argum...
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...
#JavaScript
JavaScript
(() => { 'use strict';   // main :: IO () const main = () => showGroups( circularWords( // Local copy of: // https://www.mit.edu/~ecprice/wordlist.10000 lines(readFile('~/mitWords.txt')) ) );   // circularWords :: [S...
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...
#ALGOL_68
ALGOL 68
  BEGIN REAL kelvin; read (kelvin); FORMAT f = $g(8,2), " K = ", g(8,2)xgl$; printf ((f, kelvin, kelvin - 273.15, "C")); printf ((f, kelvin, 9.0 * kelvin / 5.0, "R")); printf ((f, kelvin, 9.0 * kelvin / 5.0 - 459.67, "F")) END
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
#BASIC
BASIC
10 DEFINT A-Z 20 FOR I=1 TO 100 30 N=I: GOSUB 100 40 PRINT USING " ##";T; 50 IF I MOD 20=0 THEN PRINT 60 NEXT 70 END 100 T=1 110 IF (N AND 1)=0 THEN N=N\2: T=T+1: GOTO 110 120 P=3 130 GOTO 180 140 C=1 150 IF N MOD P=0 THEN N=N\P: C=C+1: GOTO 150 160 T=T*C 170 P=P+2 180 IF P*P<=N GOTO 140 190 IF N>1 THEN T=T*2 200 RETUR...
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
#BCPL
BCPL
get "libhdr"   let tau(n) = valof $( let total = 1 and p = 3 while (n & 1) = 0 $( total := total + 1 n := n >> 1 $) while p*p <= n $( let count = 1 while n rem p = 0 $( count := count + 1 n := n / p $) total := total * count p := p + 2...
http://rosettacode.org/wiki/Terminal_control/Clear_the_screen
Terminal control/Clear the screen
Task Clear the terminal window.
#Comal
Comal
PAGE
http://rosettacode.org/wiki/Terminal_control/Clear_the_screen
Terminal control/Clear the screen
Task Clear the terminal window.
#Common_Lisp
Common Lisp
  (format t "~C[2J" #\Esc)  
http://rosettacode.org/wiki/Terminal_control/Clear_the_screen
Terminal control/Clear the screen
Task Clear the terminal window.
#D
D
extern (C) nothrow { void disp_open(); void disp_move(int, int); void disp_eeop(); void disp_close(); }   void main() { disp_open(); disp_move(0, 0); disp_eeop(); disp_close(); }
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...
#Go
Go
package main   import "fmt"   type trit int8   const ( trFalse trit = iota - 1 trMaybe trTrue )   func (t trit) String() string { switch t { case trFalse: return "False" case trMaybe: return "Maybe" case trTrue: return "True " } panic("Invalid trit") }   func ...
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...
#JavaScript
JavaScript
var filename = 'readings.txt'; var show_lines = 5; var file_stats = { 'num_readings': 0, 'total': 0, 'reject_run': 0, 'reject_run_max': 0, 'reject_run_date': '' };   var fh = new ActiveXObject("Scripting.FileSystemObject").openTextFile(filename, 1); // 1 = for reading while ( ! fh.atEndOfStream) { ...
http://rosettacode.org/wiki/The_ISAAC_Cipher
The ISAAC Cipher
ISAAC is a cryptographically secure pseudo-random number generator (CSPRNG) and stream cipher. It was developed by Bob Jenkins from 1993 (http://burtleburtle.net/bob/rand/isaac.html) and placed in the Public Domain. ISAAC is fast - especially when optimised - and portable to most architectures in nearly all programming...
#Wren
Wren
import "/trait" for Stepped import "/dynamic" for Enum import "/fmt" for Fmt   /* external results */ var randrsl = List.filled(256, 0) var randcnt = 0   /* internal state */ var mm = List.filled(256, 0) var aa = 0 var bb = 0 var cc = 0   var GOLDEN_RATIO = 0x9e3779b9   var isaac = Fn.new { cc = cc + 1 // cc jus...
http://rosettacode.org/wiki/Text_processing/Max_licenses_in_use
Text processing/Max licenses in use
A company currently pays a fixed sum for the use of a particular licensed software package.   In determining if it has a good deal it decides to calculate its maximum use of the software from its license management log file. Assume the software's licensing daemon faithfully records a checkout event when a copy of the ...
#Ursala
Ursala
  #import std #import nat   log = ^(~&hh==`O,~&tth)*FtPS sep` *F mlijobs_dot_txt scan = @NiX ~&ar^& ^C/~&alrhr2X ~&arlh?/~&faNlCrtPXPR ~&fabt2R search = @lSzyCrSPp leql$^&hl@lK2; ^/length@hl ~&rS format = ^|C\~& --' licenses in use at'@h+ %nP   #show+   main = format search scan log
http://rosettacode.org/wiki/Text_processing/Max_licenses_in_use
Text processing/Max licenses in use
A company currently pays a fixed sum for the use of a particular licensed software package.   In determining if it has a good deal it decides to calculate its maximum use of the software from its license management log file. Assume the software's licensing daemon faithfully records a checkout event when a copy of the ...
#Vedit_macro_language
Vedit macro language
  File_Open("|(PATH_ONLY)\data\mlijobs.txt", BROWSE)   #1 = 0 // Number of licenses active #2 = 0 // Max number of active licenses found   Repeat(ALL) { Search("|{OUT,IN}|W@", ADVANCE+ERRBREAK) if (Match_Item == 1) { // "OUT" #1++ if (#1 > #2) { ...
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.
#Ruby
Ruby
def palindrome?(s) s == s.reverse end   require 'test/unit' class MyTests < Test::Unit::TestCase def test_palindrome_ok assert(palindrome? "aba") end   def test_palindrome_nok assert_equal(false, palindrome?("ab")) end   def test_object_without_reverse assert_raise(NoMethodError) {palindrome? 42...
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.
#Rust
Rust
/// Tests if the given string slice is a palindrome (with the respect to /// codepoints, not graphemes). /// /// # Examples /// /// ``` /// # use playground::palindrome::is_palindrome; /// assert!(is_palindrome("abba")); /// assert!(!is_palindrome("baa")); /// ``` pub fn is_palindrome(s: &str) -> bool { let half = ...
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...
#Factor
Factor
USING: formatting io kernel math math.ranges qw sequences ; IN: rosetta-code.twelve-days-of-christmas   CONSTANT: opener "On the %s day of Christmas, my true love sent to me:\n"   CONSTANT: ordinals qw{ first second third fourth fifth sixth seventh eighth ninth tenth eleventh twelfth }   CONSTANT: gifts { ...
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...
#Forth
Forth
create ordinals s" first" 2, s" second" 2, s" third" 2, s" fourth" 2, s" fifth" 2, s" sixth" 2, s" seventh" 2, s" eighth" 2, s" ninth" 2, s" tenth" 2, s" eleventh" 2, s" twelfth" 2, : ordinal ordinals swap 2 * cells + 2@ ;   create gifts s" A partridge in a pear tree." 2, ...
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 ...
#J
J
NB. relies on an vt100 terminal   CSI=: 27 91 { a. 'BLACK BLUE CYAN WHITE'=: 0 4 6 7 'OFF REVERSEVIDEO'=: 0 7   HIDECURSOR=: CSI,'?25l' SHOWCURSOR=: CSI,'?25h'   csi=: (,~ (CSI , (' '&=)`(,:&';')}@:":))~ clear=: csi&'J' attributes=: csi&'m' color=: BLACK&$: : (attributes@:(40 30 + ,)) NB. BACKGROUND color FOREGROUND mo...
http://rosettacode.org/wiki/Terminal_control/Cursor_movement
Terminal control/Cursor movement
Task Demonstrate how to achieve movement of the terminal cursor: how to move the cursor one position to the left how to move the cursor one position to the right how to move the cursor up one line (without affecting its horizontal position) how to move the cursor down one line (without affecting its horizontal po...
#Wren
Wren
import "timer" for Timer import "io" for Stdout   System.write("\e[2J") // clear terminal System.write("\e[12;40H") // move to (12, 40) Stdout.flush() Timer.sleep(2000) System.write("\e[D") // move left Stdout.flush() Timer.sleep(2000) System.write("\e[C") // move right Stdout.flush() Timer.sleep(2000) Sy...
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...
#AWK
AWK
#!/bin/sh -f awk ' BEGIN { print "Creating table..." dbExec("address.db", "create table address (street, city, state, zip);") print "Done." exit }   function dbExec(db, qry, result) { dbMakeQuery(db, qry) | getline result dbErrorCheck(result) }   function dbMakeQuery(db, qry, q) { ...
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...
#AppleScript
AppleScript
#!/usr/bin/osascript   -- format a number as a string with leading zero if needed to format(aNumber) set resultString to aNumber as text if length of resultString < 2 set resultString to "0" & resultString end if return resultString end format   -- join a list with a delimiter to concatenation of aList give...
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...
#D
D
void main() /*@safe*/ { import std.stdio, std.range, std.algorithm, std.typecons, std.string;   auto iCubes = iota(1u, 1201u).map!(x => tuple(x, x ^^ 3)); bool[Tuple!(uint, uint)][uint] sum2cubes; foreach (i, immutable i3; iCubes) foreach (j, immutable j3; iCubes[i .. $]) sum2cubes[i...
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
#F.23
F#
  // Tau number. Nigel Galloway: March 9th., 2021 Seq.initInfinite((+)1)|>Seq.filter(fun n->n%(tau n)=0)|>Seq.take 100|>Seq.iter(printf "%d "); printfn ""  
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
#Factor
Factor
USING: assocs grouping io kernel lists lists.lazy math math.functions math.primes.factors prettyprint sequences sequences.extras ;   : tau ( n -- count ) group-factors values [ 1 + ] map-product ;   : tau? ( n -- ? ) dup tau divisor? ;   : taus ( -- list ) 1 lfrom [ tau? ] lfilter ;   ! Task "The first 100 tau numbers ...
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
#Fermat
Fermat
Func Istau(t) = if t<3 then Return(1) else numdiv:=2; for q = 2 to t\2 do if Divides(q, t) then numdiv:=numdiv+1 fi; od; if Divides(numdiv, t)=1 then Return(1) else Return(0) fi; fi; .;   numtau:=0; i:=0;   while numtau<100 do i:=i+1; if Istau(i) = 1 then ...
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...
#jq
jq
# Input: an integer def Node: { n: ., index: -1, # -1 signifies undefined lowLink: -1, onStack: false } ;   # Input: a DirectedGraph # Output: a stream of Node ids def successors($vn): .es[$vn][];   # Input: a DirectedGraph # Output: an array of integer arrays def tarjan: . + { sccs: [], # stro...
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...
#Julia
Julia
using LightGraphs   edge_list=[(1,2),(3,1),(6,3),(6,7),(7,6),(2,3),(4,2),(4,3),(4,5),(5,6),(5,4),(8,5),(8,8),(8,7)]   grph = SimpleDiGraph(Edge.(edge_list))   tarj = strongly_connected_components(grph)   inzerobase(arrarr) = map(x -> sort(x .- 1, rev=true), arrarr)   println("Results in the zero-base scheme: $(inzeroba...
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...
#Kotlin
Kotlin
// version 1.1.3   import java.util.Stack   typealias Nodes = List<Node>   class Node(val n: Int) { var index = -1 // -1 signifies undefined var lowLink = -1 var onStack = false   override fun toString() = n.toString() }   class DirectedGraph(val vs: Nodes, val es: Map<Node, Nodes>)   fun tarjan(g: ...
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...
#jq
jq
# Output: an array of the words when read around the rim def read_teacup: . as $in | [range(0; length) | $in[.:] + $in[:.] ];   # Boolean def is_teacup_word($dict): . as $in | all( range(1; length); . as $i | $dict[ $in[$i:] + $in[:$i] ]) ;   # Output: a stream of the eligible teacup words def teacup_words: d...
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...
#Julia
Julia
using HTTP   rotate(s, n) = String(circshift(Vector{UInt8}(s), n))   isliketea(w, d) = (n = length(w); n > 2 && any(c -> c != w[1], w) && all(i -> haskey(d, rotate(w, i)), 1:n-1))   function getteawords(listuri) req = HTTP.request("GET", listuri) wdict = Dict{String, Int}((lowercase(string(x)), 1) for x in...
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...
#ALGOL-M
ALGOL-M
BEGIN DECIMAL K, C, F, R; WRITE( "Temperature in Kelvin:" ); READ( K ); C := K - 273.15; F := K * 1.8 - 459.67; R := K * 1.8; WRITE( K, " Kelvin is equivalent to" ); WRITE( C, " degrees Celsius" ); WRITE( F, " degrees Fahrenheit" ); WRITE( R, " degrees Rankine" ); END
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
#BQN
BQN
Tau ← +´0=(1+↕)|⊢ Tau¨ 5‿20⥊1+↕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
#C
C
#include <stdio.h>   // See https://en.wikipedia.org/wiki/Divisor_function unsigned int divisor_count(unsigned int n) { unsigned int total = 1; // Deal with powers of 2 first for (; (n & 1) == 0; n >>= 1) { ++total; } // Odd prime factors up to the square root for (unsigned int p = 3; p ...
http://rosettacode.org/wiki/Terminal_control/Clear_the_screen
Terminal control/Clear the screen
Task Clear the terminal window.
#Dc
Dc
!clear
http://rosettacode.org/wiki/Terminal_control/Clear_the_screen
Terminal control/Clear the screen
Task Clear the terminal window.
#Delphi
Delphi
  uses System.SysUtils, Winapi.Windows;   procedure ClearScreen; var stdout: THandle; csbi: TConsoleScreenBufferInfo; ConsoleSize: DWORD; NumWritten: DWORD; Origin: TCoord; begin stdout := GetStdHandle(STD_OUTPUT_HANDLE); Win32Check(stdout<>INVALID_HANDLE_VALUE); Win32Check(GetConsoleScreenBufferInf...
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...
#Groovy
Groovy
enum Trit { TRUE, MAYBE, FALSE   private Trit nand(Trit that) { switch ([this,that]) { case { FALSE in it }: return TRUE case { MAYBE in it }: return MAYBE default  : return FALSE } } private Trit nor(Trit that) { this.or(that).not() }   ...
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...
#jq
jq
foreach STREAM as $row ( INITIAL; EXPRESSION; VALUE ).
http://rosettacode.org/wiki/Text_processing/Max_licenses_in_use
Text processing/Max licenses in use
A company currently pays a fixed sum for the use of a particular licensed software package.   In determining if it has a good deal it decides to calculate its maximum use of the software from its license management log file. Assume the software's licensing daemon faithfully records a checkout event when a copy of the ...
#Wren
Wren
import "io" for File   var lines = File.read("mlijobs.txt").replace("\r", "").split("\n") var out = 0 var max = 0 var times = [] for (line in lines) { if (line.startsWith("License OUT")) { out = out + 1 if (out >= max) { var sp = line.split(" ") if (out > max) { ...
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.
#Scala
Scala
import org.scalacheck._ import Prop._ import Gen._   object PalindromeCheck extends Properties("Palindrome") { property("A string concatenated with its reverse is a palindrome") = forAll { s: String => isPalindrome(s + s.reverse) }   property("A string concatenated with any character and its reverse is a palind...
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.
#Scheme
Scheme
  (import (srfi 64)) (test-begin "palindrome-tests") (test-assert (palindrome? "ingirumimusnocteetconsumimurigni")) (test-assert (not (palindrome? "This is not a palindrome"))) (test-equal #t (palindrome? "ingirumimusnocteetconsumimurigni")) ; another of several test functions (test-end)  
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...
#Fortran
Fortran
program twelve_days   character days(12)*8 data days/'first', 'second', 'third', 'fourth', c 'fifth', 'sixth', 'seventh', 'eighth', c 'ninth', 'tenth', 'eleventh', 'twelfth'/   character gifts(12)*27 data gifts/'A partridge in a pear tree.', c ...
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 ...
#Julia
Julia
  using AnsiColor   function showbasecolors() for color in keys(Base.text_colors) print_with_color(color, " ", string(color), " ") end println() end   function showansicolors() for fore in keys(AnsiColor.COLORS) print(@sprintf("%15s ", fore)) for back in keys(AnsiColor.COLORS) ...
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 ...
#Kotlin
Kotlin
// version 1.1.2   const val ESC = "\u001B" const val NORMAL = ESC + "[0" const val BOLD = ESC + "[1" const val BLINK = ESC + "[5" // not working on my machine const val BLACK = ESC + "[0;40m" // black background const val WHITE = ESC + "[0;37m" // normal white foreground   fun main(args: Array<String>) { ...
http://rosettacode.org/wiki/Terminal_control/Cursor_movement
Terminal control/Cursor movement
Task Demonstrate how to achieve movement of the terminal cursor: how to move the cursor one position to the left how to move the cursor one position to the right how to move the cursor up one line (without affecting its horizontal position) how to move the cursor down one line (without affecting its horizontal po...
#XPL0
XPL0
include c:\cxpl\codes; \intrinsic 'code' declarations int I, X, Y, W, H; [Cursor(10, 13); \set cursor to arbitrary location on screen I:= ChIn(1); \wait for keystroke (no echo to display) ChOut(0, $08\BS\); \backspace moves one position right I:= ChIn(1); X:= Peek($40, $50); \get cursor loca...
http://rosettacode.org/wiki/Terminal_control/Cursor_movement
Terminal control/Cursor movement
Task Demonstrate how to achieve movement of the terminal cursor: how to move the cursor one position to the left how to move the cursor one position to the right how to move the cursor up one line (without affecting its horizontal position) how to move the cursor down one line (without affecting its horizontal po...
#zkl
zkl
print("\e[2J\e[6;3H"); // clear screen, move to an initial position Atomic.sleep(1); // pause to let cursor blink print("\e[D"); // left Atomic.sleep(1); print("\e[C"); // right Atomic.sleep(1); print("\e[A"); // up Atomic.sleep(1); print("\e[B"); // down Atomic.sleep(1); print("\e[;H"); // top left...
http://rosettacode.org/wiki/Terminal_control/Cursor_movement
Terminal control/Cursor movement
Task Demonstrate how to achieve movement of the terminal cursor: how to move the cursor one position to the left how to move the cursor one position to the right how to move the cursor up one line (without affecting its horizontal position) how to move the cursor down one line (without affecting its horizontal po...
#ZX_Spectrum_Basic
ZX Spectrum Basic
10 PRINT CHR$(8);:REM cursor one position left 20 PRINT CHR$(9);:REM cursor one position right 30 GO SUB 500: REM get cursor position 40 IF cr>0 THEN LET cr=cr-1: GO SUB 550: REM cursor up one line 50 IF cr<22 THEN LET cr=cr+1: GO SUB 550: REM cursor down one line 60 POKE 23688,33: REM cursor to beginning of the line 7...
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...
#C
C
#include <stdio.h> #include <stdlib.h> #include <sqlite3.h>   const char *code = "CREATE TABLE address (\n" " addrID INTEGER PRIMARY KEY AUTOINCREMENT,\n" " addrStreet TEXT NOT NULL,\n" " addrCity TEXT NOT NULL,\n" " addrState TEXT NOT NULL,\n" " addrZIP TEXT NOT NULL)\n" ;   int main() { sqlite3 *db = 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...
#Clojure
Clojure
(require '[clojure.java.jdbc :as sql]) ; Using h2database for this simple example. (def db {:classname "org.h2.Driver"  :subprotocol "h2:file"  :subname "db/my-dbname"})   (sql/db-do-commands db (sql/create-table-ddl :address [:id "bigint primary key auto_increment"] [:street "varchar"] [:...
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...
#Arturo
Arturo
notes: "notes.txt" if? empty? arg [ if exists? notes -> print read notes ] else [ output: (to :string now) ++ "\n" ++ "\t" ++ (join.with:" " to [:string] arg) ++ "\n" write.append notes output ]
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...
#AutoHotkey
AutoHotkey
Notes := "Notes.txt"   If 0 = 0 ; no arguments { If FileExist(Notes) { FileRead, Content, %Notes% MsgBox, %Content% } Else MsgBox, %Notes% does not exist Goto, EOF }   ; date and time, colon, newline (CRLF), tab Date := A_DD "/" A_MM "/" A_YYYY Time := A_Hour ":" A_Min ":" A_Sec "." ...
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...
#DCL
DCL
$ close /nolog sums_of_cubes $ on control_y then $ goto clean $ open /write sums_of_cubes sums_of_cubes.txt $ i = 1 $ loop1: $ write sys$output i $ j = 1 $ loop2: $ sum = i * i * i + j * j * j $ if sum .lt. 0 $ then $ write sys$output "overflow at ", j $ goto next_i $ endif $ write sums_of_cubes f$fa...
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
#Forth
Forth
: divisor_count ( n -- n ) 1 >r begin dup 2 mod 0= while r> 1+ >r 2/ repeat 3 begin 2dup dup * >= while 1 >r begin 2dup mod 0= while r> 1+ >r tuck / swap repeat 2r> * >r 2 + repeat drop 1 > if r> 2* else r> then ;   : print_tau_numbers ( 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
#FreeBASIC
FreeBASIC
function numdiv( n as uinteger ) as uinteger dim as uinteger c = 2 for i as uinteger = 2 to (n+1)\2 if n mod i = 0 then c += 1 next i return c end function   function istau( n as uinteger ) as boolean if n = 1 then return true if n mod numdiv(n) = 0 then return true else return false end...
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...
#Nim
Nim
import sequtils, strutils, tables   type   Node = ref object val: int index: int lowLink: int onStack: bool   Nodes = seq[Node]   DirectedGraph = object nodes: seq[Node] edges: Table[int, Nodes]     func initNode(n: int): Node = Node(val: n, index: -1, lowLink: -1, onStack: false)     fu...
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...
#Perl
Perl
use strict; use warnings; use feature <say state current_sub>; use List::Util qw(min);   sub tarjan { my (%k) = @_; my (%onstack, %index, %lowlink, @stack, @connected);   my sub strong_connect { my ($vertex, $i) = @_; $index{$vertex} = $i; $lowlink{$vertex} = $i + 1; $onsta...
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...
#Lychen
Lychen
  const wc = new CS.System.Net.WebClient(); const lines = wc.DownloadString("http://wiki.puzzlers.org/pub/wordlists/unixdict.txt"); const words = lines.split(/\n/g); const collection = {}; words.filter(word => word.length > 2).forEach(word => { let allok = true; let newword = word; for (let i = 0; i < word.length...
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...
#Amazing_Hopper
Amazing Hopper
  /* MISTRAL - a flavour of Hopper */   #include <mistral.h>   INICIAR: TAMAÑO DE MEMORIA 20 temperatura=0 RECIBIR PARÁMETRO NUMÉRICO(2), GUARDAR EN (temperatura); TOMAR("KELVIN  : ",temperatura, NL) CON( "CELSIUS  : ", temperatura ), CALCULAR( Conversión Kelvin a Celsius ), NUEVA LÍNEA CON( ...
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
#C.2B.2B
C++
#include <iomanip> #include <iostream>   // See https://en.wikipedia.org/wiki/Divisor_function unsigned int divisor_count(unsigned int n) { unsigned int total = 1; // Deal with powers of 2 first for (; (n & 1) == 0; n >>= 1) ++total; // Odd prime factors up to the square root for (unsigned i...
http://rosettacode.org/wiki/Terminal_control/Clear_the_screen
Terminal control/Clear the screen
Task Clear the terminal window.
#Elena
Elena
public program() { console.clear() }
http://rosettacode.org/wiki/Terminal_control/Clear_the_screen
Terminal control/Clear the screen
Task Clear the terminal window.
#Erlang
Erlang
  clear()->io:format(os:cmd("clear")).  
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...
#Haskell
Haskell
import Prelude hiding (Bool(..), not, (&&), (||), (==))   main = mapM_ (putStrLn . unlines . map unwords) [ table "not" $ unary not , table "and" $ binary (&&) , table "or" $ binary (||) , table "implies" $ binary (=->) , table "equals" $ binary (==) ]   data Trit = False | Maybe |...
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...
#Julia
Julia
  using DataFrames   function mungdata(filename) lines = readlines(filename) numlines = length(lines) dates = Array{DateTime, 1}(numlines) means = zeros(Float64, numlines) numvalid = zeros(Int, numlines) invalidlength = zeros(Int, numlines) invalidpos = zeros(Int, numlines) datamatrix = ...
http://rosettacode.org/wiki/Text_processing/Max_licenses_in_use
Text processing/Max licenses in use
A company currently pays a fixed sum for the use of a particular licensed software package.   In determining if it has a good deal it decides to calculate its maximum use of the software from its license management log file. Assume the software's licensing daemon faithfully records a checkout event when a copy of the ...
#zkl
zkl
nOut,maxOut,maxTimes:=0,-1,List(); foreach job in (File("mlijobs.txt")){ _,status,_,date:=job.split(); nOut+=( if(status.toUpper()=="OUT") 1 else -1 ); if(nOut>maxOut){ maxOut=nOut; maxTimes.clear(); } if(nOut==maxOut) maxTimes.append(date); } println(("Maximum simultaneous license use is %d at" " ...
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.
#SQL_PL
SQL PL
  CREATE OR REPLACE PROCEDURE TEST_MY_TEST() BEGIN DECLARE EXPECTED INTEGER; DECLARE ACTUAL INTEGER; CALL DB2UNIT.REGISTER_MESSAGE('My first test'); SET EXPECTED = 2; SET ACTUAL = 1+1; CALL DB2UNIT.ASSERT_INT_EQUALS('Same value', EXPECTED, ACTUAL); END @  
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.
#Swift
Swift
import Cocoa import XCTest   class PalindromTests: XCTestCase {   override func setUp() { super.setUp()   }   override func tearDown() { super.tearDown() }   func testPalindrome() { // This is an example of a functional test case. XCTAssert(isPalindrome("abcba"), "Pas...
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...
#FreeBASIC
FreeBASIC
' version 10-01-2017 ' compile with: fbc -s console   Dim As ULong d, r   Dim As String days(1 To ...) = { "first", "second", "third", "fourth", _ "fifth", "sixth", "seventh", "eighth", _ "ninth", "tenth", "eleventh", "twelfth" }   Dim As String gifts(1 To ....
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 ...
#Lasso
Lasso
#!/usr/bin/lasso9   define ec(code::string) => {   local(esc = decode_base64('Gw==')) local(codes = map('esc' = #esc, 'normal' = #esc + '[0m', 'blink' = #esc + '[5;31;49m', 'red' = #esc + '[31;49m', 'blue' = #esc + '[34;49m', 'green' = #esc + '[32;49m', 'magenta' = #esc + '[35;49m', 'yellowred' = ...
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 ...
#Locomotive_Basic
Locomotive Basic
10 mode 1:defint a-z 20 print "Mode 1 (4 colors):" 30 for y=0 to 3 40 for x=0 to 3 50 pen x:paper y:print "Test"; 60 next 70 print 80 next 90 pen 1:paper 0 100 locate 1,25:print "<Press any key>";:call &bb06 110 ink 1,8,26 120 ink 2,21,17 130 locate 1,25:print "Flashing inks --- <Press any key>";:call &bb06 140 speed i...
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...
#Ada
Ada
package Synchronous_Concurrent is task Printer is entry Put(Item : in String); entry Get_Count(Count : out Natural); end Printer; end Synchronous_Concurrent;
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...
#EchoLisp
EchoLisp
  (lib 'struct) (lib 'sql)   (define Postal (make-table (struct postal (auto: id name street city state zip))))   Postal → #table:#struct:postal [id name street city state zip]:[0]   (table-insert Postal '(0 Gallubert "29 rue de l'Ermitage" Paris Seine 75020)) (table-insert Postal '(0 Brougnard "666 rue des Ca...
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...
#Erlang
Erlang
  -module( table_creation ).   -export( [task/0] ).   -record( address, {id, street, city, zip} ).   task() -> mnesia:start(), mnesia:create_table( address, [{attributes, record_info(fields, address)}] ).  
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...
#AWK
AWK
  # syntax: GAWK -f TAKE_NOTES.AWK [notes ... ] # examples: # GAWK -f TAKE_NOTES.AWK Hello world # GAWK -f TAKE_NOTES.AWK A "B C" D # GAWK -f TAKE_NOTES.AWK BEGIN { log_name = "NOTES.TXT" (ARGC == 1) ? show_log() : update_log() exit(0) } function show_log( rec) { while (getline rec <log_name > 0)...
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...
#Delphi
Delphi
  (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/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
#Frink
Frink
tau = {|x| x mod length[allFactors[x]] == 0} println[formatTable[columnize[first[select[count[1], tau], 100], 10], "right"]]
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
#Go
Go
package main   import "fmt"   func countDivisors(n int) int { count := 0 i := 1 k := 2 if n%2 == 0 { k = 1 } for i*i <= n { if n%i == 0 { count++ j := n / i if j != i { count++ } } i += k } re...
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...
#Phix
Phix
with javascript_semantics constant g = {{2}, {3}, {1}, {2,3,5}, {6,4}, {3,7}, {6}, {5,8,7}} sequence index, lowlink, stacked, stack integer x function strong_connect(integer n, emit) index[n] = x lowlink[n] = x stacked[n] = 1 stack &= n x += 1 for b=1 to length(g[n]) do integer nb = ...
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...
#Mathematica.2FWolfram_Language
Mathematica/Wolfram Language
ClearAll[Teacuppable] TeacuppableHelper[set_List] := Module[{f, s}, f = First[set]; s = StringRotateLeft[f, #] & /@ Range[Length[set]]; Sort[s] == Sort[set] ] Teacuppable[set_List] := Module[{ss, l}, l = StringLength[First[set]]; ss = Subsets[set, {l}]; Select[ss, TeacuppableHelper] ] s = Import["http:/...
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...
#Nim
Nim
import sequtils, sets, sugar   let words = collect(initHashSet, for word in "unixdict.txt".lines: {word})   proc rotate(s: var string) = let first = s[0] for i in 1..s.high: s[i - 1] = s[i] s[^1] = first   var result: seq[string] for word in "unixdict.txt".lines: if word.len >= 3: block checkWord: var...
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...
#APL
APL
CONVERT←{⍵,(⍵-273.15),(R-459.67),(R←⍵×9÷5)}
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
#CLU
CLU
tau = proc (n: int) returns (int) total: int := 1 while n//2 = 0 do total := total + 1 n := n/2 end p: int := 3 while p*p <= n do count: int := 1 while n//p = 0 do count := count + 1 n := n/p end total := total * count p...
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
#COBOL
COBOL
IDENTIFICATION DIVISION. PROGRAM-ID. TAU-FUNCTION.   DATA DIVISION. WORKING-STORAGE SECTION. 01 TAU-VARS. 03 TOTAL PIC 999. 03 N PIC 999. 03 FILLER REDEFINES N. 05 FILLER PIC 99. ...
http://rosettacode.org/wiki/Terminal_control/Clear_the_screen
Terminal control/Clear the screen
Task Clear the terminal window.
#Euphoria
Euphoria
clear_screen()
http://rosettacode.org/wiki/Terminal_control/Clear_the_screen
Terminal control/Clear the screen
Task Clear the terminal window.
#F.23
F#
open System   Console.Clear()
http://rosettacode.org/wiki/Terminal_control/Clear_the_screen
Terminal control/Clear the screen
Task Clear the terminal window.
#Forth
Forth
page
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...
#Icon_and_Unicon
Icon and Unicon
$define TRUE 1 $define FALSE -1 $define UNKNOWN 0   invocable all link printf   procedure main() # demonstrate ternary logic   ufunc := ["not3"] bfunc := ["and3", "or3", "xor3", "eq3", "ifthen3"]   every f := !ufunc do { # display unary functions printf("\nunary function=%s:\n",f) every t1 := (TRUE | FAL...
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...
#Kotlin
Kotlin
// version 1.2.31   import java.io.File   fun main(args: Array<String>) { val rx = Regex("""\s+""") val file = File("readings.txt") val fmt = "Line:  %s Reject: %2d Accept: %2d Line_tot: %7.3f Line_avg: %7.3f" var grandTotal = 0.0 var readings = 0 var date = "" var run = 0 var maxRun...
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.
#Tailspin
Tailspin
  templates palindrome [$...] -> # when <=$(last..first:-1)> do '$...;' ! end palindrome   test 'palindrome filter' assert 'rotor' -> palindrome <='rotor'> 'rotor is a palindrome' assert ['rosetta' -> palindrome] <=[]> 'rosetta is not a palindrome' end 'palindrome filter'  
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.
#Tcl
Tcl
package require tcltest 2 source palindrome.tcl; # Assume that this is what loads the implementation of ‘palindrome’   tcltest::test palindrome-1 {check for palindromicity} -body { palindrome abcdedcba } -result 1 tcltest::test palindrome-2 {check for non-palindromicity} -body { palindrome abcdef } -result 0 tc...