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... | #C.23 | C# |
public class SubtractiveGenerator {
public static int MAX = 1000000000;
private int[] state;
private int pos;
private int mod(int n) {
return ((n % MAX) + MAX) % MAX;
}
public SubtractiveGenerator(int seed) {
state = new int[55];
int[] temp = new int[55];
... |
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... | #J | J | keysubst=: [`(a.i.])`(a."_)}
key=: 'Taehist' keysubst '!@#$%^&'
enc=: a. {~ key i. ]
dec=: key {~ a. i. ]
enc 'This is a test.'
!$%^ %^ @ &#^&.
dec '!$%^ %^ @ &#^&.'
This is a test. |
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... | #Java | Java | public class SubstitutionCipher {
final static String key = "]kYV}(!7P$n5_0i R:?jOWtF/=-pe'AD&@r6%ZXs\"v*N"
+ "[#wSl9zq2^+g;LoB`aGh{3.HIu4fbK)mU8|dMET><,Qc\\C1yxJ";
static String text = "Here we have to do is there will be a input/source "
+ "file in which we are going to Encrypt the... |
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.
| #CoffeeScript | CoffeeScript |
sum = (array) ->
array.reduce (x, y) -> x + y
product = (array) ->
array.reduce (x, y) -> x * y
|
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.
| #ColdFusion | ColdFusion | <cfset Variables.myArray = [1,2,3,4,5,6,7,8,9,10]>
<cfoutput>#ArraySum(Variables.myArray)#</cfoutput> |
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... | #COBOL | COBOL | IDENTIFICATION DIVISION.
PROGRAM-ID. sum-of-series.
DATA DIVISION.
WORKING-STORAGE SECTION.
78 N VALUE 1000.
01 series-term USAGE FLOAT-LONG.
01 i PIC 9(4).
PROCEDURE DIVISION.
PERFORM VAR... |
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, ... | #Go | Go | package main
import (
"fmt"
"sort"
)
const pow3_8 = 3 * 3 * 3 * 3 * 3 * 3 * 3 * 3 // 3^8
const pow3_9 = 3 * pow3_8 // 3^9
const maxExprs = 2 * pow3_8 // not 3^9 since first op can't be Join
type op uint8
const (
Add op = iota // insert a "+"
Sub // or a "-... |
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.
| #dc | dc | [ Sm Sn lm 1 - d ln % - d sm ln / ln lm + * 0k 2 / Ss Lm sx Ln sx Ls ]sm
[ d d d 3 r lmx r 5 r lmx + r 15 r lmx - ]ss
[ 27 P 91 P 65 P 27 P 91 P 50 P 50 P 67 P ]su
[ ll p lsx lux p ll 10 * d sl 1000000000000000000000 >d]sd
1 sl ldx |
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
| #Dc | Dc | [ I ~ S! d 0!=S L! + ] sS
1 lS x p
1234 lS x p
16 i
FE lS x p
F0E lS x p |
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
| #Emacs_Lisp | Emacs Lisp | (defun sum-of-squares (numbers)
(apply #'+ (mapcar (lambda (k) (* k k)) numbers)))
(sum-of-squares (number-sequence 0 3)) ;=> 14 |
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
| #Erlang | Erlang | lists:foldl(fun(X, Sum) -> X*X + Sum end, 0, [3,1,4,1,5,9]). |
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.
| #8th | 8th |
\
\ Simple iterative backtracking Sudoku solver for 8th
\
needs array/each-slice
[ 00, 00, 00, 03, 03, 03, 06, 06, 06,
00, 00, 00, 03, 03, 03, 06, 06, 06,
00, 00, 00, 03, 03, 03, 06, 06, 06,
27, 27, 27, 30, 30, 30, 33, 33, 33,
27, 27, 27, 30, 30, 30, 33, 33, 33,
27, 27, 27, 30, 30, 30, 33, 33, 33,
... |
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... | #11l | 11l | F subleq(&a)
V i = 0
L i >= 0
I a[i] == -1
a[a[i + 1]] = :stdin.read(1).code
E I a[i + 1] == -1
print(Char(code' a[a[i]]), end' ‘’)
E
a[a[i + 1]] -= a[a[i]]
I a[a[i + 1]] <= 0
i = a[i + 2]
L.continue
i += 3
subleq(&[15, 17, -1, ... |
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:
... | #C | C | #include <stdbool.h>
#include <stdint.h>
#include <stdio.h>
#define PRIME_COUNT 100000
int64_t PRIMES[PRIME_COUNT];
size_t primeSize = 0;
bool isPrime(int n) {
size_t i = 0;
for (i = 0; i < primeSize; i++) {
int64_t p = PRIMES[i];
if (n == p) {
return true;
}
if... |
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... | #Apex | Apex |
String strOrig = 'brooms';
String str1 = strOrig.substring(1, strOrig.length());
system.debug(str1);
String str2 = strOrig.substring(0, strOrig.length()-1);
system.debug(str2);
String str3 = strOrig.substring(1, strOrig.length()-1);
system.debug(str3);
// Regular Expressions approach
String strOrig = 'brooms';
Stri... |
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... | #C.2B.2B | C++ |
// written for clarity not efficiency.
#include <iostream>
using std::cout;
using std::endl;
#include <boost/array.hpp>
#include <boost/circular_buffer.hpp>
class Subtractive_generator {
private:
static const int param_i = 55;
static const int param_j = 24;
static const int initial_load = 219;
s... |
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... | #jq | jq | def key:
"]kYV}(!7P$n5_0i R:?jOWtF/=-pe'AD&@r6%ZXs\"v*N[#wSl9zq2^+g;LoB`aGh{3.HIu4fbK)mU8|dMET><,Qc\\C1yxJ";
def encode:
(key|explode) as $key
| explode as $exploded
| reduce range(0;length) as $i ([];
. + [$key[ $exploded[$i] - 32]] )
| implode;
def decode:
(key|explode) as $key
| explode a... |
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... | #Julia | Julia | module SubstitutionCiphers
using Compat
const key = "]kYV}(!7P\$n5_0i R:?jOWtF/=-pe'AD&@r6%ZXs\"v*N[#wSl9zq2^+g;LoB`aGh{3.HIu4fbK)mU8|dMET><,Qc\\C1yxJ"
function encode(s::AbstractString)
buf = IOBuffer()
for c in s
print(buf, key[Int(c) - 31])
end
return String(take!(buf))
end
function d... |
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... | #Klingphix | Klingphix | include ..\Utilitys.tlhy
" ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"
" VsciBjedgrzyHalvXZKtUPumGfIwJxqOCFRApnDhQWobLkESYMTN"
"A simple example"
:Encode %mode !mode
%i %t
$mode not [rot rot swap rot] if
len [
!i
$i get swap !t
rot swap find
rot swap get
... |
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.
| #Common_Lisp | Common Lisp | (let ((data #(1 2 3 4 5))) ; the array
(values (reduce #'+ data) ; sum
(reduce #'* data))) ; product |
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... | #CoffeeScript | CoffeeScript |
console.log [1..1000].reduce((acc, x) -> acc + (1.0 / (x*x)))
|
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, ... | #Haskell | Haskell | import Control.Monad (replicateM)
import Data.Char (intToDigit)
import Data.List
( find,
group,
intercalate,
nub,
sort,
sortBy,
)
import Data.Monoid ((<>))
import Data.Ord (comparing)
data Sign
= Unsigned
| Plus
| Minus
deriving (Eq, Show)
------------------------ SUM TO 100 --------... |
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.
| #Delphi | Delphi | program sum35;
{$APPTYPE CONSOLE}
var
sum: integer;
i: integer;
function isMultipleOf(aNumber, aDivisor: integer): boolean;
begin
result := aNumber mod aDivisor = 0
end;
begin
sum := 0;
for i := 3 to 999 do
begin
if isMultipleOf(i, 3) or isMultipleOf(i, 5) then
sum := sum + i;
end;
wri... |
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
| #Dyalect | Dyalect | func digits(num, bas = 10) {
while num != 0 {
let (n, digit) = (num / bas, num % bas)
num = n
yield digit
}
}
func Iterator.Sum(acc = 0) {
for x in this {
acc += x
}
return acc
}
func sumOfDigits(num, bas = 10) => digits(num, bas).Sum()
for e in [
(num: 1, ... |
http://rosettacode.org/wiki/Sum_of_squares | Sum of squares | Task
Write a program to find the sum of squares of a numeric vector.
The program should work on a zero-length vector (with an answer of 0).
Related task
Mean
| #Euphoria | Euphoria | function SumOfSquares(sequence v)
atom sum
sum = 0
for i = 1 to length(v) do
sum += v[i]*v[i]
end for
return sum
end function |
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
| #Excel | Excel |
=SUMSQ(A1:A10)
|
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... | #11l | 11l | F primes_upto(limit)
V is_prime = [0B] * 2 [+] [1B] * (limit - 1)
L(n) 0 .< Int(limit ^ 0.5 + 1.5)
I is_prime[n]
L(i) (n * n .< limit + 1).step(n)
is_prime[i] = 0B
R enumerate(is_prime).filter((i, prime) -> prime).map((i, prime) -> i)
V p = primes_upto(10'000'000)
[Int] s, w, b
L(i... |
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.
| #Ada | Ada |
with Ada.Text_IO;
procedure Sudoku is
type sudoku_ar_t is array ( integer range 0..80 ) of integer range 0..9;
FINISH_EXCEPTION : exception;
procedure prettyprint(sudoku_ar: sudoku_ar_t);
function checkValidity( val : integer; x : integer; y : integer; sudoku_ar: in sudoku_ar_t) return Boolean;
p... |
http://rosettacode.org/wiki/Subleq | Subleq | Subleq is an example of a One-Instruction Set Computer (OISC).
It is named after its only instruction, which is SUbtract and Branch if Less than or EQual to zero.
Task
Your task is to create an interpreter which emulates a SUBLEQ machine.
The machine's memory consists of an array of signed integers. These integers... | #8080_Assembly | 8080 Assembly | ;;; ---------------------------------------------------------------
;;; SUBLEQ for CP/M. The word size is 16 bits, and the program
;;; is given 16 Kwords (32 KB) of memory. (If the system doesn't
;;; have enough, the program will not run.)
;;; I/O is via the console; since it cannot normally be redirected,
;;; CR... |
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... | #8086_Assembly | 8086 Assembly | ;;; -------------------------------------------------------------
;;; SUBLEQ interpreter that runs under MS-DOS.
;;; The word size is 16 bits, and the SUBLEQ program gets a 64KB
;;; (that is, 32K Subleq words) address space.
;;; The SUBLEQ program is read from a text file given on the
;;; command line, I/O is do... |
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:
... | #C.23 | C# | using System;
using System.Collections.Generic;
using static System.Linq.Enumerable;
public static class SuccessivePrimeDifferences {
public static void Main() {
var primes = GeneratePrimes(1_000_000).ToList();
foreach (var d in new[] {
new [] { 2 },
new [] { 1 },
... |
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... | #AppleScript | AppleScript | set aString to "This is some text"
set stringLength to (count aString) -- The number of characters in the text.
-- AppleScript indices are 1-based. Ranges can be specified in several different ways.
if (stringLength > 1) then
set substring1 to text 2 thru stringLength of aString
-- set substring1 to text 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... | #Clojure | Clojure | (defn xpat2-with-seed
"produces an xpat2 function initialized from seed"
[seed]
(let [e9 1000000000
fs (fn [[i j]] [j (mod (- i j) e9)])
s (->> [seed 1] (iterate fs) (map first) (take 55) vec)
rinit (map #(-> % inc (* 34) (mod 55) s) (range 55))
r-atom (atom [54 (int-array rinit)])... |
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... | #Kotlin | Kotlin | // version 1.0.6
object SubstitutionCipher {
val key = "]kYV}(!7P\$n5_0i R:?jOWtF/=-pe'AD&@r6%ZXs\"v*N[#wSl9zq2^+g;LoB`aGh{3.HIu4fbK)mU8|dMET><,Qc\\C1yxJ"
fun encode(s: String): String {
val sb = StringBuilder()
for (c in s) sb.append(key[c.toInt() - 32])
return sb.toString()
}
... |
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... | #Lambdatalk | Lambdatalk |
{def small_ascii {S.map fromCharCode {S.serie 33 122}}}
-> small_ascii
{S.length {small_ascii}} = 90
{def substitution
{def substitution.r
{lambda {:w :n :s :i}
{if {> :i :n}
then
else {let { {:s :s} {:c {W.char2code {A.get :i :w}}}
} {if {and {>= :c 33} {<= :c 122}}
... |
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.
| #Crystal | Crystal |
def sum_product(a)
{ a.sum(), a.product() }
end
|
http://rosettacode.org/wiki/Sum_of_a_series | Sum of a series | Compute the nth term of a series, i.e. the sum of the n first terms of the corresponding sequence.
Informally this value, or its limit when n tends to infinity, is also called the sum of the series, thus the title of this task.
For this task, use:
S
n
=
∑
k
=
1
n
1
k
2
{\displa... | #Common_Lisp | Common Lisp | (loop for x from 1 to 1000 summing (expt x -2)) |
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, ... | #J | J |
p =: ,"2".>(#: (+ i.)2^8) <;.1 '123456789'
m =. (9$_1x)^"1#:i.2^9
s =. 131072 9 $ ,m *"1/ p
s2 =: (~: (10x^i._9)#.s)#s
ss =: +/"1 s2
'100=';<'bp<+>' 8!:2 (I.100=ss){s2
pos =: (0<ss)#ss =: /:~ss
({.;'times';{:)>{.\:~(#,{.) each </.~ ss
'Ten largest:';,.(->:i.10){ss
'First not expressible:';>:pos{~ 1 i.~ 1<|2-/\pos
|
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.
| #D.C3.A9j.C3.A0_Vu | Déjà Vu | sum-divisible n:
0
for i range 1 -- n:
if or = 0 % i 3 = 0 % i 5:
+ i
!. sum-divisible 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
| #Delphi | Delphi | defmodule RC do
def sumDigits(n, base\\10)
def sumDigits(n, base) when is_integer(n) do
Integer.digits(n, base) |> Enum.sum
end
def sumDigits(n, base) when is_binary(n) do
String.codepoints(n) |> Enum.map(&String.to_integer(&1, base)) |> Enum.sum
end
end
Enum.each([{1, 10}, {1234, 10}, {0xfe, 16}, {... |
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.23 | F# | [1 .. 10] |> List.fold (fun a x -> a + x * x) 0
[|1 .. 10|] |> Array.fold (fun a x -> a + x * x) 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
| #Factor | Factor | USE: math sequences ;
: sum-of-squares ( seq -- n ) [ sq ] map-sum ;
{ 1.0 2.0 4.0 8.0 16.0 } sum-of-squares |
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... | #ALGOL_68 | ALGOL 68 | # find and count strong and weak primes #
PR heap=128M PR # set heap memory size for Algol 68G #
# returns a string representation of n with commas #
PROC commatise = ( INT n )STRING:
BEGIN
STRING result := "";
... |
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 |... | #11l | 11l | V s = ‘abcdefgh’
V n = 2
V m = 3
V char = ‘d’
V chars = ‘cd’
print(s[n - 1 .+ m]) // starting from n=2 characters in and m=3 in length
print(s[n - 1 ..]) // starting from n characters in, up to the end of the string
print(s[0 .< (len)-1]) // whole string minus last character
print(s[s.index(c... |
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.
| #ALGOL_68 | ALGOL 68 | MODE AVAIL = [9]BOOL;
MODE BOX = [3, 3]CHAR;
FORMAT row fmt = $"|"3(" "3(g" ")"|")l$;
FORMAT line = $"+"3(7"-","+")l$;
FORMAT puzzle fmt = $f(line)3(3(f(row fmt))f(line))$;
AVAIL gen full = (TRUE, TRUE, TRUE, TRUE, TRUE, TRUE, TRUE, TRUE, TRUE);
OP REPR = (AVAIL avail)STRING: (
STRING out := "";
FOR i FROM LW... |
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... | #Ada | Ada | with Ada.Text_IO;
procedure Subleq is
Storage_Size: constant Positive := 2**8; -- increase or decrease memory
Steps: Natural := 999; -- "emergency exit" to stop endless loops
subtype Address is Integer range -1 .. (Storage_Size-1);
subtype Memory_Location is Address range 0 .. Address'Last;
type ... |
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:
... | #C.2B.2B | C++ | #include <iostream>
#include <cstdint>
#include <vector>
#include "prime_sieve.hpp"
using integer = uint32_t;
using vector = std::vector<integer>;
void print_vector(const vector& vec) {
if (!vec.empty()) {
auto i = vec.begin();
std::cout << '(' << *i;
for (++i; i != vec.end(); ++i)
... |
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... | #Arturo | Arturo | knight: "knight"
socks: "socks"
brooms: "brooms"
print drop knight 1 ; strip first character
print slice knight 1 (size knight)-1 ; alternate way to strip first character
print chop socks ; strip last character
print take socks (size socks)-1 ; alternate way to ... |
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... | #Common_Lisp | Common Lisp | (defun sub-rand (state)
(let ((x (last state)) (y (last state 25)))
;; I take "circular buffer" very seriously (until some guru
;; points out it's utterly wrong thing to do)
(setf (cdr x) state)
(lambda () (setf x (cdr x)
y (cdr y)
(car x) (mod (- (car x) (car y)) (expt 10 9))))))
;; r... |
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... | #Lua | Lua | -- Generate a random substitution cipher for ASCII characters 65 to 122
function randomCipher ()
local cipher, rnd = {plain = {}, encoded = {}}
for ascii = 65, 122 do
table.insert(cipher.plain, string.char(ascii))
table.insert(cipher.encoded, string.char(ascii))
end
for i = 1, #cipher.en... |
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.
| #D | D | import std.stdio;
void main() {
immutable array = [1, 2, 3, 4, 5];
int sum = 0;
int prod = 1;
foreach (x; array) {
sum += x;
prod *= x;
}
writeln("Sum: ", sum);
writeln("Product: ", 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... | #Crystal | Crystal | puts (1..1000).sum{ |x| 1.0 / x ** 2 }
puts (1..5000).sum{ |x| 1.0 / x ** 2 }
puts (1..9999).sum{ |x| 1.0 / x ** 2 }
puts Math::PI ** 2 / 6 |
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, ... | #Java | Java | /*
* RossetaCode: Sum to 100, Java 8.
*
* Find solutions to the "sum to one hundred" puzzle.
*/
package rosettacode;
import java.io.PrintStream;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Map;
import java... |
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.
| #EchoLisp | EchoLisp |
(lib 'math) ;; divides?
(lib 'sequences) ;; sum/when
(define (task n (k 3) (p 5 ))
(when (!= (gcd k p) 1) (error "expected coprimes" (list k p)))
(-
(+ (sum/mults n k) (sum/mults n p)) ;; add multiples of k , multiples of p
(sum/mults n (* k p)))) ;; remove multiples of k * p
;; using sequences
;; su... |
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
| #Elixir | Elixir | defmodule RC do
def sumDigits(n, base\\10)
def sumDigits(n, base) when is_integer(n) do
Integer.digits(n, base) |> Enum.sum
end
def sumDigits(n, base) when is_binary(n) do
String.codepoints(n) |> Enum.map(&String.to_integer(&1, base)) |> Enum.sum
end
end
Enum.each([{1, 10}, {1234, 10}, {0xfe, 16}, {... |
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
| #FALSE | FALSE |
0 3 1 4 1 5 9$*\ [$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
| #Fantom | Fantom |
class SumSquares
{
static Int sumSquares (Int[] numbers)
{
Int sum := 0
numbers.each |n| { sum += n * n }
return sum
}
public static Void main ()
{
Int[] n := [,]
echo ("Sum of squares of $n = ${sumSquares(n)}")
n = [1,2,3,4,5]
echo ("Sum of squares of $n = ${sumSquares(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... | #AWK | AWK |
# syntax: GAWK -f STRONG_AND_WEAK_PRIMES.AWK
BEGIN {
for (i=1; i<1E7; i++) {
if (is_prime(i)) {
arr[++n] = i
}
}
# strong:
stop1 = 36 ; stop2 = 1E6 ; stop3 = 1E7
count1 = count2 = count3 = 0
printf("The first %d strong primes:",stop1)
for (i=2; count1<stop1; i++) {
if... |
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 |... | #AArch64_Assembly | AArch64 Assembly |
/* ARM assembly AARCH64 Raspberry PI 3B */
/* program subString64.s */
/*******************************************/
/* Constantes file */
/*******************************************/
/* for this file see task include a file in language AArch64 assembly*/
.include "../includeConstantesAR... |
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 |... | #Action.21 | Action! | BYTE FUNC FindC(CHAR ARRAY text CHAR c)
BYTE i
i=1
WHILE i<=text(0)
DO
IF text(i)=c THEN
RETURN (i)
FI
i==+1
OD
RETURN (0)
BYTE FUNC FindS(CHAR ARRAY text,sub)
BYTE i,j,found
i=1
WHILE i<=text(0)-sub(0)+1
DO
found=0
FOR j=1 TO sub(0)
DO
IF text(i+j-1)#sub(j) T... |
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.
| #AutoHotkey | AutoHotkey | #SingleInstance, Force
SetBatchLines, -1
SetTitleMatchMode, 3
Loop 9 {
r := A_Index, y := r*17-8 + (A_Index >= 7 ? 4 : A_Index >= 4 ? 2 : 0)
Loop 9 {
c := A_Index, x := c*17+5 + (A_Index >= 7 ? 4 : A_Index >= 4 ? 2 : 0)
Gui, Add, Edit, x%x% y%y% w17 h17 v%r%_%c% Center Number Lim... |
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... | #ALGOL_68 | ALGOL 68 | # Subleq program interpreter #
# executes the program specified in code, stops when the instruction pointer #
# becomes negative #
PROC run subleq = ( []INT code )VOID:
BEGIN
INT max memory = 3 * 102... |
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:
... | #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/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... | #AutoHotkey | AutoHotkey | myString := "knights"
MsgBox % SubStr(MyString, 2)
MsgBox % SubStr(MyString, 1, StrLen(MyString)-1)
MsgBox % SubStr(MyString, 2, StrLen(MyString)-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... | #D | D | import std.stdio;
struct Subtractive {
enum MOD = 1_000_000_000;
private int[55] state;
private int si, sj;
this(in int p1) pure nothrow {
subrandSeed(p1);
}
void subrandSeed(int p1) pure nothrow {
int p2 = 1;
state[0] = p1 % MOD;
for (int i = 1, j = 21; i... |
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... | #MiniScript | MiniScript | alphabet = "abcdefghijklmnopqrstuvwxyz".split("")
cipher = alphabet[0:]
cipher.shuffle
encode = {}
decode = {}
for i in alphabet.indexes
encode[alphabet[i]] = cipher[i]
decode[cipher[i]] = alphabet[i]
encode[alphabet[i].upper] = cipher[i].upper
decode[cipher[i].upper] = alphabet[i].upper
end for
apply... |
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... | #Nim | Nim | import sequtils, strutils
proc encrypt(key: seq[char]; msg: string): string =
result.setLen(msg.len)
for i, c in msg:
result[i] = key[ord(c) - 32]
proc decrypt(key: seq[char]; msg: string): string =
result.setLen(msg.len)
for i, c in msg:
result[i] = chr(key.find(c) + 32)
when isMainModule:
im... |
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.
| #dc | dc | 1 3 5 7 9 11 13 0ss1sp[dls+sslp*spz0!=a]dsax[Sum: ]Plsp[Product: ]Plpp
Sum: 49
Product: 135135 |
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... | #D | D | import std.stdio, std.traits;
ReturnType!TF series(TF)(TF func, int end, int start=1)
pure nothrow @safe @nogc {
typeof(return) sum = 0;
foreach (immutable i; start .. end + 1)
sum += func(i);
return sum;
}
void main() {
writeln("Sum: ", series((in int n) => 1.0L / (n ^^ 2), 1_000));
} |
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, ... | #JavaScript | JavaScript | (function () {
'use strict';
// GENERIC FUNCTIONS ----------------------------------------------------
// permutationsWithRepetition :: Int -> [a] -> [[a]]
var permutationsWithRepetition = function (n, as) {
return as.length > 0 ?
foldl1(curry(cartesianProduct)(as), replicate(n, ... |
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.
| #Eiffel | Eiffel |
class
APPLICATION
create
make
feature {NONE}
make
do
io.put_integer (sum_multiples (1000))
end
sum_multiples (n: INTEGER): INTEGER
-- Sum of all positive multiples of 3 or 5 below 'n'.
do
across
1 |..| (n - 1) as c
loop
if c.item \\ 3 = 0 or c.item \\ 5 = 0 then
Result := ... |
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
| #Emacs_Lisp | Emacs Lisp | (defun digit-sum (n)
(apply #'+ (mapcar (lambda (c) (- c ?0)) (string-to-list "123"))))
(digit-sum 1234) ;=> 10 |
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
| #Fish | Fish | v
\0&
>l?!v:*&+&
>&n; |
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... | #11l | 11l | V s = " \t \r \n String with spaces \t \r \n "
print(s.ltrim((‘ ’, "\t", "\r", "\n")).len)
print(s.rtrim((‘ ’, "\t", "\r", "\n")).len)
print(s.trim((‘ ’, "\t", "\r", "\n")).len) |
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 | C | #include <stdbool.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
const int 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, 21... |
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 |... | #Ada | Ada | type String is array (Positive range <>) of Character; |
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.
| #AWK | AWK |
# syntax: GAWK -f SUDOKU_RC.AWK
BEGIN {
# row1 row2 row3 row4 row5 row6 row7 row8 row9
# puzzle = "111111111 111111111 111111111 111111111 111111111 111111111 111111111 111111111 111111111" # NG duplicate hints
# puzzle = "1........ ..274.... ...5....4 .3.......... |
http://rosettacode.org/wiki/Subleq | Subleq | Subleq is an example of a One-Instruction Set Computer (OISC).
It is named after its only instruction, which is SUbtract and Branch if Less than or EQual to zero.
Task
Your task is to create an interpreter which emulates a SUBLEQ machine.
The machine's memory consists of an array of signed integers. These integers... | #ALGOL_W | ALGOL W | % Subleq program interpreter %
begin
% executes the program specified in scode, stops when the instruction %
% pointer becomes negative %
procedure runSubleq ( integer array scode( * )
... |
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:
... | #Delphi | Delphi |
program Successive_prime_differences;
{$APPTYPE CONSOLE}
{$R *.res}
uses
System.SysUtils,
System.Generics.Collections;
function IsPrime(a: UInt64): Boolean;
var
d: UInt64;
begin
if (a < 2) then
exit(False);
if (a mod 2) = 0 then
exit(a = 2);
if (a mod 3) = 0 then
exit(a = 3);
... |
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... | #AWK | AWK | BEGIN {
mystring="knights"
print substr(mystring,2) # remove the first letter
print substr(mystring,1,length(mystring)-1) # remove the last character
print substr(mystring,2,length(mystring)-2) # remove both the first and last character
} |
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... | #dc | dc | [*
* (seed) lsx --
* Seeds the subtractive generator.
* Uses register R to hold the state.
*]sz
[
[* Fill ring buffer R[0] to R[54]. *]sz
d 54:R SA [A = R[54] = seed]sz
1 d 33:R SB [B = R[33] = 1]sz
12 SC [C = index 12, into array R.]sz
[55 -]SI
[ ... |
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... | #Perl | Perl | sub encode {
my $source = shift;
my $key = shift;
my $out = q();
@ka = split //, $key;
foreach $ch (split //, $source) {
$idx = ord($ch) - 32;
$out .= $ka[$idx];
}
return $out;
}
sub decode {
my $source = shift;
my $key = shift;
my $out = q();
foreach ... |
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.
| #Delphi | Delphi | program SumAndProductOfArray;
{$APPTYPE CONSOLE}
var
i: integer;
lIntArray: array [1 .. 5] of integer = (1, 2, 3, 4, 5);
lSum: integer = 0;
lProduct: integer = 1;
begin
for i := 1 to length(lIntArray) do
begin
Inc(lSum, lIntArray[i]);
lProduct := lProduct * lIntArray[i]
end;
Write('Sum: ')... |
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... | #Dart | Dart | main() {
var list = new List<int>.generate(1000, (i) => i + 1);
num sum = 0;
(list.map((x) => 1.0 / (x * x))).forEach((num e) {
sum += e;
});
print(sum);
} |
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, ... | #jq | jq | # Generate a "sum" in the form: [I, 1, X, 2, X, 3, ..., X, n] where I is "-" or "", and X is "+", "-", or ""
def generate(n):
def pm: ["+"], ["-"], [""];
if n == 1 then (["-"], [""]) + [1]
else generate(n-1) + pm + [n]
end;
# The numerical value of a "sum"
def addup:
reduce .[] as $x ({sum:0, previous: ... |
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 ... | #11l | 11l | F stripped(s)
R s.filter(i -> Int(i.code) C 32..126).join(‘’)
print(stripped("\ba\u0000b\n\rc\fd\xc3")) |
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.
| #Elixir | Elixir | iex(1)> Enum.filter(0..1000-1, fn x -> rem(x,3)==0 or rem(x,5)==0 end) |> Enum.sum
233168 |
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
| #Erlang | Erlang |
-module(sum_digits).
-export([sum_digits/2, sum_digits/1]).
sum_digits(N) ->
sum_digits(N,10).
sum_digits(N,B) ->
sum_digits(N,B,0).
sum_digits(0,_,Acc) ->
Acc;
sum_digits(N,B,Acc) when N < B ->
Acc+N;
sum_digits(N,B,Acc) ->
sum_digits(N div B, B, Acc + (N rem B)).
|
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
| #Forth | Forth | : fsum**2 ( addr n -- f )
0e
dup 0= if 2drop exit then
floats bounds do
i f@ fdup f* f+
1 floats +loop ;
create test 3e f, 1e f, 4e f, 1e f, 5e f, 9e f,
test 6 fsum**2 f. \ 133. |
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... | #Action.21 | Action! | DEFINE SPACE="32"
DEFINE TAB="127"
DEFINE NEWLINE="155"
BYTE FUNC IsWhitespace(CHAR c)
IF c=SPACE OR c=TAB OR c=NEWLINE THEN
RETURN (1)
FI
RETURN (0)
PROC Strip(CHAR ARRAY src,dst BYTE head,tail)
BYTE i,first,last
first=1
last=src(0)
IF head THEN
WHILE first<=last
DO
IF IsWhitespac... |
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.23 | C# | using static System.Console;
using static System.Linq.Enumerable;
using System;
public static class StrongAndWeakPrimes
{
public static void Main() {
var primes = PrimeGenerator(10_000_100).ToList();
var strongPrimes = from i in Range(1, primes.Count - 2) where primes[i] > (primes[i-1] + primes[i+... |
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 |... | #Aikido | Aikido |
const str = "abcdefg"
var n = 2
var m = 3
println (str[n:n+m-1]) // pos 2 length 3
println (str[n:]) // pos 2 to end
println (str >> 1) // remove last character
var p = find (str, 'c')
println (str[p:p+m-1]) // from pos of p length 3
var s = find (str, "bc")
println (str[s, s+m-1]) // 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.
| #BBC_BASIC | BBC BASIC | VDU 23,22,453;453;8,20,16,128
*FONT Arial,28
DIM Board%(8,8)
Board%() = %111111111
FOR L% = 0 TO 9:P% = L%*100
LINE 2,P%+2,902,P%+2
IF (L% MOD 3)=0 LINE 2,P%,902,P% : LINE 2,P%+4,902,P%+4
LINE P%+2,2,P%+2,902
IF (L% MOD 3)=0 LINE P%,2,P%,902 : LINE P%+4,... |
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... | #APL | APL | #!/usr/local/bin/apl -s --
⎕IO←0 ⍝ Index origin 0 is more intuitive with 'pointers'
∇Subleq;fn;text;M;A;B;C;X
→(5≠⍴⎕ARG)/usage ⍝ There should be one (additional) argument
fn←⊃⎕ARG[4] ⍝ This argument should be the file name
→(''≢0⍴text←⎕FIO[26]fn)/filerr ⍝ Load th... |
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:
... | #F.23 | F# |
// Successive primes. Nigel Galloway: May 6th., 2019
let sP n=let sP=pCache|>Seq.takeWhile(fun n->n<1000000)|>Seq.windowed(Array.length n+1)|>Seq.filter(fun g->g=(Array.scan(fun n g->n+g) g.[0] n))
printfn "sP %A\t-> Min element = %A Max element = %A of %d elements" n (Seq.head sP) (Seq.last sP) (Seq.length ... |
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... | #BASIC | BASIC | 10 PRINT FN F$("KNIGHTS"): REM STRIP THE FIRST LETTER
20 PRINT FN L$("SOCKS"): REM STRIP THE LAST LETTER
30 PRINT FN B$("BROOMS"): REM STRIP BOTH THE FIRST AND LAST LETTER
100 END
9000 DEF FN F$(A$)=RIGHT$(A$,LEN(A$)-1)
9010 DEF FN L$(A$)=LEFT$(A$,LEN(A$)-1)
9020 DEF FN B$(A$)=FN L$(FN F$(A$)) |
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... | #Elixir | Elixir | defmodule Subtractive do
def new(seed) when seed in 0..999_999_999 do
s = Enum.reduce(1..53, [1, seed], fn _,[a,b|_]=acc -> [b-a | acc] end)
|> Enum.reverse
|> List.to_tuple
state = for i <- 1..55, do: elem(s, rem(34*i, 55))
{:ok, _pid} = Agent.start_link(fn -> state end, name: :Subtractiv... |
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... | #Phix | Phix | constant plain = tagset('Z','A')&tagset('z','a'),
key = shuffle(plain)
function encode(string s, integer decrypt=false)
sequence {p,k} = iff(decrypt?{plain,key}:{key,plain})
for i=1 to length(s) do
integer ki = find(s[i],p)
if ki then s[i] = k[ki] end if
end for
return s
end fu... |
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.
| #E | E | pragma.enable("accumulator")
accum 0 for x in [1,2,3,4,5] { _ + x }
accum 1 for x in [1,2,3,4,5] { _ * x } |
http://rosettacode.org/wiki/Sum_of_a_series | Sum of a series | Compute the nth term of a series, i.e. the sum of the n first terms of the corresponding sequence.
Informally this value, or its limit when n tends to infinity, is also called the sum of the series, thus the title of this task.
For this task, use:
S
n
=
∑
k
=
1
n
1
k
2
{\displa... | #Delphi | Delphi |
unit Form_SumOfASeries_Unit;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls;
type
TFormSumOfASeries = class(TForm)
M_Log: TMemo;
B_Calc: TButton;
procedure B_CalcClick(Sender: TObject);
private
{ Private-Deklarationen }
publi... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.