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 | response_seed stringclasses 1
value | instruction_seed stringlengths 27 14.4k | _source stringclasses 1
value |
|---|---|---|---|---|---|---|---|---|
http://rosettacode.org/wiki/Return_multiple_values | Return multiple values | Task
Show how to return more than one value from a function.
| #Java | Java | import java.util.List;
import java.util.ArrayList;
import java.util.Map;
import java.util.HashMap;
// =============================================================================
public class RReturnMultipleVals {
public static final String K_lipsum = "Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed ... | Give a code snippet in #Java
Task
Show how to return more than one value from a function.
| christopher/rosetta-code | |
http://rosettacode.org/wiki/Power_set | Power set | A set is a collection (container) of certain values,
without any particular order, and no repeated values.
It corresponds with a finite set in mathematics.
A set can be implemented as an associative array (partial mapping)
in which the value of each key-value pair is ignored.
Given a set S, the power set (or pow... | #VBA | VBA | Option Base 1
Private Function power_set(ByRef st As Collection) As Collection
Dim subset As Collection, pwset As New Collection
For i = 0 To 2 ^ st.Count - 1
Set subset = New Collection
For j = 1 To st.Count
If i And 2 ^ (j - 1) Then subset.Add st(j)
Next j
pwset.Add... | Give a code snippet in #VBA
A set is a collection (container) of certain values,
without any particular order, and no repeated values.
It corresponds with a finite set in mathematics.
A set can be implemented as an associative array (partial mapping)
in which the value of each key-value pair is ignored.
Given a... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Hello_world/Line_printer | Hello world/Line printer | Task
Cause a line printer attached to the computer to print a line containing the message: Hello World!
Note
A line printer is not the same as standard output.
A line printer was an older-style printer which prints one line at a time to a continuous ream of paper.
With some systems, a line printer can be... | #Tcl | Tcl | exec lp << "Hello World!" | Give a code snippet in #Tcl
Task
Cause a line printer attached to the computer to print a line containing the message: Hello World!
Note
A line printer is not the same as standard output.
A line printer was an older-style printer which prints one line at a time to a continuous ream of paper.
With some s... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Universal_Turing_machine | Universal Turing machine | One of the foundational mathematical constructs behind computer science
is the universal Turing Machine.
(Alan Turing introduced the idea of such a machine in 1936–1937.)
Indeed one way to definitively prove that a language
is turing-complete
is to implement a universal Turing machine in it.
Task
Simulate such ... | #MATLAB | MATLAB | function tape=turing(rules,tape,initial,terminal)
%"rules" is cell array of cell arrays of the following form:
%First element is number representing initial state
%Second element is number representing input from the tape
%Third element is number representing output printed onto the tape
%Fourth ele... | Give a code snippet in #MATLAB
One of the foundational mathematical constructs behind computer science
is the universal Turing Machine.
(Alan Turing introduced the idea of such a machine in 1936–1937.)
Indeed one way to definitively prove that a language
is turing-complete
is to implement a universal Turing machin... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Gray_code | Gray code | Gray code
Karnaugh maps
Create functions to encode a number to and decode a number from Gray code.
Display the normal binary representations, Gray code representations, and decoded Gray code values for all 5-bit binary numbers (0-31 inclusive, leading 0's not necessary).
There are many possible Gray codes. The follow... | #Scala | Scala | def encode(n: Int) = (n ^ (n >>> 1)).toBinaryString
def decode(s: String) = Integer.parseInt( s.scanLeft(0)(_ ^ _.asDigit).tail.mkString , 2)
println("decimal binary gray decoded")
for (i <- 0 to 31; g = encode(i))
println("%7d %6s %5s %7s".format(i, i.toBinaryString, g, decode(g)))
| Give a code snippet in #Scala
Gray code
Karnaugh maps
Create functions to encode a number to and decode a number from Gray code.
Display the normal binary representations, Gray code representations, and decoded Gray code values for all 5-bit binary numbers (0-31 inclusive, leading 0's not necessary).
There are many ... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Almost_prime | Almost prime | A k-Almost-prime is a natural number
n
{\displaystyle n}
that is the product of
k
{\displaystyle k}
(possibly identical) primes.
Example
1-almost-primes, where
k
=
1
{\displaystyle k=1}
, are the prime numbers themselves.
2-almost-primes, where
k
=
2
{\displaystyl... | #Nim | Nim | proc prime(k: int, listLen: int): seq[int] =
result = @[]
var
test: int = 2
curseur: int = 0
while curseur < listLen:
var
i: int = 2
compte = 0
n = test
while i <= n:
if (n mod i)==0:
n = n div i
compte += 1
else:
i += 1
if compte == k:
result.add(test)
curseur += 1
test ... | Give a code snippet in #Nim
A k-Almost-prime is a natural number
n
{\displaystyle n}
that is the product of
k
{\displaystyle k}
(possibly identical) primes.
Example
1-almost-primes, where
k
=
1
{\displaystyle k=1}
, are the prime numbers themselves.
2-almost-primes, wher... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Catalan_numbers/Pascal%27s_triangle | Catalan numbers/Pascal's triangle | Task
Print out the first 15 Catalan numbers by extracting them from Pascal's triangle.
See
Catalan Numbers and the Pascal Triangle. This method enables calculation of Catalan Numbers using only addition and subtraction.
Catalan's Triangle for a Number Triangle that generates Catalan Numbers using onl... | #Mathematica_.2F_Wolfram_Language | Mathematica / Wolfram Language | nextrow[lastrow_] := Module[{output},
output = ConstantArray[1, Length[lastrow] + 1];
Do[
output[[i + 1]] = lastrow[[i]] + lastrow[[i + 1]];
, {i, 1, Length[lastrow] - 1}];
output
]
pascaltriangle[size_] := NestList[nextrow, {1}, size]
catalannumbers[length_] := Module[{output, basetriangle},
basetria... | Give a code snippet in #Mathematica_.2F_Wolfram_Language
Task
Print out the first 15 Catalan numbers by extracting them from Pascal's triangle.
See
Catalan Numbers and the Pascal Triangle. This method enables calculation of Catalan Numbers using only addition and subtraction.
Catalan's Triangle for ... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Gauss-Jordan_matrix_inversion | Gauss-Jordan matrix inversion | Task
Invert matrix A using Gauss-Jordan method.
A being an n × n matrix.
| #MATLAB | MATLAB | function GaussInverse(M)
original = M;
[n,~] = size(M);
I = eye(n);
for j = 1:n
for i = j:n
if ~(M(i,j) == 0)
for k = 1:n
q = M(j,k); M(j,k) = M(i,k); M(i,k) = q;
q = I(j,k); I(j,k) = I(i,k); I(i,k) = q;
end
... | Give a code snippet in #MATLAB
Task
Invert matrix A using Gauss-Jordan method.
A being an n × n matrix.
| christopher/rosetta-code | |
http://rosettacode.org/wiki/Top_rank_per_group | Top rank per group | Task
Find the top N salaries in each department, where N is provided as a parameter.
Use this data as a formatted internal data structure (adapt it to your language-native idioms, rather than parse at runtime), or identify your external data source:
Employee Name,Employee ID,Salary,Department
Tyler Bennett... | #Pascal | Pascal | program TopRankPerGroup(output);
uses
Classes, Math;
type
TData = record
name: string;
ID: string;
salary: longint;
dept: string
end;
PTData = ^TData;
const
data: array [1..13] of TData =
( (name: 'Tyler Bennett'; ID: 'E10297'; salary: 32000; dept: '... | Give a code snippet in #Pascal
Task
Find the top N salaries in each department, where N is provided as a parameter.
Use this data as a formatted internal data structure (adapt it to your language-native idioms, rather than parse at runtime), or identify your external data source:
Employee Name,Employee ID... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Smarandache_prime-digital_sequence | Smarandache prime-digital sequence | The Smarandache prime-digital sequence (SPDS for brevity) is the sequence of primes whose digits are themselves prime.
For example 257 is an element of this sequence because it is prime itself and its digits: 2, 5 and 7 are also prime.
Task
Show the first 25 SPDS primes.
Show the hundredth SPDS prime.
See also
... | #XPL0 | XPL0 | func IsPrime(N); \Return 'true' if N is prime
int N, I;
[if N <= 2 then return N = 2;
if (N&1) = 0 then \even >2\ return false;
for I:= 3 to sqrt(N) do
[if rem(N/I) = 0 then return false;
I:= I+1;
];
return true;
];
func PrimeDigits(N); \Return 'true' if all digits are prime
int N;
[repeat N:=... | Give a code snippet in #XPL0
The Smarandache prime-digital sequence (SPDS for brevity) is the sequence of primes whose digits are themselves prime.
For example 257 is an element of this sequence because it is prime itself and its digits: 2, 5 and 7 are also prime.
Task
Show the first 25 SPDS primes.
Show the hundr... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Find_the_last_Sunday_of_each_month | Find the last Sunday of each month | Write a program or a script that returns the last Sundays of each month of a given year. The year may be given through any simple input method in your language (command line, std in, etc).
Example of an expected output:
./last_sundays 2013
2013-01-27
2013-02-24
2013-03-31
2013-04-28
2013-05-26
2013-06-30
2013-07-28
2... | #Seed7 | Seed7 | $ include "seed7_05.s7i";
include "time.s7i";
include "duration.s7i";
const proc: main is func
local
var integer: weekday is 1; # 1 for monday, 2 for tuesday, and so on up to 7 for sunday.
var integer: year is 0;
var integer: month is 1;
var time: aDate is time.value;
var time: selected is t... | Give a code snippet in #Seed7
Write a program or a script that returns the last Sundays of each month of a given year. The year may be given through any simple input method in your language (command line, std in, etc).
Example of an expected output:
./last_sundays 2013
2013-01-27
2013-02-24
2013-03-31
2013-04-28
201... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Mertens_function | Mertens function | The Mertens function M(x) is the count of square-free integers up to x that have an even number of prime factors, minus the count of those that have an odd number.
It is an extension of the Möbius function. Given the Möbius function μ(n), the Mertens function M(x) is the sum of the Möbius numbers from n == 1 through n... | #jq | jq |
def sum(s): reduce s as $x (null; . + $x);
def nwise($n):
def n: if length <= $n then . else .[0:$n] , (.[$n:] | n) end;
n;
def lpad($len): tostring | ($len - length) as $l | (" " * $l)[:$l] + .;
# input: an array
# output: number of crossings at $value
def count_crossings($value):
. as $a
| reduce rang... | Give a code snippet in #jq
The Mertens function M(x) is the count of square-free integers up to x that have an even number of prime factors, minus the count of those that have an odd number.
It is an extension of the Möbius function. Given the Möbius function μ(n), the Mertens function M(x) is the sum of the Möbius n... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Terminal_control/Preserve_screen | Terminal control/Preserve screen |
Task
Clear the screen, output something on the display, and then restore the screen to the preserved state that it was in before the task was carried out.
There is no requirement to change the font or kerning in this task, however character decorations and attributes are expected to be preserved. If the implement... | #Raku | Raku | print "\e[?1049h\e[H";
say "Alternate buffer!";
for 5,4...1 {
print "\rGoing back in: $_";
sleep 1;
}
print "\e[?1049l"; | Give a code snippet in #Raku
Task
Clear the screen, output something on the display, and then restore the screen to the preserved state that it was in before the task was carried out.
There is no requirement to change the font or kerning in this task, however character decorations and attributes are expected to be... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Floyd-Warshall_algorithm | Floyd-Warshall algorithm | The Floyd–Warshall algorithm is an algorithm for finding shortest paths in a weighted graph with positive or negative edge weights.
Task
Find the lengths of the shortest paths between all pairs of vertices of the given directed graph. Your code may assume that the input has already been checked for loops, parallel ... | #Sidef | Sidef | func floyd_warshall(n, edge) {
var dist = n.of {|i| n.of { |j| i == j ? 0 : Inf }}
var nxt = n.of { n.of(nil) }
for u,v,w in edge {
dist[u-1][v-1] = w
nxt[u-1][v-1] = v-1
}
[^n] * 3 -> cartesian { |k, i, j|
if (dist[i][j] > dist[i][k]+dist[k][j]) {
dist[i][j] ... | Give a code snippet in #Sidef
The Floyd–Warshall algorithm is an algorithm for finding shortest paths in a weighted graph with positive or negative edge weights.
Task
Find the lengths of the shortest paths between all pairs of vertices of the given directed graph. Your code may assume that the input has already be... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Babbage_problem | Babbage problem |
Charles Babbage, looking ahead to the sorts of problems his Analytical Engine would be able to solve, gave this example:
What is the smallest positive integer whose square ends in the digits 269,696?
— Babbage, letter to Lord Bowden, 1837; see Hollingdale and Tootill, Electronic Computers, second edition, 1970, p.... | #Batch_File | Batch File |
:: This line is only required to increase the readability of the output by hiding the lines of code being executed
@echo off
:: Everything between the lines keeps repeating until the answer is found
:: The code works by, starting at 1, checking to see if the last 6 digits of the current number squared is equal to 269... | Give a code snippet in #Batch_File
Charles Babbage, looking ahead to the sorts of problems his Analytical Engine would be able to solve, gave this example:
What is the smallest positive integer whose square ends in the digits 269,696?
— Babbage, letter to Lord Bowden, 1837; see Hollingdale and Tootill, Electronic... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Non-decimal_radices/Input | Non-decimal radices/Input | It is common to have a string containing a number written in some format, with the most common ones being decimal, hexadecimal, octal and binary. Such strings are found in many places (user interfaces, configuration files, XML data, network protocols, etc.)
This task requires parsing of such a string (which may be ass... | #Haskell | Haskell | Prelude> read "123459" :: Integer
123459
Prelude> read "0xabcf123" :: Integer
180154659
Prelude> read "0o7651" :: Integer
4009 | Give a code snippet in #Haskell
It is common to have a string containing a number written in some format, with the most common ones being decimal, hexadecimal, octal and binary. Such strings are found in many places (user interfaces, configuration files, XML data, network protocols, etc.)
This task requires parsing o... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Sorting_algorithms/Comb_sort | Sorting algorithms/Comb sort | Sorting algorithms/Comb sort
You are encouraged to solve this task according to the task description, using any language you may know.
Sorting Algorithm
This is a sorting algorithm. It may be applied to a set of data in order to sort it.
For comparing various sorts, see compare sorts.
For other sorting algor... | #Arturo | Arturo | combSort: function [items][
a: new items
gap: size a
swapped: true
while [or? gap > 1 swapped][
gap: (gap * 10) / 13
if or? gap=9 gap=10 -> gap: 11
if gap<1 -> gap: 1
swapped: false
i: 0
loop gap..dec size items 'j [
if a\[i] > a\[j] [
... | Give a code snippet in #Arturo
Sorting algorithms/Comb sort
You are encouraged to solve this task according to the task description, using any language you may know.
Sorting Algorithm
This is a sorting algorithm. It may be applied to a set of data in order to sort it.
For comparing various sorts, see compare ... | christopher/rosetta-code | |
http://rosettacode.org/wiki/DNS_query | DNS query | DNS is an internet service that maps domain names, like rosettacode.org, to IP addresses, like 66.220.0.231.
Use DNS to resolve www.kame.net to both IPv4 and IPv6 addresses. Print these addresses.
| #Cach.C3.A9_ObjectScript | Caché ObjectScript |
Class Utils.Net Extends %RegisteredObject
{
ClassMethod QueryDNS(pHost As %String, Output ip As %List) As %Status
{
// some initialisation
K ip S ip=""
// check host operating system and input parameters
S OS=$SYSTEM.Version.GetOS()
I '$LF($LB("Windows","UNIX"), OS) Q $$$ERROR($$$GeneralError, "Not implement... | Give a code snippet in #Cach.C3.A9_ObjectScript
DNS is an internet service that maps domain names, like rosettacode.org, to IP addresses, like 66.220.0.231.
Use DNS to resolve www.kame.net to both IPv4 and IPv6 addresses. Print these addresses.
| christopher/rosetta-code | |
http://rosettacode.org/wiki/Polymorphic_copy | Polymorphic copy | An object is polymorphic when its specific type may vary.
The types a specific value may take, is called class.
It is trivial to copy an object if its type is known:
int x;
int y = x;
Here x is not polymorphic, so y is declared of same type (int) as x.
But if the specific type of x were unknown, then y could not be d... | #C | C | #include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct object *BaseObj;
typedef struct sclass *Class;
typedef void (*CloneFctn)(BaseObj s, BaseObj clo);
typedef const char * (*SpeakFctn)(BaseObj s);
typedef void (*DestroyFctn)(BaseObj s);
typedef struct sclass {
size_t csize; /* size of the ... | Give a code snippet in #C
An object is polymorphic when its specific type may vary.
The types a specific value may take, is called class.
It is trivial to copy an object if its type is known:
int x;
int y = x;
Here x is not polymorphic, so y is declared of same type (int) as x.
But if the specific type of x were unk... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Stem-and-leaf_plot | Stem-and-leaf plot | Create a well-formatted stem-and-leaf plot from the following data set, where the leaves are the last digits:
12 127 28 42 39 113 42 18 44 118 44 37 113 124 37 48 127 36 29 31 125 139 131 115 105 132 104 123 35 113 122 42 117 119 58 109 23 105 63 27 44 105 99 41 128 121 116 125 32 61 37 127 29 113 121 58 114 126 53 11... | #PowerShell | PowerShell |
$Set = -split '12 127 28 42 39 113 42 18 44 118 44 37 113 124 37 48 127 36 29 31 125 139 131 115 105 132 104 123 35 113 122 42 117 119 58 109 23 105 63 27 44 105 99 41 128 121 116 125 32 61 37 127 29 113 121 58 114 126 53 114 96 25 109 7 31 141 46 13 27 43 117 116 27 7 68 40 31 115 124 42 128 52 71 118 117 38 27 106 ... | Give a code snippet in #PowerShell
Create a well-formatted stem-and-leaf plot from the following data set, where the leaves are the last digits:
12 127 28 42 39 113 42 18 44 118 44 37 113 124 37 48 127 36 29 31 125 139 131 115 105 132 104 123 35 113 122 42 117 119 58 109 23 105 63 27 44 105 99 41 128 121 116 125 32 6... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Anonymous_recursion | Anonymous recursion | While implementing a recursive function, it often happens that we must resort to a separate helper function to handle the actual recursion.
This is usually the case when directly calling the current function would waste too many resources (stack space, execution time), causing unwanted side-effects, and/or the f... | #C.23 | C# |
static int Fib(int n)
{
if (n < 0) throw new ArgumentException("Must be non negativ", "n");
Func<int, int> fib = null; // Must be known, before we can assign recursively to it.
fib = p => p > 1 ? fib(p - 2) + fib(p - 1) : p;
return fib(n);
}
| Give a code snippet in #C.23
While implementing a recursive function, it often happens that we must resort to a separate helper function to handle the actual recursion.
This is usually the case when directly calling the current function would waste too many resources (stack space, execution time), causing unwante... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Angles_(geometric),_normalization_and_conversion | Angles (geometric), normalization and conversion | This task is about the normalization and/or conversion of (geometric) angles using
some common scales.
The angular scales that will be used in this task are:
degree
gradian
mil
radian
Definitions
The angular scales used or referenced here:
turn is a full turn or 360 degrees, also shown as 360º
... | #Haskell | Haskell | {-# LANGUAGE RankNTypes #-}
{-# LANGUAGE TypeApplications #-}
{-# LANGUAGE GeneralizedNewtypeDeriving #-}
import Text.Printf
class (Num a, Fractional a, RealFrac a) => Angle a where
fullTurn :: a -- value of the whole turn
mkAngle :: Double -> a
value :: a -> Double
fromTurn :: Double -> a
toTurn :: a -> ... | Give a code snippet in #Haskell
This task is about the normalization and/or conversion of (geometric) angles using
some common scales.
The angular scales that will be used in this task are:
degree
gradian
mil
radian
Definitions
The angular scales used or referenced here:
turn is a full turn or... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Generate_Chess960_starting_position | Generate Chess960 starting position | Chess960 is a variant of chess created by world champion Bobby Fischer. Unlike other variants of the game, Chess960 does not require a different material, but instead relies on a random initial position, with a few constraints:
as in the standard chess game, all eight white pawns must be placed on the second rank.
W... | #Factor | Factor | USING: io kernel math random sequences ;
IN: rosetta-code.chess960
: empty ( seq -- n ) 32 swap indices random ; ! return a random empty index (i.e. equal to 32) of seq
: next ( seq -- n ) 32 swap index ; ! return the leftmost empty index of seq
: place ( seq elt n -- seq' ) rot [ set-nt... | Give a code snippet in #Factor
Chess960 is a variant of chess created by world champion Bobby Fischer. Unlike other variants of the game, Chess960 does not require a different material, but instead relies on a random initial position, with a few constraints:
as in the standard chess game, all eight white pawns must ... | christopher/rosetta-code | |
http://rosettacode.org/wiki/String_concatenation | String concatenation | String concatenation
You are encouraged to solve this task according to the task description, using any language you may know.
Task
Create a string variable equal to any text value.
Create another string variable whose value is the original variable concatenated with another string literal.
To illustrate the operat... | #Ada | Ada | with Ada.Text_IO; use Ada.Text_IO;
procedure String_Concatenation is
S1 : constant String := "Hello";
S2 : constant String := S1 & " literal";
begin
Put_Line (S1);
Put_Line (S2);
end String_Concatenation; | Give a code snippet in #Ada
String concatenation
You are encouraged to solve this task according to the task description, using any language you may know.
Task
Create a string variable equal to any text value.
Create another string variable whose value is the original variable concatenated with another string liter... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Find_limit_of_recursion | Find limit of recursion | Find limit of recursion is part of Short Circuit's Console Program Basics selection.
Task
Find the limit of recursion.
| #Ursa | Ursa | def recurse (int counter)
try
recurse (+ counter 1)
catch recursionerror
out "the limit of recursion was " counter endl console
end try
end
recurse 1 | Give a code snippet in #Ursa
Find limit of recursion is part of Short Circuit's Console Program Basics selection.
Task
Find the limit of recursion.
| christopher/rosetta-code | |
http://rosettacode.org/wiki/First-class_functions/Use_numbers_analogously | First-class functions/Use numbers analogously | In First-class functions, a language is showing how its manipulation of functions is similar to its manipulation of other types.
This tasks aim is to compare and contrast a language's implementation of first class functions, with its normal handling of numbers.
Write a program to create an ordered collection of a m... | #OCaml | OCaml | # let x = 2.0;;
# let y = 4.0;;
# let z = x +. y;;
# let coll = [ x; y; z];;
# let inv_coll = List.map (fun x -> 1.0 /. x) coll;;
# let multiplier n1 n2 = (fun t -> n1 *. n2 *. t);;
(* create a list of new functions *)
# let func_list = List.map2 (fun n inv -> (multiplier n inv)) coll inv_coll;;
# List.ma... | Give a code snippet in #OCaml
In First-class functions, a language is showing how its manipulation of functions is similar to its manipulation of other types.
This tasks aim is to compare and contrast a language's implementation of first class functions, with its normal handling of numbers.
Write a program to crea... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Word_wrap | Word wrap | Even today, with proportional fonts and complex layouts, there are still cases where you need to wrap text at a specified column.
Basic task
The basic task is to wrap a paragraph of text in a simple way in your language.
If there is a way to do this that is built-in, trivial, or provided in a standard library, sho... | #Batch_File | Batch File | @echo off
set "input=Lorem ipsum dolor sit amet, consectetur adipiscing elit. Donec a diam lectus. Sed sit amet ipsum mauris. Maecenas congue ligula ac quam viverra nec consectetur ante hendrerit. Donec et mollis dolor. Praesent et diam eget libero egestas mattis sit amet vitae augue. Nam tincidunt congue enim, ut po... | Give a code snippet in #Batch_File
Even today, with proportional fonts and complex layouts, there are still cases where you need to wrap text at a specified column.
Basic task
The basic task is to wrap a paragraph of text in a simple way in your language.
If there is a way to do this that is built-in, trivial, or... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Generate_random_chess_position | Generate random chess position | Task
Generate a random chess position in FEN format.
The position does not have to be realistic or even balanced, but it must comply to the following rules:
there is one and only one king of each color (one black king and one white king);
the kings must not be placed on adjacent squares;
there can not be any p... | #Haskell | Haskell | {-# LANGUAGE LambdaCase, TupleSections #-}
module RandomChess
( placeKings
, placePawns
, placeRemaining
, emptyBoard
, toFen
, ChessBoard
, Square (..)
, BoardState (..)
, getBoard
)
where
import Control.Monad.State (State, get, gets, put)
import Data.List (find, sortBy)
import System.Random (Random, RandomGen, St... | Give a code snippet in #Haskell
Task
Generate a random chess position in FEN format.
The position does not have to be realistic or even balanced, but it must comply to the following rules:
there is one and only one king of each color (one black king and one white king);
the kings must not be placed on adjacent... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Loops/For | Loops/For | “For” loops are used to make some block of code be iterated a number of times, setting a variable or parameter to a monotonically increasing integer value for each execution of the block of code.
Common extensions of this allow other counting patterns or iterating over abstract structures other than the integers.
... | #Groovy | Groovy | for(i in (1..6)) {
for(j in (1..i)) {
print '*'
}
println ()
} | Give a code snippet in #Groovy
“For” loops are used to make some block of code be iterated a number of times, setting a variable or parameter to a monotonically increasing integer value for each execution of the block of code.
Common extensions of this allow other counting patterns or iterating over abstract struct... | christopher/rosetta-code | |
http://rosettacode.org/wiki/String_case | String case | Task
Take the string alphaBETA and demonstrate how to convert it to:
upper-case and
lower-case
Use the default encoding of a string literal or plain ASCII if there is no string literal in your language.
Note: In some languages alphabets toLower and toUpper is not reversable.
Show any additional... | #Dyalect | Dyalect | let str = "alphaBETA"
print("Lower case: ", str.Lower(), separator: "")
print("Upper case: ", str.Upper(), separator: "")
print("Capitalize: ", str.Capitalize(), separator: "") | Give a code snippet in #Dyalect
Task
Take the string alphaBETA and demonstrate how to convert it to:
upper-case and
lower-case
Use the default encoding of a string literal or plain ASCII if there is no string literal in your language.
Note: In some languages alphabets toLower and toUpper is not... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Set_of_real_numbers | Set of real numbers | All real numbers form the uncountable set ℝ. Among its subsets, relatively simple are the convex sets, each expressed as a range between two real numbers a and b where a ≤ b. There are actually four cases for the meaning of "between", depending on open or closed boundary:
[a, b]: {x | a ≤ x and x ≤ b }
(a, b): {x | ... | #PARI.2FGP | PARI/GP | set11(x,a,b)=select(x -> a <= x && x <= b, x);
set01(x,a,b)=select(x -> a < x && x <= b, x);
set10(x,a,b)=select(x -> a <= x && x < b, x);
set00(x,a,b)=select(x -> a < x && x < b, x);
V = [0, 1, 2];
setunion(set01(V, 0, 1), set10(V, 0, 2))
setintersect(set10(V, 0, 2), set01(V, 1, 2))
setminus(set10(V, 0... | Give a code snippet in #PARI.2FGP
All real numbers form the uncountable set ℝ. Among its subsets, relatively simple are the convex sets, each expressed as a range between two real numbers a and b where a ≤ b. There are actually four cases for the meaning of "between", depending on open or closed boundary:
[a, b]: {x... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Fibonacci_sequence | Fibonacci sequence | The Fibonacci sequence is a sequence Fn of natural numbers defined recursively:
F0 = 0
F1 = 1
Fn = Fn-1 + Fn-2, if n>1
Task
Write a function to generate the nth Fibonacci number.
Solutions can be iterative or recursive (though recursive solutions are generally considered too slow ... | #Befunge | Befunge | 00:.1:.>:"@"8**++\1+:67+`#@_v
^ .:\/*8"@"\%*8"@":\ < | Give a code snippet in #Befunge
The Fibonacci sequence is a sequence Fn of natural numbers defined recursively:
F0 = 0
F1 = 1
Fn = Fn-1 + Fn-2, if n>1
Task
Write a function to generate the nth Fibonacci number.
Solutions can be iterative or recursive (though recursive solutions a... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Van_Eck_sequence | Van Eck sequence | The sequence is generated by following this pseudo-code:
A: The first term is zero.
Repeatedly apply:
If the last term is *new* to the sequence so far then:
B: The next term is zero.
Otherwise:
C: The next term is how far back this last term occured previously.
Example
Using ... | #Ruby | Ruby | van_eck = Enumerator.new do |y|
ar = [0]
loop do
y << (term = ar.last) # yield
ar << (ar.count(term)==1 ? 0 : ar.size - 1 - ar[0..-2].rindex(term))
end
end
ve = van_eck.take(1000)
p ve.first(10), ve.last(10)
| Give a code snippet in #Ruby
The sequence is generated by following this pseudo-code:
A: The first term is zero.
Repeatedly apply:
If the last term is *new* to the sequence so far then:
B: The next term is zero.
Otherwise:
C: The next term is how far back this last term occured ... | christopher/rosetta-code | |
http://rosettacode.org/wiki/String_case | String case | Task
Take the string alphaBETA and demonstrate how to convert it to:
upper-case and
lower-case
Use the default encoding of a string literal or plain ASCII if there is no string literal in your language.
Note: In some languages alphabets toLower and toUpper is not reversable.
Show any additional... | #PL.2FI | PL/I |
declare s character (20) varying initial ('alphaBETA');
put skip list (uppercase(s));
put skip list (lowercase(s));
| Give a code snippet in #PL.2FI
Task
Take the string alphaBETA and demonstrate how to convert it to:
upper-case and
lower-case
Use the default encoding of a string literal or plain ASCII if there is no string literal in your language.
Note: In some languages alphabets toLower and toUpper is not ... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Loops/Downward_for | Loops/Downward for | Task
Write a for loop which writes a countdown from 10 to 0.
Related tasks
Loop over multiple arrays simultaneously
Loops/Break
Loops/Continue
Loops/Do-while
Loops/Downward for
Loops/For
Loops/For with a specified step
Loops/Foreach
Loops/Increment loop index within loop body... | #TUSCRIPT | TUSCRIPT |
$$ MODE TUSCRIPT
LOOP n=10,0,-1
PRINT n
ENDLOOP
| Give a code snippet in #TUSCRIPT
Task
Write a for loop which writes a countdown from 10 to 0.
Related tasks
Loop over multiple arrays simultaneously
Loops/Break
Loops/Continue
Loops/Do-while
Loops/Downward for
Loops/For
Loops/For with a specified step
Loops/Foreach
Loops/Inc... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Empty_string | Empty string | Languages may have features for dealing specifically with empty strings
(those containing no characters).
Task
Demonstrate how to assign an empty string to a variable.
Demonstrate how to check that a string is empty.
Demonstrate how to check that a string is not empty.
Other tasks related to string oper... | #PL.2FI | PL/I | Dcl s Char(10) Varying;
s = ''; /* assign an empty string to a variable. */
if length(s) = 0 then ... /* To test whether a string is empty */
if length(s) > 0 then ... /* to test for a non-empty string */
| Give a code snippet in #PL.2FI
Languages may have features for dealing specifically with empty strings
(those containing no characters).
Task
Demonstrate how to assign an empty string to a variable.
Demonstrate how to check that a string is empty.
Demonstrate how to check that a string is not empty.
Ot... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Longest_common_subsequence | Longest common subsequence | Introduction
Define a subsequence to be any output string obtained by deleting zero or more symbols from an input string.
The Longest Common Subsequence (LCS) is a subsequence of maximum length common to two or more strings.
Let A ≡ A[0]… A[m - 1] and B ≡ B[0]… B[n - 1], m < n be strings drawn from an alphabet Σ of ... | #Ring | Ring |
see longest("1267834", "1224533324") + nl
func longest a, b
if a = "" or b = "" return "" ok
if right(a, 1) = right(b, 1)
lcs = longest(left(a, len(a) - 1), left(b, len(b) - 1)) + right(a, 1)
return lcs
else
x1 = longest(a, left(b, len(b) - 1))
x2 = longest(left(a, l... | Give a code snippet in #Ring
Introduction
Define a subsequence to be any output string obtained by deleting zero or more symbols from an input string.
The Longest Common Subsequence (LCS) is a subsequence of maximum length common to two or more strings.
Let A ≡ A[0]… A[m - 1] and B ≡ B[0]… B[n - 1], m < n be string... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Quine | Quine | A quine is a self-referential program that can,
without any external access, output its own source.
A quine (named after Willard Van Orman Quine) is also known as:
self-reproducing automata (1972)
self-replicating program or self-replicating computer program
self-reproducing program ... | #M4 | M4 | define(`quine',``$1(`$1')'')dnl
quine(`define(`quine',``$1(`$1')'')dnl
quine') | Give a code snippet in #M4
A quine is a self-referential program that can,
without any external access, output its own source.
A quine (named after Willard Van Orman Quine) is also known as:
self-reproducing automata (1972)
self-replicating program or self-replicating computer program
se... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Rep-string | Rep-string | Given a series of ones and zeroes in a string, define a repeated string or rep-string as a string which is created by repeating a substring of the first N characters of the string truncated on the right to the length of the input string, and in which the substring appears repeated at least twice in the original.
For e... | #Python | Python | def is_repeated(text):
'check if the first part of the string is repeated throughout the string'
for x in range(len(text)//2, 0, -1):
if text.startswith(text[x:]): return x
return 0
matchstr = """\
1001110011
1110111011
0010010010
1010101010
1111111111
0100101101
0100100
101
11
00
1
"""
for line i... | Give a code snippet in #Python
Given a series of ones and zeroes in a string, define a repeated string or rep-string as a string which is created by repeating a substring of the first N characters of the string truncated on the right to the length of the input string, and in which the substring appears repeated at lea... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Parallel_brute_force | Parallel brute force | Task
Find, through brute force, the five-letter passwords corresponding with the following SHA-256 hashes:
1. 1115dd800feaacefdf481f1f9070374a2a81e27880f187396db67958b207cbad
2. 3a7bd3e2360a3d29eea436fcfb7e44c735d117c42d1c1835420b6b9942dd4f1b
3. 74e1bb62f8dabb8125a58852b63bdf6eaef667cb56ac7f7cdba6d7305c50a22f
Your p... | #FreeBASIC | FreeBASIC | Function SHA_256(Byval message As String) As String
#Macro Ch (x, y, z)
(((x) And (y)) Xor ((Not (x)) And z))
#EndMacro
#Macro Maj (x, y, z)
(((x) And (y)) Xor ((x) And (z)) Xor ((y) And (z)))
#EndMacro
#Macro sigma0 (x)
(((x) Shr 2 Or (x) Shl 30) Xor ((x) Shr 13 Or (x) Shl 19) Xor ... | Give a code snippet in #FreeBASIC
Task
Find, through brute force, the five-letter passwords corresponding with the following SHA-256 hashes:
1. 1115dd800feaacefdf481f1f9070374a2a81e27880f187396db67958b207cbad
2. 3a7bd3e2360a3d29eea436fcfb7e44c735d117c42d1c1835420b6b9942dd4f1b
3. 74e1bb62f8dabb8125a58852b63bdf6eaef66... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Special_variables | Special variables | Special variables have a predefined meaning within a computer programming language.
Task
List the special variables used within the language.
| #Pascal | Pascal | program foo(input, output);
begin
{ In this program, `input` and `output` have special meaning. }
end. | Give a code snippet in #Pascal
Special variables have a predefined meaning within a computer programming language.
Task
List the special variables used within the language.
| christopher/rosetta-code | |
http://rosettacode.org/wiki/Loops/For | Loops/For | “For” loops are used to make some block of code be iterated a number of times, setting a variable or parameter to a monotonically increasing integer value for each execution of the block of code.
Common extensions of this allow other counting patterns or iterating over abstract structures other than the integers.
... | #HolyC | HolyC | U8 i, j;
for (i = 1; i <= 5; i++) {
for (j = 1; j <= i; j++)
Print("*");
Print("\n");
} | Give a code snippet in #HolyC
“For” loops are used to make some block of code be iterated a number of times, setting a variable or parameter to a monotonically increasing integer value for each execution of the block of code.
Common extensions of this allow other counting patterns or iterating over abstract structu... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Euler%27s_constant_0.5772... | Euler's constant 0.5772... |
Task.
Compute the Euler constant 0.5772...
Discovered by Leonhard Euler around 1730, it is the most ubiquitous mathematical constant after pi and e, but appears more arcane than these.
Denoted gamma (γ), it measures the amount by which the partial sums of the harmonic series (the simplest diverging series) differ f... | #Wren | Wren | import "./fmt" for Fmt
var eps = 1e-6
System.print("From the definition, err. 3e-10")
var n = 400
var h = 1
for (k in 2..n) h = h + 1/k
//faster convergence: Negoi, 1997
var a = (n + 0.5 + 1/(24*n)).log
Fmt.print("Hn $0.14f", h)
Fmt.print("gamma $0.14f\nk = $d\n", h - a, n)
System.print("Sweeney, 1963, err. ... | Give a code snippet in #Wren
Task.
Compute the Euler constant 0.5772...
Discovered by Leonhard Euler around 1730, it is the most ubiquitous mathematical constant after pi and e, but appears more arcane than these.
Denoted gamma (γ), it measures the amount by which the partial sums of the harmonic series (the simpl... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Soundex | Soundex | Soundex is an algorithm for creating indices for words based on their pronunciation.
Task
The goal is for homophones to be encoded to the same representation so that they can be matched despite minor differences in spelling (from the soundex Wikipedia article).
Caution
There is a major issue in many of the ... | #Forth | Forth | : alpha-table create does> swap 32 or [char] a - 0 max 26 min + 1+ c@ ;
alpha-table soundex-code
," 123 12. 22455 12623 1.2 2 "
\ ABCDEFGHIJKLMNOPQRSTUVWXYZ
: soundex ( name len -- pad len )
over c@ pad c! \ First character verbatim
pad 1+ 3 [char] 0 fill \ Pad to four characters... | Give a code snippet in #Forth
Soundex is an algorithm for creating indices for words based on their pronunciation.
Task
The goal is for homophones to be encoded to the same representation so that they can be matched despite minor differences in spelling (from the soundex Wikipedia article).
Caution
There i... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Haversine_formula | Haversine formula |
This page uses content from Wikipedia. The original article was at Haversine formula. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance)
The haversine formula is an equation important in navigation, g... | #Objective-C | Objective-C | + (double) distanceBetweenLat1:(double)lat1 lon1:(double)lon1
lat2:(double)lat2 lon2:(double)lon2 {
//degrees to radians
double lat1rad = lat1 * M_PI/180;
double lon1rad = lon1 * M_PI/180;
double lat2rad = lat2 * M_PI/180;
double lon2rad = lon2 * M_PI/180;
//deltas
... | Give a code snippet in #Objective-C
This page uses content from Wikipedia. The original article was at Haversine formula. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance)
The haversine formula is a... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Apply_a_callback_to_an_array | Apply a callback to an array | Task
Take a combined set of elements and apply a function to each element.
| #Go | Go | package main
import "fmt"
func main() {
for _, i := range []int{1, 2, 3, 4, 5} {
fmt.Println(i * i)
}
} | Give a code snippet in #Go
Task
Take a combined set of elements and apply a function to each element.
| christopher/rosetta-code | |
http://rosettacode.org/wiki/OpenGL | OpenGL |
Task
Display a smooth shaded triangle with OpenGL.
Triangle created using C example compiled with GCC 4.1.2 and freeglut3.
| #Lua | Lua | local gl = require "luagl"
local iup = require "iuplua"
require "iupluagl"
local function paint()
gl.ClearColor(0.3,0.3,0.3,0.0)
gl.Clear"COLOR_BUFFER_BIT,DEPTH_BUFFER_BIT"
gl.ShadeModel"SMOOTH"
gl.LoadIdentity()
gl.Translate(-15.0, -15.0, 0.0)
gl.Begin"TRIANGLES"
gl.Color(1.0, 0.0, 0.0)
gl.Vert... | Give a code snippet in #Lua
Task
Display a smooth shaded triangle with OpenGL.
Triangle created using C example compiled with GCC 4.1.2 and freeglut3.
| christopher/rosetta-code | |
http://rosettacode.org/wiki/Snake | Snake |
This page uses content from Wikipedia. The original article was at Snake_(video_game). The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance)
Snake is a game where the player maneuvers a line which grows i... | #XPL0 | XPL0 | def Width=40, Height=25-1, \playing area including border
StartLength = 10, \starting length of snake including head
Morsels = 10; \number of food items constantly offered
int Heading; \direction snake is heading
def Up, Down, L... | Give a code snippet in #XPL0
This page uses content from Wikipedia. The original article was at Snake_(video_game). The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance)
Snake is a game where the player ... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Sequence:_nth_number_with_exactly_n_divisors | Sequence: nth number with exactly n divisors | Calculate the sequence where each term an is the nth that has n divisors.
Task
Show here, on this page, at least the first 15 terms of the sequence.
See also
OEIS:A073916
Related tasks
Sequence: smallest number greater than previous term with exactly n divisors
Sequence: smallest number with exactly n divisors | #REXX | REXX | /*REXX program finds and displays the Nth number with exactly N divisors. */
parse arg N . /*obtain optional argument from the CL.*/
if N=='' | N=="," then N= 15 /*Not specified? Then use the default.*/
if N>=50 then numeric digits 10 ... | Give a code snippet in #REXX
Calculate the sequence where each term an is the nth that has n divisors.
Task
Show here, on this page, at least the first 15 terms of the sequence.
See also
OEIS:A073916
Related tasks
Sequence: smallest number greater than previous term with exactly n divisors
Sequence: smallest number ... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Population_count | Population count | Population count
You are encouraged to solve this task according to the task description, using any language you may know.
The population count is the number of 1s (ones) in the binary representation of a non-negative integer.
Population count is also known as:
pop count
popcount
sideways sum
... | #Lua | Lua | -- Take decimal number, return binary string
function dec2bin (n)
local bin, bit = ""
while n > 0 do
bit = n % 2
n = math.floor(n / 2)
bin = bit .. bin
end
return bin
end
-- Take decimal number, return population count as number
function popCount (n)
local bin, count = dec2... | Give a code snippet in #Lua
Population count
You are encouraged to solve this task according to the task description, using any language you may know.
The population count is the number of 1s (ones) in the binary representation of a non-negative integer.
Population count is also known as:
pop count
... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Animation | Animation |
Animation is integral to many parts of GUIs, including both the fancy effects when things change used in window managers, and of course games. The core of any animation system is a scheme for periodically changing the display while still remaining responsive to the user. This task demonstrates this.
Task
Creat... | #Nim | Nim | import gintro/[glib, gobject, gdk, gtk, gio]
type
# Scrolling direction.
ScrollDirection = enum toLeft, toRight
# Data transmitted to update callback.
UpdateData = ref object
label: Label
scrollDir: ScrollDirection
#--------------------------------------------------------------------------------... | Give a code snippet in #Nim
Animation is integral to many parts of GUIs, including both the fancy effects when things change used in window managers, and of course games. The core of any animation system is a scheme for periodically changing the display while still remaining responsive to the user. This task demo... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Hamming_numbers | Hamming numbers | Hamming numbers are numbers of the form
H = 2i × 3j × 5k
where
i, j, k ≥ 0
Hamming numbers are also known as ugly numbers and also 5-smooth numbers (numbers whose prime divisors are less or equal to 5).
Task
Generate the sequence of Hamming numbers, in increasing order. In ... | #Ada | Ada |
with Ada.Numerics.Generic_Elementary_Functions;
with Ada.Text_IO; use Ada.Text_IO;
with GNATCOLL.GMP.Integers;
with GNATCOLL.GMP.Lib;
procedure Hamming is
type Log_Type is new Long_Long_Float;
package Funcs is new Ada.Numerics.Generic_Elementary_Functions (Log_Type);
type Factors_Array is array (Positi... | Give a code snippet in #Ada
Hamming numbers are numbers of the form
H = 2i × 3j × 5k
where
i, j, k ≥ 0
Hamming numbers are also known as ugly numbers and also 5-smooth numbers (numbers whose prime divisors are less or equal to 5).
Task
Generate the sequence of Hamming number... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Humble_numbers | Humble numbers | Humble numbers are positive integers which have no prime factors > 7.
Humble numbers are also called 7-smooth numbers, and sometimes called highly composite,
although this conflicts with another meaning of highly composite numbers.
Another way to express the above is:
humble = 2i × 3j × 5k... | #11l | 11l | F is_humble(i)
I i <= 1
R 1B
I i % 2 == 0 {R is_humble(i I/ 2)}
I i % 3 == 0 {R is_humble(i I/ 3)}
I i % 5 == 0 {R is_humble(i I/ 5)}
I i % 7 == 0 {R is_humble(i I/ 7)}
R 0B
DefaultDict[Int, Int] humble
V limit = 7F'FF
V count = 0
V num = 1
L count < limit
I is_humble(num)
humble[St... | Give a code snippet in #11l
Humble numbers are positive integers which have no prime factors > 7.
Humble numbers are also called 7-smooth numbers, and sometimes called highly composite,
although this conflicts with another meaning of highly composite numbers.
Another way to express the above i... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Time_a_function | Time a function | Task
Write a program which uses a timer (with the least granularity available
on your system) to time how long a function takes to execute.
Whenever possible, use methods which measure only the processing time used
by the current process; instead of the difference in system time
between start and finish, which could ... | #Racket | Racket |
#lang racket
(define (fact n) (if (zero? n) 1 (* n (fact (sub1 n)))))
(time (fact 5000))
| Give a code snippet in #Racket
Task
Write a program which uses a timer (with the least granularity available
on your system) to time how long a function takes to execute.
Whenever possible, use methods which measure only the processing time used
by the current process; instead of the difference in system time
betwee... | christopher/rosetta-code | |
http://rosettacode.org/wiki/URL_encoding | URL encoding | Task
Provide a function or mechanism to convert a provided string into URL encoding representation.
In URL encoding, special characters, control characters and extended characters
are converted into a percent symbol followed by a two digit hexadecimal code,
So a space character encodes into %20 within the string.
Fo... | #Objective-C | Objective-C | NSString *normal = @"http://foo bar/";
NSString *encoded = [normal stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSLog(@"%@", encoded); | Give a code snippet in #Objective-C
Task
Provide a function or mechanism to convert a provided string into URL encoding representation.
In URL encoding, special characters, control characters and extended characters
are converted into a percent symbol followed by a two digit hexadecimal code,
So a space character en... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Remove_lines_from_a_file | Remove lines from a file | Task
Remove a specific line or a number of lines from a file.
This should be implemented as a routine that takes three parameters (filename, starting line, and the number of lines to be removed).
For the purpose of this task, line numbers and the number of lines start at one, so to remove the first two lines from th... | #C.23 | C# | using System;
using System.IO;
using System.Linq;
public class Rosetta
{
public static void Main() => RemoveLines("foobar.txt", start: 1, count: 2);
static void RemoveLines(string filename, int start, int count = 1) =>
File.WriteAllLines(filename, File.ReadAllLines(filename)
.Where((line... | Give a code snippet in #C.23
Task
Remove a specific line or a number of lines from a file.
This should be implemented as a routine that takes three parameters (filename, starting line, and the number of lines to be removed).
For the purpose of this task, line numbers and the number of lines start at one, so to remo... | christopher/rosetta-code | |
http://rosettacode.org/wiki/AVL_tree | AVL tree |
This page uses content from Wikipedia. The original article was at AVL tree. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance)
In computer science, an AVL tree is a self-balancing binary search tree.... | #Scheme | Scheme | (cond-expand
(r7rs)
(chicken (import r7rs)))
(define-library (avl-trees)
;;
;; This library implements ‘persistent’ (that is, ‘immutable’) AVL
;; trees for R7RS Scheme.
;;
;; Included are generators of the key-data pairs in a tree. Because
;; the trees are persistent (‘immutable’), these generators ... | Give a code snippet in #Scheme
This page uses content from Wikipedia. The original article was at AVL tree. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance)
In computer science, an AVL tree is a se... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Unicode_strings | Unicode strings | As the world gets smaller each day, internationalization becomes more and more important. For handling multiple languages, Unicode is your best friend.
It is a very capable tool, but also quite complex compared to older single- and double-byte character encodings.
How well prepared is your programming language for ... | #Tcl | Tcl | @{TITLE /[あ-ん一-耙]+/} (@ROMAJI/@ENGLISH)
@(freeform)
@(coll)@{STANZA /[^\n\x3000 ]+/}@(end)@/.*/
| Give a code snippet in #Tcl
As the world gets smaller each day, internationalization becomes more and more important. For handling multiple languages, Unicode is your best friend.
It is a very capable tool, but also quite complex compared to older single- and double-byte character encodings.
How well prepared is y... | christopher/rosetta-code | |
http://rosettacode.org/wiki/SHA-256 | SHA-256 | SHA-256 is the recommended stronger alternative to SHA-1. See FIPS PUB 180-4 for implementation details.
Either by using a dedicated library or implementing the algorithm in your language, show that the SHA-256 digest of the string "Rosetta code" is: 764faf5c61ac315f1497f9dfa542713965b785e5cc2f707d6468d7d1124cdfcf
| #PicoLisp | PicoLisp | (setq *Sha256-K
(mapcar hex
'("428A2F98" "71374491" "B5C0FBCF" "E9B5DBA5" "3956C25B"
"59F111F1" "923F82A4" "AB1C5ED5" "D807AA98" "12835B01"
"243185BE" "550C7DC3" "72BE5D74" "80DEB1FE" "9BDC06A7"
"C19BF174" "E49B69C1" "EFBE4786" "0FC19DC6" "240CA1CC"
"2DE92C6F" "4A7484AA" "5C... | Give a code snippet in #PicoLisp
SHA-256 is the recommended stronger alternative to SHA-1. See FIPS PUB 180-4 for implementation details.
Either by using a dedicated library or implementing the algorithm in your language, show that the SHA-256 digest of the string "Rosetta code" is: 764faf5c61ac315f1497f9dfa542713965... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Loops/While | Loops/While | Task
Start an integer value at 1024.
Loop while it is greater than zero.
Print the value (with a newline) and divide it by two each time through the loop.
Related tasks
Loop over multiple arrays simultaneously
Loops/Break
Loops/Continue
Loops/Do-while
Loops/Downward for
Loops/For
Loops/For... | #Make | Make | NEXT=`expr $* / 2`
MAX=10
all: $(MAX)-n;
0-n:;
%-n: %-echo
@-make -f while.mk $(NEXT)-n MAX=$(MAX)
%-echo:
@echo $* | Give a code snippet in #Make
Task
Start an integer value at 1024.
Loop while it is greater than zero.
Print the value (with a newline) and divide it by two each time through the loop.
Related tasks
Loop over multiple arrays simultaneously
Loops/Break
Loops/Continue
Loops/Do-while
Loops/Downward... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Parsing/RPN_calculator_algorithm | Parsing/RPN calculator algorithm | Task
Create a stack-based evaluator for an expression in reverse Polish notation (RPN) that also shows the changes in the stack as each individual token is processed as a table.
Assume an input of a correct, space separated, string of tokens of an RPN expression
Test with the RPN expression generated from the... | #Raku | Raku | my $proggie = '3 4 2 * 1 5 - 2 3 ^ ^ / +';
class RPN is Array {
method binop(&op) { self.push: self.pop R[&op] self.pop }
method run($p) {
for $p.words {
say "$_ ({self})";
when /\d/ { self.push: $_ }
when '+' { self.binop: &[+] }
when '-' { self.b... | Give a code snippet in #Raku
Task
Create a stack-based evaluator for an expression in reverse Polish notation (RPN) that also shows the changes in the stack as each individual token is processed as a table.
Assume an input of a correct, space separated, string of tokens of an RPN expression
Test with the RPN... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Polymorphism | Polymorphism | Task
Create two classes Point(x,y) and Circle(x,y,r) with a polymorphic function print, accessors for (x,y,r), copy constructor, assignment and destructor and every possible default constructors
| #Aikido | Aikido |
class Point (protected x=0.0, protected y=0.0) {
public function print {
println ("Point")
}
public function getX { return x }
public function getY { return y }
public function setX(nx) { x = nx }
public function setY(ny) { y = ny }
}
class Circle (x=0.0, y=0.0, r=0.0) extends Po... | Give a code snippet in #Aikido
Task
Create two classes Point(x,y) and Circle(x,y,r) with a polymorphic function print, accessors for (x,y,r), copy constructor, assignment and destructor and every possible default constructors
| christopher/rosetta-code | |
http://rosettacode.org/wiki/Spinning_rod_animation/Text | Spinning rod animation/Text | Task
An animation with the following frames in the following order (if certain characters aren't available or can't be used correctly in the programming language, alternate characters can replace any of these frames) must animate with a delay of 0.25 seconds between each frame, with the previous frame being cleared be... | #Mathematica_.2F_Wolfram_Language | Mathematica / Wolfram Language | chars = "|/\[Dash]\\";
pos = 1;
Dynamic[c]
While[True,
pos = Mod[pos + 1, StringLength[chars], 1];
c = StringTake[chars, {pos}];
Pause[0.25];
] | Give a code snippet in #Mathematica_.2F_Wolfram_Language
Task
An animation with the following frames in the following order (if certain characters aren't available or can't be used correctly in the programming language, alternate characters can replace any of these frames) must animate with a delay of 0.25 seconds be... | christopher/rosetta-code | |
http://rosettacode.org/wiki/N-queens_problem | N-queens problem |
Solve the eight queens puzzle.
You can extend the problem to solve the puzzle with a board of size NxN.
For the number of solutions for small values of N, see OEIS: A000170.
Related tasks
A* search algorithm
Solve a Hidato puzzle
Solve a Holy Knight's tour
Knight's tour
Peaceful chess queen armie... | #Ruby | Ruby | # 1. Divide n by 12. Remember the remainder (n is 8 for the eight queens
# puzzle).
# 2. Write a list of the even numbers from 2 to n in order.
# 3. If the remainder is 3 or 9, move 2 to the end of the list.
# 4. Append the odd numbers from 1 to n in order, but, if the remainder is 8,
# switch pairs (i.e. 3, 1, 7... | Give a code snippet in #Ruby
Solve the eight queens puzzle.
You can extend the problem to solve the puzzle with a board of size NxN.
For the number of solutions for small values of N, see OEIS: A000170.
Related tasks
A* search algorithm
Solve a Hidato puzzle
Solve a Holy Knight's tour
Knight's to... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Happy_numbers | Happy numbers | From Wikipedia, the free encyclopedia:
A happy number is defined by the following process:
Starting with any positive integer, replace the number by the sum of the squares of its digits, and repeat the process until the number equals 1 (where it will stay), or it loops endlessly in a cycle which does not inclu... | #Mathematica_.2F_Wolfram_Language | Mathematica / Wolfram Language | AddSumSquare[input_]:=Append[input,Total[IntegerDigits[Last[input]]^2]]
NestUntilRepeat[a_,f_]:=NestWhile[f,{a},!MemberQ[Most[Last[{##}]],Last[Last[{##}]]]&,All]
HappyQ[a_]:=Last[NestUntilRepeat[a,AddSumSquare]]==1 | Give a code snippet in #Mathematica_.2F_Wolfram_Language
From Wikipedia, the free encyclopedia:
A happy number is defined by the following process:
Starting with any positive integer, replace the number by the sum of the squares of its digits, and repeat the process until the number equals 1 (where it will stay... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Conditional_structures | Conditional structures | Control Structures
These are examples of control structures. You may also be interested in:
Conditional structures
Exceptions
Flow-control structures
Loops
Task
List the conditional structures offered by a programming language. See Wikipedia: conditionals for descriptions.
Common conditional structures include ... | #Prolog | Prolog | go :- write('Hello, World!'), nl. | Give a code snippet in #Prolog
Control Structures
These are examples of control structures. You may also be interested in:
Conditional structures
Exceptions
Flow-control structures
Loops
Task
List the conditional structures offered by a programming language. See Wikipedia: conditionals for descriptions.
Common... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Singly-linked_list/Element_insertion | Singly-linked list/Element insertion | Singly-Linked List (element)
singly-linked list
Using this method, insert an element C into a list comprised of elements A->B, following element A.
See also
Array
Associative array: Creation, Iteration
Collections
Compound data type
Doubly-linked list: Definition, Element definition, Element insertion, List Trav... | #Delphi | Delphi | // Using the same type defs from the one way list example.
Type
// The pointer to the list structure
pOneWayList = ^OneWayList;
// The list structure
OneWayList = record
pData : pointer ;
Next : pOneWayList ;
end;
// I will illustrate a simple function t... | Give a code snippet in #Delphi
Singly-Linked List (element)
singly-linked list
Using this method, insert an element C into a list comprised of elements A->B, following element A.
See also
Array
Associative array: Creation, Iteration
Collections
Compound data type
Doubly-linked list: Definition, Element definiti... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Truncate_a_file | Truncate a file | Task
Truncate a file to a specific length. This should be implemented as a routine that takes two parameters: the filename and the required file length (in bytes).
Truncation can be achieved using system or library calls intended for such a task, if such methods exist, or by creating a temporary file of a reduced... | #Standard_ML | Standard ML | local
open Posix.FileSys
val perm = S.flags [S.irusr, S.iwusr, S.irgrp, S.iwgrp, S.iroth, S.iwoth]
in
fun truncate (path, len) =
let
val fd = createf (path, O_WRONLY, O.noctty, perm)
in
ftruncate (fd, len); Posix.IO.close fd
end
end | Give a code snippet in #Standard_ML
Task
Truncate a file to a specific length. This should be implemented as a routine that takes two parameters: the filename and the required file length (in bytes).
Truncation can be achieved using system or library calls intended for such a task, if such methods exist, or by c... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Higher-order_functions | Higher-order functions | Task
Pass a function as an argument to another function.
Related task
First-class functions
| #Luck | Luck | function lambda_true(x: 'a)(y: 'a): 'a = x;;
function lambda_false(x: 'a)(y: 'a): 'a = y;;
function lambda_if(c:'a -> 'a -> 'a )(t: 'a)(f: 'a): 'a = c(t)(f);;
print( lambda_if(lambda_true)("condition was true")("condition was false") );; | Give a code snippet in #Luck
Task
Pass a function as an argument to another function.
Related task
First-class functions
| christopher/rosetta-code | |
http://rosettacode.org/wiki/Box_the_compass | Box the compass | There be many a land lubber that knows naught of the pirate ways and gives direction by degree!
They know not how to box the compass!
Task description
Create a function that takes a heading in degrees and returns the correct 32-point compass heading.
Use the function to print and display a table of Index, Compass... | #Nim | Nim | import math, sequtils, strformat, strutils
const
headingNames: array[1..32, string] = [
"North", "North by east", "North-northeast", "Northeast by north",
"Northeast", "Northeast by east", "East-northeast", "East by north",
"East", "East by south", "East-southeast", "Southeast by east",
"Southeast",... | Give a code snippet in #Nim
There be many a land lubber that knows naught of the pirate ways and gives direction by degree!
They know not how to box the compass!
Task description
Create a function that takes a heading in degrees and returns the correct 32-point compass heading.
Use the function to print and disp... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Character_codes | Character codes |
Task
Given a character value in your language, print its code (could be ASCII code, Unicode code, or whatever your language uses).
Example
The character 'a' (lowercase letter A) has a code of 97 in ASCII (as well as Unicode, as ASCII forms the beginning of Unicode).
Conversely, given a code, print out... | #Metafont | Metafont | message "enter a letter: ";
string a;
a := readstring;
message decimal (ASCII a); % writes the decimal number of the first character
% of the string a
message "enter a number: ";
num := scantokens readstring;
message char num; % num can be anything between 0 and 255; what will be seen
... | Give a code snippet in #Metafont
Task
Given a character value in your language, print its code (could be ASCII code, Unicode code, or whatever your language uses).
Example
The character 'a' (lowercase letter A) has a code of 97 in ASCII (as well as Unicode, as ASCII forms the beginning of Unicode).
C... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Count_the_coins | Count the coins | There are four types of common coins in US currency:
quarters (25 cents)
dimes (10 cents)
nickels (5 cents), and
pennies (1 cent)
There are six ways to make change for 15 cents:
A dime and a nickel
A dime and 5 pennies
3 nickels
2 nickels and 5 pennies
A nickel and 10 pen... | #Mathematica_.2F_Wolfram_Language | Mathematica / Wolfram Language | CountCoins[amount_, coinlist_] := ( ways = ConstantArray[1, amount];
Do[For[j = coin, j <= amount, j++,
If[ j - coin == 0,
ways[[j]] ++,
ways[[j]] += ways[[j - coin]]
]]
, {coin, coinlist}];
ways[[amount]]) | Give a code snippet in #Mathematica_.2F_Wolfram_Language
There are four types of common coins in US currency:
quarters (25 cents)
dimes (10 cents)
nickels (5 cents), and
pennies (1 cent)
There are six ways to make change for 15 cents:
A dime and a nickel
A dime and 5 pennies
3... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Sockets | Sockets | For this exercise a program is open a socket to localhost on port 256 and send the message "hello socket world" before closing the socket.
Catching any exceptions or errors is not required.
| #Toka | Toka | needs sockets
#! A simple abstraction layer that makes writing trivial servers easy
value| server.socket server.connection server.action |
[ ( n- ) pBind to server.socket ] is server.setSocket
[ ( - ) server.socket pAccept to server.connection ] is server.acceptConnection
[ ( - ) server.connection pClose drop... | Give a code snippet in #Toka
For this exercise a program is open a socket to localhost on port 256 and send the message "hello socket world" before closing the socket.
Catching any exceptions or errors is not required.
| christopher/rosetta-code | |
http://rosettacode.org/wiki/Earliest_difference_between_prime_gaps | Earliest difference between prime gaps | When calculating prime numbers > 2, the difference between adjacent primes is always an even number. This difference, also referred to as the gap, varies in an random pattern; at least, no pattern has ever been discovered, and it is strongly conjectured that no pattern exists. However, it is also conjectured that betwe... | #Mathematica.2FWolfram_Language | Mathematica/Wolfram Language | primes = Prime[Range[10^7]];
gaps = {Differences[primes], Most[primes]} // Transpose;
tmp = GatherBy[gaps, First][[All, 1]];
tmp = SortBy[tmp, First];
starts = Association[Rule @@@ tmp];
set = {Most[tmp[[All, 1]]], Abs@Differences[tmp[[All, 2]]]} // Transpose;
data = Table[{n, k} = SelectFirst[set, Last/*GreaterThan[10... | Give a code snippet in #Mathematica.2FWolfram_Language
When calculating prime numbers > 2, the difference between adjacent primes is always an even number. This difference, also referred to as the gap, varies in an random pattern; at least, no pattern has ever been discovered, and it is strongly conjectured that no pa... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Remove_duplicate_elements | Remove duplicate elements |
Sorting Algorithm
This is a sorting algorithm. It may be applied to a set of data in order to sort it.
For comparing various sorts, see compare sorts.
For other sorting algorithms, see sorting algorithms, or:
O(n logn) sorts
Heap sort |
Merge sort |
Patience sort |
Quick sort
O(n log2n) sorts
Shell Sort
... | #Delphi | Delphi | program RemoveDuplicateElements;
{$APPTYPE CONSOLE}
uses Generics.Collections;
var
i: Integer;
lIntegerList: TList<Integer>;
const
INT_ARRAY: array[1..7] of Integer = (1, 2, 2, 3, 4, 5, 5);
begin
lIntegerList := TList<Integer>.Create;
try
for i in INT_ARRAY do
if not lIntegerList.Contains(i) then
... | Give a code snippet in #Delphi
Sorting Algorithm
This is a sorting algorithm. It may be applied to a set of data in order to sort it.
For comparing various sorts, see compare sorts.
For other sorting algorithms, see sorting algorithms, or:
O(n logn) sorts
Heap sort |
Merge sort |
Patience sort |
Quick s... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Arithmetic/Complex | Arithmetic/Complex | A complex number is a number which can be written as:
a
+
b
×
i
{\displaystyle a+b\times i}
(sometimes shown as:
b
+
a
×
i
{\displaystyle b+a\times i}
where
a
{\displaystyle a}
and
b
{\displaystyle b}
are real numbers, and
i
{\displaystyle i}
is √ -1
Typica... | #Standard_ML | Standard ML |
(* Signature for complex numbers *)
signature COMPLEX = sig
type num
val complex : real * real -> num
val negative : num -> num
val plus : num -> num -> num
val minus : num -> num -> num
val times : num -> num -> num
val invert : num -> num
val print_number : num -> unit
end;
(* Actual implementation *)... | Give a code snippet in #Standard_ML
A complex number is a number which can be written as:
a
+
b
×
i
{\displaystyle a+b\times i}
(sometimes shown as:
b
+
a
×
i
{\displaystyle b+a\times i}
where
a
{\displaystyle a}
and
b
{\displaystyle b}
are real numbers, and
i
{\dis... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Minimum_positive_multiple_in_base_10_using_only_0_and_1 | Minimum positive multiple in base 10 using only 0 and 1 | Every positive integer has infinitely many base-10 multiples that only use the digits 0 and 1. The goal of this task is to find and display the minimum multiple that has this property.
This is simple to do, but can be challenging to do efficiently.
To avoid repeating long, unwieldy phrases, the operation "minimum pos... | #Tcl | Tcl |
package require Tcl 8.5
## power of ten, modulo --> (10**expo % modval) suited for large expo
proc potmod {expo modval} {
if {$expo < 0} { return 0 }
if {$modval < 2} { return 0 } ;# x mod 1 = 0
set r 1
set p [expr {10 % $modval}]
while {$expo} {
set half [expr {$expo / ... | Give a code snippet in #Tcl
Every positive integer has infinitely many base-10 multiples that only use the digits 0 and 1. The goal of this task is to find and display the minimum multiple that has this property.
This is simple to do, but can be challenging to do efficiently.
To avoid repeating long, unwieldy phrase... | christopher/rosetta-code | |
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 ... | #UnixPipes | UnixPipes | find . -type f | egrep '\.txt$|\.TXT$' | Give a code snippet in #UnixPipes
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
... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Empty_program | Empty program | Task
Create the simplest possible program that is still considered "correct."
| #Stata | Stata | program define nop
version 15
end | Give a code snippet in #Stata
Task
Create the simplest possible program that is still considered "correct."
| christopher/rosetta-code | |
http://rosettacode.org/wiki/Farey_sequence | Farey sequence | The Farey sequence Fn of order n is the sequence of completely reduced fractions between 0 and 1 which, when in lowest terms, have denominators less than or equal to n, arranged in order of increasing size.
The Farey sequence is sometimes incorrectly called a Farey series.
Each Farey se... | #Crystal | Crystal | require "big"
def farey(n)
a, b, c, d = 0, 1, 1, n
fracs = [] of BigRational
fracs << BigRational.new(0,1)
while c <= n
k = (n + b) // d
a, b, c, d = c, d, k * c - a, k * d - b
fracs << BigRational.new(a,b)
end
fracs.uniq.sort
end
puts "Farey sequence for order 1 thro... | Give a code snippet in #Crystal
The Farey sequence Fn of order n is the sequence of completely reduced fractions between 0 and 1 which, when in lowest terms, have denominators less than or equal to n, arranged in order of increasing size.
The Farey sequence is sometimes incorrectly called a... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Thue-Morse | Thue-Morse | Task
Create a Thue-Morse sequence.
See also
YouTube entry: The Fairest Sharing Sequence Ever
YouTube entry: Math and OCD - My story with the Thue-Morse sequence
Task: Fairshare between two and more
| #BCPL | BCPL | get "libhdr"
let parity(x) =
x=0 -> 0,
(x&1) neqv parity(x>>1)
let start() be
$( for i=0 to 63 do writen(parity(i))
wrch('*N')
$) | Give a code snippet in #BCPL
Task
Create a Thue-Morse sequence.
See also
YouTube entry: The Fairest Sharing Sequence Ever
YouTube entry: Math and OCD - My story with the Thue-Morse sequence
Task: Fairshare between two and more
| christopher/rosetta-code | |
http://rosettacode.org/wiki/Mertens_function | Mertens function | The Mertens function M(x) is the count of square-free integers up to x that have an even number of prime factors, minus the count of those that have an odd number.
It is an extension of the Möbius function. Given the Möbius function μ(n), the Mertens function M(x) is the sum of the Möbius numbers from n == 1 through n... | #Ruby | Ruby | require 'prime'
def μ(n)
return 1 if self == 1
pd = n.prime_division
return 0 unless pd.map(&:last).all?(1)
pd.size.even? ? 1 : -1
end
def M(n)
(1..n).sum{|n| μ(n)}
end
([" "] + (1..199).map{|n|"%2s" % M(n)}).each_slice(20){|line| puts line.join(" ") }
ar = (1..1000).map{|n| M(n)}
puts "\nThe Mertens... | Give a code snippet in #Ruby
The Mertens function M(x) is the count of square-free integers up to x that have an even number of prime factors, minus the count of those that have an odd number.
It is an extension of the Möbius function. Given the Möbius function μ(n), the Mertens function M(x) is the sum of the Möbius... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Quine | Quine | A quine is a self-referential program that can,
without any external access, output its own source.
A quine (named after Willard Van Orman Quine) is also known as:
self-reproducing automata (1972)
self-replicating program or self-replicating computer program
self-reproducing program ... | #x86_Assembly | x86 Assembly |
.global _start;_start:mov $p,%rsi;mov $1,%rax;mov $1,%rdi;mov $255,%rdx;syscall;mov $q,%rsi;mov $1,%rax;mov $1,%rdx;syscall;mov $p,%rsi;mov $1,%rax;mov $255,%rdx;syscall;mov $q,%rsi;mov $1,%rax;mov $1,%rdx;syscall;mov $60,%rax;syscall;q:.byte 34;p:.ascii ".global _start;_start:mov $p,%rsi;mov $1,%rax;mov $1,%rdi;mov ... | Give a code snippet in #x86_Assembly
A quine is a self-referential program that can,
without any external access, output its own source.
A quine (named after Willard Van Orman Quine) is also known as:
self-reproducing automata (1972)
self-replicating program or self-replicating computer pro... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Sorting_algorithms/Shell_sort | Sorting algorithms/Shell sort |
Sorting Algorithm
This is a sorting algorithm. It may be applied to a set of data in order to sort it.
For comparing various sorts, see compare sorts.
For other sorting algorithms, see sorting algorithms, or:
O(n logn) sorts
Heap sort |
Merge sort |
Patience sort |
Quick sort
O(n log2n) sorts
Shell Sort
... | #Euphoria | Euphoria | function shell_sort(sequence s)
integer gap,j
object temp
gap = floor(length(s)/2)
while gap > 0 do
for i = gap to length(s) do
temp = s[i]
j=i-gap
while j >= 1 and compare(temp, s[j]) <= 0 do
s[j+gap]=s[j]
j -= gap
... | Give a code snippet in #Euphoria
Sorting Algorithm
This is a sorting algorithm. It may be applied to a set of data in order to sort it.
For comparing various sorts, see compare sorts.
For other sorting algorithms, see sorting algorithms, or:
O(n logn) sorts
Heap sort |
Merge sort |
Patience sort |
Quick... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Zero_to_the_zero_power | Zero to the zero power | Some computer programming languages are not exactly consistent (with other computer programming languages)
when raising zero to the zeroth power: 00
Task
Show the results of raising zero to the zeroth power.
If your computer language objects to 0**0 or 0^0 at compile time, ... | #Lambdatalk | Lambdatalk |
{pow 0 0}
-> 1
{exp 0 0}
-> 1
| Give a code snippet in #Lambdatalk
Some computer programming languages are not exactly consistent (with other computer programming languages)
when raising zero to the zeroth power: 00
Task
Show the results of raising zero to the zeroth power.
If your computer language objects to 0**0 ... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Taxicab_numbers | Taxicab numbers |
A taxicab number (the definition that is being used here) is a positive integer that can be expressed as the sum of two positive cubes in more than one way.
The first taxicab number is 1729, which is:
13 + 123 and also
93 + 103.
Taxicab numbers are also known as:
taxi numbers
tax... | #Sidef | Sidef | var (start=1, end=25) = ARGV.map{.to_i}...
func display (h, start, end) {
var i = start
for n in [h.grep {|_,v| v.len > 1 }.keys.sort_by{.to_i}[start-1 .. end-1]] {
printf("%4d %10d =>\t%s\n", i++, n,
h{n}.map{ "%4d³ + %-s" % (.first, "#{.last}³") }.join(",\t"))
}
}
var taxi = Hash(... | Give a code snippet in #Sidef
A taxicab number (the definition that is being used here) is a positive integer that can be expressed as the sum of two positive cubes in more than one way.
The first taxicab number is 1729, which is:
13 + 123 and also
93 + 103.
Taxicab numbers are also kn... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Perfect_numbers | Perfect numbers | Write a function which says whether a number is perfect.
A perfect number is a positive integer that is the sum of its proper positive divisors excluding the number itself.
Equivalently, a perfect number is a number that is half the sum of all of its positive divisors (including itself).
Note: The faster Luca... | #HicEst | HicEst | DO i = 1, 1E4
IF( perfect(i) ) WRITE() i
ENDDO
END ! end of "main"
FUNCTION perfect(n)
sum = 1
DO i = 2, n^0.5
sum = sum + (MOD(n, i) == 0) * (i + INT(n/i))
ENDDO
perfect = sum == n
END | Give a code snippet in #HicEst
Write a function which says whether a number is perfect.
A perfect number is a positive integer that is the sum of its proper positive divisors excluding the number itself.
Equivalently, a perfect number is a number that is half the sum of all of its positive divisors (including itsel... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Factors_of_an_integer | Factors of an integer |
Basic Data Operation
This is a basic data operation. It represents a fundamental action on a basic data type.
You may see other such operations in the Basic Data Operations category, or:
Integer Operations
Arithmetic |
Comparison
Boolean Operations
Bitwise |
Logical
String Operations
Concatenation |
Interpolation |... | #Phixmonti | Phixmonti | /# Rosetta Code problem: http://rosettacode.org/wiki/Factors_of_an_integer
by Galileo, 05/2022 #/
include ..\Utilitys.pmt
def Factors >ps
( ( 1 tps 2 / ) for tps over mod if drop endif endfor ps> )
enddef
11 Factors
21 Factors
32 factors
45 factors
67 factors
96 factors
pstack | Give a code snippet in #Phixmonti
Basic Data Operation
This is a basic data operation. It represents a fundamental action on a basic data type.
You may see other such operations in the Basic Data Operations category, or:
Integer Operations
Arithmetic |
Comparison
Boolean Operations
Bitwise |
Logical
String Operati... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Literals/String | Literals/String | Task
Show literal specification of characters and strings.
If supported, show how the following work:
verbatim strings (quotes where escape sequences are quoted literally)
here-strings
Also, discuss which quotes expand variables.
Related tasks
Special characters
Here document
Other tasks r... | #Objeck | Objeck | @"Hello, world!" | Give a code snippet in #Objeck
Task
Show literal specification of characters and strings.
If supported, show how the following work:
verbatim strings (quotes where escape sequences are quoted literally)
here-strings
Also, discuss which quotes expand variables.
Related tasks
Special characters
... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Numerical_integration/Gauss-Legendre_Quadrature | Numerical integration/Gauss-Legendre Quadrature |
In a general Gaussian quadrature rule, an definite integral of
f
(
x
)
{\displaystyle f(x)}
is first approximated over the interval
[
−
1
,
1
]
{\displaystyle [-1,1]}
by a polynomial approximable function
g
(
x
)
{\displaystyle g(x)}
and a known weighting function
W
(
x
)
{\displaystyle ... | #Pascal | Pascal | program Legendre(output);
const Order = 5;
Order1 = Order - 1;
Epsilon = 1E-12;
Pi = 3.1415926;
var Roots : array[0..Order1] of real;
Weight : array[0..Order1] of real;
LegCoef : array [0..Order,0..Order] of real;
I : integer;
function F(X:real) : real;
begin
F := Exp(X);
en... | Give a code snippet in #Pascal
In a general Gaussian quadrature rule, an definite integral of
f
(
x
)
{\displaystyle f(x)}
is first approximated over the interval
[
−
1
,
1
]
{\displaystyle [-1,1]}
by a polynomial approximable function
g
(
x
)
{\displaystyle g(x)}
and a known weighting functi... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Count_in_octal | Count in octal | Task
Produce a sequential count in octal, starting at zero, and using an increment of a one for each consecutive number.
Each number should appear on a single line, and the program should count until terminated, or until the maximum value of the numeric type in use is reached.
Related task
Integer sequ... | #bc | bc | obase = 8 /* Output base is octal. */
for (num = 0; 1; num++) num /* Loop forever, printing counter. */ | Give a code snippet in #bc
Task
Produce a sequential count in octal, starting at zero, and using an increment of a one for each consecutive number.
Each number should appear on a single line, and the program should count until terminated, or until the maximum value of the numeric type in use is reached.
R... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Comments | Comments | Task
Show all ways to include text in a language source file
that's completely ignored by the compiler or interpreter.
Related tasks
Documentation
Here_document
See also
Wikipedia
xkcd (Humor: hand gesture denoting // for "commenting out" people.)
| #PL.2FSQL | PL/SQL | --this is a single line comment | Give a code snippet in #PL.2FSQL
Task
Show all ways to include text in a language source file
that's completely ignored by the compiler or interpreter.
Related tasks
Documentation
Here_document
See also
Wikipedia
xkcd (Humor: hand gesture denoting // for "commenting out" people.)
| christopher/rosetta-code | |
http://rosettacode.org/wiki/Constrained_random_points_on_a_circle | Constrained random points on a circle | Task
Generate 100 <x,y> coordinate pairs such that x and y are integers sampled from the uniform distribution with the condition that
10
≤
x
2
+
y
2
≤
15
{\displaystyle 10\leq {\sqrt {x^{2}+y^{2}}}\leq 15}
.
Then display/plot them. The outcome should be a "fuzzy" circle. The actual number of point... | #Standard_ML | Standard ML | open XWindows ;
open Motif ;
val plotWindow = fn coords => (* input list of int*int within 'dim' *)
let
val dim = {tw=325,th=325} ;
val shell = XtAppInitialise "" "demo" "top" [] [ XmNwidth (#tw dim), XmNheight (#th dim) ] ; (*... | Give a code snippet in #Standard_ML
Task
Generate 100 <x,y> coordinate pairs such that x and y are integers sampled from the uniform distribution with the condition that
10
≤
x
2
+
y
2
≤
15
{\displaystyle 10\leq {\sqrt {x^{2}+y^{2}}}\leq 15}
.
Then display/plot them. The outcome should be a "fuzz... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Constrained_random_points_on_a_circle | Constrained random points on a circle | Task
Generate 100 <x,y> coordinate pairs such that x and y are integers sampled from the uniform distribution with the condition that
10
≤
x
2
+
y
2
≤
15
{\displaystyle 10\leq {\sqrt {x^{2}+y^{2}}}\leq 15}
.
Then display/plot them. The outcome should be a "fuzzy" circle. The actual number of point... | #Java | Java | import java.util.Random;
public class FuzzyCircle {
static final Random rnd = new Random();
public static void main(String[] args){
char[][] field = new char[31][31];
for(int i = 0; i < field.length; i++){
for(int j = 0; j < field[i].length; j++){
field[i][j] = ' ';
}
}
int pointsInDisc = 0;
whi... | Give a code snippet in #Java
Task
Generate 100 <x,y> coordinate pairs such that x and y are integers sampled from the uniform distribution with the condition that
10
≤
x
2
+
y
2
≤
15
{\displaystyle 10\leq {\sqrt {x^{2}+y^{2}}}\leq 15}
.
Then display/plot them. The outcome should be a "fuzzy" circ... | christopher/rosetta-code | |
http://rosettacode.org/wiki/JortSort | JortSort |
Sorting Algorithm
This is a sorting algorithm. It may be applied to a set of data in order to sort it.
For comparing various sorts, see compare sorts.
For other sorting algorithms, see sorting algorithms, or:
O(n logn) sorts
Heap sort |
Merge sort |
Patience sort |
Quick sort
O(n log2n) sorts
Shell Sort
... | #Mathematica.2FWolfram_Language | Mathematica/Wolfram Language | jortSort[list_] := list == Sort[list];
Print[jortSort[Range[100]]];
Print[jortSort[RandomSample[Range[100]]]]; | Give a code snippet in #Mathematica.2FWolfram_Language
Sorting Algorithm
This is a sorting algorithm. It may be applied to a set of data in order to sort it.
For comparing various sorts, see compare sorts.
For other sorting algorithms, see sorting algorithms, or:
O(n logn) sorts
Heap sort |
Merge sort |... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Deconvolution/1D | Deconvolution/1D | The convolution of two functions
F
{\displaystyle {\mathit {F}}}
and
H
{\displaystyle {\mathit {H}}}
of
an integer variable is defined as the function
G
{\displaystyle {\mathit {G}}}
satisfying
G
(
n
)
=
∑
m
=
−
∞
∞
F
(
m
)
H
(
n
−
m
)
{\displaystyle G(n)=\sum _{m=-\inft... | #J | J | Ai=: (i.@] =/ i.@[ -/ i.@>:@-)&#
divide=: [ +/ .*~ [:%.&.x: ] +/ .* Ai | Give a code snippet in #J
The convolution of two functions
F
{\displaystyle {\mathit {F}}}
and
H
{\displaystyle {\mathit {H}}}
of
an integer variable is defined as the function
G
{\displaystyle {\mathit {G}}}
satisfying
G
(
n
)
=
∑
m
=
−
∞
∞
F
(
m
)
H
(
n
−
m
)
{\displa... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Higher-order_functions | Higher-order functions | Task
Pass a function as an argument to another function.
Related task
First-class functions
| #ooRexx | ooRexx | say callit(.routines~fib, 10)
say callit(.routines~fact, 6)
say callit(.routines~square, 13)
say callit(.routines~cube, 3)
say callit(.routines~reverse, 721)
say callit(.routines~sumit, 1, 2)
say callit(.routines~sumit, 2, 4, 6, 8)
-- call the provided routine object with the provided variable number of arguments
::r... | Give a code snippet in #ooRexx
Task
Pass a function as an argument to another function.
Related task
First-class functions
| christopher/rosetta-code | |
http://rosettacode.org/wiki/Sum_of_squares | Sum of squares | Task
Write a program to find the sum of squares of a numeric vector.
The program should work on a zero-length vector (with an answer of 0).
Related task
Mean
| #Unix_shell | Unix shell | $ cat toto
1
2
4
8
16
$ cat toto toto | paste -sd*
1*2*4*8*16*1*2*4*8*16
$ cat toto toto | paste -sd* | bc -l
1048576
| Give a code snippet in #Unix_shell
Task
Write a program to find the sum of squares of a numeric vector.
The program should work on a zero-length vector (with an answer of 0).
Related task
Mean
| christopher/rosetta-code | |
http://rosettacode.org/wiki/Perfect_numbers | Perfect numbers | Write a function which says whether a number is perfect.
A perfect number is a positive integer that is the sum of its proper positive divisors excluding the number itself.
Equivalently, a perfect number is a number that is half the sum of all of its positive divisors (including itself).
Note: The faster Luca... | #Seed7 | Seed7 | $ include "seed7_05.s7i";
const func boolean: isPerfect (in integer: n) is func
result
var boolean: isPerfect is FALSE;
local
var integer: i is 0;
var integer: sum is 1;
var integer: q is 0;
begin
for i range 2 to sqrt(n) do
if n rem i = 0 then
sum +:= i;
q := n div i;
... | Give a code snippet in #Seed7
Write a function which says whether a number is perfect.
A perfect number is a positive integer that is the sum of its proper positive divisors excluding the number itself.
Equivalently, a perfect number is a number that is half the sum of all of its positive divisors (including itself... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Empty_string | Empty string | Languages may have features for dealing specifically with empty strings
(those containing no characters).
Task
Demonstrate how to assign an empty string to a variable.
Demonstrate how to check that a string is empty.
Demonstrate how to check that a string is not empty.
Other tasks related to string oper... | #Run_BASIC | Run BASIC | var$ = ""
' --------------
'empty string
' -------------
if var$="" then print "String is Empty"
if len(var$)=0 then print "String is Empty"
' -------------
'not empty string
' -------------
if var$<>"" then print "String Not empty."
if len(var$)>0 then print "String Not empty." | Give a code snippet in #Run_BASIC
Languages may have features for dealing specifically with empty strings
(those containing no characters).
Task
Demonstrate how to assign an empty string to a variable.
Demonstrate how to check that a string is empty.
Demonstrate how to check that a string is not empty.
... | christopher/rosetta-code |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.