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/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... | #Nim | Nim | import deques, sequtils
template shfl(idx): untyped = (K*(idx+1)) mod I
func mutuallyprime(I, K: int16): bool {.compiletime.} =
## compile time check shuffling works properly
let
x = {1'i16..I}
s = x.toSeq
var r: set[int16]
for n in 0..<I:
r.incl s[n.shfl]
r == x
func `%`(i: int, m: int): in... |
http://rosettacode.org/wiki/Substitution_cipher | Substitution cipher | Substitution Cipher Implementation - File Encryption/Decryption
Task
Encrypt a input/source file by replacing every upper/lower case alphabets of the source file with another predetermined upper/lower case alphabets or symbols and save it into another output/encrypted file and then again convert that output/encrypt... | #VBScript | VBScript |
option explicit
const maxk=94
dim key(94)
a="I'm working on modernizing Rosetta Code's infrastructure. Starting with communications."&_
" Please accept this time-limited open invite to RC's Slack.. --Michael Mol (talk) 20:59, 30 May 2020 (UTC)"
sub gen 'swaps items not previusly affected by a swap
dim i,m,... |
http://rosettacode.org/wiki/Substitution_cipher | Substitution cipher | Substitution Cipher Implementation - File Encryption/Decryption
Task
Encrypt a input/source file by replacing every upper/lower case alphabets of the source file with another predetermined upper/lower case alphabets or symbols and save it into another output/encrypted file and then again convert that output/encrypt... | #Wren | Wren | var key = "]kYV}(!7P$n5_0i R:?jOWtF/=-pe'AD&@r6\%ZXs\"v*N[#wSl9zq2^+g;LoB`aGh{3.HIu4fbK)mU8|dMET><,Qc\\C1yxJ"
var encode = Fn.new { |s|
var res = ""
for (c in s) res = res + key[c.bytes[0] - 32]
return res
}
var decode = Fn.new { |s|
var res = ""
for (c in s) res = res + String.fromByte(key.inde... |
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.
| #FreeBASIC | FreeBASIC | ' FB 1.05.0 Win64
Dim a(1 To 4) As Integer = {1, 4, 6, 3}
Dim As Integer i, sum = 0, prod = 1
For i = 1 To 4
sum += a(i)
prod *= a(i)
Next
Print "Sum ="; sum
Print "Product ="; prod
Print
Print "Press any key to quit"
Sleep |
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.
| #Frink | Frink |
a = [1,2,3,5,7]
sum[a]
product[a]
|
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... | #Erlang | Erlang | lists:sum([1/math:pow(X,2) || X <- lists:seq(1,1000)]). |
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... | #Clojure | Clojure | > (apply str (take-while #(not (#{\# \;} %)) "apples # comment"))
"apples " |
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... | #COBOL | COBOL | identification division.
program-id. StripComments.
data division.
working-storage section.
01 line-text pic x(64).
procedure division.
main.
move "apples, pears # and bananas" to line-text
perform show-striped-text
mo... |
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... | #Fortran | Fortran |
SUBROUTINE UNBLOCK(THIS,THAT) !Removes block comments bounded by THIS and THAT.
Copies from file INF to file OUT, record by record, except skipping null output records.
CHARACTER*(*) THIS,THAT !Starting and ending markers.
INTEGER LOTS !How long is a piece of string?
PARAMETER (LOTS = 666... |
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 |... | #AArch64_Assembly | AArch64 Assembly |
/* ARM assembly AARCH64 Raspberry PI 3B */
/* program insertString64.s */
/* In assembler, there is no function to insert a chain */
/* so this program offers two functions to insert */
/*******************************************/
/* Constantes file */
/*********************************... |
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 |... | #Action.21 | Action! | PROC Main()
CHAR ARRAY extra="little"
PrintF("Mary had a %S lamb.%E",extra)
RETURN |
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 |... | #Ada | Ada | with Ada.Strings.Fixed, Ada.Text_IO;
use Ada.Strings, Ada.Text_IO;
procedure String_Replace is
Original : constant String := "Mary had a @__@ lamb.";
Tbr : constant String := "@__@";
New_Str : constant String := "little";
Index : Natural := Fixed.Index (Original, Tbr);
begin
Put_Line (Fixed.Replace_Slic... |
http://rosettacode.org/wiki/Sum_to_100 | Sum to 100 | Task
Find solutions to the sum to one hundred puzzle.
Add (insert) the mathematical
operators + or - (plus
or minus) before any of the digits in the
decimal numeric string 123456789 such that the
resulting mathematical expression adds up to a
particular sum (in this iconic case, ... | #PureBasic | PureBasic | #START=6561
#STOPP=19682
#SUMME=100
#BASIS="123456789"
Structure TSumTerm
sum.i
ter.s
EndStructure
NewList Solutions.TSumTerm()
NewMap SolCount.i()
Dim op.s{1}(8)
Dim b.s{1}(8)
PokeS(@b(),#BASIS)
Procedure StripTerm(*p_Term)
If PeekS(*p_Term,1)="+" : PokeC(*p_Term,' ') : EndIf
EndProcedure
Procedure.s Tri... |
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... | #AWK | AWK | #!/usr/bin/awk -f
BEGIN {
x = "She was a soul stripper. She took my heart!";
print x;
gsub(/[aei]/,"",x);
print x;
} |
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... | #BaCon | BaCon | text$ = "She was a soul stripper. She took my heart!"
PRINT text$
PRINT EXTRACT$(text$, "[aei]", TRUE)
|
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 |... | #ColdFusion | ColdFusion |
<cfoutput>
<cfset who = "World!">
#"Hello " & who#
</cfoutput>
|
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 |... | #Common_Lisp | Common Lisp | (defmacro prependf (s &rest strs)
"Prepend the given string variable with additional strings. The string variable is modified in-place."
`(setf ,s (concatenate 'string ,@strs ,s)))
(defvar *str* "foo")
(prependf *str* "bar")
(format T "~a~%" *str*) |
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 |... | #D | D | import std.stdio;
void main() {
string s = "world!";
s = "Hello " ~ s;
writeln(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 |... | #Aime | Aime | text s, t;
s = "occidental";
t = "oriental";
# operator case sensitive comparison
o_form("~ vs ~ (==, !=, <, <=, >=, >): ~ ~ ~ ~ ~ ~\n", s, t, s == t, s != t, s < t, s <= t, s >= t, s > t);
s = "Oriental";
t = "oriental";
# case sensitive comparison
o_form("~ vs ~ (==, !=, <, >): ~ ~ ~ ~\n", s, t, !compare(s, t... |
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 |... | #ALGOL_68 | ALGOL 68 | STRING a := "abc ", b := "ABC ";
# when comparing strings, Algol 68 ignores trailing blanks #
# so e.g. "a" = "a " is true #
# test procedure, prints message if condition is TRUE #
PROC test = ( BOOL condition, STRING mess... |
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... | #68000_Assembly | 68000 Assembly | UpperCase:
;input: A0 = pointer to the string's base address.
;alters the string in-place.
MOVE.B (A0),D0 ;load a letter
BEQ .Terminated ;we've reached the null terminator.
CMP.B #'a',D0 ;compare to ascii code for a
BCS .overhead ;if less than a, keep looping.
CMP.B #'z',D0 ;compare to ... |
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 |... | #AppleScript | AppleScript | set stringA to "I felt happy because I saw the others were happy and because I knew I should feel happy, but I wasn’t really happy."
set string1 to "I felt happy"
set string2 to "I should feel happy"
set string3 to "I wasn't really happy"
-- Determining if the first string starts with second string
stringA starts w... |
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... | #Action.21 | Action! | PROC Test(CHAR ARRAY s)
PrintF("Length of ""%S"" is %B%E",s,s(0))
RETURN
PROC Main()
Test("Hello world!")
Test("")
RETURN |
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... | #ActionScript | ActionScript |
package {
import flash.display.Sprite;
import flash.events.Event;
import flash.utils.ByteArray;
public class StringByteLength extends Sprite {
public function StringByteLength() {
if ( stage ) _init();
else addEventListener(Event.ADDED_TO_STAGE, _init);
}
... |
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 ... | #Clojure | Clojure | ; generate our test string of characters with control and extended characters
(def range-of-chars (apply str (map char (range 256))))
; filter out the control characters:
(apply str (filter #(not (Character/isISOControl %)) range-of-chars))
; filter to return String of characters that are between 32 - 126:
(apply s... |
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 ... | #Common_Lisp | Common Lisp | (defun control-char-p (ch)
(or (< (char-code ch) 32)
(= (char-code ch) 127)))
(defun extended-char-p (ch)
(> (char-code ch) 127))
(defun strip-special-chars (string &key strip-extended)
(let ((needs-removing-p (if strip-extended
(lambda (ch)
(o... |
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... | #Apex | Apex |
String s1 = 'Hello ';
String s2 = 'Salesforce Developer!';
String s3 = s1+s2;
// Print output
System.debug(s3); |
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... | #AppleScript | AppleScript | try
set endMsg to "world!"
set totMsg to "Hello, " & endMsg
display dialog totMsg
end try |
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.
| #Groovy | Groovy | def sumMul = { n, f -> BigInteger n1 = (n - 1) / f; f * n1 * (n1 + 1) / 2 }
def sum35 = { sumMul(it, 3) + sumMul(it, 5) - sumMul(it, 15) } |
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
| #Groovy | Groovy | def digitsum = { number, radix = 10 ->
Integer.toString(number, radix).collect { Integer.parseInt(it, radix) }.sum()
} |
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
| #JavaScript | JavaScript | function sumsq(array) {
var sum = 0;
var i, iLen;
for (i = 0, iLen = array.length; i < iLen; i++) {
sum += array[i] * array[i];
}
return sum;
}
alert(sumsq([1,2,3,4,5])); // 55 |
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... | #Common_Lisp | Common Lisp | ; Common whitespace characters
(defvar *whitespace* '(#\Space #\Newline #\Tab))
(defvar str " foo bar baz ")
(string-trim *whitespace* str)
; -> "foo bar baz"
(string-left-trim *whitespace* str)
; -> "foo bar baz "
(string-right-trim *whitespace* str)
; -> " foo bar baz"
; Whitespace ch... |
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... | #Crystal | Crystal |
def strip_whitepace(s)
puts s.lstrip()
puts s.rstrip()
puts s.strip()
end
strip_whitepace("\t hello \t")
# => hello
# => hello
# => hello
|
http://rosettacode.org/wiki/Strong_and_weak_primes | Strong and weak primes |
Definitions (as per number theory)
The prime(p) is the pth prime.
prime(1) is 2
prime(4) is 7
A strong prime is when prime(p) is > [prime(p-1) + prime(p+1)] ÷ 2
A weak prime is when prime(p) is < [prime(p-1) + prime(p+1)] ÷ 2
Note that the defin... | #Perl | Perl | use ntheory qw(primes vecfirst);
sub comma {
(my $s = reverse shift) =~ s/(.{3})/$1,/g;
$s =~ s/,(-?)$/$1/;
$s = reverse $s;
}
sub below { my ($m, @a) = @_; vecfirst { $a[$_] > $m } 0..$#a }
my (@strong, @weak, @balanced);
my @primes = @{ primes(10_000_019) };
for my $k (1 .. $#primes - 1) {
my ... |
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 |... | #C.2B.2B | C++ | #include <iostream>
#include <string>
int main()
{
std::string s = "0123456789";
int const n = 3;
int const m = 4;
char const c = '2';
std::string const sub = "456";
std::cout << s.substr(n, m)<< "\n";
std::cout << s.substr(n) << "\n";
std::cout << s.substr(0, s.size()-1) << "\n";
std::cout << s... |
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.
| #D | D | import std.stdio, std.range, std.string, std.algorithm, std.array,
std.ascii, std.typecons;
struct Digit {
immutable char d;
this(in char d_) pure nothrow @safe @nogc
in { assert(d_ >= '0' && d_ <= '9'); }
body { this.d = d_; }
this(in int d_) pure nothrow @safe @nogc
in { assert(d_... |
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... | #Delphi | Delphi |
program SubleqTest;
{$APPTYPE CONSOLE}
{$R *.res}
uses
System.SysUtils;
var
mem: array of Integer;
instructionPointer: Integer;
a, b: Integer;
begin
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];
in... |
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:
... | #Mathematica.2FWolfram_Language | Mathematica/Wolfram Language | ClearAll[Primediffs]
p = Prime[Range[PrimePi[10^6]]];
Primediffs[seq_] := {First[#], Last[#], Length[#]} &[p[[#1 ;; #2 + 1]] & @@@ SequencePosition[Differences[p], seq]]
Primediffs[{2}]
Primediffs[{1}]
Primediffs[{2, 2}]
Primediffs[{2, 4}]
Primediffs[{4, 2}]
Primediffs[{6, 4, 2}] |
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... | #Elena | Elena | import extensions;
public program()
{
var testString := "test";
console.printLine(testString.Substring(1));
console.printLine(testString.Substring(0, testString.Length - 1));
console.printLine(testString.Substring(1, testString.Length - 2))
} |
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... | #Elixir | Elixir | iex(1)> str = "abcdefg"
"abcdefg"
iex(2)> String.slice(str, 1..-1)
"bcdefg"
iex(3)> String.slice(str, 0..-2)
"abcdef"
iex(4)> String.slice(str, 1..-2)
"bcdef" |
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... | #OCaml | OCaml | let _mod = 1_000_000_000
let state = Array.create 55 0
let si = ref 0
let sj = ref 0
let rec subrand_seed _p1 =
let p1 = ref _p1 in
let p2 = ref 1 in
state.(0) <- !p1 mod _mod;
let j = ref 21 in
for i = 1 to pred 55 do
if !j >= 55 then j := !j - 55;
state.(!j) <- !p2;
p2 := !p1 - !p2;
if !p2... |
http://rosettacode.org/wiki/Substitution_cipher | Substitution cipher | Substitution Cipher Implementation - File Encryption/Decryption
Task
Encrypt a input/source file by replacing every upper/lower case alphabets of the source file with another predetermined upper/lower case alphabets or symbols and save it into another output/encrypted file and then again convert that output/encrypt... | #zkl | zkl | class SubstitutionCipher{
// 92 characters: " !"#$%&" ... "xyz{|}", doesn't include "~"
const KEY="]kYV}(!7P$n5_0i R:?jOWtF/=-pe'AD&@r6%ZXs\"v*N"
"[#wSl9zq2^+g;LoB`aGh{3.HIu4fbK)mU8|dMET><,Qc\\C1yxJ";
fcn encode(s){ s.apply(fcn(c){ try{ KEY[c.toAsc()-32] }catch{ c } }) }
fcn decode(s){ s.apply(... |
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.
| #F.C5.8Drmul.C3.A6 | Fōrmulæ | Public Sub Main()
Dim iList As Integer[] = [1, 2, 3, 4, 5]
Dim iSum, iCount As Integer
Dim iPrd As Integer = 1
For iCount = 0 To iList.Max
iSum += iList[iCount]
iPrd *= iList[iCount]
Next
Print "The Sum =\t" & iSum
Print "The Product =\t" & iPrd
End |
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... | #Euphoria | Euphoria |
function s( atom x )
return 1 / power( x, 2 )
end function
function sum( atom low, atom high )
atom ret = 0.0
for i = low to high do
ret = ret + s( i )
end for
return ret
end function
printf( 1, "%.15f\n", sum( 1, 1000 ) ) |
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... | #Common_Lisp | Common Lisp | (defun strip-comments (s cs)
"Truncate s at the first occurrence of a character in cs."
(defun comment-char-p (c)
(some #'(lambda (x) (char= x c)) cs))
(let ((pos (position-if #'comment-char-p s)))
(subseq s 0 pos))) |
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... | #D | D | import std.stdio, std.regex;
string remove1LineComment(in string s, in string pat=";#") {
const re = "([^" ~ pat ~ "]*)([" ~ pat ~ `])[^\n\r]*([\n\r]|$)`;
return s.replace(regex(re, "gm"), "$1$3");
}
void main() {
const s = "apples, pears # and bananas
apples, pears ; and bananas ";
writeln(s, "\n... |
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... | #FreeBASIC | FreeBASIC | Const CRLF = Chr(13) + Chr(10)
Function stripBlocks(text As String, first As String, last As String) As String
Dim As String temp = ""
For i As Integer = 1 To Len(text) - Len(first)
If Mid(text, i, Len(first)) = first Then
i += Len(first)
Do
If Mid(text, i, 2) =... |
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 |... | #Aikido | Aikido | const little = "little"
printf ("Mary had a %s lamb\n", little)
// alternatively
println ("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 |... | #ALGOL_68 | ALGOL 68 | main:(
# as a STRING #
STRING extra = "little";
printf(($"Mary had a "g" lamb."l$, extra));
# as a FORMAT #
FORMAT extraf = $"little"$;
printf($"Mary had a "f(extraf)" lamb."l$);
# or: use simply use STRING concatenation #
print(("Mary had a "+extra+" lamb.", new line))
) |
http://rosettacode.org/wiki/Sum_to_100 | Sum to 100 | Task
Find solutions to the sum to one hundred puzzle.
Add (insert) the mathematical
operators + or - (plus
or minus) before any of the digits in the
decimal numeric string 123456789 such that the
resulting mathematical expression adds up to a
particular sum (in this iconic case, ... | #Python | Python | from itertools import product, islice
def expr(p):
return "{}1{}2{}3{}4{}5{}6{}7{}8{}9".format(*p)
def gen_expr():
op = ['+', '-', '']
return [expr(p) for p in product(op, repeat=9) if p[0] != '+']
def all_exprs():
values = {}
for expr in gen_expr():
val = eval(expr)
if v... |
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... | #BASIC | BASIC | DECLARE FUNCTION stripchars$(src AS STRING, remove AS STRING)
PRINT stripchars$("She was a soul stripper. She took my heart!", "aei")
FUNCTION stripchars$(src AS STRING, remove AS STRING)
DIM l0 AS LONG, t AS LONG, s AS STRING
s = src
FOR l0 = 1 TO LEN(remove)
DO
t = INSTR(s, MID$(re... |
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 |... | #Delphi | Delphi |
program String_preappend;
{$APPTYPE CONSOLE}
uses
System.SysUtils;
type
TStringHelper = record helper for string
procedure Preappend(str: string);
end;
{ TStringHelper }
procedure TStringHelper.Preappend(str: string);
begin
Self := str + self;
end;
begin
var h: string;
// with + operator... |
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 |... | #Dyalect | Dyalect | var s = "world!"
s = "Hello " + s
print(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 |... | #ALGOL_W | ALGOL W | begin
string(10) a;
string(12) b;
a := "abc";
b := "ABC";
% when comparing strings, Algol W ignores trailing blanks %
% so e.g. "a" = "a " is true %
% equality? %
... |
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 |... | #Apex | Apex | public class Compare
{
/**
* Test in the developer console:
* Compare.compare('Hello', 'Hello');
* Compare.compare('5', '5.0');
* Compare.compare('java', 'Java');
* Compare.compare('ĴÃVÁ', 'ĴÃVÁ');
*/
public static void compare (String A, String B)
{
if (A.equals(B))
System.deb... |
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... | #8080_Assembly | 8080 Assembly | org 100h
jmp demo
;;; Convert CP/M string under [HL] to upper case
unext: inx h
ucase: mov a,m ; Get character <- entry point is here
cpi '$' ; Done?
rz ; If so, stop
cpi 'a' ; >= 'a'?
jc unext ; If not, next character
cpi 'z'+1 ; <= 'z'?
jnc unext ; If not, next character
sui 32 ; Subtract 32
mov m,a ; Wri... |
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... | #Action.21 | Action! | INCLUDE "D2:CHARTEST.ACT" ;from the Action! Tool Kit
PROC UpperCase(CHAR ARRAY text,res)
BYTE i
res(0)=text(0)
FOR i=1 TO res(0)
DO
res(i)=ToUpper(text(i))
OD
RETURN
PROC LowerCase(CHAR ARRAY text,res)
BYTE i
res(0)=text(0)
FOR i=1 TO res(0)
DO
res(i)=ToLower(text(i))
OD
RETURN
PRO... |
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 |... | #ARM_Assembly | ARM Assembly |
/* ARM assembly Raspberry PI */
/* program strMatching.s */
/* Constantes */
.equ STDOUT, 1 @ Linux output console
.equ EXIT, 1 @ Linux syscall
.equ WRITE, 4 @ Linux syscall
/* Initialized data */
.data
szMessFound: ... |
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... | #Ada | Ada | Str : String := "Hello World";
Length : constant Natural := Str'Size / 8; |
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 ... | #D | D | import std.traits;
S stripChars(S)(S s, bool function(dchar) pure nothrow mustStrip)
pure nothrow if (isSomeString!S) {
S result;
foreach (c; s) {
if (!mustStrip(c))
result ~= c;
}
return result;
}
void main() {
import std.stdio, std.uni;
auto s = "\u0000\u000A ab... |
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 ... | #Erlang | Erlang |
-module( strip_control_codes ).
-export( [is_not_control_code/1, is_not_control_code_nor_extended_character/1, task/0] ).
is_not_control_code( C ) when C > 127 -> true;
is_not_control_code( C ) when C < 32; C =:= 127 -> false;
is_not_control_code( _C ) -> true.
is_not_control_code_nor_extended_character( C ) wh... |
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... | #ARM_Assembly | ARM Assembly |
/* ARM assembly Raspberry PI */
/* program strConcat.s */
/* Constantes */
.equ STDOUT, 1 @ Linux output console
.equ EXIT, 1 @ Linux syscall
.equ WRITE, 4 @ Linux syscall
/* Initialized data */
.data
szMessFinal: .asciz "The ... |
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.
| #Haskell | Haskell | import Data.List (nub)
----------------- SUM MULTIPLES OF 3 AND 5 ---------------
sum35 :: Integer -> Integer
sum35 n = f 3 + f 5 - f 15
where
f = sumMul n
sumMul :: Integer -> Integer -> Integer
sumMul n f = f * n1 * (n1 + 1) `div` 2
where
n1 = (n - 1) `div` f
--------------------------- TEST ---... |
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
| #Haskell | Haskell | digsum
:: Integral a
=> a -> a -> a
digsum base = f 0
where
f a 0 = a
f a n = f (a + r) q
where
(q, r) = n `quotRem` base
main :: IO ()
main = print $ digsum 16 255 -- "FF": 15 + 15 = 30 |
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
| #jq | jq | # ss for an input array:
def ss: map(.*.) | add;
# ss for a stream, S, without creating an intermediate array:
def ss(S): reduce S as $x (0; . + ($x * $x) ); |
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
| #Julia | Julia | julia> sum([1,2,3,4,5].^2)
55
julia> sum([x^2 for x in [1,2,3,4,5]])
55
julia> mapreduce(x->x^2,+,[1:5])
55
julia> sum([x^2 for x in []])
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... | #D | D | import std.stdio, std.string;
void main() {
auto s = " \t \r \n String with spaces \t \r \n ";
assert(s.stripLeft() == "String with spaces \t \r \n ");
assert(s.stripRight() == " \t \r \n String with spaces");
assert(s.strip() == "String with spaces");
} |
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... | #Delphi.2FPascal | Delphi/Pascal | program StripWhitespace;
{$APPTYPE CONSOLE}
uses SysUtils;
const
TEST_STRING = ' String with spaces ';
begin
Writeln('"' + TEST_STRING + '"');
Writeln('"' + TrimLeft(TEST_STRING) + '"');
Writeln('"' + TrimRight(TEST_STRING) + '"');
Writeln('"' + Trim(TEST_STRING) + '"');
end. |
http://rosettacode.org/wiki/Strong_and_weak_primes | Strong and weak primes |
Definitions (as per number theory)
The prime(p) is the pth prime.
prime(1) is 2
prime(4) is 7
A strong prime is when prime(p) is > [prime(p-1) + prime(p+1)] ÷ 2
A weak prime is when prime(p) is < [prime(p-1) + prime(p+1)] ÷ 2
Note that the defin... | #Phix | Phix | with javascript_semantics
sequence strong = {}, weak = {}
for i=2 to get_maxprime(1e14) do -- (ie idx of primes < (sqrt(1e14)==1e7), bar 1st)
integer p = get_prime(i),
c = compare(p,(get_prime(i-1)+get_prime(i+1))/2)
if c=+1 then strong &= p end if
if c=-1 then weak &= p end if
end for
printf(1,"The f... |
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 |... | #C.23 | C# | using System;
namespace SubString
{
class Program
{
static void Main(string[] args)
{
string s = "0123456789";
const int n = 3;
const int m = 2;
const char c = '3';
const string z = "345";
// A: starting from n characters ... |
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.
| #Delphi | Delphi | type
TIntArray = array of Integer;
{ TSudokuSolver }
TSudokuSolver = class
private
FGrid: TIntArray;
function CheckValidity(val: Integer; x: Integer; y: Integer): Boolean;
function ToString: string; reintroduce;
function PlaceNumber(pos: Integer): Boolean;
public
constructor Create(s... |
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... | #Draco | Draco | \util.g
proc nonrec rdch() byte:
char c;
if read(c) then
pretend(c, byte)
else
case ioerror()
incase CH_MISSING: readln(); 10
default: 0
esac
fi
corp
proc nonrec wrch(byte b) void:
if b=10
then writeln()
else write(pretend(b, char... |
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... | #Forth | Forth | create M 32 cells allot
: enter refill drop parse-word evaluate ; : M[] cells M + ;
: init M 32 cells bounds ?do i ! 1 cells +loop ;
: b-a+! dup dup cell+ @ M[] swap @ M[] @ negate over +! ;
: c b-a+! @ 1- 0< if 2 cells + @ else swap 3 + then nip ;
: b? dup cell+ @ 0< if @ M[] @ emit 3 + else c then ;
: a? dup @ 0< i... |
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:
... | #Nim | Nim | import math, strutils
const N = 1_000_000
var comp: array[2..(N - 1), bool] # True is composite, so default is prime.
for n in 2..<N:
if not comp[n]:
for k in countup(n * n, N - 1, n):
comp[k] = true
var primes = @[2]
for n in countup(3, N - 1, 2):
if not comp[n]:
primes.add n
iterator group... |
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:
... | #Perl | Perl | use strict;
use warnings;
use List::EachCons;
use Array::Compare;
use ntheory 'primes';
my $limit = 1E6;
my @primes = (2, @{ primes($limit) });
my @intervals = map { $primes[$_] - $primes[$_-1] } 1..$#primes;
print "Groups of successive primes <= $limit\n";
my $c = Array::Compare->new;
for my $diffs ([2], [1], [2... |
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... | #Emacs_Lisp | Emacs Lisp | (let ((string "top and tail"))
(substring string 1) ;=> "op and tail"
(substring string 0 (1- (length string))) ;=> "top and tai"
(substring string 1 (1- (length string)))) ;=> "op and tai" |
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... | #Erlang | Erlang | 1> Str = "Hello".
"Hello"
2> string:sub_string(Str, 2). % To strip the string from the right by 1
"ello"
3> string:sub_string(Str, 1, length(Str)-1). % To strip the string from the left by 1
"Hell"
4> string:sub_string(Str, 2, length(Str)-1). % To strip the string from both sides by 1
"ell" |
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... | #ooREXX | ooREXX | /*REXX program uses a subtractive generaTor,and creates a sequence of ranDom numbers. */
/* array index must be positive! */
s=.array~new
r=.array~new
s[1]=292929
s[2]=1
billion=1e9
numeric digits 20
ci=55
Do i=2 To ci-1
s[i+1]=mod(s[i-1]-s[i],billion)
End
cp=34
Do j=0 To ci-1
r[j+1]=s[mod(cp*(j+1),ci)+1]
End
m... |
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.
| #Gambas | Gambas | Public Sub Main()
Dim iList As Integer[] = [1, 2, 3, 4, 5]
Dim iSum, iCount As Integer
Dim iPrd As Integer = 1
For iCount = 0 To iList.Max
iSum += iList[iCount]
iPrd *= iList[iCount]
Next
Print "The Sum =\t" & iSum
Print "The Product =\t" & iPrd
End |
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... | #Excel | Excel | sumOfSeries
=LAMBDA(f,
LAMBDA(n,
SUM(
f(SEQUENCE(n, 1, 1, 1))
)
)
)
inverseSquare
=LAMBDA(n,
1 / (n ^ 2)
) |
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... | #Delphi | Delphi | program StripComments;
{$APPTYPE CONSOLE}
uses
SysUtils;
function DoStripComments(const InString: string; const CommentMarker: Char): string;
begin
Result := Trim(Copy(InString,1,Pos(CommentMarker,InString)-1));
end;
begin
Writeln('apples, pears # and bananas --> ' + DoStripComments('apples, pears # and 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... | #DWScript | DWScript | function StripComments(s : String) : String;
begin
var p := FindDelimiter('#;', s);
if p>0 then
Result := Trim(Copy(s, 1, p-1))
else Result := Trim(s);
end;
PrintLn(StripComments('apples, pears # and bananas'));
PrintLn(StripComments('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... | #Go | Go | package main
import (
"fmt"
"strings"
)
// idiomatic to name a function newX that allocates an object, initializes it,
// and returns it ready to use. the object in this case is a closure.
func newStripper(start, end string) func(string) string {
// default to c-style block comments
if start == "" ... |
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 |... | #ARM_Assembly | ARM Assembly |
/* ARM assembly Raspberry PI */
/* program insertString.s */
/* REMARK 1 : this program use routines in a include file
see task Include a file language arm assembly
for the routine affichageMess conversion10
see at end of this program the instruction include */
/*************************************... |
http://rosettacode.org/wiki/Sum_to_100 | Sum to 100 | Task
Find solutions to the sum to one hundred puzzle.
Add (insert) the mathematical
operators + or - (plus
or minus) before any of the digits in the
decimal numeric string 123456789 such that the
resulting mathematical expression adds up to a
particular sum (in this iconic case, ... | #Racket | Racket | #lang racket
(define list-partitions
(match-lambda
[(list) (list null)]
[(and L (list _)) (list (list L))]
[(list L ...)
(for*/list
((i (in-range 1 (add1 (length L))))
(r (in-list (list-partitions (drop L i)))))
(cons (take L i) r))]))
(define digits->number (curry fo... |
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... | #BASIC256 | BASIC256 | function stripchars(texto, remove)
s = texto
for i = 1 to length(remove)
s = replace(s, mid(remove, i, 1), "", true) #true se puede omitir
next i
return s
end function
print 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... | #BBC_BASIC | BBC BASIC | PRINT FNstripchars("She was a soul stripper. She took my heart!", "aei")
END
DEF FNstripchars(A$, S$)
LOCAL I%, C%, C$
FOR I% = 1 TO LEN(S$)
C$ = MID$(S$, I%, 1)
REPEAT
C% = INSTR(A$, C$)
IF C% A$ = LEFT$(A$, C%-1) + MID$(A$, C%+1)
UNTIL C% = 0... |
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 |... | #D.C3.A9j.C3.A0_Vu | Déjà Vu | local :s "world!"
set :s concat( "Hello " s)
!print 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 |... | #EchoLisp | EchoLisp |
define-syntax-rule
(set!-string-prepend a before)
(set! a (string-append before a)))
→ #syntax:set!-string-prepend
(define name "Presley")
→ name
(set!-string-prepend name "Elvis ")
name
→ "Elvis Presley"
|
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 |... | #Elena | Elena | import extensions;
import extensions'text;
public program()
{
var s := "World";
s := "Hello " + s;
console.writeLine:s;
// Alternative way
var s2 := StringWriter.load("World");
s2.insert(0, "Hello ");
console.writeLine:s2;
console.readChar()
} |
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 |... | #AppleScript | AppleScript | --Comparing two strings for exact equality
set s1 to "this"
set s2 to "that"
if s1 is s2 then
-- strings are equal
end if
--Comparing two strings for inequality (i.e., the inverse of exact equality)
if s1 is not s2 then
-- string are not equal
end if
-- Comparing two strings to see if one is lexically ordered bef... |
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... | #ActionScript | ActionScript | var string:String = 'alphaBETA';
var upper:String = string.toUpperCase();
var lower:String = string.toLowerCase(); |
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... | #Ada | Ada | with Ada.Characters.Handling, Ada.Text_IO;
use Ada.Characters.Handling, Ada.Text_IO;
procedure Upper_Case_String is
S : constant String := "alphaBETA";
begin
Put_Line (To_Upper (S));
Put_Line (To_Lower (S));
end Upper_Case_String; |
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 |... | #Arturo | Arturo | print prefix? "abcd" "ab"
print prefix? "abcd" "cd"
print suffix? "abcd" "ab"
print suffix? "abcd" "cd"
print contains? "abcd" "ab"
print contains? "abcd" "xy"
print in? "ab" "abcd"
print in? "xy" "abcd"
print index "abcd" "bc"
print index "abcd" "xy" |
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... | #Aime | Aime | length("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 ... | #F.23 | F# |
open System
let stripControl (arg:string) =
String(Array.filter (fun x -> not (Char.IsControl(x))) (arg.ToCharArray()))
//end stripControl
let stripExtended (arg:string) =
let numArr = Array.map (fun (x:char) -> Convert.ToUInt16(x)) (arg.ToCharArray()) in
String([|for num in numArr do if num >= 32us... |
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 ... | #Factor | Factor | USING: ascii kernel sequences ;
: strip-control-codes ( str -- str' ) [ control? not ] filter ;
: strip-control-codes-and-extended ( str -- str' )
strip-control-codes [ ascii? ] filter ; |
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... | #Arturo | Arturo | str1: "Hello "
str2: "World"
print str1 ++ str2 ++ "!" |
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... | #Asymptote | Asymptote | string s1 = "Hello";
write(s1 + " World!");
write(s1, " World!");
string s2 = s1 + " World!";
write(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.
| #Icon_and_Unicon | Icon and Unicon | procedure main(A)
n := (integer(A[1]) | 1000)-1
write(sum(n,3)+sum(n,5)-sum(n,15))
end
procedure sum(n,m)
return m*((n/m)*(n/m+1)/2)
end |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.