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/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...
#FreeBASIC
FreeBASIC
  redim shared as string Result(-1) 'represent our sets as strings; 'this'll do to illustrate the concept   sub sym( A() as string, B() as string ) dim as integer ai, bi, ri dim as boolean add_it for ai = lbound(A) to ubound(A) add_it = true for bi = lbound(...
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...
#PHP
PHP
  #!/usr/bin/php <?php if ($argc > 1) file_put_contents( 'notes.txt', date('r')."\n\t".implode(' ', array_slice($argv, 1))."\n", FILE_APPEND ); else @readfile('notes.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...
#PicoLisp
PicoLisp
#!/usr/bin/picolisp /usr/lib/picolisp/lib.l   (load "@lib/misc.l") (if (argv) (out "+notes.txt" (prinl (stamp) "^J^I" (glue " " @))) (and (info "notes.txt") (in "notes.txt" (echo))) ) (bye)
http://rosettacode.org/wiki/Superellipse
Superellipse
A superellipse is a geometric figure defined as the set of all points (x, y) with | x a | n + | y b | n = 1 , {\displaystyle \left|{\frac {x}{a}}\right|^{n}\!+\left|{\frac {y}{b}}\right|^{n}\!=1,} where n, a, and b are positive numbers. Task Draw a superellipse with n = 2.5, and a...
#Racket
Racket
#lang racket (require plot) #;(plot-new-window? #t)   (define ((superellipse a b n) x y) (+ (expt (abs (/ x a)) n) (expt (abs (/ y b)) n)))   (plot (isoline (superellipse 200 200 2.5) 1 -220 220 -220 220))
http://rosettacode.org/wiki/Superellipse
Superellipse
A superellipse is a geometric figure defined as the set of all points (x, y) with | x a | n + | y b | n = 1 , {\displaystyle \left|{\frac {x}{a}}\right|^{n}\!+\left|{\frac {y}{b}}\right|^{n}\!=1,} where n, a, and b are positive numbers. Task Draw a superellipse with n = 2.5, and a...
#Raku
Raku
constant a = 200; constant b = 200; constant n = 2.5;   # y in terms of x sub y ($x) { sprintf "%d", b * (1 - ($x / a).abs ** n ) ** (1/n) }   # find point pairs for one quadrant my @q = flat map -> \x { x, y(x) }, (0, 1 ... 200);   # Generate an SVG image INIT say qq:to/STOP/; <?xml version="1.0" standalone="no"?>...
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...
#Sidef
Sidef
var (start=1, end=25) = ARGV.map{.to_i}...   func display (h, start, end) { var i = start for n in [h.grep {|_,v| v.len > 1 }.keys.sort_by{.to_i}[start-1 .. end-1]] { printf("%4d %10d =>\t%s\n", i++, n, h{n}.map{ "%4d³ + %-s" % (.first, "#{.last}³") }.join(",\t")) } }   var taxi = Hash(...
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...
#F.23
F#
  // Define units of measure [<Measure>] type k [<Measure>] type f [<Measure>] type c [<Measure>] type r   // Define conversion functions let kelvinToCelsius (t : float<k>) = ((float t) - 273.15) * 1.0<c> let kelvinToFahrenheit (t : float<k>) = (((float t) * 1.8) - 459.67) * 1.0<f> let kelvinToRankine (t : float<k>) = ...
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...
#Run_BASIC
Run BASIC
testFalse = 0 ' F testDoNotKnow = 1 ' ? testTrue = 2 ' T   print "Short and long names for ternary logic values" for i = testFalse to testTrue print shortName3$(i);" ";longName3$(i) next i print   print "Single parameter functions" print "x";" ";"=x";" ";"not(x)" for i = testFalse to testTrue print shortNam...
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...
#Rust
Rust
use std::{ops, fmt};   #[derive(Copy, Clone, Debug)] enum Trit { True, Maybe, False, }   impl ops::Not for Trit { type Output = Self; fn not(self) -> Self { match self { Trit::True => Trit::False, Trit::Maybe => Trit::Maybe, Trit::False => Trit::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...
#Wren
Wren
import "io" for File import "/pattern" for Pattern import "/fmt" for Fmt   var p = Pattern.new("+1/s") var fileName = "readings.txt" var lines = File.read(fileName).trimEnd().split("\r\n") var f = "Line: $s Reject: $2d Accept: $2d Line_tot: $8.3f Line_avg: $7.3f" var grandTotal = 0 var readings = 0 var date = "" v...
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...
#q
q
  days:" "vs"first second third fourth fifth sixth seventh eighth ninth tenth eleventh twelfth"   gifts:( "Twelve drummers drumming"; "Eleven pipers piping"; "Ten lords a-leaping"; "Nine ladies dancing"; "Eight maids a-milking"; "Seven swans a-swimming"; "Six geese a-laying"; "Five golden rings"; "Fou...
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...
#Python
Python
import sys from Queue import Queue from threading import Thread   lines = Queue(1) count = Queue(1)   def read(file): try: for line in file: lines.put(line) finally: lines.put(None) print count.get()   def write(file): n = 0 while 1: line = lines.get() if ...
http://rosettacode.org/wiki/System_time
System time
Task Output the system time   (any units will do as long as they are noted) either by a system command or one built into the language. The system time can be used for debugging, network information, random number seeds, or something as simple as program performance. Related task   Date format See also   Retr...
#Crystal
Crystal
# current time in system's time zone: Time.local   # current time in UTC Time.utc   # monotonic time (useful for measuring elapsed time) Time.monotonic  
http://rosettacode.org/wiki/System_time
System time
Task Output the system time   (any units will do as long as they are noted) either by a system command or one built into the language. The system time can be used for debugging, network information, random number seeds, or something as simple as program performance. Related task   Date format See also   Retr...
#D
D
Stdout(Clock.now.span.days / 365).newline;
http://rosettacode.org/wiki/Summarize_and_say_sequence
Summarize and say sequence
There are several ways to generate a self-referential sequence. One very common one (the Look-and-say sequence) is to start with a positive integer, then generate the next term by concatenating enumerated groups of adjacent alike digits: 0, 10, 1110, 3110, 132110, 1113122110, 311311222110 ... The terms generat...
#Go
Go
package main   import ( "fmt" "strconv" )   func main() { var maxLen int var seqMaxLen [][]string for n := 1; n < 1e6; n++ { switch s := seq(n); { case len(s) == maxLen: seqMaxLen = append(seqMaxLen, s) case len(s) > maxLen: maxLen = len(s) ...
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...
#PureBasic
PureBasic
Structure point_f x.f y.f EndStructure   Procedure isInside(*p.point_f, *cp1.point_f, *cp2.point_f) If (*cp2\x - *cp1\x) * (*p\y - *cp1\y) > (*cp2\y - *cp1\y) * (*p\x - *cp1\x) ProcedureReturn 1 EndIf EndProcedure   Procedure intersection(*cp1.point_f, *cp2.point_f, *s.point_f, *e.point_f, *newPoint.poin...
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...
#Frink
Frink
A = new set["John", "Bob", "Mary", "Serena"] B = new set["Jim", "Mary", "John", "Bob"]   println["Symmetric difference: " + symmetricDifference[A,B]] println["A - B  : " + setDifference[A,B]] println["B - A  : " + setDifference[B,A]]
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...
#GAP
GAP
SymmetricDifference := function(a, b) return Union(Difference(a, b), Difference(b, a)); end;   a := ["John", "Serena", "Bob", "Mary", "Serena"]; b := ["Jim", "Mary", "John", "Jim", "Bob"]; SymmetricDifference(a,b); [ "Jim", "Serena" ]
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...
#PL.2FI
PL/I
NOTES: procedure (text) options (main); /* 8 April 2014 */ declare text character (100) varying; declare note_file file;   on undefinedfile(note_file) go to file_does_not_exist; open file (note_file) title ('/NOTES.TXT,recsize(100),type(text)'); revert error;   if text = '' then do; on ...
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...
#PowerShell
PowerShell
$notes = "notes.txt" if (($args).length -eq 0) { if(Test-Path $notes) { Get-Content $notes } } else { Get-Date | Add-Content $notes "`t" + $args -join " " | Add-Content $notes }
http://rosettacode.org/wiki/Superellipse
Superellipse
A superellipse is a geometric figure defined as the set of all points (x, y) with | x a | n + | y b | n = 1 , {\displaystyle \left|{\frac {x}{a}}\right|^{n}\!+\left|{\frac {y}{b}}\right|^{n}\!=1,} where n, a, and b are positive numbers. Task Draw a superellipse with n = 2.5, and a...
#REXX
REXX
/* REXX *************************************************************** * Create a BMP file showing a few super ellipses **********************************************************************/ Parse Version v If pos('Regina',v)>0 Then superegg='superegga.bmp' Else superegg='supereggo.bmp' 'erase' superegg s='424d46...
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...
#Swift
Swift
extension Array { func combinations(_ k: Int) -> [[Element]] { return Self._combinations(slice: self[startIndex...], k) }   static func _combinations(slice: Self.SubSequence, _ k: Int) -> [[Element]] { guard k != 1 else { return slice.map({ [$0] }) }   guard k != slice.count else { ret...
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...
#Tcl
Tcl
package require Tcl 8.6   proc heappush {heapName item} { upvar 1 $heapName heap set idx [lsearch -bisect -index 0 -integer $heap [lindex $item 0]] set heap [linsert $heap [expr {$idx + 1}] $item] } coroutine cubesum apply {{} { yield set h {} set n 1 while true { while {![llength $h] || [l...
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...
#Factor
Factor
USING: combinators formatting kernel math ; IN: rosetta-code.temperature   : k>c ( kelvin -- celsius ) 273.15 - ; : k>r ( kelvin -- rankine ) 9/5 * ; : k>f ( kelvin -- fahrenheit ) k>r 459.67 - ;   : convert ( kelvin -- ) { [ ] [ k>c ] [ k>f ] [ k>r ] } cleave "K  %.2f\nC  %.2f\nF  %.2f\nR  %.2f\n" printf...
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...
#Scala
Scala
sealed trait Trit { self => def nand(that:Trit):Trit=(this,that) match { case (TFalse, _) => TTrue case (_, TFalse) => TTrue case (TMaybe, _) => TMaybe case (_, TMaybe) => TMaybe case _ => TFalse }   def nor(that:Trit):Trit = this.or(that).not() def and(that:Trit):Trit = this.nand(that).not(...
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...
#Quackery
Quackery
[ [ table $ "first" $ "second" $ "third" $ "fourth" $ "fifth" $ "sixth" $ "seventh" $ "eighth" $ "ninth" $ "tenth" $ "eleventh" $ "twelfth" ] do echo$ ] is day ( n --> )   [ [ table $ "A partridge in a pear tree." $ "Two turtle doves...
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...
#R
R
  gifts <- c("A partridge in a pear tree.", "Two turtle doves and", "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") days <- c("first"...
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...
#Racket
Racket
  (define (reader) (for ([line (in-lines (open-input-file "input.txt"))]) (thread-send printer-thread line)) (thread-send printer-thread eof) (printf "Number of lines: ~a\n" (thread-receive)))   (define (printer) (thread-send reader-thread (for/sum ([line (in-producer thread-receive eof)]) ...
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...
#Raku
Raku
sub MAIN ($infile) { $infile.IO.lines ==> printer() ==> my $count; say "printed $count lines"; }   sub printer(*@lines) { my $lines; for @lines { .say; ++$lines; } $lines; }
http://rosettacode.org/wiki/System_time
System time
Task Output the system time   (any units will do as long as they are noted) either by a system command or one built into the language. The system time can be used for debugging, network information, random number seeds, or something as simple as program performance. Related task   Date format See also   Retr...
#DBL
DBL
XCALL TIME (D6)  ;D6=hhmmss
http://rosettacode.org/wiki/System_time
System time
Task Output the system time   (any units will do as long as they are noted) either by a system command or one built into the language. The system time can be used for debugging, network information, random number seeds, or something as simple as program performance. Related task   Date format See also   Retr...
#DCL
DCL
$ start_time = f$time() $ wait 0::10 $ end_time = f$time() $ write sys$output "start time was ", start_time $ write sys$output "end time was ", end_time $ write sys$output "delta time is ", f$delta_time( start_time, end_time )
http://rosettacode.org/wiki/Summarize_and_say_sequence
Summarize and say sequence
There are several ways to generate a self-referential sequence. One very common one (the Look-and-say sequence) is to start with a positive integer, then generate the next term by concatenating enumerated groups of adjacent alike digits: 0, 10, 1110, 3110, 132110, 1113122110, 311311222110 ... The terms generat...
#Groovy
Groovy
Number.metaClass.getSelfReferentialSequence = { def number = delegate as String; def sequence = []   while (!sequence.contains(number)) { sequence << number def encoded = new StringBuilder() ((number as List).sort().join('').reverse() =~ /(([0-9])\2*)/).each { matcher, text, digit -> encoded.appen...
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...
#Python
Python
  def clip(subjectPolygon, clipPolygon): def inside(p): return(cp2[0]-cp1[0])*(p[1]-cp1[1]) > (cp2[1]-cp1[1])*(p[0]-cp1[0])   def computeIntersection(): dc = [ cp1[0] - cp2[0], cp1[1] - cp2[1] ] dp = [ s[0] - e[0], s[1] - e[1] ] n1 = cp1[0] * cp2[1] - cp1[1] * cp2[0] n2 = s[0] * e[1]...
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...
#Go
Go
package main   import "fmt"   var a = map[string]bool{"John": true, "Bob": true, "Mary": true, "Serena": true} var b = map[string]bool{"Jim": true, "Mary": true, "John": true, "Bob": true}   func main() { sd := make(map[string]bool) for e := range a { if !b[e] { sd[e] = true } } ...
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...
#PureBasic
PureBasic
#FileName="notes.txt" Define argc=CountProgramParameters() If OpenConsole() If argc=0 If ReadFile(0,#FileName) While Eof(0)=0 PrintN(ReadString(0)) ; No new notes, so present the old Wend CloseFile(0) EndIf Else ; e.g. we have some arguments Define d$=FormatD...
http://rosettacode.org/wiki/Superellipse
Superellipse
A superellipse is a geometric figure defined as the set of all points (x, y) with | x a | n + | y b | n = 1 , {\displaystyle \left|{\frac {x}{a}}\right|^{n}\!+\left|{\frac {y}{b}}\right|^{n}\!=1,} where n, a, and b are positive numbers. Task Draw a superellipse with n = 2.5, and a...
#Scala
Scala
import java.awt._ import java.awt.geom.Path2D import java.util   import javax.swing._ import javax.swing.event.{ChangeEvent, ChangeListener}   object SuperEllipse extends App {   SwingUtilities.invokeLater(() => { new JFrame("Super Ellipse") {   class SuperEllipse extends JPanel with ChangeListener { ...
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...
#VBA
VBA
Public Type tuple i As Variant j As Variant sum As Variant End Type Public Type tuple3 i1 As Variant j1 As Variant i2 As Variant j2 As Variant i3 As Variant j3 As Variant sum As Variant End Type Sub taxicab_numbers() Dim i As Variant, j As Variant Dim k As Long Const ...
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...
#FOCAL
FOCAL
01.10 ASK "TEMPERATURE IN KELVIN", K 01.20 TYPE "K ", %6.02, K, ! 01.30 TYPE "C ", %6.02, K - 273.15, ! 01.40 TYPE "F ", %6.02, K * 1.8 - 459.67, ! 01.50 TYPE "R ", %6.02, K * 1.8, !
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...
#Forth
Forth
: k>°C ( F: kelvin -- celsius ) 273.15e0 f- ; : k>°R ( F: kelvin -- rankine ) 1.8e0 f* ; : °R>°F ( F: rankine -- fahrenheit ) 459.67e0 f- ; : k>°F ( F: kelvin -- fahrenheit ) k>°R °R>°F ; : main argc 1 > if 1 arg >float fdup f. ." K" cr fdup k>°C f. ." °C" cr fdup k>°F f. ." ...
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...
#Seed7
Seed7
$ include "seed7_05.s7i";   const type: trit is new enum False, Maybe, True end enum;   # Enum types define comparisons (=, <, >, <=, >=, <>) and # the conversions ord and conv.   const func string: str (in trit: aTrit) is return [] ("False", "Maybe", "True")[succ(ord(aTrit))];   enable_output(trit); # Allow w...
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...
#Racket
Racket
#lang racket (define (ordinal-text d) (vector-ref (vector "zeroth" "first" "second" "third" "fourth" "fifth" "sixth" "seventh" "eighth" "ninth" "tenth" "eleventh" "twelfth") d))   (define (on-the... day) (printf "On the ~a day of Christmas,~%" (ordinal-text day)) (printf "My True Love gave to me...
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...
#Raku
Raku
my @days = <first second third fourth fifth sixth seventh eighth ninth tenth eleventh twelfth>;   my @gifts = lines q:to/END/; 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, ...
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...
#Raven
Raven
'input.txt' as src_file   class Queue   new list as items condition as ready   define item_put items push ready notify   define item_get items empty if ready wait items shift   Queue as lines Queue as count   thread reader "file://r:%(src_file)s" open each lines.item_put ...
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...
#Ruby
Ruby
count = 0 IO.foreach("input.txt") { |line| print line; count += 1 } puts "Printed #{count} lines."
http://rosettacode.org/wiki/System_time
System time
Task Output the system time   (any units will do as long as they are noted) either by a system command or one built into the language. The system time can be used for debugging, network information, random number seeds, or something as simple as program performance. Related task   Date format See also   Retr...
#Delphi
Delphi
lblDateTime.Caption := FormatDateTime('dd mmmm yyyy hh:mm:ss', Now);
http://rosettacode.org/wiki/System_time
System time
Task Output the system time   (any units will do as long as they are noted) either by a system command or one built into the language. The system time can be used for debugging, network information, random number seeds, or something as simple as program performance. Related task   Date format See also   Retr...
#DWScript
DWScript
PrintLn(FormatDateTime('dd mmmm yyyy hh:mm:ss', Now));
http://rosettacode.org/wiki/Summarize_and_say_sequence
Summarize and say sequence
There are several ways to generate a self-referential sequence. One very common one (the Look-and-say sequence) is to start with a positive integer, then generate the next term by concatenating enumerated groups of adjacent alike digits: 0, 10, 1110, 3110, 132110, 1113122110, 311311222110 ... The terms generat...
#Haskell
Haskell
import Data.Set (Set, member, insert, empty) import Data.List (group, sort)   step :: String -> String step = concatMap (\list -> show (length list) ++ [head list]) . group . sort   findCycle :: (Ord a) => [a] -> [a] findCycle = aux empty where aux set (x : xs) | x `member` set = [] | otherwise = x : aux (insert x...
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...
#Racket
Racket
#lang racket   (module sutherland-hodgman racket (provide clip-to) (provide make-edges) (provide (struct-out point))   (struct point (x y) #:transparent) (struct edge (p1 p2) #:transparent) (struct polygon (points edges) #:transparent)   (define (make-edges points) (let ([points-shifted (match poi...
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...
#Groovy
Groovy
def symDiff = { Set s1, Set s2 -> assert s1 != null assert s2 != null (s1 + s2) - (s1.intersect(s2)) }
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...
#Haskell
Haskell
import Data.Set   a = fromList ["John", "Bob", "Mary", "Serena"] b = fromList ["Jim", "Mary", "John", "Bob"]   (-|-) :: Ord a => Set a -> Set a -> Set a x -|- y = (x \\ y) `union` (y \\ x) -- Equivalently: (x `union` y) \\ (x `intersect` y)
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...
#Python
Python
import sys, datetime, shutil   if len(sys.argv) == 1: try: with open('notes.txt', 'r') as f: shutil.copyfileobj(f, sys.stdout) except IOError: pass else: with open('notes.txt', 'a') as f: f.write(datetime.datetime.now().isoformat() + '\n') f.write("\t%s\n" % ' '.j...
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...
#R
R
#!/usr/bin/env Rscript --default-packages=methods   args <- commandArgs(trailingOnly=TRUE)   if (length(args) == 0) { conn <- file("notes.txt", 'r') cat(readLines(conn), sep="\n") } else { conn <- file("notes.txt", 'a') cat(file=conn, date(), "\n\t", paste(args, collapse=" "), "\n", sep="") } close(conn)
http://rosettacode.org/wiki/Superellipse
Superellipse
A superellipse is a geometric figure defined as the set of all points (x, y) with | x a | n + | y b | n = 1 , {\displaystyle \left|{\frac {x}{a}}\right|^{n}\!+\left|{\frac {y}{b}}\right|^{n}\!=1,} where n, a, and b are positive numbers. Task Draw a superellipse with n = 2.5, and a...
#Sidef
Sidef
const ( a = 200, b = 200, n = 2.5, )   # y in terms of x func y(x) { b * (1 - abs(x/a)**n -> root(n)) -> int }   func pline(q) { <<-"EOT"; <polyline points="#{q.join(' ')}" style="fill:none; stroke:black; stroke-width:3" transform="translate(#{a}, #{b})" /> EOT }   # Generate an SVG image sa...
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...
#Visual_Basic_.NET
Visual Basic .NET
  Imports System.Text   Module Module1   Function GetTaxicabNumbers(length As Integer) As IDictionary(Of Long, IList(Of Tuple(Of Integer, Integer))) Dim sumsOfTwoCubes As New SortedList(Of Long, IList(Of Tuple(Of Integer, Integer)))   For i = 1 To Integer.MaxValue - 1 For j = 1 To Intege...
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...
#Fortran
Fortran
Program Temperature implicit none   real :: kel, cel, fah, ran   write(*,*) "Input Kelvin temperature to convert" read(*,*) kel   call temp_convert(kel, cel, fah, ran) write(*, "((a10), f10.3)") "Kelvin", kel write(*, "((a10), f10.3)") "Celsius", cel write(*, "((a10), f10.3)") "Fahrenheit", fah write(...
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...
#Tcl
Tcl
package require Tcl 8.5 namespace eval ternary { # Code generator proc maketable {name count values} { set sep "" for {set i 0; set c 97} {$i<$count} {incr i;incr c} { set v [format "%c" $c] lappend args $v; append key $sep "$" $v set sep "," } foreach row [split $values \n] { if {[lleng...
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...
#REXX
REXX
/*REXX program displays the verses of the song: "The 12 days of Christmas". */ ordD= 'first second third fourth fifth sixth seventh eighth ninth tenth eleventh twelfth' pad= left('', 20) /*used for indenting the shown verses. */ @.1= 'A partridge in a pear-t...
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...
#Rust
Rust
use std::fs::File; use std::io::BufRead; use std::io::BufReader;   use std::sync::mpsc::{channel, sync_channel}; use std::thread;   fn main() { // The reader sends lines to the writer via an async channel, so the reader is never blocked. let (reader_send, writer_recv) = channel();   // The writer sends the ...
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...
#Scala
Scala
case class HowMany(asker: Actor)   val printer = actor { var count = 0 while (true) { receive { case line: String => print(line); count = count + 1 case HowMany(asker: Actor) => asker ! count; exit() } } }   def reader(printer: Actor) { scala.io.Source.fromFile("c:\\input.txt").getLi...
http://rosettacode.org/wiki/System_time
System time
Task Output the system time   (any units will do as long as they are noted) either by a system command or one built into the language. The system time can be used for debugging, network information, random number seeds, or something as simple as program performance. Related task   Date format See also   Retr...
#E
E
println(timer.now())
http://rosettacode.org/wiki/System_time
System time
Task Output the system time   (any units will do as long as they are noted) either by a system command or one built into the language. The system time can be used for debugging, network information, random number seeds, or something as simple as program performance. Related task   Date format See also   Retr...
#EasyLang
EasyLang
print timestr systime
http://rosettacode.org/wiki/Summarize_and_say_sequence
Summarize and say sequence
There are several ways to generate a self-referential sequence. One very common one (the Look-and-say sequence) is to start with a positive integer, then generate the next term by concatenating enumerated groups of adjacent alike digits: 0, 10, 1110, 3110, 132110, 1113122110, 311311222110 ... The terms generat...
#Icon_and_Unicon
Icon and Unicon
link printf   procedure main() every L := !longestselfrefseq(1000000) do every printf(" %i : %i\n",i := 1 to *L,L[i]) end     procedure longestselfrefseq(N) #: find longest sequences from 1 to N   mlen := 0 every L := selfrefseq(n := 1 to N) do { if mlen <:= *L then ML := [L] else if mlen = *L th...
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...
#Raku
Raku
sub intersection ($L11, $L12, $L21, $L22) { my ($Δ1x, $Δ1y) = $L11 »-« $L12; my ($Δ2x, $Δ2y) = $L21 »-« $L22; my $n1 = $L11[0] * $L12[1] - $L11[1] * $L12[0]; my $n2 = $L21[0] * $L22[1] - $L21[1] * $L22[0]; my $n3 = 1 / ($Δ1x * $Δ2y - $Δ2x * $Δ1y); (($n1 * $Δ2x - $n2 * $Δ1x) * $n3, ($n1 * $Δ2y - ...
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...
#HicEst
HicEst
CALL SymmDiff("John,Serena,Bob,Mary,Serena,", "Jim,Mary,John,Jim,Bob,") CALL SymmDiff("John,Bob,Mary,Serena,", "Jim,Mary,John,Bob,")   SUBROUTINE SymmDiff(set1, set2) CHARACTER set1, set2, answer*50 answer = " " CALL setA_setB( set1, set2, answer ) CALL setA_setB( set2, set1, answer ) WRITE(Messagebox,Name) a...
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...
#Racket
Racket
  #!/usr/bin/env racket #lang racket (define file "NOTES.TXT") (require racket/date) (command-line #:args notes (if (null? notes) (if (file-exists? file) (call-with-input-file* file (λ(i) (copy-port i (current-output-port)))) (raise-user-error 'notes "missing ~a file" file)) (call-with-out...
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...
#Raku
Raku
my $file = 'notes.txt';   multi MAIN() { print slurp($file); }   multi MAIN(*@note) { my $fh = open($file, :a); $fh.say: DateTime.now, "\n\t", @note; $fh.close; }
http://rosettacode.org/wiki/Superellipse
Superellipse
A superellipse is a geometric figure defined as the set of all points (x, y) with | x a | n + | y b | n = 1 , {\displaystyle \left|{\frac {x}{a}}\right|^{n}\!+\left|{\frac {y}{b}}\right|^{n}\!=1,} where n, a, and b are positive numbers. Task Draw a superellipse with n = 2.5, and a...
#Stata
Stata
sca a=200 sca b=200 sca n=2.5 twoway function y=b*(1-(abs(x/a))^n)^(1/n), range(-200 200) || function y=-b*(1-(abs(x/a))^n)^(1/n), range(-200 200)
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...
#Wren
Wren
import "/sort" for Sort import "/fmt" for Fmt   var cubesSum = {} var taxicabs = []   for (i in 1..1199) { for (j in i+1..1200) { var sum = i*i*i + j*j*j if (!cubesSum[sum]) { cubesSum[sum] = [i, j] } else { taxicabs.add([sum, cubesSum[sum], [i, j]]) } } }...
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...
#FreeBASIC
FreeBASIC
' FB 1.05.0 Win64   Sub convKelvin(temp As Double) Dim f As String = "####.##" Print Using f; temp; Print " degrees Kelvin" Print Using f; temp - 273.15; Print " degrees Celsius" Print Using f; (temp - 273.15) * 1.8 + 32.0; Print " degrees Fahreneit" Print Using f; (temp - 273.15) * 1.8 + 32.0 + 459.67...
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...
#True_BASIC
True BASIC
  FUNCTION and3(a, b) IF a < b then LET and3 = a else LET and3 = b END FUNCTION   FUNCTION eq3(a, b) IF a = tDontknow or b = tDontKnow then LET eq3 = tdontknow ELSEIF a = b then LET eq3 = ttrue ELSE LET eq3 = tfalse END IF END FUNCTION   FUNCTION longname3$(i) SELECT CASE i...
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...
#Ring
Ring
  # Project : The Twelve Days of Christmas   gifts = "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" days = "first se...
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...
#Ruby
Ruby
gifts = "A partridge in a pear tree Two turtle doves and 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".split("\n")   days = %w(first second third fourth fifth s...
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...
#Swift
Swift
// // Reader.swift //   import Foundation   class Reader: NSObject { let inputPath = "~/Desktop/input.txt".stringByExpandingTildeInPath var gotNumberOfLines = false   override init() { super.init() NSNotificationCenter.defaultCenter().addObserver(self, selector: "linesPrinted:", ...
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...
#SystemVerilog
SystemVerilog
program main;   mailbox#(bit) p2c_cmd = new; mailbox#(string) p2c_data = new; mailbox#(int) c2p_data = new;   initial begin int fh = $fopen("input.txt", "r"); string line; int count; while ($fgets(line, fh)) begin p2c_cmd.put(0); p2c_data.put(line); end p2c_cmd.put(1); c2p_data.get(co...
http://rosettacode.org/wiki/System_time
System time
Task Output the system time   (any units will do as long as they are noted) either by a system command or one built into the language. The system time can be used for debugging, network information, random number seeds, or something as simple as program performance. Related task   Date format See also   Retr...
#Elena
Elena
import extensions; import system'calendar;   public program() { console.printLine(Date.Now); }
http://rosettacode.org/wiki/System_time
System time
Task Output the system time   (any units will do as long as they are noted) either by a system command or one built into the language. The system time can be used for debugging, network information, random number seeds, or something as simple as program performance. Related task   Date format See also   Retr...
#Elixir
Elixir
:os.timestamp # => {MegaSecs, Secs, MicroSecs} :erlang.time # => {Hour, Minute, Second} :erlang.date # => {Year, Month, Day} :erlang.localtime # => {{Year, Month, Day}, {Hour, Minute, Second}} :erlang.universaltime # => {{Year, Month, Day},...
http://rosettacode.org/wiki/Summarize_and_say_sequence
Summarize and say sequence
There are several ways to generate a self-referential sequence. One very common one (the Look-and-say sequence) is to start with a positive integer, then generate the next term by concatenating enumerated groups of adjacent alike digits: 0, 10, 1110, 3110, 132110, 1113122110, 311311222110 ... The terms generat...
#J
J
require'stats' digits=: 10&#.inv"0 :. ([: ".@; (<'x'),~":&.>) summar=: (#/.~ ,@,. ~.)@\:~&.digits sequen=: ~.@(, summar@{:)^:_ values=: ~. \:~&.digits i.1e6 allvar=: [:(#~(=&<.&(10&^.) >./))@~.({~ perm@#)&.(digits"1)
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...
#Ruby
Ruby
Point = Struct.new(:x,:y) do def to_s; "(#{x}, #{y})" end end   def sutherland_hodgman(subjectPolygon, clipPolygon) # These inner functions reduce the argument passing to # "inside" and "intersection". cp1, cp2, s, e = nil inside = proc do |p| (cp2.x-cp1.x)*(p.y-cp1.y) > (cp2.y-cp1.y)*(p.x-cp1.x) end ...
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...
#Icon_and_Unicon
Icon and Unicon
procedure main()   a := set(["John", "Serena", "Bob", "Mary", "Serena"]) b := set(["Jim", "Mary", "John", "Jim", "Bob"])   showset("a",a) showset("b",b) showset("(a\\b) \xef (b\\a)",(a -- b) ++ (b -- a)) showset("(a\\b)",a -- b) showset("(b\\a)",b -- a) end     procedure showset(n,x) writes(n," = { ") every writes(!x...
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...
#REBOL
REBOL
rebol [ Title: "Notes" URL: http://rosettacode.org/wiki/Take_notes_on_the_command_line ]   notes: %notes.txt   either any [none? args: system/script/args empty? args] [ if exists? notes [print read notes] ] [ write/binary/append notes rejoin [now lf tab args lf] ]
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...
#REXX
REXX
/*REXX program implements the "NOTES" command (append text to a file from the C.L.).*/ timestamp=right(date(),11,0) time() date('W') /*create a (current) date & time stamp.*/ nFID = 'NOTES.TXT' /*the fileID of the "notes" file. */   if 'f2'x==2 then tab="05"x ...
http://rosettacode.org/wiki/Superellipse
Superellipse
A superellipse is a geometric figure defined as the set of all points (x, y) with | x a | n + | y b | n = 1 , {\displaystyle \left|{\frac {x}{a}}\right|^{n}\!+\left|{\frac {y}{b}}\right|^{n}\!=1,} where n, a, and b are positive numbers. Task Draw a superellipse with n = 2.5, and a...
#Wren
Wren
import "graphics" for Canvas, Color, Point   class Game { static init() { Canvas.resize(500, 500) // draw 200 concentric superellipses with gradually decreasing 'n'. for (a in 200..1) { superEllipse(a/80, a) } }   static update() {}   static draw(alpha) {}   ...
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...
#XPL0
XPL0
int N, I, J, SI, SJ, Count, Tally; [Count:= 0; N:= 0; repeat Tally:= 0; I:= 1; repeat J:= I+1; repeat if N = I*I*I + J*J*J then [Tally:= Tally+1; if Tally >= 2 then [Count:= Count+1; ...
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...
#zkl
zkl
fcn taxiCabNumbers{ const HeapSZ=0d5_000_000; iCubes:=[1..120].apply("pow",3); sum2cubes:=Data(HeapSZ).fill(0); // BFheap of 1 byte zeros taxiNums:=List(); foreach i,i3 in ([1..].zip(iCubes)){ foreach j,j3 in ([i+1..].zip(iCubes[i,*])){ ij3:=i3+j3; if(z:=sum2cubes[ij3]){ taxiNums....
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...
#Gambas
Gambas
Public Sub Form_Open() Dim fKelvin As Float   fKelvin = InputBox("Enter a Kelvin value", "Kelvin converter")   Print "Kelvin =\t" & Format(Str(fKelvin), "#.00") Print "Celsius =\t" & Format(Str(fKelvin - 273.15), "#.00") Print "Fahrenheit =\t" & Format(Str(fKelvin * 1.8 - 459.67), "#.00") Print "Rankine =\t" & Format(S...
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...
#Wren
Wren
var False = -1 var Maybe = 0 var True = 1 var Chrs = ["F", "M", "T"]   class Trit { construct new(v) { if (v != False && v != Maybe && v != True) Fiber.abort("Invalid argument.") _v = v }   v { _v }   ! { Trit.new(-_v) }   &(other) { (_v < other.v) ? this : other }   |(other...
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...
#Run_BASIC
Run BASIC
gifts$ = " 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"   days$ = "first second third fourth fifth sixt...
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...
#Rust
Rust
fn main() { let days = ["first", "second", "third", "fourth", "fifth", "sixth", "seventh", "eighth", "ninth", "tenth", "eleventh", "twelfth"];   let gifts = ["A Patridge in a Pear Tree", "Two Turtle Doves and", "Three French Hens", "Four Calling...
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...
#Tcl
Tcl
package require Thread   # Define the input thread set input [thread::create { proc readFile {filename receiver} { set f [open $filename] while {[gets $f line] >= 0} { thread::send $receiver [list line $line] } close $f thread::send $receiver lineCount lines puts "got $lines lines" } thread::wait...
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...
#TXR
TXR
(defstruct thread nil suspended cont (:method resume (self) [self.cont]) (:method give (self item) [self.cont item]) (:method get (self) (yield-from run nil)) (:method start (self) (set self.cont (obtain self.(run))) (unless self.suspended self.(resume))) (:postinit (self) se...
http://rosettacode.org/wiki/System_time
System time
Task Output the system time   (any units will do as long as they are noted) either by a system command or one built into the language. The system time can be used for debugging, network information, random number seeds, or something as simple as program performance. Related task   Date format See also   Retr...
#Emacs_Lisp
Emacs Lisp
(message "%s" (current-time-string)) ;; => "Wed Oct 14 22:21:05 1987"
http://rosettacode.org/wiki/System_time
System time
Task Output the system time   (any units will do as long as they are noted) either by a system command or one built into the language. The system time can be used for debugging, network information, random number seeds, or something as simple as program performance. Related task   Date format See also   Retr...
#Erlang
Erlang
1> os:timestamp(). {1250,222584,635452}
http://rosettacode.org/wiki/Summarize_and_say_sequence
Summarize and say sequence
There are several ways to generate a self-referential sequence. One very common one (the Look-and-say sequence) is to start with a positive integer, then generate the next term by concatenating enumerated groups of adjacent alike digits: 0, 10, 1110, 3110, 132110, 1113122110, 311311222110 ... The terms generat...
#Java
Java
import java.util.*; import java.util.concurrent.ConcurrentHashMap; import java.util.stream.IntStream;   public class SelfReferentialSequence {   static Map<String, Integer> cache = new ConcurrentHashMap<>(10_000);   public static void main(String[] args) { Seeds res = IntStream.range(0, 1000_000) ...
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...
#Rust
Rust
#[derive(Debug, Clone)] struct Point { x: f64, y: f64, }   #[derive(Debug, Clone)] struct Polygon(Vec<Point>);   fn is_inside(p: &Point, cp1: &Point, cp2: &Point) -> bool { (cp2.x - cp1.x) * (p.y - cp1.y) > (cp2.y - cp1.y) * (p.x - cp1.x) }   fn compute_intersection(cp1: &Point, cp2: &Point, s: &Point, e: &...
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...
#Scala
Scala
import javax.swing.{ JFrame, JPanel }   object SutherlandHodgman extends JFrame with App { import java.awt.BorderLayout   setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE) setVisible(true) val content = getContentPane() content.setLayout(new BorderLayout()) content.add(SutherlandHodgmanPanel, Borde...
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...
#J
J
A=: ~.;:'John Serena Bob Mary Serena' B=: ~. ;:'Jim Mary John Jim Bob'   (A-.B) , (B-.A) NB. Symmetric Difference ┌──────┬───┐ │Serena│Jim│ └──────┴───┘ A (-. , -.~) B NB. Tacit equivalent ┌──────┬───┐ │Serena│Jim│ └──────┴───┘
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...
#Ruby
Ruby
notes = 'NOTES.TXT' if ARGV.empty? File.copy_stream(notes, $stdout) rescue nil else File.open(notes, 'a') {|file| file.puts "%s\n\t%s" % [Time.now, ARGV.join(' ')]} end
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...
#Rust
Rust
extern crate chrono;   use std::fs::OpenOptions; use std::io::{self, BufReader, BufWriter}; use std::io::prelude::*; use std::env;   const FILENAME: &str = "NOTES.TXT";   fn show_notes() -> Result<(), io::Error> { let file = OpenOptions::new() .read(true) .create(true) // create the file if not foun...
http://rosettacode.org/wiki/Superellipse
Superellipse
A superellipse is a geometric figure defined as the set of all points (x, y) with | x a | n + | y b | n = 1 , {\displaystyle \left|{\frac {x}{a}}\right|^{n}\!+\left|{\frac {y}{b}}\right|^{n}\!=1,} where n, a, and b are positive numbers. Task Draw a superellipse with n = 2.5, and a...
#XPL0
XPL0
def X0=640/2, Y0=480/2, Scale=25.0, N=2.5; real X, Y; int IX, IY;   proc OctPoint; [ Point(X0+IX, Y0-IY, $F); Point(X0-IX, Y0-IY, $F); Point(X0+IX, Y0+IY, $F); Point(X0-IX, Y0+IY, $F); Point(X0+IY, Y0-IX, $F); Point(X0-IY, Y0-IX, $F); Point(X0+IY, Y0+IX, $F); Point(X0-IY, Y0+IX, $F); ];   [SetVid($101); \VESA graphi...
http://rosettacode.org/wiki/Superellipse
Superellipse
A superellipse is a geometric figure defined as the set of all points (x, y) with | x a | n + | y b | n = 1 , {\displaystyle \left|{\frac {x}{a}}\right|^{n}\!+\left|{\frac {y}{b}}\right|^{n}\!=1,} where n, a, and b are positive numbers. Task Draw a superellipse with n = 2.5, and a...
#Yabasic
Yabasic
open window 700, 600 backcolor 0,0,0 clear window   a=200 b=200 n=2.5 na=2/n t=.01 color 0,0,255 for i = 0 to 314 xp=a*sig(cos(t))*abs((cos(t)))^na+350 yp=b*sig(sin(t))*abs((sin(t)))^na+275 t=t+.02 line to xp, yp next i