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/Jacobsthal_numbers | Jacobsthal numbers | Jacobsthal numbers are an integer sequence related to Fibonacci numbers. Similar to Fibonacci, where each term is the sum of the previous two terms, each term is the sum of the previous, plus twice the one before that. Traditionally the sequence starts with the given terms 0, 1.
J0 = 0
J1 = 1
Jn = Jn-1 + 2 ×... | #Perl | Perl | use strict;
use warnings;
use feature <say state>;
use bigint;
use List::Util 'max';
use ntheory 'is_prime';
sub table { my $t = 5 * (my $c = 1 + length max @_); ( sprintf( ('%'.$c.'d')x@_, @_) ) =~ s/.{1,$t}\K/\n/gr }
sub jacobsthal { my($n) = @_; state @J = (0, 1); do { push @J, $J[-1] + 2 * $J[-2]} unt... |
http://rosettacode.org/wiki/Jewels_and_stones | Jewels and stones | Jewels and stones
You are encouraged to solve this task according to the task description, using any language you may know.
Task
Create a function which takes two string parameters: 'stones' and 'jewels' and returns an integer.
Both strings can contain any number of upper or lower case letters. However, in the case ... | #Swift | Swift | func countJewels(_ stones: String, _ jewels: String) -> Int {
return stones.map({ jewels.contains($0) ? 1 : 0 }).reduce(0, +)
}
print(countJewels("aAAbbbb", "aA"))
print(countJewels("ZZ", "z")) |
http://rosettacode.org/wiki/Jewels_and_stones | Jewels and stones | Jewels and stones
You are encouraged to solve this task according to the task description, using any language you may know.
Task
Create a function which takes two string parameters: 'stones' and 'jewels' and returns an integer.
Both strings can contain any number of upper or lower case letters. However, in the case ... | #Tcl | Tcl | proc shavej {stones jewels} {
set n 0
foreach c [split $stones {}] {
incr n [expr { [string first $c $jewels] >= 0 }]
}
return $n
}
puts [shavej aAAbbbb aA]
puts [shavej ZZ z] |
http://rosettacode.org/wiki/Jaro-Winkler_distance | Jaro-Winkler distance | The Jaro-Winkler distance is a metric for measuring the edit distance between words.
It is similar to the more basic Levenstein distance but the Jaro distance also accounts
for transpositions between letters in the words. With the Winkler modification to the Jaro
metric, the Jaro-Winkler distance also adds an increase ... | #Rust | Rust | use std::fs::File;
use std::io::{self, BufRead};
fn load_dictionary(filename: &str) -> std::io::Result<Vec<String>> {
let file = File::open(filename)?;
let mut dict = Vec::new();
for line in io::BufReader::new(file).lines() {
dict.push(line?);
}
Ok(dict)
}
fn jaro_winkler_distance(string... |
http://rosettacode.org/wiki/Jaro-Winkler_distance | Jaro-Winkler distance | The Jaro-Winkler distance is a metric for measuring the edit distance between words.
It is similar to the more basic Levenstein distance but the Jaro distance also accounts
for transpositions between letters in the words. With the Winkler modification to the Jaro
metric, the Jaro-Winkler distance also adds an increase ... | #Swift | Swift | import Foundation
func loadDictionary(_ path: String) throws -> [String] {
let contents = try String(contentsOfFile: path, encoding: String.Encoding.ascii)
return contents.components(separatedBy: "\n")
}
func jaroWinklerDistance(string1: String, string2: String) -> Double {
var st1 = Array(string1)
... |
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... | #Ada | Ada | Foo := 1;
loop
exit when Foo = 10;
Foo := Foo + 1;
end loop; |
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... | #ALGOL_68 | ALGOL 68 | # Inverted assignment #
# Assignment in Algol 68 is via ":=" which is automaically provided for all modes (types) #
# However we could define e.g. "=:" as an inverted assignment operator but we would need to #
# define a separate operator for each ... |
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... | #ARM_Assembly | ARM Assembly |
/* ARM assembly Raspberry PI */
/* program jarodist.s */
/* Constantes */
.equ BUFFERSIZE, 100
.equ STDIN, 0 @ Linux input console
.equ STDOUT, 1 @ Linux output console
.equ EXIT, 1 ... |
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... | #AppleScript | AppleScript | on josephus(n, k)
set m to 0
repeat with i from 2 to n
set m to (m + k) mod i
end repeat
return m + 1
end josephus
josephus(41, 3) --> 31 |
http://rosettacode.org/wiki/Knuth_shuffle | Knuth shuffle | The Knuth shuffle (a.k.a. the Fisher-Yates shuffle) is an algorithm for randomly shuffling the elements of an array.
Task
Implement the Knuth shuffle for an integer array (or, if possible, an array of any type).
Specification
Given an array items with indices ranging from 0 to last, the algorithm can be d... | #Wren | Wren | import "random" for Random
var rand = Random.new()
var knuthShuffle = Fn.new { |a|
var i = a.count - 1
while (i >= 1) {
var j = rand.int(i + 1)
var t = a[i]
a[i] = a[j]
a[j] = t
i = i - 1
}
}
var tests = [ [], [10], [10, 20], [10, 20, 30] ]
for (a in tests) {
... |
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... | #Ring | Ring |
# Project : Jensen's Device
decimals(14)
i = 100
see sum(i,1,100,"1/n") + nl
func sum(i,lo,hi,term)
temp = 0
for n = lo to hi step 1
eval("num = " + term)
temp = temp + num
next
return temp
|
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... | #Ruby | Ruby | def sum(var, lo, hi, term, context)
sum = 0.0
lo.upto(hi) do |n|
sum += eval "#{var} = #{n}; #{term}", context
end
sum
end
p sum "i", 1, 100, "1.0 / i", binding # => 5.18737751763962 |
http://rosettacode.org/wiki/Jacobsthal_numbers | Jacobsthal numbers | Jacobsthal numbers are an integer sequence related to Fibonacci numbers. Similar to Fibonacci, where each term is the sum of the previous two terms, each term is the sum of the previous, plus twice the one before that. Traditionally the sequence starts with the given terms 0, 1.
J0 = 0
J1 = 1
Jn = Jn-1 + 2 ×... | #Phix | Phix | with javascript_semantics
function jacobsthal(integer n)
return floor((power(2,n)+odd(n))/3)
end function
function jacobsthal_lucas(integer n)
return power(2,n)+power(-1,n)
end function
function jacobsthal_oblong(integer n)
return jacobsthal(n)*jacobsthal(n+1)
end function
printf(1,"First 30 Jacobsthal ... |
http://rosettacode.org/wiki/Jewels_and_stones | Jewels and stones | Jewels and stones
You are encouraged to solve this task according to the task description, using any language you may know.
Task
Create a function which takes two string parameters: 'stones' and 'jewels' and returns an integer.
Both strings can contain any number of upper or lower case letters. However, in the case ... | #Terraform | Terraform | variable "jewels" {
default = "aA"
}
variable "stones" {
default = "aAAbbbb"
}
locals {
jewel_list = split("", var.jewels)
stone_list = split("", var.stones)
found_jewels = [for s in local.stone_list: s if contains(local.jewel_list, s)]
}
output "jewel_count" {
value = length(local.found_jewels)
} |
http://rosettacode.org/wiki/Jewels_and_stones | Jewels and stones | Jewels and stones
You are encouraged to solve this task according to the task description, using any language you may know.
Task
Create a function which takes two string parameters: 'stones' and 'jewels' and returns an integer.
Both strings can contain any number of upper or lower case letters. However, in the case ... | #Transd | Transd | #lang transd
MainModule: {
countJewels: (λ j String() st String() locals: n 0
(for s in st do
(if (contains j s) (+= n 1)))
(ret n)
),
_start: (λ (lout (countJewels "aA" "aAAbbbb"))
(lout (countJewels "b" "BB")))
} |
http://rosettacode.org/wiki/Jaro-Winkler_distance | Jaro-Winkler distance | The Jaro-Winkler distance is a metric for measuring the edit distance between words.
It is similar to the more basic Levenstein distance but the Jaro distance also accounts
for transpositions between letters in the words. With the Winkler modification to the Jaro
metric, the Jaro-Winkler distance also adds an increase ... | #Typescript | Typescript |
var fs = require('fs')
// Jaro Winkler Distance Formula
function jaroDistance(string1: string, string2: string): number{
// Compute Jaro-Winkler distance between two string
// Swap strings if string1 is shorter than string 2
if (string1.length < string2.length){
const tempString: string = string... |
http://rosettacode.org/wiki/Jaro-Winkler_distance | Jaro-Winkler distance | The Jaro-Winkler distance is a metric for measuring the edit distance between words.
It is similar to the more basic Levenstein distance but the Jaro distance also accounts
for transpositions between letters in the words. With the Winkler modification to the Jaro
metric, the Jaro-Winkler distance also adds an increase ... | #Vlang | Vlang | import os
fn jaro_sim(str1 string, str2 string) f64 {
if str1.len == 0 && str2.len == 0 {
return 1
}
if str1.len == 0 || str2.len == 0 {
return 0
}
mut match_distance := str1.len
if str2.len > match_distance {
match_distance = str2.len
}
match_distance = match_d... |
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... | #ARM_Assembly | ARM Assembly | MOV R0,R3 ;copy R3 to R0
ADD R2,R1,R5 ;add R1 to R5 and store the result in R2. |
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... | #Arturo | Arturo | ifStatement: function [block, condition][
if condition -> do block
]
alias.infix {??} 'ifStatement
do [
variable: true
[print "Variable is true!"] ?? variable
] |
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... | #Bracmat | Bracmat |
double=.!arg+!arg;
(=.!arg+!arg):(=?double); { inverted assignment syntax, same result as above. }
|
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)
... | #11l | 11l | F is_isbn13(=n)
n = n.replace(‘-’, ‘’).replace(‘ ’, ‘’)
I n.len != 13
R 0B
V product = sum(n[(0..).step(2)].map(ch -> Int(ch)))
+ sum(n[(1..).step(2)].map(ch -> Int(ch) * 3))
R product % 10 == 0
V tests = |‘978-1734314502
978-1734314509
978-1788399081
... |
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... | #Arturo | Arturo | loop [
["MARTHA" "MARHTA"]
["DIXON" "DICKSONX"]
["JELLYFISH" "SMELLYFISH"]
] 'pair ->
print [pair "-> Jaro similarity:" round.to: 3 jaro first pair last pair] |
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... | #ARM_Assembly | ARM Assembly |
/* ARM assembly AARCH64 Raspberry PI 3B */
/* ARM assembly Raspberry PI */
/* program josephus.s */
/* REMARK 1 : this program use routines in a include file
see task Include a file language arm assembly
for the routine affichageMess conversion10
see at end of this program the instruction include */... |
http://rosettacode.org/wiki/Knuth_shuffle | Knuth shuffle | The Knuth shuffle (a.k.a. the Fisher-Yates shuffle) is an algorithm for randomly shuffling the elements of an array.
Task
Implement the Knuth shuffle for an integer array (or, if possible, an array of any type).
Specification
Given an array items with indices ranging from 0 to last, the algorithm can be d... | #XPL0 | XPL0 | proc Shuffle(Array, Items, BytesPerItem);
int Array, Items, BytesPerItem;
int I, J;
char Temp(8);
[for I:= Items-1 downto 1 do
[J:= Ran(I+1); \range [0..I]
CopyMem(Temp, Array+I*BytesPerItem, BytesPerItem);
CopyMem(Array+I*BytesPerItem, Array+J*BytesPerItem, BytesPerItem);
CopyMem(Array+J*BytesPe... |
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... | #Rust | Rust |
use std::f32;
fn harmonic_sum<F>(lo: usize, hi: usize, term: F) -> f32
where
F: Fn(f32) -> f32,
{
(lo..hi + 1).fold(0.0, |acc, item| acc + term(item as f32))
}
fn main() {
println!("{}", harmonic_sum(1, 100, |i| 1.0 / i));
}
|
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... | #Scala | Scala | class MyInt { var i: Int = _ }
val i = new MyInt
def sum(i: MyInt, lo: Int, hi: Int, term: => Double) = {
var temp = 0.0
i.i = lo
while(i.i <= hi) {
temp = temp + term
i.i += 1
}
temp
}
sum(i, 1, 100, 1.0 / i.i) |
http://rosettacode.org/wiki/Jacobsthal_numbers | Jacobsthal numbers | Jacobsthal numbers are an integer sequence related to Fibonacci numbers. Similar to Fibonacci, where each term is the sum of the previous two terms, each term is the sum of the previous, plus twice the one before that. Traditionally the sequence starts with the given terms 0, 1.
J0 = 0
J1 = 1
Jn = Jn-1 + 2 ×... | #Python | Python | #!/usr/bin/python
from math import floor, pow
def isPrime(n):
for i in range(2, int(n**0.5) + 1):
if n % i == 0:
return False
return True
def odd(n):
return n and 1 != 0
def jacobsthal(n):
return floor((pow(2,n)+odd(n))/3)
def jacobsthal_lucas(n):
return int(pow(2... |
http://rosettacode.org/wiki/Jewels_and_stones | Jewels and stones | Jewels and stones
You are encouraged to solve this task according to the task description, using any language you may know.
Task
Create a function which takes two string parameters: 'stones' and 'jewels' and returns an integer.
Both strings can contain any number of upper or lower case letters. However, in the case ... | #VBA | VBA | Function count_jewels(stones As String, jewels As String) As Integer
Dim res As Integer: res = 0
For i = 1 To Len(stones)
res = res - (InStr(1, jewels, Mid(stones, i, 1), vbBinaryCompare) <> 0)
Next i
count_jewels = res
End Function
Public Sub main()
Debug.Print count_jewels("aAAbbbb", "aA")... |
http://rosettacode.org/wiki/Jewels_and_stones | Jewels and stones | Jewels and stones
You are encouraged to solve this task according to the task description, using any language you may know.
Task
Create a function which takes two string parameters: 'stones' and 'jewels' and returns an integer.
Both strings can contain any number of upper or lower case letters. However, in the case ... | #Visual_Basic_.NET | Visual Basic .NET | Module Module1
Function Count(stones As String, jewels As String) As Integer
Dim bag = jewels.ToHashSet
Return stones.Count(AddressOf bag.Contains)
End Function
Sub Main()
Console.WriteLine(Count("aAAbbbb", "Aa"))
Console.WriteLine(Count("ZZ", "z"))
End Sub
End Modu... |
http://rosettacode.org/wiki/Jaro-Winkler_distance | Jaro-Winkler distance | The Jaro-Winkler distance is a metric for measuring the edit distance between words.
It is similar to the more basic Levenstein distance but the Jaro distance also accounts
for transpositions between letters in the words. With the Winkler modification to the Jaro
metric, the Jaro-Winkler distance also adds an increase ... | #Wren | Wren | import "io" for File
import "/fmt" for Fmt
import "/sort" for Sort
var jaroSim = Fn.new { |s1, s2|
var le1 = s1.count
var le2 = s2.count
if (le1 == 0 && le2 == 0) return 1
if (le1 == 0 || le2 == 0) return 0
var dist = (le2 > le1) ? le2 : le1
dist = (dist/2).floor - 1
var matches1 = List.fi... |
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... | #C | C |
#include <stdio.h>
#include <stdlib.h>
#define otherwise do { register int _o = 2; do { switch (_o) { case 1:
#define given(Mc) ;case 0: break; case 2: _o = !!(Mc); continue; } break; } while (1); } while (0)
int foo() { return 1; }
main()
{
int a = 0;
otherwise a = 4 given (foo(... |
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... | #C.2B.2B | C++ | class invertedAssign {
int data;
public:
invertedAssign(int data):data(data){}
int getData(){return data;}
void operator=(invertedAssign& other) const {
other.data = this->data;
}
};
#include <iostream>
int main(){
invertedAssign a = 0;
invertedAssign b = 42;
std::cout << a.getData() << ' ' <<... |
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)
... | #8080_Assembly | 8080 Assembly | org 100h
jmp demo
;;; ---------------------------------------------------------------
;;; Check if the string at BC is a valid ISBN-13 code.
;;; Carry set if true, clear if not.
isbn13: lxi h,0 ; HL = accumulator
mov d,h ; D = 0 (such that if E=A, DE=A).
call isbngc ; Get first character
rnc ; Carry clear = in... |
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... | #AWK | AWK |
# syntax: GAWK -f JARO_DISTANCE.AWK
BEGIN {
main("DWAYNE","DUANE")
main("MARTHA","MARHTA")
main("DIXON","DICKSONX")
main("JELLYFISH","SMELLYFISH")
exit(0)
}
function main(str1,str2) {
printf("%9.7f '%s' '%s'\n",jaro(str1,str2),str1,str2)
}
function jaro(str1,str2, begin,end,i,j,k,leng1,leng2,... |
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... | #Arturo | Arturo | josephus: function [n,k][
p: new 0..n-1
i: 0
seq: []
while [0 < size p][
i: (i+k-1) % size p
append 'seq p\[i]
remove 'p .index i
]
print ["Prisoner killing order:" chop seq]
print ["Survivor:" last seq]
print ""
]
print "josephus 5 2 =>"
josephus 5 2
print... |
http://rosettacode.org/wiki/Knuth_shuffle | Knuth shuffle | The Knuth shuffle (a.k.a. the Fisher-Yates shuffle) is an algorithm for randomly shuffling the elements of an array.
Task
Implement the Knuth shuffle for an integer array (or, if possible, an array of any type).
Specification
Given an array items with indices ranging from 0 to last, the algorithm can be d... | #Yabasic | Yabasic | // Rosetta Code problem: https://www.rosettacode.org/wiki/Ramsey%27s_theorem
// by Jjuanhdez, 06/2022
dim array(52)
for i = 1 to arraysize(array(),1) : array(i) = i : next i
print "Starting array"
for i = 1 to arraysize(array(),1)
print array(i) using "####";
next i
KnuthShuffle(array())
print "\n\nAfter Kn... |
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... | #Scheme | Scheme |
(define-syntax sum
(syntax-rules ()
((sum var low high . body)
(let loop ((var low)
(result 0))
(if (> var high)
result
(loop (+ var 1)
(+ result . body)))))))
|
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... | #Seed7 | Seed7 |
$ include "seed7_05.s7i";
include "float.s7i";
var integer: i is 0;
const func float: sum (inout integer: i, in integer: lo, in integer: hi,
ref func float: term) is func
result
var float: sum is 0.0
begin
for i range lo to hi do
sum +:= term;
end for;
end func;
const proc: main is... |
http://rosettacode.org/wiki/Jacobsthal_numbers | Jacobsthal numbers | Jacobsthal numbers are an integer sequence related to Fibonacci numbers. Similar to Fibonacci, where each term is the sum of the previous two terms, each term is the sum of the previous, plus twice the one before that. Traditionally the sequence starts with the given terms 0, 1.
J0 = 0
J1 = 1
Jn = Jn-1 + 2 ×... | #Raku | Raku | my $jacobsthal = cache lazy 0, 1, * × 2 + * … *;
my $jacobsthal-lucas = lazy 2, 1, * × 2 + * … *;
say "First 30 Jacobsthal numbers:";
say $jacobsthal[^30].batch(5)».fmt("%9d").join: "\n";
say "\nFirst 30 Jacobsthal-Lucas numbers:";
say $jacobsthal-lucas[^30].batch(5)».fmt("%9d").join: "\n";
say "\nFirst 20 Jacobs... |
http://rosettacode.org/wiki/Jewels_and_stones | Jewels and stones | Jewels and stones
You are encouraged to solve this task according to the task description, using any language you may know.
Task
Create a function which takes two string parameters: 'stones' and 'jewels' and returns an integer.
Both strings can contain any number of upper or lower case letters. However, in the case ... | #Vlang | Vlang | fn js(stones string, jewels string) int {
mut n := 0
for b in stones.bytes() {
if jewels.index_u8(b) >= 0 {
n++
}
}
return n
}
fn main() {
println(js("aAAbbbb", "aA"))
} |
http://rosettacode.org/wiki/Jewels_and_stones | Jewels and stones | Jewels and stones
You are encouraged to solve this task according to the task description, using any language you may know.
Task
Create a function which takes two string parameters: 'stones' and 'jewels' and returns an integer.
Both strings can contain any number of upper or lower case letters. However, in the case ... | #Wren | Wren | var countJewels = Fn.new { |s, j| s.count { |c| j.contains(c) } }
System.print(countJewels.call("aAAbbbb", "aA"))
System.print(countJewels.call("ZZ", "z")) |
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... | #Clojure | Clojure | ; normal
(if (= 1 1)
(print "Math works."))
; inverted
(->> (print "Math still works.")
(if (= 1 1)))
; a la Haskell
(->> (print a " is " b)
(let [a 'homoiconicity
b 'awesome])) |
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... | #CoffeeScript | CoffeeScript | alert "hello" if true
alert "hello again" unless false # the same as the above; unless is a negated if.
idx = 0
arr = (++idx while idx < 10) # arr is [1,2,3,4,5,6,7,8,9,10]
idx = 0
arr = (++idx until idx is 10) # same as above; until is an inverted while. |
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... | #Common_Lisp | Common Lisp | (eval-when (:compile-toplevel :load-toplevel :execute)
(defun unrev-syntax (form)
(cond
((atom form) form)
((null (cddr form)) form)
(t (destructuring-bind (oper &rest args) (reverse form)
`(,oper ,@(mapcar #'unrev-syntax args)))))))
(defmacro rprogn (&body forms)
`(progn ,@(mapca... |
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)
... | #8086_Assembly | 8086 Assembly | cpu 8086
bits 16
org 100h
section .text
jmp demo
isbn13: ;;; ---------------------------------------------------------------
;;; Check if the string at DS:SI is a valid ISBN-13 code.
;;; Carry set if true, clear if false.
xor dx,dx ; DX = running total
xor ah,ah ; Set AH=0 so that AX=AL
call .digit ; Get f... |
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... | #C | C | #include <stdlib.h>
#include <string.h>
#include <ctype.h>
#include <stdio.h>
#define TRUE 1
#define FALSE 0
#define max(a, b) ((a) > (b) ? (a) : (b))
#define min(a, b) ((a) < (b) ? (a) : (b))
double jaro(const char *str1, const char *str2) {
// length of the strings
int str1_len = strlen(str1);
... |
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... | #AutoHotkey | AutoHotkey | ; Since AutoHotkey is 1-based, we're numbering prisoners 1-41.
nPrisoners := 41
kth := 3
; Build a list, purposefully ending with a separator
Loop % nPrisoners
list .= A_Index . "|"
; iterate and remove from list
i := 1
Loop
{
; Step by 2; the third step was done by removing the previous prisoner
i += kth... |
http://rosettacode.org/wiki/Knuth_shuffle | Knuth shuffle | The Knuth shuffle (a.k.a. the Fisher-Yates shuffle) is an algorithm for randomly shuffling the elements of an array.
Task
Implement the Knuth shuffle for an integer array (or, if possible, an array of any type).
Specification
Given an array items with indices ranging from 0 to last, the algorithm can be d... | #zkl | zkl | fcn kshuffle(xs){
foreach i in ([xs.len()-1..1,-1]){ xs.swap(i,(0).random(0,i+1)) }
xs
}
fcn kshufflep(xs){
[xs.len()-1..1,-1].pump(Void,'wrap(i){ xs.swap(i,(0).random(0,i+1)) })
xs
} |
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... | #Sidef | Sidef | var i;
func sum (i, lo, hi, term) {
var temp = 0;
for (*i = lo; *i <= hi; (*i)++) {
temp += term.run;
};
return temp;
};
say sum(\i, 1, 100, { 1 / i }); |
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... | #Simula | Simula | comment Jensen's Device;
begin
integer i;
real procedure sum (i, lo, hi, term);
name i, term;
value lo, hi;
integer i, lo, hi;
real term;
comment term is passed by-name, and so is i;
begin
integer j;
real temp;
temp := 0;
for j := lo step 1 until hi do
... |
http://rosettacode.org/wiki/Jacobsthal_numbers | Jacobsthal numbers | Jacobsthal numbers are an integer sequence related to Fibonacci numbers. Similar to Fibonacci, where each term is the sum of the previous two terms, each term is the sum of the previous, plus twice the one before that. Traditionally the sequence starts with the given terms 0, 1.
J0 = 0
J1 = 1
Jn = Jn-1 + 2 ×... | #Red | Red | Red ["Jacobsthal numbers"]
jacobsthal: function [n] [to-integer (2 ** n - (-1 ** n) / 3)]
lucas: function [n] [2 ** n + (-1 ** n)]
oblong: function [n] [
first split mold multiply to-float jacobsthal n to-float jacobsthal n + 1 #"." ; work around integer overflow
]
prime?: function [
"Returns true if ... |
http://rosettacode.org/wiki/Jewels_and_stones | Jewels and stones | Jewels and stones
You are encouraged to solve this task according to the task description, using any language you may know.
Task
Create a function which takes two string parameters: 'stones' and 'jewels' and returns an integer.
Both strings can contain any number of upper or lower case letters. However, in the case ... | #XPL0 | XPL0 | string 0; \Use zero-terminated strings
func Count(Stones, Jewels);
\Return number of letters in Stones that match letters in Jewels
char Stones, Jewels;
int Cnt, I, J;
[Cnt:= 0;
I:= 0;
while Jewels(I) do
[J:= 0;
while Stones(J) do
[if Stones(J) = Jewels(I) then Cnt:= Cnt+1;
J:= J+1;
... |
http://rosettacode.org/wiki/Jewels_and_stones | Jewels and stones | Jewels and stones
You are encouraged to solve this task according to the task description, using any language you may know.
Task
Create a function which takes two string parameters: 'stones' and 'jewels' and returns an integer.
Both strings can contain any number of upper or lower case letters. However, in the case ... | #zkl | zkl | fcn countJewels(a,b){ a.inCommon(b).len() } |
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... | #D | D | #!/usr/bin/rdmd
import std.algorithm;
void main() {
assert("Hello, World".length == 12);
assert("Cleanliness".startsWith("Clean"));
auto r = [1, 4, 2, 8, 5, 7]
.filter!(n => n > 2)
.map!(n => n * 2);
assert(r.equal([8, 16, 10, 14]));
} |
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... | #EchoLisp | EchoLisp |
;; use reader macros to transform (a OP b) into (OP b a)
(lib 'match)
(define-macro invert-= (a <- b) (set! b a))
(define-macro invert-IF (a 'IF b) (when b a))
(define raining #f)
(#t <- raining)
raining
→ #t
('umbrella-need IF raining)
→ umbrella-need
(#f <- raining)
('umbrella-need IF raining)
→... |
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)
... | #Action.21 | Action! | INCLUDE "D2:CHARTEST.ACT" ;from the Action! Tool Kit
BYTE FUNC CheckISBN13(CHAR ARRAY t)
BYTE i,index,sum,v
sum=0 index=0
FOR i=1 TO t(0)
DO
v=t(i)
IF IsDigit(v) THEN
v==-'0
IF index MOD 2=1 THEN
v==*3
FI
sum==+v
index==+1
ELSEIF v#' AND v#'- THEN
RET... |
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)
... | #Ada | Ada | with Ada.Text_IO;
procedure ISBN_Check is
function Is_Valid (ISBN : String) return Boolean is
Odd : Boolean := True;
Sum : Integer := 0;
Value : Integer;
begin
for I in ISBN'Range loop
if ISBN (I) in '0' .. '9' then
Value := Character'Pos (ISBN (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... | #C.2B.2B | C++ | #include <algorithm>
#include <iostream>
#include <string>
double jaro(const std::string s1, const std::string s2) {
const uint l1 = s1.length(), l2 = s2.length();
if (l1 == 0)
return l2 == 0 ? 1.0 : 0.0;
const uint match_distance = std::max(l1, l2) / 2 - 1;
bool s1_matches[l1];
bool s2_ma... |
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... | #AWK | AWK |
# syntax: GAWK -f JOSEPHUS_PROBLEM.AWK
# converted from PL/I
BEGIN {
main(5,2,1)
main(41,3,1)
main(41,3,3)
exit(0)
}
function main(n,k,s, dead,errors,found,i,killed,nn,p,survived) {
# n - number of prisoners
# k - kill every k'th prisoner
# s - number of survivors
printf("\nn=%d k=%d s=%d\n",n,k,... |
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... | #Standard_ML | Standard ML | val i = ref 42 (* initial value doesn't matter *)
fun sum' (i, lo, hi, term) = let
val result = ref 0.0
in
i := lo;
while !i <= hi do (
result := !result + term ();
i := !i + 1
);
!result
end
val () =
print (Real.toString (sum' (i, 1, 100, fn () => 1.0 / real (!i))) ^ "\n") |
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... | #Swift | Swift | var i = 42 // initial value doesn't matter
func sum(inout i: Int, lo: Int, hi: Int, @autoclosure term: () -> Double) -> Double {
var result = 0.0
for i = lo; i <= hi; i++ {
result += term()
}
return result
}
println(sum(&i, 1, 100, 1 / Double(i))) |
http://rosettacode.org/wiki/Jacobsthal_numbers | Jacobsthal numbers | Jacobsthal numbers are an integer sequence related to Fibonacci numbers. Similar to Fibonacci, where each term is the sum of the previous two terms, each term is the sum of the previous, plus twice the one before that. Traditionally the sequence starts with the given terms 0, 1.
J0 = 0
J1 = 1
Jn = Jn-1 + 2 ×... | #Rust | Rust | // [dependencies]
// rug = "0.3"
use rug::integer::IsPrime;
use rug::Integer;
fn jacobsthal_numbers() -> impl std::iter::Iterator<Item = Integer> {
(0..).map(|x| ((Integer::from(1) << x) - if x % 2 == 0 { 1 } else { -1 }) / 3)
}
fn jacobsthal_lucas_numbers() -> impl std::iter::Iterator<Item = Integer> {
(... |
http://rosettacode.org/wiki/Jacobsthal_numbers | Jacobsthal numbers | Jacobsthal numbers are an integer sequence related to Fibonacci numbers. Similar to Fibonacci, where each term is the sum of the previous two terms, each term is the sum of the previous, plus twice the one before that. Traditionally the sequence starts with the given terms 0, 1.
J0 = 0
J1 = 1
Jn = Jn-1 + 2 ×... | #Sidef | Sidef | func jacobsthal(n) {
lucasU(1, -2, n)
}
func lucas_jacobsthal(n) {
lucasV(1, -2, n)
}
say "First 30 Jacobsthal numbers:"
say 30.of(jacobsthal)
say "\nFirst 30 Jacobsthal-Lucas numbers:"
say 30.of(lucas_jacobsthal)
say "\nFirst 20 Jacobsthal oblong numbers:"
say 21.of(jacobsthal).cons(2, {|a,b| a * b })
... |
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... | #Factor | Factor | 1 1 + ! 2
[ + 1 1 ] reverse call ! 2
{ 1 2 3 4 5 } [ sq ] map ! { 1 4 9 16 25 }
[ map [ sq ] { 1 2 3 4 5 } ] reverse call ! { 1 4 9 16 25 } |
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... | #Fortran | Fortran | INQUIRE(FILE = FILENAME(1:L), EXIST = MAYBE, ERR = 666, IOSTAT = RESULT) |
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... | #FreeBASIC | FreeBASIC | ' FB 1.05.0 Win64
#Define ThenIf(a, b) If b Then a
#Define InvertAssign(a, b) b = a
Dim As Boolean needUmbrella = False, raining = True
ThenIf(needUmbrella = True, raining = True)
Print "needUmbrella = "; needUmbrella
Dim As Integer b = 0, a = 3
InvertAssign(a, b)
Print "b is"; b
Sleep |
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)
... | #ALGOL_68 | ALGOL 68 | BEGIN # Check some IsBN13 check digits #
# returns TRUE if the alledged isbn13 has the correct check sum, #
# FALSE otherwise #
# non-digit characters are ignored and there must be 13 digits ... |
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... | #Clojure | Clojure |
(ns test-project-intellij.core
(:gen-class))
(defn find-matches [s t]
" find match locations in the two strings "
" s_matches is set to true wherever there is a match in t and t_matches is set conversely "
(let [s_len (count s)
t_len (count t)
match_distance (int (- (/ (max s_len t_len) 2) 1... |
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... | #11l | 11l | F next_step(=x)
V result = 0
L x > 0
result += (x % 10) ^ 2
x I/= 10
R result
F check(number)
V candidate = 0
L(n) number
candidate = candidate * 10 + n
L candidate != 89 & candidate != 1
candidate = next_step(candidate)
I candidate == 89
V digits_count = [0] * 1... |
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... | #BASIC | BASIC | 10 N=41
20 K=3
30 M=0
40 FOR I=M+1 TO N
50 M=INT(I*((M+K)/I-INT((M+K)/I))+0.5)
60 NEXT I
70 PRINT "Survivor is number";M |
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... | #Tcl | Tcl | proc sum {var lo hi term} {
upvar 1 $var x
set sum 0.0
for {set x $lo} {$x < $hi} {incr x} {
set sum [expr {$sum + [uplevel 1 [list expr $term]]}]
}
return $sum
}
puts [sum i 1 100 {1.0/$i}] ;# 5.177377517639621 |
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... | #VBA | VBA |
Private Function sum(i As String, ByVal lo As Integer, ByVal hi As Integer, term As String) As Double
Dim temp As Double
For k = lo To hi
temp = temp + Evaluate(Replace(term, i, k))
Next k
sum = temp
End Function
Sub Jensen_Device()
Debug.Print sum("i", 1, 100, "1/i")
Debug.Print sum("... |
http://rosettacode.org/wiki/Jacobsthal_numbers | Jacobsthal numbers | Jacobsthal numbers are an integer sequence related to Fibonacci numbers. Similar to Fibonacci, where each term is the sum of the previous two terms, each term is the sum of the previous, plus twice the one before that. Traditionally the sequence starts with the given terms 0, 1.
J0 = 0
J1 = 1
Jn = Jn-1 + 2 ×... | #Vlang | Vlang | import math.big
fn jacobsthal(n u32) big.Integer {
mut t := big.one_int
t=t.lshift(n)
mut s := big.one_int
if n%2 != 0 {
s=s.neg()
}
t -= s
return t/big.integer_from_int(3)
}
fn jacobsthal_lucas(n u32) big.Integer {
mut t := big.one_int
t=t.lshift(n)
mut a := big.one_... |
http://rosettacode.org/wiki/Jacobsthal_numbers | Jacobsthal numbers | Jacobsthal numbers are an integer sequence related to Fibonacci numbers. Similar to Fibonacci, where each term is the sum of the previous two terms, each term is the sum of the previous, plus twice the one before that. Traditionally the sequence starts with the given terms 0, 1.
J0 = 0
J1 = 1
Jn = Jn-1 + 2 ×... | #Wren | Wren | import "./big" for BigInt
import "./seq" for Lst
import "./fmt" for Fmt
var jacobsthal = Fn.new { |n| ((BigInt.one << n) - ((n%2 == 0) ? 1 : -1)) / 3 }
var jacobsthalLucas = Fn.new { |n| (BigInt.one << n) + ((n%2 == 0) ? 1 : -1) }
System.print("First 30 Jacobsthal numbers:")
var js = (0..29).map { |i| jacobsthal.... |
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... | #F.C5.8Drmul.C3.A6 | Fōrmulæ | package main
import "fmt"
type ibool bool
const itrue ibool = true
func (ib ibool) iif(cond bool) bool {
if cond {
return bool(ib)
}
return bool(!ib)
}
func main() {
var needUmbrella bool
raining := true
// normal syntax
if raining {
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... | #Go | Go | package main
import "fmt"
type ibool bool
const itrue ibool = true
func (ib ibool) iif(cond bool) bool {
if cond {
return bool(ib)
}
return bool(!ib)
}
func main() {
var needUmbrella bool
raining := true
// normal syntax
if raining {
needUmbrella = true
}
... |
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)
... | #APL | APL | check_isbn13←{
13≠⍴n←(⍵∊⎕D)/⍵:0
0=10|(⍎¨n)+.×13⍴1 3
} |
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... | #CLU | CLU | max = proc [T: type] (a, b: T) returns (T)
where T has lt: proctype (T,T) returns (bool)
if a<b then return(b) else return(a) end
end max
min = proc [T: type] (a, b: T) returns (T)
where T has lt: proctype (T,T) returns (bool)
if a<b then return(a) else return(b) end
end min
jaro = proc (s1, s2:... |
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... | #Ada | Ada | with Ada.Text_IO;
procedure Digits_Squaring is
function Is_89 (Number : in Positive) return Boolean
is
Squares : constant array (0 .. 9) of Natural :=
(0, 1, 4, 9, 16, 25, 36, 49, 64, 81);
Sum : Natural := Number;
Acc : Natural;
begin
loop
Acc := Sum;
Su... |
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... | #Batch_File | Batch File | @echo off
setlocal enabledelayedexpansion
set "prison=41" %== Number of prisoners ==%
set "step=3" %== The step... ==%
set "survive=1" %== Number of survivors ==%
call :josephus
set "prison=41"
set "step=3"
set "survive=3"
call :josephus
pause
exit /b 0
%== The Procedure ==%
:josephus
set "surv_list="
for /l ... |
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... | #Wren | Wren | class Box {
construct new(v) { _v = v }
v { _v }
v=(value) { _v = value }
}
var i = Box.new(0) // any initial value will do here
var sum = Fn.new { |i, lo, hi, term|
var temp = 0
i.v = lo
while (i.v <= hi) {
temp = temp + term.call()
i.v = i.v + 1
}
return temp
}
v... |
http://rosettacode.org/wiki/Jacobsthal_numbers | Jacobsthal numbers | Jacobsthal numbers are an integer sequence related to Fibonacci numbers. Similar to Fibonacci, where each term is the sum of the previous two terms, each term is the sum of the previous, plus twice the one before that. Traditionally the sequence starts with the given terms 0, 1.
J0 = 0
J1 = 1
Jn = Jn-1 + 2 ×... | #XPL0 | XPL0 | func IsPrime(N); \Return 'true' if N is prime
int N, I;
[if N <= 2 then return N = 2;
if (N&1) = 0 then \even >2\ return false;
for I:= 3 to sqrt(N) do
[if rem(N/I) = 0 then return false;
I:= I+1;
];
return true;
];
proc Jaco(J2); \Display 30 Jacobsthal (or -Lucas) numbers
real J2, J1, J;... |
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... | #Haskell | Haskell | when :: Monad m => m () -> Bool -> m ()
action `when` condition = if condition then action else 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... | #Icon_and_Unicon | Icon and Unicon | procedure main()
raining := TRUE := 1 # there is no true/false null/non-null will do
if \raining then needumbrella := TRUE # normal
needumbrella := 1(TRUE, \raining) # inverted (choose sub-expression 1)
end |
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... | #J | J | do ... while(condition); |
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)
... | #AppleScript | AppleScript | -------------------- ISBN13 CHECK DIGIT --------------------
-- isISBN13 :: String -> Bool
on isISBN13(s)
script digitValue
on |λ|(c)
if isDigit(c) then
{c as integer}
else
{}
end if
end |λ|
end script
set digits to conc... |
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... | #COBOL | COBOL |
identification division.
program-id. JaroDistance.
environment division.
configuration section.
repository.
function length intrinsic
function trim intrinsic
function max intrinsic
function min intrinsic
.
data divisi... |
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... | #ALGOL_68 | ALGOL 68 | # count the how many numbers up to 100 000 000 have squared digit sums of 89 #
# compute a table of the sum of the squared digits of the numbers 00 to 99 #
[ 0 : 99 ]INT digit pair square sum;
FOR d1 FROM 0 TO 9 DO
FOR d2 FROM 0 TO 9 DO
digit pair square sum[ ( d1 * 10 ) + d2 ] ... |
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... | #BBC_BASIC | BBC BASIC | REM >josephus
PRINT "Survivor is number "; FNjosephus(41, 3, 0)
END
:
DEF FNjosephus(n%, k%, m%)
LOCAL i%
FOR i% = m% + 1 TO n%
m% = (m% + k%) MOD i%
NEXT
= m% |
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... | #Yabasic | Yabasic | sub Evaluation()
lo = 1 : hi = 100 : temp = 0
for i = lo to hi
temp = temp + (1/i) //r(i)
next i
print temp
end sub
Evaluation() |
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... | #zkl | zkl | fcn sum(ri, lo,hi, term){
temp:=0.0; ri.set(lo);
do{ temp+=term(ri); } while(ri.inc()<hi); // inc return previous value
return(temp);
}
sum(Ref(0), 1,100, fcn(ri){ 1.0/ri.value }).println(); |
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... | #Java | Java | do ... while(condition); |
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... | #jq | jq | v as $x |
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... | #Julia | Julia | macro inv(expr, cond)
cond isa Expr && cond.head == :if || throw(ArgumentError("$cond is not an if expression"))
cond.args[2] = expr
return cond
end
@inv println("Wow! Lucky Guess!") if true else println("Not!") end |
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... | #Kotlin | Kotlin | // version 1.0.6
infix fun Boolean.iif(cond: Boolean) = if (cond) this else !this
fun main(args: Array<String>) {
val raining = true
val needUmbrella = true iif (raining)
println("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)
... | #Arturo | Arturo | validISBN?: function [isbn][
currentCheck: to :integer to :string last isbn
isbn: map split chop replace isbn "-" "" => [to :integer]
s: 0
loop.with:'i isbn 'n [
if? even? i -> s: s + n
else -> s: s + 3*n
]
checkDigit: 10 - s % 10
return currentCheck = checkDigit
]
tests:... |
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... | #CoffeeScript | CoffeeScript | jaro = (s1, s2) ->
l1 = s1.length
l2 = s2.length
if l1 == 0 then return if l2 == 0 then 1.0 else 0.0
match_distance = Math.max(l1, l2) / 2 - 1
s1_matches = []
s2_matches = []
m = 0
for i in [0...l1]
end = Math.min(i + match_distance + 1, l2)
for k in [Math.max(0, i - matc... |
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... | #Arturo | Arturo | gen: function [n][
result: n
while [not? in? result [1 89]][
s: new 0
loop digits result 'd ->
's + d*d
result: s
]
return result
]
chainsEndingWith89: function [ndigits][
[prevCount,currCount]: #[]
loop 0..9 'i -> prevCount\[i*i]: 1
res: new 0
l... |
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... | #11l | 11l | F commatize(number, step = 3, sep = ‘,’)
V s = reversed(String(number))
String r = s[0]
L(i) 1 .< s.len
I i % step == 0
r ‘’= sep
r ‘’= s[i]
R reversed(r)
F isqrt(BigInt x)
assert(x >= 0)
V q = BigInt(1)
L q <= x
q *= 4
V z = x
V r = BigInt(0)
L q > 1
... |
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... | #Befunge | Befunge | >0" :srenosirP">:#,_&>>00p>>v
v0p01<&_,#!>#:<"Step size: "<
>1+:20p00g`!#v_0" :rovivru"v
^g02%g02+g01<<@.$_,#!>#:<"S"< |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.