task_url stringlengths 30 116 | task_name stringlengths 2 86 | task_description stringlengths 0 14.4k | language_url stringlengths 2 53 | language_name stringlengths 1 52 | code stringlengths 0 61.9k |
|---|---|---|---|---|---|
http://rosettacode.org/wiki/Subtractive_generator | Subtractive generator | A subtractive generator calculates a sequence of random numbers, where each number is congruent to the subtraction of two previous numbers from the sequence.
The formula is
r
n
=
r
(
n
−
i
)
−
r
(
n
−
j
)
(
mod
m
)
{\displaystyle r_{n}=r_{(n-i)}-r_{(n-j)}{\pmod {m}}}
for some fixed values of... | #Haskell | Haskell | subtractgen :: Int -> [Int]
subtractgen seed = drop 220 out
where
out = mmod $ r <> zipWith (-) out (drop 31 out)
where
r = take 55 $ shuffle $ cycle $ take 55 s
shuffle x = (:) . head <*> shuffle $ drop 34 x
s = mmod $ seed : 1 : zipWith (-) s (tail s)
mmod = fmap (`mod` 10 ... |
http://rosettacode.org/wiki/Substitution_cipher | Substitution cipher | Substitution Cipher Implementation - File Encryption/Decryption
Task
Encrypt a input/source file by replacing every upper/lower case alphabets of the source file with another predetermined upper/lower case alphabets or symbols and save it into another output/encrypted file and then again convert that output/encrypt... | #Python | Python |
from string import printable
import random
EXAMPLE_KEY = ''.join(sorted(printable, key=lambda _:random.random()))
def encode(plaintext, key):
return ''.join(key[printable.index(char)] for char in plaintext)
def decode(plaintext, key):
return ''.join(printable[key.index(char)] for char in plaintext)
or... |
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.
| #Erlang | Erlang | % create the list:
L = lists:seq(1, 10).
% and compute its sum:
S = lists:sum(L).
P = lists:foldl(fun (X, P) -> X * P end, 1, L). |
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... | #EchoLisp | EchoLisp |
(lib 'math) ;; for (sigma f(n) nfrom nto) function
(Σ (λ(n) (// (* n n))) 1 1000)
;; or
(sigma (lambda(n) (// (* n n))) 1 1000)
→ 1.6439345666815615
(// (* PI PI) 6)
→ 1.6449340668482264
|
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... | #ALGOL_W | ALGOL W | begin
% determines the non-comment portion of the string s, startPos and endPos are %
% returned set to the beginning and ending character positions (indexed from 0) %
% of the non-comment text in s. If there is no non-comment text in s, startPos %
% will be greater than endPos ... |
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... | #Applesoft_BASIC | Applesoft BASIC | 10 LET C$ = ";#"
20 S$(1)="APPLES, PEARS # AND BANANAS"
30 S$(2)="APPLES, PEARS ; AND BANANAS"
40 FOR Q = 1 TO 2
50 LET S$ = S$(Q)
60 GOSUB 100"STRIP COMMENTS
70 PRINT S$
80 NEXT Q
90 END
100 IF S$ = "" THEN RETURN
110 FOR I = 1 TO LEN(S$)
120 LET A$ = MID$(S$, I, 1)
130 FOR J = 1 TO LEN(C$)
140 ... |
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... | #C | C | #include <stdio.h>
#include <string.h>
#include <stdlib.h>
const char *ca = "/*", *cb = "*/";
int al = 2, bl = 2;
char *loadfile(const char *fn) {
FILE *f = fopen(fn, "rb");
int l;
char *s;
if (f != NULL) {
fseek(f, 0, SEEK_END);
l = ftell(f);
s = malloc(l+1);
rewind(f);
if (s)
fread(s, ... |
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, ... | #Modula-2 | Modula-2 | MODULE SumTo100;
FROM FormatString IMPORT FormatString;
FROM Terminal IMPORT WriteString,WriteLn,ReadChar;
PROCEDURE Evaluate(code : INTEGER) : INTEGER;
VAR
value,number,power,k : INTEGER;
BEGIN
value := 0;
number := 0;
power := 1;
FOR k:=9 TO 1 BY -1 DO
number := power * k + number;
... |
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... | #Action.21 | Action! | PROC Strip(CHAR ARRAY text,chars,res)
BYTE i,j,size,found
CHAR c
size=0
FOR i=1 TO text(0)
DO
c=text(i) found=0
FOR j=1 TO chars(0)
DO
IF c=chars(j) THEN
found=1 EXIT
FI
OD
IF found=0 THEN
size==+1
res(size)=c
FI
OD
res(0)=size
RETURN
PROC Main()... |
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 |... | #AppleScript | AppleScript | set aVariable to "world!"
set aVariable to "Hello " & aVariable
return aVariable |
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 |... | #Arturo | Arturo | a: "World"
a: "Hello" ++ a
print a
b: "World"
b: append "Hello" b
print a
c: "World"
prefix 'c "Hello"
print c
d: "World"
print prefix d "Hello" |
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 |... | #11l | 11l | print(‘abcd’.starts_with(‘ab’))
print(‘abcd’.ends_with(‘zn’))
print(‘bb’ C ‘abab’)
print(‘ab’ C ‘abab’)
print(‘abab’.find(‘bb’) ? -1)
print(‘abab’.find(‘ab’) ? -1) |
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... | #360_Assembly | 360 Assembly | * String length 06/07/2016
LEN CSECT
USING LEN,15 base register
LA 1,L'C length of C
XDECO 1,PG
XPRNT PG,12
LA 1,L'H length of H
XDECO 1,PG
XPRNT PG,12
LA 1,L'F ... |
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 ... | #AWK | AWK |
# syntax: GAWK -f STRIP_CONTROL_CODES_AND_EXTENDED_CHARACTERS.AWK
BEGIN {
s = "ab\xA2\x09z" # a b cent tab z
printf("original string: %s (length %d)\n",s,length(s))
gsub(/[\x00-\x1F\x7F]/,"",s); printf("control characters stripped: %s (length %d)\n",s,length(s))
gsub(/[\x80-\xFF]/,"",s); printf("contr... |
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.
| #FBSL | FBSL | #APPTYPE CONSOLE
FUNCTION sumOfThreeFiveMultiples(n AS INTEGER)
DIM sum AS INTEGER
FOR DIM i = 1 TO n - 1
IF (NOT (i MOD 3)) OR (NOT (i MOD 5)) THEN
INCR(sum, i)
END IF
NEXT
RETURN sum
END FUNCTION
PRINT sumOfThreeFiveMultiples(1000)
PAUSE
|
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
| #Forth | Forth | : sum_int 0 begin over while swap base @ /mod swap rot + repeat nip ;
2 base ! 11110 sum_int decimal . cr
10 base ! 12345 sum_int decimal . cr
16 base ! f0e sum_int decimal . cr |
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
| #Go | Go | package main
import "fmt"
var v = []float32{1, 2, .5}
func main() {
var sum float32
for _, x := range v {
sum += x * x
}
fmt.Println(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... | #BaCon | BaCon |
'---Remove leading whitespace
PRINT CHOP$(" String with spaces "," ",1)
'---Remove trailing whitespace
PRINT CHOP$(" String with spaces "," ",2)
'---Remove both leading and trailing whitespace
PRINT CHOP$(" String with spaces "," ",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... | #Haskell | Haskell | import Text.Printf (printf)
import Data.Numbers.Primes (primes)
xPrimes :: (Real a, Fractional b) => (b -> b -> Bool) -> [a] -> [a]
xPrimes op ps@(p1:p2:p3:xs)
| realToFrac p2 `op` (realToFrac (p1 + p3) / 2) = p2 : xPrimes op (tail ps)
| otherwise = xPrimes op (tail ps)
main :: IO ()
main = do
printf "First ... |
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 |... | #Arturo | Arturo | str: "abcdefgh"
n: 2
m: 3
; starting from n=2 characters in and m=3 in length
print slice str n-1 n+m-2
; starting from n characters in, up to the end of the string
print slice str n-1 (size str)-1
; whole string minus last character
print slice str 0 (size str)-2
; starting from a known character char="d"
; w... |
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.
| #C.23 | C# | using System;
class SudokuSolver
{
private int[] grid;
public SudokuSolver(String s)
{
grid = new int[81];
for (int i = 0; i < s.Length; i++)
{
grid[i] = int.Parse(s[i].ToString());
}
}
public void solve()
{
try
{
plac... |
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... | #C | C | #include <stdlib.h>
#include <stdio.h>
void
subleq(int *code)
{
int ip = 0, a, b, c, nextIP;
char ch;
while(0 <= ip) {
nextIP = ip + 3;
a = code[ip];
b = code[ip + 1];
c = code[ip + 2];
if(a == -1) {
scanf("%c", &ch);
code[b] = (int)ch;
} else if(b == -1) {
printf("%c", (char)code[a]);
} els... |
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:
... | #J | J |
primes_less_than=: i.&.:(p:inv)
assert 2 3 5 -: primes_less_than 7
Primes=: primes_less_than 1e6
NB. Insert minus `-/' into the length two infixes `\'.
NB. Passive `~' swaps the arguments producing the positive differences.
Successive_Differences=: 2 -~/\ Primes
assert 8169 -: +/ 2 = Successive... |
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... | #C.2B.2B | C++ | #include <string>
#include <iostream>
int main( ) {
std::string word( "Premier League" ) ;
std::cout << "Without first letter: " << word.substr( 1 ) << " !\n" ;
std::cout << "Without last letter: " << word.substr( 0 , word.length( ) - 1 ) << " !\n" ;
std::cout << "Without first and last letter: " << word.... |
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... | #Icon_and_Unicon | Icon and Unicon | procedure main()
every 1 to 10 do
write(rand_sub(292929))
end
procedure rand_sub(x)
static ring,m
if /ring then {
m := 10^9
every (seed | ring) := list(55)
seed[1] := \x | ?(m-1)
seed[2] := 1
every seed[n := 3 to 55] := (seed[n-2]-seed[n-1])%m
every ring[(n := 0 to 54)... |
http://rosettacode.org/wiki/Substitution_cipher | Substitution cipher | Substitution Cipher Implementation - File Encryption/Decryption
Task
Encrypt a input/source file by replacing every upper/lower case alphabets of the source file with another predetermined upper/lower case alphabets or symbols and save it into another output/encrypted file and then again convert that output/encrypt... | #Quackery | Quackery | [ stack ] is encryption ( --> s )
[ stack ] is decryption ( --> s )
[ [] 95 times [ i^ join ]
shuffle encryption put ] is makeencrypt ( --> )
[ encryption share
0 95 of swap
witheach
[ i^ unrot poke ]
decryption put ] ... |
http://rosettacode.org/wiki/Substitution_cipher | Substitution cipher | Substitution Cipher Implementation - File Encryption/Decryption
Task
Encrypt a input/source file by replacing every upper/lower case alphabets of the source file with another predetermined upper/lower case alphabets or symbols and save it into another output/encrypted file and then again convert that output/encrypt... | #Racket | Racket | #lang racket/base
(require racket/list racket/function racket/file)
(define abc "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz")
;; Used to generate my-key for examples
(define (random-key (alphabet abc))
(list->string (shuffle (string->list alphabet))))
(define (cypher/decypher key (alphabet abc))
;; ... |
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.
| #Euphoria | Euphoria | sequence array
integer sum,prod
array = { 1, 2, 3, 4, 5 }
sum = 0
prod = 1
for i = 1 to length(array) do
sum += array[i]
prod *= array[i]
end for
printf(1,"sum is %d\n",sum)
printf(1,"prod is %d\n",prod) |
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... | #EDSAC_order_code | EDSAC order code |
[Sum of a series, Rosetta Code website.
EDSAC program, Initial Orders 2.]
..PZ [blank tape and terminator]
[Library subroutine D6 - Division, accurate, fast.
36 locations, working positons 6D and 8D.
C(0D) := C(0D)/C(4D), where C(4D) <> 0, -1.]
T56K
GKA3FT34@S4DE13@T4DSDTDE2@T4DAD... |
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... | #Arturo | Arturo | stripComments: function [str][
strip replace str {/[#;].+/} ""
]
loop ["apples, pears # and bananas", "apples, pears ; and bananas"] 'str [
print [str "->" stripComments str]
] |
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... | #AutoHotkey | AutoHotkey | Delims := "#;"
str := "apples, pears # and bananas"
str2:= "apples, pears, `; and bananas" ; needed to escape the ; since that is AHK's comment marker
msgbox % StripComments(Str,Delims)
msgbox % StripComments(Str2,Delims)
; The % forces expression mode.
StripComments(String1,Delims){
Loop, parse, delims
{
... |
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... | #C.23 | C# | using System;
class Program
{
private static string BlockCommentStrip(string commentStart, string commentEnd, string sampleText)
{
while (sampleText.IndexOf(commentStart) > -1 && sampleText.IndexOf(commentEnd, sampleText.IndexOf(commentStart) + commentStart.Length) > -1)
... |
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... | #C.2B.2B | C++ | #include <string>
#include <iostream>
#include <iterator>
#include <fstream>
#include <boost/regex.hpp>
int main( ) {
std::ifstream codeFile( "samplecode.txt" ) ;
if ( codeFile ) {
boost::regex commentre( "/\\*.*?\\*/" ) ;//comment start and end, and as few characters in between as possible
std... |
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, ... | #Nim | Nim | import algorithm, parseutils, sequtils, strutils, tables
type Expression = string
proc buildExprs(start: Natural = 0): seq[Expression] =
let item = if start == 0: "" else: $start
if start == 9: return @[item]
for expr in buildExprs(start + 1):
result.add item & expr
result.add item & '-' & expr
if... |
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... | #Ada | Ada | with Ada.Text_IO;
procedure Strip_Characters_From_String is
function Strip(The_String: String; The_Characters: String)
return String is
Keep: array (Character) of Boolean := (others => True);
Result: String(The_String'Range);
Last: Natural := Result'First-1;
begin
... |
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... | #Aime | Aime | text
stripchars1(data b, text w)
{
integer p;
p = b.look(0, w);
while (p < ~b) {
b.delete(p);
p += b.look(p, w);
}
b;
}
text
stripchars2(data b, text w)
{
b.drop(w);
}
integer
main(void)
{
o_text(stripchars1("She was a soul stripper. She took my heart!", "aei"));
... |
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 |... | #Asymptote | Asymptote | string s1 = " World!";
write("Hello" + s1);
write("Hello", s1);
string s2 = "Hello" + s1;
write(s2); |
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 |... | #AutoHotkey | AutoHotkey | s := "foo"
s := s "bar"
Msgbox % s |
http://rosettacode.org/wiki/String_matching | String matching |
Basic Data Operation
This is a basic data operation. It represents a fundamental action on a basic data type.
You may see other such operations in the Basic Data Operations category, or:
Integer Operations
Arithmetic |
Comparison
Boolean Operations
Bitwise |
Logical
String Operations
Concatenation |
Interpolation |... | #360_Assembly | 360 Assembly | * String matching 04/04/2017
STRMATCH CSECT
USING STRMATCH,R15
XPRNT SS,L'SS
*
CLC SS(L'S1),S1
BNE NOT1
XPRNT =C'-- STARTS WITH',14
XPRNT S1,L'S1
NOT1 EQU *
*
CLC SS+L'SS-L'S2(L'S2),S2
BNE NOT2
XPRNT... |
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... | #6502_Assembly | 6502 Assembly | GetStringLength: ;$00 and $01 make up the pointer to the string's base address.
;(Of course, any two consecutive zero-page memory locations can fulfill this role.)
LDY #0 ;Y is both the index into the string and the length counter.
loop_getStringLength:
LDA ($00),y
BEQ exit
INY
JMP loop_ge... |
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 ... | #BASIC | BASIC | DECLARE FUNCTION strip$ (what AS STRING)
DECLARE FUNCTION strip2$ (what AS STRING)
DIM x AS STRING, y AS STRING, z AS STRING
' tab c+cedilla eof
x = CHR$(9) + "Fran" + CHR$(135) + "ais" + CHR$(26)
y = strip(x)
z = strip2(x)
PRINT "x:"; x
PRINT "y:"; y
PRINT "z:"; z
FUNCTION strip$ (wh... |
http://rosettacode.org/wiki/String_concatenation | String concatenation | String concatenation
You are encouraged to solve this task according to the task description, using any language you may know.
Task
Create a string variable equal to any text value.
Create another string variable whose value is the original variable concatenated with another string literal.
To illustrate the operat... | #11l | 11l | V s1 = ‘hello’
print(s1‘ world’)
V s2 = s1‘ world’
print(s2) |
http://rosettacode.org/wiki/Sum_multiples_of_3_and_5 | Sum multiples of 3 and 5 | Task
The objective is to write a function that finds the sum of all positive multiples of 3 or 5 below n.
Show output for n = 1000.
This is is the same as Project Euler problem 1.
Extra credit: do this efficiently for n = 1e20 or higher.
| #Forth | Forth | : main ( n -- )
0 swap
3 do
i 3 mod 0= if
i +
else i 5 mod 0= if
i +
then then
loop
. ;
1000 main \ 233168 ok |
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
| #Fortran | Fortran |
!-*- mode: compilation; default-directory: "/tmp/" -*-
!Compilation started at Fri Jun 7 21:00:12
!
!a=./f && make $a && $a
!gfortran -std=f2008 -Wall -fopenmp -ffree-form -fall-intrinsics -fimplicit-none f.f08 -o f
!f.f08:57.29:
!
! subroutine process1(fmt,s,b)
! 1
!Warning: Unused dumm... |
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
| #Golfscript | Golfscript | {0\{.*+}%}:sqsum;
# usage example
[1 2 3]sqsum puts |
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
| #Groovy | Groovy | def array = 1..3
// square via multiplication
def sumSq = array.collect { it * it }.sum()
println sumSq
// square via exponentiation
sumSq = array.collect { it ** 2 }.sum()
println sumSq |
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... | #BASIC | BASIC | mystring$=ltrim(mystring$) ' remove leading whitespace
mystring$=rtrim(mystring$) ' remove trailing whitespace
mystring$=ltrim(rtrim(mystring$)) ' remove both leading and trailing whitespace |
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... | #BBC_BASIC | BBC BASIC | REM Remove leading whitespace:
WHILE ASC(A$)<=32 A$ = MID$(A$,2) : ENDWHILE
REM Remove trailing whitespace:
WHILE ASC(RIGHT$(A$))<=32 A$ = LEFT$(A$) : ENDWHILE
REM Remove both leading and trailing whitespace:
WHILE ASC(A$)<=32 A$ = MID$(A$,2) : ENDWHILE
WHILE ASC(RIGHT$(A$)... |
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... | #J | J | Filter =: (#~`)(`:6)
average =: +/ % #
NB. vector of primes from 2 to 10000019
PRIMES=:i.@>:&.(p:inv) 10000000
strongQ =: 1&{ > [: average {. , {:
STRONG_PRIMES=: (0, 0,~ 3&(strongQ\))Filter PRIMES
NB. first 36 strong primes
36 {. STRONG_PRIMES
11 17 29 37 41 59 67 71 79 97 101 107 127 137 1... |
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... | #Java | Java |
public class StrongAndWeakPrimes {
private static int MAX = 10_000_000 + 1000;
private static boolean[] primes = new boolean[MAX];
public static void main(String[] args) {
sieve();
System.out.println("First 36 strong primes:");
displayStrongPrimes(36);
for ( int... |
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 |... | #AutoHotkey | AutoHotkey | String := "abcdefghijklmnopqrstuvwxyz"
; also: String = abcdefghijklmnopqrstuvwxyz
n := 12
m := 5
; starting from n characters in and of m length;
subString := SubStr(String, n, m)
; alternative: StringMid, subString, String, n, m
MsgBox % subString
; starting from n characters in, up to the end of the string;
sub... |
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.
| #C.2B.2B | C++ | #include <iostream>
using namespace std;
class SudokuSolver {
private:
int grid[81];
public:
SudokuSolver(string s) {
for (unsigned int i = 0; i < s.length(); i++) {
grid[i] = (int) (s[i] - '0');
}
}
void solve() {
try {
placeNumber(0);
... |
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... | #C.23 | C# | using System;
namespace Subleq {
class Program {
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,
... |
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:
... | #Java | Java | import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class SuccessivePrimeDifferences {
private static Integer[] sieve(int limit) {
List<Integer> primes = new ArrayList<>();
primes.add(2);
boolean[] c = new boolean[limit + 1];// composite = true
// no ... |
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... | #Clojure | Clojure | ; using substring:
user=> (subs "knight" 1)
"night"
user=> (subs "socks" 0 4)
"sock"
user=> (.substring "brooms" 1 5)
"room"
; using rest and drop-last:
user=> (apply str (rest "knight"))
"night"
user=> (apply str (drop-last "socks"))
"sock"
user=> (apply str (rest (drop-last "brooms")))
"room" |
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... | #J | J | came_from_locale_sg_=: coname''
cocurrent'sg' NB. install the state of rng sg into locale sg
SEED=: 292929
'I J M first_Bentley_number B2'=: 55 24 1e9 34 165
SG=: 1 : 'M&|@:-/@:(m&{)'
r=: (I|(first_Bentley_number*>:i.I)) { (, _2 _1 SG)^:(I-2) 1,~SEED
sg=: 3 : 0
t=. (, (-I,J)SG)^:y r
r=: y }. t
t {.~ -y
)
discard=. ... |
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... | #Java | Java | import java.util.function.IntSupplier;
import static java.util.stream.IntStream.generate;
public class SubtractiveGenerator implements IntSupplier {
static final int MOD = 1_000_000_000;
private int[] state = new int[55];
private int si, sj;
public SubtractiveGenerator(int p1) {
subrandSeed(... |
http://rosettacode.org/wiki/Substitution_cipher | Substitution cipher | Substitution Cipher Implementation - File Encryption/Decryption
Task
Encrypt a input/source file by replacing every upper/lower case alphabets of the source file with another predetermined upper/lower case alphabets or symbols and save it into another output/encrypted file and then again convert that output/encrypt... | #Raku | Raku | my $chr = (' ' .. '}').join('');
my $key = $chr.comb.pick(*).join('');
# Be very boring and use the same key every time to fit task reqs.
$key = q☃3#}^",dLs*>tPMcZR!fmC rEKhlw1v4AOgj7Q]YI+|pDB82a&XFV9yzuH<WT%N;iS.0e:`G\n['6@_{bk)=-5qx(/?$JoU☃;
sub MAIN ($action = 'encode', $file = '') {
die 'Only options are ... |
http://rosettacode.org/wiki/Sum_and_product_of_an_array | Sum and product of an array | Task
Compute the sum and product of an array of integers.
| #F.23 | F# |
let numbers = [| 1..10 |]
let sum = numbers |> Array.sum
let product = numbers |> Array.reduce (*)
|
http://rosettacode.org/wiki/Sum_and_product_of_an_array | Sum and product of an array | Task
Compute the sum and product of an array of integers.
| #Factor | Factor | 1 5 1 <range> [ sum . ] [ product . ] bi
15 120
{ 1 2 3 4 } [ sum ] [ product ] bi
10 24 |
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... | #Eiffel | Eiffel |
note
description: "Compute the n-th term of a series"
class
SUM_OF_SERIES_EXAMPLE
inherit
MATH_CONST
create
make
feature -- Initialization
make
local
approximated, known: REAL_64
do
known := Pi^2 / 6
approximated := sum_until (agent g, 1001)
print ("%Nzeta function exact value: %N")
... |
http://rosettacode.org/wiki/Strip_comments_from_a_string | Strip comments from a string | Strip comments from a string
You are encouraged to solve this task according to the task description, using any language you may know.
The task is to remove text that follow any of a set of comment markers, (in these examples either a hash or a semicolon) from a string or input line.
Whitespace debacle: There is s... | #AutoIt | AutoIt |
Dim $Line1 = "apples, pears # and bananas"
Dim $Line2 = "apples, pears ; and bananas"
_StripAtMarker($Line1)
_StripAtMarker($Line2)
Func _StripAtMarker($_Line, $sMarker='# ;')
Local $aMarker = StringSplit($sMarker, ' ')
Local $iPos
For $i = 1 To $aMarker[0]
$iPos = StringInStr($_Line, $aMarker[$i])
If $iPo... |
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... | #Clojure | Clojure | (defn comment-strip [txt & args]
(let [args (conj {:delim ["/*" "*/"]} (apply hash-map args)) ; This is the standard way of doing keyword/optional arguments in Clojure
[opener closer] (:delim args)]
(loop [out "", txt txt, delim-count 0] ; delim-count is needed to handle nested comments
(let [[hdtxt resttx... |
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, ... | #Pascal | Pascal | { RossetaCode: Sum to 100, Pascal.
Find solutions to the "sum to one hundred" puzzle.
We don't use arrays, but recompute all values again and again.
It is a little surprise that the time efficiency is quite acceptable. }
program sumto100;
const
ADD = 0; SUB = 1; JOIN = 2; { opcodes inserted between dig... |
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... | #ALGOL_68 | ALGOL 68 | #!/usr/local/bin/a68g --script #
PROC strip chars = (STRING mine, ore)STRING: (
STRING out := "";
FOR i FROM LWB mine TO UPB mine DO
IF NOT char in string(mine[i], LOC INT, ore) THEN
out +:= mine[i]
FI
OD;
out[@LWB mine]
);
printf(($gl$,stripchars("She was a soul stripper. She took my heart!",... |
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... | #ALGOL_W | ALGOL W | begin
% returns s with the characters in remove removed %
% as all strings in Algol W are fixed length, the length of remove %
% must be specified in removeLength %
string(256) procedure stripCharacters( string(256) value s, remove
... |
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 |... | #AWK | AWK |
# syntax: GAWK -f STRING_PREPEND.AWK
BEGIN {
s = "bar"
s = "foo" s
print(s)
exit(0)
}
|
http://rosettacode.org/wiki/String_prepend | String prepend |
Basic Data Operation
This is a basic data operation. It represents a fundamental action on a basic data type.
You may see other such operations in the Basic Data Operations category, or:
Integer Operations
Arithmetic |
Comparison
Boolean Operations
Bitwise |
Logical
String Operations
Concatenation |
Interpolation |... | #BaCon | BaCon | s$ = "prepend"
s$ = "String " & s$
PRINT s$ |
http://rosettacode.org/wiki/String_prepend | String prepend |
Basic Data Operation
This is a basic data operation. It represents a fundamental action on a basic data type.
You may see other such operations in the Basic Data Operations category, or:
Integer Operations
Arithmetic |
Comparison
Boolean Operations
Bitwise |
Logical
String Operations
Concatenation |
Interpolation |... | #BASIC | BASIC | S$ = " World!"
S$ = "Hello" + S$
PRINT S$
|
http://rosettacode.org/wiki/String_matching | String matching |
Basic Data Operation
This is a basic data operation. It represents a fundamental action on a basic data type.
You may see other such operations in the Basic Data Operations category, or:
Integer Operations
Arithmetic |
Comparison
Boolean Operations
Bitwise |
Logical
String Operations
Concatenation |
Interpolation |... | #AArch64_Assembly | AArch64 Assembly |
/* ARM assembly AARCH64 Raspberry PI 3B */
/* program strMatching64.s */
/*******************************************/
/* Constantes file */
/*******************************************/
/* for this file see task include a file in language AArch64 assembly*/
.include "../includeConstantes... |
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... | #68000_Assembly | 68000 Assembly | GetStringLength:
; INPUT: A3 = BASE ADDRESS OF STRING
; RETURNS LENGTH IN D1 (MEASURED IN BYTES)
MOVE.L #0,D1
loop_getStringLength:
MOVE.B (A3)+,D0
CMP #0,D0
BEQ done
ADDQ.L #1,D1
BRA loop_getStringLength
done:
RTS |
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 ... | #BBC_BASIC | BBC BASIC | test$ = CHR$(9) + "Fran" + CHR$(231) + "ais." + CHR$(127)
PRINT "Original ISO-8859-1 string: " test$ " (length " ; LEN(test$) ")"
test$ = FNstripcontrol(test$)
PRINT "Control characters stripped: " test$ " (length " ; LEN(test$) ")"
test$ = FNstripextended(test$)
PRINT "Control & ext... |
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 ... | #Bracmat | Bracmat | ( "string of ☺☻♥♦⌂, may include control
characters and other ilk.\L\D§►↔◄
Rødgrød med fløde"
: ?string1
: ?string2
& :?newString
& whl
' ( @(!string1:?clean (%@:<" ") ?string1)
& !newString !clean:?newString
)
& !newString !string1:?newString
& out$(str$("Control characters stripped:
" str$!newString))... |
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... | #AArch64_Assembly | AArch64 Assembly |
/* ARM assembly AARCH64 Raspberry PI 3B */
/* program concatStr64.s */
/*******************************************/
/* Constantes file */
/*******************************************/
/* for this file see task include a file in language AArch64 assembly*/
.include "../includeConstantesAR... |
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... | #ABAP | ABAP | DATA: s1 TYPE string,
s2 TYPE string.
s1 = 'Hello'.
CONCATENATE s1 ' literal' INTO s2 RESPECTING BLANKS.
WRITE: / s1.
WRITE: / s2.
|
http://rosettacode.org/wiki/Sum_multiples_of_3_and_5 | Sum multiples of 3 and 5 | Task
The objective is to write a function that finds the sum of all positive multiples of 3 or 5 below n.
Show output for n = 1000.
This is is the same as Project Euler problem 1.
Extra credit: do this efficiently for n = 1e20 or higher.
| #Fortran | Fortran |
INTEGER*8 FUNCTION SUMI(N) !Sums the integers 1 to N inclusive.
Calculates as per the young Gauss: N*(N + 1)/2 = 1 + 2 + 3 + ... + N.
INTEGER*8 N !The number. Possibly large.
IF (MOD(N,2).EQ.0) THEN !So, I'm worried about overflow with N*(N + 1)
SUMI = N/2*(N + 1) !But since N is even,... |
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
| #FreeBASIC | FreeBASIC | ' FB 1.05.0 Win64
Function SumDigits(number As Integer, nBase As Integer) As Integer
If number < 0 Then number = -number ' convert negative numbers to positive
If nBase < 2 Then nBase = 2 ' nBase can't be less than 2
Dim As Integer sum = 0
While number > 0
sum += number Mod nBase
number \= nBase
... |
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
| #Haskell | Haskell | versions :: [[Int] -> Int]
versions =
[ sum . fmap (^ 2) -- ver 1
, sum . ((^ 2) <$>) -- ver 2
, foldr ((+) . (^ 2)) 0 -- ver 3
]
main :: IO ()
main =
mapM_ print ((`fmap` [[3, 1, 4, 1, 5, 9], [1 .. 6], [], [1]]) <$> versions) |
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... | #BQN | BQN | ws ← @+⟨9, 10, 11, 12, 13, 32, 133, 160,
5760, 8192, 8193, 8194, 8195, 8196, 8197, 8198,
8199, 8200, 8201, 8202, 8232, 8233, 8239, 8287,
12288⟩
Lead ← (¬·∧`∊⟜ws)⊸/
Trail ← (¬·⌽·∧`·∊⟜ws⌽)⊸/
•Show Lead " fs df"
•Show Trail "fdsf asd "
•Show Lead∘Trail " white space " |
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... | #Bracmat | Bracmat | ( ( ltrim
= s
. @( !arg
: ?
( ( %@
: ~( " "
| \a
| \b
| \n
| \r
| \t
| \v
)
)
?
... |
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... | #Julia | Julia | using Primes, Formatting
function parseprimelist()
primelist = primes(2, 10000019)
strongs = Vector{Int64}()
weaks = Vector{Int64}()
balanceds = Vector{Int64}()
for (n, p) in enumerate(primelist)
if n == 1 || n == length(primelist)
continue
end
x = (primelist[n ... |
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... | #Kotlin | Kotlin | private const val MAX = 10000000 + 1000
private val primes = BooleanArray(MAX)
fun main() {
sieve()
println("First 36 strong primes:")
displayStrongPrimes(36)
for (n in intArrayOf(1000000, 10000000)) {
System.out.printf("Number of strong primes below %,d = %,d%n", n, strongPrimesBelow(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 |... | #AWK | AWK | BEGIN {
str = "abcdefghijklmnopqrstuvwxyz"
n = 12
m = 5
print substr(str, n, m)
print substr(str, n)
print substr(str, 1, length(str) - 1)
print substr(str, index(str, "q"), m)
print substr(str, index(str, "pq"), m)
} |
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 |... | #Axe | Axe | Lbl SUB1
0→{r₁+r₂+r₃}
r₁+r₂
Return
Lbl SUB2
r₁+r₂
Return
Lbl SUB3
0→{r₁+length(r₁)-1}
r₁
Return
Lbl SUB4
inData(r₂,r₁)-1→I
0→{r₁+I+r₃}
r₁+I
Return |
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.
| #Clojure | Clojure | (ns rosettacode.sudoku
(:use [clojure.pprint :only (cl-format)]))
(defn- compatible? [m x y n]
(let [n= #(= n (get-in m [%1 %2]))]
(or (n= y x)
(let [c (count m)]
(and (zero? (get-in m [y x]))
(not-any? #(or (n= y %) (n= % x)) (range c))
(let [zx (* c (quot x c)), zy (*... |
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... | #C.2B.2B | C++ |
#include <fstream>
#include <iostream>
#include <iterator>
#include <vector>
class subleq {
public:
void load_and_run( std::string file ) {
std::ifstream f( file.c_str(), std::ios_base::in );
std::istream_iterator<int> i_v, i_f( f );
std::copy( i_f, i_v, std::back_inserter( memory ) );
... |
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:
... | #jq | jq | # Emit a stream of consecutive primes.
# The stream is unbounded if . is null or infinite,
# otherwise it continues up to but excluding `.`.
def primes:
(if . == null then infinite else . end) as $n
| 2, (range(3; $n; 2) | select(is_prime));
# s is a stream
# $deltas is an array
# Output: a stream of arrays, each... |
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... | #COBOL | COBOL | identification division.
program-id. toptail.
data division.
working-storage section.
01 data-field.
05 value "[this is a test]".
procedure division.
sample-main.
display data-field
*> Using reference modification, which is (start-position:leng... |
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... | #jq | jq | # If $p is null, then call `subrand`,
# which sets .x as the PRN and which expects the the input to
# be the PRNG state, which is updated.
def subrandSeed($p):
def subrand:
if (.si == .sj) then subrandSeed(0) else . end
| .si |= (if . == 0 then 54 else . - 1 end)
| .sj |= (if . == 0 then 54 else . - 1... |
http://rosettacode.org/wiki/Substitution_cipher | Substitution cipher | Substitution Cipher Implementation - File Encryption/Decryption
Task
Encrypt a input/source file by replacing every upper/lower case alphabets of the source file with another predetermined upper/lower case alphabets or symbols and save it into another output/encrypted file and then again convert that output/encrypt... | #REXX | REXX | /*REXX program implements & demonstrates a substitution cipher for the records in a file*/
parse arg fid.1 fid.2 fid.3 fid.4 . /*obtain optional arguments from the CL*/
if fid.1=='' then fid.1= "CIPHER.IN" /*Not specified? Then use the default.*/
if fid.2=='' then fid.2= "CIPHER.OUT" ... |
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.
| #FALSE | FALSE | 1 2 3 4 5 {input "array"}
5 {length of input}
0s: {sum}
1p: {product}
[$0=~][1-\$s;+s:p;*p:]#%
"Sum: "s;."
Product: "p;. |
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.
| #Fantom | Fantom |
class Main
{
public static Void main ()
{
Int[] array := (1..20).toList
// you can use a loop
Int sum := 0
array.each |Int n| { sum += n }
echo ("Sum of array is : $sum")
Int product := 1
array.each |Int n| { product *= n }
echo ("Product of array is : $product")
// or us... |
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... | #Elena | Elena | import system'routines;
import extensions;
public program()
{
var sum := new Range(1, 1000).selectBy:(x => 1.0r / (x * x)).summarize(new Real());
console.printLine:sum
} |
http://rosettacode.org/wiki/Strip_comments_from_a_string | Strip comments from a string | Strip comments from a string
You are encouraged to solve this task according to the task description, using any language you may know.
The task is to remove text that follow any of a set of comment markers, (in these examples either a hash or a semicolon) from a string or input line.
Whitespace debacle: There is s... | #AWK | AWK | #!/usr/local/bin/awk -f
{
sub("[ \t]*[#;].*$","",$0);
print;
} |
http://rosettacode.org/wiki/Strip_comments_from_a_string | Strip comments from a string | Strip comments from a string
You are encouraged to solve this task according to the task description, using any language you may know.
The task is to remove text that follow any of a set of comment markers, (in these examples either a hash or a semicolon) from a string or input line.
Whitespace debacle: There is s... | #ANSI_BASIC | ANSI BASIC | 100 DECLARE EXTERNAL FUNCTION FNstripcomment$
110 LET marker$="#;"
120 PRINT """";FNstripcomment$("apples, pears # and bananas", marker$);""""
130 PRINT """";FNstripcomment$("apples, pears ; and bananas", marker$);""""
140 PRINT """";FNstripcomment$(" apples, pears ", marker$);""""
150 END
160 !
170 EXTERNAL FUNCTI... |
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... | #D | D | import std.algorithm, std.regex;
string[2] separateComments(in string txt,
in string cpat0, in string cpat1) {
int[2] plen; // to handle /*/
int i, j; // cursors
bool inside; // is inside comment?
// pre-compute regex here if desired
//auto r0 = regex(cpat0);
//aut... |
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, ... | #Perl | Perl | #!/usr/bin/perl
use warnings;
use strict;
use feature qw{ say };
my $string = '123456789';
my $length = length $string;
my @possible_ops = ("" , '+', '-');
{
my @ops;
sub Next {
return @ops = (0) x ($length) unless @ops;
my $i = 0;
while ($i < $length) {
if ($ops[$i]++ ... |
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... | #APL | APL | 'She was a soul stripper. She took my heart!' ~ 'aei' |
http://rosettacode.org/wiki/Strip_a_set_of_characters_from_a_string | Strip a set of characters from a string | Task
Create a function that strips a set of characters from a string.
The function should take two arguments:
a string to be stripped
a string containing the set of characters to be stripped
The returned string should contain the first string, stripped of any characters in the second argument:
print str... | #AppleScript | AppleScript | stripChar("She was a soul stripper. She took my heart!", "aei")
on stripChar(str, chrs)
tell AppleScript
set oldTIDs to text item delimiters
set text item delimiters to characters of chrs
set TIs to text items of str
set text item delimiters to ""
set str to TIs as string
... |
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 |... | #Bracmat | Bracmat | World!:?string
& str$("Hello " !string):?string
& out$!string |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.