code
stringlengths 1
46.1k
⌀ | label
class label 1.18k
classes | domain_label
class label 21
classes | index
stringlengths 4
5
|
---|---|---|---|
import Data.List (elemIndex, intercalate, sortOn)
import Data.Maybe (mapMaybe)
import Text.Printf (printf)
jaro :: Ord a => [a] -> [a] -> Float
jaro x y
| 0 == m = 0
| otherwise =
(1 / 3)
* ( (m / s1) + (m / s2) + ((m - t) / m))
where
f = fromIntegral . length
[m, t] =
[f, fromIntegral . transpositions]
<*> [matches x y]
[s1, s2] = [f] <*> [x, y]
matches :: Eq a => [a] -> [a] -> [(Int, a)]
matches s1 s2 =
let [(l1, xs), (l2, ys)] =
sortOn
fst
((length >>= (,)) <$> [s1, s2])
r = quot l2 2 - 1
in mapMaybe
( \(c, n) ->
let offset = max 0 (n - (r + 1))
in
elemIndex c (drop offset (take (n + r) ys))
>>= (\i -> Just (offset + i, c))
)
(zip xs [1 ..])
transpositions :: Ord a => [(Int, a)] -> Int
transpositions =
length
. filter (uncurry (>))
. (zip <*> tail)
main :: IO ()
main =
mapM_ putStrLn $
fmap
( \(s1, s2) ->
intercalate
" -> "
[s1, s2, printf "%.3f\n" $ jaro s1 s2]
)
[ ("DWAYNE", "DUANE"),
("MARTHA", "MARHTA"),
("DIXON", "DICKSONX"),
("JELLYFISH", "SMELLYFISH")
] | 701Jaro similarity
| 8haskell
| mkzyf |
struct Wheel {
char *seq;
int len;
int pos;
};
struct Wheel *create(char *seq) {
struct Wheel *w = malloc(sizeof(struct Wheel));
if (w == NULL) {
return NULL;
}
w->seq = seq;
w->len = strlen(seq);
w->pos = 0;
return w;
}
char cycle(struct Wheel *w) {
char c = w->seq[w->pos];
w->pos = (w->pos + 1) % w->len;
return c;
}
struct Map {
struct Wheel *v;
struct Map *next;
char k;
};
struct Map *insert(char k, struct Wheel *v, struct Map *head) {
struct Map *m = malloc(sizeof(struct Map));
if (m == NULL) {
return NULL;
}
m->k = k;
m->v = v;
m->next = head;
return m;
}
struct Wheel *find(char k, struct Map *m) {
struct Map *ptr = m;
while (ptr != NULL) {
if (ptr->k == k) {
return ptr->v;
}
ptr = ptr->next;
}
return NULL;
}
void printOne(char k, struct Map *m) {
struct Wheel *w = find(k, m);
char c;
if (w == NULL) {
printf(, k);
exit(1);
}
c = cycle(w);
if ('0' <= c && c <= '9') {
printf(, c);
} else {
printOne(c, m);
}
}
void exec(char start, struct Map *m) {
struct Wheel *w;
int i;
if (m == NULL) {
printf();
return;
}
for (i = 0; i < 20; i++) {
printOne(start, m);
}
printf();
}
void group1() {
struct Wheel *a = create();
struct Map *m = insert('A', a, NULL);
exec('A', m);
}
void group2() {
struct Wheel *a = create();
struct Wheel *b = create();
struct Map *m = insert('A', a, NULL);
m = insert('B', b, m);
exec('A', m);
}
void group3() {
struct Wheel *a = create();
struct Wheel *d = create();
struct Map *m = insert('A', a, NULL);
m = insert('D', d, m);
exec('A', m);
}
void group4() {
struct Wheel *a = create();
struct Wheel *b = create();
struct Wheel *c = create();
struct Map *m = insert('A', a, NULL);
m = insert('B', b, m);
m = insert('C', c, m);
exec('A', m);
}
int main() {
group1();
group2();
group3();
group4();
return 0;
} | 706Intersecting number wheels
| 5c
| vez2o |
package main
import (
"fmt"
)
func main() {
var d, n, o, u, u89 int64
for n = 1; n < 100000000; n++ {
o = n
for {
u = 0
for {
d = o%10
o = (o - d) / 10
u += d*d
if o == 0 {
break
}
}
if u == 89 || u == 1 {
if u == 89 { u89++ }
break
}
o = u
}
}
fmt.Println(u89)
} | 703Iterated digits squaring
| 0go
| f40d0 |
Clojure 1.1.0
user=> (defn f [s1 s2 sep] (str s1 sep sep s2))
#'user/f
user=> (f "Rosetta" "Code" ":")
"Rosetta::Code"
user=> | 707Interactive programming (repl)
| 6clojure
| uwzvi |
public class JaroDistance {
public static double jaro(String s, String t) {
int s_len = s.length();
int t_len = t.length();
if (s_len == 0 && t_len == 0) return 1;
int match_distance = Integer.max(s_len, t_len) / 2 - 1;
boolean[] s_matches = new boolean[s_len];
boolean[] t_matches = new boolean[t_len];
int matches = 0;
int transpositions = 0;
for (int i = 0; i < s_len; i++) {
int start = Integer.max(0, i-match_distance);
int end = Integer.min(i+match_distance+1, t_len);
for (int j = start; j < end; j++) {
if (t_matches[j]) continue;
if (s.charAt(i) != t.charAt(j)) continue;
s_matches[i] = true;
t_matches[j] = true;
matches++;
break;
}
}
if (matches == 0) return 0;
int k = 0;
for (int i = 0; i < s_len; i++) {
if (!s_matches[i]) continue;
while (!t_matches[k]) k++;
if (s.charAt(i) != t.charAt(k)) transpositions++;
k++;
}
return (((double)matches / s_len) +
((double)matches / t_len) +
(((double)matches - transpositions/2.0) / matches)) / 3.0;
}
public static void main(String[] args) {
System.out.println(jaro( "MARTHA", "MARHTA"));
System.out.println(jaro( "DIXON", "DICKSONX"));
System.out.println(jaro("JELLYFISH", "SMELLYFISH"));
}
} | 701Jaro similarity
| 9java
| f4odv |
import Data.List (unfoldr)
import Data.Tuple (swap)
step :: Int -> Int
step = sum . map (^ 2) . unfoldr f where
f 0 = Nothing
f n = Just . swap $ n `divMod` 10
iter :: Int -> Int
iter = head . filter (`elem` [1, 89]) . iterate step
main = do
print $ length $ filter ((== 89) . iter) [1 .. 99999999] | 703Iterated digits squaring
| 8haskell
| 4qc5s |
import java.util.stream.IntStream;
public class IteratedDigitsSquaring {
public static void main(String[] args) {
long r = IntStream.range(1, 100_000_000)
.parallel()
.filter(n -> calc(n) == 89)
.count();
System.out.println(r);
}
private static int calc(int n) {
while (n != 89 && n != 1) {
int total = 0;
while (n > 0) {
total += Math.pow(n % 10, 2);
n /= 10;
}
n = total;
}
return n;
}
} | 703Iterated digits squaring
| 9java
| cpz9h |
package main
import (
"fmt"
"sort"
"strconv"
)
type wheel struct {
next int
values []string
}
type wheelMap = map[string]wheel
func generate(wheels wheelMap, start string, maxCount int) {
count := 0
w := wheels[start]
for {
s := w.values[w.next]
v, err := strconv.Atoi(s)
w.next = (w.next + 1) % len(w.values)
wheels[start] = w
if err == nil {
fmt.Printf("%d ", v)
count++
if count == maxCount {
fmt.Println("...\n")
return
}
} else {
for {
w2 := wheels[s]
ss := s
s = w2.values[w2.next]
w2.next = (w2.next + 1) % len(w2.values)
wheels[ss] = w2
v, err = strconv.Atoi(s)
if err == nil {
fmt.Printf("%d ", v)
count++
if count == maxCount {
fmt.Println("...\n")
return
}
break
}
}
}
}
}
func printWheels(wheels wheelMap) {
var names []string
for name := range wheels {
names = append(names, name)
}
sort.Strings(names)
fmt.Println("Intersecting Number Wheel group:")
for _, name := range names {
fmt.Printf(" %s:%v\n", name, wheels[name].values)
}
fmt.Print(" Generates:\n ")
}
func main() {
wheelMaps := []wheelMap{
{
"A": {0, []string{"1", "2", "3"}},
},
{
"A": {0, []string{"1", "B", "2"}},
"B": {0, []string{"3", "4"}},
},
{
"A": {0, []string{"1", "D", "D"}},
"D": {0, []string{"6", "7", "8"}},
},
{
"A": {0, []string{"1", "B", "C"}},
"B": {0, []string{"3", "4"}},
"C": {0, []string{"5", "B"}},
},
}
for _, wheels := range wheelMaps {
printWheels(wheels)
generate(wheels, "A", 20)
}
} | 706Intersecting number wheels
| 0go
| s9kqa |
package main
import (
"fmt"
"strings"
"unicode/utf8"
)
func checkIsbn13(isbn string) bool { | 704ISBN13 check digit
| 0go
| mkdyi |
object Jaro {
fun distance(s1: String, s2: String): Double {
val s1_len = s1.length
val s2_len = s2.length
if (s1_len == 0 && s2_len == 0) return 1.0
val match_distance = Math.max(s1_len, s2_len) / 2 - 1
val s1_matches = BooleanArray(s1_len)
val s2_matches = BooleanArray(s2_len)
var matches = 0
for (i in 0..s1_len - 1) {
val start = Math.max(0, i - match_distance)
val end = Math.min(i + match_distance + 1, s2_len)
(start..end - 1).find { j -> !s2_matches[j] && s1[i] == s2[j] } ?. let {
s1_matches[i] = true
s2_matches[it] = true
matches++
}
}
if (matches == 0) return 0.0
var t = 0.0
var k = 0
(0..s1_len - 1).filter { s1_matches[it] }.forEach { i ->
while (!s2_matches[k]) k++
if (s1[i] != s2[k]) t += 0.5
k++
}
val m = matches.toDouble()
return (m / s1_len + m / s2_len + (m - t) / m) / 3.0
}
}
fun main(args: Array<String>) {
println(Jaro.distance("MARTHA", "MARHTA"))
println(Jaro.distance("DIXON", "DICKSONX"))
println(Jaro.distance("JELLYFISH", "SMELLYFISH"))
} | 701Jaro similarity
| 11kotlin
| 8lx0q |
package main
import (
"fmt"
"log"
"math/big"
)
var zero = big.NewInt(0)
var one = big.NewInt(1)
func isqrt(x *big.Int) *big.Int {
if x.Cmp(zero) < 0 {
log.Fatal("Argument cannot be negative.")
}
q := big.NewInt(1)
for q.Cmp(x) <= 0 {
q.Lsh(q, 2)
}
z := new(big.Int).Set(x)
r := big.NewInt(0)
for q.Cmp(one) > 0 {
q.Rsh(q, 2)
t := new(big.Int)
t.Add(t, z)
t.Sub(t, r)
t.Sub(t, q)
r.Rsh(r, 1)
if t.Cmp(zero) >= 0 {
z.Set(t)
r.Add(r, q)
}
}
return r
}
func commatize(s string) string {
le := len(s)
for i := le - 3; i >= 1; i -= 3 {
s = s[0:i] + "," + s[i:]
}
return s
}
func main() {
fmt.Println("The integer square roots of integers from 0 to 65 are:")
for i := int64(0); i <= 65; i++ {
fmt.Printf("%d ", isqrt(big.NewInt(i)))
}
fmt.Println()
fmt.Println("\nThe integer square roots of powers of 7 from 7^1 up to 7^73 are:\n")
fmt.Println("power 7 ^ power integer square root")
fmt.Println("----- --------------------------------------------------------------------------------- -----------------------------------------")
pow7 := big.NewInt(7)
bi49 := big.NewInt(49)
for i := 1; i <= 73; i += 2 {
fmt.Printf("%2d%84s%41s\n", i, commatize(pow7.String()), commatize(isqrt(pow7).String()))
pow7.Mul(pow7, bi49)
}
} | 705Isqrt (integer square root) of X
| 0go
| gs94n |
char chr_legal[] = ;
int chr_idx[256] = {0};
char idx_chr[256] = {0};
typedef struct trie_t *trie, trie_t;
struct trie_t {
trie next[sizeof(chr_legal)];
int eow;
};
trie trie_new() { return calloc(sizeof(trie_t), 1); }
trie trie_trav(trie root, const char * str, int no_create)
{
int c;
while (root) {
if ((c = str[0]) == '\0') {
if (!root->eow && no_create) return 0;
break;
}
if (! (c = chr_idx[c]) ) {
str++;
continue;
}
if (!root->next[c]) {
if (no_create) return 0;
root->next[c] = trie_new();
}
root = root->next[c];
str++;
}
return root;
}
int trie_all(trie root, char path[], int depth, int (*callback)(char *))
{
int i;
if (root->eow && !callback(path)) return 0;
for (i = 1; i < sizeof(chr_legal); i++) {
if (!root->next[i]) continue;
path[depth] = idx_chr[i];
path[depth + 1] = '\0';
if (!trie_all(root->next[i], path, depth + 1, callback))
return 0;
}
return 1;
}
void add_index(trie root, const char *word, const char *fname)
{
trie x = trie_trav(root, word, 0);
x->eow = 1;
if (!x->next[FNAME])
x->next[FNAME] = trie_new();
x = trie_trav(x->next[FNAME], fname, 0);
x->eow = 1;
}
int print_path(char *path)
{
printf(, path);
return 1;
}
const char *files[] = { , , };
const char *text[][5] ={{ , , , , },
{ , , , 0 },
{ , , , , 0 }};
trie init_tables()
{
int i, j;
trie root = trie_new();
for (i = 0; i < sizeof(chr_legal); i++) {
chr_idx[(int)chr_legal[i]] = i + 1;
idx_chr[i + 1] = chr_legal[i];
}
void read_file(const char * fname) {
char cmd[1024];
char word[1024];
sprintf(cmd, \\n\, fname);
FILE *in = popen(cmd, );
while (!feof(in)) {
fscanf(in, , word);
add_index(root, word, fname);
}
pclose(in);
};
read_file();
read_file();
read_file();
for (i = 0; i < 3; i++) {
for (j = 0; j < 5; j++) {
if (!text[i][j]) break;
add_index(root, text[i][j], files[i]);
}
}
return root;
}
void search_index(trie root, const char *word)
{
char path[1024];
printf(%s\, word);
trie found = find_word(root, word);
if (!found) printf();
else {
trie_all(found->next[FNAME], path, 0, print_path);
printf();
}
}
int main()
{
trie root = init_tables();
search_index(root, );
search_index(root, );
search_index(root, );
search_index(root, );
return 0;
} | 708Inverted index
| 5c
| mk8ys |
null | 709Introspection
| 5c
| 4qz5t |
import Data.Char (isDigit)
import Data.List (mapAccumL)
import qualified Data.Map.Strict as M
import Data.Maybe (fromMaybe)
clockWorkTick ::
M.Map Char String ->
(M.Map Char String, Char)
clockWorkTick = flip click 'A'
where
click wheels name
| isDigit name = (wheels, name)
| otherwise =
( click
. flip
(M.insert name . leftRotate)
wheels
<*> head
)
$ fromMaybe ['?'] $ M.lookup name wheels
leftRotate :: [a] -> [a]
leftRotate = take . length <*> (tail . cycle)
main :: IO ()
main = do
let wheelSets =
[ [('A', "123")],
[('A', "1B2"), ('B', "34")],
[('A', "1DD"), ('D', "678")],
[('A', "1BC"), ('B', "34"), ('C', "5B")]
]
putStrLn "State of each wheel-set after 20 clicks:\n"
mapM_ print $
fmap
( flip
(mapAccumL (const . clockWorkTick))
(replicate 20 undefined)
. M.fromList
)
wheelSets
putStrLn "\nInitial state of the wheel-sets:\n"
mapM_ print wheelSets | 706Intersecting number wheels
| 8haskell
| 9bnmo |
import Data.Char (digitToInt, isDigit)
import Text.Printf (printf)
pair :: Num a => [a] -> [(a, a)]
pair [] = []
pair xs = p (take 2 xs): pair (drop 2 xs)
where
p ps = case ps of
(x: y: zs) -> (x, y)
(x: zs) -> (x, 0)
validIsbn13 :: String -> Bool
validIsbn13 isbn
| length (digits isbn) /= 13 = False
| otherwise = calc isbn `rem` 10 == 0
where
digits = map digitToInt . filter isDigit
calc = sum . map (\(x, y) -> x + y * 3) . pair . digits
main :: IO ()
main =
mapM_
(printf "%s: Valid:%s\n" <*> (show . validIsbn13))
[ "978-1734314502",
"978-1734314509",
"978-1788399081",
"978-1788399083"
] | 704ISBN13 check digit
| 8haskell
| kn5h0 |
null | 703Iterated digits squaring
| 11kotlin
| 37iz5 |
import Data.Bits
isqrt :: Integer -> Integer
isqrt n = go n 0 (q `shiftR` 2)
where
q = head $ dropWhile (< n) $ iterate (`shiftL` 2) 1
go z r 0 = r
go z r q = let t = z - r - q
in if t >= 0
then go t (r `shiftR` 1 + q) (q `shiftR` 2)
else go z (r `shiftR` 1) (q `shiftR` 2)
main = do
print $ isqrt <$> [1..65]
mapM_ print $ zip [1,3..73] (isqrt <$> iterate (49 *) 7) | 705Isqrt (integer square root) of X
| 8haskell
| s9bqk |
(let [version (Double/parseDouble (re-find #"\d*\.\d*" (System/getProperty "java.version")))]
(if (>= version 1.5)
(println "Version ok")
(throw (Error. "Bad version"))))
(let [version (Double/parseDouble (re-find #"\d*\.\d*" (clojure-version)))]
(if (>= version 1.0)
(println "Version ok")
(throw (Error. "Bad version")))) | 709Introspection
| 6clojure
| hi9jr |
squares = {}
for i = 0, 9 do
for j = 0, 9 do
squares[i * 10 + j] = i * i + j * j
end
end
for i = 1, 99 do
for j = 0, 99 do
squares[i * 100 + j] = squares[i] + squares[j]
end
end
function sum_squares(n)
if n < 9999.5 then
return squares[n]
else
local m = math.floor(n / 10000)
return squares[n - 10000 * m] + sum_squares(m)
end
end
memory = {}
function calc_1_or_89(n)
local m = {}
n = memory[n] or n
while n ~= 1 and n ~= 89 do
n = memory[n] or sum_squares(n)
table.insert(m, n)
end
for _, i in pairs(m) do
memory[i] = n
end
return n
end
counter = 0
for i = 1, 100000000 do
if calc_1_or_89(i) == 89 then
counter = counter + 1
end
end
print(counter) | 703Iterated digits squaring
| 1lua
| 6jn39 |
package intersectingNumberWheels;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.IntStream;
public class WheelController {
private static final String IS_NUMBER = "[0-9]";
private static final int TWENTY = 20;
private static Map<String, WheelModel> wheelMap;
public static void advance(String wheel) {
WheelModel w = wheelMap.get(wheel);
if (w.list.get(w.position).matches(IS_NUMBER)) {
w.printThePosition();
w.advanceThePosition();
} else {
String wheelName = w.list.get(w.position);
advance(wheelName);
w.advanceThePosition();
}
}
public static void run() {
System.out.println(wheelMap);
IntStream.rangeClosed(1, TWENTY).forEach(i -> advance("A"));
System.out.println();
wheelMap.clear();
}
public static void main(String[] args) {
wheelMap = new HashMap<>();
wheelMap.put("A", new WheelModel("A", "1", "2", "3"));
run();
wheelMap.put("A", new WheelModel("A", "1", "B", "2"));
wheelMap.put("B", new WheelModel("B", "3", "4"));
run();
wheelMap.put("A", new WheelModel("A", "1", "D", "D"));
wheelMap.put("D", new WheelModel("D", "6", "7", "8"));
run();
wheelMap.put("A", new WheelModel("A", "1", "B", "C"));
wheelMap.put("B", new WheelModel("B", "3", "4"));
wheelMap.put("C", new WheelModel("C", "5", "B"));
run();
}
}
class WheelModel {
String name;
List<String> list;
int position;
int endPosition;
private static final int INITIAL = 0;
public WheelModel(String name, String... values) {
super();
this.name = name.toUpperCase();
this.list = new ArrayList<>();
for (String value : values) {
list.add(value);
}
this.position = INITIAL;
this.endPosition = this.list.size() - 1;
}
@Override
public String toString() {
return list.toString();
}
public void advanceThePosition() {
if (this.position == this.endPosition) {
this.position = INITIAL; | 706Intersecting number wheels
| 9java
| tgqf9 |
public static void main(){
System.out.println(isISBN13("978-1734314502"));
System.out.println(isISBN13("978-1734314509"));
System.out.println(isISBN13("978-1788399081"));
System.out.println(isISBN13("978-1788399083"));
}
public static boolean isISBN13(String in){
int pre = Integer.parseInt(in.substring(0,3));
if (pre!=978)return false;
String postStr = in.substring(4);
if (postStr.length()!=10)return false;
int post = Integer.parseInt(postStr);
int sum = 38;
for(int x = 0; x<10;x+=2)
sum += (postStr.charAt(x)-48)*3 + ((postStr.charAt(x+1)-48));
if(sum%10==0) return true;
return false;
} | 704ISBN13 check digit
| 9java
| 4q958 |
(ns inverted-index.core
(:require [clojure.set:as sets]
[clojure.java.io:as io]))
(def pattern #"\w+")
(defn normalize [match] (.toLowerCase match))
(defn term-seq [text] (map normalize (re-seq pattern text)))
(defn set-assoc
"Produces map with v added to the set associated with key k in map m"
[m k v] (assoc m k (conj (get m k #{}) v)))
(defn index-file [index file]
(with-open [reader (io/reader file)]
(reduce
(fn [idx term] (set-assoc idx term file))
index
(mapcat term-seq (line-seq reader)))))
(defn make-index [files]
(reduce index-file {} files))
(defn search [index query]
(apply sets/intersection (map index (term-seq query)))) | 708Inverted index
| 6clojure
| vef2f |
(() => {
'use strict'; | 706Intersecting number wheels
| 10javascript
| mkiyv |
int main (int argc, char *argv[])
{
printf();
printf(, -(-2147483647-1));
printf(, 2000000000 + 2000000000);
printf(, -2147483647 - 2147483647);
printf(, 46341 * 46341);
printf(, (-2147483647-1) / -1);
printf();
printf(, -(-9223372036854775807-1));
printf(, 5000000000000000000+5000000000000000000);
printf(, -9223372036854775807 - 9223372036854775807);
printf(, 3037000500 * 3037000500);
printf(, (-9223372036854775807-1) / -1);
printf();
printf(, -4294967295U);
printf(, 3000000000U + 3000000000U);
printf(, 2147483647U - 4294967295U);
printf(, 65537U * 65537U);
printf();
printf(, -18446744073709551615LU);
printf(, 10000000000000000000LU + 10000000000000000000LU);
printf(, 9223372036854775807LU - 18446744073709551615LU);
printf(, 4294967296LU * 4294967296LU);
return 0;
} | 710Integer overflow
| 5c
| 5xfuk |
import java.math.BigInteger;
public class Isqrt {
private static BigInteger isqrt(BigInteger x) {
if (x.compareTo(BigInteger.ZERO) < 0) {
throw new IllegalArgumentException("Argument cannot be negative");
}
var q = BigInteger.ONE;
while (q.compareTo(x) <= 0) {
q = q.shiftLeft(2);
}
var z = x;
var r = BigInteger.ZERO;
while (q.compareTo(BigInteger.ONE) > 0) {
q = q.shiftRight(2);
var t = z;
t = t.subtract(r);
t = t.subtract(q);
r = r.shiftRight(1);
if (t.compareTo(BigInteger.ZERO) >= 0) {
z = t;
r = r.add(q);
}
}
return r;
}
public static void main(String[] args) {
System.out.println("The integer square root of integers from 0 to 65 are:");
for (int i = 0; i <= 65; i++) {
System.out.printf("%s ", isqrt(BigInteger.valueOf(i)));
}
System.out.println();
System.out.println("The integer square roots of powers of 7 from 7^1 up to 7^73 are:");
System.out.println("power 7 ^ power integer square root");
System.out.println("----- --------------------------------------------------------------------------------- -----------------------------------------");
var pow7 = BigInteger.valueOf(7);
var bi49 = BigInteger.valueOf(49);
for (int i = 1; i < 74; i += 2) {
System.out.printf("%2d%,84d%,41d\n", i, pow7, isqrt(pow7));
pow7 = pow7.multiply(bi49);
}
}
} | 705Isqrt (integer square root) of X
| 9java
| 1tgp2 |
import java.util.Collections
import java.util.stream.IntStream
object WheelController {
private val IS_NUMBER = "[0-9]".toRegex()
private const val TWENTY = 20
private var wheelMap = mutableMapOf<String, WheelModel>()
private fun advance(wheel: String) {
val w = wheelMap[wheel]
if (w!!.list[w.position].matches(IS_NUMBER)) {
w.printThePosition()
} else {
val wheelName = w.list[w.position]
advance(wheelName)
}
w.advanceThePosition()
}
private fun run() {
println(wheelMap)
IntStream.rangeClosed(1, TWENTY)
.forEach { advance("A") }
println()
wheelMap.clear()
}
@JvmStatic
fun main(args: Array<String>) {
wheelMap["A"] = WheelModel("1", "2", "3")
run()
wheelMap["A"] = WheelModel("1", "B", "2")
wheelMap["B"] = WheelModel("3", "4")
run()
wheelMap["A"] = WheelModel("1", "D", "D")
wheelMap["D"] = WheelModel("6", "7", "8")
run()
wheelMap["A"] = WheelModel("1", "B", "C")
wheelMap["B"] = WheelModel("3", "4")
wheelMap["C"] = WheelModel("5", "B")
run()
}
}
internal class WheelModel(vararg values: String?) {
var list = mutableListOf<String>()
var position: Int
private var endPosition: Int
override fun toString(): String {
return list.toString()
}
fun advanceThePosition() {
if (position == endPosition) {
position = INITIAL | 706Intersecting number wheels
| 11kotlin
| o218z |
package main
import "fmt"
func f(s1, s2, sep string) string {
return s1 + sep + sep + s2
}
func main() {
fmt.Println(f("Rosetta", "Code", ":"))
} | 707Interactive programming (repl)
| 0go
| e3ga6 |
C:\Apps\groovy>groovysh
Groovy Shell (1.6.2, JVM: 1.6.0_13)
Type 'help' or '\h' for help.
---------------------------------------------------------------------------------------------------
groovy:000> f = { a, b, sep -> a + sep + sep + b }
===> groovysh_evaluate$_run_closure1@5e8d7d
groovy:000> println f('Rosetta','Code',':')
Rosetta::Code
===> null
groovy:000> exit
C:\Apps\groovy> | 707Interactive programming (repl)
| 7groovy
| kn2h7 |
fun isValidISBN13(text: String): Boolean {
val isbn = text.replace(Regex("[- ]"), "")
return isbn.length == 13 && isbn.map { it - '0' }
.mapIndexed { index, value -> when (index% 2) { 0 -> value else -> 3 * value } }
.sum()% 10 == 0
} | 704ISBN13 check digit
| 11kotlin
| l1zcp |
use strict;
use warnings;
use List::Util qw(min max);
sub jaro {
my($s, $t) = @_;
my(@s_matches, @t_matches, $matches);
return 1 if $s eq $t;
my($s_len, @s) = (length $s, split //, $s);
my($t_len, @t) = (length $t, split //, $t);
my $match_distance = int (max($s_len, $t_len) / 2) - 1;
for my $i (0 .. $
my $start = max(0, $i - $match_distance);
my $end = min($i + $match_distance + 1, $t_len);
for my $j ($start .. $end - 1) {
next if $t_matches[$j] or $s[$i] ne $t[$j];
($s_matches[$i], $t_matches[$j]) = (1, 1);
$matches++ and last;
}
}
return 0 unless $matches;
my($k, $transpositions) = (0, 0);
for my $i (0 .. $
next unless $s_matches[$i];
$k++ until $t_matches[$k];
$transpositions++ if $s[$i] ne $t[$k];
$k++;
}
( $matches/$s_len + $matches/$t_len + (($matches - $transpositions/2) / $matches) ) / 3;
}
printf "%.3f\n", jaro(@$_[0], @$_[1]) for
['MARTHA', 'MARHTA'], ['DIXON', 'DICKSONX'], ['JELLYFISH', 'SMELLYFISH'],
['I repeat myself', 'I repeat myself'], ['', '']; | 701Jaro similarity
| 2perl
| 4q25d |
package main
import "fmt" | 702Josephus problem
| 0go
| r0vgm |
$ ghci
___ ___ _
/ _ \ /\ /\/ __(_)
/ /_\// /_/ / / | | GHC Interactive, version 6.4.2, for Haskell 98.
/ /_\\/ __ / /___| | http://www.haskell.org/ghc/
\____/\/ /_/\____/|_| Type:? for help.
Loading package base-1.0 ... linking ... done.
Prelude> let f as bs sep = as ++ sep ++ sep ++ bs
Prelude> f "Rosetta" "Code" ":"
"Rosetta::Code" | 707Interactive programming (repl)
| 8haskell
| 37szj |
function checkIsbn13(isbn)
local count = 0
local sum = 0
for c in isbn:gmatch"." do
if c == ' ' or c == '-' then | 704ISBN13 check digit
| 1lua
| 2a3l3 |
typedef struct{
double focalLength;
double resolution;
double memory;
}Camera;
typedef struct{
double balance;
double batteryLevel;
char** contacts;
}Phone;
typedef struct{
Camera cameraSample;
Phone phoneSample;
}CameraPhone; | 711Inheritance/Multiple
| 5c
| qm4xc |
import java.math.BigInteger
fun isqrt(x: BigInteger): BigInteger {
if (x < BigInteger.ZERO) {
throw IllegalArgumentException("Argument cannot be negative")
}
var q = BigInteger.ONE
while (q <= x) {
q = q.shiftLeft(2)
}
var z = x
var r = BigInteger.ZERO
while (q > BigInteger.ONE) {
q = q.shiftRight(2)
var t = z
t -= r
t -= q
r = r.shiftRight(1)
if (t >= BigInteger.ZERO) {
z = t
r += q
}
}
return r
}
fun main() {
println("The integer square root of integers from 0 to 65 are:")
for (i in 0..65) {
print("${isqrt(BigInteger.valueOf(i.toLong()))} ")
}
println()
println("The integer square roots of powers of 7 from 7^1 up to 7^73 are:")
println("power 7 ^ power integer square root")
println("----- --------------------------------------------------------------------------------- -----------------------------------------")
var pow7 = BigInteger.valueOf(7)
val bi49 = BigInteger.valueOf(49)
for (i in (1..73).step(2)) {
println("%2d%,84d%,41d".format(i, pow7, isqrt(pow7)))
pow7 *= bi49
}
} | 705Isqrt (integer square root) of X
| 11kotlin
| jo27r |
int[] Josephus (int size, int kill, int survivors) { | 702Josephus problem
| 7groovy
| vem28 |
use strict;
use warnings;
use feature 'say';
sub get_next {
my($w,%wheels) = @_;
my $wh = \@{$wheels{$w}};
my $value = $$wh[0][$$wh[1]];
$$wh[1] = ($$wh[1]+1) % @{$$wh[0]};
defined $wheels{$value} ? get_next($value,%wheels) : $value;
}
sub spin_wheels {
my(%wheels) = @_;
say "$_: " . join ', ', @{${$wheels{$_}}[0]} for sort keys %wheels;
print get_next('A', %wheels) . ' ' for 1..20; print "\n\n";
}
spin_wheels(%$_) for
(
{'A' => [['1', '2', '3'], 0]},
{'A' => [['1', 'B', '2'], 0], 'B' => [['3', '4'], 0]},
{'A' => [['1', 'D', 'D'], 0], 'D' => [['6', '7', '8'], 0]},
{'A' => [['1', 'B', 'C'], 0], 'B' => [['3', '4'], 0], 'C' => [['5', 'B'], 0]},
); | 706Intersecting number wheels
| 2perl
| gsm4e |
'''Jaro distance'''
from __future__ import division
def jaro(s, t):
'''Jaro distance between two strings.'''
s_len = len(s)
t_len = len(t)
if s_len == 0 and t_len == 0:
return 1
match_distance = (max(s_len, t_len)
s_matches = [False] * s_len
t_matches = [False] * t_len
matches = 0
transpositions = 0
for i in range(s_len):
start = max(0, i - match_distance)
end = min(i + match_distance + 1, t_len)
for j in range(start, end):
if t_matches[j]:
continue
if s[i] != t[j]:
continue
s_matches[i] = True
t_matches[j] = True
matches += 1
break
if matches == 0:
return 0
k = 0
for i in range(s_len):
if not s_matches[i]:
continue
while not t_matches[k]:
k += 1
if s[i] != t[k]:
transpositions += 1
k += 1
return ((matches / s_len) +
(matches / t_len) +
((matches - transpositions / 2) / matches)) / 3
def main():
'''Tests'''
for s, t in [('MARTHA', 'MARHTA'),
('DIXON', 'DICKSONX'),
('JELLYFISH', 'SMELLYFISH')]:
print(% (s, t, jaro(s, t)))
if __name__ == '__main__':
main() | 701Jaro similarity
| 3python
| gsv4h |
use warnings;
use strict;
my @sq = map { $_ ** 2 } 0 .. 9;
my %cache;
my $cnt = 0;
sub Euler92 {
my $n = 0 + join( '', sort split( '', shift ) );
$cache{$n} //= ($n == 1 || $n == 89) ? $n :
Euler92( sum( @sq[ split '', $n ] ) )
}
sub sum {
my $sum;
$sum += shift while @_;
$sum;
}
for (1 .. 100_000_000) {
++$cnt if Euler92( $_ ) == 89;
}
print $cnt; | 703Iterated digits squaring
| 2perl
| pfrb0 |
(defprotocol Camera)
(defprotocol MobilePhone)
(deftype CameraPhone []
Camera
MobilePhone) | 711Inheritance/Multiple
| 6clojure
| ivhom |
(* -1 (dec -9223372036854775807))
(+ 5000000000000000000 5000000000000000000)
(- -9223372036854775807 9223372036854775807)
(* 3037000500 3037000500) | 710Integer overflow
| 6clojure
| joy7m |
function isqrt(x)
local q = 1
local r = 0
while q <= x do
q = q << 2
end
while q > 1 do
q = q >> 2
local t = x - r - q
r = r >> 1
if t >= 0 then
x = t
r = r + q
end
end
return r
end
print("Integer square root for numbers 0 to 65:")
for n=0,65 do
io.write(isqrt(n) .. ' ')
end
print()
print()
print("Integer square roots of oddd powers of 7 from 1 to 21:")
print(" n | 7 ^ n | isqrt(7 ^ n)")
local p = 7
local n = 1
while n <= 21 do
print(string.format("%2d |%18d |%12d", n, p, isqrt(p))) | 705Isqrt (integer square root) of X
| 1lua
| hivj8 |
package main
import (
"debug/elf"
"debug/gosym"
"fmt"
"log"
"math"
"os"
"runtime"
)
var bloop = -3.4
func main() {
fmt.Println("task 1: verify version")
fmt.Println(" program compiled with", runtime.Version())
fmt.Println("task 2: check for presence of variable and function") | 709Introspection
| 0go
| o2k8q |
import Data.List ((\\))
import System.Environment (getArgs)
prisoners :: Int -> [Int]
prisoners n = [0 .. n - 1]
counter :: Int -> [Int]
counter k = cycle [k, k-1 .. 1]
killList :: [Int] -> [Int] -> ([Int], [Int], [Int])
killList xs cs = (killed, survivors, newCs)
where
(killed, newCs) = kill xs cs []
survivors = xs \\ killed
kill [] cs rs = (rs, cs)
kill (x:xs) (c:cs) rs
| c == 1 =
let ts = rs ++ [x]
in kill xs cs ts
| otherwise =
kill xs cs rs
killRecursive :: [Int] -> [Int] -> Int -> ([Int], [Int])
killRecursive xs cs m = killR ([], xs, cs)
where
killR (killed, remaining, counter)
| length remaining <= m = (killed, remaining)
| otherwise =
let (newKilled, newRemaining, newCounter) =
killList remaining counter
allKilled = killed ++ newKilled
in killR (allKilled, newRemaining, newCounter)
main :: IO ()
main = do
args <- getArgs
case args of
[n, k, m] -> print $ snd $ killRecursive (prisoners (read n))
(counter (read k)) (read m)
_ -> print $ snd $ killRecursive (prisoners 41) (counter 3) 1 | 702Josephus problem
| 8haskell
| 0ces7 |
public static void main(String[] args) {
System.out.println(concat("Rosetta", "Code", ":"));
}
public static String concat(String a, String b, String c) {
return a + c + c + b;
}
Rosetta::Code | 707Interactive programming (repl)
| 9java
| iv1os |
$ java -cp js.jar org.mozilla.javascript.tools.shell.Main
Rhino 1.7 release 2 2009 03 22
js> function f(a,b,s) {return a + s + s + b;}
js> f('Rosetta', 'Code', ':')
Rosetta::Code
js> quit()
$ | 707Interactive programming (repl)
| 10javascript
| zrqt2 |
import Data.Version
import Control.Monad
import System.Info
minGHCVersion = Version [6, 8] []
main = when (compilerName == "ghc" && compilerVersion < minGHCVersion) $
fail "Compiler too old." | 709Introspection
| 8haskell
| 2anll |
from itertools import islice
class INW():
def __init__(self, **wheels):
self._wheels = wheels
self.isect = {name: self._wstate(name, wheel)
for name, wheel in wheels.items()}
def _wstate(self, name, wheel):
assert all(val in self._wheels for val in wheel if type(val) == str), \
f
pos = 0
ln = len(wheel)
while True:
nxt, pos = wheel[pos% ln], pos + 1
yield next(self.isect[nxt]) if type(nxt) == str else nxt
def __iter__(self):
base_wheel_name = next(self.isect.__iter__())
yield from self.isect[base_wheel_name]
def __repr__(self):
return f
def __str__(self):
txt =
for name, wheel in self._wheels.items():
txt += f + ' '.join(str(v) for v in wheel)
return txt
def first(iter, n):
return ' '.join(f for nxt in islice(iter, n))
if __name__ == '__main__':
for group in[
{'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')},
]:
w = INW(**group)
print(f) | 706Intersecting number wheels
| 3python
| r09gq |
c:\kotlin-compiler-1.0.6>kotlinc
Welcome to Kotlin version 1.0.6-release-127 (JRE 1.8.0_31-b13)
Type :help for help, :quit for quit
>>> fun f(s1: String, s2: String, sep: String) = s1 + sep + sep + s2
>>> f("Rosetta", "Code", ":")
Rosetta::Code
>>> :quit | 707Interactive programming (repl)
| 11kotlin
| qmjx1 |
use strict;
use warnings;
use feature 'say';
sub check_digit {
my($isbn) = @_; my($sum);
$sum += (1,3)[$_%2] * (split '', join '', split /\D/, $isbn)[$_] for 0..11;
(10 - $sum % 10) % 10;
}
for (<978-1734314502 978-1734314509 978-1788399081 978-1788399083 978-2-74839-908-0 978-2-74839-908-5>) {
my($isbn,$check) = /(.*)(.)/;
my $check_d = check_digit($isbn);
say "$_: " . ($check == $check_d ? 'Good' : "Bad check-digit $check; should be $check_d")
} | 704ISBN13 check digit
| 2perl
| qmbx6 |
class Animal
{
}
class Dog : Animal
{
}
class Lab : Dog
{
}
class Collie : Dog
{
}
class Cat : Animal
{
} | 712Inheritance/Single
| 5c
| 37aza |
import java.util.ArrayList;
public class Josephus {
public static int execute(int n, int k){
int killIdx = 0;
ArrayList<Integer> prisoners = new ArrayList<Integer>(n);
for(int i = 0;i < n;i++){
prisoners.add(i);
}
System.out.println("Prisoners executed in order:");
while(prisoners.size() > 1){
killIdx = (killIdx + k - 1) % prisoners.size();
System.out.print(prisoners.get(killIdx) + " ");
prisoners.remove(killIdx);
}
System.out.println();
return prisoners.get(0);
}
public static ArrayList<Integer> executeAllButM(int n, int k, int m){
int killIdx = 0;
ArrayList<Integer> prisoners = new ArrayList<Integer>(n);
for(int i = 0;i < n;i++){
prisoners.add(i);
}
System.out.println("Prisoners executed in order:");
while(prisoners.size() > m){
killIdx = (killIdx + k - 1) % prisoners.size();
System.out.print(prisoners.get(killIdx) + " ");
prisoners.remove(killIdx);
}
System.out.println();
return prisoners;
}
public static void main(String[] args){
System.out.println("Survivor: " + execute(41, 3));
System.out.println("Survivors: " + executeAllButM(41, 3, 3));
}
} | 702Josephus problem
| 9java
| azh1y |
from math import ceil, log10, factorial
def next_step(x):
result = 0
while x > 0:
result += (x% 10) ** 2
x /= 10
return result
def check(number):
candidate = 0
for n in number:
candidate = candidate * 10 + n
while candidate != 89 and candidate != 1:
candidate = next_step(candidate)
if candidate == 89:
digits_count = [0] * 10
for d in number:
digits_count[d] += 1
result = factorial(len(number))
for c in digits_count:
result /= factorial(c)
return result
return 0
def main():
limit = 100000000
cache_size = int(ceil(log10(limit)))
assert 10 ** cache_size == limit
number = [0] * cache_size
result = 0
i = cache_size - 1
while True:
if i == 0 and number[i] == 9:
break
if i == cache_size - 1 and number[i] < 9:
number[i] += 1
result += check(number)
elif number[i] == 9:
i -= 1
else:
number[i] += 1
for j in xrange(i + 1, cache_size):
number[j] = number[i]
i = cache_size - 1
result += check(number)
print result
main() | 703Iterated digits squaring
| 3python
| 1t7pc |
package main
import "fmt"
func main() { | 710Integer overflow
| 0go
| 8lj0g |
char *get_line(FILE* fp)
{
int len = 0, got = 0, c;
char *buf = 0;
while ((c = fgetc(fp)) != EOF) {
if (got + 1 >= len) {
len *= 2;
if (len < 4) len = 4;
buf = realloc(buf, len);
}
buf[got++] = c;
if (c == '\n') break;
}
if (c == EOF && !got) return 0;
buf[got++] = '\0';
return buf;
}
int main()
{
char *s;
while ((s = get_line(stdin))) {
printf(,s);
free(s);
}
return 0;
} | 713Input loop
| 5c
| r0fg7 |
public class VersCheck {
public static void main(String[] args) {
String vers = System.getProperty("java.version");
vers = vers.substring(0,vers.indexOf('.')) + "." + | 709Introspection
| 9java
| 6jq3z |
var Josephus = {
init: function(n) {
this.head = {};
var current = this.head;
for (var i = 0; i < n-1; i++) {
current.label = i+1;
current.next = {prev: current};
current = current.next;
}
current.label = n;
current.next = this.head;
this.head.prev = current;
return this;
},
kill: function(spacing) {
var current = this.head;
while (current.next !== current) {
for (var i = 0; i < spacing-1; i++) {
current = current.next;
}
current.prev.next = current.next;
current.next.prev = current.prev;
current = current.next;
}
return current.label;
}
} | 702Josephus problem
| 10javascript
| s9aqz |
groups = [{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]} ]
groups.each do |group|
p group
wheels = group.transform_values(&:cycle)
res = 20.times.map do
el = wheels[:A].next
el = wheels[el].next until el.is_a?(Integer)
el
end
puts res.join(),
end | 706Intersecting number wheels
| 14ruby
| jol7x |
$ lua
Lua 5.1.2 Copyright (C) 1994-2007 Lua.org, PUC-Rio
> function conc(a, b, c)
>> return a..c..c..b
>> end
> print(conc("Rosetta", "Code", ":"))
Rosetta::Code
> | 707Interactive programming (repl)
| 1lua
| s9hq8 |
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 = []
t_matches = []
matches = 0.0
s_len.times do |i|
j_start = [0, i-match_distance].max
j_end = [i+match_distance, t_len-1].min
(j_start..j_end).each do |j|
t_matches[j] && next
s[i] == t[j] || next
s_matches[i] = true
t_matches[j] = true
matches += 1.0
break
end
end
return 0.0 if matches == 0.0
k = 0
transpositions = 0.0
s_len.times do |i|
s_matches[i] || next
k += 1 until t_matches[k]
s[i] == t[k] || (transpositions += 1.0)
k += 1
end
((matches / s_len) +
(matches / t_len) +
((matches - transpositions/2.0) / matches)) / 3.0
end
%w(
MARTHA MARHTA
DIXON DICKSONX
JELLYFISH SMELLYFISH
).each_slice(2) do |s,t|
puts
end | 701Jaro similarity
| 14ruby
| 785ri |
(gen-class:name Animal)
(gen-class:name Dog:extends Animal)
(gen-class:name Cat:extends Animal)
(gen-class:name Lab:extends Dog)
(gen-class:name Collie:extends Dog) | 712Inheritance/Single
| 6clojure
| cps9b |
null | 711Inheritance/Multiple
| 0go
| 2aol7 |
class Camera a
class MobilePhone a
class (Camera a, MobilePhone a) => CameraPhone a | 711Inheritance/Multiple
| 7groovy
| yhx6o |
class Camera a
class MobilePhone a
class (Camera a, MobilePhone a) => CameraPhone a | 711Inheritance/Multiple
| 8haskell
| az21g |
println "\nSigned 32-bit (failed):"
assert -(-2147483647-1) != 2147483648g
println(-(-2147483647-1))
assert 2000000000 + 2000000000 != 4000000000g
println(2000000000 + 2000000000)
assert -2147483647 - 2147483647 != -4294967294g
println(-2147483647 - 2147483647)
assert 46341 * 46341 != 2147488281g
println(46341 * 46341) | 710Integer overflow
| 7groovy
| w65el |
package main
import (
"bufio"
"bytes"
"errors"
"fmt"
"io"
"os"
) | 708Inverted index
| 0go
| az51f |
if (typeof bloop !== "undefined") { ... } | 709Introspection
| 10javascript
| l1icf |
use std::cmp;
pub fn jaro(s1: &str, s2: &str) -> f64 {
let s1_len = s1.len();
let s2_len = s2.len();
if s1_len == 0 && s2_len == 0 { return 1.0; }
let match_distance = cmp::max(s1_len, s2_len) / 2 - 1;
let mut s1_matches = vec![false; s1_len];
let mut s2_matches = vec![false; s2_len];
let mut m: isize = 0;
for i in 0..s1_len {
let start = cmp::max(0, i as isize - match_distance as isize) as usize;
let end = cmp::min(i + match_distance + 1, s2_len);
for j in start..end {
if!s2_matches[j] && s1.as_bytes()[i] == s2.as_bytes()[j] {
s1_matches[i] = true;
s2_matches[j] = true;
m += 1;
break;
}
}
}
if m == 0 { return 0.0; }
let mut t = 0.0;
let mut k = 0;
for i in 0..s1_len {
if s1_matches[i] {
while!s2_matches[k] { k += 1; }
if s1.as_bytes()[i]!= s2.as_bytes()[k] { t += 0.5; }
k += 1;
}
}
let m = m as f64;
(m / s1_len as f64 + m / s2_len as f64 + (m - t) / m) / 3.0
}
fn main() {
let pairs = [("MARTHA", "MARHTA"), ("DIXON", "DICKSONX"), ("JELLYFISH", "SMELLYFISH")];
for p in pairs.iter() { println!("{}/{} = {}", p.0, p.1, jaro(p.0, p.1)); }
} | 701Jaro similarity
| 15rust
| jo472 |
object Jaro extends App {
def distance(s1: String, s2: String): Double = {
val s1_len = s1.length
val s2_len = s2.length
if (s1_len == 0 && s2_len == 0) return 1.0
val match_distance = Math.max(s1_len, s2_len) / 2 - 1
val s1_matches = Array.ofDim[Boolean](s1_len)
val s2_matches = Array.ofDim[Boolean](s2_len)
var matches = 0
for (i <- 0 until s1_len) {
val start = Math.max(0, i - match_distance)
val end = Math.min(i + match_distance + 1, s2_len)
start until end find { j => !s2_matches(j) && s1(i) == s2(j) } match {
case Some(j) =>
s1_matches(i) = true
s2_matches(j) = true
matches += 1
case None =>
}
}
if (matches == 0) return 0.0
var t = 0.0
var k = 0
0 until s1_len filter s1_matches foreach { i =>
while (!s2_matches(k)) k += 1
if (s1(i) != s2(k)) t += 0.5
k += 1
}
val m = matches.toDouble
(m / s1_len + m / s2_len + (m - t) / m) / 3.0
}
val strings = List(("MARTHA", "MARHTA"), ("DIXON", "DICKSONX"), ("JELLYFISH", "SMELLYFISH"))
strings.foreach { s => println(distance(s._1, s._2)) }
} | 701Jaro similarity
| 16scala
| bd7k6 |
int main()
{
unsigned int i = 0;
while (++i) printf(, i);
return 0;
} | 714Integer sequence
| 5c
| 8l404 |
uint64_t digit_sum(uint64_t n, uint64_t sum) {
++sum;
while (n > 0 && n % 10 == 0) {
sum -= 9;
n /= 10;
}
return sum;
}
inline bool divisible(uint64_t n, uint64_t d) {
if ((d & 1) == 0 && (n & 1) == 1)
return false;
return n % d == 0;
}
int main() {
setlocale(LC_ALL, );
uint64_t previous = 1, gap = 0, sum = 0;
int niven_index = 0, gap_index = 1;
printf();
for (uint64_t niven = 1; gap_index <= 32; ++niven) {
sum = digit_sum(niven, sum);
if (divisible(niven, sum)) {
if (niven > previous + gap) {
gap = niven - previous;
printf(, gap_index++,
gap, niven_index, previous);
}
previous = niven;
++niven_index;
}
}
return 0;
} | 715Increasing gaps between consecutive Niven numbers
| 5c
| s9vq5 |
import Data.Int
import Data.Word
import Control.Exception
f x = do
catch (print x) (\e -> print (e :: ArithException))
main = do
f ((- (-2147483647 - 1)) :: Int32)
f ((2000000000 + 2000000000) :: Int32)
f (((-2147483647) - 2147483647) :: Int32)
f ((46341 * 46341) :: Int32)
f ((((-2147483647) - 1) `div` (-1)) :: Int32)
f ((- ((-9223372036854775807) - 1)) :: Int64)
f ((5000000000000000000 + 5000000000000000000) :: Int64)
f (((-9223372036854775807) - 9223372036854775807) :: Int64)
f ((3037000500 * 3037000500) :: Int64)
f ((((-9223372036854775807) - 1) `div` (-1)) :: Int64)
f ((-4294967295) :: Word32)
f ((3000000000 + 3000000000) :: Word32)
f ((2147483647 - 4294967295) :: Word32)
f ((65537 * 65537) :: Word32)
f ((-18446744073709551615) :: Word64)
f ((10000000000000000000 + 10000000000000000000) :: Word64)
f ((9223372036854775807 - 18446744073709551615) :: Word64)
f ((4294967296 * 4294967296) :: Word64) | 710Integer overflow
| 8haskell
| l1och |
(defn basic-input [fname]
(line-seq (java.io.BufferedReader. (java.io.FileReader. fname)))) | 713Input loop
| 6clojure
| bdykz |
import Control.Monad
import Data.Char (isAlpha, toLower)
import qualified Data.Map as M
import qualified Data.IntSet as S
import System.Environment (getArgs)
main = do
(files, _: q) <- liftM (break (== "
buildII files >>= mapM_ putStrLn . queryII q
data IIndex = IIndex
[FilePath]
(M.Map String S.IntSet)
deriving Show
buildII :: [FilePath] -> IO IIndex
buildII files =
liftM (IIndex files . foldl f M.empty . zip [0..]) $
mapM readFile files
where f m (i, s) =
foldl g m $ map (lowercase . filter isAlpha) $ words s
where g m word = M.insertWith S.union word (S.singleton i) m
queryII :: [String] -> IIndex -> [FilePath]
queryII q (IIndex files m) =
map (files !!) $ S.toList $ intersections $
map (\word -> M.findWithDefault S.empty (lowercase word) m) q
intersections [] = S.empty
intersections xs = foldl1 S.intersection xs
lowercase = map toLower | 708Inverted index
| 8haskell
| zrxt0 |
public interface Camera{ | 711Inheritance/Multiple
| 9java
| jo67c |
interface Camera {
val numberOfLenses : Int
}
interface MobilePhone {
fun charge(n : Int) {
if (n >= 0)
battery_level = (battery_level + n).coerceAtMost(100)
}
var battery_level : Int
}
data class CameraPhone(override val numberOfLenses : Int = 1, override var battery_level: Int) : Camera, MobilePhone
data class TwinLensCamera(override val numberOfLenses : Int = 2) : Camera
fun main(args: Array<String>) {
val c = CameraPhone(1, 50)
println(c)
c.charge(35)
println(c)
c.charge(78)
println(c)
println(listOf(c.javaClass.superclass) + c.javaClass.interfaces)
val c2 = TwinLensCamera()
println(c2)
println(listOf(c2.javaClass.superclass) + c2.javaClass.interfaces)
} | 711Inheritance/Multiple
| 11kotlin
| 5xdua |
public class integerOverflow {
public static void main(String[] args) {
System.out.println("Signed 32-bit:");
System.out.println(-(-2147483647-1));
System.out.println(2000000000 + 2000000000);
System.out.println(-2147483647 - 2147483647);
System.out.println(46341 * 46341);
System.out.println((-2147483647-1) / -1);
System.out.println("Signed 64-bit:");
System.out.println(-(-9223372036854775807L-1));
System.out.println(5000000000000000000L+5000000000000000000L);
System.out.println(-9223372036854775807L - 9223372036854775807L);
System.out.println(3037000500L * 3037000500L);
System.out.println((-9223372036854775807L-1) / -1);
}
} | 710Integer overflow
| 9java
| 37wzg |
use strict;
use warnings;
use bigint;
use CLDR::Number 'decimal_formatter';
sub integer_sqrt {
( my $x = $_[0] ) >= 0 or die;
my $q = 1;
while ($q <= $x) {
$q <<= 2
}
my ($z, $r) = ($x, 0);
while ($q > 1) {
$q >>= 2;
my $t = $z - $r - $q;
$r >>= 1;
if ($t >= 0) {
$z = $t;
$r += $q;
}
}
return $r
}
print "The integer square roots of integers from 0 to 65 are:\n";
print map { ( integer_sqrt $_ ) . ' ' } (0..65);
my $cldr = CLDR::Number->new();
my $decf = $cldr->decimal_formatter;
print "\nThe integer square roots of odd powers of 7 from 7^1 up to 7^73 are:\n";
print "power", " "x36, "7 ^ power", " "x60, "integer square root\n";
print "----- ", "-"x79, " ------------------------------------------\n";
for (my $i = 1; $i < 74; $i += 2) {
printf("%2s ", $i);
printf("%82s", $decf->format( 7**$i ) );
printf("%44s", $decf->format( integer_sqrt(7**$i) ) ) ;
print "\n";
} | 705Isqrt (integer square root) of X
| 2perl
| tgsfg |
null | 709Introspection
| 11kotlin
| d51nz |
null | 702Josephus problem
| 11kotlin
| hi4j3 |
def is_isbn13(n):
n = n.replace('-','').replace(' ', '')
if len(n) != 13:
return False
product = (sum(int(ch) for ch in n[::2])
+ sum(int(ch) * 3 for ch in n[1::2]))
return product% 10 == 0
if __name__ == '__main__':
tests = '''
978-1734314502
978-1734314509
978-1788399081
978-1788399083'''.strip().split()
for t in tests:
print(f) | 704ISBN13 check digit
| 3python
| s9pq9 |
func jaroWinklerMatch(_ s: String, _ t: String) -> Double {
let s_len: Int = s.count
let t_len: Int = t.count
if s_len == 0 && t_len == 0 {
return 1.0
}
if s_len == 0 || t_len == 0 {
return 0.0
}
var match_distance: Int = 0
if s_len == 1 && t_len == 1 {
match_distance = 1
} else {
match_distance = ([s_len, t_len].max()!/2) - 1
}
var s_matches = [Bool]()
var t_matches = [Bool]()
for _ in 1...s_len {
s_matches.append(false)
}
for _ in 1...t_len {
t_matches.append(false)
}
var matches: Double = 0.0
var transpositions: Double = 0.0
for i in 0...s_len-1 {
let start = [0, (i-match_distance)].max()!
let end = [(i + match_distance), t_len-1].min()!
if start > end {
break
}
for j in start...end {
if t_matches[j] {
continue
}
if s[String.Index.init(encodedOffset: i)]!= t[String.Index.init(encodedOffset: j)] {
continue
} | 701Jaro similarity
| 17swift
| r0ugg |
(map println (next (range))) | 714Integer sequence
| 6clojure
| f4hdm |
double inf(void) {
return HUGE_VAL;
}
int main() {
printf(, inf());
return 0;
} | 716Infinity
| 5c
| o2580 |
package main
import "fmt"
type is func() uint64
func newSum() is {
var ms is
ms = func() uint64 {
ms = newSum()
return ms()
}
var msd, d uint64
return func() uint64 {
if d < 9 {
d++
} else {
d = 0
msd = ms()
}
return msd + d
}
}
func newHarshard() is {
i := uint64(0)
sum := newSum()
return func() uint64 {
for i++; i%sum() != 0; i++ {
}
return i
}
}
func commatize(n uint64) string {
s := fmt.Sprintf("%d", n)
le := len(s)
for i := le - 3; i >= 1; i -= 3 {
s = s[0:i] + "," + s[i:]
}
return s
}
func main() {
fmt.Println("Gap Index of gap Starting Niven")
fmt.Println("=== ============= ==============")
h := newHarshard()
pg := uint64(0) | 715Increasing gaps between consecutive Niven numbers
| 0go
| ves2m |
function josephus(n, k, m)
local positions={}
for i=1,n do
table.insert(positions, i-1)
end
local i,j=1,1
local s='Execution order: '
while #positions>m do
if j==k then
s=s .. positions[i] .. ', '
table.remove(positions, i)
i=i-1
end
i=i+1
j=j+1
if i>#positions then i=1 end
if j>k then j=1 end
end
print(s:sub(1,#s-2) .. '.')
local s='Survivors: '
for _,v in pairs(positions) do s=s .. v .. ', ' end
print(s:sub(1,#s-2) .. '.')
end
josephus(41,3, 1) | 702Josephus problem
| 1lua
| kngh2 |
def iterated_square_digit(d)
f = Array.new(d+1){|n| (1..n).inject(1,:*)}
g = -> (n) { res = n.digits.sum{|d| d*d}
res==89? 0: res }
table = Array.new(d*81+1){|n| n.zero?? 1: (i=g.call(n))==89? 0: i}
table.collect!{|n| n = table[n] while n>1; n}
z = 0
[*0..9].repeated_combination(d) do |rc|
next if table[rc.inject(0){|g,n| g+n*n}].zero?
nn = [0] * 10
rc.each{|n| nn[n] += 1}
z += nn.inject(f[d]){|gn,n| gn / f[n]}
end
puts ,
end
[8, 11, 14, 17].each do |d|
t0 = Time.now
iterated_square_digit(d)
puts
end | 703Iterated digits squaring
| 14ruby
| e3hax |
##Inf
##-Inf
(Double/isInfinite ##Inf) | 716Infinity
| 6clojure
| tgjfv |
function setmetatables(t,mts) | 711Inheritance/Multiple
| 1lua
| 4qf5c |
import Control.Monad (guard)
import Text.Printf (printf)
import Data.List (intercalate, unfoldr)
import Data.List.Split (chunksOf)
import Data.Tuple (swap)
nivens :: [Int]
nivens = [1..] >>= \n -> guard (n `rem` digitSum n == 0) >> [n]
where
digitSum = sum . unfoldr (\x -> guard (x > 0) >> pure (swap $ x `quotRem` 10))
findGaps :: [(Int, Int, Int)]
findGaps = go (zip [1..] nivens) 0
where
go [] n = []
go r@((c, currentNiven):(_, nextNiven):xs) lastGap
| gap > lastGap = (gap, c, currentNiven): go (tail r) gap
| otherwise = go (tail r) lastGap
where
gap = nextNiven - currentNiven
go (x:xs) _ = []
thousands :: Int -> String
thousands = reverse . intercalate "," . chunksOf 3 . reverse . show
main :: IO ()
main = do
printf row "Gap" "Index of Gap" "Starting Niven"
mapM_ (\(gap, gapIndex, niven) -> printf row (show gap) (thousands gapIndex) (thousands niven))
$ takeWhile (\(_, gapIndex, _) -> gapIndex < 10_000_000) findGaps
where
row = "%5s%15s%15s\n" | 715Increasing gaps between consecutive Niven numbers
| 8haskell
| e39ai |
null | 710Integer overflow
| 11kotlin
| nubij |
package org.rosettacode;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Set;
public class InvertedIndex {
List<String> stopwords = Arrays.asList("a", "able", "about",
"across", "after", "all", "almost", "also", "am", "among", "an",
"and", "any", "are", "as", "at", "be", "because", "been", "but",
"by", "can", "cannot", "could", "dear", "did", "do", "does",
"either", "else", "ever", "every", "for", "from", "get", "got",
"had", "has", "have", "he", "her", "hers", "him", "his", "how",
"however", "i", "if", "in", "into", "is", "it", "its", "just",
"least", "let", "like", "likely", "may", "me", "might", "most",
"must", "my", "neither", "no", "nor", "not", "of", "off", "often",
"on", "only", "or", "other", "our", "own", "rather", "said", "say",
"says", "she", "should", "since", "so", "some", "than", "that",
"the", "their", "them", "then", "there", "these", "they", "this",
"tis", "to", "too", "twas", "us", "wants", "was", "we", "were",
"what", "when", "where", "which", "while", "who", "whom", "why",
"will", "with", "would", "yet", "you", "your");
Map<String, List<Tuple>> index = new HashMap<String, List<Tuple>>();
List<String> files = new ArrayList<String>();
public void indexFile(File file) throws IOException {
int fileno = files.indexOf(file.getPath());
if (fileno == -1) {
files.add(file.getPath());
fileno = files.size() - 1;
}
int pos = 0;
BufferedReader reader = new BufferedReader(new FileReader(file));
for (String line = reader.readLine(); line != null; line = reader
.readLine()) {
for (String _word : line.split("\\W+")) {
String word = _word.toLowerCase();
pos++;
if (stopwords.contains(word))
continue;
List<Tuple> idx = index.get(word);
if (idx == null) {
idx = new LinkedList<Tuple>();
index.put(word, idx);
}
idx.add(new Tuple(fileno, pos));
}
}
System.out.println("indexed " + file.getPath() + " " + pos + " words");
}
public void search(List<String> words) {
for (String _word : words) {
Set<String> answer = new HashSet<String>();
String word = _word.toLowerCase();
List<Tuple> idx = index.get(word);
if (idx != null) {
for (Tuple t : idx) {
answer.add(files.get(t.fileno));
}
}
System.out.print(word);
for (String f : answer) {
System.out.print(" " + f);
}
System.out.println("");
}
}
public static void main(String[] args) {
try {
InvertedIndex idx = new InvertedIndex();
for (int i = 1; i < args.length; i++) {
idx.indexFile(new File(args[i]));
}
idx.search(Arrays.asList(args[0].split(",")));
} catch (Exception e) {
e.printStackTrace();
}
}
private class Tuple {
private int fileno;
private int position;
public Tuple(int fileno, int position) {
this.fileno = fileno;
this.position = position;
}
}
} | 708Inverted index
| 9java
| o2b8d |
package main
import (
"fmt"
"go/ast"
"go/parser"
"strings"
"unicode"
)
func isValidIdentifier(identifier string) bool {
node, err := parser.ParseExpr(identifier)
if err != nil {
return false
}
ident, ok := node.(*ast.Ident)
return ok && ident.Name == identifier
}
type runeRanges struct {
ranges []string
hasStart bool
start rune
end rune
}
func (r *runeRanges) add(cp rune) {
if !r.hasStart {
r.hasStart = true
r.start = cp
r.end = cp
return
}
if cp == r.end+1 {
r.end = cp
return
}
r.writeTo(&r.ranges)
r.start = cp
r.end = cp
}
func (r *runeRanges) writeTo(ranges *[]string) {
if r.hasStart {
if r.start == r.end {
*ranges = append(*ranges, fmt.Sprintf("%U", r.end))
} else {
*ranges = append(*ranges, fmt.Sprintf("%U-%U", r.start, r.end))
}
}
}
func (r *runeRanges) String() string {
ranges := r.ranges
r.writeTo(&ranges)
return strings.Join(ranges, ", ")
}
func main() {
var validFirst runeRanges
var validFollow runeRanges
var validOnlyFollow runeRanges
for r := rune(0); r <= unicode.MaxRune; r++ {
first := isValidIdentifier(string([]rune{r}))
follow := isValidIdentifier(string([]rune{'_', r}))
if first {
validFirst.add(r)
}
if follow {
validFollow.add(r)
}
if follow && !first {
validOnlyFollow.add(r)
}
}
_, _ = fmt.Println("Valid first:", validFirst.String())
_, _ = fmt.Println("Valid follow:", validFollow.String())
_, _ = fmt.Println("Only follow:", validOnlyFollow.String())
} | 717Idiomatically determine all the characters that can be used for symbols
| 0go
| yhb64 |
fn digit_square_sum(mut num: usize) -> usize {
let mut sum = 0;
while num!= 0 {
sum += (num% 10).pow(2);
num /= 10;
}
sum
}
fn last_in_chain(num: usize) -> usize {
match num {
1 | 89 => num,
_ => last_in_chain(digit_square_sum(num)),
}
}
fn main() {
let count = (1..100_000_000).filter(|&n| last_in_chain(n) == 89).count();
println!("{}", count);
} | 703Iterated digits squaring
| 15rust
| w6ke4 |
import scala.annotation.tailrec
object Euler92 extends App {
override val executionStart = compat.Platform.currentTime
@tailrec
private def calcRec(i: Int): Int = {
@tailrec
def iter0(n: Int, total: Int): Int =
if (n > 0) {
val rest = n % 10
iter0(n / 10, total + rest * rest)
}
else total
if (i == 89 || i == 1) i else calcRec(iter0(i, 0))
}
private def calcConv(i: Int) = {
var n: Int = i
while (n != 89 && n != 1) {
var total = 0
while (n > 0) {
val x = n % 10
total += (x * x)
n /= 10
}
n = total
}
n
}
println((1 until 100000000).par.count(calcConv(_) == 89))
println(s"Runtime conventional loop.[total ${compat.Platform.currentTime - executionStart} ms]")
val executionStart0 = compat.Platform.currentTime
println((1 until 100000000).par.count(calcRec(_) == 89))
println(s"Runtime recursive loop. [total ${compat.Platform.currentTime - executionStart0} ms]")
} | 703Iterated digits squaring
| 16scala
| s91qo |
package main
import (
"fmt"
"math/big"
)
func rank(l []uint) (r big.Int) {
for _, n := range l {
r.Lsh(&r, n+1)
r.SetBit(&r, int(n), 1)
}
return
}
func unrank(n big.Int) (l []uint) {
m := new(big.Int).Set(&n)
for a := m.BitLen(); a > 0; {
m.SetBit(m, a-1, 0)
b := m.BitLen()
l = append(l, uint(a-b-1))
a = b
}
return
}
func main() {
var b big.Int
for i := 0; i <= 10; i++ {
b.SetInt64(int64(i))
u := unrank(b)
r := rank(u)
fmt.Println(i, u, &r)
}
b.SetString("12345678901234567890", 10)
u := unrank(b)
r := rank(u)
fmt.Printf("\n%v\n%d\n%d\n", &b, u, &r)
} | 718Index finite lists of positive integers
| 0go
| hinjq |
public class NivenNumberGaps { | 715Increasing gaps between consecutive Niven numbers
| 9java
| hitjm |
def isqrt ( x ):
q = 1
while q <= x:
q *= 4
z,r = x,0
while q > 1:
q /= 4
t,r = z-r-q,r/2
if t >= 0:
z,r = t,r+q
return r
print ' '.join( '%d'%isqrt( n ) for n in xrange( 66 ))
print '\n'.join( '{0:114,} = isqrt( 7^{1:3} )'.format( isqrt( 7**n ),n ) for n in range( 1,204,2 )) | 705Isqrt (integer square root) of X
| 3python
| zr0tt |
varid (small {small | large | digit | ' }) / reservedid
conid large {small | large | digit | ' }
reservedid case | class | data | default | deriving | do | else
| foreign | if | import | in | infix | infixl
| infixr | instance | let | module | newtype | of
| then | type | where | _
small ascSmall | uniSmall | _
ascSmall a | b | | z
uniSmall any Unicode lowercase letter
large ascLarge | uniLarge
ascLarge A | B | | Z
uniLarge any uppercase or titlecase Unicode letter
digit ascDigit | uniDigit
ascDigit 0 | 1 | | 9
uniDigit any Unicode decimal digit | 717Idiomatically determine all the characters that can be used for symbols
| 8haskell
| hidju |
import java.util.function.IntPredicate;
import java.util.stream.IntStream;
public class Test {
public static void main(String[] args) throws Exception {
print("Java Identifier start: ", 0, 0x10FFFF, 72,
Character::isJavaIdentifierStart, "%c");
print("Java Identifier part: ", 0, 0x10FFFF, 25,
Character::isJavaIdentifierPart, "[%d]");
print("Identifier ignorable: ", 0, 0x10FFFF, 25,
Character::isIdentifierIgnorable, "[%d]");
print("Unicode Identifier start: ", 0, 0x10FFFF, 72,
Character::isUnicodeIdentifierStart, "%c");
print("Unicode Identifier part: ", 0, 0x10FFFF, 25,
Character::isUnicodeIdentifierPart, "[%d]");
}
static void print(String msg, int start, int end, int limit,
IntPredicate p, String fmt) {
System.out.print(msg);
IntStream.rangeClosed(start, end)
.filter(p)
.limit(limit)
.forEach(cp -> System.out.printf(fmt, cp));
System.out.println("...");
}
} | 717Idiomatically determine all the characters that can be used for symbols
| 9java
| 5xsuf |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.