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/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
| #Ada | Ada | package Logic is
type Ternary is (True, Unknown, False);
-- logic functions
function "and"(Left, Right: Ternary) return Ternary;
function "or"(Left, Right: Ternary) return Ternary;
function "not"(T: Ternary) return Ternary;
function Equivalent(Left, Right: Ternary) return Ternary;
function Implies(Condition, Conclusion: Ternary) return Ternary;
-- conversion functions
function To_Bool(X: Ternary) return Boolean;
function To_Ternary(B: Boolean) return Ternary;
function Image(Value: Ternary) return Character;
end Logic; |
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).
| #ACL2 | ACL2 | (cw "£") |
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).
| #Action.21 | Action! | PROC Main()
BYTE CHBAS=$02F4 ;Character Base Register
CHBAS=$CC ;set the international character set
Position(2,2)
Put(8) ;print the GBP currency sign
RETURN |
http://rosettacode.org/wiki/Terminal_control/Display_an_extended_character | Terminal control/Display an extended character | Task
Display an extended (non ASCII) character onto the terminal.
Specifically, display a £ (GBP currency sign).
| #Ada | Ada | with Ada.Text_IO; use Ada.Text_IO;
with Ada.Characters.Latin_1;
procedure Pound is
begin
Put(Ada.Characters.Latin_1.Pound_Sign);
end Pound; |
http://rosettacode.org/wiki/Terminal_control/Display_an_extended_character | Terminal control/Display an extended character | Task
Display an extended (non ASCII) character onto the terminal.
Specifically, display a £ (GBP currency sign).
| #Arturo | Arturo | print "£" |
http://rosettacode.org/wiki/Terminal_control/Display_an_extended_character | Terminal control/Display an extended character | Task
Display an extended (non ASCII) character onto the terminal.
Specifically, display a £ (GBP currency sign).
| #AWK | AWK | BEGIN { print "£" } |
http://rosettacode.org/wiki/Text_processing/1 | Text processing/1 | This task has been flagged for clarification. Code on this page in its current state may be flagged incorrect once this task has been clarified. See this page's Talk page for discussion.
Often data is produced by one program, in the wrong format for later use by another program or person. In these situations another program can be written to parse and transform the original data into a format useful to the other. The term "Data Munging" is often used in programming circles for this task.
A request on the comp.lang.awk newsgroup led to a typical data munging task:
I have to analyse data files that have the following format:
Each row corresponds to 1 day and the field logic is: $1 is the date,
followed by 24 value/flag pairs, representing measurements at 01:00,
02:00 ... 24:00 of the respective day. In short:
<date> <val1> <flag1> <val2> <flag2> ... <val24> <flag24>
Some test data is available at:
... (nolonger available at original location)
I have to sum up the values (per day and only valid data, i.e. with
flag>0) in order to calculate the mean. That's not too difficult.
However, I also need to know what the "maximum data gap" is, i.e. the
longest period with successive invalid measurements (i.e values with
flag<=0)
The data is free to download and use and is of this format:
Data is no longer available at that link. Zipped mirror available here (offsite mirror).
1991-03-30 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1
1991-03-31 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 20.000 1 20.000 1 20.000 1 35.000 1 50.000 1 60.000 1 40.000 1 30.000 1 30.000 1 30.000 1 25.000 1 20.000 1 20.000 1 20.000 1 20.000 1 20.000 1 35.000 1
1991-03-31 40.000 1 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2
1991-04-01 0.000 -2 13.000 1 16.000 1 21.000 1 24.000 1 22.000 1 20.000 1 18.000 1 29.000 1 44.000 1 50.000 1 43.000 1 38.000 1 27.000 1 27.000 1 24.000 1 23.000 1 18.000 1 12.000 1 13.000 1 14.000 1 15.000 1 13.000 1 10.000 1
1991-04-02 8.000 1 9.000 1 11.000 1 12.000 1 12.000 1 12.000 1 27.000 1 26.000 1 27.000 1 33.000 1 32.000 1 31.000 1 29.000 1 31.000 1 25.000 1 25.000 1 24.000 1 21.000 1 17.000 1 14.000 1 15.000 1 12.000 1 12.000 1 10.000 1
1991-04-03 10.000 1 9.000 1 10.000 1 10.000 1 9.000 1 10.000 1 15.000 1 24.000 1 28.000 1 24.000 1 18.000 1 14.000 1 12.000 1 13.000 1 14.000 1 15.000 1 14.000 1 15.000 1 13.000 1 13.000 1 13.000 1 12.000 1 10.000 1 10.000 1
Only a sample of the data showing its format is given above. The full example file may be downloaded here.
Structure your program to show statistics for each line of the file, (similar to the original Python, Perl, and AWK examples below), followed by summary statistics for the file. When showing example output just show a few line statistics and the full end summary.
| #AutoHotkey | AutoHotkey | # Author AlephX Aug 17 2011
SetFormat, float, 4.2
SetFormat, FloatFast, 4.2
data = %A_scriptdir%\readings.txt
result = %A_scriptdir%\results.txt
totvalid := 0
totsum := 0
totavg:= 0
Loop, Read, %data%, %result%
{
sum := 0
Valid := 0
Couples := 0
Lines := A_Index
Loop, parse, A_LoopReadLine, %A_Tab%
{
;MsgBox, Field number %A_Index% is %A_LoopField%
if A_index = 1
{
Date := A_LoopField
Counter := 0
}
else
{
Counter++
couples := Couples + 0.5
if Counter = 1
{
value := A_LoopField / 1
}
else
{
if A_loopfield > 0
{
Sum := Sum + value
Valid++
if (wrong > maxwrong)
{
maxwrong := wrong
lastwrongdate := currwrongdate
startwrongdate := firstwrongdate
startoccurrence := firstoccurrence
lastoccurrence := curroccurrence
}
wrong := 0
}
else
{
wrong++
currwrongdate := date
curroccurrence := (A_index-1) / 2
if (wrong = 1)
{
firstwrongdate := date
firstoccurrence := curroccurrence
}
}
Counter := 0
}
}
}
avg := sum / valid
TotValid := Totvalid+valid
TotSum := Totsum+sum
FileAppend, Day: %date% sum: %sum% avg: %avg% Readings: %valid%/%couples%`n
}
Totavg := TotSum / TotValid
FileAppend, `n`nDays %Lines%`nMaximal wrong readings: %maxwrong% from %startwrongdate% at %startoccurrence% to %lastwrongdate% at %lastoccurrence%`n`n, %result%
FileAppend, Valid readings: %TotValid%`nTotal Value: %TotSUm%`nAverage: %TotAvg%, %result% |
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.
| #Ksh | Ksh |
#!/bin/ksh
# Determine the character displayed on the screen at column 3, row 6 and
# store that character in a variable.
#
# Use a group of functions "shellcurses"
# # Variables:
#
FPATH="/usr/local/functions/shellcurses/"
rst="�[0m"
red="�[31m"
whi="�[37m"
integer row=${1:-6} col=${2:-3} # Allow command line row col input
# # 10x10 grid of random digits
#
typeset -A grid
for ((i=0; i<10; i++)); do
for ((j=0; j<10; j++)); do
(( grid[${i}][${j}] = (RANDOM % 9) + 1 ))
done
done
# # Functions:
#
######
# main #
######
# # Initialize the curses screen
#
initscr ; export MAX_LINES MAX_COLS
# # Display the random number grid with target in red
#
clear
for ((i=1; i<=10; i++)); do
for ((j=1; j<=10; j++)); do
colr=${whi}
(( i == row )) && (( j == col )) && colr=${red}
mvaddstr ${i} ${j} "${colr}${grid[$((i-1))][$((j-1))]}${rst}"
done
done
str=$(rtnch ${row} ${col}) # return char at (row, col) location
mvaddstr 12 1 "Digit at (${row},${col}) = ${str}" # Display result
move 14 1
refresh
endwin |
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.
| #Nim | Nim | import random, sequtils, strutils
import ncurses
randomize()
let win = initscr()
assert not win.isNil, "Unable to initialize."
for y in 0..9:
mvaddstr(y.cint, 0, newSeqWith(10, sample({'0'..'9', 'a'..'z'})).join())
let row = rand(9).cint
let col = rand(9).cint
let ch = win.mvwinch(row, col)
mvaddstr(row, col + 11, "The character at ($1, $2) is $3.".format(row, col, chr(ch)))
mvaddstr(11, 0, "Press any key to quit.")
refresh()
discard getch()
endwin() |
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.
| #Perl | Perl | # 20200917 added Perl programming solution
use strict;
use warnings;
use Curses;
initscr or die;
my $win = Curses->new;
foreach my $row (0..9) {
$win->addstr( $row , 0, join('', map { chr(int(rand(50)) + 41) } (0..9)))
};
my $icol = 3 - 1;
my $irow = 6 - 1;
my $ch = $win->inch($irow,$icol);
$win->addstr( $irow, $icol+10, 'Character at column 3, row 6 = '.$ch );
$win->addstr( LINES() - 2, 2, "Press any key to exit..." );
$win->getch;
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.
| #Haskell | Haskell | import Data.Array (Array, (!), (//), array, elems)
import Data.Word (Word, Word32)
import Data.Bits (shift, xor)
import Data.Char (toUpper)
import Data.List (unfoldr)
import Numeric (showHex)
type IArray = Array Word32 Word32
data IsaacState = IState
{ randrsl :: IArray
, randcnt :: Word32
, mm :: IArray
, aa :: Word32
, bb :: Word32
, cc :: Word32
}
instance Show IsaacState where
show (IState _ cnt _ a b c) =
show cnt ++ " " ++ show a ++ " " ++ show b ++ " " ++ show c
toHex :: Char -> String
toHex c = showHex (fromEnum c) ""
hexify :: String -> String
hexify = map toUpper . concatMap toHex
toNum :: Char -> Word32
toNum = fromIntegral . fromEnum
toChar :: Word32 -> Char
toChar = toEnum . fromIntegral
golden :: Word32
golden = 0x9e3779b9
-- Mix up an ordering of words.
mix :: [Word32] -> [Word32]
mix set = foldl aux set [11, -2, 8, -16, 10, -4, 8, -9]
where
aux [a, b, c, d, e, f, g, h] x = [b + c, c, d + a_, e, f, g, h, a_]
where
a_ = a `xor` (b `shift` x)
-- Generate the next 256 words.
isaac :: IsaacState -> IsaacState
isaac (IState rsl _ m a b c) = IState rsl_ 0 m_ a_ b_ c_
where
c_ = c + 1
(rsl_, m_, a_, b_) =
foldl aux (rsl, m, a, b) $ zip [0 .. 255] $ cycle [13, -6, 2, -16]
aux (rsl, m, a, b) (i, s) = (rsl_, m_, a_, b_)
where
x = m ! i
a_ = (a `xor` (a `shift` s)) + m ! ((i + 128) `mod` 256)
y = a_ + b + m ! ((x `shift` (-2)) `mod` 256)
m_ = m // [(i, y)]
b_ = x + m_ ! ((y `shift` (-10)) `mod` 256)
rsl_ = rsl // [(i, b_)]
-- Given a seed value in randrsl, initialize/mixup the state.
randinit :: IsaacState -> Bool -> IsaacState
randinit state flag = isaac (IState randrsl_ 0 m 0 0 0)
where
firstSet = iterate mix (replicate 8 golden) !! 4
iter _ _ [] = []
iter flag set rsl =
let (rslH, rslT) = splitAt 8 rsl
set_ =
mix $
if flag
then zipWith (+) set rslH
else set
in set_ ++ iter flag set_ rslT
randrsl_ = randrsl state
firstPass = iter flag firstSet $ elems randrsl_
set_ = drop (256 - 8) firstPass
secondPass =
if flag
then iter True set_ firstPass
else firstPass
m = array (0, 255) $ zip [0 ..] secondPass
-- Given a string seed, optionaly use it to generate a new state.
seed :: String -> Bool -> IsaacState
seed key flag =
let m = array (0, 255) $ zip [0 .. 255] $ repeat 0
rsl = m // zip [0 ..] (map toNum key)
state = IState rsl 0 m 0 0 0
in randinit state flag
-- Produce a random word and the next state from the given state.
random :: IsaacState -> (Word32, IsaacState)
random state@(IState rsl cnt m a b c) =
let r = rsl ! cnt
state_ =
if cnt + 1 > 255
then isaac $ IState rsl 0 m a b c
else IState rsl (cnt + 1) m a b c
in (r, state_)
-- Produce a stream of random words from the given state.
randoms :: IsaacState -> [Word32]
randoms = unfoldr $ Just . random
-- Produce a random printable/typable character in the ascii range
-- and the next state from the given state.
randA :: IsaacState -> (Char, IsaacState)
randA state =
let (r, state_) = random state
in (toEnum $ fromIntegral $ (r `mod` 95) + 32, state_)
-- Produce a stream of printable characters from the given state.
randAs :: IsaacState -> String
randAs = unfoldr $ Just . randA
-- Vernam encode/decode a string with the given state.
vernam :: IsaacState -> String -> String
vernam state msg = map toChar $ zipWith xor msg_ randAs_
where
msg_ = map toNum msg
randAs_ = map toNum $ randAs state
main :: IO ()
main = do
let msg = "a Top Secret secret"
key = "this is my secret key"
st = seed key True
ver = vernam st msg
unver = vernam st ver
putStrLn $ "Message: " ++ msg
putStrLn $ "Key : " ++ key
putStrLn $ "XOR : " ++ hexify ver
putStrLn $ "XOR dcr: " ++ unver |
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.)
| #Haskell | Haskell | import Data.Decimal
import Data.Ratio
import Data.Complex |
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.)
| #J | J | isInt =: (= <.) *. (= {.@+.) |
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).
| #OCaml | OCaml | let () =
let out = ref 0 in
let max_out = ref(-1) in
let max_times = ref [] in
let ic = open_in "mlijobs.txt" in
try while true do
let line = input_line ic in
let io, date, n =
Scanf.sscanf line
"License %3[IN OUT] %_c %19[0-9/:_] for job %d"
(fun io date n -> (io, date, n))
in
if io = "OUT" then incr out else decr out;
if !out > !max_out then
( max_out := !out;
max_times := [date]; )
else if !out = !max_out then
max_times := date :: !max_times;
done
with End_of_file ->
close_in ic;
Printf.printf
"Maximum simultaneous license use is %d \
at the following times:\n" !max_out;
List.iter print_endline !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.
| #FreeBASIC | FreeBASIC |
Sub StrReverse(Byref text As String)
Dim As Integer x, lt = Len(text)
For x = 0 To lt Shr 1 - 1
Swap text[x], text[lt - x - 1]
Next x
End Sub
Sub Replace(Byref T As String, Byref I As String, Byref S As String, Byval A As Integer = 1)
Var p = Instr(A, T, I), li = Len(I), ls = Len(S) : If li = ls Then li = 0
Do While p
If li Then T = Left(T, p - 1) & S & Mid(T, p + li) Else Mid(T, p) = S
p = Instr(p + ls, T, I)
Loop
End Sub
Function IsPalindrome(Byval txt As String) As Boolean
Dim As String tempTxt = Lcase(txt), copyTxt = Lcase(txt)
Replace(tempTxt, " ", "")
Replace(copyTxt, " ", "")
StrReverse(tempTxt)
If tempTxt = copyTxt Then
Color 10
Return true
Else
Color 12
Return false
End If
End Function
'--- Programa Principal ---
Dim As String a(10) => {"abba", "mom", "dennis sinned", "Un roc lamina l animal cornu", _
"palindrome", "ba _ ab", "racecars", "racecar", "wombat", "in girum imus nocte et consumimur igni"}
Print !"¨Pal¡ndromos?\n"
For i As Byte = 0 To Ubound(a)-1
Print a(i) & " -> ";
Print IsPalindrome((a(i)))
Color 7
Next i
Sleep
|
http://rosettacode.org/wiki/Text_processing/2 | Text processing/2 | The following task concerns data that came from a pollution monitoring station with twenty-four instruments monitoring twenty-four aspects of pollution in the air. Periodically a record is added to the file, each record being a line of 49 fields separated by white-space, which can be one or more space or tab characters.
The fields (from the left) are:
DATESTAMP [ VALUEn FLAGn ] * 24
i.e. a datestamp followed by twenty-four repetitions of a floating-point instrument value and that instrument's associated integer flag. Flag values are >= 1 if the instrument is working and < 1 if there is some problem with it, in which case that instrument's value should be ignored.
A sample from the full data file readings.txt, which is also used in the Text processing/1 task, follows:
Data is no longer available at that link. Zipped mirror available here
1991-03-30 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1
1991-03-31 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 20.000 1 20.000 1 20.000 1 35.000 1 50.000 1 60.000 1 40.000 1 30.000 1 30.000 1 30.000 1 25.000 1 20.000 1 20.000 1 20.000 1 20.000 1 20.000 1 35.000 1
1991-03-31 40.000 1 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2
1991-04-01 0.000 -2 13.000 1 16.000 1 21.000 1 24.000 1 22.000 1 20.000 1 18.000 1 29.000 1 44.000 1 50.000 1 43.000 1 38.000 1 27.000 1 27.000 1 24.000 1 23.000 1 18.000 1 12.000 1 13.000 1 14.000 1 15.000 1 13.000 1 10.000 1
1991-04-02 8.000 1 9.000 1 11.000 1 12.000 1 12.000 1 12.000 1 27.000 1 26.000 1 27.000 1 33.000 1 32.000 1 31.000 1 29.000 1 31.000 1 25.000 1 25.000 1 24.000 1 21.000 1 17.000 1 14.000 1 15.000 1 12.000 1 12.000 1 10.000 1
1991-04-03 10.000 1 9.000 1 10.000 1 10.000 1 9.000 1 10.000 1 15.000 1 24.000 1 28.000 1 24.000 1 18.000 1 14.000 1 12.000 1 13.000 1 14.000 1 15.000 1 14.000 1 15.000 1 13.000 1 13.000 1 13.000 1 12.000 1 10.000 1 10.000 1
Task
Confirm the general field format of the file.
Identify any DATESTAMPs that are duplicated.
Report the number of records that have good readings for all instruments.
| #Sidef | Sidef | var good_records = 0;
var dates = Hash();
ARGF.each { |line|
var m = /^(\d\d\d\d-\d\d-\d\d)((?:\h+\d+\.\d+\h+-?\d+){24})\s*$/.match(line);
m || (warn "Bad format at line #{$.}"; next);
dates{m[0]} := 0 ++;
var i = 0;
m[1].words.all{|n| i++.is_even || (n.to_num >= 1) } && ++good_records;
}
say "#{good_records} good records out of #{$.} total";
say 'Repeated timestamps:';
say dates.to_a.grep{ .value > 1 }.map { .key }.sort.join("\n"); |
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.
| #Objeck | Objeck | 7->As(Char)->PrintLine(); |
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.
| #PARI.2FGP | PARI/GP | \\ Ringing the terminal bell.
\\ 8/14/2016 aev
Strchr(7) \\ press <Enter> |
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.
| #Pascal | Pascal | 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.
| #Perl | Perl | print "\a"; |
http://rosettacode.org/wiki/The_Twelve_Days_of_Christmas | The Twelve Days of Christmas | Task
Write a program that outputs the lyrics of the Christmas carol The Twelve Days of Christmas.
The lyrics can be found here.
(You must reproduce the words in the correct order, but case, format, and punctuation are left to your discretion.)
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
| #AutoHotkey | AutoHotkey | nth := ["first","second","third","fourth","fifth","sixth","seventh","eighth","ninth","tenth","eleventh","twelfth"]
lines := ["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"]
full:="", mid:=""
loop % lines.MaxIndex()
{
top:="On the " . nth[A_Index] . " day of Christmas,`nMy true love gave to me:"
mid:= lines[A_Index] . "`n" . mid
full:= full . top . "`n" . mid . ((A_Index<lines.MaxIndex())?"`n":"")
}
MsgBox % full |
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.
| #Racket | Racket |
#lang racket
(require racket/system)
(define (flash str)
(system "tput smcup")
(displayln str)
(sleep 2)
(system "tput rmcup")
(void))
(flash "Hello world.")
|
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.
| #Raku | Raku | print "\e[?1049h\e[H";
say "Alternate buffer!";
for 5,4...1 {
print "\rGoing back in: $_";
sleep 1;
}
print "\e[?1049l"; |
http://rosettacode.org/wiki/Terminal_control/Preserve_screen | Terminal control/Preserve screen |
Task
Clear the screen, output something on the display, and then restore the screen to the preserved state that it was in before the task was carried out.
There is no requirement to change the font or kerning in this task, however character decorations and attributes are expected to be preserved. If the implementer decides to change the font or kerning during the display of the temporary screen, then these settings need to be restored prior to exit.
| #REXX | REXX | /*REXX program saves the screen contents and also the cursor location, then clears the */
/*──── screen, writes a half screen of ~~~ lines, and then restores the original screen.*/
parse value scrsize() with sd sw . /*determine the size of terminal screen*/
parse value cursor(1,1) with curRow curCol . /*also, find the location of the cursor*/
do original=1 for sd /*obtain the original screen contents. */
@line.original=scrRead(original,1, sw) /*obtain a line of the terminal screen.*/
end /*original*/ /* [↑] obtains SD number of lines. */
'CLS' /*start with a clean slate on terminal.*/
do sd % 2 /*write a line of ~~~ for half of scr. */
say '~~~' /*writes ~~~ starting at top of screen.*/
end /*sd % 2*/ /* [↑] this shows ~~~ will be overlaid*/
/*no need to clear the screen here. */
do restore=1 for sd /*restore original screen from @line. */
call scrWrite restore,1, @line.restore /*write to terminal the original lines.*/
end /*restore*/ /* [↑] writes (restores) SD lines. */
/*stick a fork in it, we're all done. */
call cursor curRow, curCol /*restore the original cursor position.*/ |
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.
| #Rust | Rust | use std::io::{stdout, Write};
use std::time::Duration;
fn main() {
let mut output = stdout();
print!("\x1b[?1049h\x1b[H");
println!("Alternate screen buffer");
for i in (1..=5).rev() {
print!("\rgoing back in {}...", i);
output.flush().unwrap();
std::thread::sleep(Duration::from_secs(1));
}
print!("\x1b[?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.
| #C | C |
/* Please note that curs_set is terminal dependent. */
#include<curses.h>
#include<stdio.h>
int
main ()
{
printf
("At the end of this line you will see the cursor, process will sleep for 5 seconds.");
napms (5000);
curs_set (0);
printf
("\nAt the end of this line you will NOT see the cursor, process will again sleep for 5 seconds.");
napms (5000);
printf ("\nGoodbye.");
return 0;
}
|
http://rosettacode.org/wiki/Terminal_control/Hiding_the_cursor | Terminal control/Hiding the cursor | The task is to hide the cursor and show it again.
| #C.23 | C# | static void Main(string[] args)
{
Console.Write("At the end of this line you will see the cursor, process will sleep for 5 seconds.");
System.Threading.Thread.Sleep(5000);
Console.CursorVisible = false;
Console.WriteLine();
Console.Write("At the end of this line you will not see the cursor, process will sleep for 5 seconds.");
System.Threading.Thread.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.
| #C.2B.2B | C++ |
#include <Windows.h>
int main()
{
bool showCursor = false;
HANDLE std_out = GetStdHandle(STD_OUTPUT_HANDLE); // Get standard output
CONSOLE_CURSOR_INFO cursorInfo; //
GetConsoleCursorInfo(out, &cursorInfo); // Get cursorinfo from output
cursorInfo.bVisible = showCursor; // Set flag visible.
SetConsoleCursorInfo(out, &cursorInfo); // Apply changes
}
|
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.
| #BaCon | BaCon | COLOR INVERSE
PRINT "a word"
COLOR RESET
PRINT "a word" |
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.
| #BASIC | BASIC | INVERSE:?"ROSETTA";:NORMAL:?" CODE" |
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.
| #Befunge | Befunge | 0"lamroNm["39*"esrevnIm7["39*>:#,_$@ |
http://rosettacode.org/wiki/Terminal_control/Inverse_video | Terminal control/Inverse video | Task
Display a word in inverse video (or reverse video) followed by a word in normal video.
| #C | C | #include <stdio.h>
int main()
{
printf("\033[7mReversed\033[m Normal\n");
return 0;
} |
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
| #ALGOL_68 | ALGOL 68 | # -*- coding: utf-8 -*- #
INT trit width = 1, trit base = 3;
MODE TRIT = STRUCT(BITS trit);
CO FORMAT trit fmt = $c("?","⌈","⌊",#|"~"#)$; CO
# These values treated are as per "Balanced ternary" #
# eg true=1, maybe=0, false=-1 #
TRIT true =INITTRIT 4r1, maybe=INITTRIT 4r0,
false=INITTRIT 4r2;
# Warning: redefines standard builtins flip & flop #
LONGCHAR flap="?", flip="⌈", flop="⌊";
OP REPR = (TRIT t)LONGCHAR:
[]LONGCHAR(flap, flip, flop)[1+ABS trit OF t];
############################################
# Define some OPerators for coercing MODES #
############################################
OP INITTRIT = (BOOL in)TRIT:
(in|true|false);
OP INITBOOL = (TRIT in)BOOL:
(trit OF in=trit OF true|TRUE|:trit OF in=trit OF false|FALSE|
raise value error(("vague TRIT to BOOL coercion: """, REPR in,""""));~
);
OP B = (TRIT in)BOOL: INITBOOL in;
# These values treated are as per "Balanced ternary" #
# n.b true=1, maybe=0, false=-1 #
# Warning: BOOL ABS FALSE (0) is not the same as TRIT ABS false (-1) #
OP INITINT = (TRIT t)INT:
CASE 1+ABS trit OF t
IN #maybe# 0, #true # 1, #false#-1
OUT raise value error(("invalid TRIT value",REPR t)); ~
ESAC;
OP INITTRIT = (INT in)TRIT: (
TRIT out;
trit OF out:= trit OF
CASE 2+in
IN false, maybe, true
OUT raise value error(("invalid TRIT value",in)); ~
ESAC;
out
);
OP INITTRIT = (BITS b)TRIT:
(TRIT out; trit OF out:=b; out);
##################################################
# Define the LOGICAL OPerators for the TRIT MODE #
##################################################
MODE LOGICAL = TRIT;
PR READ "Template_operators_logical_mixin.a68" PR
COMMENT
Kleene logic truth tables:
END COMMENT
OP AND = (TRIT a,b)TRIT: (
[,]TRIT(
# ∧ ## false, maybe, true #
#false# (false, false, false),
#maybe# (false, maybe, maybe),
#true # (false, maybe, true )
)[@-1,@-1][INITINT a, INITINT b]
);
OP OR = (TRIT a,b)TRIT: (
[,]TRIT(
# ∨ ## false, maybe, true #
#false# (false, maybe, true),
#maybe# (maybe, maybe, true),
#true # (true, true, true)
)[@-1,@-1][INITINT a, INITINT b]
);
PRIO IMPLIES = 1; # PRIO = 1.9 #
OP IMPLIES = (TRIT a,b)TRIT: (
[,]TRIT(
# ⊃ ## false, maybe, true #
#false# (true, true, true),
#maybe# (maybe, maybe, true),
#true # (false, maybe, true)
)[@-1,@-1][INITINT a, INITINT b]
);
PRIO EQV = 1; # PRIO = 1.8 #
OP EQV = (TRIT a,b)TRIT: (
[,]TRIT(
# ≡ ## false, maybe, true #
#false# (true, maybe, false),
#maybe# (maybe, maybe, maybe),
#true # (false, maybe, true )
)[@-1,@-1][INITINT a, INITINT b]
); |
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).
| #BaCon | BaCon | ' Display extended character, pound sterling
LET c$ = UTF8$(0xA3)
PRINT c$ |
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).
| #BASIC | BASIC | 10 DATA 56,68,4,14,4,4,122,0
20 HGR
30 FOR I = 8192 TO 16383 STEP 1024
40 READ B: POKE I,B: NEXT |
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).
| #BBC_BASIC | BBC BASIC | PRINT "£" |
http://rosettacode.org/wiki/Terminal_control/Display_an_extended_character | Terminal control/Display an extended character | Task
Display an extended (non ASCII) character onto the terminal.
Specifically, display a £ (GBP currency sign).
| #bc | bc | "£
"
quit |
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).
| #beeswax | beeswax | _4~9P.P.M} |
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.
| #AWK | AWK | BEGIN{
nodata = 0; # Current run of consecutive flags<0 in lines of file
nodata_max=-1; # Max consecutive flags<0 in lines of file
nodata_maxline="!"; # ... and line number(s) where it occurs
}
FNR==1 {
# Accumulate input file names
if(infiles){
infiles = infiles "," infiles
} else {
infiles = FILENAME
}
}
{
tot_line=0; # sum of line data
num_line=0; # number of line data items with flag>0
# extract field info, skipping initial date field
for(field=2; field<=NF; field+=2){
datum=$field;
flag=$(field+1);
if(flag<1){
nodata++
}else{
# check run of data-absent fields
if(nodata_max==nodata && (nodata>0)){
nodata_maxline=nodata_maxline ", " $1
}
if(nodata_max<nodata && (nodata>0)){
nodata_max=nodata
nodata_maxline=$1
}
# re-initialise run of nodata counter
nodata=0;
# gather values for averaging
tot_line+=datum
num_line++;
}
}
# totals for the file so far
tot_file += tot_line
num_file += num_line
printf "Line: %11s Reject: %2i Accept: %2i Line_tot: %10.3f Line_avg: %10.3f\n", \
$1, ((NF -1)/2) -num_line, num_line, tot_line, (num_line>0)? tot_line/num_line: 0
# debug prints of original data plus some of the computed values
#printf "%s %15.3g %4i\n", $0, tot_line, num_line
#printf "%s\n %15.3f %4i %4i %4i %s\n", $0, tot_line, num_line, nodata, nodata_max, nodata_maxline
}
END{
printf "\n"
printf "File(s) = %s\n", infiles
printf "Total = %10.3f\n", tot_file
printf "Readings = %6i\n", num_file
printf "Average = %10.3f\n", tot_file / num_file
printf "\nMaximum run(s) of %i consecutive false readings ends at line starting with date(s): %s\n", nodata_max, nodata_maxline
} |
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.
| #Phix | Phix | --
-- demo\rosetta\Positional_read.exw
-- ================================
--
without js -- (position, get_screen_char)
position(6,1) -- line 6 column 1 (1-based)
puts(1,"abcdef")
integer {ch,attr} = get_screen_char(6,3)
printf(1,"\n\n=>%c",ch)
{} = wait_key()
|
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.
| #PowerShell | PowerShell |
$coord = [System.Management.Automation.Host.Coordinates]::new(3, 6)
$rect = [System.Management.Automation.Host.Rectangle]::new($coord, $coord)
$char = $Host.UI.RawUI.GetBufferContents($rect).Character
|
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.
| #Python | Python | import curses
from random import randint
# Print random text in a 10x10 grid
stdscr = curses.initscr()
for rows in range(10):
line = ''.join([chr(randint(41, 90)) for i in range(10)])
stdscr.addstr(line + '\n')
# Read
icol = 3 - 1
irow = 6 - 1
ch = stdscr.instr(irow, icol, 1).decode(encoding="utf-8")
# Show result
stdscr.move(irow, icol + 10)
stdscr.addstr('Character at column 3, row 6 = ' + ch + '\n')
stdscr.getch()
curses.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.
| #Haxe | Haxe |
package src ;
import haxe.Int32;
import haxe.macro.Expr;
import haxe.ds.Vector;
typedef Ub4 = Int32;
enum Ciphermode {
mEncipher;
mDecipher;
mNone;
}
class Isaac
{
public var randrsl = new Vector<Ub4>(256);
public var randcnt:Ub4;
var mm = new Vector<Ub4>(256);
var aa:Ub4 = 0;
var bb:Ub4 = 0;
var cc:Ub4 = 0;
public function isaac():Void {
var x, y;
cc++;
bb += cc;
for (i in 0...256) {
x = mm[i];
aa ^= switch (i % 4) {//Haxe unification
case 0: aa << 13;
case 1: aa >>> 6;
case 2: aa << 2;
case 3: aa >>> 16;
default: 0;//never happens
}
aa = mm[(i + 128) % 256] + aa;
mm[i] = y = mm[(x >>> 2) % 256] + aa + bb;
randrsl[i] = bb = mm[(y >>> 10) % 256] + x;
}
}
macro static function mix(a:ExprOf<Ub4>, b:ExprOf<Ub4>, c:ExprOf<Ub4>, d:ExprOf<Ub4>,
e:ExprOf<Ub4>, f:ExprOf<Ub4>, g:ExprOf<Ub4>, h:ExprOf<Ub4>) {
return macro {
$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;
};
}
public function randinit(flag:Bool):Void {
var a, b, c, d, e, f, g, h, i;
aa = bb = cc = (0:Ub4);
a = b = c = d = e = f = g = h = (0x9e3779b9:Ub4); /* the golden ratio */
for (i in 0...4) mix(a, b, c, d, e, f, g, h); /* scramble it */
i = 0;
while (i < 256) { /* fill in mm[] with messy stuff */
if (flag) { /* use all the information in the seed */
a += randrsl[i]; b += randrsl[i + 1];
c += randrsl[i + 2]; d += randrsl[i + 3];
e += randrsl[i + 4]; f += randrsl[i + 5];
g += randrsl[i + 6]; h += randrsl[i + 7];
}
mix(a, b, c, d, e, f, g, h);
mm[i] = a; mm[i + 1] = b; mm[i + 2] = c; mm[i + 3] = d;
mm[i + 4] = e; mm[i + 5] = f; mm[i + 6] = g; mm[i + 7] = h;
i += 8;
}
if (flag) { /* do a second pass to make all of the seed affect all of mm */
i = 0;
while (i<256) {
a += mm[i]; b += mm[i + 1]; c += mm[i + 2]; d += mm[i + 3];
e += mm[i + 4]; f += mm[i + 5]; g += mm[i + 6]; h += mm[i + 7];
mix(a, b, c, d, e, f, g, h);
mm[i] = a; mm[i + 1] = b; mm[i + 2] = c; mm[i + 3] = d;
mm[i + 4] = e; mm[i + 5] = f; mm[i + 6] = g; mm[i + 7] = h;
i += 8;
}
}
isaac();
randcnt = 0;
}
public function iRandom():Ub4 {
var r = randrsl[randcnt];
++randcnt;
if (randcnt > 255) {
isaac();
randcnt = 0;
}
return r;
}
public function iRandA():Int32 {
return cast(cast(iRandom(),UInt) % 95 + 32,Int32);
}
public function iSeed(seed:String, flag:Bool):Void {
var m=seed.length-1;
for (i in 0...256) mm[i] = 0;
for (i in 0...256) if (i > m) randrsl[i] = 0; else randrsl[i] = seed.charCodeAt(i);
randinit(flag);
}
inline static var modC = 95;
inline static var startC = 32;
public function vernam (msg:String):String {
var v="";
for (i in 0...msg.length) v += String.fromCharCode(iRandA() ^ msg.charCodeAt(i));
return v;
}
public function caesar(m:Ciphermode, ch:Int32, shift:Int32,
modulo:Int32, start:Int32):String {
var n:Int32;
if (m == mDecipher) n = ch - start - cast(shift,Int32);
else n = ch - start + cast(shift,Int32);
n %= modulo;
if (n < 0) n += modulo;
return String.fromCharCode(start + cast(n,Ub4));
}
public function caesarStr(m:Ciphermode, msg:String, modulo:Int32, start:Int32):String {
var c = "";
for (i in 0...msg.length)
c += caesar(m,msg.charCodeAt(i),iRandA(),modulo,start);
return c;
}
static public function main():Void {
var msg = "a Top Secret secret";
var key = "this is my secret key";
var cIsaac = new Isaac();
var vctx, vptx, cctx, cptx;
cIsaac.iSeed(key, true);
vctx = cIsaac.vernam(msg);
cctx = cIsaac.caesarStr(mEncipher, msg, modC, startC);
cIsaac.iSeed(key, true);
vptx = cIsaac.vernam(vctx);
cptx = cIsaac.caesarStr(mDecipher, cctx, modC, startC);
Sys.println("Message: " + msg);
Sys.println("Key : " + key);
var hex = "";
for (i in 0...vctx.length) hex += StringTools.hex(vctx.charCodeAt(i), 2);
Sys.println("XOR : " + hex);
Sys.println("XOR dcr: " + vptx);
hex = "";
for (i in 0...cctx.length) hex += StringTools.hex(cctx.charCodeAt(i), 2);
Sys.println("MOD : " + hex);
Sys.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.)
| #Java | Java | import java.math.BigDecimal;
import java.util.List;
public class TestIntegerness {
private static boolean isLong(double d) {
return isLong(d, 0.0);
}
private static boolean isLong(double d, double tolerance) {
return (d - Math.floor(d)) <= tolerance || (Math.ceil(d) - d) <= tolerance;
}
@SuppressWarnings("ResultOfMethodCallIgnored")
private static boolean isBigInteger(BigDecimal bd) {
try {
bd.toBigIntegerExact();
return true;
} catch (ArithmeticException ex) {
return false;
}
}
private static class Rational {
long num;
long denom;
Rational(int num, int denom) {
this.num = num;
this.denom = denom;
}
boolean isLong() {
return num % denom == 0;
}
@Override
public String toString() {
return String.format("%s/%s", num, denom);
}
}
private static class Complex {
double real;
double imag;
Complex(double real, double imag) {
this.real = real;
this.imag = imag;
}
boolean isLong() {
return TestIntegerness.isLong(real) && imag == 0.0;
}
@Override
public String toString() {
if (imag >= 0.0) {
return String.format("%s + %si", real, imag);
}
return String.format("%s - %si", real, imag);
}
}
public static void main(String[] args) {
List<Double> da = List.of(25.000000, 24.999999, 25.000100);
for (Double d : da) {
boolean exact = isLong(d);
System.out.printf("%.6f is %s integer%n", d, exact ? "an" : "not an");
}
System.out.println();
double tolerance = 0.00001;
System.out.printf("With a tolerance of %.5f:%n", tolerance);
for (Double d : da) {
boolean fuzzy = isLong(d, tolerance);
System.out.printf("%.6f is %s integer%n", d, fuzzy ? "an" : "not an");
}
System.out.println();
List<Double> fa = List.of(-2.1e120, -5e-2, Double.NaN, Double.POSITIVE_INFINITY);
for (Double f : fa) {
boolean exact = !f.isNaN() && !f.isInfinite() && isBigInteger(new BigDecimal(f.toString()));
System.out.printf("%s is %s integer%n", f, exact ? "an" : "not an");
}
System.out.println();
List<Complex> ca = List.of(new Complex(5.0, 0.0), new Complex(5.0, -5.0));
for (Complex c : ca) {
boolean exact = c.isLong();
System.out.printf("%s is %s integer%n", c, exact ? "an" : "not an");
}
System.out.println();
List<Rational> ra = List.of(new Rational(24, 8), new Rational(-5, 1), new Rational(17, 2));
for (Rational r : ra) {
boolean exact = r.isLong();
System.out.printf("%s is %s integer%n", r, exact ? "an" : "not an");
}
}
} |
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).
| #Oz | Oz | declare
fun {MaxLicenses Filename ?Times}
InUse = {NewCell 0}
MaxInUse = {NewCell 0}
MaxTimes = {NewCell nil}
in
for Job in {ReadLines Filename} do
case {List.take Job 11} of "License OUT" then
InUse := @InUse + 1
if @InUse > @MaxInUse then
MaxInUse := @InUse
MaxTimes := nil
end
if @InUse == @MaxInUse then
JobTime = {Nth {String.tokens Job & } 4}
in
MaxTimes := JobTime|@MaxTimes
end
[] "License IN " then
InUse := @InUse - 1
end
end
Times = {Reverse @MaxTimes}
@MaxInUse
end
%% Helper.
%% Returns a lazy list. So we don't keep the whole logfile in memory...
fun {ReadLines Filename}
F = {New class $ from Open.file Open.text end init(name:Filename)}
fun lazy {ReadNext}
case {F getS($)} of
false then nil
[] Line then
Line|{ReadNext}
end
end
in
%% close file when handle becomes unreachable
{Finalize.register F proc {$ F} {F close} end}
{ReadNext}
end
Times
MaxInUse = {MaxLicenses "mlijobs.txt" ?Times}
in
{System.showInfo
"Maximum simultaneous license use is "#MaxInUse#" at the following times:"}
{ForAll Times System.showInfo} |
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.
| #Go | Go | package pal
import "testing"
func TestPals(t *testing.T) {
pals := []string{
"",
".",
"11",
"ere",
"ingirumimusnocteetconsumimurigni",
}
for _, s := range pals {
if !IsPal(s) {
t.Error("IsPal returned false on palindrome,", s)
}
}
}
func TestNonPals(t *testing.T) {
nps := []string{
"no",
"odd",
"salàlas",
}
for _, s := range nps {
if IsPal(s) {
t.Error("IsPal returned true on non-palindrome,", s)
}
}
} |
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.
| #Snobol4 | Snobol4 | * Read text/2
v = array(24)
f = array(24)
tos = char(9) " " ;* break characters are both tab and space
pat1 = break(tos) . dstamp
pat2 = span(tos) break(tos) . *v[i] span(tos) (break(tos) | (len(1) rem)) . *f[i]
rowcount = 0
hold_dstamp = ""
num_bad_rows = 0
num_invalid_rows = 0
in0
row = input :f(endinput)
rowcount = rowcount + 1
row ? pat1 = :f(invalid_row)
* duplicated datestamp?
* if dstamp = hold_dstamp then duplicated
hold_dstamp = differ(hold_dstamp,dstamp) dstamp :s(nodup)
output = dstamp ": datestamp at row " rowcount " duplicates datestamp at " rowcount - 1
nodup
i = 1
in1
row ? pat2 = :f(invalid_row)
i = lt(i,24) i + 1 :s(in1)
* Is this a goodrow?
* if any flag is < 1 then row has bad data
c = 0
goodrow
c = lt(c,24) c + 1 :f(goodrow2)
num_bad_rows = lt(f[c],1) num_bad_rows + 1 :s(goodrow2)f(goodrow)
goodrow2
:(in0)
invalid_row
num_invalid_rows = num_invalid_rows + 1
:(in0)
endinput
output =
output = "Total number of rows : " rowcount
output = "Total number of rows with invalid format: " num_invalid_rows
output = "Total number of rows with bad data : " num_bad_rows
output = "Total number of good rows : " rowcount - num_invalid_rows - num_bad_rows
end
|
http://rosettacode.org/wiki/Terminal_control/Ringing_the_terminal_bell | Terminal control/Ringing the terminal bell |
Task
Make the terminal running the program ring its "bell".
On modern terminal emulators, this may be done by playing some other sound which might or might not be configurable, or by flashing the title bar or inverting the colors of the screen, but was classically a physical bell within the terminal. It is usually used to indicate a problem where a wrong character has been typed.
In most terminals, if the Bell character (ASCII code 7, \a in C) is printed by the program, it will cause the terminal to ring its bell. This is a function of the terminal, and is independent of the programming language of the program, other than the ability to print a particular character to standard out.
| #Phix | Phix | puts(1,"\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.
| #PHP | PHP | <?php
echo "\007"; |
http://rosettacode.org/wiki/Terminal_control/Ringing_the_terminal_bell | Terminal control/Ringing the terminal bell |
Task
Make the terminal running the program ring its "bell".
On modern terminal emulators, this may be done by playing some other sound which might or might not be configurable, or by flashing the title bar or inverting the colors of the screen, but was classically a physical bell within the terminal. It is usually used to indicate a problem where a wrong character has been typed.
In most terminals, if the Bell character (ASCII code 7, \a in C) is printed by the program, it will cause the terminal to ring its bell. This is a function of the terminal, and is independent of the programming language of the program, other than the ability to print a particular character to standard out.
| #PicoLisp | PicoLisp | (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.
| #PL.2FI | PL/I | declare bell character (1);
unspec (bell) = '00000111'b;
put edit (bell) (a); |
http://rosettacode.org/wiki/The_Twelve_Days_of_Christmas | The Twelve Days of Christmas | Task
Write a program that outputs the lyrics of the Christmas carol The Twelve Days of Christmas.
The lyrics can be found here.
(You must reproduce the words in the correct order, but case, format, and punctuation are left to your discretion.)
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
| #AWK | AWK |
# syntax: GAWK -f THE_TWELVE_DAYS_OF_CHRISTMAS.AWK
BEGIN {
gifts[++i] = "a partridge in a pear tree."
gifts[++i] = "two turtle doves, and"
gifts[++i] = "three french hens,"
gifts[++i] = "four calling birds,"
gifts[++i] = "five golden rings,"
gifts[++i] = "six geese a-laying,"
gifts[++i] = "seven swans a-swimming,"
gifts[++i] = "eight maids a-milking,"
gifts[++i] = "nine ladies dancing,"
gifts[++i] = "ten lords a-leaping,"
gifts[++i] = "eleven pipers piping,"
gifts[++i] = "twelve drummers drumming,"
split("first second third fourth fifth sixth seventh eighth ninth tenth eleventh twelfth",days_arr," ")
for (i=1; i<=12; i++) {
printf("On the %s day of Christmas,\n",days_arr[i])
print("my true love gave to me:")
for (j=i; j>0; j--) {
printf("%s\n",gifts[j])
}
print("")
}
exit(0)
}
|
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.
| #Scala | Scala | print("\033[?1049h\033[H")
println("Alternate buffer!")
for (i <- 5 to 0 by -1) {
println(s"Going back in: $i")
Thread.sleep(1000)
}
print("\033[?1049l") |
http://rosettacode.org/wiki/Terminal_control/Preserve_screen | Terminal control/Preserve screen |
Task
Clear the screen, output something on the display, and then restore the screen to the preserved state that it was in before the task was carried out.
There is no requirement to change the font or kerning in this task, however character decorations and attributes are expected to be preserved. If the implementer decides to change the font or kerning during the display of the temporary screen, then these settings need to be restored prior to exit.
| #Sidef | Sidef | print "\e[?1049h\e[H";
say "Alternate buffer!";
3.downto(1).each { |i|
say "Going back in: #{i}";
Sys.sleep(1);
}
print "\e[?1049l"; |
http://rosettacode.org/wiki/Terminal_control/Preserve_screen | Terminal control/Preserve screen |
Task
Clear the screen, output something on the display, and then restore the screen to the preserved state that it was in before the task was carried out.
There is no requirement to change the font or kerning in this task, however character decorations and attributes are expected to be preserved. If the implementer decides to change the font or kerning during the display of the temporary screen, then these settings need to be restored prior to exit.
| #Swift | Swift |
public let CSI = ESC+"[" // Control Sequence Introducer
func write(_ text: String...) {
for txt in text { write(STDOUT_FILENO, txt, txt.utf8.count) }
}
write(CSI,"?1049h") // open alternate screen
print("Alternate screen buffer\n")
for n in (1...5).reversed() {
print("Going back in \(n)...")
sleep(1)
}
write(CSI,"?1049l") // close alternate screen
|
http://rosettacode.org/wiki/Terminal_control/Preserve_screen | Terminal control/Preserve screen |
Task
Clear the screen, output something on the display, and then restore the screen to the preserved state that it was in before the task was carried out.
There is no requirement to change the font or kerning in this task, however character decorations and attributes are expected to be preserved. If the implementer decides to change the font or kerning during the display of the temporary screen, then these settings need to be restored prior to exit.
| #Tcl | Tcl | # A helper to make code more readable
proc terminal {args} {
exec /usr/bin/tput {*}$args >/dev/tty
}
# Save the screen with the "enter_ca_mode" capability, a.k.a. 'smcup'
terminal smcup
# Some indication to users what is happening...
puts "This is the top of a blank screen. Press Return/Enter to continue..."
gets stdin
# Restore the screen with the "exit_ca_mode" capability, a.k.a. 'rmcup'
terminal rmcup |
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.
| #Common_Lisp | Common Lisp |
(defun sh (cmd)
#+clisp (shell cmd)
#+ecl (si:system cmd)
#+sbcl (sb-ext:run-program "/bin/sh" (list "-c" cmd) :input nil :output *standard-output*)
#+clozure (ccl:run-program "/bin/sh" (list "-c" cmd) :input nil :output *standard-output*))
(defun show-cursor (x)
(if x (sh "tput cvvis") (sh "tput civis")))
(show-cursor nil)
(sleep 3)
(show-cursor t)
(sleep 3)
|
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.
| #FunL | FunL | import time.*
import console.*
hide()
sleep( 2 Second )
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.
| #Furor | Furor |
cursoroff
|
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.
| #Go | Go | package main
import (
"os"
"os/exec"
"time"
)
func main() {
tput("civis") // hide
time.Sleep(3 * time.Second)
tput("cvvis") // show
time.Sleep(3 * time.Second)
}
func tput(arg string) error {
cmd := exec.Command("tput", arg)
cmd.Stdout = os.Stdout
return cmd.Run()
} |
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.
| #COBOL | COBOL | IDENTIFICATION DIVISION.
PROGRAM-ID. terminal-reverse-video.
PROCEDURE DIVISION.
DISPLAY "Reverse-Video" WITH REVERSE-VIDEO
DISPLAY "Normal"
GOBACK
. |
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.
| #Common_Lisp | Common Lisp | (defun reverse-attribute ()
(with-screen (scr :input-blocking t :input-echoing nil :cursor-visible nil)
(add-string scr "Reverse" :attributes '(:reverse))
(add-string scr " Normal" :attributes '())
(refresh scr)
(get-char scr))) |
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.
| #Forth | Forth | : Reverse #27 emit "[7m" type ;
: Normal #27 emit "[m" type ;
: test cr Reverse ." Reverse " cr Normal ." Normal " ;
test
|
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.
| #FunL | FunL | import console.*
println( "${REVERSED}This is reversed.$RESET This is normal." ) |
http://rosettacode.org/wiki/Terminal_control/Inverse_video | Terminal control/Inverse video | Task
Display a word in inverse video (or reverse video) followed by a word in normal video.
| #Go | Go | package main
import (
"fmt"
"os"
"os/exec"
)
func main() {
tput("rev")
fmt.Print("Rosetta")
tput("sgr0")
fmt.Println(" Code")
}
func tput(arg string) error {
cmd := exec.Command("tput", arg)
cmd.Stdout = os.Stdout
return cmd.Run()
} |
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.
| #AArch64_Assembly | AArch64 Assembly |
/* ARM assembly AARCH64 Raspberry PI 3B */
/* program terminalSize64.s */
/*******************************************/
/* Constantes file */
/*******************************************/
/* for this file see task include a file in language AArch64 assembly*/
.include "../includeConstantesARM64.inc"
.equ TIOCGWINSZ, 0x5413
.equ IOCTL, 0x1D // Linux syscall
/*******************************************/
/* Structures */
/********************************************/
/* structure terminal size */
.struct 0
term_s_lines: // input modes
.struct term_s_lines + 2
term_s_cols: // output modes
.struct term_s_cols + 2
term_s_filler: // control modes
.struct term_s_filler + 12
term_fin:
/*******************************************/
/* Initialized data */
/*******************************************/
.data
szMessStartPgm: .asciz "Program start \n"
szMessEndPgm: .asciz "Program normal end.\n"
szMessResult: .asciz "Terminal lines : @ cols : @ \n"
szMessErreur: .asciz "\033[31mError IOCTL.\n"
szCarriageReturn: .asciz "\n"
/*******************************************/
/* UnInitialized data */
/*******************************************/
.bss
.align 4
sZoneConv: .skip 24
stTerminal: .skip term_fin // structure terminal
/*******************************************/
/* code section */
/*******************************************/
.text
.global main
main:
ldr x0,qAdrszMessStartPgm //display start message
bl affichageMess
/* read terminal dimensions */
mov x0,STDIN // input console
mov x1,TIOCGWINSZ // code IOCTL
ldr x2,qAdrstTerminal // structure address
mov x8,IOCTL // call system Linux
svc 0
cbnz x0,98f // error ?
ldr x2,qAdrstTerminal
ldrh w0,[x2,term_s_lines] // load two bytes
ldr x1,qAdrsZoneConv
bl conversion10 // and decimal conversion
ldr x0,qAdrszMessResult
bl strInsertAtChar // and insertion in message
mov x5,x0 // save address of new message
ldrh w0,[x2,term_s_cols] // load two bytes
ldr x1,qAdrsZoneConv
bl conversion10 // and decimal conversion
mov x0,x5 // restaur address of message
bl strInsertAtChar // and insertion in message
bl affichageMess
ldr x0,qAdrszMessEndPgm //display end message
bl affichageMess
b 100f
98: // error display
ldr x0,qAdrszMessErreur
bl affichageMess
mov x0,-1
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
qAdrszMessErreur: .quad szMessErreur
qAdrszCarriageReturn: .quad szCarriageReturn
qAdrstTerminal: .quad stTerminal
qAdrszMessResult: .quad szMessResult
qAdrsZoneConv: .quad sZoneConv
/********************************************************/
/* File Include fonctions */
/********************************************************/
/* for this file see task include a file in language AArch64 assembly */
.include "../includeARM64.inc"
|
http://rosettacode.org/wiki/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.
| #AArch64_Assembly | AArch64 Assembly |
/* ARM assembly AARCH64 Raspberry PI 3B */
/* program cursorPos64.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"
szMessMovePos: .asciz "\033[6;3HHello\n"
szCarriageReturn: .asciz "\n"
szCleax1: .byte 0x1B
.byte 'c' // other console clear
.byte 0
/*******************************************/
/* UnInitialized data */
/*******************************************/
.bss
/*******************************************/
/* code section */
/*******************************************/
.text
.global main
main:
ldr x0,qAdrszMessStartPgm // display start message
bl affichageMess
ldr x0,qAdrszCleax1
bl affichageMess
ldr x0,qAdrszMessMovePos
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
qAdrszCarriageReturn: .quad szCarriageReturn
qAdrszCleax1: .quad szCleax1
qAdrszMessMovePos: .quad szMessMovePos
/********************************************************/
/* File Include fonctions */
/********************************************************/
/* for this file see task include a file in language AArch64 assembly */
.include "../includeARM64.inc"
|
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
| #Arturo | Arturo | vals: @[true maybe false]
loop vals 'v -> print ["NOT" v "=>" not? v]
print ""
loop vals 'v1 [
loop vals 'v2
-> print [v1 "AND" v2 "=>" and? v1 v2]
]
print ""
loop vals 'v1 [
loop vals 'v2
-> print [v1 "OR" v2 "=>" or? v1 v2]
]
print ""
loop vals 'v1 [
loop vals 'v2
-> print [v1 "XOR" v2 "=>" xor? v1 v2]
] |
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).
| #Befunge | Befunge | "| "+,@ |
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).
| #Bracmat | Bracmat | put$£ |
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 | C | #include <stdio.h>
int
main()
{
puts("£");
puts("\302\243"); /* if your terminal is utf-8 */
return 0;
} |
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.
| #Batch_File | Batch File | @echo off
setlocal ENABLEDELAYEDEXPANSION
set maxrun= 0
set maxstart=
set maxend=
set notok=0
set inputfile=%1
for /F "tokens=1,*" %%i in (%inputfile%) do (
set date=%%i
call :processline %%j
)
echo\
echo max false: %maxrun% from %maxstart% until %maxend%
goto :EOF
:processline
set sum=0000
set count=0
set hour=1
:loop
if "%1"=="" goto :result
set num=%1
if "%2"=="1" (
if "%notok%" NEQ "0" (
set notok= !notok!
if /I "!notok:~-5!" GTR "%maxrun%" (
set maxrun=!notok:~-5!
set maxstart=%nok0date% %nok0hour%
set maxend=%nok1date% %nok1hour%
)
set notok=0
)
set /a sum+=%num:.=%
set /a count+=1
) else (
if "%notok%" EQU "0" (
set nok0date=%date%
set nok0hour=%hour%
) else (
set nok1date=%date%
set nok1hour=%hour%
)
set /a notok+=1
)
shift
shift
set /a hour+=1
goto :loop
:result
if "%count%"=="0" (
set mean=0
) else (
set /a mean=%sum%/%count%
)
if "%mean%"=="0" set mean=0000
if "%sum%"=="0" set sum=0000
set mean=%mean:~0,-3%.%mean:~-3%
set sum=%sum:~0,-3%.%sum:~-3%
set count= %count%
set sum= %sum%
set mean= %mean%
echo Line: %date% Accept: %count:~-3% tot: %sum:~-8% avg: %mean:~-8%
goto :EOF |
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.
| #Racket | Racket |
#lang racket
(require ffi/unsafe ffi/unsafe/define)
(define-ffi-definer defwin #f)
(defwin GetStdHandle (_fun _int -> _pointer))
(defwin ReadConsoleOutputCharacterA
(_fun _pointer _pointer _uint _uint [len : (_ptr o _uint)] -> _bool))
(define b (make-bytes 1 32))
(and (ReadConsoleOutputCharacterA (GetStdHandle -11) b 1 #x50002)
(printf "The character at 3x6 is <~a>\n" b))
|
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.
| #Raku | Raku | use NCurses;
# Reference:
# https://github.com/azawawi/perl6-ncurses
# Initialize curses window
my $win = initscr() or die "Failed to initialize ncurses\n";
# Print random text in a 10x10 grid
for ^10 { mvaddstr($_ , 0, (for ^10 {(41 .. 90).roll.chr}).join )};
# Read
my $icol = 3 - 1;
my $irow = 6 - 1;
my $ch = mvinch($irow,$icol);
# Show result
mvaddstr($irow, $icol+10, 'Character at column 3, row 6 = ' ~ $ch.chr);
mvaddstr( LINES() - 2, 2, "Press any key to exit..." );
# Refresh (this is needed)
nc_refresh;
# Wait for a keypress
getch;
# Cleanup
LEAVE {
delwin($win) if $win;
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.
| #Java | Java | import java.io.UnsupportedEncodingException;
import java.util.Arrays;
import java.util.Random;
public class IsaacRandom extends Random {
private static final long serialVersionUID = 1L;
private final int[] randResult = new int[256]; // output of last generation
private int valuesUsed; // the number of values already used up from randResult
// internal generator state
private final int[] mm = new int[256];
private int aa, bb, cc;
public IsaacRandom() {
super(0);
init(null);
}
public IsaacRandom(int[] seed) {
super(0);
setSeed(seed);
}
public IsaacRandom(String seed) {
super(0);
setSeed(seed);
}
private void generateMoreResults() {
cc++;
bb += cc;
for (int i=0; i<256; i++) {
int x = mm[i];
switch (i&3) {
case 0:
aa = aa^(aa<<13);
break;
case 1:
aa = aa^(aa>>>6);
break;
case 2:
aa = aa^(aa<<2);
break;
case 3:
aa = aa^(aa>>>16);
break;
}
aa = mm[i^128] + aa;
int y = mm[i] = mm[(x>>>2) & 0xFF] + aa + bb;
randResult[i] = bb = mm[(y>>>10) & 0xFF] + x;
}
valuesUsed = 0;
}
private static void mix(int[] s) {
s[0]^=s[1]<<11; s[3]+=s[0]; s[1]+=s[2];
s[1]^=s[2]>>>2; s[4]+=s[1]; s[2]+=s[3];
s[2]^=s[3]<<8; s[5]+=s[2]; s[3]+=s[4];
s[3]^=s[4]>>>16; s[6]+=s[3]; s[4]+=s[5];
s[4]^=s[5]<<10; s[7]+=s[4]; s[5]+=s[6];
s[5]^=s[6]>>>4; s[0]+=s[5]; s[6]+=s[7];
s[6]^=s[7]<<8; s[1]+=s[6]; s[7]+=s[0];
s[7]^=s[0]>>>9; s[2]+=s[7]; s[0]+=s[1];
}
private void init(int[] seed) {
if (seed != null && seed.length != 256) {
seed = Arrays.copyOf(seed, 256);
}
aa = bb = cc = 0;
int[] initState = new int[8];
Arrays.fill(initState, 0x9e3779b9); // the golden ratio
for (int i=0; i<4; i++) {
mix(initState);
}
for (int i=0; i<256; i+=8) {
if (seed != null) {
for (int j=0; j<8; j++) {
initState[j] += seed[i+j];
}
}
mix(initState);
for (int j=0; j<8; j++) {
mm[i+j] = initState[j];
}
}
if (seed != null) {
for (int i=0; i<256; i+=8) {
for (int j=0; j<8; j++) {
initState[j] += mm[i+j];
}
mix(initState);
for (int j=0; j<8; j++) {
mm[i+j] = initState[j];
}
}
}
valuesUsed = 256; // Make sure generateMoreResults() will be called by the next next() call.
}
@Override
protected int next(int bits) {
if (valuesUsed == 256) {
generateMoreResults();
assert(valuesUsed == 0);
}
int value = randResult[valuesUsed];
valuesUsed++;
return value >>> (32-bits);
}
@Override
public synchronized void setSeed(long seed) {
super.setSeed(0);
if (mm == null) {
// We're being called from the superclass constructor. We don't have our
// state arrays instantiated yet, and we're going to do proper initialization
// later in our own constructor anyway, so just ignore this call.
return;
}
int[] arraySeed = new int[256];
arraySeed[0] = (int) (seed & 0xFFFFFFFF);
arraySeed[1] = (int) (seed >>> 32);
init(arraySeed);
}
public synchronized void setSeed(int[] seed) {
super.setSeed(0);
init(seed);
}
public synchronized void setSeed(String seed) {
super.setSeed(0);
char[] charSeed = seed.toCharArray();
int[] intSeed = new int[charSeed.length];
for (int i=0; i<charSeed.length; i++) {
intSeed[i] = charSeed[i];
}
init(intSeed);
}
public int randomChar() {
long unsignedNext = nextInt() & 0xFFFFFFFFL; // The only way to force unsigned modulo behavior in Java is to convert to a long and mask off the copies of the sign bit.
return (int) (unsignedNext % 95 + 32); // nextInt(95) + 32 would yield a more equal distribution, but then we would be incompatible with the original C code
}
public enum CipherMode { ENCIPHER, DECIPHER, NONE };
public byte[] vernamCipher(byte[] input) {
byte[] result = new byte[input.length];
for (int i=0; i<input.length; i++) {
result[i] = (byte) (randomChar() ^ input[i]);
}
return result;
}
private static byte caesarShift(CipherMode mode, byte ch, int shift, byte modulo, byte start) {
if (mode == CipherMode.DECIPHER) {
shift = -shift;
}
int n = (ch-start) + shift;
n %= modulo;
if (n<0) {
n += modulo;
}
return (byte) (start + n);
}
public byte[] caesarCipher(CipherMode mode, byte[] input, byte modulo, byte start) {
byte[] result = new byte[input.length];
for (int i=0; i<input.length; i++) {
result[i] = caesarShift(mode, input[i], randomChar(), modulo, start);
}
return result;
}
private static String toHexString(byte[] input) {
// NOTE: This method prefers simplicity over performance.
StringBuilder sb = new StringBuilder(input.length*2);
for (byte b : input) {
sb.append(String.format("%02X", b));
}
return sb.toString();
}
public static void main(String[] args) {
final byte MOD = 95;
final byte START = 32;
String secret = "a Top Secret secret";
String key = "this is my secret key";
IsaacRandom random = new IsaacRandom(key);
byte[] vernamResult;
byte[] caesarResult;
String vernamDecrypted;
String caesarDecrypted;
try {
vernamResult = random.vernamCipher(secret.getBytes("ASCII"));
caesarResult = random.caesarCipher(CipherMode.ENCIPHER, secret.getBytes("ASCII"), MOD, START);
random.setSeed(key);
vernamDecrypted = new String(random.vernamCipher(vernamResult), "ASCII");
caesarDecrypted = new String(random.caesarCipher(CipherMode.DECIPHER, caesarResult, MOD, START), "ASCII");
} catch (UnsupportedEncodingException e) {
throw new InternalError("JVM isn't conforming - ASCII encoding isn't available");
}
System.out.printf("Message: %s\n", secret);
System.out.printf("Key : %s\n", key);
System.out.printf("XOR : %s\n", toHexString(vernamResult));
System.out.printf("XOR dcr: %s\n", vernamDecrypted);
System.out.printf("MOD : %s\n", toHexString(caesarResult));
System.out.printf("MOD dcr: %s\n", caesarDecrypted);
}
} |
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.)
| #jq | jq | def is_integral:
if type == "number" then . == floor
elif type == "array" then
length == 2 and .[1] == 0 and (.[0] | is_integral)
else type == "object"
and .type == "rational"
and .q != 0
and (.q | is_integral)
and ((.p / .q) | is_integral)
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.)
| #Julia | Julia | # v0.6.0
@show isinteger(25.000000)
@show isinteger(24.999999)
@show isinteger(25.000100)
@show isinteger(-2.1e120)
@show isinteger(-5e-2)
@show isinteger(NaN)
@show isinteger(Inf)
@show isinteger(complex(5.0, 0.0))
@show isinteger(complex(5, 5))
|
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).
| #PARI.2FGP | PARI/GP | license()={
my(v=externstr("type mlijobs.txt"),u,cur,rec,t);
for(i=1,#v,
u=Vec(v[i]);
if(#u>9 && u[9] == "O",
if(cur++>rec,
rec=cur;
t=[v[i]]
,
if(cur == rec,t=concat(t,[v[i]]))
)
,
cur--
)
);
print(apply(s->concat(vecextract(Vec(s),"15..33")), t));
rec
}; |
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.
| #Haskell | Haskell | import Test.QuickCheck
isPalindrome :: String -> Bool
isPalindrome x = x == reverse x
{- There is no built-in definition of how to generate random characters;
here we just specify ASCII characters. Generating strings then automatically
follows from the definition of String as list of Char. -}
instance Arbitrary Char where
arbitrary = choose ('\32', '\127')
-- /------------------------- the randomly-generated parameters
-- | /------------------ the constraint on the test values
-- | | /- the condition which should be true
-- v v v
main = do
putStr "Even palindromes: " >> quickCheck (\s -> isPalindrome (s ++ reverse s))
putStr "Odd palindromes: " >> quickCheck (\s -> not (null s) ==> isPalindrome (s ++ (tail.reverse) s))
putStr "Non-palindromes: " >> quickCheck (\i s -> not (null s) && 0 <= i && i < length s && i*2 /= length s
==> not (isPalindrome (take i s ++ "•" ++ drop i s))) |
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.
| #Icon_and_Unicon | Icon and Unicon | procedure main()
s := "ablewasiereisawelba"
assert{"test1",palindrome(s)}
assertFailure{"test2",palindrome(s)}
s := "un"||s
assert{"test3",palindrome(s)}
assertFailure{"test4",palindrome(s)}
end
procedure palindrome(s)
return s == reverse(s)
end
procedure assert(A)
if not @A[2] then write(@A[1],": failed")
end
procedure assertFailure(A)
if @A[2] then write(@A[1],": failed")
end |
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.
| #Tcl | Tcl | set data [lrange [split [read [open "readings.txt" "r"]] "\n"] 0 end-1]
set total [llength $data]
set correct $total
set datestamps {}
foreach line $data {
set formatOk true
set hasAllMeasurements true
set date [lindex $line 0]
if {[llength $line] != 49} { set formatOk false }
if {![regexp {\d{4}-\d{2}-\d{2}} $date]} { set formatOk false }
if {[lsearch $datestamps $date] != -1} { puts "Duplicate datestamp: $date" } {lappend datestamps $date}
foreach {value flag} [lrange $line 1 end] {
if {$flag < 1} { set hasAllMeasurements false }
if {![regexp -- {[-+]?\d+\.\d+} $value] || ![regexp -- {-?\d+} $flag]} {set formatOk false}
}
if {!$hasAllMeasurements} { incr correct -1 }
if {!$formatOk} { puts "line \"$line\" has wrong format" }
}
puts "$correct records with good readings = [expr $correct * 100.0 / $total]%"
puts "Total records: $total" |
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.
| #PostScript | PostScript | (\007) print |
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.
| #PowerShell | PowerShell | "`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.
| #PureBasic | PureBasic | Print(#BEL$) |
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
| #Batch_File | Batch File | :: The Twelve Days of Christmas
:: Batch File Implementation
@echo off
::Pseudo-array for Days
set "day1=First"
set "day2=Second"
set "day3=Third"
set "day4=Fourth"
set "day5=Fifth"
set "day6=Sixth"
set "day7=Seventh"
set "day8=Eighth"
set "day9=Nineth"
set "day10=Tenth"
set "day11=Eleventh"
set "day12=Twelveth"
::Pseudo-array for Gifts
set "gift12=Twelve drummers drumming"
set "gift11=Eleven pipers piping"
set "gift10=Ten loards a-leaping"
set "gift9=Nine ladies dancing"
set "gift8=Eight maids a-milking"
set "gift7=Seven swans a-swimming"
set "gift6=Six geese a-laying"
set "gift5=Five golden rings"
set "gift4=Four calling birds"
set "gift3=Three french hens"
set "gift2=Two turtle doves"
set "gift1=A partridge in a pear tree"
::Display It!
setlocal enabledelayedexpansion
for /l %%i in (1,1,12) do (
echo On the !day%%i! day of Christmas
echo My true love gave to me:
for /l %%j in (%%i,-1,1) do (
if %%j equ 1 (
if %%i neq 1 <nul set /p ".=And "
echo !gift1!.
) else (
echo !gift%%j!,
)
)
echo(
)
exit /b |
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.
| #UNIX_Shell | UNIX Shell | #!/bin/sh
tput smcup # Save the display
echo 'Hello'
sleep 5 # Wait five seconds
tput rmcup # Restore the display |
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.
| #Wren | Wren | import "io" for Stdout
import "timer" for Timer
System.write("\e[?1049h\e[H")
System.print("Alternate screen buffer")
for (i in 5..1) {
var s = (i != 1) ? "s" : ""
System.write("\rGoing back in %(i) second%(s)...")
Stdout.flush()
Timer.sleep(1000)
}
System.write("\e[?1049l") |
http://rosettacode.org/wiki/Terminal_control/Preserve_screen | Terminal control/Preserve screen |
Task
Clear the screen, output something on the display, and then restore the screen to the preserved state that it was in before the task was carried out.
There is no requirement to change the font or kerning in this task, however character decorations and attributes are expected to be preserved. If the implementer decides to change the font or kerning during the display of the temporary screen, then these settings need to be restored prior to exit.
| #XPL0 | XPL0 | include c:\cxpl\codes; \intrinsic 'code' declarations
proc SetPage(P); \Select active display page for video screen
int P;
int CpuReg;
[CpuReg:= GetReg; \access CPU registers
CpuReg(0):= $0500 + P; \call BIOS interrupt $10, function 5
SoftInt($10);
]; \SetPage
[SetPage(1); \enable page 1 text display screen
Clear; \clear screen and output something
Text(0, "Hit any key to restore original screen. ");
if ChIn(1) then []; \wait for keystroke
SetPage(0); \restore original, default text screen, page 0
] |
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.
| #Z80_Assembly | Z80 Assembly | org $3000
txt_output: equ $bb5a
scr_clear: equ $bc14
wait_char: equ $bb06
scr_get_loc: equ $bc0b
scr_set_off: equ $bc05
push bc
push de
push hl
push af
call scr_get_loc ; save this value just in case the
push hl ; original screen has been scrolled vertically
ld hl,$c000 ; copy screen to block 1
ld de,$4000
ld bc,$4000
ldir
call scr_clear
ld hl,text
print: ld a,(hl)
cp 0
jr z,key
call txt_output
inc hl
jr print
key: call wait_char
pop hl
call scr_set_off
ld hl,$4000 ; restore screen
ld de,$c000
ld bc,$4000
ldir
pop af
pop hl
pop de
pop bc
ret
text: defm "This is some text. Please press a key.\0" |
http://rosettacode.org/wiki/Terminal_control/Hiding_the_cursor | Terminal control/Hiding the cursor | The task is to hide the cursor and show it again.
| #J | J | smoutput HIDECURSOR
usleep(4e6) NB. wait 4 seconds
smoutput 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.
| #Julia | Julia | const ESC = "\u001B" # escape code
print("$ESC[?25l") # hide the cursor
print("Enter anything, press RETURN: ") # prompt shown
input = readline() # but no cursor
print("$ESC[0H$ESC[0J$ESC[?25h") # reset, visible again
sleep(3)
println()
|
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.
| #Kotlin | Kotlin | // version 1.1.2
fun main(args: Array<String>) {
print("\u001B[?25l") // hide cursor
Thread.sleep(2000) // wait 2 seconds before redisplaying cursor
print("\u001B[?25h") // display cursor
Thread.sleep(2000) // wait 2 more seconds before exiting
} |
http://rosettacode.org/wiki/Terminal_control/Hiding_the_cursor | Terminal control/Hiding the cursor | The task is to hide the cursor and show it again.
| #Lasso | Lasso | #!/usr/bin/lasso9
local(
esc = decode_base64('Gw==')
)
// hide the cursor
stdout(#esc + '[?25l')
// wait for 4 seconds to give time discover the cursor is gone
sleep(4000)
// show the cursor
stdout(#esc + '[?25h')
// wait for 4 seconds to give time discover the cursor is back
sleep(4000) |
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.
| #Locomotive_Basic | Locomotive Basic | 10 CURSOR 0: REM hide cursor
20 FOR l = 1 TO 2000: REM delay
30 NEXT l
40 CURSOR 1: REM show 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.
| #J | J |
;:';:,#.*."3,(C.A.)/\/&.:;:' NB. some output beforehand
attributes REVERSEVIDEO NB. does as it says
2 o.^:a:0 NB. solve the fixed point equation cos(x) == x
attributes OFF NB. no more blinky flashy
parseFrench=:;:,#.*."3,(C.A.)/\/&.:;: NB. just kidding! More output.
|
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.
| #Julia | Julia | using Crayons.Box
println(WHITE_FG, BLACK_BG, "Normal")
println(WHITE_BG, BLACK_FG, "Reversed")
println(WHITE_FG, BLACK_BG, "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.
| #Kotlin | Kotlin | // version 1.1.2
fun main(args: Array<String>) {
println("\u001B[7mInverse\u001B[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.
| #Lasso | Lasso | local(esc = decode_base64('Gw=='))
stdout( #esc + '[7m Reversed Video ' + #esc + '[0m Normal Video ') |
http://rosettacode.org/wiki/Terminal_control/Inverse_video | Terminal control/Inverse video | Task
Display a word in inverse video (or reverse video) followed by a word in normal video.
| #Mathematica.2FWolfram_Language | Mathematica/Wolfram Language | Run["tput mr"]
Run["echo foo"] (* is displayed in reverse mode *)
Run["tput me"]
Run["echo bar"] |
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.
| #Action.21 | Action! | PROC Main()
BYTE ROWCRS=$0054 ;Current cursor row
CARD COLCRS=$0055 ;Current cursor column
CARD width
BYTE height
Graphics(0)
Position(0,0) ;go to the top-left corner
Put(28) Put(30) ;go up and left - the bottom-right corner
width=COLCRS+1
height=ROWCRS+1
Position(2,1)
PrintF("Number of colums: %U%E",width)
PrintF("Number of rows: %B%E",height)
RETURN |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.