task_url
stringlengths 30
116
| task_name
stringlengths 2
86
| task_description
stringlengths 0
14.4k
| language_url
stringlengths 2
53
| language_name
stringlengths 1
52
| code
stringlengths 0
61.9k
|
---|---|---|---|---|---|
http://rosettacode.org/wiki/The_Twelve_Days_of_Christmas | The Twelve Days of Christmas | Task
Write a program that outputs the lyrics of the Christmas carol The Twelve Days of Christmas.
The lyrics can be found here.
(You must reproduce the words in the correct order, but case, format, and punctuation are left to your discretion.)
Other tasks related to string operations:
Metrics
Array length
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
| #Befunge | Befunge | 0246*+00p20#v_:#`2#g+#0:#0<>\#%"O"/#:3#:+#< g48*- >1-:!#v_\1+::"O"%\"O"/v
>-#11#\0#50#< g2-:00p4v >\#%"O"/#::$#<3#$+g48*-v^\,+*+ 55!:*!!-"|":g+3<
^02_>#`>#< 2 5 3 1 0 \1-:#^\_^#:-1\+<00_@#:>#<$<
(On the ?|A partridge in a pear tree.||&first% andL day of Christmas,|My true l
ove gave to me:2|Two turtle doves'second3|Three french hens&third4|Four calling
birds'fourth3|Five golden rings&fifth4|Six geese a-laying&sixth8|Seven swans a
-swimming(seventh7|Eight maids a-milking'eighth5|Nine ladies dancing&ninth5|Ten
lords a-leaping&tenth6|Eleven pipers piping)eleventh:|Twelve drummers drumming
(twelfth |
http://rosettacode.org/wiki/Terminal_control/Hiding_the_cursor | Terminal control/Hiding the cursor | The task is to hide the cursor and show it again.
| #Raku | Raku | say 'Hiding the cursor for 5 seconds...';
run 'tput', 'civis';
sleep 5;
run 'tput', 'cvvis'; |
http://rosettacode.org/wiki/Terminal_control/Hiding_the_cursor | Terminal control/Hiding the cursor | The task is to hide the cursor and show it again.
| #REXX | REXX | /*REXX pgm calls a function in a shared library (regutil) to hide/show cursor.*/
z=rxfuncadd('sysloadfuncs', "regutil", 'sysloadfuncs') /*add a function lib.*/
if z\==0 then do /*test the return cod*/
say 'return code' z "from rxfuncadd" /*tell about bad RC. */
exit z /*exit this program. */
end
call sysloadfuncs /*load the functions.*/
/* [↓] call a particular function. */
call syscurstate 'off' /*hide the displaying of the cursor. */
say 'showing of the cursor is now off' /*inform that the cursor is now hidden.*/
/* ··· and perform some stuff here ··· */
say 'sleeping for three seconds ...' /*inform the user of what we're doing. */
call sleep 3 /*might as well sleep for three seconds*/
call syscurstate 'on' /*(unhide) the displaying of the cursor*/
say 'showing of the cursor is now on' /*inform that the cursor is now showing*/
/*stick a fork in it, we're all done. */ |
http://rosettacode.org/wiki/Terminal_control/Hiding_the_cursor | Terminal control/Hiding the cursor | The task is to hide the cursor and show it again.
| #Ring | Ring |
# Project : Terminal control/Hiding the cursor
load "stdlib.ring"
# Linux
? "Hide Cursor using tput utility"
system("tput civis") # Invisible
sleep(10)
? "Show Cursor using tput utility"
system("tput cnorm") # Normal
|
http://rosettacode.org/wiki/Terminal_control/Hiding_the_cursor | Terminal control/Hiding the cursor | The task is to hide the cursor and show it again.
| #Ruby | Ruby | require "curses"
include Curses
init_screen
begin
curs_set(1) #visible cursor
sleep 3
curs_set(0) #invisible cursor
sleep 3
curs_set(1) #visible cursor
sleep 3
ensure
close_screen
end |
http://rosettacode.org/wiki/Terminal_control/Hiding_the_cursor | Terminal control/Hiding the cursor | The task is to hide the cursor and show it again.
| #Scala | Scala | object Main extends App {
print("\u001B[?25l") // hide cursor
Thread.sleep(2000) // wait 2 seconds before redisplaying cursor
print("\u001B[?25h") // display cursor
Thread.sleep(2000) // wait 2 more seconds before exiting
} |
http://rosettacode.org/wiki/Terminal_control/Inverse_video | Terminal control/Inverse video | Task
Display a word in inverse video (or reverse video) followed by a word in normal video.
| #Raku | Raku | say "normal";
run "tput", "rev";
say "reversed";
run "tput", "sgr0";
say "normal"; |
http://rosettacode.org/wiki/Terminal_control/Inverse_video | Terminal control/Inverse video | Task
Display a word in inverse video (or reverse video) followed by a word in normal video.
| #REXX | REXX | /*REXX program demonstrates the showing of reverse video to the display terminal. */
@day = 'day'
@night = 'night'
call scrwrite , 1, @day, , , 7 /*display to terminal: white on black.*/
call scrwrite , 1+length(@day), @night, , , 112 /* " " " black " white.*/
exit 0 /*stick a fork in it, we're all done. */ |
http://rosettacode.org/wiki/Terminal_control/Inverse_video | Terminal control/Inverse video | Task
Display a word in inverse video (or reverse video) followed by a word in normal video.
| #Ring | Ring |
nverse = char(17)+char(128)+char(17)+char(15)
normal = char(17)+char(128+15)+char(17)+char(0)
see inverse + " inverse " + normal + " video"
|
http://rosettacode.org/wiki/Terminal_control/Inverse_video | Terminal control/Inverse video | Task
Display a word in inverse video (or reverse video) followed by a word in normal video.
| #Ruby | Ruby | puts "\033[7mReversed\033[m Normal" |
http://rosettacode.org/wiki/Terminal_control/Inverse_video | Terminal control/Inverse video | Task
Display a word in inverse video (or reverse video) followed by a word in normal video.
| #Scala | Scala | object Main extends App {
println("\u001B[7mInverse\u001B[m Normal")
} |
http://rosettacode.org/wiki/Terminal_control/Dimensions | Terminal control/Dimensions | Determine the height and width of the terminal, and store this information into variables for subsequent use.
| #COBOL | COBOL | IDENTIFICATION DIVISION.
PROGRAM-ID. terminal-dimensions.
DATA DIVISION.
WORKING-STORAGE SECTION.
01 num-lines PIC 9(3).
01 num-cols PIC 9(3).
SCREEN SECTION.
01 display-screen.
03 LINE 01 COL 01 PIC 9(3) FROM num-lines.
03 LINE 01 COL 05 VALUE "rows by " .
03 LINE 01 COL 13 PIC 9(3) FROM num-cols.
03 LINE 01 COL 16 VALUE " columns.".
PROCEDURE DIVISION.
ACCEPT num-lines FROM LINES
ACCEPT num-cols FROM COLUMNS
DISPLAY display-screen
* This pauses the program, as ncurses will immediately revert
* back to the console when the program ends.
CALL "C$SLEEP" USING BY CONTENT 3
GOBACK
. |
http://rosettacode.org/wiki/Terminal_control/Dimensions | Terminal control/Dimensions | Determine the height and width of the terminal, and store this information into variables for subsequent use.
| #Common_Lisp | Common Lisp | (defun screen-dimensions ()
(with-screen (scr :input-blocking t :input-echoing nil :cursor-visible nil)
(let ((width (width scr))
(height (height scr)))
(format scr "The current terminal screen is ~A lines high, ~A columns wide.~%~%" height width)
(refresh scr)
;; wait for keypress
(get-char scr)))) |
http://rosettacode.org/wiki/Terminal_control/Cursor_movement | Terminal control/Cursor movement | Task
Demonstrate how to achieve movement of the terminal cursor:
how to move the cursor one position to the left
how to move the cursor one position to the right
how to move the cursor up one line (without affecting its horizontal position)
how to move the cursor down one line (without affecting its horizontal position)
how to move the cursor to the beginning of the line
how to move the cursor to the end of the line
how to move the cursor to the top left corner of the screen
how to move the cursor to the bottom right corner of the screen
For the purpose of this task, it is not permitted to overwrite any characters or attributes on any part of the screen (so outputting a space is not a suitable solution to achieve a movement to the right).
Handling of out of bounds locomotion
This task has no specific requirements to trap or correct cursor movement beyond the terminal boundaries, so the implementer should decide what behavior fits best in terms of the chosen language. Explanatory notes may be added to clarify how an out of bounds action would behave and the generation of error messages relating to an out of bounds cursor position is permitted.
| #Action.21 | Action! | PROC Wait(BYTE frames)
BYTE RTCLOK=$14
frames==+RTCLOK
WHILE frames#RTCLOK DO OD
RETURN
PROC Main()
BYTE
d=[50],
CH=$02FC, ;Internal hardware value for last key pressed
ROWCRS=$0054 ;Current cursor row
CARD COLCRS=$0055 ;Current cursor column
Graphics(0)
Position(2,2)
Print("Press any key to start demonstration.")
Position(20,10)
Put(28) Put(29) ;trick to show the new cursor pos
DO UNTIL CH#$FF OD
CH=$FF
Wait(d) Put(30) ;move cursor left
Wait(d) Put(31) ;move cursor right
Wait(d) Put(28) ;move cursor up
Wait(d) Put(29) ;move cursor down
Wait(d) Position(0,ROWCRS) ;move to the beginning of the line
Put(28) Put(29) ;trick to show the new cursor pos
Wait(d) Position(39,ROWCRS) ;move to the end of the line
Put(28) Put(29) ;trick to show the new cursor pos
Wait(d) Position(0,0) ;move to the top-left corner
Put(28) Put(29) ;trick to show the new cursor pos
Wait(d) Position(39,23) ;move to the bottom-right corner
Put(29) Put(28) ;trick to show the new cursor pos
Wait(d)
RETURN |
http://rosettacode.org/wiki/Terminal_control/Cursor_movement | Terminal control/Cursor movement | Task
Demonstrate how to achieve movement of the terminal cursor:
how to move the cursor one position to the left
how to move the cursor one position to the right
how to move the cursor up one line (without affecting its horizontal position)
how to move the cursor down one line (without affecting its horizontal position)
how to move the cursor to the beginning of the line
how to move the cursor to the end of the line
how to move the cursor to the top left corner of the screen
how to move the cursor to the bottom right corner of the screen
For the purpose of this task, it is not permitted to overwrite any characters or attributes on any part of the screen (so outputting a space is not a suitable solution to achieve a movement to the right).
Handling of out of bounds locomotion
This task has no specific requirements to trap or correct cursor movement beyond the terminal boundaries, so the implementer should decide what behavior fits best in terms of the chosen language. Explanatory notes may be added to clarify how an out of bounds action would behave and the generation of error messages relating to an out of bounds cursor position is permitted.
| #Ada | Ada | with Ada.Text_Io;
with Ansi;
procedure Movement is
use Ada.Text_Io;
begin
Put (Ansi.Store);
Put (Ansi.Position (Row => 20, Column => 40));
for A in 1 .. 15 loop
Put (Ansi.Back);
delay 0.020;
end loop;
for A in 1 .. 15 loop
Put (Ansi.Up);
delay 0.050;
end loop;
for A in 1 .. 15 loop
Put (Ansi.Forward);
delay 0.020;
end loop;
for A in 1 .. 15 loop
Put (Ansi.Down);
delay 0.050;
end loop;
delay 1.000;
Put (Ansi.Horizontal (Column => 1));
delay 2.000;
Put (Ansi.Position (1, 1));
delay 2.000;
Put (Ansi.Restore);
end Movement; |
http://rosettacode.org/wiki/Terminal_control/Cursor_positioning | Terminal control/Cursor positioning |
Task
Move the cursor to column 3, row 6, and display the word "Hello" (without the quotes), so that the letter H is in column 3 on row 6.
| #C.2FC.2B.2B | C/C++ | #include <stdio.h>
int main()
{
printf("\033[6;3HHello\n");
return 0;
} |
http://rosettacode.org/wiki/Terminal_control/Cursor_positioning | Terminal control/Cursor positioning |
Task
Move the cursor to column 3, row 6, and display the word "Hello" (without the quotes), so that the letter H is in column 3 on row 6.
| #C.23 | C# | static void Main(string[] args)
{
Console.SetCursorPosition(3, 6);
Console.Write("Hello");
} |
http://rosettacode.org/wiki/Terminal_control/Cursor_positioning | Terminal control/Cursor positioning |
Task
Move the cursor to column 3, row 6, and display the word "Hello" (without the quotes), so that the letter H is in column 3 on row 6.
| #COBOL | COBOL | IDENTIFICATION DIVISION.
PROGRAM-ID. cursor-positioning.
PROCEDURE DIVISION.
DISPLAY "Hello" AT LINE 6, COL 3
GOBACK
. |
http://rosettacode.org/wiki/Terminal_control/Cursor_positioning | Terminal control/Cursor positioning |
Task
Move the cursor to column 3, row 6, and display the word "Hello" (without the quotes), so that the letter H is in column 3 on row 6.
| #Common_Lisp | Common Lisp | (defun cursor-positioning ()
(with-screen (scr :input-blocking t :input-echoing nil :cursor-visible nil)
(move scr 5 2)
(princ "Hello" scr)
(refresh scr)
;; wait for keypress
(get-char scr))) |
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
| #C | C | #include <stdio.h>
typedef enum {
TRITTRUE, /* In this enum, equivalent to integer value 0 */
TRITMAYBE, /* In this enum, equivalent to integer value 1 */
TRITFALSE /* In this enum, equivalent to integer value 2 */
} trit;
/* We can trivially find the result of the operation by passing
the trinary values as indeces into the lookup tables' arrays. */
trit tritNot[3] = {TRITFALSE , TRITMAYBE, TRITTRUE};
trit tritAnd[3][3] = { {TRITTRUE, TRITMAYBE, TRITFALSE},
{TRITMAYBE, TRITMAYBE, TRITFALSE},
{TRITFALSE, TRITFALSE, TRITFALSE} };
trit tritOr[3][3] = { {TRITTRUE, TRITTRUE, TRITTRUE},
{TRITTRUE, TRITMAYBE, TRITMAYBE},
{TRITTRUE, TRITMAYBE, TRITFALSE} };
trit tritThen[3][3] = { { TRITTRUE, TRITMAYBE, TRITFALSE},
{ TRITTRUE, TRITMAYBE, TRITMAYBE},
{ TRITTRUE, TRITTRUE, TRITTRUE } };
trit tritEquiv[3][3] = { { TRITTRUE, TRITMAYBE, TRITFALSE},
{ TRITMAYBE, TRITMAYBE, TRITMAYBE},
{ TRITFALSE, TRITMAYBE, TRITTRUE } };
/* Everything beyond here is just demonstration */
const char* tritString[3] = {"T", "?", "F"};
void demo_binary_op(trit operator[3][3], const char* name)
{
trit operand1 = TRITTRUE; /* Declare. Initialize for CYA */
trit operand2 = TRITTRUE; /* Declare. Initialize for CYA */
/* Blank line */
printf("\n");
/* Demo this operator */
for( operand1 = TRITTRUE; operand1 <= TRITFALSE; ++operand1 )
{
for( operand2 = TRITTRUE; operand2 <= TRITFALSE; ++operand2 )
{
printf("%s %s %s: %s\n", tritString[operand1],
name,
tritString[operand2],
tritString[operator[operand1][operand2]]);
}
}
}
int main()
{
trit op1 = TRITTRUE; /* Declare. Initialize for CYA */
trit op2 = TRITTRUE; /* Declare. Initialize for CYA */
/* Demo 'not' */
for( op1 = TRITTRUE; op1 <= TRITFALSE; ++op1 )
{
printf("Not %s: %s\n", tritString[op1], tritString[tritNot[op1]]);
}
demo_binary_op(tritAnd, "And");
demo_binary_op(tritOr, "Or");
demo_binary_op(tritThen, "Then");
demo_binary_op(tritEquiv, "Equiv");
return 0;
} |
http://rosettacode.org/wiki/Terminal_control/Display_an_extended_character | Terminal control/Display an extended character | Task
Display an extended (non ASCII) character onto the terminal.
Specifically, display a £ (GBP currency sign).
| #J | J | '£'
£
'札幌'
札幌 |
http://rosettacode.org/wiki/Terminal_control/Display_an_extended_character | Terminal control/Display an extended character | Task
Display an extended (non ASCII) character onto the terminal.
Specifically, display a £ (GBP currency sign).
| #Java | Java | import java.io.PrintStream;
import java.io.UnsupportedEncodingException;
public class Main
{
public static void main(String[] args) throws UnsupportedEncodingException
{
PrintStream writer = new PrintStream(System.out, true, "UTF-8");
writer.println("£");
writer.println("札幌");
}
} |
http://rosettacode.org/wiki/Terminal_control/Display_an_extended_character | Terminal control/Display an extended character | Task
Display an extended (non ASCII) character onto the terminal.
Specifically, display a £ (GBP currency sign).
| #Julia | Julia | println("£")
println("\302\243"); # works if your terminal is utf-8
|
http://rosettacode.org/wiki/Terminal_control/Display_an_extended_character | Terminal control/Display an extended character | Task
Display an extended (non ASCII) character onto the terminal.
Specifically, display a £ (GBP currency sign).
| #Kotlin | Kotlin | // version 1.1.2
fun main(args:Array<String>) = println("£") |
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.
| #Clojure | Clojure |
(ns rosettacode.textprocessing1
(:require [clojure.string :as str]))
(defn parse-line [s]
(let [[date & data-toks] (str/split s #"\s+")]
{:date date
:hour-vals (for [[v flag] (partition 2 data-toks)]
{:val (Double. v)
:flag (Long. flag)})}))
(defn analyze-line [m]
(let [valid? (fn [rec] (pos? (:flag rec)))
data (->> (filter valid? (:hour-vals m))
(map :val))
n-vals (count data)
sum (reduce + data)]
{:date (:date m)
:n-vals n-vals
:sum (double sum)
:avg (if (zero? n-vals) 0.0 (/ sum n-vals))
:gaps (for [hr (:hour-vals m)]
{:gap? (not (valid? hr)) :date (:date m)})}))
(defn print-line [m]
(println (format "%s: %d valid, sum: %7.3f, mean: %6.3f"
(:date m)
(:n-vals m)
(:sum m)
(:avg m))))
(defn process-line [s]
(let [m (parse-line s)
line-info (analyze-line m)]
(print-line line-info)
line-info))
(defn update-file-stats [file-m line-m]
(let [append (fn [a b] (reduce conj a b))]
(-> file-m
(update-in [:sum] + (:sum line-m))
(update-in [:n-vals] + (:n-vals line-m))
(update-in [:gap-recs] append (:gaps line-m)))))
(defn process-file [path]
(let [file-lines (->> (slurp path)
str/split-lines)
summary (reduce (fn [res line]
(update-file-stats res (process-line line)))
{:sum 0
:n-vals 0
:gap-recs []}
file-lines)
max-gap (->> (partition-by :gap? (:gap-recs summary))
(filter #(:gap? (first %)))
(sort-by count >)
first)]
(println (format "Sum: %f\n# Values: %d\nAvg: %f"
(:sum summary)
(:n-vals summary)
(/ (:sum summary) (:n-vals summary))))
(println (format "Max gap of %d recs started on %s"
(count max-gap)
(:date (first max-gap))))))
|
http://rosettacode.org/wiki/The_ISAAC_Cipher | The ISAAC Cipher | ISAAC is a cryptographically secure pseudo-random number generator (CSPRNG) and stream cipher. It was developed by Bob Jenkins from 1993 (http://burtleburtle.net/bob/rand/isaac.html) and placed in the Public Domain. ISAAC is fast - especially when optimised - and portable to most architectures in nearly all programming and scripting languages.
It is also simple and succinct, using as it does just two 256-word arrays for its state.
ISAAC stands for "Indirection, Shift, Accumulate, Add, and Count" which are the principal bitwise operations employed.
To date - and that's after more than 20 years of existence - ISAAC has not been broken (unless GCHQ or NSA did it, but they wouldn't be telling).
ISAAC thus deserves a lot more attention than it has hitherto received and it would be salutary to see it more universally implemented.
Task
Translate ISAAC's reference C or Pascal code into your language of choice.
The RNG should then be seeded with the string "this is my secret key" and
finally the message "a Top Secret secret" should be encrypted on that key.
Your program's output cipher-text will be a string of hexadecimal digits.
Optional: Include a decryption check by re-initializing ISAAC and performing
the same encryption pass on the cipher-text.
Please use the C or Pascal as a reference guide to these operations.
Two encryption schemes are possible:
(1) XOR (Vernam) or
(2) Caesar-shift mod 95 (Vigenère).
XOR is the simplest; C-shifting offers greater security.
You may choose either scheme, or both, but please specify which you used.
Here are the alternative sample outputs for checking purposes:
Message: a Top Secret secret
Key : this is my secret key
XOR : 1C0636190B1260233B35125F1E1D0E2F4C5422
MOD : 734270227D36772A783B4F2A5F206266236978
XOR dcr: a Top Secret secret
MOD dcr: a Top Secret secret
No official seeding method for ISAAC has been published, but for this task
we may as well just inject the bytes of our key into the randrsl array,
padding with zeroes before mixing, like so:
// zeroise mm array
FOR i:= 0 TO 255 DO mm[i]:=0;
// check seed's highest array element
m := High(seed);
// inject the seed
FOR i:= 0 TO 255 DO BEGIN
// in case seed[] has less than 256 elements.
IF i>m THEN randrsl[i]:=0
ELSE randrsl[i]:=seed[i];
END;
// initialize ISAAC with seed
RandInit(true);
ISAAC can of course also be initialized with a single 32-bit unsigned integer in the manner of traditional RNGs, and indeed used as such for research and gaming purposes.
But building a strong and simple ISAAC-based stream cipher - replacing the irreparably broken RC4 - is our goal here: ISAAC's intended purpose.
| #Modula-2 | Modula-2 |
MODULE RosettaIsaac;
FROM Strings IMPORT
Length, Assign, Append;
FROM STextIO IMPORT
WriteString, WriteLn;
FROM Conversions IMPORT
CardBaseToStr;
CONST
MaxStrLength = 256;
TYPE
TMode = (iEncrypt, iDecrypt);
TString = ARRAY [0 .. MaxStrLength - 1] OF CHAR;
TCardIndexedFrom0To7 = ARRAY [0 .. 7] OF CARDINAL;
VAR
(* TASK globals *)
Msg: TString = 'a Top Secret secret';
Key: TString = 'this is my secret key';
XorCipherText: TString = '';
ModCipherText: TString = '';
XorPlainText: TString = '';
ModPlainText: TString = '';
Mode: TMode = iEncrypt;
HexText: TString;
(* ISAAC globals *)
(* external results *)
RandRsl: ARRAY [0 .. 256] OF CARDINAL;
RandCnt: CARDINAL;
(* internal state *)
MM: ARRAY [0 .. 256] OF CARDINAL;
AA: CARDINAL = 0;
BB: CARDINAL = 0;
CC: CARDINAL = 0;
PROCEDURE Isaac;
VAR
I, X, Y: CARDINAL;
BEGIN
CC := CC + 1; (* CC just gets incremented once per 256 results *)
BB := BB + CC; (* then combined with BB *)
FOR I := 0 TO 255 DO
X := MM[I];
CASE (I MOD 4) OF
0: AA := AA BXOR (AA SHL 13); |
1: AA := AA BXOR (AA SHR 6); |
2: AA := AA BXOR (AA SHL 2); |
3: AA := AA BXOR (AA SHR 16);
ELSE
END;
AA := MM[(I + 128) MOD 256] + AA;
Y := MM[(X SHR 2) MOD 256] + AA + BB;
MM[I] := Y;
BB := MM[(Y SHR 10) MOD 256] + X;
RandRsl[I] := BB;
END; (* FOR *)
RandCnt := 0; (* Prepare to use the first set of results. *)
END Isaac;
PROCEDURE Mix(VAR A: TCardIndexedFrom0To7);
BEGIN
A[0] := A[0] BXOR A[1] SHL 11; A[3] := A[3] + A[0]; A[1] := A[1] + A[2];
A[1] := A[1] BXOR A[2] SHR 2; A[4] := A[4] + A[1]; A[2] := A[2] + A[3];
A[2] := A[2] BXOR A[3] SHL 8; A[5] := A[5] + A[2]; A[3] := A[3] + A[4];
A[3] := A[3] BXOR A[4] SHR 16; A[6] := A[6] + A[3]; A[4] := A[4] + A[5];
A[4] := A[4] BXOR A[5] SHL 10; A[7] := A[7] + A[4]; A[5] := A[5] + A[6];
A[5] := A[5] BXOR A[6] SHR 4; A[0] := A[0] + A[5]; A[6] := A[6] + A[7];
A[6] := A[6] BXOR A[7] SHL 8; A[1] := A[1] + A[6]; A[7] := A[7] + A[0];
A[7] := A[7] BXOR A[0] SHR 9; A[2] := A[2] + A[7]; A[0] := A[0] + A[1];
END Mix;
PROCEDURE RandInit(Flag: BOOLEAN);
VAR
I, J: CARDINAL;
A: TCardIndexedFrom0To7;
BEGIN
AA := 0; BB := 0; CC := 0;
A[0] := 2654435769; (* $9e3779b9: the golden ratio *)
FOR J := 1 TO 7 DO
A[J] := A[0];
END;
FOR I := 0 TO 3 DO (* Scramble it *)
Mix(A);
END;
FOR I := 0 TO 255 BY 8 DO (* Fill in MM[] with messy stuff. *)
IF Flag THEN (* Use all the information in the seed. *)
FOR J := 0 TO 7 DO
A[J] := A[J] + RandRsl[I + J];
END;
END;
Mix(A);
FOR J := 0 TO 7 DO
MM[I + J] := A[J];
END;
END; (* FOR I*)
IF Flag THEN
(* Do a second pass to make all of the Seed affect all of MM *)
FOR I := 0 TO 255 BY 8 DO
FOR J := 0 TO 7 DO
A[J] := A[J] + MM[I + J];
END;
Mix(A);
FOR J := 0 TO 7 DO
MM[I + J] := A[J];
END;
END; (* FOR I *)
END;
Isaac(); (* Fill in the first set of results *)
RandCnt := 0; (* Prepare to use the first set of results *)
END RandInit;
(* Seed ISAAC with a given string.
The string can be any size. The first 256 values will be used. *)
PROCEDURE SeedIsaac(Seed: ARRAY OF CHAR; Flag: BOOLEAN);
VAR
I, M: CARDINAL;
BEGIN
FOR I := 0 TO 255 DO
MM[I] := 0;
END;
M := Length(Seed);
FOR I := 0 TO 255 DO
(* In case seed has less than 256 elements *)
IF I > M THEN
RandRsl[I] := 0
ELSE
(* Modula-2 strings are 0-based (at least, in this case). *)
RandRsl[I] := ORD(Seed[I]);
END;
END;
(* Initialize ISAAC with seed. *)
RandInit(Flag);
END SeedIsaac;
(* Get a random 32-bit value 0..MAXINT *)
PROCEDURE GetRandom32Bit(): CARDINAL;
VAR
Result: CARDINAL;
BEGIN
Result := RandRsl[RandCnt];
INC(RandCnt);
IF RandCnt > 255 THEN
Isaac();
RandCnt := 0;
END;
RETURN Result;
END GetRandom32Bit;
(* Get a random character in printable ASCII range. *)
PROCEDURE GetRandomChar(): SHORTCARD;
BEGIN
RETURN GetRandom32Bit() MOD 95 + 32;
END GetRandomChar;
(* Convert an ASCII string to a hexadecimal string. *)
PROCEDURE ASCII2Hex(Source: ARRAY OF CHAR; VAR OUT Destination: ARRAY OF CHAR);
VAR
I: CARDINAL;
NumbHex: ARRAY [0 .. 1] OF CHAR;
BEGIN
Assign('', Destination);
FOR I := 0 TO Length(Source) - 1 DO
CardBaseToStr(ORD(Source[I]), 16, NumbHex);
IF Length(NumbHex) <= 1 THEN
Append('0', Destination);
END;
Append(NumbHex, Destination);
END;
END ASCII2Hex;
(* XOR encrypt on random stream. *)
PROCEDURE Vernam(Msg: ARRAY OF CHAR; VAR OUT Destination: ARRAY OF CHAR);
VAR
I: CARDINAL;
OrdMsgI: SHORTCARD;
BEGIN
Assign('', Destination);
FOR I := 0 TO Length(Msg) - 1 DO
OrdMsgI := ORD(Msg[I]);
Append(CHR(GetRandomChar() BXOR OrdMsgI), Destination);
END;
END Vernam;
(* Get position of the letter in chosen alphabet *)
PROCEDURE LetterNum(Letter, Start: CHAR): SHORTCARD;
BEGIN
RETURN ORD(Letter) - ORD(Start);
END LetterNum;
(* Caesar-shift a character <Shift> places: Generalized Vigenere *)
PROCEDURE Caesar(M: TMode; Ch: CHAR; Shift, Modulo: INTEGER; Start: CHAR): CHAR;
VAR
N, IntOrdStart: INTEGER;
BEGIN
IF M = iDecrypt THEN
Shift := -Shift;
END;
N := LetterNum(Ch, Start);
N := N + Shift;
N := N MOD Modulo;
IF N < 0 THEN
N := N + Modulo;
END;
IntOrdStart := ORD(Start);
RETURN CHR(IntOrdStart + N);
END Caesar;
(* Vigenere mod 95 encryption & decryption. *)
PROCEDURE Vigenere(Msg: ARRAY OF CHAR; M: TMode; VAR OUT Destination: ARRAY OF CHAR);
VAR
I: CARDINAL;
BEGIN
Assign('', Destination);
FOR I := 0 TO Length(Msg) - 1 DO
Append(Caesar(M, Msg[I], GetRandomChar(), 95, ' '), Destination);
END;
END Vigenere;
BEGIN
(* (1) Seed ISAAC with the key *)
SeedIsaac(Key, TRUE);
(* (2) Encryption *)
Mode := iEncrypt;
(* (a) XOR (Vernam) *)
Vernam(Msg, XorCipherText);
(* (b) MOD (Vigenere) *)
Vigenere(Msg, Mode, ModCipherText);
(* (3) Decryption *)
Mode := iDecrypt;
SeedIsaac(Key, TRUE);
(* (a) XOR (Vernam) *)
Vernam(XorCipherText, XorPlainText);
(* (b) MOD (Vigenere) *)
Vigenere(ModCipherText, Mode, ModPlainText);
(* program output *)
WriteString('Message: '); WriteString(Msg); WriteLn;
WriteString('Key : '); WriteString(Key); WriteLn;
ASCII2Hex(XorCipherText, HexText);
WriteString('XOR : '); WriteString(HexText); WriteLn;
ASCII2Hex(ModCipherText, HexText);
WriteString('MOD : '); WriteString(HexText); WriteLn;
WriteString('XOR dcr: '); WriteString(XorPlainText); WriteLn;
WriteString('MOD dcr: '); WriteString(ModPlainText); WriteLn;
END RosettaIsaac.
|
http://rosettacode.org/wiki/Test_integerness | Test integerness | Mathematically,
the integers Z are included in the rational numbers Q,
which are included in the real numbers R,
which can be generalized to the complex numbers C.
This means that each of those larger sets, and the data types used to represent them, include some integers.
Task[edit]
Given a rational, real, or complex number of any type, test whether it is mathematically an integer.
Your code should handle all numeric data types commonly used in your programming language.
Discuss any limitations of your code.
Definition
For the purposes of this task, integerness means that a number could theoretically be represented as an integer at no loss of precision (given an infinitely wide integer type).
In other words:
Set
Common representation
C++ type
Considered an integer...
rational numbers Q
fraction
std::ratio
...if its denominator is 1 (in reduced form)
real numbers Z
(approximated)
fixed-point
...if it has no non-zero digits after the decimal point
floating-point
float, double
...if the number of significant decimal places of its mantissa isn't greater than its exponent
complex numbers C
pair of real numbers
std::complex
...if its real part is considered an integer and its imaginary part is zero
Extra credit
Optionally, make your code accept a tolerance parameter for fuzzy testing. The tolerance is the maximum amount by which the number may differ from the nearest integer, to still be considered an integer.
This is useful in practice, because when dealing with approximate numeric types (such as floating point), there may already be round-off errors from previous calculations. For example, a float value of 0.9999999998 might actually be intended to represent the integer 1.
Test cases
Input
Output
Comment
Type
Value
exact
tolerance = 0.00001
decimal
25.000000
true
24.999999
false
true
25.000100
false
floating-point
-2.1e120
true
This one is tricky, because in most languages it is too large to fit into a native integer type.
It is, nonetheless, mathematically an integer, and your code should identify it as such.
-5e-2
false
NaN
false
Inf
false
This one is debatable. If your code considers it an integer, that's okay too.
complex
5.0+0.0i
true
5-5i
false
(The types and notations shown in these tables are merely examples – you should use the native data types and number literals of your programming language and standard library. Use a different set of test-cases, if this one doesn't demonstrate all relevant behavior.)
| #PARI.2FGP | PARI/GP | isInteger(z)=real(z)==real(z)\1 && imag(z)==imag(z)\1;
apply(isInteger, [7, I, 1.7 + I, 10.0 + I, 1.0 - 7.0 * I]) |
http://rosettacode.org/wiki/Test_integerness | Test integerness | Mathematically,
the integers Z are included in the rational numbers Q,
which are included in the real numbers R,
which can be generalized to the complex numbers C.
This means that each of those larger sets, and the data types used to represent them, include some integers.
Task[edit]
Given a rational, real, or complex number of any type, test whether it is mathematically an integer.
Your code should handle all numeric data types commonly used in your programming language.
Discuss any limitations of your code.
Definition
For the purposes of this task, integerness means that a number could theoretically be represented as an integer at no loss of precision (given an infinitely wide integer type).
In other words:
Set
Common representation
C++ type
Considered an integer...
rational numbers Q
fraction
std::ratio
...if its denominator is 1 (in reduced form)
real numbers Z
(approximated)
fixed-point
...if it has no non-zero digits after the decimal point
floating-point
float, double
...if the number of significant decimal places of its mantissa isn't greater than its exponent
complex numbers C
pair of real numbers
std::complex
...if its real part is considered an integer and its imaginary part is zero
Extra credit
Optionally, make your code accept a tolerance parameter for fuzzy testing. The tolerance is the maximum amount by which the number may differ from the nearest integer, to still be considered an integer.
This is useful in practice, because when dealing with approximate numeric types (such as floating point), there may already be round-off errors from previous calculations. For example, a float value of 0.9999999998 might actually be intended to represent the integer 1.
Test cases
Input
Output
Comment
Type
Value
exact
tolerance = 0.00001
decimal
25.000000
true
24.999999
false
true
25.000100
false
floating-point
-2.1e120
true
This one is tricky, because in most languages it is too large to fit into a native integer type.
It is, nonetheless, mathematically an integer, and your code should identify it as such.
-5e-2
false
NaN
false
Inf
false
This one is debatable. If your code considers it an integer, that's okay too.
complex
5.0+0.0i
true
5-5i
false
(The types and notations shown in these tables are merely examples – you should use the native data types and number literals of your programming language and standard library. Use a different set of test-cases, if this one doesn't demonstrate all relevant behavior.)
| #Perl | Perl | use Math::Complex;
sub is_int {
my $number = shift;
if (ref $number eq 'Math::Complex') {
return 0 if $number->Im != 0;
$number = $number->Re;
}
return int($number) == $number;
}
for (5, 4.1, sqrt(2), sqrt(4), 1.1e10, 3.0-0.0*i, 4-3*i, 5.6+0*i) {
printf "%20s is%s an integer\n", $_, (is_int($_) ? "" : " NOT");
} |
http://rosettacode.org/wiki/Text_processing/Max_licenses_in_use | Text processing/Max licenses in use | A company currently pays a fixed sum for the use of a particular licensed software package. In determining if it has a good deal it decides to calculate its maximum use of the software from its license management log file.
Assume the software's licensing daemon faithfully records a checkout event when a copy of the software starts and a checkin event when the software finishes to its log file.
An example of checkout and checkin events are:
License OUT @ 2008/10/03_23:51:05 for job 4974
...
License IN @ 2008/10/04_00:18:22 for job 4974
Task
Save the 10,000 line log file from here into a local file, then write a program to scan the file extracting both the maximum licenses that were out at any time, and the time(s) at which this occurs.
Mirror of log file available as a zip here (offsite mirror).
| #Picat | Picat | import util.
go =>
Jobs = read_file_lines("mlijobs.txt"),
Counts = asum(Jobs).to_array, % convert to array for speed
Max = max(Counts),
MaxIxs = [I : I in 1..Counts.length, Counts[I] == Max],
printf("Max number of licenses is %d.\n", Max),
printf("Interval:\n%w\n", [Jobs[J,15..33] : J in MaxIxs].join("\n")),
nl.
% Accumulative sum
asum(List) = Asum =>
asum(List,[],Asum).
asum([],Asum0,Asum) =>
Asum = Asum0.reverse().
asum([H|T],[],Asum) =>
C = cond(slice(H,9,11) == "OUT", 1, -1),
asum(T,[C],Asum).
asum([H|T],Asum0,Asum) =>
Asum0 = [Last|_],
C = cond(slice(H,9,11) == "OUT", 1, -1),
asum(T,[Last+C|Asum0],Asum). |
http://rosettacode.org/wiki/Text_processing/Max_licenses_in_use | Text processing/Max licenses in use | A company currently pays a fixed sum for the use of a particular licensed software package. In determining if it has a good deal it decides to calculate its maximum use of the software from its license management log file.
Assume the software's licensing daemon faithfully records a checkout event when a copy of the software starts and a checkin event when the software finishes to its log file.
An example of checkout and checkin events are:
License OUT @ 2008/10/03_23:51:05 for job 4974
...
License IN @ 2008/10/04_00:18:22 for job 4974
Task
Save the 10,000 line log file from here into a local file, then write a program to scan the file extracting both the maximum licenses that were out at any time, and the time(s) at which this occurs.
Mirror of log file available as a zip here (offsite mirror).
| #PicoLisp | PicoLisp | #!/usr/bin/picolisp /usr/lib/picolisp/lib.l
(zero Count MaxCount)
(in (opt)
(while (split (line) " ")
(case (pack (cadr (setq Line @)))
(IN
(dec 'Count) )
(OUT
(let Time (cadddr Line)
(cond
((> (inc 'Count) MaxCount)
(setq MaxCount Count MaxTimes Time) )
((= Count MaxCount)
(setq MaxTimes (pack MaxTimes " and " Time)) ) ) ) ) ) ) )
(prinl "The biggest number of licenses is " MaxCount " at " MaxTimes " !")
(bye) |
http://rosettacode.org/wiki/Test_a_function | Test a function |
Task
Using a well-known testing-specific library/module/suite for your language, write some tests for your language's entry in Palindrome.
If your language does not have a testing specific library well known to the language's community then state this or omit the language.
| #Julia | Julia | using Base.Test
include("Palindrome_detection.jl")
# Simple test
@test palindrome("abcdcba")
@test !palindrome("abd")
# Test sets
@testset "palindromes" begin
@test palindrome("aaaaa")
@test palindrome("abcba")
@test palindrome("1")
@test palindrome("12321")
end
@testset "non-palindromes" begin
@test !palindrome("abc")
@test !palindrome("a11")
@test !palindrome("012")
end |
http://rosettacode.org/wiki/Test_a_function | Test a function |
Task
Using a well-known testing-specific library/module/suite for your language, write some tests for your language's entry in Palindrome.
If your language does not have a testing specific library well known to the language's community then state this or omit the language.
| #Kotlin | Kotlin | // version 1.1.3
fun isPalindrome(s: String) = (s == s.reversed())
fun main(args: Array<String>) {
val testCases = listOf("racecar", "alice", "eertree", "david")
for (testCase in testCases) {
try {
assert(isPalindrome(testCase)) { "$testCase is not a palindrome" }
}
catch (ae: AssertionError) {
println(ae.message)
}
}
} |
http://rosettacode.org/wiki/Text_processing/2 | Text processing/2 | The following task concerns data that came from a pollution monitoring station with twenty-four instruments monitoring twenty-four aspects of pollution in the air. Periodically a record is added to the file, each record being a line of 49 fields separated by white-space, which can be one or more space or tab characters.
The fields (from the left) are:
DATESTAMP [ VALUEn FLAGn ] * 24
i.e. a datestamp followed by twenty-four repetitions of a floating-point instrument value and that instrument's associated integer flag. Flag values are >= 1 if the instrument is working and < 1 if there is some problem with it, in which case that instrument's value should be ignored.
A sample from the full data file readings.txt, which is also used in the Text processing/1 task, follows:
Data is no longer available at that link. Zipped mirror available here
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
Task
Confirm the general field format of the file.
Identify any DATESTAMPs that are duplicated.
Report the number of records that have good readings for all instruments.
| #zkl | zkl | // the RegExp engine has a low limit on groups so
// I can't use it to select all fields, only verify them
re:=RegExp(0'|^(\d+-\d+-\d+)| + 0'|\s+\d+\.\d+\s+-*\d+| * 24 + ".+$");
w:=[1..].zip(File("readings.txt")); //-->lazy (line #,line)
reg datep,N, good=0, dd=0;
foreach n,line in (w){
N=n; // since n is local to this scope
if (not re.search(line)){ println("Line %d: malformed".fmt(n)); continue; }
date:=line[re.matchedNs[1].xplode()]; // I can group the date field
if (datep==date){ dd+=1; println("Line %4d: dup date: %s".fmt(n,date)); }
datep=date;
if (line.replace("\t"," ").split(" ").filter()[1,*] // blow fields apart, drop date
.pump(Void,Void.Read, // get (reading,status)
fcn(_,s){ // stop on first problem status and return True
if(s.strip().toInt()<1) T(Void.Stop,True) else False
})) continue;
good+=1;
}
println("%d records read, %d duplicate dates, %d valid".fmt(N,dd,good)); |
http://rosettacode.org/wiki/Terminal_control/Ringing_the_terminal_bell | Terminal control/Ringing the terminal bell |
Task
Make the terminal running the program ring its "bell".
On modern terminal emulators, this may be done by playing some other sound which might or might not be configurable, or by flashing the title bar or inverting the colors of the screen, but was classically a physical bell within the terminal. It is usually used to indicate a problem where a wrong character has been typed.
In most terminals, if the Bell character (ASCII code 7, \a in C) is printed by the program, it will cause the terminal to ring its bell. This is a function of the terminal, and is independent of the programming language of the program, other than the ability to print a particular character to standard out.
| #Sidef | Sidef | print "\a"; |
http://rosettacode.org/wiki/Terminal_control/Ringing_the_terminal_bell | Terminal control/Ringing the terminal bell |
Task
Make the terminal running the program ring its "bell".
On modern terminal emulators, this may be done by playing some other sound which might or might not be configurable, or by flashing the title bar or inverting the colors of the screen, but was classically a physical bell within the terminal. It is usually used to indicate a problem where a wrong character has been typed.
In most terminals, if the Bell character (ASCII code 7, \a in C) is printed by the program, it will cause the terminal to ring its bell. This is a function of the terminal, and is independent of the programming language of the program, other than the ability to print a particular character to standard out.
| #SNUSP | SNUSP | $+++++++.# |
http://rosettacode.org/wiki/Terminal_control/Ringing_the_terminal_bell | Terminal control/Ringing the terminal bell |
Task
Make the terminal running the program ring its "bell".
On modern terminal emulators, this may be done by playing some other sound which might or might not be configurable, or by flashing the title bar or inverting the colors of the screen, but was classically a physical bell within the terminal. It is usually used to indicate a problem where a wrong character has been typed.
In most terminals, if the Bell character (ASCII code 7, \a in C) is printed by the program, it will cause the terminal to ring its bell. This is a function of the terminal, and is independent of the programming language of the program, other than the ability to print a particular character to standard out.
| #Standard_ML | Standard ML | val () = print "\a" |
http://rosettacode.org/wiki/Terminal_control/Ringing_the_terminal_bell | Terminal control/Ringing the terminal bell |
Task
Make the terminal running the program ring its "bell".
On modern terminal emulators, this may be done by playing some other sound which might or might not be configurable, or by flashing the title bar or inverting the colors of the screen, but was classically a physical bell within the terminal. It is usually used to indicate a problem where a wrong character has been typed.
In most terminals, if the Bell character (ASCII code 7, \a in C) is printed by the program, it will cause the terminal to ring its bell. This is a function of the terminal, and is independent of the programming language of the program, other than the ability to print a particular character to standard out.
| #Tcl | Tcl | puts -nonewline "\a";flush stdout |
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
| #Bracmat | Bracmat | ( first
second
third
fourth
fifth
sixth
seventh
eighth
ninth
tenth
eleventh
twelveth
: ?days
& "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,"
: ?gifts
& :?given
& whl
' ( !gifts:%?gift ?gifts
& !gift \n !given:?given
& !days:%?day ?days
& out
$ ( str
$ ("\nOn the " !day " day of Christmas my true love gave to me:
" !given)
)
)
); |
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
| #C | C |
#include<stdio.h>
int main()
{
int i,j;
char days[12][10] =
{
"First",
"Second",
"Third",
"Fourth",
"Fifth",
"Sixth",
"Seventh",
"Eighth",
"Ninth",
"Tenth",
"Eleventh",
"Twelfth"
};
char gifts[12][33] =
{
"Twelve drummers drumming",
"Eleven pipers piping",
"Ten lords a-leaping",
"Nine ladies dancing",
"Eight maids a-milking",
"Seven swans a-swimming",
"Six geese a-laying",
"Five golden rings",
"Four calling birds",
"Three french hens",
"Two turtle doves",
"And a partridge in a pear tree."
};
for(i=0;i<12;i++)
{
printf("\n\nOn the %s day of Christmas\nMy true love gave to me:",days[i]);
for(j=i;j>=0;j--)
{
(i==0)?printf("\nA partridge in a pear tree."):printf("\n%s%c",gifts[11-j],(j!=0)?',':' ');
}
}
return 0;
} |
http://rosettacode.org/wiki/Terminal_control/Hiding_the_cursor | Terminal control/Hiding the cursor | The task is to hide the cursor and show it again.
| #Tcl | Tcl |
proc cursorVisibility {{state normal}} {
switch -- $state {
invisible {set op civis}
visible {set op cvvis}
normal {set op cnorm}
}
exec -- >@stdout tput $op
}
|
http://rosettacode.org/wiki/Terminal_control/Hiding_the_cursor | Terminal control/Hiding the cursor | The task is to hide the cursor and show it again.
| #UNIX_Shell | UNIX Shell | tput civis # Hide the cursor
sleep 5 # Sleep for 5 seconds
tput cnorm # Show the cursor |
http://rosettacode.org/wiki/Terminal_control/Hiding_the_cursor | Terminal control/Hiding the cursor | The task is to hide the cursor and show it again.
| #Wren | Wren | import "timer" for Timer
System.print("\e[?25l")
Timer.sleep(3000)
System.print("\e[?25h")
Timer.sleep(3000) |
http://rosettacode.org/wiki/Terminal_control/Hiding_the_cursor | Terminal control/Hiding the cursor | The task is to hide the cursor and show it again.
| #XPL0 | XPL0 | include c:\cxpl\codes; \intrinsic 'code' declarations
proc ShowCur(On); \Turn flashing cursor on or off
int On; \true = cursor on; false = cursor off
int CpuReg;
[CpuReg:= GetReg; \access CPU registers
CpuReg(0):= $0100; \AX:= $0100
CpuReg(2):= if On then $0007 else $2000;
SoftInt($10); \Call BIOS interrupt $10
]; \ShowCur
[ShowCur(false); \turn off flashing cursor
if ChIn(1) then []; \wait for keystroke
ShowCur(true); \turn on flashing cursor
] |
http://rosettacode.org/wiki/Terminal_control/Hiding_the_cursor | Terminal control/Hiding the cursor | The task is to hide the cursor and show it again.
| #zkl | zkl | print("\e[?25l");
Atomic.sleep(3);
print("\e[?25h"); |
http://rosettacode.org/wiki/Terminal_control/Inverse_video | Terminal control/Inverse video | Task
Display a word in inverse video (or reverse video) followed by a word in normal video.
| #Standard_ML | Standard ML | val () = print "\^[[7mReversed\^[[m Normal\n" |
http://rosettacode.org/wiki/Terminal_control/Inverse_video | Terminal control/Inverse video | Task
Display a word in inverse video (or reverse video) followed by a word in normal video.
| #Tcl | Tcl | # Get how the terminal wants to do things...
set videoSeq(reverse) [exec tput rev]
set videoSeq(normal) [exec tput rmso]
proc reverseVideo str {
global videoSeq
return "$videoSeq(reverse)${str}$videoSeq(normal)"
}
# The things to print
set inReverse "foo"
set inNormal "bar"
# Print those words
puts "[reverseVideo $inReverse] $inNormal" |
http://rosettacode.org/wiki/Terminal_control/Inverse_video | Terminal control/Inverse video | Task
Display a word in inverse video (or reverse video) followed by a word in normal video.
| #TPP | TPP | --revon
This is inverse
--revoff
This is normal |
http://rosettacode.org/wiki/Terminal_control/Inverse_video | Terminal control/Inverse video | Task
Display a word in inverse video (or reverse video) followed by a word in normal video.
| #UNIX_Shell | UNIX Shell | #!/bin/sh
tput mr # foo is reversed
echo 'foo'
tput me # bar is normal video
echo 'bar' |
http://rosettacode.org/wiki/Terminal_control/Inverse_video | Terminal control/Inverse video | Task
Display a word in inverse video (or reverse video) followed by a word in normal video.
| #Wren | Wren | System.print("\e[7mInverse")
System.print("\e[0mNormal") |
http://rosettacode.org/wiki/Terminal_control/Inverse_video | Terminal control/Inverse video | Task
Display a word in inverse video (or reverse video) followed by a word in normal video.
| #XPL0 | XPL0 | include c:\cxpl\codes;
[Attrib($70);
Text(6, "Inverse");
Attrib($07);
Text(6, " Video");
CrLf(6);
] |
http://rosettacode.org/wiki/Terminal_control/Dimensions | Terminal control/Dimensions | Determine the height and width of the terminal, and store this information into variables for subsequent use.
| #Euphoria | Euphoria | include graphics.e
sequence vc
integer term_height, term_width
vc = video_config()
term_height = vc[VC_LINES]
term_width = vc[VC_COLUMNS]
printf(1,"Terminal height is %d\n",term_height)
printf(1,"Terminal width is %d\n",term_width) |
http://rosettacode.org/wiki/Terminal_control/Dimensions | Terminal control/Dimensions | Determine the height and width of the terminal, and store this information into variables for subsequent use.
| #F.23 | F# | open System
let bufferHeight = Console.BufferHeight
let bufferWidth = Console.BufferWidth
let windowHeight = Console.WindowHeight
let windowWidth = Console.WindowWidth
Console.Write("Buffer Height: ")
Console.WriteLine(bufferHeight)
Console.Write("Buffer Width: ")
Console.WriteLine(bufferWidth)
Console.Write("Window Height: ")
Console.WriteLine(windowHeight)
Console.Write("Window Width: ")
Console.WriteLine(windowWidth)
Console.ReadLine() |
http://rosettacode.org/wiki/Terminal_control/Dimensions | Terminal control/Dimensions | Determine the height and width of the terminal, and store this information into variables for subsequent use.
| #Forth | Forth | variable term-width
variable term-height
s" gforth" environment? [if]
2drop form ( height width )
[else] \ SwiftForth
get-size ( width height ) swap
[then]
term-width ! term-height ! |
http://rosettacode.org/wiki/Terminal_control/Dimensions | Terminal control/Dimensions | Determine the height and width of the terminal, and store this information into variables for subsequent use.
| #FreeBASIC | FreeBASIC | Dim As Integer w, h, p, bpp, tasa
Dim driver_name As String
Screeninfo w, h, p, bpp, , tasa
Print !"Informaci¢n sobre el escritorio (terminal):\n"
Print " Ancho de la terminal: "; w; " (pixel)"
Print "Altura de la terminal: "; h; " (pixel)"
Print " Profundidad de color: "; p; " (bits)"
Print " Tasa de refresco: "; tasa; " (Hz)"
' Sets screen mode 13 (640*480, 8bpp)
Screen 12
Screeninfo w, h, p, bpp, , tasa, driver_name
Print !"Informaci¢n sobre el modo gr fico:\n"
Print " Ancho de la pantalla: "; w; " (pixel)"
Print "Altura de la pantalla: "; h; " (pixel)"
Print " Profundidad de color: "; p; " (bits)"
Print " Bytes por pixel: "; bpp
Print " Tasa de refresco: "; tasa; " (Hz)"
Print " Nombre del driver: "; driver_name
Sleep |
http://rosettacode.org/wiki/Terminal_control/Coloured_text | Terminal control/Coloured text | Task
Display a word in various colours on the terminal.
The system palette, or colours such as Red, Green, Blue, Magenta, Cyan, and Yellow can be used.
Optionally demonstrate:
How the system should determine if the terminal supports colour
Setting of the background colour
How to cause blinking or flashing (if supported by the terminal)
| #8086_Assembly | 8086 Assembly | .model small
.stack 1024
.data
.code
start:
mov ax,@data
mov ds,ax
mov ax,@code
mov es,ax
cld ;String functions are set to auto-increment
mov ax,13h ;select 320x200 VGA
int 10h
mov ah,0Eh
mov al,'A' ;select char to print
mov bx,11 ;select color to print it in
int 10h
ExitDOS:
mov ax,4C00h ;return to dos
int 21h
end start |
http://rosettacode.org/wiki/Terminal_control/Cursor_movement | Terminal control/Cursor movement | Task
Demonstrate how to achieve movement of the terminal cursor:
how to move the cursor one position to the left
how to move the cursor one position to the right
how to move the cursor up one line (without affecting its horizontal position)
how to move the cursor down one line (without affecting its horizontal position)
how to move the cursor to the beginning of the line
how to move the cursor to the end of the line
how to move the cursor to the top left corner of the screen
how to move the cursor to the bottom right corner of the screen
For the purpose of this task, it is not permitted to overwrite any characters or attributes on any part of the screen (so outputting a space is not a suitable solution to achieve a movement to the right).
Handling of out of bounds locomotion
This task has no specific requirements to trap or correct cursor movement beyond the terminal boundaries, so the implementer should decide what behavior fits best in terms of the chosen language. Explanatory notes may be added to clarify how an out of bounds action would behave and the generation of error messages relating to an out of bounds cursor position is permitted.
| #ARM_Assembly | ARM Assembly |
/* ARM assembly Raspberry PI */
/* program cursorMove.s */
/* Constantes */
.equ STDOUT, 1 @ Linux output console
.equ EXIT, 1 @ Linux syscall
.equ WRITE, 4 @ Linux syscall
/* Initialized data */
.data
szMessStartPgm: .asciz "Program start \n"
szMessEndPgm: .asciz "Program normal end.\n"
szMessColorRed: .asciz "Color red.\n"
szCodeInit: .asciz "\033[0m" @ color reinit
szCodeRed: .asciz "\033[31m" @ color red
szCodeBlue: .asciz "\033[34m" @ color blue
szMessMove: .asciz "\033[A\033[6CBlue Message up and 6 location right."
szMessMoveDown: .asciz "\033[31m\033[BRed text location down"
szMessTopLeft: .asciz "\033[;HTOP LEFT"
szCarriageReturn: .asciz "\n"
/* UnInitialized data */
.bss
/* code section */
.text
.global main
main:
ldr r0,iAdrszMessStartPgm @ display start message
bl affichageMess
ldr r0,iAdrszCodeRed @ color red
bl affichageMess
ldr r0,iAdrszMessColorRed
bl affichageMess
ldr r0,iAdrszCodeBlue
bl affichageMess
ldr r0,iAdrszMessMove
bl affichageMess
ldr r0,iAdrszMessMoveDown @ move pointer down
bl affichageMess
ldr r0,iAdrszMessTopLeft
bl affichageMess
ldr r0,iAdrszCarriageReturn @ start next line
bl affichageMess
ldr r0,iAdrszCodeInit @ color reinitialize
bl affichageMess
ldr r0,iAdrszMessEndPgm @ display end message
bl affichageMess
100: @ standard end of the program
mov r0, #0 @ return code
mov r7, #EXIT @ request to exit program
svc 0 @ perform system call
iAdrszMessStartPgm: .int szMessStartPgm
iAdrszMessEndPgm: .int szMessEndPgm
iAdrszCodeInit: .int szCodeInit
iAdrszCodeRed: .int szCodeRed
iAdrszCodeBlue: .int szCodeBlue
iAdrszMessColorRed: .int szMessColorRed
iAdrszMessMove: .int szMessMove
iAdrszCarriageReturn: .int szCarriageReturn
iAdrszMessMoveDown: .int szMessMoveDown
iAdrszMessTopLeft: .int szMessTopLeft
/******************************************************************/
/* display text with size calculation */
/******************************************************************/
/* r0 contains the address of the message */
affichageMess:
push {r0,r1,r2,r7,lr} @ save registers
mov r2,#0 @ counter length */
1: @ loop length calculation
ldrb r1,[r0,r2] @ read octet start position + index
cmp r1,#0 @ if 0 its over
addne r2,r2,#1 @ else add 1 in the length
bne 1b @ and loop
@ so here r2 contains the length of the message
mov r1,r0 @ address message in r1
mov r0,#STDOUT @ code to write to the standard output Linux
mov r7, #WRITE @ code call system "write"
svc #0 @ call system
pop {r0,r1,r2,r7,lr} @ restaur registers
bx lr @ return
|
http://rosettacode.org/wiki/Terminal_control/Cursor_positioning | Terminal control/Cursor positioning |
Task
Move the cursor to column 3, row 6, and display the word "Hello" (without the quotes), so that the letter H is in column 3 on row 6.
| #D | D | Position the Cursor:
\033[<L>;<C>H
or
\033[<L>;<C>f
puts the cursor at line L and column C.
|
http://rosettacode.org/wiki/Terminal_control/Cursor_positioning | Terminal control/Cursor positioning |
Task
Move the cursor to column 3, row 6, and display the word "Hello" (without the quotes), so that the letter H is in column 3 on row 6.
| #Elena | Elena | public program()
{
console.setCursorPosition(3,6).write("Hello")
} |
http://rosettacode.org/wiki/Terminal_control/Cursor_positioning | Terminal control/Cursor positioning |
Task
Move the cursor to column 3, row 6, and display the word "Hello" (without the quotes), so that the letter H is in column 3 on row 6.
| #Euphoria | Euphoria | position(6,3)
puts(1,"Hello") |
http://rosettacode.org/wiki/Terminal_control/Cursor_positioning | Terminal control/Cursor positioning |
Task
Move the cursor to column 3, row 6, and display the word "Hello" (without the quotes), so that the letter H is in column 3 on row 6.
| #F.23 | F# | open System
Console.SetCursorPosition(3, 6)
Console.Write("Hello") |
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
| #C.23 | C# | using System;
/// <summary>
/// Extension methods on nullable bool.
/// </summary>
/// <remarks>
/// The operators !, & and | are predefined.
/// </remarks>
public static class NullableBoolExtension
{
public static bool? Implies(this bool? left, bool? right)
{
return !left | right;
}
public static bool? IsEquivalentTo(this bool? left, bool? right)
{
return left.HasValue && right.HasValue ? left == right : default(bool?);
}
public static string Format(this bool? value)
{
return value.HasValue ? value.Value.ToString() : "Maybe";
}
}
public class Program
{
private static void Main()
{
var values = new[] { true, default(bool?), false };
foreach (var left in values)
{
Console.WriteLine("¬{0} = {1}", left.Format(), (!left).Format());
foreach (var right in values)
{
Console.WriteLine("{0} & {1} = {2}", left.Format(), right.Format(), (left & right).Format());
Console.WriteLine("{0} | {1} = {2}", left.Format(), right.Format(), (left | right).Format());
Console.WriteLine("{0} → {1} = {2}", left.Format(), right.Format(), left.Implies(right).Format());
Console.WriteLine("{0} ≡ {1} = {2}", left.Format(), right.Format(), left.IsEquivalentTo(right).Format());
}
}
}
} |
http://rosettacode.org/wiki/Terminal_control/Display_an_extended_character | Terminal control/Display an extended character | Task
Display an extended (non ASCII) character onto the terminal.
Specifically, display a £ (GBP currency sign).
| #Lasso | Lasso | stdout(' £ ') |
http://rosettacode.org/wiki/Terminal_control/Display_an_extended_character | Terminal control/Display an extended character | Task
Display an extended (non ASCII) character onto the terminal.
Specifically, display a £ (GBP currency sign).
| #Locomotive_Basic | Locomotive Basic | 10 PRINT CHR$(163) |
http://rosettacode.org/wiki/Terminal_control/Display_an_extended_character | Terminal control/Display an extended character | Task
Display an extended (non ASCII) character onto the terminal.
Specifically, display a £ (GBP currency sign).
| #Lua | Lua | print(string.char(156)) |
http://rosettacode.org/wiki/Terminal_control/Display_an_extended_character | Terminal control/Display an extended character | Task
Display an extended (non ASCII) character onto the terminal.
Specifically, display a £ (GBP currency sign).
| #Mathematica.2FWolfram_Language | Mathematica/Wolfram Language | FromCharacterCode[{163}] |
http://rosettacode.org/wiki/Terminal_control/Display_an_extended_character | Terminal control/Display an extended character | Task
Display an extended (non ASCII) character onto the terminal.
Specifically, display a £ (GBP currency sign).
| #NetRexx | NetRexx | /* NetRexx */
options replace format comments java crossref symbols binary
runSample(arg)
return
-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
method runSample(arg) private static
GBP = '\u00a3' -- unicode code point
say GBP
GBP = '£' -- if the editor's up to it
say GBP
GBP = 16x00a3 -- yet another way
say (Rexx GBP).d2c
return
|
http://rosettacode.org/wiki/Terminal_control/Display_an_extended_character | Terminal control/Display an extended character | Task
Display an extended (non ASCII) character onto the terminal.
Specifically, display a £ (GBP currency sign).
| #Nim | Nim | echo "£"
echo "札幌"
import unicode
echo Rune(0xa3) |
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.
| #COBOL | COBOL | IDENTIFICATION DIVISION.
PROGRAM-ID. data-munging.
ENVIRONMENT DIVISION.
INPUT-OUTPUT SECTION.
FILE-CONTROL.
SELECT input-file ASSIGN TO INPUT-FILE-PATH
ORGANIZATION LINE SEQUENTIAL
FILE STATUS file-status.
DATA DIVISION.
FILE SECTION.
FD input-file.
01 input-record.
03 date-stamp PIC X(10).
03 FILLER PIC X.
*> Curse whoever decided to use tabs and variable length
*> data in the file!
03 input-data-pairs PIC X(300).
WORKING-STORAGE SECTION.
78 INPUT-FILE-PATH VALUE "readings.txt".
01 file-status PIC 99.
88 file-is-ok VALUE 0.
88 end-of-file VALUE 10.
01 data-pair.
03 val PIC 9(3)V9(3).
03 flag PIC S9.
88 invalid-flag VALUE -9 THRU 0.
01 val-length PIC 9.
01 flag-length PIC 9.
01 offset PIC 99.
01 day-total PIC 9(5)V9(3).
01 grand-total PIC 9(8)V9(3).
01 mean-val PIC 9(8)V9(3).
01 day-rejected PIC 9(5).
01 day-accepted PIC 9(5).
01 total-rejected PIC 9(8).
01 total-accepted PIC 9(8).
01 current-data-gap PIC 9(8).
01 max-data-gap PIC 9(8).
01 max-data-gap-end PIC X(10).
PROCEDURE DIVISION.
DECLARATIVES.
*> Terminate the program if an error occurs on input-file.
input-file-error SECTION.
USE AFTER STANDARD ERROR ON input-file.
DISPLAY
"An error occurred while reading input.txt. "
"File error: " file-status
". The program will terminate."
END-DISPLAY
GOBACK
.
END DECLARATIVES.
main-line.
*> Terminate the program if the file cannot be opened.
OPEN INPUT input-file
IF NOT file-is-ok
DISPLAY "File could not be opened. The program will "
"terminate."
GOBACK
END-IF
*> Process the data in the file.
PERFORM FOREVER
*> Stop processing if at the end of the file.
READ input-file
AT END
EXIT PERFORM
END-READ
*> Split the data up and process the value-flag pairs.
PERFORM UNTIL input-data-pairs = SPACES
*> Split off the value-flag pair at the front of the
*> record.
UNSTRING input-data-pairs DELIMITED BY X"09"
INTO val COUNT val-length, flag COUNT flag-length
COMPUTE offset = val-length + flag-length + 3
MOVE input-data-pairs (offset:) TO input-data-pairs
*> Process according to flag.
IF NOT invalid-flag
ADD val TO day-total, grand-total
ADD 1 TO day-accepted, total-accepted
IF max-data-gap < current-data-gap
MOVE current-data-gap TO max-data-gap
MOVE date-stamp TO max-data-gap-end
END-IF
MOVE ZERO TO current-data-gap
ELSE
ADD 1 TO current-data-gap, day-rejected,
total-rejected
END-IF
END-PERFORM
*> Display day stats.
DIVIDE day-total BY day-accepted GIVING mean-val
DISPLAY
date-stamp
" Reject: " day-rejected
" Accept: " day-accepted
" Average: " mean-val
END-DISPLAY
INITIALIZE day-rejected, day-accepted, mean-val,
day-total
END-PERFORM
CLOSE input-file
*> Display overall stats.
DISPLAY SPACE
DISPLAY "File: " INPUT-FILE-PATH
DISPLAY "Total: " grand-total
DISPLAY "Readings: " total-accepted
DIVIDE grand-total BY total-accepted GIVING mean-val
DISPLAY "Average: " mean-val
DISPLAY SPACE
DISPLAY "Bad readings: " total-rejected
DISPLAY "Maximum number of consecutive bad readings is "
max-data-gap
DISPLAY "Ends on date " max-data-gap-end
GOBACK
. |
http://rosettacode.org/wiki/The_ISAAC_Cipher | The ISAAC Cipher | ISAAC is a cryptographically secure pseudo-random number generator (CSPRNG) and stream cipher. It was developed by Bob Jenkins from 1993 (http://burtleburtle.net/bob/rand/isaac.html) and placed in the Public Domain. ISAAC is fast - especially when optimised - and portable to most architectures in nearly all programming and scripting languages.
It is also simple and succinct, using as it does just two 256-word arrays for its state.
ISAAC stands for "Indirection, Shift, Accumulate, Add, and Count" which are the principal bitwise operations employed.
To date - and that's after more than 20 years of existence - ISAAC has not been broken (unless GCHQ or NSA did it, but they wouldn't be telling).
ISAAC thus deserves a lot more attention than it has hitherto received and it would be salutary to see it more universally implemented.
Task
Translate ISAAC's reference C or Pascal code into your language of choice.
The RNG should then be seeded with the string "this is my secret key" and
finally the message "a Top Secret secret" should be encrypted on that key.
Your program's output cipher-text will be a string of hexadecimal digits.
Optional: Include a decryption check by re-initializing ISAAC and performing
the same encryption pass on the cipher-text.
Please use the C or Pascal as a reference guide to these operations.
Two encryption schemes are possible:
(1) XOR (Vernam) or
(2) Caesar-shift mod 95 (Vigenère).
XOR is the simplest; C-shifting offers greater security.
You may choose either scheme, or both, but please specify which you used.
Here are the alternative sample outputs for checking purposes:
Message: a Top Secret secret
Key : this is my secret key
XOR : 1C0636190B1260233B35125F1E1D0E2F4C5422
MOD : 734270227D36772A783B4F2A5F206266236978
XOR dcr: a Top Secret secret
MOD dcr: a Top Secret secret
No official seeding method for ISAAC has been published, but for this task
we may as well just inject the bytes of our key into the randrsl array,
padding with zeroes before mixing, like so:
// zeroise mm array
FOR i:= 0 TO 255 DO mm[i]:=0;
// check seed's highest array element
m := High(seed);
// inject the seed
FOR i:= 0 TO 255 DO BEGIN
// in case seed[] has less than 256 elements.
IF i>m THEN randrsl[i]:=0
ELSE randrsl[i]:=seed[i];
END;
// initialize ISAAC with seed
RandInit(true);
ISAAC can of course also be initialized with a single 32-bit unsigned integer in the manner of traditional RNGs, and indeed used as such for research and gaming purposes.
But building a strong and simple ISAAC-based stream cipher - replacing the irreparably broken RC4 - is our goal here: ISAAC's intended purpose.
| #Nim | Nim | import strutils
type
IMode = enum iEncrypt, iDecrypt
State = object
# Internal.
mm: array[256, uint32]
aa, bb, cc: uint32
# External.
randrsl: array[256, uint32]
randcnt: uint32
proc isaac(s: var State) =
inc s.cc # "cc" just gets incremented once per 256 results
s.bb += s.cc # then combined with "bb".
for i in 0u32..255:
let x = s.mm[i]
case range[0..3](i and 3)
of 0: s.aa = s.aa xor s.aa shl 13
of 1: s.aa = s.aa xor s.aa shr 6
of 2: s.aa = s.aa xor s.aa shl 2
of 3: s.aa = s.aa xor s.aa shr 16
s.aa += s.mm[(i + 128) and 255]
let y = s.mm[(x shr 2) and 255] + s.aa + s.bb
s.mm[i] = y
s.bb = s.mm[(y shr 10) and 255] + x
s.randrsl[i] = s.bb
s.randcnt = 0
proc mix(a: var array[8, uint32]) =
a[0] = a[0] xor a[1] shl 11; a[3] += a[0]; a[1] += a[2]
a[1] = a[1] xor a[2] shr 2; a[4] += a[1]; a[2] += a[3]
a[2] = a[2] xor a[3] shl 8; a[5] += a[2]; a[3] += a[4]
a[3] = a[3] xor a[4] shr 16; a[6] += a[3]; a[4] += a[5]
a[4] = a[4] xor a[5] shl 10; a[7] += a[4]; a[5] += a[6]
a[5] = a[5] xor a[6] shr 4; a[0] += a[5]; a[6] += a[7]
a[6] = a[6] xor a[7] shl 8; a[1] += a[6]; a[7] += a[0]
a[7] = a[7] xor a[0] shr 9; a[2] += a[7]; a[0] += a[1]
proc iRandInit(s: var State; flag: bool) =
s.aa = 0; s.bb = 0; s.cc = 0
var a: array[8, uint32]
for item in a.mitems: item = 0x9e3779b9u32 # The golden ratio.
for i in 0..3: # Scramble it.
a.mix()
var i = 0u32
while true: # Fill in "mm" with messy stuff.
if flag:
# Use all the information in the seed.
for n in 0u32..7: a[n] += s.randrsl[n + i]
a.mix()
for n in 0u32..7: s.mm[n + i] = a[n]
inc i, 8
if i > 255: break
if flag:
# Do a second pass to make all of the seed affect all of "mm".
i = 0
while true:
for n in 0u32..7: a[n] += s.mm[n + i]
a.mix()
for n in 0u32..7: s.mm[n + i] = a[n]
inc i, 8
if i > 255: break
s.isaac() # Fill in the first set of results.
s.randcnt = 0 # Prepare to use the first set of results.
proc iSeed(s: var State; seed: string; flag: bool) =
## Seed ISAAC with a given string.
## The string can be any size. The first 256 values will be used.
s.mm.reset()
let m = seed.high
for i in 0..255:
s.randrsl[i] = if i > m: 0 else: ord(seed[i])
# Initialize ISAAC with seed.
s.iRandInit(flag)
proc iRandom(s: var State): uint32 =
## Get a random 32-bit value 0..int32.high.
result = s.randrsl[s.randcnt]
inc s.randcnt
if s.randcnt > 255:
s.isaac()
s.randcnt = 0
proc iRandA(s: var State): byte =
## Get a random character in printable ASCII range.
result = byte(s.iRandom() mod 95 + 32)
proc vernam(s: var State; msg: string): string =
## XOR encrypt on random stream. Output: ASCII string.
result.setLen(msg.len)
for i, c in msg:
result[i] = chr(s.irandA() xor byte(c))
template letterNum(letter, start: char): int =
ord(letter) - ord(start)
proc caesar(m: IMode; ch: char; shift, modulo: int; start: char): char =
let shift = if m == iEncrypt: shift else: -shift
var n = letterNum(ch, start) + shift
n = n mod modulo
if n < 0: inc n, modulo
result = chr(ord(start) + n)
proc vigenere(s: var State; msg: string; m: IMode): string =
## Vigenere MOD 95 encryption & decryption. Output: ASCII string.
result.setLen(msg.len)
for i, c in msg:
result[i] = caesar(m, c, s.iRanda().int, 95, ' ')
let
msg = "a Top Secret secret"
key = "this is my secret key"
var state: State
# 1) seed ISAAC with the key
state.iSeed(key, true)
# 2) Encryption
# a) XOR (Vernam)
let xctx = state.vernam(msg) # XOR ciphertext.
# b) MOD (Vigenere)
let mctx = state.vigenere(msg, iEncrypt) # MOD ciphertext.
# 3) Decryption
state.iSeed(key, true)
# a) XOR (Vernam)
let xptx = state.vernam(xctx) # XOR decryption (plaintext).
# b) MOD (Vigenere)
let mptx = state.vigenere(mctx, iDecrypt) # MOD decryption (plaintext).
# Program output
echo "Message: ", msg
echo " Key: ", key
echo " XOR: ", xctx.tohex
echo " MOD: ", mctx.toHex
echo "XOR dcr: ", xptx
echo "MOD dcr: ", mptx |
http://rosettacode.org/wiki/Test_integerness | Test integerness | Mathematically,
the integers Z are included in the rational numbers Q,
which are included in the real numbers R,
which can be generalized to the complex numbers C.
This means that each of those larger sets, and the data types used to represent them, include some integers.
Task[edit]
Given a rational, real, or complex number of any type, test whether it is mathematically an integer.
Your code should handle all numeric data types commonly used in your programming language.
Discuss any limitations of your code.
Definition
For the purposes of this task, integerness means that a number could theoretically be represented as an integer at no loss of precision (given an infinitely wide integer type).
In other words:
Set
Common representation
C++ type
Considered an integer...
rational numbers Q
fraction
std::ratio
...if its denominator is 1 (in reduced form)
real numbers Z
(approximated)
fixed-point
...if it has no non-zero digits after the decimal point
floating-point
float, double
...if the number of significant decimal places of its mantissa isn't greater than its exponent
complex numbers C
pair of real numbers
std::complex
...if its real part is considered an integer and its imaginary part is zero
Extra credit
Optionally, make your code accept a tolerance parameter for fuzzy testing. The tolerance is the maximum amount by which the number may differ from the nearest integer, to still be considered an integer.
This is useful in practice, because when dealing with approximate numeric types (such as floating point), there may already be round-off errors from previous calculations. For example, a float value of 0.9999999998 might actually be intended to represent the integer 1.
Test cases
Input
Output
Comment
Type
Value
exact
tolerance = 0.00001
decimal
25.000000
true
24.999999
false
true
25.000100
false
floating-point
-2.1e120
true
This one is tricky, because in most languages it is too large to fit into a native integer type.
It is, nonetheless, mathematically an integer, and your code should identify it as such.
-5e-2
false
NaN
false
Inf
false
This one is debatable. If your code considers it an integer, that's okay too.
complex
5.0+0.0i
true
5-5i
false
(The types and notations shown in these tables are merely examples – you should use the native data types and number literals of your programming language and standard library. Use a different set of test-cases, if this one doesn't demonstrate all relevant behavior.)
| #Pascal | Pascal | program integerness(output);
{ determines whether a `complex` also fits in `integer` ---------------- }
function isRealIntegral(protected x: complex): Boolean;
begin
{ It constitutes an error if no value for `trunc(x)` exists, }
{ thus check re(x) is in the range -maxInt..maxInt first. }
isRealIntegral := (im(x) = 0.0) and_then
(abs(re(x)) <= maxInt * 1.0) and_then
(trunc(re(x)) * 1.0 = re(x))
end;
{ calls isRealIntegral with zero imaginary part ------------------------ }
function isIntegral(protected x: real): Boolean;
begin
isIntegral := isRealIntegral(cmplx(x * 1.0, 0.0))
end;
{ Rosetta code test ---------------------------------------------------- }
procedure test(protected x: complex);
begin
writeLn(re(x), ' + ', im(x), ' 𝒾 : ',
isIntegral(re(x)), ' ', isRealIntegral(x))
end;
{ === MAIN ============================================================= }
begin
test(cmplx(25.0, 0.0));
test(cmplx(24.999999, 0.0));
test(cmplx(25.000100, 0.0));
test(cmplx(-2.1E120, 0.0));
test(cmplx(-5E-2, 0.0));
test(cmplx(5.0, 0.0));
test(cmplx(5, -5));
end. |
http://rosettacode.org/wiki/Text_processing/Max_licenses_in_use | Text processing/Max licenses in use | A company currently pays a fixed sum for the use of a particular licensed software package. In determining if it has a good deal it decides to calculate its maximum use of the software from its license management log file.
Assume the software's licensing daemon faithfully records a checkout event when a copy of the software starts and a checkin event when the software finishes to its log file.
An example of checkout and checkin events are:
License OUT @ 2008/10/03_23:51:05 for job 4974
...
License IN @ 2008/10/04_00:18:22 for job 4974
Task
Save the 10,000 line log file from here into a local file, then write a program to scan the file extracting both the maximum licenses that were out at any time, and the time(s) at which this occurs.
Mirror of log file available as a zip here (offsite mirror).
| #PL.2FI | PL/I |
text3: procedure options (main); /* 19 November 2011 */
declare line character (80) varying;
declare (nout, max_nout) fixed;
declare saveline character (80) varying controlled;
declare k fixed binary;
declare in file input;
open file (in) title ('/TEXT-MAX.DAT,TYPE(TEXT),RECSIZE(80)' );
on endfile (in) go to finish_up;
max_nout, nout = 0;
do forever;
get file (in) edit (line) (L);
if substr(line, 9, 4) = 'OUT' then nout = nout+1;
else if substr(line, 9, 3) = 'IN' then
nout = nout-1;
if nout = max_nout then
do; allocate saveline; saveline = line; end;
if nout > max_nout then
do;
do while (allocation(saveline) > 0); free saveline; end;
max_nout = nout;
allocate saveline;
saveline = line;
end;
end;
finish_up:
put skip list ('The maximum number of licences taken out = ' || max_nout);
do while (allocation(saveline) > 0);
k = index(saveline, '@');
if k > 0 then put skip list ('It occurred at ' || substr(saveline, k+1) );
free saveline;
end;
end text3;
|
http://rosettacode.org/wiki/Test_a_function | Test a function |
Task
Using a well-known testing-specific library/module/suite for your language, write some tests for your language's entry in Palindrome.
If your language does not have a testing specific library well known to the language's community then state this or omit the language.
| #Lasso | Lasso | // Taken from the Lasso entry in Palindrome page
define isPalindrome(text::string) => {
local(_text = string(#text)) // need to make copy to get rid of reference issues
#_text -> replace(regexp(`(?:$|\W)+`), -ignorecase)
local(reversed = string(#_text))
#reversed -> reverse
return #_text == #reversed
}
// The tests
describe(::isPalindrome) => {
it(`throws an error when not passed a string`) => {
expect->error =>{
isPalindrome(43)
}
}
it(`returns true if the string is the same forward and backwords`) => {
expect(isPalindrome('abba'))
}
it(`returns false if the string is different forward and backwords`) => {
expect(not isPalindrome('aab'))
}
it(`ignores spaces and punctuation`) => {
expect(isPalindrome(`Madam, I'm Adam`))
}
}
// Run the tests and get the summary
// (This normally isn't in the code as the test suite is run via command-line.)
lspec->stop |
http://rosettacode.org/wiki/Test_a_function | Test a function |
Task
Using a well-known testing-specific library/module/suite for your language, write some tests for your language's entry in Palindrome.
If your language does not have a testing specific library well known to the language's community then state this or omit the language.
| #Lua | Lua | assert( ispalindrome("ABCBA") )
assert( ispalindrome("ABCDE") ) |
http://rosettacode.org/wiki/Terminal_control/Ringing_the_terminal_bell | Terminal control/Ringing the terminal bell |
Task
Make the terminal running the program ring its "bell".
On modern terminal emulators, this may be done by playing some other sound which might or might not be configurable, or by flashing the title bar or inverting the colors of the screen, but was classically a physical bell within the terminal. It is usually used to indicate a problem where a wrong character has been typed.
In most terminals, if the Bell character (ASCII code 7, \a in C) is printed by the program, it will cause the terminal to ring its bell. This is a function of the terminal, and is independent of the programming language of the program, other than the ability to print a particular character to standard out.
| #UNIX_Shell | UNIX Shell | #!/bin/sh
# Ring the terminal bell
# echo "\a" # does not work in some shells
tput bel |
http://rosettacode.org/wiki/Terminal_control/Ringing_the_terminal_bell | Terminal control/Ringing the terminal bell |
Task
Make the terminal running the program ring its "bell".
On modern terminal emulators, this may be done by playing some other sound which might or might not be configurable, or by flashing the title bar or inverting the colors of the screen, but was classically a physical bell within the terminal. It is usually used to indicate a problem where a wrong character has been typed.
In most terminals, if the Bell character (ASCII code 7, \a in C) is printed by the program, it will cause the terminal to ring its bell. This is a function of the terminal, and is independent of the programming language of the program, other than the ability to print a particular character to standard out.
| #Wren | Wren | System.print("\a") |
http://rosettacode.org/wiki/Terminal_control/Ringing_the_terminal_bell | Terminal control/Ringing the terminal bell |
Task
Make the terminal running the program ring its "bell".
On modern terminal emulators, this may be done by playing some other sound which might or might not be configurable, or by flashing the title bar or inverting the colors of the screen, but was classically a physical bell within the terminal. It is usually used to indicate a problem where a wrong character has been typed.
In most terminals, if the Bell character (ASCII code 7, \a in C) is printed by the program, it will cause the terminal to ring its bell. This is a function of the terminal, and is independent of the programming language of the program, other than the ability to print a particular character to standard out.
| #X86_Assembly | X86 Assembly | ;Assemble with: tasm; tlink /t
.model tiny
.code
org 100h ;.com files start here
start: mov ah, 02h ;character output
mov dl, 07h ;bell code
int 21h ;call MS-DOS
ret ;return to MS-DOS
end start |
http://rosettacode.org/wiki/Terminal_control/Ringing_the_terminal_bell | Terminal control/Ringing the terminal bell |
Task
Make the terminal running the program ring its "bell".
On modern terminal emulators, this may be done by playing some other sound which might or might not be configurable, or by flashing the title bar or inverting the colors of the screen, but was classically a physical bell within the terminal. It is usually used to indicate a problem where a wrong character has been typed.
In most terminals, if the Bell character (ASCII code 7, \a in C) is printed by the program, it will cause the terminal to ring its bell. This is a function of the terminal, and is independent of the programming language of the program, other than the ability to print a particular character to standard out.
| #XPL0 | XPL0 | code ChOut=8;
ChOut(0,7) |
http://rosettacode.org/wiki/Terminal_control/Ringing_the_terminal_bell | Terminal control/Ringing the terminal bell |
Task
Make the terminal running the program ring its "bell".
On modern terminal emulators, this may be done by playing some other sound which might or might not be configurable, or by flashing the title bar or inverting the colors of the screen, but was classically a physical bell within the terminal. It is usually used to indicate a problem where a wrong character has been typed.
In most terminals, if the Bell character (ASCII code 7, \a in C) is printed by the program, it will cause the terminal to ring its bell. This is a function of the terminal, and is independent of the programming language of the program, other than the ability to print a particular character to standard out.
| #zkl | zkl | print("\x07"); |
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
| #C.23 | C# | using System;
public class TwelveDaysOfChristmas {
public static void Main() {
string[] days = new string[12] {
"first", "second", "third", "fourth", "fifth", "sixth", "seventh", "eighth", "ninth",
"tenth", "eleventh", "twelfth",
};
string[] gifts = new string[12] {
"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"
};
for ( int i = 0; i < 12; i++ ) {
Console.WriteLine("On the " + days[i] + " day of Christmas, my true love gave to me");
int j = i + 1;
while ( j-- > 0 )
Console.WriteLine(gifts[j]);
Console.WriteLine();
if ( i == 0 )
gifts[0] = "And a partridge in a pear tree";
}
}
} |
http://rosettacode.org/wiki/Terminal_control/Inverse_video | Terminal control/Inverse video | Task
Display a word in inverse video (or reverse video) followed by a word in normal video.
| #Z80_Assembly | Z80 Assembly | .org &8000
PrintChar equ &BB5A
InvertTextColors equ &BB9C
;main
call InvertTextColors
ld hl, HelloAddr
call PrintString
call InvertTextColors
ld hl,HelloAddr
jp PrintString ;and return to basic after that.
HelloAddr: byte "Hello",0
PrintString:
ld a,(hl)
or a
ret z
call PrintChar
inc hl
jp PrintString |
http://rosettacode.org/wiki/Terminal_control/Inverse_video | Terminal control/Inverse video | Task
Display a word in inverse video (or reverse video) followed by a word in normal video.
| #zkl | zkl | println("\e[7mReversed\e[m Normal"); |
http://rosettacode.org/wiki/Terminal_control/Dimensions | Terminal control/Dimensions | Determine the height and width of the terminal, and store this information into variables for subsequent use.
| #Go | Go | package main
import (
"fmt"
"os"
"golang.org/x/crypto/ssh/terminal"
)
func main() {
w, h, err := terminal.GetSize(int(os.Stdout.Fd()))
if err != nil {
fmt.Println(err)
return
}
fmt.Println(h, w)
} |
http://rosettacode.org/wiki/Terminal_control/Dimensions | Terminal control/Dimensions | Determine the height and width of the terminal, and store this information into variables for subsequent use.
| #J | J | _2 {.qsmsize_jijs_'' |
http://rosettacode.org/wiki/Terminal_control/Coloured_text | Terminal control/Coloured text | Task
Display a word in various colours on the terminal.
The system palette, or colours such as Red, Green, Blue, Magenta, Cyan, and Yellow can be used.
Optionally demonstrate:
How the system should determine if the terminal supports colour
Setting of the background colour
How to cause blinking or flashing (if supported by the terminal)
| #AArch64_Assembly | AArch64 Assembly |
/* ARM assembly AARCH64 Raspberry PI 3B */
/* program colorterminal64.s */
/*******************************************/
/* Constantes file */
/*******************************************/
/* for this file see task include a file in language AArch64 assembly*/
.include "../includeConstantesARM64.inc"
/*******************************************/
/* Initialized data */
/*******************************************/
.data
szMessStartPgm: .asciz "Program start \n"
szMessEndPgm: .asciz "Program normal end.\n"
szMessColorRed: .asciz "Color red.\n"
szCodeInit: .asciz "\033[0m" //color reinit
szCodeRed: .asciz "\033[31m" //color red
szMessBlue: .asciz "\033[34mColor Blue\n" //color blue
szMessTwoColor: .asciz "\033[32mColor Green \033[35m Color Velvet\n"
szMessTest: .asciz "\033[33m\033[1mMessage yellow bold\n"
szCarriageReturn: .asciz "\n"
/*******************************************/
/* UnInitialized data */
/*******************************************/
.bss
/*******************************************/
/* code section */
/*******************************************/
.text
.global main
main:
ldr x0,qAdrszMessStartPgm //display start message
bl affichageMess
ldr x0,qAdrszCodeRed //color red
bl affichageMess
ldr x0,qAdrszMessColorRed
bl affichageMess
ldr x0,qAdrszMessBlue //message color blue
bl affichageMess
ldr x0,qAdrszMessTwoColor //message two colors
bl affichageMess
ldr x0,qAdrszMessTest
bl affichageMess
ldr x0,qAdrszCodeInit //color reinitialize
bl affichageMess
ldr x0,qAdrszMessEndPgm //display end message
bl affichageMess
100: //standard end of the program
mov x0,0 //return code
mov x8,EXIT //request to exit program
svc 0 //perform system call
qAdrszMessStartPgm: .quad szMessStartPgm
qAdrszMessEndPgm: .quad szMessEndPgm
qAdrszCodeInit: .quad szCodeInit
qAdrszCodeRed: .quad szCodeRed
qAdrszMessBlue: .quad szMessBlue
qAdrszMessColorRed: .quad szMessColorRed
qAdrszMessTwoColor: .quad szMessTwoColor
qAdrszMessTest: .quad szMessTest
qAdrszCarriageReturn: .quad szCarriageReturn
/********************************************************/
/* File Include fonctions */
/********************************************************/
/* for this file see task include a file in language AArch64 assembly */
.include "../includeARM64.inc"
|
http://rosettacode.org/wiki/Terminal_control/Coloured_text | Terminal control/Coloured text | Task
Display a word in various colours on the terminal.
The system palette, or colours such as Red, Green, Blue, Magenta, Cyan, and Yellow can be used.
Optionally demonstrate:
How the system should determine if the terminal supports colour
Setting of the background colour
How to cause blinking or flashing (if supported by the terminal)
| #Ada | Ada | with Ada.Text_Io;
with Ansi;
procedure Coloured is
use Ada.Text_Io;
subtype Ansi_Colors is Ansi.Colors
range Ansi.Black .. Ansi.Colors'Last; -- Avoid default
begin
for Fg_Color in Ansi_Colors loop
Put ("Rosetta ");
Put (Ansi.Foreground (Fg_Color));
for Bg_Color in Ansi_Colors loop
Put (Ansi.Background (Bg_Color));
Put ("Code");
end loop;
Put (Ansi.Reset);
New_Line;
end loop;
end Coloured; |
http://rosettacode.org/wiki/Terminal_control/Cursor_movement | Terminal control/Cursor movement | Task
Demonstrate how to achieve movement of the terminal cursor:
how to move the cursor one position to the left
how to move the cursor one position to the right
how to move the cursor up one line (without affecting its horizontal position)
how to move the cursor down one line (without affecting its horizontal position)
how to move the cursor to the beginning of the line
how to move the cursor to the end of the line
how to move the cursor to the top left corner of the screen
how to move the cursor to the bottom right corner of the screen
For the purpose of this task, it is not permitted to overwrite any characters or attributes on any part of the screen (so outputting a space is not a suitable solution to achieve a movement to the right).
Handling of out of bounds locomotion
This task has no specific requirements to trap or correct cursor movement beyond the terminal boundaries, so the implementer should decide what behavior fits best in terms of the chosen language. Explanatory notes may be added to clarify how an out of bounds action would behave and the generation of error messages relating to an out of bounds cursor position is permitted.
| #AutoHotkey | AutoHotkey | DllCall("AllocConsole")
hConsole:=DllCall("GetConsoleWindow","UPtr")
Stdout:=FileOpen(DllCall("GetStdHandle", "int", -11, "ptr"), "h `n")
Stdin:=FileOpen(DllCall("GetStdHandle", "int", -10, "ptr"), "h `n")
;move the cursor one position to the left
GetPos(x,y)
SetPos(x-1)
;move the cursor one position to the right
GetPos(x,y)
SetPos(x+1)
;move the cursor up one line (without affecting its horizontal position)
GetPos(x,y)
SetPos(x,y-1)
;move the cursor down one line (without affecting its horizontal position)
GetPos(x,y)
SetPos(x,y+1)
;move the cursor to the beginning of the line
GetPos(x,y)
SetPos(0,y)
;move the cursor to the end of the line
;requires previous knowledge of screen width -- typically 80
SetPos(79) ;minus 1 because origin is (0,0)
;move the cursor to the top left corner of the screen
SetPos(0,0)
;move the cursor to the bottom right corner of the screen
GetConsoleSize(w,h)
SetPos(w-1,h-1) ;minus 1 because origin is (0,0)
GetPos(ByRef x, ByRef y) {
global Stdout
VarSetCapacity(struct,22,0)
e:=DllCall("GetConsoleScreenBufferInfo","UPtr",Stdout.__Handle,"Ptr",&struct)
if (!e) or (ErrorLevel)
return 0 ;Failure
x:=NumGet(&struct,4,"UShort")
y:=NumGet(&struct,6,"UShort")
return 1
}
SetPos(x="",y="") {
global Stdout
GetPos(ox,oy)
if x is not Integer
x:=ox
if y is not Integer
y:=oy
VarSetCapacity(struct,4,0)
Numput(x,struct,"UShort")
Numput(y,struct,2,"UShort")
e:=DllCall("SetConsoleCursorPosition","Ptr",Stdout.__Handle,"uint",Numget(struct,"uint"))
if (!e) or (ErrorLevel)
return 0 ;Failure
return 1
}
GetConsoleSize(ByRef bufferwidth, ByRef bufferheight) {
global Stdout
VarSetCapacity(struct,22,0)
x:=DllCall("GetConsoleScreenBufferInfo","UPtr",Stdout.__Handle,"Ptr",&struct)
if (!x) or (ErrorLevel)
return 0 ;Failure
bufferwidth:=NumGet(&struct,"UShort")
bufferheight:=NumGet(&struct,2,"UShort")
return 1
} |
http://rosettacode.org/wiki/Terminal_control/Cursor_positioning | Terminal control/Cursor positioning |
Task
Move the cursor to column 3, row 6, and display the word "Hello" (without the quotes), so that the letter H is in column 3 on row 6.
| #Forth | Forth | 2 5 at-xy ." Hello" |
http://rosettacode.org/wiki/Terminal_control/Cursor_positioning | Terminal control/Cursor positioning |
Task
Move the cursor to column 3, row 6, and display the word "Hello" (without the quotes), so that the letter H is in column 3 on row 6.
| #Fortran | Fortran | program textposition
use kernel32
implicit none
integer(HANDLE) :: hConsole
integer(BOOL) :: q
hConsole = GetStdHandle(STD_OUTPUT_HANDLE)
q = SetConsoleCursorPosition(hConsole, T_COORD(3, 6))
q = WriteConsole(hConsole, loc("Hello"), 5, NULL, NULL)
end program |
http://rosettacode.org/wiki/Terminal_control/Cursor_positioning | Terminal control/Cursor positioning |
Task
Move the cursor to column 3, row 6, and display the word "Hello" (without the quotes), so that the letter H is in column 3 on row 6.
| #FreeBASIC | FreeBASIC | Locate 6, 3 : Print "Hello"
Sleep |
http://rosettacode.org/wiki/Terminal_control/Cursor_positioning | Terminal control/Cursor positioning |
Task
Move the cursor to column 3, row 6, and display the word "Hello" (without the quotes), so that the letter H is in column 3 on row 6.
| #Go | Go | package main
import (
"bytes"
"fmt"
"os"
"os/exec"
)
func main() {
cmd := exec.Command("tput", "-S")
cmd.Stdin = bytes.NewBufferString("clear\ncup 5 2")
cmd.Stdout = os.Stdout
cmd.Run()
fmt.Println("Hello")
} |
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
| #C.2B.2B | C++ | #include <iostream>
#include <stdlib.h>
class trit {
public:
static const trit False, Maybe, True;
trit operator !() const {
return static_cast<Value>(-value);
}
trit operator &&(const trit &b) const {
return (value < b.value) ? value : b.value;
}
trit operator ||(const trit &b) const {
return (value > b.value) ? value : b.value;
}
trit operator >>(const trit &b) const {
return -value > b.value ? static_cast<Value>(-value) : b.value;
}
trit operator ==(const trit &b) const {
return static_cast<Value>(value * b.value);
}
char chr() const {
return "F?T"[value + 1];
}
protected:
typedef enum { FALSE=-1, MAYBE, TRUE } Value;
Value value;
trit(const Value value) : value(value) { }
};
std::ostream& operator<<(std::ostream &os, const trit &t)
{
os << t.chr();
return os;
}
const trit trit::False = trit(trit::FALSE);
const trit trit::Maybe = trit(trit::MAYBE);
const trit trit::True = trit(trit::TRUE);
int main(int, char**) {
const trit trits[3] = { trit::True, trit::Maybe, trit::False };
#define for_each(name) \
for (size_t name=0; name<3; ++name)
#define show_op(op) \
std::cout << std::endl << #op << " "; \
for_each(a) std::cout << ' ' << trits[a]; \
std::cout << std::endl << " -------"; \
for_each(a) { \
std::cout << std::endl << trits[a] << " |"; \
for_each(b) std::cout << ' ' << (trits[a] op trits[b]); \
} \
std::cout << std::endl;
std::cout << "! ----" << std::endl;
for_each(a) std::cout << trits[a] << " | " << !trits[a] << std::endl;
show_op(&&);
show_op(||);
show_op(>>);
show_op(==);
return EXIT_SUCCESS;
} |
http://rosettacode.org/wiki/Terminal_control/Display_an_extended_character | Terminal control/Display an extended character | Task
Display an extended (non ASCII) character onto the terminal.
Specifically, display a £ (GBP currency sign).
| #Objeck | Objeck | class Program {
function : Main(args : String[]) ~ Nil {
"£"->PrintLine();
}
} |
http://rosettacode.org/wiki/Terminal_control/Display_an_extended_character | Terminal control/Display an extended character | Task
Display an extended (non ASCII) character onto the terminal.
Specifically, display a £ (GBP currency sign).
| #Pascal | Pascal | program pound;
uses crt;
begin
write(chr( 163 ));
end.
|
http://rosettacode.org/wiki/Terminal_control/Display_an_extended_character | Terminal control/Display an extended character | Task
Display an extended (non ASCII) character onto the terminal.
Specifically, display a £ (GBP currency sign).
| #Perl | Perl | use feature 'say';
# OK as is
say '£';
# these need 'binmode needed to surpress warning about 'wide' char
binmode STDOUT, ":utf8";
say "\N{FULLWIDTH POUND SIGN}";
say "\x{FFE1}";
say chr 0xffe1; |
http://rosettacode.org/wiki/Terminal_control/Display_an_extended_character | Terminal control/Display an extended character | Task
Display an extended (non ASCII) character onto the terminal.
Specifically, display a £ (GBP currency sign).
| #Phix | Phix | puts(1,"£")
|
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.
| #Common_Lisp | Common Lisp | (defvar *invalid-count*)
(defvar *max-invalid*)
(defvar *max-invalid-date*)
(defvar *total-sum*)
(defvar *total-valid*)
(defun read-flag (stream date)
(let ((flag (read stream)))
(if (plusp flag)
(setf *invalid-count* 0)
(when (< *max-invalid* (incf *invalid-count*))
(setf *max-invalid* *invalid-count*)
(setf *max-invalid-date* date)))
flag))
(defun parse-line (line)
(with-input-from-string (s line)
(let ((date (make-string 10)))
(read-sequence date s)
(cons date (loop repeat 24 collect (list (read s)
(read-flag s date)))))))
(defun analyze-line (line)
(destructuring-bind (date &rest rest) line
(let* ((valid (remove-if-not #'plusp rest :key #'second))
(n (length valid))
(sum (apply #'+ (mapcar #'rationalize (mapcar #'first valid))))
(avg (if valid (/ sum n) 0)))
(incf *total-valid* n)
(incf *total-sum* sum)
(format t "Line: ~a Reject: ~2d Accept: ~2d ~
Line_tot: ~8,3f Line_avg: ~7,3f~%"
date (- 24 n) n sum avg))))
(defun process (pathname)
(let ((*invalid-count* 0) (*max-invalid* 0) *max-invalid-date*
(*total-sum* 0) (*total-valid* 0))
(with-open-file (f pathname)
(loop for line = (read-line f nil nil)
while line
do (analyze-line (parse-line line))))
(format t "~%File = ~a" pathname)
(format t "~&Total = ~f" *total-sum*)
(format t "~&Readings = ~a" *total-valid*)
(format t "~&Average = ~10,3f~%" (/ *total-sum* *total-valid*))
(format t "~%Maximum run(s) of ~a consecutive false readings ends at ~
line starting with date(s): ~a~%"
*max-invalid* *max-invalid-date*))) |
http://rosettacode.org/wiki/The_ISAAC_Cipher | The ISAAC Cipher | ISAAC is a cryptographically secure pseudo-random number generator (CSPRNG) and stream cipher. It was developed by Bob Jenkins from 1993 (http://burtleburtle.net/bob/rand/isaac.html) and placed in the Public Domain. ISAAC is fast - especially when optimised - and portable to most architectures in nearly all programming and scripting languages.
It is also simple and succinct, using as it does just two 256-word arrays for its state.
ISAAC stands for "Indirection, Shift, Accumulate, Add, and Count" which are the principal bitwise operations employed.
To date - and that's after more than 20 years of existence - ISAAC has not been broken (unless GCHQ or NSA did it, but they wouldn't be telling).
ISAAC thus deserves a lot more attention than it has hitherto received and it would be salutary to see it more universally implemented.
Task
Translate ISAAC's reference C or Pascal code into your language of choice.
The RNG should then be seeded with the string "this is my secret key" and
finally the message "a Top Secret secret" should be encrypted on that key.
Your program's output cipher-text will be a string of hexadecimal digits.
Optional: Include a decryption check by re-initializing ISAAC and performing
the same encryption pass on the cipher-text.
Please use the C or Pascal as a reference guide to these operations.
Two encryption schemes are possible:
(1) XOR (Vernam) or
(2) Caesar-shift mod 95 (Vigenère).
XOR is the simplest; C-shifting offers greater security.
You may choose either scheme, or both, but please specify which you used.
Here are the alternative sample outputs for checking purposes:
Message: a Top Secret secret
Key : this is my secret key
XOR : 1C0636190B1260233B35125F1E1D0E2F4C5422
MOD : 734270227D36772A783B4F2A5F206266236978
XOR dcr: a Top Secret secret
MOD dcr: a Top Secret secret
No official seeding method for ISAAC has been published, but for this task
we may as well just inject the bytes of our key into the randrsl array,
padding with zeroes before mixing, like so:
// zeroise mm array
FOR i:= 0 TO 255 DO mm[i]:=0;
// check seed's highest array element
m := High(seed);
// inject the seed
FOR i:= 0 TO 255 DO BEGIN
// in case seed[] has less than 256 elements.
IF i>m THEN randrsl[i]:=0
ELSE randrsl[i]:=seed[i];
END;
// initialize ISAAC with seed
RandInit(true);
ISAAC can of course also be initialized with a single 32-bit unsigned integer in the manner of traditional RNGs, and indeed used as such for research and gaming purposes.
But building a strong and simple ISAAC-based stream cipher - replacing the irreparably broken RC4 - is our goal here: ISAAC's intended purpose.
| #Pascal | Pascal |
PROGRAM RosettaIsaac;
USES
StrUtils;
TYPE
iMode = (iEncrypt, iDecrypt);
// TASK globals
VAR
msg : String = 'a Top Secret secret';
key : String = 'this is my secret key';
xctx: String = ''; // XOR ciphertext
mctx: String = ''; // MOD ciphertext
xptx: String = ''; // XOR decryption (plaintext)
mptx: String = ''; // MOD decryption (plaintext)
// ISAAC globals
VAR
// external results
randrsl: ARRAY[0 .. 255] OF Cardinal;
randcnt: Cardinal;
// internal state
mm: ARRAY[0 .. 255] OF Cardinal;
aa: Cardinal = 0;
bb: Cardinal = 0;
cc: Cardinal = 0;
PROCEDURE Isaac;
VAR
i, x, y: Cardinal;
BEGIN
cc := cc + 1; // cc just gets incremented once per 256 results
bb := bb + cc; // then combined with bb
FOR i := 0 TO 255 DO
BEGIN
x := mm[i];
CASE (i MOD 4) OF
0: aa := aa XOR (aa SHL 13);
1: aa := aa XOR (aa SHR 6);
2: aa := aa XOR (aa SHL 2);
3: aa := aa XOR (aa SHR 16);
END;
aa := mm[(i + 128) MOD 256] + aa;
y := mm[(x SHR 2) MOD 256] + aa + bb;
mm[i] := y;
bb := mm[(y SHR 10) MOD 256] + x;
randrsl[i] := bb;
END;
randcnt := 0; // prepare to use the first set of results
END; // Isaac
PROCEDURE Mix(VAR a, b, c, d, e, f, g, h: Cardinal);
BEGIN
a := a XOR b SHL 11; d := d + a; b := b + c;
b := b XOR c SHR 2; e := e + b; c := c + d;
c := c XOR d SHL 8; f := f + c; d := d + e;
d := d XOR e SHR 16; g := g + d; e := e + f;
e := e XOR f SHL 10; h := h + e; f := f + g;
f := f XOR g SHR 4; a := a + f; g := g + h;
g := g XOR h SHL 8; b := b + g; h := h + a;
h := h XOR a SHR 9; c := c + h; a := a + b;
END; // Mix
PROCEDURE iRandInit(flag: Boolean);
VAR
i, a, b, c, d, e, f, g, h: Cardinal;
BEGIN
aa := 0; bb := 0; cc := 0;
a := $9e3779b9; // the golden ratio
b := a; c := a; d := a; e := a; f := a; g := a; h := a;
FOR i := 0 TO 3 DO // scramble it
Mix(a, b, c, d, e, f, g, h);
i := 0;
REPEAT // fill in mm[] with messy stuff
IF flag THEN
BEGIN // use all the information in the seed
a += randrsl[i ]; b += randrsl[i + 1];
c += randrsl[i + 2]; d += randrsl[i + 3];
e += randrsl[i + 4]; f += randrsl[i + 5];
g += randrsl[i + 6]; h += randrsl[i + 7];
END;
Mix(a, b, c, d, e, f, g, h);
mm[i ] := a; mm[i + 1] := b; mm[i + 2] := c; mm[i + 3] := d;
mm[i + 4] := e; mm[i + 5] := f; mm[i + 6] := g; mm[i + 7] := h;
i += 8;
UNTIL i > 255;
IF flag THEN
BEGIN
// do a second pass to make all of the seed affect all of mm
i := 0;
REPEAT
a += mm[i ]; b += mm[i + 1]; c += mm[i + 2]; d += mm[i + 3];
e += mm[i + 4]; f += mm[i + 5]; g += mm[i + 6]; h += mm[i + 7];
Mix(a, b, c, d, e, f, g, h);
mm[i ] := a; mm[i + 1] := b; mm[i + 2] := c; mm[i + 3] := d;
mm[i + 4] := e; mm[i + 5] := f; mm[i + 6] := g; mm[i + 7] := h;
i += 8;
UNTIL i > 255;
END;
Isaac(); // fill in the first set of results
randcnt := 0; // prepare to use the first set of results
END; // iRandInit
// Seed ISAAC with a given string.
// The string can be any size. The first 256 values will be used.
PROCEDURE iSeed(seed: String; flag: Boolean);
VAR
i, m: Cardinal;
BEGIN
FOR i := 0 TO 255 DO
mm[i] := 0;
m := Length(seed) - 1;
FOR i := 0 TO 255 DO
BEGIN
// in case seed has less than 256 elements
IF i > m THEN
randrsl[i] := 0
// Pascal strings are 1-based
ELSE
randrsl[i] := Ord(seed[i + 1]);
END;
// initialize ISAAC with seed
iRandInit(flag);
END; // iSeed
// Get a random 32-bit value 0..MAXINT
FUNCTION iRandom: Cardinal;
BEGIN
iRandom := randrsl[randcnt];
inc(randcnt);
IF (randcnt > 255) THEN
BEGIN
Isaac;
randcnt := 0;
END;
END; // iRandom
// Get a random character in printable ASCII range
FUNCTION iRandA: Byte;
BEGIN
iRandA := iRandom MOD 95 + 32;
END;
// Convert an ASCII string to a hexadecimal string
FUNCTION Ascii2Hex(s: String): String;
VAR
i: Cardinal;
BEGIN
Ascii2Hex := '';
FOR i := 1 TO Length(s) DO
Ascii2Hex += Dec2Numb(Ord(s[i]), 2, 16);
END; // Ascii2Hex
// XOR encrypt on random stream. Output: ASCII string
FUNCTION Vernam(msg: String): String;
VAR
i: Cardinal;
BEGIN
Vernam := '';
FOR i := 1 to Length(msg) DO
Vernam += Chr(iRandA XOR Ord(msg[i]));
END; // Vernam
// Get position of the letter in chosen alphabet
FUNCTION LetterNum(letter, start: Char): Byte;
BEGIN
LetterNum := (Ord(letter) - Ord(start));
END; // LetterNum
// Caesar-shift a character <shift> places: Generalized Vigenere
FUNCTION Caesar(m: iMode; ch: Char; shift, modulo: Integer; start: Char): Char;
VAR
n: Integer;
BEGIN
IF m = iDecrypt THEN
shift := -shift;
n := LetterNum(ch, start) + shift;
n := n MOD modulo;
IF n < 0 THEN
n += modulo;
Caesar := Chr(Ord(start) + n);
END; // Caesar
// Vigenere MOD 95 encryption & decryption. Output: ASCII string
FUNCTION Vigenere(msg: String; m: iMode): String;
VAR
i: Cardinal;
BEGIN
Vigenere := '';
FOR i := 1 to Length(msg) DO
Vigenere += Caesar(m, msg[i], iRandA, 95, ' ');
END; // Vigenere
BEGIN
// 1) seed ISAAC with the key
iSeed(key, true);
// 2) Encryption
// a) XOR (Vernam)
xctx := Vernam(msg);
// b) MOD (Vigenere)
mctx := Vigenere(msg, iEncrypt);
// 3) Decryption
iSeed(key, true);
// a) XOR (Vernam)
xptx := Vernam(xctx);
// b) MOD (Vigenere)
mptx := Vigenere(mctx, iDecrypt);
// program output
Writeln('Message: ', msg);
Writeln('Key : ', key);
Writeln('XOR : ', Ascii2Hex(xctx));
Writeln('MOD : ', Ascii2Hex(mctx));
Writeln('XOR dcr: ', xptx);
Writeln('MOD dcr: ', mptx);
END.
|
http://rosettacode.org/wiki/Test_integerness | Test integerness | Mathematically,
the integers Z are included in the rational numbers Q,
which are included in the real numbers R,
which can be generalized to the complex numbers C.
This means that each of those larger sets, and the data types used to represent them, include some integers.
Task[edit]
Given a rational, real, or complex number of any type, test whether it is mathematically an integer.
Your code should handle all numeric data types commonly used in your programming language.
Discuss any limitations of your code.
Definition
For the purposes of this task, integerness means that a number could theoretically be represented as an integer at no loss of precision (given an infinitely wide integer type).
In other words:
Set
Common representation
C++ type
Considered an integer...
rational numbers Q
fraction
std::ratio
...if its denominator is 1 (in reduced form)
real numbers Z
(approximated)
fixed-point
...if it has no non-zero digits after the decimal point
floating-point
float, double
...if the number of significant decimal places of its mantissa isn't greater than its exponent
complex numbers C
pair of real numbers
std::complex
...if its real part is considered an integer and its imaginary part is zero
Extra credit
Optionally, make your code accept a tolerance parameter for fuzzy testing. The tolerance is the maximum amount by which the number may differ from the nearest integer, to still be considered an integer.
This is useful in practice, because when dealing with approximate numeric types (such as floating point), there may already be round-off errors from previous calculations. For example, a float value of 0.9999999998 might actually be intended to represent the integer 1.
Test cases
Input
Output
Comment
Type
Value
exact
tolerance = 0.00001
decimal
25.000000
true
24.999999
false
true
25.000100
false
floating-point
-2.1e120
true
This one is tricky, because in most languages it is too large to fit into a native integer type.
It is, nonetheless, mathematically an integer, and your code should identify it as such.
-5e-2
false
NaN
false
Inf
false
This one is debatable. If your code considers it an integer, that's okay too.
complex
5.0+0.0i
true
5-5i
false
(The types and notations shown in these tables are merely examples – you should use the native data types and number literals of your programming language and standard library. Use a different set of test-cases, if this one doesn't demonstrate all relevant behavior.)
| #Phix | Phix | ?integer(3.5+3.5) -- true
?integer(3.5+3.4) -- false
|
http://rosettacode.org/wiki/Test_integerness | Test integerness | Mathematically,
the integers Z are included in the rational numbers Q,
which are included in the real numbers R,
which can be generalized to the complex numbers C.
This means that each of those larger sets, and the data types used to represent them, include some integers.
Task[edit]
Given a rational, real, or complex number of any type, test whether it is mathematically an integer.
Your code should handle all numeric data types commonly used in your programming language.
Discuss any limitations of your code.
Definition
For the purposes of this task, integerness means that a number could theoretically be represented as an integer at no loss of precision (given an infinitely wide integer type).
In other words:
Set
Common representation
C++ type
Considered an integer...
rational numbers Q
fraction
std::ratio
...if its denominator is 1 (in reduced form)
real numbers Z
(approximated)
fixed-point
...if it has no non-zero digits after the decimal point
floating-point
float, double
...if the number of significant decimal places of its mantissa isn't greater than its exponent
complex numbers C
pair of real numbers
std::complex
...if its real part is considered an integer and its imaginary part is zero
Extra credit
Optionally, make your code accept a tolerance parameter for fuzzy testing. The tolerance is the maximum amount by which the number may differ from the nearest integer, to still be considered an integer.
This is useful in practice, because when dealing with approximate numeric types (such as floating point), there may already be round-off errors from previous calculations. For example, a float value of 0.9999999998 might actually be intended to represent the integer 1.
Test cases
Input
Output
Comment
Type
Value
exact
tolerance = 0.00001
decimal
25.000000
true
24.999999
false
true
25.000100
false
floating-point
-2.1e120
true
This one is tricky, because in most languages it is too large to fit into a native integer type.
It is, nonetheless, mathematically an integer, and your code should identify it as such.
-5e-2
false
NaN
false
Inf
false
This one is debatable. If your code considers it an integer, that's okay too.
complex
5.0+0.0i
true
5-5i
false
(The types and notations shown in these tables are merely examples – you should use the native data types and number literals of your programming language and standard library. Use a different set of test-cases, if this one doesn't demonstrate all relevant behavior.)
| #PicoLisp | PicoLisp |
(de int? (N)
(= N (* 1.0 (/ N 1.0)))) #returns T or NIL
(de integer? (N)
(and (= N (* 1.0 (/ N 1.0))) N)) #returns value of N or NIL
(scl 4) #-> 4 # *Scl the global which holds
1.0 #-> 10000
(int? 1.0) #-> T
(int? 1) #-> NIL # 1 with a scale of 4 is same as 0.0001 which is not an Integer
(int? -1.0) #-> T
(int? -0.0) #-> T
(int? "RE") #-> "RE" -- Number expected
(int? (*/ 2.0 1.0 3.0)) #-> NIL # 6667 is not an integer of the scale of 4, use of */ because of the scale
|
http://rosettacode.org/wiki/Text_processing/Max_licenses_in_use | Text processing/Max licenses in use | A company currently pays a fixed sum for the use of a particular licensed software package. In determining if it has a good deal it decides to calculate its maximum use of the software from its license management log file.
Assume the software's licensing daemon faithfully records a checkout event when a copy of the software starts and a checkin event when the software finishes to its log file.
An example of checkout and checkin events are:
License OUT @ 2008/10/03_23:51:05 for job 4974
...
License IN @ 2008/10/04_00:18:22 for job 4974
Task
Save the 10,000 line log file from here into a local file, then write a program to scan the file extracting both the maximum licenses that were out at any time, and the time(s) at which this occurs.
Mirror of log file available as a zip here (offsite mirror).
| #PowerShell | PowerShell |
[int]$count = 0
[int]$maxCount = 0
[datetime[]]$times = @()
$jobs = Get-Content -Path ".\mlijobs.txt" | ForEach-Object {
[string[]]$fields = $_.Split(" ",[StringSplitOptions]::RemoveEmptyEntries)
[datetime]$datetime = Get-Date $fields[3].Replace("_"," ")
[PSCustomObject]@{
State = $fields[1]
Date = $datetime
Job = $fields[6]
}
}
foreach ($job in $jobs)
{
switch ($job.State)
{
"IN"
{
$count--
}
"OUT"
{
$count++
if ($count -gt $maxCount)
{
$maxCount = $count
$times = @()
$times+= $job.Date
}
elseif ($count -eq $maxCount)
{
$times+= $job.Date
}
}
}
}
[PSCustomObject]@{
LicensesOut = $maxCount
StartTime = $times[0]
EndTime = $times[1]
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.