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/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.23 | C# | static void Main(string[] args)
{
//There will be a 3 second pause between each cursor movement.
Console.Write("\n\n\n\n Cursor is here --> ");
System.Threading.Thread.Sleep(3000);
Console.CursorLeft = Console.CursorLeft - 1; //Console.CursorLeft += -1 is an alternative.
System.Threading.Thread.Sleep(3000);
Console.CursorLeft = Console.CursorLeft + 1;
System.Threading.Thread.Sleep(3000);
Console.CursorTop = Console.CursorTop - 1;
System.Threading.Thread.Sleep(3000);
Console.CursorTop = Console.CursorTop + 1;
System.Threading.Thread.Sleep(3000);
Console.CursorLeft = 0; //Move the cursor far left.
System.Threading.Thread.Sleep(3000);
Console.CursorLeft = Console.BufferWidth - 1;
/* BufferWidth represents the number of characters wide the console area is.
* The exact value may vary on different systems.
* As the cursor position is a 0 based index we must subtract 1 from buffer width or we move the cursor out of bounds.
* In some cases WindowWidth may be preferable (however in this demonstration window and buffer should be the same).
*/
System.Threading.Thread.Sleep(3000);
Console.SetCursorPosition(0,0); //I have used an alternative method for moving the cursor here which I feel is cleaner for the task at hand.
System.Threading.Thread.Sleep(3000);
Console.SetCursorPosition(Console.BufferWidth-1, Console.WindowHeight-1); //Buffer height is usually longer than the window so window has been used instead.
System.Threading.Thread.Sleep(3000);
}
|
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.
| #PHP | PHP |
echo "\033[".$x.",".$y."H"; // Position line $y and column $x.
echo "\033[".$n."A"; // Up $n lines.
echo "\033[".$n."B"; // Down $n lines.
echo "\033[".$n."C"; // Forward $n columns.
echo "\033[".$n."D"; // Backward $n columns.
echo "\033[2J"; // Clear the screen, move to (0,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.
| #PicoLisp | PicoLisp | (call 'tput "cup" 6 3)
(prin "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.
| #PowerShell | PowerShell | $Host.UI.RawUI.CursorPosition = New-Object System.Management.Automation.Host.Coordinates 2,5
$Host.UI.Write('Hello') |
http://rosettacode.org/wiki/Terminal_control/Cursor_positioning | Terminal control/Cursor positioning |
Task
Move the cursor to column 3, row 6, and display the word "Hello" (without the quotes), so that the letter H is in column 3 on row 6.
| #PureBasic | PureBasic | EnableGraphicalConsole(#True)
ConsoleLocate(3,6)
Print("Hello") |
http://rosettacode.org/wiki/Tau_number | Tau number | A Tau number is a positive integer divisible by the count of its positive divisors.
Task
Show the first 100 Tau numbers.
The numbers shall be generated during run-time (i.e. the code may not contain string literals, sets/arrays of integers, or alike).
Related task
Tau function
| #11l | 11l | F tau(n)
V ans = 0
V i = 1
V j = 1
L i * i <= n
I 0 == n % i
ans++
j = n I/ i
I j != i
ans++
i++
R ans
F is_tau_number(n)
I n <= 0
R 0B
R 0 == n % tau(n)
V n = 1
[Int] ans
L ans.len < 100
I is_tau_number(n)
ans.append(n)
n++
print(ans) |
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
| #AWK | AWK |
# syntax: GAWK -f TEACUP_RIM_TEXT.AWK UNIXDICT.TXT
#
# sorting:
# PROCINFO["sorted_in"] is used by GAWK
# SORTTYPE is used by Thompson Automation's TAWK
#
{ for (i=1; i<=NF; i++) {
arr[tolower($i)] = 0
}
}
END {
PROCINFO["sorted_in"] = "@ind_str_asc" ; SORTTYPE = 1
for (i in arr) {
leng = length(i)
if (leng > 2) {
delete tmp_arr
words = str = i
tmp_arr[i] = ""
for (j=2; j<=leng; j++) {
str = substr(str,2) substr(str,1,1)
if (str in arr) {
words = words " " str
tmp_arr[str] = ""
}
}
if (length(tmp_arr) == leng) {
count = 0
for (j in tmp_arr) {
(arr[j] == 0) ? arr[j]++ : count++
}
if (count == 0) {
printf("%s\n",words)
circular++
}
}
}
}
printf("%d words, %d circular\n",length(arr),circular)
exit(0)
}
|
http://rosettacode.org/wiki/Terminal_control/Clear_the_screen | Terminal control/Clear the screen | Task
Clear the terminal window.
| #AArch64_Assembly | AArch64 Assembly |
/* ARM assembly AARCH64 Raspberry PI 3B */
/* program clearScreen.s */
/*******************************************/
/* Constantes file */
/*******************************************/
/* for this file see task include a file in language AArch64 assembly*/
.include "../includeConstantesARM64.inc"
.equ BUFFERSIZE, 100
/*******************************************/
/* Initialized data */
/*******************************************/
.data
szMessStartPgm: .asciz "Program start \n"
szMessEndPgm: .asciz "Program normal end.\n"
szClear: .asciz "\33[2J" // console clear (id language C)
szClear1: .byte 0x1B
.byte 'c' // other console clear
.byte 0
szCarriageReturn: .asciz "\n"
/*******************************************/
/* UnInitialized data */
/*******************************************/
.bss
/*******************************************/
/* code section */
/*******************************************/
.text
.global main
main:
ldr x0,qAdrszMessStartPgm // display start message
bl affichageMess
//ldr x0,qAdrszClear // clear screen
ldr x0,qAdrszClear1 // change for other clear screen
bl affichageMess
ldr x0,qAdrszMessEndPgm // display end message
bl affichageMess
100: // standard end of the program
mov x0,0 // return code
mov x8,EXIT // request to exit program
svc 0 // perform system call
qAdrszMessStartPgm: .quad szMessStartPgm
qAdrszMessEndPgm: .quad szMessEndPgm
qAdrszClear: .quad szClear
qAdrszClear1: .quad szClear1
qAdrszCarriageReturn: .quad szCarriageReturn
/********************************************************/
/* File Include fonctions */
/********************************************************/
/* for this file see task include a file in language AArch64 assembly */
.include "../includeARM64.inc"
|
http://rosettacode.org/wiki/Terminal_control/Clear_the_screen | Terminal control/Clear the screen | Task
Clear the terminal window.
| #Action.21 | Action! | proc Main()
Put(125)
return |
http://rosettacode.org/wiki/Terminal_control/Clear_the_screen | Terminal control/Clear the screen | Task
Clear the terminal window.
| #Ada | Ada | with Ada.Text_IO;
procedure CLS is
begin
Ada.Text_IO.Put(ASCII.ESC & "[2J");
end CLS; |
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
| #Elena | Elena | import extensions;
import system'routines;
import system'collections;
sealed class Trit
{
bool _value;
bool cast() = _value;
constructor(v)
{
if (v != nil)
{
_value := cast bool(v);
}
}
Trit equivalent(b)
= _value.equal(cast bool(b)) \ back:nilValue;
Trit Inverted
= _value.Inverted \ back:nilValue;
Trit and(b)
{
if (nil == _value)
{
^ b.and:nil \ back:nilValue
}
else
{
^ _value.and((lazy:cast bool(b))) \ back:nilValue
}
}
Trit or(b)
{
if (nil == _value)
{
^ b.or:nilValue \ back:nilValue
}
else
{
^ _value.or((lazy:cast bool(b))) \ back:nilValue
}
}
Trit implies(b)
= self.Inverted.or(b);
string toPrintable() = _value.toPrintable() \ back:"maybe";
}
public program()
{
List<Trit> values := new Trit[]{true, nilValue, false};
values.forEach:(left)
{
console.printLine("¬",left," = ", left.Inverted);
values.forEach:(right)
{
console.printLine(left, " & ", right, " = ", left && right);
console.printLine(left, " | ", right, " = ", left || right);
console.printLine(left, " → ", right, " = ", left.implies:right);
console.printLine(left, " ≡ ", right, " = ", left.equivalent:right)
}
}
} |
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).
| #Yabasic | Yabasic | print chr$(156) |
http://rosettacode.org/wiki/Terminal_control/Display_an_extended_character | Terminal control/Display an extended character | Task
Display an extended (non ASCII) character onto the terminal.
Specifically, display a £ (GBP currency sign).
| #zkl | zkl | "\u00a3 \Ua3;".println() //-->£ £ |
http://rosettacode.org/wiki/Text_processing/1 | Text processing/1 | This task has been flagged for clarification. Code on this page in its current state may be flagged incorrect once this task has been clarified. See this page's Talk page for discussion.
Often data is produced by one program, in the wrong format for later use by another program or person. In these situations another program can be written to parse and transform the original data into a format useful to the other. The term "Data Munging" is often used in programming circles for this task.
A request on the comp.lang.awk newsgroup led to a typical data munging task:
I have to analyse data files that have the following format:
Each row corresponds to 1 day and the field logic is: $1 is the date,
followed by 24 value/flag pairs, representing measurements at 01:00,
02:00 ... 24:00 of the respective day. In short:
<date> <val1> <flag1> <val2> <flag2> ... <val24> <flag24>
Some test data is available at:
... (nolonger available at original location)
I have to sum up the values (per day and only valid data, i.e. with
flag>0) in order to calculate the mean. That's not too difficult.
However, I also need to know what the "maximum data gap" is, i.e. the
longest period with successive invalid measurements (i.e values with
flag<=0)
The data is free to download and use and is of this format:
Data is no longer available at that link. Zipped mirror available here (offsite mirror).
1991-03-30 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1
1991-03-31 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 20.000 1 20.000 1 20.000 1 35.000 1 50.000 1 60.000 1 40.000 1 30.000 1 30.000 1 30.000 1 25.000 1 20.000 1 20.000 1 20.000 1 20.000 1 20.000 1 35.000 1
1991-03-31 40.000 1 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2
1991-04-01 0.000 -2 13.000 1 16.000 1 21.000 1 24.000 1 22.000 1 20.000 1 18.000 1 29.000 1 44.000 1 50.000 1 43.000 1 38.000 1 27.000 1 27.000 1 24.000 1 23.000 1 18.000 1 12.000 1 13.000 1 14.000 1 15.000 1 13.000 1 10.000 1
1991-04-02 8.000 1 9.000 1 11.000 1 12.000 1 12.000 1 12.000 1 27.000 1 26.000 1 27.000 1 33.000 1 32.000 1 31.000 1 29.000 1 31.000 1 25.000 1 25.000 1 24.000 1 21.000 1 17.000 1 14.000 1 15.000 1 12.000 1 12.000 1 10.000 1
1991-04-03 10.000 1 9.000 1 10.000 1 10.000 1 9.000 1 10.000 1 15.000 1 24.000 1 28.000 1 24.000 1 18.000 1 14.000 1 12.000 1 13.000 1 14.000 1 15.000 1 14.000 1 15.000 1 13.000 1 13.000 1 13.000 1 12.000 1 10.000 1 10.000 1
Only a sample of the data showing its format is given above. The full example file may be downloaded here.
Structure your program to show statistics for each line of the file, (similar to the original Python, Perl, and AWK examples below), followed by summary statistics for the file. When showing example output just show a few line statistics and the full end summary.
| #Forth | Forth | \ data munging
\ 1991-03-30[\t10.000\t[-]1]*24
\ 1. mean of valid (flag > 0) values per day and overall
\ 2. length of longest run of invalid values, and when it happened
fvariable day-sum
variable day-n
fvariable total-sum
variable total-n
10 constant date-size \ yyyy-mm-dd
create cur-date date-size allot
create bad-date date-size allot
variable bad-n
create worst-date date-size allot
variable worst-n
: split ( buf len char -- buf' l2 buf l1 ) \ where buf'[0] = char, l1 = len-l2
>r 2dup r> scan
2swap 2 pick - ;
: next-sample ( buf len -- buf' len' fvalue flag )
#tab split >float drop 1 /string
#tab split snumber? drop >r 1 /string r> ;
: ok? 0> ;
: add-sample ( value -- )
day-sum f@ f+ day-sum f!
1 day-n +! ;
: add-day
day-sum f@ total-sum f@ f+ total-sum f!
day-n @ total-n +! ;
: add-bad-run
bad-n @ 0= if
cur-date bad-date date-size move
then
1 bad-n +! ;
: check-worst-run
bad-n @ worst-n @ > if
bad-n @ worst-n !
bad-date worst-date date-size move
then
0 bad-n ! ;
: hour ( buf len -- buf' len' )
next-sample ok? if
add-sample
check-worst-run
else
fdrop
add-bad-run
then ;
: .mean ( sum count -- ) 0 d>f f/ f. ;
: day ( line len -- )
2dup + #tab swap c! 1+ \ append tab for parsing
#tab split cur-date swap move 1 /string \ skip date
0e day-sum f!
0 day-n !
24 0 do hour loop 2drop
cur-date date-size type ." mean = "
day-sum f@ day-n @ .mean cr
add-day ;
stdin value input
: main
s" input.txt" r/o open-file throw to input
0e total-sum f!
0 total-n !
0 worst-n !
begin pad 512 input read-line throw
while pad swap day
repeat
input close-file throw
worst-n @ if
." Longest interruption: " worst-n @ .
." hours starting " worst-date date-size type cr
then
." Total mean = "
total-sum f@ total-n @ .mean cr ;
main bye |
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.
| #Python | Python | import random
import collections
INT_MASK = 0xFFFFFFFF # we use this to emulate 32-bit overflow semantics by masking off higher bits after operations
class IsaacRandom(random.Random):
"""
Random number generator using the ISAAC algorithm.
"""
def seed(self, seed=None):
"""
Initialize internal state.
The seed, if given, can be a string, an integer, or an iterable that contains
integers only. If no seed is given, a fixed default state is set up; unlike
our superclass, this class will not attempt to randomize the seed from outside sources.
"""
def mix():
init_state[0] ^= ((init_state[1]<<11)&INT_MASK); init_state[3] += init_state[0]; init_state[3] &= INT_MASK; init_state[1] += init_state[2]; init_state[1] &= INT_MASK
init_state[1] ^= (init_state[2]>>2) ; init_state[4] += init_state[1]; init_state[4] &= INT_MASK; init_state[2] += init_state[3]; init_state[2] &= INT_MASK
init_state[2] ^= ((init_state[3]<<8 )&INT_MASK); init_state[5] += init_state[2]; init_state[5] &= INT_MASK; init_state[3] += init_state[4]; init_state[3] &= INT_MASK
init_state[3] ^= (init_state[4]>>16) ; init_state[6] += init_state[3]; init_state[6] &= INT_MASK; init_state[4] += init_state[5]; init_state[4] &= INT_MASK
init_state[4] ^= ((init_state[5]<<10)&INT_MASK); init_state[7] += init_state[4]; init_state[7] &= INT_MASK; init_state[5] += init_state[6]; init_state[5] &= INT_MASK
init_state[5] ^= (init_state[6]>>4 ) ; init_state[0] += init_state[5]; init_state[0] &= INT_MASK; init_state[6] += init_state[7]; init_state[6] &= INT_MASK
init_state[6] ^= ((init_state[7]<<8 )&INT_MASK); init_state[1] += init_state[6]; init_state[1] &= INT_MASK; init_state[7] += init_state[0]; init_state[7] &= INT_MASK
init_state[7] ^= (init_state[0]>>9 ) ; init_state[2] += init_state[7]; init_state[2] &= INT_MASK; init_state[0] += init_state[1]; init_state[0] &= INT_MASK
super().seed(0) # give a chance for the superclass to reset its state - the actual seed given to it doesn't matter
if seed is not None:
if isinstance(seed, str):
seed = [ord(x) for x in seed]
elif isinstance(seed, collections.Iterable):
seed = [x & INT_MASK for x in seed]
elif isinstance(seed, int):
val = abs(seed)
seed = []
while val:
seed.append(val & INT_MASK)
val >>= 32
else:
raise TypeError('Seed must be string, integer or iterable of integer')
# make sure the seed list is exactly 256 elements long
if len(seed)>256:
del seed[256:]
elif len(seed)<256:
seed.extend([0]*(256-len(seed)))
self.aa = self.bb = self.cc = 0
self.mm = []
init_state = [0x9e3779b9]*8
for _ in range(4):
mix()
for i in range(0, 256, 8):
if seed is not None:
for j in range(8):
init_state[j] += seed[i+j]
init_state[j] &= INT_MASK
mix()
self.mm += init_state
if seed is not None:
for i in range(0, 256, 8):
for j in range(8):
init_state[j] += self.mm[i+j]
init_state[j] &= INT_MASK
mix()
for j in range(8):
self.mm[i+j] = init_state[j]
self.rand_count = 256
self.rand_result = [0]*256
def getstate(self):
return super().getstate(), self.aa, self.bb, self.cc, self.mm, self.rand_count, self.rand_result
def setstate(self, state):
super().setstate(state[0])
_, self.aa, self.bb, self.cc, self.mm, self.rand_count, self.rand_result = state
def _generate(self):
# Generate 256 random 32-bit values and save them in an internal field.
# The actual random functions will dish out these values to callers.
self.cc = (self.cc + 1) & INT_MASK
self.bb = (self.bb + self.cc) & INT_MASK
for i in range(256):
x = self.mm[i]
mod = i & 3
if mod==0:
self.aa ^= ((self.aa << 13) & INT_MASK)
elif mod==1:
self.aa ^= (self.aa >> 6)
elif mod==2:
self.aa ^= ((self.aa << 2) & INT_MASK)
else: # mod == 3
self.aa ^= (self.aa >> 16)
self.aa = (self.mm[i^128] + self.aa) & INT_MASK
y = self.mm[i] = (self.mm[(x>>2) & 0xFF] + self.aa + self.bb) & INT_MASK
self.rand_result[i] = self.bb = (self.mm[(y>>10) & 0xFF] + x) & INT_MASK
self.rand_count = 0
def next_int(self):
"""Return a random integer between 0 (inclusive) and 2**32 (exclusive)."""
if self.rand_count == 256:
self._generate()
result = self.rand_result[self.rand_count]
self.rand_count += 1
return result
def getrandbits(self, k):
"""Return a random integer between 0 (inclusive) and 2**k (exclusive)."""
result = 0
ints_needed = (k+31)//32
ints_used = 0
while ints_used < ints_needed:
if self.rand_count == 256:
self._generate()
ints_to_take = min(256-self.rand_count, ints_needed)
for val in self.rand_result[self.rand_count : self.rand_count+ints_to_take]:
result = (result << 32) | val
self.rand_count += ints_to_take
ints_used += ints_to_take
result &= ((1<<k)-1) # mask off extra bits, if any
return result
def random(self):
"""Return a random float between 0 (inclusive) and 1 (exclusive)."""
# A double stores 53 significant bits, so scale a 53-bit integer into the [0..1) range.
return self.getrandbits(53) * (2**-53)
def rand_char(self):
"""Return a random integer from the printable ASCII range [32..126]."""
return self.next_int() % 95 + 32
def vernam(self, msg):
"""
Encrypt/decrypt the given bytes object with the XOR algorithm, using the current generator state.
To decrypt an encrypted string, restore the state of the generator to the state it had
during encryption, then call this method with the encrypted string.
"""
return bytes((self.rand_char() & 0xFF) ^ x for x in msg)
# Constants for selecting Caesar operation modes.
ENCIPHER = 'encipher'
DECIPHER = 'decipher'
@staticmethod
def _caesar(ciphermode, ch, shift, modulo, start):
if ciphermode == IsaacRandom.DECIPHER:
shift = -shift
n = ((ch-start)+shift) % modulo
if n<0:
n += modulo
return start+n
def caesar(self, ciphermode, msg, modulo, start):
"""
Encrypt/decrypt a string using the Caesar algorithm.
For decryption to work, the generator must be in the same state it was during encryption,
and the same modulo and start parameters must be used.
ciphermode must be one of IsaacRandom.ENCIPHER or IsaacRandom.DECIPHER.
"""
return bytes(self._caesar(ciphermode, ch, self.rand_char(), modulo, start) for ch in msg)
if __name__=='__main__':
import binascii
def hexify(b):
return binascii.hexlify(b).decode('ascii').upper()
MOD = 95
START = 32
msg = 'a Top Secret secret'
key = 'this is my secret key'
isaac_random = IsaacRandom(key)
vernam_encoded = isaac_random.vernam(msg.encode('ascii'))
caesar_encoded = isaac_random.caesar(IsaacRandom.ENCIPHER, msg.encode('ascii'), MOD, START)
isaac_random.seed(key)
vernam_decoded = isaac_random.vernam(vernam_encoded).decode('ascii')
caesar_decoded = isaac_random.caesar(IsaacRandom.DECIPHER, caesar_encoded, MOD, START).decode('ascii')
print('Message:', msg)
print('Key :', key)
print('XOR :', hexify(vernam_encoded))
print('XOR dcr:', vernam_decoded)
print('MOD :', hexify(caesar_encoded))
print('MOD dcr:', caesar_decoded)
|
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.)
| #Ruby | Ruby |
class Numeric
def to_i?
self == self.to_i rescue false
end
end
# Demo
ar = [25.000000, 24.999999, 25.000100, -2.1e120, -5e-2, # Floats
Float::NAN, Float::INFINITY, # more Floats
2r, 2.5r, # Rationals
2+0i, 2+0.0i, 5-5i] # Complexes
ar.each{|num| puts "#{num} integer? #{num.to_i?}" }
|
http://rosettacode.org/wiki/Test_integerness | Test integerness | Mathematically,
the integers Z are included in the rational numbers Q,
which are included in the real numbers R,
which can be generalized to the complex numbers C.
This means that each of those larger sets, and the data types used to represent them, include some integers.
Task[edit]
Given a rational, real, or complex number of any type, test whether it is mathematically an integer.
Your code should handle all numeric data types commonly used in your programming language.
Discuss any limitations of your code.
Definition
For the purposes of this task, integerness means that a number could theoretically be represented as an integer at no loss of precision (given an infinitely wide integer type).
In other words:
Set
Common representation
C++ type
Considered an integer...
rational numbers Q
fraction
std::ratio
...if its denominator is 1 (in reduced form)
real numbers Z
(approximated)
fixed-point
...if it has no non-zero digits after the decimal point
floating-point
float, double
...if the number of significant decimal places of its mantissa isn't greater than its exponent
complex numbers C
pair of real numbers
std::complex
...if its real part is considered an integer and its imaginary part is zero
Extra credit
Optionally, make your code accept a tolerance parameter for fuzzy testing. The tolerance is the maximum amount by which the number may differ from the nearest integer, to still be considered an integer.
This is useful in practice, because when dealing with approximate numeric types (such as floating point), there may already be round-off errors from previous calculations. For example, a float value of 0.9999999998 might actually be intended to represent the integer 1.
Test cases
Input
Output
Comment
Type
Value
exact
tolerance = 0.00001
decimal
25.000000
true
24.999999
false
true
25.000100
false
floating-point
-2.1e120
true
This one is tricky, because in most languages it is too large to fit into a native integer type.
It is, nonetheless, mathematically an integer, and your code should identify it as such.
-5e-2
false
NaN
false
Inf
false
This one is debatable. If your code considers it an integer, that's okay too.
complex
5.0+0.0i
true
5-5i
false
(The types and notations shown in these tables are merely examples – you should use the native data types and number literals of your programming language and standard library. Use a different set of test-cases, if this one doesn't demonstrate all relevant behavior.)
| #Scheme | Scheme | sash[r7rs]> (integer? 1)
#t
sash[r7rs]> (integer? 2/3)
#f
sash[r7rs]> (integer? 4/2)
#t
sash[r7rs]> (integer? 1+3i)
#f
sash[r7rs]> (integer? 1+0i)
#t
sash[r7rs]> (exact? 3.0)
#f
sash[r7rs]> (integer? 3.0)
#t
sash[r7rs]> (integer? 3.5)
#f
sash[r7rs]> (integer? 1.23e3)
#t
sash[r7rs]> (integer? 1.23e1)
#f
sash[r7rs]> (integer? 1e120)
#t
|
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).
| #Raku | Raku | my %licenses;
%licenses<count max> = 0,0;
for $*IN.lines -> $line {
my ( $license, $date_time );
( *, $license, *, $date_time ) = split /\s+/, $line;
if $license eq 'OUT' {
%licenses<count>++;
if %licenses<count> > %licenses<max> {
%licenses<max> = %licenses<count>;
%licenses<times> = [$date_time];
}
elsif %licenses<count> == %licenses<max> {
%licenses<times>.push($date_time);
}
}
elsif $license eq 'IN' {
if %licenses<count> == %licenses<max> {
%licenses<times>[*-1] ~= " through " ~ $date_time;
}
%licenses<count>--;
}
else {
# Not a licence OUT or IN event, do nothing
}
};
my $plural = %licenses<times>.elems == 1 ?? '' !! 's';
say "Maximum concurrent licenses in use: {%licenses<max>}, in the time period{$plural}:";
say join ",\n", %licenses<times>.list; |
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.
| #Perl | Perl | # 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
| #Crystal | Crystal | days = "first second third fourth fifth sixth seventh eighth ninth tenth eleventh twelfth".split " "
gifts = "A partridge in a pear tree
Two turtle doves and
Three french hens
Four calling birds
Five golden rings
Six geese a-laying
Seven swans a-swimming
Eight maids a-milking
Nine ladies dancing
Ten lords a-leaping
Eleven pipers piping
Twelve drummers drumming".split "\n"
days.each_with_index do |day, i|
puts "On the #{day} day of Christmas\nMy true love gave to me:"
gifts[0, i + 1].reverse.each &->puts(String)
puts
end |
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.
| #Retro | Retro | -3 5 out wait 5 in !cw
-4 5 out wait 5 in !ch |
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.
| #REXX | REXX | width = 'tput'( 'cols' )
height = 'tput'( 'lines' )
say 'The terminal is' width 'characters wide'
say 'and has' height '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.
| #Ring | Ring |
system("mode 50,20")
|
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.
| #Ruby | Ruby | def winsize
# Ruby 1.9.3 added 'io/console' to the standard library.
require 'io/console'
IO.console.winsize
rescue LoadError
# This works with older Ruby, but only with systems
# that have a tput(1) command, such as Unix clones.
[Integer(`tput li`), Integer(`tput co`)]
end
rows, cols = winsize
printf "%d rows by %d columns\n", rows, 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)
| #C.23 | C# |
static void Main(string[] args)
{
Console.ForegroundColor = ConsoleColor.Red;
Console.BackgroundColor = ConsoleColor.Yellow;
Console.WriteLine("Red on Yellow");
Console.ForegroundColor = ConsoleColor.White;
Console.BackgroundColor = ConsoleColor.Black;
Console.WriteLine("White on black");
Console.ResetColor();
Console.WriteLine("Back to normal");
Console.ReadKey();
}
|
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)
| #COBOL | COBOL | *> Apologies for the repetitiveness.
IDENTIFICATION DIVISION.
PROGRAM-ID. coloured-text.
DATA DIVISION.
WORKING-STORAGE SECTION.
78 example-str VALUE "COBOL".
01 fore-colour PIC 9.
01 back-colour PIC 9.
01 line-num PIC 99 VALUE 1.
01 col-num PIC 99 VALUE 1.
01 pause PIC X.
PROCEDURE DIVISION.
PERFORM VARYING fore-colour FROM 0 BY 1 UNTIL fore-colour > 7
PERFORM VARYING back-colour FROM 0 BY 1
UNTIL back-colour > 7
DISPLAY example-str AT LINE line-num, COLUMN col-num
WITH FOREGROUND-COLOR fore-colour,
BACKGROUND-COLOR back-colour
ADD 6 TO col-num
END-PERFORM
ADD 1 TO line-num
MOVE 1 TO col-num
END-PERFORM
DISPLAY "With HIGHLIGHT:" AT LINE line-num, COLUMN 1
ADD 1 TO line-num
PERFORM VARYING fore-colour FROM 0 BY 1 UNTIL fore-colour > 7
PERFORM VARYING back-colour FROM 0 BY 1
UNTIL back-colour > 7
DISPLAY example-str AT LINE line-num, COLUMN col-num
WITH FOREGROUND-COLOR fore-colour,
BACKGROUND-COLOR back-colour HIGHLIGHT
ADD 6 TO col-num
END-PERFORM
ADD 1 TO line-num
MOVE 1 TO col-num
END-PERFORM
DISPLAY "With LOWLIGHT: (has no effect on many terminals)"
AT LINE line-num, COLUMN 1
ADD 1 TO line-num
PERFORM VARYING fore-colour FROM 0 BY 1 UNTIL fore-colour > 7
PERFORM VARYING back-colour FROM 0 BY 1
UNTIL back-colour > 7
DISPLAY example-str AT LINE line-num, COLUMN col-num
WITH FOREGROUND-COLOR fore-colour,
BACKGROUND-COLOR back-colour LOWLIGHT
ADD 6 TO col-num
END-PERFORM
ADD 1 TO line-num
MOVE 1 TO col-num
END-PERFORM
DISPLAY "With BLINK:" AT LINE line-num, COLUMN 1
ADD 1 TO line-num
PERFORM VARYING fore-colour FROM 0 BY 1 UNTIL fore-colour > 7
PERFORM VARYING back-colour FROM 0 BY 1
UNTIL back-colour > 7
DISPLAY example-str AT LINE line-num, COLUMN col-num
WITH FOREGROUND-COLOR fore-colour,
BACKGROUND-COLOR back-colour BLINK
ADD 6 TO col-num
END-PERFORM
ADD 1 TO line-num
MOVE 1 TO col-num
END-PERFORM
DISPLAY "Press enter to continue."
AT LINE line-num, COLUMN 1
ACCEPT pause AT LINE line-num, COLUMN 40
GOBACK
. |
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.
| #Forth | Forth | ( ANSI terminal control lexicon )
DECIMAL
( support routines)
27 CONSTANT ESC
: <##> ( n -- ) ( sends n, radix 10, no spaces)
BASE @ >R DECIMAL 0 <# #S #> TYPE R> BASE ! ;
: ESC[ ( -- ) ESC EMIT ." [" ;
( ANSI terminal commands as Forth words)
: <CUU> ( row --) ESC[ <##> ." A" ;
: <CUD> ( row --) ESC[ <##> ." B" ;
: <CUF> ( col --) ESC[ <##> ." C" ;
: <CUB> ( col --) ESC[ <##> ." D" ;
: <CPL> ( -- ) ESC[ <##> ." F" ;
: <CHA> ( n --) ESC[ <##> ." G" ;
: <EL> ( -- ) ESC[ ." K" ;
: <ED> ( -- ) ESC[ ." 2J" ;
: <CUP> ( row col -- ) SWAP ESC[ <##> ." ;" <##> ." H" ;
( Define ANSI Forth names for these functions using our markup words)
: AT-XY ( col row -- ) SWAP <CUP> ;
: PAGE ( -- ) <ED> 1 1 <CUP> ; |
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.
| #Go | Go | package main
import (
"fmt"
"time"
"os"
"os/exec"
"strconv"
)
func main() {
tput("clear") // clear screen
tput("cup", "6", "3") // an initial position
time.Sleep(1 * time.Second)
tput("cub1") // left
time.Sleep(1 * time.Second)
tput("cuf1") // right
time.Sleep(1 * time.Second)
tput("cuu1") // up
time.Sleep(1 * time.Second)
// cud1 seems broken for me. cud 1 works fine though.
tput("cud", "1") // down
time.Sleep(1 * time.Second)
tput("cr") // begining of line
time.Sleep(1 * time.Second)
// get screen size here
var h, w int
cmd := exec.Command("stty", "size")
cmd.Stdin = os.Stdin
d, _ := cmd.Output()
fmt.Sscan(string(d), &h, &w)
// end of line
tput("hpa", strconv.Itoa(w-1))
time.Sleep(2 * time.Second)
// top left
tput("home")
time.Sleep(2 * time.Second)
// bottom right
tput("cup", strconv.Itoa(h-1), strconv.Itoa(w-1))
time.Sleep(3 * time.Second)
}
func tput(args ...string) error {
cmd := exec.Command("tput", args...)
cmd.Stdout = os.Stdout
return cmd.Run()
} |
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.
| #Python | Python | print("\033[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.
| #Quackery | Quackery | [ number$ swap number$
$ 'print("\033[' rot join
char ; join
swap join
$ 'H", end="")' join
python ] is cursor-at ( x y --> )
3 6 cursor-at say "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.
| #Racket | Racket |
#lang racket
(require (planet neil/charterm:3:0))
(with-charterm
(charterm-clear-screen)
(charterm-cursor 3 6)
(displayln "Hello World"))
|
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.
| #Raku | Raku | print "\e[6;3H";
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.
| #Retro | Retro | with console'
: hello 3 6 at-xy "Hello" puts ; |
http://rosettacode.org/wiki/Tau_number | Tau number | A Tau number is a positive integer divisible by the count of its positive divisors.
Task
Show the first 100 Tau numbers.
The numbers shall be generated during run-time (i.e. the code may not contain string literals, sets/arrays of integers, or alike).
Related task
Tau function
| #Action.21 | Action! | CARD FUNC DivisorCount(CARD n)
CARD result,p,count
result=1
WHILE (n&1)=0
DO
result==+1
n=n RSH 1
OD
p=3
WHILE p*p<=n
DO
count=1
WHILE n MOD p=0
DO
count==+1
n==/p
OD
result==*count
p==+2
OD
IF n>1 THEN
result==*2
FI
RETURN (result)
PROC Main()
CARD n=[1],max=[100],count=[0],divCount
WHILE count<max
DO
divCount=DivisorCount(n)
IF n MOD divCount=0 THEN
PrintC(n) Put(32)
count==+1
FI
n==+1
OD
RETURN |
http://rosettacode.org/wiki/Tau_number | Tau number | A Tau number is a positive integer divisible by the count of its positive divisors.
Task
Show the first 100 Tau numbers.
The numbers shall be generated during run-time (i.e. the code may not contain string literals, sets/arrays of integers, or alike).
Related task
Tau function
| #ALGOL_68 | ALGOL 68 | BEGIN # find tau numbers - numbers divisible by the count of theoir divisors #
# calculates the number of divisors of v #
PROC divisor count = ( INT v )INT:
BEGIN
INT total := 1, n := v;
# Deal with powers of 2 first #
WHILE NOT ODD n DO
total +:= 1;
n OVERAB 2
OD;
# Odd prime factors up to the square root #
INT p := 1;
WHILE p +:= 2;
( p * p ) <= n
DO
INT count := 1;
WHILE n MOD p = 0 DO
count +:= 1;
n OVERAB p
OD;
total *:= count
OD;
# If n > 1 then it's prime #
IF n > 1 THEN total *:= 2 FI;
total
END # divisor count #;
BEGIN
INT tau limit = 100;
INT tau count := 0;
print( ( "The first ", whole( tau limit, 0 ), " tau numbers:", newline ) );
FOR n WHILE tau count < tau limit DO
IF n MOD divisor count( n ) = 0 THEN
tau count +:= 1;
print( ( whole( n, -6 ) ) );
IF tau count MOD 10 = 0 THEN print( ( newline ) ) FI
FI
OD
END
END |
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
| #BaCon | BaCon | OPTION COLLAPSE TRUE
dict$ = LOAD$(DIRNAME$(ME$) & "/unixdict.txt")
FOR word$ IN dict$ STEP NL$
IF LEN(word$) = 3 AND AMOUNT(UNIQ$(EXPLODE$(word$, 1))) = 3 THEN domain$ = APPEND$(domain$, 0, word$)
NEXT
FOR w1$ IN domain$
w2$ = RIGHT$(w1$, 2) & LEFT$(w1$, 1)
w3$ = RIGHT$(w2$, 2) & LEFT$(w2$, 1)
IF TALLY(domain$, w2$) AND TALLY(domain$, w3$) AND NOT(TALLY(result$, w1$)) THEN
result$ = APPEND$(result$, 0, w1$ & " " & w2$ & " " & w3$, NL$)
ENDIF
NEXT
PRINT result$
PRINT "Total words: ", AMOUNT(dict$, NL$), ", and ", AMOUNT(result$, NL$), " are circular." |
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
| #C | C | #include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>
#include <glib.h>
int string_compare(gconstpointer p1, gconstpointer p2) {
const char* const* s1 = p1;
const char* const* s2 = p2;
return strcmp(*s1, *s2);
}
GPtrArray* load_dictionary(const char* file, GError** error_ptr) {
GError* error = NULL;
GIOChannel* channel = g_io_channel_new_file(file, "r", &error);
if (channel == NULL) {
g_propagate_error(error_ptr, error);
return NULL;
}
GPtrArray* dict = g_ptr_array_new_full(1024, g_free);
GString* line = g_string_sized_new(64);
gsize term_pos;
while (g_io_channel_read_line_string(channel, line, &term_pos,
&error) == G_IO_STATUS_NORMAL) {
char* word = g_strdup(line->str);
word[term_pos] = '\0';
g_ptr_array_add(dict, word);
}
g_string_free(line, TRUE);
g_io_channel_unref(channel);
if (error != NULL) {
g_propagate_error(error_ptr, error);
g_ptr_array_free(dict, TRUE);
return NULL;
}
g_ptr_array_sort(dict, string_compare);
return dict;
}
void rotate(char* str, size_t len) {
char c = str[0];
memmove(str, str + 1, len - 1);
str[len - 1] = c;
}
char* dictionary_search(const GPtrArray* dictionary, const char* word) {
char** result = bsearch(&word, dictionary->pdata, dictionary->len,
sizeof(char*), string_compare);
return result != NULL ? *result : NULL;
}
void find_teacup_words(GPtrArray* dictionary) {
GHashTable* found = g_hash_table_new(g_str_hash, g_str_equal);
GPtrArray* teacup_words = g_ptr_array_new();
GString* temp = g_string_sized_new(8);
for (size_t i = 0, n = dictionary->len; i < n; ++i) {
char* word = g_ptr_array_index(dictionary, i);
size_t len = strlen(word);
if (len < 3 || g_hash_table_contains(found, word))
continue;
g_ptr_array_set_size(teacup_words, 0);
g_string_assign(temp, word);
bool is_teacup_word = true;
for (size_t i = 0; i < len - 1; ++i) {
rotate(temp->str, len);
char* w = dictionary_search(dictionary, temp->str);
if (w == NULL) {
is_teacup_word = false;
break;
}
if (strcmp(word, w) != 0 && !g_ptr_array_find(teacup_words, w, NULL))
g_ptr_array_add(teacup_words, w);
}
if (is_teacup_word && teacup_words->len > 0) {
printf("%s", word);
g_hash_table_add(found, word);
for (size_t i = 0; i < teacup_words->len; ++i) {
char* teacup_word = g_ptr_array_index(teacup_words, i);
printf(" %s", teacup_word);
g_hash_table_add(found, teacup_word);
}
printf("\n");
}
}
g_string_free(temp, TRUE);
g_ptr_array_free(teacup_words, TRUE);
g_hash_table_destroy(found);
}
int main(int argc, char** argv) {
if (argc != 2) {
fprintf(stderr, "usage: %s dictionary\n", argv[0]);
return EXIT_FAILURE;
}
GError* error = NULL;
GPtrArray* dictionary = load_dictionary(argv[1], &error);
if (dictionary == NULL) {
if (error != NULL) {
fprintf(stderr, "Cannot load dictionary file '%s': %s\n",
argv[1], error->message);
g_error_free(error);
}
return EXIT_FAILURE;
}
find_teacup_words(dictionary);
g_ptr_array_free(dictionary, TRUE);
return EXIT_SUCCESS;
} |
http://rosettacode.org/wiki/Temperature_conversion | Temperature conversion | There are quite a number of temperature scales. For this task we will concentrate on four of the perhaps best-known ones:
Kelvin, Celsius, Fahrenheit, and Rankine.
The Celsius and Kelvin scales have the same magnitude, but different null points.
0 degrees Celsius corresponds to 273.15 kelvin.
0 kelvin is absolute zero.
The Fahrenheit and Rankine scales also have the same magnitude, but different null points.
0 degrees Fahrenheit corresponds to 459.67 degrees Rankine.
0 degrees Rankine is absolute zero.
The Celsius/Kelvin and Fahrenheit/Rankine scales have a ratio of 5 : 9.
Task
Write code that accepts a value of kelvin, converts it to values of the three other scales, and prints the result.
Example
K 21.00
C -252.15
F -421.87
R 37.80
| #11l | 11l | V k = 21.0
print(‘K ’k)
print(‘C ’(k - 273.15))
print(‘F ’(k * 1.8 - 459.67))
print(‘R ’(k * 1.8)) |
http://rosettacode.org/wiki/Tau_function | Tau function | Given a positive integer, count the number of its positive divisors.
Task
Show the result for the first 100 positive integers.
Related task
Tau number
| #11l | 11l | F tau(n)
V ans = 0
V i = 1
V j = 1
L i * i <= n
I 0 == n % i
ans++
j = n I/ i
I j != i
ans++
i++
R ans
print((1..100).map(n -> tau(n))) |
http://rosettacode.org/wiki/Terminal_control/Clear_the_screen | Terminal control/Clear the screen | Task
Clear the terminal window.
| #ALGOL_68 | ALGOL 68 | curses start; # needed before any screen clearing, positioning etc. #
curses clear # clear the screen # |
http://rosettacode.org/wiki/Terminal_control/Clear_the_screen | Terminal control/Clear the screen | Task
Clear the terminal window.
| #ARM_Assembly | ARM Assembly |
/* ARM assembly Raspberry PI */
/* program clearScreen.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"
szClear: .asciz "\33[2J" @ console clear (id language C)
szClear1: .byte 0x1B
.byte 'c' @ other console clear
.byte 0
szCarriageReturn: .asciz "\n"
/* UnInitialized data */
.bss
/* code section */
.text
.global main
main:
ldr r0,iAdrszMessStartPgm @ display start message
bl affichageMess
//ldr r0,iAdrszClear @ clear screen
ldr r0,iAdrszClear1 @ change for other clear screen
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
iAdrszClear: .int szClear
iAdrszClear1: .int szClear1
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/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
| #Erlang | Erlang | % Implemented by Arjun Sunel
-module(ternary).
-export([main/0, nott/1, andd/2,orr/2, then/2, equiv/2]).
main() ->
{ok, [A]} = io:fread("Enter A: ","~s"),
{ok, [B]} = io:fread("Enter B: ","~s"),
andd(A,B).
nott(S) ->
if
S=="T" ->
io : format("F\n");
S=="F" ->
io : format("T\n");
true ->
io: format("?\n")
end.
andd(A, B) ->
if
A=="T", B=="T" ->
io : format("T\n");
A=="F"; B=="F" ->
io : format("F\n");
true ->
io: format("?\n")
end.
orr(A, B) ->
if
A=="T"; B=="T" ->
io : format("T\n");
A=="?"; B=="?" ->
io : format("?\n");
true ->
io: format("F\n")
end.
then(A, B) ->
if
B=="T" ->
io : format("T\n");
A=="?" ->
io : format("?\n");
A=="F" ->
io :format("T\n");
B=="F" ->
io:format("F\n");
true ->
io: format("?\n")
end.
equiv(A, B) ->
if
A=="?" ->
io : format("?\n");
A=="F" ->
io : format("~s\n", [nott(B)]);
true ->
io: format("~s\n", [B])
end.
|
http://rosettacode.org/wiki/Text_processing/1 | Text processing/1 | This task has been flagged for clarification. Code on this page in its current state may be flagged incorrect once this task has been clarified. See this page's Talk page for discussion.
Often data is produced by one program, in the wrong format for later use by another program or person. In these situations another program can be written to parse and transform the original data into a format useful to the other. The term "Data Munging" is often used in programming circles for this task.
A request on the comp.lang.awk newsgroup led to a typical data munging task:
I have to analyse data files that have the following format:
Each row corresponds to 1 day and the field logic is: $1 is the date,
followed by 24 value/flag pairs, representing measurements at 01:00,
02:00 ... 24:00 of the respective day. In short:
<date> <val1> <flag1> <val2> <flag2> ... <val24> <flag24>
Some test data is available at:
... (nolonger available at original location)
I have to sum up the values (per day and only valid data, i.e. with
flag>0) in order to calculate the mean. That's not too difficult.
However, I also need to know what the "maximum data gap" is, i.e. the
longest period with successive invalid measurements (i.e values with
flag<=0)
The data is free to download and use and is of this format:
Data is no longer available at that link. Zipped mirror available here (offsite mirror).
1991-03-30 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1
1991-03-31 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 20.000 1 20.000 1 20.000 1 35.000 1 50.000 1 60.000 1 40.000 1 30.000 1 30.000 1 30.000 1 25.000 1 20.000 1 20.000 1 20.000 1 20.000 1 20.000 1 35.000 1
1991-03-31 40.000 1 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2
1991-04-01 0.000 -2 13.000 1 16.000 1 21.000 1 24.000 1 22.000 1 20.000 1 18.000 1 29.000 1 44.000 1 50.000 1 43.000 1 38.000 1 27.000 1 27.000 1 24.000 1 23.000 1 18.000 1 12.000 1 13.000 1 14.000 1 15.000 1 13.000 1 10.000 1
1991-04-02 8.000 1 9.000 1 11.000 1 12.000 1 12.000 1 12.000 1 27.000 1 26.000 1 27.000 1 33.000 1 32.000 1 31.000 1 29.000 1 31.000 1 25.000 1 25.000 1 24.000 1 21.000 1 17.000 1 14.000 1 15.000 1 12.000 1 12.000 1 10.000 1
1991-04-03 10.000 1 9.000 1 10.000 1 10.000 1 9.000 1 10.000 1 15.000 1 24.000 1 28.000 1 24.000 1 18.000 1 14.000 1 12.000 1 13.000 1 14.000 1 15.000 1 14.000 1 15.000 1 13.000 1 13.000 1 13.000 1 12.000 1 10.000 1 10.000 1
Only a sample of the data showing its format is given above. The full example file may be downloaded here.
Structure your program to show statistics for each line of the file, (similar to the original Python, Perl, and AWK examples below), followed by summary statistics for the file. When showing example output just show a few line statistics and the full end summary.
| #Fortran | Fortran |
Crunches a set of hourly data. Starts with a date, then 24 pairs of value,indicator for that day, on one line.
INTEGER Y,M,D !Year, month, and day.
INTEGER GOOD(24) !The indicators.
REAL*8 V(24),VTOT,T !The grist.
INTEGER NV,N,NB !Number of good values overall, and in a day.
INTEGER I,NREC,HIC !Some counters.
INTEGER BI,BN,BBI,BBN !Stuff to locate the longest run of bad data,
CHARACTER*10 BDATE,BBDATE !Along with the starting date.
LOGICAL INGOOD !State flipper for the runs of data.
INTEGER IN,MSG !I/O mnemonics.
CHARACTER*666 ACARD !Scratchpad, of sufficient length for all expectation.
IN = 10 !Unit number for the input file.
MSG = 6 !Output.
OPEN (IN,FILE="Readings1.txt", FORM="FORMATTED", !This should be a function.
1 STATUS ="OLD",ACTION="READ") !Returning success, or failure.
NB = 0 !No bad values read.
NV = 0 !Nor good values read.
VTOT = 0 !Their average is to come.
NREC = 0 !No records read.
HIC = 0 !Provoking no complaints.
INGOOD = .TRUE. !I start in hope.
BBN = 0 !And the longest previous bad run is short.
Chew into the file.
10 READ (IN,11,END=100,ERR=666) L,ACARD(1:MIN(L,LEN(ACARD))) !With some protection.
NREC = NREC + 1 !So, a record has been read.
11 FORMAT (Q,A) !Obviously, Q ascertains the length of the record being read.
READ (ACARD,12,END=600,ERR=601) Y,M,D !The date part is trouble, as always.
12 FORMAT (I4,2(1X,I2)) !Because there are no delimiters between the parts.
READ (ACARD(11:L),*,END=600,ERR=601) (V(I),GOOD(I),I = 1,24) !But after the date, delimiters abound.
Calculations. Could use COUNT(array) and SUM(array), but each requires its own pass through the array.
20 T = 0 !Start on the day's statistics.
N = 0 !No values yet.
DO I = 1,24 !So, scan the cargo and do all the twiddling in one pass..
IF (GOOD(I).GT.0) THEN !A good value?
N = N + 1 !Yes. Count it in.
T = T + V(I) !And augment for the average.
IF (.NOT.INGOOD) THEN !Had we been ungood?
INGOOD = .TRUE. !Yes. But now it changes.
IF (BN.GT.BBN) THEN !The run just ending: is it longer?
BBN = BN !Yes. Make it the new baddest.
BBI = BI !Recalling its start index,
BBDATE = BDATE !And its start date.
END IF !So much for bigger badness.
END IF !Now we're in good data.
ELSE !Otherwise, a bad value is upon us.
IF (INGOOD) THEN !Were we good?
INGOOD = .FALSE. !No longer. A new bad run is starting.
BDATE = ACARD(1:10) !Recall the date for this starter.
BI = I !And its index.
BN = 0 !Start the run-length counter.
END IF !So much for a fall.
BN = BN + 1 !Count another bad value.
END IF !Good or bad, so much for that value.
END DO !On to the next.
Commentary for the day's data..
IF (N.LE.0) THEN !I prefer to avoid dividing by zero.
WRITE (MSG,21) NREC,ACARD(1:10) !So, no average to report.
21 FORMAT ("Record",I8," (",A,") has no good data!") !Just a remark.
ELSE !But otherwise,
WRITE(MSG,22) NREC,ACARD(1:10),N,T/N !An average is possible.
22 FORMAT("Record",I8," (",A,")",I3," good, average",F9.3) !So here it is.
NB = NB + 24 - N !Count the bad by implication.
NV = NV + N !Count the good directly.
VTOT = VTOT + T !Should really sum deviations from a working average.
END IF !So much for that line.
GO TO 10 !More! More! I want more!!
Complaints. Should really distinguish between trouble in the date part and in the data part.
600 WRITE (MSG,*) '"END" declared - insufficient data?' !Not enough numbers, presumably.
GO TO 602 !Reveal the record.
601 WRITE (MSG,*) '"ERR" declared - improper number format?' !Ah, but which number?
602 WRITE (MSG,603) NREC,L,ACARD(1:L) !Anyway, reveal the uninterpreted record.
603 FORMAT(" Record ",I0,", length ",I0," reads ",A) !Just so.
HIC = HIC + 1 !This may grow into a habit.
IF (HIC.LE.12) GO TO 10 !But if not yet, try the next record.
STOP "Enough distaste." !Or, give up.
666 WRITE (MSG,101) NREC,"format error!" !For A-style data? Should never happen!
GO TO 900 !But if it does, give up!
Closedown.
100 WRITE (MSG,101) NREC,"then end-of-file" !Discovered on the next attempt.
101 FORMAT (" Record ",I0,": ",A) !A record number plus a remark.
WRITE (MSG,102) NV,NB,VTOT/NV !The overall results.
102 FORMAT (I8," values, ",I0," bad. Average",F9.4) !This should do.
IF (BBN.LE.0) THEN !Now for a special report.
WRITE (MSG,*) "No bad value presented, so no longest run." !Unneeded!
ELSE !But actually, the example data has some bad values.
WRITE (MSG,103) BBN,BBI,BBDATE !And this is for the longest encountered.
103 FORMAT ("Longest bad run: ",I0,", starting hour ",I0," on ",A) !Just so.
END IF !Enough remarks.
900 CLOSE(IN) !Done.
END !Spaghetti rules.
|
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.
| #Racket | Racket | #lang racket
;; Imperative version: Translation of C
;; Vigenère: Translation of Pascal
(module+ test (require tests/eli-tester))
;; ---------------------------------------------------------------------------------------------------
;; standard.h: Standard definitions and types, Bob Jenkins
(define UB4MAXVAL #xffffffff)
(define-syntax-rule (bit target mask) (bitwise-and target mask))
;; C-like operators
(define-syntax-rule (u4-truncate x) (bit x UB4MAXVAL))
(define-syntax-rule (u4<< a b) (u4-truncate (arithmetic-shift a b)))
(define-syntax-rule (u4>> a b) (u4-truncate (arithmetic-shift a (- b))))
(define-syntax-rule (_++ i) (let ((rv i)) (set! i (u4-truncate (add1 i))) rv))
(define-syntax-rule (u4+= a b) (begin (set! a (u4-truncate (+ a b))) a))
(define-syntax-rule (^= a b) (begin (set! a (u4-truncate (bitwise-xor a b))) a))
;; ---------------------------------------------------------------------------------------------------
;; rand.h: definitions for a random number generator
(define RANDSIZL 8)
(define RANDSIZ (u4<< 1 RANDSIZL))
(define RANDSIZ-1 (sub1 RANDSIZ))
(struct randctx
(cnt
rsl ; RANDSIZ*4 bytes (makes u4's)
mem ; RANDSIZ*4 bytes (makes u4's)
a b c) #:mutable)
(define (new-randctx)
(randctx 0 (make-bytes (* 4 RANDSIZ) 0) (make-bytes (* 4 RANDSIZ) 0) 0 0 0))
(define (bytes->hex-string B (start 0) (end #f) #:join (join "") #:show-bytes? (show-bytes? #f))
(define hexes
(for/list ((b (in-bytes B start end)))
(~a (number->string b 16) #:width 2 #:align 'right #:pad-string "0")))
(string-join
(append hexes (if show-bytes?
(list " \"" (bytes->string/utf-8 B #f start (or end (bytes-length B))) "\"")
null))
join))
(define format-randctx
(match-lambda
[(randctx C (app bytes->hex-string R) (app bytes->hex-string M) a b c)
(format "randctx: cnt:~a~%rsl:~s~%mem:~s~%a:~a b:~a c:~a" C R M a b c)]))
(define be? (system-big-endian?))
(define (bytes->u4 ary idx)
(integer-bytes->integer ary #f be? (* idx 4) (* (add1 idx) 4)))
(define (u4->bytes! ary idx v)
(integer->integer-bytes (bit v UB4MAXVAL) 4 #f be? ary (* idx 4)))
;; ---------------------------------------------------------------------------------------------------
;; rand.c: "By Bob Jenkins. My random number generator, ISAAC. Public Domain."
(define (ind mm x)
(define idx (bitwise-and x (u4<< RANDSIZ-1 2)))
(integer-bytes->integer mm #f be? idx (+ idx 4)))
(define (isaac C)
(define M (randctx-mem C))
(define R (randctx-rsl C))
(define mm 0)
(define r 0)
(define-syntax-rule (rng-step mix)
(begin
(define x (bytes->u4 M m))
(set! a (u4-truncate (+ (bitwise-xor a mix) (bytes->u4 M (_++ m2)))))
(define y (+ (ind M x) a b))
(u4->bytes! M (_++ m) y)
(set! b (u4-truncate (+ (ind M (u4>> y RANDSIZL)) x)))
(u4->bytes! R (_++ r) b)))
(define a (randctx-a C))
(set-randctx-c! C (add1 (randctx-c C)))
(define b (u4-truncate (+ (randctx-b C) (randctx-c C))))
(define m mm)
(define m2 (+ m (/ RANDSIZ 2)))
(define mend m2)
(define-syntax-rule (4-step-loop variant)
(let loop ()
(when (< variant mend)
(rng-step (u4<< a 13)) (rng-step (u4>> a 6))
(rng-step (u4<< a 2)) (rng-step (u4>> a 16))
(loop))))
(4-step-loop m)
(set! m2 mm)
(4-step-loop m2)
(set-randctx-b! C b)
(set-randctx-a! C a))
;; dot infix notation because I'm too lazy to move the operators left!
(define-syntax-rule (mix-line<< A B N D C)
(begin (A . ^= . (B . u4<< . N)) (D . u4+= . A) (B . u4+= . C)))
(define-syntax-rule (mix-line>> A B N D C)
(begin (A . ^= . (B . u4>> . N)) (D . u4+= . A) (B . u4+= . C)))
(define-syntax-rule (mix a b c d e f g h)
(begin (mix-line<< a b 11 d c) (mix-line>> b c 2 e d)
(mix-line<< c d 8 f e) (mix-line>> d e 16 g f)
(mix-line<< e f 10 h g) (mix-line>> f g 4 a h)
(mix-line<< g h 8 b a) (mix-line>> h a 9 c b)))
;; if (flag==TRUE), then use the contents of randrsl[] to initialize mm[].
(define (rand-init C flag?)
(set-randctx-a! C 0)
(set-randctx-b! C 0)
(set-randctx-c! C 0)
;; seed-ctx should set these up (with the seed!):
;; (set-ctx-rsl! C (make-bytes (* 4 RANDSIZ) 0))
;; (set-ctx-mem! C (make-bytes (* 4 RANDSIZ) 0))
(define R (randctx-rsl C))
(define M (randctx-mem C))
(define φ #x9e3779b9) ; the golden ratio
(match-define (list a b c d e f g h) (make-list 8 φ))
(for ((_ 4)) (mix a b c d e f g h)) ; scramble it
(define-syntax-rule (mix-and-assign i M2)
(begin
(mix a b c d e f g h)
(u4->bytes! M2 (+ i 0) a) (u4->bytes! M2 (+ i 1) b)
(u4->bytes! M2 (+ i 2) c) (u4->bytes! M2 (+ i 3) d)
(u4->bytes! M2 (+ i 4) e) (u4->bytes! M2 (+ i 5) f)
(u4->bytes! M2 (+ i 6) g) (u4->bytes! M2 (+ i 7) h)))
(define-syntax-rule (mix-with-mem M1 M2)
(for ((i (in-range 0 RANDSIZ 8)))
(a . u4+= . (bytes->u4 M1 (+ i 0))) (b . u4+= . (bytes->u4 M1 (+ i 1)))
(c . u4+= . (bytes->u4 M1 (+ i 2))) (d . u4+= . (bytes->u4 M1 (+ i 3)))
(e . u4+= . (bytes->u4 M1 (+ i 4))) (f . u4+= . (bytes->u4 M1 (+ i 5)))
(g . u4+= . (bytes->u4 M1 (+ i 6))) (h . u4+= . (bytes->u4 M1 (+ i 7)))
(mix-and-assign i M2)))
(cond
[flag? ; initialize using the contents of r[] as the seed
(mix-with-mem R M)
(mix-with-mem M M)] ; do a second pass to make all of the seed affect all of m
[else ; fill in m[] with messy stuff
(for ((i (in-range 0 RANDSIZ 8))) (mix-and-assign i M))])
(isaac C) ; fill in the first set of results
(set-randctx-cnt! C 0)) ; prepare to use the first set of results
(define (seed-ctx C key #:flag? (flag? #t))
(bytes-fill! (randctx-mem C) 0)
(define R (randctx-rsl C))
(bytes-fill! (randctx-rsl C) 0)
(for ((k (in-bytes key)) (i (in-range (quotient (bytes-length R) 4)))) (u4->bytes! R i k))
(rand-init C flag?))
;; Get a random 32-bit value 0..MAXINT
(define (i-random C)
(define cnt (randctx-cnt C))
(define r (bytes->u4 (randctx-rsl C) cnt))
(define cnt+1 (add1 cnt))
(cond [(>= cnt+1 RANDSIZ) (isaac C) (set-randctx-cnt! C 0)]
[else (set-randctx-cnt! C cnt+1)])
r)
;; Get a random character in printable ASCII range
(define ((i-rand-a C))
(+ 32 (modulo (i-random C) 95)))
(define (Vernham rnd-fn msg)
(define gsm (make-bytes (bytes-length msg)))
(for ((i (in-naturals)) (m (in-bytes msg)))
(define r (rnd-fn))
(define b (bitwise-xor m r))
(bytes-set! gsm i b))
gsm)
;; Get position of the letter in chosen alphabet
;; Caesar-shift a character <shift> places: Generalized Vigenere
(define ((Caesar mod-n start) encrypt? shift ch)
(define (letter-num letter/byte)
(- letter/byte (char->integer start)))
(define shift-fn (if encrypt? + -))
(+ (char->integer start) (modulo (shift-fn (letter-num ch) shift) mod-n)))
;; Vigenère mod 95 encryption & decryption. Output: bytes
(define Vigenère-Caeser (Caesar 95 #\space))
(define (Vigenère encrypt? rand-fn msg)
(list->bytes
(for/list ((b (in-bytes msg)))
(Vigenère-Caeser encrypt? (rand-fn) b))))
{module+ main
(define message #"a Top Secret secret")
(define key #"this is my secret key")
(define C (new-randctx))
(seed-ctx C key)
(define vern.msg (Vernham (i-rand-a C) message))
;; Pascal doesn't reset the context betwen XOR and MOD
;; (seed-ctx C key)
(define vigen.msg (Vigenère #t (i-rand-a C) message))
(seed-ctx C key)
(define vern2.msg (Vernham (i-rand-a C) vern.msg))
;; Pascal doesn't reset the context betwen XOR and MOD
;; (seed-ctx C key)
(define unvigen.msg (Vigenère #f (i-rand-a C) vigen.msg))
;; This is what MOD looks like from the context as seeded with key
(seed-ctx C key)
(define vigen-at-seed.msg (Vigenère #t (i-rand-a C) message))
(seed-ctx C key)
(define unvigen-at-seed.msg (Vigenère #f (i-rand-a C) vigen-at-seed.msg))
(printf #<<EOS
Message: [~a]
Key: [~a]
< context reseeded
Vernham (XOR): [~a]
Vigenère (MOD): [~a]
< context reseeded
Vernham (XOR(XOR)): [~a]
Vigenère (-MOD): [~a]
< context reseeded (different to Pascal Vigenère encryption)
Vigenère (MOD): [~a]
< context reseeded
Vigenère (-MOD): [~a]
EOS
message
key
(bytes->hex-string vern.msg)
(bytes->hex-string vigen.msg #:show-bytes? #t)
(bytes->hex-string vern2.msg #:show-bytes? #t)
(bytes->hex-string unvigen.msg #:show-bytes? #t)
(bytes->hex-string vigen-at-seed.msg #:show-bytes? #t)
(bytes->hex-string unvigen-at-seed.msg #:show-bytes? #t)
)}
{module+ test
;; "If the initial internal state is all zero, after ten calls the values of aa, bb, and cc in
;; hexadecimal will be d4d3f473, 902c0691, and 0000000a."
(let ()
(define C (new-randctx))
(for ((_ 10)) (isaac C))
(test (randctx-a C) => #xd4d3f473
(randctx-b C) => #x902c0691
(randctx-c C) => 10))
} |
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.)
| #Sidef | Sidef | func is_int (n, tolerance=0) {
!!(abs(n.real.round + n.imag - n) <= tolerance)
}
%w(25.000000 24.999999 25.000100 -2.1e120 -5e-2 Inf NaN 5.0+0.0i 5-5i).each {|s|
var n = Number(s)
printf("%-10s %-8s %-5s\n", s,
is_int(n),
is_int(n, 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.)
| #Tcl | Tcl | proc isNumberIntegral {x} {
expr {$x == entier($x)}
}
# test with various kinds of numbers:
foreach x {1e100 3.14 7 1.000000000000001 1000000000000000000000 -22.7 -123.000} {
puts [format "%s: %s" $x [expr {[isNumberIntegral $x] ? "yes" : "no"}]]
} |
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).
| #REXX | REXX | /*REXX program processes instrument data as read from a time sorted data file.*/
iFID= 'LICENSE.LOG' /*the fileID of the input file. */
high=0 /*highest number of licenses (so far). */
#=0 /*the count of number of licenses out. */
n=0 /*the number of highest licenses out. */
do recs=0 while lines(iFID)\==0 /* [↓] read file until end─of─file. */
parse value linein(iFID) with . ? . $ /*get IN│OUT status, job info.*/
if ?=='IN' then #=#-1 /*decrement the license count.*/
else if ?=='OUT' then #=#+1 /*increment " " " */
if # >high then do; n=1; job.1=$; end /*the job info for highest cnt*/
if #==high then do; n=n+1; job.n=$; end /* " " " " equal " */
high=max(high,#) /*calculate max license count.*/
end /*while ···*/
say recs 'records read from the input file: ' iFID
say 'The maximum number of licenses out is ' high " at:"
say
do j=1 for n /*show what/when max licenses occurred.*/
say left('',20) job.j /*indent the information displayed. */
end /*j*/ /*stick a fork in it, we're all done. */ |
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.
| #Phix | Phix | with javascript_semantics
requires("0.8.2")
function is_palindrome(sequence s)
return s==reverse(s)
end function
--set_test_verbosity(TEST_QUIET) -- default, no output when third call removed
--set_test_verbosity(TEST_SUMMARY) -- first and last line only [w or w/o ""]
--set_test_verbosity(TEST_SHOW_FAILED) -- first and last two lines only
set_test_verbosity(TEST_SHOW_ALL) -- as shown in last two cases below
--set_test_abort(TEST_ABORT) -- abort(1) on failure, after showing the summary
--set_test_abort(TEST_QUIET) -- quietly carry on, the default
--set_test_abort(TEST_CRASH) -- abort immmediately on failure (w/o summary)
--set_test_pause(TEST_PAUSE_FAIL) -- pause on failure, the default
--set_test_pause(TEST_QUIET) -- disable pause on failure
--set_test_pause(TEST_PAUSE) -- always pause
set_test_module("palindromes") -- optional, w/o first line is omitted
test_true(is_palindrome("abba"),"abba")
test_true(is_palindrome("abba")) -- no desc makes success hidden...
-- ...and failure somewhat laconic
test_false(is_palindrome("abc"),"not abc")
test_true(is_palindrome("failure"),"failure")
test_summary()
|
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.
| #PicoLisp | PicoLisp | (de palindrome? (S)
(= (setq S (chop S)) (reverse S)) )
(test T (palindrome? "racecar"))
(test NIL (palindrome? "ferrari")) |
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
| #D | D | immutable gifts =
"A partridge in a pear tree.
Two turtle doves
Three french hens
Four calling birds
Five golden rings
Six geese a-laying
Seven swans a-swimming
Eight maids a-milking
Nine ladies dancing
Ten lords a-leaping
Eleven pipers piping
Twelve drummers drumming";
immutable days = "first second third fourth fifth
sixth seventh eighth ninth tenth
eleventh twelfth";
void main() @safe {
import std.stdio, std.string, std.range;
foreach (immutable n, immutable day; days.split) {
auto g = gifts.splitLines.take(n + 1).retro;
writeln("On the ", day,
" day of Christmas\nMy true love gave to me:\n",
g[0 .. $ - 1].join('\n'),
(n > 0 ? " and\n" ~ g.back : g.back.capitalize), '\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.
| #Scala | Scala | /*
First execute the terminal command: 'export COLUMNS LINES'
before running this program for it to work (returned 'null' sizes otherwise).
*/
val (lines, columns) = (System.getenv("LINES"), System.getenv("COLUMNS"))
println(s"Lines = $lines, 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.
| #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);
writeln(console, "height: " <& height(console) lpad 3);
writeln(console, "width: " <& width(console) lpad 3);
# 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/Terminal_control/Dimensions | Terminal control/Dimensions | Determine the height and width of the terminal, and store this information into variables for subsequent use.
| #Sidef | Sidef | var stty = `stty -a`;
var lines = stty.match(/\brows\h+(\d+)/);
var cols = stty.match(/\bcolumns\h+(\d+)/);
say "#{lines} #{cols}"; |
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.
| #Tcl | Tcl | set width [exec tput cols]
set height [exec tput lines]
puts "The terminal is $width characters wide and has $height lines" |
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)
| #Common_Lisp | Common Lisp | (defun coloured-text ()
(with-screen (scr :input-blocking t :input-echoing nil :cursor-visible nil)
(dolist (i '(:red :green :yellow :blue :magenta :cyan :white))
(add-string scr (format nil "~A~%" i) :fgcolor i))
(refresh scr)
;; wait for keypress
(get-char scr))) |
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)
| #D | D | import
std.conv,
std.stdio;
enum Color {
fgBlack = 30,
fgRed,
fgGreen,
fgYellow,
fgBlue,
fgMagenta,
fgCyan,
fgWhite,
bgBlack = 40,
bgRed,
bgGreen,
bgYellow,
bgBlue,
bgMagenta,
bgCyan,
bgWhite
}
string color(string text, Color ink) {
return "\033["
~ ink.to!int.to!string
~ "m"
~ text
~ "\033[0m";
}
void main() {
auto colors = [
Color.fgBlack,
Color.fgRed,
Color.fgGreen,
Color.fgYellow,
Color.fgBlue,
Color.fgMagenta,
Color.fgCyan,
Color.fgWhite
];
foreach (c; colors) {
// Print the color name, in white.
c.to!string.color(Color.fgWhite).writeln;
// Print some text in the color.
"Hello, world!".color(c).writeln;
}
} |
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.
| #Julia | Julia | const ESC = "\u001B" # escape code
const moves = Dict( "left" => "[1D", "right" => "[1C", "up" => "[1A", "down" => "[1B",
"linestart" => "[9D", "topleft" => "[H", "bottomright" => "[24;79H")
print("$ESC[2J") # clear terminal first
print("$ESC[10;10H") # move cursor to (10, 10) say
const count = [0]
for d in ["left", "right", "up", "down", "linestart", "bottomright"]
sleep(3) # three second pause for display between cursor movements
print("$ESC$(moves[d])")
print(count[1] += 1)
end
println()
println()
|
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.
| #Kotlin | Kotlin | // version 1.1.2
const val ESC = "\u001B" // escape code
fun main(args: Array<String>) {
print("$ESC[2J") // clear terminal first
print("$ESC[10;10H") // move cursor to (10, 10) say
val aecs = arrayOf(
"[1D", // left
"[1C", // right
"[1A", // up
"[1B", // down
"[9D", // line start
"[H", // top left
"[24;79H" // bottom right - assuming 80 x 24 terminal
)
for (aec in aecs) {
Thread.sleep(3000) // three second display between cursor movements
print("$ESC$aec")
}
Thread.sleep(3000)
println()
} |
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.
| #Lasso | Lasso | #!/usr/bin/lasso9
local(esc = decode_base64('Gw=='))
stdoutnl('Demonstrate how to move the cursor one position to the left
Demonstrate how to move the cursor one position to the right
Demonstrate how to move the cursor up one line (without affecting its horizontal position)
Demonstrate how to move the cursor down one line (without affecting its horizontal position)
Demonstrate how to move the cursor to the beginning of the line
Demonstrate how to move the cursor to the end of the line
Demonstrate how to move the cursor to the top left corner of the screen
Demonstrate how to move the cursor to the bottom right corner of the screen
')
// place cursor in a suitable place before exercise
stdout(#esc + '[5;10H')
sleep(2000)
// move the cursor one position to the left
stdout(#esc + '[1D')
sleep(2000)
// move the cursor one position to the right
stdout(#esc + '[1C')
sleep(2000)
// move the cursor up one line
stdout(#esc + '[1A')
sleep(2000)
// move the cursor down one line
stdout(#esc + '[1B')
sleep(2000)
// move the cursor to the beginning of the line
stdout(#esc + '[100D')
sleep(2000)
// move the cursor to the top left corner of the screen
stdout(#esc + '[H')
sleep(2000)
// move the cursor to the bottom right corner of the screen
stdout(#esc + '[500;500H')
sleep(2000) |
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.
| #REXX | REXX | /*REXX program demonstrates moving the cursor position and writing of text to same place*/
call cursor 3,6 /*move the cursor to row 3, column 6. */
say 'Hello' /*write the text at that location. */
call scrwrite 30,50,'Hello.' /*another method, different location. */
call scrwrite 40,60,'Hello.',,,14 /*another method ... in yellow. */
exit 0 /*stick a fork in it, we're all done. */ |
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.
| #Ring | Ring |
# Project : Terminal control/Cursor positioning
for n = 1 to 5
see nl
next
see " 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.
| #Ruby | Ruby | require 'curses'
Curses.init_screen
begin
Curses.setpos(6, 3) # column 6, row 3
Curses.addstr("Hello")
Curses.getch # Wait until user presses some key.
ensure
Curses.close_screen
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.
| #Scala | Scala | object Main extends App {
print("\u001Bc") // clear screen first
println("\u001B[6;3HHello")
} |
http://rosettacode.org/wiki/Taxicab_numbers | Taxicab numbers |
A taxicab number (the definition that is being used here) is a positive integer that can be expressed as the sum of two positive cubes in more than one way.
The first taxicab number is 1729, which is:
13 + 123 and also
93 + 103.
Taxicab numbers are also known as:
taxi numbers
taxi-cab numbers
taxi cab numbers
Hardy-Ramanujan numbers
Task
Compute and display the lowest 25 taxicab numbers (in numeric order, and in a human-readable format).
For each of the taxicab numbers, show the number as well as it's constituent cubes.
Extra credit
Show the 2,000th taxicab number, and a half dozen more
See also
A001235: taxicab numbers on The On-Line Encyclopedia of Integer Sequences.
Hardy-Ramanujan Number on MathWorld.
taxicab number on MathWorld.
taxicab number on Wikipedia (includes the story on how taxi-cab numbers came to be called).
| #11l | 11l | V cubes = (1..1199).map(x -> Int64(x) ^ 3)
[Int64 = Int64] crev
L(x3) cubes
crev[x3] = L.index + 1
V sums = sorted(multiloop_filtered(cubes, cubes, (x, y) -> y < x, (x, y) -> x + y))
V idx = 0
L(i) 1 .< sums.len - 1
I sums[i - 1] != sums[i] & sums[i] == sums[i + 1]
idx++
I (idx > 25 & idx < 2000) | idx > 2006
L.continue
V n = sums[i]
[(Int64, Int64)] p
L(x) cubes
I n - x < x
L.break
I n - x C crev
p.append((crev[x], crev[n - x]))
print(‘#4: #10’.format(idx, n), end' ‘ ’)
L(x1, x2) p
print(‘ = #4^3 + #4^3’.format(x1, x2), end' ‘ ’)
print() |
http://rosettacode.org/wiki/Tau_number | Tau number | A Tau number is a positive integer divisible by the count of its positive divisors.
Task
Show the first 100 Tau numbers.
The numbers shall be generated during run-time (i.e. the code may not contain string literals, sets/arrays of integers, or alike).
Related task
Tau function
| #ALGOL-M | ALGOL-M | begin
integer array dcount[1:1100];
integer i, j, n;
integer function mod(a,b);
integer a,b;
mod := a-a/b*b;
% Calculate counts of divisors for 1 .. 1100 %
for i := 1 step 1 until 1100 do dcount[i] := 1;
for i := 2 step 1 until 1100 do
begin
j := i;
while j <= 1100 do
begin
dcount[j] := dcount[j] + 1;
j := j + i;
end;
end;
n := 0;
i := 1;
while n < 100 do
begin
if mod(i, dcount[i])=0 then
begin
if mod(n, 10)=0
then write(i)
else writeon(i);
n := n + 1;
end;
i := i + 1;
end;
end |
http://rosettacode.org/wiki/Tau_number | Tau number | A Tau number is a positive integer divisible by the count of its positive divisors.
Task
Show the first 100 Tau numbers.
The numbers shall be generated during run-time (i.e. the code may not contain string literals, sets/arrays of integers, or alike).
Related task
Tau function
| #APL | APL | (⊢(/⍨)(0=(0+.=⍳|⊢)|⊢)¨)⍳ 1096 |
http://rosettacode.org/wiki/Tau_number | Tau number | A Tau number is a positive integer divisible by the count of its positive divisors.
Task
Show the first 100 Tau numbers.
The numbers shall be generated during run-time (i.e. the code may not contain string literals, sets/arrays of integers, or alike).
Related task
Tau function
| #AppleScript | AppleScript | on factorCount(n)
if (n < 1) then return 0
set counter to 2
set sqrt to n ^ 0.5
if (sqrt mod 1 = 0) then set counter to 1
repeat with i from (sqrt div 1) to 2 by -1
if (n mod i = 0) then set counter to counter + 2
end repeat
return counter
end factorCount
-- Task code:
local output, n, counter, astid
set output to {"First 100 tau numbers:"}
set n to 0
set counter to 0
repeat until (counter = 100)
set n to n + 1
if (n mod (factorCount(n)) = 0) then
set counter to counter + 1
if (counter mod 20 = 1) then set end of output to linefeed
set end of output to text -5 thru -1 of (" " & n)
end if
end repeat
set astid to AppleScript's text item delimiters
set AppleScript's text item delimiters to ""
set output to output as text
set AppleScript's text item delimiters to astid
return output |
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
| #C.2B.2B | C++ | #include <algorithm>
#include <fstream>
#include <iostream>
#include <set>
#include <string>
#include <vector>
// filename is expected to contain one lowercase word per line
std::set<std::string> load_dictionary(const std::string& filename) {
std::ifstream in(filename);
if (!in)
throw std::runtime_error("Cannot open file " + filename);
std::set<std::string> words;
std::string word;
while (getline(in, word))
words.insert(word);
return words;
}
void find_teacup_words(const std::set<std::string>& words) {
std::vector<std::string> teacup_words;
std::set<std::string> found;
for (auto w = words.begin(); w != words.end(); ++w) {
std::string word = *w;
size_t len = word.size();
if (len < 3 || found.find(word) != found.end())
continue;
teacup_words.clear();
teacup_words.push_back(word);
for (size_t i = 0; i + 1 < len; ++i) {
std::rotate(word.begin(), word.begin() + 1, word.end());
if (word == *w || words.find(word) == words.end())
break;
teacup_words.push_back(word);
}
if (teacup_words.size() == len) {
found.insert(teacup_words.begin(), teacup_words.end());
std::cout << teacup_words[0];
for (size_t i = 1; i < len; ++i)
std::cout << ' ' << teacup_words[i];
std::cout << '\n';
}
}
}
int main(int argc, char** argv) {
if (argc != 2) {
std::cerr << "usage: " << argv[0] << " dictionary\n";
return EXIT_FAILURE;
}
try {
find_teacup_words(load_dictionary(argv[1]));
} catch (const std::exception& ex) {
std::cerr << ex.what() << '\n';
return EXIT_FAILURE;
}
return EXIT_SUCCESS;
} |
http://rosettacode.org/wiki/Temperature_conversion | Temperature conversion | There are quite a number of temperature scales. For this task we will concentrate on four of the perhaps best-known ones:
Kelvin, Celsius, Fahrenheit, and Rankine.
The Celsius and Kelvin scales have the same magnitude, but different null points.
0 degrees Celsius corresponds to 273.15 kelvin.
0 kelvin is absolute zero.
The Fahrenheit and Rankine scales also have the same magnitude, but different null points.
0 degrees Fahrenheit corresponds to 459.67 degrees Rankine.
0 degrees Rankine is absolute zero.
The Celsius/Kelvin and Fahrenheit/Rankine scales have a ratio of 5 : 9.
Task
Write code that accepts a value of kelvin, converts it to values of the three other scales, and prints the result.
Example
K 21.00
C -252.15
F -421.87
R 37.80
| #360_Assembly | 360 Assembly | * Temperature conversion 10/09/2015
TEMPERAT CSECT
USING TEMPERAT,R15
LA R4,1 i=1
LA R5,TT @tt(1)
LA R6,IDE @ide(1)
LOOPI CH R4,=AL2((T-TT)/8) do i=1 to hbound(tt)
BH ELOOPI
ZAP T,0(8,R5) t=tt(i)
CVD R4,DW store to packed decimal
UNPK PG(1),DW+7(1) unpack
OI PG,X'F0' zap sign
MVI PG+1,C' '
MVC PG+2(12),0(R6) ide(i)
XPRNT PG,14 output i
MVC PG(12),=C'Kelvin: '
MVC ZN,EDMASKN load mask
EDMK ZN,T+5 t (PL3)
BCTR R1,0 sign location
MVC 0(1,R1),ZN+L'ZN-1 put sign
MVC PG+12(L'ZN-1),ZN value
MVC PG+19(2),=C' K' unit
XPRNT PG,21 output Kelvin
MVC PG(12),=C'Celsius: '
ZAP DW,T t
SP DW,=P'273.15' t-273.15
MVC ZN,EDMASKN load mask
EDMK ZN,DW+5 (PL3)
BCTR R1,0 sign location
MVC 0(1,R1),ZN+L'ZN-1 put sign
MVC PG+12(L'ZN-1),ZN value
MVC PG+19(2),=C' C' unit
XPRNT PG,21 output Celsius
MVC PG(12),=C'Fahrenheit: '
ZAP DW,T t
MP DW,=P'18' *18
DP DW,=PL3'10' /10
ZAP DW,DW(5)
SP DW,=P'459.67' t*1.8-459.67
MVC ZN,EDMASKN load mask
EDMK ZN,DW+5 (PL3)
BCTR R1,0 sign location
MVC 0(1,R1),ZN+L'ZN-1 put sign
MVC PG+12(L'ZN-1),ZN value
MVC PG+19(2),=C' F' unit
XPRNT PG,21 output Fahrenheit
MVC PG(12),=C'Rankine: '
ZAP DW,T t
MP DW,=P'18' *18
DP DW,=PL3'10' /10
ZAP DW,DW(5) t*1.8
MVC ZN,EDMASKN load mask
EDMK ZN,DW+5 (PL3)
BCTR R1,0 sign location
MVC 0(1,R1),ZN+L'ZN-1 put sign
MVC PG+12(L'ZN-1),ZN value
MVC PG+19(2),=C' R' unit
XPRNT PG,21 output Rankine
LA R4,1(R4) i=i+1
LA R5,8(R5) @tt(i)
LA R6,12(R6) @ide(i)
B LOOPI
ELOOPI XR R15,R15
BR R14
IDE DC CL12'absolute',CL12'ice melts',CL12'water boils'
TT DC PL8'0.00',PL8'273.15',PL8'373.15'
T DS PL8
PG DS CL24
ZN DS ZL8 5num
DW DS D PL8 15num
EDMASKN DC X'402021204B202060' CL8 5num
YREGS
END TEMPERAT |
http://rosettacode.org/wiki/Tau_function | Tau function | Given a positive integer, count the number of its positive divisors.
Task
Show the result for the first 100 positive integers.
Related task
Tau number
| #AArch64_Assembly | AArch64 Assembly |
/* ARM assembly AARCH64 Raspberry PI 3B or android 64 bits */
/* program taufunction64.s */
/*******************************************/
/* Constantes file */
/*******************************************/
/* for this file see task include a file in language AArch64 assembly*/
.include "../includeConstantesARM64.inc"
.equ MAXI, 100
/*********************************/
/* Initialized data */
/*********************************/
.data
sMessResult: .asciz " @ "
szCarriageReturn: .asciz "\n"
/*********************************/
/* UnInitialized data */
/*********************************/
.bss
sZoneConv: .skip 24
/*********************************/
/* code section */
/*********************************/
.text
.global main
main: // entry of program
mov x0,#1 // factor number one
bl displayResult
mov x0,#2 // factor number two
bl displayResult
mov x2,#3 // begin number three
1: // begin loop
mov x5,#2 // divisor counter
mov x4,#2 // first divisor 1
2:
udiv x0,x2,x4 // compute divisor 2
msub x3,x0,x4,x2 // remainder
cmp x3,#0
bne 3f // remainder = 0 ?
cmp x0,x4 // same divisor ?
add x3,x5,1
add x6,x5,2
csel x5,x3,x6,eq
3:
add x4,x4,#1 // increment divisor
cmp x4,x0 // divisor 1 < divisor 2
blt 2b // yes -> loop
mov x0,x5 // equal -> display
bl displayResult
add x2,x2,1
cmp x2,MAXI // end ?
bls 1b // no -> loop
ldr x0,qAdrszCarriageReturn
bl affichageMess
100: // standard end of the program
mov x0, #0 // return code
mov x8, #EXIT // request to exit program
svc #0 // perform the system call
qAdrszCarriageReturn: .quad szCarriageReturn
/***************************************************/
/* display message number */
/***************************************************/
/* x0 contains the number */
displayResult:
stp x1,lr,[sp,-16]! // save registres
ldr x1,qAdrsZoneConv
bl conversion10 // call décimal conversion
strb wzr,[x1,x0]
ldr x0,qAdrsMessResult
ldr x1,qAdrsZoneConv // insert conversion in message
bl strInsertAtCharInc
bl affichageMess // display message
ldp x1,lr,[sp],16 // restaur des 2 registres
ret
qAdrsMessResult: .quad sMessResult
qAdrsZoneConv: .quad sZoneConv
/********************************************************/
/* File Include fonctions */
/********************************************************/
/* for this file see task include a file in language AArch64 assembly */
.include "../includeARM64.inc"
|
http://rosettacode.org/wiki/Tau_function | Tau function | Given a positive integer, count the number of its positive divisors.
Task
Show the result for the first 100 positive integers.
Related task
Tau number
| #Action.21 | Action! | CARD FUNC DivisorCount(CARD n)
CARD result,p,count
result=1
WHILE (n&1)=0
DO
result==+1
n=n RSH 1
OD
p=3
WHILE p*p<=n
DO
count=1
WHILE n MOD p=0
DO
count==+1
n==/p
OD
result==*count
p==+2
OD
IF n>1 THEN
result==*2
FI
RETURN (result)
PROC Main()
CARD max=[100],n,divCount
PrintF("Tau function for the first %U numbers%E",max)
FOR n=1 TO max
DO
divCount=DivisorCount(n)
PrintC(divCount) Put(32)
OD
RETURN |
http://rosettacode.org/wiki/Tau_function | Tau function | Given a positive integer, count the number of its positive divisors.
Task
Show the result for the first 100 positive integers.
Related task
Tau number
| #ALGOL_68 | ALGOL 68 | BEGIN # find the count of the divisors of the first 100 positive integers #
# calculates the number of divisors of v #
PROC divisor count = ( INT v )INT:
BEGIN
INT total := 1, n := v;
# Deal with powers of 2 first #
WHILE NOT ODD n DO
total +:= 1;
n OVERAB 2
OD;
# Odd prime factors up to the square root #
FOR p FROM 3 BY 2 WHILE ( p * p ) <= n DO
INT count := 1;
WHILE n MOD p = 0 DO
count +:= 1;
n OVERAB p
OD;
total *:= count
OD;
# If n > 1 then it's prime #
IF n > 1 THEN total *:= 2 FI;
total
END # divisor_count # ;
BEGIN
INT limit = 100;
print( ( "Count of divisors for the first ", whole( limit, 0 ), " positive integers:" ) );
FOR n TO limit DO
IF n MOD 20 = 1 THEN print( ( newline ) ) FI;
print( ( whole( divisor count( n ), -4 ) ) )
OD
END
END |
http://rosettacode.org/wiki/Terminal_control/Clear_the_screen | Terminal control/Clear the screen | Task
Clear the terminal window.
| #Arturo | Arturo | clear |
http://rosettacode.org/wiki/Terminal_control/Clear_the_screen | Terminal control/Clear the screen | Task
Clear the terminal window.
| #AutoHotkey | AutoHotkey | RunWait %comspec% /c cls |
http://rosettacode.org/wiki/Terminal_control/Clear_the_screen | Terminal control/Clear the screen | Task
Clear the terminal window.
| #AWK | AWK | system("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
| #Factor | Factor | ! rosettacode/ternary/ternary.factor
! http://rosettacode.org/wiki/Ternary_logic
USING: combinators kernel ;
IN: rosettacode.ternary
SINGLETON: m
UNION: trit t m POSTPONE: f ;
GENERIC: >trit ( object -- trit )
M: trit >trit ;
: tnot ( trit1 -- trit )
>trit { { t [ f ] } { m [ m ] } { f [ t ] } } case ;
: tand ( trit1 trit2 -- trit )
>trit {
{ t [ >trit ] }
{ m [ >trit { { t [ m ] } { m [ m ] } { f [ f ] } } case ] }
{ f [ >trit drop f ] }
} case ;
: tor ( trit1 trit2 -- trit )
>trit {
{ t [ >trit drop t ] }
{ m [ >trit { { t [ t ] } { m [ m ] } { f [ m ] } } case ] }
{ f [ >trit ] }
} case ;
: txor ( trit1 trit2 -- trit )
>trit {
{ t [ tnot ] }
{ m [ >trit drop m ] }
{ f [ >trit ] }
} case ;
: t= ( trit1 trit2 -- trit )
{
{ t [ >trit ] }
{ m [ >trit drop m ] }
{ f [ tnot ] }
} case ; |
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.
| #Go | Go | package main
import (
"bufio"
"fmt"
"log"
"os"
"strconv"
"strings"
)
const (
filename = "readings.txt"
readings = 24 // per line
fields = readings*2 + 1 // per line
)
func main() {
file, err := os.Open(filename)
if err != nil {
log.Fatal(err)
}
defer file.Close()
var (
badRun, maxRun int
badDate, maxDate string
fileSum float64
fileAccept int
)
endBadRun := func() {
if badRun > maxRun {
maxRun = badRun
maxDate = badDate
}
badRun = 0
}
s := bufio.NewScanner(file)
for s.Scan() {
f := strings.Fields(s.Text())
if len(f) != fields {
log.Fatal("unexpected format,", len(f), "fields.")
}
var accept int
var sum float64
for i := 1; i < fields; i += 2 {
flag, err := strconv.Atoi(f[i+1])
if err != nil {
log.Fatal(err)
}
if flag <= 0 { // value is bad
if badRun++; badRun == 1 {
badDate = f[0]
}
} else { // value is good
endBadRun()
value, err := strconv.ParseFloat(f[i], 64)
if err != nil {
log.Fatal(err)
}
sum += value
accept++
}
}
fmt.Printf("Line: %s Reject %2d Accept: %2d Line_tot:%9.3f",
f[0], readings-accept, accept, sum)
if accept > 0 {
fmt.Printf(" Line_avg:%8.3f\n", sum/float64(accept))
} else {
fmt.Println()
}
fileSum += sum
fileAccept += accept
}
if err := s.Err(); err != nil {
log.Fatal(err)
}
endBadRun()
fmt.Println("\nFile =", filename)
fmt.Printf("Total = %.3f\n", fileSum)
fmt.Println("Readings = ", fileAccept)
if fileAccept > 0 {
fmt.Printf("Average = %.3f\n", fileSum/float64(fileAccept))
}
if maxRun == 0 {
fmt.Println("\nAll data valid.")
} else {
fmt.Printf("\nMax data gap = %d, beginning on line %s.\n",
maxRun, maxDate)
}
} |
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.
| #Raku | Raku | my uint32 (@mm, @randrsl, $randcnt, $aa, $bb, $cc);
my \ϕ := 2654435769; constant MOD = 95; constant START = 32;
constant MAXINT = uint.Range.max;
enum CipherMode < ENCIPHER DECIPHER NONE >;
sub mix (\n) {
sub mix1 (\i, \v) {
n[i] +^= v;
n[(i+3)%8] += n[i];
n[(i+1)%8] += n[(i+2)%8];
}
mix1 0, n[1]+<11; mix1 1, n[2]+>2; mix1 2, n[3]+<8; mix1 3, n[4]+>16;
mix1 4, n[5]+<10; mix1 5, n[6]+>4; mix1 6, n[7]+<8; mix1 7, n[0]+>9 ;
}
sub randinit(\flag) {
$aa = $bb = $cc = 0;
my uint32 @n = [^8].map({ ϕ });
for ^4 { mix @n };
for 0,8 … 255 -> $i {
{ for (0..7) { @n[$^j] += @randrsl[$i + $^j] } } if flag;
mix @n;
for (0..7) { @mm[$i + $^j] = @n[$^j] }
}
if flag {
for 0,8 … 255 -> $i {
for ^8 { @n[$^j] += @mm[$i + $^j] };
mix @n;
for ^8 { @mm[$i + $^j] = @n[$^j] };
}
}
isaac;
$randcnt = 0;
}
sub isaac() {
$cc++;
$bb += $cc;
for ^256 -> $i {
my $x = @mm[$i];
given ($i % 4) {
when 0 { $aa +^= ($aa +< 13) }
when 1 { $aa +^= (($aa +& MAXINT) +> 6) }
when 2 { $aa +^= ($aa +< 2) }
when 3 { $aa +^= (($aa +& MAXINT) +> 16) }
}
$aa += @mm[($i + 128) % 256];
my $y = @mm[(($x +& MAXINT) +> 2) % 256] + $aa + $bb;
@mm[$i] = $y;
$bb = @mm[(($y +& MAXINT) +> 10) % 256] + $x;
@randrsl[$i] = $bb;
}
$randcnt = 0;
}
sub iRandom {
my $result = @randrsl[$randcnt++];
if ($randcnt > 255) {
isaac;
$randcnt = 0;
}
return $result;
}
sub iSeed(\seed, \flag) {
@mm = [^256].race.map({0});
my \m = seed.chars;
@randrsl = [^256].hyper.map({ $^i ≥ m ?? 0 !! seed.substr($^i,1).ord });
randinit(flag);
}
sub iRandA { return iRandom() % MOD + START };
sub vernam(\M) { ( map { (iRandA() +^ .ord ).chr }, M.comb ).join };
sub caesar(CipherMode \m, \ch, $shift is copy, \Modulo, \Start) {
$shift = -$shift if m == DECIPHER;
my $n = (ch.ord - Start) + $shift;
$n %= Modulo;
$n += Modulo if $n < 0;
return (Start + $n).chr;
}
sub caesarStr(CipherMode \m, \msg, \Modulo, \Start) {
my $sb = '';
for msg.comb {
$sb ~= caesar m, $^c, iRandA(), Modulo, Start;
}
return $sb;
}
multi MAIN () {
my \msg = "a Top Secret secret";
my \key = "this is my secret key";
iSeed key, True ;
my $vctx = vernam msg;
my $cctx = caesarStr ENCIPHER, msg, MOD, START;
iSeed key, True ;
my $vptx = vernam $vctx;
my $cptx = caesarStr DECIPHER, $cctx, MOD, START;
my $vctx2hex = ( map { .ord.fmt('%02X') }, $vctx.comb ).join('');
my $cctx2hex = ( map { .ord.fmt('%02X') }, $cctx.comb ).join('');
say "Message : ", msg;
say "Key : ", key;
say "XOR : ", $vctx2hex;
say "XOR dcr : ", $vptx;
say "MOD : ", $cctx2hex;
say "MOD dcr : ", $cptx;
} |
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.)
| #Wren | Wren | import "/big" for BigRat
import "/complex" for Complex
import "/rat" for Rat
import "/fmt" for Fmt
var tests1 = [25.000000, 24.999999, 25.000100]
var tests2 = ["-2.1e120"]
var tests3 = [-5e-2, 0/0, 1/0]
var tests4 = [Complex.fromString("5.0+0.0i"), Complex.fromString("5-5i")]
var tests5 = [Rat.new(24, 8), Rat.new(-5, 1), Rat.new(17, 2)]
var tests6 = tests1 + [-5e-2]
System.print("Using exact arithmetic:\n")
for (t in tests1) {
Fmt.print(" $-9.6f is integer? $s", t, t.isInteger)
}
System.print()
for (t in tests2) {
Fmt.print(" $-9s is integer? $s", t, BigRat.new(t, 1).isInteger)
}
for (t in tests3) {
Fmt.print(" $-9.6f is integer? $s", t, t.isInteger)
}
System.print()
for (t in tests4) {
Fmt.print(" $-9s is integer? $s", t, t.isRealInteger)
}
System.print()
for (t in tests5) {
Fmt.print(" $-9s is integer? $s", t, t.isInteger)
}
System.print("\nWithin a tolerance of 0.00001:\n")
var tol = 0.00001
for (t in tests6) {
var d = (t - t.round).abs
Fmt.print(" $9.6f is integer? $s", t, d <= tol)
} |
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).
| #Ruby | Ruby | out = 0
max_out = -1
max_times = []
File.foreach('mlijobs.txt') do |line|
out += line.include?("OUT") ? 1 : -1
if out > max_out
max_out = out
max_times = []
end
max_times << line.split[3] if out == max_out
end
puts "Maximum simultaneous license use is #{max_out} at the following times:"
max_times.each {|time| puts " #{time}"} |
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).
| #Run_BASIC | Run BASIC | open "c:\data\temp\logFile.txt" for input as #f
while not(eof(#f))
line input #f, a$
if word$(a$,2," ") = "IN" then count = count - 1 else count = count + 1
maxCount = max(maxCount,count)
wend
open "c:\data\temp\logFile.txt" for input as #f
while not(eof(#f))
line input #f, a$
if word$(a$,2," ") = "IN" then count = count - 1 else count = count + 1
if count = maxCount then theDate$ = theDate$ + " | " + word$(a$,4," ") + " Job:";word$(a$,7," ")
wend
print maxCount;" ";theDate$ |
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.
| #Prolog | Prolog | palindrome(Word) :- name(Word,List), reverse(List,List).
:- begin_tests(palindrome).
test(valid_palindrome) :- palindrome('ingirumimusnocteetconsumimurigni').
test(invalid_palindrome, [fail]) :- palindrome('this is not a palindrome').
:- end_tests(palindrome). |
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.
| #PureBasic | PureBasic | Macro DoubleQuote
; Needed for the Assert-Macro below
" ; " second dlbquote to prevent Rosettas misshighlighting of following code. Remove comment before execution!
EndMacro
Macro Assert(TEST,MSG="")
CompilerIf #PB_Compiler_Debugger
If Not (TEST)
If MSG<>"": Debug MSG: EndIf
Temp$="Fail: "+DoubleQuote#TEST#DoubleQuote
Debug Temp$+", Line="+Str(#PB_Compiler_Line)+" in "+#PB_Compiler_File
CallDebugger
EndIf
CompilerEndIf
EndMacro
Procedure IsPalindrome(StringToTest.s)
If StringToTest=ReverseString(StringToTest)
ProcedureReturn 1
Else
ProcedureReturn 0
EndIf
EndProcedure
text1$="racecar"
text2$="wisconsin"
Assert(IsPalindrome(text1$), "Catching this would be a fail")
Assert(IsPalindrome(text2$), "Catching this is correct") |
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
| #dc | dc | 0
d [first] r :n
d [A partridge in a pear tree.] r :g 1 +
d [second] r :n
d [Two turtle doves and] r :g 1 +
d [third] r :n
d [Three French hens,] r :g 1 +
d [fourth] r :n
d [Four calling birds,] r :g 1 +
d [fifth] r :n
d [Five gold rings,] r :g 1 +
d [sixth] r :n
d [Six geese a-laying,] r :g 1 +
d [seventh] r :n
d [Seven swans a-swimming,] r :g 1 +
d [eighth] r :n
d [Eight maids a-milking,] r :g 1 +
d [ninth] r :n
d [Nine ladies dancing,] r :g 1 +
d [tenth] r :n
d [Ten lords a-leaping,] r :g 1 +
d [eleventh] r :n
d [Eleven pipers piping,] r :g 1 +
d [twelfth] r :n
[Twelve drummers drumming,] r :g
[
d
;g n
10 P
] sp
[
d
0 r !<p
1 -
d
0 r !<r
] sr
[
[On the ] n
d ;n n
[ day of Christmas, my true love sent to me:] n
10 P
d
lr x s_
10 P
1 +
d
12 r <l
] sl
0 ll x
|
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
| #Dyalect | Dyalect | let days = [
"first", "second", "third", "fourth", "fifth", "sixth", "seventh", "eighth", "ninth",
"tenth", "eleventh", "twelfth"
]
let gifts = [
"A partridge in a pear tree",
"Two turtle doves",
"Three french hens",
"Four calling birds",
"Five golden rings",
"Six geese a-laying",
"Seven swans a-swimming",
"Eight maids a-milking",
"Nine ladies dancing",
"Ten lords a-leaping",
"Eleven pipers piping",
"Twelve drummers drumming"
]
for i in 0..11 {
print("On the \(days[i]) day of Christmas, my true love gave to me.")
for j in i^-1..0 {
print(gifts[j])
}
print()
} |
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.
| #UNIX_Shell | UNIX Shell | #!/bin/sh
WIDTH=`tput cols`
HEIGHT=`tput lines`
echo "The terminal is $WIDTH characters wide and has $HEIGHT 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.
| #Visual_Basic | Visual Basic | Module Module1
Sub Main()
Dim bufferHeight = Console.BufferHeight
Dim bufferWidth = Console.BufferWidth
Dim windowHeight = Console.WindowHeight
Dim windowWidth = Console.WindowWidth
Console.Write("Buffer Height: ")
Console.WriteLine(bufferHeight)
Console.Write("Buffer Width: ")
Console.WriteLine(bufferWidth)
Console.Write("Window Height: ")
Console.WriteLine(windowHeight)
Console.Write("Window Width: ")
Console.WriteLine(windowWidth)
End Sub
End Module |
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.
| #Wren | Wren | /* terminal_control_dimensions.wren */
class C {
foreign static terminalWidth
foreign static terminalHeight
}
var w = C.terminalWidth
var h = C.terminalHeight
System.print("The dimensions of the terminal are:")
System.print(" Width = %(w)")
System.print(" Height = %(h)") |
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.
| #XPL0 | XPL0 | include c:\cxpl\codes;
int W, H;
[W:= Peek($40, $4A); \IBM-PC BIOS data
H:= Peek($40, $84) + 1;
Text(0, "Terminal width and height = ");
IntOut(0, W); ChOut(0, ^x); IntOut(0, H);
] |
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.
| #Yabasic | Yabasic | clear screen
w = peek("screenwidth")
h = peek("screenheight")
print "Informaci¢n sobre el escritorio (terminal):"
print " Ancho de la terminal: ", w, " (pixel)"
print "Altura de la terminal: ", h, " (pixel)"
open window 640,480
w = peek("winheight")
h = peek("winwidth")
print "\n\nInformaci¢n sobre el modo gr fico:"
print " Ancho de la pantalla: ", w, " (pixel)"
print "Altura de la pantalla: ", h, " (pixel)\n"
close window |
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)
| #Dc | Dc | ## after PARI/GP
# C: for( initcode ; condcode ; incrcode ) {body}
# .[q] [1] [2] [3] [4]
# # [initcode] [condcode] [incrcode] [body] (for)
[ [q]S. 4:.3:.2:.x [2;.x 0=. 4;.x 3;.x 0;.x]d0:.x
Os.L.o
]sF # F = for
[
27P ## ESC
91P ## Bra ... together: CSI
n ## colour 1 (fg)
[;]P ## ";"
n ## colour 2 (bg)
[;1m]P ## ";1m"
]sS
[
27P ## ESC
91P ## Bra ... together: CSI
[0m]P ## "0m"
]sR
[0q]s0 [<0 1]sL ## L: isle
## for b=40 b<=47 ++b
## for f=30 f<=37 ++f
[40sb] [lb 47 lLx] [lb 1+ sb] [
[30sf] [lf 37 lLx] [lf 1+ sf] [
lb lf lSx [colour-blind]P lRx [ ]P
] lFx ## for b
AP
] lFx ## for f |
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)
| #F.23 | F# | open System
Console.ForegroundColor <- ConsoleColor.Red
Console.BackgroundColor <- ConsoleColor.Yellow
Console.WriteLine("Red on Yellow")
Console.ForegroundColor <- ConsoleColor.White
Console.BackgroundColor <- ConsoleColor.Black
Console.WriteLine("White on Black")
Console.ForegroundColor <- ConsoleColor.Green
Console.BackgroundColor <- ConsoleColor.Blue
Console.WriteLine("Green on Blue")
Console.ResetColor()
Console.WriteLine("Back to normal")
Console.ReadKey() |
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)
| #Forth | Forth | ( ANSI terminal control lexicon Colored Text)
DECIMAL
( support routines)
27 CONSTANT ESC
: <##> ( n -- ) ( sends n, radix 10, no spaces)
BASE @ >R 0 <# #S #> TYPE R> BASE ! ;
: ESC[ ( -- ) ESC EMIT ." [" ;
( Attributes )
1 CONSTANT BOLD 2 CONSTANT DIM 3 CONSTANT ITALIC
5 CONSTANT BLINK 7 CONSTANT REV 8 CONSTANT BLANK
( Colors )
0 CONSTANT BLACK 1 CONSTANT RED 2 CONSTANT GREEN
3 CONSTANT YELLOW 4 CONSTANT BLUE 5 CONSTANT MAGENTA
6 CONSTANT CYAN 7 CONSTANT WHITE
: ATTR ( attribute ) ESC[ <##> ." m" ; ( use: BOLD ATTR )
: TEXT ( color ) 30 + ATTR ; ( use: YELLOW TEXT )
: BACKGROUND ( color ) 40 + ATTR ; ( use: BLUE BACKGROUND )
|
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.
| #Mathematica.2FWolfram_Language | Mathematica/Wolfram Language | Run["tput cub1"] (* one position to the left *)
Run["tput cuf1" ] (* one position to the right *)
Run["tput cuu1" ] (* up one line *)
Run["tput cud1"] (* down one line *)
Run["tput cr"] (* beginning of line *)
Run["tput home"] (* top left corner *)
WIDTH=RunThrough["tput cols", ""];
HEIGHT=RunThrough["tput lines", ""];
Run["tput hpa "<>WIDTH] (* end of line *)
Run["tput cup "<>HEIGHT<>" "<> WIDTH] (* bottom right corner *) |
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.
| #Nim | Nim | import terminal
echo "Press the return key to go to next step."
echo "Starting in the middle of last line."
template waitUser() =
while getch() != '\r': discard
let (width, height) = terminalSize()
# Start by positionning the cursor in the middle of the line.
setCursorXPos(width div 2)
waitUser()
# Move one character backward.
cursorBackward(1)
waitUser()
# Move one character forward.
cursorForward(1)
waitUser()
# Move one character up.
cursorUp(1)
waitUser()
# Move one character down.
cursorDown(1)
waitUser()
# Move at beginning of line.
setCursorXPos(0)
waitUser()
# Move at end of line.
setCursorXPos(width - 1)
waitUser()
# Move cursor to the top left corner.
setCursorPos(0, 0)
waitUser()
# Move cursor to the bottom right corner.
setCursorPos(width - 1, height - 1)
waitUser() |
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.
| #Perl | Perl | system "tput cub1"; sleep 1; # one position to the left
system "tput cuf1"; sleep 1; # one position to the right
system "tput cuu1"; sleep 1; # up one line
system "tput cud1"; sleep 1; # down one line
system "tput cr"; sleep 1; # beginning of line
system "tput home"; sleep 1; # top left corner
$_ = qx[stty -a </dev/tty 2>&1];
my($rows,$cols) = /(\d+) rows; (\d+) col/;
$rows--; $cols--;
system "tput cup $rows $cols"; # bottom right corner
sleep 1; |
http://rosettacode.org/wiki/Terminal_control/Cursor_positioning | Terminal control/Cursor positioning |
Task
Move the cursor to column 3, row 6, and display the word "Hello" (without the quotes), so that the letter H is in column 3 on row 6.
| #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);
setPos(console, 6, 3);
write(console, "Hello");
# 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/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.
| #Tcl | Tcl | exec tput cup 5 2 >/dev/tty
puts "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.
| #UNIX_Shell | UNIX Shell | # The tput utility numbers from zero, so we have subtracted 1 from row and column
# number to obtain correct positioning.
tput cup 5 2 |
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.
| #Whitespace | Whitespace |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.