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/Walk_a_directory/Recursively | Walk a directory/Recursively | Task
Walk a given directory tree and print files matching a given pattern.
Note: This task is for recursive methods. Β These tasks should read an entire directory tree, not a single directory.
Note: Please be careful when running any code examples found here.
Related task
Β Walk a directory/Non-recursively Β (read a single directory).
| #Groovy | Groovy | new File('.').eachFileRecurse {
if (it.name =~ /.*\.txt/) println it;
} |
http://rosettacode.org/wiki/Walk_a_directory/Recursively | Walk a directory/Recursively | Task
Walk a given directory tree and print files matching a given pattern.
Note: This task is for recursive methods. Β These tasks should read an entire directory tree, not a single directory.
Note: Please be careful when running any code examples found here.
Related task
Β Walk a directory/Non-recursively Β (read a single directory).
| #GUISS | GUISS | Start,Find,Files and Folders,Dropdown: Look in>My Documents,
Inputbox: filename>m*.txt,Button:Search |
http://rosettacode.org/wiki/Water_collected_between_towers | Water collected between towers | Task
In a two-dimensional world, we begin with any bar-chart (or row of close-packed 'towers', each of unit width), and then it rains,
completely filling all convex enclosures in the chart with water.
9 ββ 9 ββ
8 ββ 8 ββ
7 ββ ββ 7 ββββββββββββ
6 ββ ββ ββ 6 ββββββββββββ
5 ββ ββ ββ ββββ 5 ββββββββββββββββ
4 ββ ββ ββββββββ 4 ββββββββββββββββ
3 ββββββ ββββββββ 3 ββββββββββββββββ
2 ββββββββββββββββ ββ 2 ββββββββββββββββββββ
1 ββββββββββββββββββββ 1 ββββββββββββββββββββ
In the example above, a bar chart representing the values [5, 3, 7, 2, 6, 4, 5, 9, 1, 2] has filled, collecting 14 units of water.
Write a function, in your language, from a given array of heights, to the number of water units that can be held in this way, by a corresponding bar chart.
Calculate the number of water units that could be collected by bar charts representing each of the following seven series:
[[1, 5, 3, 7, 2],
[5, 3, 7, 2, 6, 4, 5, 9, 1, 2],
[2, 6, 3, 5, 2, 8, 1, 4, 2, 2, 5, 3, 5, 7, 4, 1],
[5, 5, 5, 5],
[5, 6, 7, 8],
[8, 7, 7, 6],
[6, 7, 10, 7, 6]]
See, also:
Four Solutions to a Trivial Problem β a Google Tech Talk by Guy Steele
Water collected between towers on Stack Overflow, from which the example above is taken)
An interesting Haskell solution, using the Tardis monad, by Phil Freeman in a Github gist.
| #J | J | collectLevels =: >./\ <. >./\. NB. collect levels after filling
waterLevels=: collectLevels - ] NB. water levels for each tower
collectedWater=: +/@waterLevels NB. sum the units of water collected
printTowers =: ' ' , [: |.@|: '#~' #~ ] ,. waterLevels NB. print a nice graph of towers and water |
http://rosettacode.org/wiki/Video_display_modes | Video display modes | The task is to demonstrate how to switch video display modes within the language. A brief description of the supported video modes would be useful.
| #6502_Assembly | 6502 Assembly | LDA #3
JSR $FE95 |
http://rosettacode.org/wiki/Verify_distribution_uniformity/Naive | Verify distribution uniformity/Naive | This task is an adjunct to Seven-sided dice from five-sided dice.
Task
Create a function to check that the random integers returned from a small-integer generator function have uniform distribution.
The function should take as arguments:
The function (or object) producing random integers.
The number of times to call the integer generator.
A 'delta' value of some sort that indicates how close to a flat distribution is close enough.
The function should produce:
Some indication of the distribution achieved.
An 'error' if the distribution is not flat enough.
Show the distribution checker working when the produced distribution is flat enough and when it is not. (Use a generator from Seven-sided dice from five-sided dice).
See also:
Verify distribution uniformity/Chi-squared test
| #Haskell | Haskell | import System.Random
import Data.List
import Control.Monad
import Control.Arrow
Β
distribCheck :: IO Int -> Int -> Int -> IO [(Int,(Int,Bool))]
distribCheck f n d = do
nrs <- replicateM n f
let group = takeWhile (not.null) $ unfoldr (Just. (partition =<< (==). head)) nrs
avg = (fromIntegral n) / fromIntegral (length group)
ul = round $ (100 + fromIntegral d)/100 * avg
ll = round $ (100 - fromIntegral d)/100 * avg
return $ map (head &&& (id &&& liftM2 (&&) (>ll)(<ul)).length) group |
http://rosettacode.org/wiki/Voronoi_diagram | Voronoi diagram | A Voronoi diagram is a diagram consisting of a number of sites.
Each Voronoi site s also has a Voronoi cell consisting of all points closest to s.
Task
Demonstrate how to generate and display a Voroni diagram.
See algo K-means++ clustering.
| #Prolog | Prolog | :- dynamic pt/6.
voronoi :-
V is random(20) + 20,
retractall(pt(_,_,_,_)),
forall(between(1, V, I),
( X is random(390) + 5,
Y is random(390) + 5,
R is random(65535),
G is random(65535),
B is random(65535),
assertz(pt(I,X,Y, R, G, B))
)),
voronoi(manhattan, V),
voronoi(euclide, V),
voronoi(minkowski_3, V).
Β
voronoi(Distance, V) :-
sformat(A, 'Voronoi 400X400 ~w ~w', [V, Distance]),
new(D, window(A)),
send(D, size, size(400,400)),
new(Img, image(@nil, width := 400, height := 400 , kind := pixmap)),
Β
% get the list of the sites
bagof((N, X, Y), R^G^B^pt(N, X, Y, R, G, B), L),
Β
forall(between(0,399, I),
forall(between(0,399, J),
( get_nearest_site(V, Distance, I, J, L, S),
pt(S, _, _, R, G, B),
send(Img, pixel(I, J, colour(@default, R, G, B)))))),
Β
new(Bmp, bitmap(Img)),
send(D, display, Bmp, point(0,0)),
send(D, open).
Β
% define predicatea foldl (functionnal spirit)
foldl([], _Pred, R, R).
Β
foldl([H | T], Pred, Acc, R) :-
call(Pred, H, Acc, R1),
foldl(T, Pred, R1, R).
Β
% predicate for foldl
compare(Distance, XP, YP, (N, X, Y), (D, S), R) :-
call(Distance, XP, YP, X, Y, DT),
( DT < D -> R = (DT, N) ; R = (D, S)).
Β
% use of a fake site for the init of foldl
get_nearest_site(Distance, I, J, L, S) :-
foldl(L, compare(Distance, I, J), (65535, nil), (_, S)).
Β
Β
Β
manhattan(X1, Y1, X2, Y2, D) :-
D is abs(X2 - X1) + abs(Y2-Y1).
Β
euclide(X1, Y1, X2, Y2, D) :-
D is sqrt((X2 - X1)**2 + (Y2-Y1)**2).
Β
minkowski_3(X1, Y1, X2, Y2, D) :-
D is (abs(X2 - X1)**3 + abs(Y2-Y1)**3)**0.33.
Β |
http://rosettacode.org/wiki/Verify_distribution_uniformity/Chi-squared_test | Verify distribution uniformity/Chi-squared test | Task
Write a function to verify that a given distribution of values is uniform by using the
Ο
2
{\displaystyle \chi ^{2}}
test to see if the distribution has a likelihood of happening of at least the significance level (conventionally 5%).
The function should return a boolean that is true if the distribution is one that a uniform distribution (with appropriate number of degrees of freedom) may be expected to produce.
Reference
Β an entry at the MathWorld website: Β chi-squared distribution.
| #Elixir | Elixir | defmodule Verify do
defp gammaInc_Q(a, x) do
a1 = a-1
f0 = fn t ->Β :math.pow(t, a1) *Β :math.exp(-t) end
df0 = fn t -> (a1-t) *Β :math.pow(t, a-2) *Β :math.exp(-t) end
y = while_loop(f0, x, a1)
n = trunc(y / 3.0e-4)
h = y / n
hh = 0.5 * h
sum = Enum.reduce(n-1 .. 0, 0, fn j,sum ->
t = h * j
sum + f0.(t) + hh * df0.(t)
end)
h * sum / gamma_spounge(a, make_coef)
end
Β
defp while_loop(f, x, y) do
if f.(y)*(x-y) > 2.0e-8 and y < x, do: while_loop(f, x, y+0.3), else: min(x, y)
end
Β
@a 12
defp make_coef do
coef0 = [:math.sqrt(2.0 *Β :math.pi)]
{_, coef} = Enum.reduce(1..@a-1, {1.0, coef0}, fn k,{k1_factrl,c} ->
h =Β :math.exp(@a-k) *Β :math.pow(@a-k, k-0.5) / k1_factrl
{-k1_factrl*k, [h | c]}
end)
Enum.reverse(coef) |> List.to_tuple
end
Β
defp gamma_spounge(z, coef) do
accm = Enum.reduce(1..@a-1, elem(coef,0), fn k,res -> res + elem(coef,k) / (z+k) end)
accm *Β :math.exp(-(z+@a)) *Β :math.pow(z+@a, z+0.5) / z
end
Β
def chi2UniformDistance(dataSet) do
expected = Enum.sum(dataSet) / length(dataSet)
Enum.reduce(dataSet, 0, fn d,sum -> sum + (d-expected)*(d-expected) end) / expected
end
Β
def chi2Probability(dof, distance) do
1.0 - gammaInc_Q(0.5*dof, 0.5*distance)
end
Β
def chi2IsUniform(dataSet, significance\\0.05) do
dof = length(dataSet) - 1
dist = chi2UniformDistance(dataSet)
chi2Probability(dof, dist) > significance
end
end
Β
dsets = [ [ 199809, 200665, 199607, 200270, 199649 ],
[ 522573, 244456, 139979, 71531, 21461 ] ]
Β
Enum.each(dsets, fn ds ->
IO.puts "Data set:#{inspect ds}"
dof = length(ds) - 1
IO.puts " degrees of freedom: #{dof}"
distance = Verify.chi2UniformDistance(ds)
Β :io.fwrite " distance: ~.4f~n", [distance]
Β :io.fwrite " probability: ~.4f~n", [Verify.chi2Probability(dof, distance)]
Β :io.fwrite " uniform? ~s~n", [(if Verify.chi2IsUniform(ds), do: "Yes", else: "No")]
end) |
http://rosettacode.org/wiki/Verhoeff_algorithm | Verhoeff algorithm | Description
The Verhoeff algorithm is a checksum formula for error detection developed by the Dutch mathematician Jacobus Verhoeff and first published in 1969. It was the first decimal check digit algorithm which detects all single-digit errors, and all transposition errors involving two adjacent digits, which was at the time thought impossible with such a code.
As the workings of the algorithm are clearly described in the linked Wikipedia article they will not be repeated here.
Task
Write routines, methods, procedures etc. in your language to generate a Verhoeff checksum digit for non-negative integers of any length and to validate the result. A combined routine is also acceptable.
The more mathematically minded may prefer to generate the 3 tables required from the description provided rather than to hard-code them.
Write your routines in such a way that they can optionally display digit by digit calculations as in the Wikipedia example.
Use your routines to calculate check digits for the integers: 236, 12345 and 123456789012 and then validate them. Also attempt to validate the same integers if the check digits in all cases were 9 rather than what they actually are.
Display digit by digit calculations for the first two integers but not for the third.
Related task
Β Damm algorithm
| #Phix | Phix | with javascript_semantics
sequence d = {tagset(9,0)},
inv = tagset(9,0),
p = {tagset(9,0)}
for i=1 to 4 do d = append(d,extract(d[$],{2,3,4,5,1,7,8,9,10,6})) end for
for i=5 to 8 do d = append(d,reverse(d[-4])) end for
d = append(d,reverse(d[1]))
inv[2..5] = reverse(inv[2..5])
for i=1 to 7 do p = append(p,extract(p[$],{2,6,8,7,3,9,4,1,10,5})) end for
-- alternatively, if you prefer:
--constant d = {{0,1,2,3,4,5,6,7,8,9},
-- {1,2,3,4,0,6,7,8,9,5},
-- {2,3,4,0,1,7,8,9,5,6},
-- {3,4,0,1,2,8,9,5,6,7},
-- {4,0,1,2,3,9,5,6,7,8},
-- {5,9,8,7,6,0,4,3,2,1},
-- {6,5,9,8,7,1,0,4,3,2},
-- {7,6,5,9,8,2,1,0,4,3},
-- {8,7,6,5,9,3,2,1,0,4},
-- {9,8,7,6,5,4,3,2,1,0}},
-- inv = {0,4,3,2,1,5,6,7,8,9},
-- p = {{0,1,2,3,4,5,6,7,8,9},
-- {1,5,7,6,2,8,3,0,9,4},
-- {5,8,0,3,7,9,6,1,4,2},
-- {8,9,1,6,0,4,3,5,2,7},
-- {9,4,5,3,1,2,6,8,7,0},
-- {4,2,8,6,5,7,3,9,0,1},
-- {2,7,9,3,8,0,6,4,1,5},
-- {7,0,4,6,9,1,3,2,5,8}}
function verhoeff(string n, bool validate=false, show_workings=false)
string {s,t} = iff(validate?{n,"Validation"}:{n&'0',"Check digit"})
if show_workings then
printf(1,"%s calculations for `%s`:\n", {t, n})
printf(1," i ni p(i,ni) c\n")
printf(1,"------------------\n")
end if
integer c = 0
for i=1 to length(s) do
integer ni = s[-i]-'0',
pi = p[remainder(i-1,8)+1][ni+1]
c = d[c+1][pi+1]
if show_workings then
printf(1,"%2d Β %d Β %d Β %d\n", {i-1, ni, pi, c})
end if
end for
integer ch = inv[c+1]+'0'
string r = iff(validate?iff(c=0?"":"in")&"correct"
:"`"&ch&"`")
printf(1,"TheΒ %s for `%s` isΒ %s\n\n",{lower(t),n,r})
return ch
end function
constant tests = {"236", "12345", "123456789012"}
for i=1 to length(tests) do
bool show_workings = (i<=2)
integer ch = verhoeff(tests[i],false,show_workings)
assert(verhoeff(tests[i]&ch,true,show_workings)=='0')
assert(verhoeff(tests[i]&'9',true,show_workings)!='0')
end for
|
http://rosettacode.org/wiki/Vigen%C3%A8re_cipher | Vigenère cipher | Task
Implement a  Vigenère cypher,  both encryption and decryption.
The program should handle keys and text of unequal length,
and should capitalize everything and discard non-alphabetic characters.
(If your program handles non-alphabetic characters in another way,
make a note of it.)
Related tasks
Β Caesar cipher
Β Rot-13
Β Substitution Cipher
| #Common_Lisp | Common Lisp | (defun strip (s)
(remove-if-not
(lambda (c) (char<= #\A c #\Z))
(string-upcase s)))
Β
(defun vigenère (s key &key decipher
&aux (A (char-code #\A))
(op (if decipher #'- #'+)))
(labels
((to-char (c) (code-char (+ c A)))
(to-code (c) (- (char-code c) A)))
(let ((k (map 'list #'to-code (strip key))))
(setf (cdr (last k)) k)
(map 'string
(lambda (c)
(prog1
(to-char
(mod (funcall op (to-code c) (car k)) 26))
(setf k (cdr k))))
(strip s)))))
Β
(let* ((msg "Beware the Jabberwock... The jaws that... the claws that catch!")
(key "vigenere cipher")
(enc (vigenère msg key))
(dec (vigenère enc key :decipher t)))
(format t "msg: ~a~%enc: ~a~%dec: ~a~%" msg enc dec)) |
http://rosettacode.org/wiki/Visualize_a_tree | Visualize a tree | A tree structure Β (i.e. a rooted, connected acyclic graph) Β is often used in programming.
It's often helpful to visually examine such a structure.
There are many ways to represent trees to a reader, such as:
Β indented text Β (Γ la unix tree command)
Β nested HTML tables
Β hierarchical GUI widgets
Β 2D Β or Β 3D Β images
Β etc.
Task
Write a program to produce a visual representation of some tree.
The content of the tree doesn't matter, nor does the output format, the only requirement being that the output is human friendly.
Make do with the vague term "friendly" the best you can.
| #Haskell | Haskell | data Tree a = Empty | Node { value :: a, left :: Tree a, right :: Tree a }
deriving (Show, Eq)
Β
tree = Node 1 (Node 2 (Node 4 (Node 7 Empty Empty) Empty)
(Node 5 Empty Empty)) (Node 3 (Node 6 (Node 8 Empty Empty)
(Node 9 Empty Empty)) Empty)
Β
treeIndent Empty = ["-- (nil)"]
treeIndent t = ["--" ++ show (value t)]
++ map (" |"++) ls ++ (" `" ++ r):map (" "++) rs
where
(r:rs) = treeIndent$right t
ls = treeIndent$left t
Β
main = mapM_ putStrLn $ treeIndent tree |
http://rosettacode.org/wiki/Walk_a_directory/Non-recursively | Walk a directory/Non-recursively | Task
Walk a given directory and print the names of files matching a given pattern.
(How is "pattern" defined? substring match? DOS pattern? BASH pattern? ZSH pattern? Perl regular expression?)
Note: This task is for non-recursive methods. Β These tasks should read a single directory, not an entire directory tree.
Note: Please be careful when running any code presented here.
Related task
Β Walk Directory Tree Β (read entire directory tree).
| #PicoLisp | PicoLisp | (for F (dir "@src/") # Iterate directory
(when (match '`(chop "[email protected]") (chop F)) # Matches 's*.c'?
(println F) ) ) # Yes: Print it |
http://rosettacode.org/wiki/Walk_a_directory/Non-recursively | Walk a directory/Non-recursively | Task
Walk a given directory and print the names of files matching a given pattern.
(How is "pattern" defined? substring match? DOS pattern? BASH pattern? ZSH pattern? Perl regular expression?)
Note: This task is for non-recursive methods. Β These tasks should read a single directory, not an entire directory tree.
Note: Please be careful when running any code presented here.
Related task
Β Walk Directory Tree Β (read entire directory tree).
| #Pike | Pike | array(string) files = get_dir("/home/foo/bar");
foreach(files, string file)
write(file + "\n"); |
http://rosettacode.org/wiki/Walk_a_directory/Recursively | Walk a directory/Recursively | Task
Walk a given directory tree and print files matching a given pattern.
Note: This task is for recursive methods. Β These tasks should read an entire directory tree, not a single directory.
Note: Please be careful when running any code examples found here.
Related task
Β Walk a directory/Non-recursively Β (read a single directory).
| #Haskell | Haskell | import System.Environment
import System.Directory
import System.FilePath.Find
Β
search pat = find always (fileName ~~? pat)
Β
main = do
[pat] <- getArgs
dir <- getCurrentDirectory
files <- search pat dir
mapM_ putStrLn files |
http://rosettacode.org/wiki/Walk_a_directory/Recursively | Walk a directory/Recursively | Task
Walk a given directory tree and print files matching a given pattern.
Note: This task is for recursive methods. Β These tasks should read an entire directory tree, not a single directory.
Note: Please be careful when running any code examples found here.
Related task
Β Walk a directory/Non-recursively Β (read a single directory).
| #Icon_and_Unicon | Icon and Unicon | Β
###########################
# A sequential solution #
###########################
Β
procedure main()
every write(!getdirs(".")) # writes out all directories from the current directory down
end
Β
procedure getdirs(s) #: return a list of directories beneath the directory 's'
local D,d,f
Β
if ( stat(s).mode ? ="d" ) & ( d := open(s) ) then {
D := [s]
while f := read(d) do
if not ( ".." ? =f ) then # skip . and ..
D |||:= getdirs(s || "/" ||f)
close(d)
return D
}
end
Β
#########################
# A threaded solution #
#########################
Β
import threads
Β
global n, # number of the concurrently running threads
maxT, # Max number of concurrent threads ("soft limit")
tot_threads # the total number of threads created in the program
Β
procedure main(argv)
target := argv[1] | stop("Usage: tdir [dir name] [#threads]. #threads default to 2* the number of cores in the machine.")
tot_threads := n := 1
maxT := ( integer(argv[2])|
(&features? if ="CPU cores " then cores := integer(tab(0)) * 2) | # available cores * 2
4) # default to 4 threads
t := milliseconds()
L := getdirs(target) # writes out all directories from the current directory down
write((*\L)| 0, " directories in ", milliseconds() - t,
" ms using ", maxT, "-concurrent/", tot_threads, "-total threads" )
end
Β
procedure getdirs(s) # return a list of directories beneath the directory 's'
local D,d,f, thrd
Β
if ( stat(s).mode ? ="d" ) & ( d := open(s) ) then {
D := [s]
while f := read(d) do
if not ( ".." ? =f ) then # skip . and ..
if n>=maxT then # max thread count reached
D |||:= getdirs(s || "/" ||f)
else # spawn a new thread for this directory
{/thrd:=[]; n +:= 1; put(thrd, thread getdirs(s || "/" ||f))}
Β
close(d)
Β
if \thrd then{ # If I have threads, collect their results
tot_threads +:= *thrd
n -:= 1 # allow new threads to be spawned while I'm waiting/collecting results
every wait(th := !thrd) do { # wait for the thread to finish
n -:= 1
D |||:= <@th # If the thread produced a result, it is going to be
# stored in its "outbox", <@th in this case serves as
# a deferred return since the thread was created by
# thread getdirs(s || "/" ||f)
# this is similar to co-expression activation semantics
}
n +:= 1
}
return D
}
end |
http://rosettacode.org/wiki/Water_collected_between_towers | Water collected between towers | Task
In a two-dimensional world, we begin with any bar-chart (or row of close-packed 'towers', each of unit width), and then it rains,
completely filling all convex enclosures in the chart with water.
9 ββ 9 ββ
8 ββ 8 ββ
7 ββ ββ 7 ββββββββββββ
6 ββ ββ ββ 6 ββββββββββββ
5 ββ ββ ββ ββββ 5 ββββββββββββββββ
4 ββ ββ ββββββββ 4 ββββββββββββββββ
3 ββββββ ββββββββ 3 ββββββββββββββββ
2 ββββββββββββββββ ββ 2 ββββββββββββββββββββ
1 ββββββββββββββββββββ 1 ββββββββββββββββββββ
In the example above, a bar chart representing the values [5, 3, 7, 2, 6, 4, 5, 9, 1, 2] has filled, collecting 14 units of water.
Write a function, in your language, from a given array of heights, to the number of water units that can be held in this way, by a corresponding bar chart.
Calculate the number of water units that could be collected by bar charts representing each of the following seven series:
[[1, 5, 3, 7, 2],
[5, 3, 7, 2, 6, 4, 5, 9, 1, 2],
[2, 6, 3, 5, 2, 8, 1, 4, 2, 2, 5, 3, 5, 7, 4, 1],
[5, 5, 5, 5],
[5, 6, 7, 8],
[8, 7, 7, 6],
[6, 7, 10, 7, 6]]
See, also:
Four Solutions to a Trivial Problem β a Google Tech Talk by Guy Steele
Water collected between towers on Stack Overflow, from which the example above is taken)
An interesting Haskell solution, using the Tardis monad, by Phil Freeman in a Github gist.
| #Java | Java | public class WaterBetweenTowers {
public static void main(String[] args) {
int i = 1;
int[][] tba = new int[][]{
new int[]{1, 5, 3, 7, 2},
new int[]{5, 3, 7, 2, 6, 4, 5, 9, 1, 2},
new int[]{2, 6, 3, 5, 2, 8, 1, 4, 2, 2, 5, 3, 5, 7, 4, 1},
new int[]{5, 5, 5, 5},
new int[]{5, 6, 7, 8},
new int[]{8, 7, 7, 6},
new int[]{6, 7, 10, 7, 6}
};
Β
for (int[] tea : tba) {
int rht, wu = 0, bof;
do {
for (rht = tea.length - 1; rht >= 0; rht--) {
if (tea[rht] > 0) {
break;
}
}
Β
if (rht < 0) {
break;
}
Β
bof = 0;
for (int col = 0; col <= rht; col++) {
if (tea[col] > 0) {
tea[col]--;
bof += 1;
} else if (bof > 0) {
wu++;
}
}
if (bof < 2) {
break;
}
} while (true);
Β
System.out.printf("BlockΒ %d", i++);
if (wu == 0) {
System.out.print(" does not hold any");
} else {
System.out.printf(" holdsΒ %d", wu);
}
System.out.println(" water units.");
}
}
} |
http://rosettacode.org/wiki/Video_display_modes | Video display modes | The task is to demonstrate how to switch video display modes within the language. A brief description of the supported video modes would be useful.
| #8086_Assembly | 8086 Assembly | mov ah,00h
mov al,videoMode
int 10h |
http://rosettacode.org/wiki/Video_display_modes | Video display modes | The task is to demonstrate how to switch video display modes within the language. A brief description of the supported video modes would be useful.
| #Action.21 | Action! | PROC ShowMode(BYTE m,split,gr
CARD w, BYTE h,
CARD size,
CHAR ARRAY descr)
BYTE CH=$02FC
CARD i
BYTE POINTER ptr
Β
Graphics(0)
PrintF("Next video mode:Β %B%E",m)
IF split THEN
PrintF("Split video mode%E%EUpper part:%E")
FI
Β
IF gr THEN
Print("Graphics")
ELSE
Print("Text")
FI
PrintF(" mode,Β %Ux%B,Β %S%E",w,h,descr)
Β
IF split THEN
PrintF("%ELower part:%EText mode 40x4, 2 luminances%E")
FI
PrintF("%EPress any key to change video mode.")
Β
DO UNTIL CH#$FF OD
CH=$FF
Β
Graphics(m)
ptr=PeekC(88)
Β
FOR i=1 TO size
DO
ptr^=Rand(0)
ptr==+1
OD
Β
DO UNTIL CH#$FF OD
CH=$FF
RETURN
Β
PROC Main()
ShowMode(0,0,0,40,24,960,"2 luminances")
ShowMode(1,1,0,20,20,640,"5 colors")
ShowMode(2,1,0,20,10,400,"5 colors")
ShowMode(3,1,1,40,20,400,"4 colors")
ShowMode(4,1,1,80,40,640,"2 colors")
ShowMode(5,1,1,80,40,1120,"4 colors")
ShowMode(6,1,1,160,80,2080,"2 colors")
ShowMode(7,1,1,160,80,4000,"4 colors")
ShowMode(8,1,1,320,160,7856,"2 luminances")
ShowMode(9,0,1,80,192,7680,"16 luminances")
ShowMode(10,0,1,80,192,7680,"9 colors")
ShowMode(11,0,1,80,192,7680,"16 hues")
ShowMode(12,1,0,40,20,1120,"5 colors")
ShowMode(13,1,0,40,10,640,"5 colors")
ShowMode(14,1,1,160,160,4000,"2 colors")
ShowMode(15,1,1,160,160,7856,"4 colors")
ShowMode(17,0,0,20,24,480,"5 colors")
ShowMode(18,0,0,20,12,240,"5 colors")
ShowMode(19,0,1,40,24,240,"4 colors")
ShowMode(20,0,1,80,48,480,"2 colors")
ShowMode(21,0,1,80,48,960,"4 colors")
ShowMode(22,0,1,160,96,1920,"2 colors")
ShowMode(23,0,1,160,96,3840,"4 colors")
ShowMode(24,0,1,320,192,7680,"2 luminances")
ShowMode(28,0,0,40,24,960,"5 colors")
ShowMode(29,0,0,40,12,480,"5 colors")
ShowMode(30,0,1,160,192,3840,"2 colors")
ShowMode(31,0,1,160,192,7680,"4 colors")
RETURN |
http://rosettacode.org/wiki/Video_display_modes | Video display modes | The task is to demonstrate how to switch video display modes within the language. A brief description of the supported video modes would be useful.
| #AmigaBASIC | AmigaBASIC | SCREEN 1,320,200,5,1 |
http://rosettacode.org/wiki/Verify_distribution_uniformity/Naive | Verify distribution uniformity/Naive | This task is an adjunct to Seven-sided dice from five-sided dice.
Task
Create a function to check that the random integers returned from a small-integer generator function have uniform distribution.
The function should take as arguments:
The function (or object) producing random integers.
The number of times to call the integer generator.
A 'delta' value of some sort that indicates how close to a flat distribution is close enough.
The function should produce:
Some indication of the distribution achieved.
An 'error' if the distribution is not flat enough.
Show the distribution checker working when the produced distribution is flat enough and when it is not. (Use a generator from Seven-sided dice from five-sided dice).
See also:
Verify distribution uniformity/Chi-squared test
| #Hy | Hy | (import [collections [Counter]])
(import [random [randint]])
Β
(defn uniform? [f repeats delta]
; Call 'f' 'repeats' times, then check if the proportion of each
; value seen is within 'delta' of the reciprocal of the count
; of distinct values.
(setv bins (Counter (list-comp (f) [i (range repeats)])))
(setv target (/ 1 (len bins)))
(all (list-comp
(<= (- target delta) (/ n repeats) (+ target delta))
[n (.values bins)]))) |
http://rosettacode.org/wiki/Verify_distribution_uniformity/Naive | Verify distribution uniformity/Naive | This task is an adjunct to Seven-sided dice from five-sided dice.
Task
Create a function to check that the random integers returned from a small-integer generator function have uniform distribution.
The function should take as arguments:
The function (or object) producing random integers.
The number of times to call the integer generator.
A 'delta' value of some sort that indicates how close to a flat distribution is close enough.
The function should produce:
Some indication of the distribution achieved.
An 'error' if the distribution is not flat enough.
Show the distribution checker working when the produced distribution is flat enough and when it is not. (Use a generator from Seven-sided dice from five-sided dice).
See also:
Verify distribution uniformity/Chi-squared test
| #Icon_and_Unicon | Icon and Unicon | # rnd Β : a co-expression, which will generate the random numbers
# n Β : the number of numbers to test
# delta: tolerance in non-uniformity
# This procedure fails if after the sampling the difference
# in uniformity exceeds delta, a proportion of n / number-of-alternatives
procedure verify_uniform (rnd, n, delta)
# generate a table counting the outcome of the generator
results := table (0)
every (1 to n) do results[@rnd] +:= 1
# retrieve the statistics
smallest := n
largest := 0
every num := key(results) do { # record result and limits
write (num || " " || results[num])
if results[num] < smallest then smallest := results[num]
if results[num] > largest then largest := results[num]
}
# decide if difference is within bounds defined by delta
return largest-smallest < delta * n / *results
end
Β
procedure main ()
gen_1 := create (|?10) # uniform integers, 1 to 10
if verify_uniform (gen_1, 1000000, 0.01)
then write ("uniform")
else write ("skewed")
gen_2 := create (|(if ?2 = 1 then 6 else ?10)) # skewed integers, 1 to 10
if verify_uniform (gen_2, 1000000, 0.01)
then write ("uniform")
else write ("skewed")
end |
http://rosettacode.org/wiki/Voronoi_diagram | Voronoi diagram | A Voronoi diagram is a diagram consisting of a number of sites.
Each Voronoi site s also has a Voronoi cell consisting of all points closest to s.
Task
Demonstrate how to generate and display a Voroni diagram.
See algo K-means++ clustering.
| #PureBasic | PureBasic | Structure VCoo
x.i: y.i
Colour.i: FillColour.i
EndStructure
Β
Macro RandInt(MAXLIMIT)
Int(MAXLIMIT*(Random(#MAXLONG)/#MAXLONG))
EndMacro
Β
Macro SQ2(X, Y)
((X)*(X) + (Y)*(Y))
EndMacro
Β
Procedure GenRandomPoints(Array a.VCoo(1), xMax, yMax, cnt)
Protected i, j, k, l
cnt-1
Dim a(cnt)
For i=0 To cnt
a(i)\x = RandInt(xMax): a(i)\y = RandInt(yMax)
j = RandInt(255): k = RandInt(255): l = RandInt(255)
a(i)\Colour = RGBA(j, k, l, 255)
a(i)\FillColour = RGBA(255-j, 255-k, 255-l, 255)
Next i
ProcedureReturn #True
EndProcedure
Β
Procedure MakeVoronoiDiagram(Array a.VCoo(1),xMax, yMax) ; Euclidean
Protected i, x, y, img, dist.d, dt.d
img = CreateImage(#PB_Any, xMax+1, yMax+1)
If StartDrawing(ImageOutput(img))
For y=0 To yMax
For x=0 To xMax
dist = Infinity()
For i=0 To ArraySize(a())
dt = SQ2(x-a(i)\x, y-a(i)\y)
If dt > dist
Continue
ElseIf dt < dist
dist = dt
Plot(x,y,a(i)\FillColour)
Else ; 'Owner ship' is unclear, set pixel to transparent.
Plot(x,y,RGBA(0, 0, 0, 0))
EndIf
Next
Next
Next
For i=0 To ArraySize(a())
Circle(a(i)\x, a(i)\y, 1, a(i)\Colour)
Next
StopDrawing()
EndIf
ProcedureReturn img
EndProcedure
Β
; Main code
Define img, x, y, file$
Dim V.VCoo(0)
x = 640: y = 480
If Not GenRandomPoints(V(), x, y, 150): End: EndIf
img = MakeVoronoiDiagram(V(), x, y)
If img And OpenWindow(0, 0, 0, x, y, "Voronoi Diagram in PureBasic", #PB_Window_SystemMenu)
ImageGadget(0, 0, 0, x, y, ImageID(img))
Repeat: Until WaitWindowEvent() = #PB_Event_CloseWindow
EndIf
Β
UsePNGImageEncoder()
file$ = SaveFileRequester("Save Image?", "Voronoi_Diagram_in_PureBasic.png", "PNG|*.png", 0)
If file$ <> ""
SaveImage(img, file$, #PB_ImagePlugin_PNG)
EndIf |
http://rosettacode.org/wiki/Verify_distribution_uniformity/Chi-squared_test | Verify distribution uniformity/Chi-squared test | Task
Write a function to verify that a given distribution of values is uniform by using the
Ο
2
{\displaystyle \chi ^{2}}
test to see if the distribution has a likelihood of happening of at least the significance level (conventionally 5%).
The function should return a boolean that is true if the distribution is one that a uniform distribution (with appropriate number of degrees of freedom) may be expected to produce.
Reference
Β an entry at the MathWorld website: Β chi-squared distribution.
| #Fortran | Fortran | module gsl_mini_bind_m
Β
use iso_c_binding
implicit none
private
Β
public :: p_value
Β
interface
function gsl_cdf_chisq_q(x, nu) bind(c, name='gsl_cdf_chisq_Q')
import
real(c_double), value :: x
real(c_double), value :: nu
real(c_double) :: gsl_cdf_chisq_q
end function gsl_cdf_chisq_q
end interface
Β
contains
Β
!> Get p-value from chi-square distribution
real function p_value(x, df)
real, intent(in) :: x
integer, intent(in) :: df
Β
p_value = real(gsl_cdf_chisq_q(real(x, c_double), real(df, c_double)))
Β
end function p_value
Β
end module gsl_mini_bind_m |
http://rosettacode.org/wiki/Verhoeff_algorithm | Verhoeff algorithm | Description
The Verhoeff algorithm is a checksum formula for error detection developed by the Dutch mathematician Jacobus Verhoeff and first published in 1969. It was the first decimal check digit algorithm which detects all single-digit errors, and all transposition errors involving two adjacent digits, which was at the time thought impossible with such a code.
As the workings of the algorithm are clearly described in the linked Wikipedia article they will not be repeated here.
Task
Write routines, methods, procedures etc. in your language to generate a Verhoeff checksum digit for non-negative integers of any length and to validate the result. A combined routine is also acceptable.
The more mathematically minded may prefer to generate the 3 tables required from the description provided rather than to hard-code them.
Write your routines in such a way that they can optionally display digit by digit calculations as in the Wikipedia example.
Use your routines to calculate check digits for the integers: 236, 12345 and 123456789012 and then validate them. Also attempt to validate the same integers if the check digits in all cases were 9 rather than what they actually are.
Display digit by digit calculations for the first two integers but not for the third.
Related task
Β Damm algorithm
| #Python | Python | MULTIPLICATION_TABLE = [
(0, 1, 2, 3, 4, 5, 6, 7, 8, 9),
(1, 2, 3, 4, 0, 6, 7, 8, 9, 5),
(2, 3, 4, 0, 1, 7, 8, 9, 5, 6),
(3, 4, 0, 1, 2, 8, 9, 5, 6, 7),
(4, 0, 1, 2, 3, 9, 5, 6, 7, 8),
(5, 9, 8, 7, 6, 0, 4, 3, 2, 1),
(6, 5, 9, 8, 7, 1, 0, 4, 3, 2),
(7, 6, 5, 9, 8, 2, 1, 0, 4, 3),
(8, 7, 6, 5, 9, 3, 2, 1, 0, 4),
(9, 8, 7, 6, 5, 4, 3, 2, 1, 0),
]
Β
INV = (0, 4, 3, 2, 1, 5, 6, 7, 8, 9)
Β
PERMUTATION_TABLE = [
(0, 1, 2, 3, 4, 5, 6, 7, 8, 9),
(1, 5, 7, 6, 2, 8, 3, 0, 9, 4),
(5, 8, 0, 3, 7, 9, 6, 1, 4, 2),
(8, 9, 1, 6, 0, 4, 3, 5, 2, 7),
(9, 4, 5, 3, 1, 2, 6, 8, 7, 0),
(4, 2, 8, 6, 5, 7, 3, 9, 0, 1),
(2, 7, 9, 3, 8, 0, 6, 4, 1, 5),
(7, 0, 4, 6, 9, 1, 3, 2, 5, 8),
]
Β
def verhoeffchecksum(n, validate=True, terse=True, verbose=False):
"""
Calculate the Verhoeff checksum over `n`.
Terse mode or with single argument: return True if valid (last digit is a correct check digit).
If checksum mode, return the expected correct checksum digit.
If validation mode, return True if last digit checks correctly.
"""
if verbose:
print(f"\n{'Validation' if validate else 'Check digit'}",\
f"calculations for {n}:\n\n i nα΅’ p[i,nα΅’] c\n------------------")
# transform number list
c, dig = 0, list(str(n if validate else 10 * n))
for i, ni in enumerate(dig[::-1]):
p = PERMUTATION_TABLE[iΒ % 8][int(ni)]
c = MULTIPLICATION_TABLE[c][p]
if verbose:
print(f"{i:2} {ni} {p} {c}")
Β
if verbose and not validate:
print(f"\ninv({c}) = {INV[c]}")
if not terse:
print(f"\nThe validation for '{n}' is {'correct' if c == 0 else 'incorrect'}."\
if validate else f"\nThe check digit for '{n}' is {INV[c]}.")
return c == 0 if validate else INV[c]
Β
if __name__ == '__main__':
Β
for n, va, t, ve in [
(236, False, False, True), (2363, True, False, True), (2369, True, False, True),
(12345, False, False, True), (123451, True, False, True), (123459, True, False, True),
(123456789012, False, False, False), (1234567890120, True, False, False),
(1234567890129, True, False, False)]:
verhoeffchecksum(n, va, t, ve)
Β |
http://rosettacode.org/wiki/Vigen%C3%A8re_cipher | Vigenère cipher | Task
Implement a  Vigenère cypher,  both encryption and decryption.
The program should handle keys and text of unequal length,
and should capitalize everything and discard non-alphabetic characters.
(If your program handles non-alphabetic characters in another way,
make a note of it.)
Related tasks
Β Caesar cipher
Β Rot-13
Β Substitution Cipher
| #D | D | import std.stdio, std.string;
Β
string encrypt(in string txt, in string key) pure @safe
in {
assert(key.removechars("^A-Z") == key);
} body {
string res;
foreach (immutable i, immutable c; txt.toUpper.removechars("^A-Z"))
res ~= (c + key[i % $] - 2 * 'A') % 26 + 'A';
return res;
}
Β
string decrypt(in string txt, in string key) pure @safe
in {
assert(key.removechars("^A-Z") == key);
} body {
string res;
foreach (immutable i, immutable c; txt.toUpper.removechars("^A-Z"))
res ~= (c - key[i % $] + 26) % 26 + 'A';
return res;
}
Β
void main() {
immutable key = "VIGENERECIPHER";
immutable original = "Beware the Jabberwock, my son!" ~
" The jaws that bite, the claws that catch!";
immutable encoded = original.encrypt(key);
writeln(encoded, "\n", encoded.decrypt(key));
} |
http://rosettacode.org/wiki/Visualize_a_tree | Visualize a tree | A tree structure Β (i.e. a rooted, connected acyclic graph) Β is often used in programming.
It's often helpful to visually examine such a structure.
There are many ways to represent trees to a reader, such as:
Β indented text Β (Γ la unix tree command)
Β nested HTML tables
Β hierarchical GUI widgets
Β 2D Β or Β 3D Β images
Β etc.
Task
Write a program to produce a visual representation of some tree.
The content of the tree doesn't matter, nor does the output format, the only requirement being that the output is human friendly.
Make do with the vague term "friendly" the best you can.
| #Icon_and_Unicon | Icon and Unicon | procedure main(A)
showTree("", " -", [1, [2,[3],[4,[5],[6]],[7,[11]]], [8,[9,[10]]] ])
write()
showTree("", " -", [1, [2,[3,[4]]], [5,[6],[7,[8],[9]],[10]] ])
end
Β
procedure showTree(prefix, lastc, A)
write(prefix, lastc, "--", A[1])
if *A > 1 then {
prefix ||:= if prefix[-1] == "|" then " " else " "
every showTree(prefix||"|", "-", !A[2:2 < *A])
showTree(prefix, "`-", A[*A])
}
end |
http://rosettacode.org/wiki/Walk_a_directory/Non-recursively | Walk a directory/Non-recursively | Task
Walk a given directory and print the names of files matching a given pattern.
(How is "pattern" defined? substring match? DOS pattern? BASH pattern? ZSH pattern? Perl regular expression?)
Note: This task is for non-recursive methods. Β These tasks should read a single directory, not an entire directory tree.
Note: Please be careful when running any code presented here.
Related task
Β Walk Directory Tree Β (read entire directory tree).
| #Pop11 | Pop11 | lvars repp, fil;
;;; create path repeater
sys_file_match('*.p', '', false, 0) -> repp;
;;; iterate over files
while (repp() ->> fil) /= termin do
Β ;;; print the file
printf(fil, '%s\n');
endwhile; |
http://rosettacode.org/wiki/Walk_a_directory/Non-recursively | Walk a directory/Non-recursively | Task
Walk a given directory and print the names of files matching a given pattern.
(How is "pattern" defined? substring match? DOS pattern? BASH pattern? ZSH pattern? Perl regular expression?)
Note: This task is for non-recursive methods. Β These tasks should read a single directory, not an entire directory tree.
Note: Please be careful when running any code presented here.
Related task
Β Walk Directory Tree Β (read entire directory tree).
| #PowerShell | PowerShell | Get-ChildItem *.txt -Name
Get-ChildItem f* -Name |
http://rosettacode.org/wiki/Walk_a_directory/Recursively | Walk a directory/Recursively | Task
Walk a given directory tree and print files matching a given pattern.
Note: This task is for recursive methods. Β These tasks should read an entire directory tree, not a single directory.
Note: Please be careful when running any code examples found here.
Related task
Β Walk a directory/Non-recursively Β (read a single directory).
| #IDL | IDL | result = file_search( directory, '*.txt', count=cc ) |
http://rosettacode.org/wiki/Walk_a_directory/Recursively | Walk a directory/Recursively | Task
Walk a given directory tree and print files matching a given pattern.
Note: This task is for recursive methods. Β These tasks should read an entire directory tree, not a single directory.
Note: Please be careful when running any code examples found here.
Related task
Β Walk a directory/Non-recursively Β (read a single directory).
| #J | J | require 'dir'
>{."1 dirtree '*.html' |
http://rosettacode.org/wiki/Water_collected_between_towers | Water collected between towers | Task
In a two-dimensional world, we begin with any bar-chart (or row of close-packed 'towers', each of unit width), and then it rains,
completely filling all convex enclosures in the chart with water.
9 ββ 9 ββ
8 ββ 8 ββ
7 ββ ββ 7 ββββββββββββ
6 ββ ββ ββ 6 ββββββββββββ
5 ββ ββ ββ ββββ 5 ββββββββββββββββ
4 ββ ββ ββββββββ 4 ββββββββββββββββ
3 ββββββ ββββββββ 3 ββββββββββββββββ
2 ββββββββββββββββ ββ 2 ββββββββββββββββββββ
1 ββββββββββββββββββββ 1 ββββββββββββββββββββ
In the example above, a bar chart representing the values [5, 3, 7, 2, 6, 4, 5, 9, 1, 2] has filled, collecting 14 units of water.
Write a function, in your language, from a given array of heights, to the number of water units that can be held in this way, by a corresponding bar chart.
Calculate the number of water units that could be collected by bar charts representing each of the following seven series:
[[1, 5, 3, 7, 2],
[5, 3, 7, 2, 6, 4, 5, 9, 1, 2],
[2, 6, 3, 5, 2, 8, 1, 4, 2, 2, 5, 3, 5, 7, 4, 1],
[5, 5, 5, 5],
[5, 6, 7, 8],
[8, 7, 7, 6],
[6, 7, 10, 7, 6]]
See, also:
Four Solutions to a Trivial Problem β a Google Tech Talk by Guy Steele
Water collected between towers on Stack Overflow, from which the example above is taken)
An interesting Haskell solution, using the Tardis monad, by Phil Freeman in a Github gist.
| #JavaScript | JavaScript | (function () {
'use strict';
Β
// waterCollectedΒ :: [Int] -> Int
var waterCollected = function (xs) {
return sum( // water above each bar
zipWith(function (a, b) {
return a - b; // difference between water level and bar
},
zipWith(min, // lower of two flanking walls
scanl1(max, xs), // highest walls to left
scanr1(max, xs) // highest walls to right
),
xs // tops of bars
)
.filter(function (x) {
return x > 0; // only bars with water above them
})
);
};
Β
// GENERIC FUNCTIONS ----------------------------------------
Β
// zipWithΒ :: (a -> b -> c) -> [a] -> [b] -> [c]
var zipWith = function (f, xs, ys) {
var ny = ys.length;
return (xs.length <= ny ? xs : xs.slice(0, ny))
.map(function (x, i) {
return f(x, ys[i]);
});
};
Β
// scanl1 is a variant of scanl that has no starting value argument
// scanl1Β :: (a -> a -> a) -> [a] -> [a]
var scanl1 = function (f, xs) {
return xs.length > 0 ? scanl(f, xs[0], xs.slice(1)) : [];
};
Β
// scanr1 is a variant of scanr that has no starting value argument
// scanr1Β :: (a -> a -> a) -> [a] -> [a]
var scanr1 = function (f, xs) {
return xs.length > 0 ? scanr(f, xs.slice(-1)[0], xs.slice(0, -1)) : [];
};
Β
// scanlΒ :: (b -> a -> b) -> b -> [a] -> [b]
var scanl = function (f, startValue, xs) {
var lst = [startValue];
return xs.reduce(function (a, x) {
var v = f(a, x);
return lst.push(v), v;
}, startValue), lst;
};
Β
// scanrΒ :: (b -> a -> b) -> b -> [a] -> [b]
var scanr = function (f, startValue, xs) {
var lst = [startValue];
return xs.reduceRight(function (a, x) {
var v = f(a, x);
return lst.push(v), v;
}, startValue), lst.reverse();
};
Β
// sumΒ :: (Num a) => [a] -> a
var sum = function (xs) {
return xs.reduce(function (a, x) {
return a + x;
}, 0);
};
Β
// maxΒ :: Ord a => a -> a -> a
var max = function (a, b) {
return a > b ? a : b;
};
Β
// minΒ :: Ord a => a -> a -> a
var min = function (a, b) {
return b < a ? b : a;
};
Β
// TEST ---------------------------------------------------
return [
[1, 5, 3, 7, 2],
[5, 3, 7, 2, 6, 4, 5, 9, 1, 2],
[2, 6, 3, 5, 2, 8, 1, 4, 2, 2, 5, 3, 5, 7, 4, 1],
[5, 5, 5, 5],
[5, 6, 7, 8],
[8, 7, 7, 6],
[6, 7, 10, 7, 6]
].map(waterCollected);
Β
//--> [2, 14, 35, 0, 0, 0, 0]
})(); |
http://rosettacode.org/wiki/Video_display_modes | Video display modes | The task is to demonstrate how to switch video display modes within the language. A brief description of the supported video modes would be useful.
| #Applesoft_BASIC | Applesoft BASIC | TEXT, page 1, 40 x 24
GR, page 1, 40 x 40, 16 colors, mixed with four lines of text
HGR, page 1, 280 x 160, 6 colors, mixed with four lines of text
HGR2, page 2, 280 x 192, 6 colors, full screen
text, page 2, 40 x 24
gr, page 1, 40 x 48, 16 colors, full screen
gr, page 2, 40 x 40, 16 colors, mixed with four lines of text
gr, page 2, 40 x 48, 16 colors, full screen
hgr, page 1, 280 x 192, 6 colors, full screen
hgr, page 2, 280 x 160, 6 colors, mixed with four lines of text
|
http://rosettacode.org/wiki/Video_display_modes | Video display modes | The task is to demonstrate how to switch video display modes within the language. A brief description of the supported video modes would be useful.
| #ARM_Assembly | ARM Assembly | Β
MOV R1,#0x04000000
MOV R0,#0x403
STR r0,[r1] ;the game boy advance is little-endian, so I would have expected this not to work. However it does indeed work.
Β |
http://rosettacode.org/wiki/Video_display_modes | Video display modes | The task is to demonstrate how to switch video display modes within the language. A brief description of the supported video modes would be useful.
| #BBC_BASIC | BBC BASIC | 10 MODE 1: REM 320x256 4 colour graphics |
http://rosettacode.org/wiki/Video_display_modes | Video display modes | The task is to demonstrate how to switch video display modes within the language. A brief description of the supported video modes would be useful.
| #Commodore_BASIC | Commodore BASIC | 10 rem video modes - c64
15 rem rosetta code
20 print chr$(147);chr$(14):poke 53280,0:poke 53281,0:poke 646,1
25 poke 53282,2:poke 53283,11:poke 53284,9:rem set extended and multi colors
30 if peek(12288)=60 and peek(12289)=102 then goto 100
35 poke 52,32:poke 56,32:clr
40 print "Initializing - Please wait..."
45 poke 56334,peek(56334) and 254:poke1,peek(1) and 251
50 for i=0 to 4096:poke i+12288,peek(i+53248):next
55 poke1,peek(1) or 4:poke56334,peek(56334) or 1
60 for i=0 to 31:read d:poke 15368+i,d:next i
65 x=0:for i=8192 to 10239:poke i,2^x:x=(x+1) and 7:next
70 for i=10240 to 12287:poke i,228:next
100 data 60,66,165,129,165,153,66,60
105 data 60,66,165,129,153,165,66,60
110 data 245,245,245,245,10,10,10,10
115 data 10,10,10,10,245,245,245,245
480 print chr$(147);"Demonstration of Video Modes"
485 print
490 print "The video modes described at Rosetta "
495 print "Code will be demonstrated in order. "
500 print "Simply press a key to advance to the"
505 print "next video mode."
510 print
515 print "See rosettacode.org for description."
516 print
517 print "http://www.rosettacode.org/wiki/";
518 print "Video";chr$(164);"display";chr$(164);"modes#";
519 print "Commodore";chr$(164);"BASIC"
520 print
525 print "Press any key to begin."
530 gosub 9010
600 print chr$(147);"Standard Character Mode"
605 print " - ROM Characters"
610 print:gosub 1000:print:gosub 9000:print chr$(147)
615 gosub 1210
620 print chr$(147);"Multicolor Character Mode"
625 print " - ROM Characters"
630 print:gosub 1000:print:gosub 9000:print chr$(147)
635 gosub 1220
640 gosub 1310
645 print chr$(147);"Extended Color Character Mode"
650 print " - ROM Characters"
655 print:gosub 1000:print:gosub 9000:print chr$(147)
660 gosub 1320
665 gosub 1100
670 print chr$(147);"Standard Character Mode"
675 print " - Programmed Characters"
680 print:gosub 1000:print:gosub 9000:print chr$(147)
685 gosub 1210
690 print chr$(147);"Multicolor Character Mode"
695 print " - Programmed Characters"
700 print:gosub 1000:print:gosub 9000:print chr$(147)
705 gosub 1220
710 gosub 1310
715 print chr$(147);"Extended Color Character Mode"
720 print " - Programmed Characters"
725 print:gosub 1000:print:gosub 9000:print chr$(147)
730 gosub 1320
735 print chr$(147);"The next screen will be the"
740 print "High Resolution Bit Map Mode"
745 print
750 gosub 9000
755 gosub 1430:gosub 1410
760 print:gosub 1050:print:gosub 9010:print chr$(147)
765 gosub 1420:gosub 1120
770 print chr$(147);"The next screen will be the"
775 print "Multicolor High Resolution Bit Map Mode"
780 print
785 gosub 9000
790 gosub 1430:gosub 1410:gosub 1210
795 print:gosub 1050:print:gosub 9010:print chr$(147)
800 gosub 1420:gosub 1220:gosub 1120
805 print chr$(147);"End of demonstration."
810 end
1000 rem put some characters up for demo
1005 for i=0 to 15:poke 646,i
1010 print" a b c d ";
1011 print chr$(160);"A";chr$(160);"B";chr$(160);"C";chr$(160);"D";chr$(160);
1012 print chr$(18);" a b c d ";
1013 print chr$(160);"A";chr$(160);"B";chr$(160);"C";chr$(160);"D";chr$(160);
1014 print chr$(146)
1015 next i:poke 646,1
1020 return
1050 rem show color variety for hi-res modes
1051 print chr$(147)
1055 for i=0 to 255:poke 1024+i,i:poke 55296+i,1:next
1060 for i=0 to 255:poke 1280+i,i:poke 55552+i,int(rnd(1)*16):next
1065 return
1100 rem programmable character mode
1110 poke 53272,(peek(53272) and 240)+14:return:rem on
1120 poke 53272,(peek(53272) and 240)+6:return:rem off
1200 rem multicolor mode
1210 poke 53270,peek(53270) or 16:return:rem on
1220 poke 53270,peek(53270) and 239:return:rem off
1300 rem extended color mode
1310 poke 53265,peek(53265) or 64:return:rem on
1320 poke 53265,peek(53265) and 191:return:rem off
1400 rem hi res mode
1410 poke 53265,(peek(53265) or 32):return:rem on
1420 poke 53265,(peek(53265) and 223):return:rem off
1430 poke 53272,peek(53272) or 8:return:rem place bitmap at 8192
9000 print "Press any key for next screen.";
9010 get k$:if k$="" then 9010
9020 return |
http://rosettacode.org/wiki/Verify_distribution_uniformity/Naive | Verify distribution uniformity/Naive | This task is an adjunct to Seven-sided dice from five-sided dice.
Task
Create a function to check that the random integers returned from a small-integer generator function have uniform distribution.
The function should take as arguments:
The function (or object) producing random integers.
The number of times to call the integer generator.
A 'delta' value of some sort that indicates how close to a flat distribution is close enough.
The function should produce:
Some indication of the distribution achieved.
An 'error' if the distribution is not flat enough.
Show the distribution checker working when the produced distribution is flat enough and when it is not. (Use a generator from Seven-sided dice from five-sided dice).
See also:
Verify distribution uniformity/Chi-squared test
| #J | J | checkUniform=: adverb define
0.05 u checkUniform y
Β :
n=. */y
delta=. x
sample=. u n NB. the "u" refers to the verb to left of adverb
freqtable=. /:~ (~. sample) ,. #/.~ sample
expected=. nΒ % # freqtable
errmsg=. 'Distribution is potentially skewed'
errmsg assert (delta * expected) > | expected - {:"1 freqtable
freqtable
) |
http://rosettacode.org/wiki/Verify_distribution_uniformity/Naive | Verify distribution uniformity/Naive | This task is an adjunct to Seven-sided dice from five-sided dice.
Task
Create a function to check that the random integers returned from a small-integer generator function have uniform distribution.
The function should take as arguments:
The function (or object) producing random integers.
The number of times to call the integer generator.
A 'delta' value of some sort that indicates how close to a flat distribution is close enough.
The function should produce:
Some indication of the distribution achieved.
An 'error' if the distribution is not flat enough.
Show the distribution checker working when the produced distribution is flat enough and when it is not. (Use a generator from Seven-sided dice from five-sided dice).
See also:
Verify distribution uniformity/Chi-squared test
| #Java | Java | import static java.lang.Math.abs;
import java.util.*;
import java.util.function.IntSupplier;
Β
public class Test {
Β
static void distCheck(IntSupplier f, int nRepeats, double delta) {
Map<Integer, Integer> counts = new HashMap<>();
Β
for (int i = 0; i < nRepeats; i++)
counts.compute(f.getAsInt(), (k, v) -> v == null ? 1 : v + 1);
Β
double target = nRepeats / (double) counts.size();
int deltaCount = (int) (delta / 100.0 * target);
Β
counts.forEach((k, v) -> {
if (abs(target - v) >= deltaCount)
System.out.printf("distribution potentially skewed "
+ "for '%s': '%d'%n", k, v);
});
Β
counts.keySet().stream().sorted().forEach(k
-> System.out.printf("%dΒ %d%n", k, counts.get(k)));
}
Β
public static void main(String[] a) {
distCheck(() -> (int) (Math.random() * 5) + 1, 1_000_000, 1);
}
} |
http://rosettacode.org/wiki/Variable-length_quantity | Variable-length quantity | Implement some operations on variable-length quantities, at least including conversions from a normal number in the language to the binary representation of the variable-length quantity for that number, and vice versa. Any variants are acceptable.
Task
With above operations,
convert these two numbers 0x200000 (2097152 in decimal) and 0x1fffff (2097151 in decimal) into sequences of octets (an eight-bit byte);
display these sequences of octets;
convert these sequences of octets back to numbers, and check that they are equal to original numbers.
| #11l | 11l | F to_str(v)
R β[ βv.map(n -> hex(n).lowercase().zfill(2)).join(β β)β ]β
Β
F to_seq(UInt64 x)
V i = 0
L(ii) (9.<0).step(-1)
I x [&] (UInt64(127) << ii * 7)Β != 0
i = ii
L.break
Β
[Byte] out
L(j) 0 .. i
out [+]= ((x >> ((i - j) * 7)) [&] 127) [|] 128
Β
out[i] (+)= 128
R out
Β
F from_seq(seq)
UInt64 r = 0
Β
L(b) seq
r = (r << 7) [|] (b [&] 127)
Β
R r
Β
L(x) [UInt64(7'F), 40'00, 0, 003F'FFFE, 001F'FFFF, 0020'0000, 3311'A123'4DF3'1413]
V s = to_seq(x)
print(βseq from βhex(x).lowercase()β βto_str(s)β back: βhex(from_seq(s)).lowercase()) |
http://rosettacode.org/wiki/Voronoi_diagram | Voronoi diagram | A Voronoi diagram is a diagram consisting of a number of sites.
Each Voronoi site s also has a Voronoi cell consisting of all points closest to s.
Task
Demonstrate how to generate and display a Voroni diagram.
See algo K-means++ clustering.
| #Python | Python | from PIL import Image
import random
import math
Β
def generate_voronoi_diagram(width, height, num_cells):
image = Image.new("RGB", (width, height))
putpixel = image.putpixel
imgx, imgy = image.size
nx = []
ny = []
nr = []
ng = []
nb = []
for i in range(num_cells):
nx.append(random.randrange(imgx))
ny.append(random.randrange(imgy))
nr.append(random.randrange(256))
ng.append(random.randrange(256))
nb.append(random.randrange(256))
for y in range(imgy):
for x in range(imgx):
dmin = math.hypot(imgx-1, imgy-1)
j = -1
for i in range(num_cells):
d = math.hypot(nx[i]-x, ny[i]-y)
if d < dmin:
dmin = d
j = i
putpixel((x, y), (nr[j], ng[j], nb[j]))
image.save("VoronoiDiagram.png", "PNG")
image.show()
Β
generate_voronoi_diagram(500, 500, 25) |
http://rosettacode.org/wiki/Verify_distribution_uniformity/Chi-squared_test | Verify distribution uniformity/Chi-squared test | Task
Write a function to verify that a given distribution of values is uniform by using the
Ο
2
{\displaystyle \chi ^{2}}
test to see if the distribution has a likelihood of happening of at least the significance level (conventionally 5%).
The function should return a boolean that is true if the distribution is one that a uniform distribution (with appropriate number of degrees of freedom) may be expected to produce.
Reference
Β an entry at the MathWorld website: Β chi-squared distribution.
| #Go | Go | package main
Β
import (
"fmt"
"math"
)
Β
type ifctn func(float64) float64
Β
func simpson38(f ifctn, a, b float64, n int) float64 {
h := (b - a) / float64(n)
h1 := h / 3
sum := f(a) + f(b)
for j := 3*n - 1; j > 0; j-- {
if j%3 == 0 {
sum += 2 * f(a+h1*float64(j))
} else {
sum += 3 * f(a+h1*float64(j))
}
}
return h * sum / 8
}
Β
func gammaIncQ(a, x float64) float64 {
aa1 := a - 1
var f ifctn = func(t float64) float64 {
return math.Pow(t, aa1) * math.Exp(-t)
}
y := aa1
h := 1.5e-2
for f(y)*(x-y) > 2e-8 && y < x {
y += .4
}
if y > x {
y = x
}
return 1 - simpson38(f, 0, y, int(y/h/math.Gamma(a)))
}
Β
func chi2ud(ds []int) float64 {
var sum, expected float64
for _, d := range ds {
expected += float64(d)
}
expected /= float64(len(ds))
for _, d := range ds {
x := float64(d) - expected
sum += x * x
}
return sum / expected
}
Β
func chi2p(dof int, distance float64) float64 {
return gammaIncQ(.5*float64(dof), .5*distance)
}
Β
const sigLevel = .05
Β
func main() {
for _, dset := range [][]int{
{199809, 200665, 199607, 200270, 199649},
{522573, 244456, 139979, 71531, 21461},
} {
utest(dset)
}
}
Β
func utest(dset []int) {
fmt.Println("Uniform distribution test")
var sum int
for _, c := range dset {
sum += c
}
fmt.Println(" dataset:", dset)
fmt.Println(" samples: ", sum)
fmt.Println(" categories: ", len(dset))
Β
dof := len(dset) - 1
fmt.Println(" degrees of freedom: ", dof)
Β
dist := chi2ud(dset)
fmt.Println(" chi square test statistic: ", dist)
Β
p := chi2p(dof, dist)
fmt.Println(" p-value of test statistic: ", p)
Β
sig := p < sigLevel
fmt.Printf(" significant atΒ %2.0f%% level? Β %t\n", sigLevel*100, sig)
fmt.Println(" uniform? ", !sig, "\n")
} |
http://rosettacode.org/wiki/Verhoeff_algorithm | Verhoeff algorithm | Description
The Verhoeff algorithm is a checksum formula for error detection developed by the Dutch mathematician Jacobus Verhoeff and first published in 1969. It was the first decimal check digit algorithm which detects all single-digit errors, and all transposition errors involving two adjacent digits, which was at the time thought impossible with such a code.
As the workings of the algorithm are clearly described in the linked Wikipedia article they will not be repeated here.
Task
Write routines, methods, procedures etc. in your language to generate a Verhoeff checksum digit for non-negative integers of any length and to validate the result. A combined routine is also acceptable.
The more mathematically minded may prefer to generate the 3 tables required from the description provided rather than to hard-code them.
Write your routines in such a way that they can optionally display digit by digit calculations as in the Wikipedia example.
Use your routines to calculate check digits for the integers: 236, 12345 and 123456789012 and then validate them. Also attempt to validate the same integers if the check digits in all cases were 9 rather than what they actually are.
Display digit by digit calculations for the first two integers but not for the third.
Related task
Β Damm algorithm
| #Raku | Raku | my @d = [^10] xx 5;
@d[$_][^5].=rotate($_), @d[$_][5..*].=rotate($_) for 1..4;
push @d: [@d[$_].reverse] for flat 1..4, 0;
Β
my @i = 0,4,3,2,1,5,6,7,8,9;
Β
my %h = flat (0,1,5,8,9,4,2,7,0).rotor(2 =>-1).map({.[0]=>.[1]}), 6=>3, 3=>6;
my @p = [^10],;
@p.push: [@p[*-1].map: {%h{$_}}] for ^7;
Β
sub checksum (Int $int where * β₯ 0, :$verbose = True ) {
my @digits = $int.comb;
say "\nCheckdigit calculation for $int:";
say " i ni p(i, ni) c" if $verbose;
my ($i, $p, $c) = 0 xx 3;
say " $i 0 $p $c" if $verbose;
for @digits.reverse {
++$i;
$p = @p[$i % 8][$_];
$c = @d[$c; $p];
say "{$i.fmt('%2d')} $_ $p $c" if $verbose;
}
say "Checkdigit: {@i[$c]}";
+($int ~ @i[$c]);
}
Β
sub validate (Int $int where * β₯ 0, :$verbose = True) {
my @digits = $int.comb;
say "\nValidation calculation for $int:";
say " i ni p(i, ni) c" if $verbose;
my ($i, $p, $c) = 0 xx 3;
for @digits.reverse {
$p = @p[$i % 8][$_];
$c = @d[$c; $p];
say "{$i.fmt('%2d')} $_ $p $c" if $verbose;
++$i;
}
say "Checkdigit: {'in' if $c}correct";
}
Β
## TESTING
Β
for 236, 12345, 123456789012 -> $int {
my $check = checksum $int, :verbose( $int.chars < 8 );
validate $check, :verbose( $int.chars < 8 );
validate +($check.chop ~ 9), :verbose( $int.chars < 8 );
} |
http://rosettacode.org/wiki/Vigen%C3%A8re_cipher | Vigenère cipher | Task
Implement a  Vigenère cypher,  both encryption and decryption.
The program should handle keys and text of unequal length,
and should capitalize everything and discard non-alphabetic characters.
(If your program handles non-alphabetic characters in another way,
make a note of it.)
Related tasks
Β Caesar cipher
Β Rot-13
Β Substitution Cipher
| #Elena | Elena | import system'text;
import system'math;
import system'routines;
import extensions;
Β
class VCipher
{
string encrypt(string txt, string pw, int d)
{
auto outputΒ := new TextBuilder();
int pwiΒ := 0;
Β
string PWΒ := pw.upperCase();
Β
txt.upperCase().forEach:(t)
{
if(t >= $65)
{
int tmpΒ := t.toInt() - 65 + d * (PW[pwi].toInt() - 65);
if (tmp < 0)
{
tmp += 26
};
output.write((65 + tmp.mod:26).toChar());
pwi += 1;
if (pwi == PW.Length) { pwiΒ := 0 }
}
};
Β
^ output.Value
}
}
Β
public program()
{
var vΒ := new VCipher();
Β
var s0Β := "Beware the Jabberwock, my son! The jaws that bite, the claws that catch!";
var pwΒ := "VIGENERECIPHER";
Β
console.printLine(s0,newLine,pw,newLine);
var s1Β := v.encrypt(s0, pw, 1);
console.printLine("Encrypted:",s1);
s1Β := v.encrypt(s1, "VIGENERECIPHER", -1);
console.printLine("Decrypted:",s1);
console.printLine("Press any key to continue..");
console.readChar()
} |
http://rosettacode.org/wiki/Vigen%C3%A8re_cipher | Vigenère cipher | Task
Implement a  Vigenère cypher,  both encryption and decryption.
The program should handle keys and text of unequal length,
and should capitalize everything and discard non-alphabetic characters.
(If your program handles non-alphabetic characters in another way,
make a note of it.)
Related tasks
Β Caesar cipher
Β Rot-13
Β Substitution Cipher
| #Elixir | Elixir | defmodule VigenereCipher do
@base Β ?A
@size Β ?Z - @base + 1
Β
def encrypt(text, key), do: crypt(text, key, 1)
Β
def decrypt(text, key), do: crypt(text, key, -1)
Β
defp crypt(text, key, dir) do
text = String.upcase(text) |> String.replace(~r/[^A-Z]/, "") |> to_char_list
key_iterator = String.upcase(key) |> String.replace(~r/[^A-Z]/, "") |> to_char_list
|> Enum.map(fn c -> (c - @base) * dir end) |> Stream.cycle
Enum.zip(text, key_iterator)
|> Enum.reduce('', fn {char, offset}, ciphertext ->
[rem(char - @base + offset + @size, @size) + @base | ciphertext]
end)
|> Enum.reverse |> List.to_string
end
end
Β
plaintext = "Beware the Jabberwock, my son! The jaws that bite, the claws that catch!"
key = "Vigenere cipher"
ciphertext = VigenereCipher.encrypt(plaintext, key)
recovered = VigenereCipher.decrypt(ciphertext, key)
Β
IO.puts "Original: #{plaintext}"
IO.puts "Encrypted: #{ciphertext}"
IO.puts "Decrypted: #{recovered}" |
http://rosettacode.org/wiki/Visualize_a_tree | Visualize a tree | A tree structure Β (i.e. a rooted, connected acyclic graph) Β is often used in programming.
It's often helpful to visually examine such a structure.
There are many ways to represent trees to a reader, such as:
Β indented text Β (Γ la unix tree command)
Β nested HTML tables
Β hierarchical GUI widgets
Β 2D Β or Β 3D Β images
Β etc.
Task
Write a program to produce a visual representation of some tree.
The content of the tree doesn't matter, nor does the output format, the only requirement being that the output is human friendly.
Make do with the vague term "friendly" the best you can.
| #J | J | BOXC=: 9!:6 '' NB. box drawing characters
EW =: {: BOXC NB. east-west
Β
showtree=: 4Β : 0
NB. y is parent index for each node (non-indices for root nodes)
NB. x is label for each node
t=. (<EW,' ') ,@<@,:@,&":&.> x NB. tree fragments
c=. |:(#~ e./@|:);(~.,"0&.>(</. i.@#)) y
while. +./ b=. ({.c)*.//.-.e.~/c do.
i=. b#~.{.c NB. parents whose children are leaves
j=. </./(({.c)e.i)#"1 c NB. leaves grouped by parents
t=. a: (;j)}t i}~ (i{t) subtree&.> j{&.><t
c=. (-.({.c)e.i)#"1 c NB. prune edges to leaves
end.
Β ;([: ,.&.>/ extend&.>)&> t -. a:
)
Β
subtree=: 4Β : 0
p=. EW={."1 s=. >{.t=. graft y
(<(>{.x) root p),(<(connect p),.s),}.t
)
Β
graft=: 3Β : 0
n=. (-~ >./) #&> y
f=. i.@(,&0)@#&.>@{.&.> y
,&.>/ y ,&> n$&.>f
)
Β
connect=: 3Β : 0
b=. (+./\ *. +./\.) y
c=. (b+2*y){' ',9 3 3{BOXC NB. β NS β E
c=. (0{BOXC) (b i. 1)}c NB. β NW
c=. (6{BOXC) (b i: 1)}c NB. β SW
j=. (b i. 1)+<.-:+/b
EW&(j})^:(1=+/b) c j}~ ((0 3 6 9{BOXC)i.j{c){1 4 7 5{BOXC
)
Β
root=: 4Β : 0
j=. k+<.-:1+(y i: 1)-k=. y i. 1
(-j)|.(#y){.x,.,:' ',EW
)
Β
extend=: 3Β : '(+./\"1 (y=EW) *. *./\."1 y e.'' '',EW)}y,:EW'
Β |
http://rosettacode.org/wiki/Walk_a_directory/Non-recursively | Walk a directory/Non-recursively | Task
Walk a given directory and print the names of files matching a given pattern.
(How is "pattern" defined? substring match? DOS pattern? BASH pattern? ZSH pattern? Perl regular expression?)
Note: This task is for non-recursive methods. Β These tasks should read a single directory, not an entire directory tree.
Note: Please be careful when running any code presented here.
Related task
Β Walk Directory Tree Β (read entire directory tree).
| #PureBasic | PureBasic | Procedure walkDirectory(directory.s = "", pattern.s = "")
Protected directoryID
Β
directoryID = ExamineDirectory(#PB_Any,directory,pattern)
If directoryID
While NextDirectoryEntry(directoryID)
PrintN(DirectoryEntryName(directoryID))
Wend
FinishDirectory(directoryID)
EndIf
EndProcedure
Β
If OpenConsole()
walkDirectory()
Β
Print(#CRLF$ + #CRLF$ + "Press ENTER to exit")
Input()
CloseConsole()
EndIf |
http://rosettacode.org/wiki/Walk_a_directory/Non-recursively | Walk a directory/Non-recursively | Task
Walk a given directory and print the names of files matching a given pattern.
(How is "pattern" defined? substring match? DOS pattern? BASH pattern? ZSH pattern? Perl regular expression?)
Note: This task is for non-recursive methods. Β These tasks should read a single directory, not an entire directory tree.
Note: Please be careful when running any code presented here.
Related task
Β Walk Directory Tree Β (read entire directory tree).
| #Python | Python | import glob
for filename in glob.glob('/foo/bar/*.mp3'):
print(filename) |
http://rosettacode.org/wiki/Walk_a_directory/Recursively | Walk a directory/Recursively | Task
Walk a given directory tree and print files matching a given pattern.
Note: This task is for recursive methods. Β These tasks should read an entire directory tree, not a single directory.
Note: Please be careful when running any code examples found here.
Related task
Β Walk a directory/Non-recursively Β (read a single directory).
| #Java | Java | import java.io.File;
Β
public class MainEntry {
public static void main(String[] args) {
walkin(new File("/home/user")); //Replace this with a suitable directory
}
Β
/**
* Recursive function to descend into the directory tree and find all the files
* that end with ".mp3"
* @param dir A file object defining the top directory
**/
public static void walkin(File dir) {
String pattern = ".mp3";
Β
File listFile[] = dir.listFiles();
if (listFile != null) {
for (int i=0; i<listFile.length; i++) {
if (listFile[i].isDirectory()) {
walkin(listFile[i]);
} else {
if (listFile[i].getName().endsWith(pattern)) {
System.out.println(listFile[i].getPath());
}
}
}
}
}
} |
http://rosettacode.org/wiki/Water_collected_between_towers | Water collected between towers | Task
In a two-dimensional world, we begin with any bar-chart (or row of close-packed 'towers', each of unit width), and then it rains,
completely filling all convex enclosures in the chart with water.
9 ββ 9 ββ
8 ββ 8 ββ
7 ββ ββ 7 ββββββββββββ
6 ββ ββ ββ 6 ββββββββββββ
5 ββ ββ ββ ββββ 5 ββββββββββββββββ
4 ββ ββ ββββββββ 4 ββββββββββββββββ
3 ββββββ ββββββββ 3 ββββββββββββββββ
2 ββββββββββββββββ ββ 2 ββββββββββββββββββββ
1 ββββββββββββββββββββ 1 ββββββββββββββββββββ
In the example above, a bar chart representing the values [5, 3, 7, 2, 6, 4, 5, 9, 1, 2] has filled, collecting 14 units of water.
Write a function, in your language, from a given array of heights, to the number of water units that can be held in this way, by a corresponding bar chart.
Calculate the number of water units that could be collected by bar charts representing each of the following seven series:
[[1, 5, 3, 7, 2],
[5, 3, 7, 2, 6, 4, 5, 9, 1, 2],
[2, 6, 3, 5, 2, 8, 1, 4, 2, 2, 5, 3, 5, 7, 4, 1],
[5, 5, 5, 5],
[5, 6, 7, 8],
[8, 7, 7, 6],
[6, 7, 10, 7, 6]]
See, also:
Four Solutions to a Trivial Problem β a Google Tech Talk by Guy Steele
Water collected between towers on Stack Overflow, from which the example above is taken)
An interesting Haskell solution, using the Tardis monad, by Phil Freeman in a Github gist.
| #jq | jq | def waterCollected:
. as $tower
| ($tower|length) as $n
| ([0] + [range(1;$n) | ($tower[0:.] | max) ]) as $highLeft
| ( [range(1;$n) | ($tower[.:$n] | max) ] + [0]) as $highRight
| [ range(0;$n) | [ ([$highLeft[.], $highRight[.] ]| min) - $tower[.], 0 ] | max]
| addΒ ;
Β
def towers: [
[1, 5, 3, 7, 2],
[5, 3, 7, 2, 6, 4, 5, 9, 1, 2],
[2, 6, 3, 5, 2, 8, 1, 4, 2, 2, 5, 3, 5, 7, 4, 1],
[5, 5, 5, 5],
[5, 6, 7, 8],
[8, 7, 7, 6],
[6, 7, 10, 7, 6]
];
Β
towers[]
| "\(waterCollected) from \(.)" |
http://rosettacode.org/wiki/Video_display_modes | Video display modes | The task is to demonstrate how to switch video display modes within the language. A brief description of the supported video modes would be useful.
| #ERRE | ERRE | dim as integer i, w, h, d
Β
for i = 0 to 21
if i>2 and i<7 then continue for 'screens 3-6 are not defined
screen i
screeninfo w, h, d
print "Screen ";i
print using "#### x ####, color depth ##";w;h;d
sleep
next i
Β
'a more flexible alternative is ScreenRes
Β
'this sets up a window of 1618x971 pixels, colour depth 8, and 2 pages
screenres 1618, 971, 8, 2
windowtitle "Foo bar baz"
sleep
Β
Β
'see https://documentation.help/FreeBASIC/KeyPgScreengraphics.html
'for more information
Β |
http://rosettacode.org/wiki/Video_display_modes | Video display modes | The task is to demonstrate how to switch video display modes within the language. A brief description of the supported video modes would be useful.
| #FreeBASIC | FreeBASIC | dim as integer i, w, h, d
Β
for i = 0 to 21
if i>2 and i<7 then continue for 'screens 3-6 are not defined
screen i
screeninfo w, h, d
print "Screen ";i
print using "#### x ####, color depth ##";w;h;d
sleep
next i
Β
'a more flexible alternative is ScreenRes
Β
'this sets up a window of 1618x971 pixels, colour depth 8, and 2 pages
screenres 1618, 971, 8, 2
windowtitle "Foo bar baz"
sleep
Β
Β
'see https://documentation.help/FreeBASIC/KeyPgScreengraphics.html
'for more information
Β |
http://rosettacode.org/wiki/Video_display_modes | Video display modes | The task is to demonstrate how to switch video display modes within the language. A brief description of the supported video modes would be useful.
| #Go | Go | package main
Β
import (
"fmt"
"log"
"os/exec"
"time"
)
Β
func main() {
// query supported display modes
out, err := exec.Command("xrandr", "-q").Output()
if err != nil {
log.Fatal(err)
}
fmt.Println(string(out))
time.Sleep(3 * time.Second)
Β
// change display mode to 1024x768 say (no text output)
err = exec.Command("xrandr", "-s", "1024x768").Run()
if err != nil {
log.Fatal(err)
}
time.Sleep(3 * time.Second)
Β
// change it back again to 1366x768 (or whatever is optimal for your system)
err = exec.Command("xrandr", "-s", "1366x768").Run()
if err != nil {
log.Fatal(err)
}
} |
http://rosettacode.org/wiki/Verify_distribution_uniformity/Naive | Verify distribution uniformity/Naive | This task is an adjunct to Seven-sided dice from five-sided dice.
Task
Create a function to check that the random integers returned from a small-integer generator function have uniform distribution.
The function should take as arguments:
The function (or object) producing random integers.
The number of times to call the integer generator.
A 'delta' value of some sort that indicates how close to a flat distribution is close enough.
The function should produce:
Some indication of the distribution achieved.
An 'error' if the distribution is not flat enough.
Show the distribution checker working when the produced distribution is flat enough and when it is not. (Use a generator from Seven-sided dice from five-sided dice).
See also:
Verify distribution uniformity/Chi-squared test
| #JavaScript | JavaScript | function distcheck(random_func, times, opts) {
if (opts === undefined) opts = {}
opts['delta'] = opts['delta'] || 2;
Β
var count = {}, vals = [];
for (var i = 0; i < times; i++) {
var val = random_func();
if (! has_property(count, val)) {
count[val] = 1;
vals.push(val);
}
else
count[val] ++;
}
vals.sort(function(a,b) {return a-b});
Β
var target = times / vals.length;
var tolerance = target * opts['delta'] / 100;
Β
for (var i = 0; i < vals.length; i++) {
var val = vals[i];
if (Math.abs(count[val] - target) > tolerance)
throw "distribution potentially skewed for " + val +
": expected result around " + target + ", got " +count[val];
else
print(val + "\t" + count[val]);
}
}
Β
function has_property(obj, propname) {
return typeof(obj[propname]) == "undefined" ? false : true;
}
Β
try {
distcheck(function() {return Math.floor(10 * Math.random())}, 100000);
print();
distcheck(function() {return (Math.random() > 0.95 ? 1 : 0)}, 100000);
} catch (e) {
print(e);
} |
http://rosettacode.org/wiki/Variable-length_quantity | Variable-length quantity | Implement some operations on variable-length quantities, at least including conversions from a normal number in the language to the binary representation of the variable-length quantity for that number, and vice versa. Any variants are acceptable.
Task
With above operations,
convert these two numbers 0x200000 (2097152 in decimal) and 0x1fffff (2097151 in decimal) into sequences of octets (an eight-bit byte);
display these sequences of octets;
convert these sequences of octets back to numbers, and check that they are equal to original numbers.
| #Ada | Ada | with Ada.Containers.Vectors;
with Ada.Text_IO;
with Ada.Unchecked_Conversion;
Β
procedure VLQ is
Β
package Nat_IO is new Ada.Text_IO.Integer_IO (Natural);
Β
type Byte is mod 2**8;
Β
package Byte_IO is new Ada.Text_IO.Modular_IO (Byte);
Β
type Int7 is mod 2**7;
Β
package Int7_IO is new Ada.Text_IO.Modular_IO (Int7);
Β
type VLQ_Octet is record
ValueΒ : Int7Β := 0;
Next Β : BooleanΒ := True;
end record;
pragma Pack (VLQ_Octet);
for VLQ_Octet'Size use 8;
Β
function VLQ_To_Byte is new Ada.Unchecked_Conversion (VLQ_Octet, Byte);
function Byte_To_VLQ is new Ada.Unchecked_Conversion (Byte, VLQ_Octet);
Β
package VLQ_Vectors is new Ada.Containers.Vectors (Natural, VLQ_Octet);
Β
procedure Hex_Print (PositionΒ : in VLQ_Vectors.Cursor) is
ValueΒ : ByteΒ := VLQ_To_Byte (VLQ_Vectors.Element (Position));
begin
Ada.Text_IO.Put (':');
Byte_IO.Put (Item => Value, Width => 6, Base => 16);
end Hex_Print;
Β
procedure Print (XΒ : VLQ_Vectors.Vector) is
begin
X.Iterate (Hex_Print'Access);
Ada.Text_IO.New_Line;
end Print;
Β
function To_VLQ (FromΒ : Natural) return VLQ_Vectors.Vector is
ResultΒ : VLQ_Vectors.Vector;
CurrentΒ : NaturalΒ := From;
ElementΒ : VLQ_Octet;
begin
loop
Element.ValueΒ := Int7 (Current mod 2**7);
Result.Prepend (Element);
CurrentΒ := Current / 2**7;
exit when Current = 0;
end loop;
ElementΒ := Result.Last_Element;
Element.NextΒ := False;
VLQ_Vectors.Replace_Element (Result, Result.Last, Element);
return Result;
end To_VLQ;
Β
function To_Int (FromΒ : VLQ_Vectors.Vector) return Natural is
use type VLQ_Vectors.Cursor;
ResultΒ : NaturalΒ := 0;
IteratorΒ : VLQ_Vectors.CursorΒ := From.First;
begin
while Iterator /= VLQ_Vectors.No_Element loop
ResultΒ := Result * 2**7;
ResultΒ := Result + Natural(VLQ_Vectors.Element (Iterator).Value);
VLQ_Vectors.Next (Iterator);
end loop;
return Result;
end To_Int;
Β
TestΒ : VLQ_Vectors.Vector;
begin
TestΒ := To_VLQ (16#7f#);
Nat_IO.Put (To_Int (Test), 10, 16); Ada.Text_IO.Put (" = ");
Print (Test);
TestΒ := To_VLQ (16#4000#);
Nat_IO.Put (To_Int (Test), 10, 16); Ada.Text_IO.Put (" = ");
Print (Test);
TestΒ := To_VLQ (16#0#);
Nat_IO.Put (To_Int (Test), 10, 16); Ada.Text_IO.Put (" = ");
Print (Test);
TestΒ := To_VLQ (16#3FFFFE#);
Nat_IO.Put (To_Int (Test), 10, 16); Ada.Text_IO.Put (" = ");
Print (Test);
TestΒ := To_VLQ (16#1FFFFF#);
Nat_IO.Put (To_Int (Test), 10, 16); Ada.Text_IO.Put (" = ");
Print (Test);
TestΒ := To_VLQ (16#200000#);
Nat_IO.Put (To_Int (Test), 10, 16); Ada.Text_IO.Put (" = ");
Print (Test);
end VLQ; |
http://rosettacode.org/wiki/Vector | Vector | Task
Implement a Vector class (or a set of functions) that models a Physical Vector. The four basic operations and a pretty print function should be implemented.
The Vector may be initialized in any reasonable way.
Start and end points, and direction
Angular coefficient and value (length)
The four operations to be implemented are:
Vector + Vector addition
Vector - Vector subtraction
Vector * scalar multiplication
Vector / scalar division
| #11l | 11l | T Vector
Float x, y
Β
F (x, y)
.x = x
.y = y
Β
F +(vector)
R Vector(.x + vector.x, .y + vector.y)
Β
F -(vector)
R Vector(.x - vector.x, .y - vector.y)
Β
F *(mult)
R Vector(.x * mult, .y * mult)
Β
F /(denom)
R Vector(.x / denom, .y / denom)
Β
F String()
R β(#., #.)β.format(.x, .y)
Β
print(Vector(5, 7) + Vector(2, 3))
print(Vector(5, 7) - Vector(2, 3))
print(Vector(5, 7) * 11)
print(Vector(5, 7) / 2) |
http://rosettacode.org/wiki/Variable_size/Set | Variable size/Set | Task
Demonstrate how to specify the minimum size of a variable or a data type.
| #11l | 11l | Β
* Binary interger (H,F)
I2 DS H half word 2 bytes
I4 DS F full word 4 bytes
* Real (floating point) (E,D,L)
X4 DS E short 4 bytes
X8 DS D double 8 bytes
X16 DS L extended 16 bytes
* Packed decimal (P)
P3 DS PL3 2 bytes
P7 DS PL7 4 bytes
P15 DS PL15 8 bytes
* Zoned decimal (Z)
Z8 DS ZL8 8 bytes
Z16 DS ZL16 16 bytes
* Character (C)
C1 DS C 1 byte
C16 DS CL16 16 bytes
C256 DS CL256 256 bytes
* Bit value (B)
B1 DC B'10101010' 1 byte
* Hexadecimal value (X)
X1 DC X'AA' 1 byte
* Address value (A)
A4 DC A(176) 4 bytes but only 3 bytes used
* (24 bits => 16 MB of storage)
Β |
http://rosettacode.org/wiki/Voronoi_diagram | Voronoi diagram | A Voronoi diagram is a diagram consisting of a number of sites.
Each Voronoi site s also has a Voronoi cell consisting of all points closest to s.
Task
Demonstrate how to generate and display a Voroni diagram.
See algo K-means++ clustering.
| #QB64 | QB64 | _Title "Voronoi Diagram"
Β
Dim As Integer pnt, px, py, i, x, y, adjct, sy, ly
Dim As Double st
Β
'=====================================================================
' Changes number of points and screen size here
'=====================================================================
pnt = 100
px = 512
py = 512
'=====================================================================
Screen _NewImage(px, py, 32)
Randomize Timer
Β
Dim Shared As Integer pax(pnt), pay(pnt), indx(px, py)
Dim Shared As Long dSqr(px, py)
Dim As Long col(pnt)
Β
For i = 1 To pnt
pax(i) = Int(Rnd * px)
pay(i) = Int(Rnd * py)
col(i) = _RGB(Rnd * 256, Rnd * 256, Rnd * 256)
Next
st = Timer
For x = 0 To px - 1
For y = 0 To py - 1
dSqr(x, y) = (pax(1) - x) * (pax(1) - x) + (pay(1) - y) * (pay(1) - y)
indx(x, y) = 1
Next
Next
Β
For i = 2 To pnt
ly = py - 1
For x = pax(i) To 0 Step -1
If (scan(i, x, ly)) = 0 Then Exit For
Next x
For x = pax(i) + 1 To px - 1
If (scan(i, x, ly)) = 0 Then Exit For
Next
Next
Β
For x = 0 To px - 1
For y = 0 To py - 1
sy = y
adjct = indx(x, y)
For y = y + 1 To py
If indx(x, y) <> adjct Then y = y - 1: Exit For
Next
Line (x, sy)-(x, y + 1), col(adjct)
Next
Next
Β
Sleep
System
Β
Function scan (site As Integer, x As Integer, ly As Integer)
Dim As Integer ty
Dim As Long delt2, dsq
delt2 = (pax(site) - x) * (pax(site) - x)
For ty = 0 To ly
dsq = (pay(site) - ty) * (pay(site) - ty) + delt2
If dsq <= dSqr(x, ty) Then
dSqr(x, ty) = dsq
indx(x, ty) = site
scan = 1
End If
Next
End Function |
http://rosettacode.org/wiki/Voronoi_diagram | Voronoi diagram | A Voronoi diagram is a diagram consisting of a number of sites.
Each Voronoi site s also has a Voronoi cell consisting of all points closest to s.
Task
Demonstrate how to generate and display a Voroni diagram.
See algo K-means++ clustering.
| #R | R | Β
## HF#1 Random Hex color
randHclr <- function() {
m=255;r=g=b=0;
r <- sample(0:m, 1, replace=TRUE);
g <- sample(0:m, 1, replace=TRUE);
b <- sample(0:m, 1, replace=TRUE);
return(rgb(r,g,b,maxColorValue=m));
}
## HF#2 Metrics: Euclidean, Manhattan and Minkovski
Metric <- function(x, y, mt) {
if(mt==1) {return(sqrt(x*x + y*y))}
if(mt==2) {return(abs(x) + abs(y))}
if(mt==3) {return((abs(x)^3 + abs(y)^3)^0.33333)}
}
Β
## Plotting Voronoi diagram. aev 3/12/17
## ns - number of sites, fn - file name, ttl - plot title.
## mt - type of metric: 1 - Euclidean, 2 - Manhattan, 3 - Minkovski.
pVoronoiD <- function(ns, fn="", ttl="",mt=1) {
cat(" *** START VD:", date(), "\n");
if(mt<1||mt>3) {mt=1}; mts=""; if(mt>1) {mts=paste0(", mt - ",mt)};
m=640; i=j=k=m1=m-2; x=y=d=dm=0;
if(fn=="") {pf=paste0("VDR", mt, ns, ".png")} else {pf=paste0(fn, ".png")};
if(ttl=="") {ttl=paste0("Voronoi diagram, sites - ", ns, mts)};
cat(" *** Plot file -", pf, "title:", ttl, "\n");
plot(NA, xlim=c(0,m), ylim=c(0,m), xlab="", ylab="", main=ttl);
X=numeric(ns); Y=numeric(ns); C=numeric(ns);
for(i in 1:ns) {
X[i]=sample(0:m1, 1, replace=TRUE);
Y[i]=sample(0:m1, 1, replace=TRUE);
C[i]=randHclr();
}
for(i in 0:m1) {
for(j in 0:m1) {
dm=Metric(m1,m1,mt); k=-1;
for(n in 1:ns) {
d=Metric(X[n]-j,Y[n]-i, mt);
if(d<dm) {dm=d; k=n;}
}
clr=C[k]; segments(j, i, j, i, col=clr);
}
}
points(X, Y, pch = 19, col = "black", bg = "white")
dev.copy(png, filename=pf, width=m, height=m);
dev.off(); graphics.off();
cat(" *** END VD:",date(),"\n");
}
## Executing:
pVoronoiD(150) ## Euclidean metric
pVoronoiD(10,"","",2) ## Manhattan metric
pVoronoiD(10,"","",3) ## Minkovski metric
Β |
http://rosettacode.org/wiki/Verify_distribution_uniformity/Chi-squared_test | Verify distribution uniformity/Chi-squared test | Task
Write a function to verify that a given distribution of values is uniform by using the
Ο
2
{\displaystyle \chi ^{2}}
test to see if the distribution has a likelihood of happening of at least the significance level (conventionally 5%).
The function should return a boolean that is true if the distribution is one that a uniform distribution (with appropriate number of degrees of freedom) may be expected to produce.
Reference
Β an entry at the MathWorld website: Β chi-squared distribution.
| #Hy | Hy | (import
[scipy.stats [chisquare]]
[collections [Counter]])
Β
(defn uniform? [f repeats &optional [alpha .05]]
"Call 'f' 'repeats' times and do a chi-squared test for uniformity
of the resulting discrete distribution. Return false iff the
null hypothesis of uniformity is rejected for the test with
size 'alpha'."
(<= alpha (second (chisquare
(.values (Counter (take repeats (repeatedly f)))))))) |
http://rosettacode.org/wiki/Verify_distribution_uniformity/Chi-squared_test | Verify distribution uniformity/Chi-squared test | Task
Write a function to verify that a given distribution of values is uniform by using the
Ο
2
{\displaystyle \chi ^{2}}
test to see if the distribution has a likelihood of happening of at least the significance level (conventionally 5%).
The function should return a boolean that is true if the distribution is one that a uniform distribution (with appropriate number of degrees of freedom) may be expected to produce.
Reference
Β an entry at the MathWorld website: Β chi-squared distribution.
| #J | J | require 'stats/base'
Β
countCats=: #@~. NB. counts the number of unique items
getExpected=: #@]Β % [ NB. divides no of items by category count
getObserved=: #/.~@] NB. counts frequency for each category
calcX2=: [: +/ *:@(getObserved - getExpected)Β % getExpected NB. calculates test statistic
calcDf=: <:@[ NB. calculates degrees of freedom for uniform distribution
Β
NB.*isUniform v Tests (5%) whether y is uniformly distributed
NB. result is: boolean describing if distribution y is uniform
NB. y is: distribution to test
NB. x is: optionally specify number of categories possible
isUniform=: (countCats $: ])Β : (0.95 > calcDf chisqcdfΒ :: 1: calcX2) |
http://rosettacode.org/wiki/Verhoeff_algorithm | Verhoeff algorithm | Description
The Verhoeff algorithm is a checksum formula for error detection developed by the Dutch mathematician Jacobus Verhoeff and first published in 1969. It was the first decimal check digit algorithm which detects all single-digit errors, and all transposition errors involving two adjacent digits, which was at the time thought impossible with such a code.
As the workings of the algorithm are clearly described in the linked Wikipedia article they will not be repeated here.
Task
Write routines, methods, procedures etc. in your language to generate a Verhoeff checksum digit for non-negative integers of any length and to validate the result. A combined routine is also acceptable.
The more mathematically minded may prefer to generate the 3 tables required from the description provided rather than to hard-code them.
Write your routines in such a way that they can optionally display digit by digit calculations as in the Wikipedia example.
Use your routines to calculate check digits for the integers: 236, 12345 and 123456789012 and then validate them. Also attempt to validate the same integers if the check digits in all cases were 9 rather than what they actually are.
Display digit by digit calculations for the first two integers but not for the third.
Related task
Β Damm algorithm
| #Vlang | Vlang | const d = [
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9],
[1, 2, 3, 4, 0, 6, 7, 8, 9, 5],
[2, 3, 4, 0, 1, 7, 8, 9, 5, 6],
[3, 4, 0, 1, 2, 8, 9, 5, 6, 7],
[4, 0, 1, 2, 3, 9, 5, 6, 7, 8],
[5, 9, 8, 7, 6, 0, 4, 3, 2, 1],
[6, 5, 9, 8, 7, 1, 0, 4, 3, 2],
[7, 6, 5, 9, 8, 2, 1, 0, 4, 3],
[8, 7, 6, 5, 9, 3, 2, 1, 0, 4],
[9, 8, 7, 6, 5, 4, 3, 2, 1, 0],
]
Β
const inv = [0, 4, 3, 2, 1, 5, 6, 7, 8, 9]
Β
const p = [
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9],
[1, 5, 7, 6, 2, 8, 3, 0, 9, 4],
[5, 8, 0, 3, 7, 9, 6, 1, 4, 2],
[8, 9, 1, 6, 0, 4, 3, 5, 2, 7],
[9, 4, 5, 3, 1, 2, 6, 8, 7, 0],
[4, 2, 8, 6, 5, 7, 3, 9, 0, 1],
[2, 7, 9, 3, 8, 0, 6, 4, 1, 5],
[7, 0, 4, 6, 9, 1, 3, 2, 5, 8],
]
Β
fn verhoeff(ss string, validate bool, table bool) int {
mut s:= ss
if table {
mut t := "Check digit"
if validate {
t = "Validation"
}
println("$t calculations for '$s':\n")
println(" i nα΅’ p[i,nα΅’] c")
println("------------------")
}
if !validate {
s = s + "0"
}
mut c := 0
le := s.len - 1
for i := le; i >= 0; i-- {
ni := int(s[i] - 48)
pi := p[(le-i)%8][ni]
c = d[c][pi]
if table {
println("${le-i:2} $ni $pi $c")
}
}
if table && !validate {
println("\ninv[$c] = ${inv[c]}")
}
if !validate {
return inv[c]
}
return int(c == 0)
}
Β
fn main() {
ss := ["236", "12345", "123456789012"]
ts := [true, true, false, true]
for i, s in ss {
c := verhoeff(s, false, ts[i])
println("\nThe check digit for '$s' is '$c'\n")
for sc in [s + c.str(), s + "9"] {
v := verhoeff(sc, true, ts[i])
mut ans := "correct"
if v==0 {
ans = "incorrect"
}
println("\nThe validation for '$sc' is $ans\n")
}
}
} |
http://rosettacode.org/wiki/Vigen%C3%A8re_cipher | Vigenère cipher | Task
Implement a  Vigenère cypher,  both encryption and decryption.
The program should handle keys and text of unequal length,
and should capitalize everything and discard non-alphabetic characters.
(If your program handles non-alphabetic characters in another way,
make a note of it.)
Related tasks
Β Caesar cipher
Β Rot-13
Β Substitution Cipher
| #Erlang | Erlang | % Erlang implementation of Vigenère cipher
-module(vigenere).
-export([encrypt/2, decrypt/2]).
-import(lists, [append/2, filter/2, map/2, zipwith/3]).
Β
% Utility functions for character tests and conversions
isupper([C|_]) -> isupper(C);
isupper(C) -> (C >= $A) and (C =< $Z).
Β
islower([C|_]) -> islower(C);
islower(C) -> (C >= $a) and (C =< $z).
Β
isalpha([C|_]) -> isalpha(C);
isalpha(C) -> isupper(C) or islower(C).
Β
toupper(S) when is_list(S) -> lists:map(fun toupper/1, S);
toupper(C) when (C >= $a) and (C =< $z) -> C - $a + $A;
toupper(C) -> C.
Β
% modulo function that normalizes into positive range for positive divisor
mod(X,Y) -> (X rem Y + Y) rem Y.
Β
% convert letter to position in alphabet (A=0,B=1,...,Y=24,Z=25).
to_pos(L) when L >= $A, L =< $Z -> L - $A.
Β
% convert position in alphabet back to letter
from_pos(N) -> mod(N, 26) + $A.
Β
% encode the given letter given the single-letter key
encipher(P, K) -> from_pos(to_pos(P) + to_pos(K)).
Β
% decode the given letter given the single-letter key
decipher(C, K) -> from_pos(to_pos(C) - to_pos(K)).
Β
% extend a list by repeating it until it is at least N elements long
cycle_to(N, List) when length(List) >= N -> List;
cycle_to(N, List) -> append(List, cycle_to(N-length(List), List)).
Β
% Encryption prep: reduce string to only its letters, in uppercase
normalize(Str) -> toupper(filter(fun isalpha/1, Str)).
Β
crypt(RawText, RawKey, Func) ->
PlainText = normalize(RawText),
zipwith(Func, PlainText, cycle_to(length(PlainText), normalize(RawKey))).
Β
encrypt(Text, Key) -> crypt(Text, Key, fun encipher/2).
decrypt(Text, Key) -> crypt(Text, Key, fun decipher/2). |
http://rosettacode.org/wiki/Visualize_a_tree | Visualize a tree | A tree structure Β (i.e. a rooted, connected acyclic graph) Β is often used in programming.
It's often helpful to visually examine such a structure.
There are many ways to represent trees to a reader, such as:
Β indented text Β (Γ la unix tree command)
Β nested HTML tables
Β hierarchical GUI widgets
Β 2D Β or Β 3D Β images
Β etc.
Task
Write a program to produce a visual representation of some tree.
The content of the tree doesn't matter, nor does the output format, the only requirement being that the output is human friendly.
Make do with the vague term "friendly" the best you can.
| #Java | Java | public class VisualizeTree {
public static void main(String[] args) {
BinarySearchTree tree = new BinarySearchTree();
Β
tree.insert(100);
for (int i = 0; i < 20; i++)
tree.insert((int) (Math.random() * 200));
tree.display();
}
}
Β
class BinarySearchTree {
private Node root;
Β
private class Node {
private int key;
private Node left, right;
Β
Node(int k) {
key = k;
}
}
Β
public boolean insert(int key) {
if (root == null)
root = new Node(key);
else {
Node n = root;
Node parent;
while (true) {
if (n.key == key)
return false;
Β
parent = n;
Β
boolean goLeft = key < n.key;
n = goLeft ? n.left : n.right;
Β
if (n == null) {
if (goLeft) {
parent.left = new Node(key);
} else {
parent.right = new Node(key);
}
break;
}
}
}
return true;
}
Β
public void display() {
final int height = 5, width = 64;
Β
int len = width * height * 2 + 2;
StringBuilder sb = new StringBuilder(len);
for (int i = 1; i <= len; i++)
sb.append(i < len - 2 && i % width == 0 ? "\n" : ' ');
Β
displayR(sb, width / 2, 1, width / 4, width, root, " ");
System.out.println(sb);
}
Β
private void displayR(StringBuilder sb, int c, int r, int d, int w, Node n,
String edge) {
if (n != null) {
displayR(sb, c - d, r + 2, d / 2, w, n.left, " /");
Β
String s = String.valueOf(n.key);
int idx1 = r * w + c - (s.length() + 1) / 2;
int idx2 = idx1 + s.length();
int idx3 = idx1 - w;
if (idx2 < sb.length())
sb.replace(idx1, idx2, s).replace(idx3, idx3 + 2, edge);
Β
displayR(sb, c + d, r + 2, d / 2, w, n.right, "\\ ");
}
}
} |
http://rosettacode.org/wiki/Walk_a_directory/Non-recursively | Walk a directory/Non-recursively | Task
Walk a given directory and print the names of files matching a given pattern.
(How is "pattern" defined? substring match? DOS pattern? BASH pattern? ZSH pattern? Perl regular expression?)
Note: This task is for non-recursive methods. Β These tasks should read a single directory, not an entire directory tree.
Note: Please be careful when running any code presented here.
Related task
Β Walk Directory Tree Β (read entire directory tree).
| #R | R | dir("/foo/bar", "mp3") |
http://rosettacode.org/wiki/Walk_a_directory/Non-recursively | Walk a directory/Non-recursively | Task
Walk a given directory and print the names of files matching a given pattern.
(How is "pattern" defined? substring match? DOS pattern? BASH pattern? ZSH pattern? Perl regular expression?)
Note: This task is for non-recursive methods. Β These tasks should read a single directory, not an entire directory tree.
Note: Please be careful when running any code presented here.
Related task
Β Walk Directory Tree Β (read entire directory tree).
| #Racket | Racket | Β
-> (for ([f (directory-list "/tmp")] #:when (regexp-match? "\\.rkt$" f))
(displayln f))
... *.rkt files ...
Β |
http://rosettacode.org/wiki/Walk_a_directory/Recursively | Walk a directory/Recursively | Task
Walk a given directory tree and print files matching a given pattern.
Note: This task is for recursive methods. Β These tasks should read an entire directory tree, not a single directory.
Note: Please be careful when running any code examples found here.
Related task
Β Walk a directory/Non-recursively Β (read a single directory).
| #JavaScript | JavaScript | var fso = new ActiveXObject("Scripting.FileSystemObject");
Β
function walkDirectoryTree(folder, folder_name, re_pattern) {
WScript.Echo("Files in " + folder_name + " matching '" + re_pattern + "':");
walkDirectoryFilter(folder.files, re_pattern);
Β
var subfolders = folder.SubFolders;
WScript.Echo("Folders in " + folder_name + " matching '" + re_pattern + "':");
walkDirectoryFilter(subfolders, re_pattern);
Β
WScript.Echo();
var en = new Enumerator(subfolders);
while (! en.atEnd()) {
var subfolder = en.item();
walkDirectoryTree(subfolder, folder_name + "/" + subfolder.name, re_pattern);
en.moveNext();
}
}
Β
function walkDirectoryFilter(items, re_pattern) {
var e = new Enumerator(items);
while (! e.atEnd()) {
var item = e.item();
if (item.name.match(re_pattern))
WScript.Echo(item.name);
e.moveNext();
}
}
Β
walkDirectoryTree(dir, dir.name, '\\.txt$'); |
http://rosettacode.org/wiki/Water_collected_between_towers | Water collected between towers | Task
In a two-dimensional world, we begin with any bar-chart (or row of close-packed 'towers', each of unit width), and then it rains,
completely filling all convex enclosures in the chart with water.
9 ββ 9 ββ
8 ββ 8 ββ
7 ββ ββ 7 ββββββββββββ
6 ββ ββ ββ 6 ββββββββββββ
5 ββ ββ ββ ββββ 5 ββββββββββββββββ
4 ββ ββ ββββββββ 4 ββββββββββββββββ
3 ββββββ ββββββββ 3 ββββββββββββββββ
2 ββββββββββββββββ ββ 2 ββββββββββββββββββββ
1 ββββββββββββββββββββ 1 ββββββββββββββββββββ
In the example above, a bar chart representing the values [5, 3, 7, 2, 6, 4, 5, 9, 1, 2] has filled, collecting 14 units of water.
Write a function, in your language, from a given array of heights, to the number of water units that can be held in this way, by a corresponding bar chart.
Calculate the number of water units that could be collected by bar charts representing each of the following seven series:
[[1, 5, 3, 7, 2],
[5, 3, 7, 2, 6, 4, 5, 9, 1, 2],
[2, 6, 3, 5, 2, 8, 1, 4, 2, 2, 5, 3, 5, 7, 4, 1],
[5, 5, 5, 5],
[5, 6, 7, 8],
[8, 7, 7, 6],
[6, 7, 10, 7, 6]]
See, also:
Four Solutions to a Trivial Problem β a Google Tech Talk by Guy Steele
Water collected between towers on Stack Overflow, from which the example above is taken)
An interesting Haskell solution, using the Tardis monad, by Phil Freeman in a Github gist.
| #Julia | Julia | using Printf
Β
function watercollected(towers::Vector{Int})
high_lft = vcat(0, accumulate(max, towers[1:end-1]))
high_rgt = vcat(reverse(accumulate(max, towers[end:-1:2])), 0)
waterlvl = max.(min.(high_lft, high_rgt) .- towers, 0)
return waterlvl
end
Β
function towerprint(towers, levels)
ctowers = copy(towers)
clevels = copy(levels)
hmax = maximum(towers)
ntow = length(towers)
for h in hmax:-1:1
@printf("%2i |", h)
for j in 1:ntow
if ctowers[j] + clevels[j] β₯ h
if clevels[j] > 0
cell = "ββ"
clevels[j] -= 1
else
cell = "NN"
ctowers[j] -= 1
end
else
cell = " "
end
print(cell)
end
println("|")
end
Β
Β
println(" " * join(lpad(t, 2) for t in levels) * ": Water lvl")
println(" " * join(lpad(t, 2) for t in towers) * ": Tower lvl")
end
Β
for towers in [[1, 5, 3, 7, 2], [5, 3, 7, 2, 6, 4, 5, 9, 1, 2],
[2, 6, 3, 5, 2, 8, 1, 4, 2, 2, 5, 3, 5, 7, 4, 1],
[5, 5, 5, 5], [5, 6, 7, 8], [8, 7, 7, 6], [6, 7, 10, 7, 6]]
towerprint(towers, watercollected(towers))
println()
end |
http://rosettacode.org/wiki/Video_display_modes | Video display modes | The task is to demonstrate how to switch video display modes within the language. A brief description of the supported video modes would be useful.
| #Groovy | Groovy | def invoke(String cmd) { println(cmd.execute().text) }
Β
invoke("xrandr -q")
Thread.sleep(3000)
Β
invoke("xrandr -s 1024x768")
Thread.sleep(3000)
Β
invoke("xrandr -s 1366x768") |
http://rosettacode.org/wiki/Video_display_modes | Video display modes | The task is to demonstrate how to switch video display modes within the language. A brief description of the supported video modes would be useful.
| #GW-BASIC | GW-BASIC | 10 REM GW Basic can switch VGA modes
20 SCREEN 18: REM Mode 12h 640x480 16 colour graphics |
http://rosettacode.org/wiki/Video_display_modes | Video display modes | The task is to demonstrate how to switch video display modes within the language. A brief description of the supported video modes would be useful.
| #Icon_and_Unicon | Icon and Unicon | procedure main(A)
mode := A[1]
if \mode then system("xrandr -s " || \mode || " >/dev/null")
else system("xrandr -q") # Display available modes
end |
http://rosettacode.org/wiki/Video_display_modes | Video display modes | The task is to demonstrate how to switch video display modes within the language. A brief description of the supported video modes would be useful.
| #Julia | Julia | Β
if Base.Sys.islinux()
run(`xrandr -s 640x480`)
sleep(3)
run(`xrandr -s 1280x960`)
else # windows
run(`mode CON: COLS=40 LINES=100`)
sleep(3)
run(`mode CON: COLS=100 LINES=50`)
end
Β |
http://rosettacode.org/wiki/Verify_distribution_uniformity/Naive | Verify distribution uniformity/Naive | This task is an adjunct to Seven-sided dice from five-sided dice.
Task
Create a function to check that the random integers returned from a small-integer generator function have uniform distribution.
The function should take as arguments:
The function (or object) producing random integers.
The number of times to call the integer generator.
A 'delta' value of some sort that indicates how close to a flat distribution is close enough.
The function should produce:
Some indication of the distribution achieved.
An 'error' if the distribution is not flat enough.
Show the distribution checker working when the produced distribution is flat enough and when it is not. (Use a generator from Seven-sided dice from five-sided dice).
See also:
Verify distribution uniformity/Chi-squared test
| #Julia | Julia | using Printf
Β
function distcheck(f::Function, rep::Int=10000, Ξ::Int=3)
smpl = f(rep)
counts = Dict(k => count(smpl .== k) for k in unique(smpl))
expected = rep / length(counts)
lbound = expected * (1 - 0.01Ξ)
ubound = expected * (1 + 0.01Ξ)
noobs = count(x ->Β !(lbound β€ x β€ ubound), values(counts))
if noobs > 0 warn(@sprintf "%2.4f%% values out of bounds" noobs / rep) end
return counts
end
Β
# Dice5 check
distcheck(x -> rand(1:5, x))
# Dice7 check
distcheck(dice7) |
http://rosettacode.org/wiki/Verify_distribution_uniformity/Naive | Verify distribution uniformity/Naive | This task is an adjunct to Seven-sided dice from five-sided dice.
Task
Create a function to check that the random integers returned from a small-integer generator function have uniform distribution.
The function should take as arguments:
The function (or object) producing random integers.
The number of times to call the integer generator.
A 'delta' value of some sort that indicates how close to a flat distribution is close enough.
The function should produce:
Some indication of the distribution achieved.
An 'error' if the distribution is not flat enough.
Show the distribution checker working when the produced distribution is flat enough and when it is not. (Use a generator from Seven-sided dice from five-sided dice).
See also:
Verify distribution uniformity/Chi-squared test
| #Kotlin | Kotlin | // version 1.1.3
Β
import java.util.Random
Β
val r = Random()
Β
fun dice5() = 1 + r.nextInt(5)
Β
fun checkDist(gen: () -> Int, nRepeats: Int, tolerance: Double = 0.5) {
val occurs = mutableMapOf<Int, Int>()
for (i in 1..nRepeats) {
val d = gen()
if (occurs.containsKey(d))
occurs[d] = occurs[d]!! + 1
else
occurs.put(d, 1)
}
val expected = (nRepeats.toDouble()/ occurs.size).toInt()
val maxError = (expected * tolerance / 100.0).toInt()
println("Repetitions = $nRepeats, Expected = $expected")
println("Tolerance = $tolerance%, Max Error = $maxError\n")
println("Integer Occurrences Error Acceptable")
val f = " Β %d Β %5d Β %5d Β %s"
var allAcceptable = true
for ((k,v) in occurs.toSortedMap()) {
val error = Math.abs(v - expected)
val acceptable = if (error <= maxError) "Yes" else "No"
if (acceptable == "No") allAcceptable = false
println(f.format(k, v, error, acceptable))
}
println("\nAcceptable overall: ${if (allAcceptable) "Yes" else "No"}")
}
Β
fun main(args: Array<String>) {
checkDist(::dice5, 1_000_000)
println()
checkDist(::dice5, 100_000)
} |
http://rosettacode.org/wiki/Variable-length_quantity | Variable-length quantity | Implement some operations on variable-length quantities, at least including conversions from a normal number in the language to the binary representation of the variable-length quantity for that number, and vice versa. Any variants are acceptable.
Task
With above operations,
convert these two numbers 0x200000 (2097152 in decimal) and 0x1fffff (2097151 in decimal) into sequences of octets (an eight-bit byte);
display these sequences of octets;
convert these sequences of octets back to numbers, and check that they are equal to original numbers.
| #ANSI_Standard_BASIC | ANSI Standard BASIC | INPUT s$
LET s$ = LTRIM$(RTRIM$(s$))
LET v = 0
FOR i = 1 TO LEN(s$)
LET c$ = s$(i:i)
LET k = POS("0123456789abcdef", c$)
IF k > 0 THEN LET v = v*16 + k - 1
NEXT i
PRINT "S= ";s$, "V=";v
Β
! Convert back to hex
LET hex$ ="0123456789abcdef"
LET hs$=" "
Β
FOR i = LEN(hs$) TO 1 STEP -1
IF v = 0 THEN EXIT FOR
LET d = MOD(v, 16) + 1
LET hs$(i:i) = hex$(d:d)
LET v = INT(v/16)
NEXT i
PRINT hs$
END |
http://rosettacode.org/wiki/Variable-length_quantity | Variable-length quantity | Implement some operations on variable-length quantities, at least including conversions from a normal number in the language to the binary representation of the variable-length quantity for that number, and vice versa. Any variants are acceptable.
Task
With above operations,
convert these two numbers 0x200000 (2097152 in decimal) and 0x1fffff (2097151 in decimal) into sequences of octets (an eight-bit byte);
display these sequences of octets;
convert these sequences of octets back to numbers, and check that they are equal to original numbers.
| #Bracmat | Bracmat | ( ( VLQ
= b07 b8 vlq
. 0:?b8
&Β :?vlq
& whl
' (Β !arg:>0
& mod$(!arg.128):?b07
& (chr$(!b8+!b07)|)Β !vlq:?vlq
& 128:?b8
& div$(!arg.128):?arg
)
& str$!vlq
)
& ( NUM
= c num d
. 0:?num:?d
& whl
' ( @(!arg:%@?cΒ ?arg)
& asc$!c:?c:~<128
& 128*(!c+-128+!num):?num
& 1+!d:?d
)
& (!c:<128&!c+!num:?num|)
&Β !num
)
& ( printVLQ
= c h
. Β :?h
& whl
' ( @(!arg:%@?cΒ ?arg)
& d2x$(asc$!c):?x
& Β !h (@(!x:? [1)&0|)Β !x
Β :Β ?h
)
& ( asc$!c:~<128&!h 00:?h
|
)
& out$("VLQ Β :" str$!h)
)
& ( test
= vlq num
. out$("input:"Β !arg)
& VLQ$(x2d$!arg):?vlq
& printVLQ$!vlq
& NUM$!vlq:?num
& out$("backΒ :" d2x$!num \n)
)
& test$200000
& test$1fffff
& test$00
& test$7f
& test$80
& test$81
& test$82
& test$894E410E0A
); |
http://rosettacode.org/wiki/Vector | Vector | Task
Implement a Vector class (or a set of functions) that models a Physical Vector. The four basic operations and a pretty print function should be implemented.
The Vector may be initialized in any reasonable way.
Start and end points, and direction
Angular coefficient and value (length)
The four operations to be implemented are:
Vector + Vector addition
Vector - Vector subtraction
Vector * scalar multiplication
Vector / scalar division
| #Action.21 | Action! | INCLUDE "D2:REAL.ACT"Β ;from the Action! Tool Kit
Β
DEFINE X_="+0"
DEFINE Y_="+6"
Β
TYPE Vector=[CARD x1,x2,x3,y1,y2,y3]
Β
PROC PrintVec(Vector POINTER v)
Print("[") PrintR(v X_)
Print(",") PrintR(v Y_) Print("]")
RETURN
Β
PROC VecIntInit(Vector POINTER v INT ix,iy)
IntToReal(ix,v X_)
IntToReal(iy,v Y_)
RETURN
Β
PROC VecRealInit(Vector POINTER v REAL POINTER rx,ry)
RealAssign(rx,v X_)
RealAssign(ry,v Y_)
RETURN
Β
PROC VecStringInit(Vector POINTER v CHAR ARRAY sx,sy)
ValR(sx,v X_)
ValR(sy,v Y_)
RETURN
Β
PROC VecAdd(Vector POINTER v1,v2,res)
RealAdd(v1 X_,v2 X_,res X_)Β ;res.x=v1.x+v2.x
RealAdd(v1 Y_,v2 Y_,res Y_)Β ;res.y=v1.y+v2.y
RETURN
Β
PROC VecSub(Vector POINTER v1,v2,res)
RealSub(v1 X_,v2 X_,res X_)Β ;res.x=v1.x-v2.x
RealSub(v1 Y_,v2 Y_,res Y_)Β ;res.y=v1.y-v2.y
RETURN
Β
PROC VecMult(Vector POINTER v REAL POINTER a Vector POINTER res)
RealMult(v X_,a,res X_)Β ;res.x=v.x*a
RealMult(v Y_,a,res Y_)Β ;res.y=v.y*a
RETURN
Β
PROC VecDiv(Vector POINTER v REAL POINTER a Vector POINTER res)
RealDiv(v X_,a,res X_)Β ;res.x=v.x/a
RealDiv(v Y_,a,res Y_)Β ;res.y=v.y/a
RETURN
Β
PROC Main()
Vector v1,v2,res
REAL s
Β
Put(125) PutE()Β ;clear the screen
VecStringInit(v1,"12.3","-4.56")
VecStringInit(v2,"9.87","654.3")
ValR("0.1",s)
Β
VecAdd(v1,v2,res)
PrintVec(v1) Print(" + ") PrintVec(v2)
Print(" =") PutE() PrintVec(res) PutE() PutE()
Β
VecSub(v1,v2,res)
PrintVec(v1) Print(" - ") PrintVec(v2)
Print(" =") PutE() PrintVec(res) PutE() PutE()
Β
VecMult(v1,s,res)
PrintVec(v1) Print(" * ") PrintR(s)
Print(" = ") PrintVec(res) PutE() PutE()
Β
VecDiv(v1,s,res)
PrintVec(v1) Print(" / ") PrintR(s)
Print(" = ") PrintVec(res)
RETURN |
http://rosettacode.org/wiki/Vector | Vector | Task
Implement a Vector class (or a set of functions) that models a Physical Vector. The four basic operations and a pretty print function should be implemented.
The Vector may be initialized in any reasonable way.
Start and end points, and direction
Angular coefficient and value (length)
The four operations to be implemented are:
Vector + Vector addition
Vector - Vector subtraction
Vector * scalar multiplication
Vector / scalar division
| #ALGOL_68 | ALGOL 68 | # the standard mode COMPLEX is a two element vector #
MODE VECTOR = COMPLEX;
# the operations required for the task plus many others are provided as standard for COMPLEX and REAL items #
# the two components are fields called "re" and "im" #
# we can define a "pretty-print" operator: #
# returns a formatted representation of the vector #
OP TOSTRING = ( VECTOR a )STRING: "[" + TOSTRING re OF a + ", " + TOSTRING im OF a + "]";
# returns a formatted representation of the scaler #
OP TOSTRING = ( REAL a )STRING: fixed( a, 0, 4 );
Β
# test the operations #
VECTOR a = 5 I 7, b = 2 I 3; # note the use of the I operator to construct a COMPLEX from two scalers #
print( ( "a+bΒ : ", TOSTRING ( a + b ), newline ) );
print( ( "a-bΒ : ", TOSTRING ( a - b ), newline ) );
print( ( "a*11: ", TOSTRING ( a * 11 ), newline ) );
print( ( "a/2Β : ", TOSTRING ( a / 2 ), newline ) )
Β |
http://rosettacode.org/wiki/Variable_size/Set | Variable size/Set | Task
Demonstrate how to specify the minimum size of a variable or a data type.
| #360_Assembly | 360 Assembly | Β
* Binary interger (H,F)
I2 DS H half word 2 bytes
I4 DS F full word 4 bytes
* Real (floating point) (E,D,L)
X4 DS E short 4 bytes
X8 DS D double 8 bytes
X16 DS L extended 16 bytes
* Packed decimal (P)
P3 DS PL3 2 bytes
P7 DS PL7 4 bytes
P15 DS PL15 8 bytes
* Zoned decimal (Z)
Z8 DS ZL8 8 bytes
Z16 DS ZL16 16 bytes
* Character (C)
C1 DS C 1 byte
C16 DS CL16 16 bytes
C256 DS CL256 256 bytes
* Bit value (B)
B1 DC B'10101010' 1 byte
* Hexadecimal value (X)
X1 DC X'AA' 1 byte
* Address value (A)
A4 DC A(176) 4 bytes but only 3 bytes used
* (24 bits => 16 MB of storage)
Β |
http://rosettacode.org/wiki/Variable_size/Set | Variable size/Set | Task
Demonstrate how to specify the minimum size of a variable or a data type.
| #6502_Assembly | 6502 Assembly | MyByte:
byte 0 Β ;most assemblers will also accept DB or DFB
MyWord:
word 0 Β ;most assemblers will also accept DW or DFW
MyDouble:
dd 0 |
http://rosettacode.org/wiki/Variable_size/Set | Variable size/Set | Task
Demonstrate how to specify the minimum size of a variable or a data type.
| #68000_Assembly | 68000 Assembly | MyByte:
DC.B 0
EVEN ;you need this to prevent alignment problems if you define an odd number of bytes.
MyWord:
DC.W 0 ;this takes up 2 bytes even though only one 0 was written
MyLong:
DC.L 0 ;this takes up 4 bytes even though only one 0 was written |
http://rosettacode.org/wiki/Variable_size/Set | Variable size/Set | Task
Demonstrate how to specify the minimum size of a variable or a data type.
| #8086_Assembly | 8086 Assembly | Β
.data ;data segment
Β
TestValue_00 byte 0 ;an 8-bit variable
TestValue_01 word 0 ;a 16-bit variable
TestValue_02 dword 0 ;a 32-bit variable
Β
.code
Β
start:
Β
mov dh, byte ptr [ds:TestValue_00] ;load the value stored at the address "TestValue_00"
mov ax, word ptr [ds:TestValue_01] ;load the value stored at the address "TestValue_01" |
http://rosettacode.org/wiki/Voronoi_diagram | Voronoi diagram | A Voronoi diagram is a diagram consisting of a number of sites.
Each Voronoi site s also has a Voronoi cell consisting of all points closest to s.
Task
Demonstrate how to generate and display a Voroni diagram.
See algo K-means++ clustering.
| #Racket | Racket | Β
#lang racket
Β
(require plot)
Β
;; Performs clustering of points in a grid
;; using the nearest neigbour approach and shows
;; clusters in different colors
(define (plot-Voronoi-diagram point-list)
(define pts
(for*/list ([x (in-range 0 1 0.005)]
[y (in-range 0 1 0.005)])
(vector x y)))
Β
(define clusters (clusterize pts point-list))
Β
(plot
(append
(for/list ([r (in-list clusters)] [i (in-naturals)])
(points (rest r) #:color i #:sym 'fullcircle1))
(list (points point-list #:sym 'fullcircle5 #:fill-color 'white)))))
Β
;; Divides the set of points into clusters
;; using given centroids
(define (clusterize data centroids)
(for*/fold ([res (map list centroids)]) ([x (in-list data)])
(define c (argmin (curryr (metric) x) centroids))
(dict-set res c (cons x (dict-ref res c)))))
Β |
http://rosettacode.org/wiki/Verify_distribution_uniformity/Chi-squared_test | Verify distribution uniformity/Chi-squared test | Task
Write a function to verify that a given distribution of values is uniform by using the
Ο
2
{\displaystyle \chi ^{2}}
test to see if the distribution has a likelihood of happening of at least the significance level (conventionally 5%).
The function should return a boolean that is true if the distribution is one that a uniform distribution (with appropriate number of degrees of freedom) may be expected to produce.
Reference
Β an entry at the MathWorld website: Β chi-squared distribution.
| #Java | Java | import static java.lang.Math.pow;
import java.util.Arrays;
import static java.util.Arrays.stream;
import org.apache.commons.math3.special.Gamma;
Β
public class Test {
Β
static double x2Dist(double[] data) {
double avg = stream(data).sum() / data.length;
double sqs = stream(data).reduce(0, (a, b) -> a + pow((b - avg), 2));
return sqs / avg;
}
Β
static double x2Prob(double dof, double distance) {
return Gamma.regularizedGammaQ(dof / 2, distance / 2);
}
Β
static boolean x2IsUniform(double[] data, double significance) {
return x2Prob(data.length - 1.0, x2Dist(data)) > significance;
}
Β
public static void main(String[] a) {
double[][] dataSets = {{199809, 200665, 199607, 200270, 199649},
{522573, 244456, 139979, 71531, 21461}};
Β
System.out.printf("Β %4sΒ %12s Β %12sΒ %8s Β %s%n",
"dof", "distance", "probability", "Uniform?", "dataset");
Β
for (double[] ds : dataSets) {
int dof = ds.length - 1;
double dist = x2Dist(ds);
double prob = x2Prob(dof, dist);
System.out.printf("%4dΒ %12.3f Β %12.8f Β %5s Β %6s%n",
dof, dist, prob, x2IsUniform(ds, 0.05) ? "YES" : "NO",
Arrays.toString(ds));
}
}
} |
http://rosettacode.org/wiki/Verhoeff_algorithm | Verhoeff algorithm | Description
The Verhoeff algorithm is a checksum formula for error detection developed by the Dutch mathematician Jacobus Verhoeff and first published in 1969. It was the first decimal check digit algorithm which detects all single-digit errors, and all transposition errors involving two adjacent digits, which was at the time thought impossible with such a code.
As the workings of the algorithm are clearly described in the linked Wikipedia article they will not be repeated here.
Task
Write routines, methods, procedures etc. in your language to generate a Verhoeff checksum digit for non-negative integers of any length and to validate the result. A combined routine is also acceptable.
The more mathematically minded may prefer to generate the 3 tables required from the description provided rather than to hard-code them.
Write your routines in such a way that they can optionally display digit by digit calculations as in the Wikipedia example.
Use your routines to calculate check digits for the integers: 236, 12345 and 123456789012 and then validate them. Also attempt to validate the same integers if the check digits in all cases were 9 rather than what they actually are.
Display digit by digit calculations for the first two integers but not for the third.
Related task
Β Damm algorithm
| #Wren | Wren | import "/fmt" for Fmt
Β
var d = [
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9],
[1, 2, 3, 4, 0, 6, 7, 8, 9, 5],
[2, 3, 4, 0, 1, 7, 8, 9, 5, 6],
[3, 4, 0, 1, 2, 8, 9, 5, 6, 7],
[4, 0, 1, 2, 3, 9, 5, 6, 7, 8],
[5, 9, 8, 7, 6, 0, 4, 3, 2, 1],
[6, 5, 9, 8, 7, 1, 0, 4, 3, 2],
[7, 6, 5, 9, 8, 2, 1, 0, 4, 3],
[8, 7, 6, 5, 9, 3, 2, 1, 0, 4],
[9, 8, 7, 6, 5, 4, 3, 2, 1, 0]
]
Β
var inv = [0, 4, 3, 2, 1, 5, 6, 7, 8, 9]
Β
var p = [
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9],
[1, 5, 7, 6, 2, 8, 3, 0, 9, 4],
[5, 8, 0, 3, 7, 9, 6, 1, 4, 2],
[8, 9, 1, 6, 0, 4, 3, 5, 2, 7],
[9, 4, 5, 3, 1, 2, 6, 8, 7, 0],
[4, 2, 8, 6, 5, 7, 3, 9, 0, 1],
[2, 7, 9, 3, 8, 0, 6, 4, 1, 5],
[7, 0, 4, 6, 9, 1, 3, 2, 5, 8]
]
Β
var verhoeff = Fn.new { |s, validate, table|
if (table) {
System.print("%(validateΒ ? "Validation"Β : "Check digit") calculations for '%(s)':\n")
System.print(" i nα΅’ p[i,nα΅’] c")
System.print("------------------")
}
if (!validate) s = s + "0"
var c = 0
var le = s.count - 1
for (i in le..0) {
var ni = s[i].bytes[0] - 48
var pi = p[(le-i) % 8][ni]
c = d[c][pi]
if (table) Fmt.print("$2d $d $d $d", le-i, ni, pi, c)
}
if (table && !validate) System.print("\ninv[%(c)] =Β %(inv[c])")
return !validate ? inv[c] : c == 0
}
Β
var sts = [["236", true], ["12345", true], ["123456789012", false]]
for (st in sts) {
var c = verhoeff.call(st[0], false, st[1])
System.print("\nThe check digit for '%(st[0])' is '%(c)'\n")
for (stc in [st[0] + c.toString, st[0] + "9"]) {
var v = verhoeff.call(stc, true, st[1])
System.print("\nThe validation for '%(stc)' isΒ %(vΒ ? "correct"Β : "incorrect").\n")
}
} |
http://rosettacode.org/wiki/Vigen%C3%A8re_cipher | Vigenère cipher | Task
Implement a  Vigenère cypher,  both encryption and decryption.
The program should handle keys and text of unequal length,
and should capitalize everything and discard non-alphabetic characters.
(If your program handles non-alphabetic characters in another way,
make a note of it.)
Related tasks
Β Caesar cipher
Β Rot-13
Β Substitution Cipher
| #F.23 | F# | Β
module vigenere =
let keyschedule (key:string) =
let s = key.ToUpper().ToCharArray() |> Array.filter System.Char.IsLetter
let l = Array.length s
(fun n -> int s.[n % l])
Β
let enc k c = ((c + k - 130) % 26) + 65
let dec k c = ((c - k + 130) % 26) + 65
let crypt f key = Array.mapi (fun n c -> f (key n) c |> char)
Β
let encrypt key (plaintext:string) =
plaintext.ToUpper().ToCharArray()
|> Array.filter System.Char.IsLetter
|> Array.map int
|> crypt enc (keyschedule key)
|> (fun a -> new string(a))
Β
let decrypt key (ciphertext:string) =
ciphertext.ToUpper().ToCharArray()
|> Array.map int
|> crypt dec (keyschedule key)
|> (fun a -> new string(a))
Β
let passwd = "Vigenere Cipher"
let cipher = vigenere.encrypt passwd "Beware the Jabberwock, my son! The jaws that bite, the claws that catch!"
let plain = vigenere.decrypt passwd cipher
printfn "%s\n%s" cipher plain
Β |
http://rosettacode.org/wiki/Visualize_a_tree | Visualize a tree | A tree structure Β (i.e. a rooted, connected acyclic graph) Β is often used in programming.
It's often helpful to visually examine such a structure.
There are many ways to represent trees to a reader, such as:
Β indented text Β (Γ la unix tree command)
Β nested HTML tables
Β hierarchical GUI widgets
Β 2D Β or Β 3D Β images
Β etc.
Task
Write a program to produce a visual representation of some tree.
The content of the tree doesn't matter, nor does the output format, the only requirement being that the output is human friendly.
Make do with the vague term "friendly" the best you can.
| #JavaScript | JavaScript | <!doctype html>
<html id="doc">
<head><meta charset="utf-8"/>
<title>Stuff</title>
<script type="application/javascript">
function gid(id) { return document.getElementById(id); }
Β
function ce(tag, cls, parent_node) {
var e = document.createElement(tag);
e.className = cls;
if (parent_node) parent_node.appendChild(e);
return e;
}
Β
function dom_tree(id) {
gid('tree').textContent = "";
gid('tree').appendChild(mktree(gid(id), null));
}
Β
function mktree(e, p) {
var t = ce("div", "tree", p);
var tog = ce("span", "toggle", t);
var h = ce("span", "tag", t);
Β
if (e.tagName === undefined) {
h.textContent = "#Text";
var txt = e.textContent;
if (txt.length > 0 && txt.match(/\S/)) {
h = ce("div", "txt", t);
h.textContent = txt;
}
return t;
}
Β
tog.textContent = "β";
tog.onclick = function () { clicked(tog); }
h.textContent = e.nodeName;
Β
var l = e.childNodes;
for (var i = 0; iΒ != l.length; i++)
mktree(l[i], t);
return t;
}
Β
function clicked(e) {
var is_on = e.textContent == "β";
e.textContent = is_onΒ ? "+"Β : "β";
e.parentNode.className = is_onΒ ? "tree-hide"Β : "tree";
}
</script>
<style>
#tree { white-space: pre; font-family: monospace; border: 1px solid }
.tree > .tree-hide, .tree > .tree
{ margin-left: 2em; border-left: 1px dotted rgba(0,0,0,.2)}
.tree-hide > .tree, .tree-hide > .tree-hide { display: none }
.tag { color: navy }
.tree-hide > .tag { color: maroon }
.txt { color: gray; padding: 0 .5em; margin: 0 .5em 0 2em; border: 1px dotted rgba(0,0,0,.1) }
.toggle { display: inline-block; width: 2em; text-align: center }
</style>
</head>
<body>
<article>
<section>
<h1>Headline</h1>
Blah blah
</section>
<section>
<h1>More headline</h1>
<blockquote>Something something</blockquote>
<section><h2>Nested section</h2>
Somethin somethin list:
<ul>
<li>Apples</li>
<li>Oranges</li>
<li>Cetera Fruits</li>
</ul>
</section>
</section>
</article>
<div id="tree"><a href="javascript:dom_tree('doc')">click me</a></div>
</body>
</html> |
http://rosettacode.org/wiki/Walk_a_directory/Non-recursively | Walk a directory/Non-recursively | Task
Walk a given directory and print the names of files matching a given pattern.
(How is "pattern" defined? substring match? DOS pattern? BASH pattern? ZSH pattern? Perl regular expression?)
Note: This task is for non-recursive methods. Β These tasks should read a single directory, not an entire directory tree.
Note: Please be careful when running any code presented here.
Related task
Β Walk Directory Tree Β (read entire directory tree).
| #Raku | Raku | .say for dir ".", :test(/foo/); |
http://rosettacode.org/wiki/Walk_a_directory/Non-recursively | Walk a directory/Non-recursively | Task
Walk a given directory and print the names of files matching a given pattern.
(How is "pattern" defined? substring match? DOS pattern? BASH pattern? ZSH pattern? Perl regular expression?)
Note: This task is for non-recursive methods. Β These tasks should read a single directory, not an entire directory tree.
Note: Please be careful when running any code presented here.
Related task
Β Walk Directory Tree Β (read entire directory tree).
| #Rascal | Rascal | import IO;
public void Walk(loc a, str pattern){
for (entry <- listEntries(a))
endsWith(entry, pattern)Β ? println(entry);
} |
http://rosettacode.org/wiki/Walk_a_directory/Recursively | Walk a directory/Recursively | Task
Walk a given directory tree and print files matching a given pattern.
Note: This task is for recursive methods. Β These tasks should read an entire directory tree, not a single directory.
Note: Please be careful when running any code examples found here.
Related task
Β Walk a directory/Non-recursively Β (read a single directory).
| #Julia | Julia | rootpath = "/home/user/music"
pattern = r".mp3$"
Β
for (root, dirs, files) in walkdir(rootpath)
for file in files
if occursin(pattern, file) println(file) end
end
end |
http://rosettacode.org/wiki/Walk_a_directory/Recursively | Walk a directory/Recursively | Task
Walk a given directory tree and print files matching a given pattern.
Note: This task is for recursive methods. Β These tasks should read an entire directory tree, not a single directory.
Note: Please be careful when running any code examples found here.
Related task
Β Walk a directory/Non-recursively Β (read a single directory).
| #Kotlin | Kotlin | // version 1.2.0
Β
import java.io.File
Β
fun walkDirectoryRecursively(dirPath: String, pattern: Regex): Sequence<String> {
val d = File(dirPath)
require (d.exists() && d.isDirectory())
return d.walk().map { it.name }.filter { it.matches(pattern) }.sorted().distinct() }
Β
fun main(args: Array<String>) {
val r = Regex("""^v(a|f).*\.h$""") // get all C header files beginning with 'va' or 'vf'
val files = walkDirectoryRecursively("/usr/include", r)
for (file in files) println(file)
}
Β |
http://rosettacode.org/wiki/Water_collected_between_towers | Water collected between towers | Task
In a two-dimensional world, we begin with any bar-chart (or row of close-packed 'towers', each of unit width), and then it rains,
completely filling all convex enclosures in the chart with water.
9 ββ 9 ββ
8 ββ 8 ββ
7 ββ ββ 7 ββββββββββββ
6 ββ ββ ββ 6 ββββββββββββ
5 ββ ββ ββ ββββ 5 ββββββββββββββββ
4 ββ ββ ββββββββ 4 ββββββββββββββββ
3 ββββββ ββββββββ 3 ββββββββββββββββ
2 ββββββββββββββββ ββ 2 ββββββββββββββββββββ
1 ββββββββββββββββββββ 1 ββββββββββββββββββββ
In the example above, a bar chart representing the values [5, 3, 7, 2, 6, 4, 5, 9, 1, 2] has filled, collecting 14 units of water.
Write a function, in your language, from a given array of heights, to the number of water units that can be held in this way, by a corresponding bar chart.
Calculate the number of water units that could be collected by bar charts representing each of the following seven series:
[[1, 5, 3, 7, 2],
[5, 3, 7, 2, 6, 4, 5, 9, 1, 2],
[2, 6, 3, 5, 2, 8, 1, 4, 2, 2, 5, 3, 5, 7, 4, 1],
[5, 5, 5, 5],
[5, 6, 7, 8],
[8, 7, 7, 6],
[6, 7, 10, 7, 6]]
See, also:
Four Solutions to a Trivial Problem β a Google Tech Talk by Guy Steele
Water collected between towers on Stack Overflow, from which the example above is taken)
An interesting Haskell solution, using the Tardis monad, by Phil Freeman in a Github gist.
| #Kotlin | Kotlin | // version 1.1.2
Β
fun waterCollected(tower: IntArray): Int {
val n = tower.size
val highLeft = listOf(0) + (1 until n).map { tower.slice(0 until it).max()!! }
val highRight = (1 until n).map { tower.slice(it until n).max()!! } + 0
return (0 until n).map { maxOf(minOf(highLeft[it], highRight[it]) - tower[it], 0) }.sum()
}
Β
fun main(args: Array<String>) {
val towers = listOf(
intArrayOf(1, 5, 3, 7, 2),
intArrayOf(5, 3, 7, 2, 6, 4, 5, 9, 1, 2),
intArrayOf(2, 6, 3, 5, 2, 8, 1, 4, 2, 2, 5, 3, 5, 7, 4, 1),
intArrayOf(5, 5, 5, 5),
intArrayOf(5, 6, 7, 8),
intArrayOf(8, 7, 7, 6),
intArrayOf(6, 7, 10, 7, 6)
)
for (tower in towers) {
println("${"%2d".format(waterCollected(tower))} from ${tower.contentToString()}")
}
} |
http://rosettacode.org/wiki/Video_display_modes | Video display modes | The task is to demonstrate how to switch video display modes within the language. A brief description of the supported video modes would be useful.
| #Kotlin | Kotlin | // version 1.1.51
Β
import java.util.Scanner
Β
fun runSystemCommand(command: String) {
val proc = Runtime.getRuntime().exec(command)
Scanner(proc.inputStream).use {
while (it.hasNextLine()) println(it.nextLine())
}
proc.waitFor()
println()
}
Β
fun main(args: Array<String>) {
// query supported display modes
runSystemCommand("xrandr -q")
Thread.sleep(3000)
Β
// change display mode to 1024x768 say (no text output)
runSystemCommand("xrandr -s 1024x768")
Thread.sleep(3000)
Β
// change it back again to 1366x768 (or whatever is optimal for your system)
runSystemCommand("xrandr -s 1366x768")
} |
http://rosettacode.org/wiki/Video_display_modes | Video display modes | The task is to demonstrate how to switch video display modes within the language. A brief description of the supported video modes would be useful.
| #Locomotive_Basic | Locomotive Basic | 10 MODE 0: REM switch to mode 0 |
http://rosettacode.org/wiki/Video_display_modes | Video display modes | The task is to demonstrate how to switch video display modes within the language. A brief description of the supported video modes would be useful.
| #Lua | Lua | print("\33[?3h") -- 132-column text
print("\33[?3l") -- 80-column text |
http://rosettacode.org/wiki/Video_display_modes | Video display modes | The task is to demonstrate how to switch video display modes within the language. A brief description of the supported video modes would be useful.
| #Nim | Nim | import os, osproc, strformat, strscans
Β
# Retrieve video modes.
let p = startProcess("xrandr", "", ["-q"], nil, {poUsePath})
var currWidth, currHeight = 0 # Current video mode.
var width, height = 0 # Some other video mode.
for line in p.lines:
echo line
# Find current display mode, marked by an asterisk.
var f: float
if currWidth == 0:
# Find current width and height.
discard line.scanf(" $s$ix$i $s$f*", currWidth, currHeight, f)
elif width == 0:
# Find another width and height.
discard line.scanf(" $s$ix$i $s$f", width, height, f)
p.close()
Β
# Change video mode.
let newMode = &"{width}x{height}"
sleep 1000
echo "\nSwitching to ", newMode
sleep 2000
discard execProcess("xrandr", "", ["-s", newMode], nil, {poUsePath})
Β
# Restore previous video mode.
let prevMode = &"{currWidth}x{currHeight}"
sleep 1000
echo "\nSwitching back to ", prevMode
sleep 2000
discard execProcess("xrandr", "", ["-s", prevMode], nil, {poUsePath}) |
http://rosettacode.org/wiki/Verify_distribution_uniformity/Naive | Verify distribution uniformity/Naive | This task is an adjunct to Seven-sided dice from five-sided dice.
Task
Create a function to check that the random integers returned from a small-integer generator function have uniform distribution.
The function should take as arguments:
The function (or object) producing random integers.
The number of times to call the integer generator.
A 'delta' value of some sort that indicates how close to a flat distribution is close enough.
The function should produce:
Some indication of the distribution achieved.
An 'error' if the distribution is not flat enough.
Show the distribution checker working when the produced distribution is flat enough and when it is not. (Use a generator from Seven-sided dice from five-sided dice).
See also:
Verify distribution uniformity/Chi-squared test
| #Liberty_BASIC | Liberty BASIC | Β
n=1000
print "Testing ";n;" times"
if not(check(n, 0.05)) then print "Test failed" else print "Test passed"
print
Β
n=10000
print "Testing ";n;" times"
if not(check(n, 0.05)) then print "Test failed" else print "Test passed"
print
Β
n=50000
print "Testing ";n;" times"
if not(check(n, 0.05)) then print "Test failed" else print "Test passed"
print
Β
end
Β
function check(n, delta)
'fill randoms
dim a(n)
maxBucket=0
minBucket=1e10
for i = 1 to n
a(i) = GENERATOR()
if a(i)>maxBucket then maxBucket=a(i)
if a(i)<minBucket then minBucket=a(i)
next
'fill buckets
nBuckets = maxBucket+1 'from 0
dim buckets(maxBucket)
for i = 1 to n
buckets(a(i)) = buckets(a(i))+1
next
'check buckets
expected=n/(maxBucket-minBucket+1)
minVal=int(expected*(1-delta))
maxVal=int(expected*(1+delta))
expected=int(expected)
print "minVal", "Expected", "maxVal"
print minVal, expected, maxVal
print "Bucket", "Counter", "pass/fail"
check = 1
for i = minBucket to maxBucket
print i, buckets(i), _
iif$((minVal > buckets(i)) OR (buckets(i) > maxVal) ,"fail","")
if (minVal > buckets(i)) OR (buckets(i) > maxVal) then check = 0
next
end function
Β
function iif$(test, valYes$, valNo$)
iif$ = valNo$
if test then iif$ = valYes$
end function
Β
function GENERATOR()
'GENERATOR = int(rnd(0)*10) '0..9
GENERATOR = 1+int(rnd(0)*5) '1..5: dice5
end function
Β |
http://rosettacode.org/wiki/Variable-length_quantity | Variable-length quantity | Implement some operations on variable-length quantities, at least including conversions from a normal number in the language to the binary representation of the variable-length quantity for that number, and vice versa. Any variants are acceptable.
Task
With above operations,
convert these two numbers 0x200000 (2097152 in decimal) and 0x1fffff (2097151 in decimal) into sequences of octets (an eight-bit byte);
display these sequences of octets;
convert these sequences of octets back to numbers, and check that they are equal to original numbers.
| #C | C | #include <stdio.h>
#include <stdint.h>
Β
void to_seq(uint64_t x, uint8_t *out)
{
int i, j;
for (i = 9; i > 0; i--) {
if (x & 127ULL << i * 7) break;
}
for (j = 0; j <= i; j++)
out[j] = ((x >> ((i - j) * 7)) & 127) | 128;
Β
out[i] ^= 128;
}
Β
uint64_t from_seq(uint8_t *in)
{
uint64_t r = 0;
Β
do {
r = (r << 7) | (uint64_t)(*in & 127);
} while (*in++ & 128);
Β
return r;
}
Β
int main()
{
uint8_t s[10];
uint64_t x[] = { 0x7f, 0x4000, 0, 0x3ffffe, 0x1fffff, 0x200000, 0x3311a1234df31413ULL};
Β
int i, j;
for (j = 0; j < sizeof(x)/8; j++) {
to_seq(x[j], s);
printf("seq fromΒ %llx: [ ", x[j]);
Β
i = 0;
do { printf("%02x ", s[i]); } while ((s[i++] & 128));
printf("] back:Β %llx\n", from_seq(s));
}
Β
return 0;
} |
http://rosettacode.org/wiki/Variadic_function | Variadic function | Task
Create a function which takes in a variable number of arguments and prints each one on its own line.
Also show, if possible in your language, how to call the function on a list of arguments constructed at runtime.
Functions of this type are also known as Variadic Functions.
Related task
Β Call a function
| #ACL2 | ACL2 | (defun print-all-fn (xs)
(if (endp xs)
nil
(prog2$ (cw "~x0~%" (first xs))
(print-all-fn (rest xs)))))
Β
(defmacro print-all (&rest args)
`(print-all-fn (quote ,args))) |
http://rosettacode.org/wiki/Vector | Vector | Task
Implement a Vector class (or a set of functions) that models a Physical Vector. The four basic operations and a pretty print function should be implemented.
The Vector may be initialized in any reasonable way.
Start and end points, and direction
Angular coefficient and value (length)
The four operations to be implemented are:
Vector + Vector addition
Vector - Vector subtraction
Vector * scalar multiplication
Vector / scalar division
| #BASIC256 | BASIC256 | arraybase 1
dim vect1(2)
vect1[1] = 5Β : vect1[2] = 7
dim vect2(2)
vect2[1] = 2Β : vect2[2] = 3
dim vect3(vect1[?])
Β
subroutine showarray(vect3)
print "[";
svect$ = ""
for n = 1 to vect3[?]
svect$ &= vect3[n] & ", "
next n
svect$ = left(svect$, length(svect$) - 2)
print svect$;
print "]"
end subroutine
Β
for n = 1 to vect1[?]
vect3[n] = vect1[n] + vect2[n]
next n
print "[" & vect1[1] & ", " & vect1[2] & "] + [" & vect2[1] & ", " & vect2[2] & "] = ";
call showarray(vect3)
Β
for n = 1 to vect1[?]
vect3[n] = vect1[n] - vect2[n]
next n
print "[" & vect1[1] & ", " & vect1[2] & "] - [" & vect2[1] & ", " & vect2[2] & "] = ";
call showarray(vect3)
Β
for n = 1 to vect1[?]
vect3[n] = vect1[n] * 11
next n
print "[" & vect1[1] & ", " & vect1[2] & "] * " & 11 & " = ";
call showarray(vect3)
Β
for n = 1 to vect1[?]
vect3[n] = vect1[n] / 2
next n
print "[" & vect1[1] & ", " & vect1[2] & "] / " & 2 & " = ";
call showarray(vect3)
end |
http://rosettacode.org/wiki/Variable_size/Set | Variable size/Set | Task
Demonstrate how to specify the minimum size of a variable or a data type.
| #Ada | Ada | type Response is (Yes, No); -- Definition of an enumeration type with two values
for Response'Size use 1; -- Setting the size of Response to 1 bit, rather than the default single byte size |
http://rosettacode.org/wiki/Variable_size/Set | Variable size/Set | Task
Demonstrate how to specify the minimum size of a variable or a data type.
| #ARM_Assembly | ARM Assembly | .byte 0xFF
.align 4
.word 0xFFFF
.align 4
.long 0xFFFFFFFF |
http://rosettacode.org/wiki/Variable_size/Set | Variable size/Set | Task
Demonstrate how to specify the minimum size of a variable or a data type.
| #AutoHotkey | AutoHotkey | 10 DIM A%(10): REM the array size is 10 integers
20 DIM B(10): REM the array will hold 10 floating point values
30 DIM C$(12): REM a character array of 12 bytes |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.