task_url
stringlengths
30
116
task_name
stringlengths
2
86
task_description
stringlengths
0
14.4k
language_url
stringlengths
2
53
language_name
stringlengths
1
52
code
stringlengths
0
61.9k
http://rosettacode.org/wiki/String_case
String case
Task Take the string     alphaBETA     and demonstrate how to convert it to:   upper-case     and   lower-case Use the default encoding of a string literal or plain ASCII if there is no string literal in your language. Note: In some languages alphabets toLower and toUpper is not reversable. Show any additional...
#AppleScript
AppleScript
use framework "Foundation"   -- TEST ----------------------------------------------------------------------- on run   ap({toLower, toTitle, toUpper}, {"alphaBETA αβγδΕΖΗΘ"})   --> {"alphabeta αβγδεζηθ", "Alphabeta Αβγδεζηθ", "ALPHABETA ΑΒΓΔΕΖΗΘ"}   end run     -- GENERIC FUNCTIONS ------------------------------...
http://rosettacode.org/wiki/String_matching
String matching
Basic Data Operation This is a basic data operation. It represents a fundamental action on a basic data type. You may see other such operations in the Basic Data Operations category, or: Integer Operations Arithmetic | Comparison Boolean Operations Bitwise | Logical String Operations Concatenation | Interpolation |...
#AWK
AWK
#!/usr/bin/awk -f { if ($1 ~ "^"$2) { print $1" begins with "$2; } else { print $1" does not begin with "$2; }   if ($1 ~ $2) { print $1" contains "$2; } else { print $1" does not contain "$2; }   if ($1 ~ $2"$") { print $1" ends with "$2; } else { print $1" does not end with "$2; ...
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...
#AppleScript
AppleScript
count of "Hello World"
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...
#Applesoft_BASIC
Applesoft BASIC
? LEN("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 ...
#Frink
Frink
stripExtended[str] := str =~ %s/[^\u0020-\u007e]//g   stripControl[str]  := str =~ %s/[\u0000-\u001F\u007f]//g   println[stripExtended[char[0 to 127]]] println[stripControl[char[0 to 127]]]
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 ...
#Gambas
Gambas
Public Sub Main() Dim sString As String = "The\t \equick\n \fbrownfox \vcost £125.00 or €145.00 or $160.00 \bto \ncapture ©®" Dim sStd, sExtend As String Dim siCount As Short   For siCount = 32 To 126 sStd &= Chr(siCount) Next   For siCount = 128 To 255 sExtend &= Chr(siCount) Next   Print "Original string: -\t" &...
http://rosettacode.org/wiki/String_concatenation
String concatenation
String concatenation You are encouraged to solve this task according to the task description, using any language you may know. Task Create a string variable equal to any text value. Create another string variable whose value is the original variable concatenated with another string literal. To illustrate the operat...
#Batch_File
Batch File
set string=Hello echo %string% World set string2=%string% World echo %string2%
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...
#BQN
BQN
str ← "Hello " newstr ← str ∾ "world" •Show newstr
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.
#JavaScript
JavaScript
Number.MAX_SAFE_INTEGER
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
#JavaScript
JavaScript
function sumDigits(n) { n += '' for (var s=0, i=0, e=n.length; i<e; i+=1) s+=parseInt(n.charAt(i),36) return s } for (var n of [1, 12345, 0xfe, 'fe', 'f0e', '999ABCXYZ']) document.write(n, ' sum to ', sumDigits(n), '<br>')  
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
#Liberty_BASIC
Liberty BASIC
' [RC] Sum of Squares   SourceList$ ="3 1 4 1 5 9" 'SourceList$ =""   ' If saved as an array we'd have to have a flag for last data. ' LB has the very useful word$() to read from delimited strings. ' The default delimiter is a space character, " ".   SumOfSquares =0 n ...
http://rosettacode.org/wiki/Sum_of_squares
Sum of squares
Task Write a program to find the sum of squares of a numeric vector. The program should work on a zero-length vector (with an answer of   0). Related task   Mean
#LiveCode
LiveCode
put "1,2,3,4,5" into nums repeat for each item n in nums add (n * n) to m end repeat put m // 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...
#Euphoria
Euphoria
include std/console.e include std/text.e   sequence removables = " \t\n\r\x05\u0234\" " sequence extraSeq = " \x05\r \" A B C \n \t\t \u0234 \r\r \x05 "   extraSeq = trim(extraSeq,removables) --the work is done by the trim function   --only output programming next : printf(1, "String Trimmed is now: %s \r\n", {e...
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...
#F.23
F#
[<EntryPoint>] let main args = printfn "%A" (args.[0].TrimStart()) printfn "%A" (args.[0].TrimEnd()) printfn "%A" (args.[0].Trim()) 0
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...
#REXX
REXX
/*REXX program lists a sequence (or a count) of ──strong── or ──weak── primes. */ parse arg N kind _ . 1 . okind; upper kind /*obtain optional arguments from the CL*/ if N=='' | N=="," then N= 36 /*Not specified? Then assume default.*/ if kind=='' | kind=="," then kind= 'STRONG' ...
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 |...
#Common_Lisp
Common Lisp
(let ((string "0123456789") (n 2) (m 3) (start #\5) (substring "34")) (list (subseq string n (+ n m)) (subseq string n) (subseq string 0 (1- (length string))) (let ((pos (position start string))) (subseq string pos (+ pos m))) (let ((pos (search substr...
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.
#ERRE
ERRE
  !-------------------------------------------------------------------- ! risolve Sudoku: in input il file SUDOKU.TXT ! Metodo seguito : cancellazioni successive e quando non possibile ! ricerca combinatoria sulle celle con due valori ! possibili - max. 30 livelli di ricorsione ! ...
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...
#Haskell
Haskell
{-# LANGUAGE FlexibleContexts #-} import Control.Monad.State import Data.Char (chr, ord) import Data.IntMap   subleq = loop 0 where loop ip = when (ip >= 0) $ do m0 <- gets (! ip) m1 <- gets (! (ip + 1)) if m0 < 0 then do modify . insert m1 ch . or...
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: ...
#Python
Python
# https://docs.sympy.org/latest/index.html from sympy import Sieve   def nsuccprimes(count, mx): "return tuple of <count> successive primes <= mx (generator)" sieve = Sieve() sieve.extend(mx) primes = sieve._list return zip(*(primes[n:] for n in range(count)))   def check_value_diffs(diffs, values):...
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...
#Forth
Forth
: hello ( -- c-addr u ) s" Hello" ;   hello 1 /string type \ => ello   hello 1- type \ => hell   hello 1 /string 1- type \ => ell
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...
#Fortran
Fortran
program substring   character(len=5) :: string string = "Hello"   write (*,*) string write (*,*) string(2:) write (*,*) string( :len(string)-1) write (*,*) string(2:len(string)-1)   end program substring
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...
#PowerShell
PowerShell
  function Get-SubtractiveRandom ( [int]$Seed ) { function Mod ( [int]$X, [int]$M = 1000000000 ) { ( $X % $M + $M ) % $M }   If ( $Seed ) { $R = New-Object int[] 55   $N1 = 55 - 1 $N2 = ( $N1 + 34 ) % 55   $R[$N1] = $Seed $R[$N2] = 1   ForEach ( $x in ...
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.
#Haskell
Haskell
values = [1..10]   s = sum values -- the easy way p = product values   s1 = foldl (+) 0 values -- the hard way p1 = foldl (*) 1 values
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.
#HicEst
HicEst
array = $ ! 1, 2, ..., LEN(array)   sum = SUM(array)   product = 1 ! no built-in product function in HicEst DO i = 1, LEN(array) product = product * array(i) ENDDO   WRITE(ClipBoard, Name) n, sum, product ! n=100; sum=5050; product=9.33262154E157;
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...
#Fantom
Fantom
  fansh> (1..1000).toList.reduce(0.0f) |Obj a, Int v -> Obj| { (Float)a + (1.0f/(v*v)) } 1.6439345666815615  
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...
#FreeBASIC
FreeBASIC
' FB 1.05.0 Win64   Sub stripComment(s As String, commentMarkers As String) If s = "" Then Return Dim i As Integer = Instr(s, Any commentMarkers) If i > 0 Then s = Left(s, i - 1) s = Trim(s) '' removes both leading and trailing whitespace End If End Sub   Dim s(1 To 4) As String = _ { _ "apples, pea...
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...
#Go
Go
package main   import ( "fmt" "strings" "unicode" )   const commentChars = "#;"   func stripComment(source string) string { if cut := strings.IndexAny(source, commentChars); cut >= 0 { return strings.TrimRightFunc(source[:cut], unicode.IsSpace) } return source }   func main() { for _, s := range []string{ "a...
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...
#jq
jq
def strip_block_comments(open; close): def deregex: reduce ("\\\\", "\\*", "\\^", "\\?", "\\+", "\\.", "\\!", "\\{", "\\}", "\\[", "\\]", "\\$", "\\|" ) as $c (.; gsub($c; $c)); # "?" => reluctant, "m" => multiline gsub( (open|deregex) + ".*?" + (close|deregex); ""; "m") ;   strip_block_com...
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...
#Julia
Julia
function _stripcomments(txt::AbstractString, dlm::Tuple{String,String}) "Strips first nest of block comments"   dlml, dlmr = dlm indx = searchindex(txt, dlml) if indx > 0 out = IOBuffer() write(out, txt[1:indx-1]) txt = txt[indx+length(dlml):end] txt = _stripcomments(txt,...
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...
#Kotlin
Kotlin
// version 1.1.4-3   val sample = """ /** * Some comments * longer comments here that we can parse. * * Rahoo */ function subroutine() { a = /* inline comment */ b + c ; } /*/ <-- tricky comments */   /** * Another comment. */ function something() { } """   val sample2 = ...
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 |...
#Batch_File
Batch File
@echo off setlocal enabledelayedexpansion call :interpolate %1 %2 res echo %res% goto :eof   :interpolate set pat=%~1 set str=%~2 set %3=!pat:X=%str%! goto :eof
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 |...
#BQN
BQN
Str ← (3⌊•Type)◶⟨2=•Type∘⊑,0,1,0⟩ _interpolate ← {∾(•Fmt⍟(¬Str)¨𝕨)⌾((𝕗=𝕩)⊸/)𝕩}   'a'‿"def"‿45‿⟨1,2,3⟩‿0.34241 '·'_interpolate "Hi · am · and · or · float ·"
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,   ...
#Scala
Scala
object SumTo100 { def main(args: Array[String]): Unit = { val exps = expressions(9).map(str => (str, eval(str))) val sums = exps.map(_._2).sortWith(_>_)   val s1 = exps.filter(_._2 == 100) val s2 = sums.distinct.map(s => (s, sums.count(_ == s))).maxBy(_._2) val s3 = sums.distinct.reverse.filter(_>...
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...
#C.2B.2B
C++
#include <algorithm> #include <iostream> #include <string>   std::string stripchars(std::string str, const std::string &chars) { str.erase( std::remove_if(str.begin(), str.end(), [&](char c){ return chars.find(c) != std::string::npos; }), str.end() ); return str; }   int ...
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...
#Clojure
Clojure
(defn strip [coll chars] (apply str (remove #((set chars) %) coll)))   (strip "She was a soul stripper. She took my heart!" "aei") ;; => "Sh ws soul strppr. Sh took my hrt!"
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 |...
#Fortran
Fortran
INTEGER*4 I,TEXT(66) DATA TEXT(1),TEXT(2),TEXT(3)/"Wo","rl","d!"/   WRITE (6,1) (TEXT(I), I = 1,3) 1 FORMAT ("Hello ",66A2)   DO 2 I = 1,3 2 TEXT(I + 3) = TEXT(I) TEXT(1) = "He" TEXT(2) = "ll" TEXT(3) = "o "   WRITE (6,3) (TEXT(I), I = 1,6) 3 FORMAT (66A2) ...
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 |...
#FreeBASIC
FreeBASIC
' FB 1.05.0 Win64   Var s = "prepend" s = "String " + s Print s Sleep
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 |...
#Avail
Avail
Method "string comparisons_,_" is [ a : string, b : string | Print: "a & b are equal? " ++ “a = b”; Print: "a & b are not equal? " ++ “a ≠ b”; // Inequalities compare by code point Print: "a is lexically before b? " ++ “a < b”; Print: "a is lexically after b? " ++ “a > b”; // Supports no...
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 |...
#AutoHotkey
AutoHotkey
exact_equality(a,b){ return (a==b) } exact_inequality(a,b){ return !(a==b) } equality(a,b){ return (a=b) } inequality(a,b){ return !(a=b) } ordered_before(a,b){ return ("" a < "" b) } ordered_after(a,b){ return ("" a > "" b) }
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...
#Arbre
Arbre
main(): uppercase('alphaBETA') + '\n' + lowercase('alphaBETA') + '\n' -> io
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...
#Arturo
Arturo
str: "alphaBETA"   print ["uppercase  :" upper str] print ["lowercase  :" lower str] print ["capitalize :" capitalize 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 |...
#BASIC
BASIC
first$ = "qwertyuiop"   'Determining if the first string starts with second string second$ = "qwerty" IF LEFT$(first$, LEN(second$)) = second$ THEN PRINT "'"; first$; "' starts with '"; second$; "'" ELSE PRINT "'"; first$; "' does not start with '"; second$; "'" END IF   'Determining if the first string contain...
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...
#ARM_Assembly
ARM Assembly
  /* ARM assembly Raspberry PI */ /* program stringLength.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 */ /* for constantes see task include a ...
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 ...
#Go
Go
package main   import ( "golang.org/x/text/transform" "golang.org/x/text/unicode/norm" "fmt" "strings" )   // two byte-oriented functions identical except for operator comparing c to 127. func stripCtlFromBytes(str string) string { b := make([]byte, len(str)) var bl int for i := 0; i < len(str); i++ { c := 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...
#Bracmat
Bracmat
"Hello ":?var1 & "World":?var2 & str$(!var1 !var2):?var12 & put$("var1=" !var1 ", var2=" !var2 ", var12=" !var12 "\n")
http://rosettacode.org/wiki/String_concatenation
String concatenation
String concatenation You are encouraged to solve this task according to the task description, using any language you may know. Task Create a string variable equal to any text value. Create another string variable whose value is the original variable concatenated with another string literal. To illustrate the operat...
#Burlesque
Burlesque
blsq ) "Hello, ""world!"?+ "Hello, world!"
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...
#C
C
#include <stdio.h> #include <stdlib.h> #include <string.h>   char *sconcat(const char *s1, const char *s2) { char *s0 = malloc(strlen(s1)+strlen(s2)+1); strcpy(s0, s1); strcat(s0, s2); return s0; }   int main() { const char *s = "hello"; char *s2;   printf("%s literal\n", s); /* or */ printf("%s%...
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.
#jq
jq
  def sum_multiples(d): ((./d) | floor) | (d * . * (.+1))/2 ;   # Sum of multiples of a or b that are less than . (the input) def task(a;b): . - 1 | sum_multiples(a) + sum_multiples(b) - sum_multiples(a*b);
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
#jq
jq
tostring | explode | map(tonumber - 48) | add
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
#Logo
Logo
print apply "sum map [? * ?] [1 2 3 4 5]  ; 55
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
#Logtalk
Logtalk
sum(List, Sum) :- sum(List, 0, Sum).   sum([], Sum, Sum). sum([X| Xs], Acc, Sum) :- Acc2 is Acc + X, sum(Xs, Acc2, 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...
#Factor
Factor
USE: unicode " test string " [ blank? ] trim  ! leading and trailing " test string " [ blank? ] trim-head  ! only leading " test string " [ blank? ] trim-tail  ! only trailing
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...
#Forth
Forth
: -leading ( addr len -- addr' len' ) \ called "minus-leading" begin over c@ bl = \ fetch character at addr, test if blank (space) while \ cut 1 leading character by incrementing address & decrementing length 1 /string \ "cut-string" repeat ;
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...
#Ring
Ring
  load "stdlib.ring"   see "working..." + nl   p = 0 num = 0 pr1 = 37 pr2 = 38 limit1 = 457 limit2 = 1000000 limit3 = 10000000 primes = []   see "first 36 strong primes:" + nl while true p = p + 1 if isprime(p) if p < limit1 add(primes,p) else exit ok ...
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...
#Ruby
Ruby
require 'prime'   strong_gen = Enumerator.new{|y| Prime.each_cons(3){|a,b,c|y << b if a+c-b<b} } weak_gen = Enumerator.new{|y| Prime.each_cons(3){|a,b,c|y << b if a+c-b>b} }   puts "First 36 strong primes:" puts strong_gen.take(36).join(" "), "\n" puts "First 37 weak primes:" puts weak_gen.take(37).join(" "), "\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 |...
#Component_Pascal
Component Pascal
  MODULE Substrings; IMPORT StdLog,Strings;   PROCEDURE Do*; CONST aStr = "abcdefghijklmnopqrstuvwxyz"; VAR str: ARRAY 128 OF CHAR; pos: INTEGER; BEGIN Strings.Extract(aStr,3,10,str); StdLog.String("from 3, 10 characters:> ");StdLog.String(str);StdLog.Ln; Strings.Extract(aStr,3,LEN(aStr) - 3,str); StdLog.String(...
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.
#F.23
F#
module SudokuBacktrack   //Helpers let tuple2 a b = a,b let flip f a b = f b a let (>>=) f g = Option.bind g f   /// "A1" to "I9" squares as key in values dictionary let key a b = $"{a}{b}"   /// Cross product of elements in ax and elements in bx let cross ax bx = [| for a in ax do for b in bx do key a b |]   // const...
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...
#J
J
readchar=:3 :0 if.0=#INBUF do. INBUF=:LF,~1!:1]1 end. r=.3 u:{.INBUF INBUF=:}.INBUF r )   writechar=:3 :0 OUTBUF=:OUTBUF,u:y )   subleq=:3 :0 INBUF=:OUTBUF=:'' p=.0 whilst.0<:p do. 'A B C'=. (p+0 1 2){y p=.p+3 if._1=A do. y=. (readchar'') B} y elseif._1=B do. writechar A{y elseif. 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...
#Janet
Janet
(defn main [& args] (let [filename (get args 1) fh (file/open filename) program (file/read fh :all) memory (eval-string (string "@[" program "]")) size (length memory)]   (var pc 0)   (while (<= 0 pc size) (let [a (get memory pc) b (get memor...
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: ...
#Raku
Raku
use Math::Primesieve; my $sieve = Math::Primesieve.new;   my $max = 1_000_000; my @primes = $sieve.primes($max); my $filter = @primes.Set; my $primes = @primes.categorize: &successive;   sub successive ($i) { gather { take '2' if $filter{$i + 2}; take '1' if $filter{$i + 1}; take '2_2' if al...
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...
#FreeBASIC
FreeBASIC
' FB 1.05.0 Win64   Dim s As String = "panda" Dim s1 As String = Mid(s, 2) Dim s2 As String = Left(s, Len(s) - 1) Dim s3 As String = Mid(s, 2, Len(s) - 2) Print s Print s1 Print s2 Print s3 Sleep
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...
#Python
Python
  import collections s= collections.deque(maxlen=55) # Start with a single seed in range 0 to 10**9 - 1. seed = 292929   # Set s0 = seed and s1 = 1. # The inclusion of s1 = 1 avoids some bad states # (like all zeros, or all multiples of 10). s.append(seed) s.append(1)   # Compute s2,s3,...,s54 using th...
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.
#Icon_and_Unicon
Icon and Unicon
procedure main(arglist) every ( sum := 0 ) +:= !arglist every ( prod := 1 ) *:= !arglist write("sum := ", sum,", prod := ",prod) 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...
#Fermat
Fermat
Sigma<k=1,1000>[1/k^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...
#Groovy
Groovy
def stripComments = { it.replaceAll(/\s*[#;].*$/, '') }
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...
#Haskell
Haskell
ms = ";#"   main = getContents >>= mapM_ (putStrLn . takeWhile (`notElem` ms)) . lines
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...
#Icon_and_Unicon
Icon and Unicon
# strip_comments: # return part of string up to first character in 'markers', # or else the whole string if no comment marker is present procedure strip_comments (str, markers) return str ? tab(upto(markers) | 0) end   procedure main () write (strip_comments ("apples, pears and bananas", cset ("#;"))) write (...
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...
#Ksh
Ksh
  #!/bin/ksh   # Strip block comments   # # Variables: # bd=${1:-'/*'} ed=${2:-'*/'}   testcase='/** * Some comments * longer comments here that we can parse. * * Rahoo */ function subroutine() { a = /* inline comment */ b + c ; } /*/ <-- tricky comments */   /** * Another comment. */ function something()...
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...
#Liberty_BASIC
Liberty BASIC
global CRLF$ CRLF$ =chr$( 13) +chr$( 10)   sample$ =" /**"+CRLF$+_ " * Some comments"+CRLF$+_ " * longer comments here that we can parse."+CRLF$+_ " *"+CRLF$+_ " * Rahoo "+CRLF$+_ " */"+CRLF$+_ " function subroutine() {"+CRLF$+_ " a = /* inline comment */ b + c ;"+CRLF$+_ " }"+CRLF$+_ " /*/ <-- tric...
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 |...
#Bracmat
Bracmat
@("Mary had a X lamb":?a X ?z) & str$(!a little !z)
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 |...
#C
C
#include <stdio.h>   int main() { const char *extra = "little"; printf("Mary had a %s lamb.\n", extra); return 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 |...
#C.23
C#
class Program { static void Main() { string extra = "little"; string formatted = $"Mary had a {extra} lamb."; System.Console.WriteLine(formatted); } }
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,   ...
#Sidef
Sidef
func gen_expr() is cached { var x = ['-', ''] var y = ['+', '-', '']   gather { cartesian([x,y,y,y,y,y,y,y,y], {|a,b,c,d,e,f,g,h,i| take("#{a}1#{b}2#{c}3#{d}4#{e}5#{f}6#{g}7#{h}8#{i}9") }) } }   func eval_expr(expr) is cached { expr.scan(/([-+]?\d+)/).sum_by { Num(_) } } ...
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...
#CLU
CLU
stripchars = proc (input, chars: string) returns (string) result: array[char] := array[char]$[] for c: char in string$chars(input) do if string$indexc(c, chars) = 0 then array[char]$addh(result, c) end end return(string$ac2s(result)) end stripchars   start_up = proc () po...
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...
#COBOL
COBOL
IDENTIFICATION DIVISION. PROGRAM-ID. Strip-Chars.   DATA DIVISION. WORKING-STORAGE SECTION. 01 Str-Size CONSTANT 128.   LOCAL-STORAGE SECTION. 01 I PIC 999. 01 Str-Pos PIC 999.   01 Offset PIC 999. 01 New-Pos PIC 999.   01 Str-En...
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 |...
#Gambas
Gambas
Public Sub Main() Dim sString1 As String = "world!" Dim sString2 As String = "Hello "   sString1 = sString2 & sString1   Print sString1   End
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 |...
#Go
Go
s := "world!" s = "Hello, " + s
http://rosettacode.org/wiki/String_prepend
String prepend
Basic Data Operation This is a basic data operation. It represents a fundamental action on a basic data type. You may see other such operations in the Basic Data Operations category, or: Integer Operations Arithmetic | Comparison Boolean Operations Bitwise | Logical String Operations Concatenation | Interpolation |...
#Haskell
Haskell
  Prelude> let f = (++" World!") Prelude> f "Hello"  
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 |...
#AWK
AWK
BEGIN { a="BALL" b="BELL"   if (a == b) { print "The strings are equal" } if (a != b) { print "The strings are not equal" } if (a > b) { print "The first string is lexically after than the second" } if (a < b) { print "The first string is lexically before than the second" } if (a >= b) { print "The firs...
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 |...
#BASIC
BASIC
10 LET "A$="BELL" 20 LET B$="BELT" 30 IF A$ = B$ THEN PRINT "THE STRINGS ARE EQUAL": REM TEST FOR EQUALITY 40 IF A$ <> B$ THEN PRINT "THE STRINGS ARE NOT EQUAL": REM TEST FOR INEQUALITY 50 IF A$ > B$ THEN PRINT A$;" IS LEXICALLY HIGHER THAN ";B$: REM TEST FOR LEXICALLY HIGHER 60 IF A$ < B$ THEN PRINT A$;" IS LEXICALLY ...
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...
#AutoHotkey
AutoHotkey
a := "alphaBETA" StringLower, b, a ; alphabeta StringUpper, c, a ; ALPHABETA   StringUpper, d, a, T ; Alphabeta (T = title case) eg "alpha beta gamma" would become "Alpha Beta Gamma"
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 |...
#Batch_File
Batch File
::NOTE #1: This implementation might crash, or might not work properly if ::you put some of the CMD special characters (ex. %,!, etc) inside the strings. :: ::NOTE #2: The comparisons here are case-SENSITIVE. ::NOTE #3: Spaces in strings are considered.   @echo off setlocal enabledelayedexpansion ::The main things... ...
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...
#Arturo
Arturo
str: "Hello World"   print ["length =" size 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...
#AutoHotkey
AutoHotkey
Msgbox % StrLen("Hello World")
http://rosettacode.org/wiki/Strip_control_codes_and_extended_characters_from_a_string
Strip control codes and extended characters from a string
Task Strip control codes and extended characters from a string. The solution should demonstrate how to achieve each of the following results:   a string with control codes stripped (but extended characters not stripped)   a string with control codes and extended characters stripped In ASCII, the control codes ...
#Groovy
Groovy
def stripControl = { it.replaceAll(/\p{Cntrl}/, '') } def stripControlAndExtended = { it.replaceAll(/[^\p{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 ...
#Haskell
Haskell
import Control.Applicative (liftA2)   strip, strip2 :: String -> String strip = filter (liftA2 (&&) (> 31) (< 126) . fromEnum)   -- or strip2 = filter (((&&) <$> (> 31) <*> (< 126)) . fromEnum)   main :: IO () main = (putStrLn . unlines) $ [strip, strip2] <*> ["alphabetic 字母 with some less parochial parts"]
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...
#C.23
C#
using System;   class Program { static void Main(string[] args) { var s = "hello"; Console.Write(s); Console.WriteLine(" literal"); var s2 = s + " literal"; Console.WriteLine(s2); } }
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...
#C.2B.2B
C++
#include <string> #include <iostream>   int main() { std::string s = "hello"; std::cout << s << " literal" << std::endl; std::string s2 = s + " literal"; std::cout << s2 << std::endl; return 0; }
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.
#Julia
Julia
multsum(n, m, lim) = sum(0:n:lim-1) + sum(0:m:lim-1) - sum(0:lcm(n,m):lim-1)
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
#Julia
Julia
sumdigits(n, base=10) = sum(digits(n, base))
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
#Kotlin
Kotlin
// version 1.1.0   const val digits = "0123456789abcdefghijklmnopqrstuvwxyz"   fun sumDigits(ns: String, base: Int): Int { val n = ns.toLowerCase().trim() if (base !in 2..36) throw IllegalArgumentException("Base must be between 2 and 36") if (n.isEmpty()) throw IllegalArgumentException("Number string can...
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
#Lua
Lua
function squaresum(a, ...) return a and a^2 + squaresum(...) or 0 end function squaresumt(t) return squaresum(unpack(t)) end   print(squaresumt{3, 5, 4, 1, 7})
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...
#Fortran
Fortran
' FB 1.05.0 Win64   Const whitespace = !" \t\n\v\f\r"   Dim s As String = !" \tRosetta Code \v\f\r\n" Dim s1 As String = LTrim (s, Any whitespace) Dim s2 As String = RTrim (s, Any whitespace) Dim s3 As String = Trim (s, Any whitespace)   ' Under Windows console : ' "vertical tab" displays as ♂ ' "form feed" display...
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...
#Rust
Rust
fn is_prime(n: i32) -> bool { for i in 2..n { if i * i > n { return true; } if n % i == 0 { return false; } } n > 1 }   fn next_prime(n: i32) -> i32 { for i in (n+1).. { if is_prime(i) { return i; } } 0 }   fn main() { let mut n = 0; let mut prime_q = 5; let mut prime_p = 3; let mut prime...
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 |...
#Crystal
Crystal
def substring_demo(string, n, m, known_character, known_substring) n -= 1   puts string[n...n+m]   puts string[n...]   puts string.rchop   known_character_index = string.index(known_character).not_nil! puts string[known_character_index...known_character_index+m]   known_substring_index = str...
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.
#Forth
Forth
include lib/interprt.4th include lib/istype.4th include lib/argopen.4th   \ --------------------- \ Variables \ ---------------------   81 string sudokugrid 9 array sudoku_row 9 array sudoku_col 9 array sudoku_box   \ ------------- \ 4tH interface \ -------------   : >grid ( n2 a1 n...
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...
#Java
Java
import java.util.Scanner;   public class Subleq {   public static void main(String[] args) { int[] 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};   Scanner input = new Scanner(System.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: ...
#REXX
REXX
/*REXX program finds and displays primes with successive differences (up to a limit).*/ parse arg H . 1 . difs /*allow the highest number be specified*/ if H=='' | H=="," then H= 1000000 /*Not specified? Then use the default.*/ if difs='' then difs= 2 1 2.2 2.4 4.2 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...
#Go
Go
package main   import ( "fmt" "unicode/utf8" )   func main() { // ASCII contents: Interpreting "characters" as bytes. s := "ASCII" fmt.Println("String: ", s) fmt.Println("First byte removed: ", s[1:]) fmt.Println("Last byte removed: ", s[:len(s)-1]) fmt.Println("Fi...
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...
#Racket
Racket
#lang racket (define (make-initial-state a-list max-i) (for/fold ((state a-list)) ((i (in-range (length a-list) max-i))) (append state (list (- (list-ref state (- i 2)) (list-ref state (- i 1))))))) ;from the seed and 1 creates the initial state   (define (shuffle a-list) (for/list ((i (in-range (le...