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/Variable_size/Set | Variable size/Set | Task
Demonstrate how to specify the minimum size of a variable or a data type.
| #BASIC | BASIC | 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 |
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.
| #C | C | #include <stdint.h>
int_least32_t foo; |
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.
| #Raku | Raku | use Image::PNG::Portable;
my @bars = '▁▂▃▅▆▇▇▆▅▃▂▁'.comb;
my %type = ( # Voronoi diagram type distance calculation
'Taxicab' => sub ($px, $py, $x, $y) { ($px - $x).abs + ($py - $y).abs },
'Euclidean' => sub ($px, $py, $x, $y) { ($px - $x)² + ($py - $y)² },
'Minkowski' => sub ($px, $py, $x, $... |
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 distribut... | #Julia | Julia | # v0.6
using Distributions
function eqdist(data::Vector{T}, α::Float64=0.05)::Bool where T <: Real
if ! (0 ≤ α ≤ 1); error("α must be in [0, 1]") end
exp = mean(data)
chisqval = sum((x - exp) ^ 2 for x in data) / exp
pval = ccdf(Chisq(2), chisqval)
return pval > α
end
data1 = [199809, 200665, ... |
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 distribut... | #Kotlin | Kotlin | // version 1.1.51
typealias Func = (Double) -> Double
fun gammaLanczos(x: Double): Double {
var xx = x
val p = doubleArrayOf(
0.99999999999980993,
676.5203681218851,
-1259.1392167224028,
771.32342877765313,
-176.61502916214059,
12.507343278686905,
-0.13857109526572... |
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 ... | #Factor | Factor | USING: arrays ascii formatting kernel math math.functions
math.order sequences ;
IN: rosetta-code.vigenere-cipher
: mult-pad ( key input -- x )
[ length ] bi@ 2dup < [ swap ] when / ceiling ;
: lengthen-pad ( key input -- rep-key input )
[ mult-pad ] 2keep [ <repetition> concat ] dip
[ length ] keep [ h... |
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 ... | #Fortran | Fortran | program vigenere_cipher
implicit none
character(80) :: plaintext = "Beware the Jabberwock, my son! The jaws that bite, the claws that catch!", &
ciphertext = ""
character(14) :: key = "VIGENERECIPHER"
call encrypt(plaintext, ciphertext, key)
write(*,*) plaintext
write(*,*) ciphertex... |
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 ... | #jq | jq | 0
├─ 1
├─ 2
└─ 3
|
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.
... | #Raven | Raven | 'dir://.' open each as item
item m/\.txt$/ if "%(item)s\n" print |
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.
... | #REXX | REXX | /*REXX program shows files in directory tree that match a given criteria*/
parse arg xdir; if xdir='' then xdir='\' /*Any DIR? Use default.*/
@.=0 /*default in case ADDRESS fails. */
trace off /*suppress REXX err msg for fails*/
address system 'DIR'... |
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 ... | #Lasso | Lasso | // care only about visible files and filter out any directories
define dir -> eachVisibleFilePath() => {
return with name in self -> eachEntry where #name -> second != io_dir_dt_dir where not(#name -> first -> beginswith('.')) select .makeFullPath(#name -> first)
}
// care only about visible directories and filter... |
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 ... | #LiveCode | LiveCode | function pathsForDirectoryAndWildcardPattern pDirectory, pWildcardPattern
-- returns a return-delimited list of long file names
-- the last character in the list is a return, unless the list is empty
filter files(pDirectory) with pWildcardPattern
repeat for each line tFile in it
put pDirectory & sla... |
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 ██ ... | #Lua | Lua | function waterCollected(i,tower)
local length = 0
for _ in pairs(tower) do
length = length + 1
end
local wu = 0
repeat
local rht = length - 1
while rht >= 0 do
if tower[rht + 1] > 0 then
break
end
rht = rht - 1
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.
| #Perl | Perl | $| = 1;
my @info = `xrandr -q`;
$info[0] =~ /current (\d+) x (\d+)/;
my $current = "$1x$2";
my @resolutions;
for (@info) {
push @resolutions, $1 if /^\s+(\d+x\d+)/
}
system("xrandr -s $resolutions[-1]");
print "Current resolution $resolutions[-1].\n";
for (reverse 1 .. 9) {
print "\rChanging back in $_ se... |
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.
| #Phix | Phix | without js -- (system, system_exec, sleep)
if platform()=LINUX then
{} = system_exec("xrandr -s 640x480")
sleep(3)
{} = system_exec("xrandr -s 1280x960")
else -- WINDOWS
puts(1,"") -- (ensure console exists)
system("mode CON: COLS=40 LINES=25")
sleep(3)
system("mode CON: COLS=80 LINES=25")
e... |
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.
| #Python | Python | import win32api
import win32con
import pywintypes
devmode=pywintypes.DEVMODEType()
devmode.PelsWidth=640
devmode.PelsHeight=480
devmode.Fields=win32con.DM_PELSWIDTH | win32con.DM_PELSHEIGHT
win32api.ChangeDisplaySettings(devmode,0) |
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 ... | #Mathematica.2FWolfram_Language | Mathematica/Wolfram Language | SetAttributes[CheckDistribution, HoldFirst]
CheckDistribution[function_,number_,delta_] :=(Print["Expected: ", N[number/7], ", Generated :",
Transpose[Tally[Table[function, {number}]]][[2]] // Sort]; If[(Max[#]-Min[#])&
[Transpose[Tally[Table[function, {number}]]][[2]]] < delta*number/700, "Flat", "Skewed"]) |
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 ... | #Nim | Nim | import tables
proc checkDist(f: proc(): int; repeat: Positive; tolerance: float) =
var counts: CountTable[int]
for _ in 1..repeat:
counts.inc f()
let expected = (repeat / counts.len).toInt # Rounded to nearest.
let allowedDelta = (expected.toFloat * tolerance / 100).toInt
var maxDelta = 0
for... |
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 ... | #OCaml | OCaml | let distcheck fn n ?(delta=1.0) () =
let h = Hashtbl.create 5 in
for i = 1 to n do
let v = fn() in
let n =
try Hashtbl.find h v
with Not_found -> 0
in
Hashtbl.replace h v (n+1)
done;
Hashtbl.iter (fun v n -> Printf.printf "%d => %d\n%!" v n) h;
let target = (float n) /. float (... |
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 (209... | #C.2B.2B | C++ | #include <iomanip>
#include <iostream>
#include <vector>
std::ostream &operator<<(std::ostream &os, const std::vector<uint8_t> &v) {
auto it = v.cbegin();
auto end = v.cend();
os << "[ ";
if (it != end) {
os << std::setfill('0') << std::setw(2) << (uint32_t)*it;
it = std::next(it);
... |
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... | #ActionScript | ActionScript | public function printArgs(... args):void
{
for (var i:int = 0; i < args.length; i++)
trace(args[i]);
} |
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... | #Ada | Ada | with Ada.Strings.Unbounded, Ada.Text_IO;
procedure Variadic is
subtype U_String is Ada.Strings.Unbounded.Unbounded_String;
use type U_String;
function "+"(S: String) return U_String
renames Ada.Strings.Unbounded.To_Unbounded_String;
function "-"(U: U_String) return String
renames Ada.Strin... |
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... | #BQN | BQN | 5‿7 + 2‿3
⟨7 10⟩
5‿7 - 2‿3
⟨3 4⟩
5‿7 × 11
⟨55 77⟩
5‿7 ÷ 2
⟨2.5 3.5⟩ |
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... | #C | C |
#include<stdio.h>
#include<math.h>
#define pi M_PI
typedef struct{
double x,y;
}vector;
vector initVector(double r,double theta){
vector c;
c.x = r*cos(theta);
c.y = r*sin(theta);
return c;
}
vector addVector(vector a,vector b){
vector c;
c.x = a.x + b.x;
c.y = a.y + b.y;
return c;
}
vector... |
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.
| #C.2B.2B | C++ | #include <boost/cstdint.hpp>
boost::int_least32_t foo; |
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.
| #D | D | typedef long[0] zeroLength ;
writefln(zeroLength.sizeof) ; // print 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.
| #Erlang | Erlang | 15> <<1:11>>.
<<0,1:3>>
|
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.
| #ERRE | ERRE | DIM A%[10] ! the array size is 10 integers
DIM B[10] ! the array will hold 10 floating point values
DIM C$[12] ! a character array of 12 bytes |
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.
| #Fortran | Fortran | program setsize
implicit none
integer, parameter :: p1 = 6
integer, parameter :: p2 = 12
integer, parameter :: r1 = 30
integer, parameter :: r2 = 1000
integer, parameter :: r3 = 2
integer, parameter :: r4 = 4
integer, parameter :: r5 = 8
integer, parameter :: r6 = 16
integer, parameter :: rprec1 = s... |
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.
| #Red | Red | Red [
Source: https://github.com/vazub/rosetta-red
Tabs: 4
Needs: 'View
]
comment {
This is a naive and therefore inefficient approach. For production-related tasks,
a proper full implementation of Fortune's algorithm should be preferred.
}
canvas: 500x500
num-points: 50
diagram-l1: make image!... |
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.
| #ReScript | ReScript | let n_sites = 60
let size_x = 640
let size_y = 480
let rand_int_range = (a, b) => a + Random.int(b - a + 1)
let dist_euclidean = (x, y) => { (x * x + y * y) }
let dist_minkowski = (x, y) => { (x * x * x + y * y * y) }
let dist_taxicab = (x, y) => { abs(x) + abs(y) }
let dist_f = dist_euclidean
let dist_f = dist... |
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 distribut... | #Mathematica.2FWolfram_Language | Mathematica/Wolfram Language | discreteUniformDistributionQ[data_, {min_Integer, max_Integer}, confLevel_: .05] :=
If[$VersionNumber >= 8,
confLevel <= PearsonChiSquareTest[data, DiscreteUniformDistribution[{min, max}]],
Block[{v, k = max - min, n = Length@data},
v = (k + 1) (Plus @@ (((Length /@ Split[Sort@data]))^2))/n - n;
GammaRegular... |
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 distribut... | #Nim | Nim | import lenientops, math, stats, strformat, sugar
func simpson38(f: (float) -> float; a, b: float; n: int): float =
let h = (b - a) / n
let h1 = h / 3
var sum = f(a) + f(b)
for i in countdown(3 * n - 1, 1):
if i mod 3 == 0:
sum += 2 * f(a + h1 * i)
else:
sum += 3 * f(a + h1 * i)
result = ... |
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 ... | #FreeBASIC | FreeBASIC |
Function Filtrar(cadorigen As String) As String
Dim As String letra
Dim As String filtrado = ""
For i As Integer = 1 To Len(cadorigen)
letra = Ucase(Mid(cadorigen, i, 1))
If Instr("ABCDEFGHIJKLMNOPQRSTUVWXYZ", letra) Then filtrado += letra
Next i
Return filtrado
End Function
Fun... |
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 ... | #Julia | Julia | using Gadfly, LightGraphs, GraphPlot
gx = kronecker(5, 12, 0.57, 0.19, 0.19)
gplot(gx)
|
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 ... | #Kotlin | Kotlin | // version 1.2.0
import java.util.Random
class Stem(var str: String? = null, var next: Stem? = null)
const val SDOWN = " |"
const val SLAST = " `"
const val SNONE = " "
val rand = Random()
fun tree(root: Int, head: Stem?) {
val col = Stem()
var head2 = head
var tail = head
while (tail != n... |
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.
... | #Ring | Ring |
###---------------------------------------
### Directory Tree Walk
### Look for FileType for Music and Video
fileType = [".avi", ".mp4", ".mpg", ".mkv", ".mp3", ".wmv" ]
dirList = []
musicList = []
###---------------------------------------
### Main
###-----------------------------------
### Start... |
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.
... | #Ruby | Ruby | # Files under this directory:
Dir.glob('*') { |file| puts file }
# Files under path '/foo/bar':
Dir.glob( File.join('/foo/bar', '*') ) { |file| puts file }
# As a method
def file_match(pattern=/\.txt/, path='.')
Dir[File.join(path,'*')].each do |file|
puts file if file =~ pattern
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 ... | #Lua | Lua | local lfs = require("lfs")
-- This function takes two arguments:
-- - the directory to walk recursively;
-- - an optional function that takes a file name as argument, and returns a boolean.
function find(self, fn)
return coroutine.wrap(function()
for f in lfs.dir(self) do
if f ~= "." and f ~= ".." then
... |
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 ██ ... | #M2000_Interpreter | M2000 Interpreter |
Module Water {
Flush ' empty stack
Data (1, 5, 3, 7, 2)
Data (5, 3, 7, 2, 6, 4, 5, 9, 1, 2)
Data (2, 6, 3, 5, 2, 8, 1, 4, 2, 2, 5, 3, 5, 7, 4, 1)
Data (5, 5, 5, 5), (5, 6, 7, 8),(8, 7, 7, 6)
Data (6, 7, 10, 7, 6)
bars=stack.size ' mark stack frame
Dim bar()
for b... |
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.
| #QBasic | QBasic | 'QBasic can switch VGA modes
SCREEN 18 '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.
| #Raku | Raku | my @info = QX('xrandr -q').lines;
@info[0] ~~ /<?after 'current '>(\d+) ' x ' (\d+)/;
my $current = "$0x$1";
my @resolutions;
@resolutions.push: $0 if $_ ~~ /^\s+(\d+'x'\d+)/ for @info;
QX("xrandr -s @resolutions[*-1]");
say "Current resolution {@resolutions[*-1]}.";
for 9 ... 1 {
print "\rChanging back in $_... |
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.
| #REXX | REXX | /*REXX program to switch video display modes based on columns and lines.*/
parse arg cols lines .
'MODE' "CON: COLS="cols 'LINES='lines
/*stick a fork in it, we're done.*/ |
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 ... | #PARI.2FGP | PARI/GP | dice5()=random(5)+1;
dice7()={
my(t);
while((t=dice5()*5+dice5()) > 26,);
t\3-1
};
cumChi2(chi2,dof)={
my(g=gamma(dof/2));
incgam(dof/2,chi2/2,g)/g
};
test(f,n,alpha=.05)={
v=vector(n,i,f());
my(s,ave,dof,chi2,p);
s=sum(i=1,n,v[i],0.);
ave=s/n;
dof=n-1;
chi2=sum(i=1,n,(v[i]-ave)^2)/ave;
p=cumChi2(c... |
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 (209... | #C.23 | C# | namespace Vlq
{
using System;
using System.Collections.Generic;
using System.Linq;
public static class VarLenQuantity
{
public static ulong ToVlq(ulong integer)
{
var array = new byte[8];
var buffer = ToVlqCollection(integer)
.SkipWhile(b => b == 0)
.Reverse()
.To... |
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... | #Aime | Aime | void
f(...)
{
integer i;
i = 0;
while (i < count()) {
o_text($i);
o_byte('\n');
i += 1;
}
}
integer
main(void)
{
f("Mary", "had", "a", "little", "lamb");
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... | #ALGOL_68 | ALGOL 68 | main:(
MODE STRINT = UNION(STRING, INT, PROC(REF FILE)VOID, VOID);
PROC print strint = (FLEX[]STRINT argv)VOID: (
FOR i TO UPB argv DO
CASE argv[i] IN
(INT i):print(whole(i,-1)),
(STRING s):print(s),
(PROC(REF FILE)VOID f):f(stand out),
(VOID):print(error char)
ESAC... |
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... | #C.23 | C# | using System;
using System.Collections.Generic;
using System.Linq;
namespace RosettaVectors
{
public class Vector
{
public double[] store;
public Vector(IEnumerable<double> init)
{
store = init.ToArray();
}
public Vector(double x, double y)
{
... |
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.
| #Free_Pascal | Free Pascal | type
{$packEnum 4}
enum = (x, y, z); |
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.
| #FreeBASIC | FreeBASIC | package main
import (
"fmt"
"unsafe"
)
func main() {
i := 5 // default type is int
r := '5' // default type is rune (which is int32)
f := 5. // default type is float64
c := 5i // default type is complex128
fmt.Println("i:", unsafe.Sizeof(i), "bytes")
fmt.Println("r:", unsafe.Size... |
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.
| #Ring | Ring |
# Project : Voronoi diagram
load "guilib.ring"
load "stdlib.ring"
paint = null
new qapp
{
spots = 100
leftside = 400
rightside = 400
locx = list(spots)
locy = list(spots)
rgb = newlist(spots,3)
seal = newlist(leftside, rightside)
reach = n... |
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 distribut... | #OCaml | OCaml | let sqr x = x *. x
let chi2UniformDistance distrib =
let count, len = Array.fold_left (fun (s, c) e -> s + e, succ c)
(0, 0) distrib in
let expected = float count /. float len in
let distance = Array.fold_left (fun s e ->
s +. sqr (float e -. expected) /. expected
) 0. distrib in
let dof = floa... |
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 ... | #Go | Go | package main
import "fmt"
type vkey string
func newVigenère(key string) (vkey, bool) {
v := vkey(upperOnly(key))
return v, len(v) > 0 // key length 0 invalid
}
func (k vkey) encipher(pt string) string {
ct := upperOnly(pt)
for i, c := range ct {
ct[i] = 'A' + (c-'A'+k[i%len(k)]-'A')%26
... |
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 ... | #Lingo | Lingo | -- parent script "TreeItem"
-- (minimal implementation with direct property access)
property name
property children
on new (me, itemName)
me.name = itemName
me.children = []
return me
end
on addChild (me, child)
me.children.add(child)
end
-- print a tree
on printTree (me, treeItem, indent)
if voidP(tr... |
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 ... | #Lua | Lua | function makeTree(v,ac)
if type(ac) == "table" then
return {value=v,children=ac}
else
return {value=v}
end
end
function printTree(t,last,prefix)
if last == nil then
printTree(t, false, '')
else
local current = ''
local next = ''
if last then
... |
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.
... | #Run_BASIC | Run BASIC | files #g, DefaultDir$ + "\*.jpg" ' find all jpg files
if #g HASANSWER() then
count = #g rowcount() ' get count of files
for i = 1 to count
if #g hasanswer() then 'retrieve info for next file
#g nextfile$() 'print name of file
print #g NAME$()
end if
next
end if
wait |
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.
... | #Rust | Rust | extern crate docopt;
extern crate regex;
extern crate rustc_serialize;
use docopt::Docopt;
use regex::Regex;
const USAGE: &'static str = "
Usage: rosetta <pattern>
Walks the directory tree starting with the current working directory and
print filenames matching <pattern>.
";
#[derive(Debug, RustcDecodable)]
str... |
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 ... | #Mathematica.2FWolfram_Language | Mathematica/Wolfram Language | FileNames["*"]
FileNames["*.png", $RootDirectory]
FileNames["*", {"*"}, Infinity] |
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 ... | #MATLAB_.2F_Octave | MATLAB / Octave | function walk_a_directory_recursively(d, pattern)
f = dir(fullfile(d,pattern));
for k = 1:length(f)
fprintf('%s\n',fullfile(d,f(k).name));
end;
f = dir(d);
n = find([f.isdir]);
for k=n(:)'
if any(f(k).name~='.')
walk_a_directory_recursively(fullfile(d,f(k).name), pattern);
end;
end;
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 ██ ... | #Mathematica_.2F_Wolfram_Language | Mathematica / Wolfram Language | ClearAll[waterbetween]
waterbetween[h_List] := Module[{mi, ma, ch},
{mi, ma} = MinMax[h];
Sum[
ch = h - i;
Count[
Flatten@
Position[
ch, _?Negative], _?(Between[
MinMax[Position[ch, _?NonNegative]]])]
,
{i, mi + 1, ma}
]
]
h = {{1, 5, 3, 7, 2}, {5, 3, 7, 2, 6, 4, 5, 9, 1, 2}, ... |
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.
| #Ring | Ring |
system("mode 40, 25")
|
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.
| #Scala | Scala | object VideoDisplayModes extends App {
import java.util.Scanner
def runSystemCommand(command: String) {
val proc = Runtime.getRuntime.exec(command)
val a: Unit = {
val a = new Scanner(proc.getInputStream)
while (a.hasNextLine) println(a.nextLine())
}
proc.waitFor()
println()
... |
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.
| #smart_BASIC | smart BASIC | GRAPHICS
FILL RECT 50,50 SIZE 50
GRAPHICS MODE CLEAR
FILL RECT 50,50 SIZE 25 |
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.
| #UNIX_Shell | UNIX Shell | $ xrandr -q |
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 ... | #Perl | Perl | sub roll7 { 1+int rand(7) }
sub roll5 { 1+int rand(5) }
sub roll7_5 {
while(1) {
my $d7 = (5*&roll5 + &roll5 - 6) % 8;
return $d7 if $d7;
}
}
my $threshold = 5;
print dist( $_, $threshold, \&roll7 ) for <1001 1000006>;
print dist( $_, $threshold, \&roll7_5 ) for <1001 1000006>;
sub dist {
my($n, $... |
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 (209... | #D | D | import std.stdio, std.string, std.file, std.algorithm;
/// Variable length quantity (unsigned long, max 63-bit).
struct VLQ {
ulong value;
// This allows VLQ to work like an ulong.
alias value this;
uint extract(in ubyte[] v) pure
in {
assert(v.length > 0);
} body {
immutab... |
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... | #AppleScript | AppleScript | use framework "Foundation"
-- positionalArgs :: [a] -> String
on positionalArgs(xs)
-- follow each argument with a line feed
map(my putStrLn, xs) as string
end positionalArgs
-- namedArgs :: Record -> String
on namedArgs(rec)
script showKVpair
on |λ|(k)
my putStrLn(k & " -> " & key... |
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... | #C.2B.2B | C++ | #include <iostream>
#include <cmath>
#include <cassert>
using namespace std;
#define PI 3.14159265359
class Vector
{
public:
Vector(double ix, double iy, char mode)
{
if(mode=='a')
{
x=ix*cos(iy);
y=ix*sin(iy);
}
else
{
x=ix;
... |
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.
| #Go | Go | package main
import (
"fmt"
"unsafe"
)
func main() {
i := 5 // default type is int
r := '5' // default type is rune (which is int32)
f := 5. // default type is float64
c := 5i // default type is complex128
fmt.Println("i:", unsafe.Sizeof(i), "bytes")
fmt.Println("r:", unsafe.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.
| #Haskell | Haskell |
import Data.Int
import Foreign.Storable
task name value = putStrLn $ name ++ ": " ++ show (sizeOf value) ++ " byte(s)"
main = do
let i8 = 0::Int8
let i16 = 0::Int16
let i32 = 0::Int32
let i64 = 0::Int64
let int = 0::Int
task "Int8" i8
task "Int16" i16
task "Int32" i32
task "Int64" i64
task "I... |
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.
| #Ruby | Ruby | # frozen_string_literal: true
require_relative 'raster_graphics'
class ColourPixel < Pixel
def initialize(x, y, colour)
@colour = colour
super x, y
end
attr_accessor :colour
def distance_to(px, py)
Math.hypot(px - x, py - y)
end
end
width = 300
height = 200
npoints = 20
pixmap = Pixmap.new... |
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 distribut... | #PARI.2FGP | PARI/GP | cumChi2(chi2,dof)={
my(g=gamma(dof/2));
incgam(dof/2,chi2/2,g)/g
};
test(v,alpha=.05)={
my(chi2,p,s=sum(i=1,#v,v[i]),ave=s/#v);
print("chi^2 statistic: ",chi2=sum(i=1,#v,(v[i]-ave)^2)/ave);
print("p-value: ",p=cumChi2(chi2,#v-1));
if(p<alpha,
print("Significant at the alpha = "alpha" level: not uniform");
,
... |
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 ... | #Haskell | Haskell | import Data.Char
import Text.Printf
-- Perform encryption or decryption, depending on f.
crypt f key = map toLetter . zipWith f (cycle key)
where toLetter = chr . (+) (ord 'A')
-- Encrypt or decrypt one letter.
enc k c = (ord k + ord c) `mod` 26
dec k c = (ord c - ord k) `mod` 26
-- Given a key, encrypt or decr... |
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 ... | #Maple | Maple | T := GraphTheory:-Graph([1, 2, 3, 4, 5], {{1, 2}, {2, 3}, {2, 4}, {4, 5}}):
GraphTheory:-DrawGraph(T, style = 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.
... | #Scala | Scala | import java.io.File
val dir = new File("/foo/bar").list()
dir.filter(file => file.endsWith(".mp3")).foreach(println) |
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.
... | #Seed7 | Seed7 | $ include "seed7_05.s7i";
include "osfiles.s7i";
const proc: main is func
local
var string: fileName is "";
begin
for fileName range readDir(".") do
if endsWith(fileName, ".sd7") then
writeln(fileName);
end if;
end for;
end func; |
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 ... | #MAXScript | MAXScript | fn walkDir dir pattern =
(
dirArr = GetDirectories (dir + "\\*")
for d in dirArr do
(
join dirArr (getDirectories (d + "\\*"))
)
append dirArr (dir + "\\") -- Need to include the original top level directory
for f in dirArr do
(
print (getFiles (f + pattern))
)
)
... |
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 ... | #MoonScript | MoonScript | lfs = require "lfs"
-- This function takes two arguments:
-- - the directory to walk recursively;
-- - an optional function that takes a file name as argument, and returns a boolean.
find = (fn) => coroutine.wrap ->
for f in lfs.dir @
if f ~= "." and f ~= ".."
_f = @.."/"..f
coroutine.yield _f if no... |
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 ██ ... | #Nim | Nim | import math, sequtils, sugar
proc water(barChart: seq[int], isLeftPeak = false, isRightPeak = false): int =
if len(barChart) <= 2:
return
if isLeftPeak and isRightPeak:
return sum(barChart[1..^2].map(x=>min(barChart[0], barChart[^1])-x))
var i: int
if isLeftPeak:
i = maxIndex(barChart[1..^1])+1
... |
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.
| #Wren | Wren | /* video_display_modes.wren */
class C {
foreign static xrandr(args)
foreign static usleep(usec)
}
// query supported display modes
C.xrandr("-q")
C.usleep(3000)
// change display mode to 1368x768
System.print("\nChanging to 1368 x 768 mode.")
C.xrandr("-s 1368x768")
C.usleep(3000)
// change it ba... |
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.
| #XPL0 | XPL0 | code SetVid=45;
SetVid(Mode) |
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 ... | #Phix | Phix | with javascript_semantics
function check(integer fid, range, iterations, atom delta)
--
-- fid: routine_id of function that yields integer 1..range
-- range: the maximum value that is returned from fid
-- iterations: number of iterations to test
-- delta: variance, for example 0.005 means 0.5%
--
-- returns -1/0/1 for ... |
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 (209... | #Erlang | Erlang | 7> binary:encode_unsigned(2097152).
<<32,0,0>>
8> binary:decode_unsigned(<<32,0,0>>).
2097152
13> binary:encode_unsigned(16#1fffff).
<<31,255,255>>
14> binary:decode_unsigned(<<31,255,255>>).
2097151
|
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 (209... | #Euphoria | Euphoria | function vlq_encode(integer n)
sequence s
s = {}
while n > 0 do
s = prepend(s, #80 * (length(s) > 0) + and_bits(n, #7F))
n = floor(n / #80)
end while
if length(s) = 0 then
s = {0}
end if
return s
end function
function vlq_decode(sequence s)
integer n
n = 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... | #Applesoft_BASIC | Applesoft BASIC | 10 P$(0) = STR$(5)
20 P$(1) = "MARY"
30 P$(2) = "HAD"
40 P$(3) = "A"
50 P$(4) = "LITTLE"
60 P$(5) = "LAMB"
70 GOSUB 90"VARIADIC FUNCTION
80 END
90 FOR I = 1 TO VAL(P$(0)) : ? P$(I) : P$(I) = "" : NEXT I : P$(0) = "" : RETURN |
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... | #Arturo | Arturo | ;-------------------------------------------
; a quasi-variadic function
;-------------------------------------------
variadic: function [args][
loop args 'arg [
print arg
]
]
; calling function with one block param
; and the arguments inside
variadic ["one" 2 "three"]
;---------------------------... |
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... | #CLU | CLU | % Parameterized vector class
vector = cluster [T: type] is make, add, sub, mul, div,
get_x, get_y, to_string
% The inner type must support basic math
where T has add: proctype (T,T) returns (T)
signals (overflow, underflow),
... |
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... | #D | D | import std.stdio;
void main() {
writeln(VectorReal(5, 7) + VectorReal(2, 3));
writeln(VectorReal(5, 7) - VectorReal(2, 3));
writeln(VectorReal(5, 7) * 11);
writeln(VectorReal(5, 7) / 2);
}
alias VectorReal = Vector!real;
struct Vector(T) {
private T x, y;
this(T x, T y) {
this.x = ... |
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.
| #Icon_and_Unicon | Icon and Unicon | L := list(10) # 10 element list |
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.
| #J | J | v=: '' |
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.
| #Julia | Julia | types = [Bool, Char, Int8, UInt8, Int16, UInt16, Int32, UInt32, Int64, UInt64]
for t in types
println("For type ", lpad(t,6), " size is $(sizeof(t)) 8-bit bytes, or ",
lpad(string(8*sizeof(t)), 2), " bits.")
end
primitive type MyInt24 24 end
println("\nFor the 24-bit user defined type MyInt24, size is... |
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.
| #Kotlin | Kotlin | // version 1.0.6
fun main(args: Array<String>) {
/* ranges for variables of the primitive numeric types */
println("A Byte variable has a range of : ${Byte.MIN_VALUE} to ${Byte.MAX_VALUE}")
println("A Short variable has a range of : ${Short.MIN_VALUE} to ${Short.MAX_VALUE}")
println("An Int vari... |
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.
| #Run_BASIC | Run BASIC | graphic #g, 400,400
#g flush()
spots = 100
leftSide = 400
rightSide = 400
dim locX(spots)
dim locY(spots)
dim rgb(spots,3)
dim seal(leftSide, rightSide)
dim reach(leftSide, rightSide)
for i =1 to spots
locX(i) = int(leftSide * rnd(1))
locY(i) = int(rightSide * rnd(1))
rgb(i,1) = int(256 * rnd(1))
... |
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.
| #Rust | Rust | extern crate piston;
extern crate opengl_graphics;
extern crate graphics;
extern crate touch_visualizer;
#[cfg(feature = "include_sdl2")]
extern crate sdl2_window;
extern crate getopts;
extern crate voronoi;
extern crate rand;
use touch_visualizer::TouchVisualizer;
use opengl_graphics::{ GlGraphics, OpenGL };
use... |
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 distribut... | #Perl | Perl | use List::Util qw(sum reduce);
use constant pi => 3.14159265;
sub incomplete_G_series {
my($s, $z) = @_;
my $n = 10;
push @numers, $z**$_ for 1..$n;
my @denoms = $s+1;
push @denoms, $denoms[-1]*($s+$_) for 2..$n;
my $M = 1;
$M += $numers[$_-1]/$denoms[$_-1] for 1..$n;
$z**$s / $s * exp... |
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 ... | #Icon_and_Unicon | Icon and Unicon | procedure main()
ptext := "Beware the Jabberwock, my son! The jaws that bite, the claws that catch!"
write("Key = ",ekey := "VIGENERECIPHER")
write("Plain Text = ",ptext)
write("Normalized = ",GFormat(ptext := NormalizeText(ptext)))
write("Enciphered = ",GFormat(ctext := Vignere("e",ekey,ptext)))
... |
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 ... | #Mathematica.2FWolfram_Language | Mathematica/Wolfram Language | edges = {1 \[DirectedEdge] 2, 1 \[DirectedEdge] 3, 2 \[DirectedEdge] 4, 2 \[DirectedEdge] 5,
3 \[DirectedEdge] 6, 4 \[DirectedEdge] 7};
t = TreeGraph[edges, GraphStyle -> "VintageDiagram"] |
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.
... | #Sidef | Sidef | '*.p[lm]'.glob.each { |file| say file } # Perl files under this directory |
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.
... | #Smalltalk | Smalltalk | (Directory name: 'a_directory')
allFilesMatching: '*.st' do: [ :f | (f name) displayNl ] |
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 ... | #Nanoquery | Nanoquery | import Nanoquery.IO
def get_files(dirname)
local_filenames = new(File).listDir(dirname)
filenames = {}
for i in range(0, len(local_filenames) - 1)
if len(local_filenames) > 0
if not new(File, local_filenames[i]).isDir()
filenames.append(local_filenames[i])
else
filenames += get_files(local_file... |
Subsets and Splits
Rosetta Code COBOL Python Hard Tasks
Identifies and retrieves challenging tasks that exist in both COBOL and Python, revealing cross-language programming patterns and difficulty levels for comparative analysis.
Rosetta Code Task Comparisons
Identifies tasks common to both COBOL and Python languages that are described as having difficulty levels, revealing cross-language task similarities and providing useful comparative programming examples.
Select Specific Languages Codes
Retrieves specific programming language names and codes from training data, providing basic filtering but limited analytical value beyond identifying these particular languages.