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/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... | #11l | 11l | F remove_comments(line, sep)
V? p = line.find(sep)
I p != N
R line[0.<p].rtrim(‘ ’)
R line
print(remove_comments(‘apples ; pears # and bananas’, (‘;’, ‘#’)))
print(remove_comments(‘apples ; pears # and bananas’, ‘#’))
print(remove_comments(‘apples ; pears # and bananas’, ‘!’)) |
http://rosettacode.org/wiki/Strip_block_comments | Strip block comments | A block comment begins with a beginning delimiter and ends with a ending delimiter, including the delimiters. These delimiters are often multi-character sequences.
Task
Strip block comments from program text (of a programming language much like classic C).
Your demos should at least handle simple, non-ne... | #11l | 11l | F strip_comments(s, b_delim = ‘/*’, e_delim = ‘*/’)
V r = ‘’
V i = 0
L
V? p = s.find(b_delim, i)
I p == N
L.break
r ‘’= s[i .< p]
V? e = s.find(e_delim, p + b_delim.len)
assert(e != N)
i = e + e_delim.len
r ‘’= s[i..]
R r
V text = ‘
/**
* Some comments
... |
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, ... | #Julia | Julia | using Printf, IterTools, DataStructures
expr(p::String...)::String = @sprintf("%s1%s2%s3%s4%s5%s6%s7%s8%s9", p...)
function genexpr()::Vector{String}
op = ["+", "-", ""]
return collect(expr(p...) for (p) in Iterators.product(op, op, op, op, op, op, op, op, op) if p[1] != "+")
end
using DataStructures
func... |
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 ... | #8086_Assembly | 8086 Assembly | .model small
.stack 1024
.data
StringStrip db "abc",13,10,8,7,"def",90h
.code
start:
mov ax,@data
mov ds,ax
mov ax,@code
mov es,ax
mov ax,03h
int 10h ;clear screen
mov si,offset StringStrip
call PrintString_PartiallyStripped
call NewLine
mov si,offset StringStrip
call PrintSt... |
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.
| #Emacs_Lisp | Emacs Lisp | (defun sum-3-5 (n)
(let ((sum 0))
(dotimes (x n)
(when (or (zerop (% x 3)) (zerop (% x 5)))
(setq sum (+ sum x))))
sum)) |
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
| #Excel | Excel | digitSum
=LAMBDA(s,
FOLDROW(
LAMBDA(a,
LAMBDA(c,
a + digitValue(c)
)
)
)(0)(
CHARSROW(s)
)
)
digitValue
=LAMBDA(c,
LET(
ic, UNICODE(MID(c, 1, 1)),
IF(AND(47 < ic, 58 > ic),
ic - 48,
IF(AND(64 < ... |
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
| #Fortran | Fortran | real, dimension(1000) :: a = (/ (i, i=1, 1000) /)
real, pointer, dimension(:) :: p => a(2:1) ! pointer to zero-length array
real :: result, zresult
result = sum(a*a) ! Multiply array by itself to get squares
result = sum(a**2) ! Use exponentiation operator to get squares
zresult = sum(p*p) ! P is zer... |
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... | #Ada | Ada | with Ada.Text_IO; use Ada.Text_IO;
with Ada.Strings; use Ada.Strings;
with Ada.Strings.Fixed; use Ada.Strings.Fixed;
procedure StripDemo is
str : String := " Jabberwocky ";
begin
Put_Line ("'" & Trim (str, Left) & "'");
Put_Line ("'" & Trim (str, Right) & "'");
Put_Line ("'" & Trim (str, Both) & "'"... |
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... | #ALGOL_68 | ALGOL 68 | # returns "text" with leading non-printing characters removed #
PROC trim leading whitespace = ( STRING text )STRING:
BEGIN
INT pos := LWB text;
WHILE
IF pos > UPB text
THEN
FALSE
ELSE
text[ pos ] <= " "
FI
DO
pos +:= 1
OD;
text[ ... |
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... | #C.2B.2B | C++ | #include <algorithm>
#include <iostream>
#include <iterator>
#include <locale>
#include <vector>
#include "prime_sieve.hpp"
const int limit1 = 1000000;
const int limit2 = 10000000;
class prime_info {
public:
explicit prime_info(int max) : max_print(max) {}
void add_prime(int prime);
void print(std::ostr... |
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 |... | #Aime | Aime | text s;
data b, d;
s = "The quick brown fox jumps over the lazy dog.";
o_text(cut(s, 4, 15));
o_newline();
o_text(cut(s, 4, length(s)));
o_newline();
o_text(delete(s, -1));
o_newline();
o_text(cut(s, index(s, 'q'), 5));
o_newline();
b_cast(b, s);
b_cast(d, "brown");
o_text(cut(s, b_find(b, d), 15));
o_newline(); |
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 |... | #ALGOL_68 | ALGOL 68 | main: (
STRING s = "abcdefgh";
INT n = 2, m = 3;
CHAR char = "d";
STRING chars = "cd";
printf(($gl$, s[n:n+m-1]));
printf(($gl$, s[n:]));
printf(($gl$, s[:UPB s-1]));
INT pos;
char in string("d", pos, s);
printf(($gl$, s[pos:pos+m-1]));
string in string("de", pos, s);
printf(($gl$, s[pos:... |
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.
| #BCPL | BCPL | // This can be run using Cintcode BCPL freely available from www.cl.cam.ac.uk/users/mr10.
// Implemented by Martin Richards.
// If you have cintcode BCPL installed on a Linux system you can compile and run this program
// execute the following sequence of commands.
// cd $BCPLROOT
// cintsys
// c bc sudoku
// sudok... |
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... | #ARM_Assembly | ARM Assembly | @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
@@@ ARM SUBLEQ for Linux @@@
@@@ Word size is 32 bits. The program is @@@
@@@ given 8 MB (2 Mwords) to run in. @@@
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
.text
.global _start
@@@ Linux syscalls
.equ exit, 1
.equ read, 3
.equ write, 4
.equ open, 5
... |
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... | #AWK | AWK |
# syntax: GAWK -f SUBLEQ.AWK SUBLEQ.TXT
# converted from Java
BEGIN {
instruction_pointer = 0
}
{ printf("%s\n",$0)
for (i=1; i<=NF; i++) {
if ($i == "*") {
ncomments++
break
}
mem[instruction_pointer++] = $i
}
}
END {
if (instruction_pointer == 0) {
print("er... |
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:
... | #Factor | Factor | USING: formatting fry grouping kernel math math.primes
math.statistics sequences ;
IN: rosetta-code.successive-prime-differences
: seq-diff ( seq diffs -- seq' quot )
dup [ length 1 + <clumps> ] dip '[ differences _ sequence= ]
; inline
: show ( seq diffs -- )
[ "...for differences %u:\n" printf ] keep ... |
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... | #BQN | BQN | str ← "substring"
"substring"
1↓str
"ubstring"
¯1↓str
"substrin"
1↓¯1↓str
"ubstrin" |
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... | #BBC_BASIC | BBC BASIC | s$ = "Rosetta Code"
PRINT MID$(s$, 2)
PRINT LEFT$(s$)
PRINT LEFT$(MID$(s$, 2)) |
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... | #F.23 | F# | [<EntryPoint>]
let main argv =
let m = 1000000000
let init = Seq.unfold (fun ((i, s2, s1)) -> Some((s2,i), (i+1, s1, (m+s2-s1)%m))) (0, 292929, 1)
|> Seq.take 55
|> Seq.sortBy (fun (_,i) -> (34*i+54)%55)
|> Seq.map fst
let rec r = seq {
yield! init
yield! ... |
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... | #Phixmonti | Phixmonti | include ..\Utilitys.pmt
" ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"
" VsciBjedgrzyHalvXZKtUPumGfIwJxqOCFRApnDhQWobLkESYMTN"
"A simple example"
def Encode
>ps
tps not if >ps swap ps> endif
len for
>ps
tps get swap >ps
rot swap find
rot swap get
ps> swap... |
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... | #PHP | PHP | <?php
$alphabet = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
$key = 'cPYJpjsBlaOEwRbVZIhQnHDWxMXiCtUToLkFrzdAGymKvgNufeSq';
// Encode input.txt, and save result in output.txt
file_put_contents('output.txt', strtr(file_get_contents('input.txt'), $alphabet, $key));
$source = file_get_contents('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.
| #Eiffel | Eiffel |
class
APPLICATION
create
make
feature {NONE}
make
local
test: ARRAY [INTEGER]
do
create test.make_empty
test := <<5, 1, 9, 7>>
io.put_string ("Sum: " + sum (test).out)
io.new_line
io.put_string ("Product: " + product (test).out)
end
sum (ar: ARRAY [INTEGER]): INTEGER
-- Sum of t... |
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... | #DWScript | DWScript |
var s : Float;
for var i := 1 to 1000 do
s += 1 / Sqr(i);
PrintLn(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... | #68000_Assembly | 68000 Assembly | StripComments:
;prints a string but stops at the comment character
;INPUT: D7 = comment character(s) of choice
;A0 = source address of string
;up to four can be used, each takes up a different 8 bits of the register
;to omit an argument, leave its bits as zero.
.loop:
MOVE.B (A0)+,D0
CMP.B #0,D0 ;check ... |
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... | #Ada | Ada | with Ada.Strings.Fixed;
with Ada.Strings.Unbounded;
with Ada.Text_IO;
with Ada.Command_Line;
procedure Strip is
use Ada.Strings.Unbounded;
procedure Print_Usage is
begin
Ada.Text_IO.Put_Line ("Usage:");
Ada.Text_IO.New_Line;
Ada.Text_IO.Put_Line (" strip <file> [<opening> [<closing>]]");
... |
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, ... | #Kotlin | Kotlin | // version 1.1.51
class Expression {
private enum class Op { ADD, SUB, JOIN }
private val code = Array<Op>(NUMBER_OF_DIGITS) { Op.ADD }
companion object {
private const val NUMBER_OF_DIGITS = 9
private const val THREE_POW_4 = 3 * 3 * 3 * 3
private const val FMT = "%9d"
... |
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... | #11l | 11l | F stripchars(s, chars)
R s.filter(c -> c !C @chars).join(‘’)
print(stripchars(‘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 |... | #11l | 11l | V s = ‘12345678’
s = ‘0’s
print(s) |
http://rosettacode.org/wiki/Strip_control_codes_and_extended_characters_from_a_string | Strip control codes and extended characters from a string | Task
Strip control codes and extended characters from a string.
The solution should demonstrate how to achieve each of the following results:
a string with control codes stripped (but extended characters not stripped)
a string with control codes and extended characters stripped
In ASCII, the control codes ... | #Action.21 | Action! | BYTE FUNC IsAscii(CHAR c)
IF c<32 OR c>124 OR c=96 OR c=123 THEN
RETURN (0)
FI
RETURN (1)
PROC Strip(CHAR ARRAY src,dst)
CHAR c
BYTE i
dst(0)=0
FOR i=1 TO src(0)
DO
c=src(i)
IF IsAscii(c) THEN
dst(0)==+1
dst(dst(0))=c
FI
OD
RETURN
PROC Main()
CHAR ARRAY
src(20)=[1... |
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 ... | #Ada | Ada | with Ada.Text_IO;
procedure Strip_ASCII is
Full: String := 'a' & Character'Val(11) & 'b' & Character'Val(166) &
'c' & Character'Val(127) & Character'Val(203) &
Character'Val(202) & "de";
-- 5 ordinary characters ('a' .. 'e')
-- 2 control characters (11, 127); note that... |
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.
| #Erlang | Erlang | sum_3_5(X) when is_number(X) -> sum_3_5(erlang:round(X)-1, 0).
sum_3_5(X, Total) when X < 3 -> Total;
sum_3_5(X, Total) when X rem 3 =:= 0 orelse X rem 5 =:= 0 ->
sum_3_5(X-1, Total+X);
sum_3_5(X, Total) ->
sum_3_5(X-1, Total).
io:format("~B~n", [sum_3_5(1000)]). |
http://rosettacode.org/wiki/Sum_digits_of_an_integer | Sum digits of an integer | Task
Take a Natural Number in a given base and return the sum of its digits:
110 sums to 1
123410 sums to 10
fe16 sums to 29
f0e16 sums to 29
| #Ezhil | Ezhil |
# இது ஒரு எழில் தமிழ் நிரலாக்க மொழி உதாரணம்
# sum of digits of a number
# எண்ணிக்கையிலான இலக்கங்களின் தொகை
நிரல்பாகம் எண்_கூட்டல்( எண் )
தொகை = 0
@( எண் > 0 ) வரை
d = எண்%10;
பதிப்பி "digit = ",d
எண் = (எண்-d)/10;
தொகை = தொகை + d
முடி
பின்கொடு தொகை
முடி
பதிப்பி எண்_கூட்டல்( 1289... |
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
| #FreeBASIC | FreeBASIC | ' FB 1.05.0 Win64
Function SumSquares(a() As Double) As Double
Dim As Integer length = UBound(a) - LBound(a) + 1
If length = 0 Then Return 0.0
Dim As Double sum = 0.0
For i As Integer = LBound(a) To UBound(a)
sum += a(i) * a(i)
Next
Return sum
End Function
Dim a(5) As Double = {1.0, 2.0, 3.0, -1.0, ... |
http://rosettacode.org/wiki/Strip_whitespace_from_a_string/Top_and_tail | Strip whitespace from a string/Top and tail | Task
Demonstrate how to strip leading and trailing whitespace from a string.
The solution should demonstrate how to achieve the following three results:
String with leading whitespace removed
String with trailing whitespace removed
String with both leading and trailing whitespace removed
For the purposes of thi... | #AppleScript | AppleScript | use framework "Foundation" -- "OS X" Yosemite onwards, for NSRegularExpression
-- STRIP WHITESPACE ----------------------------------------------------------
-- isSpace :: Char -> Bool
on isSpace(c)
((length of c) = 1) and regexTest("\\s", c)
end isSpace
-- stripStart :: Text -> Text
on stripStart(s)
drop... |
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... | #D | D | import std.algorithm;
import std.array;
import std.range;
import std.stdio;
immutable PRIMES = [
2, 3, 5, 7,
11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97,
101, 103, 107, 109, 113, 127, 131, 137, 139, 149, 151, 157, 163, 167, 173, 179, 181, 191, 193, 197, 199, 211, 223... |
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 |... | #Apex | Apex | String x = 'testing123';
//Test1: testing123
System.debug('Test1: ' + x.substring(0,x.length()));
//Test2: esting123
System.debug('Test2: ' + x.substring(1,x.length()));
//Test3: testing123
System.debug('Test3: ' + x.substring(0));
//Test4: 3
System.debug('Test4: ' + x.substring(x.length()-1));
//Test5:
System.debug('... |
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.
| #Befunge | Befunge | 99*>1-:0>:#$"0"\# #~`#$_"0"-\::9%:9+00p3/\9/:99++10p3vv%2g\g01<
2%v|:p+9/9\%9:\p\g02\1p\g01\1:p\g00\1:+8:\p02+*93+*3/<>\20g\g#:
v<+>:0\`>v >\::9%:9+00p3/\9/:99++10p3/3*+39*+20p\:8+::00g\g2%\^
v^+^pppp$_:|v<::<_>1-::9%\9/9+g.::9%!\3%+>>#v_>" "v..v,<<<+55<<
03!$v9:_>1v$>9%\v^|:<_v#<%<9<:<<_v#+%*93\!::<,,"|"<\/>:#^_>>>v^
... |
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... | #BASIC | BASIC | 10 DEFINT A-Z: DIM M(8192)
20 INPUT "Filename";F$
30 OPEN "I",1,F$
40 GOTO 70
50 INPUT #1,M(I)
60 I=I+1
70 IF EOF(1) THEN CLOSE(1) ELSE GOTO 50
80 I=0
90 A=M(I): B=M(I+1): C=M(I+2): I=I+3
100 IF A=-1 GOTO 150 ELSE IF B=-1 GOTO 190
120 M(B) = M(B) - M(A)
130 IF M(B)<=0 THEN I=C
140 IF I>=0 GOTO 90 ELSE END
150 A$ = INPU... |
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:
... | #FreeBASIC | FreeBASIC | #include "isprime.bas"
function nextprime( n as uinteger ) as uinteger
'finds the next prime after n
if n = 0 then return 2
if n < 3 then return n + 1
dim as integer q = n + 2
while not isprime(q)
q+=2
wend
return q
end function
function spd( byval n as integer, d() as integer ) ... |
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... | #Bracmat | Bracmat | (substringUTF-8=
@( Δημοτική
: (%?a&utf$!a) ?"String with first character removed"
)
& @( Δημοτική
: ?"String with last character removed" (?z&utf$!z)
)
& @( Δημοτική
: (%?a&utf$!a)
?"String with both the first and last characters removed"
(?z&utf$!z)
)
& out
$ ("String with firs... |
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... | #Fortran | Fortran | module subgenerator
implicit none
integer, parameter :: modulus = 1000000000
integer :: s(0:54), r(0:54)
contains
subroutine initgen(seed)
integer :: seed
integer :: n, rnum
s(0) = seed
s(1) = 1
do n = 2, 54
s(n) = mod(s(n-2) - s(n-1), modulus)
if (s(n) < 0) s(n) = s(n) + modulus
en... |
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... | #Picat | Picat | main =>
S = "The quick brown fox jumped over the lazy dog",
cypher(S,E), % encrypt
println(E),
cypher(D, E), % decrypt
println(D),
S == D,
println(ok).
cypher(O, S) :-
nonvar(O),
var(S),
sub_chars(O,S).
cypher(O, S) :-
nonvar(S),
var(O),
sub_chars(O,S).
base("ABCDEFGHIJKLMNOPQRSTUVWXY... |
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... | #PicoLisp | PicoLisp | (setq *A (chop "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"))
(setq *K (chop "VsciBjedgrzyHalvXZKtUPumGfIwJxqOCFRApnDhQWobLkESYMTN"))
(de cipher (Str D)
(let (K *K A *A)
(and D (xchg 'A 'K))
(pack
(mapcar
'((N)
(or
(pick
... |
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... | #Pike | Pike | string alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
string key = "VsciBjedgrzyHalvXZKtUPumGfIwJxqOCFRApnDhQWobLkESYMTN";
mapping key_mapping = mkmapping(alphabet/1, key/1);
object c = Crypto.Substitution()->set_key(key_mapping);
string msg = "The quick brown fox jumped over the lazy dogs";
... |
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.
| #Elena | Elena | import system'routines;
import extensions;
public program()
{
var list := new int[]{1, 2, 3, 4, 5 };
var sum := list.summarize(new Integer());
var product := list.accumulate(new Integer(1), (var,val => var * val));
} |
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.
| #Elixir | Elixir | iex(26)> Enum.reduce([1,2,3,4,5], 0, fn x,acc -> x+acc end)
15
iex(27)> Enum.reduce([1,2,3,4,5], 1, fn x,acc -> x*acc end)
120
iex(28)> Enum.reduce([1,2,3,4,5], fn x,acc -> x+acc end)
15
iex(29)> Enum.reduce([1,2,3,4,5], fn x,acc -> x*acc end)
120
iex(30)> Enum.reduce([], 0, fn x,acc -> x+acc end)
0
iex(31)> Enum.reduc... |
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... | #Dyalect | Dyalect | func Integer.SumSeries() {
var ret = 0
for i in 1..this {
ret += 1 / pow(Float(i), 2)
}
ret
}
var x = 1000
print(x.SumSeries()) |
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... | #Action.21 | Action! | PROC Strip(CHAR ARRAY text,chars,result)
BYTE i,j,pos,found
pos=text(0)
FOR i=1 TO text(0)
DO
found=0
FOR j=1 TO chars(0)
DO
IF text(i)=chars(j) THEN
found=1 EXIT
FI
OD
IF found THEN
pos=i-1 EXIT
FI
OD
WHILE pos>0 AND text(pos)='
DO
pos==-1
OD
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... | #Ada | Ada | with Ada.Text_IO;
procedure Program is
Comment_Characters : String := "#;";
begin
loop
declare
Line : String := Ada.Text_IO.Get_Line;
begin
exit when Line'Length = 0;
Outer_Loop : for I in Line'Range loop
for J in Comment_Characters'Range loop
if Comment_Characters(J) = Line(I) then... |
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... | #ALGOL_W | ALGOL W | begin
% strips block comments from a source %
% the source is read from standard input and the result written to %
% standard output, The comment start text is in cStart and the ending %
% is in cEnd. ... |
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... | #AutoHotkey | AutoHotkey | code =
(
/**
* Some comments
* longer comments here that we can parse.
*
* Rahoo
*/
function subroutine() {
a = /* inline comment */ b + c ;
}
/*/ <-- tricky comments */
/**
* Another comment.
*/
function something() {
}
)
;Open-Close Comment delimiters
openC:="/*"
c... |
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, ... | #Lua | Lua | local expressionsLength = 0
function compareExpressionBySum(a, b)
return a.sum - b.sum
end
local countSumsLength = 0
function compareCountSumsByCount(a, b)
return a.counts - b.counts
end
function evaluate(code)
local value = 0
local number = 0
local power = 1
for k=9,1,-1 do
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... | #360_Assembly | 360 Assembly | * Strip a set of characters from a string 07/07/2016
STRIPCH CSECT
USING STRIPCH,R13 base register
B 72(R15) skip savearea
DC 17F'0' savearea
STM R14,R12,12(R13) prolog
ST R13,4(R15) " <-
ST R15,... |
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... | #8080_Assembly | 8080 Assembly | org 100h
jmp demo
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;; Strip a set of chracters from a string, in place.
;;; Input:
;;; DE = $-terminated string to be stripped
;;; HL = $-terminated string containing characters to strip
stripchars: push h ; Store characters to strip on ... |
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 |... | #360_Assembly | 360 Assembly | * String prepend - 14/04/2020
PREPEND CSECT
USING PREPEND,13 base register
B 72(15) skip savearea
DC 17F'0' savearea
SAVE (14,12) save previous context
ST 13,4(15) link backward
ST 15,8... |
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 |... | #AArch64_Assembly | AArch64 Assembly |
/* ARM assembly AARCH64 Raspberry PI 3B */
/* program appendstr64.s */
/*******************************************/
/* Constantes file */
/*******************************************/
/* for this file see task include a file in language AArch64 assembly*/
.include "../includeConstantesAR... |
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 |... | #Action.21 | Action! | PROC Append(CHAR ARRAY text,suffix)
BYTE POINTER srcPtr,dstPtr
BYTE len
len=suffix(0)
IF text(0)+len>255 THEN
len=255-text(0)
FI
IF len THEN
srcPtr=suffix+1
dstPtr=text+text(0)+1
MoveBlock(dstPtr,srcPtr,len)
text(0)==+suffix(0)
FI
RETURN
PROC Prepend(CHAR ARRAY text,prefix)
CHAR ... |
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 ... | #ALGOL_68 | ALGOL 68 | # remove control characters and optionally extended characters from the string text #
# assums ASCII is the character set #
PROC strip characters = ( STRING text, BOOL strip extended )STRING:
BEGIN
# we build the result in a []CHAR and convert back to a st... |
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.
| #F.23 | F# |
let sum35 n = Seq.init n (id) |> Seq.reduce (fun sum i -> if i % 3 = 0 || i % 5 = 0 then sum + i else sum)
printfn "%d" (sum35 1000)
printfn "----------"
let sumUpTo (n : bigint) = n * (n + 1I) / 2I
let sumMultsBelow k n = k * (sumUpTo ((n-1I)/k))
let sum35fast n = (sumMultsBelow 3I n) + (sumMultsBelow 5I n) ... |
http://rosettacode.org/wiki/Sum_digits_of_an_integer | Sum digits of an integer | Task
Take a Natural Number in a given base and return the sum of its digits:
110 sums to 1
123410 sums to 10
fe16 sums to 29
f0e16 sums to 29
| #F.23 | F# | open System
let digsum b n =
let rec loop acc = function
| n when n > 0 ->
let m, r = Math.DivRem(n, b)
loop (acc + r) m
| _ -> acc
loop 0 n
[<EntryPoint>]
let main argv =
let rec show = function
| n :: b :: r -> printf " %d" (digsum b n); show r
... |
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
| #Frink | Frink |
f = {|x| x^2} // Anonymous function which squares its argument
a = [1,2,3,5,7]
println[sum[map[f,a], 0]]
|
http://rosettacode.org/wiki/Sum_of_squares | Sum of squares | Task
Write a program to find the sum of squares of a numeric vector.
The program should work on a zero-length vector (with an answer of 0).
Related task
Mean
| #F.C5.8Drmul.C3.A6 | Fōrmulæ | # Just multiplying a vector by itself yields the sum of squares (it's an inner product)
# It's necessary to check for the empty vector though
SumSq := function(v)
if Size(v) = 0 then
return 0;
else
return v*v;
fi;
end; |
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... | #Arturo | Arturo | str: " Hello World "
print [pad "strip all:" 15 ">" strip str "<"]
print [pad "strip leading:" 15 ">" strip.start str "<"]
print [pad "strip trailing:" 15 ">" strip.end str "<"] |
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... | #AutoHotkey | AutoHotkey | string := " abc "
MsgBox % clipboard := "<" LTrim(string) ">`n<" RTrim(string) ">`n<" . Trim(string) ">" |
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... | #Factor | Factor | USING: formatting grouping kernel math math.primes sequences
tools.memory.private ;
IN: rosetta-code.strong-primes
: fn ( p-1 p p+1 -- p sum ) rot + 2 / ;
: strong? ( p-1 p p+1 -- ? ) fn > ;
: weak? ( p-1 p p+1 -- ? ) fn < ;
: swprimes ( seq quot -- seq )
[ 3 <clumps> ] dip [ first3 ] prepose filter [ second ] ... |
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... | #FreeBASIC | FreeBASIC |
#include "isprime.bas"
function nextprime( n as uinteger ) as uinteger
'finds the next prime after n, excluding n if it happens to be prime itself
if n = 0 then return 2
if n < 3 then return n + 1
dim as integer q = n + 2
while not isprime(q)
q+=2
wend
return q
end function
fun... |
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 |... | #AppleScript | AppleScript | -- SUBSTRINGS -----------------------------------------------------------------
-- take :: Int -> Text -> Text
on take(n, s)
text 1 thru n of s
end take
-- drop :: Int -> Text -> Text
on drop(n, s)
text (n + 1) thru -1 of s
end drop
-- breakOn :: Text -> Text -> (Text, Text)
on breakOn(strPattern, s)
... |
http://rosettacode.org/wiki/Sudoku | Sudoku | Task
Solve a partially filled-in normal 9x9 Sudoku grid and display the result in a human-readable format.
references
Algorithmics of Sudoku may help implement this.
Python Sudoku Solver Computerphile video.
| #Bracmat | Bracmat | {sudokuSolver.bra
Solves any 9x9 sudoku, using backtracking.
Not a simple brute force algorithm!}
sudokuSolver=
( sudoku
= ( new
= create
. ( create
= a
. !arg:%(<3:?a) ?arg
& ( !a
. !arg:
... |
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... | #BBC_BASIC | BBC BASIC | REM >subleq
DIM memory%(255)
counter% = 0
INPUT "SUBLEQ> " program$
WHILE INSTR(program$, " ")
memory%(counter%) = VAL(LEFT$(program$, INSTR(program$, " ") - 1))
program$ = MID$(program$, INSTR(program$, " ") + 1)
counter% += 1
ENDWHILE
memory%(counter%) = VAL(program$)
counter% = 0
REPEAT
a% = memory%(... |
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... | #BCPL | BCPL | get "libhdr"
// Read a string
let reads(v) be
$( let ch = ?
v%0 := 0
ch := rdch()
until ch = '*N' do
$( v%0 := v%0 + 1
v%(v%0) := ch
ch := rdch()
$)
$)
// Try to read a number, fail on EOF
// (Alas, the included READN just returns 0 and that's a valid number)
let readnum(n) = v... |
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:
... | #Go | Go | package main
import "fmt"
func sieve(limit int) []int {
primes := []int{2}
c := make([]bool, limit+1) // composite = true
// no need to process even numbers > 2
p := 3
for {
p2 := p * p
if p2 > limit {
break
}
for i := p2; i <= limit; i += 2 * p {
... |
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... | #Burlesque | Burlesque |
blsq ) "RosettaCode"[-
"osettaCode"
blsq ) "RosettaCode"-]
'R
blsq ) "RosettaCode"~]
"RosettaCod"
blsq ) "RosettaCode"[~
'e
blsq ) "RosettaCode"~-
"osettaCod"
|
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 | C | #include <string.h>
#include <stdlib.h>
#include <stdio.h>
int main( int argc, char ** argv ){
const char * str_a = "knight";
const char * str_b = "socks";
const char * str_c = "brooms";
char * new_a = malloc( strlen( str_a ) - 1 );
char * new_b = malloc( strlen( str_b ) - 1 );
char * new_c = malloc( st... |
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... | #Go | Go | package main
import (
"fmt"
"os"
)
// A fairly close port of the Bentley code, but parameterized to better
// conform to the algorithm description in the task, which didn't assume
// constants for i, j, m, and seed. also parameterized here are k,
// the reordering factor, and s, the number of intial number... |
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... | #Prolog | Prolog | cypher(O, S) :-
nonvar(O),
var(S),
atom_chars(O,Oc),
sub_chars(Oc,Sc),
atom_chars(S,Sc).
cypher(O, S) :-
nonvar(S),
var(O),
atom_chars(S,Sc),
sub_chars(Oc,Sc),
atom_chars(O,Oc).
% mapping based on ADA implementation but have added space character
base(['A','B','C','D','E','F','G','H','I','J','K','L','M','... |
http://rosettacode.org/wiki/Sum_and_product_of_an_array | Sum and product of an array | Task
Compute the sum and product of an array of integers.
| #Emacs_Lisp | Emacs Lisp | (let ((array [1 2 3 4 5]))
(apply #'+ (append array nil))
(apply #'* (append array nil))) |
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... | #E | E | pragma.enable("accumulator")
accum 0 for x in 1..1000 { _ + 1 / x ** 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... | #Aime | Aime | strip_comments(data b)
{
b.size(b.look(0, ";#")).bf_drop(" \t").bb_drop(" \t");
}
main(void)
{
for (, text n in list("apples, pears # and bananas", "apples, pears ; and bananas")) {
o_(strip_comments(n), "\n");
}
0;
} |
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_68 | ALGOL 68 | #!/usr/local/bin/a68g --script #
PROC trim comment = (STRING line, CHAR marker)STRING:(
INT index := UPB line+1;
char in string(marker, index, line);
FOR i FROM index-1 BY -1 TO LWB line
WHILE line[i]=" " DO index := i OD;
line[:index-1]
);
CHAR q = """";
print((
q, trim comment("apples, pears # and b... |
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... | #AWK | AWK |
# syntax: GAWK -f STRIP_BLOCK_COMMENTS.AWK filename
# source: https://www.gnu.org/software/gawk/manual/gawk.html#Plain-Getline
# Remove text between /* and */, inclusive
{ while ((start = index($0,"/*")) != 0) {
out = substr($0,1,start-1) # leading part of the string
rest = substr($0,start+2) # ... */ .... |
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... | #BBC_BASIC | BBC BASIC | infile$ = "C:\sample.c"
outfile$ = "C:\stripped.c"
PROCstripblockcomments(infile$, outfile$, "/*", "*/")
END
DEF PROCstripblockcomments(infile$, outfile$, start$, finish$)
LOCAL infile%, outfile%, comment%, test%, A$
infile% = OPENIN(infile$)
IF infile%=0 ERROR 100,... |
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, ... | #Mathematica.2FWolfram_Language | Mathematica/Wolfram Language | operations = DeleteCases[Tuples[{"+", "-", ""}, 9], {x_, y__} /; x == "+"];
sums = Map[StringJoin[Riffle[#, CharacterRange["1", "9"]]] &, operations]; |
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... | #8086_Assembly | 8086 Assembly | bits 16
cpu 8086
section .text
org 100h
jmp demo
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;; Strip a set of characters from a string, in place.
;;; Input:
;;; DS:DI = $-terminated string to be stripped.
;;; DS:SI = $-terminated string containing chars to strip
stripchar... |
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 |... | #Ada | Ada | with Ada.Text_IO; with Ada.Strings.Unbounded; use Ada.Strings.Unbounded;
procedure Prepend_String is
S: Unbounded_String := To_Unbounded_String("World!");
begin
S := "Hello " & S;-- this is the operation to prepend "Hello " to S.
Ada.Text_IO.Put_Line(To_String(S));
end Prepend_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 |... | #ALGOL_68 | ALGOL 68 | #!/usr/bin/a68g --script #
# -*- coding: utf-8 -*- #
STRING str := "12345678";
"0" +=: str;
print(str) |
http://rosettacode.org/wiki/Strip_control_codes_and_extended_characters_from_a_string | Strip control codes and extended characters from a string | Task
Strip control codes and extended characters from a string.
The solution should demonstrate how to achieve each of the following results:
a string with control codes stripped (but extended characters not stripped)
a string with control codes and extended characters stripped
In ASCII, the control codes ... | #Arturo | Arturo | str: {string of ☺☻♥♦⌂, may include control characters and other ♫☼§►↔◄░▒▓█┌┴┐±÷²¬└┬┘ilk.}
print "with extended characters"
print join select split str 'x ->
not? in? to :integer to :char x (0..31)++127
print "without extended characters"
print join select split str 'x ->
and? ascii? x
not? in? t... |
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 ... | #AutoHotkey | AutoHotkey | Stripped(x){
Loop Parse, x
if Asc(A_LoopField) > 31 and Asc(A_LoopField) < 128
r .= A_LoopField
return r
}
MsgBox % stripped("`ba" Chr(00) "b`n`rc`fd" Chr(0xc3)) |
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.
| #Factor | Factor | USING: kernel math prettyprint ;
: sum-multiples ( m n upto -- sum )
>integer 1 - [ 2dup * ] dip
[ 2dup swap [ mod - + ] [ /i * 2/ ] 2bi ] curry tri@
[ + ] [ - ] bi* ;
3 5 1000 sum-multiples .
3 5 1e20 sum-multiples . |
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
| #Factor | Factor | : sum-digits ( base n -- sum ) 0 swap [ dup zero? ] [ pick /mod swapd + swap ] until drop nip ;
{ 10 10 16 16 } { 1 1234 0xfe 0xf0e } [ sum-digits ] 2each |
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
| #GAP | GAP | # Just multiplying a vector by itself yields the sum of squares (it's an inner product)
# It's necessary to check for the empty vector though
SumSq := function(v)
if Size(v) = 0 then
return 0;
else
return v*v;
fi;
end; |
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
| #GEORGE | GEORGE | read (n) print ;
0
1, n rep (i)
read print dup mult +
]
print |
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... | #AWK | AWK | function trimleft(str ,c, out, arr) {
c = split(str, arr, "")
for ( i = match(str, /[[:graph:]]/); i <= c; i++)
out = out arr[i]
return out
}
function reverse(str ,n, tmp, j, out) {
n = split(str, tmp, "")
for (j = n; j > 0; j--)
out = out tmp[j]
return out
}
func... |
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... | #Frink | Frink |
strongPrimes[end=undef] := select[primes[3,end], {|p| p > (previousPrime[p] + nextPrime[p])/2 }]
weakPrimes[end=undef] := select[primes[3,end], {|p| p < (previousPrime[p] + nextPrime[p])/2 }]
println["First 36 strong primes: " + first[strongPrimes[], 36]]
println["Strong primes below 1,000,000: " + length[str... |
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... | #Go | Go | package main
import "fmt"
func sieve(limit int) []bool {
limit++
// True denotes composite, false denotes prime.
// Don't bother marking even numbers >= 4 as composite.
c := make([]bool, limit)
c[0] = true
c[1] = true
p := 3 // start from 3
for {
p2 := p * p
if p2 >... |
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 |... | #ARM_Assembly | ARM Assembly |
/* ARM assembly Raspberry PI */
/* program substring.s */
/* Constantes */
.equ STDOUT, 1 @ Linux output console
.equ EXIT, 1 @ Linux syscall
.equ WRITE, 4 @ Linux syscall
.equ BUFFERSIZE, 100
/* Initialized data ... |
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 | C | #include <stdio.h>
void show(int *x)
{
int i, j;
for (i = 0; i < 9; i++) {
if (!(i % 3)) putchar('\n');
for (j = 0; j < 9; j++)
printf(j % 3 ? "%2d" : "%3d", *x++);
putchar('\n');
}
}
int trycell(int *x, int pos)
{
int row = pos / 9;
int col = pos % 9;
int i, j, used = 0;
if (pos == 81) return 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... | #Befunge | Befunge | 01-00p00g:0`*2/00p010p0>$~>:4v4:-1g02p+5/"P"\%"P":p01+1:g01+g00*p02+1_v#!`"/":<
\0_v#-"-":\1_v#!`\*84:_^#- *8< >\#%"P"/#:5#<+g00g-\1+:"P"%\"P"v>5+#\*#<+"0"-~>^
<~0>#<$#-0#\<>$0>:3+\::"P"%\"P"/5+g00g-:1+#^_$:~>00gvv0gp03:+5/"P"\p02:%"P":< ^
>>>>>> , >>>>>> ^$p+5/"P"\%"P":-g00g+5/"P"\%"P":+1\+<>0g-\-:0v>5+g00g-: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... | #BQN | BQN |
# Helpers
_while_ ← {𝔽⍟𝔾∘𝔽_𝕣_𝔾∘𝔽⍟𝔾𝕩}
ToNum ← {neg ← '-'=⊑𝕩 ⋄ (¯1⋆neg)×10⊸×⊸+˜´·⌽-⟜'0'neg↓𝕩}
Subleq ← {
𝕊 memory:
{
𝕊 ip‿mem:
{
¯1‿b‿·: ⟨ip+3, (@-˜•term.CharB@)⌾(b⊸⊑) mem⟩;
a‿¯1‿·: •Out @+a⊑mem, ⟨ip+3, mem⟩;
a‿b‿c : d ← b-○(⊑⟜mem)a, ⟨(0<d)⊑⟨c, ip+3⟩, d⌾(b⊸⊑) mem⟩
} mem⊏˜... |
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:
... | #Haskell | Haskell | {-# LANGUAGE NumericUnderscores #-}
import Data.Numbers.Primes (primes)
type Result = [(String, [Int])]
oneMillionPrimes :: Integral p => [p]
oneMillionPrimes = takeWhile (<1_000_000) primes
getGroups :: [Int] -> Result
getGroups [] = []
getGroups ps@(n:x:y:z:xs)
| x-n == 6 && y-x == 4 && z-y == 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... | #C.23 | C# |
using System;
class Program
{
static void Main(string[] args)
{
string testString = "test";
Console.WriteLine(testString.Substring(1));
Console.WriteLine(testString.Substring(0, testString.Length - 1));
Console.WriteLine(testString.Substring(1, testString.Length - 2));
}
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.