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/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... | #CMake | CMake | string(TOUPPER alphaBETA s)
message(STATUS "Uppercase: ${s}")
string(TOLOWER alphaBETA s)
message(STATUS "Lowercase: ${s}") |
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 |... | #Component_Pascal | Component Pascal |
MODULE StringMatch;
IMPORT StdLog,Strings;
CONST
strSize = 1024;
patSize = 256;
TYPE
Matcher* = POINTER TO LIMITED RECORD
str: ARRAY strSize OF CHAR;
pat: ARRAY patSize OF CHAR;
pos: INTEGER
END;
PROCEDURE NewMatcher*(IN str: ARRAY OF CHAR): Matcher;
VAR
m: Matcher;
BEGIN
NEW(m);m.str := str$;m.pos:=... |
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.2B.2B | C++ | #include <string> // (not <string.h>!)
using std::string;
int main()
{
string s = "Hello, world!";
string::size_type length = s.length(); // option 1: In Characters/Bytes
string::size_type size = s.size(); // option 2: In Characters/Bytes
// In bytes same as above since sizeof(char) == 1
string::size_ty... |
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 ... | #Nim | Nim | proc stripped(str: string): string =
result = ""
for c in str:
if ord(c) in 32..126:
result.add c
proc strippedControl(str: string): string =
result = ""
for c in str:
if ord(c) in {32..126, 128..255}:
result.add c
echo strippedControl "\ba\x00b\n\rc\fdÄ"
echo stripped "\ba\x00b\n\rc\fd\... |
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 ... | #OCaml | OCaml | let is_control_code c =
let d = int_of_char c in
d < 32 || d = 127
let is_extended_char c =
let d = int_of_char c in
d > 127
let strip f str =
let len = String.length str in
let res = Bytes.create len in
let rec aux i j =
if i >= len
then Bytes.to_string (Bytes.sub res 0 j)
else if f str.[... |
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... | #Elena | Elena | public program()
{
var s := "Hello";
var s2 := s + " literal";
console.writeLine:s;
console.writeLine:s2;
console.readChar()
} |
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... | #Elixir | Elixir |
s = "hello"
t = s <> " literal"
IO.puts s
IO.puts t
|
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... | #Emacs_Lisp | Emacs Lisp | (defvar foo "foo")
(defvar foobar (concat foo "bar"))
(message "%sbar" foo)
(message "%s" foobar) |
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.
| #MATLAB_.2F_Octave | MATLAB / Octave | n=1:999; sum(n(mod(n,3)==0 | mod(n,5)==0)) |
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
| #NetRexx | NetRexx | /* NetRexx */
options replace format comments java crossref symbols nobinary
parse arg input
inputs = ['1234', '01234', '0xfe', '0xf0e', '0', '00', '0,2' '1', '070', '77, 8' '0xf0e, 10', '070, 16', '0xf0e, 36', '000999ABCXYZ, 36', 'ff, 16', 'f, 10', 'z, 37'] -- test data
if input.length() > 0 then inputs = [input] --... |
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
| #Nemerle | Nemerle | SS(x : list[double]) : double
{
|[] => 0.0
|_ => x.Map(fun (x) {x*x}).FoldLeft(0.0, _+_)
} |
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
| #NetRexx | NetRexx | /*NetRexx *************************************************************
* program to sum the squares of a vector of fifteen numbers.
* translated from REXX
* 14.05.2013 Walter Pachl
**********************************************************************/
numeric digits 50 /*allow 50-digit # (default is... |
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... | #Jsish | Jsish | #!/usr/bin/env jsish
/* Strip whitespace from string, in Jsi */
var str = ' \n \t String with whitespace \t \n ';
;'Original';
;str;
;'Default trim characters are space, tab, newline, carriage return';
;'trimLeft, remove leading characters';
;str.trimLeft();
;'trimRight, remove trailing characters';
;str.trimRigh... |
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... | #Julia | Julia | julia> s = " \t \r \n String with spaces \t \r \n "
" \t \r \n String with spaces \t \r \n "
julia> lstrip(s)
"String with spaces \t \r \n "
julia> rstrip(s)
" \t \r \n String with spaces"
julia> strip(s)
"String with spaces" |
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 |... | #Erlang | Erlang | 1> N = 3.
2> M = 5.
3> string:sub_string( "abcdefghijklm", N ).
"cdefghijklm"
4> string:sub_string( "abcdefghijklm", N, N + M - 1 ).
"cdefg"
6> string:sub_string( "abcdefghijklm", 1, string:len("abcdefghijklm") - 1 ).
"abcdefghijkl"
7> Start_character = string:chr( "abcdefghijklm", $e ).
8> string:sub_strin... |
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 |... | #Euphoria | Euphoria | sequence baseString, subString, findString
integer findChar
integer m, n
baseString = "abcdefghijklmnopqrstuvwxyz"
-- starting from n characters in and of m length;
n = 12
m = 5
subString = baseString[n..n+m-1]
puts(1, subString )
puts(1,'\n')
-- starting from n characters in, up to the end of the string;
n = 12
... |
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.
| #Java | Java | 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... | #Pascal | Pascal | PROGRAM OISC;
CONST
MAXADDRESS = 1255;
TYPE
MEMORY = PACKED ARRAY [0 .. MAXADDRESS] OF INTEGER;
VAR
MEM : MEMORY;
FILENAME : STRING;
PROCEDURE LOADTEXT (FILENAME : STRING; VAR MEM : MEMORY);
VAR
NUMBERS : TEXT;
ADDRESS : INTEGER;
BEGIN
ASSIGN (NUMBERS, FILENAME);
ADDRESS := 0;
RESET (NUMBERS);
... |
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... | #Lambdatalk | Lambdatalk |
{def R rosetta} -> rosetta
{W.rest {R}} -> osetta
{W.reverse {W.rest {W.reverse {R}}}} -> rosett
{W.rest {W.reverse {W.rest {W.reverse {R}}}}} -> osett
or
{W.slice 1 {W.length {R}} {R}} -> osetta
{W.slice 0 {- {W.length {... |
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.
| #Lasso | Lasso | local(x = array(1,2,3,4,5,6,7,8,9,10))
// sum of array elements
'Sum: '
with n in #x
sum #n
'\r'
// product of arrray elements
'Product: '
local(product = 1)
with n in #x do => { #product *= #n }
#product |
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.
| #Liberty_BASIC | Liberty BASIC | Dim array(19)
For i = 0 To 19
array(i) = Int(Rnd(1) * 20)
Next i
'product must first equal one or you will get 0 as the product
product = 1
For i = 0 To 19
sum = (sum + array(i))
product = (product * array(i))
next i
Print "Sum is " + str$(sum)
Print "Product is " + str$(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... | #Groovy | Groovy | println ((1000..1).collect { x -> 1/(x*x) }.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... | #Phix | Phix | with javascript_semantics
function strip_comments(string s, sequence comments={"#",";"})
for i=1 to length(comments) do
integer k = match(comments[i],s)
if k then
s = s[1..k-1]
s = trim_tail(s)
end if
end for
return s
end function
?strip_comments("apples, pe... |
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... | #PicoLisp | PicoLisp | (for Str '("apples, pears # and bananas" "apples, pears ; and bananas")
(prinl (car (split (chop Str) "#" ";"))) ) |
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... | #Ring | Ring |
example = "123/*456*/abc/*def*/789"
example2 = example
nr = 1
while nr = 1
n1 = substr(example2,"/*")
n2 = substr(example2,"*/")
if n1 > 0 and n2 > 0
example3 = substr(example2,n1,n2-n1+2)
example2 = substr(example2,example3,"")
else nr = 0 ok
end
see example2 + nl
|
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... | #Ruby | Ruby | def remove_comments!(str, comment_start='/*', comment_end='*/')
while start_idx = str.index(comment_start)
end_idx = str.index(comment_end, start_idx + comment_start.length) + comment_end.length - 1
str[start_idx .. end_idx] = ""
end
str
end
def remove_comments(str, comment_start='/*', comment_end='*/... |
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 |... | #Falcon | Falcon |
/* created by Aykayayciti Earl Lamont Montgomery
April 9th, 2018 */
size = "little"
> @ "Mary had a $size lamb"
// line 1: use of the = operator
// line 2: use of the @ and $ operator
|
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 |... | #Fantom | Fantom |
fansh> x := "little"
little
fansh> echo ("Mary had a $x lamb")
Mary had a little 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... | #FreeBASIC | FreeBASIC | ' FB 1.05.0 Win64
Function stripChars(s As Const String, chars As Const String) As String
If s = "" Then Return ""
Dim count As Integer = 0
Dim strip(0 To Len(s) - 1) As Boolean
For i As Integer = 0 To Len(s) - 1
For j As Integer = 0 To Len(chars) - 1
If s[i] = chars[j] Then
count += 1
... |
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 |... | #Perl | Perl | use strict;
use warnings;
use feature ':all';
# explicit concatentation
$_ = 'bar';
$_ = 'Foo' . $_;
say;
# lvalue substr
$_ = 'bar';
substr $_, 0, 0, 'Foo';
say;
# interpolation as concatenation
# (NOT safe if concatenate sigils)
$_ = 'bar';
$_ = "Foo$_";
say; |
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 |... | #Phix | Phix | string s = "World"
s = "Hello "&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 |... | #Dyalect | Dyalect | func compare(a, b) {
if a == b {
print("'\(a)' and '\(b)' are lexically equal.")
}
if a != b {
print("'\(a)' and '\(b)' are not lexically equal.")
}
if a < b {
print("'\(a)' is lexically before '\(b)'.")
}
if a > b {
print("'\(a)' is lexically after '\(b)'.")
}
if a >= b {
prin... |
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 |... | #Elena | Elena | import extensions;
compareStrings = (val1,val2)
{
if (val1 == val2) { console.printLine("The strings ",val1," and ",val2," are equal") };
if (val1 != val2) { console.printLine("The strings ",val1," and ",val2," are not equal") };
if (val1 > val2) { console.printLine("The string ",val1," is lexically afte... |
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... | #COBOL | COBOL | IDENTIFICATION DIVISION.
PROGRAM-ID. string-case-85.
DATA DIVISION.
WORKING-STORAGE SECTION.
01 example PIC X(9) VALUE "alphaBETA".
01 result PIC X(9).
PROCEDURE DIVISION.
DISPLAY "Example: " example
*> Using the intrinsic functions.
... |
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 |... | #D | D | void main() {
import std.stdio;
import std.algorithm: startsWith, endsWith, find, countUntil;
"abcd".startsWith("ab").writeln; // true
"abcd".endsWith("zn").writeln; // false
"abab".find("bb").writeln; // empty array (no match)
"abcd".find("bc").writeln; // "b... |
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... | #Clean | Clean | import StdEnv
strlen :: String -> Int
strlen string = size string
Start = strlen "Hello, world!" |
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 ... | #Pascal | Pascal | program StripCharacters(output);
function Strip (s: string; control, extended: boolean): string;
var
index: integer;
begin
Strip := '';
for index:= 1 to length(s) do
if not ((control and (ord(s[index]) <= 32)) or (extended and (ord(s[index]) > 127))) then
Strip := Strip + s[index];
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... | #Erlang | Erlang | S = "hello",
S1 = S ++ " literal",
io:format ("~s literal~n",[S]),
io:format ("~s~n",[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... | #ERRE | ERRE |
..........
S$="HELLO"
PRINT(S$;" LITERAL") ! or S$+" LITERAL"
S2$=S$+" LITERAL"
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.
| #Maxima | Maxima | sumi(n, inc):= block(
[kmax],
/* below n means [1 .. n-1] */
kmax: quotient(n-1, inc),
return(
''(ev(sum(inc*k, k, 1, kmax), simpsum))
)
);
sum35(n):= sumi(n, 3) + sumi(n, 5) - sumi(n, 15);
sum35(1000);
sum35(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
| #Never | Never |
func sum_digits(n : int, base : int) -> int {
var sum = 0;
do
{
sum = sum + n % base;
n = n / base
}
while (n != 0);
sum
}
func main() -> int {
print(sum_digits(1, 10));
print(sum_digits(12345, 10));
print(sum_digits(123045, 10));
print(sum_digits(0xfe, 16... |
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
| #Nim | Nim | proc sumdigits(n, base: Natural): Natural =
var n = n
while n > 0:
result += n mod base
n = n div base
echo sumDigits(1, 10)
echo sumDigits(12345, 10)
echo sumDigits(123045, 10)
echo sumDigits(0xfe, 16)
echo sumDigits(0xf0e, 16) |
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
| #NewLISP | NewLISP | (apply + (map (fn(x) (* x x)) '(3 1 4 1 5 9)))
-> 133
(apply + (map (fn(x) (* x x)) '()))
-> 0 |
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
| #Nim | Nim | import math, sequtils
proc sumSquares[T: SomeNumber](a: openArray[T]): T =
sum(a.mapIt(it * it))
let a1 = [1, 2, 3, 4, 5]
echo a1, " → ", sumSquares(a1)
let a2: seq[float] = @[]
echo a2, " → ", sumSquares(a2) |
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... | #Kotlin | Kotlin | fun main(args: Array<String>) {
val s = " \tRosetta Code \r \u2009 \n"
println("Untrimmed => [$s]")
println("Left Trimmed => [${s.trimStart()}]")
println("Right Trimmed => [${s.trimEnd()}]")
println("Fully Trimmed => [${s.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... | #Ksh | Ksh |
#!/bin/ksh
# Strip whitespace from a string/Top and tail
# # Variables:
#
str=${1:-" This is a test. "}
# # Functions:
#
# # Function _striphead(str) - Return str with leading while space stripped
#
function _striphead {
typeset _str ; _str="$1"
echo "${_str##*(\s)}"
}
# # Function _striptail(str) -... |
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 |... | #F.23 | F# | [<EntryPoint>]
let main args =
let s = "一二三四五六七八九十"
let n, m = 3, 2
let c = '六'
let z = "六七八"
printfn "%s" (s.Substring(n, m))
printfn "%s" (s.Substring(n))
printfn "%s" (s.Substring(0, s.Length - 1))
printfn "%s" (s.Substring(s.IndexOf(c), m))
printfn "%s" (s.Substring(s.IndexOf(... |
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.
| #JavaScript | JavaScript | //-------------------------------------------[ Dancing Links and Algorithm X ]--
/**
* The doubly-doubly circularly linked data object.
* Data object X
*/
class DoX {
/**
* @param {string} V
* @param {!DoX=} H
*/
constructor(V, H) {
this.V = V;
this.L = this;
this.R = this;
this.U = this... |
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... | #Perl | Perl | #!/usr/bin/env perl
use strict;
use warnings;
my $file = shift;
my @memory = ();
open (my $fh, $file);
while (<$fh>) {
chomp;
push @memory, split;
}
close($fh);
my $ip = 0;
while ($ip >= 0 && $ip < @memory) {
my ($a, $b, $c) = @memory[$ip,$ip+1,$ip+2];
$ip += 3;
if ($a < 0) {
$memory[$b] = ord(getc);
} els... |
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... | #Lasso | Lasso | local(str = 'The quick grey rhino jumped over the lazy green fox.')
// String with first character removed
string_remove(#str,-startposition=1,-endposition=1)
// String with last character removed
string_remove(#str,-startposition=#str->size,-endposition=#str->size)
// String with both the first and last characte... |
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... | #Liberty_BASIC | Liberty BASIC | string$ = "Rosetta Code"
Print Mid$(string$, 2)
Print Left$(string$, (Len(string$) - 1))
Print Mid$(string$, 2, (Len(string$) - 2)) |
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.
| #Lingo | Lingo | on sum (intList)
res = 0
repeat with v in intList
res = res + v
end repeat
return res
end
on product (intList)
res = 1
repeat with v in intList
res = res * v
end repeat
return res
end |
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.
| #LiveCode | LiveCode | //sum
put "1,2,3,4" into nums
split nums using comma
answer sum(nums)
// product
local prodNums
repeat for each element n in nums
if prodNums is empty then
put n into prodNums
else
multiply prodnums by n
end if
end repeat
answer prodnums |
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... | #Haskell | Haskell | sum [1 / x ^ 2 | x <- [1..1000]] |
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... | #Haxe | Haxe | using StringTools;
class Main {
static function main() {
var sum = 0.0;
for (x in 1...1001)
sum += 1.0/(x * x);
Sys.println('Approximation: $sum');
Sys.println('Exact: '.lpad(' ', 15) + Math.PI * Math.PI / 6);
}
} |
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... | #PL.2FI | PL/I | k = search(text, '#;');
if k = 0 then put skip list (text);
else put skip list (substr(text, 1, k-1)); |
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... | #Prolog | Prolog | stripcomment(A,B) :- stripcomment(A,B,a).
stripcomment([A|AL],[A|BL],a) :- \+ A=0';, \+ A=0'# , \+ A=10, \+ A=13 , stripcomment(AL,BL,a).
stripcomment([A|AL], BL ,a) :- ( A=0';; A=0'#), \+ A=10, \+ A=13 , stripcomment(AL,BL,b).
stripcomment([A|AL], BL ,b) :- \+ A=10, \+ A=13 , stripcomment(... |
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... | #Scala | Scala | import java.util.regex.Pattern.quote
def strip1(x: String, s: String = "/*", e: String = "*/") =
x.replaceAll("(?s)"+quote(s)+".*?"+quote(e), "") |
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... | #Seed7 | Seed7 | $ include "seed7_05.s7i";
const proc: main is func
local
const string: stri is "\
\ /**\n\
\ * Some comments\n\
\ * longer comments here that we can parse.\n\
\ *\n\
\ * Rahoo\n\
\ */\n\
\ function subroutine() {\n\
\ a = /* inline ... |
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 |... | #Forth | Forth | variable 'src
variable #src
variable 'out
variable #out
: Replace~ dup [char] ~ = \ test for escape char
if 'out @ 1+ #out @ type drop \ replace the escape char
else emit \ otherwise write char
then... |
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 |... | #Fortran | Fortran | program interpolate
write (*,*) trim(inter("Mary had a X lamb.","X","little"))
contains
elemental function inter(string,place,ins) result(new)
character(len=*), intent(in) :: string,place,ins
character(len=len(string)+max(0,len(ins)-len(place))) :: new
integer ... |
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... | #Frink | Frink | stripchars[str, remove] :=
{
set = toSet[chars[remove]]
return char[remove[char[str], {|c, set| set.contains[c]}, set]]
}
println[stripchars["She was a soul stripper. She took my heart!","aei"]]
|
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.C5.8Drmul.C3.A6 | Fōrmulæ | Public Sub Main()
Print StripChars("She was a soul stripper. She took my heart!", "aei")
End
'_____________________________________________________________________
Public Sub StripChars(sText As String, sRemove As String) As String
Dim siCount As Short
For siCount = 1 To Len(sRemove)
sText = Replace(sText, Mid(... |
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 |... | #Picat | Picat | go =>
S = "123456789",
println(S),
S := "A" ++ S,
println(S),
% append
append("B",S,T),
S := T,
println(S),
% insert at position
S := insert(S,1,'C'), % note: must be a char to keep it a proper string
println(S),
% insert many characters
S := insert_all(S,1,"DE"),
println(S),
nl. |
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 |... | #PicoLisp | PicoLisp | (setq Str1 "12345678!")
(setq Str1 (pack "0" Str1))
(println Str1) |
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 |... | #PL.2FI | PL/I |
Pre_Cat: procedure options (main); /* 2 November 2013 */
declare s character (100) varying;
s = ' bowl';
s = 'dust' || s;
put (s);
end Pre_Cat;
|
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 |... | #Plain_TeX | Plain TeX | \def\prepend#1#2{% #1=string #2=macro containing a string
\def\tempstring{#1}%
\expandafter\expandafter\expandafter
\def\expandafter\expandafter\expandafter
#2\expandafter\expandafter\expandafter
{\expandafter\tempstring#2}%
}
\def\mystring{world!}
\prepend{Hello }\mystring
Result : \mystring
\bye |
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 |... | #Elixir | Elixir | s = "abcd"
s == "abcd" #=> true
s == "abce" #=> false
s != "abcd" #=> false
s != "abce" #=> true
s > "abcd" #=> false
s < "abce" #=> true
s >= "abce" #=> false
s <= "abce" #=> true |
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 |... | #Erlang | Erlang |
10> V = "abcd".
"abcd"
11> V =:= "abcd".
true
12> V =/= "abcd".
false
13> V < "b".
true
15> V > "aa".
true
16> string:to_lower(V) =:= string:to_lower("ABCD").
true
|
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... | #ColdFusion | ColdFusion | <cfset upper = UCase("alphaBETA")>
<cfset lower = LCase("alphaBETA")> |
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... | #Common_Lisp | Common Lisp | CL-USER> (string-upcase "alphaBETA")
"ALPHABETA" |
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 |... | #DCL | DCL | $ first_string = p1
$ length_of_first_string = f$length( first_string )
$ second_string = p2
$ length_of_second_string = f$length( second_string )
$ offset = f$locate( second_string, first_string )
$ if offset .eq. 0
$ then
$ write sys$output "first string starts with second string"
$ else
$ write sys$output "first s... |
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... | #Clojure | Clojure | (def utf-8-octet-length #(-> % (.getBytes "UTF-8") count))
(map utf-8-octet-length ["møøse" "𝔘𝔫𝔦𝔠𝔬𝔡𝔢" "J\u0332o\u0332s\u0332e\u0301\u0332"]) ; (7 28 14)
(def utf-16-octet-length (comp (partial * 2) count))
(map utf-16-octet-length ["møøse" "𝔘𝔫𝔦𝔠𝔬𝔡𝔢" "J\u0332o\u0332s\u0332e\u0301\u0332"]) ; (10 28 18)
... |
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 ... | #Peloton | Peloton | Create variable with control characters: <@ SAYLETVARLIT>i|This string has control characters
- - - - - -
in it</@>
Strip control characters <@ SAYSALVAR>i</@>
Assign infix <@ LETVARSALVAR>j|i</@> <@ SAYVAR>j</@>
Assign prepend <@ LETSALVARVAR>k|i</@> <@ SAYVAR>k</@>
Reflexive assign <@ ACTSALVAR>i</@> <@ SAYVAR>i<... |
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 ... | #Perl | Perl | #!/usr/bin/perl -w
use strict ;
my @letters ;
my @nocontrols ;
my @noextended ;
for ( 1..40 ) {
push @letters , int( rand( 256 ) ) ;
}
print "before sanitation : " ;
print join( '' , map { chr( $_ ) } @letters ) ;
print "\n" ;
@nocontrols = grep { $_ > 32 && $_ != 127 } @letters ;
print "Without controls: " ;
p... |
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... | #Euphoria | Euphoria | sequence s, s1
s = "hello"
puts(1, s & " literal")
puts(1,'\n')
s1 = s & " literal"
print (1, s1))
puts(1,'\n') |
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... | #Excel | Excel |
=CONCATENATE(A1;" ";B1)
|
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.
| #MiniScript | MiniScript | // simple version:
sum35 = function(n)
sum = 0
for i in range(3, n-1, 3)
sum = sum + i
end for
for i in range(5, n-1, 5)
if i % 3 then sum = sum + i // (skip multiples of 3 here)
end for
return sum
end function
print 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
| #Oberon-2 | Oberon-2 |
MODULE SumDigits;
IMPORT Out;
PROCEDURE Sum(n: LONGINT;base: INTEGER): LONGINT;
VAR
sum: LONGINT;
BEGIN
sum := 0;
WHILE (n > 0) DO
INC(sum,(n MOD base));
n := n DIV base
END;
RETURN sum
END Sum;
BEGIN
Out.String("1 : ");Out.LongInt(Sum(1,10),10);Out.Ln;
Out.String("1234 : ");Out.LongInt(Sum(1234,10),1... |
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
| #Objeck | Objeck |
bundle Default {
class Sum {
function : native : SquaredSum(values : Float[]) ~ Float {
sum := 0.0;
for(i := 0 ; i < values->Size() ; i += 1;) {
sum += (values[i] * values[i]);
};
return sum;
}
function : Main(args : String[]) ~ Nil {
SquaredSum([3.0, 1.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... | #Lambdatalk | Lambdatalk |
initial string : {def string ___String with "_" displaying space_____}
-> string ___String with "_" displaying space_____
trimLeft : {S.replace ^_+ by in {string}}
-> String with "_" displaying space_____
trimRight : {S.replace _+$ by in {string}}
-> ___String with "_" ... |
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... | #Lasso | Lasso | // String with leading whitespace removed
'>' + (' \t Hello')->trim& + '<'
// String with trailing whitespace removed
'>' + ('Hello \t ')->trim& + '<'
// String with both leading and trailing whitespace removed
'>' + (' \t Hello \t ')->trim& + '<' |
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 |... | #Factor | Factor | USING: math sequences kernel ;
! starting from n characters in and of m length
: subseq* ( from length seq -- newseq ) [ over + ] dip subseq ;
! starting from n characters in, up to the end of the string
: dummy ( seq n -- tailseq ) tail ;
! whole string minus last character
: dummy1 ( seq -- headseq ) but-last ;... |
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 |... | #Falcon | Falcon |
/* created by Aykayayciti Earl Lamont Montgomery
April 9th, 2018 */
s = "FalconPL is not just a multi-paradign language but also fun"
n = 12
m = 5
> "starting from n characters in and of m length: ", s[n:n+m]
> "starting from n characters in, up to the end of the string: ", s[n:]
> "whole string minus last characte... |
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.
| #Julia | Julia | function check(i, j)
id, im = div(i, 9), mod(i, 9)
jd, jm = div(j, 9), mod(j, 9)
jd == id && return true
jm == im && return true
div(id, 3) == div(jd, 3) &&
div(jm, 3) == div(im, 3)
end
const lookup = zeros(Bool, 81, 81)
for i in 1:81
for j in 1:81
lookup[i,j] = check(i-1, j-... |
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... | #Phix | Phix | procedure subleq(sequence code)
integer ip := 0
while ip>=0 do
integer {a,b,c} = code[ip+1..ip+3]
ip += 3
if a=-1 then
code[b+1] = iff(platform()=JS?'?':getc(0))
elsif b=-1 then
puts(1,code[a+1])
else
code[b+1] -= code[a+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... | #LiveCode | LiveCode | put "pple" into x
answer char 2 to len(x) of x // pple
answer char 1 to -2 of x // ppl
answer char 2 to -2 of x // ppl |
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... | #Locomotive_Basic | Locomotive Basic | 10 a$="knight":b$="socks":c$="brooms"
20 PRINT MID$(a$,2)
30 PRINT LEFT$(b$,LEN(b$)-1)
40 PRINT MID$(c$,2,LEN(c$)-2) |
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.
| #Logo | Logo | print apply "sum arraytolist {1 2 3 4 5}
print apply "product arraytolist {1 2 3 4 5} |
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.
| #Lua | Lua |
function sumf(a, ...) return a and a + sumf(...) or 0 end
function sumt(t) return sumf(unpack(t)) end
function prodf(a, ...) return a and a * prodf(...) or 1 end
function prodt(t) return prodf(unpack(t)) end
print(sumt{1, 2, 3, 4, 5})
print(prodt{1, 2, 3, 4, 5}) |
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... | #HicEst | HicEst | REAL :: a(1000)
a = 1 / $^2
WRITE(ClipBoard, Format='F17.15') SUM(a) |
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... | #PureBasic | PureBasic | Procedure.s Strip_comments(Str$)
Protected result$=Str$, l, l1, l2
l1 =FindString(Str$,"#",1)
l2 =FindString(Str$,";",1)
;
; See if any comment sign was found, prioritizing '#'
If l1
l=l1
ElseIf l2
l=l2
EndIf
l-1
If l>0
result$=Left(Str$,l)
EndIf
ProcedureReturn result$
EndProcedure |
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... | #Python | Python | def remove_comments(line, sep):
for s in sep:
i = line.find(s)
if i >= 0:
line = line[:i]
return line.strip()
# test
print remove_comments('apples ; pears # and bananas', ';#')
print remove_comments('apples ; pears # and bananas', '!')
|
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... | #Sidef | Sidef | func strip_block_comments(code, beg='/*', end='*/') {
var re = Regex.new(beg.escape + '.*?' + end.escape, 's');
code.gsub(re, '');
}
say strip_block_comments(ARGF.slurp); |
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... | #SNOBOL4 | SNOBOL4 |
* Program: strip_block_comments.sbl
* To run: sbl -r extract_extension.sbl
* Description: Strip block comments.
* Can use different begin and end delimiters.
* Handles comment nesting and unmatched end delimiters.
* Unmatched begin delimiters remove text to end of file.
* ... |
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... | #Swift | Swift | import Foundation
func stripBlocks(from str: String, open: String = "/*", close: String = "*/") -> String {
guard !open.isEmpty && !close.isEmpty else {
return str
}
var ret = str
while let begin = ret.range(of: open), let end = ret[begin.upperBound...].range(of: close) {
ret.replaceSubrange(Range... |
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 |... | #FreeBASIC | FreeBASIC | ' FB 1.05.0 Win64
#Include "crt/stdio.bi" '' header needed for printf
Dim x As String = "big"
Print "Mary had a "; x; " lamb" '' FB's native Print statement
x = "little"
printf("Mary also had a %s lamb", x)
Sleep |
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 |... | #Frink | Frink | x = "little"
println["Mary had a $x 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... | #Gambas | Gambas | Public Sub Main()
Print StripChars("She was a soul stripper. She took my heart!", "aei")
End
'_____________________________________________________________________
Public Sub StripChars(sText As String, sRemove As String) As String
Dim siCount As Short
For siCount = 1 To Len(sRemove)
sText = Replace(sText, Mid(... |
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... | #Go | Go | package main
import (
"fmt"
"strings"
)
func stripchars(str, chr string) string {
return strings.Map(func(r rune) rune {
if strings.IndexRune(chr, r) < 0 {
return r
}
return -1
}, str)
}
func main() {
fmt.Println(stripchars("She was a soul stripper. She took... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.