task_url
stringlengths 30
116
| task_name
stringlengths 2
86
| task_description
stringlengths 0
14.4k
| language_url
stringlengths 2
53
| language_name
stringlengths 1
52
| code
stringlengths 0
61.9k
|
---|---|---|---|---|---|
http://rosettacode.org/wiki/Text_processing/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.
| #R | R | # Read in data from file
dfr <- read.delim("d:/readings.txt", colClasses=c("character", rep(c("numeric", "integer"), 24)))
dates <- strptime(dfr[,1], "%Y-%m-%d")
# Any bad values?
dfr[which(is.na(dfr))]
# Any duplicated dates
dates[duplicated(dates)]
# Number of rows with no bad values
flags <- as.matrix(dfr[,seq(3,49,2)])>0
sum(apply(flags, 1, all)) |
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.
| #gnuplot | gnuplot | print "\007" |
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.
| #Go | Go | package main
import "fmt"
func main() {
fmt.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.
| #Groovy | Groovy | println '\7' |
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
| #Action.21 | Action! | PROC Wait(BYTE frames)
BYTE RTCLOK=$14
frames==+RTCLOK
WHILE frames#RTCLOK DO OD
RETURN
PROC Main()
DEFINE PTR="CARD"
PTR ARRAY num(12),obj(12)
BYTE i,j
num(0)="first" num(1)="second" num(2)="third"
num(3)="fourth" num(4)="fifth" num(5)="sixth"
num(6)="seventh" num(7)="eight" num(8)="ninth"
num(9)="tenth" num(10)="eleventh" num(11)="Twelfth"
obj(0)="And a partridge in a pear tree."
obj(1)="Two turtle doves"
obj(2)="Three french hens"
obj(3)="Four calling birds"
obj(4)="Five golden rings"
obj(5)="Six geese a-laying"
obj(6)="Seven swans a-swimming"
obj(7)="Eight maids a-milking"
obj(8)="Nine ladies dancing"
obj(9)="Ten lords a-leaping"
obj(10)="Eleven pipers piping"
obj(11)="Twelve drummers drumming"
FOR i=0 TO 11
DO
PrintF("On the %S day of Christmas,%E",num(i))
PrintE("My true love gave to me:")
IF i=0 THEN
PrintE("A partridge in a pear tree.")
ELSE
j=i+1
WHILE j>0
DO
j==-1
PrintE(obj(j))
OD
FI
PutE()
Wait(50)
OD
RETURN |
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
| #ActionScript | ActionScript | package {
import flash.display.Sprite;
import flash.events.Event;
import flash.events.KeyboardEvent;
import flash.events.MouseEvent;
import flash.text.TextField;
import flash.text.TextFieldAutoSize;
import flash.text.TextFormat;
import flash.ui.Keyboard;
public class TwelveDaysOfChristmas extends Sprite {
private var _textArea:TextField = new TextField();
public function TwelveDaysOfChristmas() {
if ( stage ) _init();
else addEventListener(Event.ADDED_TO_STAGE, _init);
}
private function _init(e:Event = null):void {
removeEventListener(Event.ADDED_TO_STAGE, _init);
_textArea = new TextField();
_textArea.x = 10;
_textArea.y = 10;
_textArea.autoSize = TextFieldAutoSize.LEFT;
_textArea.wordWrap = true;
_textArea.width = stage.stageWidth - 20;
_textArea.height = stage.stageHeight - 10;
_textArea.multiline = true;
var format:TextFormat = new TextFormat();
format.size = 14;
_textArea.defaultTextFormat = format;
var verses:Vector.<String> = new Vector.<String>(12, true);
var lines:Vector.<String>;
var days:Vector.<String> = new Vector.<String>(12, true);
var gifts:Vector.<String> = new Vector.<String>(12, true);
days[0] = 'first';
days[1] = 'second';
days[2] = 'third';
days[3] = 'fourth';
days[4] = 'fifth';
days[5] = 'sixth';
days[6] = 'seventh';
days[7] = 'eighth';
days[8] = 'ninth';
days[9] = 'tenth';
days[10] = 'eleventh';
days[11] = 'twelfth';
gifts[0] = 'A partridge in a pear tree';
gifts[1] = 'Two turtle doves';
gifts[2] = 'Three french hens';
gifts[3] = 'Four calling birds';
gifts[4] = 'Five golden rings';
gifts[5] = 'Six geese a-laying';
gifts[6] = 'Seven swans a-swimming';
gifts[7] = 'Eight maids a-milking';
gifts[8] = 'Nine ladies dancing';
gifts[9] = 'Ten lords a-leaping';
gifts[10] = 'Eleven pipers piping';
gifts[11] = 'Twelve drummers drumming';
var i:uint, j:uint, k:uint, line:String;
for ( i = 0; i < 12; i++ ) {
lines = new Vector.<String>(i + 2, true);
lines[0] = "On the " + days[i] + " day of Christmas, my true love gave to me";
j = i + 1;
k = 0;
while ( j-- > 0 )
lines[++k] = gifts[j];
verses[i] = lines.join('\n');
if ( i == 0 )
gifts[0] = 'And a partridge in a pear tree';
}
var song:String = verses.join('\n\n');
_textArea.text = song;
addChild(_textArea);
_textArea.addEventListener(MouseEvent.MOUSE_WHEEL, _onMouseWheel);
stage.addEventListener(KeyboardEvent.KEY_DOWN, _onKeyDown);
}
private function _onKeyDown(e:KeyboardEvent):void {
if ( e.keyCode == Keyboard.DOWN )
_textArea.y -= 40;
else if ( e.keyCode == Keyboard.UP )
_textArea.y += 40;
}
private function _onMouseWheel(e:MouseEvent):void {
_textArea.y += 20 * e.delta;
}
}
} |
http://rosettacode.org/wiki/Terminal_control/Preserve_screen | Terminal control/Preserve screen |
Task
Clear the screen, output something on the display, and then restore the screen to the preserved state that it was in before the task was carried out.
There is no requirement to change the font or kerning in this task, however character decorations and attributes are expected to be preserved. If the implementer decides to change the font or kerning during the display of the temporary screen, then these settings need to be restored prior to exit.
| #Common_Lisp | Common Lisp |
(format t "~C[?1049h~C[H" (code-char #O33) (code-char #O33))
(format t "Alternate screen buffer~%")
(loop for i from 5 downto 1 do (progn
(format t "~%going back in ~a" i)
(sleep 1)
))
(format t "~C[?1049l" (code-char #O33))
|
http://rosettacode.org/wiki/Terminal_control/Preserve_screen | Terminal control/Preserve screen |
Task
Clear the screen, output something on the display, and then restore the screen to the preserved state that it was in before the task was carried out.
There is no requirement to change the font or kerning in this task, however character decorations and attributes are expected to be preserved. If the implementer decides to change the font or kerning during the display of the temporary screen, then these settings need to be restored prior to exit.
| #Emacs_Lisp | Emacs Lisp | #!/usr/local/bin/emacs --script
;; -*- lexical-binding: t; -*-
;; "ESC [ ? 1049 h" - Enable alternative screen buffer
(princ "\033[?1049h")
(princ "Alternate screen buffer\n")
(let ((i 5))
(while (> i 0)
(princ (format "\rgoing back in %d..." i))
;; flush stdout
(set-binary-mode 'stdout t)
(sleep-for 1)
(setq i (1- i))))
;; "ESC [ ? 1049 l" - Disable alternative screen buffer
(princ "\033[?1049l") |
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.
| #11l | 11l | V nodata = 0
V nodata_max = -1
[String] nodata_maxline
V tot_file = 0.0
V num_file = 0
:start:
L(line) File(:argv[1]).read().rtrim("\n").split("\n")
V tot_line = 0.0
V num_line = 0
V field = line.split("\t")
V date = field[0]
V data = field[(1..).step(2)].map(f -> Float(f))
V flags = field[(2..).step(2)].map(f -> Int(f))
L(datum, flag) zip(data, flags)
I flag < 1
nodata++
E
I nodata_max == nodata & nodata > 0
nodata_maxline.append(date)
I nodata_max < nodata & nodata > 0
nodata_max = nodata
nodata_maxline = [date]
nodata = 0
tot_line += datum
num_line++
tot_file += tot_line
num_file += num_line
print(‘Line: #11 Reject: #2 Accept: #2 Line_tot: #6.3 Line_avg: #6.3’.format(
date, data.len - num_line, num_line, tot_line, I (num_line > 0) {tot_line / num_line} E 0))
print()
print(‘File(s) = #.’.format(:argv[1]))
print(‘Total = #6.3’.format(tot_file))
print(‘Readings = #6’.format(num_file))
print(‘Average = #6.3’.format(tot_file / num_file))
print("\nMaximum run(s) of #. consecutive false readings ends at line starting with date(s): #.".format(nodata_max, nodata_maxline.join(‘, ’))) |
http://rosettacode.org/wiki/Terminal_control/Positional_read | Terminal control/Positional read | Determine the character displayed on the screen at column 3, row 6 and store that character in a variable. Note that it is permissible to utilize system or language provided methods or system provided facilities, system maintained records or available buffers or system maintained display records to achieve this task, rather than query the terminal directly, if those methods are more usual for the system type or language.
| #Action.21 | Action! | proc Main()
byte CHARS, cursorinh=$2F0
graphics(0) cursorinh=1
position(2,2) printe("Action!")
CHARS=Locate(2,2) position(2,2) put(CHARS)
cursorinh=0
position(2,4) printf("Character at column 2 row 2 was %C",CHARS)
return |
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.
| #Delphi | Delphi |
{$apptype console}
PROGRAM RosettaIsaac;
USES SysUtils;
// TASK globals
VAR msg : STRING = 'a Top Secret secret';
VAR key : STRING = 'this is my secret key';
VAR xctx: STRING = ''; // XOR ciphertext
VAR mctx: STRING = ''; // MOD ciphertext
// ISAAC globals
// external results
VAR randrsl: ARRAY[0..256] OF CARDINAL;
VAR randcnt: cardinal;
// internal state
VAR mm: ARRAY[0..256] OF CARDINAL;
VAR 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;
// this reset was not in original readable.c!
randcnt:=0; // prepare to use the first set of results
END; {Isaac}
// if (flag==TRUE), then use the contents of randrsl[] to initialize mm[].
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:=a+randrsl[i ]; b:=b+randrsl[i+1]; c:=c+randrsl[i+2]; d:=d+randrsl[i+3];
e:=e+randrsl[i+4]; f:=f+randrsl[i+5]; g:=g+randrsl[i+6]; h:=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:=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:=a+mm[i ]; b:=b+mm[i+1]; c:=c+mm[i+2]; d:=d+mm[i+3];
e:=e+mm[i+4]; f:=f+mm[i+5]; g:=g+mm[i+6]; h:=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:=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; {randinit}
{ 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
result := 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
result := iRandom mod 95 + 32;
END;
{ convert an ASCII string to a hexadecimal string }
FUNCTION ascii2hex(s: STRING): STRING;
VAR i,l: CARDINAL;
BEGIN
result := '';
l := Length(s);
FOR i := 1 TO l DO
result := result + IntToHex(ord(s[i]),2);
END;
{ XOR encrypt on random stream. Output: string of hex chars }
FUNCTION Vernam(msg: STRING): STRING;
VAR i: CARDINAL;
BEGIN
result := '';
FOR i := 1 to length(msg) DO
result := result + chr(iRandA xor ord(msg[i]));
result := ascii2hex(result);
END;
{ Get position of the letter in chosen alphabet }
FUNCTION letternum(letter, start: CHAR): byte;
BEGIN
result := (ord(letter)-ord(start));
END;
{ Caesar-shift a character <shift> places: Generalized Vigenere }
FUNCTION Caesar(ch: CHAR; shift, modulo: INTEGER; start: CHAR): CHAR;
VAR n: INTEGER;
BEGIN
n := letternum(ch,start) + shift;
n := n MOD modulo;
result := chr(ord(start)+n);
END;
{ Vigenere mod 95 encryption. Output: string of hex chars }
FUNCTION Vigenere(msg: STRING): STRING;
VAR i: CARDINAL;
BEGIN
result := '';
FOR i := 1 to length(msg) DO
result := result + Caesar(msg[i],iRandA,95,' ');
result := ascii2hex(result);
END;
BEGIN
// 1) seed ISAAC with the key
iSeed(key,true);
// 2) Vernam XOR encryption
xctx := Vernam(msg);
// 3) MOD encryption
mctx := Vigenere(msg);
// program output
Writeln('Message: ',msg);
Writeln('Key : ',key);
Writeln('XOR : ',xctx);
Writeln('MOD : ',mctx);
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.)
| #Elixir | Elixir | defmodule Test do
def integer?(n) when n == trunc(n), do: true
def integer?(_), do: false
end
Enum.each([2, 2.0, 2.5, 2.000000000000001, 1.23e300, 1.0e-300, "123", '123', :"123"], fn n ->
IO.puts "#{inspect n} is integer?: #{Test.integer?(n)}"
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.)
| #Factor | Factor | USING: formatting io kernel math math.functions sequences ;
IN: rosetta-code.test-integerness
GENERIC: integral? ( n -- ? )
M: real integral? [ ] [ >integer ] bi number= ;
M: complex integral? >rect [ integral? ] [ 0 number= ] bi* and ;
GENERIC# fuzzy-int? 1 ( n tolerance -- ? )
M: real fuzzy-int? [ dup round - abs ] dip <= ;
M: complex fuzzy-int? [ >rect ] dip swapd fuzzy-int? swap 0
number= and ;
{
25/1
50+2/3
34/73
312459210312903/129381293812491284512951
25.000000
24.999999
25.000100
-2.1e120
-5e-2
0/0. ! NaN
1/0. ! Infinity
C{ 5.0 0.0 }
C{ 5 -5 }
C{ 5 0 }
}
"Number" "Exact int?" "Fuzzy int? (tolerance=0.00001)"
"%-41s %-11s %s\n" printf
[
[ ] [ integral? ] [ 0.00001 fuzzy-int? ] tri
"%-41u %-11u %u\n" printf
] each |
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).
| #Lua | Lua |
filename = "mlijobs.txt"
io.input( filename )
max_out, n_out = 0, 0
occurr_dates = {}
while true do
line = io.read( "*line" )
if line == nil then break end
if string.find( line, "OUT" ) ~= nil then
n_out = n_out + 1
if n_out > max_out then
max_out = n_out
occurr_dates = {}
occurr_dates[#occurr_dates+1] = string.match( line, "@ ([%d+%p]+)" )
elseif n_out == max_out then
occurr_dates[#occurr_dates+1] = string.match( line, "@ ([%d+%p]+)" )
end
else
n_out = n_out - 1
end
end
print( "Maximum licenses in use:", max_out )
print( "Occurrences:" )
for i = 1, #occurr_dates do
print( "", occurr_dates[i] )
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.
| #EchoLisp | EchoLisp |
(assert (palindrome? "aba")) → #t
(assert (palindrome? "abbbca") "palindrome fail")
💥 error: palindrome fail : assertion failed : (palindrome? abbbca)
(check-expect (palindrome? "aba") #t) → #t
(check-expect (palindrome? "abcda") #f) → #t
(check-expect (palindrome? "abcda") #t)
😐 warning: #t : check failed : (palindrome? abcda) → #f
(assert (palindrome? "un roc lamina l animal cornu")) → #t
|
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.
| #Erlang | Erlang |
-module( palindrome_tests ).
-compile( export_all ).
-include_lib( "eunit/include/eunit.hrl" ).
abcba_test() -> ?assert( palindrome:is_palindrome("abcba") ).
abcdef_test() -> ?assertNot( palindrome:is_palindrome("abcdef") ).
|
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.
| #Racket | Racket | #lang racket
(read-decimal-as-inexact #f)
;; files to read is a sequence, so it could be either a list or vector of files
(define (text-processing/2 files-to-read)
(define seen-datestamps (make-hash))
(define (datestamp-seen? ds) (hash-ref seen-datestamps ds #f))
(define (datestamp-seen! ds pos) (hash-set! seen-datestamps ds pos))
(define (fold-into-pairs l (acc null))
(match l ['() (reverse acc)]
[(list _) (reverse (cons l acc))]
[(list-rest a b tl) (fold-into-pairs tl (cons (list a b) acc))]))
(define (match-valid-field line pos)
(match (string-split line)
;; if we don't hit an error, then the file is valid
((list-rest (not (pregexp #px"[[:digit:]]{4}-[[:digit:]]{2}-[[:digit:]]{2}")) _)
(error 'match-valid-field "invalid format non-datestamp at head: ~a~%" line))
;; check for duplicates
((list-rest (? datestamp-seen? ds) _)
(printf "duplicate datestamp: ~a at line: ~a (first seen at: ~a)~%"
ds pos (datestamp-seen? ds))
#f)
;; register the datestamp as seen, then move on to rest of match
((list-rest ds _) (=> next-match-rule) (datestamp-seen! ds pos) (next-match-rule))
((list-rest
_
(app fold-into-pairs
(list (list (app string->number (and (? number?) vs))
(app string->number (and (? integer?) statuss)))
...)))
(=> next-match-rule)
(unless (= (length vs) 24) (next-match-rule))
(not (for/first ((s statuss) #:unless (positive? s)) #t)))
;; if we don't hit an error, then the file is valid
(else (error 'match-valid-field "bad field format: ~a~%" line))))
(define (sub-t-p/1)
(for/sum ((line (in-lines))
(line-number (in-naturals 1)))
(if (match-valid-field line line-number) 1 0)))
(for/sum ((file-name files-to-read))
(with-input-from-file file-name sub-t-p/1)))
(printf "~a records have good readings for all instruments~%"
(text-processing/2 (current-command-line-arguments))) |
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.
| #Raku | Raku | my $good-records;
my $line;
my %dates;
for lines() {
$line++;
/ ^
(\d ** 4 '-' \d\d '-' \d\d)
[ \h+ \d+'.'\d+ \h+ ('-'?\d+) ] ** 24
$ /
or note "Bad format at line $line" and next;
%dates.push: $0 => $line;
$good-records++ if $1.all >= 1;
}
say "$good-records good records out of $line total";
say 'Repeated timestamps (with line numbers):';
.say for sort %dates.pairs.grep: *.value.elems > 1; |
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.
| #Haskell | Haskell | main = putStr "\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.
| #Icon_and_Unicon | Icon and Unicon |
procedure main ()
write ("\7") # ASCII 7 rings the bell under Bash
end
|
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.
| #J | J | 7{a. NB. noun a. is a complete ASCII ordered character vector. |
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.
| #Java | Java | public class Bell{
public static void main(String[] args){
java.awt.Toolkit.getDefaultToolkit().beep();
//or
System.out.println((char)7);
}
} |
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
| #Ada | Ada | with Ada.Text_IO; use Ada.Text_IO;
with Ada.Strings.Unbounded; use Ada.Strings.Unbounded;
procedure Twelve_Days_Of_Christmas is
type Days is (First, Second, Third, Fourth, Fifth, Sixth,
Seventh, Eighth, Ninth, Tenth, Eleventh, Twelfth);
package E_IO is new Ada.Text_IO.Enumeration_IO(Days);
use E_IO;
Gifts : array (Days) of Unbounded_String :=
(To_Unbounded_String(" A partridge in a pear-tree."),
To_Unbounded_String(" Two turtle doves"),
To_Unbounded_String(" Three French hens"),
To_Unbounded_String(" Four calling birds"),
To_Unbounded_String(" Five golden rings"),
To_Unbounded_String(" Six geese a-laying"),
To_Unbounded_String(" Seven swans a-swimming"),
To_Unbounded_String(" Eight maids a-milking"),
To_Unbounded_String(" Nine ladies dancing"),
To_Unbounded_String(" Ten lords a-leaping"),
To_Unbounded_String(" Eleven pipers piping"),
To_Unbounded_String(" Twelve drummers drumming"));
begin
for Day in Days loop
Put("On the "); Put(Day, Set => Lower_Case); Put(" day of Christmas,");
New_Line; Put_Line("My true love gave to me:");
for D in reverse Days'First..Day loop
Put_Line(To_String(Gifts(D)));
end loop;
if Day = First then
Replace_Slice(Gifts(Day), 2, 2, "And a");
end if;
New_Line;
end loop;
end Twelve_Days_Of_Christmas;
|
http://rosettacode.org/wiki/Terminal_control/Preserve_screen | Terminal control/Preserve screen |
Task
Clear the screen, output something on the display, and then restore the screen to the preserved state that it was in before the task was carried out.
There is no requirement to change the font or kerning in this task, however character decorations and attributes are expected to be preserved. If the implementer decides to change the font or kerning during the display of the temporary screen, then these settings need to be restored prior to exit.
| #Forth | Forth | .\" \033[?1049h\033[H" \ preserve screen
." Press any key to return" ekey drop
.\" \033[?1049l" \ restore screen |
http://rosettacode.org/wiki/Terminal_control/Preserve_screen | Terminal control/Preserve screen |
Task
Clear the screen, output something on the display, and then restore the screen to the preserved state that it was in before the task was carried out.
There is no requirement to change the font or kerning in this task, however character decorations and attributes are expected to be preserved. If the implementer decides to change the font or kerning during the display of the temporary screen, then these settings need to be restored prior to exit.
| #FreeBASIC | FreeBASIC | '' 640x480x8, with 3 pages
Screen 12,,3
Windowtitle "Terminal control/Preserve screen"
'' text for working page #2 (visible page #0)
Screenset 2, 0
Cls
Print "This is the new screen, following a CLS"
'' text for working page #1 (visible page #0)
Screenset 1, 0
Cls
Print "This is the original screen"
' page #0 is the working page (visible page #0)
Screenset 0, 0
Screencopy 1, 0
Sleep 1000 '1 second
Screencopy 2, 0
Sleep 1000
Print
For i As Byte = 5 To 1 Step -1
Print "Going back in: "; i
Sleep 1000
Next i
Screencopy 1, 0
Sleep |
http://rosettacode.org/wiki/Terminal_control/Preserve_screen | Terminal control/Preserve screen |
Task
Clear the screen, output something on the display, and then restore the screen to the preserved state that it was in before the task was carried out.
There is no requirement to change the font or kerning in this task, however character decorations and attributes are expected to be preserved. If the implementer decides to change the font or kerning during the display of the temporary screen, then these settings need to be restored prior to exit.
| #Go | Go | package main
import (
"fmt"
"time"
)
func main() {
fmt.Print("\033[?1049h\033[H")
fmt.Println("Alternate screen buffer\n")
s := "s"
for i := 5; i > 0; i-- {
if i == 1 {
s = ""
}
fmt.Printf("\rgoing back in %d second%s...", i, s)
time.Sleep(time.Second)
}
fmt.Print("\033[?1049l")
} |
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.
| #Ada | Ada | with Ada.Text_IO; use Ada.Text_IO;
with Strings_Edit; use Strings_Edit;
with Strings_Edit.Floats; use Strings_Edit.Floats;
with Strings_Edit.Integers; use Strings_Edit.Integers;
procedure Data_Munging is
Syntax_Error : exception;
type Gap_Data is record
Count : Natural := 0;
Line : Natural := 0;
Pointer : Integer;
Year : Integer;
Month : Integer;
Day : Integer;
end record;
File : File_Type;
Max : Gap_Data;
This : Gap_Data;
Current : Gap_Data;
Count : Natural := 0;
Sum : Float := 0.0;
begin
Open (File, In_File, "readings.txt");
loop
declare
Line : constant String := Get_Line (File);
Pointer : Integer := Line'First;
Flag : Integer;
Data : Float;
begin
Current.Line := Current.Line + 1;
Get (Line, Pointer, SpaceAndTab);
Get (Line, Pointer, Current.Year);
Get (Line, Pointer, Current.Month);
Get (Line, Pointer, Current.Day);
while Pointer <= Line'Last loop
Get (Line, Pointer, SpaceAndTab);
Current.Pointer := Pointer;
Get (Line, Pointer, Data);
Get (Line, Pointer, SpaceAndTab);
Get (Line, Pointer, Flag);
if Flag < 0 then
if This.Count = 0 then
This := Current;
end if;
This.Count := This.Count + 1;
else
if This.Count > 0 and then Max.Count < This.Count then
Max := This;
end if;
This.Count := 0;
Count := Count + 1;
Sum := Sum + Data;
end if;
end loop;
exception
when End_Error =>
raise Syntax_Error;
end;
end loop;
exception
when End_Error =>
Close (File);
if This.Count > 0 and then Max.Count < This.Count then
Max := This;
end if;
Put_Line ("Average " & Image (Sum / Float (Count)) & " over " & Image (Count));
if Max.Count > 0 then
Put ("Max. " & Image (Max.Count) & " false readings start at ");
Put (Image (Max.Line) & ':' & Image (Max.Pointer) & " stamped ");
Put_Line (Image (Max.Year) & Image (Max.Month) & Image (Max.Day));
end if;
when others =>
Close (File);
Put_Line ("Syntax error at " & Image (Current.Line) & ':' & Image (Max.Pointer));
end Data_Munging; |
http://rosettacode.org/wiki/Terminal_control/Positional_read | Terminal control/Positional read | Determine the character displayed on the screen at column 3, row 6 and store that character in a variable. Note that it is permissible to utilize system or language provided methods or system provided facilities, system maintained records or available buffers or system maintained display records to achieve this task, rather than query the terminal directly, if those methods are more usual for the system type or language.
| #AutoHotkey | AutoHotkey | DllCall( "AllocConsole" ) ; create a console if not launched from one
hConsole := DllCall( "GetStdHandle", int, STDOUT := -11 )
Loop 10
{
Loop 10
{
Random, asc, % asc("A"), % Asc("Z")
WriteConsole(hConsole, Chr(asc))
}
WriteConsole(hConsole, "`n")
}
MsgBox % ReadConsoleOutputCharacter(hConsole, 1, 3, 6)
; === The below simply wraps part of the WinAPI ===
WriteConsole(hConsole, text){
VarSetCapacity(out, 16)
If DllCall( "WriteConsole", UPtr, hConsole, Str, text, UInt, StrLen(text)
, UPtrP, out, uint, 0 )
return out
return 0
}
ReadConsoleOutputCharacter(hConsole, length, x, y){
VarSetCapacity(out, length * (1 << !!A_IsUnicode))
VarSetCapacity(n, 16)
if DllCall( "ReadConsoleOutputCharacter"
, UPtr, hConsole
, Str, out
, UInt, length
, UInt, x | (y << 16)
, UPtrP, n )
&& VarSetCapacity(out, -1)
return out
return 0
} |
http://rosettacode.org/wiki/Terminal_control/Positional_read | Terminal control/Positional read | Determine the character displayed on the screen at column 3, row 6 and store that character in a variable. Note that it is permissible to utilize system or language provided methods or system provided facilities, system maintained records or available buffers or system maintained display records to achieve this task, rather than query the terminal directly, if those methods are more usual for the system type or language.
| #BASIC | BASIC | 10 DEF FN C(H) = SCRN( H - 1,(V - 1) * 2) + SCRN( H - 1,(V - 1) * 2 + 1) * 16
20 LET V = 6:C$ = CHR$ ( FN C(3)) |
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.
| #ECMAScript | ECMAScript | randrsl = new Uint32Array(256);
randcnt = 0;
mm = new Uint32Array(256);
aa = 0;
bb = 0;
cc = 0;
function isaac() {
cc++;
bb += cc;
for(var i = 0; i < 256; i++) {
var x = mm[i];
var sw = i & 3;
if(sw == 0) aa = aa ^ (aa << 13);
else if(sw == 1) aa = aa ^ (aa >>> 6);
else if(sw == 2) aa = aa ^ (aa << 2);
else if(sw == 3) aa = aa ^ (aa >>> 16);
aa = mm[(i+128) & 255] + aa;
mm[i] = mm[(x >>> 2) & 255] + aa + bb;
bb = mm[(mm[i] >>> 10) & 255] + x;
randrsl[i] = bb;
}
}
function isaac_mix(x) {
x[0] = x[0] ^ x[1] << 11; x[3]+=x[0]; x[1]+=x[2];
x[1] = x[1] ^ x[2] >>> 2; x[4]+=x[1]; x[2]+=x[3];
x[2] = x[2] ^ x[3] << 8; x[5]+=x[2]; x[3]+=x[4];
x[3] = x[3] ^ x[4] >>> 16; x[6]+=x[3]; x[4]+=x[5];
x[4] = x[4] ^ x[5] << 10; x[7]+=x[4]; x[5]+=x[6];
x[5] = x[5] ^ x[6] >>> 4; x[0]+=x[5]; x[6]+=x[7];
x[6] = x[6] ^ x[7] << 8; x[1]+=x[6]; x[7]+=x[0];
x[7] = x[7] ^ x[0] >>> 9; x[2]+=x[7]; x[0]+=x[1];
}
function isaac_init(flag) {
var x = Uint32Array([2654435769, 2654435769, 2654435769, 2654435769,
2654435769, 2654435769, 2654435769, 2654435769]);
aa=0, bb=0, cc=0;
isaac_mix(x); isaac_mix(x); isaac_mix(x); isaac_mix(x);
var i = 0;
while(i < 255) {
if(flag) for(var j = 0; j < 8; j++) x[j] += randrsl[i+j];
isaac_mix(x);
for(var j = 0; j < 8; j++) mm[i+j] = x[j];
i += 8;
}
if(flag) {
var i = 0;
while(i < 255) {
for(var j = 0; j < 8; j++) x[j] += mm[i+j];
isaac_mix(x);
for(var j = 0; j < 8; j++) mm[i+j] = x[j];
i += 8;
}
}
isaac();
randcnt = 0;
}
function isaac_seed(string, flag) {
mm = new Uint32Array(256);
randrsl = new Uint32Array(256);
var m = string.length;
for(var i = 0; i < m; i++) randrsl[i] = string.charCodeAt(i);
isaac_init(flag);
}
function isaac_random() {
var out = randrsl[randcnt++];
if(randcnt > 255) {
isaac();
randcnt = 0;
}
return out
}
function vernam(msg) {
var out = "";
for(var i = 0; i < msg.length; i++) {
var ra = isaac_random() % 95 + 32;
out += String.fromCharCode(ra ^ msg.charCodeAt(i));
}
return out;
}
function printable_hex(s) {
out = "";
for(var i = 0; i < s.length; i++)
out += (s.charCodeAt(i) / 16 > 1 ? '' : '0') + s.charCodeAt(i).toString(16);
return out;
}
function run_isaac(key, msg)
{
isaac_seed(key, true);
// XOR encrypt
var xctx = vernam(msg);
// XOR decrypt
isaac_seed(key, true);
var xptx = vernam(xctx);
return [xctx, xptx]
}
var key = 'this is my secret key'
var msg = 'a Top Secret secret'
console.log('key: '+key)
console.log('msg: '+msg)
var z = run_isaac(key, msg)
xctx = z[0];
xptx = z[1];
console.log('xor: '+printable_hex(xctx))
console.log('decrypted: '+xptx) |
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.)
| #Fortran | Fortran | MODULE ZERMELO !Approach the foundations of mathematics.
CONTAINS
LOGICAL FUNCTION ISINTEGRAL(X) !A whole number?
REAL*8 X !Alas, this is not really a REAL number.
INTEGER*8 N !Largest available.
IF (ISNAN(X)) THEN !Avoid some sillyness.
ISINTEGRAL = .FALSE. !And possible error messages.
ELSE !But now it is safe to try.
N = KIDINT(X) !This one truncates.
ISINTEGRAL = N .EQ. X !Any difference?
END IF !A floating-point number may overflow an integer.
END FUNCTION ISINTEGRAL !And even if integral, it will not seem so.
LOGICAL FUNCTION ISINTEGRALZ(Z) !For complex numbers, two tests.
DOUBLE COMPLEX Z !Still not really REAL, though.
ISINTEGRALZ = ISINTEGRAL(DBLE(Z)) .AND. ISINTEGRAL(DIMAG(Z)) !Separate the parts.
END FUNCTION ISINTEGRALZ!No INTEGER COMPLEX type is offered.
END MODULE ZERMELO !Much more mathematics lie elsewhere.
PROGRAM TEST
USE ZERMELO
DOUBLE COMPLEX Z
WRITE (6,*) "See if some numbers are integral..."
WRITE (6,*) ISINTEGRAL(666D0),666D0
Z = DCMPLX(-3D0,4*ATAN(1D0))
WRITE (6,*) ISINTEGRALZ(Z),Z
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).
| #M2000_Interpreter | M2000 Interpreter |
Module Checkit {
Document a$, max_time$
Load.doc a$, "mlijobs.txt"
const dl$=" ", nl$={
}
Def long m, out, max_out=-1
m=Paragraph(a$, 0)
If Forward(a$,m) then {
While m {
job$=Paragraph$(a$,(m))
out+=If(Piece$(job$,dl$,2)="OUT"->1&, -1&)
If out>max_out then max_out=out : Clear max_time$
If out=max_out then max_time$=Piece$(job$,dl$,4)+nl$
}
}
Report Format$("Maximum simultaneous license use is {0} at the following times:",max_out)
Print " "; ' left margin
Report max_time$
}
Checkit
|
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).
| #M4 | M4 |
divert(-1)
define(`current',0)
define(`max',0)
define(`OUT',`define(`current',incr(current))`'ifelse(eval(current>max),1,
`define(`max',current)`'divert(-1)`'undivert(1)`'divert(1)',
`ifelse(current,max,`divert(1)undivert(1)')')')
define(`IN',`define(`current',decr(current))')
define(`for',`divert(-1)')
include(mlijobs.txt))
divert
max
undivert(1)
|
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.
| #Euphoria | Euphoria |
--unittest in standard library 4.0+
include std/unittest.e
include palendrome.e --routines to be tested
object p = "12321"
test_equal("12321", 1, isPalindrome(p))
test_equal("r12321", 1, isPalindrome(reverse(p)))
test_report()
|
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.
| #F.23 | F# | let palindrome (s : string) =
let a = s.ToUpper().ToCharArray()
Array.rev a = a
open NUnit.Framework
[<TestFixture>]
type TestCases() =
[<Test>]
member x.Test01() =
Assert.IsTrue(palindrome "radar")
[<Test>]
member x.Test02() =
Assert.IsFalse(palindrome "hello") |
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.
| #REXX | REXX | /*REXX program to process instrument data from a data file. */
numeric digits 20 /*allow for bigger numbers. */
ifid='READINGS.TXT' /*name of the input file. */
ofid='READINGS.OUT' /* " " " output " */
grandSum=0 /*grand sum of the whole file. */
grandFlg=0 /*grand number of flagged data. */
grandOKs=0
Lflag=0 /*longest period of flagged data. */
Cflag=0 /*longest continuous flagged data. */
oldDate =0 /*placeholder of penultimate date. */
w =16 /*width of fields when displayed. */
dupDates=0 /*count of duplicated timestamps. */
badFlags=0 /*count of bad flags (not integer). */
badDates=0 /*count of bad dates (bad format). */
badData =0 /*count of bad data (not numeric). */
ignoredR=0 /*count of ignored records, bad records*/
maxInstruments=24 /*maximum number of instruments. */
yyyyCurr=right(date(),4) /*get the current year (today). */
monDD. =31 /*number of days in every month. */
/*# days in Feb. is figured on the fly.*/
monDD.4 =30
monDD.6 =30
monDD.9 =30
monDD.11=30
do records=1 while lines(ifid)\==0 /*read until finished. */
rec=linein(ifid) /*read the next record (line). */
parse var rec datestamp Idata /*pick off the the dateStamp and data. */
if datestamp==oldDate then do /*found a duplicate timestamp. */
dupDates=dupDates+1 /*bump the dupDate counter*/
call sy datestamp copies('~',30),
'is a duplicate of the',
"previous datestamp."
ignoredR=ignoredR+1 /*bump # of ignoredRecs.*/
iterate /*ignore this duplicate record. */
end
parse var datestamp yyyy '-' mm '-' dd /*obtain YYYY, MM, and the DD. */
monDD.2=28+leapyear(yyyy) /*how long is February in year YYYY ? */
/*check for various bad formats. */
if verify(yyyy||mm||dd,1234567890)\==0 |,
length(datestamp)\==10 |,
length(yyyy)\==4 |,
length(mm )\==2 |,
length(dd )\==2 |,
yyyy<1970 |,
yyyy>yyyyCurr |,
mm=0 | dd=0 |,
mm>12 | dd>monDD.mm then do
badDates=badDates+1
call sy datestamp copies('~'),
'has an illegal format.'
ignoredR=ignoredR+1 /*bump number ignoredRecs.*/
iterate /*ignore this bad record. */
end
oldDate=datestamp /*save datestamp for the next read. */
sum=0
flg=0
OKs=0
do j=1 until Idata='' /*process the instrument data. */
parse var Idata data.j flag.j Idata
if pos('.',flag.j)\==0 |, /*does flag have a decimal point -or- */
\datatype(flag.j,'W') then do /* ··· is the flag not a whole number? */
badFlags=badFlags+1 /*bump badFlags counter*/
call sy datestamp copies('~'),
'instrument' j "has a bad flag:",
flag.j
iterate /*ignore it and it's data. */
end
if \datatype(data.j,'N') then do /*is the flag not a whole number?*/
badData=badData+1 /*bump counter.*/
call sy datestamp copies('~'),
'instrument' j "has bad data:",
data.j
iterate /*ignore it & it's flag.*/
end
if flag.j>0 then do /*if good data, ~~~ */
OKs=OKs+1
sum=sum+data.j
if Cflag>Lflag then do
Ldate=datestamp
Lflag=Cflag
end
Cflag=0
end
else do /*flagged data ~~~ */
flg=flg+1
Cflag=Cflag+1
end
end /*j*/
if j>maxInstruments then do
badData=badData+1 /*bump the badData counter.*/
call sy datestamp copies('~'),
'too many instrument datum'
end
if OKs\==0 then avg=format(sum/OKs,,3)
else avg='[n/a]'
grandOKs=grandOKs+OKs
_=right(commas(avg),w)
grandSum=grandSum+sum
grandFlg=grandFlg+flg
if flg==0 then call sy datestamp ' average='_
else call sy datestamp ' average='_ ' flagged='right(flg,2)
end /*records*/
records=records-1 /*adjust for reading the end─of─file. */
if grandOKs\==0 then grandAvg=format(grandsum/grandOKs,,3)
else grandAvg='[n/a]'
call sy
call sy copies('=',60)
call sy ' records read:' right(commas(records ),w)
call sy ' records ignored:' right(commas(ignoredR),w)
call sy ' grand sum:' right(commas(grandSum),w+4)
call sy ' grand average:' right(commas(grandAvg),w+4)
call sy ' grand OK data:' right(commas(grandOKs),w)
call sy ' grand flagged:' right(commas(grandFlg),w)
call sy ' duplicate dates:' right(commas(dupDates),w)
call sy ' bad dates:' right(commas(badDates),w)
call sy ' bad data:' right(commas(badData ),w)
call sy ' bad flags:' right(commas(badFlags),w)
if Lflag\==0 then call sy ' longest flagged:' right(commas(LFlag),w) " ending at " Ldate
call sy copies('=',60)
exit /*stick a fork in it, we're all done.*/
/*────────────────────────────────────────────────────────────────────────────*/
commas: procedure; parse arg _; n=_'.9'; #=123456789; b=verify(n,#,"M")
e=verify(n,#'0',,verify(n,#"0.",'M'))-4
do j=e to b by -3; _=insert(',',_,j); end /*j*/; return _
/*────────────────────────────────────────────────────────────────────────────*/
leapyear: procedure; arg y /*year could be: Y, YY, YYY, or YYYY*/
if length(y)==2 then y=left(right(date(),4),2)y /*adjust for YY year.*/
if y//4\==0 then return 0 /* not divisible by 4? Not a leapyear*/
return y//100\==0 | y//400==0 /*apply the 100 and the 400 year rule.*/
/*────────────────────────────────────────────────────────────────────────────*/
sy: say arg(1); call lineout ofid,arg(1); return |
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.
| #Julia | Julia |
println("This should ring a bell.\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.
| #Kotlin | Kotlin | // version 1.1.2
fun main(args: Array<String>) {
println("\u0007")
} |
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.
| #Lasso | Lasso | stdoutnl('\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.
| #Logo | Logo | type char 7 |
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
| #ALGOL_68 | ALGOL 68 | BEGIN
[]STRING labels = ("first", "second", "third", "fourth",
"fifth", "sixth", "seventh", "eighth",
"ninth", "tenth", "eleventh", "twelfth");
[]STRING gifts = ("A partridge in a pear tree.",
"Two turtle doves, and",
"Three French hens,",
"Four calling birds,",
"Five gold rings,",
"Six geese a-laying,",
"Seven swans a-swimming,",
"Eight maids a-milking,",
"Nine ladies dancing,",
"Ten lords a-leaping,",
"Eleven pipers piping,",
"Twelve drummers drumming,");
FOR day TO 12 DO
print(("On the ", labels[day],
" day of Christmas, my true love sent to me:", newline));
FOR gift FROM day BY -1 TO 1 DO
print((gifts[gift], newline))
OD;
print(newline)
OD
END |
http://rosettacode.org/wiki/Terminal_control/Preserve_screen | Terminal control/Preserve screen |
Task
Clear the screen, output something on the display, and then restore the screen to the preserved state that it was in before the task was carried out.
There is no requirement to change the font or kerning in this task, however character decorations and attributes are expected to be preserved. If the implementer decides to change the font or kerning during the display of the temporary screen, then these settings need to be restored prior to exit.
| #Java | Java | public class PreserveScreen
{
public static void main(String[] args) throws InterruptedException {
System.out.print("\033[?1049h\033[H");
System.out.println("Alternate screen buffer\n");
for (int i = 5; i > 0; i--) {
String s = (i > 1) ? "s" : "";
System.out.printf("\rgoing back in %d second%s...", i, s);
Thread.sleep(1000);
}
System.out.print("\033[?1049l");
}
} |
http://rosettacode.org/wiki/Terminal_control/Preserve_screen | Terminal control/Preserve screen |
Task
Clear the screen, output something on the display, and then restore the screen to the preserved state that it was in before the task was carried out.
There is no requirement to change the font or kerning in this task, however character decorations and attributes are expected to be preserved. If the implementer decides to change the font or kerning during the display of the temporary screen, then these settings need to be restored prior to exit.
| #JavaScript | JavaScript | (function() {
var orig= document.body.innerHTML
document.body.innerHTML= '';
setTimeout(function() {
document.body.innerHTML= 'something';
setTimeout(function() {
document.body.innerHTML= orig;
}, 1000);
}, 1000);
})(); |
http://rosettacode.org/wiki/Terminal_control/Preserve_screen | Terminal control/Preserve screen |
Task
Clear the screen, output something on the display, and then restore the screen to the preserved state that it was in before the task was carried out.
There is no requirement to change the font or kerning in this task, however character decorations and attributes are expected to be preserved. If the implementer decides to change the font or kerning during the display of the temporary screen, then these settings need to be restored prior to exit.
| #Julia | Julia | const ESC = "\u001B" # escape code
print("$ESC[?1049h$ESC[H")
print("\n\nNow using an alternate screen buffer. Returning after count of: ")
foreach(x -> (sleep(1); print(" $x")), 5:-1:0)
print("$ESC[?1049l\n\n\n")
|
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.
| #Action.21 | Action! | PROC Wait(BYTE frames)
BYTE RTCLOK=$14
frames==+RTCLOK
WHILE frames#RTCLOK DO OD
RETURN
PROC Main()
BYTE CRSINH=$02F0 ;Controls visibility of cursor
Print("Hiding the cursor...")
Wait(50)
CRSINH=1 PutE() ;put the new line character to force hide the cursor
Wait(50)
Print("Showing the cursor...")
Wait(50)
CRSINH=0 PutE() ;put the new line character to force show the cursor
Wait(50)
RETURN |
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.
| #11l | 11l | print("\033[7mReversed\033[m Normal") |
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.
| #Aime | Aime | integer bads, count, max_bads;
file f;
list l;
real s;
text bad_day, worst_day;
f.stdin;
max_bads = count = bads = s = 0;
while (f.list(l, 0) ^ -1) {
integer i;
i = 2;
while (i < 49) {
if (0 < atoi(l[i])) {
count += 1;
s += atof(l[i - 1]);
if (max_bads < bads) {
max_bads = bads;
worst_day = bad_day;
}
bads = 0;
} else {
if (!bads) {
bad_day = l[0];
}
bads += 1;
}
i += 2;
}
}
o_form("Averaged /d3/ over ~ readings.\n", s / count, count);
o_("Longest bad run ", max_bads, ", started ", worst_day, ".\n"); |
http://rosettacode.org/wiki/Terminal_control/Positional_read | Terminal control/Positional read | Determine the character displayed on the screen at column 3, row 6 and store that character in a variable. Note that it is permissible to utilize system or language provided methods or system provided facilities, system maintained records or available buffers or system maintained display records to achieve this task, rather than query the terminal directly, if those methods are more usual for the system type or language.
| #C | C | #include <windows.h>
#include <wchar.h>
int
main()
{
CONSOLE_SCREEN_BUFFER_INFO info;
COORD pos;
HANDLE conout;
long len;
wchar_t c;
/* Create a handle to the console screen. */
conout = CreateFileW(L"CONOUT$", GENERIC_READ | GENERIC_WRITE,
FILE_SHARE_READ | FILE_SHARE_WRITE, NULL, OPEN_EXISTING,
0, NULL);
if (conout == INVALID_HANDLE_VALUE)
return 1;
/* Where is the display window? */
if (GetConsoleScreenBufferInfo(conout, &info) == 0)
return 1;
/* c = character at position. */
pos.X = info.srWindow.Left + 3; /* Column */
pos.Y = info.srWindow.Top + 6; /* Row */
if (ReadConsoleOutputCharacterW(conout, &c, 1, pos, &len) == 0 ||
len <= 0)
return 1;
wprintf(L"Character at (3, 6) had been '%lc'\n", c);
return 0;
} |
http://rosettacode.org/wiki/Terminal_control/Positional_read | Terminal control/Positional read | Determine the character displayed on the screen at column 3, row 6 and store that character in a variable. Note that it is permissible to utilize system or language provided methods or system provided facilities, system maintained records or available buffers or system maintained display records to achieve this task, rather than query the terminal directly, if those methods are more usual for the system type or language.
| #Common_Lisp | Common Lisp | (defun positional-read ()
(with-screen (scr :input-blocking t :input-echoing nil :cursor-visible nil)
;; print random characters in a 10x20 grid
(loop for i from 0 to 9 do
(loop for j from 0 to 19 do
(add-char scr (+ 33 (random 94)) :y i :x j)))
;; highlight char to extract at row 6 column 3
(change-attributes scr 1 (list :reverse) :y 5 :x 2)
(refresh scr)
;; wait for keypress
(get-char scr)
;; extract char from row 6 column 3
(let ((char (extract-char scr :y 5 :x 2)))
;; then print it out again
(move scr 11 0)
(format scr "extracted char: ~A" char))
(refresh scr)
(get-char scr))) |
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.
| #FreeBASIC | FreeBASIC | ' version 03-11-2016
' compile with: fbc -s console
Dim Shared As UInteger<32> randrsl(256), randcnt
Static Shared As UInteger<32> mm(256)
Static Shared As UInteger<32> aa, bb ,cc
Sub ISAAC()
Dim As UInteger<32> i, x, y
cc = cc + 1
bb = bb + cc
For i = 0 To 256 -1
x = mm(i)
Select Case (i Mod 4)
Case 0 : aa = aa Xor (aa Shl 13)
Case 1 : aa = aa Xor (aa Shr 6)
Case 2 : aa = aa Xor (aa Shl 2)
Case 3 : aa = aa Xor (aa Shr 16)
End Select
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
Next
randcnt = 0
End Sub
#Macro mix(a, b, c, d, e, f, g, h)
a Xor= b Shl 11 : d += a : b += c
b Xor= c Shr 2 : e += b : c += d
c Xor= d Shl 8 : f += c : d += e
d Xor= e Shr 16 : g += d : e += f
e Xor= f Shl 10 : h += e : f += g
f Xor= g Shr 4 : a += f : g += h
g Xor= h Shl 8 : b += g : h += a
h Xor= a Shr 9 : c += h : a += b
#EndMacro
Sub randinit(flag As Long)
Dim As Long i
Dim As UInteger<32> a = &H9e3779b9 '/* the golden ratio *
Dim As UInteger<32> b = &H9e3779b9
Dim As UInteger<32> c = &H9e3779b9
Dim As UInteger<32> d = &H9e3779b9
Dim As UInteger<32> e = &H9e3779b9
Dim As UInteger<32> f = &H9e3779b9
Dim As UInteger<32> g = &H9e3779b9
Dim As UInteger<32> h = &H9e3779b9
aa = 0 : bb = 0 : cc = 0
For i = 0 To 3
mix(a, b, c, d, e, f, g, h)
Next
For i = 0 To 255 Step 8
If flag = 1 Then
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)
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
End If
Next
If flag = 1 Then
For i = 0 To 255 Step 8
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
Next
End If
ISAAC()
randcnt = 0
End Sub
' // Get a random 32-bit value 0..MAXINT
Function iRandom() As UInteger<32>
Dim As UInteger<32> r = randrsl(randcnt)
randcnt += 1
If randcnt > 255 Then
ISAAC()
randcnt = 0
End If
Return r
End Function
' // Get a random character in printable ASCII range
Function iRandA() As UByte
Return iRandom() Mod 95 +32
End Function
' // Seed ISAAC with a string
Sub iSeed(seed As String, flag As Long)
Dim As ULong i, m = Len(seed) -1
For i = 0 To 255
mm(i) = 0
Next
For i = 0 To 255
If i > m Then
randrsl(i) = 0
Else
randrsl(i) = seed[i]
End If
Next
randinit(flag)
End Sub
' // maximum length of message
'#define MAXMSG 4096
#Define _MOD_ 95 ' mod is FreeBASIC keyword
#Define _START_ 32 ' start is used as variable name
' // cipher modes for Caesar
Enum ciphermode
mEncipher
mDecipher
mNone
End Enum
' // XOR cipher on random stream. Output: ASCII string
' no maximum lenght for input and output string
Function Vernam(msg As String) As String
Dim As ULong i
Dim As String v
For i = 0 To Len(msg) -1
v += Chr(iRandA() Xor msg[i])
Next
Return v
End Function
' // Caesar-shift a printable character
Function Ceasar(m As ciphermode, ch As UByte, shift As UByte, modulo As UByte, _
start As UByte) As UByte
' FreeBASIC Mod does not handle negative numbers correctly
' also there is litte problem with shift (declared UByte)
' the IIF() statement helps with shift
' to avoid a negative n a 8 times modulo is added
' modulo * 8 get translateted by FreeBASIC to modulo shl 3
Dim As Long n = (ch - start) + IIf(m = mDecipher, -shift, shift) + modulo * 8
n = n Mod modulo
Return start + n
End Function
' // Caesar-shift a string on a pseudo-random stream
Function CeasarStr(m As ciphermode, msg As String, modulo As UByte, _
start As UByte) As String
Dim As Long i
Dim As String v
For i = 0 To Len(msg) -1
v += Chr(Ceasar(m, msg[i], iRandA(), modulo, start))
Next
Return v
End Function
' ------=< MAIN >=------
Dim As Long n, l
Dim As String msg = "a Top Secret secret"
Dim As String key = "this is my secret key"
Dim As String vctx, vptx
Dim As String cctx, cptx
l = Len(msg)
' // Encrypt: Vernam XOR
iSeed(key, 1)
vctx = Vernam(msg)
' // Encrypt: Caesar
cctx = CeasarStr(mEncipher, msg, _mod_, _start_)
' // Decrypt: Vernam XOR
iSeed(key, 1)
vptx = Vernam(vctx)
' // Decrypt: Caesar
cptx = CeasarStr(mDecipher, cctx, _mod_, _start_)
Print "message: "; msg
Print " key: "; key
Print " XOR: ";
' // Output Vernam ciphertext as a string of hex digits
For n = 0 To l -1
Print Hex(vctx[n], 2);
Next
Print
' // Output Vernam decrypted plaintext
Print "XOR dcr: "; vptx
' // Caesar
Print " MOD: ";
' // Output Caesar ciphertext as a string of hex digits
For n= 0 To l -1
Print Hex(cctx[n], 2);
Next
Print
' // Output Caesar decrypted plaintext
Print "MOD dcr: " ; cptx
' empty keyboard buffer
While InKey <> "" : Wend
Print : Print "hit any key to end program"
Sleep
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.)
| #Free_Pascal | Free Pascal | // in FPC 3.2.0 the definition of `integer` still depends on the compiler mode
{$mode objFPC}
uses
// used for `isInfinite`, `isNan` and `fMod`
math,
// NB: `ucomplex`’s `complex` isn’t a simple data type as ISO 10206 requires
ucomplex;
{ --- determines whether a `float` value is (almost) an `integer` ------ }
function isInteger(x: float; const fuzziness: float = 0.0): Boolean;
// nested routine allows us to spare an `if … then` statement below
function fuzzyInteger: Boolean;
begin
// `x mod 1.0` uses `fMod` function from `math` unit
x := x mod 1.0;
result := (x <= fuzziness) or (x >= 1.0 - fuzziness);
end;
begin
{$push}
// just for emphasis: use lazy evaluation strategy (currently default)
{$boolEval off}
result := not isInfinite(x) and not isNan(x) and fuzzyInteger;
{$pop}
end;
{ --- check whether a `complex` number is (almost) in ℤ ---------------- }
function isInteger(const x: complex; const fuzziness: float = 0.0): Boolean;
begin
// you could use `isZero` from the `math` unit for a fuzzy zero
isInteger := (x.im = 0.0) and isInteger(x.re, fuzziness)
end;
{ --- test routine ----------------------------------------------------- }
procedure test(const x: float);
const
tolerance = 0.00001;
w = 42;
var
s: string;
begin
writeStr(s, 'isInteger(', x);
writeLn(s:w, ') = ', isInteger(x):5,
s:w, ', ', tolerance:7:5, ') = ', isInteger(x, tolerance):5);
end;
{ === MAIN ============================================================= }
begin
test(25.000000);
test(24.999999);
test(25.000100);
test(-2.1e120);
test(-5e-2);
test(NaN);
test(Infinity);
writeLn(isInteger(5.0 + 0.0 * i));
writeLn(isInteger(5 - 5 * i));
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).
| #Mathematica.2FWolfram_Language | Mathematica/Wolfram Language | LC = 0; LCMax = 0; Scan[
If[MemberQ[#, "OUT"], LC++;
If[LCMax < LC, LCMax = LC; LCMaxtimes = {};];
If[LCMax == LC, AppendTo[LCMaxtimes, #[[4]]]],
LC--;] &, Import["mlijobs.txt", "Table"]]
Print["The maximum number of licenses used was ", LCMax, ", at ", LCMaxtimes] |
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.
| #Factor | Factor | USING: kernel sequences ;
IN: palindrome
: palindrome? ( string -- ? ) dup reverse = ; |
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.
| #Fantom | Fantom |
class TestPalindrome : Test
{
public Void testIsPalindrome ()
{
verify(Palindrome.isPalindrome(""))
verify(Palindrome.isPalindrome("a"))
verify(Palindrome.isPalindrome("aa"))
verify(Palindrome.isPalindrome("aba"))
verifyFalse(Palindrome.isPalindrome("abb"))
verify(Palindrome.isPalindrome("salàlas"))
verify(Palindrome.isPalindrome("In girum imus nocte et consumimur igni".lower.replace(" ","")))
}
}
|
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.
| #Ruby | Ruby | require 'set'
def munge2(readings, debug=false)
datePat = /^\d{4}-\d{2}-\d{2}/
valuPat = /^[-+]?\d+\.\d+/
statPat = /^-?\d+/
totalLines = 0
dupdate, badform, badlen, badreading = Set[], Set[], Set[], 0
datestamps = Set[[]]
for line in readings
totalLines += 1
fields = line.split(/\t/)
date = fields.shift
pairs = fields.enum_slice(2).to_a
lineFormatOk = date =~ datePat &&
pairs.all? { |x,y| x =~ valuPat && y =~ statPat }
if !lineFormatOk
puts 'Bad formatting ' + line if debug
badform << date
end
if pairs.length != 24 ||
pairs.any? { |x,y| y.to_i < 1 }
puts 'Missing values ' + line if debug
end
if pairs.length != 24
badlen << date
end
if pairs.any? { |x,y| y.to_i < 1 }
badreading += 1
end
if datestamps.include?(date)
puts 'Duplicate datestamp ' + line if debug
dupdate << date
end
datestamps << date
end
puts 'Duplicate dates:', dupdate.sort.map { |x| ' ' + x }
puts 'Bad format:', badform.sort.map { |x| ' ' + x }
puts 'Bad number of fields:', badlen.sort.map { |x| ' ' + x }
puts 'Records with good readings: %i = %5.2f%%' % [
totalLines-badreading, (totalLines-badreading)/totalLines.to_f*100 ]
puts
puts 'Total records: %d' % totalLines
end
open('readings.txt','r') do |readings|
munge2(readings)
end |
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.
| #Lua | Lua | 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.
| #M2000_Interpreter | M2000 Interpreter |
Module CheckIt {
After 300 {beep}
Print "Begin"
for i=0 to 100 {
wait 10
Print i
}
Print "End"
}
CheckIt
|
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.
| #Mathematica.2FWolfram_Language | Mathematica/Wolfram Language | Print["\007"] |
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.
| #MUMPS | MUMPS | write $char(7) |
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
| #AppleScript | AppleScript | set gifts to {"A partridge in a pear tree.", "Two turtle doves, and", ¬
"Three French hens,", "Four calling birds,", ¬
"Five gold rings,", "Six geese a-laying,", ¬
"Seven swans a-swimming,", "Eight maids a-milking,", ¬
"Nine ladies dancing,", "Ten lords a-leaping,", ¬
"Eleven pipers piping,", "Twelve drummers drumming"}
set labels to {"first", "second", "third", "fourth", "fifth", "sixth", ¬
"seventh", "eighth", "ninth", "tenth", "eleventh", "twelfth"}
repeat with day from 1 to 12
log "On the " & item day of labels & " day of Christmas, my true love sent to me:"
repeat with gift from day to 1 by -1
log item gift of gifts
end repeat
log ""
end repeat |
http://rosettacode.org/wiki/Terminal_control/Preserve_screen | Terminal control/Preserve screen |
Task
Clear the screen, output something on the display, and then restore the screen to the preserved state that it was in before the task was carried out.
There is no requirement to change the font or kerning in this task, however character decorations and attributes are expected to be preserved. If the implementer decides to change the font or kerning during the display of the temporary screen, then these settings need to be restored prior to exit.
| #Kotlin | Kotlin | // version 1.1.2
const val ESC = "\u001B"
fun main(args: Array<String>) {
print("$ESC[?1049h$ESC[H")
println("Alternate screen buffer")
for(i in 5 downTo 1) {
print("\rGoing back in $i second${if (i != 1) "s" else ""}...")
Thread.sleep(1000)
}
print("$ESC[?1049l")
} |
http://rosettacode.org/wiki/Terminal_control/Preserve_screen | Terminal control/Preserve screen |
Task
Clear the screen, output something on the display, and then restore the screen to the preserved state that it was in before the task was carried out.
There is no requirement to change the font or kerning in this task, however character decorations and attributes are expected to be preserved. If the implementer decides to change the font or kerning during the display of the temporary screen, then these settings need to be restored prior to exit.
| #M2000_Interpreter | M2000 Interpreter |
Module PreserveScreen {
Bold 1
Font "Arial"
Paper=#225511
SplitScreenRow=0
Cls Paper, SplitScreenRow
Print "Test"
Gosub GetState
Font "Tahoma"
Bold 1 : Italic 1: Pen 15
cls 0, 5
For i=1 to 100 : Print i: Next i
Move 6000,6000
For i=1000 to 6000 step 1000 : Circle i : Next i
WaitKey$=Key$
Gosub RestoreState
Print "End"
End
GetState:
prevfont$=fontname$
prevbold=bold
previtalic=italic
prevpen=pen
posx=pos
posy=row
graphicx=pos.x
graphicy=pos.y
OldPaper=Paper
OldSplit=SplitScreenRow
Hold
Return
RestoreState:
Paper=OldPaper
SplitScreenRow=OldSplit
Cls Paper, SplitScreenRow
Release
font prevfont$
bold prevbold
italic previtalic
pen prevpen
cursor posx, posy
move graphicx, graphicy
Return
}
PreserveScreen
|
http://rosettacode.org/wiki/Terminal_control/Preserve_screen | Terminal control/Preserve screen |
Task
Clear the screen, output something on the display, and then restore the screen to the preserved state that it was in before the task was carried out.
There is no requirement to change the font or kerning in this task, however character decorations and attributes are expected to be preserved. If the implementer decides to change the font or kerning during the display of the temporary screen, then these settings need to be restored prior to exit.
| #Mathematica.2FWolfram_Language | Mathematica/Wolfram Language | Run["tput smcup"] (* Save the display *)
Run["echo Hello"]
Pause[5] (* Wait five seconds *)
Run["tput rmcup"] |
http://rosettacode.org/wiki/Terminal_control/Preserve_screen | Terminal control/Preserve screen |
Task
Clear the screen, output something on the display, and then restore the screen to the preserved state that it was in before the task was carried out.
There is no requirement to change the font or kerning in this task, however character decorations and attributes are expected to be preserved. If the implementer decides to change the font or kerning during the display of the temporary screen, then these settings need to be restored prior to exit.
| #Nim | Nim | import os
echo "\e[?1049h\e[H"
echo "Alternate buffer!"
for i in countdown(5, 1):
echo "Going back in: ", i
sleep 1000
echo "\e[?1049l" |
http://rosettacode.org/wiki/Terminal_control/Preserve_screen | Terminal control/Preserve screen |
Task
Clear the screen, output something on the display, and then restore the screen to the preserved state that it was in before the task was carried out.
There is no requirement to change the font or kerning in this task, however character decorations and attributes are expected to be preserved. If the implementer decides to change the font or kerning during the display of the temporary screen, then these settings need to be restored prior to exit.
| #Perl | Perl | print "\033[?1049h\033[H";
print "Alternate screen buffer\n";
for (my $i = 5; $i > 0; --$i) {
print "going back in $i...\n";
sleep(1);
}
print "\033[?1049l"; |
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.
| #Ada | Ada | with Ada.Text_Io;
with Ansi;
procedure Hiding is
use Ada.Text_Io;
begin
Put ("Hiding the cursor for 2.0 seconds...");
delay 0.500;
Put (Ansi.Hide);
delay 2.000;
Put ("And showing again.");
delay 0.500;
Put (Ansi.Show);
delay 2.000;
New_Line;
end Hiding; |
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.
| #Arturo | Arturo | cursor false
print "hiding the cursor"
pause 2000
cursor true
print "showing 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.
| #AutoHotkey | AutoHotkey | DllCall("AllocConsole") ; Create a console if not launched from one
hConsole := DllCall("GetStdHandle", UInt, STDOUT := -11)
VarSetCapacity(cci, 8) ; CONSOLE_CURSOR_INFO structure
DllCall("GetConsoleCursorInfo", UPtr, hConsole, UPtr, &cci)
NumPut(0, cci, 4)
DllCall("SetConsoleCursorInfo", UPtr, hConsole, UPtr, &cci)
FileAppend, Cursor hidden for 3 seconds..., CONOUT$ ; Prints to stdout
Sleep 3000
NumPut(1, cci, 4)
DllCall("SetConsoleCursorInfo", UPtr, hConsole, UPtr, &cci)
FileAppend, `nCursor shown, CONOUT$
MsgBox |
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.
| #6502_Assembly | 6502 Assembly | tmpx -i inverse-video.s -o inverse-video.prg
|
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.
| #Action.21 | Action! | PROC PrintInv(CHAR ARRAY a)
BYTE i
IF a(0)>0 THEN
FOR i=1 TO a(0)
DO
Put(a(i)%$80)
OD
FI
RETURN
PROC Main()
Position(2,2)
PrintInv("Inverse")
Print(" video")
RETURN |
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.
| #Ada | Ada | with Ada.Text_IO; use Ada.Text_IO;
procedure Reverse_Video is
Rev_Video : String := Ascii.ESC & "[7m";
Norm_Video : String := Ascii.ESC & "[m";
begin
Put (Rev_Video & "Reversed");
Put (Norm_Video & " Normal");
end Reverse_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.
| #ARM_Assembly | ARM Assembly | ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
; Program Start
.equ ramarea, 0x02000000
.equ CursorX,ramarea
.equ CursorY,ramarea+1
ProgramStart:
mov sp,#0x03000000 ;Init Stack Pointer
mov r4,#0x04000000 ;DISPCNT -LCD Control
mov r2,#0x403 ;4= Layer 2 on / 3= ScreenMode 3
str r2,[r4]
bl ResetTextCursors ;set text cursors to top left of screen
adr r1,HelloWorld
mov r2,#0x7FFF
mov r11,#1
bl PrintString
adr r1,HelloWorld
mov r2,#0x7FFF
mov r11,#0
bl PrintString
forever:
b forever
BitmapFont:
.include "M:\SrcAll\BitmapFont.asm"
HelloWorld:
.byte "HELLO",255
.align 4
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
PrintString: ;Print 255 terminated string
STMFD sp!,{r0-r12, lr}
PrintStringAgain:
ldrB r0,[r1],#1
cmp r0,#255
beq PrintStringDone ;Repeat until 255
bl printchar ;Print Char
b PrintStringAgain
PrintStringDone:
LDMFD sp!,{r0-r12, lr}
bx lr
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
PrintChar:
;input: R1 = ADDR OF TEXT
; R2 = DESIRED COLOR (ABBBBBGGGGGRRRRR A=Alpha)
; CursorX = X POS OF WHERE TO DRAW
; CursorY = Y POS OF WHERE TO DRAW
; R11 = 1 FOR INVERTED TEXT, 0 FOR NORMAL TEXT
STMFD sp!,{r4-r12, lr}
mov r4,#0
mov r5,#0
mov r3,#CursorX
ldrB r4,[r3] ;X pos
mov r3,#CursorY
ldrB r5,[r3] ;Y pos
mov r3,#0x06000000 ;VRAM base
mov r6,r4,lsl #4 ;Xpos, 2 bytes per pixel, 8 bytes per char
add r3,r3,r6
;Ypos, 240 pixels per line,2 bytes per pixel, 8 lines per char
mov r4,r5,lsl #4
mov r5,r5,lsl #8
sub r6,r5,r4
mov r6,r6,lsl #4 ;ypos * 240 * 8 * 2 = ((((ypos << 8)-(ypos << 4)) << 3)<< 1
add r3,r3,r6
adr r4,BitmapFont ;Font source
subs r0,r0,#32 ;First Char is 32 (space)
beq LineDone ;if it's a space, just move the cursor without actually writing anything
add r4,r4,r0,asl #3 ;8 bytes per char
mov r6,#8 ;8 lines
DrawLine:
mov r7,#8 ;8 pixels per line
ldrb r8,[r4],#1 ;Load this piece of the letter
cmp r11,#1 ;does r11 = 1?
mvneq r8,r8 ;if so, flip the bits of r8 before printing.
mov r9,#0b100000000 ;Bit Mask for testing whether to fill
DrawPixel:
tst r8,r9 ;Is bit 1?
strneh r2,[r3] ;Yes? then fill pixel (HalfWord)
add r3,r3,#2
mov r9,r9,ror #1 ;Bitshift Mask
subs r7,r7,#1
bne DrawPixel ;Next Hpixel
add r3,r3,#480-16 ;Move Down a line (240 pixels * 2 bytes)
subs r6,r6,#1 ;-1 char (16 px)
bne DrawLine ;Next Vline
LineDone:
mov r3,#CursorX
ldrB r0,[r3]
add r0,r0,#1 ;Move across screen
strB r0,[r3]
mov r10,#30
cmp r0,r10
bleq NewLine
LDMFD sp!,{r4-r12, lr}
bx lr
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
NewLine:
STMFD sp!,{r0-r12, lr}
mov r3,#CursorX
mov r0,#0
strB r0,[r3]
mov r4,#CursorY
ldrB r0,[r4]
add r0,r0,#1
strB r0,[r4]
LDMFD sp!,{r0-r12, pc}
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
ResetTextCursors:
STMFD sp!,{r4-r6,lr}
mov r4,#0
mov r5,#CursorX
mov r6,#CursorY
strB r4,[r5]
strB r4,[r6]
LDMFD sp!,{r4-r6,lr}
bx lr |
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
| #Action.21 | Action! | DEFINE TERNARY="BYTE"
DEFINE FALSE="0"
DEFINE MAYBE="1"
DEFINE TRUE="2"
PROC PrintT(TERNARY a)
IF a=FALSE THEN Print("F")
ELSEIF a=MAYBE THEN Print("?")
ELSE Print("T")
FI
RETURN
TERNARY FUNC NotT(TERNARY a)
RETURN (TRUE-a)
TERNARY FUNC AndT(TERNARY a,b)
IF a<b THEN RETURN (a) FI
RETURN (b)
TERNARY FUNC OrT(TERNARY a,b)
IF a>b THEN RETURN (a) FI
RETURN (b)
TERNARY FUNC IfThenT(TERNARY a,b)
IF a=TRUE THEN RETURN (b)
ELSEIF a=FALSE THEN RETURN (TRUE)
ELSEIF a+b>TRUE THEN RETURN (TRUE)
FI
RETURN (MAYBE)
TERNARY FUNC EquivT(TERNARY a,b)
IF a=b THEN RETURN (TRUE)
ELSEIF a=TRUE THEN RETURN (b)
ELSEIF b=TRUE THEN RETURN (a)
FI
RETURN (MAYBE)
PROC Main()
BYTE x,y,a,b,res
x=2 y=1
FOR a=FALSE TO TRUE
DO
res=NotT(a)
Position(x,y) y==+1
Print("not ") PrintT(a)
Print(" = ") PrintT(res)
OD
y==+1
FOR a=FALSE TO TRUE
DO
FOR b=FALSE TO TRUE
DO
res=AndT(a,b)
Position(x,y) y==+1
PrintT(a) Print(" and ") PrintT(b)
Print(" = ") PrintT(res)
OD
OD
y==+1
FOR a=FALSE TO TRUE
DO
FOR b=FALSE TO TRUE
DO
res=OrT(a,b)
Position(x,y) y==+1
PrintT(a) Print(" or ") PrintT(b)
Print(" = ") PrintT(res)
OD
OD
x=20 y=5
FOR a=FALSE TO TRUE
DO
FOR b=FALSE TO TRUE
DO
res=IfThenT(a,b)
Position(x,y) y==+1
Print("if ") PrintT(a)
Print(" then ") PrintT(b)
Print(" = ") PrintT(res)
OD
OD
y==+1
FOR a=FALSE TO TRUE
DO
FOR b=FALSE TO TRUE
DO
res=EquivT(a,b)
Position(x,y) y==+1
PrintT(a) Print(" equiv ") PrintT(b)
Print(" = ") PrintT(res)
OD
OD
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).
| #11l | 11l | print(‘£’) |
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.
| #ALGOL_68 | ALGOL 68 | INT no data := 0; # Current run of consecutive flags<0 in lines of file #
INT no data max := -1; # Max consecutive flags<0 in lines of file #
FLEX[0]STRING no data max line; # ... and line number(s) where it occurs #
REAL tot file := 0; # Sum of file data #
INT num file := 0; # Number of file data items with flag>0 #
# CHAR fs = " "; #
INT nf = 24;
INT upb list := nf;
FORMAT list repr = $n(upb list-1)(g", ")g$;
PROC exception = ([]STRING args)VOID:(
putf(stand error, ($"Exception"$, $", "g$, args, $l$));
stop
);
PROC raise io error = (STRING message)VOID:exception(("io error", message));
OP +:= = (REF FLEX []STRING rhs, STRING append)REF FLEX[]STRING: (
HEAP [UPB rhs+1]STRING out rhs;
out rhs[:UPB rhs] := rhs;
out rhs[UPB rhs+1] := append;
rhs := out rhs;
out rhs
);
INT upb opts = 3; # these are "a68g" "./Data_Munging.a68" & "-" #
[argc - upb opts]STRING in files;
FOR arg TO UPB in files DO in files[arg] := argv(upb opts + arg) OD;
MODE FIELD = STRUCT(REAL data, INT flag);
FORMAT field repr = $2(g)$;
FOR index file TO UPB in files DO
STRING file name = in files[index file], FILE file;
IF open(file, file name, stand in channel) NE 0 THEN
raise io error("Cannot open """+file name+"""") FI;
on logical file end(file, (REF FILE f)BOOL: logical file end done);
REAL tot line, INT num line;
# make term(file, ", ") for CSV data #
STRING date;
DO
tot line := 0; # sum of line data #
num line := 0; # number of line data items with flag>0 #
# extract field info #
[nf]FIELD data;
getf(file, ($10a$, date, field repr, data, $l$));
FOR key TO UPB data DO
FIELD field = data[key];
IF flag OF field<1 THEN
no data +:= 1
ELSE
# check run of data-absent data #
IF no data max = no data AND no data>0 THEN
no data max line +:= date FI;
IF no data max<no data AND no data>0 THEN
no data max := no data;
no data max line := date FI;
# re-initialise run of no data counter #
no data := 0;
# gather values for averaging #
tot line +:= data OF field;
num line +:= 1
FI
OD;
# totals for the file so far #
tot file +:= tot line;
num file +:= num line;
printf(($"Line: "g" Reject: "g(-2)" Accept: "g(-2)" Line tot: "g(-14, 3)" Line avg: "g(-14, 3)l$,
date,
UPB(data) -num line,
num line, tot line,
IF num line>0 THEN tot line/num line ELSE 0 FI))
OD;
logical file end done:
close(file)
OD;
FORMAT plural = $b(" ", "s")$,
p = $b("", "s")$;
upb list := UPB in files;
printf(($l"File"f(plural)" = "$, upb list = 1, list repr, in files, $l$,
$"Total = "g(-0, 3)l$, tot file,
$"Readings = "g(-0)l$, num file,
$"Average = "g(-0, 3)l$, tot file / num file));
upb list := UPB no data max line;
printf(($l"Maximum run"f(p)" of "g(-0)" consecutive false reading"f(p)" ends at line starting with date"f(p)": "$,
upb list = 1, no data max, no data max = 0, upb list = 1, list repr, no data max line, $l$)) |
http://rosettacode.org/wiki/Terminal_control/Positional_read | Terminal control/Positional read | Determine the character displayed on the screen at column 3, row 6 and store that character in a variable. Note that it is permissible to utilize system or language provided methods or system provided facilities, system maintained records or available buffers or system maintained display records to achieve this task, rather than query the terminal directly, if those methods are more usual for the system type or language.
| #Go | Go | package main
/*
#include <windows.h>
*/
import "C"
import "fmt"
func main() {
for i := 0; i < 80*25; i++ {
fmt.Print("A") // fill 80 x 25 console with 'A's
}
fmt.Println()
conOut := C.GetStdHandle(C.STD_OUTPUT_HANDLE)
info := C.CONSOLE_SCREEN_BUFFER_INFO{}
pos := C.COORD{}
C.GetConsoleScreenBufferInfo(conOut, &info)
pos.X = info.srWindow.Left + 3 // column number 3 of display window
pos.Y = info.srWindow.Top + 6 // row number 6 of display window
var c C.wchar_t
var le C.ulong
ret := C.ReadConsoleOutputCharacterW(conOut, &c, 1, pos, &le)
if ret == 0 || le <= 0 {
fmt.Println("Something went wrong!")
return
}
fmt.Printf("The character at column 3, row 6 is '%c'\n", c)
} |
http://rosettacode.org/wiki/Terminal_control/Positional_read | Terminal control/Positional read | Determine the character displayed on the screen at column 3, row 6 and store that character in a variable. Note that it is permissible to utilize system or language provided methods or system provided facilities, system maintained records or available buffers or system maintained display records to achieve this task, rather than query the terminal directly, if those methods are more usual for the system type or language.
| #Julia | Julia | using LibNCurses
randtxt(n) = foldl(*, rand(split("1234567890abcdefghijklmnopqrstuvwxyz", ""), n))
initscr()
for i in 1:20
LibNCurses.mvwaddstr(i, 1, randtxt(50))
end
row = rand(1:20)
col = rand(1:50)
ch = LibNCurses.winch(row, col)
LibNCurses.mvwaddstr(col, 52, "The character at ($row, $col) is $ch.") )
|
http://rosettacode.org/wiki/Terminal_control/Positional_read | Terminal control/Positional read | Determine the character displayed on the screen at column 3, row 6 and store that character in a variable. Note that it is permissible to utilize system or language provided methods or system provided facilities, system maintained records or available buffers or system maintained display records to achieve this task, rather than query the terminal directly, if those methods are more usual for the system type or language.
| #Kotlin | Kotlin | // Kotlin Native version 0.3
import kotlinx.cinterop.*
import win32.*
fun main(args: Array<String>) {
for (i in 0 until (80 * 25)) print("A") // fill 80 x 25 console with 'A's
println()
memScoped {
val conOut = GetStdHandle(-11)
val info = alloc<CONSOLE_SCREEN_BUFFER_INFO>()
val pos = alloc<COORD>()
GetConsoleScreenBufferInfo(conOut, info.ptr)
pos.X = (info.srWindow.Left + 3).toShort() // column number 3 of display window
pos.Y = (info.srWindow.Top + 6).toShort() // row number 6 of display window
val c = alloc<wchar_tVar>()
val len = alloc<IntVar>()
ReadConsoleOutputCharacterW(conOut, c.ptr, 1, pos.readValue(), len.ptr)
if (len.value == 1) {
val ch = c.value.toChar()
println("The character at column 3, row 6 is '$ch'")
}
else println("Something went wrong!")
}
} |
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.
| #Go | Go | package main
import "fmt"
const (
msg = "a Top Secret secret"
key = "this is my secret key"
)
func main() {
var z state
z.seed(key)
fmt.Println("Message: ", msg)
fmt.Println("Key : ", key)
fmt.Println("XOR : ", z.vernam(msg))
}
type state struct {
aa, bb, cc uint32
mm [256]uint32
randrsl [256]uint32
randcnt int
}
func (z *state) isaac() {
z.cc++
z.bb += z.cc
for i, x := range z.mm {
switch i % 4 {
case 0:
z.aa = z.aa ^ z.aa<<13
case 1:
z.aa = z.aa ^ z.aa>>6
case 2:
z.aa = z.aa ^ z.aa<<2
case 3:
z.aa = z.aa ^ z.aa>>16
}
z.aa += z.mm[(i+128)%256]
y := z.mm[x>>2%256] + z.aa + z.bb
z.mm[i] = y
z.bb = z.mm[y>>10%256] + x
z.randrsl[i] = z.bb
}
}
func (z *state) randInit() {
const gold = uint32(0x9e3779b9)
a := [8]uint32{gold, gold, gold, gold, gold, gold, gold, gold}
mix1 := func(i int, v uint32) {
a[i] ^= v
a[(i+3)%8] += a[i]
a[(i+1)%8] += a[(i+2)%8]
}
mix := func() {
mix1(0, a[1]<<11)
mix1(1, a[2]>>2)
mix1(2, a[3]<<8)
mix1(3, a[4]>>16)
mix1(4, a[5]<<10)
mix1(5, a[6]>>4)
mix1(6, a[7]<<8)
mix1(7, a[0]>>9)
}
for i := 0; i < 4; i++ {
mix()
}
for i := 0; i < 256; i += 8 {
for j, rj := range z.randrsl[i : i+8] {
a[j] += rj
}
mix()
for j, aj := range a {
z.mm[i+j] = aj
}
}
for i := 0; i < 256; i += 8 {
for j, mj := range z.mm[i : i+8] {
a[j] += mj
}
mix()
for j, aj := range a {
z.mm[i+j] = aj
}
}
z.isaac()
}
func (z *state) seed(seed string) {
for i, r := range seed {
if i == 256 {
break
}
z.randrsl[i] = uint32(r)
}
z.randInit()
}
func (z *state) random() (r uint32) {
r = z.randrsl[z.randcnt]
z.randcnt++
if z.randcnt == 256 {
z.isaac()
z.randcnt = 0
}
return
}
func (z *state) randA() byte {
return byte(z.random()%95 + 32)
}
func (z *state) vernam(msg string) string {
b := []byte(msg)
for i := range b {
b[i] ^= z.randA()
}
return fmt.Sprintf("%X", b)
} |
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.)
| #Go | Go | package main
import (
"fmt"
"math"
"math/big"
"reflect"
"strings"
"unsafe"
)
// Go provides an integerness test only for the big.Rat and big.Float types
// in the standard library.
// The fundamental piece of code needed for built-in floating point types
// is a test on the float64 type:
func Float64IsInt(f float64) bool {
_, frac := math.Modf(f)
return frac == 0
}
// Other built-in or stanadard library numeric types are either always
// integer or can be easily tested using Float64IsInt.
func Float32IsInt(f float32) bool {
return Float64IsInt(float64(f))
}
func Complex128IsInt(c complex128) bool {
return imag(c) == 0 && Float64IsInt(real(c))
}
func Complex64IsInt(c complex64) bool {
return imag(c) == 0 && Float64IsInt(float64(real(c)))
}
// Usually just the above statically typed functions would be all that is used,
// but if it is desired to have a single function that can test any arbitrary
// type, including the standard math/big types, user defined types based on
// an integer, float, or complex builtin types, or user defined types that
// have an IsInt() method, then reflection can be used.
type hasIsInt interface {
IsInt() bool
}
var bigIntT = reflect.TypeOf((*big.Int)(nil))
func IsInt(i interface{}) bool {
if ci, ok := i.(hasIsInt); ok {
// Handles things like *big.Rat
return ci.IsInt()
}
switch v := reflect.ValueOf(i); v.Kind() {
case reflect.Int, reflect.Int8, reflect.Int16,
reflect.Int32, reflect.Int64,
reflect.Uint, reflect.Uint8, reflect.Uint16,
reflect.Uint32, reflect.Uint64, reflect.Uintptr:
// Built-in types and any custom type based on them
return true
case reflect.Float32, reflect.Float64:
// Built-in floats and anything based on them
return Float64IsInt(v.Float())
case reflect.Complex64, reflect.Complex128:
// Built-in complexes and anything based on them
return Complex128IsInt(v.Complex())
case reflect.String:
// Could also do strconv.ParseFloat then FloatIsInt but
// big.Rat handles everything ParseFloat can plus more.
// Note, there is no strconv.ParseComplex.
if r, ok := new(big.Rat).SetString(v.String()); ok {
return r.IsInt()
}
case reflect.Ptr:
// Special case for math/big.Int
if v.Type() == bigIntT {
return true
}
}
return false
}
// The rest is just demonstration and display
type intbased int16
type complexbased complex64
type customIntegerType struct {
// Anything that stores or represents a sub-set
// of integer values in any way desired.
}
func (customIntegerType) IsInt() bool { return true }
func (customIntegerType) String() string { return "<…>" }
func main() {
hdr := fmt.Sprintf("%27s %-6s %s\n", "Input", "IsInt", "Type")
show2 := func(t bool, i interface{}, args ...interface{}) {
istr := fmt.Sprint(i)
fmt.Printf("%27s %-6t %T ", istr, t, i)
fmt.Println(args...)
}
show := func(i interface{}, args ...interface{}) {
show2(IsInt(i), i, args...)
}
fmt.Print("Using Float64IsInt with float64:\n", hdr)
neg1 := -1.
for _, f := range []float64{
0, neg1 * 0, -2, -2.000000000000001, 10. / 2, 22. / 3,
math.Pi,
math.MinInt64, math.MaxUint64,
math.SmallestNonzeroFloat64, math.MaxFloat64,
math.NaN(), math.Inf(1), math.Inf(-1),
} {
show2(Float64IsInt(f), f)
}
fmt.Print("\nUsing Complex128IsInt with complex128:\n", hdr)
for _, c := range []complex128{
3, 1i, 0i, 3.4,
} {
show2(Complex128IsInt(c), c)
}
fmt.Println("\nUsing reflection:")
fmt.Print(hdr)
show("hello")
show(math.MaxFloat64)
show("9e100")
f := new(big.Float)
show(f)
f.SetString("1e-3000")
show(f)
show("(4+0i)", "(complex strings not parsed)")
show(4 + 0i)
show(rune('§'), "or rune")
show(byte('A'), "or byte")
var t1 intbased = 5200
var t2a, t2b complexbased = 5 + 0i, 5 + 1i
show(t1)
show(t2a)
show(t2b)
x := uintptr(unsafe.Pointer(&t2b))
show(x)
show(math.MinInt32)
show(uint64(math.MaxUint64))
b, _ := new(big.Int).SetString(strings.Repeat("9", 25), 0)
show(b)
r := new(big.Rat)
show(r)
r.SetString("2/3")
show(r)
show(r.SetFrac(b, new(big.Int).SetInt64(9)))
show("12345/5")
show(new(customIntegerType))
} |
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).
| #MAXScript | MAXScript | fn licencesInUse =
(
local logFile = openFile "mlijobs.txt"
local out = 0
local maxOut = -1
local maxTimes = #()
while not EOF logFile do
(
line = readLine logFile
if findString line "OUT" != undefined then
(
out += 1
)
else
(
out -= 1
)
if out > maxOut then
(
maxOut = out
maxTimes = #()
)
if out == maxOut then
(
append maxTimes (filterString line " ")[4]
)
)
format "Maximum simultaneous license use is % at the following times:\n" maxOut
for time in maxTimes do
(
format "%\n" time
)
close logFile
)
licencesInUse() |
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).
| #Nim | Nim | import strutils
var
curOut = 0
maxOut = -1
maxTimes = newSeq[string]()
for job in lines "mlijobs.txt":
if "OUT" in job: inc curOut else: dec curOut
if curOut > maxOut:
maxOut = curOut
maxTimes.setLen(0)
if curOut == maxOut:
maxTimes.add job.split[3]
echo "Maximum simultaneous license use is ", maxOut, " at the following times:"
for i in maxTimes: echo " ", i |
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.
| #Fortran | Fortran |
Sub StrReverse(Byref text As String)
Dim As Integer x, lt = Len(text)
For x = 0 To lt Shr 1 - 1
Swap text[x], text[lt - x - 1]
Next x
End Sub
Sub Replace(Byref T As String, Byref I As String, Byref S As String, Byval A As Integer = 1)
Var p = Instr(A, T, I), li = Len(I), ls = Len(S) : If li = ls Then li = 0
Do While p
If li Then T = Left(T, p - 1) & S & Mid(T, p + li) Else Mid(T, p) = S
p = Instr(p + ls, T, I)
Loop
End Sub
Function IsPalindrome(Byval txt As String) As Boolean
Dim As String tempTxt = Lcase(txt), copyTxt = Lcase(txt)
Replace(tempTxt, " ", "")
Replace(copyTxt, " ", "")
StrReverse(tempTxt)
If tempTxt = copyTxt Then
Color 10
Return true
Else
Color 12
Return false
End If
End Function
'--- Programa Principal ---
Dim As String a(10) => {"abba", "mom", "dennis sinned", "Un roc lamina l animal cornu", _
"palindrome", "ba _ ab", "racecars", "racecar", "wombat", "in girum imus nocte et consumimur igni"}
Print !"¨Pal¡ndromos?\n"
For i As Byte = 0 To Ubound(a)-1
Print a(i) & " -> ";
Print IsPalindrome((a(i)))
Color 7
Next i
Sleep
|
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.
| #Scala | Scala | object DataMunging2 {
import scala.io.Source
import scala.collection.immutable.{TreeMap => Map}
val pattern = """^(\d+-\d+-\d+)""" + """\s+(\d+\.\d+)\s+(-?\d+)""" * 24 + "$" r;
def main(args: Array[String]) {
val files = args map (new java.io.File(_)) filter (file => file.isFile && file.canRead)
val (numFormatErrors, numValidRecords, dateMap) =
files.iterator.flatMap(file => Source fromFile file getLines ()).
foldLeft((0, 0, new Map[String, Int] withDefaultValue 0)) {
case ((nFE, nVR, dM), line) => pattern findFirstMatchIn line map (_.subgroups) match {
case Some(List(date, rawData @ _*)) =>
val allValid = (rawData map (_ toDouble) iterator) grouped 2 forall (_.last > 0)
(nFE, nVR + (if (allValid) 1 else 0), dM(date) += 1)
case None => (nFE + 1, nVR, dM)
}
}
dateMap foreach {
case (date, repetitions) if repetitions > 1 => println(date+": "+repetitions+" repetitions")
case _ =>
}
println("""|
|Valid records: %d
|Duplicated dates: %d
|Duplicated records: %d
|Data format errors: %d
|Invalid data records: %d
|Total records: %d""".stripMargin format (
numValidRecords,
dateMap filter { case (_, repetitions) => repetitions > 1 } size,
dateMap.valuesIterable filter (_ > 1) map (_ - 1) sum,
numFormatErrors,
dateMap.valuesIterable.sum - numValidRecords,
dateMap.valuesIterable.sum))
}
} |
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.
| #Nanoquery | Nanoquery | print chr(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.
| #Nemerle | Nemerle | using System.Console;
module Beep
{
Main() : void
{
Write("\a");
System.Threading.Thread.Sleep(1000);
Beep();
System.Threading.Thread.Sleep(1000);
Beep(2600, 1000); // limited OS support
}
} |
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.
| #NetRexx | NetRexx | /* NetRexx */
options replace format comments java crossref symbols binary
runSample(arg)
return
-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
method runSample(arg) private static
do
BEL = 8x07
jtk = java.awt.toolkit.getDefaultToolkit()
say 'Bing!'(Rexx BEL).d2c
Thread.sleep(500)
say 'Ding\x07-ding\u0007!'
Thread.sleep(500)
say 'Beep!'
jtk.beep()
catch ex = Exception
ex.printStackTrace()
end
return
|
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.
| #Nim | Nim | echo "\a" |
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
| #Arturo | Arturo | gifts: [
"A partridge in a pear tree."
"Two turtle doves"
"Three french hens"
"Four calling birds"
"Five golden rings"
"Six geese a-laying"
"Seven swans a-swimming"
"Eight maids a-milking"
"Nine ladies dancing"
"Ten lords a-leaping"
"Eleven pipers piping"
"Twelve drummers drumming"
]
days: ["first" "second" "third" "fourth" "fifth" "sixth"
"seventh" "eighth" "ninth" "tenth" "eleventh" "twelfth"]
loop.with:'n days 'day [
g: reverse slice gifts 0 n
print ~"On the |day| day of Christmas\n" ++
"My true love gave to me:\n" ++
(join.with:"\n" chop g) ++
(n>0)? -> " and \n" ++ last g
-> capitalize last g
print ""
] |
http://rosettacode.org/wiki/Terminal_control/Preserve_screen | Terminal control/Preserve screen |
Task
Clear the screen, output something on the display, and then restore the screen to the preserved state that it was in before the task was carried out.
There is no requirement to change the font or kerning in this task, however character decorations and attributes are expected to be preserved. If the implementer decides to change the font or kerning during the display of the temporary screen, then these settings need to be restored prior to exit.
| #Phix | Phix | without js -- (save_text_image, sleep, display_text_image)
sequence s = save_text_image({1,1}, {25,80})
clear_screen()
puts(1,"\n\n *** hello ***\n")
sleep(5)
display_text_image({1,1}, s)
sleep(3)
|
http://rosettacode.org/wiki/Terminal_control/Preserve_screen | Terminal control/Preserve screen |
Task
Clear the screen, output something on the display, and then restore the screen to the preserved state that it was in before the task was carried out.
There is no requirement to change the font or kerning in this task, however character decorations and attributes are expected to be preserved. If the implementer decides to change the font or kerning during the display of the temporary screen, then these settings need to be restored prior to exit.
| #PicoLisp | PicoLisp | #!/usr/bin/picolisp /usr/lib/picolisp/lib.l
(call 'tput "smcup")
(prinl "something")
(wait 3000)
(call 'tput "rmcup")
(bye) |
http://rosettacode.org/wiki/Terminal_control/Preserve_screen | Terminal control/Preserve screen |
Task
Clear the screen, output something on the display, and then restore the screen to the preserved state that it was in before the task was carried out.
There is no requirement to change the font or kerning in this task, however character decorations and attributes are expected to be preserved. If the implementer decides to change the font or kerning during the display of the temporary screen, then these settings need to be restored prior to exit.
| #Python | Python | #!/usr/bin/env python
import time
print "\033[?1049h\033[H"
print "Alternate buffer!"
for i in xrange(5, 0, -1):
print "Going back in:", i
time.sleep(1)
print "\033[?1049l" |
http://rosettacode.org/wiki/Terminal_control/Preserve_screen | Terminal control/Preserve screen |
Task
Clear the screen, output something on the display, and then restore the screen to the preserved state that it was in before the task was carried out.
There is no requirement to change the font or kerning in this task, however character decorations and attributes are expected to be preserved. If the implementer decides to change the font or kerning during the display of the temporary screen, then these settings need to be restored prior to exit.
| #R | R | cat("\033[?1049h\033[H")
cat("Alternate screen buffer\n")
for (i in 5:1) {
cat("\rgoing back in ", i, "...", sep = "")
Sys.sleep(1)
cat("\33[2J")
}
cat("\033[?1049l") |
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.
| #BaCon | BaCon | ' Hiding the cursor for an ANSI compliant terminal
CURSOR OFF
CURSOR ON |
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.
| #BASIC | BASIC | 'hide the cursor:
LOCATE , , 0
'wait for a keypress...
SLEEP
'show the cursor:
LOCATE , , 1 |
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.
| #BBC_BASIC | BBC BASIC | OFF : REM Hide the cursor
WAIT 400
ON : REM Show the cursor again |
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.
| #Befunge | Befunge | "l52?["39*,,,,,, >v
"retnE sserP">:#,_v>
"h52?["39*,,,,,,@ >~ |
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.
| #AutoHotkey | AutoHotkey | DllCall( "AllocConsole" ) ; create a console if not launched from one
hConsole := DllCall( "GetStdHandle", int, STDOUT := -11 )
SetConsoleTextAttribute(hConsole, 0x70) ; gray background, black foreground
FileAppend, Reversed`n, CONOUT$ ; print to stdout
SetConsoleTextAttribute(hConsole, 0x07) ; black background, gray foreground
FileAppend, Normal, CONOUT$
MsgBox
SetConsoleTextAttribute(hConsole, Attributes){
return DllCall( "SetConsoleTextAttribute", UPtr, hConsole, UShort, Attributes)
} |
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.
| #AWK | AWK | BEGIN {
system ("tput rev")
print "foo"
system ("tput sgr0")
print "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.
| #Axe | Axe | Fix 3
Disp "INVERTED"
Fix 2
Disp "REGULAR",i
Pause 4500 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.