task_url stringlengths 30 116 | task_name stringlengths 2 86 | task_description stringlengths 0 14.4k | language_url stringlengths 2 53 | language_name stringlengths 1 52 | code stringlengths 0 61.9k |
|---|---|---|---|---|---|
http://rosettacode.org/wiki/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.
| #Groovy | Groovy | final CELL_VALUES = ('1'..'9')
class GridException extends Exception {
GridException(String message) { super(message) }
}
def string2grid = { string ->
assert string.size() == 81
(0..8).collect { i -> (0..8).collect { j -> string[9*i+j] } }
}
def gridRow = { grid, slot -> grid[slot.i] as Set }
def g... |
http://rosettacode.org/wiki/Subleq | Subleq | Subleq is an example of a One-Instruction Set Computer (OISC).
It is named after its only instruction, which is SUbtract and Branch if Less than or EQual to zero.
Task
Your task is to create an interpreter which emulates a SUBLEQ machine.
The machine's memory consists of an array of signed integers. These integers... | #Nim | Nim | import streams
type
Interpreter = object
mem: seq[int]
ip: int
input, output: Stream
proc load(prog: openArray[int]; inp, outp: Stream): Interpreter =
Interpreter(mem: prog, input: inp, output: outp)
proc run(i: var Interpreter) =
while i.ip >= 0:
let A = i.mem[i.ip]
let B = i.mem[i.ip+1... |
http://rosettacode.org/wiki/Successive_prime_differences | Successive prime differences | The series of increasing prime numbers begins: 2, 3, 5, 7, 11, 13, 17, 19, 23, 29, ...
The task applies a filter to the series returning groups of successive primes, (s'primes), that differ from the next by a given value or values.
Example 1: Specifying that the difference between s'primes be 2 leads to the groups:
... | #Visual_Basic_.NET | Visual Basic .NET | Imports System.Text
Module Module1
Function Sieve(limit As Integer) As Integer()
Dim primes As New List(Of Integer) From {2}
Dim c(limit + 1) As Boolean REM composite = true
REM no need to process even numbers > 2
Dim p = 3
While True
Dim p2 = p * p
... |
http://rosettacode.org/wiki/Substring/Top_and_tail | Substring/Top and tail | The task is to demonstrate how to remove the first and last characters from a string.
The solution should demonstrate how to obtain the following results:
String with first character removed
String with last character removed
String with both the first and last characters removed
If the program uses UTF-8 or UTF... | #JavaScript | JavaScript | alert("knight".slice(1)); // strip first character
alert("socks".slice(0, -1)); // strip last character
alert("brooms".slice(1, -1)); // strip both first and last characters |
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... | #Tcl | Tcl | package require Tcl 8.5
namespace eval subrand {
variable mod 1000000000 state [lrepeat 55 0] si 0 sj 0
proc seed p1 {
global subrand::mod subrand::state subrand::si subrand::sj
set p2 1
lset state 0 [expr {$p1 % $mod}]
for {set i 1; set j 21} {$i < 55} {incr i; incr j 21} {
if {$j >= 55} {incr j -55... |
http://rosettacode.org/wiki/Sum_and_product_of_an_array | Sum and product of an array | Task
Compute the sum and product of an array of integers.
| #Kotlin | Kotlin | // version 1.1.2
fun main(args: Array<String>) {
val a = intArrayOf(1, 5, 8, 11, 15)
println("Array contains : ${a.contentToString()}")
val sum = a.sum()
println("Sum is $sum")
val product = a.fold(1) { acc, i -> acc * i }
println("Product is $product")
} |
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... | #GAP | GAP | # We will compute the sum exactly
# Computing an approximation of a rationnal (giving a string)
# Value is truncated toward zero
Approx := function(x, d)
local neg, a, b, n, m, s;
if x < 0 then
x := -x;
neg := true;
else
neg := false;
fi;
a := NumeratorRat(x);
b := DenominatorRat(x);
n := QuoInt(a, b);
... |
http://rosettacode.org/wiki/Strip_comments_from_a_string | Strip comments from a string | Strip comments from a string
You are encouraged to solve this task according to the task description, using any language you may know.
The task is to remove text that follow any of a set of comment markers, (in these examples either a hash or a semicolon) from a string or input line.
Whitespace debacle: There is s... | #MiniScript | MiniScript | strip = function(test)
comment = test.indexOf("#")
if comment == null then comment = test.indexOf(";")
if comment then test = test[:comment]
while test[-1] == " "
test = test - " "
end while
return test
end function
print strip("This is a hash test # a comment") + "."
print strip("T... |
http://rosettacode.org/wiki/Strip_comments_from_a_string | Strip comments from a string | Strip comments from a string
You are encouraged to solve this task according to the task description, using any language you may know.
The task is to remove text that follow any of a set of comment markers, (in these examples either a hash or a semicolon) from a string or input line.
Whitespace debacle: There is s... | #Nim | Nim | import strutils
proc removeComments(line: string; sep: char): string =
line.split(sep)[0].strip(leading = false)
const
Str1 = "apples, pears # and bananas"
Str2 = "apples, pears ; and bananas"
echo "Original: “$#”" % Str1
echo "Stripped: “$#”" % Str1.removeComments('#')
echo "Original: “$#”" % Str2
echo "St... |
http://rosettacode.org/wiki/Strip_block_comments | Strip block comments | A block comment begins with a beginning delimiter and ends with a ending delimiter, including the delimiters. These delimiters are often multi-character sequences.
Task
Strip block comments from program text (of a programming language much like classic C).
Your demos should at least handle simple, non-ne... | #PureBasic | PureBasic | Procedure.s escapeChars(text.s)
Static specialChars.s = "[\^$.|?*+()"
Protected output.s, nextChar.s, i, countChar = Len(text)
For i = 1 To countChar
nextChar = Mid(text, i, 1)
If FindString(specialChars, nextChar, 1)
output + "\" + nextChar
Else
output + nextChar
EndIf
Next
Proce... |
http://rosettacode.org/wiki/String_interpolation_(included) | String interpolation (included) |
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 |... | #EchoLisp | EchoLisp |
;; format uses %a or ~a as replacement directive
(format "Mary had a ~a lamb" "little")
→ "Mary had a little lamb"
(format "Mary had a %a lamb" "little")
→ "Mary had a little lamb"
|
http://rosettacode.org/wiki/String_interpolation_(included) | String interpolation (included) |
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 |... | #ECL | ECL |
IMPORT STD;
STD.Str.FindReplace('Mary had a X Lamb', 'X','little');
|
http://rosettacode.org/wiki/String_interpolation_(included) | String interpolation (included) |
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 |... | #Elena | Elena | import extensions;
public program()
{
var s := "little";
console.printLineFormatted("Mary had a {0} lamb.",s).readChar()
} |
http://rosettacode.org/wiki/Strip_a_set_of_characters_from_a_string | Strip a set of characters from a string | Task
Create a function that strips a set of characters from a string.
The function should take two arguments:
a string to be stripped
a string containing the set of characters to be stripped
The returned string should contain the first string, stripped of any characters in the second argument:
print str... | #Euphoria | Euphoria | include std\sequence.e
include std\console.e
sequence originalString = "She was a soul stripper. She took my heart!"
puts(1,"Before : " & originalString & "\n")
originalString = transmute(originalString, {{} , "a", "e", "i"}, {{} , "", "", ""})
puts(1,"After : " & originalString & "\n")
any_key() |
http://rosettacode.org/wiki/Strip_a_set_of_characters_from_a_string | Strip a set of characters from a string | Task
Create a function that strips a set of characters from a string.
The function should take two arguments:
a string to be stripped
a string containing the set of characters to be stripped
The returned string should contain the first string, stripped of any characters in the second argument:
print str... | #Excel | Excel | exceptChars
=LAMBDA(excluded,
LAMBDA(src,
CONCAT(
FILTERP(
LAMBDA(c,
ISERROR(
FIND(c, excluded, 1)
)
)
)(
CHARSROW(src)
)
)
)
) |
http://rosettacode.org/wiki/String_prepend | String prepend |
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 |... | #Nanoquery | Nanoquery | s1 = " a test"
s1 = "this is" + s1
println s1 |
http://rosettacode.org/wiki/String_prepend | String prepend |
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 |... | #Neko | Neko | /**
<doc><p>String prepend in Neko</pre></doc>
**/
var str = ", world"
str = "Hello" + str
$print(str, "\n") |
http://rosettacode.org/wiki/String_prepend | String prepend |
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 |... | #NetRexx | NetRexx | s_ = 'world!'
s_ = 'Hello, 's_
say s_ |
http://rosettacode.org/wiki/String_prepend | String prepend |
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 |... | #NewLISP | NewLISP | (setq str "bar")
(push "foo" str)
(println str) |
http://rosettacode.org/wiki/String_comparison | String comparison |
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 |... | #Common_Lisp | Common Lisp | >(string= "foo" "foo")
T
> (string= "foo" "FOO")
NIL
> (string/= "foo" "bar")
0
> (string/= "bar" "baz")
2
> (string/= "foo" "foo")
NIL
> (string> "foo" "Foo")
0
> (string< "foo" "Foo")
NIL
> (string>= "FOo" "Foo")
NIL
> (string<= "FOo" "Foo")
1 |
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.23 | C# |
class Program
{
static void Main(string[] args)
{
string input;
Console.Write("Enter a series of letters: ");
input = Console.ReadLine();
stringCase(input);
}
private static void stringCase(string str)
{
char[] chars = str.ToCharArray();
string new... |
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 |... | #CoffeeScript | CoffeeScript |
matchAt = (s, frag, i) ->
s[i...i+frag.length] == frag
startsWith = (s, frag) ->
matchAt s, frag, 0
endsWith = (s, frag) ->
matchAt s, frag, s.length - frag.length
matchLocations = (s, frag) ->
(i for i in [0..s.length - frag.length] when matchAt s, frag, i)
console.log startsWith "tacoloco", "taco" #... |
http://rosettacode.org/wiki/String_length | String length | Task
Find the character and byte length of a string.
This means encodings like UTF-8 need to be handled properly, as there is not necessarily a one-to-one relationship between bytes and characters.
By character, we mean an individual Unicode code point, not a user-visible grapheme containing combining characters.
F... | #BQN | BQN | BLen ← {(≠𝕩)+´⥊𝕩≥⌜@+128‿2048‿65536} |
http://rosettacode.org/wiki/String_length | String length | Task
Find the character and byte length of a string.
This means encodings like UTF-8 need to be handled properly, as there is not necessarily a one-to-one relationship between bytes and characters.
By character, we mean an individual Unicode code point, not a user-visible grapheme containing combining characters.
F... | #Bracmat | Bracmat | (ByteLength=
length
. @(!arg:? [?length)
& !length
);
out$ByteLength$𝔘𝔫𝔦𝔠𝔬𝔡𝔢 |
http://rosettacode.org/wiki/Strip_control_codes_and_extended_characters_from_a_string | Strip control codes and extended characters from a string | Task
Strip control codes and extended characters from a string.
The solution should demonstrate how to achieve each of the following results:
a string with control codes stripped (but extended characters not stripped)
a string with control codes and extended characters stripped
In ASCII, the control codes ... | #Liberty_BASIC | Liberty BASIC |
all$ =""
for i =0 to 255
all$ =all$ +chr$( i)
next i
print "Original string of bytes. ( chr$( 10) causes a CRLF.)"
print all$
print
lessControl$ =controlStripped$( all$)
print "With control codes stripped out."
print lessControl$
print
lessExtendedAndControl$... |
http://rosettacode.org/wiki/Strip_control_codes_and_extended_characters_from_a_string | Strip control codes and extended characters from a string | Task
Strip control codes and extended characters from a string.
The solution should demonstrate how to achieve each of the following results:
a string with control codes stripped (but extended characters not stripped)
a string with control codes and extended characters stripped
In ASCII, the control codes ... | #Lua | Lua | function Strip_Control_Codes( str )
local s = ""
for i in str:gmatch( "%C+" ) do
s = s .. i
end
return s
end
function Strip_Control_and_Extended_Codes( str )
local s = ""
for i = 1, str:len() do
if str:byte(i) >= 32 and str:byte(i) <= 126 then
s = s .. str:sub(i,i)
end
end
r... |
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... | #Dyalect | Dyalect | var s = "hello"
print(s + " literal")
var s1 = s + " literal"
print(s1) |
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... | #Dylan.NET | Dylan.NET |
//to be compiled using dylan.NET v. 11.5.1.2 or later.
#refstdasm mscorlib.dll
import System
assembly concatex exe
ver 1.3.0.0
class public Program
method public static void main()
var s as string = "hello"
Console::Write(s)
Console::WriteLine(" literal")
var s2 as string = ... |
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... | #D.C3.A9j.C3.A0_Vu | Déjà Vu | local :s1 "hello"
local :s2 concat( s1 ", world" )
!print s2 |
http://rosettacode.org/wiki/Sum_multiples_of_3_and_5 | Sum multiples of 3 and 5 | Task
The objective is to write a function that finds the sum of all positive multiples of 3 or 5 below n.
Show output for n = 1000.
This is is the same as Project Euler problem 1.
Extra credit: do this efficiently for n = 1e20 or higher.
| #Maple | Maple |
F := unapply( sum(3*i,i=1..floor((n-1)/3))
+ sum(5*i,i=1..floor((n-1)/5))
- sum(15*i,i=1..floor((n-1)/15)), n);
F(1000);
F(10^20);
|
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
| #ML | ML |
local
open IntInf
in
fun summDigits base = ( fn 0 => 0 | n => n mod base + summDigits base (n div base ) )
end;
summDigits 10 1 ;
summDigits 10 1234 ;
summDigits 16 0xfe ;
summDigits 16 0xf0e ;
summDigits 4332489243570890023480923 0x8092eeac80923984098234098efad2109ce341000c3f0912527130 ;
|
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
| #Modula-3 | Modula-3 | MODULE SumSquares EXPORTS Main;
IMPORT IO, Fmt;
TYPE RealArray = ARRAY OF REAL;
PROCEDURE SumOfSquares(x: RealArray): REAL =
VAR sum := 0.0;
BEGIN
FOR i := FIRST(x) TO LAST(x) DO
sum := sum + x[i] * x[i];
END;
RETURN sum;
END SumOfSquares;
BEGIN
IO.Put(Fmt.Real(SumOfSquares(RealArray{3... |
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
| #MOO | MOO | @verb #100:sum_squares this none this rd
@program #100:sum_squares
sum = 0;
list = args[1];
for i in (list)
sum = sum + (i^2);
endfor
player:tell(toliteral(list), " => ", sum);
.
{{out}}
;#100:sum_squares({3,1,4,1,5,9})
{3, 1, 4, 1, 5, 9} => 133
;#100:sum_squares({})
{} => 0
|
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... | #Java | Java | public class Trims{
public static String ltrim(String s) {
int i = 0;
while (i < s.length() && Character.isWhitespace(s.charAt(i))) {
i++;
}
return s.substring(i);
}
public static String rtrim(String s) {
int i = s.length() - 1;
while (i > 0 && C... |
http://rosettacode.org/wiki/Substring | Substring |
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 |... | #ECL | ECL |
/* In this task display a substring:
1. starting from n characters in and of m length;
2. starting from n characters in, up to the end of the string;
3. whole string minus last character;
4. starting from a known character within the string and of m length;
5. starting from a known sub... |
http://rosettacode.org/wiki/Substring | Substring |
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 |... | #Eero | Eero | #import <Foundation/Foundation.h>
int main()
autoreleasepool
str := 'abcdefgh'
n := 2
m := 3
Log( '%@', str[0 .. str.length-1] ) // abcdefgh
Log( '%@', str[n .. m] ) // cd
Log( '%@', str[n .. str.length-1] ) // cdefgh
... |
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.
| #Haskell | Haskell | public class Sudoku
{
private int mBoard[][];
private int mBoardSize;
private int mBoxSize;
private boolean mRowSubset[][];
private boolean mColSubset[][];
private boolean mBoxSubset[][];
public Sudoku(int board[][]) {
mBoard = board;
mBoardSize = mBoard.length;
mBo... |
http://rosettacode.org/wiki/Subleq | Subleq | Subleq is an example of a One-Instruction Set Computer (OISC).
It is named after its only instruction, which is SUbtract and Branch if Less than or EQual to zero.
Task
Your task is to create an interpreter which emulates a SUBLEQ machine.
The machine's memory consists of an array of signed integers. These integers... | #Objeck | Objeck | use System.IO;
class Sublet {
function : Main(args : String[]) ~ Nil {
mem := [
15, 17, -1, 17, -1, -1, 16, 1, -1, 16,
3, -1, 15, 15, 0, 0, -1, 72, 101, 108,
108, 111, 44, 32, 119, 111, 114, 108, 100, 33,
10, 0];
instructionPointer := 0;
do {
a := mem[instructionPointer... |
http://rosettacode.org/wiki/Successive_prime_differences | Successive prime differences | The series of increasing prime numbers begins: 2, 3, 5, 7, 11, 13, 17, 19, 23, 29, ...
The task applies a filter to the series returning groups of successive primes, (s'primes), that differ from the next by a given value or values.
Example 1: Specifying that the difference between s'primes be 2 leads to the groups:
... | #Wren | Wren | import "/math" for Int
var successivePrimes = Fn.new { |primes, diffs|
var results = []
var dl = diffs.count
for (i in 0...primes.count-dl) {
var group = List.filled(dl+1, 0)
group[0] = primes[i]
var outer = false
for (j in i...i+dl) {
var cont = false
... |
http://rosettacode.org/wiki/Substring/Top_and_tail | Substring/Top and tail | The task is to demonstrate how to remove the first and last characters from a string.
The solution should demonstrate how to obtain the following results:
String with first character removed
String with last character removed
String with both the first and last characters removed
If the program uses UTF-8 or UTF... | #jq | jq | "一二三四五六七八九十"[1:]' => "二三四五六七八九十"
"一二三四五六七八九十"[:-1]' => "一二三四五六七八九"
"一二三四五六七八九十"[1:-1]' => "二三四五六七八九"
"a"[1:-1] # => ""
|
http://rosettacode.org/wiki/Substring/Top_and_tail | Substring/Top and tail | The task is to demonstrate how to remove the first and last characters from a string.
The solution should demonstrate how to obtain the following results:
String with first character removed
String with last character removed
String with both the first and last characters removed
If the program uses UTF-8 or UTF... | #Julia | Julia | julia> "My String"[2:end] # without first character
"y String"
julia> "My String"[1:end-1] # without last character
"My Strin"
julia> "My String"[2:end-1] # without first and last characters
"y Strin" |
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... | #uBasic.2F4tH | uBasic/4tH | Push 292929 : Gosub 100 : d = Pop()
For i = 1 To 10
Push 0 : Gosub 100
Print Pop()
Next
End
100 s = Pop()
If s = 0 Then
p = (p + 1) % 55
@(p) = @(p) - @((p + 31) % 55)
If @(p) < 0 Then
@(p) = @(p) + 1000000000
Endif
Push (@(p)) : Return
Endif
@(54) = ... |
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... | #Wren | Wren | var mod = 1e9
var state = List.filled(55, 0)
var si = 0
var sj = 0
var subrand // forward declaration
var subrandSeed = Fn.new { |p|
var p2 = 1
state[0] = p % mod
var j = 21
for (i in 1..54) {
if (j >= 55) j = j - 55
state[j] = p2
p2 = p - p2
if (p2 < 0) p2 = p2 + mod... |
http://rosettacode.org/wiki/Sum_and_product_of_an_array | Sum and product of an array | Task
Compute the sum and product of an array of integers.
| #Lambdatalk | Lambdatalk |
{A.serie start end [step]} creates a sequence from start to end with optional step
{A.new words} creates an array from a sequence of words
{A.toS array} creates a sequence from the items of an array
{long_add x y} returns the sum of two integers of any size
{long_mult x y} ... |
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... | #Genie | Genie | [indent=4]
/*
Sum of series, in Genie
valac sumOfSeries.gs
./sumOfSeries
*/
delegate sumFunc(n:int):double
def sum_series(start:int, end:int, f:sumFunc):double
sum:double = 0.0
for var i = start to end do sum += f(i)
return sum
def oneOverSquare(n:int):double
return (1 / (double)(n * n)... |
http://rosettacode.org/wiki/Strip_comments_from_a_string | Strip comments from a string | Strip comments from a string
You are encouraged to solve this task according to the task description, using any language you may know.
The task is to remove text that follow any of a set of comment markers, (in these examples either a hash or a semicolon) from a string or input line.
Whitespace debacle: There is s... | #Objeck | Objeck | use System.IO.File;
class StripComments {
function : Main(args : String[]) ~ Nil {
reader : FileReader;
if(args->Size() = 1) {
reader := FileReader->New(args[0]);
line := reader->ReadString();
while(line <> Nil) {
index := line->FindLast(';');
if(index < 0) {
inde... |
http://rosettacode.org/wiki/Strip_comments_from_a_string | Strip comments from a string | Strip comments from a string
You are encouraged to solve this task according to the task description, using any language you may know.
The task is to remove text that follow any of a set of comment markers, (in these examples either a hash or a semicolon) from a string or input line.
Whitespace debacle: There is s... | #OCaml | OCaml | let strip_comments str =
let len = String.length str in
let rec aux print i =
if i >= len then () else
match str.[i] with
| '#' | ';' ->
aux false (succ i)
| '\n' ->
print_char '\n';
aux true (succ i)
| c ->
if print then print_char c;
aux print (succ i)
... |
http://rosettacode.org/wiki/Strip_block_comments | Strip block comments | A block comment begins with a beginning delimiter and ends with a ending delimiter, including the delimiters. These delimiters are often multi-character sequences.
Task
Strip block comments from program text (of a programming language much like classic C).
Your demos should at least handle simple, non-ne... | #Python | Python | def _commentstripper(txt, delim):
'Strips first nest of block comments'
deliml, delimr = delim
out = ''
if deliml in txt:
indx = txt.index(deliml)
out += txt[:indx]
txt = txt[indx+len(deliml):]
txt = _commentstripper(txt, delim)
assert delimr in txt, 'Cannot fin... |
http://rosettacode.org/wiki/Strip_block_comments | Strip block comments | A block comment begins with a beginning delimiter and ends with a ending delimiter, including the delimiters. These delimiters are often multi-character sequences.
Task
Strip block comments from program text (of a programming language much like classic C).
Your demos should at least handle simple, non-ne... | #Racket | Racket |
#lang at-exp racket
;; default delimiters (strings -- not regexps)
(define comment-start-str "/*")
(define comment-end-str "*/")
(define (strip-comments text [rx1 comment-start-str] [rx2 comment-end-str])
(regexp-replace* (~a (regexp-quote rx1) ".*?" (regexp-quote rx2))
text ""))
((compose1... |
http://rosettacode.org/wiki/String_interpolation_(included) | String interpolation (included) |
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 |... | #Elixir | Elixir |
x = "little"
IO.puts "Mary had a #{x} lamb"
|
http://rosettacode.org/wiki/String_interpolation_(included) | String interpolation (included) |
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 |... | #Emacs_Lisp | Emacs Lisp | (let ((little "little"))
(format "Mary had a %s lamb." little)
;; message takes a format string as argument
(message "Mary had a %s lamb." little)) |
http://rosettacode.org/wiki/String_interpolation_(included) | String interpolation (included) |
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 | 7> S1 = "Mary had a ~s lamb".
8> S2 = lists:flatten( io_lib:format(S1, ["big"]) ).
9> S2.
"Mary had a big lamb"
|
http://rosettacode.org/wiki/Strip_a_set_of_characters_from_a_string | Strip a set of characters from a string | Task
Create a function that strips a set of characters from a string.
The function should take two arguments:
a string to be stripped
a string containing the set of characters to be stripped
The returned string should contain the first string, stripped of any characters in the second argument:
print str... | #F.23 | F# | let stripChars text (chars:string) =
Array.fold (
fun (s:string) c -> s.Replace(c.ToString(),"")
) text (chars.ToCharArray())
[<EntryPoint>]
let main args =
printfn "%s" (stripChars "She was a soul stripper. She took my heart!" "aei")
0 |
http://rosettacode.org/wiki/Strip_a_set_of_characters_from_a_string | Strip a set of characters from a string | Task
Create a function that strips a set of characters from a string.
The function should take two arguments:
a string to be stripped
a string containing the set of characters to be stripped
The returned string should contain the first string, stripped of any characters in the second argument:
print str... | #Factor | Factor | without |
http://rosettacode.org/wiki/String_prepend | String prepend |
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 |... | #Nim | Nim | # Direct way.
var str1, str2 = "12345678"
str1 = "0" & str1
echo str1
# Using "insert".
str2.insert("0")
echo str2
|
http://rosettacode.org/wiki/String_prepend | String prepend |
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 |... | #Objeck | Objeck | class Prepend {
function : Main(args : String[]) ~ Nil {
s := "world!";
"Hello {$s}"->PrintLine();
}
} |
http://rosettacode.org/wiki/String_prepend | String prepend |
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 |... | #OCaml | OCaml | let () =
let s = ", world" in
let s = "Hello" ^ s in
print_endline s |
http://rosettacode.org/wiki/String_comparison | String comparison |
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 |... | #Component_Pascal | Component Pascal | MODULE StringComparision;
IMPORT StdLog,Strings;
PROCEDURE Do*;
VAR
str1,str2,aux1,aux2: ARRAY 128 OF CHAR;
BEGIN
str1 := "abcde";str2 := "abcde";
StdLog.String(str1+" equals " + str2 + ":> ");StdLog.Bool(str1 = str2);StdLog.Ln;
str2 := "abcd";
StdLog.String(str1+" equals " + str2 + ":> ");StdLog.Bool(str1 = s... |
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);
}... |
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 |... | #Common_Lisp | Common Lisp |
(defun starts-with-p (str1 str2)
"Determine whether `str1` starts with `str2`"
(let ((p (search str2 str1)))
(and p (= 0 p))))
(print (starts-with-p "foobar" "foo")) ; T
(print (starts-with-p "foobar" "bar")) ; NIL
(defun ends-with-p (str1 str2)
"Determine whether `str1` ends with `str2`"
(let ((p (m... |
http://rosettacode.org/wiki/String_length | String length | Task
Find the character and byte length of a string.
This means encodings like UTF-8 need to be handled properly, as there is not necessarily a one-to-one relationship between bytes and characters.
By character, we mean an individual Unicode code point, not a user-visible grapheme containing combining characters.
F... | #C | C | #include <string.h>
int main(void)
{
const char *string = "Hello, world!";
size_t length = strlen(string);
return 0;
} |
http://rosettacode.org/wiki/String_length | String length | Task
Find the character and byte length of a string.
This means encodings like UTF-8 need to be handled properly, as there is not necessarily a one-to-one relationship between bytes and characters.
By character, we mean an individual Unicode code point, not a user-visible grapheme containing combining characters.
F... | #C.23 | C# | string s = "Hello, world!";
int characterLength = s.Length; |
http://rosettacode.org/wiki/Strip_control_codes_and_extended_characters_from_a_string | Strip control codes and extended characters from a string | Task
Strip control codes and extended characters from a string.
The solution should demonstrate how to achieve each of the following results:
a string with control codes stripped (but extended characters not stripped)
a string with control codes and extended characters stripped
In ASCII, the control codes ... | #Mathematica.2FWolfram_Language | Mathematica/Wolfram Language | stripCtrl[x_]:=StringJoin[Select[Characters[x],
MemberQ[CharacterRange["!","~"]~Join~Characters[FromCharacterCode[Range[128,255]]],#]&]]
stripCtrlExt[x_]:=StringJoin[Select[Characters[x],
MemberQ[CharacterRange["!","~"],#]&]] |
http://rosettacode.org/wiki/Strip_control_codes_and_extended_characters_from_a_string | Strip control codes and extended characters from a string | Task
Strip control codes and extended characters from a string.
The solution should demonstrate how to achieve each of the following results:
a string with control codes stripped (but extended characters not stripped)
a string with control codes and extended characters stripped
In ASCII, the control codes ... | #MATLAB_.2F_Octave | MATLAB / Octave | function str = stripped(str)
str = str(31<str & str<127);
end; |
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... | #EasyLang | EasyLang | a$ = "hello"
b$ = a$ & " world"
print b$ |
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... | #Ela | Ela | hello = "Hello"
hello'world = hello ++ ", " ++ "world"
(hello, hello'world) |
http://rosettacode.org/wiki/Sum_multiples_of_3_and_5 | Sum multiples of 3 and 5 | Task
The objective is to write a function that finds the sum of all positive multiples of 3 or 5 below n.
Show output for n = 1000.
This is is the same as Project Euler problem 1.
Extra credit: do this efficiently for n = 1e20 or higher.
| #Mathematica.2FWolfram_Language | Mathematica/Wolfram Language | sum35[n_] :=
Sum[k, {k, 3, n - 1, 3}] + Sum[k, {k, 5, n - 1, 5}] -
Sum[k, {k, 15, n - 1, 15}]
sum35[1000] |
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
| #Modula-2 | Modula-2 |
MODULE SumOFDigits;
FROM STextIO IMPORT
WriteString, WriteLn;
FROM SWholeIO IMPORT
WriteInt;
FROM Conversions IMPORT
StrBaseToLong;
PROCEDURE SumOfDigitBase(N: LONGCARD; Base: CARDINAL): CARDINAL;
VAR
Tmp, LBase: LONGCARD;
Digit, Sum : CARDINAL;
BEGIN
Digit := 0;
Sum := 0;
LBase := Base;
WHILE N... |
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
| #MUMPS | MUMPS | SUMSQUARE(X)
;X is assumed to be a list of numbers separated by "^"
NEW RESULT,I
SET RESULT=0,I=1
FOR QUIT:(I>$LENGTH(X,"^")) SET RESULT=($PIECE(X,"^",I)*$PIECE(X,"^",I))+RESULT,I=I+1
QUIT RESULT |
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
| #Nanoquery | Nanoquery | def sum_squares(vector)
if len(vector) = 0
return 0
end
sum = 0
for n in vector
sum += n ^ 2
end
return sum
end
println sum_squares({})
println sum_squares({1, 2, 3, 4, 5})
println sum_squares({10, 3456, 2, 6}) |
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... | #JavaScript | JavaScript | {
let s = " \t String with spaces \t ";
// a future version of ECMAScript will have trimStart(). Some current
// implementations have trimLeft().
console.log("original: '" + s + "'");
console.log("trimmed left: '" + s.replace(/^\s+/,'') + "'");
// a future version of ECMAScript will have trim... |
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... | #jq | jq | def lstrip: sub( "^[\\s\\p{Cc}]+"; "" );
def rstrip: sub( "[\\s\\p{Cc}]+$"; "" );
def strip: lstrip | rstrip; |
http://rosettacode.org/wiki/Substring | Substring |
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 |... | #Elena | Elena | import extensions;
public program()
{
var s := "0123456789";
var n := 3;
var m := 2;
var c := $51;
var z := "345";
console.writeLine(s.Substring(n, m));
console.writeLine(s.Substring(n, s.Length - n));
console.writeLine(s.Substring(0, s.Length - 1));
console.writeLine(s.Substring... |
http://rosettacode.org/wiki/Substring | Substring |
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 |... | #Elixir | Elixir | s = "abcdefgh"
String.slice(s, 2, 3) #=> "cde"
String.slice(s, 1..3) #=> "bcd"
String.slice(s, -3, 2) #=> "fg"
String.slice(s, 3..-1) #=> "defgh"
# UTF-8
s = "αβγδεζηθ"
String.slice(s, 2, 3) #=> "γδε"
String.slice(s, 1..3) #=> "βγδ"
String.slice(s, -3, 2) ... |
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.
| #J | J | public class Sudoku
{
private int mBoard[][];
private int mBoardSize;
private int mBoxSize;
private boolean mRowSubset[][];
private boolean mColSubset[][];
private boolean mBoxSubset[][];
public Sudoku(int board[][]) {
mBoard = board;
mBoardSize = mBoard.length;
mBo... |
http://rosettacode.org/wiki/Subleq | Subleq | Subleq is an example of a One-Instruction Set Computer (OISC).
It is named after its only instruction, which is SUbtract and Branch if Less than or EQual to zero.
Task
Your task is to create an interpreter which emulates a SUBLEQ machine.
The machine's memory consists of an array of signed integers. These integers... | #Oforth | Oforth | : subleq(program)
| ip a b c newb |
program asListBuffer ->program
0 ->ip
while( ip 0 >= ) [
ip 1+ dup program at ->a 1+ dup program at ->b 1+ program at ->c
ip 3 + ->ip
a -1 = ifTrue: [ b System.In >> nip program put continue ]
b -1 = ifTrue: [ System.Out a 1+ program at <<c drop conti... |
http://rosettacode.org/wiki/Subleq | Subleq | Subleq is an example of a One-Instruction Set Computer (OISC).
It is named after its only instruction, which is SUbtract and Branch if Less than or EQual to zero.
Task
Your task is to create an interpreter which emulates a SUBLEQ machine.
The machine's memory consists of an array of signed integers. These integers... | #ooRexx | ooRexx | /*REXX program simulates execution of a One-Instruction Set Computer (OISC). */
Signal on Halt /*enable user to halt the simulation. */
cell.=0 /*zero-out all of real memory locations*/
ip=0 /*initialize ip (instruction pointer)... |
http://rosettacode.org/wiki/Successive_prime_differences | Successive prime differences | The series of increasing prime numbers begins: 2, 3, 5, 7, 11, 13, 17, 19, 23, 29, ...
The task applies a filter to the series returning groups of successive primes, (s'primes), that differ from the next by a given value or values.
Example 1: Specifying that the difference between s'primes be 2 leads to the groups:
... | #zkl | zkl | const PRIME_LIMIT=1_000_000;
var [const] BI=Import("zklBigNum"); // libGMP
var [const] primeBitMap=Data(PRIME_LIMIT).fill(0x30); // one big string
p:= BI(1);
while(p.nextPrime()<=PRIME_LIMIT){ primeBitMap[p]="1" } // bitmap of primes
fcn primeWindows(m,deltas){ // eg (6,4,2)
n,r := 0,List();
ds:=deltas.len()... |
http://rosettacode.org/wiki/Substring/Top_and_tail | Substring/Top and tail | The task is to demonstrate how to remove the first and last characters from a string.
The solution should demonstrate how to obtain the following results:
String with first character removed
String with last character removed
String with both the first and last characters removed
If the program uses UTF-8 or UTF... | #K | K |
s: "1234567890"
"1234567890"
s _di 0 /Delete 1st character
"234567890"
s _di -1+#s /Delete last character
"123456789"
(s _di -1+#s) _di 0 /String with both 1st and last character removed
"23456789"
|
http://rosettacode.org/wiki/Substring/Top_and_tail | Substring/Top and tail | The task is to demonstrate how to remove the first and last characters from a string.
The solution should demonstrate how to obtain the following results:
String with first character removed
String with last character removed
String with both the first and last characters removed
If the program uses UTF-8 or UTF... | #Kotlin | Kotlin | // version 1.0.6
fun main(args: Array<String>) {
val s = "Rosetta"
println(s.drop(1))
println(s.dropLast(1))
println(s.drop(1).dropLast(1))
} |
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... | #zkl | zkl | fcn rand_sub(x){
var ring=L(),m=(1e9).toInt();
mod:='wrap(n){ if(n<0) n+m else n };
if(not ring){
seed:=L( (if(vm.numArgs) x else m-1), 1);
foreach n in ([2 .. 54]){ seed.append((seed[n-2]-seed[n-1]):mod(_)) }
foreach n in (55){ ring.append(seed[(34*(n+1))%55]) }
do(220-ring.len()){ sel... |
http://rosettacode.org/wiki/Sum_and_product_of_an_array | Sum and product of an array | Task
Compute the sum and product of an array of integers.
| #Lang5 | Lang5 | 4 iota 1 + dup
'+ reduce
'* reduce |
http://rosettacode.org/wiki/Sum_and_product_of_an_array | Sum and product of an array | Task
Compute the sum and product of an array of integers.
| #langur | langur | val .arr = series 19
writeln " array: ", .arr
writeln " sum: ", fold f .x + .y, .arr
writeln "product: ", fold f .x x .y, .arr |
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... | #GEORGE | GEORGE |
0 (s)
1, 1000 rep (i)
s 1 i dup × / + (s) ;
]
P
|
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... | #Go | Go | package main
import ("fmt"; "math")
func main() {
fmt.Println("known: ", math.Pi*math.Pi/6)
sum := 0.
for i := 1e3; i > 0; i-- {
sum += 1 / (i * i)
}
fmt.Println("computed:", sum)
} |
http://rosettacode.org/wiki/Strip_comments_from_a_string | Strip comments from a string | Strip comments from a string
You are encouraged to solve this task according to the task description, using any language you may know.
The task is to remove text that follow any of a set of comment markers, (in these examples either a hash or a semicolon) from a string or input line.
Whitespace debacle: There is s... | #Oforth | Oforth | : stripComments(s, markers)
| firstMarker |
markers map(#[ s indexOf ]) reduce(#min) ->firstMarker
s firstMarker ifNotNull: [ left(firstMarker 1 - ) ] strip ; |
http://rosettacode.org/wiki/Strip_comments_from_a_string | Strip comments from a string | Strip comments from a string
You are encouraged to solve this task according to the task description, using any language you may know.
The task is to remove text that follow any of a set of comment markers, (in these examples either a hash or a semicolon) from a string or input line.
Whitespace debacle: There is s... | #Pascal | Pascal | while (<>)
{
s/[#;].*$//s; # remove comment
s/^\s+//; # remove leading whitespace
s/\s+$//; # remove trailing whitespace
print
} |
http://rosettacode.org/wiki/Strip_comments_from_a_string | Strip comments from a string | Strip comments from a string
You are encouraged to solve this task according to the task description, using any language you may know.
The task is to remove text that follow any of a set of comment markers, (in these examples either a hash or a semicolon) from a string or input line.
Whitespace debacle: There is s... | #Perl | Perl | while (<>)
{
s/[#;].*$//s; # remove comment
s/^\s+//; # remove leading whitespace
s/\s+$//; # remove trailing whitespace
print
} |
http://rosettacode.org/wiki/Strip_block_comments | Strip block comments | A block comment begins with a beginning delimiter and ends with a ending delimiter, including the delimiters. These delimiters are often multi-character sequences.
Task
Strip block comments from program text (of a programming language much like classic C).
Your demos should at least handle simple, non-ne... | #Raku | Raku | sample().split(/ '/*' .+? '*/' /).print;
sub sample {
' /**
* Some comments
* longer comments here that we can parse.
*
* Rahoo
*/
function subroutine() {
a = /* inline comment */ b + c ;
}
/*/ <-- tricky comments */
/**
* Another comment.
*/
function somethi... |
http://rosettacode.org/wiki/Strip_block_comments | Strip block comments | A block comment begins with a beginning delimiter and ends with a ending delimiter, including the delimiters. These delimiters are often multi-character sequences.
Task
Strip block comments from program text (of a programming language much like classic C).
Your demos should at least handle simple, non-ne... | #REXX | REXX | /* REXX ***************************************************************
* Split comments
* This program ignores comment delimiters within literal strings
* such as, e.g., in b = "--' O'Connor's widow --";
* it does not (yet) take care of -- comments (ignore rest of line)
* also it does not take care of say 667/*yuppers... |
http://rosettacode.org/wiki/String_interpolation_(included) | String interpolation (included) |
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 |... | #Euphoria | Euphoria | constant lambType = "little"
sequence s
s = sprintf("Mary had a %s lamb.",{lambType})
puts(1,s) |
http://rosettacode.org/wiki/String_interpolation_(included) | String interpolation (included) |
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 |... | #F.23 | F# | let lambType = "little"
printfn "Mary had a %s lamb." lambType |
http://rosettacode.org/wiki/String_interpolation_(included) | String interpolation (included) |
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 |... | #Factor | Factor | USE: formatting
SYMBOL: little
"little" little set
little get "Mary had a %s lamb" sprintf |
http://rosettacode.org/wiki/Strip_a_set_of_characters_from_a_string | Strip a set of characters from a string | Task
Create a function that strips a set of characters from a string.
The function should take two arguments:
a string to be stripped
a string containing the set of characters to be stripped
The returned string should contain the first string, stripped of any characters in the second argument:
print str... | #Forth | Forth | : append-char ( char str -- ) dup >r count dup 1+ r> c! + c! ; \ append char to a counted string
: strippers ( -- addr len) s" aeiAEI" ; \ a string literal returns addr and length
: stripchars ( addr1 len1 addr2 len2 -- PAD len )
0 PAD c! \ clear the PAD buffer
... |
http://rosettacode.org/wiki/Strip_a_set_of_characters_from_a_string | Strip a set of characters from a string | Task
Create a function that strips a set of characters from a string.
The function should take two arguments:
a string to be stripped
a string containing the set of characters to be stripped
The returned string should contain the first string, stripped of any characters in the second argument:
print str... | #Fortran | Fortran | elemental subroutine strip(string,set)
character(len=*), intent(inout) :: string
character(len=*), intent(in) :: set
integer :: old, new, stride
old = 1; new = 1
do
stride = scan( string( old : ), set )
if ( stride > 0 ) then
string( new : new+stride-2 ) = string( old ... |
http://rosettacode.org/wiki/String_prepend | String prepend |
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 |... | #Oforth | Oforth | " World" "Hello" swap + println |
http://rosettacode.org/wiki/String_prepend | String prepend |
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 |... | #PARI.2FGP | PARI/GP | s = "world!";
s = Str("Hello, ", s) |
http://rosettacode.org/wiki/String_prepend | String prepend |
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 |... | #Pascal | Pascal | program StringPrepend;
{$mode objfpc}{$H+}
uses
{$IFDEF UNIX}{$IFDEF UseCThreads}
cthreads,
{$ENDIF}{$ENDIF}
Classes
{ you can add units after this };
var
s: String = ' World !';
begin
s := 'Hello' + s;
WriteLn(S);
ReadLn;
end. |
http://rosettacode.org/wiki/String_comparison | String comparison |
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 |... | #D | D | import std.stdio, std.string, std.algorithm;
void main() {
auto s = "abcd";
/* Comparing two strings for exact equality */
assert (s == "abcd"); // same object
/* Comparing two strings for inequality */
assert(s != "ABCD"); // different objects
/* Comparing the lexical order of two strin... |
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... | #Clojure | Clojure | (def string "alphaBETA")
(println (.toUpperCase string))
(println (.toLowerCase string)) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.