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/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 program can be written to parse and transform the original data into a format useful to the other. The term "Data Munging" is often used in programming circles for this task. A request on the comp.lang.awk newsgroup led to a typical data munging task: I have to analyse data files that have the following format: Each row corresponds to 1 day and the field logic is: $1 is the date, followed by 24 value/flag pairs, representing measurements at 01:00, 02:00 ... 24:00 of the respective day. In short: <date> <val1> <flag1> <val2> <flag2> ... <val24> <flag24> Some test data is available at: ... (nolonger available at original location) I have to sum up the values (per day and only valid data, i.e. with flag>0) in order to calculate the mean. That's not too difficult. However, I also need to know what the "maximum data gap" is, i.e. the longest period with successive invalid measurements (i.e values with flag<=0) The data is free to download and use and is of this format: Data is no longer available at that link. Zipped mirror available here (offsite mirror). 1991-03-30 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 1991-03-31 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 20.000 1 20.000 1 20.000 1 35.000 1 50.000 1 60.000 1 40.000 1 30.000 1 30.000 1 30.000 1 25.000 1 20.000 1 20.000 1 20.000 1 20.000 1 20.000 1 35.000 1 1991-03-31 40.000 1 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 1991-04-01 0.000 -2 13.000 1 16.000 1 21.000 1 24.000 1 22.000 1 20.000 1 18.000 1 29.000 1 44.000 1 50.000 1 43.000 1 38.000 1 27.000 1 27.000 1 24.000 1 23.000 1 18.000 1 12.000 1 13.000 1 14.000 1 15.000 1 13.000 1 10.000 1 1991-04-02 8.000 1 9.000 1 11.000 1 12.000 1 12.000 1 12.000 1 27.000 1 26.000 1 27.000 1 33.000 1 32.000 1 31.000 1 29.000 1 31.000 1 25.000 1 25.000 1 24.000 1 21.000 1 17.000 1 14.000 1 15.000 1 12.000 1 12.000 1 10.000 1 1991-04-03 10.000 1 9.000 1 10.000 1 10.000 1 9.000 1 10.000 1 15.000 1 24.000 1 28.000 1 24.000 1 18.000 1 14.000 1 12.000 1 13.000 1 14.000 1 15.000 1 14.000 1 15.000 1 13.000 1 13.000 1 13.000 1 12.000 1 10.000 1 10.000 1 Only a sample of the data showing its format is given above. The full example file may be downloaded here. Structure your program to show statistics for each line of the file, (similar to the original Python, Perl, and AWK examples below), followed by summary statistics for the file. When showing example output just show a few line statistics and the full end summary.
#Sidef
Sidef
var gaps = []; var previous = :valid;   ARGF.each { |line| var (date, *readings) = line.words...; var valid = []; var hour = 0; readings.map{.to_n}.each_slice(2, { |slice| var(reading, flag) = slice...; if (flag > 0) { valid << reading; if (previous == :invalid) { gaps[-1]{:end} = "#{date} #{hour}:00"; previous = :valid; } } else { if (previous == :valid) { gaps << Hash(start => "#{date} #{hour}:00"); } gaps[-1]{:count} := 0 ++; previous = :invalid; } ++hour; }) say ("#{date}: #{ '%8s' % (valid ? ('%.3f' % Math.avg(valid...)) : 0) }", " mean from #{ '%2s' % valid.len } valid."); }   var longest = gaps.sort_by{|a| -a{:count} }.first;   say ("Longest period of invalid readings was #{longest{:count}} hours,\n", "from #{longest{:start}} till #{longest{: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 String length Copy a string Empty string  (assignment) Counting Word frequency Letter frequency Jewels and stones I before E except after C Bioinformatics/base count Count occurrences of a substring Count how many vowels and consonants occur in a string Remove/replace XXXX redacted Conjugate a Latin verb Remove vowels from a string String interpolation (included) Strip block comments Strip comments from a string Strip a set of characters from a string Strip whitespace from a string -- top and tail Strip control codes and extended characters from a string Anagrams/Derangements/shuffling Word wheel ABC problem Sattolo cycle Knuth shuffle Ordered words Superpermutation minimisation Textonyms (using a phone text pad) Anagrams Anagrams/Deranged anagrams Permutations/Derangements Find/Search/Determine ABC words Odd words Word ladder Semordnilap Word search Wordiff  (game) String matching Tea cup rim text Alternade words Changeable words State name puzzle String comparison Unique characters Unique characters in each string Extract file extension Levenshtein distance Palindrome detection Common list elements Longest common suffix Longest common prefix Compare a list of strings Longest common substring Find common directory path Words from neighbour ones Change e letters to i in words Non-continuous subsequences Longest common subsequence Longest palindromic substrings Longest increasing subsequence Words containing "the" substring Sum of the digits of n is substring of n Determine if a string is numeric Determine if a string is collapsible Determine if a string is squeezable Determine if a string has all unique characters Determine if a string has all the same characters Longest substrings without repeating characters Find words which contains all the vowels Find words which contains most consonants Find words which contains more than 3 vowels Find words which first and last three letters are equals Find words which odd letters are consonants and even letters are vowels or vice_versa Formatting Substring Rep-string Word wrap String case Align columns Literals/String Repeat a string Brace expansion Brace expansion using ranges Reverse a string Phrase reversals Comma quibbling Special characters String concatenation Substring/Top and tail Commatizing numbers Reverse words in a string Suffixation of decimal numbers Long literals, with continuations Numerical and alphabetical suffixes Abbreviations, easy Abbreviations, simple Abbreviations, automatic Song lyrics/poems/Mad Libs/phrases Mad Libs Magic 8-ball 99 Bottles of Beer The Name Game (a song) The Old lady swallowed a fly The Twelve Days of Christmas Tokenize Text between Tokenize a string Word break problem Tokenize a string with escaping Split a character string based on change of character Sequences Show ASCII table De Bruijn sequences Self-referential sequences Generate lower case ASCII alphabet
#Phixmonti
Phixmonti
include ..\Utilitys.pmt   ( "A partridge in a pear tree." "Two turtle doves, and" "Three French hens," "Four calling birds," "Five gold 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," )   ( "first" "second" "third" "fourth" "fifth" "sixth" "seventh" "eighth" "ninth" "tenth" "eleventh" "twelfth" )   10 tochar var cr   12 for >ps tps get "On the " swap " day of Christmas," cr "my true love gave to me:" 5 tolist lprint nl swap ( ps> 1 -1 ) for get ? endfor swap nl endfor
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 String length Copy a string Empty string  (assignment) Counting Word frequency Letter frequency Jewels and stones I before E except after C Bioinformatics/base count Count occurrences of a substring Count how many vowels and consonants occur in a string Remove/replace XXXX redacted Conjugate a Latin verb Remove vowels from a string String interpolation (included) Strip block comments Strip comments from a string Strip a set of characters from a string Strip whitespace from a string -- top and tail Strip control codes and extended characters from a string Anagrams/Derangements/shuffling Word wheel ABC problem Sattolo cycle Knuth shuffle Ordered words Superpermutation minimisation Textonyms (using a phone text pad) Anagrams Anagrams/Deranged anagrams Permutations/Derangements Find/Search/Determine ABC words Odd words Word ladder Semordnilap Word search Wordiff  (game) String matching Tea cup rim text Alternade words Changeable words State name puzzle String comparison Unique characters Unique characters in each string Extract file extension Levenshtein distance Palindrome detection Common list elements Longest common suffix Longest common prefix Compare a list of strings Longest common substring Find common directory path Words from neighbour ones Change e letters to i in words Non-continuous subsequences Longest common subsequence Longest palindromic substrings Longest increasing subsequence Words containing "the" substring Sum of the digits of n is substring of n Determine if a string is numeric Determine if a string is collapsible Determine if a string is squeezable Determine if a string has all unique characters Determine if a string has all the same characters Longest substrings without repeating characters Find words which contains all the vowels Find words which contains most consonants Find words which contains more than 3 vowels Find words which first and last three letters are equals Find words which odd letters are consonants and even letters are vowels or vice_versa Formatting Substring Rep-string Word wrap String case Align columns Literals/String Repeat a string Brace expansion Brace expansion using ranges Reverse a string Phrase reversals Comma quibbling Special characters String concatenation Substring/Top and tail Commatizing numbers Reverse words in a string Suffixation of decimal numbers Long literals, with continuations Numerical and alphabetical suffixes Abbreviations, easy Abbreviations, simple Abbreviations, automatic Song lyrics/poems/Mad Libs/phrases Mad Libs Magic 8-ball 99 Bottles of Beer The Name Game (a song) The Old lady swallowed a fly The Twelve Days of Christmas Tokenize Text between Tokenize a string Word break problem Tokenize a string with escaping Split a character string based on change of character Sequences Show ASCII table De Bruijn sequences Self-referential sequences Generate lower case ASCII alphabet
#PHP
PHP
  <?php   header("Content-Type: text/plain; charset=UTF-8");   $days = array( 'first', 'second', 'third', 'fourth', 'fifth', 'sixth', 'seventh', 'eighth', 'ninth', 'tenth', 'eleventh', 'twelfth', );   $gifts = array( "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" );   $verses = [];   for ( $i = 0; $i < 12; $i++ ) { $lines = []; $lines[0] = "On the {$days[$i]} day of Christmas, my true love gave to me";   $j = $i; $k = 0; while ( $j >= 0 ) { $lines[++$k] = $gifts[$j]; $j--; }   $verses[$i] = implode(PHP_EOL, $lines);   if ( $i == 0 ) $gifts[0] = "And a partridge in a pear tree"; }   echo implode(PHP_EOL . PHP_EOL, $verses);   ?>  
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 the term threads, others use the term tasks, while others use co-processes. This task should not be implemented using fork, spawn, or the Linux/UNIX/Win32 pipe command, as communication should be between threads, not processes. One of the concurrent units will read from a file named "input.txt" and send the contents of that file, one line at a time, to the other concurrent unit, which will print the line it receives to standard output. The printing unit must count the number of lines it prints. After the concurrent unit reading the file sends its last line to the printing unit, the reading unit will request the number of lines printed by the printing unit. The reading unit will then print the number of lines printed by the printing unit. This task requires two-way communication between the concurrent units. All concurrent units must cleanly terminate at the end of the program.
#ooRexx
ooRexx
  queue = .workqueue~new input = .stream~new("jabberwocky.txt") output = .output   reader = .filereader~new(input, queue) writer = .filewriter~new(output, queue)   ::class workQueue ::method init expose queue stopped actionpending queue = .queue~new stopped = .false actionPending = .false   -- add an item to the work queue. This is a -- guarded method, which means this is a synchronized access ::method addItem guarded expose queue actionPending use arg item -- add the item to the queue queue~queue(item) -- indicate there's something new. This is a condition variable -- that any will wake up any thread that's waiting on access. They'll -- be able to get access once we exit actionPending = .true   -- another method for coordinating access with the other thread. This indicates -- it is time to shut down ::method stop guarded expose actionPending stopped -- indicate this has been stopped and also flip the condition variable to -- wake up any waiters stopped = .true actionPending = .true   -- read the next item off of the queue. .nil indicates we've reached -- the last item on the queue. This is also a guarded method, but we'll use -- the GUARD ON instruction to wait for work if the queue is currently empty ::method nextItem expose queue stopped actionPending -- we might need to loop a little to get an item do forever -- if there's something on the queue, pull the front item and return if \queue~isEmpty then return queue~pull -- if the other thread says it is done sending is stuff, time to shut down if stopped then return .nil -- nothing on the queue, not stopped yet, so release the guard and wait until -- there's something pending to work on. guard on when actionPending end   -- one half of the synchronization effort. This will read lines and -- add them to the work queue. The thread will terminate once we hit end-of-file ::class filereader ::method init -- accept a generic stream...the data source need not be a file use arg stream, queue   reply -- now multithreaded   signal on notready loop forever queue~addItem(stream~linein) end -- we come here on an EOF condition. Indicate we're done and terminate -- the thread notready: queue~stop   -- the other end of this. This class will read lines from a work queue -- and write it to a stream ::class filewriter ::method init -- accept a generic stream...the data source need not be a file use arg stream, queue   reply -- now multithreaded   loop forever item = queue~nextItem -- .nil means last item received if item == .nil then return -- write to the stream stream~lineout(item) end  
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   Retrieving system time (wiki)
#Batch_File
Batch File
date /t time /t
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   Retrieving system time (wiki)
#BBC_BASIC
BBC BASIC
PRINT 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 generated grow in length geometrically and never converge. Another way to generate a self-referential sequence is to summarize the previous term. Count how many of each alike digit there is, then concatenate the sum and digit for each of the sorted enumerated digits. Note that the first five terms are the same as for the previous sequence. 0, 10, 1110, 3110, 132110, 13123110, 23124110 ... Sort the digits largest to smallest. Do not include counts of digits that do not appear in the previous term. Depending on the seed value, series generated this way always either converge to a stable value or to a short cyclical pattern. (For our purposes, I'll use converge to mean an element matches a previously seen element.) The sequence shown, with a seed value of 0, converges to a stable value of 1433223110 after 11 iterations. The seed value that converges most quickly is 22. It goes stable after the first element. (The next element is 22, which has been seen before.) Task Find all the positive integer seed values under 1000000, for the above convergent self-referential sequence, that takes the largest number of iterations before converging. Then print out the number of iterations and the sequence they return. Note that different permutations of the digits of the seed will yield the same sequence. For this task, assume leading zeros are not permitted. Seed Value(s): 9009 9090 9900 Iterations: 21 Sequence: (same for all three seeds except for first element) 9009 2920 192210 19222110 19323110 1923123110 1923224110 191413323110 191433125110 19151423125110 19251413226110 1916151413325110 1916251423127110 191716151413326110 191726151423128110 19181716151413327110 19182716151423129110 29181716151413328110 19281716151423228110 19281716151413427110 19182716152413228110 Related tasks   Fours is the number of letters in the ...   Look-and-say sequence   Number names   Self-describing numbers   Spelling of ordinal numbers Other tasks related to string operations: Metrics Array length String length Copy a string Empty string  (assignment) Counting Word frequency Letter frequency Jewels and stones I before E except after C Bioinformatics/base count Count occurrences of a substring Count how many vowels and consonants occur in a string Remove/replace XXXX redacted Conjugate a Latin verb Remove vowels from a string String interpolation (included) Strip block comments Strip comments from a string Strip a set of characters from a string Strip whitespace from a string -- top and tail Strip control codes and extended characters from a string Anagrams/Derangements/shuffling Word wheel ABC problem Sattolo cycle Knuth shuffle Ordered words Superpermutation minimisation Textonyms (using a phone text pad) Anagrams Anagrams/Deranged anagrams Permutations/Derangements Find/Search/Determine ABC words Odd words Word ladder Semordnilap Word search Wordiff  (game) String matching Tea cup rim text Alternade words Changeable words State name puzzle String comparison Unique characters Unique characters in each string Extract file extension Levenshtein distance Palindrome detection Common list elements Longest common suffix Longest common prefix Compare a list of strings Longest common substring Find common directory path Words from neighbour ones Change e letters to i in words Non-continuous subsequences Longest common subsequence Longest palindromic substrings Longest increasing subsequence Words containing "the" substring Sum of the digits of n is substring of n Determine if a string is numeric Determine if a string is collapsible Determine if a string is squeezable Determine if a string has all unique characters Determine if a string has all the same characters Longest substrings without repeating characters Find words which contains all the vowels Find words which contains most consonants Find words which contains more than 3 vowels Find words which first and last three letters are equals Find words which odd letters are consonants and even letters are vowels or vice_versa Formatting Substring Rep-string Word wrap String case Align columns Literals/String Repeat a string Brace expansion Brace expansion using ranges Reverse a string Phrase reversals Comma quibbling Special characters String concatenation Substring/Top and tail Commatizing numbers Reverse words in a string Suffixation of decimal numbers Long literals, with continuations Numerical and alphabetical suffixes Abbreviations, easy Abbreviations, simple Abbreviations, automatic Song lyrics/poems/Mad Libs/phrases Mad Libs Magic 8-ball 99 Bottles of Beer The Name Game (a song) The Old lady swallowed a fly The Twelve Days of Christmas Tokenize Text between Tokenize a string Word break problem Tokenize a string with escaping Split a character string based on change of character Sequences Show ASCII table De Bruijn sequences Self-referential sequences Generate lower case ASCII alphabet Also see   The On-Line Encyclopedia of Integer Sequences.
#Common_Lisp
Common Lisp
(defun count-and-say (str) (let* ((s (sort (map 'list #'identity str) #'char>)) (out (list (first s) 0))) (loop for x in s do (if (char= x (first out)) (incf (second out)) (setf out (nconc (list x 1) out)))) (format nil "~{~a~^~}" (nreverse out))))   (defun ref-seq-len (n &optional doprint) (let ((s (format nil "~d" n)) hist) (loop (push s hist) (if doprint (format t "~a~%" s)) (setf s (count-and-say s)) (loop for item in hist for i from 0 to 2 do (if (string= s item) (return-from ref-seq-len (length hist)))))))   (defun find-longest (top) (let (nums (len 0)) (dotimes (x top) (let ((l (ref-seq-len x))) (if (> l len) (setf len l nums nil)) (if (= l len) (push x nums)))) (list nums len)))   (let ((r (find-longest 1000000))) (format t "Longest: ~a~%" r) (ref-seq-len (first (first r)) t))
http://rosettacode.org/wiki/Summarize_primes
Summarize primes
Task Considering in order of length, n, all sequences of consecutive primes, p, from 2 onwards, where p < 1000 and n>0, select those sequences whose sum is prime, and for these display the length of the sequence, the last item in the sequence, and the sum.
#Raku
Raku
use Lingua::EN::Numbers;   my @primes = grep *.is-prime, ^Inf; my @primesums = [\+] @primes; say "{.elems} cumulative prime sums:\n", .map( -> $p { sprintf "The sum of the first %3d (up to {@primes[$p]}) is prime: %s", 1 + $p, comma @primesums[$p] } ).join("\n") given grep { @primesums[$_].is-prime }, ^1000;
http://rosettacode.org/wiki/Summarize_primes
Summarize primes
Task Considering in order of length, n, all sequences of consecutive primes, p, from 2 onwards, where p < 1000 and n>0, select those sequences whose sum is prime, and for these display the length of the sequence, the last item in the sequence, and the sum.
#REXX
REXX
/*REXX pgm finds summation primes P, primes which the sum of primes up to P are prime. */ parse arg hi . /*obtain optional argument from the CL.*/ if hi=='' | hi=="," then hi= 1000 /*Not specified? Then use the default.*/ call genP /*build array of semaphores for primes.*/ w= 30; w2= w*2%3; pad= left('',w-w2) /*the width of the columns two & three.*/ title= ' summation primes which the sum of primes up to P is also prime, P < ' , commas(hi) say ' index │' center(subword(title, 1, 2), w) center('prime sum', w) /*display title.*/ say '───────┼'center("" , 1 + (w+1)*2, '─') /* " sep. */ found= 0 /*initialize # of summation primes. */ $= 0 /*sum of primes up to the current prime*/ do j=1 for hi-1; p= @.j; $= $ + p /*find summation primes within range. */ if \!.$ then iterate /*Is sum─of─primes a prime? Then skip.*/ found= found + 1 /*bump the number of summation primes. */ say right(j, 6) '│'strip( right(commas(p), w2)pad || right(commas($), w2), "T") end /*j*/   say '───────┴'center("" , 1 + (w+1)*2, '─') /*display foot separator after output. */ say say 'Found ' commas(found) title exit 0 /*stick a fork in it, we're all done. */ /*──────────────────────────────────────────────────────────────────────────────────────*/ commas: parse arg ?; do jc=length(?)-3 to 1 by -3; ?=insert(',', ?, jc); end; return ? /*──────────────────────────────────────────────────────────────────────────────────────*/ genP: !.= 0; sP= 0 /*prime semaphores; sP= sum of primes.*/ @.1=2; @.2=3; @.3=5; @.4=7; @.5=11 /*define some low primes. */  !.2=1;  !.3=1;  !.5=1;  !.7=1;  !.11=1 /* " " " " flags. */ #=5; sq.#= @.# **2 /*number of primes so far; prime². */ /* [↓] generate more primes ≤ high.*/ do j=@.#+2 by 2 until @.#>=hi & @.#>sP /*find odd primes where P≥hi and P>sP.*/ parse var j '' -1 _; if _==5 then iterate /*J ÷ by 5? (right digit)*/ if j//3==0 then iterate; if j//7==0 then iterate /*J ÷ by 3?; J ÷ by 7? */ do k=5 while sq.k<=j /* [↓] divide by the known odd primes.*/ if j // @.k == 0 then iterate j /*Is J ÷ X? Then not prime. ___ */ end /*k*/ /* [↑] only process numbers ≤ √ J */ #= #+1; @.#= j; sq.#= j*j;  !.j= 1 /*bump # Ps; assign next P; P square; P*/ if @.#<hi then sP= sP + @.# /*maybe add this prime to sum─of─primes*/ end /*j*/; return
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 polygon that do not need to be displayed. Task Take the closed polygon defined by the points: [ ( 50 , 150 ) , ( 200 , 50 ) , ( 350 , 150 ) , ( 350 , 300 ) , ( 250 , 300 ) , ( 200 , 250 ) , ( 150 , 350 ) , ( 100 , 250 ) , ( 100 , 200 ) ] {\displaystyle [(50,150),(200,50),(350,150),(350,300),(250,300),(200,250),(150,350),(100,250),(100,200)]} and clip it by the rectangle defined by the points: [ ( 100 , 100 ) , ( 300 , 100 ) , ( 300 , 300 ) , ( 100 , 300 ) ] {\displaystyle [(100,100),(300,100),(300,300),(100,300)]} Print the sequence of points that define the resulting clipped polygon. Extra credit Display all three polygons on a graphical surface, using a different color for each polygon and filling the resulting polygon. (When displaying you may use either a north-west or a south-west origin, whichever is more convenient for your display mechanism.)
#Mathematica.2FWolfram_Language
Mathematica/Wolfram Language
p1 = Polygon[{{50, 150}, {200, 50}, {350, 150}, {350, 300}, {250, 300}, {200, 250}, {150, 350}, {100, 250}, {100, 200}}]; p2 = Polygon[{{100, 100}, {300, 100}, {300, 300}, {100, 300}}]; RegionIntersection[p1, p2] Graphics[{Red, p1, Blue, p2, Green, RegionIntersection[p1, p2]}]
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\cap B)} (the set of items that are in at least one of A or B minus the set of items that are in both A and B). Optionally, give the individual differences ( A ∖ B {\displaystyle A\setminus B} and B ∖ A {\displaystyle B\setminus A} ) as well. Test cases A = {John, Bob, Mary, Serena} B = {Jim, Mary, John, Bob} Notes If your code uses lists of items to represent sets then ensure duplicate items in lists are correctly handled. For example two lists representing sets of a = ["John", "Serena", "Bob", "Mary", "Serena"] and b = ["Jim", "Mary", "John", "Jim", "Bob"] should produce the result of just two strings: ["Serena", "Jim"], in any order. In the mathematical notation above A \ B gives the set of items in A that are not in B; A ∪ B gives the set of items in both A and B, (their union); and A ∩ B gives the set of items that are in both A and B (their intersection).
#Eiffel
Eiffel
note description: "Summary description for {SYMETRIC_DIFFERENCE_EXAMPLE}." URI: "http://rosettacode.org/wiki/Symmetric_difference"   class SYMETRIC_DIFFERENCE_EXAMPLE   create make   feature {NONE} -- Initialization   make local a,a1,b,b1: ARRAYED_SET [STRING] do create a.make (4) create b.make (4) a.compare_objects b.compare_objects a.put ("John") a.put ("Bob") a.put ("Mary") a.put ("Serena")   create a1.make (4) a1.copy (a)   b.put ("Jim") b.put ("Mary") b.put ("John") b.put ("Bob")   create b1.make (4) b1.copy (b)   a1.subtract (b1) b.subtract (a) a1.merge (b) across a1 as c loop print (" " + c.item) end end   end
http://rosettacode.org/wiki/Super-d_numbers
Super-d numbers
A super-d number is a positive, decimal (base ten) integer   n   such that   d × nd   has at least   d   consecutive digits   d   where 2 ≤ d ≤ 9 For instance, 753 is a super-3 number because 3 × 7533 = 1280873331. Super-d   numbers are also shown on   MathWorld™   as   super-d   or   super-d. Task Write a function/procedure/routine to find super-d numbers. For   d=2   through   d=6,   use the routine to show the first   10   super-d numbers. Extra credit Show the first   10   super-7, super-8, and/or super-9 numbers   (optional). See also   Wolfram MathWorld - Super-d Number.   OEIS: A014569 - Super-3 Numbers.
#zkl
zkl
var [const] BI=Import("zklBigNum"); // libGMP   fcn superDW(d){ digits:=d.toString()*d; [2..].tweak('wrap(n) { BI(n).pow(d).mul(d).toString().holds(digits) and n or Void.Skip }); } foreach d in ([2..8]){ println(d," : ",superDW(d).walk(10).concat(" ")) }
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 all the arguments, joined with spaces, prepended with a tab, and appended with a trailing newline, are written to NOTES.TXT. If NOTES.TXT doesn't already exist in the current directory then a new NOTES.TXT file should be created.
#Lua
Lua
filename = "NOTES.TXT"   if #arg == 0 then fp = io.open( filename, "r" ) if fp ~= nil then print( fp:read( "*all*" ) ) fp:close() end else fp = io.open( filename, "a+" )   fp:write( os.date( "%x %X\n" ) )   fp:write( "\t" ) for i = 1, #arg do fp:write( arg[i], " " ) end fp:write( "\n" )   fp:close() end
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 = b = 200
#Perl
Perl
my $a = 200; my $b = 200; my $n = 2.5;   # y in terms of x sub y_from_x { my($x) = @_; int $b * abs(1 - ($x / $a) ** $n ) ** (1/$n) }   # find point pairs for one quadrant push @q, $_, y_from_x($_) for 0..200;   # Generate an SVG image open $fh, '>', 'superellipse.svg'; print $fh qq|<svg height="@{[2*$b]}" width="@{[2*$a]}" xmlns="http://www.w3.org/2000/svg">\n|, pline( 1, 1, @q ), pline( 1,-1, @q ), # flip and mirror pline(-1,-1, @q ), # for the other pline(-1, 1, @q ), # three quadrants '</svg>';   sub pline { my($sx,$sy,@q) = @_;   for (0..$#q/2) { $q[ 2*$_] *= $sx; $q[1+2*$_] *= $sy; }   qq|<polyline points="@{[join ' ',@q]}" style="fill:none;stroke:black;stroke-width:3" transform="translate($a, $b)" />\n| }
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   taxi-cab numbers   taxi cab numbers   Hardy-Ramanujan numbers Task Compute and display the lowest 25 taxicab numbers (in numeric order, and in a human-readable format). For each of the taxicab numbers, show the number as well as it's constituent cubes. Extra credit Show the 2,000th taxicab number, and a half dozen more See also A001235: taxicab numbers on The On-Line Encyclopedia of Integer Sequences. Hardy-Ramanujan Number on MathWorld. taxicab number on MathWorld. taxicab number on Wikipedia   (includes the story on how taxi-cab numbers came to be called).
#Racket
Racket
#lang racket   (define (cube x) (* x x x))   ;floor of cubic root (define (cubic-root x) (let ([aprox (inexact->exact (round (expt x (/ 1 3))))]) (if (> (cube aprox) x) (- aprox 1) aprox)))   (let loop ([p 1] [n 1]) (let () (define pairs (for*/list ([j (in-range 1 (add1 (cubic-root (quotient n 2))))] [k (in-value (cubic-root (- n (cube j))))] #:when (= n (+ (cube j) (cube k)))) (cons j k))) (if (>= (length pairs) 2) (begin (printf "~a: ~a" p n) (for ([pair (in-list pairs)]) (printf " = ~a^3 + ~a^3" (car pair) (cdr pair))) (newline) (when (< p 25) (loop (add1 p) (add1 n)))) (loop p (add1 n)))))
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   taxi-cab numbers   taxi cab numbers   Hardy-Ramanujan numbers Task Compute and display the lowest 25 taxicab numbers (in numeric order, and in a human-readable format). For each of the taxicab numbers, show the number as well as it's constituent cubes. Extra credit Show the 2,000th taxicab number, and a half dozen more See also A001235: taxicab numbers on The On-Line Encyclopedia of Integer Sequences. Hardy-Ramanujan Number on MathWorld. taxicab number on MathWorld. taxicab number on Wikipedia   (includes the story on how taxi-cab numbers came to be called).
#Raku
Raku
constant @cu = (^Inf).map: { .³ }   sub MAIN ($start = 1, $end = 25) { my %taxi; my int $taxis = 0; my $terminate = 0; my int $max = 0;   for 1 .. * -> $c1 { last if ?$terminate && ($terminate < $c1); for 1 .. $c1 -> $c2 { my $this = @cu[$c1] + @cu[$c2]; %taxi{$this}.push: [$c2, $c1]; if %taxi{$this}.elems == 2 { ++$taxis; $max max= $this; } $terminate = ceiling $max ** (1/3) if $taxis == $end and !$terminate; } }   display( %taxi, $start, $end );   }   sub display (%this_stuff, $start, $end) { my $i = $start; printf "%4d %10d =>\t%s\n", $i++, $_.key, (.value.map({ sprintf "%4d³ + %-s\³", |$_ })).join: ",\t" for %this_stuff.grep( { $_.value.elems > 1 } ).sort( +*.key )[$start-1..$end-1]; }
http://rosettacode.org/wiki/Superpermutation_minimisation
Superpermutation minimisation
A superpermutation of N different characters is a string consisting of an arrangement of multiple copies of those N different characters in which every permutation of those characters can be found as a substring. For example, representing the characters as A..Z, using N=2 we choose to use the first two characters 'AB'. The permutations of 'AB' are the two, (i.e. two-factorial), strings: 'AB' and 'BA'. A too obvious method of generating a superpermutation is to just join all the permutations together forming 'ABBA'. A little thought will produce the shorter (in fact the shortest) superpermutation of 'ABA' - it contains 'AB' at the beginning and contains 'BA' from the middle to the end. The "too obvious" method of creation generates a string of length N!*N. Using this as a yardstick, the task is to investigate other methods of generating superpermutations of N from 1-to-7 characters, that never generate larger superpermutations. Show descriptions and comparisons of algorithms used here, and select the "Best" algorithm as being the one generating shorter superpermutations. The problem of generating the shortest superpermutation for each N might be NP complete, although the minimal strings for small values of N have been found by brute -force searches. Other tasks related to string operations: Metrics Array length String length Copy a string Empty string  (assignment) Counting Word frequency Letter frequency Jewels and stones I before E except after C Bioinformatics/base count Count occurrences of a substring Count how many vowels and consonants occur in a string Remove/replace XXXX redacted Conjugate a Latin verb Remove vowels from a string String interpolation (included) Strip block comments Strip comments from a string Strip a set of characters from a string Strip whitespace from a string -- top and tail Strip control codes and extended characters from a string Anagrams/Derangements/shuffling Word wheel ABC problem Sattolo cycle Knuth shuffle Ordered words Superpermutation minimisation Textonyms (using a phone text pad) Anagrams Anagrams/Deranged anagrams Permutations/Derangements Find/Search/Determine ABC words Odd words Word ladder Semordnilap Word search Wordiff  (game) String matching Tea cup rim text Alternade words Changeable words State name puzzle String comparison Unique characters Unique characters in each string Extract file extension Levenshtein distance Palindrome detection Common list elements Longest common suffix Longest common prefix Compare a list of strings Longest common substring Find common directory path Words from neighbour ones Change e letters to i in words Non-continuous subsequences Longest common subsequence Longest palindromic substrings Longest increasing subsequence Words containing "the" substring Sum of the digits of n is substring of n Determine if a string is numeric Determine if a string is collapsible Determine if a string is squeezable Determine if a string has all unique characters Determine if a string has all the same characters Longest substrings without repeating characters Find words which contains all the vowels Find words which contains most consonants Find words which contains more than 3 vowels Find words which first and last three letters are equals Find words which odd letters are consonants and even letters are vowels or vice_versa Formatting Substring Rep-string Word wrap String case Align columns Literals/String Repeat a string Brace expansion Brace expansion using ranges Reverse a string Phrase reversals Comma quibbling Special characters String concatenation Substring/Top and tail Commatizing numbers Reverse words in a string Suffixation of decimal numbers Long literals, with continuations Numerical and alphabetical suffixes Abbreviations, easy Abbreviations, simple Abbreviations, automatic Song lyrics/poems/Mad Libs/phrases Mad Libs Magic 8-ball 99 Bottles of Beer The Name Game (a song) The Old lady swallowed a fly The Twelve Days of Christmas Tokenize Text between Tokenize a string Word break problem Tokenize a string with escaping Split a character string based on change of character Sequences Show ASCII table De Bruijn sequences Self-referential sequences Generate lower case ASCII alphabet Reference The Minimal Superpermutation Problem. by Nathaniel Johnston. oeis A180632 gives 0-5 as 0, 1, 3, 9, 33, 153. 6 is thought to be 872. Superpermutations - Numberphile. A video Superpermutations: the maths problem solved by 4chan - Standupmaths. A video of recent (2018) mathematical progress. New Superpermutations Discovered! Standupmaths & Numberphile.
#zkl
zkl
const MAX = 12; var super=Data(), pos, cnt; // global state, ick   fcn fact_sum(n){ // -->1! + 2! + ... + n! [1..n].reduce(fcn(s,n){ s + [2..n].reduce('*,1) },0) }   fcn r(n){ if (not n) return(0);   c := super[pos - n]; if (not (cnt[n]-=1)){ cnt[n] = n; if (not r(n-1)) return(0); } super[pos] = c; pos+=1; 1 }   fcn superperm(n){ pos = n; len := fact_sum(n); super.fill(0,len); // this is pretty close to recalloc()   cnt = (n+1).pump(List()); //-->(0,1,2,3,..n) foreach i in (n){ super[i] = i + 0x31; } //-->"1" ... "123456789:;" while (r(n)){} }   foreach n in (MAX){ superperm(n); print("superperm(%2d) len = %d".fmt(n,super.len())); // uncomment next line to see the string itself //print(": %s".fmt(super.text)); println(); }
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 zero. The Fahrenheit and Rankine scales also have the same magnitude, but different null points. 0 degrees Fahrenheit corresponds to 459.67 degrees Rankine. 0 degrees Rankine is absolute zero. The Celsius/Kelvin and Fahrenheit/Rankine scales have a ratio of 5 : 9. Task Write code that accepts a value of kelvin, converts it to values of the three other scales, and prints the result. Example K 21.00 C -252.15 F -421.87 R 37.80
#EasyLang
EasyLang
k = number input print k & " °K" print k - 273.15 & " °C" print k * 1.8 - 459.67 & " °F" print k * 1.8 & " °R"
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 logic, sometimes abbreviated 3VL) is any of several many-valued logic systems in which there are three truth values indicating true, false and some indeterminate third value. This is contrasted with the more commonly known bivalent logics (such as classical sentential or boolean logic) which provide only for true and false. Conceptual form and basic ideas were initially created by Łukasiewicz, Lewis and Sulski. These were then re-formulated by Grigore Moisil in an axiomatic algebraic form, and also extended to n-valued logics in 1945. Example Ternary Logic Operators in Truth Tables: not a ¬ True False Maybe Maybe False True a and b ∧ True Maybe False True True Maybe False Maybe Maybe Maybe False False False False False a or b ∨ True Maybe False True True True True Maybe True Maybe Maybe False True Maybe False if a then b ⊃ True Maybe False True True Maybe False Maybe True Maybe Maybe False True True True a is equivalent to b ≡ True Maybe False True True Maybe False Maybe Maybe Maybe Maybe False False Maybe True Task Define a new type that emulates ternary logic by storing data trits. Given all the binary logic operators of the original programming language, reimplement these operators for the new Ternary logic type trit. Generate a sampling of results using trit variables. Kudos for actually thinking up a test case algorithm where ternary logic is intrinsically useful, optimises the test case algorithm and is preferable to binary logic. Note:   Setun   (Сетунь) was a   balanced ternary   computer developed in 1958 at   Moscow State University.   The device was built under the lead of   Sergei Sobolev   and   Nikolay Brusentsov.   It was the only modern   ternary computer,   using three-valued ternary logic
#Quackery
Quackery
  [ 2 ] is maybe ( --> t )   [ table 2 0 1 ] is jiggle ( t --> n )   [ jiggle 1+ ]this[ swap peek do ]done[ ] is 1-trit ( t --> t )   [ swap jiggle 1+ ]this[ swap peek swap jiggle peek do ]done[ ] is 2-trits ( t t --> t )   [ 1-trit $ "true" $ "maybe" $ "false" ] is trit$ ( t --> $ )   [ trit$ echo$ ] is echotrit ( t --> )   [ dup echotrit true = if sp ] is paddedtrit ( t --> )   ( true maybe false ) [ 1-trit false maybe true ] is t.not ( t --> t )   ( true maybe false ) [ 2-trits ( true ) [ false maybe true ] ( maybe ) [ maybe maybe true ] ( false ) [ true true true ] ] is t.nand ( t t --> t )   ( true maybe false ) [ 2-trits ( true ) [ true maybe false ] ( maybe ) [ maybe maybe false ] ( false ) [ false false false ] ] is t.and ( t t --> t )   ( true maybe false ) [ 2-trits ( true ) [ true true true ] ( maybe ) [ true maybe maybe ] ( false ) [ true maybe false ] ] is t.or ( t t --> t )   ( true maybe false ) [ 2-trits ( true ) [ false maybe true ] ( maybe ) [ maybe maybe maybe ] ( false ) [ true maybe false ] ] is t.xor ( t t --> t )   ( Quackery does not have operators for material implication (if a then b, a implies b) or material equivalence (a ≣ b, A <=> b). However, The Book of Quackery notes that they can be defined as: "[ swap not or ] is implies ( a b --> c )" "[ xor not ] is <=> ( a b --> c )" so we will adapt these to test some of the ternary operators. )   [ swap t.not t.or ] is t.implies ( t t --> t )   [ t.xor t.not ] is t.<=> ( t t --> t )   cr say " t.not | true | maybe | false" cr say " ---------------------------------" cr say " | " true t.not paddedtrit sp say "| " maybe t.not paddedtrit sp say "| " false t.not paddedtrit cr cr say " t.and | true | maybe | false" cr say " ---------------------------------" cr say " true | " true true t.and paddedtrit sp say "| " true maybe t.and paddedtrit sp say "| " true false t.and paddedtrit cr say " maybe | " maybe true t.and paddedtrit sp say "| " maybe maybe t.and paddedtrit sp say "| " maybe false t.and paddedtrit cr say " false | " false true t.and paddedtrit sp say "| " false maybe t.and paddedtrit sp say "| " false false t.and paddedtrit cr cr say " t.or | true | maybe | false" cr say " ---------------------------------" cr say " true | " true true t.or paddedtrit sp say "| " true maybe t.or paddedtrit sp say "| " true false t.or paddedtrit cr say " maybe | " maybe true t.or paddedtrit sp say "| " maybe maybe t.or paddedtrit sp say "| " maybe false t.or paddedtrit cr say " false | " false true t.or paddedtrit sp say "| " false maybe t.or paddedtrit sp say "| " false false t.or paddedtrit cr cr say " t.implies | true | maybe | false" cr say " ---------------------------------" cr say " true | " true true t.implies paddedtrit sp say "| " true maybe t.implies paddedtrit sp say "| " true false t.implies paddedtrit cr say " maybe | " maybe true t.implies paddedtrit sp say "| " maybe maybe t.implies paddedtrit sp say "| " maybe false t.implies paddedtrit cr say " false | " false true t.implies paddedtrit sp say "| " false maybe t.implies paddedtrit sp say "| " false false t.implies paddedtrit cr cr say " t.<=> | true | maybe | false" cr say " ---------------------------------" cr say " true | " true true t.<=> paddedtrit sp say "| " true maybe t.<=> paddedtrit sp say "| " true false t.<=> paddedtrit cr say " maybe | " maybe true t.<=> paddedtrit sp say "| " maybe maybe t.<=> paddedtrit sp say "| " maybe false t.<=> paddedtrit cr say " false | " false true t.<=> paddedtrit sp say "| " false maybe t.<=> paddedtrit sp say "| " false false t.<=> paddedtrit cr
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 logic, sometimes abbreviated 3VL) is any of several many-valued logic systems in which there are three truth values indicating true, false and some indeterminate third value. This is contrasted with the more commonly known bivalent logics (such as classical sentential or boolean logic) which provide only for true and false. Conceptual form and basic ideas were initially created by Łukasiewicz, Lewis and Sulski. These were then re-formulated by Grigore Moisil in an axiomatic algebraic form, and also extended to n-valued logics in 1945. Example Ternary Logic Operators in Truth Tables: not a ¬ True False Maybe Maybe False True a and b ∧ True Maybe False True True Maybe False Maybe Maybe Maybe False False False False False a or b ∨ True Maybe False True True True True Maybe True Maybe Maybe False True Maybe False if a then b ⊃ True Maybe False True True Maybe False Maybe True Maybe Maybe False True True True a is equivalent to b ≡ True Maybe False True True Maybe False Maybe Maybe Maybe Maybe False False Maybe True Task Define a new type that emulates ternary logic by storing data trits. Given all the binary logic operators of the original programming language, reimplement these operators for the new Ternary logic type trit. Generate a sampling of results using trit variables. Kudos for actually thinking up a test case algorithm where ternary logic is intrinsically useful, optimises the test case algorithm and is preferable to binary logic. Note:   Setun   (Сетунь) was a   balanced ternary   computer developed in 1958 at   Moscow State University.   The device was built under the lead of   Sergei Sobolev   and   Nikolay Brusentsov.   It was the only modern   ternary computer,   using three-valued ternary logic
#Racket
Racket
#lang typed/racket   ; to avoid the hassle of adding a maybe value that is as special as ; the two standard booleans, we'll use symbols to make our own (define-type trit (U 'true 'false 'maybe))   (: not (trit -> trit)) (define (not a) (case a [(true) 'false] [(maybe) 'maybe] [(false) 'true]))   (: and (trit trit -> trit)) (define (and a b) (case a [(false) 'false] [(maybe) (case b [(false) 'false] [else 'maybe])] [(true) (case b [(true) 'true] [(maybe) 'maybe] [(false) 'false])]))   (: or (trit trit -> trit)) (define (or a b) (case a [(true) 'true] [(maybe) (case b [(true) 'true] [else 'maybe])] [(false) (case b [(true) 'true] [(maybe) 'maybe] [(false) 'false])]))   (: ifthen (trit trit -> trit)) (define (ifthen a b) (case b [(true) 'true] [(maybe) (case a [(false) 'true] [else 'maybe])] [(false) (case a [(true) 'false] [(maybe) 'maybe] [(false) 'true])]))   (: iff (trit trit -> trit)) (define (iff a b) (case a [(maybe) 'maybe] [(true) b] [(false) (not b)]))   (for: : Void ([a (in-list '(true maybe false))]) (printf "~a ~a = ~a~n" (object-name not) a (not a))) (for: : Void ([proc (in-list (list and or ifthen iff))]) (for*: : Void ([a (in-list '(true maybe false))] [b (in-list '(true maybe false))]) (printf "~a ~a ~a = ~a~n" a (object-name proc) b (proc a b))))
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 program can be written to parse and transform the original data into a format useful to the other. The term "Data Munging" is often used in programming circles for this task. A request on the comp.lang.awk newsgroup led to a typical data munging task: I have to analyse data files that have the following format: Each row corresponds to 1 day and the field logic is: $1 is the date, followed by 24 value/flag pairs, representing measurements at 01:00, 02:00 ... 24:00 of the respective day. In short: <date> <val1> <flag1> <val2> <flag2> ... <val24> <flag24> Some test data is available at: ... (nolonger available at original location) I have to sum up the values (per day and only valid data, i.e. with flag>0) in order to calculate the mean. That's not too difficult. However, I also need to know what the "maximum data gap" is, i.e. the longest period with successive invalid measurements (i.e values with flag<=0) The data is free to download and use and is of this format: Data is no longer available at that link. Zipped mirror available here (offsite mirror). 1991-03-30 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 1991-03-31 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 20.000 1 20.000 1 20.000 1 35.000 1 50.000 1 60.000 1 40.000 1 30.000 1 30.000 1 30.000 1 25.000 1 20.000 1 20.000 1 20.000 1 20.000 1 20.000 1 35.000 1 1991-03-31 40.000 1 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 1991-04-01 0.000 -2 13.000 1 16.000 1 21.000 1 24.000 1 22.000 1 20.000 1 18.000 1 29.000 1 44.000 1 50.000 1 43.000 1 38.000 1 27.000 1 27.000 1 24.000 1 23.000 1 18.000 1 12.000 1 13.000 1 14.000 1 15.000 1 13.000 1 10.000 1 1991-04-02 8.000 1 9.000 1 11.000 1 12.000 1 12.000 1 12.000 1 27.000 1 26.000 1 27.000 1 33.000 1 32.000 1 31.000 1 29.000 1 31.000 1 25.000 1 25.000 1 24.000 1 21.000 1 17.000 1 14.000 1 15.000 1 12.000 1 12.000 1 10.000 1 1991-04-03 10.000 1 9.000 1 10.000 1 10.000 1 9.000 1 10.000 1 15.000 1 24.000 1 28.000 1 24.000 1 18.000 1 14.000 1 12.000 1 13.000 1 14.000 1 15.000 1 14.000 1 15.000 1 13.000 1 13.000 1 13.000 1 12.000 1 10.000 1 10.000 1 Only a sample of the data showing its format is given above. The full example file may be downloaded here. Structure your program to show statistics for each line of the file, (similar to the original Python, Perl, and AWK examples below), followed by summary statistics for the file. When showing example output just show a few line statistics and the full end summary.
#Swift
Swift
import Foundation   let fmtDbl = { String(format: "%10.3f", $0) }   Task.detached { let formatter = DateFormatter()   formatter.dateFormat = "yyyy-MM-dd"   let (data, _) = try await URLSession.shared.bytes(from: URL(fileURLWithPath: CommandLine.arguments[1])) var rowStats = [(Date, Double, Int)]() var invalidPeriods = 0 var invalidStart: Date? var sumFile = 0.0 var readings = 0 var longestInvalid = 0 var longestInvalidStart: Date? var longestInvalidEnd: Date?   for try await line in data.lines { let lineSplit = line.components(separatedBy: "\t")   guard !lineSplit.isEmpty, let date = formatter.date(from: lineSplit[0]) else { fatalError("Invalid date \(lineSplit[0])") }   let data = Array(lineSplit.dropFirst()) let parsed = stride(from: 0, to: data.endIndex, by: 2).map({idx -> (Double, Int) in let slice = data[idx..<idx+2]   return (Double(slice[idx]) ?? 0, Int(slice[idx+1]) ?? 0) })   var sum = 0.0 var numValid = 0   for (val, flag) in parsed { if flag <= 0 { if invalidStart == nil { invalidStart = date }   invalidPeriods += 1 } else { if invalidPeriods > longestInvalid { longestInvalid = invalidPeriods longestInvalidStart = invalidStart longestInvalidEnd = date }   sumFile += val sum += val numValid += 1 readings += 1 invalidPeriods = 0 invalidStart = nil } }   if numValid != 0 { rowStats.append((date, sum / Double(numValid), parsed.count - numValid)) } }   for stat in rowStats.lazy.reversed().prefix(5) { print("\(stat.0): Average: \(fmtDbl(stat.1)); Valid Readings: \(24 - stat.2); Invalid Readings: \(stat.2)") }   print("""   Sum File: \(fmtDbl(sumFile)) Average: \(fmtDbl(sumFile / Double(readings))) Readings: \(readings) Longest Invalid: \(longestInvalid) (\(longestInvalidStart!) - \(longestInvalidEnd!)) """)   exit(0) }   dispatchMain()  
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 String length Copy a string Empty string  (assignment) Counting Word frequency Letter frequency Jewels and stones I before E except after C Bioinformatics/base count Count occurrences of a substring Count how many vowels and consonants occur in a string Remove/replace XXXX redacted Conjugate a Latin verb Remove vowels from a string String interpolation (included) Strip block comments Strip comments from a string Strip a set of characters from a string Strip whitespace from a string -- top and tail Strip control codes and extended characters from a string Anagrams/Derangements/shuffling Word wheel ABC problem Sattolo cycle Knuth shuffle Ordered words Superpermutation minimisation Textonyms (using a phone text pad) Anagrams Anagrams/Deranged anagrams Permutations/Derangements Find/Search/Determine ABC words Odd words Word ladder Semordnilap Word search Wordiff  (game) String matching Tea cup rim text Alternade words Changeable words State name puzzle String comparison Unique characters Unique characters in each string Extract file extension Levenshtein distance Palindrome detection Common list elements Longest common suffix Longest common prefix Compare a list of strings Longest common substring Find common directory path Words from neighbour ones Change e letters to i in words Non-continuous subsequences Longest common subsequence Longest palindromic substrings Longest increasing subsequence Words containing "the" substring Sum of the digits of n is substring of n Determine if a string is numeric Determine if a string is collapsible Determine if a string is squeezable Determine if a string has all unique characters Determine if a string has all the same characters Longest substrings without repeating characters Find words which contains all the vowels Find words which contains most consonants Find words which contains more than 3 vowels Find words which first and last three letters are equals Find words which odd letters are consonants and even letters are vowels or vice_versa Formatting Substring Rep-string Word wrap String case Align columns Literals/String Repeat a string Brace expansion Brace expansion using ranges Reverse a string Phrase reversals Comma quibbling Special characters String concatenation Substring/Top and tail Commatizing numbers Reverse words in a string Suffixation of decimal numbers Long literals, with continuations Numerical and alphabetical suffixes Abbreviations, easy Abbreviations, simple Abbreviations, automatic Song lyrics/poems/Mad Libs/phrases Mad Libs Magic 8-ball 99 Bottles of Beer The Name Game (a song) The Old lady swallowed a fly The Twelve Days of Christmas Tokenize Text between Tokenize a string Word break problem Tokenize a string with escaping Split a character string based on change of character Sequences Show ASCII table De Bruijn sequences Self-referential sequences Generate lower case ASCII alphabet
#Picat
Picat
go => Days = "first second third fourth fifth sixth seventh eighth ninth tenth eleventh twelfth".split(" "), 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"),   println([to_fstring("On the %s day of Christmas,\nMy true love gave to me:\n%w\n", Day, slice(Gifts,1,D).reverse().join("\n")) : {Day,D} in zip(Days,1..length(Days))] .join("\n")), nl.
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 String length Copy a string Empty string  (assignment) Counting Word frequency Letter frequency Jewels and stones I before E except after C Bioinformatics/base count Count occurrences of a substring Count how many vowels and consonants occur in a string Remove/replace XXXX redacted Conjugate a Latin verb Remove vowels from a string String interpolation (included) Strip block comments Strip comments from a string Strip a set of characters from a string Strip whitespace from a string -- top and tail Strip control codes and extended characters from a string Anagrams/Derangements/shuffling Word wheel ABC problem Sattolo cycle Knuth shuffle Ordered words Superpermutation minimisation Textonyms (using a phone text pad) Anagrams Anagrams/Deranged anagrams Permutations/Derangements Find/Search/Determine ABC words Odd words Word ladder Semordnilap Word search Wordiff  (game) String matching Tea cup rim text Alternade words Changeable words State name puzzle String comparison Unique characters Unique characters in each string Extract file extension Levenshtein distance Palindrome detection Common list elements Longest common suffix Longest common prefix Compare a list of strings Longest common substring Find common directory path Words from neighbour ones Change e letters to i in words Non-continuous subsequences Longest common subsequence Longest palindromic substrings Longest increasing subsequence Words containing "the" substring Sum of the digits of n is substring of n Determine if a string is numeric Determine if a string is collapsible Determine if a string is squeezable Determine if a string has all unique characters Determine if a string has all the same characters Longest substrings without repeating characters Find words which contains all the vowels Find words which contains most consonants Find words which contains more than 3 vowels Find words which first and last three letters are equals Find words which odd letters are consonants and even letters are vowels or vice_versa Formatting Substring Rep-string Word wrap String case Align columns Literals/String Repeat a string Brace expansion Brace expansion using ranges Reverse a string Phrase reversals Comma quibbling Special characters String concatenation Substring/Top and tail Commatizing numbers Reverse words in a string Suffixation of decimal numbers Long literals, with continuations Numerical and alphabetical suffixes Abbreviations, easy Abbreviations, simple Abbreviations, automatic Song lyrics/poems/Mad Libs/phrases Mad Libs Magic 8-ball 99 Bottles of Beer The Name Game (a song) The Old lady swallowed a fly The Twelve Days of Christmas Tokenize Text between Tokenize a string Word break problem Tokenize a string with escaping Split a character string based on change of character Sequences Show ASCII table De Bruijn sequences Self-referential sequences Generate lower case ASCII alphabet
#PicoLisp
PicoLisp
(de days first second third fourth fifth sixth seventh eight ninth tenth eleventh twelfth )   (de texts "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" )   (for (X . Day) days (prinl "On the " Day " day of Christmas") (prinl "My true love game to me:") (for (Y X (gt0 Y) (dec Y)) (prinl (if (and (= 12 X) (= 1 Y)) "And a partridge in a pear tree." (get texts Y)) ) ) (prinl) )   (bye)
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 the term threads, others use the term tasks, while others use co-processes. This task should not be implemented using fork, spawn, or the Linux/UNIX/Win32 pipe command, as communication should be between threads, not processes. One of the concurrent units will read from a file named "input.txt" and send the contents of that file, one line at a time, to the other concurrent unit, which will print the line it receives to standard output. The printing unit must count the number of lines it prints. After the concurrent unit reading the file sends its last line to the printing unit, the reading unit will request the number of lines printed by the printing unit. The reading unit will then print the number of lines printed by the printing unit. This task requires two-way communication between the concurrent units. All concurrent units must cleanly terminate at the end of the program.
#Oz
Oz
declare %% Helper function to read a file lazily. %% Returns a lazy list of lines. fun {ReadLines FN} F = {New class $ from Open.file Open.text end init(name:FN)} fun lazy {ReadNext} case {F getS($)} of false then nil [] Line then Line|{ReadNext} end end in %% close file when handle becomes unreachable {Finalize.register F proc {$ F} {F close} end} {ReadNext} end   Count %% Will receive the number of lines PrinterPort in %% Printer thread thread Stream Counter = {NewCell 0} %% mutable variable in PrinterPort = {NewPort ?Stream} for Line in Stream do case Line of eof then Count = @Counter else {System.showInfo Line} Counter := @Counter + 1 end end end   %% Send all lines to printer thread; make sure that eof is sent. try for Line in {ReadLines "input.txt"} do {Send PrinterPort Line} end finally {Send PrinterPort eof} end   %% Sync on Count and print its value. {Wait Count} {Show Count}
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   Retrieving system time (wiki)
#BQN
BQN
•Show •UnixTime @
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   Retrieving system time (wiki)
#C
C
#include<time.h> #include<stdio.h> #include<stdlib.h> int main(){ time_t my_time = time(NULL); printf("%s", ctime(&my_time)); return 0; }
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 generated grow in length geometrically and never converge. Another way to generate a self-referential sequence is to summarize the previous term. Count how many of each alike digit there is, then concatenate the sum and digit for each of the sorted enumerated digits. Note that the first five terms are the same as for the previous sequence. 0, 10, 1110, 3110, 132110, 13123110, 23124110 ... Sort the digits largest to smallest. Do not include counts of digits that do not appear in the previous term. Depending on the seed value, series generated this way always either converge to a stable value or to a short cyclical pattern. (For our purposes, I'll use converge to mean an element matches a previously seen element.) The sequence shown, with a seed value of 0, converges to a stable value of 1433223110 after 11 iterations. The seed value that converges most quickly is 22. It goes stable after the first element. (The next element is 22, which has been seen before.) Task Find all the positive integer seed values under 1000000, for the above convergent self-referential sequence, that takes the largest number of iterations before converging. Then print out the number of iterations and the sequence they return. Note that different permutations of the digits of the seed will yield the same sequence. For this task, assume leading zeros are not permitted. Seed Value(s): 9009 9090 9900 Iterations: 21 Sequence: (same for all three seeds except for first element) 9009 2920 192210 19222110 19323110 1923123110 1923224110 191413323110 191433125110 19151423125110 19251413226110 1916151413325110 1916251423127110 191716151413326110 191726151423128110 19181716151413327110 19182716151423129110 29181716151413328110 19281716151423228110 19281716151413427110 19182716152413228110 Related tasks   Fours is the number of letters in the ...   Look-and-say sequence   Number names   Self-describing numbers   Spelling of ordinal numbers Other tasks related to string operations: Metrics Array length String length Copy a string Empty string  (assignment) Counting Word frequency Letter frequency Jewels and stones I before E except after C Bioinformatics/base count Count occurrences of a substring Count how many vowels and consonants occur in a string Remove/replace XXXX redacted Conjugate a Latin verb Remove vowels from a string String interpolation (included) Strip block comments Strip comments from a string Strip a set of characters from a string Strip whitespace from a string -- top and tail Strip control codes and extended characters from a string Anagrams/Derangements/shuffling Word wheel ABC problem Sattolo cycle Knuth shuffle Ordered words Superpermutation minimisation Textonyms (using a phone text pad) Anagrams Anagrams/Deranged anagrams Permutations/Derangements Find/Search/Determine ABC words Odd words Word ladder Semordnilap Word search Wordiff  (game) String matching Tea cup rim text Alternade words Changeable words State name puzzle String comparison Unique characters Unique characters in each string Extract file extension Levenshtein distance Palindrome detection Common list elements Longest common suffix Longest common prefix Compare a list of strings Longest common substring Find common directory path Words from neighbour ones Change e letters to i in words Non-continuous subsequences Longest common subsequence Longest palindromic substrings Longest increasing subsequence Words containing "the" substring Sum of the digits of n is substring of n Determine if a string is numeric Determine if a string is collapsible Determine if a string is squeezable Determine if a string has all unique characters Determine if a string has all the same characters Longest substrings without repeating characters Find words which contains all the vowels Find words which contains most consonants Find words which contains more than 3 vowels Find words which first and last three letters are equals Find words which odd letters are consonants and even letters are vowels or vice_versa Formatting Substring Rep-string Word wrap String case Align columns Literals/String Repeat a string Brace expansion Brace expansion using ranges Reverse a string Phrase reversals Comma quibbling Special characters String concatenation Substring/Top and tail Commatizing numbers Reverse words in a string Suffixation of decimal numbers Long literals, with continuations Numerical and alphabetical suffixes Abbreviations, easy Abbreviations, simple Abbreviations, automatic Song lyrics/poems/Mad Libs/phrases Mad Libs Magic 8-ball 99 Bottles of Beer The Name Game (a song) The Old lady swallowed a fly The Twelve Days of Christmas Tokenize Text between Tokenize a string Word break problem Tokenize a string with escaping Split a character string based on change of character Sequences Show ASCII table De Bruijn sequences Self-referential sequences Generate lower case ASCII alphabet Also see   The On-Line Encyclopedia of Integer Sequences.
#D
D
import std.stdio, std.algorithm, std.conv;   string[] selfReferentialSeq(string n, string[] seen=[]) nothrow { __gshared static string[][string] cache; if (n in cache) return cache[n]; if (seen.canFind(n)) return [];   int[10] digit_count; foreach (immutable d; n) digit_count[d - '0']++; string term; foreach_reverse (immutable d; 0 .. 10) if (digit_count[d] > 0) term ~= text(digit_count[d], d); return cache[n] = [n] ~ selfReferentialSeq(term, [n] ~ seen); }   void main() { enum int limit = 1_000_000; int max_len; int[] max_vals;   foreach (immutable n; 1 .. limit) { const seq = n.text().selfReferentialSeq(); if (seq.length > max_len) { max_len = seq.length; max_vals = [n]; } else if (seq.length == max_len) max_vals ~= n; }   writeln("values: ", max_vals); writeln("iterations: ", max_len); writeln("sequence:"); foreach (const idx, const val; max_vals[0].text.selfReferentialSeq) writefln("%2d %s", idx + 1, val); }
http://rosettacode.org/wiki/Summarize_primes
Summarize primes
Task Considering in order of length, n, all sequences of consecutive primes, p, from 2 onwards, where p < 1000 and n>0, select those sequences whose sum is prime, and for these display the length of the sequence, the last item in the sequence, and the sum.
#Ring
Ring
  load "stdlib.ring" see "working..." + nl see "Summarize primes:" + nl see "n sum" + nl row = 0 sum = 0 limit = 1000 Primes = []   for n = 2 to limit if isprime(n) add(Primes,n) ok next   for n = 1 to len(Primes) sum = sum + Primes[n] if isprime(sum) row = row + 1 see "" + n + " " + sum + nl ok next   see "Found " + row + " numbers" + nl see "done..." + nl  
http://rosettacode.org/wiki/Summarize_primes
Summarize primes
Task Considering in order of length, n, all sequences of consecutive primes, p, from 2 onwards, where p < 1000 and n>0, select those sequences whose sum is prime, and for these display the length of the sequence, the last item in the sequence, and the sum.
#Ruby
Ruby
def isPrime(n) if n < 2 then return false end   if n % 2 == 0 then return n == 2 end if n % 3 == 0 then return n == 3 end   i = 5 while i * i <= n if n % i == 0 then return false end i += 2   if n % i == 0 then return false end i += 4 end return true end   START = 1 STOP = 1000   sum = 0 count = 0 sc = 0   for p in START .. STOP if isPrime(p) then count += 1 sum += p if isPrime(sum) then print "The sum of %3d primes in [2, %3d] is %5d which is also prime\n" % [count, p, sum] sc += 1 end end end print "There are %d summerized primes in [%d, %d]\n" % [sc, START, STOP]
http://rosettacode.org/wiki/Summarize_primes
Summarize primes
Task Considering in order of length, n, all sequences of consecutive primes, p, from 2 onwards, where p < 1000 and n>0, select those sequences whose sum is prime, and for these display the length of the sequence, the last item in the sequence, and the sum.
#Rust
Rust
// [dependencies] // primal = "0.3"   fn main() { let limit = 1000; let mut sum = 0; println!("count prime sum"); for (n, p) in primal::Sieve::new(limit) .primes_from(2) .take_while(|x| *x < limit) .enumerate() { sum += p; if primal::is_prime(sum as u64) { println!(" {:>3} {:>3} {:>5}", n + 1, p, sum); } } }
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 polygon that do not need to be displayed. Task Take the closed polygon defined by the points: [ ( 50 , 150 ) , ( 200 , 50 ) , ( 350 , 150 ) , ( 350 , 300 ) , ( 250 , 300 ) , ( 200 , 250 ) , ( 150 , 350 ) , ( 100 , 250 ) , ( 100 , 200 ) ] {\displaystyle [(50,150),(200,50),(350,150),(350,300),(250,300),(200,250),(150,350),(100,250),(100,200)]} and clip it by the rectangle defined by the points: [ ( 100 , 100 ) , ( 300 , 100 ) , ( 300 , 300 ) , ( 100 , 300 ) ] {\displaystyle [(100,100),(300,100),(300,300),(100,300)]} Print the sequence of points that define the resulting clipped polygon. Extra credit Display all three polygons on a graphical surface, using a different color for each polygon and filling the resulting polygon. (When displaying you may use either a north-west or a south-west origin, whichever is more convenient for your display mechanism.)
#MATLAB_.2F_Octave
MATLAB / Octave
%The inputs are a table of x-y pairs for the verticies of the subject %polygon and boundary polygon. (x values in column 1 and y values in column %2) The output is a table of x-y pairs for the clipped version of the %subject polygon.   function clippedPolygon = sutherlandHodgman(subjectPolygon,clipPolygon)   %% Helper Functions   %computerIntersection() assumes the two lines intersect function intersection = computeIntersection(line1,line2)   %this is an implementation of %http://en.wikipedia.org/wiki/Line-line_intersection   intersection = zeros(1,2);   detL1 = det(line1); detL2 = det(line2);   detL1x = det([line1(:,1),[1;1]]); detL1y = det([line1(:,2),[1;1]]);   detL2x = det([line2(:,1),[1;1]]); detL2y = det([line2(:,2),[1;1]]);   denominator = det([detL1x detL1y;detL2x detL2y]);   intersection(1) = det([detL1 detL1x;detL2 detL2x]) / denominator; intersection(2) = det([detL1 detL1y;detL2 detL2y]) / denominator;   end %computeIntersection   %inside() assumes the boundary is oriented counter-clockwise function in = inside(point,boundary)   pointPositionVector = [diff([point;boundary(1,:)]) 0]; boundaryVector = [diff(boundary) 0]; crossVector = cross(pointPositionVector,boundaryVector);   if ( crossVector(3) <= 0 ) in = true; else in = false; end   end %inside   %% Sutherland-Hodgman Algorithm   clippedPolygon = subjectPolygon; numVerticies = size(clipPolygon,1); clipVertexPrevious = clipPolygon(end,:);   for clipVertex = (1:numVerticies)   clipBoundary = [clipPolygon(clipVertex,:) ; clipVertexPrevious];   inputList = clippedPolygon;   clippedPolygon = []; if ~isempty(inputList), previousVertex = inputList(end,:); end   for subjectVertex = (1:size(inputList,1))   if ( inside(inputList(subjectVertex,:),clipBoundary) )   if( not(inside(previousVertex,clipBoundary)) ) subjectLineSegment = [previousVertex;inputList(subjectVertex,:)]; clippedPolygon(end+1,1:2) = computeIntersection(clipBoundary,subjectLineSegment); end   clippedPolygon(end+1,1:2) = inputList(subjectVertex,:);   elseif( inside(previousVertex,clipBoundary) ) subjectLineSegment = [previousVertex;inputList(subjectVertex,:)]; clippedPolygon(end+1,1:2) = computeIntersection(clipBoundary,subjectLineSegment); end   previousVertex = inputList(subjectVertex,:); clipVertexPrevious = clipPolygon(clipVertex,:);   end %for subject verticies end %for boundary verticies end %sutherlandHodgman
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\cap B)} (the set of items that are in at least one of A or B minus the set of items that are in both A and B). Optionally, give the individual differences ( A ∖ B {\displaystyle A\setminus B} and B ∖ A {\displaystyle B\setminus A} ) as well. Test cases A = {John, Bob, Mary, Serena} B = {Jim, Mary, John, Bob} Notes If your code uses lists of items to represent sets then ensure duplicate items in lists are correctly handled. For example two lists representing sets of a = ["John", "Serena", "Bob", "Mary", "Serena"] and b = ["Jim", "Mary", "John", "Jim", "Bob"] should produce the result of just two strings: ["Serena", "Jim"], in any order. In the mathematical notation above A \ B gives the set of items in A that are not in B; A ∪ B gives the set of items in both A and B, (their union); and A ∩ B gives the set of items that are in both A and B (their intersection).
#Elixir
Elixir
iex(1)> a = ~w[John Bob Mary Serena] |> MapSet.new #MapSet<["Bob", "John", "Mary", "Serena"]> iex(2)> b = ~w[Jim Mary John Bob] |> MapSet.new #MapSet<["Bob", "Jim", "John", "Mary"]> iex(3)> sym_dif = fn(a,b) -> MapSet.difference(MapSet.union(a,b), MapSet.intersection(a,b)) end #Function<12.54118792/2 in :erl_eval.expr/5> iex(4)> sym_dif.(a,b) #MapSet<["Jim", "Serena"]>
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\cap B)} (the set of items that are in at least one of A or B minus the set of items that are in both A and B). Optionally, give the individual differences ( A ∖ B {\displaystyle A\setminus B} and B ∖ A {\displaystyle B\setminus A} ) as well. Test cases A = {John, Bob, Mary, Serena} B = {Jim, Mary, John, Bob} Notes If your code uses lists of items to represent sets then ensure duplicate items in lists are correctly handled. For example two lists representing sets of a = ["John", "Serena", "Bob", "Mary", "Serena"] and b = ["Jim", "Mary", "John", "Jim", "Bob"] should produce the result of just two strings: ["Serena", "Jim"], in any order. In the mathematical notation above A \ B gives the set of items in A that are not in B; A ∪ B gives the set of items in both A and B, (their union); and A ∩ B gives the set of items that are in both A and B (their intersection).
#Erlang
Erlang
%% Implemented by Arjun Sunel -module(symdiff). -export([main/0]).   main() -> SetA = sets:from_list(["John","Bob","Mary","Serena"]), SetB = sets:from_list(["Jim","Mary","John","Bob"]), AUnionB = sets:union(SetA,SetB), AIntersectionB = sets:intersection(SetA,SetB), SymmDiffAB = sets:subtract(AUnionB,AIntersectionB), sets:to_list(SymmDiffAB).  
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 all the arguments, joined with spaces, prepended with a tab, and appended with a trailing newline, are written to NOTES.TXT. If NOTES.TXT doesn't already exist in the current directory then a new NOTES.TXT file should be created.
#Mathematica.2FWolfram_Language
Mathematica/Wolfram Language
If[Length[$CommandLine < 11], str = OpenRead["NOTES.TXT"]; Print[ReadString[str, EndOfFile]]; Close[str], str = OpenAppend["NOTES.TXT"]; WriteLine[str, DateString[]]; WriteLine[str, "\t" <> StringRiffle[$CommandLine[[11 ;;]]]]; Close[str]]
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 all the arguments, joined with spaces, prepended with a tab, and appended with a trailing newline, are written to NOTES.TXT. If NOTES.TXT doesn't already exist in the current directory then a new NOTES.TXT file should be created.
#MATLAB_.2F_Octave
MATLAB / Octave
function notes(varargin) % NOTES can be used for taking notes % usage: % notes displays the content of the file NOTES.TXT % notes arg1 arg2 ... % add the current date, time and arg# to NOTES.TXT %   filename = 'NOTES.TXT'; if nargin==0 fid = fopen(filename,'rt'); if fid<0, return; end; while ~feof(fid) fprintf('%s\n',fgetl(fid)); end; fclose(fid); else fid = fopen(filename,'a+'); if fid<0, error('cannot open %s\n',filename); end; fprintf(fid, '%s\n\t%s', datestr(now),varargin{1}); for k=2:length(varargin) fprintf(fid, ', %s', varargin{k}); end; fprintf(fid,'\n'); fclose(fid); end;
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 = b = 200
#Phix
Phix
-- -- demo\rosetta\Superellipse.exw -- ============================= -- with javascript_semantics atom n = 2.5 -- '+' and '-' increase/decrease in steps of 0.1 include pGUI.e Ihandle dlg, canvas cdCanvas cddbuffer, cdcanvas function redraw_cb(Ihandle /*ih*/) integer {w, h} = IupGetIntInt(canvas, "DRAWSIZE"), hw = floor(w/2), hh = floor(h/2), a = max(10,hw-100), -- (initially 200, from 602x ) b = max(10,hh-50) -- (initially 200, from x502) sequence y = b&repeat(0,a) for x=1 to a-1 do y[x+1] = floor(exp(log(1-power(x/a,n))/n)*b) end for cdCanvasActivate(cddbuffer) cdCanvasClear(cddbuffer) cdCanvasBegin(cddbuffer, CD_OPEN_LINES) cdCanvasVertex(cddbuffer, hw, hh-b) -- starting point for x=1 to a-1 do cdCanvasVertex(cddbuffer, hw+x, hh-y[x+1]) end for for x=a to 0 by -1 do cdCanvasVertex(cddbuffer, hw+x, hh+y[x+1]) end for for x=0 to a do cdCanvasVertex(cddbuffer, hw-x, hh+y[x+1]) end for for x=a to 0 by -1 do cdCanvasVertex(cddbuffer, hw-x, hh-y[x+1]) end for cdCanvasEnd(cddbuffer) cdCanvasFlush(cddbuffer) return IUP_DEFAULT end function function map_cb(Ihandle ih) cdcanvas = cdCreateCanvas(CD_IUP, ih) cddbuffer = cdCreateCanvas(CD_DBUFFER, cdcanvas) cdCanvasSetBackground(cddbuffer, CD_WHITE) cdCanvasSetForeground(cddbuffer, CD_BLACK) return IUP_DEFAULT end function function key_cb(Ihandle /*ih*/, atom c) if c=K_ESC then return IUP_CLOSE end if if c='+' then n = min(130,n+0.1) -- (otherwise [>130] power overflow) IupUpdate(canvas) elsif c='-' then n = max(0.1,n-0.1) -- (otherwise [=0.0] divide by zero) IupUpdate(canvas) end if return IUP_CONTINUE end function procedure main() IupOpen() canvas = IupCanvas("RASTERSIZE=602x502") IupSetCallbacks(canvas, {"MAP_CB", Icallback("map_cb"), "ACTION", Icallback("redraw_cb")}) dlg = IupDialog(canvas,"TITLE=Superellipse") IupSetCallback(dlg, "KEY_CB", Icallback("key_cb")) IupShow(dlg) IupSetAttribute(canvas, "RASTERSIZE", NULL) -- release the minimum limitation if platform()!=JS then IupMainLoop() IupClose() end if end procedure main()
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   taxi-cab numbers   taxi cab numbers   Hardy-Ramanujan numbers Task Compute and display the lowest 25 taxicab numbers (in numeric order, and in a human-readable format). For each of the taxicab numbers, show the number as well as it's constituent cubes. Extra credit Show the 2,000th taxicab number, and a half dozen more See also A001235: taxicab numbers on The On-Line Encyclopedia of Integer Sequences. Hardy-Ramanujan Number on MathWorld. taxicab number on MathWorld. taxicab number on Wikipedia   (includes the story on how taxi-cab numbers came to be called).
#REXX
REXX
/*REXX program displays the specified first (lowest) taxicab numbers (for three ranges).*/ parse arg L.1 H.1 L.2 H.2 L.3 H.3 . /*obtain optional arguments from the CL*/ if L.1=='' | L.1=="," then L.1= 1 /*L1 is the low part of 1st range. */ if H.1=='' | H.1=="," then H.1= 25 /*H1 " " high " " " " */ if L.2=='' | L.2=="," then L.2= 454 /*L2 " " low " " 2nd " */ if H.2=='' | H.2=="," then H.2= 456 /*H2 " " high " " " " */ if L.3=='' | L.3=="," then L.3=2000 /*L3 " " low " " 3rd " */ if H.3=='' | H.3=="," then H.3=2006 /*H3 " " high " " " " */ mx= max(H.1, H.2, H.3) /*find how many taxicab numbers needed.*/ mx= mx + mx % 10 /*cushion; compensate for the triples.*/ ww= length(mx) * 3; w= ww % 2 /*widths used for formatting the output*/ numeric digits max(9, ww) /*prepare to use some larger numbers. */ @.=.; #= 0; @@.= 0; @and= " ──and── " /*set some REXX vars and handy literals*/ $.= /* [↓] generate extra taxicab numbers.*/ do j=1 until #>=mx; C= j**3 /*taxicab numbers may not be in order. */  !.j= C /*use memoization for cube calculation.*/ do k=1 for j-1; s= C + !.k /*define a whole bunch of cube sums. */ if @.s==. then do; @.s= j; b.s= k /*Cube not defined? Then process it. */ iterate /*define @.S and B.S≡sum of 2 cubes*/ end /* [↑] define one cube sum at a time. */ has= @@.s /*has this number been defined before? */ if has then $.s= $.s @and U(j,' +')U(k) /* ◄─ build a display string. [↓] */ else $.s= right(s,ww) '───►' U(@.s," +")U(b.s) @and U(j,' +')U(k) @@.s= 1 /*mark taxicab number as a sum of cubes*/ if has then iterate /*S is a triple (or sometimes better).*/ #= # + 1; #.#= s /*bump taxicab counter; define taxicab#*/ end /*k*/ /* [↑] build the cubes one─at─a─time. */ end /*j*/ /* [↑] complete with overage numbers. */ A.= do k=1 for mx; _= #.k; A.k= $._ /*re─assign disjoint $. elements to A. */ end /*k*/ call Esort mx /*sort taxicab #s with an exchange sort*/ do grp=1 for 3; call tell L.grp, H.grp /*display the three grps of numbers. */ end /*grp*/ exit /*stick a fork in it, we're all done. */ /*──────────────────────────────────────────────────────────────────────────────────────*/ tell: do t=arg(1) to arg(2); say right(t, 9)':' A.t; end; say; return U: return right(arg(1), w)'^3'arg(2) /*right─justify a number, append "^3" */ /*──────────────────────────────────────────────────────────────────────────────────────*/ Esort: procedure expose A.; parse arg N; h= N /*Esort when items have blanks.*/ do while h>1; h= h % 2 do i=1 for N-h; k=h + i; j= i do forever; parse var A.k xk .; parse var A.j xj .; if xk>=xj then leave _= A.j; A.j= A.k; A.k= _ /*swap two elements of A. array*/ if h>=j then leave; j=j - h; k= k - h end /*forever*/ end /*i*/ end /*while h>1*/; return
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 zero. The Fahrenheit and Rankine scales also have the same magnitude, but different null points. 0 degrees Fahrenheit corresponds to 459.67 degrees Rankine. 0 degrees Rankine is absolute zero. The Celsius/Kelvin and Fahrenheit/Rankine scales have a ratio of 5 : 9. Task Write code that accepts a value of kelvin, converts it to values of the three other scales, and prints the result. Example K 21.00 C -252.15 F -421.87 R 37.80
#Elena
Elena
import extensions;   convertKelvinToFahrenheit(x) = x * 1.8r - 459.6r;   convertKelvinToRankine(x) = x * 1.8r;   convertKelvinToCelsius(x) = x - 273.15r;   public program() { console.print("Enter a Kelvin Temperature: "); var inputVal := console.readLine(); real kelvinTemp := 0.0r; try { kelvinTemp := realConvertor.convert(inputVal) } catch(Exception e) { console.printLine("Invalid input value: ", inputVal);   AbortException.raise() };   console.printLine("Kelvin: ", kelvinTemp); console.printLine("Fahrenheit: ", convertKelvinToFahrenheit(kelvinTemp)); console.printLine("Rankine: ", convertKelvinToRankine(kelvinTemp)); console.printLine("Celsius: ", convertKelvinToCelsius(kelvinTemp)); console.readChar() }
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 logic, sometimes abbreviated 3VL) is any of several many-valued logic systems in which there are three truth values indicating true, false and some indeterminate third value. This is contrasted with the more commonly known bivalent logics (such as classical sentential or boolean logic) which provide only for true and false. Conceptual form and basic ideas were initially created by Łukasiewicz, Lewis and Sulski. These were then re-formulated by Grigore Moisil in an axiomatic algebraic form, and also extended to n-valued logics in 1945. Example Ternary Logic Operators in Truth Tables: not a ¬ True False Maybe Maybe False True a and b ∧ True Maybe False True True Maybe False Maybe Maybe Maybe False False False False False a or b ∨ True Maybe False True True True True Maybe True Maybe Maybe False True Maybe False if a then b ⊃ True Maybe False True True Maybe False Maybe True Maybe Maybe False True True True a is equivalent to b ≡ True Maybe False True True Maybe False Maybe Maybe Maybe Maybe False False Maybe True Task Define a new type that emulates ternary logic by storing data trits. Given all the binary logic operators of the original programming language, reimplement these operators for the new Ternary logic type trit. Generate a sampling of results using trit variables. Kudos for actually thinking up a test case algorithm where ternary logic is intrinsically useful, optimises the test case algorithm and is preferable to binary logic. Note:   Setun   (Сетунь) was a   balanced ternary   computer developed in 1958 at   Moscow State University.   The device was built under the lead of   Sergei Sobolev   and   Nikolay Brusentsov.   It was the only modern   ternary computer,   using three-valued ternary logic
#Raku
Raku
# Implementation: enum Trit <Foo Moo Too>;   sub prefix:<¬> (Trit $a) { Trit(1-($a-1)) }   sub infix:<∧> (Trit $a, Trit $b) is equiv(&infix:<*>) { $a min $b } sub infix:<∨> (Trit $a, Trit $b) is equiv(&infix:<+>) { $a max $b }   sub infix:<⇒> (Trit $a, Trit $b) is equiv(&infix:<..>) { ¬$a max $b } sub infix:<≡> (Trit $a, Trit $b) is equiv(&infix:<eq>) { Trit(1 + ($a-1) * ($b-1)) }   # Testing: say '¬'; say "Too {¬Too}"; say "Moo {¬Moo}"; say "Foo {¬Foo}";   sub tbl (&op,$name) { say ''; say "$name Too Moo Foo"; say " ╔═══════════"; say "Too║{op Too,Too} {op Too,Moo} {op Too,Foo}"; say "Moo║{op Moo,Too} {op Moo,Moo} {op Moo,Foo}"; say "Foo║{op Foo,Too} {op Foo,Moo} {op Foo,Foo}"; }   tbl(&infix:<∧>, '∧'); tbl(&infix:<∨>, '∨'); tbl(&infix:<⇒>, '⇒'); tbl(&infix:<≡>, '≡');   say ''; say 'Precedence tests should all print "Too":'; say ~( Foo ∧ Too ∨ Too ≡ Too, Foo ∧ (Too ∨ Too) ≡ Foo, Too ∨ Too ∧ Foo ≡ Too, (Too ∨ Too) ∧ Foo ≡ Foo,   ¬Too ∧ Too ∨ Too ≡ Too, ¬Too ∧ (Too ∨ Too) ≡ ¬Too, Too ∨ Too ∧ ¬Too ≡ Too, (Too ∨ Too) ∧ ¬Too ≡ ¬Too,   Foo ∧ Too ∨ Foo ⇒ Foo ≡ Too, Foo ∧ Too ∨ Too ⇒ Foo ≡ Foo, );
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 program can be written to parse and transform the original data into a format useful to the other. The term "Data Munging" is often used in programming circles for this task. A request on the comp.lang.awk newsgroup led to a typical data munging task: I have to analyse data files that have the following format: Each row corresponds to 1 day and the field logic is: $1 is the date, followed by 24 value/flag pairs, representing measurements at 01:00, 02:00 ... 24:00 of the respective day. In short: <date> <val1> <flag1> <val2> <flag2> ... <val24> <flag24> Some test data is available at: ... (nolonger available at original location) I have to sum up the values (per day and only valid data, i.e. with flag>0) in order to calculate the mean. That's not too difficult. However, I also need to know what the "maximum data gap" is, i.e. the longest period with successive invalid measurements (i.e values with flag<=0) The data is free to download and use and is of this format: Data is no longer available at that link. Zipped mirror available here (offsite mirror). 1991-03-30 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 1991-03-31 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 20.000 1 20.000 1 20.000 1 35.000 1 50.000 1 60.000 1 40.000 1 30.000 1 30.000 1 30.000 1 25.000 1 20.000 1 20.000 1 20.000 1 20.000 1 20.000 1 35.000 1 1991-03-31 40.000 1 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 1991-04-01 0.000 -2 13.000 1 16.000 1 21.000 1 24.000 1 22.000 1 20.000 1 18.000 1 29.000 1 44.000 1 50.000 1 43.000 1 38.000 1 27.000 1 27.000 1 24.000 1 23.000 1 18.000 1 12.000 1 13.000 1 14.000 1 15.000 1 13.000 1 10.000 1 1991-04-02 8.000 1 9.000 1 11.000 1 12.000 1 12.000 1 12.000 1 27.000 1 26.000 1 27.000 1 33.000 1 32.000 1 31.000 1 29.000 1 31.000 1 25.000 1 25.000 1 24.000 1 21.000 1 17.000 1 14.000 1 15.000 1 12.000 1 12.000 1 10.000 1 1991-04-03 10.000 1 9.000 1 10.000 1 10.000 1 9.000 1 10.000 1 15.000 1 24.000 1 28.000 1 24.000 1 18.000 1 14.000 1 12.000 1 13.000 1 14.000 1 15.000 1 14.000 1 15.000 1 13.000 1 13.000 1 13.000 1 12.000 1 10.000 1 10.000 1 Only a sample of the data showing its format is given above. The full example file may be downloaded here. Structure your program to show statistics for each line of the file, (similar to the original Python, Perl, and AWK examples below), followed by summary statistics for the file. When showing example output just show a few line statistics and the full end summary.
#Tcl
Tcl
set max_invalid_run 0 set max_invalid_run_end "" set tot_file 0 set num_file 0   set linefmt "Line: %11s Reject: %2d Accept: %2d Line_tot: %10.3f Line_avg: %10.3f"   set filename readings.txt set fh [open $filename] while {[gets $fh line] != -1} { set tot_line [set count [set num_line 0]] set fields [regexp -all -inline {\S+} $line] set date [lindex $fields 0] foreach {val flag} [lrange $fields 1 end] { incr count if {$flag > 0} { incr num_line incr num_file set tot_line [expr {$tot_line + $val}] set invalid_run_count 0 } else { incr invalid_run_count if {$invalid_run_count > $max_invalid_run} { set max_invalid_run $invalid_run_count set max_invalid_run_end $date } } } set tot_file [expr {$tot_file + $tot_line}] puts [format $linefmt $date [expr {$count - $num_line}] $num_line $tot_line \ [expr {$num_line > 0 ? $tot_line / $num_line : 0}]] } close $fh   puts "" puts "File(s) = $filename" puts "Total = [format %.3f $tot_file]" puts "Readings = $num_file" puts "Average = [format %.3f [expr {$tot_file / $num_file}]]" puts "" puts "Maximum run(s) of $max_invalid_run consecutive false readings ends at $max_invalid_run_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 String length Copy a string Empty string  (assignment) Counting Word frequency Letter frequency Jewels and stones I before E except after C Bioinformatics/base count Count occurrences of a substring Count how many vowels and consonants occur in a string Remove/replace XXXX redacted Conjugate a Latin verb Remove vowels from a string String interpolation (included) Strip block comments Strip comments from a string Strip a set of characters from a string Strip whitespace from a string -- top and tail Strip control codes and extended characters from a string Anagrams/Derangements/shuffling Word wheel ABC problem Sattolo cycle Knuth shuffle Ordered words Superpermutation minimisation Textonyms (using a phone text pad) Anagrams Anagrams/Deranged anagrams Permutations/Derangements Find/Search/Determine ABC words Odd words Word ladder Semordnilap Word search Wordiff  (game) String matching Tea cup rim text Alternade words Changeable words State name puzzle String comparison Unique characters Unique characters in each string Extract file extension Levenshtein distance Palindrome detection Common list elements Longest common suffix Longest common prefix Compare a list of strings Longest common substring Find common directory path Words from neighbour ones Change e letters to i in words Non-continuous subsequences Longest common subsequence Longest palindromic substrings Longest increasing subsequence Words containing "the" substring Sum of the digits of n is substring of n Determine if a string is numeric Determine if a string is collapsible Determine if a string is squeezable Determine if a string has all unique characters Determine if a string has all the same characters Longest substrings without repeating characters Find words which contains all the vowels Find words which contains most consonants Find words which contains more than 3 vowels Find words which first and last three letters are equals Find words which odd letters are consonants and even letters are vowels or vice_versa Formatting Substring Rep-string Word wrap String case Align columns Literals/String Repeat a string Brace expansion Brace expansion using ranges Reverse a string Phrase reversals Comma quibbling Special characters String concatenation Substring/Top and tail Commatizing numbers Reverse words in a string Suffixation of decimal numbers Long literals, with continuations Numerical and alphabetical suffixes Abbreviations, easy Abbreviations, simple Abbreviations, automatic Song lyrics/poems/Mad Libs/phrases Mad Libs Magic 8-ball 99 Bottles of Beer The Name Game (a song) The Old lady swallowed a fly The Twelve Days of Christmas Tokenize Text between Tokenize a string Word break problem Tokenize a string with escaping Split a character string based on change of character Sequences Show ASCII table De Bruijn sequences Self-referential sequences Generate lower case ASCII alphabet
#Pike
Pike
int main() { array(string) days = ({"first", "second", "third", "fourth", "fifth", "sixth", "seventh", "eighth", "ninth", "tenth", "eleventh", "twelfth"}); array(string) 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"});   for (int i = 0; i < 12; i++) { write("On the " + (string)days[i] + " day of Christmas\n"); write("My true love gave to me:\n"); for (int j = 0; j < i + 1; j++) { write((string)gifts[i - j] + "\n"); } if (i != 11) { write("\n"); } } return 0; }
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 the term threads, others use the term tasks, while others use co-processes. This task should not be implemented using fork, spawn, or the Linux/UNIX/Win32 pipe command, as communication should be between threads, not processes. One of the concurrent units will read from a file named "input.txt" and send the contents of that file, one line at a time, to the other concurrent unit, which will print the line it receives to standard output. The printing unit must count the number of lines it prints. After the concurrent unit reading the file sends its last line to the printing unit, the reading unit will request the number of lines printed by the printing unit. The reading unit will then print the number of lines printed by the printing unit. This task requires two-way communication between the concurrent units. All concurrent units must cleanly terminate at the end of the program.
#Perl
Perl
use threads; use Thread::Queue qw();   my $q1 = Thread::Queue->new; my $q2 = Thread::Queue->new;   my $reader = threads->create(sub { my $q1 = shift; my $q2 = shift;   open my $fh, '<', 'input.txt'; $q1->enqueue($_) while <$fh>; close $fh; $q1->enqueue(undef);   print $q2->dequeue; }, $q1, $q2);   my $printer = threads->create(sub { my $q1 = shift; my $q2 = shift;   my $count; while (my $line = $q1->dequeue) { print $line; $count++; };   $q2->enqueue($count); }, $q1, $q2);   $reader->join; $printer->join;
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   Retrieving system time (wiki)
#C.23
C#
Console.WriteLine(DateTime.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   Retrieving system time (wiki)
#C.2B.2B
C++
#include <iostream> #include <boost/date_time/posix_time/posix_time.hpp>   int main( ) { boost::posix_time::ptime t ( boost::posix_time::second_clock::local_time( ) ) ; std::cout << to_simple_string( t ) << std::endl ; return 0 ; }
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 generated grow in length geometrically and never converge. Another way to generate a self-referential sequence is to summarize the previous term. Count how many of each alike digit there is, then concatenate the sum and digit for each of the sorted enumerated digits. Note that the first five terms are the same as for the previous sequence. 0, 10, 1110, 3110, 132110, 13123110, 23124110 ... Sort the digits largest to smallest. Do not include counts of digits that do not appear in the previous term. Depending on the seed value, series generated this way always either converge to a stable value or to a short cyclical pattern. (For our purposes, I'll use converge to mean an element matches a previously seen element.) The sequence shown, with a seed value of 0, converges to a stable value of 1433223110 after 11 iterations. The seed value that converges most quickly is 22. It goes stable after the first element. (The next element is 22, which has been seen before.) Task Find all the positive integer seed values under 1000000, for the above convergent self-referential sequence, that takes the largest number of iterations before converging. Then print out the number of iterations and the sequence they return. Note that different permutations of the digits of the seed will yield the same sequence. For this task, assume leading zeros are not permitted. Seed Value(s): 9009 9090 9900 Iterations: 21 Sequence: (same for all three seeds except for first element) 9009 2920 192210 19222110 19323110 1923123110 1923224110 191413323110 191433125110 19151423125110 19251413226110 1916151413325110 1916251423127110 191716151413326110 191726151423128110 19181716151413327110 19182716151423129110 29181716151413328110 19281716151423228110 19281716151413427110 19182716152413228110 Related tasks   Fours is the number of letters in the ...   Look-and-say sequence   Number names   Self-describing numbers   Spelling of ordinal numbers Other tasks related to string operations: Metrics Array length String length Copy a string Empty string  (assignment) Counting Word frequency Letter frequency Jewels and stones I before E except after C Bioinformatics/base count Count occurrences of a substring Count how many vowels and consonants occur in a string Remove/replace XXXX redacted Conjugate a Latin verb Remove vowels from a string String interpolation (included) Strip block comments Strip comments from a string Strip a set of characters from a string Strip whitespace from a string -- top and tail Strip control codes and extended characters from a string Anagrams/Derangements/shuffling Word wheel ABC problem Sattolo cycle Knuth shuffle Ordered words Superpermutation minimisation Textonyms (using a phone text pad) Anagrams Anagrams/Deranged anagrams Permutations/Derangements Find/Search/Determine ABC words Odd words Word ladder Semordnilap Word search Wordiff  (game) String matching Tea cup rim text Alternade words Changeable words State name puzzle String comparison Unique characters Unique characters in each string Extract file extension Levenshtein distance Palindrome detection Common list elements Longest common suffix Longest common prefix Compare a list of strings Longest common substring Find common directory path Words from neighbour ones Change e letters to i in words Non-continuous subsequences Longest common subsequence Longest palindromic substrings Longest increasing subsequence Words containing "the" substring Sum of the digits of n is substring of n Determine if a string is numeric Determine if a string is collapsible Determine if a string is squeezable Determine if a string has all unique characters Determine if a string has all the same characters Longest substrings without repeating characters Find words which contains all the vowels Find words which contains most consonants Find words which contains more than 3 vowels Find words which first and last three letters are equals Find words which odd letters are consonants and even letters are vowels or vice_versa Formatting Substring Rep-string Word wrap String case Align columns Literals/String Repeat a string Brace expansion Brace expansion using ranges Reverse a string Phrase reversals Comma quibbling Special characters String concatenation Substring/Top and tail Commatizing numbers Reverse words in a string Suffixation of decimal numbers Long literals, with continuations Numerical and alphabetical suffixes Abbreviations, easy Abbreviations, simple Abbreviations, automatic Song lyrics/poems/Mad Libs/phrases Mad Libs Magic 8-ball 99 Bottles of Beer The Name Game (a song) The Old lady swallowed a fly The Twelve Days of Christmas Tokenize Text between Tokenize a string Word break problem Tokenize a string with escaping Split a character string based on change of character Sequences Show ASCII table De Bruijn sequences Self-referential sequences Generate lower case ASCII alphabet Also see   The On-Line Encyclopedia of Integer Sequences.
#EchoLisp
EchoLisp
  (lib 'hash) (lib 'list) ;; permutations   (define H (make-hash))   ;; G R A P H ;; generate 'normalized' starter vectors D[i] = number of digits 'i' (0 <=i < 10) ;; reduce graph size : 9009, 9900 .. will be generated once : vector #(2 0 0 0 0 0 0 0 0 2)   (define (generate D dstart ndigits (sd 0)) (when (> ndigits 0) (set! sd (vector-ref D dstart)) ;; save before recurse (for ((i (in-range 0 (1+ ndigits)))) #:continue (and ( = i 0) (> dstart 0)) (vector-set! D dstart i) (sequence D) ;; sequence length from D (for ((j (in-range (1+ dstart) 10))) (generate D j (- ndigits i)))) (vector-set! D dstart sd))) ;; restore     ;; compute follower of D (at most 99 same digits) (define (dnext D (dd 0)) (define N (make-vector 10)) (for ((d D) (i 10)) #:continue (zero? d) (vector-set! N i (1+ (vector-ref N i))) (if (< d 10) (vector-set! N d (1+ (vector-ref N d))) ;; d < 9 (begin (set! dd (modulo d 10)) (vector-set! N dd (1+ (vector-ref N dd))) (set! dd (quotient d 10)) (vector-set! N dd (1+ (vector-ref N dd)))))) N)     ;; update all nodes in same sequence ;; seq-length (next D) = 1 - seq-length(D) (define (sequence D) (define (dists D d) (unless (hash-ref H D) (hash-set H D d) (dists (dnext D ) (1- d))))   (unless (hash-ref H D) (dists D (sequence-length D))))   ;; sequence length from D ;; stops on loop found (node N) (define (sequence-length D ) (define (looper N looplg depth) ;; looper 2 : a b a (when ( > depth 0) (hash-set H N looplg) (looper (dnext N) looplg (1- depth))))   (define followers (make-hash)) (define N (dnext D)) (define seqlg 0) (define looplg 0)   (hash-set followers D 0)   (set! seqlg (for ((lg (in-naturals 1 ))) #:break (hash-ref H N) => (+ lg (hash-ref H N)) ;; already known #:break (hash-ref followers N) => lg ;; loop found (hash-set followers N lg) (set! N (dnext N))))   ;; update nodes in loop : same seq-length (when (hash-ref followers N) ;; loop found (set! looplg ( - seqlg (hash-ref followers N))) (looper N looplg looplg))   seqlg )   ;; O U T P U T ;; backwards from D - normalized vector - to numbers (as strings) (define (starters D) (define (not-leading-zero list) (!zero? (first list))) (map list->string (filter not-leading-zero (make-set (permutations (for/fold (acc null) ((d D) (i 10)) #:continue (zero? d) (append acc (for/list ((j d)) i))))))))     ;; printing one node (define (D-print D) (set! D (reverse (vector->list D))) (for/string ( (d D) (i (in-range 9 -1 -1))) #:continue (zero? d) (string-append d i)))   ;; print graph contents (define (print-sequence D) (writeln 1 (starters D)) (writeln 2 (D-print D )) (for ((i (in-range 1 (hash-ref H D)))) (writeln (+ i 2) (D-print (setv! D (dnext D))))))     ;; TA S K (define (task (n 6) (verbose #t)) (generate (make-vector 10) 0 n) (define seqmax (apply max (hash-values H))) (when verbose (for ((kv H)) #:continue (!= (rest kv ) seqmax) (print-sequence (first kv))))   (writeln (expt 10 n) '--> 'max-sequence= (1+ seqmax) 'nodes= (length (hash-values H))))    
http://rosettacode.org/wiki/Summarize_primes
Summarize primes
Task Considering in order of length, n, all sequences of consecutive primes, p, from 2 onwards, where p < 1000 and n>0, select those sequences whose sum is prime, and for these display the length of the sequence, the last item in the sequence, and the sum.
#Sidef
Sidef
1000.primes.map_reduce {|a,b| a + b }.map_kv {|k,v| [k+1, prime(k+1), v] }.grep { .tail.is_prime }.prepend( ['count', 'prime', 'sum'] ).each_2d {|n,p,s| printf("%5s %6s %8s\n", n, p, s) }
http://rosettacode.org/wiki/Summarize_primes
Summarize primes
Task Considering in order of length, n, all sequences of consecutive primes, p, from 2 onwards, where p < 1000 and n>0, select those sequences whose sum is prime, and for these display the length of the sequence, the last item in the sequence, and the sum.
#Wren
Wren
import "/math" for Int import "/fmt" for Fmt   var primes = Int.primeSieve(999) var sum = 0 var n = 0 var c = 0 System.print("Summing the first n primes (<1,000) where the sum is itself prime:") System.print(" n cumulative sum") for (p in primes) { n = n + 1 sum = sum + p if (Int.isPrime(sum)) { c = c + 1 Fmt.print("$3d $,6d", n, sum) } } System.print("\n%(c) such prime sums found")
http://rosettacode.org/wiki/Summarize_primes
Summarize primes
Task Considering in order of length, n, all sequences of consecutive primes, p, from 2 onwards, where p < 1000 and n>0, select those sequences whose sum is prime, and for these display the length of the sequence, the last item in the sequence, and the sum.
#XPL0
XPL0
func IsPrime(N); \Return 'true' if N is a prime number int N, I; [if N <= 1 then return false; for I:= 2 to sqrt(N) do if rem(N/I) = 0 then return false; return true; ];   int Count, N, Sum, Prime; [Text(0, "Prime Prime count sum "); Count:= 0; N:= 0; Sum:= 0; for Prime:= 2 to 1000-1 do if IsPrime(Prime) then [N:= N+1; Sum:= Sum + Prime; if IsPrime(Sum) then [Count:= Count+1; IntOut(0, N); ChOut(0, 9\tab\); IntOut(0, Sum); CrLf(0); ]; ]; IntOut(0, Count); Text(0, " prime sums of primes found below 1000. "); ]
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 polygon that do not need to be displayed. Task Take the closed polygon defined by the points: [ ( 50 , 150 ) , ( 200 , 50 ) , ( 350 , 150 ) , ( 350 , 300 ) , ( 250 , 300 ) , ( 200 , 250 ) , ( 150 , 350 ) , ( 100 , 250 ) , ( 100 , 200 ) ] {\displaystyle [(50,150),(200,50),(350,150),(350,300),(250,300),(200,250),(150,350),(100,250),(100,200)]} and clip it by the rectangle defined by the points: [ ( 100 , 100 ) , ( 300 , 100 ) , ( 300 , 300 ) , ( 100 , 300 ) ] {\displaystyle [(100,100),(300,100),(300,300),(100,300)]} Print the sequence of points that define the resulting clipped polygon. Extra credit Display all three polygons on a graphical surface, using a different color for each polygon and filling the resulting polygon. (When displaying you may use either a north-west or a south-west origin, whichever is more convenient for your display mechanism.)
#Nim
Nim
import sequtils, strformat   type Vec2 = tuple[x, y: float] Edge = tuple[p, q: Vec2] Polygon = seq[Vec2]     func `-`(a, b: Vec2): Vec2 = (a.x - b.x, a.y - b.y)   func cross(a, b: Vec2): float = a.x * b.y - a.y * b.x   func isInside(p: Vec2; edge: Edge): bool = (edge.q.x - edge.p.x) * (p.y - edge.p.y) > (edge.q.y - edge.p.y) * (p.x - edge.p.x)     func intersection(sEdge, cEdge: Edge): Vec2 = let dc = cEdge.p - cEdge.q dp = sEdge.p - sEdge.q n1 = cEdge.p.cross(cEdge.q) n2 = sEdge.p.cross(sEdge.q) n3 = 1 / dc.cross(dp) result = ((n1 * dp.x - n2 * dc.x) * n3, (n1 * dp.y - n2 * dc.y) * n3)     func edges(poly: Polygon): seq[Edge] = (poly[^1] & poly).zip(poly)     func clip(subjectPolygon, clipPolygon: Polygon): Polygon = assert subjectPolygon.len > 1 assert clipPolygon.len > 1   result = subjectPolygon for clipEdge in clipPolygon.edges: let inputList = move(result) result.reset() for inEdge in inputList.edges: if inEdge.q.isInside(clipEdge): if not inEdge.p.isInside(clipEdge): result.add intersection(inEdge, clipEdge) result.add inEdge.q elif inEdge.p.isInside(clipEdge): result.add intersection(inEdge, clipEdge)     proc saveEpsImage(filename: string; subject, clip, clipped: Polygon) = let eps = open(filename, fmWrite) eps.write "%%!PS-Adobe-3.0\n%%%%BoundingBox: 40 40 360 360\n/l {lineto} def\n/m {moveto} def\n", "/s {setrgbcolor} def\n/c {closepath} def\n/gs {fill grestore stroke} def\n"   eps.write &"0 setlinewidth {clip[0].x} {clip[0].y} m " for i in 1..clip.high: eps.write &"{clip[i].x} {clip[i].y} l " eps.writeLine "c 0.5 0 0 s gsave 1 0.7 0.7 s gs"   eps.write &"{subject[0].x} {subject[0].y} m " for i in 1..subject.high: eps.write &"{subject[i].x} {subject[i].y} l " eps.writeLine "c 0 0.2 0.5 s gsave 0.4 0.7 1 s gs"   eps.write &"2 setlinewidth [10 8] 0 setdash {clipped[0].x} {clipped[0].y} m " for i in 1..clipped.high: eps.write &"{clipped[i].x} {clipped[i].y} l " eps.writeLine &"c 0.5 0 0.5 s gsave 0.7 0.3 0.8 s gs"   eps.writeLine "%%%%EOF" eps.close() echo &"File “{filename}” written."     when isMainModule:   let subjectPolygon = @[(50.0, 150.0), (200.0, 50.0), (350.0, 150.0), (350.0, 300.0), (250.0, 300.0), (200.0, 250.0), (150.0, 350.0), (100.0, 250.0), (100.0, 200.0)] clippingPolygon = @[(100.0, 100.0), (300.0, 100.0), (300.0, 300.0), (100.0, 300.0)]   clipped = subjectPolygon.clip(clippingPolygon)   for point in clipped: echo &"({point.x:.3f}, {point.y:.3f})" saveEpsImage("sutherland_hodgman_clipping_out.eps", subjectPolygon, clippingPolygon, clipped)
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 polygon that do not need to be displayed. Task Take the closed polygon defined by the points: [ ( 50 , 150 ) , ( 200 , 50 ) , ( 350 , 150 ) , ( 350 , 300 ) , ( 250 , 300 ) , ( 200 , 250 ) , ( 150 , 350 ) , ( 100 , 250 ) , ( 100 , 200 ) ] {\displaystyle [(50,150),(200,50),(350,150),(350,300),(250,300),(200,250),(150,350),(100,250),(100,200)]} and clip it by the rectangle defined by the points: [ ( 100 , 100 ) , ( 300 , 100 ) , ( 300 , 300 ) , ( 100 , 300 ) ] {\displaystyle [(100,100),(300,100),(300,300),(100,300)]} Print the sequence of points that define the resulting clipped polygon. Extra credit Display all three polygons on a graphical surface, using a different color for each polygon and filling the resulting polygon. (When displaying you may use either a north-west or a south-west origin, whichever is more convenient for your display mechanism.)
#OCaml
OCaml
let is_inside (x,y) ((ax,ay), (bx,by)) = (bx -. ax) *. (y -. ay) > (by -. ay) *. (x -. ax)   let intersection (sx,sy) (ex,ey) ((ax,ay), (bx,by)) = let dc_x, dc_y = (ax -. bx, ay -. by) in let dp_x, dp_y = (sx -. ex, sy -. ey) in let n1 = ax *. by -. ay *. bx in let n2 = sx *. ey -. sy *. ex in let n3 = 1.0 /. (dc_x *. dp_y -. dc_y *. dp_x) in ((n1 *. dp_x -. n2 *. dc_x) *. n3, (n1 *. dp_y -. n2 *. dc_y) *. n3)   let last lst = List.hd (List.rev lst)   let polygon_iter_edges poly f init = if poly = [] then init else let p0 = List.hd poly in let rec aux acc = function | p1 :: p2 :: tl -> aux (f (p1, p2) acc) (p2 :: tl) | p :: [] -> f (p, p0) acc | [] -> acc in aux init poly   let poly_clip subject_polygon clip_polygon = polygon_iter_edges clip_polygon (fun clip_edge input_list -> fst ( List.fold_left (fun (out, s) e ->   match (is_inside e clip_edge), (is_inside s clip_edge) with | true, false -> (e :: (intersection s e clip_edge) :: out), e | true, true -> (e :: out), e | false, true -> ((intersection s e clip_edge) :: out), e | false, false -> (out, e)   ) ([], last input_list) input_list)   ) subject_polygon   let () = let subject_polygon = [ ( 50.0, 150.0); (200.0, 50.0); (350.0, 150.0); (350.0, 300.0); (250.0, 300.0); (200.0, 250.0); (150.0, 350.0); (100.0, 250.0); (100.0, 200.0); ] in   let clip_polygon = [ (100.0, 100.0); (300.0, 100.0); (300.0, 300.0); (100.0, 300.0) ] in   List.iter (fun (x,y) -> Printf.printf " (%g, %g)\n" x y; ) (poly_clip subject_polygon clip_polygon)
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\cap B)} (the set of items that are in at least one of A or B minus the set of items that are in both A and B). Optionally, give the individual differences ( A ∖ B {\displaystyle A\setminus B} and B ∖ A {\displaystyle B\setminus A} ) as well. Test cases A = {John, Bob, Mary, Serena} B = {Jim, Mary, John, Bob} Notes If your code uses lists of items to represent sets then ensure duplicate items in lists are correctly handled. For example two lists representing sets of a = ["John", "Serena", "Bob", "Mary", "Serena"] and b = ["Jim", "Mary", "John", "Jim", "Bob"] should produce the result of just two strings: ["Serena", "Jim"], in any order. In the mathematical notation above A \ B gives the set of items in A that are not in B; A ∪ B gives the set of items in both A and B, (their union); and A ∩ B gives the set of items that are in both A and B (their intersection).
#F.23
F#
> let a = set ["John"; "Bob"; "Mary"; "Serena"] let b = set ["Jim"; "Mary"; "John"; "Bob"];;   val a : Set<string> = set ["Bob"; "John"; "Mary"; "Serena"] val b : Set<string> = set ["Bob"; "Jim"; "John"; "Mary"]   > (a-b) + (b-a);; val it : Set<string> = set ["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 all the arguments, joined with spaces, prepended with a tab, and appended with a trailing newline, are written to NOTES.TXT. If NOTES.TXT doesn't already exist in the current directory then a new NOTES.TXT file should be created.
#Mercury
Mercury
:- module notes. :- interface.   :- import_module io. :- pred main(io::di, io::uo) is det.   :- implementation.   :- import_module list, time.   main(!IO) :- io.command_line_arguments(Args, !IO), ( if Args = [] then print_notes(!IO) else add_note(Args, !IO) ).   :- pred print_notes(io::di, io::uo) is det.   print_notes(!IO) :- io.open_input(notes_filename, InputRes, !IO), ( InputRes = ok(Input), io.input_stream_foldl_io(Input, io.write_char, WriteRes, !IO), ( WriteRes = ok  ; WriteRes = error(WriteError), print_io_error(WriteError, !IO) ), io.close_input(Input, !IO)  ; InputRes = error(_InputError) ).   :- pred add_note(list(string)::in, io::di, io::uo) is det.   add_note(Words, !IO) :- io.open_append(notes_filename, OutputRes, !IO), ( OutputRes = ok(Output), time(Time, !IO), io.write_string(Output, ctime(Time), !IO), io.write_char(Output, '\t', !IO), io.write_list(Output, Words, " ", io.write_string, !IO), io.nl(Output, !IO), io.close_output(Output, !IO)  ; OutputRes = error(OutputError), print_io_error(OutputError, !IO) ).   :- pred print_io_error(io.error::in, io::di, io::uo) is det.   print_io_error(Error, !IO) :- io.stderr_stream(Stderr, !IO), io.write_string(Stderr, io.error_message(Error), !IO), io.set_exit_status(1, !IO).   :- func notes_filename = string.   notes_filename = "NOTES.TXT".   :- end_module notes.
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 all the arguments, joined with spaces, prepended with a tab, and appended with a trailing newline, are written to NOTES.TXT. If NOTES.TXT doesn't already exist in the current directory then a new NOTES.TXT file should be created.
#Nim
Nim
import os, times, strutils   if paramCount() == 0: try: stdout.write readFile("notes.txt") except IOError: discard else: var f = open("notes.txt", fmAppend) f.writeLine getTime() f.writeLine "\t", commandLineParams().join(" ") f.close()
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 all the arguments, joined with spaces, prepended with a tab, and appended with a trailing newline, are written to NOTES.TXT. If NOTES.TXT doesn't already exist in the current directory then a new NOTES.TXT file should be created.
#OCaml
OCaml
#! /usr/bin/env ocaml #load "unix.cma"   let notes_file = "notes.txt"   let take_notes() = let gmt = Unix.gmtime (Unix.time()) in let date = Printf.sprintf "%d-%02d-%02d %02d:%02d:%02d" (1900 + gmt.Unix.tm_year) (1 + gmt.Unix.tm_mon) gmt.Unix.tm_mday gmt.Unix.tm_hour gmt.Unix.tm_min gmt.Unix.tm_sec in let oc = open_out_gen [Open_append; Open_creat; Open_text] 0o644 notes_file in output_string oc (date ^ "\t"); output_string oc (String.concat " " (List.tl(Array.to_list Sys.argv))); output_string oc "\n"; ;;   let dump_notes() = if not(Sys.file_exists notes_file) then (prerr_endline "no local notes found"; exit 1); let ic = open_in notes_file in try while true do print_endline (input_line ic) done with End_of_file -> close_in ic   let () = if Array.length Sys.argv = 1 then dump_notes() else take_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 = b = 200
#Processing
Processing
  //Aamrun, 29th June 2022   float a = 200, b = 200, n = 2.5; float i, incr = 0.001; int xMul,yMul;   size(500,500);   stroke(#ff0000);   for(i=0;i<2*PI;i+=incr){ if(PI/2<i && i<3*PI/2) xMul = -1; else xMul = 1; if(PI<i && i<2*PI) yMul = -1; else yMul = 1;   ellipse(width/2 + xMul * a*pow(abs(cos(i)),2/n),height/2 + yMul * b*pow(abs(sin(i)),2/n),1,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   taxi-cab numbers   taxi cab numbers   Hardy-Ramanujan numbers Task Compute and display the lowest 25 taxicab numbers (in numeric order, and in a human-readable format). For each of the taxicab numbers, show the number as well as it's constituent cubes. Extra credit Show the 2,000th taxicab number, and a half dozen more See also A001235: taxicab numbers on The On-Line Encyclopedia of Integer Sequences. Hardy-Ramanujan Number on MathWorld. taxicab number on MathWorld. taxicab number on Wikipedia   (includes the story on how taxi-cab numbers came to be called).
#Ring
Ring
  # Project : Taxicab numbers   num = 0 for n = 1 to 500000 nr = 0 tax = [] for m = 1 to 75 for p = m + 1 to 75 if n = pow(m, 3) + pow(p, 3) add(tax, m) add(tax, p) nr = nr + 1 ok next next if nr > 1 num = num + 1 see "" + num + " " + n + " => " + tax[1] + "^3 + " + tax[2] + "^3" + ", " see "" + tax[3] + "^3 +" + tax[4] + "^3" + nl if num = 25 exit ok ok next see "ok" + nl  
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   taxi-cab numbers   taxi cab numbers   Hardy-Ramanujan numbers Task Compute and display the lowest 25 taxicab numbers (in numeric order, and in a human-readable format). For each of the taxicab numbers, show the number as well as it's constituent cubes. Extra credit Show the 2,000th taxicab number, and a half dozen more See also A001235: taxicab numbers on The On-Line Encyclopedia of Integer Sequences. Hardy-Ramanujan Number on MathWorld. taxicab number on MathWorld. taxicab number on Wikipedia   (includes the story on how taxi-cab numbers came to be called).
#Ruby
Ruby
def taxicab_number(nmax=1200) [*1..nmax].repeated_combination(2).group_by{|x,y| x**3 + y**3}.select{|k,v| v.size>1}.sort end   t = [0] + taxicab_number   [*1..25, *2000...2007].each do |i| puts "%4d: %10d" % [i, t[i][0]] + t[i][1].map{|a| " = %4d**3 + %4d**3" % a}.join end
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 zero. The Fahrenheit and Rankine scales also have the same magnitude, but different null points. 0 degrees Fahrenheit corresponds to 459.67 degrees Rankine. 0 degrees Rankine is absolute zero. The Celsius/Kelvin and Fahrenheit/Rankine scales have a ratio of 5 : 9. Task Write code that accepts a value of kelvin, converts it to values of the three other scales, and prints the result. Example K 21.00 C -252.15 F -421.87 R 37.80
#Elixir
Elixir
defmodule Temperature do def conversion(t) do IO.puts "K : #{f(t)}" IO.puts "\nC : #{f(t - 273.15)}" IO.puts "\nF : #{f(t * 1.8 - 459.67)}" IO.puts "\nR : #{f(t * 1.8)}" end   defp f(a) do Float.round(a, 2) end   def task, do: conversion(21.0) end   Temperature.task
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 zero. The Fahrenheit and Rankine scales also have the same magnitude, but different null points. 0 degrees Fahrenheit corresponds to 459.67 degrees Rankine. 0 degrees Rankine is absolute zero. The Celsius/Kelvin and Fahrenheit/Rankine scales have a ratio of 5 : 9. Task Write code that accepts a value of kelvin, converts it to values of the three other scales, and prints the result. Example K 21.00 C -252.15 F -421.87 R 37.80
#Erlang
Erlang
% Implemented by Arjun Sunel -module(temp_conv). -export([main/0]).   main() -> conversion(21).   conversion(T) -> io:format("\nK : ~p\n\n",[f(T)]), io:format("C : ~p \n\n",[f(T - 273.15)]), io:format("F : ~p\n\n",[f(T * 1.8 - 459.67)]), io:format("R : ~p\n\n",[f(T * 1.8)]).   f(A) -> (round(A*100))/100 .  
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 logic, sometimes abbreviated 3VL) is any of several many-valued logic systems in which there are three truth values indicating true, false and some indeterminate third value. This is contrasted with the more commonly known bivalent logics (such as classical sentential or boolean logic) which provide only for true and false. Conceptual form and basic ideas were initially created by Łukasiewicz, Lewis and Sulski. These were then re-formulated by Grigore Moisil in an axiomatic algebraic form, and also extended to n-valued logics in 1945. Example Ternary Logic Operators in Truth Tables: not a ¬ True False Maybe Maybe False True a and b ∧ True Maybe False True True Maybe False Maybe Maybe Maybe False False False False False a or b ∨ True Maybe False True True True True Maybe True Maybe Maybe False True Maybe False if a then b ⊃ True Maybe False True True Maybe False Maybe True Maybe Maybe False True True True a is equivalent to b ≡ True Maybe False True True Maybe False Maybe Maybe Maybe Maybe False False Maybe True Task Define a new type that emulates ternary logic by storing data trits. Given all the binary logic operators of the original programming language, reimplement these operators for the new Ternary logic type trit. Generate a sampling of results using trit variables. Kudos for actually thinking up a test case algorithm where ternary logic is intrinsically useful, optimises the test case algorithm and is preferable to binary logic. Note:   Setun   (Сетунь) was a   balanced ternary   computer developed in 1958 at   Moscow State University.   The device was built under the lead of   Sergei Sobolev   and   Nikolay Brusentsov.   It was the only modern   ternary computer,   using three-valued ternary logic
#Red
Red
Red ["Ternary logic"]   ; define trits as a set of 3 Red words: 'oui, 'non and 'bof ; ('bof is a French teenager word expressing indifference) trits: [oui bof non]   ; set the value of each word to itself ; so the expression " oui " will evaluate to word 'oui foreach t trits [set t to-lit-word t]   ; utility function to test if a word is a trit trit?: function [t] [not none? find trits t]   ; ------ prefix operators ------ ; unary operator tnot: !: function [a][ select [oui non oui bof bof] a ] ; binary (prefix) operators tand: function [a b][ either all [a = oui b = oui][oui][ either any [a = non b = non][non][bof] ]] tor: function [a b][ either any [a = oui b = oui][oui][ either all [a = non b = non][non][bof] ]] timp: function [a b][ either a = oui [b][ either a = non [oui][ either b = oui [oui][bof] ]]] teq: function [a b][ either any [a = bof b = bof][bof][ either a = b [oui][non] ]] ; ------ infix operators ------ &: make op! :tand |: make op! :tor =>: make op! :timp <=>: make op! :teq   ; some examples probe init: [ a: oui b: bof c: non] do init foreach s [[! (! a)] [a & b] [a | (b & (oui | non))] [! ((a | b) | b & c)] [(a & b) | c]][ print rejoin [pad mold s 25 " " do s] ]  
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 program can be written to parse and transform the original data into a format useful to the other. The term "Data Munging" is often used in programming circles for this task. A request on the comp.lang.awk newsgroup led to a typical data munging task: I have to analyse data files that have the following format: Each row corresponds to 1 day and the field logic is: $1 is the date, followed by 24 value/flag pairs, representing measurements at 01:00, 02:00 ... 24:00 of the respective day. In short: <date> <val1> <flag1> <val2> <flag2> ... <val24> <flag24> Some test data is available at: ... (nolonger available at original location) I have to sum up the values (per day and only valid data, i.e. with flag>0) in order to calculate the mean. That's not too difficult. However, I also need to know what the "maximum data gap" is, i.e. the longest period with successive invalid measurements (i.e values with flag<=0) The data is free to download and use and is of this format: Data is no longer available at that link. Zipped mirror available here (offsite mirror). 1991-03-30 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 1991-03-31 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 20.000 1 20.000 1 20.000 1 35.000 1 50.000 1 60.000 1 40.000 1 30.000 1 30.000 1 30.000 1 25.000 1 20.000 1 20.000 1 20.000 1 20.000 1 20.000 1 35.000 1 1991-03-31 40.000 1 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 1991-04-01 0.000 -2 13.000 1 16.000 1 21.000 1 24.000 1 22.000 1 20.000 1 18.000 1 29.000 1 44.000 1 50.000 1 43.000 1 38.000 1 27.000 1 27.000 1 24.000 1 23.000 1 18.000 1 12.000 1 13.000 1 14.000 1 15.000 1 13.000 1 10.000 1 1991-04-02 8.000 1 9.000 1 11.000 1 12.000 1 12.000 1 12.000 1 27.000 1 26.000 1 27.000 1 33.000 1 32.000 1 31.000 1 29.000 1 31.000 1 25.000 1 25.000 1 24.000 1 21.000 1 17.000 1 14.000 1 15.000 1 12.000 1 12.000 1 10.000 1 1991-04-03 10.000 1 9.000 1 10.000 1 10.000 1 9.000 1 10.000 1 15.000 1 24.000 1 28.000 1 24.000 1 18.000 1 14.000 1 12.000 1 13.000 1 14.000 1 15.000 1 14.000 1 15.000 1 13.000 1 13.000 1 13.000 1 12.000 1 10.000 1 10.000 1 Only a sample of the data showing its format is given above. The full example file may be downloaded here. Structure your program to show statistics for each line of the file, (similar to the original Python, Perl, and AWK examples below), followed by summary statistics for the file. When showing example output just show a few line statistics and the full end summary.
#Ursala
Ursala
#import std #import nat #import flo   parsed_data = ^|A(~&,* ^|/%ep@iNC ~&h==`1)*htK27K28pPCS (sep 9%cOi&)*FyS readings_dot_txt   daily_stats =   * ^|A(~&,@rFlS ^/length ^/plus:-0. ||0.! ~&i&& mean); mat` + <. ~&n, 'accept: '--+ @ml printf/'%7.0f'+ float, 'total: '--+ @mrl printf/'%10.1f', 'average: '--+ @mrr printf/'%7.3f'>   long_run =   -+ ~&i&& ^|TNC('maximum of '--@h+ %nP,' consecutive false readings ending on line '--), @nmrSPDSL -&~&,leql$^; ^/length ~&zn&-@hrZPF+ rlc both ~&rZ+-   main = ^T(daily_stats^lrNCT/~& @mSL 'summary ':,long_run) parsed_data
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 String length Copy a string Empty string  (assignment) Counting Word frequency Letter frequency Jewels and stones I before E except after C Bioinformatics/base count Count occurrences of a substring Count how many vowels and consonants occur in a string Remove/replace XXXX redacted Conjugate a Latin verb Remove vowels from a string String interpolation (included) Strip block comments Strip comments from a string Strip a set of characters from a string Strip whitespace from a string -- top and tail Strip control codes and extended characters from a string Anagrams/Derangements/shuffling Word wheel ABC problem Sattolo cycle Knuth shuffle Ordered words Superpermutation minimisation Textonyms (using a phone text pad) Anagrams Anagrams/Deranged anagrams Permutations/Derangements Find/Search/Determine ABC words Odd words Word ladder Semordnilap Word search Wordiff  (game) String matching Tea cup rim text Alternade words Changeable words State name puzzle String comparison Unique characters Unique characters in each string Extract file extension Levenshtein distance Palindrome detection Common list elements Longest common suffix Longest common prefix Compare a list of strings Longest common substring Find common directory path Words from neighbour ones Change e letters to i in words Non-continuous subsequences Longest common subsequence Longest palindromic substrings Longest increasing subsequence Words containing "the" substring Sum of the digits of n is substring of n Determine if a string is numeric Determine if a string is collapsible Determine if a string is squeezable Determine if a string has all unique characters Determine if a string has all the same characters Longest substrings without repeating characters Find words which contains all the vowels Find words which contains most consonants Find words which contains more than 3 vowels Find words which first and last three letters are equals Find words which odd letters are consonants and even letters are vowels or vice_versa Formatting Substring Rep-string Word wrap String case Align columns Literals/String Repeat a string Brace expansion Brace expansion using ranges Reverse a string Phrase reversals Comma quibbling Special characters String concatenation Substring/Top and tail Commatizing numbers Reverse words in a string Suffixation of decimal numbers Long literals, with continuations Numerical and alphabetical suffixes Abbreviations, easy Abbreviations, simple Abbreviations, automatic Song lyrics/poems/Mad Libs/phrases Mad Libs Magic 8-ball 99 Bottles of Beer The Name Game (a song) The Old lady swallowed a fly The Twelve Days of Christmas Tokenize Text between Tokenize a string Word break problem Tokenize a string with escaping Split a character string based on change of character Sequences Show ASCII table De Bruijn sequences Self-referential sequences Generate lower case ASCII alphabet
#PowerShell
PowerShell
$days = @{ 1 = "first"; 2 = "second"; 3 = "third"; 4 = "fourth"; 5 = "fifth"; 6 = "sixth"; 7 = "seventh"; 8 = "eight"; 9 = "ninth"; 10 = "tenth"; 11 = "eleventh"; 12 = "twelfth"; }   $gifts = @{ 1 = 'A partridge in a pear tree'; 2 = 'Two turtle doves'; 3 = 'Three french hens'; 4 = 'Four calling birds'; 5 = 'Five golden rings'; 6 = 'Six geese a-laying'; 7 = 'Seven swans a-swimming'; 8 = 'Eight maids a-milking'; 9 = 'Nine ladies dancing'; 10 = 'Ten lords a-leaping'; 11 = 'Eleven pipers piping'; 12 = 'Twelve drummers drumming'; }   1 .. 12 | % { "On the $($days[$_]) day of Christmas`nMy true love gave to me" $_ .. 1 | % { $gift = $gifts[$_] if ($_ -eq 2) { $gift += " and" } $gift } "" }
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 the term threads, others use the term tasks, while others use co-processes. This task should not be implemented using fork, spawn, or the Linux/UNIX/Win32 pipe command, as communication should be between threads, not processes. One of the concurrent units will read from a file named "input.txt" and send the contents of that file, one line at a time, to the other concurrent unit, which will print the line it receives to standard output. The printing unit must count the number of lines it prints. After the concurrent unit reading the file sends its last line to the printing unit, the reading unit will request the number of lines printed by the printing unit. The reading unit will then print the number of lines printed by the printing unit. This task requires two-way communication between the concurrent units. All concurrent units must cleanly terminate at the end of the program.
#Phix
Phix
-- demo\rosetta\Synchronous_concurrency.exw without js -- threads, file i/o, command_line() string filename = substitute(command_line()[2],".exe",".exw") atom frThread, -- file reader thread lcThread -- line counter thread sequence queue = {} integer qlock = init_cs(), linecount = 1 procedure readfile() integer fn = open(filename,"r") while 1 do object line = gets(fn) enter_cs(qlock) queue = append(queue,line) line = atom(line) -- kill refcount! leave_cs(qlock) if line then exit end if end while close(fn) wait_thread(lcThread) printf(1,"Lines read: %d\n",linecount) exit_thread(0) end procedure procedure countlines() linecount = 0 while 1 do enter_cs(qlock) if length(queue)=0 then leave_cs(qlock) -- sleep(0.1) else object line = queue[1] queue = queue[2..$] leave_cs(qlock) if atom(line) then exit end if --  ?line linecount += 1 end if end while exit_thread(0) end procedure lcThread = create_thread(countlines,{}) frThread = create_thread(readfile,{}) wait_thread(frThread) puts(1,"done") {} = wait_key()
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   Retrieving system time (wiki)
#Clojure
Clojure
(import '[java.util Date]) ; the current system date time string (print (new Date)) ; the system time as milliseconds since 1970 (print (. (new Date) getTime)) ; or (print (System/currentTimeMillis))
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   Retrieving system time (wiki)
#CLU
CLU
start_up = proc () stream$putl(stream$primary_output(), date$unparse(now())) end start_up
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 generated grow in length geometrically and never converge. Another way to generate a self-referential sequence is to summarize the previous term. Count how many of each alike digit there is, then concatenate the sum and digit for each of the sorted enumerated digits. Note that the first five terms are the same as for the previous sequence. 0, 10, 1110, 3110, 132110, 13123110, 23124110 ... Sort the digits largest to smallest. Do not include counts of digits that do not appear in the previous term. Depending on the seed value, series generated this way always either converge to a stable value or to a short cyclical pattern. (For our purposes, I'll use converge to mean an element matches a previously seen element.) The sequence shown, with a seed value of 0, converges to a stable value of 1433223110 after 11 iterations. The seed value that converges most quickly is 22. It goes stable after the first element. (The next element is 22, which has been seen before.) Task Find all the positive integer seed values under 1000000, for the above convergent self-referential sequence, that takes the largest number of iterations before converging. Then print out the number of iterations and the sequence they return. Note that different permutations of the digits of the seed will yield the same sequence. For this task, assume leading zeros are not permitted. Seed Value(s): 9009 9090 9900 Iterations: 21 Sequence: (same for all three seeds except for first element) 9009 2920 192210 19222110 19323110 1923123110 1923224110 191413323110 191433125110 19151423125110 19251413226110 1916151413325110 1916251423127110 191716151413326110 191726151423128110 19181716151413327110 19182716151423129110 29181716151413328110 19281716151423228110 19281716151413427110 19182716152413228110 Related tasks   Fours is the number of letters in the ...   Look-and-say sequence   Number names   Self-describing numbers   Spelling of ordinal numbers Other tasks related to string operations: Metrics Array length String length Copy a string Empty string  (assignment) Counting Word frequency Letter frequency Jewels and stones I before E except after C Bioinformatics/base count Count occurrences of a substring Count how many vowels and consonants occur in a string Remove/replace XXXX redacted Conjugate a Latin verb Remove vowels from a string String interpolation (included) Strip block comments Strip comments from a string Strip a set of characters from a string Strip whitespace from a string -- top and tail Strip control codes and extended characters from a string Anagrams/Derangements/shuffling Word wheel ABC problem Sattolo cycle Knuth shuffle Ordered words Superpermutation minimisation Textonyms (using a phone text pad) Anagrams Anagrams/Deranged anagrams Permutations/Derangements Find/Search/Determine ABC words Odd words Word ladder Semordnilap Word search Wordiff  (game) String matching Tea cup rim text Alternade words Changeable words State name puzzle String comparison Unique characters Unique characters in each string Extract file extension Levenshtein distance Palindrome detection Common list elements Longest common suffix Longest common prefix Compare a list of strings Longest common substring Find common directory path Words from neighbour ones Change e letters to i in words Non-continuous subsequences Longest common subsequence Longest palindromic substrings Longest increasing subsequence Words containing "the" substring Sum of the digits of n is substring of n Determine if a string is numeric Determine if a string is collapsible Determine if a string is squeezable Determine if a string has all unique characters Determine if a string has all the same characters Longest substrings without repeating characters Find words which contains all the vowels Find words which contains most consonants Find words which contains more than 3 vowels Find words which first and last three letters are equals Find words which odd letters are consonants and even letters are vowels or vice_versa Formatting Substring Rep-string Word wrap String case Align columns Literals/String Repeat a string Brace expansion Brace expansion using ranges Reverse a string Phrase reversals Comma quibbling Special characters String concatenation Substring/Top and tail Commatizing numbers Reverse words in a string Suffixation of decimal numbers Long literals, with continuations Numerical and alphabetical suffixes Abbreviations, easy Abbreviations, simple Abbreviations, automatic Song lyrics/poems/Mad Libs/phrases Mad Libs Magic 8-ball 99 Bottles of Beer The Name Game (a song) The Old lady swallowed a fly The Twelve Days of Christmas Tokenize Text between Tokenize a string Word break problem Tokenize a string with escaping Split a character string based on change of character Sequences Show ASCII table De Bruijn sequences Self-referential sequences Generate lower case ASCII alphabet Also see   The On-Line Encyclopedia of Integer Sequences.
#Eiffel
Eiffel
  class SELF_REFERENTIAL_SEQUENCE   create make   feature   make local i: INTEGER length, max: INTEGER_64 do create seed_value.make create sequence.make (25) create permuted_values.make from i := 1 until i > 1000000 loop length := check_length (i.out) if length > max then max := length seed_value.wipe_out seed_value.extend (i) elseif length = max then seed_value.extend (i) end sequence.wipe_out i := next_ascending (i).to_integer end io.put_string ("Maximal length: " + max.out) io.put_string ("%NSeed Value: %N") across seed_value as s loop permute (s.item.out, 1) end across permuted_values as p loop io.put_string (p.item + "%N") end io.put_string ("Sequence:%N") max := check_length (seed_value [1].out) across sequence as s loop io.put_string (s.item) io.new_line end end   next_ascending (n: INTEGER_64): STRING -- Next number with ascending digits after 'n'. -- Numbers with trailing zeros are treated as ascending numbers. local st: STRING first, should_be, zero: STRING i: INTEGER do create Result.make_empty create zero.make_empty st := (n + 1).out from until st.count < 2 loop first := st.at (1).out if st [2] ~ '0' then from i := 3 until i > st.count loop zero.append ("0") i := i + 1 end Result.append (first + first + zero) st := "" else should_be := st.at (2).out if first > should_be then should_be := first end st.remove_head (2) st.prepend (should_be) Result.append (first) end end if st.count > 0 then Result.append (st [st.count].out) end end   feature {NONE}   seed_value: SORTED_TWO_WAY_LIST [INTEGER]   permuted_values: SORTED_TWO_WAY_LIST [STRING]   sequence: ARRAYED_LIST [STRING]   permute (a: STRING; k: INTEGER) -- All permutations of 'a'. require count_positive: a.count > 0 k_valid_index: k > 0 local t: CHARACTER b: STRING found: BOOLEAN do across permuted_values as p loop if p.item ~ a then found := True end end if k = a.count and a [1] /= '0' and not found then create b.make_empty b.deep_copy (a) permuted_values.extend (b) else across k |..| a.count as c loop t := a [k] a [k] := a [c.item] a [c.item] := t permute (a, k + 1) t := a [k] a [k] := a [c.item] a [c.item] := t end end end   check_length (i: STRING): INTEGER_64 -- Length of the self referential sequence starting with 'i'. local found: BOOLEAN j: INTEGER s: STRING do create s.make_from_string (i) from until found loop sequence.extend (s) s := next (s) from j := sequence.count - 1 until j < 1 loop if sequence [j] ~ s then found := True end j := j - 1 end end Result := sequence.count end   next (n: STRING): STRING -- Next item after 'n' in a self referential sequence. local i, count: INTEGER counter: ARRAY [INTEGER] do create counter.make_filled (0, 0, 9) create Result.make_empty from i := 1 until i > n.count loop count := n [i].out.to_integer counter [count] := counter [count] + 1 i := i + 1 end from i := 9 until i < 0 loop if counter [i] > 0 then Result.append (counter [i].out + i.out) end i := i - 1 end end   end  
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 polygon that do not need to be displayed. Task Take the closed polygon defined by the points: [ ( 50 , 150 ) , ( 200 , 50 ) , ( 350 , 150 ) , ( 350 , 300 ) , ( 250 , 300 ) , ( 200 , 250 ) , ( 150 , 350 ) , ( 100 , 250 ) , ( 100 , 200 ) ] {\displaystyle [(50,150),(200,50),(350,150),(350,300),(250,300),(200,250),(150,350),(100,250),(100,200)]} and clip it by the rectangle defined by the points: [ ( 100 , 100 ) , ( 300 , 100 ) , ( 300 , 300 ) , ( 100 , 300 ) ] {\displaystyle [(100,100),(300,100),(300,300),(100,300)]} Print the sequence of points that define the resulting clipped polygon. Extra credit Display all three polygons on a graphical surface, using a different color for each polygon and filling the resulting polygon. (When displaying you may use either a north-west or a south-west origin, whichever is more convenient for your display mechanism.)
#Perl
Perl
use strict; use warnings;   sub intersection { my($L11, $L12, $L21, $L22) = @_; my ($d1x, $d1y) = ($$L11[0] - $$L12[0], $$L11[1] - $$L12[1]); my ($d2x, $d2y) = ($$L21[0] - $$L22[0], $$L21[1] - $$L22[1]); my $n1 = $$L11[0] * $$L12[1] - $$L11[1] * $$L12[0]; my $n2 = $$L21[0] * $$L22[1] - $$L21[1] * $$L22[0]; my $n3 = 1 / ($d1x * $d2y - $d2x * $d1y); [($n1 * $d2x - $n2 * $d1x) * $n3, ($n1 * $d2y - $n2 * $d1y) * $n3] }   sub is_inside { my($p1, $p2, $p3) = @_; ($$p2[0] - $$p1[0]) * ($$p3[1] - $$p1[1]) > ($$p2[1] - $$p1[1]) * ($$p3[0] - $$p1[0]) }   sub sutherland_hodgman { my($polygon, $clip) = @_; my @output = @$polygon; my $clip_point1 = $$clip[-1]; for my $clip_point2 (@$clip) { my @input = @output; @output = (); my $start = $input[-1]; for my $end (@input) { if (is_inside($clip_point1, $clip_point2, $end)) { push @output, intersection($clip_point1, $clip_point2, $start, $end) unless is_inside($clip_point1, $clip_point2, $start); push @output, $end; } elsif (is_inside($clip_point1, $clip_point2, $start)) { push @output, intersection($clip_point1, $clip_point2, $start, $end); } $start = $end; } $clip_point1 = $clip_point2; } @output }   my @polygon = ([50, 150], [200, 50], [350, 150], [350, 300], [250, 300], [200, 250], [150, 350], [100, 250], [100, 200]);   my @clip = ([100, 100], [300, 100], [300, 300], [100, 300]);   my @clipped = sutherland_hodgman(\@polygon, \@clip);   print "Clipped polygon:\n"; print '(' . join(' ', @$_) . ') ' for @clipped;
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\cap B)} (the set of items that are in at least one of A or B minus the set of items that are in both A and B). Optionally, give the individual differences ( A ∖ B {\displaystyle A\setminus B} and B ∖ A {\displaystyle B\setminus A} ) as well. Test cases A = {John, Bob, Mary, Serena} B = {Jim, Mary, John, Bob} Notes If your code uses lists of items to represent sets then ensure duplicate items in lists are correctly handled. For example two lists representing sets of a = ["John", "Serena", "Bob", "Mary", "Serena"] and b = ["Jim", "Mary", "John", "Jim", "Bob"] should produce the result of just two strings: ["Serena", "Jim"], in any order. In the mathematical notation above A \ B gives the set of items in A that are not in B; A ∪ B gives the set of items in both A and B, (their union); and A ∩ B gives the set of items that are in both A and B (their intersection).
#Factor
Factor
: symmetric-diff ( a b -- c ) [ diff ] [ swap diff ] 2bi append ;   { "John" "Bob" "Mary" "Serena" } { "Jim" "Mary" "John" "Bob" } symmetric-diff .
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\cap B)} (the set of items that are in at least one of A or B minus the set of items that are in both A and B). Optionally, give the individual differences ( A ∖ B {\displaystyle A\setminus B} and B ∖ A {\displaystyle B\setminus A} ) as well. Test cases A = {John, Bob, Mary, Serena} B = {Jim, Mary, John, Bob} Notes If your code uses lists of items to represent sets then ensure duplicate items in lists are correctly handled. For example two lists representing sets of a = ["John", "Serena", "Bob", "Mary", "Serena"] and b = ["Jim", "Mary", "John", "Jim", "Bob"] should produce the result of just two strings: ["Serena", "Jim"], in any order. In the mathematical notation above A \ B gives the set of items in A that are not in B; A ∪ B gives the set of items in both A and B, (their union); and A ∩ B gives the set of items that are in both A and B (their intersection).
#Forth
Forth
: elm ( n -- ; one cell per set ) [ cell 8 * 1- ] literal umin CREATE 1 swap lshift , DOES> ( -- 2^n ) @ ;   : universe ( u "name" -- ) dup 0 DO I elm latest swap LOOP CREATE dup , 0 DO , LOOP DOES> ( n a -- ) dup @ tuck cells + swap 0 DO ( n a' ) over I rshift 1 AND IF dup @ name>string space type THEN 1 cells - LOOP 2drop ;   5 universe john bob mary serena jim persons john bob mary serena or or or jim mary john bob or or or   2dup xor persons 2dup -1 xor and cr persons swap -1 xor and cr persons cr bye  
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 all the arguments, joined with spaces, prepended with a tab, and appended with a trailing newline, are written to NOTES.TXT. If NOTES.TXT doesn't already exist in the current directory then a new NOTES.TXT file should be created.
#Oz
Oz
functor import Application Open OS System define fun {TimeStamp} N = {OS.localTime} in (1900+N.year)#"-"#(1+N.mon)#"-"#N.mDay#", "#N.hour#":"#N.min#":"#N.sec end   fun {Join X|Xr Sep} {FoldL Xr fun {$ Z X} Z#Sep#X end X} end   case {Application.getArgs plain} of nil then try F = {New Open.file init(name:"notes.txt")} in {System.printInfo {F read(list:$ size:all)}} {F close} catch _ then skip end [] Args then F = {New Open.file init(name:"notes.txt" flags:[write text create append])} in {F write(vs:{TimeStamp}#"\n")} {F write(vs:"\t"#{Join Args " "}#"\n")} {F close} end {Application.exit 0} 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 all the arguments, joined with spaces, prepended with a tab, and appended with a trailing newline, are written to NOTES.TXT. If NOTES.TXT doesn't already exist in the current directory then a new NOTES.TXT file should be created.
#Pascal
Pascal
  {$mode delphi} PROGRAM notes; // Notes: a time-stamped command line notebook // usage: >notes "note"< or >notes< to display contents USES Classes, SysUtils;   VAR Note : TStringList; Fname : STRING = 'Notes.txt'; Dtime : STRING; Ntext : STRING; c : Cardinal;   BEGIN DTime := FormatDateTime('YYYY-MM-DD-hhnn',Now); Note := TStringList.Create; WITH Note DO BEGIN TRY LoadFromFile(Fname); EXCEPT Add(DTime); NText := 'Notes.txt created.'; END; // command line args present: // add note with date & time IF ParamStr(1) <> '' THEN BEGIN NText := ParamStr(1); Add(DTime); Add(NText); SaveToFile(Fname); // command line args absent: // display contents of notebook END ELSE FOR c := 0 TO Count-1 DO Writeln(Note[c]); Free; END; END.  
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 = b = 200
#Python
Python
  # Superellipse drawing in Python 2.7.9 # pic can see at http://www.imgup.cz/image/712   import matplotlib.pyplot as plt from math import sin, cos, pi   def sgn(x): return ((x>0)-(x<0))*1   a,b,n=200,200,2.5 # param n making shape na=2/n step=100 # accuracy piece=(pi*2)/step xp=[];yp=[]   t=0 for t1 in range(step+1): # because sin^n(x) is mathematically the same as (sin(x))^n... x=(abs((cos(t)))**na)*a*sgn(cos(t)) y=(abs((sin(t)))**na)*b*sgn(sin(t)) xp.append(x);yp.append(y) t+=piece   plt.plot(xp,yp) # plotting all point from array xp, yp plt.title("Superellipse with parameter "+str(n)) plt.show()  
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   taxi-cab numbers   taxi cab numbers   Hardy-Ramanujan numbers Task Compute and display the lowest 25 taxicab numbers (in numeric order, and in a human-readable format). For each of the taxicab numbers, show the number as well as it's constituent cubes. Extra credit Show the 2,000th taxicab number, and a half dozen more See also A001235: taxicab numbers on The On-Line Encyclopedia of Integer Sequences. Hardy-Ramanujan Number on MathWorld. taxicab number on MathWorld. taxicab number on Wikipedia   (includes the story on how taxi-cab numbers came to be called).
#Rust
Rust
  use std::collections::HashMap; use itertools::Itertools;   fn cubes(n: u64) -> Vec<u64> { let mut cube_vector = Vec::new(); for i in 1..=n { cube_vector.push(i.pow(3)); } cube_vector }   fn main() { let c = cubes(1201); let it = c.iter().combinations(2); let mut m = HashMap::new(); for x in it { let sum = x[0] + x[1]; m.entry(sum).or_insert(Vec::new()).push(x) }   let mut result = Vec::new();   for (k,v) in m.iter() { if v.len() > 1 { result.push((k,v)); } }   result.sort(); for f in result { println!("{:?}", f); } }  
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   taxi-cab numbers   taxi cab numbers   Hardy-Ramanujan numbers Task Compute and display the lowest 25 taxicab numbers (in numeric order, and in a human-readable format). For each of the taxicab numbers, show the number as well as it's constituent cubes. Extra credit Show the 2,000th taxicab number, and a half dozen more See also A001235: taxicab numbers on The On-Line Encyclopedia of Integer Sequences. Hardy-Ramanujan Number on MathWorld. taxicab number on MathWorld. taxicab number on Wikipedia   (includes the story on how taxi-cab numbers came to be called).
#Scala
Scala
import scala.collection.MapView import scala.math.pow   implicit class Pairs[A, B]( p:List[(A, B)]) { def collectPairs: MapView[A, List[B]] = p.groupBy(_._1).view.mapValues(_.map(_._2)).filterNot(_._2.size<2) }   // Make a sorted List of Taxi Cab Numbers. Limit it to the cube of 1200 because we know it's high enough. val taxiNums = { (1 to 1200).toList // Start with a sequential list of integers .combinations(2).toList // Find all two number combinations .map { case a :: b :: nil => ((pow(a, 3) + pow(b, 3)).toInt, (a, b)) case _ => 0 ->(0, 0) } // Turn the list into the sum of two cubes and // remember what we started with, eg. 28->(1,3) .collectPairs // Only keep taxi cab numbers with a duplicate .toList.sortBy(_._1) // Sort the results }   def output() : Unit = { println( "%20s".format( "Taxi Cab Numbers" ) ) println( "%20s%15s%15s".format( "-"*20, "-"*15, "-"*15 ) )   taxiNums.take(25) foreach { case (p, a::b::Nil) => println( "%20d\t(%d\u00b3 + %d\u00b3)\t\t(%d\u00b3 + %d\u00b3)".format(p,a._1,a._2,b._1,b._2) ) }   taxiNums.slice(1999,2007) foreach { case (p, a::b::Nil) => println( "%20d\t(%d\u00b3 + %d\u00b3)\t(%d\u00b3 + %d\u00b3)".format(p,a._1,a._2,b._1,b._2) ) } }
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 zero. The Fahrenheit and Rankine scales also have the same magnitude, but different null points. 0 degrees Fahrenheit corresponds to 459.67 degrees Rankine. 0 degrees Rankine is absolute zero. The Celsius/Kelvin and Fahrenheit/Rankine scales have a ratio of 5 : 9. Task Write code that accepts a value of kelvin, converts it to values of the three other scales, and prints the result. Example K 21.00 C -252.15 F -421.87 R 37.80
#Euphoria
Euphoria
  include std/console.e   atom K while 1 do K = prompt_number("Enter temperature in Kelvin >=0: ",{0,4294967296}) printf(1,"K = %5.2f\nC = %5.2f\nF = %5.2f\nR = %5.2f\n\n",{K,K-273.15,K*1.8-459.67,K*1.8}) end while  
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 logic, sometimes abbreviated 3VL) is any of several many-valued logic systems in which there are three truth values indicating true, false and some indeterminate third value. This is contrasted with the more commonly known bivalent logics (such as classical sentential or boolean logic) which provide only for true and false. Conceptual form and basic ideas were initially created by Łukasiewicz, Lewis and Sulski. These were then re-formulated by Grigore Moisil in an axiomatic algebraic form, and also extended to n-valued logics in 1945. Example Ternary Logic Operators in Truth Tables: not a ¬ True False Maybe Maybe False True a and b ∧ True Maybe False True True Maybe False Maybe Maybe Maybe False False False False False a or b ∨ True Maybe False True True True True Maybe True Maybe Maybe False True Maybe False if a then b ⊃ True Maybe False True True Maybe False Maybe True Maybe Maybe False True True True a is equivalent to b ≡ True Maybe False True True Maybe False Maybe Maybe Maybe Maybe False False Maybe True Task Define a new type that emulates ternary logic by storing data trits. Given all the binary logic operators of the original programming language, reimplement these operators for the new Ternary logic type trit. Generate a sampling of results using trit variables. Kudos for actually thinking up a test case algorithm where ternary logic is intrinsically useful, optimises the test case algorithm and is preferable to binary logic. Note:   Setun   (Сетунь) was a   balanced ternary   computer developed in 1958 at   Moscow State University.   The device was built under the lead of   Sergei Sobolev   and   Nikolay Brusentsov.   It was the only modern   ternary computer,   using three-valued ternary logic
#REXX
REXX
/*REXX program displays a ternary truth table [true, false, maybe] for the variables */ /*──── and one or more expressions. */ /*──── Infix notation is supported with one character propositional constants. */ /*──── Variables (propositional constants) allowed: A ──► Z, a ──► z except u.*/ /*──── All propositional constants are case insensative (except lowercase v). */ parse arg $express /*obtain optional argument from the CL.*/ if $express\='' then do /*Got one? Then show user's expression*/ call truthTable $express /*display the user's truth table──►term*/ exit /*we're all done with the truth table. */ end   call truthTable "a & b ; AND" call truthTable "a | b ; OR" call truthTable "a ^ b ; XOR" call truthTable "a ! b ; NOR" call truthTable "a ¡ b ; NAND" call truthTable "a xnor b ; XNOR" /*XNOR is the same as NXOR. */ exit /*stick a fork in it, we're all done. */ /*──────────────────────────────────────────────────────────────────────────────────────*/ truthTable: procedure; parse arg $ ';' comm 1 $o; $o=strip($o) $=translate(strip($), '|', "v"); $u=$; upper $u $u=translate($u, '()()()', "[]{}«»"); $$.=0; PCs=; hdrPCs= @abc= 'abcdefghijklmnopqrstuvwxyz'; @abcU=@abc; upper @abcU @= 'ff'x /*─────────infix operators───────*/ op.= /*a single quote (') wasn't */ /* implemented for negation. */ op.0 = 'false boolFALSE' /*unconditionally FALSE */ op.1 = 'and and & *' /* AND, conjunction */ op.2 = 'naimpb NaIMPb' /*not A implies B */ op.3 = 'boolb boolB' /*B (value of) */ op.4 = 'nbimpa NbIMPa' /*not B implies A */ op.5 = 'boola boolA' /*A (value of) */ op.6 = 'xor xor && % ^' /* XOR, exclusive OR */ op.7 = 'or or | + v' /* OR, disjunction */ op.8 = 'nor nor ! ↓' /* NOR, not OR, Pierce operator */ op.9 = 'xnor xnor nxor' /*NXOR, not exclusive OR, not XOR*/ op.10 = 'notb notB' /*not B (value of) */ op.11 = 'bimpa bIMPa' /* B implies A */ op.12 = 'nota notA' /*not A (value of) */ op.13 = 'aimpb aIMPb' /* A implies B */ op.14 = 'nand nand ¡ ↑' /*NAND, not AND, Sheffer operator*/ op.15 = 'true boolTRUE' /*unconditionally TRUE */ /*alphabetic names need changing.*/ op.16 = '\ NOT ~ ─ . ¬' /* NOT, negation */ op.17 = '> GT' /*conditional greater than */ op.18 = '>= GE ─> => ──> ==>' "1a"x /*conditional greater than or eq.*/ op.19 = '< LT' /*conditional less than */ op.20 = '<= LE <─ <= <── <==' /*conditional less then or equal */ op.21 = '\= NE ~= ─= .= ¬=' /*conditional not equal to */ op.22 = '= EQ EQUAL EQUALS =' "1b"x /*biconditional (equals) */ op.23 = '0 boolTRUE' /*TRUEness */ op.24 = '1 boolFALSE' /*FALSEness */   op.25 = 'NOT NOT NEG' /*not, neg (negative) */   do jj=0 while op.jj\=='' | jj<16 /*change opers──►what REXX likes.*/ new=word(op.jj,1) do kk=2 to words(op.jj) /*handle each token separately. */ _=word(op.jj, kk); upper _ if wordpos(_, $u)==0 then iterate /*no such animal in this string. */ if datatype(new, 'm') then new!=@ /*expresion needs transcribing. */ else new!=new $u=changestr(_, $u, new!) /*transcribe the function (maybe)*/ if new!==@ then $u=changeFunc($u, @, new) /*use the internal boolean name. */ end /*kk*/ end /*jj*/   $u=translate($u, '()', "{}") /*finish cleaning up transcribing*/ do jj=1 for length(@abcU) /*see what variables are used. */ _=substr(@abcU, jj, 1) /*use available upercase alphabet*/ if pos(_,$u)==0 then iterate /*found one? No, keep looking. */ $$.jj=2 /*found: set upper bound for it.*/ PCs=PCs _ /*also, add to propositional cons*/ hdrPCs=hdrPCS center(_, length('false')) /*build a propositional cons hdr.*/ end /*jj*/ $u=PCs '('$u")" /*sep prop. cons. from expression*/ ptr='_────►_' /*a pointer for the truth table. */ hdrPCs=substr(hdrPCs,2) /*create a header for prop. cons.*/ say hdrPCs left('', length(ptr) -1) $o /*show prop cons hdr +expression.*/ say copies('───── ', words(PCs)) left('', length(ptr)-2) copies('─', length($o)) /*Note: "true"s: right─justified*/ do a=0 to $$.1 do b=0 to $$.2 do c=0 to $$.3 do d=0 to $$.4 do e=0 to $$.5 do f=0 to $$.6 do g=0 to $$.7 do h=0 to $$.8 do i=0 to $$.9 do j=0 to $$.10 do k=0 to $$.11 do l=0 to $$.12 do m=0 to $$.13 do n=0 to $$.14 do o=0 to $$.15 do p=0 to $$.16 do q=0 to $$.17 do r=0 to $$.18 do s=0 to $$.19 do t=0 to $$.20 do u=0 to $$.21 do !=0 to $$.22 do w=0 to $$.23 do x=0 to $$.24 do y=0 to $$.25 do z=0 to $$.26 interpret '_=' $u /*evaluate truth T.*/ _=changestr(0, _, 'false') /*convert 0──►false*/ _=changestr(1, _, '_true') /*convert 1──►_true*/ _=changestr(2, _, 'maybe') /*convert 2──►maybe*/ _=insert(ptr, _, wordindex(_, words(_)) -1) /*──►*/ say translate(_, , '_') /*display truth tab*/ end /*z*/ end /*y*/ end /*x*/ end /*w*/ end /*v*/ end /*u*/ end /*t*/ end /*s*/ end /*r*/ end /*q*/ end /*p*/ end /*o*/ end /*n*/ end /*m*/ end /*l*/ end /*k*/ end /*j*/ end /*i*/ end /*h*/ end /*g*/ end /*f*/ end /*e*/ end /*d*/ end /*c*/ end /*b*/ end /*a*/ say return /*──────────────────────────────────────────────────────────────────────────────────────*/ scan: procedure; parse arg x,at; L=length(x); t=L; lp=0; apost=0; quote=0 if at<0 then do; t=1; x= translate(x, '()', ")("); end   do j=abs(at) to t by sign(at); _=substr(x,j,1); __=substr(x,j,2) if quote then do; if _\=='"' then iterate if __=='""' then do; j=j+1; iterate; end quote=0; iterate end if apost then do; if _\=="'" then iterate if __=="''" then do; j=j+1; iterate; end apost=0; iterate end if _=='"' then do; quote=1; iterate; end if _=="'" then do; apost=1; iterate; end if _==' ' then iterate if _=='(' then do; lp=lp+1; iterate; end if lp\==0 then do; if _==')' then lp=lp-1; iterate; end if datatype(_,'U') then return j - (at<0) if at<0 then return j + 1 end /*j*/ return min(j,L) /*──────────────────────────────────────────────────────────────────────────────────────*/ changeFunc: procedure; parse arg z,fC,newF; funcPos= 0 do forever funcPos= pos(fC, z, funcPos + 1); if funcPos==0 then return z origPos= funcPos z= changestr(fC, z, ",'"newF"',") funcPos= funcPos + length(newF) + 4 where= scan(z, funcPos)  ; z= insert( '}', z, where) where= scan(z, 1 - origPos) ; z= insert('trit{', z, where) end /*forever*/ /*──────────────────────────────────────────────────────────────────────────────────────*/ trit: procedure; arg a,$,b; v= \(a==2 | b==2); o= (a==1 | b==1); z= (a==0 | b==0) select when $=='FALSE' then return 0 when $=='AND' then if v then return a & b; else return 2 when $=='NAIMPB' then if v then return \(\a & \b); else return 2 when $=='BOOLB' then return b when $=='NBIMPA' then if v then return \(\b & \a); else return 2 when $=='BOOLA' then return a when $=='XOR' then if v then return a && b  ; else return 2 when $=='OR' then if v then return a | b  ; else if o then return 1 else return 2 when $=='NOR' then if v then return \(a | b)  ; else return 2 when $=='XNOR' then if v then return \(a && b) ; else return 2 when $=='NOTB' then if v then return \b  ; else return 2 when $=='NOTA' then if v then return \a  ; else return 2 when $=='AIMPB' then if v then return \(a & \b) ; else return 2 when $=='NAND' then if v then return \(a & b) ; else if z then return 1 else return 2 when $=='TRUE' then return 1 otherwise return -13 /*error, unknown function.*/ end /*select*/  
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 program can be written to parse and transform the original data into a format useful to the other. The term "Data Munging" is often used in programming circles for this task. A request on the comp.lang.awk newsgroup led to a typical data munging task: I have to analyse data files that have the following format: Each row corresponds to 1 day and the field logic is: $1 is the date, followed by 24 value/flag pairs, representing measurements at 01:00, 02:00 ... 24:00 of the respective day. In short: <date> <val1> <flag1> <val2> <flag2> ... <val24> <flag24> Some test data is available at: ... (nolonger available at original location) I have to sum up the values (per day and only valid data, i.e. with flag>0) in order to calculate the mean. That's not too difficult. However, I also need to know what the "maximum data gap" is, i.e. the longest period with successive invalid measurements (i.e values with flag<=0) The data is free to download and use and is of this format: Data is no longer available at that link. Zipped mirror available here (offsite mirror). 1991-03-30 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 1991-03-31 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 20.000 1 20.000 1 20.000 1 35.000 1 50.000 1 60.000 1 40.000 1 30.000 1 30.000 1 30.000 1 25.000 1 20.000 1 20.000 1 20.000 1 20.000 1 20.000 1 35.000 1 1991-03-31 40.000 1 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 1991-04-01 0.000 -2 13.000 1 16.000 1 21.000 1 24.000 1 22.000 1 20.000 1 18.000 1 29.000 1 44.000 1 50.000 1 43.000 1 38.000 1 27.000 1 27.000 1 24.000 1 23.000 1 18.000 1 12.000 1 13.000 1 14.000 1 15.000 1 13.000 1 10.000 1 1991-04-02 8.000 1 9.000 1 11.000 1 12.000 1 12.000 1 12.000 1 27.000 1 26.000 1 27.000 1 33.000 1 32.000 1 31.000 1 29.000 1 31.000 1 25.000 1 25.000 1 24.000 1 21.000 1 17.000 1 14.000 1 15.000 1 12.000 1 12.000 1 10.000 1 1991-04-03 10.000 1 9.000 1 10.000 1 10.000 1 9.000 1 10.000 1 15.000 1 24.000 1 28.000 1 24.000 1 18.000 1 14.000 1 12.000 1 13.000 1 14.000 1 15.000 1 14.000 1 15.000 1 13.000 1 13.000 1 13.000 1 12.000 1 10.000 1 10.000 1 Only a sample of the data showing its format is given above. The full example file may be downloaded here. Structure your program to show statistics for each line of the file, (similar to the original Python, Perl, and AWK examples below), followed by summary statistics for the file. When showing example output just show a few line statistics and the full end summary.
#VBScript
VBScript
Set objFSO = CreateObject("Scripting.FileSystemObject") Set objFile = objFSO.OpenTextFile(objFSO.GetParentFolderName(WScript.ScriptFullName) &_ "\data.txt",1)   bad_readings_total = 0 good_readings_total = 0 data_gap = 0 start_date = "" end_date = "" tmp_datax_gap = 0 tmp_start_date = ""   Do Until objFile.AtEndOfStream bad_readings = 0 good_readings = 0 line_total = 0 line = objFile.ReadLine token = Split(line,vbTab) n = 1 Do While n <= UBound(token) If n + 1 <= UBound(token) Then If CInt(token(n+1)) < 1 Then bad_readings = bad_readings + 1 bad_readings_total = bad_readings_total + 1 'Account for bad readings. If tmp_start_date = "" Then tmp_start_date = token(0) End If tmp_data_gap = tmp_data_gap + 1 Else good_readings = good_readings + 1 line_total = line_total + CInt(token(n)) good_readings_total = good_readings_total + 1 'Sum up the bad readings. If (tmp_start_date <> "") And (tmp_data_gap > data_gap) Then start_date = tmp_start_date end_date = token(0) data_gap = tmp_data_gap tmp_start_date = "" tmp_data_gap = 0 Else tmp_start_date = "" tmp_data_gap = 0 End If End If End If n = n + 2 Loop line_avg = line_total/good_readings WScript.StdOut.Write "Date: " & token(0) & vbTab &_ "Bad Reads: " & bad_readings & vbTab &_ "Good Reads: " & good_readings & vbTab &_ "Line Total: " & FormatNumber(line_total,3) & vbTab &_ "Line Avg: " & FormatNumber(line_avg,3) WScript.StdOut.WriteLine Loop WScript.StdOut.WriteLine WScript.StdOut.Write "Maximum run of " & data_gap &_ " consecutive bad readings from " & start_date & " to " &_ end_date & "." WScript.StdOut.WriteLine objFile.Close Set objFSO = Nothing
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 String length Copy a string Empty string  (assignment) Counting Word frequency Letter frequency Jewels and stones I before E except after C Bioinformatics/base count Count occurrences of a substring Count how many vowels and consonants occur in a string Remove/replace XXXX redacted Conjugate a Latin verb Remove vowels from a string String interpolation (included) Strip block comments Strip comments from a string Strip a set of characters from a string Strip whitespace from a string -- top and tail Strip control codes and extended characters from a string Anagrams/Derangements/shuffling Word wheel ABC problem Sattolo cycle Knuth shuffle Ordered words Superpermutation minimisation Textonyms (using a phone text pad) Anagrams Anagrams/Deranged anagrams Permutations/Derangements Find/Search/Determine ABC words Odd words Word ladder Semordnilap Word search Wordiff  (game) String matching Tea cup rim text Alternade words Changeable words State name puzzle String comparison Unique characters Unique characters in each string Extract file extension Levenshtein distance Palindrome detection Common list elements Longest common suffix Longest common prefix Compare a list of strings Longest common substring Find common directory path Words from neighbour ones Change e letters to i in words Non-continuous subsequences Longest common subsequence Longest palindromic substrings Longest increasing subsequence Words containing "the" substring Sum of the digits of n is substring of n Determine if a string is numeric Determine if a string is collapsible Determine if a string is squeezable Determine if a string has all unique characters Determine if a string has all the same characters Longest substrings without repeating characters Find words which contains all the vowels Find words which contains most consonants Find words which contains more than 3 vowels Find words which first and last three letters are equals Find words which odd letters are consonants and even letters are vowels or vice_versa Formatting Substring Rep-string Word wrap String case Align columns Literals/String Repeat a string Brace expansion Brace expansion using ranges Reverse a string Phrase reversals Comma quibbling Special characters String concatenation Substring/Top and tail Commatizing numbers Reverse words in a string Suffixation of decimal numbers Long literals, with continuations Numerical and alphabetical suffixes Abbreviations, easy Abbreviations, simple Abbreviations, automatic Song lyrics/poems/Mad Libs/phrases Mad Libs Magic 8-ball 99 Bottles of Beer The Name Game (a song) The Old lady swallowed a fly The Twelve Days of Christmas Tokenize Text between Tokenize a string Word break problem Tokenize a string with escaping Split a character string based on change of character Sequences Show ASCII table De Bruijn sequences Self-referential sequences Generate lower case ASCII alphabet
#Prolog
Prolog
day(1, 'first'). day(2, 'second'). day(3, 'third'). day(4, 'fourth'). day(5, 'fifth'). day(6, 'sixth'). day(7, 'seventh'). day(8, 'eighth'). day(9, 'ninth'). day(10, 'tenth'). day(11, 'eleventh'). day(12, 'twelfth').   gift(1, 'A partridge in a pear tree.'). gift(2, 'Two turtle doves and'). gift(3, 'Three French hens,'). gift(4, 'Four calling birds,'). gift(5, 'Five gold rings,'). gift(6, 'Six geese a-laying,'). gift(7, 'Seven swans a-swimming,'). gift(8, 'Eight maids a-milking,'). gift(9, 'Nine ladies dancing,'). gift(10, 'Ten lords a-leaping,'). gift(11, 'Eleven pipers piping,'). gift(12, 'Twelve drummers drumming,').   giftsFor(0, []) :- !. giftsFor(N, [H|T]) :- gift(N, H), M is N-1, giftsFor(M,T).   writeln(S) :- write(S), write('\n').   writeList([]) :- writeln(''), !. writeList([H|T]) :- writeln(H), writeList(T).   writeGifts(N) :- day(N, Nth), write('On the '), write(Nth), writeln(' day of Christmas, my true love sent to me:'), giftsFor(N,L), writeList(L).   writeLoop(0) :- !. writeLoop(N) :- Day is 13 - N, writeGifts(Day), M is N - 1, writeLoop(M).   main :- writeLoop(12), halt.
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 the term threads, others use the term tasks, while others use co-processes. This task should not be implemented using fork, spawn, or the Linux/UNIX/Win32 pipe command, as communication should be between threads, not processes. One of the concurrent units will read from a file named "input.txt" and send the contents of that file, one line at a time, to the other concurrent unit, which will print the line it receives to standard output. The printing unit must count the number of lines it prints. After the concurrent unit reading the file sends its last line to the printing unit, the reading unit will request the number of lines printed by the printing unit. The reading unit will then print the number of lines printed by the printing unit. This task requires two-way communication between the concurrent units. All concurrent units must cleanly terminate at the end of the program.
#PicoLisp
PicoLisp
# Reading task (synchronous) (task (open "input.txt") (let Fd @ (if (in Fd (line T)) # More lines? (udp "localhost" 4444 @) # Yes: Send next line (task (port T 4445) # Else install handler (prinl (udp @) " lines") # to receive and print count (task (close @)) ) (udp "localhost" 4444 T) # Send 'T' for "Done" (task (close Fd)) ) ) ) # Stop the task   # Printing task (asynchronous) (sigio (setq "Sock" (port T 4444)) (job '((Cnt . 0)) (let? X (udp "Sock") (if (=T X) # Done? (prog (udp "localhost" 4445 Cnt) # Yes: Send count (sigio (close "Sock")) ) # and stop the task (println X) # Else print line to stdout (inc 'Cnt) ) ) ) ) # and increment count
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 the term threads, others use the term tasks, while others use co-processes. This task should not be implemented using fork, spawn, or the Linux/UNIX/Win32 pipe command, as communication should be between threads, not processes. One of the concurrent units will read from a file named "input.txt" and send the contents of that file, one line at a time, to the other concurrent unit, which will print the line it receives to standard output. The printing unit must count the number of lines it prints. After the concurrent unit reading the file sends its last line to the printing unit, the reading unit will request the number of lines printed by the printing unit. The reading unit will then print the number of lines printed by the printing unit. This task requires two-way communication between the concurrent units. All concurrent units must cleanly terminate at the end of the program.
#Pony
Pony
use "files"   actor Main let _env: Env // The environment contains stdout, so we save it here   new create(env: Env) => _env = env let printer: Printer tag = Printer(env) try let path = FilePath(env.root as AmbientAuth, "input.txt")? // this may fail, hence the ? let file = File.open(path) for line in FileLines(file) do printer(line) // sugar for "printer.apply(line)" end end printer.done(this)   be finish(count: USize) => _env.out.print("Printed: " + count.string() + " lines")     actor Printer let _env: Env var _count: USize = 0 new create(env: Env) => _env = env   be apply(line: String) => _count = _count + 1 _env.out.print(line)   be done(main: Main tag) => main.finish(_count)
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   Retrieving system time (wiki)
#COBOL
COBOL
WORKING-STORAGE SECTION. 01 WS-CURRENT-DATE-FIELDS. 05 WS-CURRENT-DATE. 10 WS-CURRENT-YEAR PIC 9(4). 10 WS-CURRENT-MONTH PIC 9(2). 10 WS-CURRENT-DAY PIC 9(2). 05 WS-CURRENT-TIME. 10 WS-CURRENT-HOUR PIC 9(2). 10 WS-CURRENT-MINUTE PIC 9(2). 10 WS-CURRENT-SECOND PIC 9(2). 10 WS-CURRENT-MS PIC 9(2). 05 WS-DIFF-FROM-GMT PIC S9(4).   PROCEDURE DIVISION. MOVE FUNCTION CURRENT-DATE TO WS-CURRENT-DATE-FIELDS.
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 generated grow in length geometrically and never converge. Another way to generate a self-referential sequence is to summarize the previous term. Count how many of each alike digit there is, then concatenate the sum and digit for each of the sorted enumerated digits. Note that the first five terms are the same as for the previous sequence. 0, 10, 1110, 3110, 132110, 13123110, 23124110 ... Sort the digits largest to smallest. Do not include counts of digits that do not appear in the previous term. Depending on the seed value, series generated this way always either converge to a stable value or to a short cyclical pattern. (For our purposes, I'll use converge to mean an element matches a previously seen element.) The sequence shown, with a seed value of 0, converges to a stable value of 1433223110 after 11 iterations. The seed value that converges most quickly is 22. It goes stable after the first element. (The next element is 22, which has been seen before.) Task Find all the positive integer seed values under 1000000, for the above convergent self-referential sequence, that takes the largest number of iterations before converging. Then print out the number of iterations and the sequence they return. Note that different permutations of the digits of the seed will yield the same sequence. For this task, assume leading zeros are not permitted. Seed Value(s): 9009 9090 9900 Iterations: 21 Sequence: (same for all three seeds except for first element) 9009 2920 192210 19222110 19323110 1923123110 1923224110 191413323110 191433125110 19151423125110 19251413226110 1916151413325110 1916251423127110 191716151413326110 191726151423128110 19181716151413327110 19182716151423129110 29181716151413328110 19281716151423228110 19281716151413427110 19182716152413228110 Related tasks   Fours is the number of letters in the ...   Look-and-say sequence   Number names   Self-describing numbers   Spelling of ordinal numbers Other tasks related to string operations: Metrics Array length String length Copy a string Empty string  (assignment) Counting Word frequency Letter frequency Jewels and stones I before E except after C Bioinformatics/base count Count occurrences of a substring Count how many vowels and consonants occur in a string Remove/replace XXXX redacted Conjugate a Latin verb Remove vowels from a string String interpolation (included) Strip block comments Strip comments from a string Strip a set of characters from a string Strip whitespace from a string -- top and tail Strip control codes and extended characters from a string Anagrams/Derangements/shuffling Word wheel ABC problem Sattolo cycle Knuth shuffle Ordered words Superpermutation minimisation Textonyms (using a phone text pad) Anagrams Anagrams/Deranged anagrams Permutations/Derangements Find/Search/Determine ABC words Odd words Word ladder Semordnilap Word search Wordiff  (game) String matching Tea cup rim text Alternade words Changeable words State name puzzle String comparison Unique characters Unique characters in each string Extract file extension Levenshtein distance Palindrome detection Common list elements Longest common suffix Longest common prefix Compare a list of strings Longest common substring Find common directory path Words from neighbour ones Change e letters to i in words Non-continuous subsequences Longest common subsequence Longest palindromic substrings Longest increasing subsequence Words containing "the" substring Sum of the digits of n is substring of n Determine if a string is numeric Determine if a string is collapsible Determine if a string is squeezable Determine if a string has all unique characters Determine if a string has all the same characters Longest substrings without repeating characters Find words which contains all the vowels Find words which contains most consonants Find words which contains more than 3 vowels Find words which first and last three letters are equals Find words which odd letters are consonants and even letters are vowels or vice_versa Formatting Substring Rep-string Word wrap String case Align columns Literals/String Repeat a string Brace expansion Brace expansion using ranges Reverse a string Phrase reversals Comma quibbling Special characters String concatenation Substring/Top and tail Commatizing numbers Reverse words in a string Suffixation of decimal numbers Long literals, with continuations Numerical and alphabetical suffixes Abbreviations, easy Abbreviations, simple Abbreviations, automatic Song lyrics/poems/Mad Libs/phrases Mad Libs Magic 8-ball 99 Bottles of Beer The Name Game (a song) The Old lady swallowed a fly The Twelve Days of Christmas Tokenize Text between Tokenize a string Word break problem Tokenize a string with escaping Split a character string based on change of character Sequences Show ASCII table De Bruijn sequences Self-referential sequences Generate lower case ASCII alphabet Also see   The On-Line Encyclopedia of Integer Sequences.
#F.23
F#
  // Summarize and say sequence . Nigel Galloway: April 23rd., 2021 let rec fN g=let n=let n,g=List.head g|>List.countBy id|>List.unzip in n@(g|>List.collect(fun g->if g<10 then [g] else [g/10;g%10])) if List.contains n g then g.Tail|>List.rev else fN(n::g) let rec fG n g=seq{yield! n; if g>1 then yield! fG(n|>Seq.collect(fun n->[for g in 0..List.head n->g::n]))(g-1)} let n,g=seq{yield [0]; yield! fG(Seq.init 9 (fun n->[n+1])) 6} |>Seq.fold(fun(n,l) g->let g=fN [g] in match g.Length with e when e<n->(n,l) |e when e>n->(e,[[g]]) |e->(n,[g]::l))(0,[]) printfn "maximum number of iterations is %d" (n+1) for n in g do for n in n do printf "Permutations of "; n.Head|>List.rev|>List.iter(printf "%d"); printfn " produce:" for n in n do (for n,g in List.countBy id n|>List.sort|>List.rev do printf "%d%d" g n); printfn ""  
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 polygon that do not need to be displayed. Task Take the closed polygon defined by the points: [ ( 50 , 150 ) , ( 200 , 50 ) , ( 350 , 150 ) , ( 350 , 300 ) , ( 250 , 300 ) , ( 200 , 250 ) , ( 150 , 350 ) , ( 100 , 250 ) , ( 100 , 200 ) ] {\displaystyle [(50,150),(200,50),(350,150),(350,300),(250,300),(200,250),(150,350),(100,250),(100,200)]} and clip it by the rectangle defined by the points: [ ( 100 , 100 ) , ( 300 , 100 ) , ( 300 , 300 ) , ( 100 , 300 ) ] {\displaystyle [(100,100),(300,100),(300,300),(100,300)]} Print the sequence of points that define the resulting clipped polygon. Extra credit Display all three polygons on a graphical surface, using a different color for each polygon and filling the resulting polygon. (When displaying you may use either a north-west or a south-west origin, whichever is more convenient for your display mechanism.)
#Phix
Phix
-- -- demo\rosetta\Sutherland_Hodgman_polygon_clipping.exw -- ==================================================== -- with javascript_semantics enum X,Y function inside(sequence cp1, cp2, p) return (cp2[X]-cp1[X])*(p[Y]-cp1[Y])>(cp2[Y]-cp1[Y])*(p[X]-cp1[X]) end function function intersect(sequence cp1, cp2, s, e) atom {dcx,dcy} = {cp1[X]-cp2[X],cp1[Y]-cp2[Y]}, {dpx,dpy} = {s[X]-e[X],s[Y]-e[Y]}, n1 = cp1[X]*cp2[Y]-cp1[Y]*cp2[X], n2 = s[X]*e[Y]-s[Y]*e[X], n3 = 1/(dcx*dpy-dcy*dpx) return {(n1*dpx-n2*dcx)*n3,(n1*dpy-n2*dcy)*n3} end function function sutherland_hodgman(sequence subjectPolygon, clipPolygon) sequence cp1 = clipPolygon[$], outputList = subjectPolygon for i=1 to length(clipPolygon) do sequence cp2 = clipPolygon[i], inputList = outputList, s = inputList[$] outputList = {} for j=1 to length(inputList) do sequence e = inputList[j] if inside(cp1,cp2,e) then if not inside(cp1,cp2,s) then outputList = append(outputList,intersect(cp1,cp2,s,e)) end if outputList = append(outputList,e) elsif inside(cp1,cp2,s) then outputList = append(outputList,intersect(cp1,cp2,s,e)) end if s = e end for cp1 = cp2 end for return outputList end function constant subjectPolygon = {{50, 150}, {200, 50}, {350, 150}, {350, 300}, {250, 300}, {200, 250}, {150, 350}, {100, 250}, {100, 200}}, clipPolygon = {{100, 100}, {300, 100}, {300, 300}, {100, 300}} sequence clippedPolygon = sutherland_hodgman(subjectPolygon,clipPolygon) include pGUI.e Ihandle dlg, canvas cdCanvas cddbuffer, cdcanvas procedure draw_poly(sequence poly) cdCanvasBegin(cddbuffer,CD_FILL) for i=1 to length(poly) do atom {x,y} = poly[i] cdCanvasVertex(cddbuffer,x,y) end for cdCanvasEnd(cddbuffer) end procedure function redraw_cb(Ihandle /*ih*/) cdCanvasActivate(cddbuffer) cdCanvasClear(cddbuffer) cdCanvasSetForeground(cddbuffer, CD_CYAN) draw_poly(subjectPolygon) cdCanvasSetForeground(cddbuffer, CD_MAGENTA) draw_poly(clipPolygon) cdCanvasSetForeground(cddbuffer, CD_ORANGE) draw_poly(clippedPolygon) cdCanvasFlush(cddbuffer) return IUP_DEFAULT end function function map_cb(Ihandle ih) cdcanvas = cdCreateCanvas(CD_IUP, ih) cddbuffer = cdCreateCanvas(CD_DBUFFER, cdcanvas) cdCanvasSetBackground(cddbuffer, CD_WHITE) cdCanvasSetForeground(cddbuffer, CD_GRAY) return IUP_DEFAULT end function procedure main() IupOpen() canvas = IupCanvas("RASTERSIZE=400x400") IupSetCallbacks(canvas, {"MAP_CB", Icallback("map_cb"), "ACTION", Icallback("redraw_cb")}) dlg = IupDialog(canvas, "RESIZE=NO") IupSetAttribute(dlg, "TITLE", "Sutherland-Hodgman polygon clipping") IupShow(dlg) if platform()!=JS then IupMainLoop() IupClose() end if end procedure main()
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\cap B)} (the set of items that are in at least one of A or B minus the set of items that are in both A and B). Optionally, give the individual differences ( A ∖ B {\displaystyle A\setminus B} and B ∖ A {\displaystyle B\setminus A} ) as well. Test cases A = {John, Bob, Mary, Serena} B = {Jim, Mary, John, Bob} Notes If your code uses lists of items to represent sets then ensure duplicate items in lists are correctly handled. For example two lists representing sets of a = ["John", "Serena", "Bob", "Mary", "Serena"] and b = ["Jim", "Mary", "John", "Jim", "Bob"] should produce the result of just two strings: ["Serena", "Jim"], in any order. In the mathematical notation above A \ B gives the set of items in A that are not in B; A ∪ B gives the set of items in both A and B, (their union); and A ∩ B gives the set of items that are in both A and B (their intersection).
#Fortran
Fortran
program Symmetric_difference implicit none   character(6) :: a(4) = (/ "John ", "Bob ", "Mary ", "Serena" /) character(6) :: b(4) = (/ "Jim ", "Mary ", "John ", "Bob " /) integer :: i, j   outer1: do i = 1, size(a) do j = 1, i-1 if(a(i) == a(j)) cycle outer1 ! Do not check duplicate items end do if(.not. any(b == a(i))) write(*,*) a(i) end do outer1   outer2: do i = 1, size(b) do j = 1, i-1 if(b(i) == b(j)) cycle outer2 ! Do not check duplicate items end do if(.not. any(a == b(i))) write(*,*) b(i) end do outer2   end program
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 all the arguments, joined with spaces, prepended with a tab, and appended with a trailing newline, are written to NOTES.TXT. If NOTES.TXT doesn't already exist in the current directory then a new NOTES.TXT file should be created.
#Perl
Perl
my $file = 'notes.txt'; if ( @ARGV ) { open NOTES, '>>', $file or die "Can't append to file $file: $!"; print NOTES scalar localtime, "\n\t@ARGV\n"; } else { open NOTES, '<', $file or die "Can't read file $file: $!"; print <NOTES>; } close NOTES;
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 all the arguments, joined with spaces, prepended with a tab, and appended with a trailing newline, are written to NOTES.TXT. If NOTES.TXT doesn't already exist in the current directory then a new NOTES.TXT file should be created.
#Phix
Phix
without js -- (file i/o) constant cmd = command_line(), filename = "notes.txt" if length(cmd)<3 then object text = get_text(filename) printf(1,"%s\n",iff(string(text)?text:"<empty>")) else integer fn = open(filename,"a") printf(fn,"%d-%02d-%02d %d:%02d:%02d\n",date()) printf(fn,"\t%s\n",join(cmd[3..$])) close(fn) end if
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 = b = 200
#QB64
QB64
_Title "Super Ellipse"   Dim As Integer sw, sh Dim As Single i sw = 480: sh = 480   Screen _NewImage(sw, sh, 8) Cls , 15   'Show different possible Super Ellipse shapes Color 10 For i = 0.2 To 5.0 Step .1 Call SuperEllipse(sw \ 2, sh \ 2, 200, 200, i, 80) Next   'Show task specified Super Ellipse Color 0 Call SuperEllipse(sw \ 2, sh \ 2, 200, 200, 2.5, 200) Sleep System   Sub SuperEllipse (cX As Integer, cY As Integer, wide As Integer, high As Integer, pow As Double, segs As Integer) Dim As Double power, inc, theta, cosTheta, sinTheta Dim As Integer x1, y1 'Limit 'pow' to acceptable values If pow < .1 Then pow = .1 If pow > 150 Then pow = 150 power = 2 / pow - 1 inc = 360.0 / segs * 0.0174532925199432957692369 PSet (wide + cX, cY) For theta = inc To 6.28318530717958647692528 + inc Step inc cosTheta = Cos(theta): sinTheta = Sin(theta) x1 = wide * cosTheta * Abs(cosTheta) ^ power + cX y1 = high * sinTheta * Abs(sinTheta) ^ power + cY Line -(x1, y1) Next End Sub
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 = b = 200
#QBasic
QBasic
SCREEN 12 CLS a = 200 b = 200 n = 2.5 na = 2 / n t = .01   LINE -(520, 245), 0, BF FOR i = 0 TO 314 xp = a * SGN(COS(t)) * ABS((COS(t))) ^ na + 320 yp = b * SGN(SIN(t)) * ABS((SIN(t))) ^ na + 240 t = t + .02 LINE -(xp, yp), 1, BF NEXT i
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   taxi-cab numbers   taxi cab numbers   Hardy-Ramanujan numbers Task Compute and display the lowest 25 taxicab numbers (in numeric order, and in a human-readable format). For each of the taxicab numbers, show the number as well as it's constituent cubes. Extra credit Show the 2,000th taxicab number, and a half dozen more See also A001235: taxicab numbers on The On-Line Encyclopedia of Integer Sequences. Hardy-Ramanujan Number on MathWorld. taxicab number on MathWorld. taxicab number on Wikipedia   (includes the story on how taxi-cab numbers came to be called).
#Scheme
Scheme
  (import (scheme base) (scheme write) (srfi 1) ; lists (srfi 69) ; hash tables (srfi 132)) ; sorting   (define *max-n* 1500) ; let's go up to here, maximum for x and y (define *numbers* (make-hash-table eqv?)) ; hash table for total -> list of list of pairs   (define (retrieve key) (hash-table-ref/default *numbers* key '()))   ;; add all combinations to the hash table (do ((i 1 (+ i 1))) ((= i *max-n*) ) (do ((j (+ 1 i) (+ j 1))) ((= j *max-n*) ) (let ((n (+ (* i i i) (* j j j)))) (hash-table-set! *numbers* n (cons (list i j) (retrieve n))))))   (define (display-number i key) (display (+ 1 i)) (display ": ") (display key) (display " -> ") (display (retrieve key)) (newline))   (let ((sorted-keys (list-sort < (filter (lambda (key) (> (length (retrieve key)) 1)) (hash-table-keys *numbers*))))) ;; first 25 (for-each (lambda (i) (display-number i (list-ref sorted-keys i))) (iota 25)) ;; 2000-2006 (for-each (lambda (i) (display-number i (list-ref sorted-keys i))) (iota 7 1999)) )  
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 zero. The Fahrenheit and Rankine scales also have the same magnitude, but different null points. 0 degrees Fahrenheit corresponds to 459.67 degrees Rankine. 0 degrees Rankine is absolute zero. The Celsius/Kelvin and Fahrenheit/Rankine scales have a ratio of 5 : 9. Task Write code that accepts a value of kelvin, converts it to values of the three other scales, and prints the result. Example K 21.00 C -252.15 F -421.87 R 37.80
#Excel
Excel
A1 : Kelvin B1 : Celsius C1 : Fahrenheit D1 : Rankine Name A2 : K B2 : =K-273.15 C2 : =K*1.8-459.67 D2 : =K*1.8 Input in A1
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 zero. The Fahrenheit and Rankine scales also have the same magnitude, but different null points. 0 degrees Fahrenheit corresponds to 459.67 degrees Rankine. 0 degrees Rankine is absolute zero. The Celsius/Kelvin and Fahrenheit/Rankine scales have a ratio of 5 : 9. Task Write code that accepts a value of kelvin, converts it to values of the three other scales, and prints the result. Example K 21.00 C -252.15 F -421.87 R 37.80
#Ezhil
Ezhil
  # convert from Kelvin நிரல்பாகம் கெல்வின்_இருந்து_மாற்று( k ) பதிப்பி "Kelvin: ",k,"Celsius: ",round(k-273.15)," Fahrenheit: ",(round(k*1.8 - 459.67))," Rankine: ",(round(k*1.8)) முடி   கெல்வின்_இருந்து_மாற்று( 0 ) #absolute zero கெல்வின்_இருந்து_மாற்று( 273 ) #freezing pt of water கெல்வின்_இருந்து_மாற்று( 30 + 273 ) #room temperature in Summer  
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 logic, sometimes abbreviated 3VL) is any of several many-valued logic systems in which there are three truth values indicating true, false and some indeterminate third value. This is contrasted with the more commonly known bivalent logics (such as classical sentential or boolean logic) which provide only for true and false. Conceptual form and basic ideas were initially created by Łukasiewicz, Lewis and Sulski. These were then re-formulated by Grigore Moisil in an axiomatic algebraic form, and also extended to n-valued logics in 1945. Example Ternary Logic Operators in Truth Tables: not a ¬ True False Maybe Maybe False True a and b ∧ True Maybe False True True Maybe False Maybe Maybe Maybe False False False False False a or b ∨ True Maybe False True True True True Maybe True Maybe Maybe False True Maybe False if a then b ⊃ True Maybe False True True Maybe False Maybe True Maybe Maybe False True True True a is equivalent to b ≡ True Maybe False True True Maybe False Maybe Maybe Maybe Maybe False False Maybe True Task Define a new type that emulates ternary logic by storing data trits. Given all the binary logic operators of the original programming language, reimplement these operators for the new Ternary logic type trit. Generate a sampling of results using trit variables. Kudos for actually thinking up a test case algorithm where ternary logic is intrinsically useful, optimises the test case algorithm and is preferable to binary logic. Note:   Setun   (Сетунь) was a   balanced ternary   computer developed in 1958 at   Moscow State University.   The device was built under the lead of   Sergei Sobolev   and   Nikolay Brusentsov.   It was the only modern   ternary computer,   using three-valued ternary logic
#Ruby
Ruby
# trit.rb - ternary logic # http://rosettacode.org/wiki/Ternary_logic   require 'singleton'   # MAYBE, the only instance of MaybeClass, enables a system of ternary # logic using TrueClass#trit, MaybeClass#trit and FalseClass#trit. # #  !a.trit # ternary not # a.trit & b # ternary and # a.trit | b # ternary or # a.trit ^ b # ternary exclusive or # a.trit == b # ternary equal # # Though +true+ and +false+ are internal Ruby values, +MAYBE+ is not. # Programs may want to assign +maybe = MAYBE+ in scopes that use # ternary logic. Then programs can use +true+, +maybe+ and +false+. class MaybeClass include Singleton   # maybe.to_s # => "maybe" def to_s; "maybe"; end end   MAYBE = MaybeClass.instance   class TrueClass TritMagic = Object.new class << TritMagic def index; 0; end def !; false; end def & other; other; end def | other; true; end def ^ other; [false, MAYBE, true][other.trit.index]; end def == other; other; end end   # Performs ternary logic. See MaybeClass. #  !true.trit # => false # true.trit & obj # => obj # true.trit | obj # => true # true.trit ^ obj # => false, maybe or true # true.trit == obj # => obj def trit; TritMagic; end end   class MaybeClass TritMagic = Object.new class << TritMagic def index; 1; end def !; MAYBE; end def & other; [MAYBE, MAYBE, false][other.trit.index]; end def | other; [true, MAYBE, MAYBE][other.trit.index]; end def ^ other; MAYBE; end def == other; MAYBE; end end   # Performs ternary logic. See MaybeClass. #  !maybe.trit # => maybe # maybe.trit & obj # => maybe or false # maybe.trit | obj # => true or maybe # maybe.trit ^ obj # => maybe # maybe.trit == obj # => maybe def trit; TritMagic; end end   class FalseClass TritMagic = Object.new class << TritMagic def index; 2; end def !; true; end def & other; false; end def | other; other; end def ^ other; other; end def == other; [false, MAYBE, true][other.trit.index]; end end   # Performs ternary logic. See MaybeClass. #  !false.trit # => true # false.trit & obj # => false # false.trit | obj # => obj # false.trit ^ obj # => obj # false.trit == obj # => false, maybe or true def trit; TritMagic; end end
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 program can be written to parse and transform the original data into a format useful to the other. The term "Data Munging" is often used in programming circles for this task. A request on the comp.lang.awk newsgroup led to a typical data munging task: I have to analyse data files that have the following format: Each row corresponds to 1 day and the field logic is: $1 is the date, followed by 24 value/flag pairs, representing measurements at 01:00, 02:00 ... 24:00 of the respective day. In short: <date> <val1> <flag1> <val2> <flag2> ... <val24> <flag24> Some test data is available at: ... (nolonger available at original location) I have to sum up the values (per day and only valid data, i.e. with flag>0) in order to calculate the mean. That's not too difficult. However, I also need to know what the "maximum data gap" is, i.e. the longest period with successive invalid measurements (i.e values with flag<=0) The data is free to download and use and is of this format: Data is no longer available at that link. Zipped mirror available here (offsite mirror). 1991-03-30 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 1991-03-31 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 20.000 1 20.000 1 20.000 1 35.000 1 50.000 1 60.000 1 40.000 1 30.000 1 30.000 1 30.000 1 25.000 1 20.000 1 20.000 1 20.000 1 20.000 1 20.000 1 35.000 1 1991-03-31 40.000 1 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 1991-04-01 0.000 -2 13.000 1 16.000 1 21.000 1 24.000 1 22.000 1 20.000 1 18.000 1 29.000 1 44.000 1 50.000 1 43.000 1 38.000 1 27.000 1 27.000 1 24.000 1 23.000 1 18.000 1 12.000 1 13.000 1 14.000 1 15.000 1 13.000 1 10.000 1 1991-04-02 8.000 1 9.000 1 11.000 1 12.000 1 12.000 1 12.000 1 27.000 1 26.000 1 27.000 1 33.000 1 32.000 1 31.000 1 29.000 1 31.000 1 25.000 1 25.000 1 24.000 1 21.000 1 17.000 1 14.000 1 15.000 1 12.000 1 12.000 1 10.000 1 1991-04-03 10.000 1 9.000 1 10.000 1 10.000 1 9.000 1 10.000 1 15.000 1 24.000 1 28.000 1 24.000 1 18.000 1 14.000 1 12.000 1 13.000 1 14.000 1 15.000 1 14.000 1 15.000 1 13.000 1 13.000 1 13.000 1 12.000 1 10.000 1 10.000 1 Only a sample of the data showing its format is given above. The full example file may be downloaded here. Structure your program to show statistics for each line of the file, (similar to the original Python, Perl, and AWK examples below), followed by summary statistics for the file. When showing example output just show a few line statistics and the full end summary.
#Vedit_macro_language
Vedit macro language
#50 = Buf_Num // Current edit buffer (source data) File_Open("output.txt") #51 = Buf_Num // Edit buffer for output file Buf_Switch(#50) #10 = 0 // total sum of file data #11 = 0 // number of valid data items in file #12 = 0 // Current run of consecutive flags<0 in lines of file #13 = -1 // Max consecutive flags<0 in lines of file Reg_Empty(15) // ... and date tag(s) at line(s) where it occurs   While(!At_EOF) { #20 = 0 // sum of line data #21 = 0 // number of line data items with flag>0 #22 = 0 // number of line data items with flag<0 Reg_Copy_Block(14, Cur_Pos, Cur_Pos+10) // date field   // extract field info, skipping initial date field Repeat(ALL) { Search("|{|T,|N}", ADVANCE+ERRBREAK) // next Tab or Newline if (Match_Item==2) { Break } // end of line #30 = Num_Eval(ADVANCE) * 1000 // #30 = value Char // fixed point, 3 decimal digits #30 += Num_Eval(ADVANCE+SUPPRESS) #31 = Num_Eval(ADVANCE) // #31 = flag if (#31 < 1) { // not valid field? #12++ #22++ } else { // valid field // check run of data-absent fields if(#13 == #12 && #12 > 0) { Reg_Set(15, ", ", APPEND) Reg_Set(15, @14, APPEND) } if(#13 < #12 && #12 > 0) { #13 = #12 Reg_Set(15, @14) }   // re-initialise run of nodata counter #12 = 0 // gather values for averaging #20 += #30 #21++ } }   // totals for the file so far #10 += #20 #11 += #21   Buf_Switch(#51) // buffer for output data IT("Line: ") Reg_Ins(14) IT(" Reject:") Num_Ins(#22, COUNT, 3) IT(" Accept:") Num_Ins(#21, COUNT, 3) IT(" Line tot:") Num_Ins(#20, COUNT, 8) Char(-3) IC('.') EOL IT(" Line avg:") Num_Ins((#20+#21/2)/#21, COUNT, 7) Char(-3) IC('.') EOL IN Buf_Switch(#50) // buffer for input data }   Buf_Switch(#51) // buffer for output data IN IT("Total: ") Num_Ins(#10, FORCE+NOCR) Char(-3) IC('.') EOL IN IT("Readings: ") Num_Ins(#11, FORCE) IT("Average: ") Num_Ins((#10+#11/2)/#11, FORCE+NOCR) Char(-3) IC('.') EOL IN IN IT("Maximum run(s) of ") Num_Ins(#13, LEFT+NOCR) IT(" consecutive false readings ends at line starting with date(s): ") Reg_Ins(15) IN
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 String length Copy a string Empty string  (assignment) Counting Word frequency Letter frequency Jewels and stones I before E except after C Bioinformatics/base count Count occurrences of a substring Count how many vowels and consonants occur in a string Remove/replace XXXX redacted Conjugate a Latin verb Remove vowels from a string String interpolation (included) Strip block comments Strip comments from a string Strip a set of characters from a string Strip whitespace from a string -- top and tail Strip control codes and extended characters from a string Anagrams/Derangements/shuffling Word wheel ABC problem Sattolo cycle Knuth shuffle Ordered words Superpermutation minimisation Textonyms (using a phone text pad) Anagrams Anagrams/Deranged anagrams Permutations/Derangements Find/Search/Determine ABC words Odd words Word ladder Semordnilap Word search Wordiff  (game) String matching Tea cup rim text Alternade words Changeable words State name puzzle String comparison Unique characters Unique characters in each string Extract file extension Levenshtein distance Palindrome detection Common list elements Longest common suffix Longest common prefix Compare a list of strings Longest common substring Find common directory path Words from neighbour ones Change e letters to i in words Non-continuous subsequences Longest common subsequence Longest palindromic substrings Longest increasing subsequence Words containing "the" substring Sum of the digits of n is substring of n Determine if a string is numeric Determine if a string is collapsible Determine if a string is squeezable Determine if a string has all unique characters Determine if a string has all the same characters Longest substrings without repeating characters Find words which contains all the vowels Find words which contains most consonants Find words which contains more than 3 vowels Find words which first and last three letters are equals Find words which odd letters are consonants and even letters are vowels or vice_versa Formatting Substring Rep-string Word wrap String case Align columns Literals/String Repeat a string Brace expansion Brace expansion using ranges Reverse a string Phrase reversals Comma quibbling Special characters String concatenation Substring/Top and tail Commatizing numbers Reverse words in a string Suffixation of decimal numbers Long literals, with continuations Numerical and alphabetical suffixes Abbreviations, easy Abbreviations, simple Abbreviations, automatic Song lyrics/poems/Mad Libs/phrases Mad Libs Magic 8-ball 99 Bottles of Beer The Name Game (a song) The Old lady swallowed a fly The Twelve Days of Christmas Tokenize Text between Tokenize a string Word break problem Tokenize a string with escaping Split a character string based on change of character Sequences Show ASCII table De Bruijn sequences Self-referential sequences Generate lower case ASCII alphabet
#PureBasic
PureBasic
#TXT$ = "On the * day of Christmas, my true love sent to me:" days$ = ~"first\nsecond\nthird\nfourth\nfifth\nsixth\nseventh\neighth\nninth\ntenth\neleventh\ntwelfth\n" gifts$= ~"Twelve drummers drumming,\nEleven pipers piping,\nTen lords a-leaping,\nNine ladies dancing,\n"+ ~"Eight maids a-milking,\nSeven swans a-swimming,\nSix geese a-laying,\nFive golden rings,\n"+ ~"Four calling birds,\nThree french hens,\nTwo turtle doves,\nA partridge in a pear tree.\n" Define I.i, J.i   If OpenConsole("The twelve days of Christmas") For I = 1 To 12 PrintN(ReplaceString(#TXT$,"*",StringField(days$,I,~"\n"))) For J = 13-I To 12 PrintN(" -> "+StringField(gifts$,J,~"\n")) Next J Next I Input() EndIf
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 String length Copy a string Empty string  (assignment) Counting Word frequency Letter frequency Jewels and stones I before E except after C Bioinformatics/base count Count occurrences of a substring Count how many vowels and consonants occur in a string Remove/replace XXXX redacted Conjugate a Latin verb Remove vowels from a string String interpolation (included) Strip block comments Strip comments from a string Strip a set of characters from a string Strip whitespace from a string -- top and tail Strip control codes and extended characters from a string Anagrams/Derangements/shuffling Word wheel ABC problem Sattolo cycle Knuth shuffle Ordered words Superpermutation minimisation Textonyms (using a phone text pad) Anagrams Anagrams/Deranged anagrams Permutations/Derangements Find/Search/Determine ABC words Odd words Word ladder Semordnilap Word search Wordiff  (game) String matching Tea cup rim text Alternade words Changeable words State name puzzle String comparison Unique characters Unique characters in each string Extract file extension Levenshtein distance Palindrome detection Common list elements Longest common suffix Longest common prefix Compare a list of strings Longest common substring Find common directory path Words from neighbour ones Change e letters to i in words Non-continuous subsequences Longest common subsequence Longest palindromic substrings Longest increasing subsequence Words containing "the" substring Sum of the digits of n is substring of n Determine if a string is numeric Determine if a string is collapsible Determine if a string is squeezable Determine if a string has all unique characters Determine if a string has all the same characters Longest substrings without repeating characters Find words which contains all the vowels Find words which contains most consonants Find words which contains more than 3 vowels Find words which first and last three letters are equals Find words which odd letters are consonants and even letters are vowels or vice_versa Formatting Substring Rep-string Word wrap String case Align columns Literals/String Repeat a string Brace expansion Brace expansion using ranges Reverse a string Phrase reversals Comma quibbling Special characters String concatenation Substring/Top and tail Commatizing numbers Reverse words in a string Suffixation of decimal numbers Long literals, with continuations Numerical and alphabetical suffixes Abbreviations, easy Abbreviations, simple Abbreviations, automatic Song lyrics/poems/Mad Libs/phrases Mad Libs Magic 8-ball 99 Bottles of Beer The Name Game (a song) The Old lady swallowed a fly The Twelve Days of Christmas Tokenize Text between Tokenize a string Word break problem Tokenize a string with escaping Split a character string based on change of character Sequences Show ASCII table De Bruijn sequences Self-referential sequences Generate lower case ASCII alphabet
#Python
Python
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'''.split('\n')   days = '''first second third fourth fifth sixth seventh eighth ninth tenth eleventh twelfth'''.split()   for n, day in enumerate(days, 1): g = gifts[:n][::-1] print(('\nOn the %s day of Christmas\nMy true love gave to me:\n' % day) + '\n'.join(g[:-1]) + (' and\n' + g[-1] if n > 1 else g[-1].capitalize()))
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 the term threads, others use the term tasks, while others use co-processes. This task should not be implemented using fork, spawn, or the Linux/UNIX/Win32 pipe command, as communication should be between threads, not processes. One of the concurrent units will read from a file named "input.txt" and send the contents of that file, one line at a time, to the other concurrent unit, which will print the line it receives to standard output. The printing unit must count the number of lines it prints. After the concurrent unit reading the file sends its last line to the printing unit, the reading unit will request the number of lines printed by the printing unit. The reading unit will then print the number of lines printed by the printing unit. This task requires two-way communication between the concurrent units. All concurrent units must cleanly terminate at the end of the program.
#PureBasic
PureBasic
Enumeration #Write #Done EndEnumeration   Structure commblock txtline.s Order.i EndStructure   Global MessageSent=CreateSemaphore() Global LineWritten=CreateSemaphore() Global LinesWritten, com.commblock   Procedure Writer(arg) Repeat WaitSemaphore(MessageSent) If com\Order=#Write PrintN(com\txtline) LinesWritten+1 EndIf SignalSemaphore(LineWritten) Until com\Order=#Done EndProcedure   Procedure Reader(arg) Protected File=ReadFile(#PB_Any,OpenFileRequester("","input.txt","",0)) While file And Not Eof(file) com\txtline=ReadString(File) com\Order=#Write SignalSemaphore(MessageSent) WaitSemaphore(LineWritten) Wend com\Order=#Done SignalSemaphore(MessageSent) WaitSemaphore(LineWritten) PrintN(Str(LinesWritten)+" lines written.") EndProcedure   If OpenConsole() Define Thread1=CreateThread(@Reader(),0) Define Thread2=CreateThread(@Writer(),0) WaitThread(Thread1) And WaitThread(Thread2) Print("Press Enter to exit"):Input() EndIf
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   Retrieving system time (wiki)
#ColdFusion
ColdFusion
<cfscript> // Date Time currentTime = Now(); writeOutput( currentTime );   // Epoch // Credit for Epoch time should go to Ben Nadel // bennadel.com is his blog utcDate = dateConvert( "local2utc", currentTime ); writeOutput( utcDate.getTime() ); </cfscript>
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   Retrieving system time (wiki)
#Common_Lisp
Common Lisp
(multiple-value-bind (second minute hour day month year) (get-decoded-time) (format t "~4,'0D-~2,'0D-~2,'0D ~2,'0D:~2,'0D:~2,'0D" year month day hour minute second))
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 generated grow in length geometrically and never converge. Another way to generate a self-referential sequence is to summarize the previous term. Count how many of each alike digit there is, then concatenate the sum and digit for each of the sorted enumerated digits. Note that the first five terms are the same as for the previous sequence. 0, 10, 1110, 3110, 132110, 13123110, 23124110 ... Sort the digits largest to smallest. Do not include counts of digits that do not appear in the previous term. Depending on the seed value, series generated this way always either converge to a stable value or to a short cyclical pattern. (For our purposes, I'll use converge to mean an element matches a previously seen element.) The sequence shown, with a seed value of 0, converges to a stable value of 1433223110 after 11 iterations. The seed value that converges most quickly is 22. It goes stable after the first element. (The next element is 22, which has been seen before.) Task Find all the positive integer seed values under 1000000, for the above convergent self-referential sequence, that takes the largest number of iterations before converging. Then print out the number of iterations and the sequence they return. Note that different permutations of the digits of the seed will yield the same sequence. For this task, assume leading zeros are not permitted. Seed Value(s): 9009 9090 9900 Iterations: 21 Sequence: (same for all three seeds except for first element) 9009 2920 192210 19222110 19323110 1923123110 1923224110 191413323110 191433125110 19151423125110 19251413226110 1916151413325110 1916251423127110 191716151413326110 191726151423128110 19181716151413327110 19182716151423129110 29181716151413328110 19281716151423228110 19281716151413427110 19182716152413228110 Related tasks   Fours is the number of letters in the ...   Look-and-say sequence   Number names   Self-describing numbers   Spelling of ordinal numbers Other tasks related to string operations: Metrics Array length String length Copy a string Empty string  (assignment) Counting Word frequency Letter frequency Jewels and stones I before E except after C Bioinformatics/base count Count occurrences of a substring Count how many vowels and consonants occur in a string Remove/replace XXXX redacted Conjugate a Latin verb Remove vowels from a string String interpolation (included) Strip block comments Strip comments from a string Strip a set of characters from a string Strip whitespace from a string -- top and tail Strip control codes and extended characters from a string Anagrams/Derangements/shuffling Word wheel ABC problem Sattolo cycle Knuth shuffle Ordered words Superpermutation minimisation Textonyms (using a phone text pad) Anagrams Anagrams/Deranged anagrams Permutations/Derangements Find/Search/Determine ABC words Odd words Word ladder Semordnilap Word search Wordiff  (game) String matching Tea cup rim text Alternade words Changeable words State name puzzle String comparison Unique characters Unique characters in each string Extract file extension Levenshtein distance Palindrome detection Common list elements Longest common suffix Longest common prefix Compare a list of strings Longest common substring Find common directory path Words from neighbour ones Change e letters to i in words Non-continuous subsequences Longest common subsequence Longest palindromic substrings Longest increasing subsequence Words containing "the" substring Sum of the digits of n is substring of n Determine if a string is numeric Determine if a string is collapsible Determine if a string is squeezable Determine if a string has all unique characters Determine if a string has all the same characters Longest substrings without repeating characters Find words which contains all the vowels Find words which contains most consonants Find words which contains more than 3 vowels Find words which first and last three letters are equals Find words which odd letters are consonants and even letters are vowels or vice_versa Formatting Substring Rep-string Word wrap String case Align columns Literals/String Repeat a string Brace expansion Brace expansion using ranges Reverse a string Phrase reversals Comma quibbling Special characters String concatenation Substring/Top and tail Commatizing numbers Reverse words in a string Suffixation of decimal numbers Long literals, with continuations Numerical and alphabetical suffixes Abbreviations, easy Abbreviations, simple Abbreviations, automatic Song lyrics/poems/Mad Libs/phrases Mad Libs Magic 8-ball 99 Bottles of Beer The Name Game (a song) The Old lady swallowed a fly The Twelve Days of Christmas Tokenize Text between Tokenize a string Word break problem Tokenize a string with escaping Split a character string based on change of character Sequences Show ASCII table De Bruijn sequences Self-referential sequences Generate lower case ASCII alphabet Also see   The On-Line Encyclopedia of Integer Sequences.
#Factor
Factor
USING: assocs grouping io kernel math math.combinatorics math.functions math.ranges math.statistics math.text.utils prettyprint sequences sets ; IN: rosetta-code.self-referential-sequence   : next-term ( seq -- seq ) histogram >alist concat ;   ! Output the self-referential sequence, given a seed value. : srs ( seq -- seq n ) V{ } clone [ 2dup member? ] [ 2dup push [ next-term ] dip ] until nip dup length ;   : digit-before? ( m n -- ? ) dup zero? [ 2drop t ] [ <= ] if ;   ! The numbers from 1 rto n sans permutations. : candidates ( n -- seq ) [1,b] [ 1 digit-groups reverse ] map [ [ digit-before? ] monotonic? ] filter ;   : max-seed ( n -- seq ) candidates [ srs nip ] supremum-by ;   : max-seeds ( n -- seq ) max-seed <permutations> members [ first zero? ] reject ;   : digits>number ( seq -- n ) [ 10^ * ] map-index sum ;   : >numbers ( seq -- seq ) [ digits>number ] map ;   : main ( -- ) "Seed value(s): " write 1,000,000 max-seeds [ [ reverse ] map >numbers . ] [ first srs ] bi "Iterations: " write . "Sequence:" print >numbers . ;   MAIN: main
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 polygon that do not need to be displayed. Task Take the closed polygon defined by the points: [ ( 50 , 150 ) , ( 200 , 50 ) , ( 350 , 150 ) , ( 350 , 300 ) , ( 250 , 300 ) , ( 200 , 250 ) , ( 150 , 350 ) , ( 100 , 250 ) , ( 100 , 200 ) ] {\displaystyle [(50,150),(200,50),(350,150),(350,300),(250,300),(200,250),(150,350),(100,250),(100,200)]} and clip it by the rectangle defined by the points: [ ( 100 , 100 ) , ( 300 , 100 ) , ( 300 , 300 ) , ( 100 , 300 ) ] {\displaystyle [(100,100),(300,100),(300,300),(100,300)]} Print the sequence of points that define the resulting clipped polygon. Extra credit Display all three polygons on a graphical surface, using a different color for each polygon and filling the resulting polygon. (When displaying you may use either a north-west or a south-west origin, whichever is more convenient for your display mechanism.)
#PHP
PHP
  <?php function clip ($subjectPolygon, $clipPolygon) {   function inside ($p, $cp1, $cp2) { return ($cp2[0]-$cp1[0])*($p[1]-$cp1[1]) > ($cp2[1]-$cp1[1])*($p[0]-$cp1[0]); }   function intersection ($cp1, $cp2, $e, $s) { $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] - $s[1] * $e[0]; $n3 = 1.0 / ($dc[0] * $dp[1] - $dc[1] * $dp[0]);   return [($n1*$dp[0] - $n2*$dc[0]) * $n3, ($n1*$dp[1] - $n2*$dc[1]) * $n3]; }   $outputList = $subjectPolygon; $cp1 = end($clipPolygon); foreach ($clipPolygon as $cp2) { $inputList = $outputList; $outputList = []; $s = end($inputList); foreach ($inputList as $e) { if (inside($e, $cp1, $cp2)) { if (!inside($s, $cp1, $cp2)) { $outputList[] = intersection($cp1, $cp2, $e, $s); } $outputList[] = $e; } else if (inside($s, $cp1, $cp2)) { $outputList[] = intersection($cp1, $cp2, $e, $s); } $s = $e; } $cp1 = $cp2; } return $outputList; }   $subjectPolygon = [[50, 150], [200, 50], [350, 150], [350, 300], [250, 300], [200, 250], [150, 350], [100, 250], [100, 200]]; $clipPolygon = [[100, 100], [300, 100], [300, 300], [100, 300]]; $clippedPolygon = clip($subjectPolygon, $clipPolygon);   echo json_encode($clippedPolygon); echo "\n"; ?>