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/Dimensions | Terminal control/Dimensions | Determine the height and width of the terminal, and store this information into variables for subsequent use.
| #Applesoft_BASIC | Applesoft BASIC | WIDTH = PEEK(33)
HEIGHT = PEEK(35) - PEEK(34) |
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.
| #Arturo | Arturo | print ["Terminal width:" terminal\width]
print ["Terminal height:" terminal\height] |
http://rosettacode.org/wiki/Terminal_control/Dimensions | Terminal control/Dimensions | Determine the height and width of the terminal, and store this information into variables for subsequent use.
| #AutoHotkey | AutoHotkey | DllCall( "AllocConsole" ) ; create a console if not launched from one
hConsole := DllCall( "GetStdHandle", int, STDOUT := -11 )
MsgBox Resize the console...
VarSetCapacity(csbi, 22) ; CONSOLE_SCREEN_BUFFER_INFO structure
DllCall("GetConsoleScreenBufferInfo", UPtr, hConsole, UPtr, &csbi)
Left := NumGet(csbi, 10, "short")
Top := NumGet(csbi, 12, "short")
Right := NumGet(csbi, 14, "short")
Bottom := NumGet(csbi, 16, "short")
columns := right - left + 1
rows := bottom - top + 1
MsgBox %columns% columns and %rows% rows |
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.
| #Action.21 | Action! | PROC Main()
Position(3,6)
Print("Hello")
RETURN |
http://rosettacode.org/wiki/Terminal_control/Cursor_positioning | Terminal control/Cursor positioning |
Task
Move the cursor to column 3, row 6, and display the word "Hello" (without the quotes), so that the letter H is in column 3 on row 6.
| #Ada | Ada | with Ada.Text_IO;
procedure Cursor_Pos is
begin
Ada.Text_IO.Set_Line(6);
Ada.Text_IO.Set_Col(3);
Ada.Text_IO.Put("Hello");
end Cursor_Pos; |
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.
| #ARM_Assembly | ARM Assembly |
/* ARM assembly Raspberry PI */
/* program cursorPos.s */
/* Constantes */
.equ STDOUT, 1 @ Linux output console
.equ EXIT, 1 @ Linux syscall
.equ WRITE, 4 @ Linux syscall
/* Initialized data */
.data
szMessStartPgm: .asciz "Program start \n"
szMessEndPgm: .asciz "Program normal end.\n"
szMessMovePos: .asciz "\033[6;3HHello\n"
szCarriageReturn: .asciz "\n"
szClear1: .byte 0x1B
.byte 'c' @ other console clear
.byte 0
/* UnInitialized data */
.bss
/* code section */
.text
.global main
main:
ldr r0,iAdrszMessStartPgm @ display start message
bl affichageMess
ldr r0,iAdrszClear1
bl affichageMess
ldr r0,iAdrszMessMovePos
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
iAdrszCarriageReturn: .int szCarriageReturn
iAdrszClear1: .int szClear1
iAdrszMessMovePos: .int szMessMovePos
/******************************************************************/
/* 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
| #AutoHotkey | AutoHotkey | Ternary_Not(a){
SetFormat, Float, 2.1
return Abs(a-1)
}
Ternary_And(a,b){
return a<b?a:b
}
Ternary_Or(a,b){
return a>b?a:b
}
Ternary_IfThen(a,b){
return a=1?b:a=0?1:a+b>1?1:0.5
}
Ternary_Equiv(a,b){
return a=b?1:a=1?b:b=1?a:0.5
} |
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).
| #C.23 | C# | class Program
{
static void Main()
{
System.Console.WriteLine("£");
}
} |
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).
| #C.2B.2B | C++ | #include <iostream>
int main()
{
std::cout << static_cast<char>(163); // pound sign
return 0;
} |
http://rosettacode.org/wiki/Terminal_control/Display_an_extended_character | Terminal control/Display an extended character | Task
Display an extended (non ASCII) character onto the terminal.
Specifically, display a £ (GBP currency sign).
| #Clojure | Clojure | (println "£") |
http://rosettacode.org/wiki/Terminal_control/Display_an_extended_character | Terminal control/Display an extended character | Task
Display an extended (non ASCII) character onto the terminal.
Specifically, display a £ (GBP currency sign).
| #COBOL | COBOL | IDENTIFICATION DIVISION.
PROGRAM-ID. Display-Pound.
PROCEDURE DIVISION.
DISPLAY "£"
GOBACK
. |
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.
| #BBC_BASIC | BBC BASIC | file% = OPENIN("readings.txt")
IF file% = 0 THEN PRINT "Could not open test data file" : END
Total = 0
Count% = 0
BadMax% = 0
bad% = 0
WHILE NOT EOF#file%
text$ = GET$#file%
IF text$<>"" THEN
tab% = INSTR(text$, CHR$(9))
date$ = LEFT$(text$, tab% - 1)
acc = 0
cnt% = 0
FOR field% = 1 TO 24
dval = VALMID$(text$, tab%+1)
tab% = INSTR(text$, CHR$(9), tab%+1)
flag% = VALMID$(text$, tab%+1)
tab% = INSTR(text$, CHR$(9), tab%+1)
IF flag% > 0 THEN
acc += dval
cnt% += 1
bad% = 0
ELSE
bad% += 1
IF bad% > BadMax% BadMax% = bad% : BadDate$ = date$
ENDIF
NEXT field%
@% = &90A
PRINT "Date: " date$ " Good = "; cnt%, " Bad = "; 24-cnt%, ;
@% = &20308
IF cnt% THEN PRINT " Total = " acc " Mean = " acc / cnt% ;
PRINT
Total += acc
Count% += cnt%
ENDIF
ENDWHILE
CLOSE #file%
PRINT ' "Grand total = " ; Total
PRINT "Number of valid readings = " ; STR$(Count%)
PRINT "Overall mean = " ; Total / Count%
@% = &90A
PRINT '"Longest run of bad readings = " ; BadMax% " ending " BadDate$ |
http://rosettacode.org/wiki/Terminal_control/Positional_read | Terminal control/Positional read | Determine the character displayed on the screen at column 3, row 6 and store that character in a variable. Note that it is permissible to utilize system or language provided methods or system provided facilities, system maintained records or available buffers or system maintained display records to achieve this task, rather than query the terminal directly, if those methods are more usual for the system type or language.
| #REXX | REXX | /*REXX program demonstrates reading a character from (at) at specific screen location. */
row = 6 /*point to a particular row on screen*/
col = 3 /* " " " " column " " */
howMany = 1 /*read this many characters from screen*/
stuff = scrRead(row, col, howMany) /*this'll do it. */
other = scrRead(40, 3, 1) /*same thing, but for row forty. */
/*stick a fork in it, we're all done. */ |
http://rosettacode.org/wiki/Terminal_control/Positional_read | Terminal control/Positional read | Determine the character displayed on the screen at column 3, row 6 and store that character in a variable. Note that it is permissible to utilize system or language provided methods or system provided facilities, system maintained records or available buffers or system maintained display records to achieve this task, rather than query the terminal directly, if those methods are more usual for the system type or language.
| #TXR | TXR | ;;; Type definitions and constants
(typedef BOOL (enum BOOL FALSE TRUE))
(typedef HANDLE cptr)
(typedef WCHAR wchar)
(typedef DWORD uint32)
(typedef WORD uint16)
(typedef SHORT short)
(typedef COORD
(struct COORD
(X SHORT)
(Y SHORT)))
(typedef SMALL_RECT
(struct SMALL_RECT
(Left SHORT)
(Top SHORT)
(Right SHORT)
(Bottom SHORT)))
(typedef CONSOLE_SCREEN_BUFFER_INFO
(struct CONSOLE_SCREEN_BUFFER_INFO
(dwSize COORD)
(dwCursorPosition COORD)
(wAttributes WORD)
(srWindow SMALL_RECT)
(dwMaximumWindowSize COORD)))
;;; Various constants
(defvarl STD_INPUT_HANDLE (- #x100000000 10))
(defvarl STD_OUTPUT_HANDLE (- #x100000000 11))
(defvarl STD_ERROR_HANDLE (- #x100000000 12))
(defvarl NULL cptr-null)
(defvarl INVALID_HANDLE_VALUE (cptr-int -1))
;;; Foreign Function Bindings
(with-dyn-lib "kernel32.dll"
(deffi GetStdHandle "GetStdHandle" HANDLE (DWORD))
(deffi GetConsoleScreenBufferInfo "GetConsoleScreenBufferInfo"
BOOL (HANDLE (ptr-out CONSOLE_SCREEN_BUFFER_INFO)))
(deffi ReadConsoleOutputCharacter "ReadConsoleOutputCharacterW"
BOOL (HANDLE (ptr-out (array 1 WCHAR))
DWORD COORD (ptr-out (array 1 DWORD)))))
;;; Now the character at <2, 5> -- column 3, row 6.
(let ((console-handle (GetStdHandle STD_OUTPUT_HANDLE)))
(when (equal console-handle INVALID_HANDLE_VALUE)
(error "couldn't get console handle"))
(let* ((cinfo (new CONSOLE_SCREEN_BUFFER_INFO))
(getinfo-ok (GetConsoleScreenBufferInfo console-handle cinfo))
(coord (if getinfo-ok
^#S(COORD X ,(+ 2 cinfo.srWindow.Left)
Y ,(+ 5 cinfo.srWindow.Top))
#S(COORD X 0 Y 0)))
(chars (vector 1))
(nread (vector 1))
(read-ok (ReadConsoleOutputCharacter console-handle chars
1 coord nread)))
(when (eq getinfo-ok 'FALSE)
(error "GetConsoleScreenBufferInfo failed"))
(prinl cinfo)
(when (eq read-ok 'FALSE)
(error "ReadConsoleOutputCharacter failed"))
(unless (plusp [nread 0])
(error "ReadConsoleOutputCharacter read zero characters"))
(format t "character is ~s\n" [chars 0]))) |
http://rosettacode.org/wiki/Terminal_control/Positional_read | Terminal control/Positional read | Determine the character displayed on the screen at column 3, row 6 and store that character in a variable. Note that it is permissible to utilize system or language provided methods or system provided facilities, system maintained records or available buffers or system maintained display records to achieve this task, rather than query the terminal directly, if those methods are more usual for the system type or language.
| #Wren | Wren | /* terminal_control_positional_read.wren */
import "random" for Random
foreign class Window {
construct initscr() {}
foreign addstr(str)
foreign inch(y, x)
foreign move(y, x)
foreign refresh()
foreign getch()
foreign delwin()
}
class Ncurses {
foreign static endwin()
}
// initialize curses window
var win = Window.initscr()
if (win == 0) {
System.print("Failed to initialize ncurses.")
return
}
// print random text in a 10x10 grid
var rand = Random.new()
for (row in 0..9) {
var line = (0..9).map{ |d| String.fromByte(rand.int(41, 91)) }.join()
win.addstr(line + "\n")
}
// read
var col = 3 - 1
var row = 6 - 1
var ch = win.inch(row, col)
// show result
win.move(row, col + 10)
win.addstr("Character at column 3, row 6 = %(ch)")
win.move(11, 0)
win.addstr("Press any key to exit...")
// refresh
win.refresh()
// wait for a keypress
win.getch()
// clean-up
win.delwin()
Ncurses.endwin() |
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.
| #Julia | Julia |
"""
Julia translation of code from the following:
------------------------------------------------------------------------------
readable.c: My random number generator, ISAAC.
(c) Bob Jenkins, March 1996, Public Domain
You may use this code in any way you wish, and it is free. No warrantee.
------------------------------------------------------------------------------
"""
# maximum length of message here is set to 4096
const MAXMSG = 4096
# cipher modes for encryption versus decryption modes
@enum CipherMode mEncipher mDecipher mNone
# external results
mutable struct IState
randrsl::Array{UInt32, 1}
randcnt::UInt32
mm::Array{UInt32, 1}
aa::UInt32
bb::UInt32
cc::UInt32
function IState()
this = new()
this.randrsl = zeros(UInt32, 256)
this.randcnt = UInt32(0)
this.mm = zeros(UInt32, 256)
this.aa = this.bb = this.cc = UInt32(0)
this
end
end
"""
isaac
Randomize the pool
"""
function isaac(istate)
istate.cc += 1 # cc gets incremented once per 256 results
istate.bb += istate.cc # then combined with bb
for (j, c) in enumerate(istate.mm) # Julia NB: indexing ahead so use i for c indexing
i = j - 1
xmod4 = i % 4
if(xmod4 == 0)
istate.aa ⊻= istate.aa << 13
elseif(xmod4 == 1)
istate.aa ⊻= istate.aa >> 6
elseif(xmod4 == 2)
istate.aa ⊻= istate.aa << 2
else
istate.aa ⊻= istate.aa >> 16
end
istate.aa += istate.mm[(i + 128) % 256 + 1]
y = istate.mm[(c >> 2) % 256 + 1] + istate.aa + istate.bb
istate.mm[j] = y
istate.bb = istate.mm[(y >> 10) % 256 + 1] + c
istate.randrsl[j] = istate.bb
end
# not in original readable.c
istate.randcnt = 0
end
"""
mix
Mix the bytes in a reversible way.
"""
function mix(arr) # Julia NB: use E for e in c code here
(a,b,c,d,E,f,g,h) = arr
a⊻=b<<11; d+=a; b+=c;
b⊻=c>>2; E+=b; c+=d;
c⊻=d<<8; f+=c; d+=E;
d⊻=E>>16; g+=d; E+=f;
E⊻=f<<10; h+=E; f+=g;
f⊻=g>>4; a+=f; g+=h;
g⊻=h<<8; b+=g; h+=a;
h⊻=a>>9; c+=h; a+=b;
(a,b,c,d,E,f,g,h)
end
"""
randinit
Make a random UInt32 array.
If flag is true, use the contents of randrsl[] to initialize mm[].
"""
function randinit(istate, flag::Bool)
istate.aa = istate.bb = istate.cc = 0
mixer = Array{UInt32,1}(8)
fill!(mixer, 0x9e3779b9) # the golden ratio
for i in 1:4 # scramble it
mixer = mix(mixer)
end
for i in 0:8:255 # fill in mm[] with messy stuff
if(flag) # use all the information in the seed
mixer = [mixer[j] + istate.randrsl[i+j] for j in 1:8]
end
mixer = mix(mixer)
istate.mm[i+1:i+8] .= mixer
end
if(flag) # do a second pass to seed all of mm
for i in 0:8:255
mixer = [mixer[j] + istate.mm[i+j] for j in 1:8]
mixer = mix(mixer)
istate.mm[i+1:i+8] .= mixer
end
end
isaac(istate) # fill in the first set of results
istate.randcnt = 0
end
"""
Get a random 32-bit value 0..MAXINT
"""
function irandom(istate)
retval::UInt32 = istate.randrsl[istate.randcnt+1]
istate.randcnt += 1
if(istate.randcnt > 255)
isaac(istate)
istate.randcnt = 0
end
retval
end
"""
Get a random character in printable ASCII range
"""
iranda(istate) = UInt8(irandom(istate) % 95 + 32)
"""
Do XOR cipher on random stream.
Output: UInt8 array
"""
vernam(istate, msg) = [UInt8(iranda(istate) ⊻ c) for c in msg]
"""
Seed ISAAC with a string
"""
function iseed(istate, seed, flag)
fill!(istate.mm, 0)
fill!(istate.randrsl, 0)
len = min(length(seed), length(istate.randrsl))
istate.randrsl[1:len] .= seed[1:len]
randinit(istate, flag) # initialize ISAAC with seed
end
tohexstring(arr::Array{UInt8,1}) = join([hex(i, 2) for i in arr])
function test(istate, msg, key)
# Vernam ciphertext & plaintext
vctx = zeros(UInt8, MAXMSG)
vptx = zeros(UInt8, MAXMSG)
# Encrypt: Vernam XOR
iseed(istate, Vector{UInt8}(key), true)
vctx = vernam(istate, Vector{UInt8}(msg))
# Decrypt: Vernam XOR
iseed(istate, Vector{UInt8}(key), true)
vptx = vernam(istate, vctx)
# Program output
println("Message: $msg")
println("Key : $key")
println("XOR : $(tohexstring(vctx))")
# Output Vernam decrypted plaintext
println("XOR dcr: $(join(map(c -> Char(c), vptx)))")
0
end
"""
Test the above.
"""
const msg = "a Top Secret secret"
const key = "this is my secret key"
test(IState(), msg, key)
|
http://rosettacode.org/wiki/Test_integerness | Test integerness | Mathematically,
the integers Z are included in the rational numbers Q,
which are included in the real numbers R,
which can be generalized to the complex numbers C.
This means that each of those larger sets, and the data types used to represent them, include some integers.
Task[edit]
Given a rational, real, or complex number of any type, test whether it is mathematically an integer.
Your code should handle all numeric data types commonly used in your programming language.
Discuss any limitations of your code.
Definition
For the purposes of this task, integerness means that a number could theoretically be represented as an integer at no loss of precision (given an infinitely wide integer type).
In other words:
Set
Common representation
C++ type
Considered an integer...
rational numbers Q
fraction
std::ratio
...if its denominator is 1 (in reduced form)
real numbers Z
(approximated)
fixed-point
...if it has no non-zero digits after the decimal point
floating-point
float, double
...if the number of significant decimal places of its mantissa isn't greater than its exponent
complex numbers C
pair of real numbers
std::complex
...if its real part is considered an integer and its imaginary part is zero
Extra credit
Optionally, make your code accept a tolerance parameter for fuzzy testing. The tolerance is the maximum amount by which the number may differ from the nearest integer, to still be considered an integer.
This is useful in practice, because when dealing with approximate numeric types (such as floating point), there may already be round-off errors from previous calculations. For example, a float value of 0.9999999998 might actually be intended to represent the integer 1.
Test cases
Input
Output
Comment
Type
Value
exact
tolerance = 0.00001
decimal
25.000000
true
24.999999
false
true
25.000100
false
floating-point
-2.1e120
true
This one is tricky, because in most languages it is too large to fit into a native integer type.
It is, nonetheless, mathematically an integer, and your code should identify it as such.
-5e-2
false
NaN
false
Inf
false
This one is debatable. If your code considers it an integer, that's okay too.
complex
5.0+0.0i
true
5-5i
false
(The types and notations shown in these tables are merely examples – you should use the native data types and number literals of your programming language and standard library. Use a different set of test-cases, if this one doesn't demonstrate all relevant behavior.)
| #Kotlin | Kotlin | // version 1.1.2
import java.math.BigInteger
import java.math.BigDecimal
fun Double.isLong(tolerance: Double = 0.0) =
(this - Math.floor(this)) <= tolerance || (Math.ceil(this) - this) <= tolerance
fun BigDecimal.isBigInteger() =
try {
this.toBigIntegerExact()
true
}
catch (ex: ArithmeticException) {
false
}
class Rational(val num: Long, val denom: Long) {
fun isLong() = num % denom == 0L
override fun toString() = "$num/$denom"
}
class Complex(val real: Double, val imag: Double) {
fun isLong() = real.isLong() && imag == 0.0
override fun toString() =
if (imag >= 0.0)
"$real + ${imag}i"
else
"$real - ${-imag}i"
}
fun main(args: Array<String>) {
val da = doubleArrayOf(25.000000, 24.999999, 25.000100)
for (d in da) {
val exact = d.isLong()
println("${"%.6f".format(d)} is ${if (exact) "an" else "not an"} integer")
}
val tolerance = 0.00001
println("\nWith a tolerance of ${"%.5f".format(tolerance)}:")
for (d in da) {
val fuzzy = d.isLong(tolerance)
println("${"%.6f".format(d)} is ${if (fuzzy) "an" else "not an"} integer")
}
println()
val fa = doubleArrayOf(-2.1e120, -5e-2, Double.NaN, Double.POSITIVE_INFINITY)
for (f in fa) {
val exact = if (f.isNaN() || f.isInfinite()) false
else BigDecimal(f.toString()).isBigInteger()
println("$f is ${if (exact) "an" else "not an"} integer")
}
println()
val ca = arrayOf(Complex(5.0, 0.0), Complex(5.0, -5.0))
for (c in ca) {
val exact = c.isLong()
println("$c is ${if (exact) "an" else "not an"} integer")
}
println()
val ra = arrayOf(Rational(24, 8), Rational(-5, 1), Rational(17, 2))
for (r in ra) {
val exact = r.isLong()
println("$r is ${if (exact) "an" else "not an"} integer")
}
} |
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).
| #Perl | Perl | #!/usr/bin/perl -w
use strict;
my $out = 0;
my $max_out = -1;
my @max_times;
open FH, '<mlijobs.txt' or die "Can't open file: $!";
while (<FH>) {
chomp;
if (/OUT/) {
$out++;
} else {
$out--;
}
if ($out > $max_out) {
$max_out = $out;
@max_times = ();
}
if ($out == $max_out) {
push @max_times, (split)[3];
}
}
close FH;
print "Maximum simultaneous license use is $max_out at the following times:\n";
print " $_\n" foreach @max_times; |
http://rosettacode.org/wiki/Test_a_function | Test a function |
Task
Using a well-known testing-specific library/module/suite for your language, write some tests for your language's entry in Palindrome.
If your language does not have a testing specific library well known to the language's community then state this or omit the language.
| #J | J | NB. Contents of palindrome_test.ijs
NB. Basic testing
test_palinA=: monad define
assert isPalin0 'abcba'
assert isPalin0 'aa'
assert isPalin0 ''
assert -. isPalin0 'ab'
assert -. isPalin0 'abcdba'
)
NB. Can test for expected failure instead
palinB_expect=: 'assertion failure'
test_palinB=: monad define
assert isPalin0 'ab'
) |
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.
| #Java | Java | import static ExampleClass.pali; // or from wherever it is defined
import static ExampleClass.rPali; // or from wherever it is defined
import org.junit.*;
public class PalindromeTest extends junit.framework.TestCase {
@Before
public void setUp(){
//runs before each test
//set up instance variables, network connections, etc. needed for all tests
}
@After
public void tearDown(){
//runs after each test
//clean up instance variables (close files, network connections, etc.).
}
/**
* Test the pali(...) method.
*/
@Test
public void testNonrecursivePali() throws Exception {
assertTrue(pali("abcba"));
assertTrue(pali("aa"));
assertTrue(pali("a"));
assertTrue(pali(""));
assertFalse(pali("ab"));
assertFalse(pali("abcdba"));
}
/**
* Test the rPali(...) method.
*/
@Test
public void testRecursivePali() throws Exception {
assertTrue(rPali("abcba"));
assertTrue(rPali("aa"));
assertTrue(rPali("a"));
assertTrue(rPali(""));
assertFalse(rPali("ab"));
assertFalse(rPali("abcdba"));
}
/**
* Expect a WhateverExcpetion
*/
@Test(expected=WhateverException.class)
public void except(){
//some code that should throw a WhateverException
}
} |
http://rosettacode.org/wiki/Text_processing/2 | Text processing/2 | The following task concerns data that came from a pollution monitoring station with twenty-four instruments monitoring twenty-four aspects of pollution in the air. Periodically a record is added to the file, each record being a line of 49 fields separated by white-space, which can be one or more space or tab characters.
The fields (from the left) are:
DATESTAMP [ VALUEn FLAGn ] * 24
i.e. a datestamp followed by twenty-four repetitions of a floating-point instrument value and that instrument's associated integer flag. Flag values are >= 1 if the instrument is working and < 1 if there is some problem with it, in which case that instrument's value should be ignored.
A sample from the full data file readings.txt, which is also used in the Text processing/1 task, follows:
Data is no longer available at that link. Zipped mirror available here
1991-03-30 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1
1991-03-31 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 20.000 1 20.000 1 20.000 1 35.000 1 50.000 1 60.000 1 40.000 1 30.000 1 30.000 1 30.000 1 25.000 1 20.000 1 20.000 1 20.000 1 20.000 1 20.000 1 35.000 1
1991-03-31 40.000 1 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2
1991-04-01 0.000 -2 13.000 1 16.000 1 21.000 1 24.000 1 22.000 1 20.000 1 18.000 1 29.000 1 44.000 1 50.000 1 43.000 1 38.000 1 27.000 1 27.000 1 24.000 1 23.000 1 18.000 1 12.000 1 13.000 1 14.000 1 15.000 1 13.000 1 10.000 1
1991-04-02 8.000 1 9.000 1 11.000 1 12.000 1 12.000 1 12.000 1 27.000 1 26.000 1 27.000 1 33.000 1 32.000 1 31.000 1 29.000 1 31.000 1 25.000 1 25.000 1 24.000 1 21.000 1 17.000 1 14.000 1 15.000 1 12.000 1 12.000 1 10.000 1
1991-04-03 10.000 1 9.000 1 10.000 1 10.000 1 9.000 1 10.000 1 15.000 1 24.000 1 28.000 1 24.000 1 18.000 1 14.000 1 12.000 1 13.000 1 14.000 1 15.000 1 14.000 1 15.000 1 13.000 1 13.000 1 13.000 1 12.000 1 10.000 1 10.000 1
Task
Confirm the general field format of the file.
Identify any DATESTAMPs that are duplicated.
Report the number of records that have good readings for all instruments.
| #Ursala | Ursala | #import std
#import nat
readings = (*F ~&c/;digits+ rlc ==+ ~~ -={` ,9%cOi&,13%cOi&}) readings_dot_txt
valid_format = all -&length==49,@tK27 all ~&w/`.&& ~&jZ\digits--'-.',@tK28 all ~&jZ\digits--'-'&-
duplicate_dates = :/'duplicated dates:'+ ~&hK2tFhhPS|| -[(none)]-!
good_readings = --' good readings'@h+ %nP+ length+ *~ @tK28 all ~='0'&& ~&wZ/`-
#show+
main = valid_format?(^C/good_readings duplicate_dates,-[invalid format]-!) readings |
http://rosettacode.org/wiki/Text_processing/2 | Text processing/2 | The following task concerns data that came from a pollution monitoring station with twenty-four instruments monitoring twenty-four aspects of pollution in the air. Periodically a record is added to the file, each record being a line of 49 fields separated by white-space, which can be one or more space or tab characters.
The fields (from the left) are:
DATESTAMP [ VALUEn FLAGn ] * 24
i.e. a datestamp followed by twenty-four repetitions of a floating-point instrument value and that instrument's associated integer flag. Flag values are >= 1 if the instrument is working and < 1 if there is some problem with it, in which case that instrument's value should be ignored.
A sample from the full data file readings.txt, which is also used in the Text processing/1 task, follows:
Data is no longer available at that link. Zipped mirror available here
1991-03-30 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1
1991-03-31 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 20.000 1 20.000 1 20.000 1 35.000 1 50.000 1 60.000 1 40.000 1 30.000 1 30.000 1 30.000 1 25.000 1 20.000 1 20.000 1 20.000 1 20.000 1 20.000 1 35.000 1
1991-03-31 40.000 1 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2
1991-04-01 0.000 -2 13.000 1 16.000 1 21.000 1 24.000 1 22.000 1 20.000 1 18.000 1 29.000 1 44.000 1 50.000 1 43.000 1 38.000 1 27.000 1 27.000 1 24.000 1 23.000 1 18.000 1 12.000 1 13.000 1 14.000 1 15.000 1 13.000 1 10.000 1
1991-04-02 8.000 1 9.000 1 11.000 1 12.000 1 12.000 1 12.000 1 27.000 1 26.000 1 27.000 1 33.000 1 32.000 1 31.000 1 29.000 1 31.000 1 25.000 1 25.000 1 24.000 1 21.000 1 17.000 1 14.000 1 15.000 1 12.000 1 12.000 1 10.000 1
1991-04-03 10.000 1 9.000 1 10.000 1 10.000 1 9.000 1 10.000 1 15.000 1 24.000 1 28.000 1 24.000 1 18.000 1 14.000 1 12.000 1 13.000 1 14.000 1 15.000 1 14.000 1 15.000 1 13.000 1 13.000 1 13.000 1 12.000 1 10.000 1 10.000 1
Task
Confirm the general field format of the file.
Identify any DATESTAMPs that are duplicated.
Report the number of records that have good readings for all instruments.
| #VBScript | VBScript | Set objFSO = CreateObject("Scripting.FileSystemObject")
Set objFile = objFSO.OpenTextFile(objFSO.GetParentFolderName(WScript.ScriptFullName) &_
"\readings.txt",1)
Set objDateStamp = CreateObject("Scripting.Dictionary")
Total_Records = 0
Valid_Records = 0
Duplicate_TimeStamps = ""
Do Until objFile.AtEndOfStream
line = objFile.ReadLine
If line <> "" Then
token = Split(line,vbTab)
If objDateStamp.Exists(token(0)) = False Then
objDateStamp.Add token(0),""
Total_Records = Total_Records + 1
If IsValid(token) Then
Valid_Records = Valid_Records + 1
End If
Else
Duplicate_TimeStamps = Duplicate_TimeStamps & token(0) & vbCrLf
Total_Records = Total_Records + 1
End If
End If
Loop
Function IsValid(arr)
IsValid = True
Bad_Readings = 0
n = 1
Do While n <= UBound(arr)
If n + 1 <= UBound(arr) Then
If CInt(arr(n+1)) < 1 Then
Bad_Readings = Bad_Readings + 1
End If
End If
n = n + 2
Loop
If Bad_Readings > 0 Then
IsValid = False
End If
End Function
WScript.StdOut.Write "Total Number of Records = " & Total_Records
WScript.StdOut.WriteLine
WScript.StdOut.Write "Total Valid Records = " & Valid_Records
WScript.StdOut.WriteLine
WScript.StdOut.Write "Duplicate Timestamps:"
WScript.StdOut.WriteLine
WScript.StdOut.Write Duplicate_TimeStamps
WScript.StdOut.WriteLine
objFile.Close
Set objFSO = Nothing |
http://rosettacode.org/wiki/Terminal_control/Ringing_the_terminal_bell | Terminal control/Ringing the terminal bell |
Task
Make the terminal running the program ring its "bell".
On modern terminal emulators, this may be done by playing some other sound which might or might not be configurable, or by flashing the title bar or inverting the colors of the screen, but was classically a physical bell within the terminal. It is usually used to indicate a problem where a wrong character has been typed.
In most terminals, if the Bell character (ASCII code 7, \a in C) is printed by the program, it will cause the terminal to ring its bell. This is a function of the terminal, and is independent of the programming language of the program, other than the ability to print a particular character to standard out.
| #Python | Python | print "\a" |
http://rosettacode.org/wiki/Terminal_control/Ringing_the_terminal_bell | Terminal control/Ringing the terminal bell |
Task
Make the terminal running the program ring its "bell".
On modern terminal emulators, this may be done by playing some other sound which might or might not be configurable, or by flashing the title bar or inverting the colors of the screen, but was classically a physical bell within the terminal. It is usually used to indicate a problem where a wrong character has been typed.
In most terminals, if the Bell character (ASCII code 7, \a in C) is printed by the program, it will cause the terminal to ring its bell. This is a function of the terminal, and is independent of the programming language of the program, other than the ability to print a particular character to standard out.
| #Quackery | Quackery | ding |
http://rosettacode.org/wiki/Terminal_control/Ringing_the_terminal_bell | Terminal control/Ringing the terminal bell |
Task
Make the terminal running the program ring its "bell".
On modern terminal emulators, this may be done by playing some other sound which might or might not be configurable, or by flashing the title bar or inverting the colors of the screen, but was classically a physical bell within the terminal. It is usually used to indicate a problem where a wrong character has been typed.
In most terminals, if the Bell character (ASCII code 7, \a in C) is printed by the program, it will cause the terminal to ring its bell. This is a function of the terminal, and is independent of the programming language of the program, other than the ability to print a particular character to standard out.
| #R | R | alarm() |
http://rosettacode.org/wiki/Terminal_control/Ringing_the_terminal_bell | Terminal control/Ringing the terminal bell |
Task
Make the terminal running the program ring its "bell".
On modern terminal emulators, this may be done by playing some other sound which might or might not be configurable, or by flashing the title bar or inverting the colors of the screen, but was classically a physical bell within the terminal. It is usually used to indicate a problem where a wrong character has been typed.
In most terminals, if the Bell character (ASCII code 7, \a in C) is printed by the program, it will cause the terminal to ring its bell. This is a function of the terminal, and is independent of the programming language of the program, other than the ability to print a particular character to standard out.
| #Racket | Racket |
#lang racket
(require (planet neil/charterm:3:0))
(with-charterm
(void (charterm-bell)))
|
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
| #BASIC | BASIC | 10 DEFINT I,J: DEFSTR N,V: DIM N(12),V(12)
20 FOR I=1 TO 12: READ N(I): NEXT
30 FOR I=1 TO 12: READ V(I): NEXT
40 FOR I=1 TO 12
50 PRINT "On the ";N(I);" day of Christmas"
60 PRINT "My true love gave to me:"
70 FOR J=I TO 1 STEP -1: PRINT V(J): NEXT
75 PRINT
80 NEXT
90 END
100 DATA first,second,third,fourth,fifth,sixth
110 DATA seventh,eighth,ninth,tenth,eleventh,twelfth
120 DATA "A partridge in a pear tree."
130 DATA "Two turtle doves and"
140 DATA "Three french hens"
150 DATA "Four calling birds"
160 DATA "Five golden rings"
170 DATA "Six geese a-laying"
180 DATA "Seven swans a-swimming"
190 DATA "Eight maids a-milking"
200 DATA "Nine ladies dancing"
210 DATA "Ten lords a-leaping"
220 DATA "Eleven pipers piping"
230 DATA "Twelve drummers drumming" |
http://rosettacode.org/wiki/Terminal_control/Preserve_screen | Terminal control/Preserve screen |
Task
Clear the screen, output something on the display, and then restore the screen to the preserved state that it was in before the task was carried out.
There is no requirement to change the font or kerning in this task, however character decorations and attributes are expected to be preserved. If the implementer decides to change the font or kerning during the display of the temporary screen, then these settings need to be restored prior to exit.
| #zkl | zkl | print("\e[?1049h\e[H");
println("Alternate screen buffer");
foreach i in ([5..1,-1]){
print("\rgoing back in %d...".fmt(i));
Atomic.sleep(1);
}
print("\e[?1049l"); |
http://rosettacode.org/wiki/Terminal_control/Hiding_the_cursor | Terminal control/Hiding the cursor | The task is to hide the cursor and show it again.
| #Mathematica.2FWolfram_Language | Mathematica/Wolfram Language | Run["tput civis"] (* Cursor hidden *)
Pause[2]
Run["tput cvvis"] (* Cursor Visible *) |
http://rosettacode.org/wiki/Terminal_control/Hiding_the_cursor | Terminal control/Hiding the cursor | The task is to hide the cursor and show it again.
| #Nemerle | Nemerle | using System.Console;
using System.Threading.Thread;
module CursorVisibility
{
Main() : void
{
repeat(3) {
CursorVisible = !CursorVisible;
Sleep(5000);
}
}
} |
http://rosettacode.org/wiki/Terminal_control/Hiding_the_cursor | Terminal control/Hiding the cursor | The task is to hide the cursor and show it again.
| #Nim | Nim | import terminal
echo "Cursor hidden. Press a key to show the cursor and exit."
stdout.hideCursor()
discard getCh()
stdout.showCursor()
|
http://rosettacode.org/wiki/Terminal_control/Hiding_the_cursor | Terminal control/Hiding the cursor | The task is to hide the cursor and show it again.
| #Perl | Perl | print "\e[?25l"; # hide the cursor
print "Enter anything, press RETURN: "; # prompt shown
$input = <>; # but no cursor
print "\e[0H\e[0J\e[?25h"; # reset, visible again |
http://rosettacode.org/wiki/Terminal_control/Hiding_the_cursor | Terminal control/Hiding the cursor | The task is to hide the cursor and show it again.
| #Phix | Phix | cursor(NO_CURSOR)
sleep(1)
cursor(UNDERLINE_CURSOR)
|
http://rosettacode.org/wiki/Terminal_control/Inverse_video | Terminal control/Inverse video | Task
Display a word in inverse video (or reverse video) followed by a word in normal video.
| #Nim | Nim | import terminal
stdout.styledWrite("normal ", styleReverse, "inverse", resetStyle, " normal\n") |
http://rosettacode.org/wiki/Terminal_control/Inverse_video | Terminal control/Inverse video | Task
Display a word in inverse video (or reverse video) followed by a word in normal video.
| #OCaml | OCaml | $ ocaml unix.cma -I +ANSITerminal ANSITerminal.cma
# open ANSITerminal ;;
# print_string [Inverse] "Hello\n" ;;
Hello
- : unit = () |
http://rosettacode.org/wiki/Terminal_control/Inverse_video | Terminal control/Inverse video | Task
Display a word in inverse video (or reverse video) followed by a word in normal video.
| #Pascal | Pascal | program InverseVideo;
{$LINKLIB tinfo}
uses
ncurses;
begin
initscr;
attron(A_REVERSE);
printw('reversed');
attroff(A_REVERSE);
printw(' normal');
refresh;
getch;
endwin;
end.
|
http://rosettacode.org/wiki/Terminal_control/Inverse_video | Terminal control/Inverse video | Task
Display a word in inverse video (or reverse video) followed by a word in normal video.
| #Perl | Perl | print "normal\n";
system "tput rev";
print "reversed\n";
system "tput sgr0";
print "normal\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.
| #Axe | Axe | ' ANSI terminal dimensions
X = COLUMNS
Y = ROWS
PRINT "X,Y: ", X, ",", Y |
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.
| #BaCon | BaCon | ' ANSI terminal dimensions
X = COLUMNS
Y = ROWS
PRINT "X,Y: ", X, ",", Y |
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.
| #Batch_File | Batch File | @echo off
for /f "tokens=1,2 delims= " %%A in ('mode con') do (
if "%%A"=="Lines:" set line=%%B
if "%%A"=="Columns:" set cols=%%B
)
echo Lines: %line%
echo Columns: %cols%
exit /b 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.
| #Arturo | Arturo | goto 3 6
print "Hello" |
http://rosettacode.org/wiki/Terminal_control/Cursor_positioning | Terminal control/Cursor positioning |
Task
Move the cursor to column 3, row 6, and display the word "Hello" (without the quotes), so that the letter H is in column 3 on row 6.
| #AutoHotkey | AutoHotkey | DllCall( "AllocConsole" ) ; create a console if not launched from one
hConsole := DllCall( "GetStdHandle", int, STDOUT := -11 )
DllCall("SetConsoleCursorPosition", UPtr, hConsole, UInt, (6 << 16) | 3)
WriteConsole(hConsole, "Hello")
MsgBox
WriteConsole(hConsole, text){
VarSetCapacity(out, 16)
If DllCall( "WriteConsole", UPtr, hConsole, Str, text, UInt, StrLen(text)
, UPtrP, out, uint, 0 )
return out
return 0
} |
http://rosettacode.org/wiki/Terminal_control/Cursor_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.
| #Axe | Axe | Output(2,5,"HELLO") |
http://rosettacode.org/wiki/Ternary_logic | Ternary logic |
This page uses content from Wikipedia. The original article was at Ternary logic. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance)
In logic, a three-valued logic (also trivalent, ternary, or trinary logic, sometimes abbreviated 3VL) is any of several many-valued logic systems in which there are three truth values indicating true, false and some indeterminate third value.
This is contrasted with the more commonly known bivalent logics (such as classical sentential or boolean logic) which provide only for true and false.
Conceptual form and basic ideas were initially created by Łukasiewicz, Lewis and Sulski.
These were then re-formulated by Grigore Moisil in an axiomatic algebraic form, and also extended to n-valued logics in 1945.
Example Ternary Logic Operators in Truth Tables:
not a
¬
True
False
Maybe
Maybe
False
True
a and b
∧
True
Maybe
False
True
True
Maybe
False
Maybe
Maybe
Maybe
False
False
False
False
False
a or b
∨
True
Maybe
False
True
True
True
True
Maybe
True
Maybe
Maybe
False
True
Maybe
False
if a then b
⊃
True
Maybe
False
True
True
Maybe
False
Maybe
True
Maybe
Maybe
False
True
True
True
a is equivalent to b
≡
True
Maybe
False
True
True
Maybe
False
Maybe
Maybe
Maybe
Maybe
False
False
Maybe
True
Task
Define a new type that emulates ternary logic by storing data trits.
Given all the binary logic operators of the original programming language, reimplement these operators for the new Ternary logic type trit.
Generate a sampling of results using trit variables.
Kudos for actually thinking up a test case algorithm where ternary logic is intrinsically useful, optimises the test case algorithm and is preferable to binary logic.
Note: Setun (Сетунь) was a balanced ternary computer developed in 1958 at Moscow State University. The device was built under the lead of Sergei Sobolev and Nikolay Brusentsov. It was the only modern ternary computer, using three-valued ternary logic
| #BASIC256 | BASIC256 |
global tFalse, tDontKnow, tTrue
tFalse = 0
tDontKnow = 1
tTrue = 2
print "Nombres cortos y largos para valores lógicos ternarios:"
for i = tFalse to tTrue
print shortName3$(i); " "; longName3$(i)
next i
print
print "Funciones de parámetro único"
print "x"; " "; "=x"; " "; "not(x)"
for i = tFalse to tTrue
print shortName3$(i); " "; shortName3$(i); " "; shortName3$(not3(i))
next i
print
print "Funciones de doble parámetro"
print "x";" ";"y";" ";"x AND y";" ";"x OR y";" ";"x EQ y";" ";"x XOR y"
for a = tFalse to tTrue
for b = tFalse to tTrue
print shortName3$(a); " "; shortName3$(b); " ";
print shortName3$(and3(a,b)); " "; shortName3$(or3(a,b));" ";
print shortName3$(eq3(a,b)); " "; shortName3$(xor3(a,b))
next b
next a
end
function and3(a,b)
if a < b then return a else return b
end function
function or3(a,b)
if a > b then return a else return b
end function
function eq3(a,b)
begin case
case a = tDontKnow or b = tDontKnow
return tDontKnow
case a = b
return tTrue
else
return tFalse
end case
end function
function xor3(a,b)
return not3(eq3(a,b))
end function
function not3(b)
return 2-b
end function
function shortName3$(i)
return mid("F?T", i+1, 1)
end function
function longName3$(i)
begin case
case i = 1
return "Don't know"
case i = 2
return "True"
else
return "False"
end case
end function
|
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).
| #Common_Lisp | Common Lisp |
(format t "札幌~%")
(format t "~C~%" (code-char #x00A3))
|
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).
| #D | D | import std.stdio;
void main() {
writeln('\u00A3');
} |
http://rosettacode.org/wiki/Terminal_control/Display_an_extended_character | Terminal control/Display an extended character | Task
Display an extended (non ASCII) character onto the terminal.
Specifically, display a £ (GBP currency sign).
| #Dc | Dc | 49827 P |
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).
| #EchoLisp | EchoLisp |
;; simplest
(display "£")
;; unicode character
(display "\u00a3")
;; HTML special character
(display "£")
;; CSS enhancement
(display "£" "color:blue;font-size:2em")
|
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).
| #Erlang | Erlang | 8> Pound = [163].
9> io:fwrite( "~s~n", [Pound] ).
£
|
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.
| #C | C | #include <stdio.h>
#include <stdlib.h>
#include <string.h>
static int badHrs, maxBadHrs;
static double hrsTot = 0.0;
static int rdgsTot = 0;
char bhEndDate[40];
int mungeLine( char *line, int lno, FILE *fout )
{
char date[40], *tkn;
int dHrs, flag, hrs2, hrs;
double hrsSum;
int hrsCnt = 0;
double avg;
tkn = strtok(line, ".");
if (tkn) {
int n = sscanf(tkn, "%s %d", &date, &hrs2);
if (n<2) {
printf("badly formated line - %d %s\n", lno, tkn);
return 0;
}
hrsSum = 0.0;
while( tkn= strtok(NULL, ".")) {
n = sscanf(tkn,"%d %d %d", &dHrs, &flag, &hrs);
if (n>=2) {
if (flag > 0) {
hrsSum += 1.0*hrs2 + .001*dHrs;
hrsCnt += 1;
if (maxBadHrs < badHrs) {
maxBadHrs = badHrs;
strcpy(bhEndDate, date);
}
badHrs = 0;
}
else {
badHrs += 1;
}
hrs2 = hrs;
}
else {
printf("bad file syntax line %d: %s\n",lno, tkn);
}
}
avg = (hrsCnt > 0)? hrsSum/hrsCnt : 0.0;
fprintf(fout, "%s Reject: %2d Accept: %2d Average: %7.3f\n",
date, 24-hrsCnt, hrsCnt, hrsSum/hrsCnt);
hrsTot += hrsSum;
rdgsTot += hrsCnt;
}
return 1;
}
int main()
{
FILE *infile, *outfile;
int lineNo = 0;
char line[512];
const char *ifilename = "readings.txt";
outfile = fopen("V0.txt", "w");
infile = fopen(ifilename, "rb");
if (!infile) {
printf("Can't open %s\n", ifilename);
exit(1);
}
while (NULL != fgets(line, 512, infile)) {
lineNo += 1;
if (0 == mungeLine(line, lineNo, outfile))
printf("Bad line at %d",lineNo);
}
fclose(infile);
fprintf(outfile, "File: %s\n", ifilename);
fprintf(outfile, "Total: %.3f\n", hrsTot);
fprintf(outfile, "Readings: %d\n", rdgsTot);
fprintf(outfile, "Average: %.3f\n", hrsTot/rdgsTot);
fprintf(outfile, "\nMaximum number of consecutive bad readings is %d\n", maxBadHrs);
fprintf(outfile, "Ends on date %s\n", bhEndDate);
fclose(outfile);
return 0;
} |
http://rosettacode.org/wiki/Terminal_control/Positional_read | Terminal control/Positional read | Determine the character displayed on the screen at column 3, row 6 and store that character in a variable. Note that it is permissible to utilize system or language provided methods or system provided facilities, system maintained records or available buffers or system maintained display records to achieve this task, rather than query the terminal directly, if those methods are more usual for the system type or language.
| #XPL0 | XPL0 | include c:\cxpl\stdlib;
int C;
[Cursor(3, 6); \move cursor to column 3, row 6 (top left = 0,0)
\Call BIOS interrupt routine to read character (& attribute) at cursor position
C:= CallInt($10, $0800, 0) & $00FF; \mask off attribute, leaving the character
] |
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.
| #Kotlin | Kotlin | // version 1.1.3
/* external results */
val randrsl = IntArray(256)
var randcnt = 0
/* internal state */
val mm = IntArray(256)
var aa = 0
var bb = 0
var cc = 0
const val GOLDEN_RATIO = 0x9e3779b9.toInt()
fun isaac() {
cc++ // cc just gets incremented once per 256 results
bb += cc // then combined with bb
for (i in 0..255) {
val x = mm[i]
when (i % 4) {
0 -> aa = aa xor (aa shl 13)
1 -> aa = aa xor (aa ushr 6)
2 -> aa = aa xor (aa shl 2)
3 -> aa = aa xor (aa ushr 16)
}
aa += mm[(i + 128) % 256]
val y = mm[(x ushr 2) % 256] + aa + bb
mm[i] = y
bb = mm[(y ushr 10) % 256] + x
randrsl[i] = bb
}
randcnt = 0
}
/* if (flag == true), then use the contents of randrsl to initialize mm. */
fun mix(n: IntArray) {
n[0] = n[0] xor (n[1] shl 11); n[3] += n[0]; n[1] += n[2]
n[1] = n[1] xor (n[2] ushr 2); n[4] += n[1]; n[2] += n[3]
n[2] = n[2] xor (n[3] shl 8); n[5] += n[2]; n[3] += n[4]
n[3] = n[3] xor (n[4] ushr 16); n[6] += n[3]; n[4] += n[5]
n[4] = n[4] xor (n[5] shl 10); n[7] += n[4]; n[5] += n[6]
n[5] = n[5] xor (n[6] ushr 4); n[0] += n[5]; n[6] += n[7]
n[6] = n[6] xor (n[7] shl 8); n[1] += n[6]; n[7] += n[0]
n[7] = n[7] xor (n[0] ushr 9); n[2] += n[7]; n[0] += n[1]
}
fun randinit(flag: Boolean) {
aa = 0
bb = 0
cc = 0
val n = IntArray(8) { GOLDEN_RATIO }
for (i in 0..3) mix(n) // scramble the array
for (i in 0..255 step 8) { // fill in mm with messy stuff
if (flag) { // use all the information in the seed
for (j in 0..7) n[j] += randrsl[i + j]
}
mix(n)
for (j in 0..7) mm[i + j] = n[j]
}
if (flag) {
/* do a second pass to make all of the seed affect all of mm */
for (i in 0..255 step 8) {
for (j in 0..7) n[j] += mm[i + j]
mix(n)
for (j in 0..7) mm[i + j] = n[j]
}
}
isaac() // fill in the first set of results
randcnt = 0 // prepare to use the first set of results
}
/* As Kotlin doesn't (yet) support unsigned types, we need to use
Long here to get a random value in the range of a UInt */
fun iRandom(): Long {
val r = randrsl[randcnt++]
if (randcnt > 255) {
isaac()
randcnt = 0
}
return r.toLong() and 0xFFFFFFFFL
}
/* Get a random character (as Int) in printable ASCII range */
fun iRandA() = (iRandom() % 95 + 32).toInt()
/* Seed ISAAC with a string */
fun iSeed(seed: String, flag: Boolean) {
for (i in 0..255) mm[i] = 0
val m = seed.length
for (i in 0..255) {
/* in case seed has less than 256 elements */
randrsl[i] = if (i >= m) 0 else seed[i].toInt()
}
/* initialize ISAAC with seed */
randinit(flag)
}
/* XOR cipher on random stream. Output: ASCII string */
fun vernam(msg: String) : String {
val len = msg.length
val v = ByteArray(len)
for (i in 0 until len) {
v[i] = (iRandA() xor msg[i].toInt()).toByte()
}
return v.toString(charset("ASCII"))
}
/* constants for Caesar */
const val MOD = 95
const val START = 32
/* cipher modes for Caesar */
enum class CipherMode {
ENCIPHER, DECIPHER, NONE
}
/* Caesar-shift a printable character */
fun caesar(m: CipherMode, ch: Int, shift: Int, modulo: Int, start: Int): Char {
val sh = if (m == CipherMode.DECIPHER) -shift else shift
var n = (ch - start) + sh
n %= modulo
if (n < 0) n += modulo
return (start + n).toChar()
}
/* Caesar-shift a string on a pseudo-random stream */
fun caesarStr(m: CipherMode, msg: String, modulo: Int, start: Int): String {
val sb = StringBuilder(msg.length)
/* Caesar-shift message */
for (c in msg) {
sb.append(caesar(m, c.toInt(), iRandA(), modulo, start))
}
return sb.toString()
}
fun String.toHexByteString() =
this.map { "%02X".format(it.toInt()) }.joinToString("")
fun main(args: Array<String>) {
val msg = "a Top Secret secret"
val key = "this is my secret key"
// Vernam & Caesar ciphertext
iSeed(key, true)
val vctx = vernam(msg)
val cctx = caesarStr(CipherMode.ENCIPHER, msg, MOD, START)
// Vernam & Caesar plaintext
iSeed(key, true)
val vptx = vernam(vctx)
val cptx = caesarStr(CipherMode.DECIPHER, cctx, MOD, START)
// Program output
println("Message : $msg")
println("Key : $key")
println("XOR : ${vctx.toHexByteString()}")
println("XOR dcr : $vptx")
println("MOD : ${cctx.toHexByteString()}")
println("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.)
| #Lua | Lua | function isInt (x) return type(x) == "number" and x == math.floor(x) end
print("Value\tInteger?")
print("=====\t========")
local testCases = {2, 0, -1, 3.5, "String!", true}
for _, input in pairs(testCases) do print(input, isInt(input)) end |
http://rosettacode.org/wiki/Test_integerness | Test integerness | Mathematically,
the integers Z are included in the rational numbers Q,
which are included in the real numbers R,
which can be generalized to the complex numbers C.
This means that each of those larger sets, and the data types used to represent them, include some integers.
Task[edit]
Given a rational, real, or complex number of any type, test whether it is mathematically an integer.
Your code should handle all numeric data types commonly used in your programming language.
Discuss any limitations of your code.
Definition
For the purposes of this task, integerness means that a number could theoretically be represented as an integer at no loss of precision (given an infinitely wide integer type).
In other words:
Set
Common representation
C++ type
Considered an integer...
rational numbers Q
fraction
std::ratio
...if its denominator is 1 (in reduced form)
real numbers Z
(approximated)
fixed-point
...if it has no non-zero digits after the decimal point
floating-point
float, double
...if the number of significant decimal places of its mantissa isn't greater than its exponent
complex numbers C
pair of real numbers
std::complex
...if its real part is considered an integer and its imaginary part is zero
Extra credit
Optionally, make your code accept a tolerance parameter for fuzzy testing. The tolerance is the maximum amount by which the number may differ from the nearest integer, to still be considered an integer.
This is useful in practice, because when dealing with approximate numeric types (such as floating point), there may already be round-off errors from previous calculations. For example, a float value of 0.9999999998 might actually be intended to represent the integer 1.
Test cases
Input
Output
Comment
Type
Value
exact
tolerance = 0.00001
decimal
25.000000
true
24.999999
false
true
25.000100
false
floating-point
-2.1e120
true
This one is tricky, because in most languages it is too large to fit into a native integer type.
It is, nonetheless, mathematically an integer, and your code should identify it as such.
-5e-2
false
NaN
false
Inf
false
This one is debatable. If your code considers it an integer, that's okay too.
complex
5.0+0.0i
true
5-5i
false
(The types and notations shown in these tables are merely examples – you should use the native data types and number literals of your programming language and standard library. Use a different set of test-cases, if this one doesn't demonstrate all relevant behavior.)
| #Mathematica_.2F_Wolfram_Language | Mathematica / Wolfram Language | IntegerQ /@ {E, 2.4, 7, 9/2} |
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).
| #Phix | Phix | -- demo\rosetta\Max_licences.exw
with javascript_semantics -- (include version/first of next three lines only)
include mlijobs.e -- global constant lines, or:
--assert(write_lines("mlijobs.txt",lines)!=-1) -- first run, or get from link above, then:
--constant lines = read_lines("mlijobs.txt")
integer maxout = 0, jobnumber
sequence jobs = {}, maxtime, scanres
string inout, jobtime
for i=1 to length(lines) do
string line = lines[i]
scanres = scanf(line,"License %s @ %s for job %d")
if length(scanres)!=1 then
printf(1,"error scanning line: %s\n",{line})
{} = wait_key()
abort(0)
end if
{{inout,jobtime,jobnumber}} = scanres
if inout="OUT" then
jobs &= jobnumber
if length(jobs)>maxout then
maxout = length(jobs)
maxtime = {jobtime}
elsif length(jobs)=maxout then
maxtime = append(maxtime, jobtime)
end if
else
jobs[find(jobnumber,jobs)] = jobs[$]
jobs = jobs[1..$-1]
end if
end for
printf(1, "Maximum simultaneous license use is %d at the following times:\n", maxout)
for i = 1 to length(maxtime) do
printf(1, "%s\n", {maxtime[i]})
end for
?"done"
{} = wait_key()
|
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.
| #JavaScript | JavaScript | const assert = require('assert');
describe('palindrome', () => {
const pali = require('../lib/palindrome');
describe('.check()', () => {
it('should return true on encountering a palindrome', () => {
assert.ok(pali.check('racecar'));
assert.ok(pali.check('abcba'));
assert.ok(pali.check('aa'));
assert.ok(pali.check('a'));
});
it('should return true on encountering an empty string', () => {
assert.ok(pali.check(''));
});
it('should return false on encountering a non-palindrome', () => {
assert.ok(!pali.check('alice'));
assert.ok(!pali.check('ab'));
assert.ok(!pali.check('abcdba'));
});
})
}); |
http://rosettacode.org/wiki/Text_processing/2 | Text processing/2 | The following task concerns data that came from a pollution monitoring station with twenty-four instruments monitoring twenty-four aspects of pollution in the air. Periodically a record is added to the file, each record being a line of 49 fields separated by white-space, which can be one or more space or tab characters.
The fields (from the left) are:
DATESTAMP [ VALUEn FLAGn ] * 24
i.e. a datestamp followed by twenty-four repetitions of a floating-point instrument value and that instrument's associated integer flag. Flag values are >= 1 if the instrument is working and < 1 if there is some problem with it, in which case that instrument's value should be ignored.
A sample from the full data file readings.txt, which is also used in the Text processing/1 task, follows:
Data is no longer available at that link. Zipped mirror available here
1991-03-30 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1
1991-03-31 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 20.000 1 20.000 1 20.000 1 35.000 1 50.000 1 60.000 1 40.000 1 30.000 1 30.000 1 30.000 1 25.000 1 20.000 1 20.000 1 20.000 1 20.000 1 20.000 1 35.000 1
1991-03-31 40.000 1 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2
1991-04-01 0.000 -2 13.000 1 16.000 1 21.000 1 24.000 1 22.000 1 20.000 1 18.000 1 29.000 1 44.000 1 50.000 1 43.000 1 38.000 1 27.000 1 27.000 1 24.000 1 23.000 1 18.000 1 12.000 1 13.000 1 14.000 1 15.000 1 13.000 1 10.000 1
1991-04-02 8.000 1 9.000 1 11.000 1 12.000 1 12.000 1 12.000 1 27.000 1 26.000 1 27.000 1 33.000 1 32.000 1 31.000 1 29.000 1 31.000 1 25.000 1 25.000 1 24.000 1 21.000 1 17.000 1 14.000 1 15.000 1 12.000 1 12.000 1 10.000 1
1991-04-03 10.000 1 9.000 1 10.000 1 10.000 1 9.000 1 10.000 1 15.000 1 24.000 1 28.000 1 24.000 1 18.000 1 14.000 1 12.000 1 13.000 1 14.000 1 15.000 1 14.000 1 15.000 1 13.000 1 13.000 1 13.000 1 12.000 1 10.000 1 10.000 1
Task
Confirm the general field format of the file.
Identify any DATESTAMPs that are duplicated.
Report the number of records that have good readings for all instruments.
| #Vedit_macro_language | Vedit macro language | #50 = Buf_Num // Current edit buffer (source data)
File_Open("|(PATH_ONLY)\output.txt")
#51 = Buf_Num // Edit buffer for output file
Buf_Switch(#50)
#11 = #12 = #13 = #14 = #15 = 0
Reg_Set(15, "xxx")
While(!At_EOF) {
#10 = 0
#12++
// Check for repeated date field
if (Match(@15) == 0) {
#20 = Cur_Line
Buf_Switch(#51) // Output file
Reg_ins(15) IT(": duplicate record at ") Num_Ins(#20)
Buf_Switch(#50) // Input file
#13++
}
// Check format of date field
if (Match("|d|d|d|d-|d|d-|d|d|w", ADVANCE) != 0) {
#10 = 1
#14++
}
Reg_Copy_Block(15, BOL_pos, Cur_Pos-1)
// Check data fields and flags:
Repeat(24) {
if ( Match("|d|*.|d|d|d|w", ADVANCE) != 0 || Num_Eval(ADVANCE) < 1) {
#10 = 1
#15++
Break
}
Match("|W", ADVANCE)
}
if (#10 == 0) { #11++ } // record was OK
Line(1, ERRBREAK)
}
Buf_Switch(#51) // buffer for output data
IN
IT("Valid records: ") Num_Ins(#11)
IT("Duplicates: ") Num_Ins(#13)
IT("Date format errors: ") Num_Ins(#14)
IT("Invalid data records:") Num_Ins(#15)
IT("Total records: ") Num_Ins(#12) |
http://rosettacode.org/wiki/Terminal_control/Ringing_the_terminal_bell | Terminal control/Ringing the terminal bell |
Task
Make the terminal running the program ring its "bell".
On modern terminal emulators, this may be done by playing some other sound which might or might not be configurable, or by flashing the title bar or inverting the colors of the screen, but was classically a physical bell within the terminal. It is usually used to indicate a problem where a wrong character has been typed.
In most terminals, if the Bell character (ASCII code 7, \a in C) is printed by the program, it will cause the terminal to ring its bell. This is a function of the terminal, and is independent of the programming language of the program, other than the ability to print a particular character to standard out.
| #Raku | Raku | print 7.chr; |
http://rosettacode.org/wiki/Terminal_control/Ringing_the_terminal_bell | Terminal control/Ringing the terminal bell |
Task
Make the terminal running the program ring its "bell".
On modern terminal emulators, this may be done by playing some other sound which might or might not be configurable, or by flashing the title bar or inverting the colors of the screen, but was classically a physical bell within the terminal. It is usually used to indicate a problem where a wrong character has been typed.
In most terminals, if the Bell character (ASCII code 7, \a in C) is printed by the program, it will cause the terminal to ring its bell. This is a function of the terminal, and is independent of the programming language of the program, other than the ability to print a particular character to standard out.
| #Retro | Retro | 7 putc |
http://rosettacode.org/wiki/Terminal_control/Ringing_the_terminal_bell | Terminal control/Ringing the terminal bell |
Task
Make the terminal running the program ring its "bell".
On modern terminal emulators, this may be done by playing some other sound which might or might not be configurable, or by flashing the title bar or inverting the colors of the screen, but was classically a physical bell within the terminal. It is usually used to indicate a problem where a wrong character has been typed.
In most terminals, if the Bell character (ASCII code 7, \a in C) is printed by the program, it will cause the terminal to ring its bell. This is a function of the terminal, and is independent of the programming language of the program, other than the ability to print a particular character to standard out.
| #REXX | REXX | /*REXX program illustrates methods to ring the terminal bell or use the PC speaker. */
/*╔═══════════════════════════════════════════════════════════════╗
║ ║
║ Note that the hexadecimal code to ring the terminal bell ║
║ is different on an ASCII machine than an EBCDIC machine. ║
║ ║
║ On an ASCII machine, it is (hexadecimal) '07'x. ║
║ " " EBCDIC " " " " '2F'x. ║
║ ║
╚═══════════════════════════════════════════════════════════════╝*/
if 3=='F3' then bell= '2f'x /*we are running on an EBCDIC machine. */
else bell= '07'x /* " " " " " ASCII " */
say bell /*sound the bell on the terminal. */
say copies(bell, 20) /*as above, but much more annoying. */
/*╔═══════════════════════════════════════════════════════════════╗
║ ║
║ Some REXX interpreters have a built-in function (BIF) to ║
║ to produce a sound on the PC speaker, the sound is specified ║
║ by frequency and an optional duration. ║
║ ║
╚═══════════════════════════════════════════════════════════════╝*/
/* [↓] supported by Regina REXX: */
freq= 1200 /*frequency in (nearest) cycles per second. */
call beep freq /*sounds the PC speaker, duration= 1 second.*/
ms= 500 /*duration in milliseconds. */
call beep freq, ms /* " " " " " 1/2 " */
/* [↓] supported by PC/REXX & Personal REXX:*/
freq= 2000 /*frequency in (nearest) cycles per second. */
call sound freq /*sounds PC speaker, duration= .2 second. */
secs= .333 /*duration in seconds (round to nearest tenth).*/
call sound freq, secs /* " " " " 3/10 " */
/*stick a fork in it, we're done making noises.*/ |
http://rosettacode.org/wiki/Terminal_control/Ringing_the_terminal_bell | Terminal control/Ringing the terminal bell |
Task
Make the terminal running the program ring its "bell".
On modern terminal emulators, this may be done by playing some other sound which might or might not be configurable, or by flashing the title bar or inverting the colors of the screen, but was classically a physical bell within the terminal. It is usually used to indicate a problem where a wrong character has been typed.
In most terminals, if the Bell character (ASCII code 7, \a in C) is printed by the program, it will cause the terminal to ring its bell. This is a function of the terminal, and is independent of the programming language of the program, other than the ability to print a particular character to standard out.
| #Ring | Ring |
see char(7)
|
http://rosettacode.org/wiki/The_Twelve_Days_of_Christmas | The Twelve Days of Christmas | Task
Write a program that outputs the lyrics of the Christmas carol The Twelve Days of Christmas.
The lyrics can be found here.
(You must reproduce the words in the correct order, but case, format, and punctuation are left to your discretion.)
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
| #BASIC256 | BASIC256 | dim dia$ = {"first","second","third","fourth","fifth","sixth","seventh","eighth","ninth","tenth","eleventh","twelfth"}
dim gift$ = {"A partridge in a pear tree.","Two turtle doves and","Three french hens","Four calling birds","Five golden rings","Six geese a-laying","Seven swans a-swimming","Eight maids a-milking","Nine ladies dancing","Ten lords a-leaping","Eleven pipers piping","Twelve drummers drumming"}
for i = 0 to 11
print "On the "; dia$[i]; " dia of Christmas,"
print "My true love gave to me:"
for j = i to 1 step -1
print gift$[j]
next j
print
next i |
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
| #BCPL | BCPL | get "libhdr"
let ordinal(n) =
n=1 -> "first", n=2 -> "second", n=3 -> "third",
n=4 -> "fourth", n=5 -> "fifth", n=6 -> "sixth",
n=7 -> "seventh", n=8 -> "eighth", n=9 -> "ninth",
n=10 -> "tenth", n=11 -> "eleventh", n=12 -> "twelfth",
valof finish
let gift(n) =
n=1 -> "A partridge in a pear tree.",
n=2 -> "Two turtle doves, and",
n=3 -> "Three french hens,",
n=4 -> "Four calling birds,",
n=5 -> "Five golden rings,",
n=6 -> "Six geese a-laying,",
n=7 -> "Seven swans a-swimming,",
n=8 -> "Eight maids a-milking,",
n=9 -> "Nine ladies dancing,",
n=10 -> "Ten lords a-leaping,",
n=11 -> "Eleven pipers piping,",
n=12 -> "Twelve drummers drumming,",
valof finish
let verse(n) be
$( writef("On the %S day of Christmas,*N", ordinal(n))
writes("My true love gave to me:*N")
for i=n to 1 by -1 do writef("%S*N", gift(i))
wrch('*N')
$)
let start() be for n=1 to 12 do verse(n) |
http://rosettacode.org/wiki/Terminal_control/Hiding_the_cursor | Terminal control/Hiding the cursor | The task is to hide the cursor and show it again.
| #PicoLisp | PicoLisp | (call "tput" "civis") # Invisible
(wait 1000)
(call "tput" "cvvis") # Visible |
http://rosettacode.org/wiki/Terminal_control/Hiding_the_cursor | Terminal control/Hiding the cursor | The task is to hide the cursor and show it again.
| #PureBasic | PureBasic | #cursorSize = 10 ;use a full sized cursor
If OpenConsole()
Print("Press any key to toggle cursor: ")
EnableGraphicalConsole(1)
height = #cursorSize
ConsoleCursor(height)
Repeat
If Inkey()
height ! #cursorSize
ConsoleCursor(height)
EndIf
ForEver
EndIf |
http://rosettacode.org/wiki/Terminal_control/Hiding_the_cursor | Terminal control/Hiding the cursor | The task is to hide the cursor and show it again.
| #Python | Python | print("\x1b[?25l") # hidden
print("\x1b[?25h") # shown
|
http://rosettacode.org/wiki/Terminal_control/Hiding_the_cursor | Terminal control/Hiding the cursor | The task is to hide the cursor and show it again.
| #Quackery | Quackery | [ $ &print("\x1b[?25l",end='')& python ] is hide ( --> )
[ $ &print("\x1b[?25h",end='')& python ] is show ( --> ) |
http://rosettacode.org/wiki/Terminal_control/Hiding_the_cursor | Terminal control/Hiding the cursor | The task is to hide the cursor and show it again.
| #R | R | cat("\x1b[?25l") # Hide
Sys.sleep(2)
cat("\x1b[?25h") # Show |
http://rosettacode.org/wiki/Terminal_control/Hiding_the_cursor | Terminal control/Hiding the cursor | The task is to hide the cursor and show it again.
| #Racket | Racket |
#lang racket
(void (system "tput civis")) (sleep 2) (void (system "tput cvvis"))
|
http://rosettacode.org/wiki/Terminal_control/Inverse_video | Terminal control/Inverse video | Task
Display a word in inverse video (or reverse video) followed by a word in normal video.
| #Phix | Phix | --
-- demo\rosetta\Inverse_Video.exw
-- ================================
--
with javascript_semantics
text_color(BLACK)
bk_color(WHITE)
printf(1,"Inverse")
text_color(WHITE)
bk_color(BLACK)
printf(1," Video")
printf(1,"\n\npress enter to exit")
{} = wait_key()
|
http://rosettacode.org/wiki/Terminal_control/Inverse_video | Terminal control/Inverse video | Task
Display a word in inverse video (or reverse video) followed by a word in normal video.
| #PicoLisp | PicoLisp | (prin "abc")
(call "tput" "rev")
(prin "def") # These three chars are displayed in reverse video
(call "tput" "sgr0")
(prinl "ghi") |
http://rosettacode.org/wiki/Terminal_control/Inverse_video | Terminal control/Inverse video | Task
Display a word in inverse video (or reverse video) followed by a word in normal video.
| #Python | Python | #!/usr/bin/env python
print "\033[7mReversed\033[m Normal" |
http://rosettacode.org/wiki/Terminal_control/Inverse_video | Terminal control/Inverse video | Task
Display a word in inverse video (or reverse video) followed by a word in normal video.
| #Quackery | Quackery | [ $ 'print("\033[7m", end="")' python ] is inversetext ( --> )
[ $ 'print("\033[m", end="")' python ] is regulartext ( --> )
inversetext say "inverse video"
regulartext say " normal text" |
http://rosettacode.org/wiki/Terminal_control/Inverse_video | Terminal control/Inverse video | Task
Display a word in inverse video (or reverse video) followed by a word in normal video.
| #Racket | Racket |
#lang racket
(require (planet neil/charterm:3:0))
(with-charterm
(charterm-clear-screen)
(charterm-cursor 0 0)
(charterm-inverse)
(charterm-display "Hello")
(charterm-normal)
(charterm-display "World"))
|
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.
| #BBC_BASIC | BBC BASIC | dx% = @vdu.tr%[email protected]% : REM Width of text viewport in pixels
dy% = @vdu.tb%[email protected]% : REM Height of text viewport in pixels |
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.
| #C | C | #include <sys/ioctl.h> /* ioctl, TIOCGWINSZ */
#include <err.h> /* err */
#include <fcntl.h> /* open */
#include <stdio.h> /* printf */
#include <unistd.h> /* close */
int
main()
{
struct winsize ws;
int fd;
/* Open the controlling terminal. */
fd = open("/dev/tty", O_RDWR);
if (fd < 0)
err(1, "/dev/tty");
/* Get window size of terminal. */
if (ioctl(fd, TIOCGWINSZ, &ws) < 0)
err(1, "/dev/tty");
printf("%d rows by %d columns\n", ws.ws_row, ws.ws_col);
printf("(%d by %d pixels)\n", ws.ws_xpixel, ws.ws_ypixel);
close(fd);
return 0;
} |
http://rosettacode.org/wiki/Terminal_control/Dimensions | Terminal control/Dimensions | Determine the height and width of the terminal, and store this information into variables for subsequent use.
| #C.23 | C# |
static void Main(string[] args)
{
int bufferHeight = Console.BufferHeight;
int bufferWidth = Console.BufferWidth;
int windowHeight = Console.WindowHeight;
int windowWidth = Console.WindowWidth;
Console.Write("Buffer Height: ");
Console.WriteLine(bufferHeight);
Console.Write("Buffer Width: ");
Console.WriteLine(bufferWidth);
Console.Write("Window Height: ");
Console.WriteLine(windowHeight);
Console.Write("Window Width: ");
Console.WriteLine(windowWidth);
Console.ReadLine();
}
|
http://rosettacode.org/wiki/Terminal_control/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.
| #AArch64_Assembly | AArch64 Assembly |
/* ARM assembly AARCH64 Raspberry PI 3B */
/* program cursorMove64.s */
/*******************************************/
/* Constantes file */
/*******************************************/
/* for this file see task include a file in language AArch64 assembly*/
.include "../includeConstantesARM64.inc"
/* Initialized data */
.data
szMessStartPgm: .asciz "Program start \n"
szMessEndPgm: .asciz "Program normal end.\n"
szMessColorRed: .asciz "Color red.\n"
szCodeInit: .asciz "\033[0m" // color reinit
szCodeRed: .asciz "\033[31m" // color red
szCodeBlue: .asciz "\033[34m" // color blue
szMessMove: .asciz "\033[A\033[6CBlue Message up and 6 location right."
szMessMoveDown: .asciz "\033[31m\033[BRed text location down"
szMessTopLeft: .asciz "\033[;HTOP LEFT"
szCarriageReturn: .asciz "\n"
/* UnInitialized data */
.bss
/* code section */
.text
.global main
main:
ldr x0,qAdrszMessStartPgm // display start message
bl affichageMess
ldr x0,qAdrszCodeRed // color red
bl affichageMess
ldr x0,qAdrszMessColorRed
bl affichageMess
ldr x0,qAdrszCodeBlue
bl affichageMess
ldr x0,qAdrszMessMove
bl affichageMess
ldr x0,qAdrszMessMoveDown // move pointer down
bl affichageMess
ldr x0,qAdrszMessTopLeft
bl affichageMess
ldr x0,qAdrszCarriageReturn // start next line
bl affichageMess
ldr x0,qAdrszCodeInit // color reinitialize
bl affichageMess
ldr x0,qAdrszMessEndPgm // display end message
bl affichageMess
100: // standard end of the program
mov x0,0 // return code
mov x8,EXIT // request to exit program
svc 0 // perform system call
qAdrszMessStartPgm: .quad szMessStartPgm
qAdrszMessEndPgm: .quad szMessEndPgm
qAdrszCodeInit: .quad szCodeInit
qAdrszCodeRed: .quad szCodeRed
qAdrszCodeBlue: .quad szCodeBlue
qAdrszMessColorRed: .quad szMessColorRed
qAdrszMessMove: .quad szMessMove
qAdrszCarriageReturn: .quad szCarriageReturn
qAdrszMessMoveDown: .quad szMessMoveDown
qAdrszMessTopLeft: .quad szMessTopLeft
/********************************************************/
/* File Include fonctions */
/********************************************************/
/* for this file see task include a file in language AArch64 assembly */
.include "../includeARM64.inc"
|
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.
| #BaCon | BaCon | ' Cursor positioning, requires ANSI compliant terminal
GOTOXY 3,6
PRINT "Hello" |
http://rosettacode.org/wiki/Terminal_control/Cursor_positioning | Terminal control/Cursor positioning |
Task
Move the cursor to column 3, row 6, and display the word "Hello" (without the quotes), so that the letter H is in column 3 on row 6.
| #BASIC | BASIC | 10 VTAB 6: HTAB 3
20 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.
| #Befunge | Befunge | 0"olleHH3;6["39*>:#,_$@ |
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.
| #Blast | Blast | # This will display a message at a specific position on the terminal screen
.begin
cursor 6,3
display "Hello!"
return
# This is the end of the script |
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
| #BBC_BASIC | BBC BASIC | INSTALL @lib$ + "CLASSLIB"
REM Create a ternary class:
DIM trit{tor, tand, teqv, tnot, tnor, s, v}
DEF PRIVATE trit.s (t&) LOCAL t$():DIM t$(2):t$()="FALSE","MAYBE","TRUE":=t$(t&)
DEF PRIVATE trit.v (t$) = INSTR("FALSE MAYBE TRUE", t$) DIV 6
DEF trit.tnot (t$) = FN(trit.s)(2 - FN(trit.v)(t$))
DEF trit.tor (a$,b$) LOCAL t:t=FN(trit.v)(a$)ORFN(trit.v)(b$):=FN(trit.s)(t+(t>2))
DEF trit.tnor (a$,b$) = FN(trit.tnot)(FN(trit.tor)(a$,b$))
DEF trit.tand (a$,b$) = FN(trit.tnor)(FN(trit.tnot)(a$),FN(trit.tnot)(b$))
DEF trit.teqv (a$,b$) = FN(trit.tor)(FN(trit.tand)(a$,b$),FN(trit.tnor)(a$,b$))
PROC_class(trit{})
PROC_new(mytrit{}, trit{})
REM Test it:
PRINT "Testing NOT:"
PRINT "NOT FALSE = " FN(mytrit.tnot)("FALSE")
PRINT "NOT MAYBE = " FN(mytrit.tnot)("MAYBE")
PRINT "NOT TRUE = " FN(mytrit.tnot)("TRUE")
PRINT '"Testing OR:"
PRINT "FALSE OR FALSE = " FN(mytrit.tor)("FALSE","FALSE")
PRINT "FALSE OR MAYBE = " FN(mytrit.tor)("FALSE","MAYBE")
PRINT "FALSE OR TRUE = " FN(mytrit.tor)("FALSE","TRUE")
PRINT "MAYBE OR MAYBE = " FN(mytrit.tor)("MAYBE","MAYBE")
PRINT "MAYBE OR TRUE = " FN(mytrit.tor)("MAYBE","TRUE")
PRINT "TRUE OR TRUE = " FN(mytrit.tor)("TRUE","TRUE")
PRINT '"Testing AND:"
PRINT "FALSE AND FALSE = " FN(mytrit.tand)("FALSE","FALSE")
PRINT "FALSE AND MAYBE = " FN(mytrit.tand)("FALSE","MAYBE")
PRINT "FALSE AND TRUE = " FN(mytrit.tand)("FALSE","TRUE")
PRINT "MAYBE AND MAYBE = " FN(mytrit.tand)("MAYBE","MAYBE")
PRINT "MAYBE AND TRUE = " FN(mytrit.tand)("MAYBE","TRUE")
PRINT "TRUE AND TRUE = " FN(mytrit.tand)("TRUE","TRUE")
PRINT '"Testing EQV (similar to EOR):"
PRINT "FALSE EQV FALSE = " FN(mytrit.teqv)("FALSE","FALSE")
PRINT "FALSE EQV MAYBE = " FN(mytrit.teqv)("FALSE","MAYBE")
PRINT "FALSE EQV TRUE = " FN(mytrit.teqv)("FALSE","TRUE")
PRINT "MAYBE EQV MAYBE = " FN(mytrit.teqv)("MAYBE","MAYBE")
PRINT "MAYBE EQV TRUE = " FN(mytrit.teqv)("MAYBE","TRUE")
PRINT "TRUE EQV TRUE = " FN(mytrit.teqv)("TRUE","TRUE")
PROC_discard(mytrit{}) |
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).
| #Forth | Forth | 163 xemit \ , or
s" £" type |
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).
| #FreeBASIC | FreeBASIC | 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).
| #Go | Go | package main
import "fmt"
func main() {
fmt.Println("£")
} |
http://rosettacode.org/wiki/Terminal_control/Display_an_extended_character | Terminal control/Display an extended character | Task
Display an extended (non ASCII) character onto the terminal.
Specifically, display a £ (GBP currency sign).
| #Haskell | Haskell |
module Main where
main = do
putStrLn "£"
putStrLn "札幌"
|
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).
| #Icon_and_Unicon | Icon and Unicon |
procedure main ()
write ("£ " || char (163)) # £
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.
| #C.2B.2B | C++ | #include <iostream>
#include <fstream>
#include <string>
#include <vector>
#include <iomanip>
#include <boost/lexical_cast.hpp>
#include <boost/algorithm/string.hpp>
using std::cout;
using std::endl;
const int NumFlags = 24;
int main()
{
std::fstream file("readings.txt");
int badCount = 0;
std::string badDate;
int badCountMax = 0;
while(true)
{
std::string line;
getline(file, line);
if(!file.good())
break;
std::vector<std::string> tokens;
boost::algorithm::split(tokens, line, boost::is_space());
if(tokens.size() != NumFlags * 2 + 1)
{
cout << "Bad input file." << endl;
return 0;
}
double total = 0.0;
int accepted = 0;
for(size_t i = 1; i < tokens.size(); i += 2)
{
double val = boost::lexical_cast<double>(tokens[i]);
int flag = boost::lexical_cast<int>(tokens[i+1]);
if(flag > 0)
{
total += val;
++accepted;
badCount = 0;
}
else
{
++badCount;
if(badCount > badCountMax)
{
badCountMax = badCount;
badDate = tokens[0];
}
}
}
cout << tokens[0];
cout << " Reject: " << std::setw(2) << (NumFlags - accepted);
cout << " Accept: " << std::setw(2) << accepted;
cout << " Average: " << std::setprecision(5) << total / accepted << endl;
}
cout << endl;
cout << "Maximum number of consecutive bad readings is " << badCountMax << endl;
cout << "Ends on date " << badDate << endl;
} |
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.
| #Lua | Lua | #!/usr/bin/env lua
-- ISAAC - Lua 5.3
-- External Results
local randRsl = {};
local randCnt = 0;
-- Internal State
local mm = {};
local aa,bb,cc = 0,0,0;
-- Cap to maintain 32 bit maths
local cap = 0x100000000;
-- CipherMode
local ENCRYPT = 1;
local DECRYPT = 2;
function isaac()
cc = ( cc + 1 ) % cap; -- cc just gets incremented once per 256 results
bb = ( bb + cc ) % cap; -- then combined with bb
for i = 0,255 do
local x = mm[i];
local y;
local imod = i % 4;
if imod == 0 then aa = aa ~ (aa << 13);
elseif imod == 1 then aa = aa ~ (aa >> 6);
elseif imod == 2 then aa = aa ~ (aa << 2);
elseif imod == 3 then aa = aa ~ (aa >> 16);
end
aa = ( mm[(i+128)%256] + aa ) % cap;
y = ( mm[(x>>2) % 256] + aa + bb ) % cap;
mm[i] = y;
bb = ( mm[(y>>10)%256] + x ) % cap;
randRsl[i] = bb;
end
randCnt = 0; -- Prepare to use the first set of results.
end
function mix(a)
a[0] = ( a[0] ~ ( a[1] << 11 ) ) % cap; a[3] = ( a[3] + a[0] ) % cap; a[1] = ( a[1] + a[2] ) % cap;
a[1] = ( a[1] ~ ( a[2] >> 2 ) ) % cap; a[4] = ( a[4] + a[1] ) % cap; a[2] = ( a[2] + a[3] ) % cap;
a[2] = ( a[2] ~ ( a[3] << 8 ) ) % cap; a[5] = ( a[5] + a[2] ) % cap; a[3] = ( a[3] + a[4] ) % cap;
a[3] = ( a[3] ~ ( a[4] >> 16 ) ) % cap; a[6] = ( a[6] + a[3] ) % cap; a[4] = ( a[4] + a[5] ) % cap;
a[4] = ( a[4] ~ ( a[5] << 10 ) ) % cap; a[7] = ( a[7] + a[4] ) % cap; a[5] = ( a[5] + a[6] ) % cap;
a[5] = ( a[5] ~ ( a[6] >> 4 ) ) % cap; a[0] = ( a[0] + a[5] ) % cap; a[6] = ( a[6] + a[7] ) % cap;
a[6] = ( a[6] ~ ( a[7] << 8 ) ) % cap; a[1] = ( a[1] + a[6] ) % cap; a[7] = ( a[7] + a[0] ) % cap;
a[7] = ( a[7] ~ ( a[0] >> 9 ) ) % cap; a[2] = ( a[2] + a[7] ) % cap; a[0] = ( a[0] + a[1] ) % cap;
end
function randInit(flag)
-- The golden ratio in 32 bit
-- math.floor((((math.sqrt(5)+1)/2)%1)*2^32) == 2654435769 == 0x9e3779b9
local a = { [0] = 0x9e3779b9, 0x9e3779b9, 0x9e3779b9, 0x9e3779b9, 0x9e3779b9, 0x9e3779b9, 0x9e3779b9, 0x9e3779b9, };
aa,bb,cc = 0,0,0;
for i = 1,4 do mix(a) end -- Scramble it.
for i = 0,255,8 do -- Fill in mm[] with messy stuff.
if flag then -- Use all the information in the seed.
for j = 0,7 do
a[j] = ( a[j] + randRsl[i+j] ) % cap;
end
end
mix(a);
for j = 0,7 do
mm[i+j] = a[j];
end
end
if flag then
-- Do a second pass to make all of the seed affect all of mm.
for i = 0,255,8 do
for j = 0,7 do
a[j] = ( a[j] + mm[i+j] ) % cap;
end
mix(a);
for j = 0,7 do
mm[i+j] = a[j];
end
end
end
isaac(); -- Fill in the first set of results.
randCnt = 0; -- Prepare to use the first set of results.
end
-- Seed ISAAC with a given string.
-- The string can be any size. The first 256 values will be used.
function seedIsaac(seed,flag)
local seedLength = #seed;
for i = 0,255 do mm[i] = 0; end
for i = 0,255 do randRsl[i] = seed:byte(i+1,i+1) or 0; end
randInit(flag);
end
-- Get a random 32-bit value 0..MAXINT
function getRandom32Bit()
local result = randRsl[randCnt];
randCnt = randCnt + 1;
if randCnt > 255 then
isaac();
randCnt = 0;
end
return result;
end
-- Get a random character in printable ASCII range
function getRandomChar()
return getRandom32Bit() % 95 + 32;
end
-- Convert an ASCII string to a hexadecimal string.
function ascii2hex(source)
local ss = "";
for i = 1,#source do
ss = ss..string.format("%02X",source:byte(i,i));
end
return ss
end
-- XOR encrypt on random stream.
function vernam(msg)
local msgLength = #msg;
local destination = {};
for i = 1, msgLength do
destination[i] = string.char(getRandomChar() ~ msg:byte(i,i));
end
return table.concat(destination);
end
-- Caesar-shift a character <shift> places: Generalized Vigenere
function caesar(m, ch, shift, modulo, start)
local n
local si = 1
if m == DECRYPT then shift = shift*-1 ; end
n = (ch - start) + shift;
if n < 0 then si,n = -1,n*-1 ; end
n = ( n % modulo ) * si;
if n < 0 then n = n + modulo ; end
return start + n;
end
-- Vigenere mod 95 encryption & decryption.
function vigenere(msg,m)
local msgLength = #msg;
local destination = {};
for i = 1,msgLength do
destination[i] = string.char( caesar(m, msg:byte(i,i), getRandomChar(), 95, 32) );
end
return table.concat(destination);
end
function main()
local msg = "a Top Secret secret";
local key = "this is my secret key";
local xorCipherText, modCipherText, xorPlainText, modPlainText;
-- (1) Seed ISAAC with the key
seedIsaac(key, true);
-- (2) Encryption
-- (a) XOR (Vernam)
xorCipherText = vernam(msg);
-- (b) MOD (Vigenere)
modCipherText = vigenere(msg, ENCRYPT);
-- (3) Decryption
seedIsaac(key, true);
-- (a) XOR (Vernam)
xorPlainText = vernam(xorCipherText);
-- (b) MOD (Vigenere)
modPlainText = vigenere(modCipherText, DECRYPT);
-- Program output
print("Message: " .. msg);
print("Key : " .. key);
print("XOR : " .. ascii2hex(xorCipherText));
print("XOR dcr: " .. xorPlainText);
print("MOD : " .. ascii2hex(modCipherText));
print("MOD dcr: " .. modPlainText);
end
main()
|
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.)
| #Nim | Nim | import complex, rationals, math, fenv, sugar
func isInteger[T: Complex | Rational | SomeNumber](x: T; tolerance = 0f64): bool =
when T is Complex:
x.im == 0 and x.re.isInteger
elif T is Rational:
x.dup(reduce).den == 1
elif T is SomeFloat:
ceil(x) - x <= tolerance
elif T is SomeInteger:
true
# Floats.
assert not NaN.isInteger
assert not INF.isInteger # Indeed, "ceil(INF) - INF" is NaN.
assert not (-5e-2).isInteger
assert (-2.1e120).isInteger
assert 25.0.isInteger
assert not 24.999999.isInteger
assert 24.999999.isInteger(tolerance = 0.00001)
assert not (1f64 + epsilon(float64)).isInteger
assert not (1f32 - epsilon(float32)).isInteger
# Rationals.
assert not (5 // 3).isInteger
assert (9 // 3).isInteger
assert (-143 // 13).isInteger
# Unsigned integers.
assert 3u.isInteger
# Complex numbers.
assert not (1.0 + im 1.0).isInteger
assert (5.0 + im 0.0).isInteger |
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.)
| #ooRexx | ooRexx | /* REXX ---------------------------------------------------------------
* 22.06.2014 Walter Pachl using a complex data class
* ooRexx Distribution contains an elaborate complex class
* parts of which are used here
* see REXX for Extra Credit implementation
*--------------------------------------------------------------------*/
Numeric Digits 1000
Call test_integer .complex~new(1e+12,0e-3)
Call test_integer .complex~new(3.14)
Call test_integer .complex~new(1.00000)
Call test_integer .complex~new(33)
Call test_integer .complex~new(999999999)
Call test_integer .complex~new(99999999999)
Call test_integer .complex~new(1e272)
Call test_integer .complex~new(0)
Call test_integer .complex~new(1.000,-3)
Call test_integer .complex~new(1.000,-3.3)
Call test_integer .complex~new(,4)
Call test_integer .complex~new(2.00000000,+0)
Call test_integer .complex~new(,0)
Call test_integer .complex~new(333)
Call test_integer .complex~new(-1,-1)
Call test_integer .complex~new(1,1)
Call test_integer .complex~new(,.00)
Call test_integer .complex~new(,1)
Call test_integer .complex~new(0003,00.0)
Exit
test_integer:
Use Arg cpx
cpxa=left(changestr('+-',cpx,'-'),13) -- beautify representation
Select
When cpx~imaginary<>0 Then
Say cpxa 'is not an integer'
When datatype(cpx~real,'W') Then
Say cpxa 'is an integer'
Otherwise
Say cpxa 'is not an integer'
End
Return
::class complex
::method init /* initialize a complex number */
expose real imaginary /* expose the state data */
use Strict arg first=0, second=0 /* access the two numbers */
real = first + 0 /* force rounding */
imaginary = second + 0 /* force rounding on the second */
::method real /* return real part of a complex */
expose real /* access the state information */
return real /* return that value */
::method imaginary /* return imaginary part */
expose imaginary /* access the state information */
return imaginary /* return the value */
::method string /* format as a string value */
expose real imaginary /* get the state info */
return real'+'imaginary'i' /* format as real+imaginaryi */ |
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).
| #PHP | PHP | $handle = fopen ("mlijobs.txt", "rb");
$maxcount = 0;
$count = 0;
$times = array();
while (!feof($handle)) {
$buffer = fgets($handle);
$op = trim(substr($buffer,8,3));
switch ($op){
case 'IN':
$count--;
break;
case 'OUT':
$count++;
preg_match('/([\d|\/|_|:]+)/',$buffer,$time);
if($count>$maxcount){
$maxcount = $count;
$times = Array($time[0]);
}elseif($count == $maxcount){
$times[] = $time[0];
}
break;
}
}
fclose ($handle);
echo $maxcount . '<br>';
for($i=0;$i<count($times);$i++){
echo $times[$i] . '<br>';
} |
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.
| #jq | jq | # Test case 1:
.
1
1
# Test case 2:
1+1
null
2
# Test case 3 (with the wrong result):
1+1
null
0
# A test case with a function definition:
def factorial: if . <= 0 then 1 else . * ((. - 1) | factorial) end; factorial
3
6 |
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.
| #Jsish | Jsish | /* Palindrome detection, in Jsish */
function isPalindrome(str:string, exact:boolean=true) {
if (!exact) {
str = str.toLowerCase().replace(/[^a-z0-9]/g, '');
}
return str === str.split('').reverse().join('');
} |
http://rosettacode.org/wiki/Text_processing/2 | Text processing/2 | The following task concerns data that came from a pollution monitoring station with twenty-four instruments monitoring twenty-four aspects of pollution in the air. Periodically a record is added to the file, each record being a line of 49 fields separated by white-space, which can be one or more space or tab characters.
The fields (from the left) are:
DATESTAMP [ VALUEn FLAGn ] * 24
i.e. a datestamp followed by twenty-four repetitions of a floating-point instrument value and that instrument's associated integer flag. Flag values are >= 1 if the instrument is working and < 1 if there is some problem with it, in which case that instrument's value should be ignored.
A sample from the full data file readings.txt, which is also used in the Text processing/1 task, follows:
Data is no longer available at that link. Zipped mirror available here
1991-03-30 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1
1991-03-31 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 20.000 1 20.000 1 20.000 1 35.000 1 50.000 1 60.000 1 40.000 1 30.000 1 30.000 1 30.000 1 25.000 1 20.000 1 20.000 1 20.000 1 20.000 1 20.000 1 35.000 1
1991-03-31 40.000 1 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2
1991-04-01 0.000 -2 13.000 1 16.000 1 21.000 1 24.000 1 22.000 1 20.000 1 18.000 1 29.000 1 44.000 1 50.000 1 43.000 1 38.000 1 27.000 1 27.000 1 24.000 1 23.000 1 18.000 1 12.000 1 13.000 1 14.000 1 15.000 1 13.000 1 10.000 1
1991-04-02 8.000 1 9.000 1 11.000 1 12.000 1 12.000 1 12.000 1 27.000 1 26.000 1 27.000 1 33.000 1 32.000 1 31.000 1 29.000 1 31.000 1 25.000 1 25.000 1 24.000 1 21.000 1 17.000 1 14.000 1 15.000 1 12.000 1 12.000 1 10.000 1
1991-04-03 10.000 1 9.000 1 10.000 1 10.000 1 9.000 1 10.000 1 15.000 1 24.000 1 28.000 1 24.000 1 18.000 1 14.000 1 12.000 1 13.000 1 14.000 1 15.000 1 14.000 1 15.000 1 13.000 1 13.000 1 13.000 1 12.000 1 10.000 1 10.000 1
Task
Confirm the general field format of the file.
Identify any DATESTAMPs that are duplicated.
Report the number of records that have good readings for all instruments.
| #Wren | Wren | import "io" for File
import "/pattern" for Pattern
import "/fmt" for Fmt
import "/sort" for Sort
var p = Pattern.new("+1/s")
var fileName = "readings.txt"
var lines = File.read(fileName).trimEnd().split("\r\n")
var count = 0
var invalid = 0
var allGood = 0
var map = {}
for (line in lines) {
count = count + 1
var fields = p.splitAll(line)
var date = fields[0]
if (fields.count == 49) {
map[date] = map.containsKey(date) ? map[date] + 1 : 1
var good = 0
var i = 2
while (i < fields.count) {
if (Num.fromString(fields[i]) >= 1) good = good + 1
i = i + 2
}
if (good == 24) allGood = allGood + 1
} else {
invalid = invalid + 1
}
}
Fmt.print("File = $s", fileName)
System.print("\nDuplicated dates:")
var keys = map.keys.toList
Sort.quick(keys)
for (k in keys) {
var v = map[k]
if (v > 1) Fmt.print(" $s ($d times)", k, v)
}
Fmt.print("\nTotal number of records : $d", count)
var percent = invalid/count * 100
Fmt.print("Number of invalid records : $d ($5.2f)\%", invalid, percent)
percent = allGood/count * 100
Fmt.print("Number which are all good : $d ($5.2f)\%", allGood, percent) |
http://rosettacode.org/wiki/Terminal_control/Ringing_the_terminal_bell | Terminal control/Ringing the terminal bell |
Task
Make the terminal running the program ring its "bell".
On modern terminal emulators, this may be done by playing some other sound which might or might not be configurable, or by flashing the title bar or inverting the colors of the screen, but was classically a physical bell within the terminal. It is usually used to indicate a problem where a wrong character has been typed.
In most terminals, if the Bell character (ASCII code 7, \a in C) is printed by the program, it will cause the terminal to ring its bell. This is a function of the terminal, and is independent of the programming language of the program, other than the ability to print a particular character to standard out.
| #Ruby | Ruby | print "\a" |
http://rosettacode.org/wiki/Terminal_control/Ringing_the_terminal_bell | Terminal control/Ringing the terminal bell |
Task
Make the terminal running the program ring its "bell".
On modern terminal emulators, this may be done by playing some other sound which might or might not be configurable, or by flashing the title bar or inverting the colors of the screen, but was classically a physical bell within the terminal. It is usually used to indicate a problem where a wrong character has been typed.
In most terminals, if the Bell character (ASCII code 7, \a in C) is printed by the program, it will cause the terminal to ring its bell. This is a function of the terminal, and is independent of the programming language of the program, other than the ability to print a particular character to standard out.
| #Rust | Rust | fn main() {
print!("\x07");
} |
http://rosettacode.org/wiki/Terminal_control/Ringing_the_terminal_bell | Terminal control/Ringing the terminal bell |
Task
Make the terminal running the program ring its "bell".
On modern terminal emulators, this may be done by playing some other sound which might or might not be configurable, or by flashing the title bar or inverting the colors of the screen, but was classically a physical bell within the terminal. It is usually used to indicate a problem where a wrong character has been typed.
In most terminals, if the Bell character (ASCII code 7, \a in C) is printed by the program, it will cause the terminal to ring its bell. This is a function of the terminal, and is independent of the programming language of the program, other than the ability to print a particular character to standard out.
| #Scala | Scala | java.awt.Toolkit.getDefaultToolkit().beep() |
http://rosettacode.org/wiki/Terminal_control/Ringing_the_terminal_bell | Terminal control/Ringing the terminal bell |
Task
Make the terminal running the program ring its "bell".
On modern terminal emulators, this may be done by playing some other sound which might or might not be configurable, or by flashing the title bar or inverting the colors of the screen, but was classically a physical bell within the terminal. It is usually used to indicate a problem where a wrong character has been typed.
In most terminals, if the Bell character (ASCII code 7, \a in C) is printed by the program, it will cause the terminal to ring its bell. This is a function of the terminal, and is independent of the programming language of the program, other than the ability to print a particular character to standard out.
| #Seed7 | Seed7 | $ include "seed7_05.s7i";
const proc: main is func
begin
write("\a");
end func; |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.