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/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.
| #Mathematica.2FWolfram_Language | Mathematica/Wolfram Language | myFun[x_] := Block[{y},y = x^2; Assert[y > 5]; Sin[y]]
On[Assert];myFun[1.0] |
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.
| #NetRexx | NetRexx | /* NetRexx */
options replace format comments java crossref savelog symbols binary
import junit.framework.TestCase
import RCPalindrome
class RCTestAFunction public final extends TestCase
method setUp public
return
method tearDown public
return
method testIsPal public signals AssertionError
assertTrue(RCPalindrome.isPal(Rexx 'abcba'))
assertTrue(RCPalindrome.isPal(Rexx 'aa'))
assertTrue(RCPalindrome.isPal(Rexx 'a'))
assertTrue(RCPalindrome.isPal(Rexx ''))
assertFalse(RCPalindrome.isPal(Rexx 'ab'))
assertFalse(RCPalindrome.isPal(Rexx 'abcdba'))
return
method except signals RuntimeException
signal RuntimeException()
method main(args = String[]) public constant
testResult = org.junit.runner.JUnitCore.runClasses([RCTestAFunction.class])
secs = Rexx testResult.getRunTime / 1000.0
if testResult.wasSuccessful then say 'Tests successful'
else say 'Tests failed'
say ' failure count:' testResult.getFailureCount
say ' ignore count:' testResult.getIgnoreCount
say ' run count:' testResult.getRunCount
say ' run time:' secs.format(null, 3)
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
| #C.2B.2B | C++ | #include <iostream>
#include <array>
#include <string>
using namespace std;
int main()
{
const array<string, 12> days
{
"first",
"second",
"third",
"fourth",
"fifth",
"sixth",
"seventh",
"eighth",
"ninth",
"tenth",
"eleventh",
"twelfth"
};
const array<string, 12> gifts
{
"And a partridge in a pear tree",
"Two turtle doves",
"Three french hens",
"Four calling birds",
"FIVE GOLDEN RINGS",
"Six geese a-laying",
"Seven swans a-swimming",
"Eight maids a-milking",
"Nine ladies dancing",
"Ten lords a-leaping",
"Eleven pipers piping",
"Twelve drummers drumming"
};
for(int i = 0; i < days.size(); ++i)
{
cout << "On the " << days[i] << " day of christmas, my true love gave to me\n";
if(i == 0)
{
cout << "A partridge in a pear tree\n";
}
else
{
int j = i + 1;
while(j-- > 0) cout << gifts[j] << '\n';
}
cout << '\n';
}
return 0;
} |
http://rosettacode.org/wiki/Terminal_control/Dimensions | Terminal control/Dimensions | Determine the height and width of the terminal, and store this information into variables for subsequent use.
| #Julia | Julia |
julia> using Gtk
julia> screen_size()
(3840, 1080)
julia>
|
http://rosettacode.org/wiki/Terminal_control/Dimensions | Terminal control/Dimensions | Determine the height and width of the terminal, and store this information into variables for subsequent use.
| #Kotlin | Kotlin | // version 1.1.2
/*
I needed to execute the terminal command: 'export COLUMNS LINES'
before running this program for it to work (returned 'null' sizes otherwise).
*/
fun main(args: Array<String>) {
val lines = System.getenv("LINES")
val columns = System.getenv("COLUMNS")
println("Lines = $lines")
println("Columns = $columns")
} |
http://rosettacode.org/wiki/Terminal_control/Dimensions | Terminal control/Dimensions | Determine the height and width of the terminal, and store this information into variables for subsequent use.
| #Locomotive_Basic | Locomotive Basic | 4000 d5 push de
4001 e5 push hl
4002 cd 69 bb call &bb69
4005 ed 53 20 40 ld (&4020),de
4009 22 22 40 ld (&4022),hl
400c e1 pop hl
400d d1 pop de
400e c9 ret |
http://rosettacode.org/wiki/Terminal_control/Coloured_text | Terminal control/Coloured text | Task
Display a word in various colours on the terminal.
The system palette, or colours such as Red, Green, Blue, Magenta, Cyan, and Yellow can be used.
Optionally demonstrate:
How the system should determine if the terminal supports colour
Setting of the background colour
How to cause blinking or flashing (if supported by the terminal)
| #ARM_Assembly | ARM Assembly |
/* ARM assembly Raspberry PI */
/* program colorText.s */
/* Constantes */
.equ STDOUT, 1 @ Linux output console
.equ EXIT, 1 @ Linux syscall
.equ WRITE, 4 @ Linux syscall
.equ BUFFERSIZE, 100
/* Initialized data */
.data
szMessStartPgm: .asciz "Program start \n"
szMessEndPgm: .asciz "Program normal end.\n"
szMessColorRed: .asciz "Color red.\n"
szCodeInit: .asciz "\033[0m" @ color reinit
szCodeRed: .asciz "\033[31m" @ color red
szMessBlue: .asciz "\033[34mColor Blue\n" @ color blue
szMessTwoColor: .asciz "\033[32mColor Green \033[35m Color Velvet\n"
szMessTest: .asciz "\033[33m\033[1mMessage yellow bold\n"
szCarriageReturn: .asciz "\n"
/* UnInitialized data */
.bss
/* code section */
.text
.global main
main:
ldr r0,iAdrszMessStartPgm @ display start message
bl affichageMess
ldr r0,iAdrszCodeRed @ color red
bl affichageMess
ldr r0,iAdrszMessColorRed
bl affichageMess
ldr r0,iAdrszMessBlue @ message color blue
bl affichageMess
ldr r0,iAdrszMessTwoColor @ message two colors
bl affichageMess
ldr r0,iAdrszMessTest
bl affichageMess
ldr r0,iAdrszCodeInit @ color reinitialize
bl affichageMess
ldr r0,iAdrszMessEndPgm @ display end message
bl affichageMess
100: @ standard end of the program
mov r0, #0 @ return code
mov r7, #EXIT @ request to exit program
svc 0 @ perform system call
iAdrszMessStartPgm: .int szMessStartPgm
iAdrszMessEndPgm: .int szMessEndPgm
iAdrszCodeInit: .int szCodeInit
iAdrszCodeRed: .int szCodeRed
iAdrszMessBlue: .int szMessBlue
iAdrszMessColorRed: .int szMessColorRed
iAdrszMessTwoColor: .int szMessTwoColor
iAdrszMessTest: .int szMessTest
iAdrszCarriageReturn: .int szCarriageReturn
/******************************************************************/
/* display text with size calculation */
/******************************************************************/
/* r0 contains the address of the message */
affichageMess:
push {r0,r1,r2,r7,lr} @ save registers
mov r2,#0 @ counter length */
1: @ loop length calculation
ldrb r1,[r0,r2] @ read octet start position + index
cmp r1,#0 @ if 0 its over
addne r2,r2,#1 @ else add 1 in the length
bne 1b @ and loop
@ so here r2 contains the length of the message
mov r1,r0 @ address message in r1
mov r0,#STDOUT @ code to write to the standard output Linux
mov r7, #WRITE @ code call system "write"
svc #0 @ call system
pop {r0,r1,r2,r7,lr} @ restaur registers
bx lr @ return
|
http://rosettacode.org/wiki/Terminal_control/Cursor_movement | Terminal control/Cursor movement | Task
Demonstrate how to achieve movement of the terminal cursor:
how to move the cursor one position to the left
how to move the cursor one position to the right
how to move the cursor up one line (without affecting its horizontal position)
how to move the cursor down one line (without affecting its horizontal position)
how to move the cursor to the beginning of the line
how to move the cursor to the end of the line
how to move the cursor to the top left corner of the screen
how to move the cursor to the bottom right corner of the screen
For the purpose of this task, it is not permitted to overwrite any characters or attributes on any part of the screen (so outputting a space is not a suitable solution to achieve a movement to the right).
Handling of out of bounds locomotion
This task has no specific requirements to trap or correct cursor movement beyond the terminal boundaries, so the implementer should decide what behavior fits best in terms of the chosen language. Explanatory notes may be added to clarify how an out of bounds action would behave and the generation of error messages relating to an out of bounds cursor position is permitted.
| #Axe | Axe | Output(X-1,Y)
Output(X+1,Y)
Output(X,Y-1)
Output(X,Y+1)
Output(0,Y)
Output(15,Y)
Output(0,0)
Output(15,7) |
http://rosettacode.org/wiki/Terminal_control/Cursor_movement | Terminal control/Cursor movement | Task
Demonstrate how to achieve movement of the terminal cursor:
how to move the cursor one position to the left
how to move the cursor one position to the right
how to move the cursor up one line (without affecting its horizontal position)
how to move the cursor down one line (without affecting its horizontal position)
how to move the cursor to the beginning of the line
how to move the cursor to the end of the line
how to move the cursor to the top left corner of the screen
how to move the cursor to the bottom right corner of the screen
For the purpose of this task, it is not permitted to overwrite any characters or attributes on any part of the screen (so outputting a space is not a suitable solution to achieve a movement to the right).
Handling of out of bounds locomotion
This task has no specific requirements to trap or correct cursor movement beyond the terminal boundaries, so the implementer should decide what behavior fits best in terms of the chosen language. Explanatory notes may be added to clarify how an out of bounds action would behave and the generation of error messages relating to an out of bounds cursor position is permitted.
| #BaCon | BaCon | ' ANSI terminal cursor movement
' Default number of positions, if not specified, is 1.
' Left 1 position, blocks at first position
CURSOR BACK 1
' Right 1, blocks at end of line
CURSOR FORWARD 1
' Up 1, column uneffected, blocks at top
CURSOR UP 1
' Down 1, column uneffected, until scroll at bottom
CURSOR DOWN 1
' First column of current row
R = GETY
GOTOXY 1,R
' Last column of current row
C = COLUMNS
GOTOXY C,R
' Home position, top left
GOTOXY 1,1
' Bottom right
R = ROWS
GOTOXY C,R |
http://rosettacode.org/wiki/Terminal_control/Cursor_movement | Terminal control/Cursor movement | Task
Demonstrate how to achieve movement of the terminal cursor:
how to move the cursor one position to the left
how to move the cursor one position to the right
how to move the cursor up one line (without affecting its horizontal position)
how to move the cursor down one line (without affecting its horizontal position)
how to move the cursor to the beginning of the line
how to move the cursor to the end of the line
how to move the cursor to the top left corner of the screen
how to move the cursor to the bottom right corner of the screen
For the purpose of this task, it is not permitted to overwrite any characters or attributes on any part of the screen (so outputting a space is not a suitable solution to achieve a movement to the right).
Handling of out of bounds locomotion
This task has no specific requirements to trap or correct cursor movement beyond the terminal boundaries, so the implementer should decide what behavior fits best in terms of the chosen language. Explanatory notes may be added to clarify how an out of bounds action would behave and the generation of error messages relating to an out of bounds cursor position is permitted.
| #BASIC | BASIC | 10 'move left
20 LOCATE , POS(0) - 1
30 'move right
40 LOCATE , POS(0) + 1
50 'move up
60 LOCATE CSRLIN - 1
70 'move down
80 LOCATE CSRLIN + 1
900 'beginning of line
100 LOCATE , 1
110 'end of line; requires previous knowledge of screen width -- typically 80
120 LOCATE , 80
130 'top left corner
140 LOCATE 1, 1
150 'bottom right corner; requires knowledge of screen dimensions (80x25 here)
160 LOCATE 25, 80 |
http://rosettacode.org/wiki/Terminal_control/Cursor_positioning | Terminal control/Cursor positioning |
Task
Move the cursor to column 3, row 6, and display the word "Hello" (without the quotes), so that the letter H is in column 3 on row 6.
| #Icon_and_Unicon | Icon and Unicon | procedure main()
writes(CUP(6,3), "Hello")
end
procedure CUP(i,j)
writes("\^[[",i,";",j,"H")
return
end |
http://rosettacode.org/wiki/Terminal_control/Cursor_positioning | Terminal control/Cursor positioning |
Task
Move the cursor to column 3, row 6, and display the word "Hello" (without the quotes), so that the letter H is in column 3 on row 6.
| #J | J | 'Hello',~move 6 3 |
http://rosettacode.org/wiki/Terminal_control/Cursor_positioning | Terminal control/Cursor positioning |
Task
Move the cursor to column 3, row 6, and display the word "Hello" (without the quotes), so that the letter H is in column 3 on row 6.
| #Julia | Julia | const ESC = "\u001B"
gotoANSI(x, y) = print("$ESC[$(y);$(x)H")
gotoANSI(3, 6)
println("Hello")
|
http://rosettacode.org/wiki/Terminal_control/Cursor_positioning | Terminal control/Cursor positioning |
Task
Move the cursor to column 3, row 6, and display the word "Hello" (without the quotes), so that the letter H is in column 3 on row 6.
| #Kotlin | Kotlin | // version 1.1.2
fun main(args: Array<String>) {
print("\u001Bc") // clear screen first
println("\u001B[6;3HHello")
} |
http://rosettacode.org/wiki/Terminal_control/Cursor_positioning | Terminal control/Cursor positioning |
Task
Move the cursor to column 3, row 6, and display the word "Hello" (without the quotes), so that the letter H is in column 3 on row 6.
| #Lasso | Lasso | local(esc = decode_base64('Gw=='))
stdout( #esc + '[6;3HHello') |
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
| #Common_Lisp | Common Lisp | (defun tri-not (x) (- 1 x))
(defun tri-and (&rest x) (apply #'* x))
(defun tri-or (&rest x) (tri-not (apply #'* (mapcar #'tri-not x))))
(defun tri-eq (x y) (+ (tri-and x y) (tri-and (- 1 x) (- 1 y))))
(defun tri-imply (x y) (tri-or (tri-not x) y))
(defun tri-test (x) (< (random 1e0) x))
(defun tri-string (x) (if (= x 1) "T" (if (= x 0) "F" "?")))
;; to say (tri-if (condition) (yes) (no))
(defmacro tri-if (tri ifcase &optional elsecase)
`(if (tri-test ,tri) ,ifcase ,elsecase))
(defun print-table (func header)
(let ((vals '(1 .5 0)))
(format t "~%~a:~%" header)
(format t " ~{~a ~^~}~%---------~%" (mapcar #'tri-string vals))
(loop for row in vals do
(format t "~a | " (tri-string row))
(loop for col in vals do
(format t "~a " (tri-string (funcall func row col))))
(write-line ""))))
(write-line "NOT:")
(loop for row in '(1 .5 0) do
(format t "~a | ~a~%" (tri-string row) (tri-string (tri-not row))))
(print-table #'tri-and "AND")
(print-table #'tri-or "OR")
(print-table #'tri-imply "IMPLY")
(print-table #'tri-eq "EQUAL") |
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).
| #Picat | Picat | go =>
println("£"),
println(chr(163)),
println("太極拳"), % Tàijíquán
nl. |
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).
| #PicoLisp | PicoLisp | (prinl (char 26413) (char 24140)) # Sapporo |
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).
| #PL.2FI | PL/I | declare pound character (1) static initial ('9c'x);
put skip list (pound); |
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).
| #PureBasic | PureBasic | Print(Chr(163)) |
http://rosettacode.org/wiki/Terminal_control/Display_an_extended_character | Terminal control/Display an extended character | Task
Display an extended (non ASCII) character onto the terminal.
Specifically, display a £ (GBP currency sign).
| #Python | Python | print u'\u00a3' |
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).
| #R | R | cat("£") |
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.
| #D | D | void main(in string[] args) {
import std.stdio, std.conv, std.string;
const fileNames = (args.length == 1) ? ["readings.txt"] :
args[1 .. $];
int noData, noDataMax = -1;
string[] noDataMaxLine;
double fileTotal = 0.0;
int fileValues;
foreach (const fileName; fileNames) {
foreach (char[] line; fileName.File.byLine) {
double lineTotal = 0.0;
int lineValues;
// Extract field info.
const parts = line.split;
const date = parts[0];
const fields = parts[1 .. $];
assert(fields.length % 2 == 0,
format("Expected even number of fields, not %d.",
fields.length));
for (int i; i < fields.length; i += 2) {
immutable value = fields[i].to!double;
immutable flag = fields[i + 1].to!int;
if (flag < 1) {
noData++;
continue;
}
// Check run of data-absent fields.
if (noDataMax == noData && noData > 0)
noDataMaxLine ~= date.idup;
if (noDataMax < noData && noData > 0) {
noDataMax = noData;
noDataMaxLine.length = 1;
noDataMaxLine[0] = date.idup;
}
// Re-initialise run of noData counter.
noData = 0;
// Gather values for averaging.
lineTotal += value;
lineValues++;
}
// Totals for the file so far.
fileTotal += lineTotal;
fileValues += lineValues;
writefln("Line: %11s Reject: %2d Accept: %2d" ~
" Line_tot: %10.3f Line_avg: %10.3f",
date,
fields.length / 2 - lineValues,
lineValues,
lineTotal,
(lineValues > 0) ? lineTotal / lineValues : 0.0);
}
}
writefln("\nFile(s) = %-(%s, %)", fileNames);
writefln("Total = %10.3f", fileTotal);
writefln("Readings = %6d", fileValues);
writefln("Average = %10.3f", fileTotal / fileValues);
writefln("\nMaximum run(s) of %d consecutive false " ~
"readings ends at line starting with date(s): %-(%s, %)",
noDataMax, noDataMaxLine);
} |
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.
| #Perl | Perl | use warnings;
use strict;
use Math::Random::ISAAC;
my $message = "a Top Secret secret";
my $key = "this is my secret key";
my $enc = xor_isaac($key, $message);
my $dec = xor_isaac($key, join "", pack "H*", $enc);
print "Message: $message\n";
print "Key : $key\n";
print "XOR : $enc\n";
print "XOR dcr: ", join("", pack "H*", $dec), "\n";
sub xor_isaac {
my($key, $msg) = @_;
# Make an ISAAC stream with the desired seed
my $rng = Math::Random::ISAAC->new( map { ord } split "",$key );
# Get ISAAC output in the order the task wants
my @iranda = map { $_ % 95 + 32 } # Alpha-tize as the task desires
reverse # MRI gives state from the end
map { $rng->irand } # Get random inputs...
0..255; # a state chunk at a time
# Encode:
join "", map { sprintf "%02X",$_ } # join hex digits
map { ord($_) ^ shift(@iranda) } # xor it with rand char
split "", $msg; # Take each character
} |
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.)
| #PowerShell | PowerShell |
function Test-Integer ($Number)
{
try
{
$Number = [System.Numerics.Complex]$Number
if (($Number.Real -eq [int]$Number.Real) -and ($Number.Imaginary -eq 0))
{
return $true
}
else
{
return $false
}
}
catch
{
Write-Host "Parameter was not a number."
}
}
|
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.)
| #Python | Python | >>> def isint(f):
return complex(f).imag == 0 and complex(f).real.is_integer()
>>> [isint(f) for f in (1.0, 2, (3.0+0.0j), 4.1, (3+4j), (5.6+0j))]
[True, True, True, False, False, False]
>>> # Test cases
...
>>> isint(25.000000)
True
>>> isint(24.999999)
False
>>> isint(25.000100)
False
>>> isint(-2.1e120)
True
>>> isint(-5e-2)
False
>>> isint(float('nan'))
False
>>> isint(float('inf'))
False
>>> isint(5.0+0.0j)
True
>>> isint(5-5j)
False
|
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).
| #PureBasic | PureBasic | OpenConsole()
If ReadFile(0, OpenFileRequester("Text processing/3","mlijobs.txt","All files",1))
While Not Eof(0)
currline$=ReadString(0)
If StringField(currline$,2," ")="OUT"
counter+1
Else
counter-1
EndIf
If counter>max
max=counter
maxtime$=StringField(currline$,4," ")
ElseIf counter=max
maxtime$+#CRLF$+StringField(currline$,4," ")
EndIf
Wend
PrintN(Str(max)+" license(s) used at ;"+#CRLF$+maxtime$)
CloseFile(0)
Else
PrintN("Failed to open the file.")
EndIf
PrintN(#CRLF$+"Press ENTER to exit"): Input()
CloseConsole() |
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.
| #Nim | Nim | proc reversed(s: string): string =
result = newString(s.len)
for i, c in s:
result[s.high - i] = c
proc isPalindrome(s: string): bool =
s == reversed(s)
when isMainModule:
assert(isPalindrome(""))
assert(isPalindrome("a"))
assert(isPalindrome("aa"))
assert(not isPalindrome("baa"))
assert(isPalindrome("baab"))
assert(isPalindrome("ba_ab"))
assert(not isPalindrome("ba_ ab"))
assert(isPalindrome("ba _ ab"))
assert(not isPalindrome("abab")) |
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.
| #OCaml | OCaml | ocaml unix.cma -I +oUnit oUnit.cma palindrome.cmo palindrome_tests.ml
|
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
| #Clojure | Clojure | (let
[numbers '(first second third fourth fifth sixth
seventh eighth ninth tenth eleventh twelfth)
gifts ["And a partridge in a pear tree", "Two turtle doves",
"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"]
day (fn [n]
(printf "On the %s day of Christmas, my true love sent to me\n"
(nth numbers n)))]
(day 0)
(println (clojure.string/replace (first gifts) "And a" "A"))
(dorun (for [d (range 1 12)] (do
(println)
(day d)
(dorun (for [n (range d -1 -1)]
(println (nth gifts n))))))))
|
http://rosettacode.org/wiki/Terminal_control/Dimensions | Terminal control/Dimensions | Determine the height and width of the terminal, and store this information into variables for subsequent use.
| #Mathematica.2FWolfram_Language | Mathematica/Wolfram Language | WIDTH=RunThrough["tput cols", ""];
HEIGHT=RunThrough["tput lines", ""]; |
http://rosettacode.org/wiki/Terminal_control/Dimensions | Terminal control/Dimensions | Determine the height and width of the terminal, and store this information into variables for subsequent use.
| #Nim | Nim | import terminal
let (width, height) = terminalSize()
echo "Terminal width: ", width
echo "Terminal height: ", height |
http://rosettacode.org/wiki/Terminal_control/Dimensions | Terminal control/Dimensions | Determine the height and width of the terminal, and store this information into variables for subsequent use.
| #OCaml | OCaml | $ ocaml unix.cma -I +ANSITerminal ANSITerminal.cma
# let width, height = ANSITerminal.size () ;;
val width : int = 126
val height : int = 47 |
http://rosettacode.org/wiki/Terminal_control/Dimensions | Terminal control/Dimensions | Determine the height and width of the terminal, and store this information into variables for subsequent use.
| #Perl | Perl | use Term::Size;
($cols, $rows) = Term::Size::chars;
print "The terminal has $cols columns and $rows lines\n"; |
http://rosettacode.org/wiki/Terminal_control/Coloured_text | Terminal control/Coloured text | Task
Display a word in various colours on the terminal.
The system palette, or colours such as Red, Green, Blue, Magenta, Cyan, and Yellow can be used.
Optionally demonstrate:
How the system should determine if the terminal supports colour
Setting of the background colour
How to cause blinking or flashing (if supported by the terminal)
| #Arturo | Arturo | str: "Hello World"
print color #red str
print color #green str
print color #blue str
print color #magenta str
print color #yellow str
print color #cyan str
print color #black str
print color #white str |
http://rosettacode.org/wiki/Terminal_control/Coloured_text | Terminal control/Coloured text | Task
Display a word in various colours on the terminal.
The system palette, or colours such as Red, Green, Blue, Magenta, Cyan, and Yellow can be used.
Optionally demonstrate:
How the system should determine if the terminal supports colour
Setting of the background colour
How to cause blinking or flashing (if supported by the terminal)
| #AutoHotkey | AutoHotkey | DllCall( "AllocConsole" ) ; create a console if not launched from one
hConsole := DllCall( "GetStdHandle", int, STDOUT := -11 )
Loop 15
SetConsoleTextAttribute(hConsole, A_Index)
,WriteConsole(hConsole, "AutoHotkey`n")
MsgBox
SetConsoleTextAttribute(hConsole, Attributes){
return DllCall( "SetConsoleTextAttribute", UPtr, hConsole, UShort, Attributes)
}
WriteConsole(hConsole, text){
VarSetCapacity(out, 16)
If DllCall( "WriteConsole", UPtr, hConsole, Str, text, UInt, StrLen(text)
, UPtrP, out, uint, 0 )
return out
return 0
} |
http://rosettacode.org/wiki/Terminal_control/Cursor_movement | Terminal control/Cursor movement | Task
Demonstrate how to achieve movement of the terminal cursor:
how to move the cursor one position to the left
how to move the cursor one position to the right
how to move the cursor up one line (without affecting its horizontal position)
how to move the cursor down one line (without affecting its horizontal position)
how to move the cursor to the beginning of the line
how to move the cursor to the end of the line
how to move the cursor to the top left corner of the screen
how to move the cursor to the bottom right corner of the screen
For the purpose of this task, it is not permitted to overwrite any characters or attributes on any part of the screen (so outputting a space is not a suitable solution to achieve a movement to the right).
Handling of out of bounds locomotion
This task has no specific requirements to trap or correct cursor movement beyond the terminal boundaries, so the implementer should decide what behavior fits best in terms of the chosen language. Explanatory notes may be added to clarify how an out of bounds action would behave and the generation of error messages relating to an out of bounds cursor position is permitted.
| #BBC_BASIC | BBC BASIC | VDU 8 : REM Move one position to the left
VDU 9 : REM Move one position to the right
VDU 11 : REM Move up one line
VDU 10 : REM Move down one line
VDU 13 : REM Move to the beginning of the line
VDU 30 : REM Move to the top left corner
VDU 23,16,16;0;0;0; : REM Disable scrolling
VDU 13,8,10 : REM Move to the end of the line
VDU 30,8 : REM Move to the bottom right corner
VDU 23,16,0;0;0;0; : REM Enable scrolling |
http://rosettacode.org/wiki/Terminal_control/Cursor_movement | Terminal control/Cursor movement | Task
Demonstrate how to achieve movement of the terminal cursor:
how to move the cursor one position to the left
how to move the cursor one position to the right
how to move the cursor up one line (without affecting its horizontal position)
how to move the cursor down one line (without affecting its horizontal position)
how to move the cursor to the beginning of the line
how to move the cursor to the end of the line
how to move the cursor to the top left corner of the screen
how to move the cursor to the bottom right corner of the screen
For the purpose of this task, it is not permitted to overwrite any characters or attributes on any part of the screen (so outputting a space is not a suitable solution to achieve a movement to the right).
Handling of out of bounds locomotion
This task has no specific requirements to trap or correct cursor movement beyond the terminal boundaries, so the implementer should decide what behavior fits best in terms of the chosen language. Explanatory notes may be added to clarify how an out of bounds action would behave and the generation of error messages relating to an out of bounds cursor position is permitted.
| #Befunge | Befunge |
#include<conio.h>
#include<dos.h>
char *strings[] = {"The cursor will move one position to the left",
"The cursor will move one position to the right",
"The cursor will move vetically up one line",
"The cursor will move vertically down one line",
"The cursor will move to the beginning of the line",
"The cursor will move to the end of the line",
"The cursor will move to the top left corner of the screen",
"The cursor will move to the bottom right corner of the screen"};
int main()
{
int i,j,MAXROW,MAXCOL;
struct text_info tInfo;
gettextinfo(&tInfo);
MAXROW = tInfo.screenheight;
MAXCOL = tInfo.screenwidth;
clrscr();
cprintf("This is a demonstration of cursor control using gotoxy(). Press any key to continue.");
getch();
for(i=0;i<8;i++)
{
clrscr();
gotoxy(5,MAXROW/2);
cprintf("%s",strings[i]);
getch();
switch(i){
case 0:gotoxy(wherex()-1,wherey());
break;
case 1:gotoxy(wherex()+1,wherey());
break;
case 2:gotoxy(wherex(),wherey()-1);
break;
case 3:gotoxy(wherex(),wherey()+1);
break;
case 4:for(j=0;j<strlen(strings[i]);j++){
gotoxy(wherex()-1,wherey());
delay(100);
}
break;
case 5:gotoxy(wherex()-strlen(strings[i]),wherey());
for(j=0;j<strlen(strings[i]);j++){
gotoxy(wherex()+1,wherey());
delay(100);
}
break;
case 6:while(wherex()!=1)
{
gotoxy(wherex()-1,wherey());
delay(100);
}
while(wherey()!=1)
{
gotoxy(wherex(),wherey()-1);
delay(100);
}
break;
case 7:while(wherex()!=MAXCOL)
{
gotoxy(wherex()+1,wherey());
delay(100);
}
while(wherey()!=MAXROW)
{
gotoxy(wherex(),wherey()+1);
delay(100);
}
break;
};
getch();
}
clrscr();
cprintf("End of demonstration.");
getch();
return 0;
}
|
http://rosettacode.org/wiki/Terminal_control/Cursor_positioning | Terminal control/Cursor positioning |
Task
Move the cursor to column 3, row 6, and display the word "Hello" (without the quotes), so that the letter H is in column 3 on row 6.
| #Liberty_BASIC | Liberty BASIC | locate 3, 6
print "Hello"
|
http://rosettacode.org/wiki/Terminal_control/Cursor_positioning | Terminal control/Cursor positioning |
Task
Move the cursor to column 3, row 6, and display the word "Hello" (without the quotes), so that the letter H is in column 3 on row 6.
| #Logo | Logo | setcursor [2 5]
type "Hello |
http://rosettacode.org/wiki/Terminal_control/Cursor_positioning | Terminal control/Cursor positioning |
Task
Move the cursor to column 3, row 6, and display the word "Hello" (without the quotes), so that the letter H is in column 3 on row 6.
| #Mathematica.2FWolfram_Language | Mathematica/Wolfram Language | Run["tput cup 6 3"]
Print["Hello"] |
http://rosettacode.org/wiki/Terminal_control/Cursor_positioning | Terminal control/Cursor positioning |
Task
Move the cursor to column 3, row 6, and display the word "Hello" (without the quotes), so that the letter H is in column 3 on row 6.
| #Nim | Nim | import terminal
setCursorPos(3, 6)
echo "Hello" |
http://rosettacode.org/wiki/Terminal_control/Cursor_positioning | Terminal control/Cursor positioning |
Task
Move the cursor to column 3, row 6, and display the word "Hello" (without the quotes), so that the letter H is in column 3 on row 6.
| #NS-HUBASIC | NS-HUBASIC | 10 LOCATE 3,6
20 PRINT "HELLO" |
http://rosettacode.org/wiki/Teacup_rim_text | Teacup rim text | On a set of coasters we have, there's a picture of a teacup. On the rim of the teacup the word TEA appears a number of times separated by bullet characters (•).
It occurred to me that if the bullet were removed and the words run together, you could start at any letter and still end up with a meaningful three-letter word.
So start at the T and read TEA. Start at the E and read EAT, or start at the A and read ATE.
That got me thinking that maybe there are other words that could be used rather that TEA. And that's just English. What about Italian or Greek or ... um ... Telugu.
For English, we will use the unixdict (now) located at: unixdict.txt.
(This will maintain continuity with other Rosetta Code tasks that also use it.)
Task
Search for a set of words that could be printed around the edge of a teacup. The words in each set are to be of the same length, that length being greater than two (thus precluding AH and HA, for example.)
Having listed a set, for example [ate tea eat], refrain from displaying permutations of that set, e.g.: [eat tea ate] etc.
The words should also be made of more than one letter (thus precluding III and OOO etc.)
The relationship between these words is (using ATE as an example) that the first letter of the first becomes the last letter of the second. The first letter of the second becomes the last letter of the third. So ATE becomes TEA and TEA becomes EAT.
All of the possible permutations, using this particular permutation technique, must be words in the list.
The set you generate for ATE will never included the word ETA as that cannot be reached via the first-to-last movement method.
Display one line for each set of teacup rim words.
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
| #11l | 11l | F rotated(String s)
R s[1..]‘’s[0]
V s = Set(File(‘unixdict.txt’).read().rtrim("\n").split("\n"))
L !s.empty
L(=word) s // `=` is needed here because otherwise after `s.remove(word)` `word` becomes invalid
s.remove(word)
I word.len < 3
L.break
V w = word
L 0 .< word.len - 1
w = rotated(w)
I w C s
s.remove(w)
E
L.break
L.was_no_break
print(word, end' ‘’)
w = word
L 0 .< word.len - 1
w = rotated(w)
print(‘ -> ’w, end' ‘’)
print()
L.break |
http://rosettacode.org/wiki/Terminal_control/Clear_the_screen | Terminal control/Clear the screen | Task
Clear the terminal window.
| #11l | 11l | os:(‘clear’) |
http://rosettacode.org/wiki/Ternary_logic | Ternary logic |
This page uses content from Wikipedia. The original article was at Ternary logic. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance)
In logic, a three-valued logic (also trivalent, ternary, or trinary 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
| #D | D | import std.stdio;
struct Trit {
private enum Val : byte { F = -1, M, T }
private Val t;
alias t this;
static immutable Trit[3] vals = [{Val.F}, {Val.M}, {Val.T}];
static immutable F = Trit(Val.F); // Not necessary but handy.
static immutable M = Trit(Val.M);
static immutable T = Trit(Val.T);
string toString() const pure nothrow {
return "F?T"[t + 1 .. t + 2];
}
Trit opUnary(string op)() const pure nothrow
if (op == "~") {
return Trit(-t);
}
Trit opBinary(string op)(in Trit b) const pure nothrow
if (op == "&") {
return t < b ? this : b;
}
Trit opBinary(string op)(in Trit b) const pure nothrow
if (op == "|") {
return t > b ? this : b;
}
Trit opBinary(string op)(in Trit b) const pure nothrow
if (op == "^") {
return ~(this == b);
}
Trit opEquals(in Trit b) const pure nothrow {
return Trit(cast(Val)(t * b));
}
Trit imply(in Trit b) const pure nothrow {
return -t > b ? ~this : b;
}
}
void showOperation(string op)(in string opName) {
writef("\n[%s]\n F ? T\n -------", opName);
foreach (immutable a; Trit.vals) {
writef("\n%s |", a);
foreach (immutable b; Trit.vals)
static if (op == "==>")
writef(" %s", a.imply(b));
else
writef(" %s", mixin("a " ~ op ~ " b"));
}
writeln();
}
void main() {
writeln("[Not]");
foreach (const a; Trit.vals)
writefln("%s | %s", a, ~a);
showOperation!"&"("And");
showOperation!"|"("Or");
showOperation!"^"("Xor");
showOperation!"=="("Equiv");
showOperation!"==>"("Imply");
} |
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).
| #Racket | Racket |
#lang racket
(display "£")
|
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).
| #Raku | Raku | say '£';
say "\x[FFE1]";
say "\c[FULLWIDTH POUND SIGN]";
0xffe1.chr.say; |
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).
| #REXX | REXX | /*REXX program demonstrates displaying an extended character (glyph) to the terminal.*/
/* [↓] this SAY will display the £ glyph (if the term supports it).*/
say '£' /*this assumes the pound sign glyph is displayable on the terminal. */
/*this program can execute correctly on an EBCDIC or ASCII machine.*/
/*stick a fork in it, we're all done. */ |
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).
| #Ring | Ring |
# Project : Terminal control/Display an extended character
see "£"
|
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).
| #Ruby | Ruby | #encoding: UTF-8 #superfluous in Ruby > 1.9.3
puts "£" |
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).
| #Scala | Scala | object ExtendedCharacter extends App {
println("£")
println("札幌")
} |
http://rosettacode.org/wiki/Terminal_control/Display_an_extended_character | Terminal control/Display an extended character | Task
Display an extended (non ASCII) character onto the terminal.
Specifically, display a £ (GBP currency sign).
| #Seed7 | Seed7 | $ include "seed7_05.s7i";
include "console.s7i";
const proc: main is func
local
var text: console is STD_NULL;
begin
console := open(CONSOLE);
write(console, "£");
# Terminal windows often restore the previous
# content, when a program is terminated. Therefore
# the program waits until Return/Enter is pressed.
readln;
end func; |
http://rosettacode.org/wiki/Text_processing/1 | Text processing/1 | This task has been flagged for clarification. Code on this page in its current state may be flagged incorrect once this task has been clarified. See this page's Talk page for discussion.
Often data is produced by one program, in the wrong format for later use by another program or person. In these situations another 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.
| #Eiffel | Eiffel |
class
APPLICATION
create
make
feature
make
-- Summary statistics for 'hash'.
local
reject, accept, reading_total: INTEGER
total, average, file_total: REAL
do
read_wordlist
across
hash as h
loop
io.put_string (h.key + "%T")
reject := 0
accept := 0
total := 0
across
h.item as data
loop
if data.item.flag > 0 then
accept := accept + 1
total := total + data.item.val
else
reject := reject + 1
end
end
file_total := file_total + total
reading_total := reading_total + accept
io.put_string ("accept: " + accept.out + "%Treject: " + reject.out + "%Ttotal: " + total.out + "%T")
average := total / accept.to_real
io.put_string ("average: " + average.out + "%N")
end
io.put_string ("File total: " + file_total.out + "%N")
io.put_string ("Readings total: " + reading_total.out + "%N")
find_longest_gap
end
find_longest_gap
-- Longest gap (flag values <= 0).
local
count: INTEGER
longest_gap: INTEGER
end_date: STRING
do
create end_date.make_empty
across
hash as h
loop
across
h.item as data
loop
if data.item.flag <= 0 then
count := count + 1
else
if count > longest_gap then
longest_gap := count
end_date := h.key
end
count := 0
end
end
end
io.put_string ("%NThe longest gap is " + longest_gap.out + ". It ends at the date stamp " + end_date + ". %N")
end
original_list: STRING = "readings.txt"
read_wordlist
-- Preprocessed wordlist in 'hash'.
local
l_file: PLAIN_TEXT_FILE
data: LIST [STRING]
by_dates: LIST [STRING]
date: STRING
data_tup: TUPLE [val: REAL; flag: INTEGER]
data_arr: ARRAY [TUPLE [val: REAL; flag: INTEGER]]
i: INTEGER
do
create l_file.make_open_read_write (original_list)
l_file.read_stream (l_file.count)
data := l_file.last_string.split ('%N')
l_file.close
create hash.make (data.count)
across
data as d
loop
if not d.item.is_empty then
by_dates := d.item.split ('%T')
date := by_dates [1]
by_dates.prune (date)
create data_tup
create data_arr.make_empty
from
i := 1
until
i > by_dates.count - 1
loop
data_tup := [by_dates [i].to_real, by_dates [i + 1].to_integer]
data_arr.force (data_tup, data_arr.count + 1)
i := i + 2
end
hash.put (data_arr, date)
if not hash.inserted then
date.append ("_double_date_stamp")
hash.put (data_arr, date)
end
end
end
end
hash: HASH_TABLE [ARRAY [TUPLE [val: REAL; flag: INTEGER]], STRING]
end
|
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.
| #Phix | Phix | --
-- demo\rosetta\ISAAC_Cipher.exw
--
with javascript_semantics
sequence randrsl = repeat(0,256)
integer randcnt
sequence mm
atom aa,bb,cc
function r32(object a)
if sequence(a) then
for i=1 to length(a) do
a[i] = r32(a[i])
end for
return a
end if
if a<0 then a+=#100000000 end if
return remainder(a,#100000000)
end function
function shl(atom word, integer bits)
return r32(word*power(2,bits))
end function
function shr(atom v, integer bits)
return floor(v/power(2,bits))
end function
procedure Isaac()
cc += 1; -- cc just gets incremented once per 256 results
bb += cc; -- then combined with bb
for i=1 to 256 do
atom x = mm[i]
switch mod(i-1,4) do
case 0: aa := xor_bits(aa,shl(aa,13))
case 1: aa := xor_bits(aa,shr(aa, 6))
case 2: aa := xor_bits(aa,shl(aa, 2))
case 3: aa := xor_bits(aa,shr(aa,16))
end switch
aa = r32(mm[xor_bits(i-1,#80)+1]+aa)
atom y := mm[and_bits(shr(x,2),#FF)+1]+aa+bb
mm[i] := y;
bb := r32(mm[and_bits(shr(y,10),#FF)+1] + x)
randrsl[i]:= bb;
end for
randcnt = 1
end procedure
function mix(sequence a8)
atom {a,b,c,d,e,f,g,h} = a8
a = xor_bits(a,shl(b,11)); {d,b} = r32({d+a,b+c});
b = xor_bits(b,shr(c, 2)); {e,c} = r32({e+b,c+d});
c = xor_bits(c,shl(d, 8)); {f,d} = r32({f+c,d+e});
d = xor_bits(d,shr(e,16)); {g,e} = r32({g+d,e+f});
e = xor_bits(e,shl(f,10)); {h,f} = r32({h+e,f+g});
f = xor_bits(f,shr(g, 4)); {a,g} = r32({a+f,g+h});
g = xor_bits(g,shl(h, 8)); {b,h} = r32({b+g,h+a});
h = xor_bits(h,shr(a, 9)); {c,a} = r32({c+h,a+b});
a8 = {a,b,c,d,e,f,g,h}
return a8
end function
procedure iRandInit()
{aa,bb,cc} = {0,0,0}
sequence a8 = repeat(#9e3779b9,8) -- the golden ratio
for i=1 to 4 do -- scramble it
a8 = mix(a8)
end for
for i=1 to 255 by 8 do
a8 = mix(sq_add(a8,randrsl[i..i+7]))
mm[i..i+7] = a8
end for
for i=1 to 255 by 8 do
a8 = mix(r32(sq_add(a8,mm[i..i+7])))
mm[i..i+7] = a8
end for
Isaac() -- fill in the first set of results
end procedure
procedure iSeed(string seed)
mm = repeat(0,256)
randrsl = repeat(0,256)
randrsl[1..min(length(seed),256)] = seed
iRandInit()
end procedure
function randch()
atom res = mod(randrsl[randcnt],95)+32
randcnt += 1
if randcnt>256 then
Isaac()
end if
return res
end function
function Vernam(string msg)
string res = ""
for i=1 to length(msg) do
res &= xor_bits(msg[i],randch())
end for
return res
end function
function Caesar(integer ch, shift)
return ' '+mod(ch-' '+shift,95)
end function
enum ENCRYPT = +1,
DECRYPT = -1
function Vigenere(string msg, integer mode)
string res = ""
for i=1 to length(msg) do
res &= Caesar(msg[i],randch()*mode)
end for
return res
end function
constant string msg = "a Top Secret secret",
key = "this is my secret key"
iSeed(key)
string xctx := Vernam(msg),
mctx := Vigenere(msg,ENCRYPT)
iSeed(key)
string xptx := Vernam(xctx),
mptx := Vigenere(mctx,DECRYPT)
function ascii2hex(string s)
string res = ""
for i=1 to length(s) do
res &= sprintf("%02x",s[i])
end for
return res
end function
printf(1,"Message: %s\n",{msg})
printf(1,"Key : %s\n",{key})
printf(1,"XOR : %s\n",{ascii2hex(xctx)})
printf(1,"MOD : %s\n",{ascii2hex(mctx)})
printf(1,"XOR dcr: %s\n",{xptx})
printf(1,"MOD dcr: %s\n",{mptx})
?"done"
{} = wait_key()
|
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.)
| #Quackery | Quackery | [ $ "bigrat.qky" loadfile ] now!
[ mod not ] is v-is-num ( n/d --> b )
[ 1+ dip [ proper rot drop ]
10 swap ** round v-is-num ] is approxint ( n/d n --> 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.)
| #Racket | Racket | #lang racket
(require tests/eli-tester)
(test ;; known representations of integers:
;; - as exacts
(integer? -1) => #t
(integer? 0) => #t
(integer? 1) => #t
(integer? 1234879378539875943875937598379587539875498792424323432432343242423432432) => #t
(integer? -1234879378539875943875937598379587539875498792424323432432343242423432432) => #t
(integer? #xff) => #t
;; - as inexacts
(integer? -1.) => #t
(integer? 0.) => #t
(integer? 1.) => #t
(integer? 1234879378539875943875937598379587539875498792424323432432343242423432432.) => #t
(integer? #xff.0) => #t
;; - but without a decimal fractional part
(integer? -1.1) => #f
;; - fractional representation
(integer? -42/3) => #t
(integer? 0/1) => #t
(integer? 27/9) => #t
(integer? #xff/f) => #t
(integer? #b11111111/1111) => #t
;; - but obviously not fractions
(integer? 5/7) => #f
; - as scientific
(integer? 1.23e2) => #t
(integer? 1.23e120) => #t
; - but not with a small exponent
(integer? 1.23e1) => #f
; - complex representations with 0 imaginary component
; ℤ is a subset of the sets of rational and /real/ numbers and
(integer? 1+0i) => #t
(integer? (sqr 0+1i)) => #t
(integer? 0+1i) => #f
;; oh, there's so much else that isn't an integer:
(integer? "woo") => #f
(integer? "100") => #f
(integer? (string->number "22/11")) => #t ; just cast it!
(integer? +inf.0) => #f
(integer? -inf.0) => #f
(integer? +nan.0) => #f ; duh! it's not even a number!
(integer? -NaN.0) => #f
(integer? pi) => #f
)
|
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).
| #Python | Python | out, max_out, max_times = 0, -1, []
for job in open('mlijobs.txt'):
out += 1 if "OUT" in job else -1
if out > max_out:
max_out, max_times = out, []
if out == max_out:
max_times.append(job.split()[3])
print("Maximum simultaneous license use is %i at the following times:" % max_out)
print(' ' + '\n '.join(max_times)) |
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.
| #Oforth | Oforth | test: [ "abcd" isPalindrome ]
test: ["abba" isPalindrome ]
test: [ "abcba" isPalindrome ] |
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.
| #PARI.2FGP | PARI/GP | ? ispal("abc")
0
? ispal("aba")
1 |
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
| #CLU | CLU | christmas = cluster is carol
rep = null
own ordinals: array[string] := array[string]$[
"first", "second", "third", "fourth", "fifth",
"sixth", "seventh", "eighth", "ninth", "tenth",
"eleventh", "twelfth"
]
own gifts: array[string] := array[string]$[
"A partridge in a pear tree.",
"Two turtle doves, and",
"Three french hens,",
"Four calling birds,",
"Five golden rings,",
"Six geese a-laying,",
"Seven swans a-swimming,",
"Eight maids a-milking,",
"Nine ladies dancing,",
"Ten lords a-leaping,",
"Eleven pipers piping,",
"Twelve drummers drumming,"
]
verse = proc (s: stream, n: int)
stream$putl(s, "On the " || ordinals[n] || " day of Christmas,")
stream$putl(s, "My true love gave to me:")
for gift: int in int$from_to_by(n, 1, -1) do
stream$putl(s, gifts[gift])
end
stream$putl(s, "")
end verse
carol = proc (s: stream)
for n: int in int$from_to(1, 12) do
verse(s, n)
end
end carol
end christmas
start_up = proc ()
christmas$carol(stream$primary_output())
end start_up |
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
| #COBOL | COBOL | >>SOURCE FREE
PROGRAM-ID. twelve-days-of-christmas.
DATA DIVISION.
WORKING-STORAGE SECTION.
01 gifts-area VALUE "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 ".
03 gifts PIC X(30) OCCURS 12 TIMES
INDEXED BY gift-idx.
01 ordinals-area VALUE "first second third fourth fifth "
& "sixth seventh eighth ninth tenth eleventh twelfth ".
03 ordinals PIC X(10) OCCURS 12 TIMES.
01 day-num PIC 99 COMP.
PROCEDURE DIVISION.
PERFORM VARYING day-num FROM 1 BY 1 UNTIL day-num > 12
DISPLAY "On the " FUNCTION TRIM(ordinals (day-num)) " day of Christmas,"
" my true love gave to me"
IF day-num = 1
DISPLAY "A " gifts (1)
ELSE
PERFORM VARYING gift-idx FROM day-num BY -1 UNTIL gift-idx = 1
DISPLAY gifts (gift-idx)
END-PERFORM
DISPLAY "And a " gifts (1)
END-IF
DISPLAY SPACE
END-PERFORM
.
END PROGRAM twelve-days-of-christmas. |
http://rosettacode.org/wiki/Terminal_control/Dimensions | Terminal control/Dimensions | Determine the height and width of the terminal, and store this information into variables for subsequent use.
| #Phix | Phix | without js -- (video_config)
sequence vc = video_config()
printf(1,"Terminal buffer height is %d\n",vc[VC_LINES])
printf(1,"Terminal buffer width is %d\n",vc[VC_COLUMNS])
printf(1,"Terminal screen height is %d\n",vc[VC_SCRNLINES])
printf(1,"Terminal screen width is %d\n",vc[VC_SCRNCOLS])
|
http://rosettacode.org/wiki/Terminal_control/Dimensions | Terminal control/Dimensions | Determine the height and width of the terminal, and store this information into variables for subsequent use.
| #PicoLisp | PicoLisp | (setq
Width (in '(tput cols) (read))
Height (in '(tput lines) (read)) ) |
http://rosettacode.org/wiki/Terminal_control/Dimensions | Terminal control/Dimensions | Determine the height and width of the terminal, and store this information into variables for subsequent use.
| #PureBasic | PureBasic | Macro ConsoleHandle()
GetStdHandle_( #STD_OUTPUT_HANDLE )
EndMacro
Procedure ConsoleWidth()
Protected CBI.CONSOLE_SCREEN_BUFFER_INFO
Protected hConsole = ConsoleHandle()
GetConsoleScreenBufferInfo_( hConsole, @CBI )
ProcedureReturn CBI\srWindow\right - CBI\srWindow\left + 1
EndProcedure
Procedure ConsoleHeight()
Protected CBI.CONSOLE_SCREEN_BUFFER_INFO
Protected hConsole = ConsoleHandle()
GetConsoleScreenBufferInfo_( hConsole, @CBI )
ProcedureReturn CBI\srWindow\bottom - CBI\srWindow\top + 1
EndProcedure
If OpenConsole()
x$=Str(ConsoleWidth())
y$=Str(ConsoleHeight())
PrintN("This window is "+x$+"x"+y$+ " chars.")
;
Print(#CRLF$+"Press ENTER to exit"):Input()
EndIf |
http://rosettacode.org/wiki/Terminal_control/Coloured_text | Terminal control/Coloured text | Task
Display a word in various colours on the terminal.
The system palette, or colours such as Red, Green, Blue, Magenta, Cyan, and Yellow can be used.
Optionally demonstrate:
How the system should determine if the terminal supports colour
Setting of the background colour
How to cause blinking or flashing (if supported by the terminal)
| #BaCon | BaCon | ' ANSI terminal coloured text
COLOR FG TO BLACK
PRINT "a word"
COLOR FG TO RED
PRINT "a word"
COLOR FG TO GREEN
PRINT "a word"
' Other colours include YELLOW, BLUE, MAGENTA, CYAN, WHITE
' Second keyword can be BG for background colour control
' The COLOR command also accepts keywords of NORMAL, INTENSE, INVERSE, RESET |
http://rosettacode.org/wiki/Terminal_control/Coloured_text | Terminal control/Coloured text | Task
Display a word in various colours on the terminal.
The system palette, or colours such as Red, Green, Blue, Magenta, Cyan, and Yellow can be used.
Optionally demonstrate:
How the system should determine if the terminal supports colour
Setting of the background colour
How to cause blinking or flashing (if supported by the terminal)
| #BASIC | BASIC | FOR n = 1 TO 15
COLOR n
PRINT "Rosetta Code"
NEXT |
http://rosettacode.org/wiki/Terminal_control/Cursor_movement | Terminal control/Cursor movement | Task
Demonstrate how to achieve movement of the terminal cursor:
how to move the cursor one position to the left
how to move the cursor one position to the right
how to move the cursor up one line (without affecting its horizontal position)
how to move the cursor down one line (without affecting its horizontal position)
how to move the cursor to the beginning of the line
how to move the cursor to the end of the line
how to move the cursor to the top left corner of the screen
how to move the cursor to the bottom right corner of the screen
For the purpose of this task, it is not permitted to overwrite any characters or attributes on any part of the screen (so outputting a space is not a suitable solution to achieve a movement to the right).
Handling of out of bounds locomotion
This task has no specific requirements to trap or correct cursor movement beyond the terminal boundaries, so the implementer should decide what behavior fits best in terms of the chosen language. Explanatory notes may be added to clarify how an out of bounds action would behave and the generation of error messages relating to an out of bounds cursor position is permitted.
| #C | C |
#include<conio.h>
#include<dos.h>
char *strings[] = {"The cursor will move one position to the left",
"The cursor will move one position to the right",
"The cursor will move vetically up one line",
"The cursor will move vertically down one line",
"The cursor will move to the beginning of the line",
"The cursor will move to the end of the line",
"The cursor will move to the top left corner of the screen",
"The cursor will move to the bottom right corner of the screen"};
int main()
{
int i,j,MAXROW,MAXCOL;
struct text_info tInfo;
gettextinfo(&tInfo);
MAXROW = tInfo.screenheight;
MAXCOL = tInfo.screenwidth;
clrscr();
cprintf("This is a demonstration of cursor control using gotoxy(). Press any key to continue.");
getch();
for(i=0;i<8;i++)
{
clrscr();
gotoxy(5,MAXROW/2);
cprintf("%s",strings[i]);
getch();
switch(i){
case 0:gotoxy(wherex()-1,wherey());
break;
case 1:gotoxy(wherex()+1,wherey());
break;
case 2:gotoxy(wherex(),wherey()-1);
break;
case 3:gotoxy(wherex(),wherey()+1);
break;
case 4:for(j=0;j<strlen(strings[i]);j++){
gotoxy(wherex()-1,wherey());
delay(100);
}
break;
case 5:gotoxy(wherex()-strlen(strings[i]),wherey());
for(j=0;j<strlen(strings[i]);j++){
gotoxy(wherex()+1,wherey());
delay(100);
}
break;
case 6:while(wherex()!=1)
{
gotoxy(wherex()-1,wherey());
delay(100);
}
while(wherey()!=1)
{
gotoxy(wherex(),wherey()-1);
delay(100);
}
break;
case 7:while(wherex()!=MAXCOL)
{
gotoxy(wherex()+1,wherey());
delay(100);
}
while(wherey()!=MAXROW)
{
gotoxy(wherex(),wherey()+1);
delay(100);
}
break;
};
getch();
}
clrscr();
cprintf("End of demonstration.");
getch();
return 0;
}
|
http://rosettacode.org/wiki/Terminal_control/Cursor_positioning | Terminal control/Cursor positioning |
Task
Move the cursor to column 3, row 6, and display the word "Hello" (without the quotes), so that the letter H is in column 3 on row 6.
| #OCaml | OCaml | #load "unix.cma"
#directory "+ANSITerminal"
#load "ANSITerminal.cma"
module Trm = ANSITerminal
let () =
Trm.erase Trm.Screen;
Trm.set_cursor 3 6;
Trm.print_string [] "Hello";
;; |
http://rosettacode.org/wiki/Terminal_control/Cursor_positioning | Terminal control/Cursor positioning |
Task
Move the cursor to column 3, row 6, and display the word "Hello" (without the quotes), so that the letter H is in column 3 on row 6.
| #Pascal | Pascal |
program cursor_pos;
uses crt;
begin
gotoxy(6,3);
write('Hello');
end.
|
http://rosettacode.org/wiki/Terminal_control/Cursor_positioning | Terminal control/Cursor positioning |
Task
Move the cursor to column 3, row 6, and display the word "Hello" (without the quotes), so that the letter H is in column 3 on row 6.
| #Perl | Perl |
use Term::Cap;
my $t = Term::Cap->Tgetent;
print $t->Tgoto("cm", 2, 5); # 0-based
print "Hello";
|
http://rosettacode.org/wiki/Terminal_control/Cursor_positioning | Terminal control/Cursor positioning |
Task
Move the cursor to column 3, row 6, and display the word "Hello" (without the quotes), so that the letter H is in column 3 on row 6.
| #Phix | Phix | without js -- position
position(6,3)
puts(1,"Hello")
|
http://rosettacode.org/wiki/Teacup_rim_text | Teacup rim text | On a set of coasters we have, there's a picture of a teacup. On the rim of the teacup the word TEA appears a number of times separated by bullet characters (•).
It occurred to me that if the bullet were removed and the words run together, you could start at any letter and still end up with a meaningful three-letter word.
So start at the T and read TEA. Start at the E and read EAT, or start at the A and read ATE.
That got me thinking that maybe there are other words that could be used rather that TEA. And that's just English. What about Italian or Greek or ... um ... Telugu.
For English, we will use the unixdict (now) located at: unixdict.txt.
(This will maintain continuity with other Rosetta Code tasks that also use it.)
Task
Search for a set of words that could be printed around the edge of a teacup. The words in each set are to be of the same length, that length being greater than two (thus precluding AH and HA, for example.)
Having listed a set, for example [ate tea eat], refrain from displaying permutations of that set, e.g.: [eat tea ate] etc.
The words should also be made of more than one letter (thus precluding III and OOO etc.)
The relationship between these words is (using ATE as an example) that the first letter of the first becomes the last letter of the second. The first letter of the second becomes the last letter of the third. So ATE becomes TEA and TEA becomes EAT.
All of the possible permutations, using this particular permutation technique, must be words in the list.
The set you generate for ATE will never included the word ETA as that cannot be reached via the first-to-last movement method.
Display one line for each set of teacup rim words.
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 | wordset: map read.lines relative "unixdict.txt" => strip
rotateable?: function [w][
loop 1..dec size w 'i [
rotated: rotate w i
if or? [rotated = w][not? contains? wordset rotated] ->
return false
]
return true
]
results: new []
loop select wordset 'word [3 =< size word] 'word [
if rotateable? word ->
'results ++ @[ sort map 1..size word 'i [ rotate word i ]]
]
loop sort unique results 'result [
root: first result
print join.with: " -> " map 1..size root 'i [ rotate.left root i]
] |
http://rosettacode.org/wiki/Teacup_rim_text | Teacup rim text | On a set of coasters we have, there's a picture of a teacup. On the rim of the teacup the word TEA appears a number of times separated by bullet characters (•).
It occurred to me that if the bullet were removed and the words run together, you could start at any letter and still end up with a meaningful three-letter word.
So start at the T and read TEA. Start at the E and read EAT, or start at the A and read ATE.
That got me thinking that maybe there are other words that could be used rather that TEA. And that's just English. What about Italian or Greek or ... um ... Telugu.
For English, we will use the unixdict (now) located at: unixdict.txt.
(This will maintain continuity with other Rosetta Code tasks that also use it.)
Task
Search for a set of words that could be printed around the edge of a teacup. The words in each set are to be of the same length, that length being greater than two (thus precluding AH and HA, for example.)
Having listed a set, for example [ate tea eat], refrain from displaying permutations of that set, e.g.: [eat tea ate] etc.
The words should also be made of more than one letter (thus precluding III and OOO etc.)
The relationship between these words is (using ATE as an example) that the first letter of the first becomes the last letter of the second. The first letter of the second becomes the last letter of the third. So ATE becomes TEA and TEA becomes EAT.
All of the possible permutations, using this particular permutation technique, must be words in the list.
The set you generate for ATE will never included the word ETA as that cannot be reached via the first-to-last movement method.
Display one line for each set of teacup rim words.
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
| #AutoHotkey | AutoHotkey | Teacup_rim_text(wList){
oWord := [], oRes := [], n := 0
for i, w in StrSplit(wList, "`n", "`r")
if StrLen(w) >= 3
oWord[StrLen(w), w] := true
for l, obj in oWord
{
for w, bool in obj
{
loop % l
if oWord[l, rotate(w)]
{
oWord[l, w] := 0
if (A_Index = 1)
n++, oRes[n] := w
if (A_Index < l)
oRes[n] := oRes[n] "," (w := rotate(w))
}
if (StrSplit(oRes[n], ",").Count() <> l)
oRes.RemoveAt(n)
}
}
return oRes
}
rotate(w){
return SubStr(w, 2) . SubStr(w, 1, 1)
} |
http://rosettacode.org/wiki/Terminal_control/Clear_the_screen | Terminal control/Clear the screen | Task
Clear the terminal window.
| #6502_Assembly | 6502 Assembly | tmpx -i clrscr.s -o bin/clrscr.prg
|
http://rosettacode.org/wiki/Terminal_control/Clear_the_screen | Terminal control/Clear the screen | Task
Clear the terminal window.
| #68000_Assembly | 68000 Assembly | JSR $C004C2 ;clear the FIX layer
JSR $C004C8 ;clear hardware sprites |
http://rosettacode.org/wiki/Terminal_control/Clear_the_screen | Terminal control/Clear the screen | Task
Clear the terminal window.
| #8080_Assembly | 8080 Assembly | putch: equ 2 ; CP/M 'putchar' syscall
bdos: equ 5 ; CP/M BDOS entry point
FF: equ 12 ; ASCII form feed
org 100h
mvi c,putch ; Print character (syscall goes in C register)
mvi e,FF ; Form feed (argument goes in E register)
jmp bdos ; Call CP/M BDOS and quit |
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
| #Delphi | Delphi | unit TrinaryLogic;
interface
//Define our own type for ternary logic.
//This is actually still a Boolean, but the compiler will use distinct RTTI information.
type
TriBool = type Boolean;
const
TTrue:TriBool = True;
TFalse:TriBool = False;
TMaybe:TriBool = TriBool(2);
function TVL_not(Value: TriBool): TriBool;
function TVL_and(A, B: TriBool): TriBool;
function TVL_or(A, B: TriBool): TriBool;
function TVL_xor(A, B: TriBool): TriBool;
function TVL_eq(A, B: TriBool): TriBool;
implementation
Uses
SysUtils;
function TVL_not(Value: TriBool): TriBool;
begin
if Value = True Then
Result := TFalse
else If Value = False Then
Result := TTrue
else
Result := Value;
end;
function TVL_and(A, B: TriBool): TriBool;
begin
Result := TriBool(Iff(Integer(A * B) > 1, Integer(TMaybe), A * B));
end;
function TVL_or(A, B: TriBool): TriBool;
begin
Result := TVL_not(TVL_and(TVL_not(A), TVL_not(B)));
end;
function TVL_xor(A, B: TriBool): TriBool;
begin
Result := TVL_and(TVL_or(A, B), TVL_not(TVL_or(A, B)));
end;
function TVL_eq(A, B: TriBool): TriBool;
begin
Result := TVL_not(TVL_xor(A, B));
end;
end. |
http://rosettacode.org/wiki/Terminal_control/Display_an_extended_character | Terminal control/Display an extended character | Task
Display an extended (non ASCII) character onto the terminal.
Specifically, display a £ (GBP currency sign).
| #Sidef | Sidef | say '£';
say "\x{FFE1}";
say "\N{FULLWIDTH POUND SIGN}";
say 0xffe1.chr; |
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).
| #Tcl | Tcl | puts \u00a3 |
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).
| #Verilog | Verilog | module main;
initial begin
$display("£");
end
endmodule |
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).
| #Wren | Wren | System.print("£") |
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).
| #Xidel | Xidel | xidel -s -e 'parse-html("£ or £")'
£ or £ |
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).
| #XPL0 | XPL0 | code ChOut=8;
ChOut(0, $9C) \code for IBM PC's extended (OEM) character set
|
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.
| #Erlang | Erlang |
-module( text_processing ).
-export( [file_contents/1, main/1] ).
-record( acc, {failed={"", 0, 0}, files=[], ok=0, total=0} ).
file_contents( Name ) ->
{ok, Binary} = file:read_file( Name ),
[line_contents(X) || X <- binary:split(Binary, <<"\r\n">>, [global]), X =/= <<>>].
main( Files ) ->
Acc = lists:foldl( fun file/2, #acc{}, Files ),
{Failed_date, Failed, _Continuation} = Acc#acc.failed,
io:fwrite( "~nFile(s)=~p~nTotal=~.2f~nReadings=~p~nAverage=~.2f~n~nMaximum run(s) of ~p consecutive false readings ends at line starting with date(s): ~p~n",
[lists:reverse(Acc#acc.files), Acc#acc.total, Acc#acc.ok, Acc#acc.total / Acc#acc.ok, Failed, Failed_date] ).
file( Name, #acc{files=Files}=Acc ) ->
try
Line_contents = file_contents( Name ),
lists:foldl( fun file_content_line/2, Acc#acc{files=[Name | Files]}, Line_contents )
catch
_:Error ->
io:fwrite( "Error: Failed to read ~s: ~p~n", [Name, Error] ),
Acc
end.
file_content_line( {Date, Value_flags}, #acc{failed=Failed, ok=Ok, total=Total}=Acc ) ->
New_failed = file_content_line_failed( Value_flags, Date, Failed ),
{Sum, Oks, Average} = file_content_line_oks_0( [X || {X, ok} <- Value_flags] ),
io:fwrite( "Line=~p\tRejected=~p\tAccepted=~p\tLine total=~.2f\tLine average=~.2f~n", [Date, erlang:length(Value_flags) - Oks, Oks, Sum, Average] ),
Acc#acc{failed=New_failed, ok=Ok + Oks, total=Total + Sum}.
file_content_line_failed( [], Date, {_Failed_date, Failed, Acc} ) when Acc > Failed ->
{Date, Acc, Acc};
file_content_line_failed( [], _Date, Failed ) ->
Failed;
file_content_line_failed( [{_V, error} | T], Date, {Failed_date, Failed, Acc} ) ->
file_content_line_failed( T, Date, {Failed_date, Failed, Acc + 1} );
file_content_line_failed( [_H | T], Date, {_Failed_date, Failed, Acc} ) when Acc > Failed ->
file_content_line_failed( T, Date, {Date, Acc, 0} );
file_content_line_failed( [_H | T], Date, {Failed_date, Failed, _Acc} ) ->
file_content_line_failed( T, Date, {Failed_date, Failed, 0} ).
file_content_line_flag( N ) when N > 0 -> ok;
file_content_line_flag( _N ) -> error.
file_content_line_oks_0( [] ) -> {0.0, 0, 0.0};
file_content_line_oks_0( Ok_value_flags ) ->
Sum = lists:sum( Ok_value_flags ),
Oks = erlang:length( Ok_value_flags ),
{Sum, Oks, Sum / Oks}.
file_content_line_value_flag( Binary, {[], Acc} ) ->
Flag = file_content_line_flag( erlang:list_to_integer(binary:bin_to_list(Binary)) ),
{[Flag], Acc};
file_content_line_value_flag( Binary, {[Flag], Acc} ) ->
Value = erlang:list_to_float( binary:bin_to_list(Binary) ),
{[], [{Value, Flag} | Acc]}.
line_contents( Line ) ->
[Date_binary | Rest] = binary:split( Line, <<"\t">>, [global] ),
{_Previous, Value_flags} = lists:foldr( fun file_content_line_value_flag/2, {[], []}, Rest ), % Preserve order
{binary:bin_to_list( Date_binary ), Value_flags}.
|
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.
| #PicoLisp | PicoLisp | (de add32 @
(mod32 (pass +)) )
(de mod32 (N)
(& N `(hex "FFFFFFFF")) )
(de isaac()
(let (Y 0 S (-13 6 -2 16 .))
(setq *CC (add32 *CC 1))
(setq *BB (add32 *BB *CC))
(for (I . X) *MM
(set (nth *MM I)
(setq Y
(add32
(get *MM (inc (% (>> 2 X) 256)))
(setq *AA
(add32
(x| *AA (>> (pop 'S) *AA))
(get *MM (inc (% (+ 127 I) 256))) ) )
*BB ) ) )
(set (nth *RR I)
(setq *BB
(add32
(get *MM (inc (% (>> 10 Y) 256)))
X ) ) ) ) ) )
(de mixA()
(let S (-11 2 -8 16 -10 4 -8 9 .)
(for I 8
(set (nth *A I)
(mod32
(x|
(get *A I)
(mod32
(>>
(pop 'S)
(get *A (inc (% I 8))) ) ) ) ) )
(set (nth *A (inc (% (+ 2 I) 8)))
(add32
(get *A (inc (% (+ 2 I) 8)))
(get *A I) ) )
(set (nth *A (inc (% I 8)))
(add32
(get *A (inc (% I 8)))
(get *A (inc (% (inc I) 8))) ) ) ) ) )
(de iseed ()
(do 4
(mixA) )
(for (I 1 (> 256 I) (inc 'I 8))
(for (J I (> (+ 8 I) J) (inc J))
(set (nth *A (inc (% (dec J) 8)))
(add32
(get *A (inc (% (dec J) 8)))
(get *RR J) ) ) )
(mixA)
(for (J I (> (+ 8 I) J) (inc J))
(set (nth *MM J)
(get *A (inc (% (dec J) 8))) ) ) )
(for (I 1 (> 256 I) (inc 'I 8))
(for (J I (> (+ 8 I) J) (inc J))
(set (nth *A (inc (% (dec J) 8)))
(add32
(get *A (inc (% (dec J) 8)))
(get *MM J) ) ) )
(mixA)
(for (J I (> (+ 8 I) J) (inc J))
(set (nth *MM J)
(get *A (inc (% (dec J) 8))) ) ) )
(isaac) )
(let
(*AA 0
*BB 0
*CC 0
*MM (need 256 0)
*RC 0
*RR (need
-256
(mapcar
char
(head 256 (chop "this is my secret key")) ) 0 )
*A (need 8 `(hex "9E3779B9")) )
(iseed)
(println
(pack
(mapcar
'((B) (pad 2 (hex B)))
(make
(for I (mapcar char (chop "a Top Secret secret"))
(link
(x|
I
(+
32
(%
(get
*RR
(if (>= 256 (inc '*RC))
*RC
(isaac)
(one *RC) ) )
95 ) ) ) ) ) ) ) ) ) )
(bye) |
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.)
| #Raku | Raku | multi is-int ($n) { $n.narrow ~~ Int }
multi is-int ($n, :$tolerance!) {
abs($n.round - $n) <= $tolerance
}
multi is-int (Complex $n, :$tolerance!) {
is-int($n.re, :$tolerance) && abs($n.im) < $tolerance
}
# Testing:
for 25.000000, 24.999999, 25.000100, -2.1e120, -5e-2, Inf, NaN, 5.0+0.0i, 5-5i {
printf "%-7s %-9s %-5s %-5s\n", .^name, $_,
is-int($_),
is-int($_, :tolerance<0.00001>);
} |
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.)
| #REXX | REXX | /* REXX ---------------------------------------------------------------
* 20.06.2014 Walter Pachl
* 22.06.2014 WP add complex numbers such as 13-12j etc.
* (using 13e-12 or so is not (yet) supported)
*--------------------------------------------------------------------*/
Call test_integer 3.14
Call test_integer 1.00000
Call test_integer 33
Call test_integer 999999999
Call test_integer 99999999999
Call test_integer 1e272
Call test_integer 'AA'
Call test_integer '0'
Call test_integer '1.000-3i'
Call test_integer '1.000-3.3i'
Call test_integer '4j'
Call test_integer '2.00000000+0j'
Call test_integer '0j'
Call test_integer '333'
Call test_integer '-1-i'
Call test_integer '1+i'
Call test_integer '.00i'
Call test_integer 'j'
Call test_integer '0003-00.0j'
Exit
test_integer:
Parse Arg xx
Numeric Digits 1000
Parse Value parse_number(xx) With x imag
If imag<>0 Then Do
Say left(xx,13) 'is not an integer (imaginary part is not zero)'
Return
End
Select
When datatype(x)<>'NUM' Then
Say left(xx,13) 'is not an integer (not even a number)'
Otherwise Do
If datatype(x,'W') Then
Say left(xx,13) 'is an integer'
Else
Say left(xx,13) 'isn''t an integer'
End
End
Return
parse_number: Procedure
Parse Upper Arg x
x=translate(x,'I','J')
If pos('I',x)>0 Then Do
pi=verify(x,'+-','M')
Select
When pi>1 Then Do
real=left(x,pi-1)
imag=substr(x,pi)
End
When pi=0 Then Do
real=0
imag=x
End
Otherwise /*pi=1*/Do
p2=verify(substr(x,2),'+-','M')
If p2>0 Then Do
real=left(x,p2)
imag=substr(x,p2+1)
End
Else Do
real=0
imag=x
End
End
End
End
Else Do
real=x
imag='0I'
End
pi=verify(imag,'+-','M')
If pi=0 Then Do
Parse Var imag imag_v 'I'
imag_sign='+'
End
Else
Parse Var imag imag_sign 2 imag_v 'I'
If imag_v='' Then
imag_v=1
imag=imag_sign||imag_v
Return real imag |
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).
| #R | R |
# Read in data, discard useless bits
dfr <- read.table("mlijobs.txt")
dfr <- dfr[,c(2,4)]
# Find most concurrent licences, and when
n.checked.out <- cumsum(ifelse(dfr$V2=="OUT", 1, -1))
times <- strptime(dfr$V4, "%Y/%m/%d_%H:%M:%S")
most.checked.out <- max(n.checked.out)
when.most.checked.out <- times[which(n.checked.out==most.checked.out)]
# As a bonus, plot license use
plot(times, n.checked.out, type="s")
|
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).
| #Racket | Racket | #lang racket
;;; reads a licence file on standard input
;;; returns max licences used and list of times this occurred
(define (count-licences)
(let inner ((ln (read-line)) (in-use 0) (max-in-use 0) (times-list null))
(if (eof-object? ln)
(values max-in-use (reverse times-list))
(let ((mtch (regexp-match #px"License (IN |OUT) @ (.*) for job.*" ln)))
(cond
[(string=? "OUT" (second mtch))
(let ((in-use+1 (add1 in-use)))
(cond
[(> in-use+1 max-in-use)
(inner (read-line) in-use+1 in-use+1 (list (third mtch)))]
[(= in-use+1 max-in-use)
(inner (read-line) in-use+1 max-in-use (cons (third mtch) times-list))]
[else (inner (read-line) in-use+1 max-in-use times-list)]))]
[(string=? "IN " (second mtch))
(inner (read-line) (sub1 in-use) max-in-use times-list)]
[else (inner (read-line) in-use max-in-use times-list)])))))
(define-values (max-used max-used-when)
(with-input-from-file "mlijobs.txt" count-licences))
(printf "Maximum licences in simultaneously used is ~a at the following times:~%"
max-used)
(for-each displayln max-used-when)
|
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.
| #Pascal | Pascal | # ptest.t
use strict;
use warnings;
use Test;
my %tests;
BEGIN {
# plan tests before loading Palindrome.pm
%tests = (
'A man, a plan, a canal: Panama.' => 1,
'My dog has fleas' => 0,
"Madam, I'm Adam." => 1,
'1 on 1' => 0,
'In girum imus nocte et consumimur igni' => 1,
'' => 1,
);
# plan 4 tests per string
plan tests => (keys(%tests) * 4);
}
use Palindrome;
for my $key (keys %tests) {
$_ = lc $key; # convert to lowercase
s/[\W_]//g; # keep only alphanumeric characters
my $expect = $tests{$key};
my $note = ("\"$key\" should " . ($expect ? '' : 'not ') .
"be a palindrome.");
ok palindrome == $expect, 1, "palindrome: $note";
ok palindrome_c == $expect, 1, "palindrome_c: $note";
ok palindrome_r == $expect, 1, "palindrome_r: $note";
ok palindrome_e == $expect, 1, "palindrome_e: $note";
} |
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
| #Common_Lisp | Common Lisp | let
((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," )))
(loop for day from 1 to 12 doing
(format t "On the ~:r day of Christmas, my true love sent to me:~%" day)
(loop for gift from (1- day) downto 0 doing
(format t "~a~%" (nth gift gifts)))
(format t "~%")))
|
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
| #Cowgol | Cowgol | include "cowgol.coh";
var ordinals: [uint8][] := {
"first","second","third","fourth","fifth",
"sixth","seventh","eighth","ninth","tenth",
"eleventh","twelfth"
};
var gifts: [uint8][] := {
"Twelve drummers drumming",
"Eleven pipers piping",
"Ten lords a-leaping",
"Nine ladies dancing",
"Eight maids a-milking",
"Seven swans a-swimming",
"Six geese a-laying",
"Five golden rings",
"Four calling birds",
"Three french hens",
"Two turtle doves and",
"A partridge in a pear tree."
};
var verse: @indexof ordinals := 0;
var gift: @indexof gifts;
while verse < 12 loop
print("On the ");
print(ordinals[verse]);
print(" day of Christmas, my true love gave to me:\n");
gift := 11 - verse;
while gift < 12 loop
print(gifts[gift]);
print_nl();
gift := gift + 1;
end loop;
print_nl();
verse := verse + 1;
end loop; |
http://rosettacode.org/wiki/Terminal_control/Dimensions | Terminal control/Dimensions | Determine the height and width of the terminal, and store this information into variables for subsequent use.
| #Python | Python | import os
def get_windows_terminal():
from ctypes import windll, create_string_buffer
h = windll.kernel32.GetStdHandle(-12)
csbi = create_string_buffer(22)
res = windll.kernel32.GetConsoleScreenBufferInfo(h, csbi)
#return default size if actual size can't be determined
if not res: return 80, 25
import struct
(bufx, bufy, curx, cury, wattr, left, top, right, bottom, maxx, maxy)\
= struct.unpack("hhhhHhhhhhh", csbi.raw)
width = right - left + 1
height = bottom - top + 1
return width, height
def get_linux_terminal():
width = os.popen('tput cols', 'r').readline()
height = os.popen('tput lines', 'r').readline()
return int(width), int(height)
print get_linux_terminal() if os.name == 'posix' else get_windows_terminal()
|
http://rosettacode.org/wiki/Terminal_control/Dimensions | Terminal control/Dimensions | Determine the height and width of the terminal, and store this information into variables for subsequent use.
| #Racket | Racket |
#lang racket
(require (planet neil/charterm:3:0))
(with-charterm
(charterm-screen-size))
|
http://rosettacode.org/wiki/Terminal_control/Dimensions | Terminal control/Dimensions | Determine the height and width of the terminal, and store this information into variables for subsequent use.
| #Raku | Raku | my $stty = qx[stty -a];
my $lines = $stty.match(/ 'rows ' <( \d+/);
my $cols = $stty.match(/ 'columns ' <( \d+/);
say "$lines $cols"; |
http://rosettacode.org/wiki/Terminal_control/Coloured_text | Terminal control/Coloured text | Task
Display a word in various colours on the terminal.
The system palette, or colours such as Red, Green, Blue, Magenta, Cyan, and Yellow can be used.
Optionally demonstrate:
How the system should determine if the terminal supports colour
Setting of the background colour
How to cause blinking or flashing (if supported by the terminal)
| #BBC_BASIC | BBC BASIC | FOR col% = 0 TO 14
COLOUR col% : REM foreground
COLOUR 128+(15-col%) : REM background
PRINT "Rosetta Code"
NEXT |
http://rosettacode.org/wiki/Terminal_control/Coloured_text | Terminal control/Coloured text | Task
Display a word in various colours on the terminal.
The system palette, or colours such as Red, Green, Blue, Magenta, Cyan, and Yellow can be used.
Optionally demonstrate:
How the system should determine if the terminal supports colour
Setting of the background colour
How to cause blinking or flashing (if supported by the terminal)
| #Befunge | Befunge | <v0"1Red"0"2Green"0"4Blue"0"5Magenta"0"6Cyan"0"3Yellow"00
,_:!#@_:"m3["39*,,,\,,"m4["39*,,,\"g"\->:#,_55+"m["39*,,, |
http://rosettacode.org/wiki/Terminal_control/Coloured_text | Terminal control/Coloured text | Task
Display a word in various colours on the terminal.
The system palette, or colours such as Red, Green, Blue, Magenta, Cyan, and Yellow can be used.
Optionally demonstrate:
How the system should determine if the terminal supports colour
Setting of the background colour
How to cause blinking or flashing (if supported by the terminal)
| #C | C | #include <stdio.h>
void table(const char *title, const char *mode)
{
int f, b;
printf("\n\033[1m%s\033[m\n bg\t fg\n", title);
for (b = 40; b <= 107; b++) {
if (b == 48) b = 100;
printf("%3d\t\033[%s%dm", b, mode, b);
for (f = 30; f <= 97; f++) {
if (f == 38) f = 90;
printf("\033[%dm%3d ", f, f);
}
puts("\033[m");
}
}
int main(void)
{
int fg, bg, blink, inverse;
table("normal ( ESC[22m or ESC[m )", "22;");
table("bold ( ESC[1m )", "1;");
table("faint ( ESC[2m ), not well supported", "2;");
table("italic ( ESC[3m ), not well supported", "3;");
table("underline ( ESC[4m ), support varies", "4;");
table("blink ( ESC[5m )", "5;");
table("inverted ( ESC[7m )", "7;");
return 0;
} |
http://rosettacode.org/wiki/Terminal_control/Cursor_movement | Terminal control/Cursor movement | Task
Demonstrate how to achieve movement of the terminal cursor:
how to move the cursor one position to the left
how to move the cursor one position to the right
how to move the cursor up one line (without affecting its horizontal position)
how to move the cursor down one line (without affecting its horizontal position)
how to move the cursor to the beginning of the line
how to move the cursor to the end of the line
how to move the cursor to the top left corner of the screen
how to move the cursor to the bottom right corner of the screen
For the purpose of this task, it is not permitted to overwrite any characters or attributes on any part of the screen (so outputting a space is not a suitable solution to achieve a movement to the right).
Handling of out of bounds locomotion
This task has no specific requirements to trap or correct cursor movement beyond the terminal boundaries, so the implementer should decide what behavior fits best in terms of the chosen language. Explanatory notes may be added to clarify how an out of bounds action would behave and the generation of error messages relating to an out of bounds cursor position is permitted.
| #Common_Lisp | Common Lisp | (defun cursor-movement ()
(with-screen (scr :input-blocking t :input-echoing nil :cursor-visible t)
;; display the screen and wait for a keypress
(refresh scr) (get-char scr)
(move-direction scr :right) (refresh scr) (get-char scr)
(move-direction scr :left) (refresh scr) (get-char scr)
(move-direction scr :down) (refresh scr) (get-char scr)
(move-direction scr :up) (refresh scr) (get-char scr)
;; end of line
(move scr (car (cursor-position scr)) (1- (width scr))) (refresh scr) (get-char scr)
;; beginning of line
(move scr (car (cursor-position scr)) 0) (refresh scr) (get-char scr)
;; bottom right corner
(move scr (1- (height scr)) (1- (width scr))) (refresh scr) (get-char scr)
;; top left corner
(move scr 0 0) (refresh scr) (get-char scr))) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.