code
stringlengths
1
46.1k
label
class label
1.18k classes
domain_label
class label
21 classes
index
stringlengths
4
5
function clone(obj){ if (obj == null || typeof(obj) != 'object') return obj; var temp = {}; for (var key in obj) temp[key] = clone(obj[key]); return temp; }
414Polymorphic copy
10javascript
sriqz
package main import ( "fmt" "log" "gonum.org/v1/gonum/mat" ) func main() { var ( x = []float64{0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10} y = []float64{1, 6, 17, 34, 57, 86, 121, 162, 209, 262, 321} degree = 2 a = Vandermonde(x, degree+1) b = mat.NewDense(len(y), 1, y) c = mat.NewDense(degree+1, 1, nil) ) var qr mat.QR qr.Factorize(a) const trans = false err := qr.SolveTo(c, trans, b) if err != nil { log.Fatalf("could not solve QR:%+v", err) } fmt.Printf("%.3f\n", mat.Formatted(c)) } func Vandermonde(a []float64, d int) *mat.Dense { x := mat.NewDense(len(a), d, nil) for i := range a { for j, p := 0, 1.0; j < d; j, p = j+1, p*a[i] { x.Set(i, j, p) } } return x }
417Polynomial regression
0go
gzr4n
PriorityQueue = { __index = { put = function(self, p, v) local q = self[p] if not q then q = {first = 1, last = 0} self[p] = q end q.last = q.last + 1 q[q.last] = v end, pop = function(self) for p, q in pairs(self) do if q.first <= q.last then local v = q[q.first] q[q.first] = nil q.first = q.first + 1 return p, v else self[p] = nil end end end }, __call = function(cls) return setmetatable({}, cls) end } setmetatable(PriorityQueue, PriorityQueue)
408Priority queue
1lua
5f1u6
import BigInt func factorial<T: BinaryInteger>(_ n: T) -> T { guard n!= 0 else { return 1 } return stride(from: n, to: 0, by: -1).reduce(1, *) } func isWilsonPrime<T: BinaryInteger>(_ n: T) -> Bool { guard n >= 2 else { return false } return (factorial(n - 1) + 1)% n == 0 } print((1...100).map({ BigInt($0) }).filter(isWilsonPrime))
412Primality by Wilson's theorem
17swift
bcxkd
null
423Pointers and references
11kotlin
5d9ua
package main import ( "fmt" "sort" "strings" ) type card struct { face byte suit byte } const faces = "23456789tjqka" const suits = "shdc" func isStraight(cards []card) bool { sorted := make([]card, 5) copy(sorted, cards) sort.Slice(sorted, func(i, j int) bool { return sorted[i].face < sorted[j].face }) if sorted[0].face+4 == sorted[4].face { return true } if sorted[4].face == 14 && sorted[0].face == 2 && sorted[3].face == 5 { return true } return false } func isFlush(cards []card) bool { suit := cards[0].suit for i := 1; i < 5; i++ { if cards[i].suit != suit { return false } } return true } func analyzeHand(hand string) string { temp := strings.Fields(strings.ToLower(hand)) splitSet := make(map[string]bool) var split []string for _, s := range temp { if !splitSet[s] { splitSet[s] = true split = append(split, s) } } if len(split) != 5 { return "invalid" } var cards []card for _, s := range split { if len(s) != 2 { return "invalid" } fIndex := strings.IndexByte(faces, s[0]) if fIndex == -1 { return "invalid" } sIndex := strings.IndexByte(suits, s[1]) if sIndex == -1 { return "invalid" } cards = append(cards, card{byte(fIndex + 2), s[1]}) } groups := make(map[byte][]card) for _, c := range cards { groups[c.face] = append(groups[c.face], c) } switch len(groups) { case 2: for _, group := range groups { if len(group) == 4 { return "four-of-a-kind" } } return "full-house" case 3: for _, group := range groups { if len(group) == 3 { return "three-of-a-kind" } } return "two-pair" case 4: return "one-pair" default: flush := isFlush(cards) straight := isStraight(cards) switch { case flush && straight: return "straight-flush" case flush: return "flush" case straight: return "straight" default: return "high-card" } } } func main() { hands := [...]string{ "2h 2d 2c kc qd", "2h 5h 7d 8c 9s", "ah 2d 3c 4c 5d", "2h 3h 2d 3c 3d", "2h 7h 2d 3c 3d", "2h 7h 7d 7c 7s", "th jh qh kh ah", "4h 4s ks 5d ts", "qc tc 7c 6c 4c", "ah ah 7c 6c 4c", } for _, hand := range hands { fmt.Printf("%s:%s\n", hand, analyzeHand(hand)) } }
419Poker hand analyser
0go
ev1a6
int main() { { unsigned long long n = 1; for (int i = 0; i < 30; i++) { printf(, __builtin_popcountll(n)); n *= 3; } printf(); } int od[30]; int ne = 0, no = 0; printf(); for (int n = 0; ne+no < 60; n++) { if ((__builtin_popcount(n) & 1) == 0) { if (ne < 30) { printf(, n); ne++; } } else { if (no < 30) { od[no++] = n; } } } printf(); printf(); for (int i = 0; i < 30; i++) { printf(, od[i]); } printf(); return 0; }
424Population count
5c
3eoza
null
414Polymorphic copy
11kotlin
hm1j3
T = { name=function(s) return "T" end, tostring=function(s) return "I am a "..s:name() end } function clone(s) local t={} for k,v in pairs(s) do t[k]=v end return t end S1 = clone(T) S1.name=function(s) return "S1" end function merge(s,t) for k,v in pairs(t) do s[k]=v end return s end S2 = merge(clone(T), {name=function(s) return "S2" end}) function prototype(base,mixin) return merge(merge(clone(base),mixin),{prototype=base}) end S3 = prototype(T, {name=function(s) return "S3" end}) print("T: "..T:tostring()) print("S1: " ..S1:tostring()) print("S2: " ..S2:tostring()) print("S3: " ..S3:tostring()) print("S3's parent: "..S3.prototype:tostring())
414Polymorphic copy
1lua
k9ah2
import Data.List import Data.Array import Control.Monad import Control.Arrow import Matrix.LU ppoly p x = map (x**) p polyfit d ry = elems $ solve mat vec where mat = listArray ((1,1), (d,d)) $ liftM2 concatMap ppoly id [0..fromIntegral $ pred d] vec = listArray (1,d) $ take d ry
417Polynomial regression
8haskell
sr0qk
import java.util.Collections; import java.util.LinkedList; import java.util.List; public class Proper{ public static List<Integer> properDivs(int n){ List<Integer> divs = new LinkedList<Integer>(); if(n == 1) return divs; divs.add(1); for(int x = 2; x < n; x++){ if(n % x == 0) divs.add(x); } Collections.sort(divs); return divs; } public static void main(String[] args){ for(int x = 1; x <= 10; x++){ System.out.println(x + ": " + properDivs(x)); } int x = 0, count = 0; for(int n = 1; n <= 20000; n++){ if(properDivs(n).size() > count){ x = n; count = properDivs(n).size(); } } System.out.println(x + ": " + count); } }
411Proper divisors
9java
zeltq
var total = 0 var prim = 0 var maxPeri = 100 func newTri(s0:Int, _ s1:Int, _ s2: Int) -> () { let p = s0 + s1 + s2 if p <= maxPeri { prim += 1 total += maxPeri / p newTri( s0 + 2*(-s1+s2), 2*( s0+s2) - s1, 2*( s0-s1+s2) + s2) newTri( s0 + 2*( s1+s2), 2*( s0+s2) + s1, 2*( s0+s1+s2) + s2) newTri(-s0 + 2*( s1+s2), 2*(-s0+s2) + s1, 2*(-s0+s1+s2) + s2) } } while maxPeri <= 100_000_000 { prim = 0 total = 0 newTri(3, 4, 5) print("Up to \(maxPeri): \(total) triples \( prim) primitives.") maxPeri *= 10 }
399Pythagorean triples
17swift
gzn49
local table1 = {1,2,3} local table2 = table1 table2[3] = 4 print(unpack(table1))
423Pointers and references
1lua
4fc5c
import Data.Function (on) import Data.List (group, nub, any, sort, sortBy) import Data.Maybe (mapMaybe) import Text.Read (readMaybe) data Suit = Club | Diamond | Spade | Heart deriving (Show, Eq) data Rank = Ace | Two | Three | Four | Five | Six | Seven | Eight | Nine | Ten | Jack | Queen | King deriving (Show, Eq, Enum, Ord, Bounded) data Card = Card { suit :: Suit, rank :: Rank } deriving (Show, Eq) type Hand = [Card] consumed = pure . (, "") instance Read Suit where readsPrec d s = case s of "" -> consumed Heart "" -> consumed Diamond "" -> consumed Spade "" -> consumed Club "h" -> consumed Heart _ -> [] instance Read Rank where readsPrec d s = case s of "a" -> consumed Ace "2" -> consumed Two "3" -> consumed Three "4" -> consumed Four "5" -> consumed Five "6" -> consumed Six "7" -> consumed Seven "8" -> consumed Eight "9" -> consumed Nine "10" -> consumed Ten "j" -> consumed Jack "q" -> consumed Queen "k" -> consumed King _ -> [] instance Read Card where readsPrec d = fmap (, "") . mapMaybe card . lex where card (r, s) = Card <$> (readMaybe s :: Maybe Suit) <*> (readMaybe r :: Maybe Rank) acesHigh :: [Rank] acesHigh = [Ace, Ten, Jack, Queen, King] isSucc :: (Enum a, Eq a, Bounded a) => [a] -> Bool isSucc [] = True isSucc [x] = True isSucc (x:y:zs) = (x /= maxBound && y == succ x) && isSucc (y:zs) nameHand :: Hand -> String nameHand [] = "Invalid Input" nameHand cards | invalidHand = "Invalid hand" | straight && flush = "Straight flush" | ofKind 4 = "Four of a kind" | ofKind 3 && ofKind 2 = "Full house" | flush = "Flush" | straight = "Straight" | ofKind 3 = "Three of a kind" | uniqRanks == 3 = "Two pair" | uniqRanks == 4 = "One pair" | otherwise = "High card" where sortedRank = sort $ rank <$> cards rankCounts = sortBy (compare `on` snd) $ (,) <$> head <*> length <$> group sortedRank uniqRanks = length rankCounts ofKind n = any ((==n) . snd) rankCounts straight = isSucc sortedRank || sortedRank == acesHigh flush = length (nub $ suit <$> cards) == 1 invalidHand = length (nub cards) /= 5 testHands :: [(String, Hand)] testHands = (,) <$> id <*> mapMaybe readMaybe . words <$> [ "2 2 2 k q" , "2 5 7 8 9" , "a 2 3 4 5" , "2 3 2 3 3" , "2 7 2 3 3" , "2 7 7 7 7" , "10 j q k a" , "4 4 k 5 10" , "q 10 7 6 4" , "q 10 7 6 7" , "Bad input" ] main :: IO () main = mapM_ (putStrLn . (fst <> const ": " <> nameHand . snd)) testHands
419Poker hand analyser
8haskell
3etzj
(function () {
411Proper divisors
10javascript
904ml
import java.util.Arrays; import java.util.Collections; import java.util.HashSet; public class PokerHandAnalyzer { final static String faces = "AKQJT98765432"; final static String suits = "HDSC"; final static String[] deck = buildDeck(); public static void main(String[] args) { System.out.println("Regular hands:\n"); for (String input : new String[]{"2H 2D 2S KS QD", "2H 5H 7D 8S 9D", "AH 2D 3S 4S 5S", "2H 3H 2D 3S 3D", "2H 7H 2D 3S 3D", "2H 7H 7D 7S 7C", "TH JH QH KH AH", "4H 4C KC 5D TC", "QC TC 7C 6C 4C", "QC TC 7C 7C TD"}) { System.out.println(analyzeHand(input.split(" "))); } System.out.println("\nHands with wildcards:\n"); for (String input : new String[]{"2H 2D 2S KS WW", "2H 5H 7D 8S WW", "AH 2D 3S 4S WW", "2H 3H 2D 3S WW", "2H 7H 2D 3S WW", "2H 7H 7D WW WW", "TH JH QH WW WW", "4H 4C KC WW WW", "QC TC 7C WW WW", "QC TC 7H WW WW"}) { System.out.println(analyzeHandWithWildcards(input.split(" "))); } } private static Score analyzeHand(final String[] hand) { if (hand.length != 5) return new Score("invalid hand: wrong number of cards", -1, hand); if (new HashSet<>(Arrays.asList(hand)).size() != hand.length) return new Score("invalid hand: duplicates", -1, hand); int[] faceCount = new int[faces.length()]; long straight = 0, flush = 0; for (String card : hand) { int face = faces.indexOf(card.charAt(0)); if (face == -1) return new Score("invalid hand: non existing face", -1, hand); straight |= (1 << face); faceCount[face]++; if (suits.indexOf(card.charAt(1)) == -1) return new Score("invalid hand: non-existing suit", -1, hand); flush |= (1 << card.charAt(1)); }
419Poker hand analyser
9java
ih8os
(defn population-count [n] (Long/bitCount n)) (defn exp [n pow] (reduce * (repeat pow n))) (defn evil? [n] (even? (population-count n))) (defn odious? [n] (odd? (population-count n))) (defn integers [] (iterate inc 0)) (defn powers-of-n [n] (map #(exp n %) (integers))) (defn evil-numbers [] (filter evil? (integers))) (defn odious-numbers [] (filter odious? (integers)))
424Population count
6clojure
c0t9b
package main import "fmt" func main() { n := []float64{-42, 0, -12, 1} d := []float64{-3, 1} fmt.Println("N:", n) fmt.Println("D:", d) q, r, ok := pld(n, d) if ok { fmt.Println("Q:", q) fmt.Println("R:", r) } else { fmt.Println("error") } } func degree(p []float64) int { for d := len(p) - 1; d >= 0; d-- { if p[d] != 0 { return d } } return -1 } func pld(nn, dd []float64) (q, r []float64, ok bool) { if degree(dd) < 0 { return } nn = append(r, nn...) if degree(nn) >= degree(dd) { q = make([]float64, degree(nn)-degree(dd)+1) for degree(nn) >= degree(dd) { d := make([]float64, degree(nn)+1) copy(d[degree(nn)-degree(dd):], dd) q[degree(nn)-degree(dd)] = nn[degree(nn)] / d[degree(d)] for i := range d { d[i] *= q[degree(nn)-degree(dd)] nn[i] -= d[i] } } } return q, nn, true }
416Polynomial long division
0go
mscyi
const FACES = ['2', '3', '4', '5', '6', '7', '8', '9', '10', 'j', 'q', 'k', 'a']; const SUITS = ['', '', '', '']; function analyzeHand(hand){ let cards = hand.split(' ').filter(x => x !== 'joker'); let jokers = hand.split(' ').length - cards.length; let faces = cards.map( card => FACES.indexOf(card.slice(0,-1)) ); let suits = cards.map( card => SUITS.indexOf(card.slice(-1)) ); if( cards.some( (card, i, self) => i !== self.indexOf(card) ) || faces.some(face => face === -1) || suits.some(suit => suit === -1) ) return 'invalid'; let flush = suits.every(suit => suit === suits[0]); let groups = FACES.map( (face,i) => faces.filter(j => i === j).length).sort( (x, y) => y - x ); let shifted = faces.map(x => (x + 1) % 13); let distance = Math.min( Math.max(...faces) - Math.min(...faces), Math.max(...shifted) - Math.min(...shifted)); let straight = groups[0] === 1 && distance < 5; groups[0] += jokers; if (groups[0] === 5) return 'five-of-a-kind' else if (straight && flush) return 'straight-flush' else if (groups[0] === 4) return 'four-of-a-kind' else if (groups[0] === 3 && groups[1] === 2) return 'full-house' else if (flush) return 'flush' else if (straight) return 'straight' else if (groups[0] === 3) return 'three-of-a-kind' else if (groups[0] === 2 && groups[1] === 2) return 'two-pair' else if (groups[0] === 2) return 'one-pair' else return 'high-card'; }
419Poker hand analyser
10javascript
zaft2
import Data.List shift n l = l ++ replicate n 0 pad n l = replicate n 0 ++ l norm :: Fractional a => [a] -> [a] norm = dropWhile (== 0) deg l = length (norm l) - 1 zipWith' op p q = zipWith op (pad (-d) p) (pad d q) where d = (length p) - (length q) polydiv f g = aux (norm f) (norm g) [] where aux f s q | ddif < 0 = (q, f) | otherwise = aux f' s q' where ddif = (deg f) - (deg s) k = (head f) / (head s) ks = map (* k) $ shift ddif s q' = zipWith' (+) q $ shift ddif [k] f' = norm $ tail $ zipWith' (-) f ks
416Polynomial long division
8haskell
k9ph0
package T; sub new { my $cls = shift; bless [ @_ ], $cls } sub set_data { my $self = shift; @$self = @_; } sub copy { my $self = shift; bless [ @$self ], ref $self; } sub manifest { my $self = shift; print "type T, content: @$self\n\n"; } package S; our @ISA = 'T'; sub manifest { my $self = shift; print "type S, content: @$self\n\n"; } package main; print " my $t = T->new('abc'); $t->manifest; print " my $s = S->new('SPQR'); $s->manifest; print " my $x = $t->copy; $x->manifest; print " $x = $s->copy; $x->manifest; print " $x->set_data('totally different'); print "\$x is: "; $x->manifest;
414Polymorphic copy
2perl
zemtb
import java.util.Arrays; import java.util.function.IntToDoubleFunction; import java.util.stream.IntStream; public class PolynomialRegression { private static void polyRegression(int[] x, int[] y) { int n = x.length; int[] r = IntStream.range(0, n).toArray(); double xm = Arrays.stream(x).average().orElse(Double.NaN); double ym = Arrays.stream(y).average().orElse(Double.NaN); double x2m = Arrays.stream(r).map(a -> a * a).average().orElse(Double.NaN); double x3m = Arrays.stream(r).map(a -> a * a * a).average().orElse(Double.NaN); double x4m = Arrays.stream(r).map(a -> a * a * a * a).average().orElse(Double.NaN); double xym = 0.0; for (int i = 0; i < x.length && i < y.length; ++i) { xym += x[i] * y[i]; } xym /= Math.min(x.length, y.length); double x2ym = 0.0; for (int i = 0; i < x.length && i < y.length; ++i) { x2ym += x[i] * x[i] * y[i]; } x2ym /= Math.min(x.length, y.length); double sxx = x2m - xm * xm; double sxy = xym - xm * ym; double sxx2 = x3m - xm * x2m; double sx2x2 = x4m - x2m * x2m; double sx2y = x2ym - x2m * ym; double b = (sxy * sx2x2 - sx2y * sxx2) / (sxx * sx2x2 - sxx2 * sxx2); double c = (sx2y * sxx - sxy * sxx2) / (sxx * sx2x2 - sxx2 * sxx2); double a = ym - b * xm - c * x2m; IntToDoubleFunction abc = (int xx) -> a + b * xx + c * xx * xx; System.out.println("y = " + a + " + " + b + "x + " + c + "x^2"); System.out.println(" Input Approximation"); System.out.println(" x y y1"); for (int i = 0; i < n; ++i) { System.out.printf("%2d%3d %5.1f\n", x[i], y[i], abc.applyAsDouble(x[i])); } } public static void main(String[] args) { int[] x = IntStream.range(0, 11).toArray(); int[] y = new int[]{1, 6, 17, 34, 57, 86, 121, 162, 209, 262, 321}; polyRegression(x, y); } }
417Polynomial regression
9java
12ap2
int is_prime(unsigned int n) { unsigned int p; if (!(n & 1) || n < 2 ) return n == 2; for (p = 3; p <= n/p; p += 2) if (!(n % p)) return 0; return 1; }
425Primality by trial division
5c
rzcg7
package main import "fmt" func pf(v float64) float64 { switch { case v < .06: return .10 case v < .11: return .18 case v < .16: return .26 case v < .21: return .32 case v < .26: return .38 case v < .31: return .44 case v < .36: return .50 case v < .41: return .54 case v < .46: return .58 case v < .51: return .62 case v < .56: return .66 case v < .61: return .70 case v < .66: return .74 case v < .71: return .78 case v < .76: return .82 case v < .81: return .86 case v < .86: return .90 case v < .91: return .94 case v < .96: return .98 } return 1 } func main() { tests := []float64{0.3793, 0.4425, 0.0746, 0.6918, 0.2993, 0.5486, 0.7848, 0.9383, 0.2292, 0.9760} for _, v := range tests { fmt.Printf("%0.4f ->%0.2f\n", v, pf(v)) } }
415Price fraction
0go
f13d0
null
411Proper divisors
11kotlin
ik6o4
import random, bisect def probchoice(items, probs): '''\ Splits the interval 0.0-1.0 in proportion to probs then finds where each random.random() choice lies ''' prob_accumulator = 0 accumulator = [] for p in probs: prob_accumulator += p accumulator.append(prob_accumulator) while True: r = random.random() yield items[bisect.bisect(accumulator, r)] def probchoice2(items, probs, bincount=10000): '''\ Puts items in bins in proportion to probs then uses random.choice() to select items. Larger bincount for more memory use but higher accuracy (on avarage). ''' bins = [] for item,prob in zip(items, probs): bins += [item]*int(bincount*prob) while True: yield random.choice(bins) def tester(func=probchoice, items='good bad ugly'.split(), probs=[0.5, 0.3, 0.2], trials = 100000 ): def problist2string(probs): '''\ Turns a list of probabilities into a string Also rounds FP values ''' return .join('%8.6f'% (p,) for p in probs) from collections import defaultdict counter = defaultdict(int) it = func(items, probs) for dummy in xrange(trials): counter[it.next()] += 1 print % func.func_name.upper() print , trials print , ' '.join(items) print , problist2string(probs) print , problist2string( counter[x]/float(trials) for x in items) if __name__ == '__main__': items = 'aleph beth gimel daleth he waw zayin heth'.split() probs = [1/(float(n)+5) for n in range(len(items))] probs[-1] = 1-sum(probs[:-1]) tester(probchoice, items, probs, 1000000) tester(probchoice2, items, probs, 1000000)
410Probabilistic choice
3python
r3agq
my $scalar = 'aa'; my @array = ('bb', 'cc'); my %hash = ( dd => 'DD', ee => 'EE' ); my $scalarref = \$scalar; my $arrayref = \@array; my $hashref = \%hash;
423Pointers and references
2perl
ojw8x
package main import ( "fmt" "log" "os/exec" ) var ( x = []int{0, 1, 2, 3, 4, 5, 6, 7, 8, 9} y = []float64{2.7, 2.8, 31.4, 38.1, 58.0, 76.2, 100.5, 130.0, 149.3, 180.0} ) func main() { g := exec.Command("gnuplot", "-persist") w, err := g.StdinPipe() if err != nil { log.Fatal(err) } if err = g.Start(); err != nil { log.Fatal(err) } fmt.Fprintln(w, "unset key; plot '-'") for i, xi := range x { fmt.Fprintf(w, "%d%f\n", xi, y[i]) } fmt.Fprintln(w, "e") w.Close() g.Wait() }
422Plot coordinate pairs
0go
87w0g
<?php class T { function name() { return ; } } class S { function name() { return ; } } $obj1 = new T(); $obj2 = new S(); $obj3 = clone $obj1; $obj4 = clone $obj2; echo $obj3->name(), ; echo $obj4->name(), ; ?>
414Polymorphic copy
12php
bcek9
def priceFraction(value) { assert value >= 0.0 && value <= 1.0 def priceMappings = [(0.06): 0.10, (0.11): 0.18, (0.16): 0.26, (0.21): 0.32, (0.26): 0.38, (0.31): 0.44, (0.36): 0.50, (0.41): 0.54, (0.46): 0.58, (0.51): 0.62, (0.56): 0.66, (0.61): 0.70, (0.66): 0.74, (0.71): 0.78, (0.76): 0.82, (0.81): 0.86, (0.86): 0.90, (0.91): 0.94, (0.96): 0.98] for (price in priceMappings.keySet()) { if (value < price) return priceMappings[price] } 1.00 } for (def v = 0.00; v <= 1.00; v += 0.01) { println "$v --> ${priceFraction(v)}" }
415Price fraction
7groovy
8jn0b
null
411Proper divisors
1lua
nbyi8
prob = c(aleph=1/5, beth=1/6, gimel=1/7, daleth=1/8, he=1/9, waw=1/10, zayin=1/11, heth=1759/27720) hebrew = c(rmultinom(1, 1e6, prob)) d = data.frame( Requested = prob, Obtained = hebrew/sum(hebrew)) print(d)
410Probabilistic choice
13r
udkvx
<?php $a = 1; $b =& $a; $b = 2; $c = $b; $c = 7; unset($a); function &pass_out() { global $filestr; $filestr = get_file_contents(); return $_GLOBALS['filestr']; } function pass_in(&$in_filestr) { echo . strlen($in_filestr); $in_filestr .= ; echo . strlen($in_filestr); } $tmp = &pass_out(); pass_in($tmp); ?>
423Pointers and references
12php
gtl42
import groovy.swing.SwingBuilder import javax.swing.JFrame import org.jfree.chart.ChartFactory import org.jfree.chart.ChartPanel import org.jfree.data.xy.XYSeries import org.jfree.data.xy.XYSeriesCollection import org.jfree.chart.plot.PlotOrientation def chart = { x = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] y = [2.7, 2.8, 31.4, 38.1, 58.0, 76.2, 100.5, 130.0, 149.3, 180.0] def series = new XYSeries('plots') [x, y].transpose().each { x, y -> series.add x, y } def labels = ["Plot Demo", "X", "Y"] def data = new XYSeriesCollection(series) def options = [false, true, false] def chart = ChartFactory.createXYLineChart(*labels, data, PlotOrientation.VERTICAL, *options) new ChartPanel(chart) } new SwingBuilder().edt { frame(title:'Plot coordinate pairs', defaultCloseOperation:JFrame.EXIT_ON_CLOSE, pack:true, show:true) { widget(chart()) } }
422Plot coordinate pairs
7groovy
wubel
null
419Poker hand analyser
11kotlin
q4wx1
import java.math.BigInteger; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.List; public class PolynomialLongDivision { public static void main(String[] args) { RunDivideTest(new Polynomial(1, 3, -12, 2, -42, 0), new Polynomial(1, 1, -3, 0)); RunDivideTest(new Polynomial(5, 2, 4, 1, 1, 0), new Polynomial(2, 1, 3, 0)); RunDivideTest(new Polynomial(5, 10, 4, 7, 1, 0), new Polynomial(2, 4, 2, 2, 3, 0)); RunDivideTest(new Polynomial(2,7,-24,6,2,5,-108,4,3,3,-120,2,-126,0), new Polynomial(2, 4, 2, 2, 3, 0)); } private static void RunDivideTest(Polynomial p1, Polynomial p2) { Polynomial[] result = p1.divide(p2); System.out.printf("Compute: (%s) / (%s) =%s reminder%s%n", p1, p2, result[0], result[1]); System.out.printf("Test: (%s) * (%s) + (%s) =%s%n%n", result[0], p2, result[1], result[0].multiply(p2).add(result[1])); } private static final class Polynomial { private List<Term> polynomialTerms;
416Polynomial long division
9java
4tr58
import copy class T: def classname(self): return self.__class__.__name__ def __init__(self): self.myValue = def speak(self): print self.classname(), 'Hello', self.myValue def clone(self): return copy.copy(self) class S1(T): def speak(self): print self.classname(),, self.myValue class S2(T): def speak(self): print self.classname(),, self.myValue print a = S1() a.myValue = 'Green' a.speak() b = S2() b.myValue = 'Blue' b.speak() u = T() u.myValue = 'Purple' u.speak() print u = a.clone() u.speak() a.speak() print u.myValue = u.speak() a.speak() print u = b u.speak() b.speak() print u.myValue = u.speak() b.speak()
414Polymorphic copy
3python
3w9zc
null
417Polynomial regression
11kotlin
jyh7r
price_fraction n | n < 0 || n > 1 = error "Values must be between 0 and 1." | n < 0.06 = 0.10 | n < 0.11 = 0.18 | n < 0.16 = 0.26 | n < 0.21 = 0.32 | n < 0.26 = 0.38 | n < 0.31 = 0.44 | n < 0.36 = 0.50 | n < 0.41 = 0.54 | n < 0.46 = 0.58 | n < 0.51 = 0.62 | n < 0.56 = 0.66 | n < 0.61 = 0.70 | n < 0.66 = 0.74 | n < 0.71 = 0.78 | n < 0.76 = 0.82 | n < 0.81 = 0.86 | n < 0.86 = 0.90 | n < 0.91 = 0.94 | n < 0.96 = 0.98 | otherwise = 1.00
415Price fraction
8haskell
4t75s
import Graphics.Gnuplot.Simple pnts = [2.7, 2.8, 31.4, 38.1, 58.0, 76.2, 100.5, 130.0, 149.3, 180.0] doPlot = plotPathStyle [ ( Title "plotting dots" )] (PlotStyle Points (CustomStyle [])) (zip [0..] pnts)
422Plot coordinate pairs
8haskell
l86ch
null
419Poker hand analyser
1lua
sgxq8
function eval(a,b,c,x) return a + (b + c * x) * x end function regression(xa,ya) local n = #xa local xm = 0.0 local ym = 0.0 local x2m = 0.0 local x3m = 0.0 local x4m = 0.0 local xym = 0.0 local x2ym = 0.0 for i=1,n do xm = xm + xa[i] ym = ym + ya[i] x2m = x2m + xa[i] * xa[i] x3m = x3m + xa[i] * xa[i] * xa[i] x4m = x4m + xa[i] * xa[i] * xa[i] * xa[i] xym = xym + xa[i] * ya[i] x2ym = x2ym + xa[i] * xa[i] * ya[i] end xm = xm / n ym = ym / n x2m = x2m / n x3m = x3m / n x4m = x4m / n xym = xym / n x2ym = x2ym / n local sxx = x2m - xm * xm local sxy = xym - xm * ym local sxx2 = x3m - xm * x2m local sx2x2 = x4m - x2m * x2m local sx2y = x2ym - x2m * ym local b = (sxy * sx2x2 - sx2y * sxx2) / (sxx * sx2x2 - sxx2 * sxx2) local c = (sx2y * sxx - sxy * sxx2) / (sxx * sx2x2 - sxx2 * sxx2) local a = ym - b * xm - c * x2m print("y = "..a.." + "..b.."x + "..c.."x^2") for i=1,n do print(string.format("%2d%3d %3d", xa[i], ya[i], eval(a, b, c, xa[i]))) end end local xa = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10} local ya = {1, 6, 17, 34, 57, 86, 121, 162, 209, 262, 321} regression(xa, ya)
417Polynomial regression
1lua
hmkj8
a = b = [] class Foo(object): pass c = Foo() class Bar(object): def __init__(self, initializer = None) if initializer is not None: self.value = initializer d = Bar(10) print d.value if a is b: pass if id(a) == id(b): pass def a(fmt, *args): if fmt is None: fmt = print fmt% (args) b.append(a) del(a) b[0]()
423Pointers and references
3python
ihxof
null
416Polynomial long division
11kotlin
lovcp
class T def name end end class S def name end end obj1 = T.new obj2 = S.new puts obj1.dup.name puts obj2.dup.name
414Polymorphic copy
14ruby
yql6n
object PolymorphicCopy { def main(args: Array[String]) { val a: Animal = Dog("Rover", 3, "Terrier") val b: Animal = a.copy()
414Polymorphic copy
16scala
lo5cq
(defn divides? [k n] (zero? (mod k n)))
425Primality by trial division
6clojure
b95kz
probabilities = { => 1/5.0, => 1/6.0, => 1/7.0, => 1/8.0, => 1/9.0, => 1/10.0, => 1/11.0, } probabilities[] = 1.0 - probabilities.each_value.inject(:+) ordered_keys = probabilities.keys sum, sums = 0.0, {} ordered_keys.each do |key| sum += probabilities[key] sums[key] = sum end actual = Hash.new(0) samples = 1_000_000 samples.times do r = rand for k in ordered_keys if r < sums[k] actual[k] += 1 break end end end puts for k in ordered_keys act = Float(actual[k]) / samples val = probabilities[k] printf , k, val, act, 100*(act-val)/val end
410Probabilistic choice
14ruby
jyw7x
import java.awt.*; import java.awt.event.*; import java.awt.geom.*; import javax.swing.JApplet; import javax.swing.JFrame; public class Plot2d extends JApplet { double[] xi; double[] yi; public Plot2d(double[] x, double[] y) { this.xi = x; this.yi = y; } public static double max(double[] t) { double maximum = t[0]; for (int i = 1; i < t.length; i++) { if (t[i] > maximum) { maximum = t[i]; } } return maximum; } public static double min(double[] t) { double minimum = t[0]; for (int i = 1; i < t.length; i++) { if (t[i] < minimum) { minimum = t[i]; } } return minimum; } public void init() { setBackground(Color.white); setForeground(Color.white); } public void paint(Graphics g) { Graphics2D g2 = (Graphics2D) g; g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); g2.setPaint(Color.black); int x0 = 70; int y0 = 10; int xm = 670; int ym = 410; int xspan = xm - x0; int yspan = ym - y0; double xmax = max(xi); double xmin = min(xi); double ymax = max(yi); double ymin = min(yi); g2.draw(new double+java.sun.com&btnI=I%27m%20Feeling%20Lucky">Line2D.Double(x0, ym, xm, ym)); g2.draw(new double+java.sun.com&btnI=I%27m%20Feeling%20Lucky">Line2D.Double(x0, ym, x0, y0)); for (int j = 0; j < 5; j++) { int interv = 4; g2.drawString("" + (j * (xmax - xmin) / interv + xmin), j * xspan / interv + x0 - 10, ym + 20); g2.drawString("" + (j * (ymax - ymin) / interv + ymin), x0 - 20 - (int) (9 * Math.log10(ymax)), ym - j * yspan / interv + y0 - 5); g2.draw(new double+java.sun.com&btnI=I%27m%20Feeling%20Lucky">Line2D.Double(j * xspan / interv + x0, ym, j * xspan / interv + x0, ym + 5)); g2.draw(new double+java.sun.com&btnI=I%27m%20Feeling%20Lucky">Line2D.Double(x0 - 5, j * yspan / interv + y0, x0, j * yspan / interv + y0)); } for (int i = 0; i < xi.length; i++) { int f = (int) ((xi[i] - xmin) * xspan / (xmax - xmin)); int h = (int) (((ymax - ymin) - (yi[i] - ymin)) * yspan / (ymax - ymin)); g2.drawString("o", x0 + f - 3, h + 14); } for (int i = 0; i < xi.length - 1; i++) { int f = (int) ((xi[i] - xmin) * xspan / (xmax - xmin)); int f2 = (int) ((xi[i + 1] - xmin) * xspan / (xmax - xmin)); int h = (int) (((ymax - ymin) - (yi[i] - ymin)) * yspan / (ymax - ymin)); int h2 = (int) (((ymax - ymin) - (yi[i + 1] - ymin)) * yspan / (ymax - ymin)); g2.draw(new double+java.sun.com&btnI=I%27m%20Feeling%20Lucky">Line2D.Double(f + x0, h + y0, f2 + x0, h2 + y0)); } } public static void main(String args[]) { JFrame f = new JFrame("ShapesDemo2D"); f.addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent e) { System.exit(0); } }); double[] r = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9}; double[] t = {2.7, 2.8, 31.4, 38.1, 58.0, 76.2, 100.5, 130.0, 149.3, 180.09}; JApplet applet = new Plot2d(r, t); f.getContentPane().add("Center", applet); applet.init(); f.pack(); f.setSize(new Dimension(720, 480)); f.show(); } }
422Plot coordinate pairs
9java
3enzg
package main import "fmt" type point struct { x, y float64 } type circle struct { x, y, r float64 } type printer interface { print() } func (p *point) print() { fmt.Println(p.x, p.y) } func (c *circle) print() { fmt.Println(c.x, c.y, c.r) } func main() { var i printer
420Polymorphism
0go
a2b1f
use strict; use warnings; use utf8; use feature 'say'; use open qw<:encoding(utf-8) :std>; package Hand { sub describe { my $str = pop; my $hand = init($str); return "$str: INVALID" if !$hand; return analyze($hand); } sub init { (my $str = lc shift) =~ tr/234567891jqka//cd; return if $str !~ m/\A (?: [234567891jqka] [] ){5} \z/x; for (my ($i, $cnt) = (0, 0); $i < 10; $i += 2, $cnt = 0) { my $try = substr $str, $i, 2; ++$cnt while $str =~ m/$try/g; return if $cnt > 1; } my $suits = $str =~ tr/234567891jqka//dr; my $ranks = $str =~ tr///dr; return { hand => $str, suits => $suits, ranks => $ranks, }; } sub analyze { my $hand = shift; my @ranks = split //, $hand->{ranks}; my %cards; for (@ranks) { $_ = 10, next if $_ eq '1'; $_ = 11, next if $_ eq 'j'; $_ = 12, next if $_ eq 'q'; $_ = 13, next if $_ eq 'k'; $_ = 14, next if $_ eq 'a'; } continue { ++$cards{ $_ }; } my $kicker = 0; my (@pairs, $set, $quads, $straight, $flush); while (my ($card, $count) = each %cards) { if ($count == 1) { $kicker = $card if $kicker < $card; } elsif ($count == 2) { push @pairs, $card; } elsif ($count == 3) { $set = $card; } elsif ($count == 4) { $quads = $card; } else { die "Five of a kind? Cheater!\n"; } } $flush = 1 if $hand->{suits} =~ m/\A (.) \1 {4}/x; $straight = check_straight(@ranks); return get_high($kicker, \@pairs, $set, $quads, $straight, $flush,); } sub check_straight { my $sequence = join ' ', sort { $a <=> $b } @_; return 1 if index('2 3 4 5 6 7 8 9 10 11 12 13 14', $sequence) != -1; return 'wheel' if index('2 3 4 5 14 6 7 8 9 10 11 12 13', $sequence) == 0; return undef; } sub get_high { my ($kicker, $pairs, $set, $quads, $straight, $flush) = @_; $kicker = to_s($kicker, 's'); return 'straight-flush: Royal Flush!' if $straight && $flush && $kicker eq 'Ace' && $straight ne 'wheel'; return "straight-flush: Steel Wheel!" if $straight && $flush && $straight eq 'wheel'; return "straight-flush: $kicker high" if $straight && $flush; return 'four-of-a-kind: '. to_s($quads, 'p') if $quads; return 'full-house: '. to_s($set, 'p') .' full of '. to_s($pairs->[0], 'p') if $set && @$pairs; return "flush: $kicker high" if $flush; return 'straight: Wheel!' if $straight && $straight eq 'wheel'; return "straight: $kicker high" if $straight; return 'three-of-a-kind: '. to_s($set, 'p') if $set; return 'two-pairs: '. to_s($pairs->[0], 'p') .' and '. to_s($pairs->[1], 'p') if @$pairs == 2; return 'one-pair: '. to_s($pairs->[0], 'p') if @$pairs == 1; return "high-card: $kicker"; } my %to_str = ( 2 => 'Two', 3 => 'Three', 4 => 'Four', 5 => 'Five', 6 => 'Six', 7 => 'Seven', 8 => 'Eight', 9 => 'Nine', 10 => 'Ten', 11 => 'Jack', 12 => 'Queen', 13 => 'King', 14 => 'Ace', ); my %to_str_diffs = (2 => 'Deuces', 6 => 'Sixes',); sub to_s { my ($num, $verb) = @_; if ($verb =~ m/\A p/xi) { return $to_str_diffs{ $num } if $to_str_diffs{ $num }; return $to_str{ $num } .'s'; } return $to_str{ $num }; } } my @cards = ( '10 j q k a', '2 3 4 5 a', '2 2 2 3 2', '10 K K K 10', 'q 10 7 6 3', '5 10 7 6 4', '9 10 q k j', 'a a 3 4 5', '2 2 2 k q', '6 7 6 j j', '2 6 2 3 3', '7 7 k 3 10', '4 4 k 2 10', '2 5 j 8 9', '2 5 7 8 9', 'a a 3 4 5', ); say Hand::describe($_) for @cards;
419Poker hand analyser
2perl
vil20
class T { required init() { }
414Polymorphic copy
17swift
6xc3j
extern crate rand; use rand::distributions::{IndependentSample, Sample, Weighted, WeightedChoice}; use rand::{weak_rng, Rng}; const DATA: [(&str, f64); 8] = [ ("aleph", 1.0 / 5.0), ("beth", 1.0 / 6.0), ("gimel", 1.0 / 7.0), ("daleth", 1.0 / 8.0), ("he", 1.0 / 9.0), ("waw", 1.0 / 10.0), ("zayin", 1.0 / 11.0), ("heth", 1759.0 / 27720.0), ]; const SAMPLES: usize = 1_000_000;
410Probabilistic choice
15rust
hmxj2
object ProbabilisticChoice extends App { import scala.collection.mutable.LinkedHashMap def weightedProb[A](prob: LinkedHashMap[A,Double]): A = { require(prob.forall{case (_, p) => p > 0 && p < 1}) assume(prob.values.sum == 1) def weighted(todo: Iterator[(A,Double)], rand: Double, accum: Double = 0): A = todo.next match { case (s, i) if rand < (accum + i) => s case (_, i) => weighted(todo, rand, accum + i) } weighted(prob.toIterator, scala.util.Random.nextDouble) } def weightedFreq[A](freq: LinkedHashMap[A,Int]): A = { require(freq.forall{case (_, f) => f >= 0}) require(freq.values.sum > 0) def weighted(todo: Iterator[(A,Int)], rand: Int, accum: Int = 0): A = todo.next match { case (s, i) if rand < (accum + i) => s case (_, i) => weighted(todo, rand, accum + i) } weighted(freq.toIterator, scala.util.Random.nextInt(freq.values.sum)) }
410Probabilistic choice
16scala
pl0bj
use 5.10.0; use strict; use Heap::Priority; my $h = new Heap::Priority; $h->highest_first(); $h->add(@$_) for ["Clear drains", 3], ["Feed cat", 4], ["Make tea", 5], ["Solve RC tasks", 1], ["Tax return", 2]; say while ($_ = $h->pop);
408Priority queue
2perl
8jy0w
#!/usr/local/bin/shale aVariable var
423Pointers and references
16scala
3eizy
@Canonical @TupleConstructor(force = true) @ToString(includeNames = true) class Point { Point(Point p) { x = p.x; y = p.y } void print() { println toString() } Number x Number y } @Canonical @TupleConstructor(force = true) @ToString(includeNames = true, includeSuper = true) class Circle extends Point { Circle(Circle c) { super(c); r = c.r } void print() { println toString() } Number r }
420Polymorphism
7groovy
hyrj9
import java.util.Random; public class Main { private static float priceFraction(float f) { if (0.00f <= f && f < 0.06f) return 0.10f; else if (f < 0.11f) return 0.18f; else if (f < 0.16f) return 0.26f; else if (f < 0.21f) return 0.32f; else if (f < 0.26f) return 0.38f; else if (f < 0.31f) return 0.44f; else if (f < 0.36f) return 0.50f; else if (f < 0.41f) return 0.54f; else if (f < 0.46f) return 0.58f; else if (f < 0.51f) return 0.62f; else if (f < 0.56f) return 0.66f; else if (f < 0.61f) return 0.70f; else if (f < 0.66f) return 0.74f; else if (f < 0.71f) return 0.78f; else if (f < 0.76f) return 0.82f; else if (f < 0.81f) return 0.86f; else if (f < 0.86f) return 0.90f; else if (f < 0.91f) return 0.94f; else if (f < 0.96f) return 0.98f; else if (f < 1.01f) return 1.00f; else throw new IllegalArgumentException(); } public static void main(String[] args) { Random rnd = new Random(); for (int i = 0; i < 5; i++) { float f = rnd.nextFloat(); System.out.format("%8.6f ->%4.2f%n", f, priceFraction(f)); } } }
415Price fraction
9java
c8v9h
null
422Plot coordinate pairs
11kotlin
nksij
data Point = Point Integer Integer instance Show Point where show (Point x y) = "Point at "++(show x)++","++(show y) ponXAxis = flip Point 0 ponYAxis = Point 0 porigin = Point 0 0 data Circle = Circle Integer Integer Integer instance Show Circle where show (Circle x y r) = "Circle at "++(show x)++","++(show y)++" with radius "++(show r) conXAxis = flip Circle 0 conYAxis = Circle 0 catOrigin = Circle 0 0 c0OnXAxis = flip (flip Circle 0) 0 c0OnYAxis = flip (Circle 0) 0
420Polymorphism
8haskell
zadt0
function getScaleFactor(v) { var values = ['0.10','0.18','0.26','0.32','0.38','0.44','0.50','0.54', '0.58','0.62','0.66','0.70','0.74','0.78','0.82','0.86', '0.90','0.94','0.98','1.00']; return values[(v * 100 - 1) / 5 | 0]; }
415Price fraction
10javascript
5frur
<?php $pq = new SplPriorityQueue; $pq->insert('Clear drains', 3); $pq->insert('Feed cat', 4); $pq->insert('Make tea', 5); $pq->insert('Solve RC tasks', 1); $pq->insert('Tax return', 2); $pq->setExtractFlags(SplPriorityQueue::EXTR_BOTH); while (!$pq->isEmpty()) { print_r($pq->extract()); } ?>
408Priority queue
12php
4ta5n
use strict; use List::Util qw(min); sub poly_long_div { my ($rn, $rd) = @_; my @n = @$rn; my $gd = scalar(@$rd); if ( scalar(@n) >= $gd ) { my @q = (); while ( scalar(@n) >= $gd ) { my $piv = $n[0]/$rd->[0]; push @q, $piv; $n[$_] -= $rd->[$_] * $piv foreach ( 0 .. min(scalar(@n), $gd)-1 ); shift @n; } return ( \@q, \@n ); } else { return ( [0], $rn ); } }
416Polynomial long division
2perl
qg0x6
package main import ( "fmt" "math/big" ) var ( ZERO = big.NewInt(0) ONE = big.NewInt(1) ) func Primes(n *big.Int) []*big.Int { res := []*big.Int{} mod, div := new(big.Int), new(big.Int) for i := big.NewInt(2); i.Cmp(n) != 1; { div.DivMod(n, i, mod) for mod.Cmp(ZERO) == 0 { res = append(res, new(big.Int).Set(i)) n.Set(div) div.DivMod(n, i, mod) } i.Add(i, ONE) } return res } func main() { vals := []int64{ 1 << 31, 1234567, 333333, 987653, 2 * 3 * 5 * 7 * 11 * 13 * 17, } for _, v := range vals { fmt.Println(v, "->", Primes(big.NewInt(v))) } }
418Prime decomposition
0go
srsqa
w_width = love.graphics.getWidth() w_height = love.graphics.getHeight() x = {0,1,2,3,4,5,6,7,8,9} y = {2.7, 2.8, 31.4, 38.1, 58.0, 76.2, 100.5, 130.0, 149.3, 180.0} origin = {24,24} points = {} x_unit = w_width/x[10]/2 y_unit = w_height/10
422Plot coordinate pairs
1lua
db0nq
class Point { protected int x, y; public Point() { this(0); } public Point(int x) { this(x, 0); } public Point(int x, int y) { this.x = x; this.y = y; } public Point(Point p) { this(p.x, p.y); } public int getX() { return this.x; } public int getY() { return this.y; } public void setX(int x) { this.x = x; } public void setY(int y) { this.y = y; } public void print() { System.out.println("Point x: " + this.x + " y: " + this.y); } } class Circle extends Point { private int r; public Circle(Point p) { this(p, 0); } public Circle(Point p, int r) { super(p); this.r = r; } public Circle() { this(0); } public Circle(int x) { this(x, 0); } public Circle(int x, int y) { this(x, y, 0); } public Circle(int x, int y, int r) { super(x, y); this.r = r; } public Circle(Circle c) { this(c.x, c.y, c.r); } public int getR() { return this.r; } public void setR(int r) { this.r = r; } public void print() { System.out.println("Circle x: " + this.x + " y: " + this.y + " r: " + this.r); } } public class test { public static void main(String args[]) { Point p = new Point(); Point c = new Circle(); p.print(); c.print(); } }
420Polymorphism
9java
ojs8d
from collections import namedtuple class Card(namedtuple('Card', 'face, suit')): def __repr__(self): return ''.join(self) suit = ' '.split() faces = '2 3 4 5 6 7 8 9 10 j q k a' lowaces = 'a 2 3 4 5 6 7 8 9 10 j q k' face = faces.split() lowace = lowaces.split() def straightflush(hand): f,fs = ( (lowace, lowaces) if any(card.face == '2' for card in hand) else (face, faces) ) ordered = sorted(hand, key=lambda card: (f.index(card.face), card.suit)) first, rest = ordered[0], ordered[1:] if ( all(card.suit == first.suit for card in rest) and ' '.join(card.face for card in ordered) in fs ): return 'straight-flush', ordered[-1].face return False def fourofakind(hand): allfaces = [f for f,s in hand] allftypes = set(allfaces) if len(allftypes) != 2: return False for f in allftypes: if allfaces.count(f) == 4: allftypes.remove(f) return 'four-of-a-kind', [f, allftypes.pop()] else: return False def fullhouse(hand): allfaces = [f for f,s in hand] allftypes = set(allfaces) if len(allftypes) != 2: return False for f in allftypes: if allfaces.count(f) == 3: allftypes.remove(f) return 'full-house', [f, allftypes.pop()] else: return False def flush(hand): allstypes = {s for f, s in hand} if len(allstypes) == 1: allfaces = [f for f,s in hand] return 'flush', sorted(allfaces, key=lambda f: face.index(f), reverse=True) return False def straight(hand): f,fs = ( (lowace, lowaces) if any(card.face == '2' for card in hand) else (face, faces) ) ordered = sorted(hand, key=lambda card: (f.index(card.face), card.suit)) first, rest = ordered[0], ordered[1:] if ' '.join(card.face for card in ordered) in fs: return 'straight', ordered[-1].face return False def threeofakind(hand): allfaces = [f for f,s in hand] allftypes = set(allfaces) if len(allftypes) <= 2: return False for f in allftypes: if allfaces.count(f) == 3: allftypes.remove(f) return ('three-of-a-kind', [f] + sorted(allftypes, key=lambda f: face.index(f), reverse=True)) else: return False def twopair(hand): allfaces = [f for f,s in hand] allftypes = set(allfaces) pairs = [f for f in allftypes if allfaces.count(f) == 2] if len(pairs) != 2: return False p0, p1 = pairs other = [(allftypes - set(pairs)).pop()] return 'two-pair', pairs + other if face.index(p0) > face.index(p1) else pairs[::-1] + other def onepair(hand): allfaces = [f for f,s in hand] allftypes = set(allfaces) pairs = [f for f in allftypes if allfaces.count(f) == 2] if len(pairs) != 1: return False allftypes.remove(pairs[0]) return 'one-pair', pairs + sorted(allftypes, key=lambda f: face.index(f), reverse=True) def highcard(hand): allfaces = [f for f,s in hand] return 'high-card', sorted(allfaces, key=lambda f: face.index(f), reverse=True) handrankorder = (straightflush, fourofakind, fullhouse, flush, straight, threeofakind, twopair, onepair, highcard) def rank(cards): hand = handy(cards) for ranker in handrankorder: rank = ranker(hand) if rank: break assert rank, % cards return rank def handy(cards='2 2 2 k q'): hand = [] for card in cards.split(): f, s = card[:-1], card[-1] assert f in face, % f assert s in suit, % s hand.append(Card(f, s)) assert len(hand) == 5, % len(hand) assert len(set(hand)) == 5, % cards return hand if __name__ == '__main__': hands = [, , , , , , ] + [ , , ] print(% (, , )) for cards in hands: r = rank(cards) print(% (cards, r[0], r[1]))
419Poker hand analyser
3python
un2vd
package main import ( "fmt" "strconv" "strings" )
421Power set
0go
ojq8q
null
415Price fraction
11kotlin
3wmz5
def factorize = { long target -> if (target == 1) return [1L] if (target < 4) return [1L, target] def targetSqrt = Math.sqrt(target) def lowfactors = (2L..targetSqrt).findAll { (target % it) == 0 } if (lowfactors == []) return [1L, target] def nhalf = lowfactors.size() - ((lowfactors[-1]**2 == target) ? 1: 0) [1] + lowfactors + (0..<nhalf).collect { target.intdiv(lowfactors[it]) }.reverse() + [target] } def decomposePrimes = { target -> def factors = factorize(target) - [1] def primeFactors = [] factors.eachWithIndex { f, i -> if (i==0 || factors[0..<i].every {f % it != 0}) { primeFactors << f def pfPower = f*f while (target % pfPower == 0) { primeFactors << f pfPower *= f } } } primeFactors }
418Prime decomposition
7groovy
ava1p
function Point() { var arg1 = arguments[0]; var arg2 = arguments[1]; if (arg1 instanceof Point) { this.x = arg1.x; this.y = arg1.y; } else { this.x = arg1 == null ? 0 : arg1; this.y = arg2 == null ? 0 : arg1; } this.set_x = function(_x) {this.x = _x;} this.set_y = function(_y) {this.y = _y;} } Point.prototype.print = function() { var out = "Point(" + this.x + "," + this.y + ")"; print(out); } function Circle() { var arg1 = arguments[0]; var arg2 = arguments[1]; var arg3 = arguments[2]; if (arg1 instanceof Circle) { this.x = arg1.x; this.y = arg1.y; this.r = arg1.r; } else if (arg1 instanceof Point) { this.x = arg1.x; this.y = arg1.y; this.r = arg2 == null ? 0 : arg2; } else { this.x = arg1 == null ? 0 : arg1; this.y = arg2 == null ? 0 : arg2; this.r = arg3 == null ? 0 : arg3; } this.set_x = function(_x) {this.x = _x;} this.set_y = function(_y) {this.y = _y;} this.set_r = function(_r) {this.r = _r;} } Circle.prototype.print = function() { var out = "Circle(" + this.x + "," + this.y + "," + this.r + ")"; print(out); }
420Polymorphism
10javascript
t1nfm
from itertools import izip def degree(poly): while poly and poly[-1] == 0: poly.pop() return len(poly)-1 def poly_div(N, D): dD = degree(D) dN = degree(N) if dD < 0: raise ZeroDivisionError if dN >= dD: q = [0] * dN while dN >= dD: d = [0]*(dN - dD) + D mult = q[dN - dD] = N[-1] / float(d[-1]) d = [coeff*mult for coeff in d] N = [coeffN - coeffd for coeffN, coeffd in izip(N, d)] dN = degree(N) r = N else: q = [0] r = N return q, r if __name__ == '__main__': print N = [-42, 0, -12, 1] D = [-3, 1, 0, 0] print % (N,D), print % poly_div(N, D)
416Polynomial long division
3python
sr8q9
def powerSetRec(head, tail) { if (!tail) return [head] powerSetRec(head, tail.tail()) + powerSetRec(head + [tail.head()], tail.tail()) } def powerSet(set) { powerSetRec([], set as List) as Set}
421Power set
7groovy
x51wl
use ntheory qw/divisors/; sub proper_divisors { my $n = shift; return 1 if $n == 0; my @d = divisors($n); pop @d; @d; } say "$_: ", join " ", proper_divisors($_) for 1..10; my($max,$ind) = (0,0); for (1..20000) { my $nd = scalar proper_divisors($_); ($max,$ind) = ($nd,$_) if $nd > $max; } say "$max $ind"; { use List::Util qw/max/; no warnings 'numeric'; say max(map { scalar(proper_divisors($_)) . " $_" } 1..20000); }
411Proper divisors
2perl
r31gd
factorize n = [ d | p <- [2..n], isPrime p, d <- divs n p ] where divs n p | rem n p == 0 = p: divs (quot n p) p | otherwise = []
418Prime decomposition
8haskell
909mo
polylongdiv <- function(n,d) { gd <- length(d) pv <- vector("numeric", length(n)) pv[1:gd] <- d if ( length(n) >= gd ) { q <- c() while ( length(n) >= gd ) { q <- c(q, n[1]/pv[1]) n <- n - pv * (n[1]/pv[1]) n <- n[2:length(n)] pv <- pv[1:(length(pv)-1)] } list(q=q, r=n) } else { list(q=c(0), r=n) } } print.polynomial <- function(p) { i <- length(p)-1 for(a in p) { if ( i == 0 ) { cat(a, "\n") } else { cat(a, "x^", i, " + ", sep="") } i <- i - 1 } } r <- polylongdiv(c(1,-12,0,-42), c(1,-3)) print.polynomial(r$q) print.polynomial(r$r)
416Polynomial long division
13r
euxad
import Data.Set import Control.Monad powerset :: Ord a => Set a -> Set (Set a) powerset = fromList . fmap fromList . listPowerset . toList listPowerset :: [a] -> [[a]] listPowerset = filterM (const [True, False])
421Power set
8haskell
2omll
null
420Polymorphism
11kotlin
x5aws
use strict; use warnings; use Statistics::Regression; my @x = <0 1 2 3 4 5 6 7 8 9 10>; my @y = <1 6 17 34 57 86 121 162 209 262 321>; my @model = ('const', 'X', 'X**2'); my $reg = Statistics::Regression->new( '', [@model] ); $reg->include( $y[$_], [ 1.0, $x[$_], $x[$_]**2 ]) for 0..@y-1; my @coeff = $reg->theta(); printf "%-6s%8.3f\n", $model[$_], $coeff[$_] for 0..@model-1;
417Polynomial regression
2perl
tazfg
scaleTable = { {0.06, 0.10}, {0.11, 0.18}, {0.16, 0.26}, {0.21, 0.32}, {0.26, 0.38}, {0.31, 0.44}, {0.36, 0.50}, {0.41, 0.54}, {0.46, 0.58}, {0.51, 0.62}, {0.56, 0.66}, {0.61, 0.70}, {0.66, 0.74}, {0.71, 0.78}, {0.76, 0.82}, {0.81, 0.86}, {0.86, 0.90}, {0.91, 0.94}, {0.96, 0.98}, {1.01, 1.00} } function rescale (price) if price < 0 or price > 1 then return "Out of range!" end for k, v in pairs(scaleTable) do if price < v[1] then return v[2] end end end math.randomseed(os.time()) for i = 1, 5 do rnd = math.random() print("Random value:", rnd) print("Adjusted price:", rescale(rnd)) print() end
415Price fraction
1lua
6x939
<?php function ProperDivisors($n) { yield 1; $large_divisors = []; for ($i = 2; $i <= sqrt($n); $i++) { if ($n % $i == 0) { yield $i; if ($i*$i != $n) { $large_divisors[] = $n / $i; } } } foreach (array_reverse($large_divisors) as $i) { yield $i; } } assert([1, 2, 4, 5, 10, 20, 25, 50] == iterator_to_array(ProperDivisors(100))); foreach (range(1, 10) as $n) { echo ; foreach (ProperDivisors($n) as $divisor) { echo ; } echo ; } $divisorsCount = []; for ($i = 1; $i < 20000; $i++) { $divisorsCount[sizeof(iterator_to_array(ProperDivisors($i)))][] = $i; } ksort($divisorsCount); echo , implode(, end($divisorsCount)), ; echo , key($divisorsCount), ;
411Proper divisors
12php
dpmn8
>>> import queue >>> pq = queue.PriorityQueue() >>> for item in ((3, ), (4, ), (5, ), (1, ), (2, )): pq.put(item) >>> while not pq.empty(): print(pq.get_nowait()) (1, 'Solve RC tasks') (2, 'Tax return') (3, 'Clear drains') (4, 'Feed cat') (5, 'Make tea') >>>
408Priority queue
3python
ohm81
null
420Polymorphism
1lua
q4ex0
class Card include Comparable attr_accessor :ordinal attr_reader :suit, :face SUITS = %i( ) FACES = %i(2 3 4 5 6 7 8 9 10 j q k a) def initialize(str) @face, @suit = parse(str) @ordinal = FACES.index(@face) end def <=> (other) self.ordinal <=> other.ordinal end def to_s end private def parse(str) face, suit = str.chop.to_sym, str[-1].to_sym raise ArgumentError, unless FACES.include?(face) && SUITS.include?(suit) [face, suit] end end class Hand include Comparable attr_reader :cards, :rank RANKS = %i(high-card one-pair two-pair three-of-a-kind straight flush full-house four-of-a-kind straight-flush five-of-a-kind) WHEEL_FACES = %i(2 3 4 5 a) def initialize(str_of_cards) @cards = str_of_cards.downcase.tr(',',' ').split.map{|str| Card.new(str)} grouped = @cards.group_by(&:face).values @face_pattern = grouped.map(&:size).sort @rank = categorize @rank_num = RANKS.index(@rank) @tiebreaker = grouped.map{|ar| [ar.size, ar.first.ordinal]}.sort.reverse end def <=> (other) self.compare_value <=> other.compare_value end def to_s @cards.map(&:to_s).join() end protected def compare_value [@rank_num, @tiebreaker] end private def one_suit? @cards.map(&:suit).uniq.size == 1 end def consecutive? sort.each_cons(2).all? {|c1,c2| c2.ordinal - c1.ordinal == 1 } end def sort if @cards.sort.map(&:face) == WHEEL_FACES @cards.detect {|c| c.face == :a}.ordinal = -1 end @cards.sort end def categorize if consecutive? one_suit??:'straight-flush': :straight elsif one_suit? :flush else case @face_pattern when [1,1,1,1,1] then:'high-card' when [1,1,1,2] then:'one-pair' when [1,2,2] then:'two-pair' when [1,1,3] then:'three-of-a-kind' when [2,3] then:'full-house' when [1,4] then:'four-of-a-kind' when [5] then:'five-of-a-kind' end end end end test_hands = <<EOS 2 2 2 k q 2 5 7 8 9 a 2 3 4 5 2 3 2 3 3 2 7 2 3 3 2 6 2 3 3 10 j q k a 4 4 k 2 10 4 4 k 3 10 q 10 7 6 4 q 10 7 6 3 9 10 q k j 2 3 4 5 a 2 2 2 3 3 EOS hands = test_hands.each_line.map{|line| Hand.new(line) } puts hands.sort.reverse.each{|hand| puts } puts str = <<EOS joker 2 2 k q joker 5 7 8 9 joker 2 3 4 5 joker 3 2 3 3 joker 7 2 3 3 joker 7 7 7 7 joker j q k A joker 4 k 5 10 joker k 7 6 4 joker 2 joker 4 5 joker Q joker A 10 joker Q joker A 10 joker 2 2 joker q EOS DECK = Card::FACES.product(Card::SUITS).map(&:join) str.each_line do |line| cards_in_arrays = line.split.map{|c| c == ? DECK.dup: [c]} all_tries = cards_in_arrays.shift.product(*cards_in_arrays).map{|ar| Hand.new(ar.join)} best = all_tries.max puts end
419Poker hand analyser
14ruby
4fu5p
public boolean prime(BigInteger i);
418Prime decomposition
9java
tatf9
fn main() { let hands = vec![ " ", " ", " ", " ", " ", " ", " ", " ", " ", " ", " ", " ", " ", " ", " ", " ", ]; for hand in hands{ println!("{} {}", hand, poker_hand(hand)); } } fn poker_hand(cards: &str) -> &str { let mut suits = vec![0u8; 4]; let mut faces = vec![0u8; 15]; let mut hand = vec![]; for card in cards.chars(){ if card == ' ' { continue; } let values = get_card_value(card); if values.0 < 14 && hand.contains(&values) { return "invalid"; } hand.push(values); faces[values.0 as usize]+=1; if values.1 >= 0 { suits[values.1 as usize]+=1; } } if hand.len()!=5 { return "invalid"; } faces[13] = faces[0];
419Poker hand analyser
15rust
gt54o
public static ArrayList<String> getpowerset(int a[],int n,ArrayList<String> ps) { if(n<0) { return null; } if(n==0) { if(ps==null) ps=new ArrayList<String>(); ps.add(" "); return ps; } ps=getpowerset(a, n-1, ps); ArrayList<String> tmp=new ArrayList<String>(); for(String s:ps) { if(s.equals(" ")) tmp.add(""+a[n-1]); else tmp.add(s+a[n-1]); } ps.addAll(tmp); return ps; }
421Power set
9java
6wf3z
PriorityQueue <- function() { keys <- values <- NULL insert <- function(key, value) { ord <- findInterval(key, keys) keys <<- append(keys, key, ord) values <<- append(values, value, ord) } pop <- function() { head <- list(key=keys[1],value=values[[1]]) values <<- values[-1] keys <<- keys[-1] return(head) } empty <- function() length(keys) == 0 environment() } pq <- PriorityQueue() pq$insert(3, "Clear drains") pq$insert(4, "Feed cat") pq$insert(5, "Make tea") pq$insert(1, "Solve RC tasks") pq$insert(2, "Tax return") while(!pq$empty()) { with(pq$pop(), cat(key,":",value,"\n")) }
408Priority queue
13r
qgzxs
function run_factorize(input, output) { var n = new BigInteger(input.value, 10); var TWO = new BigInteger("2", 10); var divisor = new BigInteger("3", 10); var prod = false; if (n.compareTo(TWO) < 0) return; output.value = ""; while (true) { var qr = n.divideAndRemainder(TWO); if (qr[1].equals(BigInteger.ZERO)) { if (prod) output.value += "*"; else prod = true; output.value += "2"; n = qr[0]; } else break; } while (!n.equals(BigInteger.ONE)) { var qr = n.divideAndRemainder(divisor); if (qr[1].equals(BigInteger.ZERO)) { if (prod) output.value += "*"; else prod = true; output.value += divisor; n = qr[0]; } else divisor = divisor.add(TWO); } }
418Prime decomposition
10javascript
msmyv
val faces = "23456789TJQKA" val suits = "CHSD" sealed trait Card object Joker extends Card case class RealCard(face: Int, suit: Char) extends Card val allRealCards = for { face <- 0 until faces.size suit <- suits } yield RealCard(face, suit) def parseCard(str: String): Card = { if (str == "joker") { Joker } else { RealCard(faces.indexOf(str(0)), str(1)) } } def parseHand(str: String): List[Card] = { str.split(" ").map(parseCard).toList } trait HandType { def name: String def check(hand: List[RealCard]): Boolean } case class And(x: HandType, y: HandType, name: String) extends HandType { def check(hand: List[RealCard]) = x.check(hand) && y.check(hand) } object Straight extends HandType { val name = "straight" def check(hand: List[RealCard]): Boolean = { val faces = hand.map(_.face).toSet faces.size == 5 && (faces.min == faces.max - 4 || faces == Set(0, 1, 2, 3, 12)) } } object Flush extends HandType { val name = "flush" def check(hand: List[RealCard]): Boolean = { hand.map(_.suit).toSet.size == 1 } } case class NOfAKind(n: Int, name: String = "", nOccur: Int = 1) extends HandType { def check(hand: List[RealCard]): Boolean = { hand.groupBy(_.face).values.count(_.size == n) >= nOccur } } val allHandTypes = List( NOfAKind(5, "five-of-a-kind"), And(Straight, Flush, "straight-flush"), NOfAKind(4, "four-of-a-kind"), And(NOfAKind(3), NOfAKind(2), "full-house"), Flush, Straight, NOfAKind(3, "three-of-a-kind"), NOfAKind(2, "two-pair", 2), NOfAKind(2, "one-pair") ) def possibleRealHands(hand: List[Card]): List[List[RealCard]] = { val realCards = hand.collect { case r: RealCard => r } val nJokers = hand.count(_ == Joker) allRealCards.toList.combinations(nJokers).map(_ ++ realCards).toList } def analyzeHand(hand: List[Card]): String = { val possibleHands = possibleRealHands(hand) allHandTypes.find(t => possibleHands.exists(t.check)).map(_.name).getOrElse("high-card") }
419Poker hand analyser
16scala
j6r7i
def polynomial_long_division(numerator, denominator) dd = degree(denominator) raise ArgumentError, if dd < 0 if dd == 0 return [multiply(numerator, 1.0/denominator[0]), [0]*numerator.length] end q = [0] * numerator.length while (dn = degree(numerator)) >= dd d = shift_right(denominator, dn - dd) q[dn-dd] = numerator[dn] / d[degree(d)] d = multiply(d, q[dn-dd]) numerator = subtract(numerator, d) end [q, numerator] end def degree(ary) idx = ary.rindex(&:nonzero?) idx? idx: -1 end def shift_right(ary, n) [0]*n + ary[0, ary.length - n] end def subtract(a1, a2) a1.zip(a2).collect {|v1,v2| v1 - v2} end def multiply(ary, num) ary.collect {|x| x * num} end f = [-42, 0, -12, 1] g = [-3, 1, 0, 0] q, r = polynomial_long_division(f, g) puts g = [-3, 1, 1, 0] q, r = polynomial_long_division(f, g) puts
416Polynomial long division
14ruby
8ji01
>>> x = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10] >>> y = [1, 6, 17, 34, 57, 86, 121, 162, 209, 262, 321] >>> coeffs = numpy.polyfit(x,y,deg=2) >>> coeffs array([ 3., 2., 1.])
417Polynomial regression
3python
ze3tt
function powerset(ary) { var ps = [[]]; for (var i=0; i < ary.length; i++) { for (var j = 0, len = ps.length; j < len; j++) { ps.push(ps[j].concat(ary[i])); } } return ps; } var res = powerset([1,2,3,4]); load('json2.js'); print(JSON.stringify(res));
421Power set
10javascript
l8ycf
use GD::Graph::points; @data = ( [0, 1, 2, 3, 4, 5, 6, 7, 8, 9], [2.7, 2.8, 31.4, 38.1, 58.0, 76.2, 100.5, 130.0, 149.3, 180.0], ); $graph = GD::Graph::points->new(400, 300); open my $fh, '>', "qsort-range-10-9.png"; binmode $fh; print $fh $graph->plot(\@data)->png; close $fh;
422Plot coordinate pairs
2perl
73urh
package main import ( "fmt" "math/bits" ) func main() { fmt.Println("Pop counts, powers of 3:") n := uint64(1)
424Population count
0go
b94kh
x <- c(0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10) y <- c(1, 6, 17, 34, 57, 86, 121, 162, 209, 262, 321) coef(lm(y ~ x + I(x^2)))
417Polynomial regression
13r
nbdi2
import Data.Bits (popCount) printPops :: (Show a, Integral a) => String -> [a] -> IO () printPops title counts = putStrLn $ title ++ show (take 30 counts) main :: IO () main = do printPops "popcount " $ map popCount $ iterate (*3) (1 :: Integer) printPops "evil " $ filter (even . popCount) ([0..] :: [Integer]) printPops "odious " $ filter ( odd . popCount) ([0..] :: [Integer])
424Population count
8haskell
dbqn4
null
418Prime decomposition
11kotlin
oho8z
class PriorityQueueNaive def initialize(data=nil) @q = Hash.new {|h, k| h[k] = []} data.each {|priority, item| @q[priority] << item} if data @priorities = @q.keys.sort end def push(priority, item) @q[priority] << item @priorities = @q.keys.sort end def pop p = @priorities[0] item = @q[p].shift if @q[p].empty? @q.delete(p) @priorities.shift end item end def peek unless empty? @q[@priorities[0]][0] end end def empty? @priorities.empty? end def each @q.each do |priority, items| items.each {|item| yield priority, item} end end def dup @q.each_with_object(self.class.new) do |(priority, items), obj| items.each {|item| obj.push(priority, item)} end end def merge(other) raise TypeError unless self.class == other.class pq = dup other.each {|priority, item| pq.push(priority, item)} pq end def inspect @q.inspect end end test = [ [6, ], [3, ], [4, ], [5, ], [6, ], [1, ], [2, ], ] pq = PriorityQueueNaive.new test.each {|pr, str| pq.push(pr, str) } until pq.empty? puts pq.pop end puts test2 = test.shift(3) p pq1 = PriorityQueueNaive.new(test) p pq2 = PriorityQueueNaive.new(test2) p pq3 = pq1.merge(pq2) puts until pq3.empty? puts pq3.pop end puts
408Priority queue
14ruby
nbcit
protocol Dividable { static func / (lhs: Self, rhs: Self) -> Self } extension Int: Dividable { } struct Solution<T> { var quotient: [T] var remainder: [T] } func polyDegree<T: SignedNumeric>(_ p: [T]) -> Int { for i in stride(from: p.count - 1, through: 0, by: -1) where p[i]!= 0 { return i } return Int.min } func polyShiftRight<T: SignedNumeric>(p: [T], places: Int) -> [T] { guard places > 0 else { return p } let deg = polyDegree(p) assert(deg + places < p.count, "Number of places to shift too large") var res = p for i in stride(from: deg, through: 0, by: -1) { res[i + places] = res[i] res[i] = 0 } return res } func polyMul<T: SignedNumeric>(_ p: inout [T], by: T) { for i in 0..<p.count { p[i] *= by } } func polySub<T: SignedNumeric>(_ p: inout [T], by: [T]) { for i in 0..<p.count { p[i] -= by[i] } } func polyLongDiv<T: SignedNumeric & Dividable>(numerator n: [T], denominator d: [T]) -> Solution<T>? { guard n.count == d.count else { return nil } var nDeg = polyDegree(n) let dDeg = polyDegree(d) guard dDeg >= 0, nDeg >= dDeg else { return nil } var n2 = n var quo = [T](repeating: 0, count: n.count) while nDeg >= dDeg { let i = nDeg - dDeg var d2 = polyShiftRight(p: d, places: i) quo[i] = n2[nDeg] / d2[nDeg] polyMul(&d2, by: quo[i]) polySub(&n2, by: d2) nDeg = polyDegree(n2) } return Solution(quotient: quo, remainder: n2) } func polyPrint<T: SignedNumeric & Comparable>(_ p: [T]) { let deg = polyDegree(p) for i in stride(from: deg, through: 0, by: -1) where p[i]!= 0 { let coeff = p[i] switch coeff { case 1 where i < deg: print(" + ", terminator: "") case 1: print("", terminator: "") case -1 where i < deg: print(" - ", terminator: "") case -1: print("-", terminator: "") case _ where coeff < 0 && i < deg: print(" - \(-coeff)", terminator: "") case _ where i < deg: print(" + \(coeff)", terminator: "") case _: print("\(coeff)", terminator: "") } if i > 1 { print("x^\(i)", terminator: "") } else if i == 1 { print("x", terminator: "") } } print() } let n = [-42, 0, -12, 1] let d = [-3, 1, 0, 0] print("Numerator: ", terminator: "") polyPrint(n) print("Denominator: ", terminator: "") polyPrint(d) guard let sol = polyLongDiv(numerator: n, denominator: d) else { fatalError() } print("----------") print("Quotient: ", terminator: "") polyPrint(sol.quotient) print("Remainder: ", terminator: "") polyPrint(sol.remainder)
416Polynomial long division
17swift
07os6