code
stringlengths 1
46.1k
⌀ | label
class label 1.18k
classes | domain_label
class label 21
classes | index
stringlengths 4
5
|
---|---|---|---|
sub shuffle {
my @a = @_;
foreach my $n (1 .. $
my $k = int rand $n + 1;
$k == $n or @a[$k, $n] = @a[$n, $k];
}
return @a;
} | 686Knuth shuffle
| 2perl
| uxavr |
WITH KnapsackItems (item, [weight], VALUE) AS
(
SELECT 'map',9, 150
UNION ALL SELECT 'compass',13, 35
UNION ALL SELECT 'water',153, 200
UNION ALL SELECT 'sandwich',50, 160
UNION ALL SELECT 'glucose',15, 60
UNION ALL SELECT 'tin',68, 45
UNION ALL SELECT 'banana',27, 60
UNION ALL SELECT 'apple',39, 40
UNION ALL SELECT 'cheese',23, 30
UNION ALL SELECT 'beer',52, 10
UNION ALL SELECT 'suntan cream',11, 70
UNION ALL SELECT 'camera',32, 30
UNION ALL SELECT 'T-shirt',24, 15
UNION ALL SELECT 'trousers',48, 10
UNION ALL SELECT 'umbrella',73, 40
UNION ALL SELECT 'waterproof trousers',42, 70
UNION ALL SELECT 'waterproof overclothes',43, 75
UNION ALL SELECT 'note-case',22, 80
UNION ALL SELECT 'sunglasses',7, 20
UNION ALL SELECT 'towel',18, 12
UNION ALL SELECT 'socks',4, 50
UNION ALL SELECT 'book',30, 10
)
SELECT *
INTO
FROM KnapsackItems;
WITH UNIQUEnTuples (n, Tuples, ID, [weight], VALUE) AS (
SELECT 1, CAST(item AS VARCHAR(8000)), item, [weight], VALUE
FROM
UNION ALL
SELECT 1 + n.n, t.item + ',' + n.Tuples, item, n.[weight] + t.[weight], n.VALUE + t.VALUE
FROM UNIQUEnTuples n
CROSS APPLY (
SELECT item, [weight], VALUE
FROM
WHERE t.item < n.ID AND n.[weight] + t.[weight] < 400) t
)
SELECT TOP 5 *
FROM UNIQUEnTuples
ORDER BY VALUE DESC, n, Tuples;
GO
DROP TABLE | 692Knapsack problem/0-1
| 19sql
| 4sk5x |
function yates_shuffle($arr){
$shuffled = Array();
while($arr){
$rnd = array_rand($arr);
$shuffled[] = $arr[$rnd];
array_splice($arr, $rnd, 1);
}
return $shuffled;
}
function knuth_shuffle(&$arr){
for($i=count($arr)-1;$i>0;$i--){
$rnd = mt_rand(0,$i);
list($arr[$i], $arr[$rnd]) = array($arr[$rnd], $arr[$i]);
}
} | 686Knuth shuffle
| 12php
| 8290m |
struct KnapsackItem {
var name: String
var weight: Int
var value: Int
}
func knapsack(items: [KnapsackItem], limit: Int) -> [KnapsackItem] {
var table = Array(repeating: Array(repeating: 0, count: limit + 1), count: items.count + 1)
for j in 1..<items.count+1 {
let item = items[j-1]
for w in 1..<limit+1 {
if item.weight > w {
table[j][w] = table[j-1][w]
} else {
table[j][w] = max(table[j-1][w], table[j-1][w-item.weight] + item.value)
}
}
}
var result = [KnapsackItem]()
var w = limit
for j in stride(from: items.count, to: 0, by: -1) where table[j][w]!= table[j-1][w] {
let item = items[j-1]
result.append(item)
w -= item.weight
}
return result
}
let items = [
KnapsackItem(name: "map", weight: 9, value: 150), KnapsackItem(name: "compass", weight: 13, value: 35),
KnapsackItem(name: "water", weight: 153, value: 200), KnapsackItem(name: "sandwich", weight: 50, value: 160),
KnapsackItem(name: "glucose", weight: 15, value: 60), KnapsackItem(name: "tin", weight: 68, value: 45),
KnapsackItem(name: "banana", weight: 27, value: 60), KnapsackItem(name: "apple", weight: 39, value: 40),
KnapsackItem(name: "cheese", weight: 23, value: 30), KnapsackItem(name: "beer", weight: 52, value: 10),
KnapsackItem(name: "suntan cream", weight: 11, value: 70), KnapsackItem(name: "camera", weight: 32, value: 30),
KnapsackItem(name: "t-shirt", weight: 24, value: 15), KnapsackItem(name: "trousers", weight: 48, value: 10),
KnapsackItem(name: "umbrella", weight: 73, value: 40), KnapsackItem(name: "waterproof trousers", weight: 42, value: 70),
KnapsackItem(name: "waterproof overclothes", weight: 43, value: 75), KnapsackItem(name: "note-case", weight: 22, value: 80),
KnapsackItem(name: "sunglasses", weight: 7, value: 20), KnapsackItem(name: "towel", weight: 18, value: 12),
KnapsackItem(name: "socks", weight: 4, value: 50), KnapsackItem(name: "book", weight: 30, value: 10)
]
let kept = knapsack(items: items, limit: 400)
print("Kept: ")
for item in kept {
print(" \(item.name)")
}
let (tValue, tWeight) = kept.reduce((0, 0), { ($0.0 + $1.value, $0.1 + $1.weight) })
print("For a total value of \(tValue) and a total weight of \(tWeight)") | 692Knapsack problem/0-1
| 17swift
| mbuyk |
from random import randrange
def knuth_shuffle(x):
for i in range(len(x)-1, 0, -1):
j = randrange(i + 1)
x[i], x[j] = x[j], x[i]
x = list(range(10))
knuth_shuffle(x)
print(, x) | 686Knuth shuffle
| 3python
| 5qeux |
int number_of_digits(int x){
int NumberOfDigits;
for(NumberOfDigits=0;x!=0;NumberOfDigits++){
x=x/10;
}
return NumberOfDigits;
}
int* convert_array(char array[], int NumberOfElements)
{
int *convertedArray=malloc(NumberOfElements*sizeof(int));
int originalElement, convertedElement;
for(convertedElement=0, originalElement=0; convertedElement<NumberOfElements; convertedElement++)
{
convertedArray[convertedElement]=atoi(&array[originalElement]);
originalElement+=number_of_digits(convertedArray[convertedElement])+1;
}
return convertedArray;
}
int isSorted(int array[], int numberOfElements){
int sorted=1;
for(int counter=0;counter<numberOfElements;counter++){
if(counter!=0 && array[counter-1]>array[counter]) sorted--;
}
return sorted;
}
int main(int argc, char* argv[])
{
int* convertedArray;
convertedArray=convert_array(*(argv+1), argc-1);
if(isSorted(convertedArray, argc-1)==1) printf();
else if(argc-1<=10) printf();
else printf();
free(convertedArray);
return 0;
} | 694JortSort
| 5c
| d43nv |
fisheryatesshuffle <- function(n)
{
pool <- seq_len(n)
a <- c()
while(length(pool) > 0)
{
k <- sample.int(length(pool), 1)
a <- c(a, pool[k])
pool <- pool[-k]
}
a
} | 686Knuth shuffle
| 13r
| labce |
int i;
double sum(int *i, int lo, int hi, double (*term)()) {
double temp = 0;
for (*i = lo; *i <= hi; (*i)++)
temp += term();
return temp;
}
double term_func() { return 1.0 / i; }
int main () {
printf(, sum(&i, 1, 100, term_func));
return 0;
} | 695Jensen's Device
| 5c
| e6qav |
(defn jort-sort [x] (= x (sort x))) | 694JortSort
| 6clojure
| 6hc3q |
int count_jewels(const char *s, const char *j) {
int count = 0;
for ( ; *s; ++s) if (strchr(j, *s)) ++count;
return count;
}
int main() {
printf(, count_jewels(, ));
printf(, count_jewels(, ));
return 0;
} | 696Jewels and stones
| 5c
| xmswu |
int jacobi(unsigned long a, unsigned long n) {
if (a >= n) a %= n;
int result = 1;
while (a) {
while ((a & 1) == 0) {
a >>= 1;
if ((n & 7) == 3 || (n & 7) == 5) result = -result;
}
SWAP(a, n);
if ((a & 3) == 3 && (n & 3) == 3) result = -result;
a %= n;
}
if (n == 1) return result;
return 0;
}
void print_table(unsigned kmax, unsigned nmax) {
printf();
for (int k = 0; k <= kmax; ++k) printf(, k);
printf();
for (int k = 0; k <= kmax; ++k) printf();
putchar('\n');
for (int n = 1; n <= nmax; n += 2) {
printf(, n);
for (int k = 0; k <= kmax; ++k)
printf(, jacobi(k, n));
putchar('\n');
}
}
int main() {
print_table(20, 21);
return 0;
} | 697Jacobi symbol
| 5c
| ykm6f |
package main
import (
"log"
"sort"
)
func main() {
log.Println(jortSort([]int{1, 2, 1, 11, 213, 2, 4})) | 694JortSort
| 0go
| 7obr2 |
class Array
def knuth_shuffle!
j = length
i = 0
while j > 1
r = i + rand(j)
self[i], self[r] = self[r], self[i]
i += 1
j -= 1
end
self
end
end
r = Hash.new(0)
100_000.times do |i|
a = [1,2,3].knuth_shuffle!
r[a] += 1
end
r.keys.sort.each {|a| puts } | 686Knuth shuffle
| 14ruby
| g0x4q |
import Data.List (sort)
jortSort :: (Ord a) => [a] -> Bool
jortSort list = list == sort list | 694JortSort
| 8haskell
| 82d0z |
public class JortSort {
public static void main(String[] args) {
System.out.println(jortSort(new int[]{1, 2, 3}));
}
static boolean jortSort(int[] arr) {
return true;
}
} | 694JortSort
| 9java
| e6sa5 |
use rand::Rng;
extern crate rand;
fn knuth_shuffle<T>(v: &mut [T]) {
let mut rng = rand::thread_rng();
let l = v.len();
for n in 0..l {
let i = rng.gen_range(0, l - n);
v.swap(i, l - n - 1);
}
}
fn main() {
let mut v: Vec<_> = (0..10).collect();
println!("before: {:?}", v);
knuth_shuffle(&mut v);
println!("after: {:?}", v);
} | 686Knuth shuffle
| 15rust
| r8qg5 |
var jortSort = function( array ) { | 694JortSort
| 10javascript
| 0lnsz |
def shuffle[T](a: Array[T]) = {
for (i <- 1 until a.size reverse) {
val j = util.Random nextInt (i + 1)
val t = a(i)
a(i) = a(j)
a(j) = t
}
a
} | 686Knuth shuffle
| 16scala
| hn8ja |
package main
import "fmt"
var i int
func sum(i *int, lo, hi int, term func() float64) float64 {
temp := 0.0
for *i = lo; *i <= hi; (*i)++ {
temp += term()
}
return temp
}
func main() {
fmt.Printf("%f\n", sum(&i, 1, 100, func() float64 { return 1.0 / float64(i) }))
} | 695Jensen's Device
| 0go
| 9p2mt |
package main
import (
"fmt"
"log"
"math/big"
)
func jacobi(a, n uint64) int {
if n%2 == 0 {
log.Fatal("'n' must be a positive odd integer")
}
a %= n
result := 1
for a != 0 {
for a%2 == 0 {
a /= 2
nn := n % 8
if nn == 3 || nn == 5 {
result = -result
}
}
a, n = n, a
if a%4 == 3 && n%4 == 3 {
result = -result
}
a %= n
}
if n == 1 {
return result
}
return 0
}
func main() {
fmt.Println("Using hand-coded version:")
fmt.Println("n/a 0 1 2 3 4 5 6 7 8 9")
fmt.Println("---------------------------------")
for n := uint64(1); n <= 17; n += 2 {
fmt.Printf("%2d ", n)
for a := uint64(0); a <= 9; a++ {
fmt.Printf("% d", jacobi(a, n))
}
fmt.Println()
}
ba, bn := new(big.Int), new(big.Int)
fmt.Println("\nUsing standard library function:")
fmt.Println("n/a 0 1 2 3 4 5 6 7 8 9")
fmt.Println("---------------------------------")
for n := uint64(1); n <= 17; n += 2 {
fmt.Printf("%2d ", n)
for a := uint64(0); a <= 9; a++ {
ba.SetUint64(a)
bn.SetUint64(n)
fmt.Printf("% d", big.Jacobi(ba, bn))
}
fmt.Println()
}
} | 697Jacobi symbol
| 0go
| 1zap5 |
def sum = { i, lo, hi, term ->
(lo..hi).sum { i.value = it; term() }
}
def obj = [:]
println (sum(obj, 1, 100, { 1 / obj.value })) | 695Jensen's Device
| 7groovy
| z7yt5 |
import Control.Monad.ST
import Data.STRef
sum_ :: STRef s Double -> Double -> Double -> ST s Double -> ST s Double
sum_ ref_i lo hi term = sum <$> mapM ((>> term) . writeSTRef ref_i) [lo .. hi]
foo :: Double
foo =
runST $
do i <- newSTRef undefined
sum_ i 1 100 $ recip <$> readSTRef i
main :: IO ()
main = print foo | 695Jensen's Device
| 8haskell
| bfak2 |
package main
import (
"fmt"
"strings"
)
func js(stones, jewels string) (n int) {
for _, b := range []byte(stones) {
if strings.IndexByte(jewels, b) >= 0 {
n++
}
}
return
}
func main() {
fmt.Println(js("aAAbbbb", "aA"))
} | 696Jewels and stones
| 0go
| lavcw |
jewelCount
:: Eq a
=> [a] -> [a] -> Int
jewelCount jewels = foldr go 0
where
go c
| c `elem` jewels = succ
| otherwise = id
main :: IO ()
main = mapM_ print $ uncurry jewelCount <$> [("aA", "aAAbbbb"), ("z", "ZZ")] | 696Jewels and stones
| 8haskell
| 1zeps |
jacobi :: Integer -> Integer -> Integer
jacobi 0 1 = 1
jacobi 0 _ = 0
jacobi a n =
let a_mod_n = rem a n
in if even a_mod_n
then case rem n 8 of
1 -> jacobi (div a_mod_n 2) n
3 -> negate $ jacobi (div a_mod_n 2) n
5 -> negate $ jacobi (div a_mod_n 2) n
7 -> jacobi (div a_mod_n 2) n
else if rem a_mod_n 4 == 3 && rem n 4 == 3
then negate $ jacobi n a_mod_n
else jacobi n a_mod_n | 697Jacobi symbol
| 8haskell
| trzf7 |
null | 694JortSort
| 11kotlin
| kdah3 |
import java.util.HashSet;
import java.util.Set;
public class App {
private static int countJewels(String stones, String jewels) {
Set<Character> bag = new HashSet<>();
for (char c : jewels.toCharArray()) {
bag.add(c);
}
int count = 0;
for (char c : stones.toCharArray()) {
if (bag.contains(c)) {
count++;
}
}
return count;
}
public static void main(String[] args) {
System.out.println(countJewels("aAAbbbb", "aA"));
System.out.println(countJewels("ZZ", "z"));
}
} | 696Jewels and stones
| 9java
| 7ohrj |
public class JacobiSymbol {
public static void main(String[] args) {
int max = 30;
System.out.printf("n\\k ");
for ( int k = 1 ; k <= max ; k++ ) {
System.out.printf("%2d ", k);
}
System.out.printf("%n");
for ( int n = 1 ; n <= max ; n += 2 ) {
System.out.printf("%2d ", n);
for ( int k = 1 ; k <= max ; k++ ) {
System.out.printf("%2d ", jacobiSymbol(k, n));
}
System.out.printf("%n");
}
} | 697Jacobi symbol
| 9java
| 82o06 |
import java.util.function.*;
import java.util.stream.*;
public class Jensen {
static double sum(int lo, int hi, IntToDoubleFunction f) {
return IntStream.rangeClosed(lo, hi).mapToDouble(f).sum();
}
public static void main(String args[]) {
System.out.println(sum(1, 100, (i -> 1.0/i)));
}
} | 695Jensen's Device
| 9java
| g0j4m |
function copy (t)
local new = {}
for k, v in pairs(t) do new[k] = v end
return new
end
function jortSort (array)
local originalArray = copy(array)
table.sort(array)
for i = 1, #originalArray do
if originalArray[i] ~= array[i] then return false end
end
return true
end | 694JortSort
| 1lua
| bfeka |
(() => { | 696Jewels and stones
| 10javascript
| ptab7 |
var obj;
function sum(o, lo, hi, term) {
var tmp = 0;
for (o.val = lo; o.val <= hi; o.val++)
tmp += term();
return tmp;
}
obj = {val: 0};
alert(sum(obj, 1, 100, function() {return 1 / obj.val})); | 695Jensen's Device
| 10javascript
| kd1hq |
null | 696Jewels and stones
| 11kotlin
| ux4vc |
fun jacobi(A: Int, N: Int): Int {
assert(N > 0 && N and 1 == 1)
var a = A % N
var n = N
var result = 1
while (a != 0) {
var aMod4 = a and 3
while (aMod4 == 0) { | 697Jacobi symbol
| 11kotlin
| wyxek |
function count_jewels(s, j)
local count = 0
for i=1,#s do
local c = s:sub(i,i)
if string.match(j, c) then
count = count + 1
end
end
return count
end
print(count_jewels("aAAbbbb", "aA"))
print(count_jewels("ZZ", "z")) | 696Jewels and stones
| 1lua
| 5qgu6 |
fun sum(lo: Int, hi: Int, f: (Int) -> Double) = (lo..hi).sumByDouble(f)
fun main(args: Array<String>) = println(sum(1, 100, { 1.0 / it })) | 695Jensen's Device
| 11kotlin
| 2e5li |
function sum(var, a, b, str)
local ret = 0
for i = a, b do
ret = ret + setfenv(loadstring("return "..str), {[var] = i})()
end
return ret
end
print(sum("i", 1, 100, "1/i")) | 695Jensen's Device
| 1lua
| vw42x |
use strict;
use warnings;
sub J {
my($k,$n) = @_;
$k %= $n;
my $jacobi = 1;
while ($k) {
while (0 == $k % 2) {
$k = int $k / 2;
$jacobi *= -1 if $n%8 == 3 or $n%8 == 5;
}
($k, $n) = ($n, $k);
$jacobi *= -1 if $n%4 == 3 and $k%4 == 3;
$k %= $n;
}
$n == 1 ? $jacobi : 0
}
my $maxa = 1 + (my $maxn = 29);
print 'n\k';
printf '%4d', $_ for 1..$maxa;
print "\n";
print ' ' . '-' x (4 * $maxa) . "\n";
for my $n (1..$maxn) {
next if 0 == $n % 2;
printf '%3d', $n;
printf '%4d', J($_, $n) for 1..$maxa;
print "\n"
} | 697Jacobi symbol
| 2perl
| la2c5 |
sub jortsort {
my @s=sort @_;
for (0..$
return 0 unless $_[$_] eq $s[$_];
}
1;
} | 694JortSort
| 2perl
| 3j9zs |
def jacobi(a, n):
if n <= 0:
raise ValueError()
if n% 2 == 0:
raise ValueError()
a%= n
result = 1
while a != 0:
while a% 2 == 0:
a /= 2
n_mod_8 = n% 8
if n_mod_8 in (3, 5):
result = -result
a, n = n, a
if a% 4 == 3 and n% 4 == 3:
result = -result
a%= n
if n == 1:
return result
else:
return 0 | 697Jacobi symbol
| 3python
| 2evlz |
import func Darwin.arc4random_uniform
extension Array {
func shuffle() -> Array {
var result = self; result.shuffleInPlace(); return result
}
mutating func shuffleInPlace() {
for i in 1 ..< count { swap(&self[i], &self[Int(arc4random_uniform(UInt32(i+1)))]) }
}
} | 686Knuth shuffle
| 17swift
| 4sw5g |
sub count_jewels {
my( $j, $s ) = @_;
my($c,%S);
$S{$_}++ for split //, $s;
$c += $S{$_} for split //, $j;
return "$c\n";
}
print count_jewels 'aA' , 'aAAbbbb';
print count_jewels 'z' , 'ZZ'; | 696Jewels and stones
| 2perl
| 82i0w |
>>> def jortsort(sequence):
return list(sequence) == sorted(sequence)
>>> for data in [(1,2,4,3), (14,6,8), ['a', 'c'], ['s', 'u', 'x'], 'CVGH', 'PQRST']:
print(f'jortsort({repr(data)}) is {jortsort(data)}')
jortsort((1, 2, 4, 3)) is False
jortsort((14, 6, 8)) is False
jortsort(['a', 'c']) is True
jortsort(['s', 'u', 'x']) is True
jortsort('CVGH') is False
jortsort('PQRST') is True
>>> | 694JortSort
| 3python
| 6hc3w |
def jacobi(a, n)
raise ArgumentError.new if n < 1 || n.even?
res = 1
until (a %= n) == 0
while a.even?
a >>= 1
res = -res if [3, 5].include? n % 8
end
a, n = n, a
res = -res if [a % 4, n % 4] == [3, 3]
end
n == 1? res: 0
end
puts
puts
puts
1.step(to: 17, by: 2) do |n|
printf(, n)
(0..10).each { |a| printf(, jacobi(a, n)) }
puts
end | 697Jacobi symbol
| 14ruby
| ux5vz |
fn jacobi(mut n: i32, mut k: i32) -> i32 {
assert!(k > 0 && k% 2 == 1);
n%= k;
let mut t = 1;
while n!= 0 {
while n% 2 == 0 {
n /= 2;
let r = k% 8;
if r == 3 || r == 5 {
t = -t;
}
}
std::mem::swap(&mut n, &mut k);
if n% 4 == 3 && k% 4 == 3 {
t = -t;
}
n%= k;
}
if k == 1 {
t
} else {
0
}
}
fn print_table(kmax: i32, nmax: i32) {
print!("n\\k|");
for k in 0..=kmax {
print!(" {:2}", k);
}
print!("\n----");
for _ in 0..=kmax {
print!("---");
}
println!();
for n in (1..=nmax).step_by(2) {
print!("{:2} |", n);
for k in 0..=kmax {
print!(" {:2}", jacobi(k, n));
}
println!();
}
}
fn main() {
print_table(20, 21);
} | 697Jacobi symbol
| 15rust
| 5q4uq |
package main
import (
"bytes"
"fmt"
"io/ioutil"
"log"
"sort"
)
func jaroSim(str1, str2 string) float64 {
if len(str1) == 0 && len(str2) == 0 {
return 1
}
if len(str1) == 0 || len(str2) == 0 {
return 0
}
match_distance := len(str1)
if len(str2) > match_distance {
match_distance = len(str2)
}
match_distance = match_distance/2 - 1
str1_matches := make([]bool, len(str1))
str2_matches := make([]bool, len(str2))
matches := 0.
transpositions := 0.
for i := range str1 {
start := i - match_distance
if start < 0 {
start = 0
}
end := i + match_distance + 1
if end > len(str2) {
end = len(str2)
}
for k := start; k < end; k++ {
if str2_matches[k] {
continue
}
if str1[i] != str2[k] {
continue
}
str1_matches[i] = true
str2_matches[k] = true
matches++
break
}
}
if matches == 0 {
return 0
}
k := 0
for i := range str1 {
if !str1_matches[i] {
continue
}
for !str2_matches[k] {
k++
}
if str1[i] != str2[k] {
transpositions++
}
k++
}
transpositions /= 2
return (matches/float64(len(str1)) +
matches/float64(len(str2)) +
(matches-transpositions)/matches) / 3
}
func jaroWinklerDist(s, t string) float64 {
ls := len(s)
lt := len(t)
lmax := lt
if ls < lt {
lmax = ls
}
if lmax > 4 {
lmax = 4
}
l := 0
for i := 0; i < lmax; i++ {
if s[i] == t[i] {
l++
}
}
js := jaroSim(s, t)
p := 0.1
ws := js + float64(l)*p*(1-js)
return 1 - ws
}
type wd struct {
word string
dist float64
}
func main() {
misspelt := []string{
"accomodate", "definately", "goverment", "occured", "publically",
"recieve", "seperate", "untill", "wich",
}
b, err := ioutil.ReadFile("unixdict.txt")
if err != nil {
log.Fatal("Error reading file")
}
words := bytes.Fields(b)
for _, ms := range misspelt {
var closest []wd
for _, w := range words {
word := string(w)
if word == "" {
continue
}
jwd := jaroWinklerDist(ms, word)
if jwd < 0.15 {
closest = append(closest, wd{word, jwd})
}
}
fmt.Println("Misspelt word:", ms, ":")
sort.Slice(closest, func(i, j int) bool { return closest[i].dist < closest[j].dist })
for i, c := range closest {
fmt.Printf("%0.4f%s\n", c.dist, c.word)
if i == 5 {
break
}
}
fmt.Println()
}
} | 698Jaro-Winkler distance
| 0go
| scsqa |
def jacobi(a_p: Int, n_p: Int): Int =
{
var a = a_p
var n = n_p
if (n <= 0) return -1
if (n % 2 == 0) return -1
a %= n
var result = 1
while (a != 0) {
while (a % 2 == 0) {
a /= 2
if (n % 8 == 3 || n % 8 == 5) result = -result
}
val t = a
a = n
n = t
if (a % 4 == 3 && n % 4 == 3) result = -result
a %= n
}
if (n != 1) result = 0
result
}
def main(args: Array[String]): Unit =
{
for {
a <- 0 until 11
n <- 1 until 31 by 2
} yield println("n = " + n + ", a = " + a + ": " + jacobi(a, n))
} | 697Jacobi symbol
| 16scala
| r87gn |
void jacobsthal(mpz_t r, unsigned long n) {
mpz_t s;
mpz_init(s);
mpz_set_ui(r, 1);
mpz_mul_2exp(r, r, n);
mpz_set_ui(s, 1);
if (n % 2) mpz_neg(s, s);
mpz_sub(r, r, s);
mpz_div_ui(r, r, 3);
}
void jacobsthal_lucas(mpz_t r, unsigned long n) {
mpz_t a;
mpz_init(a);
mpz_set_ui(r, 1);
mpz_mul_2exp(r, r, n);
mpz_set_ui(a, 1);
if (n % 2) mpz_neg(a, a);
mpz_add(r, r, a);
}
int main() {
int i, count;
mpz_t jac[30], j;
printf();
for (i = 0; i < 30; ++i) {
mpz_init(jac[i]);
jacobsthal(jac[i], i);
gmp_printf(, jac[i]);
if (!((i+1)%5)) printf();
}
printf();
mpz_init(j);
for (i = 0; i < 30; ++i) {
jacobsthal_lucas(j, i);
gmp_printf(, j);
if (!((i+1)%5)) printf();
}
printf();
for (i = 0; i < 20; ++i) {
mpz_mul(j, jac[i], jac[i+1]);
gmp_printf(, j);
if (!((i+1)%5)) printf();
}
printf();
for (i = 0, count = 0; count < 20; ++i) {
jacobsthal(j, i);
if (mpz_probab_prime_p(j, 15) > 0) {
gmp_printf(, j);
++count;
}
}
return 0;
} | 699Jacobsthal numbers
| 5c
| uw2v4 |
def countJewels(s, j):
return sum(x in j for x in s)
print countJewels(, )
print countJewels(, ) | 696Jewels and stones
| 3python
| ovn81 |
J_n_S <- function(stones ="aAAbbbb", jewels = "aA") {
stones <- unlist(strsplit(stones, split = ""))
jewels <- unlist(strsplit(jewels, split = ""))
count <- sum(stones%in% jewels)
}
print(J_n_S("aAAbbbb", "aA"))
print(J_n_S("ZZ", "z"))
print(J_n_S("lgGKJGljglghGLGHlhglghoIPOgfdtrdDCHnvbnmBVC", "fFgGhH")) | 696Jewels and stones
| 13r
| q90xs |
import java.io.*;
import java.util.*;
public class JaroWinkler {
public static void main(String[] args) {
try {
List<String> words = loadDictionary("linuxwords.txt");
String[] strings = {
"accomodate", "definately", "goverment", "occured",
"publically", "recieve", "seperate", "untill", "wich"
};
for (String string : strings) {
System.out.printf("Close dictionary words (distance < 0.15 using Jaro-Winkler distance) to '%s' are:\n"
+ " Word | Distance\n", string);
for (StringDistance s : withinDistance(words, 0.15, string, 5)) {
System.out.printf("%14s |%.4f\n", s.word, s.distance);
}
System.out.println();
}
} catch (Exception e) {
e.printStackTrace();
}
}
private static class StringDistance implements Comparable<StringDistance> {
private StringDistance(String word, double distance) {
this.word = word;
this.distance = distance;
}
public int compareTo(StringDistance s) {
return Double.compare(distance, s.distance);
}
private String word;
private double distance;
}
private static List<StringDistance> withinDistance(List<String> words,
double maxDistance, String string, int max) {
List<StringDistance> result = new ArrayList<>();
for (String word : words) {
double distance = jaroWinklerDistance(word, string);
if (distance <= maxDistance)
result.add(new StringDistance(word, distance));
}
Collections.sort(result);
if (result.size() > max)
result = result.subList(0, max);
return result;
}
private static double jaroWinklerDistance(String string1, String string2) {
int len1 = string1.length();
int len2 = string2.length();
if (len1 < len2) {
String s = string1;
string1 = string2;
string2 = s;
int tmp = len1;
len1 = len2;
len2 = tmp;
}
if (len2 == 0)
return len1 == 0 ? 0.0 : 1.0;
int delta = Math.max(1, len1 / 2) - 1;
boolean[] flag = new boolean[len2];
Arrays.fill(flag, false);
char[] ch1Match = new char[len1];
int matches = 0;
for (int i = 0; i < len1; ++i) {
char ch1 = string1.charAt(i);
for (int j = 0; j < len2; ++j) {
char ch2 = string2.charAt(j);
if (j <= i + delta && j + delta >= i && ch1 == ch2 && !flag[j]) {
flag[j] = true;
ch1Match[matches++] = ch1;
break;
}
}
}
if (matches == 0)
return 1.0;
int transpositions = 0;
for (int i = 0, j = 0; j < len2; ++j) {
if (flag[j]) {
if (string2.charAt(j) != ch1Match[i])
++transpositions;
++i;
}
}
double m = matches;
double jaro = (m / len1 + m / len2 + (m - transpositions / 2.0) / m) / 3.0;
int commonPrefix = 0;
len2 = Math.min(4, len2);
for (int i = 0; i < len2; ++i) {
if (string1.charAt(i) == string2.charAt(i))
++commonPrefix;
}
return 1.0 - (jaro + commonPrefix * 0.1 * (1.0 - jaro));
}
private static List<String> loadDictionary(String path) throws IOException {
try (BufferedReader reader = new BufferedReader(new FileReader(path))) {
List<String> words = new ArrayList<>();
String word;
while ((word = reader.readLine()) != null)
words.add(word);
return words;
}
}
} | 698Jaro-Winkler distance
| 9java
| trtf9 |
def jort_sort(array)
array == array.sort
end | 694JortSort
| 14ruby
| mb2yj |
use std::cmp::{Ord, Eq};
fn jort_sort<T: Ord + Eq + Clone>(array: Vec<T>) -> bool { | 694JortSort
| 15rust
| 9pvmm |
import Foundation
func jacobi(a: Int, n: Int) -> Int {
var a = a% n
var n = n
var res = 1
while a!= 0 {
while a & 1 == 0 {
a >>= 1
if n% 8 == 3 || n% 8 == 5 {
res = -res
}
}
(a, n) = (n, a)
if a% 4 == 3 && n% 4 == 3 {
res = -res
}
a%= n
}
return n == 1? res: 0
}
print("n/a 0 1 2 3 4 5 6 7 8 9")
print("---------------------------------")
for n in stride(from: 1, through: 17, by: 2) {
print(String(format: "%2d", n), terminator: "")
for a in 0..<10 {
print(String(format: "% d", jacobi(a: a, n: n)), terminator: "")
}
print()
} | 697Jacobi symbol
| 17swift
| vwu2r |
my $i;
sub sum {
my ($i, $lo, $hi, $term) = @_;
my $temp = 0;
for ($$i = $lo; $$i <= $hi; $$i++) {
$temp += $term->();
}
return $temp;
}
print sum(\$i, 1, 100, sub { 1 / $i }), "\n"; | 695Jensen's Device
| 2perl
| scoq3 |
import java.util.Objects.deepEquals
def jortSort[K:Ordering]( a:Array[K] ) = deepEquals(a.sorted, a) | 694JortSort
| 16scala
| 2e4lb |
$i;
function sum (&$i, $lo, $hi, $term) {
$temp = 0;
for ($i = $lo; $i <= $hi; $i++) {
$temp += $term();
}
return $temp;
}
echo sum($i, 1, 100, create_function('', 'global $i; return 1 / $i;')), ;
function sum ($lo,$hi)
{
$temp = 0;
for ($i = $lo; $i <= $hi; $i++)
{
$temp += (1 / $i);
}
return $temp;
}
echo sum(1,100); | 695Jensen's Device
| 12php
| uxgv5 |
func jortSort<T:Comparable>(array: [T]) -> Bool {
return array == sorted(array)
} | 694JortSort
| 17swift
| ykl6e |
package main
import (
"fmt"
"math/big"
)
func jacobsthal(n uint) *big.Int {
t := big.NewInt(1)
t.Lsh(t, n)
s := big.NewInt(1)
if n%2 != 0 {
s.Neg(s)
}
t.Sub(t, s)
return t.Div(t, big.NewInt(3))
}
func jacobsthalLucas(n uint) *big.Int {
t := big.NewInt(1)
t.Lsh(t, n)
a := big.NewInt(1)
if n%2 != 0 {
a.Neg(a)
}
return t.Add(t, a)
}
func main() {
jac := make([]*big.Int, 30)
fmt.Println("First 30 Jacobsthal numbers:")
for i := uint(0); i < 30; i++ {
jac[i] = jacobsthal(i)
fmt.Printf("%9d ", jac[i])
if (i+1)%5 == 0 {
fmt.Println()
}
}
fmt.Println("\nFirst 30 Jacobsthal-Lucas numbers:")
for i := uint(0); i < 30; i++ {
fmt.Printf("%9d ", jacobsthalLucas(i))
if (i+1)%5 == 0 {
fmt.Println()
}
}
fmt.Println("\nFirst 20 Jacobsthal oblong numbers:")
for i := uint(0); i < 20; i++ {
t := big.NewInt(0)
fmt.Printf("%11d ", t.Mul(jac[i], jac[i+1]))
if (i+1)%5 == 0 {
fmt.Println()
}
}
fmt.Println("\nFirst 20 Jacobsthal primes:")
for n, count := uint(0), 0; count < 20; n++ {
j := jacobsthal(n)
if j.ProbablyPrime(10) {
fmt.Println(j)
count++
}
}
} | 699Jacobsthal numbers
| 0go
| 0cqsk |
use strict;
use warnings;
use List::Util qw(min max head);
sub jaro_winkler {
my($s, $t) = @_;
my(@s_matches, @t_matches, $matches);
return 0 if $s eq $t;
my $s_len = length $s; my @s = split //, $s;
my $t_len = length $t; my @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, $t_len - 1);
for my $j ($start .. $end) {
next if $t_matches[$j] or $s[$i] ne $t[$j];
($s_matches[$i], $t_matches[$j]) = (1, 1);
$matches++ and last;
}
}
return 1 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++;
}
my $prefix = 0;
$s[$_] eq $t[$_] and ++$prefix for 0 .. -1 + min 5, $s_len, $t_len;
my $jaro = ($matches / $s_len + $matches / $t_len +
(($matches - $transpositions / 2) / $matches)) / 3;
1 - ($jaro + $prefix * .1 * ( 1 - $jaro) )
}
my @words = split /\n/, `cat ./unixdict.txt`;
for my $word (<accomodate definately goverment occured publically recieve seperate untill wich>) {
my %J;
$J{$_} = jaro_winkler($word, $_) for @words;
print "\nClosest 5 dictionary words with a Jaro-Winkler distance < .15 from '$word':\n";
printf "%15s:%0.4f\n", $_, $J{$_}
for head 5, sort { $J{$a} <=> $J{$b} or $a cmp $b } grep { $J{$_} < 0.15 } keys %J;
} | 698Jaro-Winkler distance
| 2perl
| g0g4e |
jacobsthal :: [Integer]
jacobsthal = 0: 1: zipWith (\x y -> 2 * x + y) jacobsthal (tail jacobsthal)
jacobsthalLucas :: [Integer]
jacobsthalLucas = 2: 1: zipWith (\x y -> 2 * x + y) jacobsthalLucas (tail jacobsthalLucas)
jacobsthalOblong :: [Integer]
jacobsthalOblong = zipWith (*) jacobsthal (tail jacobsthal)
isPrime :: Integer -> Bool
isPrime n = n > 1 && not (or [n `mod` i == 0 | i <- [2 .. floor (sqrt (fromInteger n))]])
main :: IO ()
main = do
putStrLn "First 30 Jacobsthal numbers:"
print $ take 30 jacobsthal
putStrLn ""
putStrLn "First 30 Jacobsthal-Lucas numbers:"
print $ take 30 jacobsthalLucas
putStrLn ""
putStrLn "First 20 Jacobsthal oblong numbers:"
print $ take 20 jacobsthalOblong
putStrLn ""
putStrLn "First 10 Jacobsthal primes:"
print $ take 10 $ filter isPrime jacobsthal | 699Jacobsthal numbers
| 8haskell
| cpm94 |
stones, jewels = ,
stones.count(jewels) | 696Jewels and stones
| 14ruby
| n5fit |
fn count_jewels(stones: &str, jewels: &str) -> u8 {
let mut count: u8 = 0;
for cur_char in stones.chars() {
if jewels.contains(cur_char) {
count += 1;
}
}
count
}
fn main() {
println!("{}", count_jewels("aAAbbbb", "aA"));
println!("{}", count_jewels("ZZ", "z"));
} | 696Jewels and stones
| 15rust
| d4tny |
class Ref(object):
def __init__(self, value=None):
self.value = value
def harmonic_sum(i, lo, hi, term):
temp = 0
i.value = lo
while i.value <= hi:
temp += term()
i.value += 1
return temp
i = Ref()
print harmonic_sum(i, 1, 100, lambda: 1.0/i.value) | 695Jensen's Device
| 3python
| 0lisq |
sum <- function(var, lo, hi, term)
eval(substitute({
.temp <- 0;
for (var in lo:hi) {
.temp <- .temp + term
}
.temp
}, as.list(match.call()[-1])),
enclos=parent.frame())
sum(i, 1, 100, 1/i)
x <- -1
sum(i, 1, 100, i^x) | 695Jensen's Device
| 13r
| wyse5 |
object JewelsStones extends App {
def countJewels(s: String, j: String): Int = s.count(i => j.contains(i))
println(countJewels("aAAbbbb", "aA"))
println(countJewels("ZZ", "z"))
} | 696Jewels and stones
| 16scala
| z76tr |
WORDS = [s.strip() for s in open().read().split()]
MISSPELLINGS = [
,
,
,
,
,
,
,
,
,
]
def jaro_winkler_distance(st1, st2):
if len(st1) < len(st2):
st1, st2 = st2, st1
len1, len2 = len(st1), len(st2)
if len2 == 0:
return 0.0
delta = max(0, len2
flag = [False for _ in range(len2)]
ch1_match = []
for idx1, ch1 in enumerate(st1):
for idx2, ch2 in enumerate(st2):
if idx2 <= idx1 + delta and idx2 >= idx1 - delta and ch1 == ch2 and not flag[idx2]:
flag[idx2] = True
ch1_match.append(ch1)
break
matches = len(ch1_match)
if matches == 0:
return 1.0
transpositions, idx1 = 0, 0
for idx2, ch2 in enumerate(st2):
if flag[idx2]:
transpositions += (ch2 != ch1_match[idx1])
idx1 += 1
jaro = (matches / len1 + matches / len2 + (matches - transpositions/2) / matches) / 3.0
commonprefix = 0
for i in range(min(4, len2)):
commonprefix += (st1[i] == st2[i])
return 1.0 - (jaro + commonprefix * 0.1 * (1 - jaro))
def within_distance(maxdistance, stri, maxtoreturn):
arr = [w for w in WORDS if jaro_winkler_distance(stri, w) <= maxdistance]
arr.sort(key=lambda x: jaro_winkler_distance(stri, x))
return arr if len(arr) <= maxtoreturn else arr[:maxtoreturn]
for STR in MISSPELLINGS:
print('\nClose dictionary words ( distance < 0.15 using Jaro-Winkler distance) to are:\n Word | Distance')
for w in within_distance(0.15, STR, 5):
print('{:>14} | {:6.4f}'.format(w, jaro_winkler_distance(STR, w))) | 698Jaro-Winkler distance
| 3python
| r8rgq |
-- See how many jewels are among the stones
DECLARE @S VARCHAR(1024) = 'AaBbCcAa'
, @J VARCHAR(1024) = 'aA';
DECLARE @SLEN INT = len(@S);
DECLARE @JLEN INT = len(@J);
DECLARE @TCNT INT = 0;
DECLARE @SPOS INT = 1; -- curr position in @S
DECLARE @JPOS INT = 1; -- curr position in @J
DECLARE @FCHR CHAR(1); -- char to find
while @JPOS <= @JLEN
BEGIN
SET @FCHR = SUBSTRING(@J, @JPOS, 1);
SET @SPOS = 1;
while @SPOS > 0 AND @SPOS <= @SLEN
BEGIN
SET @SPOS = charindex(@FCHR, @S COLLATE Latin1_General_CS_AS, @SPOS);
IF @SPOS > 0 BEGIN
SET @TCNT = @TCNT + 1;
SET @SPOS = @SPOS + 1;
END
END
SET @JPOS = @JPOS + 1;
END
print 'J='+@J+' S='+@S+' TOTAL = '+CAST(@TCNT AS VARCHAR(8)); | 696Jewels and stones
| 19sql
| yk96x |
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]} until @J > $n; $J[$n] }
sub jacobsthal_lucas { my($n) = @_; state @JL = (2, 1); do { push @JL, $JL[-1] + 2 * $JL[-2]} until @JL > $n; $JL[$n] }
my(@j,@jp,$c,$n);
push @j, jacobsthal $_ for 0..29;
do { is_prime($n = ( 2**++$c - -1**$c ) / 3) and push @jp, $n } until @jp == 20;
say "First 30 Jacobsthal numbers:\n", table @j;
say "First 30 Jacobsthal-Lucas numbers:\n", table map { jacobsthal_lucas $_-1 } 1..30;
say "First 20 Jacobsthal oblong numbers:\n", table map { $j[$_-1] * $j[$_] } 1..20;
say "First 20 Jacobsthal primes:\n", join "\n", @jp; | 699Jacobsthal numbers
| 2perl
| r04gd |
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")) | 696Jewels and stones
| 17swift
| iudo0 |
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(string1: &str, string2: &str) -> f64 {
let mut st1 = string1;
let mut st2 = string2;
let mut len1 = st1.chars().count();
let mut len2 = st2.chars().count();
if len1 < len2 {
std::mem::swap(&mut st1, &mut st2);
std::mem::swap(&mut len1, &mut len2);
}
if len2 == 0 {
return if len1 == 0 { 0.0 } else { 1.0 };
}
let delta = std::cmp::max(1, len1 / 2) - 1;
let mut flag = vec![false; len2];
let mut ch1_match = vec![];
for (idx1, ch1) in st1.chars().enumerate() {
for (idx2, ch2) in st2.chars().enumerate() {
if idx2 <= idx1 + delta && idx2 + delta >= idx1 && ch1 == ch2 &&!flag[idx2] {
flag[idx2] = true;
ch1_match.push(ch1);
break;
}
}
}
let matches = ch1_match.len();
if matches == 0 {
return 1.0;
}
let mut transpositions = 0;
let mut idx1 = 0;
for (idx2, ch2) in st2.chars().enumerate() {
if flag[idx2] {
transpositions += (ch2!= ch1_match[idx1]) as i32;
idx1 += 1;
}
}
let m = matches as f64;
let jaro =
(m / (len1 as f64) + m / (len2 as f64) + (m - (transpositions as f64) / 2.0) / m) / 3.0;
let mut commonprefix = 0;
for (c1, c2) in st1.chars().zip(st2.chars()).take(std::cmp::min(4, len2)) {
commonprefix += (c1 == c2) as i32;
}
1.0 - (jaro + commonprefix as f64 * 0.1 * (1.0 - jaro))
}
fn within_distance<'a>(
dict: &'a Vec<String>,
max_distance: f64,
stri: &str,
max_to_return: usize,
) -> Vec<(&'a String, f64)> {
let mut arr: Vec<(&String, f64)> = dict
.iter()
.map(|w| (w, jaro_winkler_distance(stri, w)))
.filter(|x| x.1 <= max_distance)
.collect(); | 698Jaro-Winkler distance
| 15rust
| hnhj2 |
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)
var st2 = Array(string2)
var len1 = st1.count
var len2 = st2.count
if len1 < len2 {
swap(&st1, &st2)
swap(&len1, &len2)
}
if len2 == 0 {
return len1 == 0? 0.0: 1.0
}
let delta = max(1, len1 / 2) - 1
var flag = Array(repeating: false, count: len2)
var ch1Match: [Character] = []
ch1Match.reserveCapacity(len1)
for idx1 in 0..<len1 {
let ch1 = st1[idx1]
for idx2 in 0..<len2 {
let ch2 = st2[idx2]
if idx2 <= idx1 + delta && idx2 + delta >= idx1 && ch1 == ch2 &&!flag[idx2] {
flag[idx2] = true
ch1Match.append(ch1)
break
}
}
}
let matches = ch1Match.count
if matches == 0 {
return 1.0
}
var transpositions = 0
var idx1 = 0
for idx2 in 0..<len2 {
if flag[idx2] {
if st2[idx2]!= ch1Match[idx1] {
transpositions += 1
}
idx1 += 1
}
}
let m = Double(matches)
let jaro =
(m / Double(len1) + m / Double(len2) + (m - Double(transpositions) / 2.0) / m) / 3.0
var commonPrefix = 0
for i in 0..<min(4, len2) {
if st1[i] == st2[i] {
commonPrefix += 1
}
}
return 1.0 - (jaro + Double(commonPrefix) * 0.1 * (1.0 - jaro))
}
func withinDistance(words: [String], maxDistance: Double, string: String,
maxToReturn: Int) -> [(String, Double)] {
var arr = Array(words.map{($0, jaroWinklerDistance(string1: string, string2: $0))}
.filter{$0.1 <= maxDistance})
arr.sort(by: { x, y in return x.1 < y.1 })
return Array(arr[0..<min(maxToReturn, arr.count)])
}
func pad(string: String, width: Int) -> String {
if string.count >= width {
return string
}
return String(repeating: " ", count: width - string.count) + string
}
do {
let dict = try loadDictionary("linuxwords.txt")
for word in ["accomodate", "definately", "goverment", "occured",
"publically", "recieve", "seperate", "untill", "wich"] {
print("Close dictionary words (distance < 0.15 using Jaro-Winkler distance) to '\(word)' are:")
print(" Word | Distance")
for (w, dist) in withinDistance(words: dict, maxDistance: 0.15,
string: word, maxToReturn: 5) {
print("\(pad(string: w, width: 14)) | \(String(format: "%6.4f", dist))")
}
print()
}
} catch {
print(error.localizedDescription)
} | 698Jaro-Winkler distance
| 17swift
| 7o7rq |
def sum(var, lo, hi, term, context)
sum = 0.0
lo.upto(hi) do |n|
sum += eval , context
end
sum
end
p sum , 1, 100, , binding | 695Jensen's Device
| 14ruby
| ovd8v |
var fs = require('fs') | 698Jaro-Winkler distance
| 20typescript
| 8280i |
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));
} | 695Jensen's Device
| 15rust
| iufod |
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) | 695Jensen's Device
| 16scala
| fg3d4 |
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,n)+pow(-1,n))
def jacobsthal_oblong(n):
return jacobsthal(n)*jacobsthal(n+1)
if __name__ == '__main__':
print()
for j in range(0, 30):
print(jacobsthal(j), end=)
print()
for j in range(0, 30):
print(jacobsthal_lucas(j), end = '\t')
print()
for j in range(0, 20):
print(jacobsthal_oblong(j), end=)
print()
for j in range(3, 33):
if isPrime(jacobsthal(j)):
print(jacobsthal(j)) | 699Jacobsthal numbers
| 3python
| 78grm |
int foo() { return 1; }
main()
{
int a = 0;
otherwise a = 4 given (foo());
printf(, a);
exit(0);
} | 700Inverted syntax
| 5c
| gsu45 |
(if (= 1 1)
(print "Math works."))
(->> (print "Math still works.")
(if (= 1 1)))
(->> (print a " is " b)
(let [a 'homoiconicity
b 'awesome])) | 700Inverted syntax
| 6clojure
| kn7hs |
double jaro(const char *str1, const char *str2) {
int str1_len = strlen(str1);
int str2_len = strlen(str2);
if (str1_len == 0) return str2_len == 0 ? 1.0 : 0.0;
int match_distance = (int) max(str1_len, str2_len)/2 - 1;
int *str1_matches = calloc(str1_len, sizeof(int));
int *str2_matches = calloc(str2_len, sizeof(int));
double matches = 0.0;
double transpositions = 0.0;
for (int i = 0; i < str1_len; i++) {
int start = max(0, i - match_distance);
int end = min(i + match_distance + 1, str2_len);
for (int k = start; k < end; k++) {
if (str2_matches[k]) continue;
if (str1[i] != str2[k]) continue;
str1_matches[i] = TRUE;
str2_matches[k] = TRUE;
matches++;
break;
}
}
if (matches == 0) {
free(str1_matches);
free(str2_matches);
return 0.0;
}
int k = 0;
for (int i = 0; i < str1_len; i++) {
if (!str1_matches[i]) continue;
while (!str2_matches[k]) k++;
if (str1[i] != str2[k]) transpositions++;
k++;
}
transpositions /= 2.0;
free(str1_matches);
free(str2_matches);
return ((matches / str1_len) +
(matches / str2_len) +
((matches - transpositions) / matches)) / 3.0;
}
int main() {
printf(, jaro(, ));
printf(, jaro(, ));
printf(, jaro(, ));
} | 701Jaro similarity
| 5c
| 2amlo |
var i = 42 | 695Jensen's Device
| 17swift
| 82n0v |
null | 699Jacobsthal numbers
| 15rust
| knjh5 |
(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))
matches 0
transpositions 0
fn-start (fn [i] (max 0 (- i match_distance)))
fn-end (fn [i] (min (+ i match_distance 1) (- t_len 1))) ]
(loop [i 0
start (fn-start i)
end (fn-end i)
k start
s_matches (vec (repeat (count s) false))
t_matches (vec (repeat (count t) false))
matches 0]
(if (< i s_len)
(if (<= k end)
(if (get t_matches k)
(recur i start end (inc k) s_matches t_matches matches)
(if (= (get s i) (get t k))
(recur (inc i) (fn-start (inc i)) (fn-end (inc i)) (fn-start (inc i)) (assoc s_matches i true) (assoc t_matches k true) (inc matches))
(recur i start end (inc k) s_matches t_matches matches)))
(recur (inc i) (fn-start (inc i)) (fn-end (inc i)) (fn-start (inc i)) s_matches t_matches matches))
[matches s_matches t_matches]))))
(defn count-transpositions [s t s_matches t_matches]
" Utility function to count the number of transpositions "
(let [s_len (count s)]
(loop [i 0
k 0
transpositions 0]
(if (< i s_len)
(if (not (get s_matches i nil))
(recur (inc i) k transpositions)
(if (not (get t_matches k nil))
(recur i (inc k) transpositions)
(if (not= (get s i) (get t k))
(recur (inc i) (inc k) (inc transpositions))
(recur (inc i) (inc k) transpositions))))
transpositions))))
(defn jaro [s t]
" Main Jaro Distance routine"
(if (= s t)
1
(let [[matches s_matches t_matches] (find-matches s t)]
(if (= 0 matches)
0
(let [s_len (count s)
t_len (count t)
transpositions (count-transpositions s t s_matches t_matches)]
(float (/ (+ (/ matches s_len) (/ matches t_len) (/ (- matches (/ transpositions 2)) matches)) 3)))))))
(println (jaro "MARTHA" "MARHTA"))
(println (jaro "DIXON" "DICKSONX"))
(println (jaro "JELLYFISH" "SMELLYFISH")) | 701Jaro similarity
| 6clojure
| gsv4f |
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 | 700Inverted syntax
| 0go
| iv0og |
when :: Monad m => m () -> Bool -> m ()
action `when` condition = if condition then action else return () | 700Inverted syntax
| 8haskell
| vec2k |
do ... while(condition); | 700Inverted syntax
| 9java
| yhz6g |
null | 700Inverted syntax
| 11kotlin
| f4ido |
int jos(int n, int k, int m) {
int a;
for (a = m + 1; a <= n; a++)
m = (m + k) % a;
return m;
}
typedef unsigned long long xint;
xint jos_large(xint n, xint k, xint m) {
if (k <= 1) return n - m - 1;
xint a = m;
while (a < n) {
xint q = (a - m + k - 2) / (k - 1);
if (a + q > n) q = n - a;
else if (!q) q = 1;
m = (m + q * k) % (a += q);
}
return m;
}
int main(void) {
xint n, k, i;
n = 41;
k = 3;
printf(, n, k, jos(n, k, 0));
n = 9876543210987654321ULL;
k = 12031;
printf(, n, k);
for (i = 3; i--; )
printf(, jos_large(n, k, i));
putchar('\n');
return 0;
} | 702Josephus problem
| 5c
| nusi6 |
if ($guess == 6) { print "Wow! Lucky Guess!"; };
print 'Wow! Lucky Guess!' if $guess == 6;
unless ($guess == 6) { print "Sorry, your guess was wrong!"; }
print 'Huh! You Guessed Wrong!' unless $guess == 6; | 700Inverted syntax
| 2perl
| hirjl |
typedef unsigned long long ull;
int is89(int x)
{
while (1) {
int s = 0;
do s += (x%10)*(x%10); while ((x /= 10));
if (s == 89) return 1;
if (s == 1) return 0;
x = s;
}
}
int main(void)
{
ull sums[32*81 + 1] = {1, 0};
for (int n = 1; ; n++) {
for (int i = n*81; i; i--) {
for (int j = 1; j < 10; j++) {
int s = j*j;
if (s > i) break;
sums[i] += sums[i-s];
}
}
ull count89 = 0;
for (int i = 1; i < n*81 + 1; i++) {
if (!is89(i)) continue;
if (sums[i] > ~0ULL - count89) {
printf(, n);
return 0;
}
count89 += sums[i];
}
printf(, n, count89);
}
return 0;
} | 703Iterated digits squaring
| 5c
| jou70 |
int check_isbn13(const char *isbn) {
int ch = *isbn, count = 0, sum = 0;
for ( ; ch != 0; ch = *++isbn, ++count) {
if (ch == ' ' || ch == '-') {
--count;
continue;
}
if (ch < '0' || ch > '9') {
return 0;
}
if (count & 1) {
sum += 3 * (ch - '0');
} else {
sum += ch - '0';
}
}
if (count != 13) return 0;
return !(sum%10);
}
int main() {
int i;
const char* isbns[] = {, , , };
for (i = 0; i < 4; ++i) {
printf(, isbns[i], check_isbn13(isbns[i]) ? : );
}
return 0;
} | 704ISBN13 check digit
| 5c
| az711 |
(defn rotate [n s] (lazy-cat (drop n s) (take n s)))
(defn josephus [n k]
(letfn [(survivor [[ h & r:as l] k]
(cond (empty? r) h
:else (survivor (rest (rotate (dec k) l)) k)))]
(survivor (range n) k)))
(let [n 41 k 3]
(println (str "Given " n " prisoners in a circle numbered 1.." n
", an executioner moving around the"))
(println (str "circle " k " at a time will leave prisoner number "
(inc (josephus n k)) " as the last survivor."))) | 702Josephus problem
| 6clojure
| 37nzr |
x = truevalue if condition else falsevalue | 700Inverted syntax
| 3python
| kn7hf |
do.if <- function(expr, cond) if(cond) expr | 700Inverted syntax
| 13r
| r05gj |
(ns async-example.core
(:require [clojure.math.numeric-tower :as math])
(:use [criterium.core])
(:gen-class))
(defn sum-sqr [digits]
" Square sum of list of digits "
(let [digits-sqr (fn [n]
(apply + (map #(* % %) digits)))]
(digits-sqr digits)))
(defn get-digits [n]
" Converts a digit to a list of digits (e.g. 545 -> ((5) (4) (5)) (used for squaring digits) "
(map #(Integer/valueOf (str %)) (String/valueOf n)))
(defn -isNot89 [x]
" Returns nil on 89 "
(cond
(= x 0) 0
(= x 89) nil
(= x 1) 0
(< x 10) (recur (* x x))
:else (recur (sum-sqr (get-digits x)))))
(def isNot89 (memoize -isNot89))
(defn direct-method [ndigits]
" Simple approach of looping through all the numbers from 0 to 10^ndigits - 1 "
(->>
(math/expt 10 ndigits)
(range 0)
(filter #(isNot89 (sum-sqr (get-digits %))))
(count)
(- (math/expt 10 ndigits))))
(time (println (direct-method 8))) | 703Iterated digits squaring
| 6clojure
| 1t7py |
int64_t isqrt(int64_t x) {
int64_t q = 1, r = 0;
while (q <= x) {
q <<= 2;
}
while (q > 1) {
int64_t t;
q >>= 2;
t = x - r - q;
r >>= 1;
if (t >= 0) {
x = t;
r += q;
}
}
return r;
}
int main() {
int64_t p;
int n;
printf();
for (n = 0; n <= 65; n++) {
printf(, isqrt(n));
}
printf();
printf();
printf();
p = 7;
for (n = 1; n <= 21; n += 2, p *= 49) {
printf(, n, p, isqrt(p));
}
} | 705Isqrt (integer square root) of X
| 5c
| iveo2 |
if n < 0 then raise ArgumentError, end
raise ArgumentError, if n < 0
unless Process.respond_to?:fork then exit 1 end
exit 1 unless Process.respond_to?:fork
while ary.length > 0 do puts ary.shift end
puts ary.shift while ary.length > 0
until ary.empty? do puts ary.shift end
puts ary.shift until ary.empty? | 700Inverted syntax
| 14ruby
| pfhbh |
object Main extends App {
val raining = true
val needUmbrella = raining
println(s"Do I need an umbrella? ${if (needUmbrella) "Yes" else "No"}")
} | 700Inverted syntax
| 16scala
| w61es |
infix operator ~= {}
infix operator! {}
func ~=(lhs:Int, inout rhs:Int) {
rhs = lhs
}
func!(lhs:(() -> Void), rhs:Bool) {
if (rhs) {
lhs()
}
} | 700Inverted syntax
| 17swift
| bdjkd |
package main
import "fmt"
func jaro(str1, str2 string) float64 {
if len(str1) == 0 && len(str2) == 0 {
return 1
}
if len(str1) == 0 || len(str2) == 0 {
return 0
}
match_distance := len(str1)
if len(str2) > match_distance {
match_distance = len(str2)
}
match_distance = match_distance/2 - 1
str1_matches := make([]bool, len(str1))
str2_matches := make([]bool, len(str2))
matches := 0.
transpositions := 0.
for i := range str1 {
start := i - match_distance
if start < 0 {
start = 0
}
end := i + match_distance + 1
if end > len(str2) {
end = len(str2)
}
for k := start; k < end; k++ {
if str2_matches[k] {
continue
}
if str1[i] != str2[k] {
continue
}
str1_matches[i] = true
str2_matches[k] = true
matches++
break
}
}
if matches == 0 {
return 0
}
k := 0
for i := range str1 {
if !str1_matches[i] {
continue
}
for !str2_matches[k] {
k++
}
if str1[i] != str2[k] {
transpositions++
}
k++
}
transpositions /= 2
return (matches/float64(len(str1)) +
matches/float64(len(str2)) +
(matches-transpositions)/matches) / 3
}
func main() {
fmt.Printf("%f\n", jaro("MARTHA", "MARHTA"))
fmt.Printf("%f\n", jaro("DIXON", "DICKSONX"))
fmt.Printf("%f\n", jaro("JELLYFISH", "SMELLYFISH"))
} | 701Jaro similarity
| 0go
| qmaxz |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.