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/Jensen%27s_Device | Jensen's Device | Jensen's Device
You are encouraged to solve this task according to the task description, using any language you may know.
This task is an exercise in call by name.
Jensen's Device is a computer programming technique devised by Danish computer scientist Jørn Jensen after studying the ALGOL 60 Report.
The following pr... | #ZX_Spectrum_Basic | ZX Spectrum Basic | 10 DEF FN r(x)=1/x
20 LET f$="FN r(i)"
30 LET lo=1: LET hi=100
40 GO SUB 1000
50 PRINT temp
60 STOP
1000 REM Evaluation
1010 LET temp=0
1020 FOR i=lo TO hi
1030 LET temp=temp+VAL f$
1040 NEXT i
1050 RETURN
|
http://rosettacode.org/wiki/Inverted_syntax | Inverted syntax | Inverted syntax with conditional expressions
In traditional syntax conditional expressions are usually shown before the action within a statement or code block:
IF raining=true THEN needumbrella=true
In inverted syntax, the action is listed before the conditional expression in the statement or code block:
needumb... | #Latitude | Latitude | local 'raining = True.
local 'needUmbrella = False.
if (raining) then {
needUmbrella = True.
} else {}.
{ raining. } ifTrue {
needUmbrella = True.
}. |
http://rosettacode.org/wiki/Inverted_syntax | Inverted syntax | Inverted syntax with conditional expressions
In traditional syntax conditional expressions are usually shown before the action within a statement or code block:
IF raining=true THEN needumbrella=true
In inverted syntax, the action is listed before the conditional expression in the statement or code block:
needumb... | #M2000_Interpreter | M2000 Interpreter |
expr=lambda ->{
Print "ok"
}
ifrev=lambda (dothis, cond) ->{
if cond then call dothis()
}
a=1
call ifrev(expr, a=1)
\\ on module call
Module Subtract (a, b) {
Push a-b
}
Module PrintTop {
Print Number
}
Subtract 10, 3 : PrintTop
\\ pushing before calling in reverse order
Push 3, 10 : Subtrac... |
http://rosettacode.org/wiki/Inverted_syntax | Inverted syntax | Inverted syntax with conditional expressions
In traditional syntax conditional expressions are usually shown before the action within a statement or code block:
IF raining=true THEN needumbrella=true
In inverted syntax, the action is listed before the conditional expression in the statement or code block:
needumb... | #m4 | m4 | define(`thenif', `ifelse($2, $3, `$1')')dnl
dnl
ifelse(eval(23 > 5), 1, 23 is greater than 5)
ifelse(eval(23 > 5), 0, math is broken)
thenif(23 is greater than 5, eval(23 > 5), 1)
thenif(math is broken, eval(23 > 5), 0) |
http://rosettacode.org/wiki/Inverted_syntax | Inverted syntax | Inverted syntax with conditional expressions
In traditional syntax conditional expressions are usually shown before the action within a statement or code block:
IF raining=true THEN needumbrella=true
In inverted syntax, the action is listed before the conditional expression in the statement or code block:
needumb... | #Mathematica.2FWolfram_Language | Mathematica/Wolfram Language | a = 4
->4
b = 5
->5
If[1<2,
Print["This was expected"]
]
->This was expected |
http://rosettacode.org/wiki/ISBN13_check_digit | ISBN13 check digit | Task
Validate the check digit of an ISBN-13 code:
Multiply every other digit by 3.
Add these numbers and the other digits.
Take the remainder of this number after division by 10.
If it is 0, the ISBN-13 check digit is correct.
Use the following codes for testing:
978-1734314502 (good)
... | #AutoHotkey | AutoHotkey | ISBN13_check_digit(n){
for i, v in StrSplit(RegExReplace(n, "[^0-9]"))
sum += !Mod(i, 2) ? v*3 : v
return n "`t" (Mod(sum, 10) ? "(bad)" : "(good)")
} |
http://rosettacode.org/wiki/Jaro_similarity | Jaro similarity | The Jaro distance is a measure of edit distance between two strings; its inverse, called the Jaro similarity, is a measure of two strings' similarity: the higher the value, the more similar the strings are. The score is normalized such that 0 equates to no similarities and 1 is an exact match.
Definition
The... | #Crystal | Crystal | def jaro(s, t)
return 1.0 if s == t
s_len = s.size
t_len = t.size
match_distance = ({s_len, t_len}.max // 2) - 1
s_matches = Array.new(s_len, false)
t_matches = Array.new(t_len, false)
matches = 0.0
s_len.times do |i|
j_start = {0, i - match_distance}.max
j_end = {i... |
http://rosettacode.org/wiki/Iterated_digits_squaring | Iterated digits squaring | If you add the square of the digits of a Natural number (an integer bigger than zero), you always end with either 1 or 89:
15 -> 26 -> 40 -> 16 -> 37 -> 58 -> 89
7 -> 49 -> 97 -> 130 -> 10 -> 1
An example in Python:
>>> step = lambda x: sum(int(d) ** 2 for d in str(x))
>>> iterate = lambda x: x if x in [1, 89] else i... | #AWK | AWK | # Usage: GAWK -f ITERATED_DIGITS_SQUARING.AWK
BEGIN {
# Setup buffer for results up to 9*9*8
for (i = 1; i <= 648; i++) {
k = i
do {
k = squaredigitsum(k)
} while ((k != 1) && (k != 89))
if (k == 1) # This will give us 90 entries
buffer[i] = ""
}
#... |
http://rosettacode.org/wiki/Isqrt_(integer_square_root)_of_X | Isqrt (integer square root) of X | Sometimes a function is needed to find the integer square root of X, where X can be a
real non─negative number.
Often X is actually a non─negative integer.
For the purposes of this task, X can be an integer or a real number, but if it
simplifies things in your computer programming language, assume... | #Ada | Ada | with Ada.Text_Io;
with Ada.Numerics.Big_Numbers.Big_Integers;
with Ada.Strings.Fixed;
procedure Integer_Square_Root is
use Ada.Numerics.Big_Numbers.Big_Integers;
use Ada.Text_Io;
function Isqrt (X : Big_Integer) return Big_Integer is
Q : Big_Integer := 1;
Z, T, R : Big_Integer;
begin... |
http://rosettacode.org/wiki/Josephus_problem | Josephus problem | Josephus problem is a math puzzle with a grim description:
n
{\displaystyle n}
prisoners are standing on a circle, sequentially numbered from
0
{\displaystyle 0}
to
n
−
1
{\displaystyle n-1}
.
An executioner walks along the circle, starting from prisoner
0
{\displaystyle 0}
,
removing eve... | #C | C | #include <stdio.h>
// m-th on the reversed kill list; m = 0 is final survivor
int jos(int n, int k, int m) {
int a;
for (a = m + 1; a <= n; a++)
m = (m + k) % a;
return m;
}
typedef unsigned long long xint;
// same as jos(), useful if n is large and k is not
xint jos_large(xint n, xint k, xint m) {
if (k <=... |
http://rosettacode.org/wiki/Inverted_syntax | Inverted syntax | Inverted syntax with conditional expressions
In traditional syntax conditional expressions are usually shown before the action within a statement or code block:
IF raining=true THEN needumbrella=true
In inverted syntax, the action is listed before the conditional expression in the statement or code block:
needumb... | #Mercury | Mercury | :- pred progress(int::in, int::in, int::out, int::out) is det.
progress(Past, Future, At, Total) :-
At = Past + 1,
Total = Past + Future.
progress(Past, Future, At, Total) :-
Past + Future = Total,
Past + 1 = At. |
http://rosettacode.org/wiki/Inverted_syntax | Inverted syntax | Inverted syntax with conditional expressions
In traditional syntax conditional expressions are usually shown before the action within a statement or code block:
IF raining=true THEN needumbrella=true
In inverted syntax, the action is listed before the conditional expression in the statement or code block:
needumb... | #Metafont | Metafont | x=6;
7=y; |
http://rosettacode.org/wiki/Inverted_syntax | Inverted syntax | Inverted syntax with conditional expressions
In traditional syntax conditional expressions are usually shown before the action within a statement or code block:
IF raining=true THEN needumbrella=true
In inverted syntax, the action is listed before the conditional expression in the statement or code block:
needumb... | #Nim | Nim | #--
# if statements
#--
template `?`(expression, condition) =
if condition:
expression
let raining = true
var needUmbrella: bool
# Normal syntax
if raining: needUmbrella = true
# Inverted syntax
(needUmbrella = true) ? (raining == true)
#--
# Assignments
#--
template `~=`(right, left) =
left = right... |
http://rosettacode.org/wiki/Inverted_syntax | Inverted syntax | Inverted syntax with conditional expressions
In traditional syntax conditional expressions are usually shown before the action within a statement or code block:
IF raining=true THEN needumbrella=true
In inverted syntax, the action is listed before the conditional expression in the statement or code block:
needumb... | #Oforth | Oforth | 6 -> a : Push 6 on the stack and set the top of the stack as value of local variable a (top of the stack is consumed)
6 := a : Push 6 on the stack and set the top of the satck as value of attribute a (top of the stack is consumed).
raining ifTrue: [ true ->needumbrella ]
|
http://rosettacode.org/wiki/ISBN13_check_digit | ISBN13 check digit | Task
Validate the check digit of an ISBN-13 code:
Multiply every other digit by 3.
Add these numbers and the other digits.
Take the remainder of this number after division by 10.
If it is 0, the ISBN-13 check digit is correct.
Use the following codes for testing:
978-1734314502 (good)
... | #AWK | AWK |
# syntax: GAWK -f ISBN13_CHECK_DIGIT.AWK
BEGIN {
arr[++n] = "978-1734314502"
arr[++n] = "978-1734314509"
arr[++n] = "978-1788399081"
arr[++n] = "978-1788399083"
arr[++n] = "9780820424521"
arr[++n] = "0820424528"
for (i=1; i<=n; i++) {
printf("%s %s\n",arr[i],isbn13(arr[i]))
}
... |
http://rosettacode.org/wiki/Jaro_similarity | Jaro similarity | The Jaro distance is a measure of edit distance between two strings; its inverse, called the Jaro similarity, is a measure of two strings' similarity: the higher the value, the more similar the strings are. The score is normalized such that 0 equates to no similarities and 1 is an exact match.
Definition
The... | #D | D | auto jaro(in string s1, in string s2) {
int s1_len = cast(int) s1.length;
int s2_len = cast(int) s2.length;
if (s1_len == 0 && s2_len == 0) return 1;
import std.algorithm.comparison: min, max;
auto match_distance = max(s1_len, s2_len) / 2 - 1;
auto s1_matches = new bool[s1_len];
auto s2_ma... |
http://rosettacode.org/wiki/Iterated_digits_squaring | Iterated digits squaring | If you add the square of the digits of a Natural number (an integer bigger than zero), you always end with either 1 or 89:
15 -> 26 -> 40 -> 16 -> 37 -> 58 -> 89
7 -> 49 -> 97 -> 130 -> 10 -> 1
An example in Python:
>>> step = lambda x: sum(int(d) ** 2 for d in str(x))
>>> iterate = lambda x: x if x in [1, 89] else i... | #BBC_BASIC | BBC BASIC | REM Version 1: Brute force
REM ---------------------------------------------------------
T%=TIME
N%=0
FOR I%=1 TO 100000000
J%=I%
REPEAT
K%=0:REPEAT K%+=(J%MOD10)^2:J%=J%DIV10:UNTIL J%=0
J%=K%
UNTIL J%=89 OR J%=1
IF J%>1 N%+=1
NEXT
... |
http://rosettacode.org/wiki/Iterated_digits_squaring | Iterated digits squaring | If you add the square of the digits of a Natural number (an integer bigger than zero), you always end with either 1 or 89:
15 -> 26 -> 40 -> 16 -> 37 -> 58 -> 89
7 -> 49 -> 97 -> 130 -> 10 -> 1
An example in Python:
>>> step = lambda x: sum(int(d) ** 2 for d in str(x))
>>> iterate = lambda x: x if x in [1, 89] else i... | #Befunge | Befunge | 1-1\10v!:/+55\<>::**>>-!|
v0:\+<_:55+%:*^^"d":+1$<:
>\`!#^ _$:"Y"-#v_$\1+\:^0
>01-\0^ @,+55.<>:1>-!>#^_
>,,,$." >=",,,^ >>".1">#< |
http://rosettacode.org/wiki/Isqrt_(integer_square_root)_of_X | Isqrt (integer square root) of X | Sometimes a function is needed to find the integer square root of X, where X can be a
real non─negative number.
Often X is actually a non─negative integer.
For the purposes of this task, X can be an integer or a real number, but if it
simplifies things in your computer programming language, assume... | #ALGOL_68 | ALGOL 68 | BEGIN # Integer square roots #
PR precision 200 PR
# returns the integer square root of x; x must be >= 0 #
PROC isqrt = ( LONG LONG INT x )LONG LONG INT:
IF x < 0 THEN print( ( "Negative number in isqrt", newline ) );stop
ELIF x < 2 THEN x
ELSE
# x... |
http://rosettacode.org/wiki/Josephus_problem | Josephus problem | Josephus problem is a math puzzle with a grim description:
n
{\displaystyle n}
prisoners are standing on a circle, sequentially numbered from
0
{\displaystyle 0}
to
n
−
1
{\displaystyle n-1}
.
An executioner walks along the circle, starting from prisoner
0
{\displaystyle 0}
,
removing eve... | #C.23 | C# |
namespace Josephus
{
using System;
using System.Collections;
using System.Collections.Generic;
public class Program
{
public static int[] JosephusProblem(int n, int m)
{
var circle = new List<int>();
var order = new int[n];
for (var i = 0; i ... |
http://rosettacode.org/wiki/Inverted_syntax | Inverted syntax | Inverted syntax with conditional expressions
In traditional syntax conditional expressions are usually shown before the action within a statement or code block:
IF raining=true THEN needumbrella=true
In inverted syntax, the action is listed before the conditional expression in the statement or code block:
needumb... | #OxygenBasic | OxygenBasic |
macro cond(a,c) {c then a}
macro store(b,a) {a=b}
sys a,c=10
if c>4 then a=4
'INVERTED SYNTAX FORMS:
cond a=40, if c>4
store 4,a
'COMBINED:
cond store(5,a), if c>4
|
http://rosettacode.org/wiki/Inverted_syntax | Inverted syntax | Inverted syntax with conditional expressions
In traditional syntax conditional expressions are usually shown before the action within a statement or code block:
IF raining=true THEN needumbrella=true
In inverted syntax, the action is listed before the conditional expression in the statement or code block:
needumb... | #PARI.2FGP | PARI/GP | fi(f, condition)=if(condition,f());
if(raining, print("Umbrella needed"))
fi(->print("Umbrella needed"), raining) |
http://rosettacode.org/wiki/Inverted_syntax | Inverted syntax | Inverted syntax with conditional expressions
In traditional syntax conditional expressions are usually shown before the action within a statement or code block:
IF raining=true THEN needumbrella=true
In inverted syntax, the action is listed before the conditional expression in the statement or code block:
needumb... | #Perl | Perl | if ($guess == 6) { print "Wow! Lucky Guess!"; }; # Traditional syntax
print 'Wow! Lucky Guess!' if $guess == 6; # Inverted syntax (note missing braces and parens)
unless ($guess == 6) { print "Sorry, your guess was wrong!"; } # Traditional syntax
print 'Huh! You Guessed Wrong!' unless $guess == 6; ... |
http://rosettacode.org/wiki/ISBN13_check_digit | ISBN13 check digit | Task
Validate the check digit of an ISBN-13 code:
Multiply every other digit by 3.
Add these numbers and the other digits.
Take the remainder of this number after division by 10.
If it is 0, the ISBN-13 check digit is correct.
Use the following codes for testing:
978-1734314502 (good)
... | #BCPL | BCPL | get "libhdr"
let checkISBN(s) = valof
$( let tally = 0
unless s%0 = 14 resultis false
unless s%4 = '-' resultis false
for i=1 to 3
$( let digit = s%i-'0'
test i rem 2 = 0
do tally := tally + 3 * digit
or tally := tally + digit
$)
for i=5 to 14
$( le... |
http://rosettacode.org/wiki/Jaro_similarity | Jaro similarity | The Jaro distance is a measure of edit distance between two strings; its inverse, called the Jaro similarity, is a measure of two strings' similarity: the higher the value, the more similar the strings are. The score is normalized such that 0 equates to no similarities and 1 is an exact match.
Definition
The... | #Delphi | Delphi | defmodule Jaro do
def distance(s, t) when is_binary(s) and is_binary(t), do:
distance(to_charlist(s), to_charlist(t))
def distance(x, x), do: 1.0
def distance(s, t) do
s_len = length(s)
t_len = length(t)
{s_matches, t_matches, matches} = matching(s, t, s_len, t_len)
if matches == 0 do
0.... |
http://rosettacode.org/wiki/Iterated_digits_squaring | Iterated digits squaring | If you add the square of the digits of a Natural number (an integer bigger than zero), you always end with either 1 or 89:
15 -> 26 -> 40 -> 16 -> 37 -> 58 -> 89
7 -> 49 -> 97 -> 130 -> 10 -> 1
An example in Python:
>>> step = lambda x: sum(int(d) ** 2 for d in str(x))
>>> iterate = lambda x: x if x in [1, 89] else i... | #BQN | BQN | +´1↓1≠ ⊏˜⍟(⌈2⋆⁼≠) ⥊+⌜´6⥊<ט↕10
856929 |
http://rosettacode.org/wiki/Iterated_digits_squaring | Iterated digits squaring | If you add the square of the digits of a Natural number (an integer bigger than zero), you always end with either 1 or 89:
15 -> 26 -> 40 -> 16 -> 37 -> 58 -> 89
7 -> 49 -> 97 -> 130 -> 10 -> 1
An example in Python:
>>> step = lambda x: sum(int(d) ** 2 for d in str(x))
>>> iterate = lambda x: x if x in [1, 89] else i... | #C | C | #include <stdio.h>
typedef unsigned long long ull;
int is89(int x)
{
while (1) {
int s = 0;
do s += (x%10)*(x%10); while ((x /= 10));
if (s == 89) return 1;
if (s == 1) return 0;
x = s;
}
}
int main(void)
{
// array bounds is sort of random here, it's big enough for 64bit unsigned.
ull sums[32*8... |
http://rosettacode.org/wiki/Isqrt_(integer_square_root)_of_X | Isqrt (integer square root) of X | Sometimes a function is needed to find the integer square root of X, where X can be a
real non─negative number.
Often X is actually a non─negative integer.
For the purposes of this task, X can be an integer or a real number, but if it
simplifies things in your computer programming language, assume... | #ALGOL-M | ALGOL-M |
BEGIN
% RETURN INTEGER SQUARE ROOT OF N %
INTEGER FUNCTION ISQRT(N);
INTEGER N;
BEGIN
INTEGER R1, R2;
R1 := N;
R2 := 1;
WHILE R1 > R2 DO
BEGIN
R1 := (R1+R2) / 2;
R2 := N / R1;
END;
ISQRT := R1;
END;
COMMENT - LET'S EXERCISE THE FUNCTION;
INTEGER I, COL... |
http://rosettacode.org/wiki/Isqrt_(integer_square_root)_of_X | Isqrt (integer square root) of X | Sometimes a function is needed to find the integer square root of X, where X can be a
real non─negative number.
Often X is actually a non─negative integer.
For the purposes of this task, X can be an integer or a real number, but if it
simplifies things in your computer programming language, assume... | #AppleScript | AppleScript | on isqrt(x)
set q to 1
repeat until (q > x)
set q to q * 4
end repeat
set z to x
set r to 0
repeat while (q > 1)
set q to q div 4
set t to z - r - q
set r to r div 2
if (t > -1) then
set z to t
set r to r + q
end if
end ... |
http://rosettacode.org/wiki/Josephus_problem | Josephus problem | Josephus problem is a math puzzle with a grim description:
n
{\displaystyle n}
prisoners are standing on a circle, sequentially numbered from
0
{\displaystyle 0}
to
n
−
1
{\displaystyle n-1}
.
An executioner walks along the circle, starting from prisoner
0
{\displaystyle 0}
,
removing eve... | #C.2B.2B | C++ |
#include <iostream>
#include <vector>
//--------------------------------------------------------------------------------------------------
using namespace std;
typedef unsigned long long bigint;
//--------------------------------------------------------------------------------------------------
class josephus
{
p... |
http://rosettacode.org/wiki/Inverted_syntax | Inverted syntax | Inverted syntax with conditional expressions
In traditional syntax conditional expressions are usually shown before the action within a statement or code block:
IF raining=true THEN needumbrella=true
In inverted syntax, the action is listed before the conditional expression in the statement or code block:
needumb... | #Phix | Phix | if end
(&"test.exw"[1]cl)system
then >2(cl)length if
(&"\n"(pgm)mung,"test.exw")write_file = {}
write_file.e include
([$]cl)get_text = pgm string
()command_line = cl sequence
function end
("\n",lines)join return
for end (nup,rip,((([i]lines)split)reverse)join)substitute_all = [i]lines do (lines)length to 1=i fo... |
http://rosettacode.org/wiki/Inverted_syntax | Inverted syntax | Inverted syntax with conditional expressions
In traditional syntax conditional expressions are usually shown before the action within a statement or code block:
IF raining=true THEN needumbrella=true
In inverted syntax, the action is listed before the conditional expression in the statement or code block:
needumb... | #PicoLisp | PicoLisp | (de rv Prg
(append (last Prg) (head -1 Prg)) ) |
http://rosettacode.org/wiki/ISBN13_check_digit | ISBN13 check digit | Task
Validate the check digit of an ISBN-13 code:
Multiply every other digit by 3.
Add these numbers and the other digits.
Take the remainder of this number after division by 10.
If it is 0, the ISBN-13 check digit is correct.
Use the following codes for testing:
978-1734314502 (good)
... | #C | C | #include <stdio.h>
int check_isbn13(const char *isbn) {
int ch = *isbn, count = 0, sum = 0;
/* check isbn contains 13 digits and calculate weighted sum */
for ( ; ch != 0; ch = *++isbn, ++count) {
/* skip hyphens or spaces */
if (ch == ' ' || ch == '-') {
--count;
c... |
http://rosettacode.org/wiki/Jaro_similarity | Jaro similarity | The Jaro distance is a measure of edit distance between two strings; its inverse, called the Jaro similarity, is a measure of two strings' similarity: the higher the value, the more similar the strings are. The score is normalized such that 0 equates to no similarities and 1 is an exact match.
Definition
The... | #Elixir | Elixir | defmodule Jaro do
def distance(s, t) when is_binary(s) and is_binary(t), do:
distance(to_charlist(s), to_charlist(t))
def distance(x, x), do: 1.0
def distance(s, t) do
s_len = length(s)
t_len = length(t)
{s_matches, t_matches, matches} = matching(s, t, s_len, t_len)
if matches == 0 do
0.... |
http://rosettacode.org/wiki/Iterated_digits_squaring | Iterated digits squaring | If you add the square of the digits of a Natural number (an integer bigger than zero), you always end with either 1 or 89:
15 -> 26 -> 40 -> 16 -> 37 -> 58 -> 89
7 -> 49 -> 97 -> 130 -> 10 -> 1
An example in Python:
>>> step = lambda x: sum(int(d) ** 2 for d in str(x))
>>> iterate = lambda x: x if x in [1, 89] else i... | #C.23 | C# | using System;
public static class IteratedDigitsSquaring
{
public static void Main() {
Console.WriteLine(Count89s(1_000_000));
Console.WriteLine(Count89s(100_000_000));
}
public static int Count89s(int limit) {
if (limit < 1) return 0;
int[] end = new int[Math.Min(limit, 9 ... |
http://rosettacode.org/wiki/Isqrt_(integer_square_root)_of_X | Isqrt (integer square root) of X | Sometimes a function is needed to find the integer square root of X, where X can be a
real non─negative number.
Often X is actually a non─negative integer.
For the purposes of this task, X can be an integer or a real number, but if it
simplifies things in your computer programming language, assume... | #APL | APL | i←{x←⍵
q←(×∘4)⍣{⍺>x}⊢1
⊃{ r z q←⍵
q←⌊q÷4
t←(z-r)-q
r←⌊r÷2
z←z t[1+t≥0]
r←r+q×t≥0
r z q
}⍣{ r z q←⍺
q≤1
}⊢0 x q
} |
http://rosettacode.org/wiki/Isqrt_(integer_square_root)_of_X | Isqrt (integer square root) of X | Sometimes a function is needed to find the integer square root of X, where X can be a
real non─negative number.
Often X is actually a non─negative integer.
For the purposes of this task, X can be an integer or a real number, but if it
simplifies things in your computer programming language, assume... | #Arturo | Arturo | commatize: function [x][
reverse join.with:"," map split.every: 3 split reverse to :string x => join
]
isqrt: function [x][
num: new x
q: new 1
r: new 0
while [q =< num]-> shl.safe 'q 2
while [q > 1][
shr 'q 2
t: (num-r)-q
shr 'r 1
if t >= 0 [
num:... |
http://rosettacode.org/wiki/Josephus_problem | Josephus problem | Josephus problem is a math puzzle with a grim description:
n
{\displaystyle n}
prisoners are standing on a circle, sequentially numbered from
0
{\displaystyle 0}
to
n
−
1
{\displaystyle n-1}
.
An executioner walks along the circle, starting from prisoner
0
{\displaystyle 0}
,
removing eve... | #Clojure | Clojure | (defn rotate [n s] (lazy-cat (drop n s) (take n s)))
(defn josephus [n k]
(letfn [(survivor [[ h & r :as l] k]
(cond (empty? r) h
:else (survivor (rest (rotate (dec k) l)) k)))]
(survivor (range n) k)))
(let [n 41 k 3]
(println (str "Given " n " prisoners in a circle... |
http://rosettacode.org/wiki/Inverted_syntax | Inverted syntax | Inverted syntax with conditional expressions
In traditional syntax conditional expressions are usually shown before the action within a statement or code block:
IF raining=true THEN needumbrella=true
In inverted syntax, the action is listed before the conditional expression in the statement or code block:
needumb... | #PowerShell | PowerShell |
if ((Get-Date 5/27/2016).DayOfWeek -eq "Friday") {"Thank God it's Friday!"}
|
http://rosettacode.org/wiki/Inverted_syntax | Inverted syntax | Inverted syntax with conditional expressions
In traditional syntax conditional expressions are usually shown before the action within a statement or code block:
IF raining=true THEN needumbrella=true
In inverted syntax, the action is listed before the conditional expression in the statement or code block:
needumb... | #Prolog | Prolog | % Dracula is a vampire.
% Also, you become a vampire if someone who is a vampire bites you.
vampire(dracula).
vampire(You) :- bites(Someone, You), vampire(Someone).
% Oh no! Dracula just bit Bob...
bites(dracula, bob). |
http://rosettacode.org/wiki/Inverted_syntax | Inverted syntax | Inverted syntax with conditional expressions
In traditional syntax conditional expressions are usually shown before the action within a statement or code block:
IF raining=true THEN needumbrella=true
In inverted syntax, the action is listed before the conditional expression in the statement or code block:
needumb... | #Python | Python | x = truevalue if condition else falsevalue |
http://rosettacode.org/wiki/ISBN13_check_digit | ISBN13 check digit | Task
Validate the check digit of an ISBN-13 code:
Multiply every other digit by 3.
Add these numbers and the other digits.
Take the remainder of this number after division by 10.
If it is 0, the ISBN-13 check digit is correct.
Use the following codes for testing:
978-1734314502 (good)
... | #C.2B.2B | C++ | #include <iostream>
bool check_isbn13(std::string isbn) {
int count = 0;
int sum = 0;
for (auto ch : isbn) {
/* skip hyphens or spaces */
if (ch == ' ' || ch == '-') {
continue;
}
if (ch < '0' || ch > '9') {
return false;
}
if (coun... |
http://rosettacode.org/wiki/Jaro_similarity | Jaro similarity | The Jaro distance is a measure of edit distance between two strings; its inverse, called the Jaro similarity, is a measure of two strings' similarity: the higher the value, the more similar the strings are. The score is normalized such that 0 equates to no similarities and 1 is an exact match.
Definition
The... | #F.23 | F# |
// Calculate Jaro distance of 2 strings. Nigel Galloway: August 7th., 2020
let fG n g=Seq.map2(fun n g->if g=1 then Some n else None) n g |> Seq.choose id
let J (n:string) (g:string)=
let s1,s2=n.Length,g.Length
let w,m1,m2=(max s1 s2)/2-1,Array.zeroCreate<int>s1,Array.zeroCreate<int>s2
g|>Seq.iteri(fun i g->ma... |
http://rosettacode.org/wiki/Iterated_digits_squaring | Iterated digits squaring | If you add the square of the digits of a Natural number (an integer bigger than zero), you always end with either 1 or 89:
15 -> 26 -> 40 -> 16 -> 37 -> 58 -> 89
7 -> 49 -> 97 -> 130 -> 10 -> 1
An example in Python:
>>> step = lambda x: sum(int(d) ** 2 for d in str(x))
>>> iterate = lambda x: x if x in [1, 89] else i... | #C.2B.2B | C++ |
#include <iostream>
// returns sum of squares of digits of n
unsigned int sum_square_digits(unsigned int n) {
int i,num=n,sum=0;
// process digits one at a time until there are none left
while (num > 0) {
// peal off the last digit from the number
int digit=nu... |
http://rosettacode.org/wiki/Isqrt_(integer_square_root)_of_X | Isqrt (integer square root) of X | Sometimes a function is needed to find the integer square root of X, where X can be a
real non─negative number.
Often X is actually a non─negative integer.
For the purposes of this task, X can be an integer or a real number, but if it
simplifies things in your computer programming language, assume... | #ATS | ATS | (*
Compile with "myatscc isqrt.dats", thus obtaining an executable called
"isqrt".
##myatsccdef=\
patscc -O2 \
-I"${PATSHOME}/contrib/atscntrb" \
-IATS "${PATSHOME}/contrib/atscntrb" \
-D_GNU_SOURCE -DATS_MEMALLOC_LIBC \
-o $fname($1) $1 -lgmp
*)
#include "share/atspre_staload.hats"
(* An interface to... |
http://rosettacode.org/wiki/Isqrt_(integer_square_root)_of_X | Isqrt (integer square root) of X | Sometimes a function is needed to find the integer square root of X, where X can be a
real non─negative number.
Often X is actually a non─negative integer.
For the purposes of this task, X can be an integer or a real number, but if it
simplifies things in your computer programming language, assume... | #BASIC256 | BASIC256 | print "Integer square root of first 65 numbers:"
for n = 1 to 65
print ljust(isqrt(n),3);
next n
print : print
print "Integer square root of odd powers of 7"
print " n 7^n isqrt"
print "-"*36
for n = 1 to 21 step 2
pow7 = int(7 ^ n)
print rjust(n,3);rjust(pow7,20);rjust(isqrt(pow7),12... |
http://rosettacode.org/wiki/Josephus_problem | Josephus problem | Josephus problem is a math puzzle with a grim description:
n
{\displaystyle n}
prisoners are standing on a circle, sequentially numbered from
0
{\displaystyle 0}
to
n
−
1
{\displaystyle n-1}
.
An executioner walks along the circle, starting from prisoner
0
{\displaystyle 0}
,
removing eve... | #Common_Lisp | Common Lisp | (defun kill (n k &aux (m 0))
(loop for a from (1+ m) upto n do
(setf m (mod (+ m k) a)))
m) |
http://rosettacode.org/wiki/Inverted_syntax | Inverted syntax | Inverted syntax with conditional expressions
In traditional syntax conditional expressions are usually shown before the action within a statement or code block:
IF raining=true THEN needumbrella=true
In inverted syntax, the action is listed before the conditional expression in the statement or code block:
needumb... | #Qi | Qi |
(define set-needumbrella
Raining -> (set needumbrella true) where (= true Raining)
Raining -> (set needumbrella false) where (= false Raining))
(define set-needumbrella
Raining -> (if (= true Raining)
(set needumbrella true)
(set needumbrella false)))
Alternatives:
(def... |
http://rosettacode.org/wiki/Inverted_syntax | Inverted syntax | Inverted syntax with conditional expressions
In traditional syntax conditional expressions are usually shown before the action within a statement or code block:
IF raining=true THEN needumbrella=true
In inverted syntax, the action is listed before the conditional expression in the statement or code block:
needumb... | #R | R | do.if <- function(expr, cond) if(cond) expr |
http://rosettacode.org/wiki/Inverted_syntax | Inverted syntax | Inverted syntax with conditional expressions
In traditional syntax conditional expressions are usually shown before the action within a statement or code block:
IF raining=true THEN needumbrella=true
In inverted syntax, the action is listed before the conditional expression in the statement or code block:
needumb... | #Racket | Racket |
#lang racket
(when #t (displayln "true"))
((displayln "true") . when . #t)
(define a 6)
(set! a 5)
(a . set! . 6)
|
http://rosettacode.org/wiki/Inverted_syntax | Inverted syntax | Inverted syntax with conditional expressions
In traditional syntax conditional expressions are usually shown before the action within a statement or code block:
IF raining=true THEN needumbrella=true
In inverted syntax, the action is listed before the conditional expression in the statement or code block:
needumb... | #Raku | Raku | if $guess == 6 { say "Wow! Lucky Guess!" } # Traditional
say 'Wow! Lucky Guess!' if $guess == 6; # Inverted
unless $guess == 6 { say "Huh! You Guessed Rong!" } # Traditional
say 'Huh! You Guessed Rong!' unless $guess == 6; # Inverted |
http://rosettacode.org/wiki/ISBN13_check_digit | ISBN13 check digit | Task
Validate the check digit of an ISBN-13 code:
Multiply every other digit by 3.
Add these numbers and the other digits.
Take the remainder of this number after division by 10.
If it is 0, the ISBN-13 check digit is correct.
Use the following codes for testing:
978-1734314502 (good)
... | #C.23 | C# | using System;
using System.Linq;
public class Program
{
public static void Main() {
Console.WriteLine(CheckISBN13("978-1734314502"));
Console.WriteLine(CheckISBN13("978-1734314509"));
Console.WriteLine(CheckISBN13("978-1788399081"));
Console.WriteLine(CheckISBN13("978-1788399083"))... |
http://rosettacode.org/wiki/Jaro_similarity | Jaro similarity | The Jaro distance is a measure of edit distance between two strings; its inverse, called the Jaro similarity, is a measure of two strings' similarity: the higher the value, the more similar the strings are. The score is normalized such that 0 equates to no similarities and 1 is an exact match.
Definition
The... | #Factor | Factor | USING: formatting fry generalizations kernel locals make math
math.order sequences sequences.extras ;
IN: rosetta-code.jaro-distance
: match? ( s1 s2 n -- ? )
[ pick nth swap indices nip ] [ 2nip ]
[ drop [ length ] bi@ max 2/ 1 - ] 3tri
'[ _ - abs _ <= ] any? ;
: matches ( s1 s2 -- seq )
over lengt... |
http://rosettacode.org/wiki/Iterated_digits_squaring | Iterated digits squaring | If you add the square of the digits of a Natural number (an integer bigger than zero), you always end with either 1 or 89:
15 -> 26 -> 40 -> 16 -> 37 -> 58 -> 89
7 -> 49 -> 97 -> 130 -> 10 -> 1
An example in Python:
>>> step = lambda x: sum(int(d) ** 2 for d in str(x))
>>> iterate = lambda x: x if x in [1, 89] else i... | #Ceylon | Ceylon | shared void run() {
function digitsSquaredSum(variable Integer n) {
variable value total = 0;
while(n > 0) {
total += (n % 10) ^ 2;
n /= 10;
}
return total;
}
function lastSum(variable Integer n) {
while(true) {
n = digitsSquaredSum(n);
if(n == 89 || n == 1) {
return n;
}
}
}
v... |
http://rosettacode.org/wiki/Iterated_digits_squaring | Iterated digits squaring | If you add the square of the digits of a Natural number (an integer bigger than zero), you always end with either 1 or 89:
15 -> 26 -> 40 -> 16 -> 37 -> 58 -> 89
7 -> 49 -> 97 -> 130 -> 10 -> 1
An example in Python:
>>> step = lambda x: sum(int(d) ** 2 for d in str(x))
>>> iterate = lambda x: x if x in [1, 89] else i... | #Clojure | Clojure | (ns async-example.core
(:require [clojure.math.numeric-tower :as math])
(:use [criterium.core])
(:gen-class))
(defn sum-sqr [digits]
" Square sum of list of digits "
(let [digits-sqr (fn [n]
(apply + (map #(* % %) digits)))]
(digits-sqr digits)))
(defn get-digits [n]
" Converts a ... |
http://rosettacode.org/wiki/Isqrt_(integer_square_root)_of_X | Isqrt (integer square root) of X | Sometimes a function is needed to find the integer square root of X, where X can be a
real non─negative number.
Often X is actually a non─negative integer.
For the purposes of this task, X can be an integer or a real number, but if it
simplifies things in your computer programming language, assume... | #C | C | #include <stdint.h>
#include <stdio.h>
int64_t isqrt(int64_t x) {
int64_t q = 1, r = 0;
while (q <= x) {
q <<= 2;
}
while (q > 1) {
int64_t t;
q >>= 2;
t = x - r - q;
r >>= 1;
if (t >= 0) {
x = t;
r += q;
}
}
retur... |
http://rosettacode.org/wiki/Josephus_problem | Josephus problem | Josephus problem is a math puzzle with a grim description:
n
{\displaystyle n}
prisoners are standing on a circle, sequentially numbered from
0
{\displaystyle 0}
to
n
−
1
{\displaystyle n-1}
.
An executioner walks along the circle, starting from prisoner
0
{\displaystyle 0}
,
removing eve... | #Crystal | Crystal | n = ARGV.fetch(0, 41).to_i # n default is 41 or ARGV[0]
k = ARGV.fetch(1, 3).to_i # k default is 3 or ARGV[1]
prisoners = (0...n).to_a
while prisoners.size > 1; prisoners.rotate!(k-1).shift end
puts "From #{n} prisoners, eliminating each prisoner #{k} leaves prisoner #{prisoners.first}."
|
http://rosettacode.org/wiki/Inverted_syntax | Inverted syntax | Inverted syntax with conditional expressions
In traditional syntax conditional expressions are usually shown before the action within a statement or code block:
IF raining=true THEN needumbrella=true
In inverted syntax, the action is listed before the conditional expression in the statement or code block:
needumb... | #REXX | REXX | SIGNAL {ON|OFF} someCondition {name}
|
http://rosettacode.org/wiki/Inverted_syntax | Inverted syntax | Inverted syntax with conditional expressions
In traditional syntax conditional expressions are usually shown before the action within a statement or code block:
IF raining=true THEN needumbrella=true
In inverted syntax, the action is listed before the conditional expression in the statement or code block:
needumb... | #Ruby | Ruby | # Raise ArgumentError if n is negative.
if n < 0 then raise ArgumentError, "negative n" end
raise ArgumentError, "negative n" if n < 0
# Exit 1 unless we can call Process.fork.
unless Process.respond_to? :fork then exit 1 end
exit 1 unless Process.respond_to? :fork
# Empty an array, printing each element.
while ary... |
http://rosettacode.org/wiki/Inverted_syntax | Inverted syntax | Inverted syntax with conditional expressions
In traditional syntax conditional expressions are usually shown before the action within a statement or code block:
IF raining=true THEN needumbrella=true
In inverted syntax, the action is listed before the conditional expression in the statement or code block:
needumb... | #Scala | Scala | object Main extends App {
val raining = true
val needUmbrella = raining
println(s"Do I need an umbrella? ${if (needUmbrella) "Yes" else "No"}")
} |
http://rosettacode.org/wiki/ISBN13_check_digit | ISBN13 check digit | Task
Validate the check digit of an ISBN-13 code:
Multiply every other digit by 3.
Add these numbers and the other digits.
Take the remainder of this number after division by 10.
If it is 0, the ISBN-13 check digit is correct.
Use the following codes for testing:
978-1734314502 (good)
... | #CLU | CLU | isbn13_check = proc (s: string) returns (bool)
if string$size(s) ~= 14 then return(false) end
if s[4] ~= '-' then return(false) end
begin
check: int := 0
for i: int in int$from_to(1, 14) do
if i=4 then continue end
d: int := int$parse(string$c2s(s[i]))
if ... |
http://rosettacode.org/wiki/ISBN13_check_digit | ISBN13 check digit | Task
Validate the check digit of an ISBN-13 code:
Multiply every other digit by 3.
Add these numbers and the other digits.
Take the remainder of this number after division by 10.
If it is 0, the ISBN-13 check digit is correct.
Use the following codes for testing:
978-1734314502 (good)
... | #COBOL | COBOL | ******************************************************************
* Author: Jay Moseley
* Date: November 10, 2019
* Purpose: Testing various subprograms/ functions.
* Tectonics: cobc -xj testSubs.cbl
******************************************************************
IDENTIFIC... |
http://rosettacode.org/wiki/Jaro_similarity | Jaro similarity | The Jaro distance is a measure of edit distance between two strings; its inverse, called the Jaro similarity, is a measure of two strings' similarity: the higher the value, the more similar the strings are. The score is normalized such that 0 equates to no similarities and 1 is an exact match.
Definition
The... | #FreeBASIC | FreeBASIC | ' version 09-10-2016
' compile with: fbc -s console
#Macro max(x, y)
IIf((x) > (y), (x), (y))
#EndMacro
#Macro min(x, y)
IIf((x) < (y), (x), (y))
#EndMacro
Function jaro(word1 As String, word2 As String) As Double
If Len(word1) > Len(word2) Then Swap word1, word2
Dim As Long i, j, j1, m, t
Dim As Lo... |
http://rosettacode.org/wiki/Iterated_digits_squaring | Iterated digits squaring | If you add the square of the digits of a Natural number (an integer bigger than zero), you always end with either 1 or 89:
15 -> 26 -> 40 -> 16 -> 37 -> 58 -> 89
7 -> 49 -> 97 -> 130 -> 10 -> 1
An example in Python:
>>> step = lambda x: sum(int(d) ** 2 for d in str(x))
>>> iterate = lambda x: x if x in [1, 89] else i... | #Common_Lisp | Common Lisp |
(defun square (number)
(expt number 2))
(defun list-digits (number)
"Return the `number' as a list of its digits."
(loop
:for (rest digit) := (multiple-value-list (truncate number 10))
:then (multiple-value-list (truncate rest 10))
:collect digit
:until (zerop rest)))
(defu... |
http://rosettacode.org/wiki/Isqrt_(integer_square_root)_of_X | Isqrt (integer square root) of X | Sometimes a function is needed to find the integer square root of X, where X can be a
real non─negative number.
Often X is actually a non─negative integer.
For the purposes of this task, X can be an integer or a real number, but if it
simplifies things in your computer programming language, assume... | #C.2B.2B | C++ | #include <iomanip>
#include <iostream>
#include <sstream>
#include <boost/multiprecision/cpp_int.hpp>
using big_int = boost::multiprecision::cpp_int;
template <typename integer>
integer isqrt(integer x) {
integer q = 1;
while (q <= x)
q <<= 2;
integer r = 0;
while (q > 1) {
q >>= 2;
... |
http://rosettacode.org/wiki/Josephus_problem | Josephus problem | Josephus problem is a math puzzle with a grim description:
n
{\displaystyle n}
prisoners are standing on a circle, sequentially numbered from
0
{\displaystyle 0}
to
n
−
1
{\displaystyle n-1}
.
An executioner walks along the circle, starting from prisoner
0
{\displaystyle 0}
,
removing eve... | #D | D | import std.stdio, std.algorithm, std.array, std.string, std.range;
T pop(T)(ref T[] items, in size_t i) pure /*nothrow*/ @safe /*@nogc*/ {
auto aux = items[i];
items = items.remove(i);
return aux;
}
string josephus(in int n, in int k) pure /*nothrow*/ @safe {
auto p = n.iota.array;
int i;
im... |
http://rosettacode.org/wiki/Inverted_syntax | Inverted syntax | Inverted syntax with conditional expressions
In traditional syntax conditional expressions are usually shown before the action within a statement or code block:
IF raining=true THEN needumbrella=true
In inverted syntax, the action is listed before the conditional expression in the statement or code block:
needumb... | #Sidef | Sidef | # Inverted syntax with assignment
var raining = true;
[false]»(\var needumbrella);
# Inverted syntax with conditional expressions
if (raining==true) {needumbrella=true};
{needumbrella=true} -> if (raining==true);
(needumbrella=true) if (raining==true); |
http://rosettacode.org/wiki/Inverted_syntax | Inverted syntax | Inverted syntax with conditional expressions
In traditional syntax conditional expressions are usually shown before the action within a statement or code block:
IF raining=true THEN needumbrella=true
In inverted syntax, the action is listed before the conditional expression in the statement or code block:
needumb... | #Swift | Swift | infix operator ~= {}
infix operator ! {}
func ~=(lhs:Int, inout rhs:Int) {
rhs = lhs
}
func !(lhs:(() -> Void), rhs:Bool) {
if (rhs) {
lhs()
}
}
// Traditional assignment
var a = 0
// Inverted using a custom operator
20 ~= a
let raining = true
let tornado = true
var needUmbrella = false
va... |
http://rosettacode.org/wiki/Inverted_syntax | Inverted syntax | Inverted syntax with conditional expressions
In traditional syntax conditional expressions are usually shown before the action within a statement or code block:
IF raining=true THEN needumbrella=true
In inverted syntax, the action is listed before the conditional expression in the statement or code block:
needumb... | #Tcl | Tcl |
# do.tcl --
#
# Tcl implementation of a "do ... while|until" loop.
#
# Originally written for the "Texas Tcl Shootout" programming contest
# at the 2000 Tcl Conference in Austin/Texas.
#
# Copyright (c) 2001 by Reinhard Max <Reinhard.Max@gmx.de>
#
# See the file "license.terms" for information on usage and red... |
http://rosettacode.org/wiki/Intersecting_number_wheels | Intersecting number wheels | A number wheel has:
A name which is an uppercase letter.
A set of ordered values which are either numbers or names.
A number is generated/yielded from a named wheel by:
1. Starting at the first value of the named wheel and advancing through subsequent values and wrapping around to the first value to form a "wheel"... | #11l | 11l | F nextfrom(&w, =name)
L
V nxt = w[name][0]
w[name] = w[name][1..] + w[name][0.<1]
I nxt[0] C ‘0’..‘9’
R nxt
name = nxt
L(group) |‘A: 1 2 3
A: 1 B 2; B: 3 4
A: 1 D D; D: 6 7 8
A: 1 B C; B: 3 4; C: 5 B’.split("\n")
print("Intersecting Number Wheel ... |
http://rosettacode.org/wiki/Interactive_programming_(repl) | Interactive programming (repl) | Many language implementations come with an interactive mode.
This is a command-line interpreter that reads lines from the user and evaluates these lines as statements or expressions.
An interactive mode may also be known as a command mode, a read-eval-print loop (REPL), or a shell.
Task
Show how to start this... | #8th | 8th | $ 8th
8th 1.0.2 Linux 64 (f1b7a8c2)
ok>
|
http://rosettacode.org/wiki/ISBN13_check_digit | ISBN13 check digit | Task
Validate the check digit of an ISBN-13 code:
Multiply every other digit by 3.
Add these numbers and the other digits.
Take the remainder of this number after division by 10.
If it is 0, the ISBN-13 check digit is correct.
Use the following codes for testing:
978-1734314502 (good)
... | #Cowgol | Cowgol | include "cowgol.coh";
sub check_isbn13(isbn: [uint8]): (r: uint8) is
var n: uint8 := 0;
r := 0;
loop
var c := [isbn];
isbn := @next isbn;
if c == 0 then break; end if;
c := c - '0';
if c <= 9 then
r := r + c;
n := n + 1;
if ... |
http://rosettacode.org/wiki/ISBN13_check_digit | ISBN13 check digit | Task
Validate the check digit of an ISBN-13 code:
Multiply every other digit by 3.
Add these numbers and the other digits.
Take the remainder of this number after division by 10.
If it is 0, the ISBN-13 check digit is correct.
Use the following codes for testing:
978-1734314502 (good)
... | #D | D | import std.stdio;
bool isValidISBN13(string text) {
int sum, i;
foreach (c; text) {
if ('0' <= c && c <= '9') {
int value = c - '0';
if (i % 2 == 0) {
sum += value;
} else {
sum += 3 * value;
}
i++;
}... |
http://rosettacode.org/wiki/Jaro_similarity | Jaro similarity | The Jaro distance is a measure of edit distance between two strings; its inverse, called the Jaro similarity, is a measure of two strings' similarity: the higher the value, the more similar the strings are. The score is normalized such that 0 equates to no similarities and 1 is an exact match.
Definition
The... | #Go | Go | package main
import "fmt"
func jaro(str1, str2 string) float64 {
if len(str1) == 0 && len(str2) == 0 {
return 1
}
if len(str1) == 0 || len(str2) == 0 {
return 0
}
match_distance := len(str1)
if len(str2) > match_distance {
match_distance = len(str2)
}
match_di... |
http://rosettacode.org/wiki/Iterated_digits_squaring | Iterated digits squaring | If you add the square of the digits of a Natural number (an integer bigger than zero), you always end with either 1 or 89:
15 -> 26 -> 40 -> 16 -> 37 -> 58 -> 89
7 -> 49 -> 97 -> 130 -> 10 -> 1
An example in Python:
>>> step = lambda x: sum(int(d) ** 2 for d in str(x))
>>> iterate = lambda x: x if x in [1, 89] else i... | #D | D | import std.stdio, std.algorithm, std.range, std.functional;
uint step(uint x) pure nothrow @safe @nogc {
uint total = 0;
while (x) {
total += (x % 10) ^^ 2;
x /= 10;
}
return total;
}
uint iterate(in uint x) nothrow @safe {
return (x == 89 || x == 1) ? x : x.step.memoize!iterate;... |
http://rosettacode.org/wiki/Isqrt_(integer_square_root)_of_X | Isqrt (integer square root) of X | Sometimes a function is needed to find the integer square root of X, where X can be a
real non─negative number.
Often X is actually a non─negative integer.
For the purposes of this task, X can be an integer or a real number, but if it
simplifies things in your computer programming language, assume... | #C.23 | C# | using System;
using static System.Console;
using BI = System.Numerics.BigInteger;
class Program {
static BI isqrt(BI x) { BI q = 1, r = 0, t; while (q <= x) q <<= 2; while (q > 1) {
q >>= 2; t = x - r - q; r >>= 1; if (t >= 0) { x = t; r += q; } } return r; }
static void Main() { const int max = 7... |
http://rosettacode.org/wiki/Josephus_problem | Josephus problem | Josephus problem is a math puzzle with a grim description:
n
{\displaystyle n}
prisoners are standing on a circle, sequentially numbered from
0
{\displaystyle 0}
to
n
−
1
{\displaystyle n-1}
.
An executioner walks along the circle, starting from prisoner
0
{\displaystyle 0}
,
removing eve... | #EchoLisp | EchoLisp |
;; input
(define N 41)
(define K 3)
(define prisoners (apply circular-list (iota N)))
(define last-one prisoners) ; current position
;; kill returns current position = last killed
(define (kill lst skip)
(cond
((eq? (mark? lst) '🔫 )(kill (cdr lst) skip)) ;; dead ? goto next
((zero? skip) (mark lst '🔫)) ;;... |
http://rosettacode.org/wiki/Inverted_syntax | Inverted syntax | Inverted syntax with conditional expressions
In traditional syntax conditional expressions are usually shown before the action within a statement or code block:
IF raining=true THEN needumbrella=true
In inverted syntax, the action is listed before the conditional expression in the statement or code block:
needumb... | #TI-83_BASIC | TI-83 BASIC | 536→N |
http://rosettacode.org/wiki/Inverted_syntax | Inverted syntax | Inverted syntax with conditional expressions
In traditional syntax conditional expressions are usually shown before the action within a statement or code block:
IF raining=true THEN needumbrella=true
In inverted syntax, the action is listed before the conditional expression in the statement or code block:
needumb... | #Wortel | Wortel | ; a = expr
:a expr
; expr = a
~:expr a
; if cond expr
@if cond expr
; if expr cond
~@if expr cond |
http://rosettacode.org/wiki/Inverted_syntax | Inverted syntax | Inverted syntax with conditional expressions
In traditional syntax conditional expressions are usually shown before the action within a statement or code block:
IF raining=true THEN needumbrella=true
In inverted syntax, the action is listed before the conditional expression in the statement or code block:
needumb... | #Wren | Wren | class IBool {
construct new(b) {
if (!(b is Bool)) Fiber.abort("B must be a boolean")
_b = b
}
iff(cond) { cond ? _b : !_b }
}
var itrue = IBool.new(true)
var needUmbrella
var raining = true
// normal syntax
if (raining) needUmbrella = true
System.print("Is it raining? %(raining). Do... |
http://rosettacode.org/wiki/Intersecting_number_wheels | Intersecting number wheels | A number wheel has:
A name which is an uppercase letter.
A set of ordered values which are either numbers or names.
A number is generated/yielded from a named wheel by:
1. Starting at the first value of the named wheel and advancing through subsequent values and wrapping around to the first value to form a "wheel"... | #ALGOL_68 | ALGOL 68 | BEGIN
# a number wheel element #
MODE NWELEMENT = UNION( CHAR # wheel name #, INT # wheel value # );
# a number wheel #
MODE NW = STRUCT( CHAR name, REF INT position, FLEX[ 1 : 0 ]NWELEMENT values )... |
http://rosettacode.org/wiki/Interactive_programming_(repl) | Interactive programming (repl) | Many language implementations come with an interactive mode.
This is a command-line interpreter that reads lines from the user and evaluates these lines as statements or expressions.
An interactive mode may also be known as a command mode, a read-eval-print loop (REPL), or a shell.
Task
Show how to start this... | #ACL2 | ACL2 | $ acl2
Welcome to Clozure Common Lisp Version 1.7-r14925M (DarwinX8664)!
ACL2 Version 4.3 built September 8, 2011 09:08:23.
Copyright (C) 2011 University of Texas at Austin
ACL2 comes with ABSOLUTELY NO WARRANTY. This is free software and you
are welcome to redistribute it under certain conditions. For detail... |
http://rosettacode.org/wiki/Interactive_programming_(repl) | Interactive programming (repl) | Many language implementations come with an interactive mode.
This is a command-line interpreter that reads lines from the user and evaluates these lines as statements or expressions.
An interactive mode may also be known as a command mode, a read-eval-print loop (REPL), or a shell.
Task
Show how to start this... | #Arturo | Arturo | ➜ $ arturo
Arturo
(c) 2019-2021 Yanis Zafirópulos
# v/0.9.6.5 b/1097 @ 2021-02-09T16:40:43+01:00
# arch: amd64/macosx
# Type info 'symbol for info about a specific symbol or built-in function
# Type help to get a list of all available functions with a short description
# For multi-line input, just add a blank spac... |
http://rosettacode.org/wiki/ISBN13_check_digit | ISBN13 check digit | Task
Validate the check digit of an ISBN-13 code:
Multiply every other digit by 3.
Add these numbers and the other digits.
Take the remainder of this number after division by 10.
If it is 0, the ISBN-13 check digit is correct.
Use the following codes for testing:
978-1734314502 (good)
... | #Draco | Draco | proc nonrec isbn13_check(*char isbn) bool:
byte n, check, d;
char cur;
bool ok;
n := 0;
check := 0;
ok := true;
while
cur := isbn*;
isbn := isbn + 1;
ok and cur ~= '\e'
do
if n=3 then
if cur ~= '-' then ok := false fi
elif cur<'0' or cu... |
http://rosettacode.org/wiki/Jaro_similarity | Jaro similarity | The Jaro distance is a measure of edit distance between two strings; its inverse, called the Jaro similarity, is a measure of two strings' similarity: the higher the value, the more similar the strings are. The score is normalized such that 0 equates to no similarities and 1 is an exact match.
Definition
The... | #Haskell | Haskell | import Data.List (elemIndex, intercalate, sortOn)
import Data.Maybe (mapMaybe)
import Text.Printf (printf)
---------------------- JARO DISTANCE ---------------------
jaro :: Ord a => [a] -> [a] -> Float
jaro x y
| 0 == m = 0
| otherwise =
(1 / 3)
* ( (m / s1) + (m / s2) + ((m - t) / m))
where
f ... |
http://rosettacode.org/wiki/Iterated_digits_squaring | Iterated digits squaring | If you add the square of the digits of a Natural number (an integer bigger than zero), you always end with either 1 or 89:
15 -> 26 -> 40 -> 16 -> 37 -> 58 -> 89
7 -> 49 -> 97 -> 130 -> 10 -> 1
An example in Python:
>>> step = lambda x: sum(int(d) ** 2 for d in str(x))
>>> iterate = lambda x: x if x in [1, 89] else i... | #ERRE | ERRE |
PROGRAM ITERATION
BEGIN
PRINT(CHR$(12);) ! CLS
INPUT(N)
LOOP
N$=MID$(STR$(N),2)
S=0
FOR I=1 TO LEN(N$) DO
A=VAL(MID$(N$,I,1))
S=S+A*A
END FOR
IF S=89 OR S=1 THEN PRINT(S;) EXIT END IF
PRINT(S;)
N=S
END LOOP
PRINT
END PROGRAM
|
http://rosettacode.org/wiki/Iterated_digits_squaring | Iterated digits squaring | If you add the square of the digits of a Natural number (an integer bigger than zero), you always end with either 1 or 89:
15 -> 26 -> 40 -> 16 -> 37 -> 58 -> 89
7 -> 49 -> 97 -> 130 -> 10 -> 1
An example in Python:
>>> step = lambda x: sum(int(d) ** 2 for d in str(x))
>>> iterate = lambda x: x if x in [1, 89] else i... | #Factor | Factor | USING: kernel math math.ranges math.text.utils memoize
prettyprint sequences tools.time ;
IN: rosetta-code.iterated-digits-squaring
: sum-digit-sq ( n -- m ) 1 digit-groups [ sq ] map-sum ;
MEMO: 1or89 ( n -- m )
[ dup [ 1 = ] [ 89 = ] bi or ] [ sum-digit-sq ] until ;
[
0 1
[
dup sum-digit-sq ... |
http://rosettacode.org/wiki/Isqrt_(integer_square_root)_of_X | Isqrt (integer square root) of X | Sometimes a function is needed to find the integer square root of X, where X can be a
real non─negative number.
Often X is actually a non─negative integer.
For the purposes of this task, X can be an integer or a real number, but if it
simplifies things in your computer programming language, assume... | #CLU | CLU | % This program uses the 'bigint' cluster from PCLU's 'misc.lib'
% Integer square root of a bigint
isqrt = proc (x: bigint) returns (bigint)
% Initialize a couple of bigints we will reuse
own zero: bigint := bigint$i2bi(0)
own one: bigint := bigint$i2bi(1)
own two: bigint := bigint$i2bi(2)
own four... |
http://rosettacode.org/wiki/Isqrt_(integer_square_root)_of_X | Isqrt (integer square root) of X | Sometimes a function is needed to find the integer square root of X, where X can be a
real non─negative number.
Often X is actually a non─negative integer.
For the purposes of this task, X can be an integer or a real number, but if it
simplifies things in your computer programming language, assume... | #Common_Lisp | Common Lisp | #!/bin/sh
#|-*- mode:lisp -*-|#
#|
exec ros -Q -- $0 "$@"
|#
(progn ;;init forms
(ros:ensure-asdf)
#+quicklisp(ql:quickload '() :silent t)
)
(defpackage :ros.script.isqrt.3860764029
(:use :cl))
(in-package :ros.script.isqrt.3860764029)
;;
;; The Rosetta Code integer square root task, in Common Lisp.
;;
;; I... |
http://rosettacode.org/wiki/Josephus_problem | Josephus problem | Josephus problem is a math puzzle with a grim description:
n
{\displaystyle n}
prisoners are standing on a circle, sequentially numbered from
0
{\displaystyle 0}
to
n
−
1
{\displaystyle n-1}
.
An executioner walks along the circle, starting from prisoner
0
{\displaystyle 0}
,
removing eve... | #Eiffel | Eiffel |
class
APPLICATION
create
make
feature
make
do
io.put_string ("Survivor is prisoner: " + execute (12, 4).out)
end
execute (n, k: INTEGER): INTEGER
-- Survivor of 'n' prisoners, when every 'k'th is executed.
require
n_positive: n > 0
k_positive: k > 0
n_larger: n > k
local
killidx:... |
http://rosettacode.org/wiki/Inverted_syntax | Inverted syntax | Inverted syntax with conditional expressions
In traditional syntax conditional expressions are usually shown before the action within a statement or code block:
IF raining=true THEN needumbrella=true
In inverted syntax, the action is listed before the conditional expression in the statement or code block:
needumb... | #Z80_Assembly | Z80 Assembly | byte &EF,&BE
word &BEEF |
http://rosettacode.org/wiki/Inverted_syntax | Inverted syntax | Inverted syntax with conditional expressions
In traditional syntax conditional expressions are usually shown before the action within a statement or code block:
IF raining=true THEN needumbrella=true
In inverted syntax, the action is listed before the conditional expression in the statement or code block:
needumb... | #zkl | zkl | if (raining==True) needumbrella:=True;
(raining==True) : if (_) needumbrella:=True; |
http://rosettacode.org/wiki/Intersecting_number_wheels | Intersecting number wheels | A number wheel has:
A name which is an uppercase letter.
A set of ordered values which are either numbers or names.
A number is generated/yielded from a named wheel by:
1. Starting at the first value of the named wheel and advancing through subsequent values and wrapping around to the first value to form a "wheel"... | #AutoHotkey | AutoHotkey | obj1 := {"A":[1, 2, 3]}
obj2 := {"A":[1, "B", 2] , "B":[3, 4]}
obj3 := {"A":[1, "D", "D"] , "D":[6, 7, 8]}
obj4 := {"A":[1, "B", "C"] , "B":[3, 4] , "C":[5, "B"]}
loop 4
{
str := ""
for k, v in obj%A_Index% {
str .= "{" k " : "
for i, t in v
str .= t ","
str := Trim(str, ",") "}, "
}
str := Trim(str, ",... |
http://rosettacode.org/wiki/Interactive_programming_(repl) | Interactive programming (repl) | Many language implementations come with an interactive mode.
This is a command-line interpreter that reads lines from the user and evaluates these lines as statements or expressions.
An interactive mode may also be known as a command mode, a read-eval-print loop (REPL), or a shell.
Task
Show how to start this... | #BASIC | BASIC | 10 DEF FN f$(a$, b$, s$) = a$+s$+s$+b$
PRINT FN f$("Rosetta", "Code", ":") |
http://rosettacode.org/wiki/Interactive_programming_(repl) | Interactive programming (repl) | Many language implementations come with an interactive mode.
This is a command-line interpreter that reads lines from the user and evaluates these lines as statements or expressions.
An interactive mode may also be known as a command mode, a read-eval-print loop (REPL), or a shell.
Task
Show how to start this... | #Batch_File | Batch File | >set r=Rosetta
>set c=Code
>set s=:
>echo %r%%s%%s%%c%
Rosetta::Code
> |
http://rosettacode.org/wiki/ISBN13_check_digit | ISBN13 check digit | Task
Validate the check digit of an ISBN-13 code:
Multiply every other digit by 3.
Add these numbers and the other digits.
Take the remainder of this number after division by 10.
If it is 0, the ISBN-13 check digit is correct.
Use the following codes for testing:
978-1734314502 (good)
... | #Excel | Excel | ISBN13Check
=LAMBDA(s,
LET(
ns, FILTERP(
LAMBDA(v,
NOT(ISERROR(v))
)
)(
VALUE(CHARSROW(s))
),
ixs, SEQUENCE(
1, COLUMNS(ns),
1, 1
),
0 = MOD(
SUM(
IF(0 <> MOD(ixs... |
http://rosettacode.org/wiki/Jaro_similarity | Jaro similarity | The Jaro distance is a measure of edit distance between two strings; its inverse, called the Jaro similarity, is a measure of two strings' similarity: the higher the value, the more similar the strings are. The score is normalized such that 0 equates to no similarities and 1 is an exact match.
Definition
The... | #Haxe | Haxe | class Jaro {
private static function jaro(s1: String, s2: String): Float {
var s1_len = s1.length;
var s2_len = s2.length;
if (s1_len == 0 && s2_len == 0) return 1;
var match_distance = Std.int(Math.max(s1_len, s2_len)) / 2 - 1;
var matches = { s1: [for(n in 0...s1_len) fa... |
http://rosettacode.org/wiki/Iterated_digits_squaring | Iterated digits squaring | If you add the square of the digits of a Natural number (an integer bigger than zero), you always end with either 1 or 89:
15 -> 26 -> 40 -> 16 -> 37 -> 58 -> 89
7 -> 49 -> 97 -> 130 -> 10 -> 1
An example in Python:
>>> step = lambda x: sum(int(d) ** 2 for d in str(x))
>>> iterate = lambda x: x if x in [1, 89] else i... | #Forth | Forth |
Tested for VFX Forth and GForth in Linux
\ To explain the algorithm: Each iteration is performed in set-count-sumsq below.
\ sum square of digits for 1 digit numbers are
\ Base 1 2 3 4 5 6 7 8 9
\ Sumsq: 1 4 9 16 25 36 49 54 81
\ Adding 10 to the base adds 1 to the sumsq,
\ Adding 20 to the base adds... |
http://rosettacode.org/wiki/Iterated_digits_squaring | Iterated digits squaring | If you add the square of the digits of a Natural number (an integer bigger than zero), you always end with either 1 or 89:
15 -> 26 -> 40 -> 16 -> 37 -> 58 -> 89
7 -> 49 -> 97 -> 130 -> 10 -> 1
An example in Python:
>>> step = lambda x: sum(int(d) ** 2 for d in str(x))
>>> iterate = lambda x: x if x in [1, 89] else i... | #FreeBASIC | FreeBASIC | ' FB 1.05.0 Win64
' similar to C Language (first approach)
' timing for i3 @ 2.13 GHz
Function endsWith89(n As Integer) As Boolean
Dim As Integer digit, sum = 0
Do
While n > 0
digit = n Mod 10
sum += digit * digit
n \= 10
Wend
If sum = 89 Then Return True
If sum = 1 Then Return... |
http://rosettacode.org/wiki/Isqrt_(integer_square_root)_of_X | Isqrt (integer square root) of X | Sometimes a function is needed to find the integer square root of X, where X can be a
real non─negative number.
Often X is actually a non─negative integer.
For the purposes of this task, X can be an integer or a real number, but if it
simplifies things in your computer programming language, assume... | #Cowgol | Cowgol | include "cowgol.coh";
# Integer square root
sub isqrt(x: uint32): (x0: uint32) is
x0 := x >> 1;
if x0 == 0 then
x0 := x;
return;
end if;
loop
var x1 := (x0 + x/x0) >> 1;
if x1 >= x0 then
break;
end if;
x0 := x1;
end loop;
end sub;
#... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.