code
stringlengths
1
46.1k
label
class label
1.18k classes
domain_label
class label
21 classes
index
stringlengths
4
5
package main import "fmt" type point struct { x, y float64 } func (p point) String() string { return fmt.Sprintf("(%.1f,%.1f)", p.x, p.y) } type triangle struct { p1, p2, p3 point } func (t *triangle) String() string { return fmt.Sprintf("Triangle%s,%s,%s", t.p1, t.p2, t.p3) } func (t *triangle) det2D() float64 { return t.p1.x * (t.p2.y - t.p3.y) + t.p2.x * (t.p3.y - t.p1.y) + t.p3.x * (t.p1.y - t.p2.y) } func (t *triangle) checkTriWinding(allowReversed bool) { detTri := t.det2D() if detTri < 0.0 { if allowReversed { a := t.p3 t.p3 = t.p2 t.p2 = a } else { panic("Triangle has wrong winding direction.") } } } func boundaryCollideChk(t *triangle, eps float64) bool { return t.det2D() < eps } func boundaryDoesntCollideChk(t *triangle, eps float64) bool { return t.det2D() <= eps } func triTri2D(t1, t2 *triangle, eps float64, allowReversed, onBoundary bool) bool {
950Determine if two triangles overlap
0go
sfbqa
int isNumeric (const char * s) { if (s == NULL || *s == '\0' || isspace(*s)) return 0; char * p; strtod (s, &p); return *p == '\0'; }
956Determine if a string is numeric
5c
a8211
null
948Determine if a string is collapsible
9java
7avrj
package main import "fmt" func analyze(s string) { chars := []rune(s) le := len(chars) fmt.Printf("Analyzing%q which has a length of%d:\n", s, le) if le > 1 { for i := 1; i < le; i++ { if chars[i] != chars[i-1] { fmt.Println(" Not all characters in the string are the same.") fmt.Printf(" %q (%#[1]x) is different at position%d.\n\n", chars[i], i+1) return } } } fmt.Println(" All characters in the string are the same.\n") } func main() { strings := []string{ "", " ", "2", "333", ".55", "tttTTT", "4444 444k", "pp", "", "", } for _, s := range strings { analyze(s) } }
949Determine if a string has all the same characters
0go
10rp5
import Data.Bifunctor (bimap) import Data.List (unfoldr) import Data.Tuple (swap) digSum :: Int -> Int -> Int digSum base = sum . unfoldr f where f 0 = Nothing f n = Just (swap (quotRem n base)) digRoot :: Int -> Int -> (Int, Int) digRoot base = head . dropWhile ((>= base) . snd) . iterate (bimap succ (digSum base)) . (,) 0 main :: IO () main = do putStrLn "in base 10:" mapM_ (print . ((,) <*> digRoot 10)) [627615, 39390, 588225, 393900588225]
945Digital root
8haskell
wi1ed
import Stream._ object MDR extends App { def mdr(x: BigInt, base: Int = 10): (BigInt, Long) = { def multiplyDigits(x: BigInt): BigInt = ((x.toString(base) map (_.asDigit)) :\ BigInt(1))(_*_) def loop(p: BigInt, c: Long): (BigInt, Long) = if (p < base) (p, c) else loop(multiplyDigits(p), c+1) loop(multiplyDigits(x), 1) } printf("%15s\t%10s\t%s\n","Number","MDR","MP") printf("%15s\t%10s\t%s\n","======","===","==") Seq[BigInt](123321, 7739, 893, 899998, BigInt("393900588225"), BigInt("999999999999")) foreach {x => val (s, c) = mdr(x) printf("%15s\t%10s\t%2s\n",x,s,c) } println val mdrs: Stream[Int] => Stream[(Int, BigInt)] = i => i map (x => (x, mdr(x)._1)) println("MDR: [n0..n4]") println("==== ========") ((for {i <- 0 to 9} yield (mdrs(from(0)) take 11112 toList) filter {_._2 == i}) .map {_ take 5} map {xs => xs map {_._1}}).zipWithIndex .foreach{p => printf("%3s: [%s]\n",p._2,p._1.mkString(", "))} }
936Digital root/Multiplicative digital root
16scala
iy6ox
use strict; use warnings; use feature <state say>; use List::Util 1.33 qw(pairmap); use Algorithm::Permute qw(permute); our %predicates = ( 'on bottom' => [ '' , '$f[%s] == 1' ], 'on top' => [ '' , '$f[%s] == @f' ], 'lower than' => [ 'person' , '$f[%s] < $f[%s]' ], 'higher than' => [ 'person' , '$f[%s] > $f[%s]' ], 'directly below' => [ 'person' , '$f[%s] == $f[%s] - 1' ], 'directly above' => [ 'person' , '$f[%s] == $f[%s] + 1' ], 'adjacent to' => [ 'person' , 'abs($f[%s] - $f[%s]) == 1' ], 'on' => [ 'ordinal' , '$f[%s] == \'%s\'' ], ); our %nouns = ( 'person' => qr/[a-z]+/i, 'ordinal' => qr/1st | 2nd | 3rd | \d+th/x, ); sub parse_and_solve { my @facts = @_; state $parser = qr/^(?<subj>$nouns{person}) (?<not>not )?(?|@{[ join '|', pairmap { "(?<pred>$a)" . ($b->[0] ? " (?<obj>$nouns{$b->[0]})" : '') } %predicates ]})$/; my (@expressions, %ids, $i); my $id = sub { defined $_[0] ? $ids{$_[0]} //= $i++ : () }; foreach (@facts) { /$parser/ or die "Cannot parse '$_'\n"; my $pred = $predicates{$+{pred}}; { no warnings; my $expr = '(' . sprintf($pred->[1], $id->($+{subj}), $pred->[0] eq 'person' ? $id->($+{obj}) : $+{obj}). ')'; $expr = '!' . $expr if $+{not}; push @expressions, $expr; } } my @f = 1..$i; eval ' permute { say join(", ", pairmap { "$f[$b] $a" }%ids) if ('.join(' && ', @expressions).'); } @f;'; }
939Dinesman's multiple-dwelling problem
2perl
5b7u2
dotp :: Num a => [a] -> [a] -> a dotp a b | length a == length b = sum (zipWith (*) a b) | otherwise = error "Vector sizes must match" main = print $ dotp [1, 3, -5] [4, -2, -1]
938Dot product
8haskell
6ul3k
null
954Deming's Funnel
11kotlin
hw9j3
(defprotocol Thing (thing [_])) (defprotocol Operation (operation [_])) (defrecord Delegator [delegate] Operation (operation [_] (try (thing delegate) (catch IllegalArgumentException e "default implementation")))) (defrecord Delegate [] Thing (thing [_] "delegate implementation"))
955Delegates
6clojure
102py
import java.util.function.BiFunction class TriangleOverlap { private static class Pair { double first double second Pair(double first, double second) { this.first = first this.second = second } @Override String toString() { return String.format("(%s,%s)", first, second) } } private static class Triangle { Pair p1, p2, p3 Triangle(Pair p1, Pair p2, Pair p3) { this.p1 = p1 this.p2 = p2 this.p3 = p3 } @Override String toString() { return String.format("Triangle:%s,%s,%s", p1, p2, p3) } } private static double det2D(Triangle t) { Pair p1 = t.p1 Pair p2 = t.p2 Pair p3 = t.p3 return p1.first * (p2.second - p3.second) + p2.first * (p3.second - p1.second) + p3.first * (p1.second - p2.second) } private static void checkTriWinding(Triangle t, boolean allowReversed) { double detTri = det2D(t) if (detTri < 0.0) { if (allowReversed) { Pair a = t.p3 t.p3 = t.p2 t.p2 = a } else throw new RuntimeException("Triangle has wrong winding direction") } } private static boolean boundaryCollideChk(Triangle t, double eps) { return det2D(t) < eps } private static boolean boundaryDoesntCollideChk(Triangle t, double eps) { return det2D(t) <= eps } private static boolean triTri2D(Triangle t1, Triangle t2) { return triTri2D(t1, t2, 0.0, false, true) } private static boolean triTri2D(Triangle t1, Triangle t2, double eps, boolean allowedReversed) { return triTri2D(t1, t2, eps, allowedReversed, true) } private static boolean triTri2D(Triangle t1, Triangle t2, double eps, boolean allowedReversed, boolean onBoundary) {
950Determine if two triangles overlap
7groovy
a8r1p
package main import ( "fmt" "permute" ) func determinant(m [][]float64) (d float64) { p := make([]int, len(m)) for i := range p { p[i] = i } it := permute.Iter(p) for s := it(); s != 0; s = it() { pr := 1. for i, := range p { pr *= m[i][] } d += float64(s) * pr } return } func permanent(m [][]float64) (d float64) { p := make([]int, len(m)) for i := range p { p[i] = i } it := permute.Iter(p) for s := it(); s != 0; s = it() { pr := 1. for i, := range p { pr *= m[i][] } d += pr } return } var m2 = [][]float64{ {1, 2}, {3, 4}} var m3 = [][]float64{ {2, 9, 4}, {7, 5, 3}, {6, 1, 8}} func main() { fmt.Println(determinant(m2), permanent(m2)) fmt.Println(determinant(m3), permanent(m3)) }
947Determinant and permanent
0go
94zmt
String.prototype.collapse = function() { let str = this; for (let i = 0; i < str.length; i++) { while (str[i] == str[i+1]) str = str.substr(0,i) + str.substr(i+1); } return str; }
948Determine if a string is collapsible
10javascript
psrb7
class Main { static void main(String[] args) { String[] tests = ["", " ", "2", "333", ".55", "tttTTT", "4444 444k"] for (String s: tests) { analyze(s) } } static void analyze(String s) { println("Examining [$s] which has a length of ${s.length()}") if (s.length() > 1) { char firstChar = s.charAt(0) int lastIndex = s.lastIndexOf(firstChar as String) if (lastIndex != 0) { println("\tNot all characters in the string are the same.") println("\t'$firstChar' (0x${Integer.toHexString(firstChar as Integer)}) is different at position $lastIndex") return } } println("\tAll characters in the string are the same.") } }
949Determine if a string has all the same characters
7groovy
jev7o
fun main() { val testStrings = arrayOf( "", "\"If I were two-faced, would I be wearing this one?\" --- Abraham Lincoln ", "..1111111111111111111111111111111111111111111111111111111111111117777888", "I never give 'em hell, I just tell the truth, and they think it's hell. ", " --- Harry S Truman ", "122333444455555666666777777788888888999999999", "The better the 4-wheel drive, the further you'll be from help when ya get stuck!", "headmistressship") val testChar = arrayOf( " ", "-", "7", ".", " -r", "5", "e", "s") for (testNum in testStrings.indices) { val s = testStrings[testNum] for (c in testChar[testNum].toCharArray()) { val result = squeeze(s, c) System.out.printf("use: '%c'%nold: %2d &gt;&gt;&gt;%s&lt;&lt;&lt;%nnew: %2d &gt;&gt;&gt;%s&lt;&lt;&lt;%n%n", c, s.length, s, result.length, result) } } } private fun squeeze(input: String, include: Char): String { val sb = StringBuilder() for (i in input.indices) { if (i == 0 || input[i - 1] != input[i] || input[i - 1] == input[i] && input[i] != include) { sb.append(input[i]) } } return sb.toString() }
946Determine if a string is squeezable
11kotlin
kxrh3
isOverlapping :: Triangle Double -> Triangle Double -> Bool isOverlapping t1 t2 = vertexInside || midLineInside where vertexInside = any (isInside t1) (vertices t2) || any (isInside t2) (vertices t1) isInside t = (Outside /=) . overlapping t midLineInside = any (\p -> isInside t1 p && isInside t2 p) midPoints midPoints = [ intersections l1 l2 | l1 <- midLines t1 , l2 <- midLines t2 ] intersections (a1,b1,c1) (a2,b2,c2) = ( -(-b2*c1+b1*c2)/(a2*b1-a1*b2) , -(a2*c1-a1*c2)/(a2*b1-a1*b2) ) midLines (Triangle a b c) = [line a b c, line b c a, line c a b] line (x,y) (ax, ay) (bx, by) = (ay+by-2*y, -ax-bx+2*x, -ay*x-by*x+ax*y+bx*y) test = map (uncurry isOverlapping) [ (Triangle (0,0) (5,0) (0,5), Triangle (0,0) (5,0) (0,6)) , (Triangle (0,0) (0,5) (5,0), Triangle (0,0) (0,5) (5,0)) , (Triangle (0,0) (5,0) (0,5), Triangle (-10,0) (-5,0) (-1,6)) , (Triangle (0,0) (5,0) (2.5,5), Triangle (0,4) (2.5,-1) (5,4)) , (Triangle (0,0) (1,1) (0,2), Triangle (2,1) (3,0) (3,2)) , (Triangle (0,0) (1,1) (0,2), Triangle (2,1) (3,-2) (3,4)) , (Triangle (0,0) (1,0) (0,1), Triangle (1,0) (2,0) (1,1))]
950Determine if two triangles overlap
8haskell
94dmo
int main() { remove(); remove(); remove(); remove(); return 0; }
957Delete a file
5c
i6jo2
sPermutations :: [a] -> [([a], Int)] sPermutations = flip zip (cycle [1, -1]) . foldl aux [[]] where aux items x = do (f, item) <- zip (cycle [reverse, id]) items f (insertEv x item) insertEv x [] = [[x]] insertEv x l@(y:ys) = (x: l): ((y:) <$>) (insertEv x ys) elemPos :: [[a]] -> Int -> Int -> a elemPos ms i j = (ms !! i) !! j prod :: Num a => ([[a]] -> Int -> Int -> a) -> [[a]] -> [Int] -> a prod f ms = product . zipWith (f ms) [0 ..] sDeterminant :: Num a => ([[a]] -> Int -> Int -> a) -> [[a]] -> [([Int], Int)] -> a sDeterminant f ms = sum . fmap (\(is, s) -> fromIntegral s * prod f ms is) determinant :: Num a => [[a]] -> a determinant ms = sDeterminant elemPos ms . sPermutations $ [0 .. pred . length $ ms] permanent :: Num a => [[a]] -> a permanent ms = sum . fmap (prod elemPos ms . fst) . sPermutations $ [0 .. pred . length $ ms] result :: (Num a, Show a) => [[a]] -> String result ms = unlines [ "Matrix:" , unlines (show <$> ms) , "Determinant:" , show (determinant ms) , "Permanent:" , show (permanent ms) ] main :: IO () main = mapM_ (putStrLn . result) [ [[5]] , [[1, 0, 0], [0, 1, 0], [0, 0, 1]] , [[0, 0, 1], [0, 1, 0], [1, 0, 0]] , [[4, 3], [2, 5]] , [[2, 5], [4, 3]] , [[4, 4], [2, 2]] ]
947Determinant and permanent
8haskell
bqrk2
(defn numeric? [s] (if-let [s (seq s)] (let [s (if (= (first s) \-) (next s) s) s (drop-while #(Character/isDigit %) s) s (if (= (first s) \.) (next s) s) s (drop-while #(Character/isDigit %) s)] (empty? s))))
956Determine if a string is numeric
6clojure
sfgqr
fun collapse(s: String): String { val cs = StringBuilder() var last: Char = 0.toChar() for (c in s) { if (c != last) { cs.append(c) last = c } } return cs.toString() } fun main() { val strings = arrayOf( "", "\"If I were two-faced, would I be wearing this one?\" --- Abraham Lincoln ", "..1111111111111111111111111111111111111111111111111111111111111117777888", "I never give 'em hell, I just tell the truth, and they think it's hell. ", " --- Harry S Truman ", "The better the 4-wheel drive, the further you'll be from help when ya get stuck!", "headmistressship", "aardvark" ) for (s in strings) { val c = collapse(s) println("original: length = ${s.length}, string = $s") println("collapsed: length = ${c.length}, string = $c") println() } }
948Determine if a string is collapsible
11kotlin
uhmvc
import Numeric (showHex) import Data.List (span) import Data.Char (ord) inconsistentChar :: Eq a => [a] -> Maybe (Int, a) inconsistentChar [] = Nothing inconsistentChar xs@(x:_) = let (pre, post) = span (x ==) xs in if null post then Nothing else Just (length pre, head post) samples :: [String] samples = [" ", "2", "333", ".55", "tttTTT", "4444 444"] main :: IO () main = do let w = succ . maximum $ length <$> samples justifyRight n c = (drop . length) <*> (replicate n c ++) f = (++ "' -> ") . justifyRight w ' ' . ('\'':) (putStrLn . unlines) $ (\s -> maybe (f s ++ "consistent") (\(n, c) -> f s ++ "inconsistent '" ++ c: "' (0x" ++ showHex (ord c) ")" ++ " at char " ++ show (succ n)) (inconsistentChar s)) <$> samples
949Determine if a string has all the same characters
8haskell
tc0f7
import java.math.BigInteger; class DigitalRoot { public static int[] calcDigitalRoot(String number, int base) { BigInteger bi = new BigInteger(number, base); int additivePersistence = 0; if (bi.signum() < 0) bi = bi.negate(); BigInteger biBase = BigInteger.valueOf(base); while (bi.compareTo(biBase) >= 0) { number = bi.toString(base); bi = BigInteger.ZERO; for (int i = 0; i < number.length(); i++) bi = bi.add(new BigInteger(number.substring(i, i + 1), base)); additivePersistence++; } return new int[] { additivePersistence, bi.intValue() }; } public static void main(String[] args) { for (String arg : args) { int[] results = calcDigitalRoot(arg, 10); System.out.println(arg + " has additive persistence " + results[0] + " and digital root of " + results[1]); } } }
945Digital root
9java
kx7hm
function squeezable(s, rune) print("squeeze: `" .. rune .. "`") print("old: <<<" .. s .. ">>>, length = " .. string.len(s)) local last = nil local le = 0 io.write("new: <<<") for c in s:gmatch"." do if c ~= last or c ~= rune then io.write(c) le = le + 1 end last = c end print(">>>, length = " .. le) print() end function main() squeezable("", ' '); squeezable("\"If I were two-faced, would I be wearing this one?\"
946Determine if a string is squeezable
1lua
bq7ka
class Delegator { var delegate; String operation() { if (delegate == null) return "default implementation"; else return delegate.thing(); } } class Delegate { String thing() => "delegate implementation"; } main() {
955Delegates
18dart
uhdvs
import java.util.function.BiFunction; public class TriangleOverlap { private static class Pair { double first; double second; Pair(double first, double second) { this.first = first; this.second = second; } @Override public String toString() { return String.format("(%s,%s)", first, second); } } private static class Triangle { Pair p1, p2, p3; Triangle(Pair p1, Pair p2, Pair p3) { this.p1 = p1; this.p2 = p2; this.p3 = p3; } @Override public String toString() { return String.format("Triangle:%s,%s,%s", p1, p2, p3); } } private static double det2D(Triangle t) { Pair p1 = t.p1; Pair p2 = t.p2; Pair p3 = t.p3; return p1.first * (p2.second - p3.second) + p2.first * (p3.second - p1.second) + p3.first * (p1.second - p2.second); } private static void checkTriWinding(Triangle t, boolean allowReversed) { double detTri = det2D(t); if (detTri < 0.0) { if (allowReversed) { Pair a = t.p3; t.p3 = t.p2; t.p2 = a; } else throw new RuntimeException("Triangle has wrong winding direction"); } } private static boolean boundaryCollideChk(Triangle t, double eps) { return det2D(t) < eps; } private static boolean boundaryDoesntCollideChk(Triangle t, double eps) { return det2D(t) <= eps; } private static boolean triTri2D(Triangle t1, Triangle t2) { return triTri2D(t1, t2, 0.0, false, true); } private static boolean triTri2D(Triangle t1, Triangle t2, double eps, boolean allowedReversed) { return triTri2D(t1, t2, eps, allowedReversed, true); } private static boolean triTri2D(Triangle t1, Triangle t2, double eps, boolean allowedReversed, boolean onBoundary) {
950Determine if two triangles overlap
9java
tcsf9
(import '(java.io File)) (.delete (File. "output.txt")) (.delete (File. "docs")) (.delete (new File (str (File/separator) "output.txt"))) (.delete (new File (str (File/separator) "docs")))
957Delete a file
6clojure
zl1tj
import java.util.Scanner; public class MatrixArithmetic { public static double[][] minor(double[][] a, int x, int y){ int length = a.length-1; double[][] result = new double[length][length]; for(int i=0;i<length;i++) for(int j=0;j<length;j++){ if(i<x && j<y){ result[i][j] = a[i][j]; }else if(i>=x && j<y){ result[i][j] = a[i+1][j]; }else if(i<x && j>=y){ result[i][j] = a[i][j+1]; }else{
947Determinant and permanent
9java
gp24m
function collapse(s) local ns = "" local last = nil for c in s:gmatch"." do if last then if last ~= c then ns = ns .. c end last = c else ns = ns .. c last = c end end return ns end function test(s) print("old: " .. s:len() .. " <<<" .. s .. ">>>") local a = collapse(s) print("new: " .. a:len() .. " <<<" .. a .. ">>>") end function main() test("") test("The better the 4-wheel drive, the further you'll be from help when ya get stuck!") test("headmistressship") test("\"If I were two-faced, would I be wearing this one?\"
948Determine if a string is collapsible
1lua
5k9u6
public class Main{ public static void main(String[] args){ String[] tests = {"", " ", "2", "333", ".55", "tttTTT", "4444 444k"}; for(String s:tests) analyze(s); } public static void analyze(String s){ System.out.printf("Examining [%s] which has a length of%d:\n", s, s.length()); if(s.length() > 1){ char firstChar = s.charAt(0); int lastIndex = s.lastIndexOf(firstChar); if(lastIndex != 0){ System.out.println("\tNot all characters in the string are the same."); System.out.printf("\t'%c' (0x%x) is different at position%d\n", firstChar, (int) firstChar, lastIndex); return; } } System.out.println("\tAll characters in the string are the same."); } }
949Determine if a string has all the same characters
9java
8za06
null
945Digital root
10javascript
eopao
const determinant = arr => arr.length === 1 ? ( arr[0][0] ) : arr[0].reduce( (sum, v, i) => sum + v * (-1) ** i * determinant( arr.slice(1) .map(x => x.filter((_, j) => i !== j)) ), 0 ); const permanent = arr => arr.length === 1 ? ( arr[0][0] ) : arr[0].reduce( (sum, v, i) => sum + v * permanent( arr.slice(1) .map(x => x.filter((_, j) => i !== j)) ), 0 ); const M = [ [0, 1, 2, 3, 4], [5, 6, 7, 8, 9], [10, 11, 12, 13, 14], [15, 16, 17, 18, 19], [20, 21, 22, 23, 24] ]; console.log(determinant(M)); console.log(permanent(M));
947Determinant and permanent
10javascript
kxghq
const check = s => { const arr = [...s]; const at = arr.findIndex( (v, i) => i === 0 ? false : v !== arr[i - 1] ) const l = arr.length; const ok = at === -1; const p = ok ? "" : at + 1; const v = ok ? "" : arr[at]; const vs = v === "" ? v : `"${v}"` const h = ok ? "" : `0x${v.codePointAt(0).toString(16)}`; console.log(`"${s}" => Length:${l}\tSame:${ok}\tPos:${p}\tChar:${vs}\tHex:${h}`) } ['', ' ', '2', '333', '.55', 'tttTTT', '4444 444k', '', ''].forEach(check)
949Determine if a string has all the same characters
10javascript
f9sdg
use 5.010; use strict; use warnings; use Time::Piece (); my @seasons = (qw< Chaos Discord Confusion Bureaucracy >, 'The Aftermath'); my @week_days = (qw< Sweetmorn Boomtime Pungenday Prickle-Prickle >, 'Setting Orange'); sub ordinal { my ($n) = @_; return $n . "th" if int($n/10) == 1; return $n . ((qw< th st nd rd th th th th th th>)[$n % 10]); } sub ddate { my $d = Time::Piece->strptime( $_[0], '%Y-%m-%d' ); my $yold = 'in the YOLD ' . ($d->year + 1166); my $day_of_year0 = $d->day_of_year; if( $d->is_leap_year ) { return "St. Tib's Day, $yold" if $d->mon == 2 and $d->mday == 29; $day_of_year0-- if $day_of_year0 >= 60; } my $weekday = $week_days[ $day_of_year0 % @week_days ]; my $season = $seasons[ $day_of_year0 / 73 ]; my $season_day = ordinal( $day_of_year0 % 73 + 1 ); return "$weekday, the $season_day day of $season $yold"; } say "$_ is " . ddate($_) for qw< 2010-07-22 2012-02-28 2012-02-29 2012-03-01 >;
944Discordian date
2perl
6vz36
use strict; use warnings; use constant True => 1; sub add_edge { my ($g, $a, $b, $weight) = @_; $g->{$a} ||= {name => $a}; $g->{$b} ||= {name => $b}; push @{$g->{$a}{edges}}, {weight => $weight, vertex => $g->{$b}}; } sub push_priority { my ($a, $v) = @_; my $i = 0; my $j = $ while ($i <= $j) { my $k = int(($i + $j) / 2); if ($a->[$k]{dist} >= $v->{dist}) { $j = $k - 1 } else { $i = $k + 1 } } splice @$a, $i, 0, $v; } sub dijkstra { my ($g, $a, $b) = @_; for my $v (values %$g) { $v->{dist} = 10e7; delete @$v{'prev', 'visited'} } $g->{$a}{dist} = 0; my $h = []; push_priority($h, $g->{$a}); while () { my $v = shift @$h; last if !$v or $v->{name} eq $b; $v->{visited} = True; for my $e (@{$v->{edges}}) { my $u = $e->{vertex}; if (!$u->{visited} && $v->{dist} + $e->{weight} <= $u->{dist}) { $u->{prev} = $v; $u->{dist} = $v->{dist} + $e->{weight}; push_priority($h, $u); } } } } my $g = {}; add_edge($g, @$_) for (['a', 'b', 7], ['a', 'c', 9], ['a', 'f', 14], ['b', 'c', 10], ['b', 'd', 15], ['c', 'd', 11], ['c', 'f', 2], ['d', 'e', 6], ['e', 'f', 9]); dijkstra($g, 'a', 'e'); my $v = $g->{e}; my @a; while ($v) { push @a, $v->{name}; $v = $v->{prev}; } my $path = join '', reverse @a; print "$g->{e}{dist} $path\n";
942Dijkstra's algorithm
2perl
5b4u2
use strict; use warnings; use Unicode::UCD 'charinfo'; for ( ['', ' '], ['"If I were two-faced, would I be wearing this one?" --- Abraham Lincoln ', '-'], ['..1111111111111111111111111111111111111111111111111111111111111117777888', '7'], ["I never give 'em hell, I just tell the truth, and they think it's hell. ", '.'], [' --- Harry S Truman ', ' '], [' --- Harry S Truman ', '-'], [' --- Harry S Truman ', 'r'] ) { my($phrase,$char) = @$_; (my $squeeze = $phrase) =~ s/([$char])\1+/$1/g; printf "\nOriginal length:%d <<<%s>>>\nSqueezable on \"%s\":%s\nSqueezed length:%d <<<%s>>>\n", length($phrase), $phrase, charinfo(ord $char)->{'name'}, $phrase ne $squeeze ? 'True' : 'False', length($squeeze), $squeeze }
946Determine if a string is squeezable
2perl
32dzs
@dx = qw< -0.533 0.270 0.859 -0.043 -0.205 -0.127 -0.071 0.275 1.251 -0.231 -0.401 0.269 0.491 0.951 1.150 0.001 -0.382 0.161 0.915 2.080 -2.337 0.034 -0.126 0.014 0.709 0.129 -1.093 -0.483 -1.193 0.020 -0.051 0.047 -0.095 0.695 0.340 -0.182 0.287 0.213 -0.423 -0.021 -0.134 1.798 0.021 -1.099 -0.361 1.636 -1.134 1.315 0.201 0.034 0.097 -0.170 0.054 -0.553 -0.024 -0.181 -0.700 -0.361 -0.789 0.279 -0.174 -0.009 -0.323 -0.658 0.348 -0.528 0.881 0.021 -0.853 0.157 0.648 1.774 -1.043 0.051 0.021 0.247 -0.310 0.171 0.000 0.106 0.024 -0.386 0.962 0.765 -0.125 -0.289 0.521 0.017 0.281 -0.749 -0.149 -2.436 -0.909 0.394 -0.113 -0.598 0.443 -0.521 -0.799 0.087>; @dy = qw< 0.136 0.717 0.459 -0.225 1.392 0.385 0.121 -0.395 0.490 -0.682 -0.065 0.242 -0.288 0.658 0.459 0.000 0.426 0.205 -0.765 -2.188 -0.742 -0.010 0.089 0.208 0.585 0.633 -0.444 -0.351 -1.087 0.199 0.701 0.096 -0.025 -0.868 1.051 0.157 0.216 0.162 0.249 -0.007 0.009 0.508 -0.790 0.723 0.881 -0.508 0.393 -0.226 0.710 0.038 -0.217 0.831 0.480 0.407 0.447 -0.295 1.126 0.380 0.549 -0.445 -0.046 0.428 -0.074 0.217 -0.822 0.491 1.347 -0.141 1.230 -0.044 0.079 0.219 0.698 0.275 0.056 0.031 0.421 0.064 0.721 0.104 -0.729 0.650 -1.103 0.154 -1.720 0.051 -0.385 0.477 1.537 -0.901 0.939 -0.411 0.341 -0.411 0.106 0.224 -0.947 -1.424 -0.542 -1.032>; sub mean { my $s; $s += $_ for @_; $s / @_ } sub stddev { sqrt( mean(map { $_**2 } @_) - mean(@_)**2) } @rules = ( sub { 0 }, sub { -$_[1] }, sub { -$_[0] - $_[1] }, sub { $_[0] + $_[1] } ); for (@rules) { print "Rule " . ++$cnt . "\n"; my @ddx; my $tx = 0; for my $x (@dx) { push @ddx, $tx + $x; $tx = &$_($tx, $x) } my @ddy; my $ty = 0; for my $y (@dy) { push @ddy, $ty + $y; $ty = &$_($ty, $y) } printf "Mean x, y :%7.4f%7.4f\n", mean(@ddx), mean(@ddy); printf "Std dev x, y :%7.4f%7.4f\n", stddev(@ddx), stddev(@ddy); }
954Deming's Funnel
2perl
zlwtb
package main import "fmt" func analyze(s string) { chars := []rune(s) le := len(chars) fmt.Printf("Analyzing%q which has a length of%d:\n", s, le) if le > 1 { for i := 0; i < le-1; i++ { for j := i + 1; j < le; j++ { if chars[j] == chars[i] { fmt.Println(" Not all characters in the string are unique.") fmt.Printf(" %q (%#[1]x) is duplicated at positions%d and%d.\n\n", chars[i], i+1, j+1) return } } } } fmt.Println(" All characters in the string are unique.\n") } func main() { strings := []string{ "", ".", "abcABC", "XYZ ZYX", "1234567890ABCDEFGHIJKLMN0PQRSTUVWXYZ", "01234567890ABCDEFGHIJKLMN0PQRSTUVWXYZ0X", "htrognit", "", "", "", } for _, s := range strings { analyze(s) } }
952Determine if a string has all unique characters
0go
i61og
use threads; use threads::shared; my @names = qw(Aristotle Kant Spinoza Marx Russell); my @forks = ('On Table') x @names; share $forks[$_] for 0 .. $ sub pick_up_forks { my $philosopher = shift; my ($first, $second) = ($philosopher, $philosopher-1); ($first, $second) = ($second, $first) if $philosopher % 2; for my $fork ( @forks[ $first, $second ] ) { lock $fork; cond_wait($fork) while $fork ne 'On Table'; $fork = 'In Hand'; } } sub drop_forks { my $philosopher = shift; for my $fork ( @forks[$philosopher, $philosopher-1] ) { lock $fork; die unless $fork eq 'In Hand'; $fork = 'On Table'; cond_signal($fork); } } sub philosopher { my $philosopher = shift; my $name = $names[$philosopher]; for my $meal ( 1..5 ) { print $name, " is pondering\n"; sleep 1 + rand 8; print $name, " is hungry\n"; pick_up_forks( $philosopher ); print $name, " is eating\n"; sleep 1 + rand 8; drop_forks( $philosopher ); } print $name, " is done\n"; } my @t = map { threads->new(\&philosopher, $_) } 0 .. $ for my $thread ( @t ) { $thread->join; } print "Done\n"; __END__
941Dining philosophers
2perl
cr29a
null
945Digital root
11kotlin
gpu4d
public class DotProduct { public static void main(String[] args) { double[] a = {1, 3, -5}; double[] b = {4, -2, -1}; System.out.println(dotProd(a,b)); } public static double dotProd(double[] a, double[] b){ if(a.length != b.length){ throw new IllegalArgumentException("The dimensions have to be equal!"); } double sum = 0; for(int i = 0; i < a.length; i++){ sum += a[i] * b[i]; } return sum; } }
938Dot product
9java
nm3ih
package main import "fmt" type Delegator struct { delegate interface{}
955Delegates
0go
f91d0
null
950Determine if two triangles overlap
11kotlin
o3a8z
null
947Determinant and permanent
11kotlin
27yli
class StringUniqueCharacters { static void main(String[] args) { printf("%-40s %2s %10s %8s %s %s%n", "String", "Length", "All Unique", "1st Diff", "Hex", "Positions") printf("%-40s %2s %10s %8s %s %s%n", "------------------------", "------", "----------", "--------", "---", "---------") for (String s: ["", ".", "abcABC", "XYZ ZYX", "1234567890ABCDEFGHIJKLMN0PQRSTUVWXYZ"]) { processString(s) } } private static void processString(String input) { Map<Character, Integer> charMap = new HashMap<>() char dup = 0 int index = 0 int pos1 = -1 int pos2 = -1 for (char key: input.toCharArray()) { index++ if (charMap.containsKey(key)) { dup = key pos1 = charMap.get(key) pos2 = index break } charMap.put(key, index) } String unique = (int) dup == 0 ? "yes": "no" String diff = (int) dup == 0 ? "": "'" + dup + "'" String hex = (int) dup == 0 ? "": Integer.toHexString((int) dup).toUpperCase() String position = (int) dup == 0 ? "": pos1 + " " + pos2 printf("%-40s %-6d %-10s %-8s %-3s %-5s%n", input, input.length(), unique, diff, hex, position) } }
952Determine if a string has all unique characters
7groovy
qdjxp
use strict; use warnings; use utf8; binmode STDOUT, ":utf8"; my @lines = split "\n", <<~'STRINGS'; "If I were two-faced, would I be wearing this one?" --- Abraham Lincoln ..1111111111111111111111111111111111111111111111111111111111111117777888 I never give 'em hell, I just tell the truth, and they think it's hell. --- Harry S Truman The American people have a right to know if their president is a crook. --- Richard Nixon AAAAAAAAAAAAAAAAAAAAAAAA AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA STRINGS for (@lines) { my $squish = s/(.)\1+/$1/gr; printf "\nLength:%2d <<<%s>>>\nCollapsible:%s\nLength:%2d <<<%s>>>\n", length($_), $_, $_ ne $squish ? 'True' : 'False', length($squish), $squish }
948Determine if a string is collapsible
2perl
8ze0w
fun analyze(s: String) { println("Examining [$s] which has a length of ${s.length}:") if (s.length > 1) { val b = s[0] for ((i, c) in s.withIndex()) { if (c != b) { println(" Not all characters in the string are the same.") println(" '$c' (0x${Integer.toHexString(c.toInt())}) is different at position $i") return } } } println(" All characters in the string are the same.") } fun main() { val strs = listOf("", " ", "2", "333", ".55", "tttTTT", "4444 444k") for (str in strs) { analyze(str) } }
949Determine if a string has all the same characters
11kotlin
wihek
<?php $Anerisia = array(31,28,31,30,31,30,31,31,30,31,30,31); $MONTHS = array(,,,,); $DAYS = array(,,,,); $Dsuff = array('th','st','nd','rd','th','th','th','th','th','th'); $Holy5 = array(,,,,); $Holy50 = array(,,,,); $edate = explode(,date('Y m j L')); $usery = $edate[0]; $userm = $edate[1]; $userd = $edate[2]; $IsLeap = $edate[3]; if (isset($_GET['y']) && isset($_GET['m']) && isset($_GET['d'])) { $usery = $_GET['y']; $userm = $_GET['m']; $userd = $_GET['d']; $IsLeap = 0; if (($usery%4 == 0) && ($usery%100 >0)) $IsLeap =1; if ($usery%400 == 0) $IsLeap = 1; } $userdays = 0; $i = 0; while ($i < ($userm-1)) { $userdays = $userdays + $Anerisia[$i]; $i = $i +1; } $userdays = $userdays + $userd; $IsHolyday = 0; $dyear = $usery + 1166; $dmonth = $MONTHS[$userdays/73.2]; $dday = $userdays%73; if (0 == $dday) $dday = 73; $Dname = $DAYS[$userdays%5]; $Holyday = ; if ($dday == 5) { $Holyday = $Holy5[$userdays/73.2]; $IsHolyday =1; } if ($dday == 50) { $Holyday = $Holy50[$userdays/73.2]; $IsHolyday =1; } if (($IsLeap ==1) && ($userd ==29) and ($userm ==2)) $IsHolyday = 2; $suff = $Dsuff[$dday%10] ; if ((11 <= $dday) && (19 >= $dday)) $suff='th'; if ($IsHolyday ==2) echo ,$Holyday,,$dmonth,,$dyear; if ($IsHolyday ==1) echo , $Dname , , $dday,,$suff,, , $dmonth , , $dyear , , $Holyday; if ($IsHolyday == 0) echo , $Dname , , $dday ,,$suff, , $dmonth , , $dyear; ?>
944Discordian date
12php
10bpq
<?php function dijkstra($graph_array, $source, $target) { $vertices = array(); $neighbours = array(); foreach ($graph_array as $edge) { array_push($vertices, $edge[0], $edge[1]); $neighbours[$edge[0]][] = array( => $edge[1], => $edge[2]); $neighbours[$edge[1]][] = array( => $edge[0], => $edge[2]); } $vertices = array_unique($vertices); foreach ($vertices as $vertex) { $dist[$vertex] = INF; $previous[$vertex] = NULL; } $dist[$source] = 0; $Q = $vertices; while (count($Q) > 0) { $min = INF; foreach ($Q as $vertex){ if ($dist[$vertex] < $min) { $min = $dist[$vertex]; $u = $vertex; } } $Q = array_diff($Q, array($u)); if ($dist[$u] == INF or $u == $target) { break; } if (isset($neighbours[$u])) { foreach ($neighbours[$u] as $arr) { $alt = $dist[$u] + $arr[]; if ($alt < $dist[$arr[]]) { $dist[$arr[]] = $alt; $previous[$arr[]] = $u; } } } } $path = array(); $u = $target; while (isset($previous[$u])) { array_unshift($path, $u); $u = $previous[$u]; } array_unshift($path, $u); return $path; } $graph_array = array( array(, , 7), array(, , 9), array(, , 14), array(, , 10), array(, , 15), array(, , 11), array(, , 2), array(, , 6), array(, , 9) ); $path = dijkstra($graph_array, , ); echo .implode(, $path).;
942Dijkstra's algorithm
12php
o6i85
function digital_root(n, base) p = 0 while n > 9.5 do n = sum_digits(n, base) p = p + 1 end return n, p end print(digital_root(627615, 10)) print(digital_root(39390, 10)) print(digital_root(588225, 10)) print(digital_root(393900588225, 10))
945Digital root
1lua
r15ga
import re from itertools import product problem_re = re.compile(r) names, lennames = None, None floors = None constraint_expr = 'len(set(alloc)) == lennames' def do_namelist(txt): global names, lennames names = txt.replace(' and ', ' ').split(', ') lennames = len(names) def do_floorcount(txt): global floors floors = '||two|three|four|five|six|seven|eight|nine|ten'.split('|').index(txt) def do_not_live(txt): global constraint_expr t = txt.strip().split() who, floor = t[0], t[-2] w, f = (names.index(who), ('|first|second|third|fourth|fifth|sixth|' + 'seventh|eighth|ninth|tenth|top|bottom|').split('|').index(floor) ) if f == 11: f = floors if f == 12: f = 1 constraint_expr += ' and alloc[%i]!=%i'% (w, f) def do_not_either(txt): global constraint_expr t = txt.replace(' or ', ' ').replace(' the ', ' ').strip().split() who, floor = t[0], t[6:-1] w, fl = (names.index(who), [('|first|second|third|fourth|fifth|sixth|' + 'seventh|eighth|ninth|tenth|top|bottom|').split('|').index(f) for f in floor] ) for f in fl: if f == 11: f = floors if f == 12: f = 1 constraint_expr += ' and alloc[%i]!=%i'% (w, f) def do_hi_lower(txt): global constraint_expr t = txt.replace('.', '').strip().split() name_indices = [names.index(who) for who in (t[0], t[-1])] if 'lower' in t: name_indices = name_indices[::-1] constraint_expr += ' and alloc[%i] > alloc[%i]'% tuple(name_indices) def do_adjacency(txt): ''' E.g. ''' global constraint_expr t = txt.replace('.', '').replace(, '').strip().split() name_indices = [names.index(who) for who in (t[0], t[-1])] constraint_expr += ' and abs(alloc[%i] - alloc[%i]) > 1'% tuple(name_indices) def do_question(txt): global constraint_expr, names, lennames exec_txt = ''' for alloc in product(range(1,floors+1), repeat=len(names)): if%s: break else: alloc = None '''% constraint_expr exec(exec_txt, globals(), locals()) a = locals()['alloc'] if a: output= ['Floors are numbered from 1 to%i inclusive.'% floors] for a2n in zip(a, names): output += [' Floor%i is occupied by%s'% a2n] output.sort(reverse=True) print('\n'.join(output)) else: print('No solution found.') print() handler = { 'namelist': do_namelist, 'floorcount': do_floorcount, 'not_live': do_not_live, 'not_either': do_not_either, 'hi_lower': do_hi_lower, 'adjacency': do_adjacency, 'question': do_question, } def parse_and_solve(problem): p = re.sub(r'\s+', ' ', problem).strip() for x in problem_re.finditer(p): groupname, txt = [(k,v) for k,v in x.groupdict().items() if v][0] handler[groupname](txt)
939Dinesman's multiple-dwelling problem
3python
4pj5k
function dot_product(ary1, ary2) { if (ary1.length != ary2.length) throw "can't find dot product: arrays have different lengths"; var dotprod = 0; for (var i = 0; i < ary1.length; i++) dotprod += ary1[i] * ary2[i]; return dotprod; } print(dot_product([1,3,-5],[4,-2,-1]));
938Dot product
10javascript
3vcz0
<?php function squeezeString($string, $squeezeChar) { $previousChar = null; $squeeze = ''; $charArray = preg_split(' for ($i = 0 ; $i < count($charArray) ; $i++) { $currentChar = $charArray[$i]; if ($previousChar !== $currentChar || $currentChar !== $squeezeChar) { $squeeze .= $charArray[$i]; } $previousChar = $currentChar; } return $squeeze; } function isSqueezable($string, $squeezeChar) { return ($string !== squeezeString($string, $squeezeChar)); } $strings = array( ['-', ' --- Abraham Lincoln '], ['1', '..1111111111111111111111111111111111111111111111111111111111111117777888'], ['l', ], [' ', ' --- Harry S Truman '], ['9', '0112223333444445555556666666777777778888888889999999999'], ['e', ], ['k', ], ); foreach ($strings as $params) { list($char, $original) = $params; echo 'Original : <<<', $original, '>>> (len=', mb_strlen($original), ')', PHP_EOL; if (isSqueezable($original, $char)) { $squeeze = squeezeString($original, $char); echo 'Squeeze(', $char, '): <<<', $squeeze, '>>> (len=', mb_strlen($squeeze), ')', PHP_EOL, PHP_EOL; } else { echo 'Squeeze(', $char, '): string is not squeezable (char=', $char, ')...', PHP_EOL, PHP_EOL; } }
946Determine if a string is squeezable
12php
psjba
import math dxs = [-0.533, 0.27, 0.859, -0.043, -0.205, -0.127, -0.071, 0.275, 1.251, -0.231, -0.401, 0.269, 0.491, 0.951, 1.15, 0.001, -0.382, 0.161, 0.915, 2.08, -2.337, 0.034, -0.126, 0.014, 0.709, 0.129, -1.093, -0.483, -1.193, 0.02, -0.051, 0.047, -0.095, 0.695, 0.34, -0.182, 0.287, 0.213, -0.423, -0.021, -0.134, 1.798, 0.021, -1.099, -0.361, 1.636, -1.134, 1.315, 0.201, 0.034, 0.097, -0.17, 0.054, -0.553, -0.024, -0.181, -0.7, -0.361, -0.789, 0.279, -0.174, -0.009, -0.323, -0.658, 0.348, -0.528, 0.881, 0.021, -0.853, 0.157, 0.648, 1.774, -1.043, 0.051, 0.021, 0.247, -0.31, 0.171, 0.0, 0.106, 0.024, -0.386, 0.962, 0.765, -0.125, -0.289, 0.521, 0.017, 0.281, -0.749, -0.149, -2.436, -0.909, 0.394, -0.113, -0.598, 0.443, -0.521, -0.799, 0.087] dys = [0.136, 0.717, 0.459, -0.225, 1.392, 0.385, 0.121, -0.395, 0.49, -0.682, -0.065, 0.242, -0.288, 0.658, 0.459, 0.0, 0.426, 0.205, -0.765, -2.188, -0.742, -0.01, 0.089, 0.208, 0.585, 0.633, -0.444, -0.351, -1.087, 0.199, 0.701, 0.096, -0.025, -0.868, 1.051, 0.157, 0.216, 0.162, 0.249, -0.007, 0.009, 0.508, -0.79, 0.723, 0.881, -0.508, 0.393, -0.226, 0.71, 0.038, -0.217, 0.831, 0.48, 0.407, 0.447, -0.295, 1.126, 0.38, 0.549, -0.445, -0.046, 0.428, -0.074, 0.217, -0.822, 0.491, 1.347, -0.141, 1.23, -0.044, 0.079, 0.219, 0.698, 0.275, 0.056, 0.031, 0.421, 0.064, 0.721, 0.104, -0.729, 0.65, -1.103, 0.154, -1.72, 0.051, -0.385, 0.477, 1.537, -0.901, 0.939, -0.411, 0.341, -0.411, 0.106, 0.224, -0.947, -1.424, -0.542, -1.032] def funnel(dxs, rule): x, rxs = 0, [] for dx in dxs: rxs.append(x + dx) x = rule(x, dx) return rxs def mean(xs): return sum(xs) / len(xs) def stddev(xs): m = mean(xs) return math.sqrt(sum((x-m)**2 for x in xs) / len(xs)) def experiment(label, rule): rxs, rys = funnel(dxs, rule), funnel(dys, rule) print label print 'Mean x, y :%.4f,%.4f'% (mean(rxs), mean(rys)) print 'Std dev x, y:%.4f,%.4f'% (stddev(rxs), stddev(rys)) print experiment('Rule 1:', lambda z, dz: 0) experiment('Rule 2:', lambda z, dz: -dz) experiment('Rule 3:', lambda z, dz: -(z+dz)) experiment('Rule 4:', lambda z, dz: z+dz)
954Deming's Funnel
3python
32xzc
interface Thingable { String thing(); } class Delegator { public Thingable delegate; public String operation() { if (delegate == null) return "default implementation"; else return delegate.thing(); } } class Delegate implements Thingable { public String thing() { return "delegate implementation"; } }
955Delegates
9java
cg89h
import Data.List (groupBy, intersperse, sort, transpose) import Data.Char (ord, toUpper) import Data.Function(on) import Numeric (showHex) hexFromChar :: Char -> String hexFromChar c = map toUpper $ showHex (ord c) "" string :: String -> String string xs = ('\"': xs) <> "\"" char :: Char -> String char c = ['\'', c, '\''] size :: String -> String size = show . length positions :: (Int, Int) -> String positions (a, b) = show a <> " " <> show b forTable :: String -> [String] forTable xs = string xs: go (allUnique xs) where go Nothing = [size xs, "yes", "", "", ""] go (Just (u, ij)) = [size xs, "no", char u, hexFromChar u, positions ij] showTable :: Bool -> Char -> Char -> Char -> [[String]] -> String showTable _ _ _ _ [] = [] showTable header ver hor sep contents = unlines $ hr: (if header then z: hr: zs else intersperse hr zss) <> [hr] where vss = map (map length) contents ms = map maximum (transpose vss) :: [Int] hr = concatMap (\n -> sep: replicate n hor) ms <> [sep] top = replicate (length hr) hor bss = map (map (`replicate` ' ') . zipWith (-) ms) vss zss@(z:zs) = zipWith (\us bs -> concat (zipWith (\x y -> (ver: x) <> y) us bs) <> [ver]) contents bss table xs = showTable True '|' '-' '+' (["string", "length", "all unique", "1st diff", "hex", "positions"]: map forTable xs) allUnique :: (Ord b, Ord a, Num b, Enum b) => [a] -> Maybe (a, (b, b)) allUnique xs = go . groupBy (on (==) fst) . sort . zip xs $ [0 ..] where go [] = Nothing go ([_]:us) = go us go (((u, i):(_, j):_):_) = Just (u, (i, j)) main :: IO () main = putStrLn $ table ["", ".", "abcABC", "XYZ ZYX", "1234567890ABCDEFGHIJKLMN0PQRSTUVWXYZ"]
952Determine if a string has all unique characters
8haskell
vjt2k
<?php function collapseString($string) { $previousChar = null; $collapse = ''; $charArray = preg_split(' for ($i = 0 ; $i < count($charArray) ; $i++) { $currentChar = $charArray[$i]; if ($previousChar !== $currentChar) { $collapse .= $charArray[$i]; } $previousChar = $currentChar; } return $collapse; } function isCollapsible($string) { return ($string !== collapseString($string)); } $strings = array( '', 'another non colapsing string', ' --- Abraham Lincoln ', '..1111111111111111111111111111111111111111111111111111111111111117777888', , ' --- Harry S Truman ', '0112223333444445555556666666777777778888888889999999999', , 'headmistressship', , ); foreach ($strings as $original) { echo 'Original: <<<', $original, '>>> (len=', mb_strlen($original), ')', PHP_EOL; if (isCollapsible($original)) { $collapse = collapseString($original); echo 'Collapse: <<<', $collapse, '>>> (len=', mb_strlen($collapse), ')', PHP_EOL, PHP_EOL; } else { echo 'Collapse: string is not collapsing...', PHP_EOL, PHP_EOL; } }
948Determine if a string is collapsible
12php
4bc5n
function analyze(s) print(string.format("Examining [%s] which has a length of%d:", s, string.len(s))) if string.len(s) > 1 then local last = string.byte(string.sub(s,1,1)) for i=1,string.len(s) do local c = string.byte(string.sub(s,i,i)) if last ~= c then print(" Not all characters in the string are the same.") print(string.format(" '%s' (0x%x) is different at position%d", string.sub(s,i,i), c, i - 1)) return end end end print(" All characters in the string are the same.") end function main() analyze("") analyze(" ") analyze("2") analyze("333") analyze(".55") analyze("tttTTT") analyze("4444 444k") end main()
949Determine if a string has all the same characters
1lua
xnkwz
names = unlist(strsplit("baker cooper fletcher miller smith", " ")) test <- function(floors) { f <- function(name) which(name == floors) if ((f('baker')!= 5) && (f('cooper')!= 1) && (any(f('fletcher') == 2:4)) && (f('miller') > f('cooper')) && (abs(f('fletcher') - f('cooper')) > 1) && (abs(f('smith') - f('fletcher')) > 1)) cat("\nFrom bottom to top: --> ", floors, "\n") } do.perms <- function(seq, func, built = c()){ if (0 == length(seq)) func(built) else for (x in seq) do.perms( seq[!seq==x], func, c(x, built)) }
939Dinesman's multiple-dwelling problem
13r
2j4lg
from itertools import groupby def squeezer(s, txt): return ''.join(item if item == s else ''.join(grp) for item, grp in groupby(txt)) if __name__ == '__main__': strings = [ , ' --- Abraham Lincoln ', , , , , , , , ] squeezers = ' ,-,7,., -r,e,s,a,'.split(',') for txt, chars in zip(strings, squeezers): this = print(f ) for ch in chars: this = f sqz = squeezer(ch, txt) print(f )
946Determine if a string is squeezable
3python
6vf3w
int main() { int police,sanitation,fire; printf(); printf(); for(police=2;police<=6;police+=2){ for(sanitation=1;sanitation<=7;sanitation++){ for(fire=1;fire<=7;fire++){ if(police!=sanitation && sanitation!=fire && fire!=police && police+fire+sanitation==12){ printf(,police,sanitation,fire); } } } } return 0; }
958Department numbers
5c
vj82o
function Delegator() { this.delegate = null ; this.operation = function(){ if(this.delegate && typeof(this.delegate.thing) == 'function') return this.delegate.thing() ; return 'default implementation' ; } } function Delegate() { this.thing = function(){ return 'Delegate Implementation' ; } } function testDelegator(){ var a = new Delegator() ; document.write(a.operation() + "\n") ; a.delegate = 'A delegate may be any object' ; document.write(a.operation() + "\n") ; a.delegate = new Delegate() ; document.write(a.operation() + "\n") ; }
955Delegates
10javascript
5kfur
function det2D(p1,p2,p3) return p1.x * (p2.y - p3.y) + p2.x * (p3.y - p1.y) + p3.x * (p1.y - p2.y) end function checkTriWinding(p1,p2,p3,allowReversed) local detTri = det2D(p1,p2,p3) if detTri < 0.0 then if allowReversed then local t = p3 p3 = p2 p2 = t else error("triangle has wrong winding direction") end end return nil end function boundaryCollideChk(p1,p2,p3,eps) return det2D(p1,p2,p3) < eps end function boundaryDoesntCollideChk(p1,p2,p3,eps) return det2D(p1,p2,p3) <= eps end function triTri2D(t1,t2,eps,allowReversed,onBoundary) eps = eps or 0.0 allowReversed = allowReversed or false onBoundary = onBoundary or true
950Determine if two triangles overlap
1lua
i6eot
null
947Determinant and permanent
1lua
vjm2x
import java.util.HashMap; import java.util.Map;
952Determine if a string has all unique characters
9java
yu86g
squeeze_string <- function(string, character){ str_iterable <- strsplit(string, "")[[1]] message(paste0("Original String: ", "<<<", string, ">>>\n", "Length: ", length(str_iterable), "\n", "Character: ", character)) detect <- rep(TRUE, length(str_iterable)) for(i in 2:length(str_iterable)){ if(length(str_iterable) == 0) break if(str_iterable[i]!= character) next if(str_iterable[i] == str_iterable[i-1]) detect[i] <- FALSE } squeezed_string <- paste(str_iterable[detect], collapse = "") message(paste0("squeezed string: ", "<<<",squeezed_string, ">>>\n", "Length: ", length(str_iterable[detect])), "\n") } squeeze_string("", " ") squeeze_string("'If I were two-faced, would I be wearing this one?' --- Abraham Lincoln ", "-") squeeze_string("..1111111111111111111111111111111111111111111111111111111111111117777888", "7") squeeze_string("I never give 'em hell, I just tell the truth, and they think it's hell. ", ".") squeeze_string(" --- Harry S Truman ", " ") squeeze_string(" --- Harry S Truman ", "-") squeeze_string(" --- Harry S Truman ", "r") squeeze_string(" Ciao Mamma, guarda come mi diverto!!! ", "!")
946Determine if a string is squeezable
13r
f9odc
def funnel(dxs, &rule) x, rxs = 0, [] for dx in dxs rxs << (x + dx) x = rule[x, dx] end rxs end def mean(xs) xs.inject(:+) / xs.size end def stddev(xs) m = mean(xs) Math.sqrt(xs.inject(0.0){|sum,x| sum + (x-m)**2} / xs.size) end def experiment(label, dxs, dys, &rule) rxs, rys = funnel(dxs, &rule), funnel(dys, &rule) puts label puts 'Mean x, y :%7.4f,%7.4f' % [mean(rxs), mean(rys)] puts 'Std dev x, y:%7.4f,%7.4f' % [stddev(rxs), stddev(rys)] puts end dxs = [ -0.533, 0.270, 0.859, -0.043, -0.205, -0.127, -0.071, 0.275, 1.251, -0.231, -0.401, 0.269, 0.491, 0.951, 1.150, 0.001, -0.382, 0.161, 0.915, 2.080, -2.337, 0.034, -0.126, 0.014, 0.709, 0.129, -1.093, -0.483, -1.193, 0.020, -0.051, 0.047, -0.095, 0.695, 0.340, -0.182, 0.287, 0.213, -0.423, -0.021, -0.134, 1.798, 0.021, -1.099, -0.361, 1.636, -1.134, 1.315, 0.201, 0.034, 0.097, -0.170, 0.054, -0.553, -0.024, -0.181, -0.700, -0.361, -0.789, 0.279, -0.174, -0.009, -0.323, -0.658, 0.348, -0.528, 0.881, 0.021, -0.853, 0.157, 0.648, 1.774, -1.043, 0.051, 0.021, 0.247, -0.310, 0.171, 0.000, 0.106, 0.024, -0.386, 0.962, 0.765, -0.125, -0.289, 0.521, 0.017, 0.281, -0.749, -0.149, -2.436, -0.909, 0.394, -0.113, -0.598, 0.443, -0.521, -0.799, 0.087] dys = [ 0.136, 0.717, 0.459, -0.225, 1.392, 0.385, 0.121, -0.395, 0.490, -0.682, -0.065, 0.242, -0.288, 0.658, 0.459, 0.000, 0.426, 0.205, -0.765, -2.188, -0.742, -0.010, 0.089, 0.208, 0.585, 0.633, -0.444, -0.351, -1.087, 0.199, 0.701, 0.096, -0.025, -0.868, 1.051, 0.157, 0.216, 0.162, 0.249, -0.007, 0.009, 0.508, -0.790, 0.723, 0.881, -0.508, 0.393, -0.226, 0.710, 0.038, -0.217, 0.831, 0.480, 0.407, 0.447, -0.295, 1.126, 0.380, 0.549, -0.445, -0.046, 0.428, -0.074, 0.217, -0.822, 0.491, 1.347, -0.141, 1.230, -0.044, 0.079, 0.219, 0.698, 0.275, 0.056, 0.031, 0.421, 0.064, 0.721, 0.104, -0.729, 0.650, -1.103, 0.154, -1.720, 0.051, -0.385, 0.477, 1.537, -0.901, 0.939, -0.411, 0.341, -0.411, 0.106, 0.224, -0.947, -1.424, -0.542, -1.032] experiment('Rule 1:', dxs, dys) {|z, dz| 0} experiment('Rule 2:', dxs, dys) {|z, dz| -dz} experiment('Rule 3:', dxs, dys) {|z, dz| -(z+dz)} experiment('Rule 4:', dxs, dys) {|z, dz| z+dz}
954Deming's Funnel
14ruby
yus6n
null
955Delegates
11kotlin
32wz5
package main import "fmt" func divCheck(x, y int) (q int, ok bool) { defer func() { recover() }() q = x / y return q, true } func main() { fmt.Println(divCheck(3, 2)) fmt.Println(divCheck(3, 0)) }
953Detect division by zero
0go
qd7xz
def dividesByZero = { double n, double d -> assert ! n.infinite: 'Algorithm fails if the numerator is already infinite.' (n/d).infinite || (n/d).naN }
953Detect division by zero
7groovy
10up6
(() => { 'use strict';
952Determine if a string has all unique characters
10javascript
27flr
from itertools import groupby def collapser(txt): return ''.join(item for item, grp in groupby(txt)) if __name__ == '__main__': strings = [ , ' --- Abraham Lincoln ', , , , , , , , ] for txt in strings: this = print(f ) this = sqz = collapser(txt) print(f )
948Determine if a string is collapsible
3python
o3w81
from collections import namedtuple, deque from pprint import pprint as pp inf = float('inf') Edge = namedtuple('Edge', ['start', 'end', 'cost']) class Graph(): def __init__(self, edges): self.edges = [Edge(*edge) for edge in edges] self.vertices = {e.start for e in self.edges} | {e.end for e in self.edges} def dijkstra(self, source, dest): assert source in self.vertices dist = {vertex: inf for vertex in self.vertices} previous = {vertex: None for vertex in self.vertices} dist[source] = 0 q = self.vertices.copy() neighbours = {vertex: set() for vertex in self.vertices} for start, end, cost in self.edges: neighbours[start].add((end, cost)) neighbours[end].add((start, cost)) while q: u = min(q, key=lambda vertex: dist[vertex]) q.remove(u) if dist[u] == inf or u == dest: break for v, cost in neighbours[u]: alt = dist[u] + cost if alt < dist[v]: dist[v] = alt previous[v] = u s, u = deque(), dest while previous[u]: s.appendleft(u) u = previous[u] s.appendleft(u) return s graph = Graph([(, , 7), (, , 9), (, , 14), (, , 10), (, , 15), (, , 11), (, , 2), (, , 6), (, , 9)]) pp(graph.dijkstra(, ))
942Dijkstra's algorithm
3python
4pg5k
fun dot(v1: Array<Double>, v2: Array<Double>) = v1.zip(v2).map { it.first * it.second }.reduce { a, b -> a + b } fun main(args: Array<String>) { dot(arrayOf(1.0, 3.0, -5.0), arrayOf(4.0, -2.0, -1.0)).let { println(it) } }
938Dot product
11kotlin
stnq7
local function Delegator() return { operation = function(self) if (type(self.delegate)=="table") and (type(self.delegate.thing)=="function") then return self.delegate:thing() else return "default implementation" end end } end local function Delegate() return { thing = function(self) return "delegate implementation" end } end local function NonDelegate(which) if (which == 1) then return true
955Delegates
1lua
6vx39
import qualified Control.Exception as C check x y = C.catch (x `div` y `seq` return False) (\_ -> return True)
953Detect division by zero
8haskell
m58yf
collapse_string <- function(string){ str_iterable <- strsplit(string, "")[[1]] message(paste0("Original String: ", "<<<", string, ">>>\n", "Length: ", length(str_iterable))) detect <- rep(TRUE, length(str_iterable)) for(i in 2:length(str_iterable)){ if(length(str_iterable)==0) break if(str_iterable[i] == str_iterable[i-1]) detect[i] <- FALSE } collapsed_string <- paste(str_iterable[detect],collapse = "") message(paste0("Collapsed string: ", "<<<",collapsed_string, ">>>\n", "Length: ", length(str_iterable[detect])), "\n") } test_strings <- c( "", "'If I were two-faced, would I be wearing this one?' --- Abraham Lincoln ", "..1111111111111111111111111111111111111111111111111111111111111117777888", "I never give 'em hell, I just tell the truth, and they think it's hell. ", " --- Harry S Truman ", "The better the 4-wheel drive, the further you'll be from help when ya get stuck!", "headmistressship", "aardvark", "Ciao Mamma, guarda come mi diverto!!" ) for(test in test_strings){ collapse_string(test) }
948Determine if a string is collapsible
13r
qdpxs
strings = [, ' --- Abraham Lincoln ', , , , ,] squeeze_these = [, , , , , ] strings.zip(squeeze_these).each do |str, st| puts st.chars.each do |c| ssq = str.squeeze(c) puts end puts end
946Determine if a string is squeezable
14ruby
m5zyj
fn squeezable_string<'a>(s: &'a str, squeezable: char) -> impl Iterator<Item = char> + 'a { let mut previous = None; s.chars().filter(move |c| match previous { Some(p) if p == squeezable && p == *c => false, _ => { previous = Some(*c); true } }) } fn main() { fn show(input: &str, c: char) { println!("Squeeze: '{}'", c); println!("Input ({} chars): \t{}", input.chars().count(), input); let output: String = squeezable_string(input, c).collect(); println!("Output ({} chars): \t{}", output.chars().count(), output); println!(); } let harry = r#"I never give 'em hell, I just tell the truth, and they think it's hell. --- Harry S Truman"#; #[rustfmt::skip] let inputs = [ ("", ' '), (r#""If I were two-faced, would I be wearing this one?" --- Abraham Lincoln "#, '-'), ("..1111111111111111111111111111111111111111111111111111111111111117777888", '7'), (harry, ' '), (harry, '-'), (harry, 'r'), ("The better the 4-wheel drive, the further you'll be from help when ya get stuck!", 'e'), ("headmistressship", 's'), ]; inputs.iter().for_each(|(input, c)| show(input, *c)); }
946Determine if a string is squeezable
15rust
943mm
import Foundation let dxs = [ -0.533, 0.270, 0.859, -0.043, -0.205, -0.127, -0.071, 0.275, 1.251, -0.231, -0.401, 0.269, 0.491, 0.951, 1.150, 0.001, -0.382, 0.161, 0.915, 2.080, -2.337, 0.034, -0.126, 0.014, 0.709, 0.129, -1.093, -0.483, -1.193, 0.020, -0.051, 0.047, -0.095, 0.695, 0.340, -0.182, 0.287, 0.213, -0.423, -0.021, -0.134, 1.798, 0.021, -1.099, -0.361, 1.636, -1.134, 1.315, 0.201, 0.034, 0.097, -0.170, 0.054, -0.553, -0.024, -0.181, -0.700, -0.361, -0.789, 0.279, -0.174, -0.009, -0.323, -0.658, 0.348, -0.528, 0.881, 0.021, -0.853, 0.157, 0.648, 1.774, -1.043, 0.051, 0.021, 0.247, -0.310, 0.171, 0.000, 0.106, 0.024, -0.386, 0.962, 0.765, -0.125, -0.289, 0.521, 0.017, 0.281, -0.749, -0.149, -2.436, -0.909, 0.394, -0.113, -0.598, 0.443, -0.521, -0.799, 0.087 ] let dys = [ 0.136, 0.717, 0.459, -0.225, 1.392, 0.385, 0.121, -0.395, 0.490, -0.682, -0.065, 0.242, -0.288, 0.658, 0.459, 0.000, 0.426, 0.205, -0.765, -2.188, -0.742, -0.010, 0.089, 0.208, 0.585, 0.633, -0.444, -0.351, -1.087, 0.199, 0.701, 0.096, -0.025, -0.868, 1.051, 0.157, 0.216, 0.162, 0.249, -0.007, 0.009, 0.508, -0.790, 0.723, 0.881, -0.508, 0.393, -0.226, 0.710, 0.038, -0.217, 0.831, 0.480, 0.407, 0.447, -0.295, 1.126, 0.380, 0.549, -0.445, -0.046, 0.428, -0.074, 0.217, -0.822, 0.491, 1.347, -0.141, 1.230, -0.044, 0.079, 0.219, 0.698, 0.275, 0.056, 0.031, 0.421, 0.064, 0.721, 0.104, -0.729, 0.650, -1.103, 0.154, -1.720, 0.051, -0.385, 0.477, 1.537, -0.901, 0.939, -0.411, 0.341, -0.411, 0.106, 0.224, -0.947, -1.424, -0.542, -1.032 ] extension Collection where Element: FloatingPoint { @inlinable public func mean() -> Element { return reduce(0, +) / Element(count) } @inlinable public func stdDev() -> Element { let m = mean() return map({ ($0 - m) * ($0 - m) }).mean().squareRoot() } } typealias Rule = (Double, Double) -> Double func funnel(_ arr: [Double], rule: Rule) -> [Double] { var x = 0.0 var res = [Double](repeating: 0, count: arr.count) for (i, d) in arr.enumerated() { res[i] = x + d x = rule(x, d) } return res } func experiment(label: String, rule: Rule) { let rxs = funnel(dxs, rule: rule) let rys = funnel(dys, rule: rule) print("\(label)\t: x y") print("Mean\t:\(String(format: "%7.4f,%7.4f", rxs.mean(), rys.mean()))") print("Std Dev\t:\(String(format: "%7.4f,%7.4f", rxs.stdDev(), rys.stdDev()))") print() } experiment(label: "Rule 1", rule: {_, _ in 0 }) experiment(label: "Rule 2", rule: {_, dz in -dz }) experiment(label: "Rule 3", rule: {z, dz in -(z + dz) }) experiment(label: "Rule 4", rule: {z, dz in z + dz })
954Deming's Funnel
17swift
6vq3j
(let [n (range 1 8)] (for [police n sanitation n fire n :when (distinct? police sanitation fire) :when (even? police) :when (= 12 (+ police sanitation fire))] (println police sanitation fire)))
958Department numbers
6clojure
r1fg2
import java.util.HashMap fun main() { System.out.printf("%-40s %2s %10s %8s %s %s%n", "String", "Length", "All Unique", "1st Diff", "Hex", "Positions") System.out.printf("%-40s %2s %10s %8s %s %s%n", "------------------------", "------", "----------", "--------", "---", "---------") for (s in arrayOf("", ".", "abcABC", "XYZ ZYX", "1234567890ABCDEFGHIJKLMN0PQRSTUVWXYZ")) { processString(s) } } private fun processString(input: String) { val charMap: MutableMap<Char, Int?> = HashMap() var dup = 0.toChar() var index = 0 var pos1 = -1 var pos2 = -1 for (key in input.toCharArray()) { index++ if (charMap.containsKey(key)) { dup = key pos1 = charMap[key]!! pos2 = index break } charMap[key] = index } val unique = if (dup.toInt() == 0) "yes" else "no" val diff = if (dup.toInt() == 0) "" else "'$dup'" val hex = if (dup.toInt() == 0) "" else Integer.toHexString(dup.toInt()).toUpperCase() val position = if (dup.toInt() == 0) "" else "$pos1 $pos2" System.out.printf("%-40s %-6d %-10s %-8s %-3s %-5s%n", input, input.length, unique, diff, hex, position) }
952Determine if a string has all unique characters
11kotlin
f9wdo
import threading import random import time class Philosopher(threading.Thread): running = True def __init__(self, xname, forkOnLeft, forkOnRight): threading.Thread.__init__(self) self.name = xname self.forkOnLeft = forkOnLeft self.forkOnRight = forkOnRight def run(self): while(self.running): time.sleep( random.uniform(3,13)) print '%s is hungry.'% self.name self.dine() def dine(self): fork1, fork2 = self.forkOnLeft, self.forkOnRight while self.running: fork1.acquire(True) locked = fork2.acquire(False) if locked: break fork1.release() print '%s swaps forks'% self.name fork1, fork2 = fork2, fork1 else: return self.dining() fork2.release() fork1.release() def dining(self): print '%s starts eating '% self.name time.sleep(random.uniform(1,10)) print '%s finishes eating and leaves to think.'% self.name def DiningPhilosophers(): forks = [threading.Lock() for n in range(5)] philosopherNames = ('Aristotle','Kant','Spinoza','Marx', 'Russel') philosophers= [Philosopher(philosopherNames[i], forks[i%5], forks[(i+1)%5]) \ for i in range(5)] random.seed(507129) Philosopher.running = True for p in philosophers: p.start() time.sleep(100) Philosopher.running = False print () DiningPhilosophers()
941Dining philosophers
3python
l7vcv
use strict; use warnings; use PDL; use PDL::NiceSlice; sub permanent{ my $mat = shift; my $n = shift // $mat->dim(0); return undef if $mat->dim(0) != $mat->dim(1); return $mat(0,0) if $n == 1; my $sum = 0; --$n; my $m = $mat(1:,1:)->copy; for(my $i = 0; $i <= $n; ++$i){ $sum += $mat($i,0) * permanent($m, $n); last if $i == $n; $m($i,:) .= $mat($i,1:); } return sclr($sum); } my $M = pdl([[2,9,4], [7,5,3], [6,1,8]]); print "M = $M\n"; print "det(M) = " . $M->determinant . ".\n"; print "det(M) = " . $M->det . ".\n"; print "perm(M) = " . permanent($M) . ".\n";
947Determinant and permanent
2perl
sfaq3
local find, format = string.find, string.format local function printf(fmt, ...) print(format(fmt,...)) end local pattern = '(.).-%1'
952Determine if a string has all unique characters
1lua
tcxfn
strings = [, ' --- Abraham Lincoln ', , , , , , , ,] strings.each do |str| puts ssq = str.squeeze puts puts end
948Determine if a string is collapsible
14ruby
nyqit
fn collapse_string(val: &str) -> String { let mut output = String::new(); let mut chars = val.chars().peekable(); while let Some(c) = chars.next() { while let Some(&b) = chars.peek() { if b == c { chars.next(); } else { break; } } output.push(c); } output } fn main() { let tests = [ "122333444455555666666777777788888888999999999", "", "\"If I were two-faced, would I be wearing this one?\" --- Abraham Lincoln ", "..1111111111111111111111111111111111111111111111111111111111111117777888", "I never give 'em hell, I just tell the truth, and they think it's hell. ", " --- Harry S Truman ", "The better the 4-wheel drive, the further you'll be from help when ya get stuck!", "headmistressship", ]; for s in &tests { println!("Old: {:>3} <<<{}>>>", s.len(), s); let collapsed = collapse_string(s); println!("New: {:>3} <<<{}>>>", collapsed.len(), collapsed); println!(); } }
948Determine if a string is collapsible
15rust
dmsny
use strict; use warnings; use feature 'say'; use utf8; binmode(STDOUT, ':utf8'); use List::AllUtils qw(uniq); use Unicode::UCD 'charinfo'; use Unicode::Normalize qw(NFC); for my $str ( '', ' ', '2', '333', '.55', 'tttTTT', '4444 444k', '', '', "\N{LATIN CAPITAL LETTER A}\N{COMBINING DIAERESIS}\N{COMBINING MACRON}" . "\N{LATIN CAPITAL LETTER A WITH DIAERESIS}\N{COMBINING MACRON}" . "\N{LATIN CAPITAL LETTER A WITH DIAERESIS AND MACRON}" ) { my @S; push @S, NFC $1 while $str =~ /(\X)/g; printf qq{\n"$str" (length: %d) has }, scalar @S; my @U = uniq @S; if (1 != @U and @U > 0) { say 'different characters:'; for my $l (@U) { printf "'%s'%s (0x%x) in positions:%s\n", $l, charinfo(ord $l)->{'name'}, ord($l), join ', ', map { 1+$_ } grep { $l eq $S[$_] } 0..$ } } else { say 'the same character in all positions.' } }
949Determine if a string has all the same characters
2perl
lrzc5
def solve( problem ) lines = problem.split() names = lines.first.scan( /[A-Z]\w*/ ) re_names = Regexp.union( names ) words = %w(first second third fourth fifth sixth seventh eighth ninth tenth bottom top higher lower adjacent) re_keywords = Regexp.union( words ) predicates = lines[1..-2].flat_map do |line| keywords = line.scan( re_keywords ) name1, name2 = line.scan( re_names ) keywords.map do |keyword| l = case keyword when then ->(c){ c.first == name1 } when then ->(c){ c.last == name1 } when then ->(c){ c.index( name1 ) > c.index( name2 ) } when then ->(c){ c.index( name1 ) < c.index( name2 ) } when then ->(c){ (c.index( name1 ) - c.index( name2 )).abs == 1 } else ->(c){ c[words.index(keyword)] == name1 } end line =~ /\bnot\b/? ->(c){not l.call(c) }: l end end names.permutation.detect{|candidate| predicates.all?{|predicate| predicate.(candidate)}} end
939Dinesman's multiple-dwelling problem
14ruby
rakgs
package main import "os" func main() { os.Remove("input.txt") os.Remove("/input.txt") os.Remove("docs") os.Remove("/docs")
957Delete a file
0go
gpf4n
public static boolean infinity(double numer, double denom){ return Double.isInfinite(numer/denom); }
953Detect division by zero
9java
f9edv
object CollapsibleString { def collapseString (s : String) : String = { var res = s var isOver = false var i = 0 if(res.size == 0) res else while(!isOver){ if(res(i) == res(i+1)){ res = res.take(i) ++ res.drop(i+1) i-=1 } i+=1 if(i==res.size-1) isOver = true } res } def isCollapsible (s : String) : Boolean = collapseString(s).length != s.length def reportResults (s : String) : String = { val sCollapsed = collapseString(s) val originalRes = "ORIGINAL : length = " + s.length() + ", string = " + s + "" val collapsedRes = "COLLAPSED: length = " + sCollapsed.length() + ", string = " + sCollapsed + ""
948Determine if a string is collapsible
16scala
zlotr
import datetime, calendar DISCORDIAN_SEASONS = [, , , , ] def ddate(year, month, day): today = datetime.date(year, month, day) is_leap_year = calendar.isleap(year) if is_leap_year and month == 2 and day == 29: return + (year + 1166) day_of_year = today.timetuple().tm_yday - 1 if is_leap_year and day_of_year >= 60: day_of_year -= 1 season, dday = divmod(day_of_year, 73) return % (DISCORDIAN_SEASONS[season], dday + 1, year + 1166)
944Discordian date
3python
yu36q
use strict; use warnings; use List::Util qw(sum); my @digit = (0..9, 'a'..'z'); my %digit = map { +$digit[$_], $_ } 0 .. $ sub base { my ($n, $b) = @_; $b ||= 10; die if $b > @digit; my $result = ''; while( $n ) { $result .= $digit[ $n % $b ]; $n = int( $n / $b ); } reverse($result) || '0'; } sub digi_root { my ($n, $b) = @_; my $inbase = base($n, $b); my $additive_persistance = 0; while( length($inbase) > 1 ) { ++$additive_persistance; $n = sum @digit{split //, $inbase}; $inbase = base($n, $b); } $additive_persistance, $n; } MAIN: { my @numbers = (5, 627615, 39390, 588225, 393900588225); my @bases = (2, 3, 8, 10, 16, 36); my $fmt = "%25s(%2s): persistance =%s, root =%2s\n"; if( eval { require Math::BigInt; 1 } ) { push @numbers, Math::BigInt->new("5814271898167303040368". "1039458302204471300738980834668522257090844071443085937"); } for my $base (@bases) { for my $num (@numbers) { my $inbase = base($num, $base); $inbase = 'BIG' if length($inbase) > 25; printf $fmt, $inbase, $base, digi_root($num, $base); } print "\n"; } }
945Digital root
2perl
ny8iw
import scala.math.abs object Dinesman3 extends App { val tenants = List("Baker", "Cooper2", "Fletcher4", "Miller", "Smith") val (groundFloor, topFloor) = (1, tenants.size) val exclusions = List((suggestedFloor0: Map[String, Int]) => suggestedFloor0("Baker") != topFloor, (suggestedFloor1: Map[String, Int]) => suggestedFloor1("Cooper2") != groundFloor, (suggestedFloor2: Map[String, Int]) => !List(groundFloor, topFloor).contains(suggestedFloor2("Fletcher4")), (suggestedFloor3: Map[String, Int]) => suggestedFloor3("Miller") > suggestedFloor3("Cooper2"), (suggestedFloor4: Map[String, Int]) => abs(suggestedFloor4("Smith") - suggestedFloor4("Fletcher4")) != 1, (suggestedFloor5: Map[String, Int]) => abs(suggestedFloor5("Fletcher4") - suggestedFloor5("Cooper2")) != 1) tenants.permutations.map(_ zip (groundFloor to topFloor)). filter(p => exclusions.forall(_(p.toMap))).toList match { case Nil => println("No solution") case xss => { println(s"Solutions: ${xss.size}") xss.foreach { l => println("possible solution:") l.foreach(p => println(f"${p._1}%11s lives on floor number ${p._2}")) } } } }
939Dinesman's multiple-dwelling problem
16scala
kqahk
use strict; use warnings; sub det2D { my $p1 = shift or die "4 Missing first point\n"; my $p2 = shift or die "Missing second point\n"; my $p3 = shift or die "Missing third point\n"; return $p1->{x} * ($p2->{y} - $p3->{y}) + $p2->{x} * ($p3->{y} - $p1->{y}) + $p3->{x} * ($p1->{y} - $p2->{y}); } sub checkTriWinding { my $p1 = shift or die "14 Missing first point\n"; my $p2 = shift or die "Missing second point\n"; my $p3 = shift or die "Missing third point\n"; my $allowReversed = shift; my $detTri = det2D($p1, $$p2, $$p3); if ($detTri < 0.0) { if ($allowReversed) { my $t = $$p3; $$p3 = $$p2; $$p2 = $t; } else { die "triangle has wrong winding direction"; } } return undef; } sub boundaryCollideChk { my $p1 = shift or die "33 Missing first point\n"; my $p2 = shift or die "Missing second point\n"; my $p3 = shift or die "Missing third point\n"; my $eps = shift; return det2D($p1, $p2, $p3) < $eps; } sub boundaryDoesntCollideChk { my $p1 = shift or die "42 Missing first point\n"; my $p2 = shift or die "Missing second point\n"; my $p3 = shift or die "Missing third point\n"; my $eps = shift; return det2D($p1, $p2, $p3) <= $eps; } sub triTri2D { my $t1 = shift or die "Missing first triangle to calculate with\n"; my $t2 = shift or die "Missing second triangle to calculate with\n"; my $eps = shift; my $allowReversed = shift; my $onBoundary = shift; checkTriWinding($t1->[0], \$t1->[1], \$t1->[2], $allowReversed); checkTriWinding($t2->[0], \$t2->[1], \$t2->[2], $allowReversed); my $chkEdge; if ($onBoundary) { $chkEdge = \&boundaryCollideChk; } else { $chkEdge = \&boundaryDoesntCollideChk; } foreach my $i (0, 1, 2) { my $j = ($i + 1) % 3; if ($chkEdge->($t1->[$i], $t1->[$j], $t2->[0], $eps) and $chkEdge->($t1->[$i], $t1->[$j], $t2->[1], $eps) and $chkEdge->($t1->[$i], $t1->[$j], $t2->[2], $eps)) { return 0; } } foreach my $i (0, 1, 2) { my $j = ($i + 1) % 3; if ($chkEdge->($t2->[$i], $t2->[$j], $t1->[0], $eps) and $chkEdge->($t2->[$i], $t2->[$j], $t1->[1], $eps) and $chkEdge->($t2->[$i], $t2->[$j], $t1->[2], $eps)) { return 0; } } return 1; } sub formatTri { my $t = shift or die "Missing triangle to format\n"; my $p1 = $t->[0]; my $p2 = $t->[1]; my $p3 = $t->[2]; return "Triangle: ($p1->{x}, $p1->{y}), ($p2->{x}, $p2->{y}), ($p3->{x}, $p3->{y})"; } sub overlap { my $t1 = shift or die "Missing first triangle to calculate with\n"; my $t2 = shift or die "Missing second triangle to calculate with\n"; my $eps = shift; my $allowReversed = shift or 0; my $onBoundary = shift or 1; unless ($eps) { $eps = 0.0; } if (triTri2D($t1, $t2, $eps, $allowReversed, $onBoundary)) { return "overlap\n"; } else { return "do not overlap\n"; } } my @t1 = ({x=>0, y=>0}, {x=>5, y=>0}, {x=>0, y=>5}); my @t2 = ({x=>0, y=>0}, {x=>5, y=>0}, {x=>0, y=>6}); print formatTri(\@t1), " and\n", formatTri(\@t2), "\n", overlap(\@t1, \@t2), "\n"; @t1 = ({x=>0, y=>0}, {x=>0, y=>5}, {x=>5, y=>0}); @t2 = ({x=>0, y=>0}, {x=>0, y=>5}, {x=>5, y=>0}); print formatTri(\@t1), " and\n", formatTri(\@t2), "\n", overlap(\@t1, \@t2, 0.0, 1), "\n"; @t1 = ({x=>0, y=>0}, {x=>5, y=>0}, {x=>0, y=>5}); @t2 = ({x=>-10, y=>0}, {x=>-5, y=>0}, {x=>-1, y=>6}); print formatTri(\@t1), " and\n", formatTri(\@t2), "\n", overlap(\@t1, \@t2), "\n"; @t1 = ({x=>0, y=>0}, {x=>5, y=>0}, {x=>2.5, y=>5}); @t2 = ({x=>0, y=>4}, {x=>2.5, y=>-1}, {x=>5, y=>4}); print formatTri(\@t1), " and\n", formatTri(\@t2), "\n", overlap(\@t1, \@t2), "\n"; @t1 = ({x=>0, y=>0}, {x=>1, y=>1}, {x=>0, y=>2}); @t2 = ({x=>2, y=>1}, {x=>3, y=>0}, {x=>3, y=>2}); print formatTri(\@t1), " and\n", formatTri(\@t2), "\n", overlap(\@t1, \@t2), "\n"; @t1 = ({x=>0, y=>0}, {x=>1, y=>1}, {x=>0, y=>2}); @t2 = ({x=>2, y=>1}, {x=>3, y=>-2}, {x=>3, y=>4}); print formatTri(\@t1), " and\n", formatTri(\@t2), "\n", overlap(\@t1, \@t2), "\n"; @t1 = ({x=>0, y=>0}, {x=>1, y=>0}, {x=>0, y=>1}); @t2 = ({x=>1, y=>0}, {x=>2, y=>0}, {x=>1, y=>1}); print formatTri(\@t1), " and\n", formatTri(\@t2), "\n", overlap(\@t1, \@t2, 0.0, 0, 1), "\n"; @t1 = ({x=>0, y=>0}, {x=>1, y=>0}, {x=>0, y=>1}); @t2 = ({x=>1, y=>0}, {x=>2, y=>0}, {x=>1, y=>1}); print formatTri(\@t1), " and\n", formatTri(\@t2), "\n", overlap(\@t1, \@t2, 0.0, 0, 0), "\n";
950Determine if two triangles overlap
2perl
gp94e
null
957Delete a file
7groovy
278lv
function divByZero(dividend,divisor) { var quotient=dividend/divisor; if(isNaN(quotient)) return 0;
953Detect division by zero
10javascript
yu06r
class Graph Vertex = Struct.new(:name,:neighbours,:dist,:prev) def initialize(graph) @vertices = Hash.new{|h,k| h[k]=Vertex.new(k,[],Float::INFINITY)} @edges = {} graph.each do |(v1, v2, dist)| @vertices[v1].neighbours << v2 @vertices[v2].neighbours << v1 @edges[[v1, v2]] = @edges[[v2, v1]] = dist end @dijkstra_source = nil end def dijkstra(source) return if @dijkstra_source == source q = @vertices.values q.each do |v| v.dist = Float::INFINITY v.prev = nil end @vertices[source].dist = 0 until q.empty? u = q.min_by {|vertex| vertex.dist} break if u.dist == Float::INFINITY q.delete(u) u.neighbours.each do |v| vv = @vertices[v] if q.include?(vv) alt = u.dist + @edges[[u.name, v]] if alt < vv.dist vv.dist = alt vv.prev = u.name end end end end @dijkstra_source = source end def shortest_path(source, target) dijkstra(source) path = [] u = target while u path.unshift(u) u = @vertices[u].prev end return path, @vertices[target].dist end def to_s % [self.class.name, @vertices.values, @edges] end end g = Graph.new([ [:a,:b, 7], [:a,:c, 9], [:a,:f, 14], [:b,:c, 10], [:b,:d, 15], [:c,:d, 11], [:c,:f, 2], [:d,:e, 6], [:e,:f, 9], ]) start, stop =:a,:e path, dist = g.shortest_path(start, stop) puts puts path.join()
942Dijkstra's algorithm
14ruby
ra7gs
function dotprod(a, b) local ret = 0 for i = 1, #a do ret = ret + a[i] * b[i] end return ret end print(dotprod({1, 3, -5}, {4, -2, 1}))
938Dot product
1lua
0zdsd
import System.IO import System.Directory main = do removeFile "output.txt" removeDirectory "docs" removeFile "/output.txt" removeDirectory "/docs"
957Delete a file
8haskell
sf4qk