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/Shortest_common_supersequence | Shortest common supersequence | The shortest common supersequence is a problem closely related to the longest common subsequence, which you can use as an external function for this task.
Task
Given two strings
u
{\displaystyle u}
and
v
{\displaystyle v}
, find the shortest possible sequence
s
{\displaystyle s}
, whic... | #Wren | Wren | var lcs // recursive
lcs = Fn.new { |x, y|
if (x.count == 0 || y.count == 0) return ""
var x1 = x[0...-1]
var y1 = y[0...-1]
if (x[-1] == y[-1]) return lcs.call(x1, y1) + x[-1]
var x2 = lcs.call(x, y1)
var y2 = lcs.call(x1, y)
return (x2.count > y2.count) ? x2 : y2
}
var scs = Fn.new { |u,... | Give a code snippet in #Wren
The shortest common supersequence is a problem closely related to the longest common subsequence, which you can use as an external function for this task.
Task
Given two strings
u
{\displaystyle u}
and
v
{\displaystyle v}
, find the shortest possible sequence
... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Empty_program | Empty program | Task
Create the simplest possible program that is still considered "correct."
| #Verilog | Verilog | module main;
endmodule | Give a code snippet in #Verilog
Task
Create the simplest possible program that is still considered "correct."
| christopher/rosetta-code | |
http://rosettacode.org/wiki/Repeat_a_string | Repeat a string | Take a string and repeat it some number of times.
Example: repeat("ha", 5) => "hahahahaha"
If there is a simpler/more efficient way to repeat a single “character” (i.e. creating a string filled with a certain character), you might want to show that as well (i.e. repeat-char("*", 5) => "*****").
Other tasks re... | #NetRexx | NetRexx | /* NetRexx */
ha5 = 'ha'.copies(5)
| Give a code snippet in #NetRexx
Take a string and repeat it some number of times.
Example: repeat("ha", 5) => "hahahahaha"
If there is a simpler/more efficient way to repeat a single “character” (i.e. creating a string filled with a certain character), you might want to show that as well (i.e. repeat-char("*", 5... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Hello_world/Text | Hello world/Text | Hello world/Text is part of Short Circuit's Console Program Basics selection.
Task
Display the string Hello world! on a text console.
Related tasks
Hello world/Graphical
Hello world/Line Printer
Hello world/Newbie
Hello world/Newline omission
Hello world/Standard error
Hello world/Web server
| #TestML | TestML | %TestML 0.1.0
Print("Hello world!") | Give a code snippet in #TestML
Hello world/Text is part of Short Circuit's Console Program Basics selection.
Task
Display the string Hello world! on a text console.
Related tasks
Hello world/Graphical
Hello world/Line Printer
Hello world/Newbie
Hello world/Newline omission
Hello world/Standard error
... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Delegates | Delegates | A delegate is a helper object used by another object. The delegator may send the delegate certain messages, and provide a default implementation when there is no delegate or the delegate does not respond to a message. This pattern is heavily used in Cocoa framework on Mac OS X. See also wp:Delegation pattern.
Objects ... | #JavaScript | JavaScript | function Delegator() {
this.delegate = null ;
this.operation = function(){
if(this.delegate && typeof(this.delegate.thing) == 'function')
return this.delegate.thing() ;
return 'default implementation' ;
}
}
function Delegate() {
this.thing = function(){
return 'Delegate Implementation' ;
}... | Give a code snippet in #JavaScript
A delegate is a helper object used by another object. The delegator may send the delegate certain messages, and provide a default implementation when there is no delegate or the delegate does not respond to a message. This pattern is heavily used in Cocoa framework on Mac OS X. See a... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Sum_of_a_series | Sum of a series | Compute the nth term of a series, i.e. the sum of the n first terms of the corresponding sequence.
Informally this value, or its limit when n tends to infinity, is also called the sum of the series, thus the title of this task.
For this task, use:
S
n
=
∑
k
=
1
n
1
k
2
{\displa... | #Smalltalk | Smalltalk | ( (1 to: 1000) fold: [:sum :aNumber |
sum + (aNumber squared reciprocal) ] ) asFloat displayNl. | Give a code snippet in #Smalltalk
Compute the nth term of a series, i.e. the sum of the n first terms of the corresponding sequence.
Informally this value, or its limit when n tends to infinity, is also called the sum of the series, thus the title of this task.
For this task, use:
S
n
=
∑
k... | 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... | #Phix | Phix | with javascript_semantics
enum NAME, METHOD
procedure me_t()
puts(1,"I is a T\n")
end procedure
procedure me_s()
puts(1,"I is an S\n")
end procedure
type T(object o)
-- as o[METHOD] can be overidden, don't verify it (as in test for me_t)!
return sequence(o) and length(o)=2 and string(o[NAME]) and int... | Give a code snippet in #Phix
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 ... | 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... | #Erlang | Erlang |
-module( n_queens ).
-export( [display/1, solve/1, task/0] ).
display( Board ) ->
%% Queens are in the positions in the Board list.
%% Top left corner is {1, 1}, Bottom right is {N, N}. There is a queen in the max column.
N = lists:max( [X || {X, _Y} <- Board] ),
[display_row(Y, N, Board) || Y <- lists:seq(1,... | Give a code snippet in #Erlang
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 ... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Combinations_and_permutations | Combinations and permutations |
This page uses content from Wikipedia. The original article was at Combination. 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)
This page uses content from Wikipedia. The original article was at P... | #Sidef | Sidef | func P(n, k) { n! / ((n-k)!) }
func C(n, k) { binomial(n, k) }
class Logarithm(value) {
method to_s {
var e = int(value/10.log)
"%.8fE%+d" % (exp(value - e*10.log), e)
}
}
func lstirling(n) {
n < 10 ? (lstirling(n+1) - log(n+1))
: (0.5*log(2*Num.pi*n) + n*log(n/Num.e + 1/(12*N... | Give a code snippet in #Sidef
This page uses content from Wikipedia. The original article was at Combination. 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)
This page uses content from Wikipedia... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Greatest_element_of_a_list | Greatest element of a list | Task
Create a function that returns the maximum value in a provided set of values,
where the number of values may not be known until run-time.
| #Efene | Efene | list_max = fn ([Head:Rest]) {
list_max(Rest, Head)
}
list_max = fn ([], Res) {
Res
}
fn ([Head:Rest], Max) when Head > Max {
list_max(Rest, Head)
}
fn ([_Head:Rest], Max) {
list_max(Rest, Max)
}
list_max1 = fn ([H:T]) {
lists.foldl(fn erlang.max:2, H, T)
}
@public
run = fn () {
io.format("~p~n", [... | Give a code snippet in #Efene
Task
Create a function that returns the maximum value in a provided set of values,
where the number of values may not be known until run-time.
| christopher/rosetta-code | |
http://rosettacode.org/wiki/Digital_root | Digital root | The digital root,
X
{\displaystyle X}
, of a number,
n
{\displaystyle n}
, is calculated:
find
X
{\displaystyle X}
as the sum of the digits of
n
{\displaystyle n}
find a new
X
{\displaystyle X}
by summing the digits of
X
{\displaystyle X}
, repeating until
X
{\displ... | #Erlang | Erlang | -module( digital_root ).
-export( [task/0] ).
task() ->
Ns = [N || N <- [627615, 39390, 588225, 393900588225]],
Persistances = [persistance_root(X) || X <- Ns],
[io:fwrite("~p has additive persistence ~p and digital root of ~p~n", [X, Y, Z]) || {X, {Y, Z}} <- lists:zip(Ns, Persistances)].
persistanc... | Give a code snippet in #Erlang
The digital root,
X
{\displaystyle X}
, of a number,
n
{\displaystyle n}
, is calculated:
find
X
{\displaystyle X}
as the sum of the digits of
n
{\displaystyle n}
find a new
X
{\displaystyle X}
by summing the digits of
X
{\displaystyle X}
,... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Knapsack_problem/Continuous | Knapsack problem/Continuous |
A thief burgles a butcher's shop, where he can select from some items.
The thief knows the weights and prices of each items. Because he has a knapsack with 15 kg maximal capacity, he wants to select the items such that he would have his profit maximized. He may cut the items; the item has a reduced price after... | #Fortran | Fortran | program KNAPSACK_CONTINUOUS
implicit none
real, parameter :: maxweight = 15.0
real :: total_weight = 0, total_value = 0, frac
integer :: i, j
type Item
character(7) :: name
real :: weight
real :: value
end type Item
type(Item) :: items(9), temp
items(1) = Item("beef", 3.8, 36.0)
... | Give a code snippet in #Fortran
A thief burgles a butcher's shop, where he can select from some items.
The thief knows the weights and prices of each items. Because he has a knapsack with 15 kg maximal capacity, he wants to select the items such that he would have his profit maximized. He may cut the items; t... | 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... | #C.2B.2B | C++ | #include <algorithm>
#include <string>
#include <cctype>
/// \brief in-place convert string to upper case
/// \return ref to transformed string
void str_toupper(std::string &str) {
std::transform(str.begin(),
str.end(),
str.begin(),
(int(*)(int)) std::toupper);
}... | Give a code snippet in #C.2B.2B
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/Stair-climbing_puzzle | Stair-climbing puzzle | From Chung-Chieh Shan (LtU):
Your stair-climbing robot has a very simple low-level API: the "step" function takes no argument and attempts to climb one step as a side effect. Unfortunately, sometimes the attempt fails and the robot clumsily falls one step instead. The "step" function detects what happens and returns a... | #R | R | step <- function() {
success <- runif(1) > p
## Requires that the "robot" is a variable named "level"
level <<- level - 1 + (2 * success)
success
} | Give a code snippet in #R
From Chung-Chieh Shan (LtU):
Your stair-climbing robot has a very simple low-level API: the "step" function takes no argument and attempts to climb one step as a side effect. Unfortunately, sometimes the attempt fails and the robot clumsily falls one step instead. The "step" function detects... | christopher/rosetta-code | |
http://rosettacode.org/wiki/One-dimensional_cellular_automata | One-dimensional cellular automata | Assume an array of cells with an initial distribution of live and dead cells,
and imaginary cells off the end of the array having fixed values.
Cells in the next generation of the array are calculated based on the value of the cell and its left and right nearest neighbours in the current generation.
If, in the follow... | #Vedit_macro_language | Vedit macro language | IT("Gen 0: ..###.##.#.#.#.#..#.....") // initial pattern
#9 = Cur_Col
for (#8 = 1; #8 < 10; #8++) { // 10 generations
Goto_Col(7)
Reg_Empty(20)
while (Cur_Col < #9-1) {
if (Match("|{##|!#,#.#,|!###}")==0) {
Reg_Set(20, "#", APPEND)
} else {
Reg_Set(... | Give a code snippet in #Vedit_macro_language
Assume an array of cells with an initial distribution of live and dead cells,
and imaginary cells off the end of the array having fixed values.
Cells in the next generation of the array are calculated based on the value of the cell and its left and right nearest neighbours... | christopher/rosetta-code | |
http://rosettacode.org/wiki/FizzBuzz | FizzBuzz | Task
Write a program that prints the integers from 1 to 100 (inclusive).
But:
for multiples of three, print Fizz (instead of the number)
for multiples of five, print Buzz (instead of the number)
for multiples of both three and five, print FizzBuzz (instead of the number)
... | #NewtonScript | NewtonScript | for i := 1 to 100 do
begin
if i mod 15 = 0 then
print("FizzBuzz")
else if i mod 3 = 0 then
print("Fizz")
else if i mod 5 = 0 then
print("Buzz")
else
print(i);
print("\n")
end | Give a code snippet in #NewtonScript
Task
Write a program that prints the integers from 1 to 100 (inclusive).
But:
for multiples of three, print Fizz (instead of the number)
for multiples of five, print Buzz (instead of the number)
for multiples of both three and five, print F... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Evolutionary_algorithm | Evolutionary algorithm | Starting with:
The target string: "METHINKS IT IS LIKE A WEASEL".
An array of random characters chosen from the set of upper-case letters together with the space, and of the same length as the target string. (Call it the parent).
A fitness function that computes the ‘closeness’ of its argument to the target string.... | #PicoLisp | PicoLisp | (load "@lib/simul.l")
(setq *Target (chop "METHINKS IT IS LIKE A WEASEL"))
# Generate random character
(de randChar ()
(if (=0 (rand 0 26))
" "
(char (rand `(char "A") `(char "Z"))) ) )
# Fitness function (Hamming distance)
(de fitness (A)
(cnt = A *Target) )
# Genetic algorithm
(gen
(make ... | Give a code snippet in #PicoLisp
Starting with:
The target string: "METHINKS IT IS LIKE A WEASEL".
An array of random characters chosen from the set of upper-case letters together with the space, and of the same length as the target string. (Call it the parent).
A fitness function that computes the ‘closeness’ of ... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Sieve_of_Eratosthenes | Sieve of Eratosthenes | This task has been clarified. Its programming examples are in need of review to ensure that they still fit the requirements of the task.
The Sieve of Eratosthenes is a simple algorithm that finds the prime numbers up to a given integer.
Task
Implement the Sieve of Eratosthenes algorithm, with the only allowed... | #Erlang | Erlang |
-module( sieve_of_eratosthenes ).
-export( [primes_upto/1] ).
primes_upto( N ) ->
Ns = lists:seq( 2, N ),
Dict = dict:from_list( [{X, potential_prime} || X <- Ns] ),
{Upto_sqrt_ns, _T} = lists:split( erlang:round(math:sqrt(N)), Ns ),
{N, Prime_dict} = lists:foldl( fun find_prime/2, {N, Dict}, Upto_sqrt_ns ),
... | Give a code snippet in #Erlang
This task has been clarified. Its programming examples are in need of review to ensure that they still fit the requirements of the task.
The Sieve of Eratosthenes is a simple algorithm that finds the prime numbers up to a given integer.
Task
Implement the Sieve of Eratosthenes ... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Square_but_not_cube | Square but not cube | Task
Show the first 30 positive integers which are squares but not cubes of such integers.
Optionally, show also the first 3 positive integers which are both squares and cubes, and mark them as such.
| #dc | dc |
[n = # of non-cube squares found; we stop when it hits 30]sz
[b = # found that are both squares and cubes]sz
0 d sn sb
[c = current cube, s = current square,
r = current cube root, q = current square root,
f = "first" flag, to control comma delimiting]sz
1 d sc d ss d sq d sr sf
[M = main loop]sz
[
lq d... | Give a code snippet in #dc
Task
Show the first 30 positive integers which are squares but not cubes of such integers.
Optionally, show also the first 3 positive integers which are both squares and cubes, and mark them as such.
| christopher/rosetta-code | |
http://rosettacode.org/wiki/Even_or_odd | Even or odd | Task
Test whether an integer is even or odd.
There is more than one way to solve this task:
Use the even and odd predicates, if the language provides them.
Check the least significant digit. With binary integers, i bitwise-and 1 equals 0 iff i is even, or equals 1 iff i is odd.
Divide i by 2. The remainder equals... | #Kotlin | Kotlin | // version 1.0.5-2
fun main(args: Array<String>) {
while (true) {
print("Enter an integer or 0 to finish : ")
val n = readLine()!!.toInt()
when {
n == 0 -> return
n % 2 == 0 -> println("Your number is even")
else -> println("Your number is odd"... | Give a code snippet in #Kotlin
Task
Test whether an integer is even or odd.
There is more than one way to solve this task:
Use the even and odd predicates, if the language provides them.
Check the least significant digit. With binary integers, i bitwise-and 1 equals 0 iff i is even, or equals 1 iff i is odd.
Div... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Variable_size/Get | Variable size/Get | Demonstrate how to get the size of a variable.
See also: Host introspection
| #Ring | Ring |
list1 = list(2)
list2 = list(4)
list3 = list(6)
list4 = list(7)
list5 = list(5)
see "Size of list1 is : " + len(list1) + nl
see "Size of list2 is : " + len(list2) + nl
see "Size of list3 is : " + len(list3) + nl
see "Size of list4 is : " + len(list4) + nl
see "Size of list5 is : " + len(list5) + nl
| Give a code snippet in #Ring
Demonstrate how to get the size of a variable.
See also: Host introspection
| christopher/rosetta-code | |
http://rosettacode.org/wiki/2048 | 2048 | Task
Implement a 2D sliding block puzzle game where blocks with numbers are combined to add their values.
Rules of the game
The rules are that on each turn the player must choose a direction (up, down, left or right).
All tiles move as far as possible in that direction, some move more than others.
Two ... | #Ruby | Ruby |
#!/usr/bin/ruby
require 'io/console'
class Board
def initialize size=4, win_limit=2048, cell_width = 6
@size = size; @cw = cell_width; @win_limit = win_limit
@board = Array.new(size) {Array.new(size, 0)}
@moved = true; @score = 0; @no_more_moves = false
spawn
end
def draw
print "\n\n" ... | Give a code snippet in #Ruby
Task
Implement a 2D sliding block puzzle game where blocks with numbers are combined to add their values.
Rules of the game
The rules are that on each turn the player must choose a direction (up, down, left or right).
All tiles move as far as possible in that direction, some m... | 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... | #Groovy | Groovy | def asCompassPoint(angle) {
def cardinalDirections = ["north", "east", "south", "west"]
int index = Math.floor(angle / 11.25 + 0.5)
int cardinalIndex = (index / 8)
def c1 = cardinalDirections[cardinalIndex % 4]
def c2 = cardinalDirections[(cardinalIndex + 1) % 4]
def c3 = (cardinalIndex == 0... | Give a code snippet in #Groovy
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 d... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Best_shuffle | Best shuffle | Task
Shuffle the characters of a string in such a way that as many of the character values are in a different position as possible.
A shuffle that produces a randomized result among the best choices is to be preferred. A deterministic approach that produces the same sequence every time is acceptable as an alternative... | #C | C | #include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <assert.h>
#include <limits.h>
#define DEBUG
void best_shuffle(const char* txt, char* result) {
const size_t len = strlen(txt);
if (len == 0)
return;
#ifdef DEBUG
// txt and result must have the same length
assert(len == s... | Give a code snippet in #C
Task
Shuffle the characters of a string in such a way that as many of the character values are in a different position as possible.
A shuffle that produces a randomized result among the best choices is to be preferred. A deterministic approach that produces the same sequence every time is a... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Multi-dimensional_array | Multi-dimensional array | For the purposes of this task, the actual memory layout or access method of this data structure is not mandated.
It is enough to:
State the number and extent of each index to the array.
Provide specific, ordered, integer indices for all dimensions of the array together with a new value to update the indexed value.
... | #Mathematica_.2F_Wolfram_Language | Mathematica / Wolfram Language | a = ConstantArray[0, {2, 3, 4, 5}]
a[[1, 2, 3, 4]] = 15;
a[[1, 2, 3, 4]]
a
a[[2, 2]] = 8;
a | Give a code snippet in #Mathematica_.2F_Wolfram_Language
For the purposes of this task, the actual memory layout or access method of this data structure is not mandated.
It is enough to:
State the number and extent of each index to the array.
Provide specific, ordered, integer indices for all dimensions of the arr... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Phrase_reversals | Phrase reversals | Task
Given a string of space separated words containing the following phrase:
rosetta code phrase reversal
Reverse the characters of the string.
Reverse the characters of each individual word in the string, maintaining original word order within the string.
Reverse the order of each word of the string, maintaini... | #ALGOL_68 | ALGOL 68 | # reverses the characters in str from start pos to end pos #
PROC in place reverse = ( REF STRING str, INT start pos, INT end pos )VOID:
BEGIN
INT fpos := start pos, epos := end pos;
WHILE fpos < epos
DO
CHAR c := str[ fpos ];
str[ fpos ] := str... | Give a code snippet in #ALGOL_68
Task
Given a string of space separated words containing the following phrase:
rosetta code phrase reversal
Reverse the characters of the string.
Reverse the characters of each individual word in the string, maintaining original word order within the string.
Reverse the order of ... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Reverse_a_string | Reverse a string | Task
Take a string and reverse it.
For example, "asdf" becomes "fdsa".
Extra credit
Preserve Unicode combining characters.
For example, "as⃝df̅" becomes "f̅ds⃝a", not "̅fd⃝sa".
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
... | #AWK | AWK | function reverse(s)
{
p = ""
for(i=length(s); i > 0; i--) { p = p substr(s, i, 1) }
return p
}
BEGIN {
print reverse("edoCattesoR")
} | Give a code snippet in #AWK
Task
Take a string and reverse it.
For example, "asdf" becomes "fdsa".
Extra credit
Preserve Unicode combining characters.
For example, "as⃝df̅" becomes "f̅ds⃝a", not "̅fd⃝sa".
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty s... | 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.... | #Prolog | Prolog | :- use_module(library(clpfd)).
babbage_(B, B, Sq) :-
B * B #= Sq,
number_chars(Sq, R),
append(_, ['2','6','9','6','9','6'], R).
babbage_(B, R, Sq) :-
N #= B + 1,
babbage_(N, R, Sq).
babbage :-
once(babbage_(1, Num, Square)),
format('lowest number is ~p which squared becomes ~p~n', [Num, Square]). | Give a code snippet in #Prolog
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 Com... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Sorting_algorithms/Permutation_sort | Sorting algorithms/Permutation 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
... | #Python | Python | from itertools import permutations
in_order = lambda s: all(x <= s[i+1] for i,x in enumerate(s[:-1]))
perm_sort = lambda s: (p for p in permutations(s) if in_order(p)).next() | Give a code snippet in #Python
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/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... | #MATLAB | MATLAB | function perf = isPerfect(n)
total = 0;
for k = 1:n-1
if ~mod(n, k)
total = total+k;
end
end
perf = total == n;
end | Give a code snippet in #MATLAB
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/Terminal_control/Clear_the_screen | Terminal control/Clear the screen | Task
Clear the terminal window.
| #Perl | Perl | system('clear') | Give a code snippet in #Perl
Task
Clear the terminal window.
| 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... | #BQN | BQN | _while_ ← {𝔽⍟𝔾∘𝔽_𝕣_𝔾∘𝔽⍟𝔾𝕩}
(⌊∘÷⟜2 •Show) _while_ (>⟜0) 1024 | Give a code snippet in #BQN
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/Additive_primes | Additive primes | Definitions
In mathematics, additive primes are prime numbers for which the sum of their decimal digits are also primes.
Task
Write a program to determine (and show here) all additive primes less than 500.
Optionally, show the number of additive primes.
Also see
the OEIS entry: A046704 additive primes.
... | #Raku | Raku | unit sub MAIN ($limit = 500);
say "{+$_} additive primes < $limit:\n{$_».fmt("%" ~ $limit.chars ~ "d").batch(10).join("\n")}",
with ^$limit .grep: { .is-prime and .comb.sum.is-prime } | Give a code snippet in #Raku
Definitions
In mathematics, additive primes are prime numbers for which the sum of their decimal digits are also primes.
Task
Write a program to determine (and show here) all additive primes less than 500.
Optionally, show the number of additive primes.
Also see
the OEIS entry: ... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Even_or_odd | Even or odd | Task
Test whether an integer is even or odd.
There is more than one way to solve this task:
Use the even and odd predicates, if the language provides them.
Check the least significant digit. With binary integers, i bitwise-and 1 equals 0 iff i is even, or equals 1 iff i is odd.
Divide i by 2. The remainder equals... | #Bracmat | Bracmat | ( ( even
=
. @( !arg
: ?
[-2
( 0
| 2
| 4
| 6
| 8
)
)
)
& (odd=.~(even$!arg))
& ( eventest
=
. out
$ (!arg is (even$!arg&|not) even)
)
& ( oddtest
=
. out
$ (!arg is (odd$!arg&|not) odd)
)... | Give a code snippet in #Bracmat
Task
Test whether an integer is even or odd.
There is more than one way to solve this task:
Use the even and odd predicates, if the language provides them.
Check the least significant digit. With binary integers, i bitwise-and 1 equals 0 iff i is even, or equals 1 iff i is odd.
Di... | christopher/rosetta-code | |
http://rosettacode.org/wiki/String_matching | String matching |
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 |... | #Gambas | Gambas | Public Sub Main()
Dim sString1 As String = "Hello world"
Dim sString2 As String = "Hello"
Print sString1 Begins Left(sString2, 5) 'Determine if the first string starts with second string
If InStr(sString1, sString2) Then Print "True" Else Print "False" 'Determine if the first string cont... | Give a code snippet in #Gambas
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... | christopher/rosetta-code | |
http://rosettacode.org/wiki/MD5 | MD5 | Task
Encode a string using an MD5 algorithm. The algorithm can be found on Wikipedia.
Optionally, validate your implementation by running all of the test values in IETF RFC (1321) for MD5.
Additionally, RFC 1321 provides more precise information on the algorithm than the Wikipedia article.
Warning:... | #S-lang | S-lang | require("chksum");
print(md5sum("The quick brown fox jumped over the lazy dog's back")); | Give a code snippet in #S-lang
Task
Encode a string using an MD5 algorithm. The algorithm can be found on Wikipedia.
Optionally, validate your implementation by running all of the test values in IETF RFC (1321) for MD5.
Additionally, RFC 1321 provides more precise information on the algorithm than the... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Arbitrary-precision_integers_(included) | Arbitrary-precision integers (included) | Using the in-built capabilities of your language, calculate the integer value of:
5
4
3
2
... | #ACL2 | ACL2 | (in-package "ACL2")
(include-book "arithmetic-3/floor-mod/floor-mod" :dir :system)
(set-print-length 0 state)
(defun arbitrary-precision ()
(declare (xargs :mode :program))
(let* ((x (expt 5 (expt 4 (expt 3 2))))
(s (mv-let (col str)
(fmt1-to-string "~xx"
... | Give a code snippet in #ACL2
Using the in-built capabilities of your language, calculate the integer value of:
5
4
3
2
... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Sieve_of_Eratosthenes | Sieve of Eratosthenes | This task has been clarified. Its programming examples are in need of review to ensure that they still fit the requirements of the task.
The Sieve of Eratosthenes is a simple algorithm that finds the prime numbers up to a given integer.
Task
Implement the Sieve of Eratosthenes algorithm, with the only allowed... | #Befunge | Befunge | 2>:3g" "-!v\ g30 <
|!`"O":+1_:.:03p>03g+:"O"`|
@ ^ p3\" ":<
2 234567890123456789012345678901234567890123456789012345678901234567890123456789
| Give a code snippet in #Befunge
This task has been clarified. Its programming examples are in need of review to ensure that they still fit the requirements of the task.
The Sieve of Eratosthenes is a simple algorithm that finds the prime numbers up to a given integer.
Task
Implement the Sieve of Eratosthenes ... | 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
| #F.C5.8Drmul.C3.A6 | Fōrmulæ | # Just multiplying a vector by itself yields the sum of squares (it's an inner product)
# It's necessary to check for the empty vector though
SumSq := function(v)
if Size(v) = 0 then
return 0;
else
return v*v;
fi;
end; | Give a code snippet in #F.C5.8Drmul.C3.A6
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/Narcissistic_decimal_number | Narcissistic decimal number | A Narcissistic decimal number is a non-negative integer,
n
{\displaystyle n}
, that is equal to the sum of the
m
{\displaystyle m}
-th powers of each of the digits in the decimal representation of
n
{\displaystyle n}
, where
m
{\displaystyle m}
is the number of digits in... | #REXX | REXX | /*REXX program generates and displays a number of narcissistic (Armstrong) numbers. */
numeric digits 39 /*be able to handle largest Armstrong #*/
parse arg N . /*obtain optional argument from the CL.*/
if N=='' | N=="," then N=25 ... | Give a code snippet in #REXX
A Narcissistic decimal number is a non-negative integer,
n
{\displaystyle n}
, that is equal to the sum of the
m
{\displaystyle m}
-th powers of each of the digits in the decimal representation of
n
{\displaystyle n}
, where
m
{\displaystyle m}
... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Draw_a_cuboid | Draw a cuboid | Task
Draw a cuboid with relative dimensions of 2 × 3 × 4.
The cuboid can be represented graphically, or in ASCII art, depending on the language capabilities.
To fulfill the criteria of being a cuboid, three faces must be visible.
Either static or rotational projection is acceptable for this task.
R... | #FreeBASIC | FreeBASIC | #include once "GL/gl.bi"
#include once "GL/glu.bi"
dim rquad as single
screen 18, 16, , 2
glViewport 0, 0, 640, 480 '' Reset The Current Viewport
glMatrixMode GL_PROJECTION '' Select The Projection Matrix
glLoadIdentity '' Reset The Projecti... | Give a code snippet in #FreeBASIC
Task
Draw a cuboid with relative dimensions of 2 × 3 × 4.
The cuboid can be represented graphically, or in ASCII art, depending on the language capabilities.
To fulfill the criteria of being a cuboid, three faces must be visible.
Either static or rotational projectio... | christopher/rosetta-code | |
http://rosettacode.org/wiki/User_input/Text | User input/Text | User input/Text is part of Short Circuit's Console Program Basics selection.
Task
Input a string and the integer 75000 from the text console.
See also: User input/Graphical
| #Bracmat | Bracmat | ( doit
= out'"Enter a string"
& get':?mystring
& whl
' ( out'"Enter a number"
& get':?mynumber
& !mynumber:~#
& out'"I said:\"a number\"!"
)
& out$(mystring is !mystring \nmynumber is !mynumber \n)
); | Give a code snippet in #Bracmat
User input/Text is part of Short Circuit's Console Program Basics selection.
Task
Input a string and the integer 75000 from the text console.
See also: User input/Graphical
| 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... | #F.23 | F# | let rec loop n = if n > 0 then printf "%d " n; loop (n / 2)
loop 1024 | Give a code snippet in #F.23
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/Leonardo_numbers | Leonardo numbers |
Leonardo numbers are also known as the Leonardo series.
The Leonardo numbers are a sequence of numbers defined by:
L(0) = 1 [1st equation]
L(1) = 1 [2nd equation]
L(n) = L(n-1) + L(n-2) + 1 ... | #Raku | Raku | sub 𝑳 ( $𝑳0 = 1, $𝑳1 = 1, $𝑳add = 1 ) { $𝑳0, $𝑳1, { $^n2 + $^n1 + $𝑳add } ... * }
# Part 1
say "The first 25 Leonardo numbers:";
put 𝑳()[^25];
# Part 2
say "\nThe first 25 numbers using 𝑳0 of 0, 𝑳1 of 1, and adder of 0:";
put 𝑳( 0, 1, 0 )[^25]; | Give a code snippet in #Raku
Leonardo numbers are also known as the Leonardo series.
The Leonardo numbers are a sequence of numbers defined by:
L(0) = 1 [1st equation]
L(1) = 1 [2nd equation]
L(n) = ... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Roman_numerals/Decode | Roman numerals/Decode | Task
Create a function that takes a Roman numeral as its argument and returns its value as a numeric decimal integer.
You don't need to validate the form of the Roman numeral.
Modern Roman numerals are written by expressing each decimal digit of the number to be encoded separately,
starting with the leftmost decima... | #Nanoquery | Nanoquery | def decodeSingle(letter)
if letter = "M"
return 1000
else if letter = "D"
return 500
else if letter = "C"
return 100
else if letter = "L"
return 50
else if letter = "X"
return 10
else if letter = "V"
return 5
else if letter = "I"
return 1
else
return 0
end
end
def decode(roman)
result = 0
... | Give a code snippet in #Nanoquery
Task
Create a function that takes a Roman numeral as its argument and returns its value as a numeric decimal integer.
You don't need to validate the form of the Roman numeral.
Modern Roman numerals are written by expressing each decimal digit of the number to be encoded separately,... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Logical_operations | Logical operations |
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 |... | #Retro | Retro | : .bool ( f- ) [ "true" ] [ "false" ] if puts cr ;
: logic ( ab- )
"\na = " puts over .bool "b = " puts dup .bool
"\na and b = " puts 2dup and .bool
"\na or b = " puts over or .bool
"\nnot a = " puts not .bool ; | Give a code snippet in #Retro
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
... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Sudoku | Sudoku | Task
Solve a partially filled-in normal 9x9 Sudoku grid and display the result in a human-readable format.
references
Algorithmics of Sudoku may help implement this.
Python Sudoku Solver Computerphile video.
| #XPL0 | XPL0 | code ChOut=8, CrLf=9, IntOut=11, Text=12;
proc Show(X);
char X;
int I, J;
[for I:= 0 to 8 do
[if rem(I/3) = 0 then CrLf(0);
for J:= 0 to 8 do
[if rem(J/3) = 0 then ChOut(0, ^ );
ChOut(0, ^ ); IntOut(0, X(0));
X:= X+1;
];
... | Give a code snippet in #XPL0
Task
Solve a partially filled-in normal 9x9 Sudoku grid and display the result in a human-readable format.
references
Algorithmics of Sudoku may help implement this.
Python Sudoku Solver Computerphile video.
| christopher/rosetta-code | |
http://rosettacode.org/wiki/Primality_by_trial_division | Primality by trial division | Task
Write a boolean function that tells whether a given integer is prime.
Remember that 1 and all non-positive numbers are not prime.
Use trial division.
Even numbers greater than 2 may be eliminated right away.
A loop from 3 to √ n will suffice, but other loops are allowed.
Related tasks
... | #Picat | Picat | is_prime1(N) =>
if N == 2 then
true
elseif N <= 1 ; N mod 2 == 0 then
false
else
foreach(I in 3..2..ceiling(sqrt(N)))
N mod I > 0
end
end. | Give a code snippet in #Picat
Task
Write a boolean function that tells whether a given integer is prime.
Remember that 1 and all non-positive numbers are not prime.
Use trial division.
Even numbers greater than 2 may be eliminated right away.
A loop from 3 to √ n will suffice, but other loops... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Nim_game | Nim game | Nim game
You are encouraged to solve this task according to the task description, using any language you may know.
Nim is a simple game where the second player ─── if they know the trick ─── will always win.
The game has only 3 rules:
start with 12 tokens
each player takes 1, 2, or 3 tokens in tur... | #FreeBASIC | FreeBASIC | dim as ubyte heap=12, take
while heap > 0
print using "There are ## tokens remaining. How many would you like to take?"; heap
input take
while take=0 orelse take>3
print "You must take 1, 2, or 3 tokens. How many would you like to take?"
input take
wend
print using "On my turn I ... | Give a code snippet in #FreeBASIC
Nim game
You are encouraged to solve this task according to the task description, using any language you may know.
Nim is a simple game where the second player ─── if they know the trick ─── will always win.
The game has only 3 rules:
start with 12 tokens
each player ta... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Subtractive_generator | Subtractive generator | A subtractive generator calculates a sequence of random numbers, where each number is congruent to the subtraction of two previous numbers from the sequence.
The formula is
r
n
=
r
(
n
−
i
)
−
r
(
n
−
j
)
(
mod
m
)
{\displaystyle r_{n}=r_{(n-i)}-r_{(n-j)}{\pmod {m}}}
for some fixed values of... | #C.23 | C# |
public class SubtractiveGenerator {
public static int MAX = 1000000000;
private int[] state;
private int pos;
private int mod(int n) {
return ((n % MAX) + MAX) % MAX;
}
public SubtractiveGenerator(int seed) {
state = new int[55];
int[] temp = new int[55];
... | Give a code snippet in #C.23
A subtractive generator calculates a sequence of random numbers, where each number is congruent to the subtraction of two previous numbers from the sequence.
The formula is
r
n
=
r
(
n
−
i
)
−
r
(
n
−
j
)
(
mod
m
)
{\displaystyle r_{n}=r_{(n-i)}-r_{(n-j)}{\pmod {m... | christopher/rosetta-code | |
http://rosettacode.org/wiki/2048 | 2048 | Task
Implement a 2D sliding block puzzle game where blocks with numbers are combined to add their values.
Rules of the game
The rules are that on each turn the player must choose a direction (up, down, left or right).
All tiles move as far as possible in that direction, some move more than others.
Two ... | #Haskell | Haskell | import System.IO
import Data.List
import Data.Maybe
import Control.Monad
import Data.Random
import Data.Random.Distribution.Categorical
import System.Console.ANSI
import Control.Lens
-- Logic
-- probability to get a 4
prob4 :: Double
prob4 = 0.1
type Position = [[Int]]
combine, shift :: [Int]->[Int]
combine (x:... | Give a code snippet in #Haskell
Task
Implement a 2D sliding block puzzle game where blocks with numbers are combined to add their values.
Rules of the game
The rules are that on each turn the player must choose a direction (up, down, left or right).
All tiles move as far as possible in that direction, som... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Ackermann_function | Ackermann function | The Ackermann function is a classic example of a recursive function, notable especially because it is not a primitive recursive function. It grows very quickly in value, as does the size of its call tree.
The Ackermann function is usually defined as follows:
A
(
m
,
n
)
=
{
n
+
1
if
m
=
0
A
(
m
... | #Dylan | Dylan | define method ack(m == 0, n :: <integer>)
n + 1
end;
define method ack(m :: <integer>, n :: <integer>)
ack(m - 1, if (n == 0) 1 else ack(m, n - 1) end)
end; | Give a code snippet in #Dylan
The Ackermann function is a classic example of a recursive function, notable especially because it is not a primitive recursive function. It grows very quickly in value, as does the size of its call tree.
The Ackermann function is usually defined as follows:
A
(
m
,
n
)
=
{
... | 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... | #Ruby | Ruby | s = ""
s = String.new
s = "any string"; s.clear | Give a code snippet in #Ruby
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.
Othe... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Singly-linked_list/Traversal | Singly-linked list/Traversal | Traverse from the beginning of a singly-linked list to the end.
See also
Array
Associative array: Creation, Iteration
Collections
Compound data type
Doubly-linked list: Definition, Element definition, Element insertion, List Traversal, Element Removal
Linked list
Queue: Definition, Usage
Set
Singly-linked ... | #Elena | Elena |
while(nil != current){
console printLine(current.Item);
current := current.Next
} | Give a code snippet in #Elena
Traverse from the beginning of a singly-linked list to the end.
See also
Array
Associative array: Creation, Iteration
Collections
Compound data type
Doubly-linked list: Definition, Element definition, Element insertion, List Traversal, Element Removal
Linked list
Queue: Definit... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Sort_an_array_of_composite_structures | Sort an array of composite structures |
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
... | #C | C |
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
typedef struct twoStringsStruct {
char * key, *value;
} sTwoStrings;
int ord( char v )
{
static char *dgts = "012345679";
char *cp;
for (cp=dgts; v != *cp; cp++);
return (cp-dgts);
}
int cmprStrgs(const sTwoStrings *s1,const sTwoStrin... | Give a code snippet in #C
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... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Sequence:_smallest_number_greater_than_previous_term_with_exactly_n_divisors | Sequence: smallest number greater than previous term with exactly n divisors | Calculate the sequence where each term an is the smallest natural number greater than the previous term, that has exactly n divisors.
Task
Show here, on this page, at least the first 15 terms of the sequence.
See also
OEIS:A069654
Related tasks
Sequence: smallest number with exactly n divisors
Sequence: nth ... | #Sidef | Sidef | func n_divisors(n, from=1) {
from..Inf -> first_by { .sigma0 == n }
}
with (1) { |from|
say 15.of { from = n_divisors(_+1, from) }
} | Give a code snippet in #Sidef
Calculate the sequence where each term an is the smallest natural number greater than the previous term, that has exactly n divisors.
Task
Show here, on this page, at least the first 15 terms of the sequence.
See also
OEIS:A069654
Related tasks
Sequence: smallest number with exa... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Mutual_recursion | Mutual recursion | Two functions are said to be mutually recursive if the first calls the second,
and in turn the second calls the first.
Write two mutually recursive functions that compute members of the Hofstadter Female and Male sequences defined as:
F
(
0
)
=
1
;
M
(
0
)
=
0
F
(
n
)
=
n
−
M
(
F
(
n
−
1
)
)
,
... | #Ring | Ring |
see "F sequence : "
for i = 0 to 20
see "" + f(i) + " "
next
see nl
see "M sequence : "
for i = 0 to 20
see "" + m(i) + " "
next
func f n
fr = 1
if n != 0 fr = n - m(f(n - 1)) ok
return fr
func m n
mr = 0
if n != 0 mr = n - f(m(n - 1)) ok
return mr
| Give a code snippet in #Ring
Two functions are said to be mutually recursive if the first calls the second,
and in turn the second calls the first.
Write two mutually recursive functions that compute members of the Hofstadter Female and Male sequences defined as:
F
(
0
)
=
1
;
M
(
0
)
=
0
F
(
n
)... | 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... | #Maple | Maple | for i from 10 to 0 by -1 do print(i) end: | Give a code snippet in #Maple
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/Increm... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Rosetta_Code/Fix_code_tags | Rosetta Code/Fix code tags | Task
Fix Rosetta Code deprecated code tags, with these rules:
Change <%s> to <lang %s>
Change </%s> to </lang>
Change <code %s> to <lang %s>
Change </code> to </lang>
Usage
./convert.py < wikisource.txt > converted.txt
| #Phix | Phix | with javascript_semantics
constant ltext = `_div abap actionscript actionscript3 ada apache
applescript apt_sources asm asp autoit avisynth bash basic4gl bf
blitzbasic bnf boo c c_mac caddcl cadlisp cfdg cfm cil cobol cpp
cpp-qt csharp css d delphi diff dos dot eiffel email fortran
freebasic genero gettext glsl gml gnu... | Give a code snippet in #Phix
Task
Fix Rosetta Code deprecated code tags, with these rules:
Change <%s> to <lang %s>
Change </%s> to </lang>
Change <code %s> to <lang %s>
Change </code> to </lang>
Usage
./convert.py < wikisource.txt > converted.txt
| christopher/rosetta-code | |
http://rosettacode.org/wiki/Interactive_programming_(repl) | Interactive programming (repl) | Many language implementations come with an interactive mode.
This is a command-line interpreter that reads lines from the user and evaluates these lines as statements or expressions.
An interactive mode may also be known as a command mode, a read-eval-print loop (REPL), or a shell.
Task
Show how to start this... | #Oz | Oz | declare fun {F As Bs Sep} {Append As Sep|Sep|Bs} end | Give a code snippet in #Oz
Many language implementations come with an interactive mode.
This is a command-line interpreter that reads lines from the user and evaluates these lines as statements or expressions.
An interactive mode may also be known as a command mode, a read-eval-print loop (REPL), or a shell.
... | 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 |... | #ALGOL_W | ALGOL W | begin
% return the factors of n ( n should be >= 1 ) in the array factor %
% the bounds of factor should be 0 :: len (len must be at least 1) %
% the number of factors will be returned in factor( 0 ) %
procedure getFactorsOf ( integer value n
; int... | Give a code snippet in #ALGOL_W
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 Operation... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Pseudo-random_numbers/Splitmix64 | Pseudo-random numbers/Splitmix64 | Splitmix64 is the default pseudo-random number generator algorithm in Java and is included / available in many other languages. It uses a fairly simple algorithm that, though it is considered to be poor for cryptographic purposes, is very fast to calculate, and is "good enough" for many random number needs. It passes s... | #Ada | Ada | with Interfaces; use Interfaces;
package Random_Splitmix64 is
function next_Int return Unsigned_64;
function next_float return Float;
procedure Set_State (Seed : in Unsigned_64);
end Random_Splitmix64; | Give a code snippet in #Ada
Splitmix64 is the default pseudo-random number generator algorithm in Java and is included / available in many other languages. It uses a fairly simple algorithm that, though it is considered to be poor for cryptographic purposes, is very fast to calculate, and is "good enough" for many ran... | 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.
| #Dyalect | Dyalect | func Integer.Double() {
this + this
}
print(8.Double()) | Give a code snippet in #Dyalect
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/Queue/Usage | Queue/Usage |
Data Structure
This illustrates a data structure, a means of storing data within a program.
You may see other such structures in the Data Structures category.
Illustration of FIFO behavior
Task
Create a queue data structure and demonstrate its operations.
(For implementations of queues, see the FIFO task.)
Ope... | #Kotlin | Kotlin | // version 1.1.2
import java.util.*
fun main(args: Array<String>) {
val q: Queue<Int> = ArrayDeque<Int>()
(1..5).forEach { q.add(it) }
println(q)
println("Size of queue = ${q.size}")
print("Removing: ")
(1..3).forEach { print("${q.remove()} ") }
println("\nRemaining in queue: $q")
pr... | Give a code snippet in #Kotlin
Data Structure
This illustrates a data structure, a means of storing data within a program.
You may see other such structures in the Data Structures category.
Illustration of FIFO behavior
Task
Create a queue data structure and demonstrate its operations.
(For implementations of qu... | 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... | #Smalltalk | Smalltalk | "Assign empty string to a variable"
str := ''.
"Check that string is empty"
str isEmpty.
"Check that string is not empty"
str isEmpty not.
"alternatives:"
str notEmpty
str size = 0
str = '' | Give a code snippet in #Smalltalk
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 | |
http://rosettacode.org/wiki/Averages/Pythagorean_means | Averages/Pythagorean means | Task[edit]
Compute all three of the Pythagorean means of the set of integers 1 through 10 (inclusive).
Show that
A
(
x
1
,
…
,
x
n
)
≥
G
(
x
1
,
…
,
x
n
)
≥
H
(
x
1
,
…
,
x
n
)
{\displaystyle A(x_{1},\ldots ,x_{n})\geq G(x_{1},\ldots ,x_{n})\geq H(x_{1},\ldots ,x_{n})}
for this set of p... | #Futhark | Futhark |
fun arithmetic_mean(as: [n]f64): f64 =
reduce (+) 0.0 (map (/f64(n)) as)
fun geometric_mean(as: [n]f64): f64 =
reduce (*) 1.0 (map (**(1.0/f64(n))) as)
fun harmonic_mean(as: [n]f64): f64 =
f64(n) / reduce (+) 0.0 (map (1.0/) as)
fun main(as: [n]f64): (f64,f64,f64) =
(arithmetic_mean as,
geometric_mea... | Give a code snippet in #Futhark
Task[edit]
Compute all three of the Pythagorean means of the set of integers 1 through 10 (inclusive).
Show that
A
(
x
1
,
…
,
x
n
)
≥
G
(
x
1
,
…
,
x
n
)
≥
H
(
x
1
,
…
,
x
n
)
{\displaystyle A(x_{1},\ldots ,x_{n})\geq G(x_{1},\ldots ,x_{n})\geq H(x_{1},\l... | 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... | #S-BASIC | S-BASIC |
rem - return p mod q
function mod(p, q = integer) = integer
end = p - q * (p / q)
rem - return octal representation of n
function oct$(n = integer) = string
var s = string
s = ""
while n > 0 do
begin
s = chr(mod(n,8) + '0') + s
n = n / 8
end
end = s
rem - count in octal until overflow
var i = intege... | Give a code snippet in #S-BASIC
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.... | 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.... | #AppleScript | AppleScript | -- BABBAGE -------------------------------------------------------------------
-- babbage :: Int -> [Int]
on babbage(intTests)
script test
on toSquare(x)
(x * 1000000) + 269696
end toSquare
on |λ|(x)
hasIntRoot(toSquare(x))
end |λ|
end script
s... | Give a code snippet in #AppleScript
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, Electroni... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Currying | Currying |
This page uses content from Wikipedia. The original article was at Currying. 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)
Task
Create a simple demonstrative example of Currying in a specific la... | #Io | Io | curry := method(fn,
a := call evalArgs slice(1)
block(
b := a clone appendSeq(call evalArgs)
performWithArgList("fn", b)
)
)
// example:
increment := curry( method(a,b,a+b), 1 )
increment call(5)
// result => 6 | Give a code snippet in #Io
This page uses content from Wikipedia. The original article was at Currying. 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)
Task
Create a simple demonstrative example ... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Reverse_a_string | Reverse a string | Task
Take a string and reverse it.
For example, "asdf" becomes "fdsa".
Extra credit
Preserve Unicode combining characters.
For example, "as⃝df̅" becomes "f̅ds⃝a", not "̅fd⃝sa".
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
... | #Raven | Raven | "asdf" reverse | Give a code snippet in #Raven
Task
Take a string and reverse it.
For example, "asdf" becomes "fdsa".
Extra credit
Preserve Unicode combining characters.
For example, "as⃝df̅" becomes "f̅ds⃝a", not "̅fd⃝sa".
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Short-circuit_evaluation | Short-circuit evaluation | Control Structures
These are examples of control structures. You may also be interested in:
Conditional structures
Exceptions
Flow-control structures
Loops
Assume functions a and b return boolean values, and further, the execution of function b takes considerable resources without side effects, an... | #Kotlin | Kotlin | // version 1.1.2
fun a(v: Boolean): Boolean {
println("'a' called")
return v
}
fun b(v: Boolean): Boolean {
println("'b' called")
return v
}
fun main(args: Array<String>){
val pairs = arrayOf(Pair(true, true), Pair(true, false), Pair(false, true), Pair(false, false))
for (pair in pairs) {
... | Give a code snippet in #Kotlin
Control Structures
These are examples of control structures. You may also be interested in:
Conditional structures
Exceptions
Flow-control structures
Loops
Assume functions a and b return boolean values, and further, the execution of function b takes considerable re... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Magic_squares_of_odd_order | Magic squares of odd order | A magic square is an NxN square matrix whose numbers (usually integers) consist of consecutive numbers arranged so that the sum of each row and column, and both long (main) diagonals are equal to the same sum (which is called the magic number or magic constant).
The numbers are usually (but not always) t... | #bc | bc | define magic_constant(n) {
return(((n * n + 1) / 2) * n)
}
define print_magic_square(n) {
auto i, x, col, row, len, old_scale
old_scale = scale
scale = 0
len = length(n * n)
print "Magic constant for n=", n, ": ", magic_constant(n), "\n"
for (row = 1; row <= n; row++) {
for (co... | Give a code snippet in #bc
A magic square is an NxN square matrix whose numbers (usually integers) consist of consecutive numbers arranged so that the sum of each row and column, and both long (main) diagonals are equal to the same sum (which is called the magic number or magic constant).
The numbers ar... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Greatest_element_of_a_list | Greatest element of a list | Task
Create a function that returns the maximum value in a provided set of values,
where the number of values may not be known until run-time.
| #Elena | Elena | import extensions;
extension op
{
get Maximal()
{
auto en := cast Enumerator(self.enumerator());
object maximal := nil;
while (en.next())
{
var item := en.get();
if (nil == maximal)
{
maximal := item
}
... | Give a code snippet in #Elena
Task
Create a function that returns the maximum value in a provided set of values,
where the number of values may not be known until run-time.
| christopher/rosetta-code | |
http://rosettacode.org/wiki/Sum_digits_of_an_integer | Sum digits of an integer | Task
Take a Natural Number in a given base and return the sum of its digits:
110 sums to 1
123410 sums to 10
fe16 sums to 29
f0e16 sums to 29
| #BASIC | BASIC | FUNCTION sumDigits(num AS STRING, bas AS LONG) AS LONG
'can handle up to base 36
DIM outp AS LONG
DIM validNums AS STRING, tmp AS LONG, x AS LONG, lennum AS LONG, L0 AS LONG
'ensure num contains only valid characters
validNums = LEFT$("0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ", bas)
lennum = LEN(num... | Give a code snippet in #BASIC
Task
Take a Natural Number in a given base and return the sum of its digits:
110 sums to 1
123410 sums to 10
fe16 sums to 29
f0e16 sums to 29
| 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 ... | #Picat | Picat | go =>
N = 10,
% "direct" test that will fail if not satisfied
N < 14,
% if/then/elseif/else
if N < 14 then
println("less than 14")
elseif N == 14 then
println("is 14")
else
println("not less than 14")
end,
% From Prolog: (condition -> then ; else)
( N < 14 ->
println("less than ... | Give a code snippet in #Picat
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/Superpermutation_minimisation | Superpermutation minimisation | A superpermutation of N different characters is a string consisting of an arrangement of multiple copies of those N different characters in which every permutation of those characters can be found as a substring.
For example, representing the characters as A..Z, using N=2 we choose to use the first two characters 'AB'... | #Perl | Perl | use ntheory qw/forperm/;
for my $len (1..8) {
my($pre, $post, $t) = ("","");
forperm {
$t = join "",@_;
$post .= $t unless index($post ,$t) >= 0;
$pre = $t . $pre unless index($pre, $t) >= 0;
} $len;
printf "%2d: %8d %8d\n", $len, length($pre), length($post);
} | Give a code snippet in #Perl
A superpermutation of N different characters is a string consisting of an arrangement of multiple copies of those N different characters in which every permutation of those characters can be found as a substring.
For example, representing the characters as A..Z, using N=2 we choose to use... | christopher/rosetta-code | |
http://rosettacode.org/wiki/FizzBuzz | FizzBuzz | Task
Write a program that prints the integers from 1 to 100 (inclusive).
But:
for multiples of three, print Fizz (instead of the number)
for multiples of five, print Buzz (instead of the number)
for multiples of both three and five, print FizzBuzz (instead of the number)
... | #MEL | MEL | for($i=1; $i<=100; $i++)
{
if($i % 15 == 0)
print "FizzBuzz\n";
else if ($i % 3 == 0)
print "Fizz\n";
else if ($i % 5 == 0)
print "Buzz\n";
else
print ($i + "\n");
} | Give a code snippet in #MEL
Task
Write a program that prints the integers from 1 to 100 (inclusive).
But:
for multiples of three, print Fizz (instead of the number)
for multiples of five, print Buzz (instead of the number)
for multiples of both three and five, print FizzBuzz ... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Roman_numerals/Decode | Roman numerals/Decode | Task
Create a function that takes a Roman numeral as its argument and returns its value as a numeric decimal integer.
You don't need to validate the form of the Roman numeral.
Modern Roman numerals are written by expressing each decimal digit of the number to be encoded separately,
starting with the leftmost decima... | #Julia | Julia | function parseroman(rnum::AbstractString)
romandigits = Dict('I' => 1, 'V' => 5, 'X' => 10, 'L' => 50,
'C' => 100, 'D' => 500, 'M' => 1000)
mval = accm = 0
for d in reverse(uppercase(rnum))
val = try
romandigits[d]
catch
throw(DomainError())
... | Give a code snippet in #Julia
Task
Create a function that takes a Roman numeral as its argument and returns its value as a numeric decimal integer.
You don't need to validate the form of the Roman numeral.
Modern Roman numerals are written by expressing each decimal digit of the number to be encoded separately,
st... | 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 ... | #C | C | #include <stdio.h>
static char sym[] = "\n\t\\\"";
int main(void) {
const char *code = "#include <stdio.h>%c%cstatic char sym[] = %c%cn%ct%c%c%c%c%c;%c%cint main(void) {%c%cconst char *code = %c%s%c;%c%cprintf(code, sym[0], sym[0], sym[3], sym[2], sym[2], sym[2], sym[2], sym[2], sym[3], sym[3], sym[0], sym[0], sym... | Give a code snippet in #C
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
sel... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Elliptic_curve_arithmetic | Elliptic curve arithmetic | Elliptic curves are sometimes used in cryptography as a way to perform digital signatures.
The purpose of this task is to implement a simplified (without modular arithmetic) version of the elliptic curve arithmetic which is required by the elliptic curve DSA protocol.
In a nutshell, an elliptic curve is a... | #Perl | Perl | package EC;
{
our ($A, $B) = (0, 7);
package EC::Point;
sub new { my $class = shift; bless [ @_ ], $class }
sub zero { bless [], shift }
sub x { shift->[0] }; sub y { shift->[1] };
sub double {
my $self = shift;
return $self unless @$self;
my $L = (3 * $self->x**2) / (2*$... | Give a code snippet in #Perl
Elliptic curves are sometimes used in cryptography as a way to perform digital signatures.
The purpose of this task is to implement a simplified (without modular arithmetic) version of the elliptic curve arithmetic which is required by the elliptic curve DSA protocol.
In a nu... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Bitmap/Read_an_image_through_a_pipe | Bitmap/Read an image through a pipe | This task is the opposite of the PPM conversion through a pipe. In this task, using a delegate tool (like cjpeg, one of the netpbm package, or convert of the ImageMagick package) we read an image file and load it into the data storage type defined here. We can also use the code from Read ppm file, so that we can use PP... | #Python | Python |
"""
Adapted from https://stackoverflow.com/questions/26937143/ppm-to-jpeg-jpg-conversion-for-python-3-4-1
Requires pillow-5.3.0 with Python 3.7.1 32-bit on Windows.
Sample ppm graphics files from http://www.cs.cornell.edu/courses/cs664/2003fa/images/
"""
from PIL import Image
# boxes_1.jpg is the jpg version of b... | Give a code snippet in #Python
This task is the opposite of the PPM conversion through a pipe. In this task, using a delegate tool (like cjpeg, one of the netpbm package, or convert of the ImageMagick package) we read an image file and load it into the data storage type defined here. We can also use the code from Read... | 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... | #F.23 | F# | open System
open System.IO
let cutOut (arr : 'a[]) from n = // confine syntax highlighting confusion'
let slicer = fun i -> if i < from || (from + n) <= i then Some(arr.[i-1]) else None
((Array.choose slicer [| 1 .. arr.Length |]), from + n - arr.Length > 1)
[<EntryPoint>]
let main argv =
let nums = Ar... | Give a code snippet in #F.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/Copy_a_string | Copy a string | This task is about copying a string.
Task
Where it is relevant, distinguish between copying the contents of a string
versus making an additional reference to an existing string.
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
W... | #XPL0 | XPL0 | proc StrCopy(A, B); \Copy string: A --> B
char A, B; \Strings: B must already have enough space "Reserved"
int I; \Beware if strings overlap
for I:= 0 to -1>>1-1 do
[B(I):= A(I);
if A(I) >= $80 then return
];
char S1, S2, S3(13);
[S1:= "Hello, world!"; \S1 now points to ... | Give a code snippet in #XPL0
This task is about copying a string.
Task
Where it is relevant, distinguish between copying the contents of a string
versus making an additional reference to an existing string.
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty st... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Truth_table | Truth table | A truth table is a display of the inputs to, and the output of a Boolean function organized as a table where each row gives one combination of input values and the corresponding value of the function.
Task
Input a Boolean function from the user as a string then calculate and print a formatted truth table for the g... | #11l | 11l | T Symbol
String id
Int lbp
Int nud_bp
Int led_bp
(ASTNode -> ASTNode) nud
((ASTNode, ASTNode) -> ASTNode) led
F set_nud_bp(nud_bp, nud)
.nud_bp = nud_bp
.nud = nud
F set_led_bp(led_bp, led)
.led_bp = led_bp
.led = led
T Var
String name
Int value
F (name)
... | Give a code snippet in #11l
A truth table is a display of the inputs to, and the output of a Boolean function organized as a table where each row gives one combination of input values and the corresponding value of the function.
Task
Input a Boolean function from the user as a string then calculate and print a fo... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Simple_windowed_application | Simple windowed application | Task
Create a window that has:
a label that says "There have been no clicks yet"
a button that says "click me"
Upon clicking the button with the mouse, the label should change and show the number of times the button has been clicked.
| #C | C | #include <stdio.h>
#include <gtk/gtk.h>
const gchar *clickme = "Click Me";
guint counter = 0;
#define MAXLEN 64
void clickedme(GtkButton *o, gpointer d)
{
GtkLabel *l = GTK_LABEL(d);
char nt[MAXLEN];
counter++;
snprintf(nt, MAXLEN, "You clicked me %d times", counter);
gtk_label_set_text(l, nt)... | Give a code snippet in #C
Task
Create a window that has:
a label that says "There have been no clicks yet"
a button that says "click me"
Upon clicking the button with the mouse, the label should change and show the number of times the button has been clicked.
| christopher/rosetta-code | |
http://rosettacode.org/wiki/100_doors | 100 doors | There are 100 doors in a row that are all initially closed.
You make 100 passes by the doors.
The first time through, visit every door and toggle the door (if the door is closed, open it; if it is open, close it).
The second time, only visit every 2nd door (door #2, #4, #6, ...), and toggle it.
The third... | #newLISP | newLISP | (define (status door-num)
(let ((x (int (sqrt door-num))))
(if
(= (* x x) door-num) (string "Door " door-num " Open")
(string "Door " door-num " Closed"))))
(dolist (n (map status (sequence 1 100)))
(println n))
| Give a code snippet in #newLISP
There are 100 doors in a row that are all initially closed.
You make 100 passes by the doors.
The first time through, visit every door and toggle the door (if the door is closed, open it; if it is open, close it).
The second time, only visit every 2nd door (door #2, #4, #6, ... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Knuth%27s_power_tree | Knuth's power tree | (Knuth's power tree is used for computing xn efficiently.)
Task
Compute and show the list of Knuth's power tree integers necessary for the computation of:
xn for any real x and any non-negative integer n.
Then, using those integers, calculate and show the exact values of (at least) the integer po... | #jq | jq | # Input: {p, lvl, path}
def kpath($n):
if $n == 0 then .path=[]
else until( .p[$n|tostring];
.q = []
| reduce .lvl[0][] as $x (.;
kpath($x)
| label $out
| foreach (.path[], null) as $y (.;
if $y == null then .
else (($x + $y)|tos... | Give a code snippet in #jq
(Knuth's power tree is used for computing xn efficiently.)
Task
Compute and show the list of Knuth's power tree integers necessary for the computation of:
xn for any real x and any non-negative integer n.
Then, using those integers, calculate and show the exact values ... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Strip_whitespace_from_a_string/Top_and_tail | Strip whitespace from a string/Top and tail | Task
Demonstrate how to strip leading and trailing whitespace from a string.
The solution should demonstrate how to achieve the following three results:
String with leading whitespace removed
String with trailing whitespace removed
String with both leading and trailing whitespace removed
For the purposes of thi... | #Emacs_Lisp | Emacs Lisp | (string-trim-left " left center right ") ;=> "left center right "
(string-trim-right " left center right ") ;=> " left center right"
(string-trim " left center right ") ;=> "left center right" | Give a code snippet in #Emacs_Lisp
Task
Demonstrate how to strip leading and trailing whitespace from a string.
The solution should demonstrate how to achieve the following three results:
String with leading whitespace removed
String with trailing whitespace removed
String with both leading and trailing whitespa... | 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... | #JavaScript | JavaScript | function fibo(n) {
if (n < 0) { throw "Argument cannot be negative"; }
return (function(n) {
return (n < 2) ? 1 : arguments.callee(n-1) + arguments.callee(n-2);
})(n);
} | Give a code snippet in #JavaScript
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 u... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Nth_root | Nth root | Task
Implement the algorithm to compute the principal nth root
A
n
{\displaystyle {\sqrt[{n}]{A}}}
of a positive real number A, as explained at the Wikipedia page.
| #Delphi | Delphi |
USES
Math;
function NthRoot(A, Precision: Double; n: Integer): Double;
var
x_p, X: Double;
begin
x_p := Sqrt(A);
while Abs(A - Power(x_p, n)) > Precision do
begin
x := (1/n) * (((n-1) * x_p) + (A/(Power(x_p, n - 1))));
x_p := x;
end;
Result := x_p;
end;
| Give a code snippet in #Delphi
Task
Implement the algorithm to compute the principal nth root
A
n
{\displaystyle {\sqrt[{n}]{A}}}
of a positive real number A, as explained at the Wikipedia page.
| christopher/rosetta-code | |
http://rosettacode.org/wiki/Abundant_odd_numbers | Abundant odd numbers | An Abundant number is a number n for which the sum of divisors σ(n) > 2n,
or, equivalently, the sum of proper divisors (or aliquot sum) s(n) > n.
E.G.
12 is abundant, it has the proper divisors 1,2,3,4 & 6 which sum to 16 ( > 12 or n);
or alternately, has the sigma sum of ... | #Quackery | Quackery | [ 0 swap factors witheach + ] is sigmasum ( n --> n )
0 -1 [ 2 +
dup sigmasum
over 2 * over < iff
[ over echo sp
echo cr
dip 1+ ]
else drop
over 25 = until ]
2drop
cr
0 -1
[ 2 + dup sigmasum
over 2 * > if [ dip 1+ ]
ove... | Give a code snippet in #Quackery
An Abundant number is a number n for which the sum of divisors σ(n) > 2n,
or, equivalently, the sum of proper divisors (or aliquot sum) s(n) > n.
E.G.
12 is abundant, it has the proper divisors 1,2,3,4 & 6 which sum to 16 ( > 12 or n);
or al... | 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 |... | #Erlang | Erlang | factors(N) ->
[I || I <- lists:seq(1,trunc(N/2)), N rem I == 0]++[N]. | Give a code snippet in #Erlang
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... | 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
... | #D.C3.A9j.C3.A0_Vu | Déjà Vu | }
for item in [ 1 10 1 :hi :hello :hi :hi ]:
@item
!. keys set{ | Give a code snippet in #D.C3.A9j.C3.A0_Vu
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 sor... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Magic_squares_of_odd_order | Magic squares of odd order | A magic square is an NxN square matrix whose numbers (usually integers) consist of consecutive numbers arranged so that the sum of each row and column, and both long (main) diagonals are equal to the same sum (which is called the magic number or magic constant).
The numbers are usually (but not always) t... | #zkl | zkl | fcn rmod(n,m){ n=n%m; if (n<0) n+=m; n } // Ruby: -5%3-->1
fcn odd_magic_square(n){ //-->list of n*n numbers, row order
if (n.isEven or n <= 0) throw(Exception.ValueError("Need odd positive number"));
[[(i,j); n; n; '{ n*((i+j+1+n/2):rmod(_,n)) + ((i+2*j-5):rmod(_,n)) + 1 }]]
}
T(3, 5, 9).pump(Void,fcn(n){
"... | Give a code snippet in #zkl
A magic square is an NxN square matrix whose numbers (usually integers) consist of consecutive numbers arranged so that the sum of each row and column, and both long (main) diagonals are equal to the same sum (which is called the magic number or magic constant).
The numbers a... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Elementary_cellular_automaton/Infinite_length | Elementary cellular automaton/Infinite length | The purpose of this task is to create a version of an Elementary cellular automaton whose number of cells is only limited by the memory size of the computer.
To be precise, consider the state of the automaton to be made of an infinite number of cells, but with a bounded support. In other words, to describe the state o... | #Kotlin | Kotlin | // version 1.1.51
fun evolve(l: Int, rule: Int) {
println(" Rule #$rule:")
var cells = StringBuilder("*")
for (x in 0 until l) {
addNoCells(cells)
val width = 40 + (cells.length shr 1)
println(cells.padStart(width))
cells = step(cells, rule)
}
}
fun step(cells: String... | Give a code snippet in #Kotlin
The purpose of this task is to create a version of an Elementary cellular automaton whose number of cells is only limited by the memory size of the computer.
To be precise, consider the state of the automaton to be made of an infinite number of cells, but with a bounded support. In othe... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Reflection/List_properties | Reflection/List properties | Task
The goal is to get the properties of an object, as names, values or both.
Some languages support dynamic properties, which in general can only be inspected if a class' public API includes a way of listing them.
| #Python | Python | class Parent(object):
__priv = 'private'
def __init__(self, name):
self.name = name
def __repr__(self):
return '%s(%s)' % (type(self).__name__, self.name)
def doNothing(self):
pass
import re
class Child(Parent):
# prefix for "private" fields
__rePrivate = re.com... | Give a code snippet in #Python
Task
The goal is to get the properties of an object, as names, values or both.
Some languages support dynamic properties, which in general can only be inspected if a class' public API includes a way of listing them.
| christopher/rosetta-code | |
http://rosettacode.org/wiki/Generic_swap | Generic swap | Task
Write a generic swap function or operator which exchanges the values of two variables (or, more generally, any two storage places that can be assigned), regardless of their types.
If your solution language is statically typed please describe the way your language provides genericity.
If variables are typed in t... | #RLaB | RLaB |
swap = function(x,y)
{
if (!exist($$.[x]))
{ return 0; }
if (!exist($$.[y]))
{ return 0; }
local (t);
t = $$.[x];
$$.[x] = $$.[y];
$$.[y] = t;
return 1;
};
>> a=1
1
>> b = "fish"
fish
>> swap( "a" , "b" );
>> a
fish
>> b
1
| Give a code snippet in #RLaB
Task
Write a generic swap function or operator which exchanges the values of two variables (or, more generally, any two storage places that can be assigned), regardless of their types.
If your solution language is statically typed please describe the way your language provides genericity... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Determine_if_a_string_has_all_unique_characters | Determine if a string has all unique characters | Task
Given a character string (which may be empty, or have a length of zero characters):
create a function/procedure/routine to:
determine if all the characters in the string are unique
indicate if or which character is duplicated and where
display each string and its length (as the strings are being ... | #Arturo | Arturo | strings: [
"", ".", "abcABC", "XYZ ZYX",
"1234567890ABCDEFGHIJKLMN0PQRSTUVWXYZ",
"01234567890ABCDEFGHIJKLMN0PQRSTUVWXYZ0X",
"hétérogénéité",
"🎆🎃🎇🎈", "😍😀🙌💃😍🙌", "🐠🐟🐡🦈🐬🐳🐋🐡"
]
loop strings 'str [
chars: split str
prints ["\"" ++ str ++ "\"" ~"(size |size str|):"]
if? ch... | Give a code snippet in #Arturo
Task
Given a character string (which may be empty, or have a length of zero characters):
create a function/procedure/routine to:
determine if all the characters in the string are unique
indicate if or which character is duplicated and where
display each string and its len... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Program_termination | Program termination |
Task
Show the syntax for a complete stoppage of a program inside a conditional.
This includes all threads/processes which are part of your program.
Explain the cleanup (or lack thereof) caused by the termination (allocated memory, database connections, open files, object finalizers/destructors, run-on-exit hooks... | #EDSAC_order_code | EDSAC order code | if rcode != :ok, do: System.halt(1) | Give a code snippet in #EDSAC_order_code
Task
Show the syntax for a complete stoppage of a program inside a conditional.
This includes all threads/processes which are part of your program.
Explain the cleanup (or lack thereof) caused by the termination (allocated memory, database connections, open files, object... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Sorting_algorithms/Selection_sort | Sorting algorithms/Selection 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
... | #LSE | LSE |
(*
** Tri par Sélection
** (LSE2000)
*)
PROCEDURE &Test(TABLEAU DE ENTIER pDonnees[], ENTIER pTaille) LOCAL pTaille
ENTIER i, j, minimum, tmp
POUR i <- 0 JUSQUA pTaille-1 FAIRE
minimum <- i
POUR j <- i+1 JUSQUA pTaille FAIRE
SI pDonnees[j] < pDonnees[minimum] ALORS
... | Give a code snippet in #LSE
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... | christopher/rosetta-code |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.