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/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
| #PL.2FI | PL/I |
declare A(10) float initial (10, 9, 8, 7, 6, 5, 4, 3, 2, 1);
put (sum(A**2));
|
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... | #OCaml | OCaml | let left_pos s len =
let rec aux i =
if i >= len then None
else match s.[i] with
| ' ' | '\n' | '\t' | '\r' -> aux (succ i)
| _ -> Some i
in
aux 0
let right_pos s len =
let rec aux i =
if i < 0 then None
else match s.[i] with
| ' ' | '\n' | '\t' | '\r' -> aux (pred i)
| _ -> So... |
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 |... | #J | J | 5{.3}.'Marshmallow'
shmal
3}.'Marshmallow'
shmallow
}.'Marshmallow'
arshmallow
}:'Marshmallow'
Marshmallo
5{.(}.~ i.&'m')'Marshmallow'
mallo
5{.(}.~ I.@E.~&'sh')'Marshmallow'
shmal |
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.
| #Pascal | Pascal | Program soduko;
{$IFDEF FPC}
{$CODEALIGN proc=16,loop=8}
{$ENDIF}
uses
sysutils,crt;
const
carreeSize = 3;
maxCoor = carreeSize*carreeSize;
maxValue = maxCoor;
maxMask = 1 shl (maxCoor+1)-1;
type
tLimit = 0..maxCoor-1;
tValue = 0..maxCoor;
tSteps = 0..maxCoor*maxCoor;
tValField = array[tLimit,tLimit... |
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... | #Swift | Swift | func subleq(_ inst: inout [Int]) {
var i = 0
while i >= 0 {
if inst[i] == -1 {
inst[inst[i + 1]] = Int(readLine(strippingNewline: true)!.unicodeScalars.first!.value)
} else if inst[i + 1] == -1 {
print(String(UnicodeScalar(inst[inst[i]])!), terminator: "")
} else {
inst[inst[i + 1]] ... |
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... | #Tcl | Tcl |
namespace import ::tcl::mathop::-
proc subleq {pgm} {
set ip 0
while {$ip >= 0} {
lassign [lrange $pgm $ip $ip+2] a b c
incr ip 3
if {$a == -1} {
scan [read stdin 1] %C char
lset pgm $b $char
} elseif {$b == -1} {
set char [format %c [linde... |
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... | #OCaml | OCaml | let strip_first_char str =
if str = "" then "" else
String.sub str 1 ((String.length str) - 1)
let strip_last_char str =
if str = "" then "" else
String.sub str 0 ((String.length str) - 1)
let strip_both_chars str =
match String.length str with
| 0 | 1 | 2 -> ""
| len -> String.sub str 1 (len - 2)
l... |
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.
| #Nial | Nial | + 1 2 3
= 6
* 1 2 3
= 6 |
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.
| #Nim | Nim | var xs = [1, 2, 3, 4, 5, 6]
var sum, product: int
product = 1
for x in xs:
sum += x
product *= x |
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... | #Kotlin | Kotlin | // version 1.0.6
fun main(args: Array<String>) {
val n = 1000
val sum = (1..n).sumByDouble { 1.0 / (it * it) }
println("Actual sum is $sum")
println("zeta(2) is ${Math.PI * Math.PI / 6.0}")
} |
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 |... | #Maxima | Maxima | printf(true, "Mary had a ~a lamb", "little"); |
http://rosettacode.org/wiki/String_interpolation_(included) | String interpolation (included) |
Basic Data Operation
This is a basic data operation. It represents a fundamental action on a basic data type.
You may see other such operations in the Basic Data Operations category, or:
Integer Operations
Arithmetic |
Comparison
Boolean Operations
Bitwise |
Logical
String Operations
Concatenation |
Interpolation |... | #Neko | Neko | /**
<doc><h2>String interpolation, in Neko</h2>
<p><a href="https://nekovm.org/doc/view/string/">NekoVM String Library</a></p>
</doc>
**/
var sprintf = $loader.loadprim("std@sprintf", 2)
$print(sprintf("Mary had a %s lamb\n", "little")) |
http://rosettacode.org/wiki/String_interpolation_(included) | String interpolation (included) |
Basic Data Operation
This is a basic data operation. It represents a fundamental action on a basic data type.
You may see other such operations in the Basic Data Operations category, or:
Integer Operations
Arithmetic |
Comparison
Boolean Operations
Bitwise |
Logical
String Operations
Concatenation |
Interpolation |... | #Nemerle | Nemerle | using System;
using System.Console;
using Nemerle.IO; // contains printf() and print()
module Stringy
{
Main() : void
{
def extra = "little";
printf("Mary had a %s lamb.\n", extra);
print("Mary had a $extra lamb.\n");
WriteLine($"Mary had a $extra 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... | #Mathematica.2FWolfram_Language | Mathematica/Wolfram Language | stripchars[a_,b_]:=StringReplace[a,(#->"")&/@Characters[b]]
stripchars["She was a soul stripper. She took my heart!","aei"]
->Sh ws soul strppr. Sh took my hrt! |
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... | #MATLAB_.2F_Octave | MATLAB / Octave | function str = stripchars(str, charlist)
% MATLAB after 2016b: str = erase(str, charlist);
str(ismember(str, charlist)) = ''; |
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 |... | #Julia | Julia | function compare(a, b)
println("\n$a is of type $(typeof(a)) and $b is of type $(typeof(b))")
if a < b println("$a is strictly less than $b") end
if a <= b println("$a is less than or equal to $b") end
if a > b println("$a is strictly greater than $b") end
if a >= b println("$a is greater than or ... |
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 |... | #Kotlin | Kotlin | // version 1.0.6
fun main(args: Array<String>) {
val k1 = "kotlin"
val k2 = "Kotlin"
println("Case sensitive comparisons:\n")
println("kotlin and Kotlin are equal = ${k1 == k2}")
println("kotlin and Kotlin are not equal = ${k1 != k2}")
println("kotlin comes before Kotlin = ${k1 < k2}"... |
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... | #Fantom | Fantom |
fansh> a := "alphaBETA"
alphaBETA
fansh> a.upper // convert whole string to upper case
ALPHABETA
fansh> a.lower // convert whole string to lower case
alphabeta
fansh> a.capitalize // make sure first letter is capital
AlphaBETA
fansh> "BETAalpha".decapitalize // make sure first letter is not capital
bETAalpha
|
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... | #Forth | Forth | : tolower ( C -- c ) 32 or ;
: toupper ( c -- C ) 32 invert and ;
: lower ( addr len -- ) over + swap do i c@ tolower i c! loop ;
: upper ( addr len -- ) over + swap do i c@ toupper i c! loop ;
|
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 |... | #Fantom | Fantom |
class Main
{
public static Void main ()
{
string := "Fantom Language"
echo ("String is: " + string)
echo ("does string start with 'Fantom'? " + string.startsWith("Fantom"))
echo ("does string start with 'Language'? " + string.startsWith("Language"))
echo ("does string contain 'age'? " + 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 |... | #FBSL | FBSL | #APPTYPE CONSOLE
DIM s = "roko, mat jane do"
IF LEFT(s, 4) = "roko" THEN PRINT STRENC(s), " starts with ", STRENC("roko")
IF INSTR(s, "mat") THEN PRINT STRENC(s), " contains ", STRENC("mat"), " at ", INSTR
IF RIGHT(s, 2) = "do" THEN PRINT STRENC(s), " ends with ", STRENC("do")
PRINT STRENC(s), " contains ", STRENC(... |
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... | #Elixir | Elixir |
name = "J\x{332}o\x{332}s\x{332}e\x{301}\x{332}"
byte_size(name)
# => 14
|
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... | #Emacs_Lisp | Emacs Lisp | (length "hello")
;; => 5 |
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 ... | #Standard_ML | Standard ML | (* string -> string *)
val stripCntrl = concat o String.tokens Char.isCntrl
(* string -> string *)
val stripCntrlAndExt = concat o String.tokens (not o Char.isPrint) |
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 ... | #Tcl | Tcl | proc stripAsciiCC str {
regsub -all {[\u0000-\u001f\u007f]+} $str ""
}
proc stripCC str {
regsub -all {[^\u0020-\u007e]+} $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... | #JavaScript | JavaScript | var s = "hello"
print(s + " there!") |
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... | #jq | jq | "hello" as $s | $s + " there!" |
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... | #Julia | Julia | s = "hello"
println(s * " there!") |
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.
| #Pascal | Pascal | program Sum3sAnd5s;
function Multiple(x, y: integer): Boolean;
{ Is X a multiple of Y? }
begin
Multiple := (X mod Y) = 0
end;
function SumMultiples(n: integer): longint;
{ Return the sum of all multiples of 3 or 5. }
var i: integer; sum: longint;
begin
sum := 0;
for i := 1 to pred(... |
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
| #Picat | Picat | go =>
println(1=sum_digits(1)),
println(1234=sum_digits(1234)),
println('"1234"'=sum_digits("1234")),
println(1234=sum_digits(1234)),
println('"fe(16)"'=sum_digits("fe", 16)), % -> 29
println('"f0e(16)"'=sum_digits("f0e", 16)), % -> 29
println('"FOE(16)"'=sum_digits("F0E", 16)), % -> 29
println('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
| #Plain_English | Plain English | To run:
Start up.
Create a list.
Sum the squares of the list giving a ratio.
Destroy the list.
Write "Sum of squares: " then the ratio on the console.
Wait for the escape key.
Shut down.
An element is a thing with a ratio.
A list is some elements.
To add a ratio to a list:
Allocate memory for an element.
Put the ... |
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
| #Pop11 | Pop11 | define sum_squares(v);
lvars s = 0, j;
for j from 1 to length(v) do
s + v(j)*v(j) -> s;
endfor;
s;
enddefine;
sum_squares({1 2 3 4 5}) => |
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... | #OpenEdge.2FProgress | OpenEdge/Progress | DEF VAR cc AS CHAR INIT " string with spaces ".
MESSAGE
"|" + LEFT-TRIM( cc ) + "|" SKIP
"|" + RIGHT-TRIM( cc ) + "|" SKIP
"|" + TRIM( cc ) + "|"
VIEW-AS ALERT-BOX. |
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... | #Perl | Perl | sub ltrim { shift =~ s/^\s+//r }
sub rtrim { shift =~ s/\s+$//r }
sub trim { ltrim rtrim shift }
# Usage:
my $p = " this is a string ";
print "'", $p, "'\n";
print "'", trim($p), "'\n";
print "'", ltrim($p), "'\n";
print "'", rtrim($p), "'\n"; |
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 |... | #Java | Java | public static String Substring(String str, int n, int m){
return str.substring(n, n+m);
}
public static String Substring(String str, int n){
return str.substring(n);
}
public static String Substring(String str){
return str.substring(0, str.length()-1);
}
public static String Substring(String str, char c, in... |
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.
| #Perl | Perl | #!/usr/bin/perl
use integer;
use strict;
my @A = qw(
5 3 0 0 2 4 7 0 0
0 0 2 0 0 0 8 0 0
1 0 0 7 0 3 9 0 2
0 0 8 0 7 2 0 4 9
0 2 0 9 8 0 0 7 0
7 9 0 0 0 0 0 8 0
0 0 0 0 3 0 5 0 6
9 6 0 0 1 0 3 0 0
0 5 0 6 9 0 0 1 0
);
sub solve {
my $i;
forea... |
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... | #uBasic.2F4tH | uBasic/4tH | GoSub _Initialize ' Initialize memory
i = 0 ' Reset instruction pointer
Do While i > -1 ' While IP is not negative
A = @(i) ' Fill the registers with
B = @(i+1) ' opcodes and operan... |
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... | #UNIX_Shell | UNIX Shell | #!/bin/sh
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 "
i=0
for v in $mem
do
eval 'mem_'$i=$v
i=$(( $i + 1 ))
done
get_m () {
eval echo '$mem_'$1
}
set_m () {
eval 'mem_'$1=$2
}
ADDR=0
STEP=0
while [ ${STEP} -lt 9999 ]
do
STEP=$(( $STEP + ... |
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... | #Oforth | Oforth | : topAndTail(s)
s right(s size 1-) println
s left(s size 1-) println
s extract(2, s size 1- ) println ; |
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... | #PARI.2FGP | PARI/GP | df(s)=concat(vecextract(Vec(s),1<<#s-2));
dl(s)=concat(vecextract(Vec(s),1<<(#s-1)-1));
db(s)=concat(vecextract(Vec(s),1<<(#s-1)-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.
| #Objeck | Objeck |
sum := 0;
prod := 1;
arg := [1, 2, 3, 4, 5];
each(i : arg) {
sum += arg[i];
prod *= arg[i];
};
|
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.
| #Objective-C | Objective-C | - (float) sum:(NSMutableArray *)array
{
int i, sum, value;
sum = 0;
value = 0;
for (i = 0; i < [array count]; i++) {
value = [[array objectAtIndex: i] intValue];
sum += value;
}
return suml;
} |
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... | #Lambdatalk | Lambdatalk |
{+ {S.map {lambda {:k} {/ 1 {* :k :k}}} {S.serie 1 1000}}}
-> 1.6439345666815615 ~ 1.6449340668482264 = PI^2/6
|
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 |... | #NetRexx | NetRexx | /* NetRexx */
options replace format comments java crossref savelog symbols
import java.text.MessageFormat
import java.text.FieldPosition
useBif()
useMessageFormat()
return
method useBif public static
st = "Mary had a %1$ lamb."
si = 'little'
say st.changestr('%1$', si)
return
method useMessag... |
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 |... | #Nim | Nim | import strutils
var str = "little"
echo "Mary had a $# lamb".format(str)
echo "Mary had a $# lamb" % [str]
# Note: doesn't need an array for a single substitution, but uses an array for multiple substitutions. |
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... | #Nanoquery | Nanoquery | def stripchars(string, chars)
for char in chars
string = string.replace(char, "")
end
return string
end |
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... | #Nemerle | Nemerle | StripChars( text : string, remove : string ) : string
{
def chuck = Explode(remove);
Concat( "", Split(text, chuck))
} |
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 |... | #Lasso | Lasso | // Comparing two strings for exact equality
"'this' == 'this': " + ('this' == 'this') // true
"'this' == 'This': " + ('this' == 'This') // true, as it's case insensitive
// Comparing two strings for inequality (i.e., the inverse of exact equality)
"'this' != 'this': " + ('this' != 'this')// false
"'this' != 'that': "... |
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 |... | #Lingo | Lingo | put "abc"="ABC"
-- 1
put "abc"<>"def"
-- 1
put "abc"<"def"
-- 1
put "abc">"def"
-- 0 |
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... | #Fortran | Fortran | program example
implicit none
character(9) :: teststring = "alphaBETA"
call To_upper(teststring)
write(*,*) teststring
call To_lower(teststring)
write(*,*) teststring
contains
subroutine To_upper(str)
character(*), intent(in out) :: str
integer :: i
do i = 1, len(str)
... |
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 |... | #Forth | Forth | : starts-with ( a l a2 l2 -- ? )
tuck 2>r min 2r> compare 0= ;
: ends-with ( a l a2 l2 -- ? )
tuck 2>r negate over + 0 max /string 2r> compare 0= ;
\ use SEARCH ( a l a2 l2 -- a3 l3 ? ) for contains |
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 |... | #Fortran | Fortran |
SUBROUTINE STARTS(A,B) !Text A starts with text B?
CHARACTER*(*) A,B
IF (INDEX(A,B).EQ.1) THEN !Searches A to find B.
WRITE (6,*) ">",A,"< starts with >",B,"<"
ELSE
WRITE (6,*) ">",A,"< does not start with >",B,"<"
END IF
END SUBROUTINE STARTS
SU... |
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... | #Erlang | Erlang | 9> U = "𝔘𝔫𝔦𝔠𝔬𝔡𝔢".
[120088,120107,120102,120096,120108,120097,120098]
10> erlang:length(U).
7
|
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... | #Euphoria | Euphoria | print(1,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 ... | #TI-83_BASIC | TI-83 BASIC | #$&@;_`abcdefghijklmnopqrstuvwxyz|~ |
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 ... | #TXR | TXR | (defun strip-controls (str)
(regsub #/[\x0-\x1F\x7F]+/ "" str))
(defun strip-controls-and-extended (str)
(regsub #/[^\x20-\x7F]+/ "" str)) |
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 ... | #VBScript | VBScript |
Function StripCtrlCodes(s)
tmp = ""
For i = 1 To Len(s)
n = Asc(Mid(s,i,1))
If (n >= 32 And n <= 126) Or n >=128 Then
tmp = tmp & Mid(s,i,1)
End If
Next
StripCtrlCodes = tmp
End Function
Function StripCtrlCodesExtChrs(s)
tmp = ""
For i = 1 To Len(s)
n = Asc(Mid(s,i,1))
If n >= 32 And n <= 126 Th... |
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... | #K | K |
s1: "Some "
s1, "text "
s2: s1 , "more text!"
|
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... | #Kotlin | Kotlin | fun main(args: Array<String>) {
val s1 = "James"
val s2 = "Bond"
println(s1)
println(s2)
val s3 = s1 + " " + s2
println(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... | #LabVIEW | LabVIEW |
{def christian_name Albert}
-> christian_name
{def name de Jeumont-Schneidre}
-> name
{christian_name} {name}
-> Albert de Jeumont-Schneidre
|
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.
| #Perl | Perl | #!/usr/bin/perl
use v5.20;
use experimental qw(signatures);
use List::Util qw( sum ) ;
sub sum_3_5($limit) {
return sum grep { $_ % 3 == 0 || $_ % 5 == 0 } ( 1..$limit - 1 ) ;
}
say "The sum is ${\(sum_3_5 1000)}!\n" ; |
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
| #PicoLisp | PicoLisp | (de sumDigits (N Base)
(or
(=0 N)
(+ (% N Base) (sumDigits (/ N Base) Base)) ) ) |
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
| #PostScript | PostScript |
/sqrsum{
/x exch def
/sum 0 def
/i 0 def
x length 0 eq
{}
{
x length{
/sum sum x i get 2 exp add def
/i i 1 add def
}repeat
}ifelse
sum ==
}def
|
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
| #PowerShell | PowerShell | function Get-SquareSum ($a) {
if ($a.Length -eq 0) {
return 0
} else {
$x = $a `
| ForEach-Object { $_ * $_ } `
| Measure-Object -Sum
return $x.Sum
}
} |
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... | #Phix | Phix | with javascript_semantics
constant s = "\t test \n"
?s
?trim_head(s)
?trim_tail(s)
?trim(s)
|
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... | #PHP | PHP | <?php
/**
* @author Elad Yosifon
*/
$string = ' this is a string ';
echo '^'.trim($string) .'$'.PHP_EOL;
echo '^'.ltrim($string).'$'.PHP_EOL;
echo '^'.rtrim($string).'$'.PHP_EOL;
|
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 |... | #JavaScript | JavaScript | var str = "abcdefgh";
var n = 2;
var m = 3;
// * starting from n characters in and of m length;
str.substr(n, m); // => "cde"
// * starting from n characters in, up to the end of the string;
str.substr(n); // => "cdefgh"
str.substring(n); // => "cdefgh"
// * whole string minus last character;
str.substri... |
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.
| #Phix | Phix | with javascript_semantics
sequence board = split("""
.......39
.....1..5
..3.5.8..
..8.9...6
.7...2...
1..4.....
..9.8..5.
.2....6..
4..7.....""",'\n')
function valid_move(integer y, x, ch)
for i=1 to 9 do
if ch=board[i][x] then return false end if
if ch=board[y][i] then return false end if
end... |
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... | #Wren | Wren | import "io" for Stdin, Stdout
var subleq = Fn.new { |program|
var words = program.split(" ").map { |w| Num.fromString(w) }.toList
var sb = ""
var ip = 0
while (true) {
var a = words[ip]
var b = words[ip+1]
var c = words[ip+2]
ip = ip + 3
if (a < 0) {
... |
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... | #Pascal | Pascal | print substr("knight",1), "\n"; # strip first character
print substr("socks", 0, -1), "\n"; # strip last character
print substr("brooms", 1, -1), "\n"; # strip both first and last characters |
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.
| #OCaml | OCaml | (* ints *)
let a = [| 1; 2; 3; 4; 5 |];;
Array.fold_left (+) 0 a;;
Array.fold_left ( * ) 1 a;;
(* floats *)
let a = [| 1.0; 2.0; 3.0; 4.0; 5.0 |];;
Array.fold_left (+.) 0.0 a;;
Array.fold_left ( *.) 1.0 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... | #Lang5 | Lang5 | 1000 iota 1 + 1 swap / 2 ** '+ reduce . |
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 |... | #OCaml | OCaml | let extra = "little" in
Printf.printf "Mary had a %s lamb." extra |
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 |... | #OOC | OOC |
main: func {
X := "little"
"Mary had a #{X} lamb" println()
}
|
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 |... | #Oz | Oz | declare
X = "little"
in
{System.showInfo "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... | #NetRexx | NetRexx | /* NetRexx */
options replace format comments java crossref savelog symbols
say stripchars("She was a soul stripper. She took my heart!", "aei")
return
method stripchars(haystack, chs) public static
loop c_ = 1 to chs.length
needle = chs.substr(c_, 1)
haystack = haystack.changestr(needle, '')
en... |
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... | #NewLISP | NewLISP | (let (sentence "She was a soul stripper. She took my heart!")
(replace "[aei]" sentence "" 0)) |
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 |... | #Lua | Lua | function compare(a, b)
print(("%s is of type %s and %s is of type %s"):format(
a, type(a),
b, type(b)
))
if a < b then print(('%s is strictly less than %s'):format(a, b)) end
if a <= b then print(('%s is less than or equal to %s'):format(a, b)) end
if a > b then print(('%s is stric... |
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... | #FreeBASIC | FreeBASIC | ' FB 1.05.0 Win64
Dim s As String = "alphaBETA"
Print UCase(s)
Print LCase(s)
Sleep |
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... | #Frink | Frink |
a = "alphaBETA"
println[lc[a]]
println[uc[a]]
|
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 |... | #FreeBASIC | FreeBASIC | ' FB 1.05.0 Win64
Dim As String s1 = "abracadabra"
Dim As String s2 = "abra"
Print "First string : "; s1
Print "Second string : "; s2
Print
Print "First string begins with second string : "; CBool(s2 = Left(s1, Len(s2)))
Dim As Integer i1 = Instr(s1, s2)
Dim As Integer i2
Print "First string contains second string... |
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... | #F.23 | F# | open System.Text
let byte_length str = Encoding.UTF8.GetByteCount(str) |
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... | #Factor | Factor | : string-byte-length ( string -- n ) [ code-point-length ] map-sum ;
: string-byte-length-2 ( string -- n ) utf8 encode length ; |
http://rosettacode.org/wiki/Strip_control_codes_and_extended_characters_from_a_string | Strip control codes and extended characters from a string | Task
Strip control codes and extended characters from a string.
The solution should demonstrate how to achieve each of the following results:
a string with control codes stripped (but extended characters not stripped)
a string with control codes and extended characters stripped
In ASCII, the control codes ... | #Wren | Wren | import "/pattern" for Pattern
var s = "\t\n\r\x01\0\fabc\v\v\b\a\x1f\x7f🌇Páez😃É"
// strip control codes only
var p = Pattern.new("+1/c")
var r = p.replaceAll(s, "")
System.print("%(r) -> length %(r.count)")
// strip extended characters as well
p = Pattern.new("[+1/c|+1/R]")
r = p.replaceAll(s, "")
System.print(... |
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 ... | #XPL0 | XPL0 | include c:\cxpl\codes; \intrinsic 'code' declarations
string 0; \use zero-terminated string convention
proc Strip(Str, Both); \Strip out control and optionally extended chars
char Str; int Both;
int I, J, C;
[I:= 0;
while Str(I) do
[C:= Str(I);
if Both then C:= extend(... |
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... | #Lambdatalk | Lambdatalk |
{def christian_name Albert}
-> christian_name
{def name de Jeumont-Schneidre}
-> name
{christian_name} {name}
-> Albert de Jeumont-Schneidre
|
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... | #Lang5 | Lang5 | : concat 2 compress "" join ;
'hello " literal" concat |
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... | #Lasso | Lasso | local(x = 'Hello')
local(y = #x + ', World!')
#x // Hello
#y // Hello, World! |
http://rosettacode.org/wiki/Sum_multiples_of_3_and_5 | Sum multiples of 3 and 5 | Task
The objective is to write a function that finds the sum of all positive multiples of 3 or 5 below n.
Show output for n = 1000.
This is is the same as Project Euler problem 1.
Extra credit: do this efficiently for n = 1e20 or higher.
| #Phix | Phix | function sumMul(atom n, f)
n = floor((n-1)/f)
return f*n*(n+1)/2
end function
function sum35(atom n)
return sumMul(n,3) +
sumMul(n,5) -
sumMul(n,15)
end function
for i=0 to 8 do
string sp = repeat(' ',9-i),
pt = "1"&repeat('0',i)
printf(1,"%s%s%s %d\n",{sp,pt,sp,... |
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
| #PL.2FI | PL/I |
sum_digits: procedure options (main); /* 4/9/2012 */
declare ch character (1);
declare (k, sd) fixed;
on endfile (sysin) begin; put skip data (sd); stop; end;
sd = 0;
do forever;
get edit (ch) (a(1)); put edit (ch) (a);
k = index('abcdef', ch);
if k > 0 then /* we have a base abov... |
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
| #PowerShell | PowerShell |
function Get-DigitalSum ([string] $number, $base = 10)
{
if ($number.ToCharArray().Length -le 1) { [Convert]::ToInt32($number, $base) }
else
{
$result = 0
foreach ($character in $number.ToCharArray())
{
$digit = [Convert]::ToInt32(([string]$character), $base)
... |
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
| #Prolog | Prolog | sum([],0).
sum([H|T],S) :- sum(T, S1), S is S1 + (H * H).
|
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
| #PureBasic | PureBasic | Procedure SumOfSquares(List base())
ForEach base()
Sum + base()*base()
Next
ProcedureReturn Sum
EndProcedure |
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... | #Picat | Picat | import util.
go =>
S = " Jabberwocky ",
println("<" ++ S ++ ">"),
println("<" ++ lstrip(S) ++ ">"),
println("<" ++ rstrip(S) ++ ">"),
println("<" ++ strip(S) ++ ">"),
println("<" ++ strip("\t\r\bTwas brillig, and the slithy toves\r \t\v"," \b\v\t\r\v") ++ ">"),
nl. |
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... | #PicoLisp | PicoLisp | (de trimLeft (Str)
(pack (flip (trim (flip (chop Str))))) )
(de trimRight (Str)
(pack (trim (chop Str))) )
(de trimBoth (Str)
(pack (clip (chop 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 |... | #jq | jq | def s: "一二三四五六七八九十"; |
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 |... | #Jsish | Jsish | #!/usr/local/bin/jsish -u %s
var str = "abcdefgh";
var n = 2;
var m = 3;
// In jsish, semi-colon first character lines are echoed with result
;str;
;n;
;m;
// * starting from n characters in and of m length;
;str.substr(n, m);
// * starting from n characters in, up to the end of the string;
;str.substr(n);... |
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.
| #PHP | PHP | class SudokuSolver {
protected $grid = [];
protected $emptySymbol;
public static function parseString($str, $emptySymbol = '0')
{
$grid = str_split($str);
foreach($grid as &$v)
{
if($v == $emptySymbol)
{
$v = 0;
}
else
{
$v = (int)$v;
}
}
return $grid;
}
p... |
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... | #zkl | zkl | fcn subleq(a,a1,a2,etc){ a=vm.arglist.copy();
i:=0;
while(i>=0){ A,B,C:=a[i,3];
if(A==-1) a[B]=ask("::").toInt(); // or File.stdin.read(1)[0] // int
else if(B==-1) print(a[A].toChar());
else if( (a[B]-=a[A]) <=0) { i=C; continue; }
i+=3;
}
} |
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... | #ZX_Spectrum_Basic | ZX Spectrum Basic | 10 DIM m(512)
20 INPUT p$
30 LET word=1
40 LET char=1
50 IF char<LEN p$ THEN GO TO 80
60 LET m(word)=VAL p$
70 GO TO 150
80 IF p$(char)=" " THEN GO TO 110
90 LET char=char+1
100 GO TO 50
110 LET m(word)=VAL p$( TO char-1)
120 LET p$=p$(char+1 TO )
130 LET word=word+1
140 GO TO 40
150 LET ptr=0
160 LET a=m(ptr+... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.