code
stringlengths
1
46.1k
label
class label
1.18k classes
domain_label
class label
21 classes
index
stringlengths
4
5
null
797Functional coverage tree
1lua
wzoea
fizz :: (Integral a, Show a) => a -> [(a, String)] -> String fizz a xs | null result = show a | otherwise = result where result = concatMap (fizz' a) xs fizz' a (factor, str) | a `mod` factor == 0 = str | otherwise = "" main = do line <- getLine let n = read line contents <- getContents let multiples = map (convert . words) $ lines contents mapM_ (\ x -> putStrLn $ fizz x multiples) [1..n] where convert [x, y] = (read x, y)
791General FizzBuzz
8haskell
mjjyf
int main(void) { netbuf *nbuf; FtpInit(); FtpConnect(, &nbuf); FtpLogin(, , nbuf); FtpOptions(FTPLIB_CONNMODE, FTPLIB_PASSIVE, nbuf); FtpChdir(, nbuf); FtpDir((void*)0, , nbuf); FtpGet(, , FTPLIB_ASCII, nbuf); FtpQuit(nbuf); return 0; }
800FTP
5c
fu3d3
add :: Int -> Int -> Int add x y = x+y
795Function prototype
8haskell
y7566
use strict; use warnings; sub walktree { my @parts; while( $_[0] =~ /(?<head> (\s*) \N+\n ) (?<body> (?:\2 \s\N+\n)*)/gx ) { my($head, $body) = ($+{head}, $+{body}); $head =~ /^.*? \| (\S*) \s* \| (\S*) /x; my $weight = sprintf '%-8s', $1 || 1; my $coverage = sprintf '%-10s', $2 || 0; my($w, $wsum) = (0, 0); $head .= $_->[0], $w += $_->[1], $wsum += $_->[1] * $_->[2] for walktree( $body ); $coverage = sprintf '%-10.2g', $wsum/$w unless $w == 0; push @parts, [ $head =~ s/\|.*/|$weight|$coverage|/r, $weight, $coverage ]; } return @parts; } print $_->[0] for walktree( join '', <DATA> ); __DATA__ NAME_HIERARCHY |WEIGHT |COVERAGE | cleaning | | | house1 |40 | | bedrooms | |0.25 | bathrooms | | | bathroom1 | |0.5 | bathroom2 | | | outside_lavatory | |1 | attic | |0.75 | kitchen | |0.1 | living_rooms | | | lounge | | | dining_room | | | conservatory | | | playroom | |1 | basement | | | garage | | | garden | |0.8 | house2 |60 | | upstairs | | | bedrooms | | | suite_1 | | | suite_2 | | | bedroom_3 | | | bedroom_4 | | | bathroom | | | toilet | | | attics | |0.6 | groundfloor | | | kitchen | | | living_rooms | | | lounge | | | dining_room | | | conservatory | | | playroom | | | wet_room_&_toilet | | | garage | | | garden | |0.9 | hot_tub_suite | |1 | basement | | | cellars | |1 | wine_cellar | |1 | cinema | |0.75 |
797Functional coverage tree
2perl
ck49a
null
792Gauss-Jordan matrix inversion
11kotlin
9hjmh
public class FizzBuzz { public static void main(String[] args) { Sound[] sounds = {new Sound(3, "Fizz"), new Sound(5, "Buzz"), new Sound(7, "Baxx")}; for (int i = 1; i <= 20; i++) { StringBuilder sb = new StringBuilder(); for (Sound sound : sounds) { sb.append(sound.generate(i)); } System.out.println(sb.length() == 0 ? i : sb.toString()); } } private static class Sound { private final int trigger; private final String onomatopoeia; public Sound(int trigger, String onomatopoeia) { this.trigger = trigger; this.onomatopoeia = onomatopoeia; } public String generate(int i) { return i % trigger == 0 ? onomatopoeia : ""; } } }
791General FizzBuzz
9java
fuudv
null
788Generator/Exponential
11kotlin
7sor4
null
795Function prototype
10javascript
6ru38
package main import ( "fmt" "math/rand" "time" ) const boxW = 41
798Galton box animation
0go
x3owf
function fizz(d, e) { return function b(a) { return a ? b(a - 1).concat(a) : []; }(e).reduce(function (b, a) { return b + (d.reduce(function (b, c) { return b + (a % c[0] ? "" : c[1]); }, "") || a.toString()) + "\n"; }, ""); }
791General FizzBuzz
10javascript
y776r
>>> from itertools import permutations >>> pieces = 'KQRrBbNN' >>> starts = {''.join(p).upper() for p in permutations(pieces) if p.index('B')% 2 != p.index('b')% 2 and ( p.index('r') < p.index('K') < p.index('R') or p.index('R') < p.index('K') < p.index('r') ) } >>> len(starts) 960 >>> starts.pop() 'QNBRNKRB' >>>
790Generate Chess960 starting position
3python
mjhyh
null
795Function prototype
11kotlin
0mzsf
from itertools import zip_longest fc2 = '''\ cleaning,, house1,40, bedrooms,,.25 bathrooms,, bathroom1,,.5 bathroom2,, outside_lavatory,,1 attic,,.75 kitchen,,.1 living_rooms,, lounge,, dining_room,, conservatory,, playroom,,1 basement,, garage,, garden,,.8 house2,60, upstairs,, bedrooms,, suite_1,, suite_2,, bedroom_3,, bedroom_4,, bathroom,, toilet,, attics,,.6 groundfloor,, kitchen,, living_rooms,, lounge,, dining_room,, conservatory,, playroom,, wet_room_&_toilet,, garage,, garden,,.9 hot_tub_suite,,1 basement,, cellars,,1 wine_cellar,,1 cinema,,.75 ''' NAME, WT, COV = 0, 1, 2 def right_type(txt): try: return float(txt) except ValueError: return txt def commas_to_list(the_list, lines, start_indent=0): ''' Output format is a nest of lists and tuples lists are for coverage leaves without children items in the list are name, weight, coverage tuples are 2-tuples for nodes with children. The first element is a list representing the name, weight, coverage of the node (some to be calculated); the second element is a list of child elements which may be 2-tuples or lists as above. the_list is modified in-place lines must be a generator of successive lines of input like fc2 ''' for n, line in lines: indent = 0 while line.startswith(' ' * (4 * indent)): indent += 1 indent -= 1 fields = [right_type(f) for f in line.strip().split(',')] if indent == start_indent: the_list.append(fields) elif indent > start_indent: lst = [fields] sub = commas_to_list(lst, lines, indent) the_list[-1] = (the_list[-1], lst) if sub not in (None, ['']): the_list.append(sub) else: return fields if fields else None return None def pptreefields(lst, indent=0, widths=['%-32s', '%-8g', '%-10g']): ''' Pretty prints the format described from function commas_to_list as a table with names in the first column suitably indented and all columns having a fixed minimum column width. ''' lhs = ' ' * (4 * indent) for item in lst: if type(item) != tuple: name, *rest = item print(widths[0]% (lhs + name), end='|') for width, item in zip_longest(widths[1:len(rest)], rest, fillvalue=widths[-1]): if type(item) == str: width = width[:-1] + 's' print(width% item, end='|') print() else: item, children = item name, *rest = item print(widths[0]% (lhs + name), end='|') for width, item in zip_longest(widths[1:len(rest)], rest, fillvalue=widths[-1]): if type(item) == str: width = width[:-1] + 's' print(width% item, end='|') print() pptreefields(children, indent+1) def default_field(node_list): node_list[WT] = node_list[WT] if node_list[WT] else 1.0 node_list[COV] = node_list[COV] if node_list[COV] else 0.0 def depth_first(tree, visitor=default_field): for item in tree: if type(item) == tuple: item, children = item depth_first(children, visitor) visitor(item) def covercalc(tree): ''' Depth first weighted average of coverage ''' sum_covwt, sum_wt = 0, 0 for item in tree: if type(item) == tuple: item, children = item item[COV] = covercalc(children) sum_wt += item[WT] sum_covwt += item[COV] * item[WT] cov = sum_covwt / sum_wt return cov if __name__ == '__main__': lstc = [] commas_to_list(lstc, ((n, ln) for n, ln in enumerate(fc2.split('\n')))) depth_first(lstc) print('\n\nTOP COVERAGE =%f\n'% covercalc(lstc)) depth_first(lstc) pptreefields(['NAME_HIERARCHY WEIGHT COVERAGE'.split()] + lstc)
797Functional coverage tree
3python
lbgcv
package main import ( "fmt" "go/ast" "go/parser" "go/token" "io/ioutil" "os" "sort" ) func main() { if len(os.Args) != 2 { fmt.Println("usage ff <go source filename>") return } src, err := ioutil.ReadFile(os.Args[1]) if err != nil { fmt.Println(err) return } fs := token.NewFileSet() a, err := parser.ParseFile(fs, os.Args[1], src, 0) if err != nil { fmt.Println(err) return } f := fs.File(a.Pos()) m := make(map[string]int) ast.Inspect(a, func(n ast.Node) bool { if ce, ok := n.(*ast.CallExpr); ok { start := f.Offset(ce.Pos()) end := f.Offset(ce.Lparen) m[string(src[start:end])]++ } return true }) cs := make(calls, 0, len(m)) for k, v := range m { cs = append(cs, &call{k, v}) } sort.Sort(cs) for i, c := range cs { fmt.Printf("%-20s%4d\n", c.expr, c.count) if i == 9 { break } } } type call struct { expr string count int } type calls []*call func (c calls) Len() int { return len(c) } func (c calls) Swap(i, j int) { c[i], c[j] = c[j], c[i] } func (c calls) Less(i, j int) bool { return c[i].count > c[j].count }
799Function frequency
0go
dv3ne
import Data.Map hiding (map, filter) import Graphics.Gloss import Control.Monad.Random data Ball = Ball { position :: (Int, Int), turns :: [Int] } type World = ( Int , [Ball] , Map Int Int ) updateWorld :: World -> World updateWorld (nRows, balls, bins) | y < -nRows-5 = (nRows, map update bs, bins <+> x) | otherwise = (nRows, map update balls, bins) where (Ball (x,y) _): bs = balls b <+> x = unionWith (+) b (singleton x 1) update (Ball (x,y) turns) | -nRows <= y && y < 0 = Ball (x + head turns, y - 1) (tail turns) | otherwise = Ball (x, y - 1) turns drawWorld :: World -> Picture drawWorld (nRows, balls, bins) = pictures [ color red ballsP , color black binsP , color blue pinsP ] where ballsP = foldMap (disk 1) $ takeWhile ((3 >).snd) $ map position balls binsP = foldMapWithKey drawBin bins pinsP = foldMap (disk 0.2) $ [1..nRows] >>= \i -> [1..i] >>= \j -> [(2*j-i-1, -i-1)] disk r pos = trans pos $ circleSolid (r*10) drawBin x h = trans (x,-nRows-7) $ rectangleUpperSolid 20 (-fromIntegral h) trans (x,y) = Translate (20 * fromIntegral x) (20 * fromIntegral y) startSimulation :: Int -> [Ball] -> IO () startSimulation nRows balls = simulate display white 50 world drawWorld update where display = InWindow "Galton box" (400, 400) (0, 0) world = (nRows, balls, empty) update _ _ = updateWorld main = evalRandIO balls >>= startSimulation 10 where balls = mapM makeBall [1..] makeBall y = Ball (0, y) <$> randomTurns randomTurns = filter (/=0) <$> getRandomRs (-1, 1)
798Galton box animation
8haskell
y7266
package main import ( "errors" "fmt" "log" "math" ) type testCase struct { a [][]float64 b []float64 x []float64 } var tc = testCase{
794Gaussian elimination
0go
wzdeg
fun main(args: Array<String>) {
791General FizzBuzz
11kotlin
8990q
null
788Generator/Exponential
1lua
j0i71
pieces <- c("R","B","N","Q","K","N","B","R") generateFirstRank <- function() { attempt <- paste0(sample(pieces), collapse = "") while (!check_position(attempt)) { attempt <- paste0(sample(pieces), collapse = "") } return(attempt) } check_position <- function(position) { if (regexpr('.*R.*K.*R.*', position) == -1) return(FALSE) if (regexpr('.*B(..|....|......|)B.*', position) == -1) return(FALSE) TRUE } convert_to_unicode <- function(s) { s <- sub("K","\u2654", s) s <- sub("Q","\u2655", s) s <- gsub("R","\u2656", s) s <- gsub("B","\u2657", s) s <- gsub("N","\u2658", s) } cat(convert_to_unicode(generateFirstRank()), "\n")
790Generate Chess960 starting position
13r
z4gth
package main import ( "fmt" "io" "log" "os" "github.com/stacktic/ftp" ) func main() {
800FTP
0go
j0b7d
@Grab(group='commons-net', module='commons-net', version='2.0') import org.apache.commons.net.ftp.FTPClient println("About to connect...."); new FTPClient().with { connect "ftp.easynet.fr" enterLocalPassiveMode() login "anonymous", "[email protected]" changeWorkingDirectory "/debian/" def incomingFile = new File("README.html") incomingFile.withOutputStream { ostream -> retrieveFile "README.html", ostream } disconnect() } println(" ...Done.");
800FTP
7groovy
5eruv
function Func()
795Function prototype
1lua
8930e
package main import ( "bufio" "fmt" "os" "strconv" "strings" ) var ( gregorianStr = []string{"January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"} gregorian = []int{31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31} republicanStr = []string{"Vendemiaire", "Brumaire", "Frimaire", "Nivose", "Pluviose", "Ventose", "Germinal", "Floreal", "Prairial", "Messidor", "Thermidor", "Fructidor"} sansculottidesStr = []string{"Fete de la vertu", "Fete du genie", "Fete du travail", "Fete de l'opinion", "Fete des recompenses", "Fete de la Revolution"} ) func main() { fmt.Println("*** French Republican ***") fmt.Println("*** calendar converter ***") fmt.Println("Enter a date to convert, in the format 'day month year'") fmt.Println("e.g.: 1 Prairial 3,") fmt.Println(" 20 May 1795.") fmt.Println("For Sansculottides, use 'day year'") fmt.Println("e.g.: Fete de l'opinion 9.") fmt.Println("Or just press 'RETURN' to exit the program.") fmt.Println() for sc := bufio.NewScanner(os.Stdin); ; { fmt.Print("> ") sc.Scan() src := sc.Text() if src == "" { return } day, month, year := split(src) if year < 1792 { day, month, year = dayToGre(repToDay(day, month, year)) fmt.Println(day, gregorianStr[month-1], year) } else { day, month, year := dayToRep(greToDay(day, month, year)) if month == 13 { fmt.Println(sansculottidesStr[day-1], year) } else { fmt.Println(day, republicanStr[month-1], year) } } } } func split(s string) (d, m, y int) { if strings.HasPrefix(s, "Fete") { m = 13 for i, sc := range sansculottidesStr { if strings.HasPrefix(s, sc) { d = i + 1 y, _ = strconv.Atoi(s[len(sc)+1:]) } } } else { d, _ = strconv.Atoi(s[:strings.Index(s, " ")]) my := s[strings.Index(s, " ")+1:] mStr := my[:strings.Index(my, " ")] y, _ = strconv.Atoi(my[strings.Index(my, " ")+1:]) months := gregorianStr if y < 1792 { months = republicanStr } for i, mn := range months { if mn == mStr { m = i + 1 } } } return } func greToDay(d, m, y int) int { if m < 3 { y-- m += 12 } return y*36525/100 - y/100 + y/400 + 306*(m+1)/10 + d - 654842 } func repToDay(d, m, y int) int { if m == 13 { m-- d += 30 } if repLeap(y) { d-- } return 365*y + (y+1)/4 - (y+1)/100 + (y+1)/400 + 30*m + d - 395 } func dayToGre(day int) (d, m, y int) { y = day * 100 / 36525 d = day - y*36525/100 + 21 y += 1792 d += y/100 - y/400 - 13 m = 8 for d > gregorian[m] { d -= gregorian[m] m++ if m == 12 { m = 0 y++ if greLeap(y) { gregorian[1] = 29 } else { gregorian[1] = 28 } } } m++ return } func dayToRep(day int) (d, m, y int) { y = (day-1) * 100 / 36525 if repLeap(y) { y-- } d = day - (y+1)*36525/100 + 365 + (y+1)/100 - (y+1)/400 y++ m = 1 sansculottides := 5 if repLeap(y) { sansculottides = 6 } for d > 30 { d -= 30 m += 1 if m == 13 { if d > sansculottides { d -= sansculottides m = 1 y++ sansculottides = 5 if repLeap(y) { sansculottides = 6 } } } } return } func repLeap(year int) bool { return (year+1)%4 == 0 && ((year+1)%100 != 0 || (year+1)%400 == 0) } func greLeap(year int) bool { return year%4 == 0 && (year%100 != 0 || year%400 == 0) }
801French Republican calendar
0go
ua4vt
import Language.Haskell.Parser (parseModule) import Data.List.Split (splitOn) import Data.List (nub, sortOn, elemIndices) findApps src = freq $ concat [apps, comps] where ast = show $ parseModule src apps = extract <$> splitApp ast comps = extract <$> concat (splitComp <$> splitInfix ast) splitApp = tail . splitOn "(HsApp (HsVar (UnQual (HsIdent \"" splitInfix = tail . splitOn "(HsInfixApp (HsVar (UnQual (HsIdent \"" splitComp = take 1 . splitOn "(HsQVarOp (UnQual (HsSymbol \"" extract = takeWhile (/= '\"') freq lst = [ (count x lst, x) | x <- nub lst ] count x = length . elemIndices x main = do src <- readFile "CountFunctions.hs" let res = sortOn (negate . fst) $ findApps src mapM_ (\(n, f) -> putStrLn $ show n ++ "\t" ++ f) res
799Function frequency
8haskell
5e7ug
double st_gamma(double x) { return sqrt(2.0*M_PI/x)*pow(x/M_E, x); } double sp_gamma(double z) { const int a = A; static double c_space[A]; static double *c = NULL; int k; double accm; if ( c == NULL ) { double k1_factrl = 1.0; c = c_space; c[0] = sqrt(2.0*M_PI); for(k=1; k < a; k++) { c[k] = exp(a-k) * pow(a-k, k-0.5) / k1_factrl; k1_factrl *= -k; } } accm = c[0]; for(k=1; k < a; k++) { accm += c[k] / ( z + k ); } accm *= exp(-(z+a)) * pow(z+a, z+0.5); return accm/z; } int main() { double x; printf(, , , , ); for(x=1.0; x <= 10.0; x+=1.0) { printf(, st_gamma(x/3.0), sp_gamma(x/3.0), gsl_sf_gamma(x/3.0), tgamma(x/3.0)); } return 0; }
802Gamma function
5c
dvfnv
package main import "fmt" func commatize(n uint64) string { s := fmt.Sprintf("%d", n) le := len(s) for i := le - 3; i >= 1; i -= 3 { s = s[0:i] + "," + s[i:] } return s } func main() { starts := []uint64{1e2, 1e6, 1e7, 1e9, 7123} counts := []int{30, 15, 15, 10, 25} for i := 0; i < len(starts); i++ { count := 0 j := starts[i] pow := uint64(100) for { if j < pow*10 { break } pow *= 10 } fmt.Printf("First%d gapful numbers starting at%s:\n", counts[i], commatize(starts[i])) for count < counts[i] { fl := (j/pow)*10 + (j % 10) if j%fl == 0 { fmt.Printf("%d ", j) count++ } j++ if j >= 10*pow { pow *= 10 } } fmt.Println("\n") } }
793Gapful numbers
0go
ckj9g
isMatrix xs = null xs || all ((== (length.head $ xs)).length) xs isSquareMatrix xs = null xs || all ((== (length xs)).length) xs mult:: Num a => [[a]] -> [[a]] -> [[a]] mult uss vss = map ((\xs -> if null xs then [] else foldl1 (zipWith (+)) xs). zipWith (\vs u -> map (u*) vs) vss) uss gauss::[[Double]] -> [[Double]] -> [[Double]] gauss xs bs = map (map fromRational) $ solveGauss (toR xs) (toR bs) where toR = map $ map toRational solveGauss:: (Fractional a, Ord a) => [[a]] -> [[a]] -> [[a]] solveGauss xs bs | null xs || null bs || length xs /= length bs || (not $ isSquareMatrix xs) || (not $ isMatrix bs) = [] | otherwise = uncurry solveTriangle $ triangle xs bs solveTriangle::(Fractional a,Eq a) => [[a]] -> [[a]] -> [[a]] solveTriangle us _ | not.null.dropWhile ((/= 0).head) $ us = [] solveTriangle ([c]:as) (b:bs) = go as bs [map (/c) b] where val us vs ws = let u = head us in map (/u) $ zipWith (-) vs (head $ mult [tail us] ws) go [] _ zs = zs go _ [] zs = zs go (x:xs) (y:ys) zs = go xs ys $ (val x y zs):zs triangle::(Num a, Ord a) => [[a]] -> [[a]] -> ([[a]],[[a]]) triangle xs bs = triang ([],[]) (xs,bs) where triang ts (_,[]) = ts triang ts ([],_) = ts triang (os,ps) zs = triang (us:os,cs:ps).unzip $ [(fun tus vs, fun cs es) | (v:vs,es) <- zip uss css,let fun = zipWith (\x y -> v*x - u*y)] where ((us@(u:tus)):uss,cs:css) = bubble zs bubble::(Num a, Ord a) => ([[a]],[[a]]) -> ([[a]],[[a]]) bubble (xs,bs) = (go xs, go bs) where idmax = snd.maximum.flip zip [0..].map (abs.head) $ xs go ys = let (us,vs) = splitAt idmax ys in vs ++ us main = do let a = [[1.00, 0.00, 0.00, 0.00, 0.00, 0.00], [1.00, 0.63, 0.39, 0.25, 0.16, 0.10], [1.00, 1.26, 1.58, 1.98, 2.49, 3.13], [1.00, 1.88, 3.55, 6.70, 12.62, 23.80], [1.00, 2.51, 6.32, 15.88, 39.90, 100.28], [1.00, 3.14, 9.87, 31.01, 97.41, 306.02]] let b = [[-0.01], [0.61], [0.91], [0.99], [0.60], [0.02]] mapM_ print $ gauss a b
794Gaussian elimination
8haskell
6r53k
function genFizz (param) local response print("\n") for n = 1, param.limit do response = "" for i = 1, 3 do if n % param.factor[i] == 0 then response = response .. param.word[i] end end if response == "" then print(n) else print(response) end end end local param = {factor = {}, word = {}} param.limit = io.read() for i = 1, 3 do param.factor[i], param.word[i] = io.read("*number", "*line") end genFizz(param)
791General FizzBuzz
1lua
occ8h
module Main (main) where import Control.Exception (bracket) import Control.Monad (void) import Data.Foldable (for_) import Network.FTP.Client ( cwd , easyConnectFTP , getbinary , loginAnon , nlst , quit , setPassive ) main :: IO () main = bracket ((flip setPassive) True <$> easyConnectFTP "ftp.kernel.org") quit $ \h -> do void $ loginAnon h void $ cwd h "/pub/linux/kernel/Historic" fileNames <- nlst h Nothing for_ fileNames $ \fileName -> putStrLn fileName (fileData, _) <- getbinary h "linux-0.01.tar.gz.sign" print fileData
800FTP
8haskell
ocd8p
null
801French Republican calendar
11kotlin
gx74d
int fusc(int n){ if(n==0||n==1) return n; else if(n%2==0) return fusc(n/2); else return fusc((n-1)/2) + fusc((n+1)/2); } int numLen(int n){ int sum = 1; while(n>9){ n = n/10; sum++; } return sum; } void printLargeFuscs(int limit){ int i,f,len,maxLen = 1; printf(,limit); for(i=0;i<=limit;i++){ f = fusc(i); len = numLen(f); if(len>maxLen){ maxLen = len; printf(,i,f); } } } int main() { int i; printf(); for(i=0;i<61;i++) printf(,i,fusc(i)); printLargeFuscs(INT_MAX); return 0; }
803Fusc sequence
5c
eteav
import Foundation extension String { func paddedLeft(totalLen: Int) -> String { let needed = totalLen - count guard needed > 0 else { return self } return String(repeating: " ", count: needed) + self } } class FCNode { let name: String let weight: Int var coverage: Double { didSet { if oldValue!= coverage { parent?.updateCoverage() } } } weak var parent: FCNode? var children = [FCNode]() init(name: String, weight: Int = 1, coverage: Double = 0) { self.name = name self.weight = weight self.coverage = coverage } func addChildren(_ children: [FCNode]) { for child in children { child.parent = self } self.children += children updateCoverage() } func show(level: Int = 0) { let indent = level * 4 let nameLen = name.count + indent print(name.paddedLeft(totalLen: nameLen), terminator: "") print("|".paddedLeft(totalLen: 32 - nameLen), terminator: "") print(String(format: " %3d |", weight), terminator: "") print(String(format: "%8.6f |", coverage)) for child in children { child.show(level: level + 1) } } func updateCoverage() { let v1 = children.reduce(0.0, { $0 + $1.coverage * Double($1.weight) }) let v2 = children.reduce(0.0, { $0 + Double($1.weight) }) coverage = v1 / v2 } } let houses = [ FCNode(name: "house1", weight: 40), FCNode(name: "house2", weight: 60) ] let house1 = [ FCNode(name: "bedrooms", weight: 1, coverage: 0.25), FCNode(name: "bathrooms"), FCNode(name: "attic", weight: 1, coverage: 0.75), FCNode(name: "kitchen", weight: 1, coverage: 0.1), FCNode(name: "living_rooms"), FCNode(name: "basement"), FCNode(name: "garage"), FCNode(name: "garden", weight: 1, coverage: 0.8) ] let house2 = [ FCNode(name: "upstairs"), FCNode(name: "groundfloor"), FCNode(name: "basement") ] let h1Bathrooms = [ FCNode(name: "bathroom1", weight: 1, coverage: 0.5), FCNode(name: "bathroom2"), FCNode(name: "outside_lavatory", weight: 1, coverage: 1.0) ] let h1LivingRooms = [ FCNode(name: "lounge"), FCNode(name: "dining_room"), FCNode(name: "conservatory"), FCNode(name: "playroom", weight: 1, coverage: 1.0) ] let h2Upstairs = [ FCNode(name: "bedrooms"), FCNode(name: "bathroom"), FCNode(name: "toilet"), FCNode(name: "attics", weight: 1, coverage: 0.6) ] let h2Groundfloor = [ FCNode(name: "kitchen"), FCNode(name: "living_rooms"), FCNode(name: "wet_room_&_toilet"), FCNode(name: "garage"), FCNode(name: "garden", weight: 1, coverage: 0.9), FCNode(name: "hot_tub_suite", weight: 1, coverage: 1.0) ] let h2Basement = [ FCNode(name: "cellars", weight: 1, coverage: 1.0), FCNode(name: "wine_cellar", weight: 1, coverage: 1.0), FCNode(name: "cinema", weight: 1, coverage: 0.75) ] let h2UpstairsBedrooms = [ FCNode(name: "suite_1"), FCNode(name: "suite_2"), FCNode(name: "bedroom_3"), FCNode(name: "bedroom_4") ] let h2GroundfloorLivingRooms = [ FCNode(name: "lounge"), FCNode(name: "dining_room"), FCNode(name: "conservatory"), FCNode(name: "playroom") ] let cleaning = FCNode(name: "cleaning") house1[1].addChildren(h1Bathrooms) house1[4].addChildren(h1LivingRooms) houses[0].addChildren(house1) h2Upstairs[0].addChildren(h2UpstairsBedrooms) house2[0].addChildren(h2Upstairs) h2Groundfloor[1].addChildren(h2GroundfloorLivingRooms) house2[1].addChildren(h2Groundfloor) house2[2].addChildren(h2Basement) houses[1].addChildren(house2) cleaning.addChildren(houses) let top = cleaning.coverage print("Top Coverage: \(String(format: "%8.6f", top))") print("Name Hierarchy | Weight | Coverage |") cleaning.show() h2Basement[2].coverage = 1.0 let diff = cleaning.coverage - top print("\nIf the coverage of the Cinema node were increased from 0.75 to 1.0") print("the top level coverage would increase by ") print("\(String(format: "%8.6f", diff)) to \(String(format: "%8.6f", top))")
797Functional coverage tree
17swift
2prlj
class GapfulNumbers { private static String commatize(long n) { StringBuilder sb = new StringBuilder(Long.toString(n)) int le = sb.length() for (int i = le - 3; i >= 1; i -= 3) { sb.insert(i, ',') } return sb.toString() } static void main(String[] args) { List<Long> starts = [(long) 1e2, (long) 1e6, (long) 1e7, (long) 1e9, (long) 7123] List<Integer> counts = [30, 15, 15, 10, 25] for (int i = 0; i < starts.size(); ++i) { println("First ${counts.get(i)} gapful numbers starting at ${commatize(starts.get(i))}") long j = starts.get(i) long pow = 100 while (j >= pow * 10) { pow *= 10 } int count = 0 while (count < counts.get(i)) { long fl = ((long) (j / pow)) * 10 + (j % 10) if (j % fl == 0) { print("$j ") count++ } if (++j >= 10 * pow) { pow *= 10 } } println() println() } } }
793Gapful numbers
7groovy
3g5zd
import java.io.FileOutputStream; import java.io.IOException; import java.io.OutputStream; import org.apache.commons.net.ftp.FTP; import org.apache.commons.net.ftp.FTPClient; import org.apache.commons.net.ftp.FTPFile; import org.apache.commons.net.ftp.FTPReply; public class FTPconn { public static void main(String[] args) throws IOException { String server = "ftp.hq.nasa.gov"; int port = 21; String user = "anonymous"; String pass = "[email protected]"; OutputStream output = null; FTPClient ftpClient = new FTPClient(); try { ftpClient.connect(server, port); serverReply(ftpClient); int replyCode = ftpClient.getReplyCode(); if (!FTPReply.isPositiveCompletion(replyCode)) { System.out.println("Failure. Server reply code: " + replyCode); return; } serverReply(ftpClient); if (!ftpClient.login(user, pass)) { System.out.println("Could not login to the server."); return; } String dir = "pub/issoutreach/Living in Space Stories (MP3 Files)/"; if (!ftpClient.changeWorkingDirectory(dir)) { System.out.println("Change directory failed."); return; } ftpClient.enterLocalPassiveMode(); for (FTPFile file : ftpClient.listFiles()) System.out.println(file); String filename = "Can People go to Mars.mp3"; output = new FileOutputStream(filename); ftpClient.setFileType(FTP.BINARY_FILE_TYPE); if (!ftpClient.retrieveFile(filename, output)) { System.out.println("Retrieving file failed"); return; } serverReply(ftpClient); ftpClient.logout(); } finally { if (output != null) output.close(); } } private static void serverReply(FTPClient ftpClient) { for (String reply : ftpClient.getReplyStrings()) { System.out.println(reply); } } }
800FTP
9java
wzsej
use feature 'state'; use DateTime; my @month_names = qw{ Vendmiaire Brumaire Frimaire Nivse Pluvise Ventse Germinal Floral Prairial Messidor Thermidor Fructidor }; my @intercalary = ( 'Fte de la vertu', 'Fte du gnie', 'Fte du travail', "Fte de l'opinion", 'Fte des rcompenses', 'Fte de la Rvolution', ); my %month_nums = map { $month_names[$_] => $_+1 } 0 .. $ my %i_cal_nums = map { $intercalary[$_] => $_+1 } 0 .. $ my $i_cal_month = 13; my $epoch = DateTime->new( year => 1792, month => 9, day => 22 ); sub is_republican_leap_year { my $y = $_[0] + 1; return !!( ($y % 4)==0 and (($y % 100)!=0 or ($y % 400)==0) ); } sub Republican_to_Gregorian { my ($rep_date) = @_; state $months = join '|', map { quotemeta } @month_names; state $intercal = join '|', map { quotemeta } @intercalary; state $re = qr{ \A \s* (?: (?<ic> $intercal) | (?<day> \d+) \s+ (?<month> $months) ) \s+ (?<year> \d+) \s* \z }msx; $rep_date =~ /$re/ or die "Republican date not recognized: '$rep_date'"; my $day1 = $+{ic} ? $i_cal_nums{$+{ic}} : $+{day}; my $month1 = $+{month} ? $month_nums{$+{month}} : $i_cal_month; my $year1 = $+{year}; my $days_since_epoch = ($year1-1) * 365 + ($month1-1) * 30 + ($day1-1); my $leap_days = grep { is_republican_leap_year($_) } 1 .. $year1-1; return $epoch->clone->add( days => ($days_since_epoch + $leap_days) ); } sub Gregorian_to_Republican { my ($greg_date) = @_; my $days_since_epoch = $epoch->delta_days($greg_date)->in_units('days'); die if $days_since_epoch < 0; my ( $year, $days ) = ( 1, $days_since_epoch ); while (1) { my $year_length = 365 + ( is_republican_leap_year($year) ? 1 : 0 ); last if $days < $year_length; $days -= $year_length; $year += 1; } my $day0 = $days % 30; my $month0 = ($days - $day0) / 30; my ( $day1, $month1 ) = ( $day0 + 1, $month0 + 1 ); return $month1 == $i_cal_month ? "$intercalary[$day0 ] $year" : "$day1 $month_names[$month0] $year"; } while (<DATA>) { s{\s*\ /^(\d{4})-(\d{2})-(\d{2})\s+(\S.+?\S)\s*$/ or die; my $g = DateTime->new( year => $1, month => $2, day => $3 ); my $r = $4; die if Republican_to_Gregorian($r) != $g or Gregorian_to_Republican($g) ne $r; die if Gregorian_to_Republican(Republican_to_Gregorian($r)) ne $r or Republican_to_Gregorian(Gregorian_to_Republican($g)) != $g; } say 'All tests successful.'; __DATA__ 1792-09-22 1 Vendmiaire 1 1795-05-20 1 Prairial 3 1799-07-15 27 Messidor 7 1803-09-23 Fte de la Rvolution 11 1805-12-31 10 Nivse 14 1871-03-18 27 Ventse 79 1944-08-25 7 Fructidor 152 2016-09-19 Fte du travail 224 1871-05-06 16 Floral 79 1871-05-23 3 Prairial 79 1799-11-09 18 Brumaire 8 1804-12-02 11 Frimaire 13 1794-10-30 9 Brumaire 3 1794-07-27 9 Thermidor 2 1799-05-27 8 Prairial 7 1792-09-22 1 Vendmiaire 1 1793-09-22 1 Vendmiaire 2 1794-09-22 1 Vendmiaire 3 1795-09-23 1 Vendmiaire 4 1796-09-22 1 Vendmiaire 5 1797-09-22 1 Vendmiaire 6 1798-09-22 1 Vendmiaire 7 1799-09-23 1 Vendmiaire 8 1800-09-23 1 Vendmiaire 9 1801-09-23 1 Vendmiaire 10 1802-09-23 1 Vendmiaire 11 1803-09-24 1 Vendmiaire 12 1804-09-23 1 Vendmiaire 13 1805-09-23 1 Vendmiaire 14 1806-09-23 1 Vendmiaire 15 1807-09-24 1 Vendmiaire 16 1808-09-23 1 Vendmiaire 17 1809-09-23 1 Vendmiaire 18 1810-09-23 1 Vendmiaire 19 1811-09-24 1 Vendmiaire 20 2015-09-23 1 Vendmiaire 224 2016-09-22 1 Vendmiaire 225 2017-09-22 1 Vendmiaire 226
801French Republican calendar
2perl
n2fiw
use PPI::Tokenizer; my $Tokenizer = PPI::Tokenizer->new( '/path/to/your/script.pl' ); my %counts; while (my $token = $Tokenizer->get_token) { if ($token =~ /\A[\$\@\%*[:alpha:]]/) { $counts{$token}++; } } my @desc_by_occurrence = sort {$counts{$b} <=> $counts{$a} || $a cmp $b} keys(%counts); my @top_ten_by_occurrence = @desc_by_occurrence[0 .. 9]; foreach my $token (@top_ten_by_occurrence) { print $counts{$token}, "\t", $token, "\n"; }
799Function frequency
2perl
biek4
import java.util.Random; import java.util.List; import java.util.ArrayList; public class GaltonBox { public static void main( final String[] args ) { new GaltonBox( 8, 200 ).run(); } private final int m_pinRows; private final int m_startRow; private final Position[] m_balls; private final Random m_random = new Random(); public GaltonBox( final int pinRows, final int ballCount ) { m_pinRows = pinRows; m_startRow = pinRows + 1; m_balls = new Position[ ballCount ]; for ( int ball = 0; ball < ballCount; ball++ ) m_balls[ ball ] = new Position( m_startRow, 0, 'o' ); } private static class Position { int m_row; int m_col; char m_char; Position( final int row, final int col, final char ch ) { m_row = row; m_col = col; m_char = ch; } } public void run() { for ( int ballsInPlay = m_balls.length; ballsInPlay > 0; ) { ballsInPlay = dropBalls(); print(); } } private int dropBalls() { int ballsInPlay = 0; int ballToStart = -1;
798Galton box animation
9java
dv6n9
gapful :: Int -> Bool gapful n = n `rem` firstLastDigit == 0 where firstLastDigit = read [head asDigits, last asDigits] asDigits = show n main :: IO () main = do putStrLn $ "\nFirst 30 Gapful numbers >= 100:\n" ++ r 30 [100,101..] putStrLn $ "\nFirst 15 Gapful numbers >= 1,000,000:\n" ++ r 15 [1_000_000,1_000_001..] putStrLn $ "\nFirst 10 Gapful numbers >= 1,000,000,000:\n" ++ r 10 [1_000_000_000,1_000_000_001..] where r n = show . take n . filter gapful
793Gapful numbers
8haskell
pnobt
import java.util.Locale; public class GaussianElimination { public static double solve(double[][] a, double[][] b) { if (a == null || b == null || a.length == 0 || b.length == 0) { throw new IllegalArgumentException("Invalid dimensions"); } int n = b.length, p = b[0].length; if (a.length != n || a[0].length != n) { throw new IllegalArgumentException("Invalid dimensions"); } double det = 1.0; for (int i = 0; i < n - 1; i++) { int k = i; for (int j = i + 1; j < n; j++) { if (Math.abs(a[j][i]) > Math.abs(a[k][i])) { k = j; } } if (k != i) { det = -det; for (int j = i; j < n; j++) { double s = a[i][j]; a[i][j] = a[k][j]; a[k][j] = s; } for (int j = 0; j < p; j++) { double s = b[i][j]; b[i][j] = b[k][j]; b[k][j] = s; } } for (int j = i + 1; j < n; j++) { double s = a[j][i] / a[i][i]; for (k = i + 1; k < n; k++) { a[j][k] -= s * a[i][k]; } for (k = 0; k < p; k++) { b[j][k] -= s * b[i][k]; } } } for (int i = n - 1; i >= 0; i--) { for (int j = i + 1; j < n; j++) { double s = a[i][j]; for (int k = 0; k < p; k++) { b[i][k] -= s * b[j][k]; } } double s = a[i][i]; det *= s; for (int k = 0; k < p; k++) { b[i][k] /= s; } } return det; } public static void main(String[] args) { double[][] a = new double[][] {{4.0, 1.0, 0.0, 0.0, 0.0}, {1.0, 4.0, 1.0, 0.0, 0.0}, {0.0, 1.0, 4.0, 1.0, 0.0}, {0.0, 0.0, 1.0, 4.0, 1.0}, {0.0, 0.0, 0.0, 1.0, 4.0}}; double[][] b = new double[][] {{1.0 / 2.0}, {2.0 / 3.0}, {3.0 / 4.0}, {4.0 / 5.0}, {5.0 / 6.0}}; double[] x = {39.0 / 400.0, 11.0 / 100.0, 31.0 / 240.0, 37.0 / 300.0, 71.0 / 400.0}; System.out.println("det: " + solve(a, b)); for (int i = 0; i < 5; i++) { System.out.printf(Locale.US, "%12.8f%12.4e\n", b[i][0], b[i][0] - x[i]); } } }
794Gaussian elimination
9java
n29ih
sub rref { our @m; local *m = shift; @m or return; my ($lead, $rows, $cols) = (0, scalar(@m), scalar(@{$m[0]})); foreach my $r (0 .. $rows - 1) { $lead < $cols or return; my $i = $r; until ($m[$i][$lead]) {++$i == $rows or next; $i = $r; ++$lead == $cols and return;} @m[$i, $r] = @m[$r, $i]; my $lv = $m[$r][$lead]; $_ /= $lv foreach @{ $m[$r] }; my @mr = @{ $m[$r] }; foreach my $i (0 .. $rows - 1) {$i == $r and next; ($lv, my $n) = ($m[$i][$lead], -1); $_ -= $lv * $mr[++$n] foreach @{ $m[$i] };} ++$lead;} } sub display { join("\n" => map join(" " => map(sprintf("%6.2f", $_), @$_)), @{+shift})."\n" } sub gauss_jordan_invert { my(@m) = @_; my $rows = @m; my @i = identity(scalar @m); push @{$m[$_]}, @{$i[$_]} for 0..$rows-1; rref(\@m); map { splice @$_, 0, $rows } @m; @m; } sub identity { my($n) = @_; map { [ (0) x $_, 1, (0) x ($n-1 - $_) ] } 0..$n-1 } my @tests = ( [ [ 2, -1, 0 ], [-1, 2, -1 ], [ 0, -1, 2 ] ], [ [ -1, -2, 3, 2 ], [ -4, -1, 6, 2 ], [ 7, -8, 9, 1 ], [ 1, -2, 1, 3 ] ], ); for my $matrix (@tests) { print "Original Matrix:\n" . display(\@$matrix) . "\n"; my @gj = gauss_jordan_invert( @$matrix ); print "Gauss-Jordan Inverted Matrix:\n" . display(\@gj) . "\n"; my @rt = gauss_jordan_invert( @gj ); print "After round-trip:\n" . display(\@rt) . "\n";} . "\n" }
792Gauss-Jordan matrix inversion
2perl
wzte6
pieces = %i( ) regexes = [/(..)*/, /.*.*/] row = pieces.shuffle.join until regexes.all?{|re| re.match(row)} puts row
790Generate Chess960 starting position
14ruby
ckb9k
use std::collections::BTreeSet; struct Chess960 ( BTreeSet<String> ); impl Chess960 { fn invoke(&mut self, b: &str, e: &str) { if e.len() <= 1 { let s = b.to_string() + e; if Chess960::is_valid(&s) { self.0.insert(s); } } else { for (i, c) in e.char_indices() { let mut b = b.to_string(); b.push(c); let mut e = e.to_string(); e.remove(i); self.invoke(&b, &e); } } } fn is_valid(s: &str) -> bool { let k = s.find('K').unwrap(); k > s.find('R').unwrap() && k < s.rfind('R').unwrap() && s.find('B').unwrap()% 2!= s.rfind('B').unwrap()% 2 } }
790Generate Chess960 starting position
15rust
lbpcc
headers = /usr/include/ftplib.h linkerOpts.linux = -L/usr/lib -lftp --- #include <sys/time.h> struct NetBuf { char *cput,*cget; int handle; int cavail,cleft; char *buf; int dir; netbuf *ctrl; netbuf *data; int cmode; struct timeval idletime; FtpCallback idlecb; void *idlearg; int xfered; int cbbytes; int xfered1; char response[256]; };
800FTP
11kotlin
biakb
sub noargs(); sub twoargs($$); sub noargs :prototype(); sub twoargs :prototype($$);
795Function prototype
2perl
5ebu2
import ast class CallCountingVisitor(ast.NodeVisitor): def __init__(self): self.calls = {} def visit_Call(self, node): if isinstance(node.func, ast.Name): fun_name = node.func.id call_count = self.calls.get(fun_name, 0) self.calls[fun_name] = call_count + 1 self.generic_visit(node) filename = input('Enter a filename to parse: ') with open(filename, encoding='utf-8') as f: contents = f.read() root = ast.parse(contents, filename=filename) visitor = CallCountingVisitor() visitor.visit(root) top10 = sorted(visitor.calls.items(), key=lambda x: x[1], reverse=True)[:10] for name, count in top10: print(name,'called',count,'times')
799Function frequency
3python
pnwbm
(defn gamma "Returns Gamma(z + 1 = number) using Lanczos approximation." [number] (if (< number 0.5) (/ Math/PI (* (Math/sin (* Math/PI number)) (gamma (- 1 number)))) (let [n (dec number) c [0.99999999999980993 676.5203681218851 -1259.1392167224028 771.32342877765313 -176.61502916214059 12.507343278686905 -0.13857109526572012 9.9843695780195716e-6 1.5056327351493116e-7]] (* (Math/sqrt (* 2 Math/PI)) (Math/pow (+ n 7 0.5) (+ n 0.5)) (Math/exp (- (+ n 7 0.5))) (+ (first c) (apply + (map-indexed #(/ %2 (+ n %1 1)) (next c))))))))
802Gamma function
6clojure
6ry3q
const readline = require('readline'); const galtonBox = (layers, balls) => { const speed = 100; const ball = 'o'; const peg = '.'; const result = []; const sleep = ms => new Promise(resolve => { setTimeout(resolve,ms) }); const board = [...Array(layers)] .map((e, i) => { const sides = Array(layers - i).fill(' '); const a = Array(i + 1).fill(peg).join(' ').split(''); return [...sides, ...a, ...sides]; }); const emptyRow = () => Array(board[0].length).fill(' '); const bounce = i => Math.round(Math.random()) ? i - 1 : i + 1; const show = () => { readline.cursorTo(process.stdout, 0, 0); readline.clearScreenDown(process.stdout); board.forEach(e => console.log(e.join(''))); result.reverse(); result.forEach(e => console.log(e.join(''))); result.reverse(); }; const appendToResult = idx => { const row = result.find(e => e[idx] === ' '); if (row) { row[idx] = ball; } else { const newRow = emptyRow(); newRow[idx] = ball; result.push(newRow); } }; const iter = () => { let hasNext = false; [...Array(bordSize)].forEach((e, i) => { const rowIdx = (bordSize - 1) - i; const idx = board[rowIdx].indexOf(ball); if (idx > -1) { board[rowIdx][idx] = ' '; const nextRowIdx = rowIdx + 1; if (nextRowIdx < bordSize) { hasNext = true; const nextRow = board[nextRowIdx]; nextRow[bounce(idx)] = ball; } else { appendToResult(idx); } } }); return hasNext; }; const addBall = () => { board[0][apex] = ball; balls = balls - 1; return balls; }; board.unshift(emptyRow()); result.unshift(emptyRow()); const bordSize = board.length; const apex = board[1].indexOf(peg); (async () => { while (addBall()) { await sleep(speed).then(show); iter(); } await sleep(speed).then(show); while (iter()) { await sleep(speed).then(show); } await sleep(speed).then(show); })(); }; galtonBox(12, 50);
798Galton box animation
10javascript
6rl38
import java.util.List; public class GapfulNumbers { private static String commatize(long n) { StringBuilder sb = new StringBuilder(Long.toString(n)); int le = sb.length(); for (int i = le - 3; i >= 1; i -= 3) { sb.insert(i, ','); } return sb.toString(); } public static void main(String[] args) { List<Long> starts = List.of((long) 1e2, (long) 1e6, (long) 1e7, (long) 1e9, (long) 7123); List<Integer> counts = List.of(30, 15, 15, 10, 25); for (int i = 0; i < starts.size(); ++i) { int count = 0; Long j = starts.get(i); long pow = 100; while (j >= pow * 10) { pow *= 10; } System.out.printf("First%d gapful numbers starting at%s:\n", counts.get(i), commatize(starts.get(i))); while (count < counts.get(i)) { long fl = (j / pow) * 10 + (j % 10); if (j % fl == 0) { System.out.printf("%d ", j); count++; } j++; if (j >= 10 * pow) { pow *= 10; } } System.out.println('\n'); } } }
793Gapful numbers
9java
rqwg0
null
794Gaussian elimination
10javascript
3guz0
import scala.annotation.tailrec object Chess960 extends App { private val pieces = List('', '', '', '', '', '', '', '') @tailrec private def generateFirstRank(pieces: List[Char]): List[Char] = { def check(rank: String) = rank.matches(".*.*.*.*") && rank.matches(".*(..|....|......|).*") val p = scala.util.Random.shuffle(pieces) if (check(p.toString.replaceAll("[^\\p{Upper}]", ""))) generateFirstRank(pieces) else p } loop(10) @tailrec private def loop(n: Int): Unit = { println(generateFirstRank(pieces)) if (n <= 0) () else loop(n - 1) } }
790Generate Chess960 starting position
16scala
uaev8
use Net::FTP; my $host = 'speedtest.tele2.net'; my $user = 'anonymous'; my $password = ''; my $f = Net::FTP->new($host) or die "Can't open $host\n"; $f->login($user, $password) or die "Can't login as $user\n"; $f->passive(); $f->cwd('upload'); @files = $f->ls(); printf "Currently%d files in the 'upload' directory.\n", @files; $f->cwd('/'); $f->type('binary'); $local = $f->get('512KB.zip'); print "Your file was stored as $local in the current directory\n";
800FTP
2perl
6r936
null
798Galton box animation
11kotlin
0mdsf
null
793Gapful numbers
10javascript
bi8ki
double rand_fl(){ return (double)rand() / (double)RAND_MAX; } void draw_tree(SDL_Surface * surface, double offsetx, double offsety, double directionx, double directiony, double size, double rotation, int depth) { cairo_surface_t *surf = cairo_image_surface_create_for_data( surface->pixels, CAIRO_FORMAT_RGB24, surface->w, surface->h, surface->pitch ); cairo_t *ct = cairo_create(surf); cairo_set_line_width(ct, 1); cairo_set_source_rgba(ct, 0,0,0,1); cairo_move_to(ct, (int)offsetx, (int)offsety); cairo_line_to(ct, (int)(offsetx + directionx * size), (int)(offsety + directiony * size)); cairo_stroke(ct); sge_AALine(surface, (int)offsetx, (int)offsety, (int)(offsetx + directionx * size), (int)(offsety + directiony * size), SDL_MapRGB(surface->format, 0, 0, 0)); if (depth > 0){ draw_tree(surface, offsetx + directionx * size, offsety + directiony * size, directionx * cos(rotation) + directiony * sin(rotation), directionx * -sin(rotation) + directiony * cos(rotation), size * rand_fl() / SCALE + size * (SCALE - 1) / SCALE, rotation * ROTATION_SCALE, depth - 1); draw_tree(surface, offsetx + directionx * size, offsety + directiony * size, directionx * cos(-rotation) + directiony * sin(-rotation), directionx * -sin(-rotation) + directiony * cos(-rotation), size * rand_fl() / SCALE + size * (SCALE - 1) / SCALE, rotation * ROTATION_SCALE, depth - 1); } } void render(SDL_Surface * surface){ SDL_FillRect(surface, NULL, SDL_MapRGB(surface->format, 255, 255, 255)); draw_tree(surface, surface->w / 2.0, surface->h - 10.0, 0.0, -1.0, INITIAL_LENGTH, PI / 8, BRANCHES); SDL_UpdateRect(surface, 0, 0, 0, 0); } int main(){ SDL_Surface * screen; SDL_Event evt; SDL_Init(SDL_INIT_VIDEO); srand((unsigned)time(NULL)); screen = SDL_SetVideoMode(SIZE, SIZE, 32, SDL_HWSURFACE); render(screen); while(1){ if (SDL_PollEvent(&evt)){ if(evt.type == SDL_QUIT) break; } SDL_Delay(1); } SDL_Quit(); return 0; }
804Fractal tree
5c
xzewu
program="1/1 455/33 11/13 1/11 3/7 11/2 1/3" echo $program | tr " " "\n" | cut -d"/" -f1 | tr "\n" " " > "data" read -a ns < "data" echo $program | tr " " "\n" | cut -d"/" -f2 | tr "\n" " " > "data" read -a ds < "data" t=0 n=72 echo "steps of computation" > steps.csv while [ $t -le 6 ]; do if [ $(($n*${ns[$t]}%${ds[$t]})) -eq 0 ]; then let "n=$(($n*${ns[$t]}/${ds[$t]}))" let "t=0" factor $n >> steps.csv fi let "t=$t+1" done
805Fractran
4bash
34fzx
$server = ; $user = ; $pass = ; $conn = ftp_connect($server); if (!$conn) { die('unable to connect to: '. $server); } $login = ftp_login($conn, $user, $pass); if (!$login) { echo 'unable to log in to '. $server. ' with user: '.$user.' and pass: '. $pass; } else{ echo 'connected successfully'.PHP_EOL; $directory = ftp_nlist($conn,''); print_r($directory); } if (ftp_get($conn, '1KB.zip', '1KB.zip', FTP_BINARY)) { echo .PHP_EOL; } else { echo ; }
800FTP
12php
1dwpq
from ftplib import FTP ftp = FTP('kernel.org') ftp.login() ftp.cwd('/pub/linux/kernel') ftp.set_pasv(True) print ftp.retrlines('LIST') print ftp.retrbinary('RETR README', open('README', 'wb').write) ftp.quit()
800FTP
3python
y7c6q
import numpy as np from numpy.linalg import inv a = np.array([[1., 2., 3.], [4., 1., 6.],[ 7., 8., 9.]]) ainv = inv(a) print(a) print(ainv)
792Gauss-Jordan matrix inversion
3python
x3zwr
sub gen_pow { my $m = shift; my $e = 0; return sub { return $e++ ** $m; }; } sub gen_filter { my($g1, $g2) = @_; my $v1; my $v2 = $g2->(); return sub { for (;;) { $v1 = $g1->(); $v2 = $g2->() while $v1 > $v2; return $v1 unless $v1 == $v2; } }; } my $squares = gen_pow(2); my $cubes = gen_pow(3); my $squares_without_cubes = gen_filter($squares, $cubes); $squares_without_cubes->() for (1..20); my @answer; push @answer, $squares_without_cubes->() for (1..10); print "[", join(", ", @answer), "]\n";
788Generator/Exponential
2perl
fugd7
typedef struct double_to_double { double (*fn)(struct double_to_double *, double); } double_to_double; typedef struct compose_functor { double (*fn)(struct compose_functor *, double); double_to_double *f; double_to_double *g; } compose_functor; double compose_call(compose_functor *this, double x) { return CALL(this->f, CALL(this->g, x)); } double_to_double *compose(double_to_double *f, double_to_double *g) { compose_functor *result = malloc(sizeof(compose_functor)); result->fn = &compose_call; result->f = f; result->g = g; return (double_to_double *)result; } double sin_call(double_to_double *this, double x) { return sin(x); } double asin_call(double_to_double *this, double x) { return asin(x); } int main() { double_to_double *my_sin = malloc(sizeof(double_to_double)); my_sin->fn = &sin_call; double_to_double *my_asin = malloc(sizeof(double_to_double)); my_asin->fn = &asin_call; double_to_double *sin_asin = compose(my_sin, my_asin); printf(, CALL(sin_asin, 0.5)); free(sin_asin); free(my_sin); free(my_asin); return 0; }
806Function composition
5c
vp92o
Bitmap.render = function(self) for y = 1, self.height do print(table.concat(self.pixels[y], " ")) end end
798Galton box animation
1lua
89f0e
private fun commatize(n: Long): String { val sb = StringBuilder(n.toString()) val le = sb.length var i = le - 3 while (i >= 1) { sb.insert(i, ',') i -= 3 } return sb.toString() } fun main() { val starts = listOf(1e2.toLong(), 1e6.toLong(), 1e7.toLong(), 1e9.toLong(), 7123.toLong()) val counts = listOf(30, 15, 15, 10, 25) for (i in starts.indices) { var count = 0 var j = starts[i] var pow: Long = 100 while (j >= pow * 10) { pow *= 10 } System.out.printf( "First%d gapful numbers starting at%s:\n", counts[i], commatize(starts[i]) ) while (count < counts[i]) { val fl = j / pow * 10 + j % 10 if (j % fl == 0L) { System.out.printf("%d ", j) count++ } j++ if (j >= 10 * pow) { pow *= 10 } } println('\n') } }
793Gapful numbers
11kotlin
v1b21
use 5.020; use strict; use warnings; say("Please enter the maximum possible multiple. "); my $max = <STDIN>; my @factors = (); my $buffer; say("Now enter the first factor and its associated word. Ex: 3 Fizz "); chomp($buffer = <STDIN>); push @factors, $buffer; say("Now enter the second factor and its associated word. Ex: 5 Buzz "); chomp($buffer = <STDIN>); push @factors, $buffer; say("Now enter the third factor and its associated word. Ex: 7 Baxx "); chomp($buffer = <STDIN>); push @factors, $buffer; for(my $i = 1; $i <= $max; $i++) { my $oBuffer; $buffer = $i; foreach my $element (@factors) { $element =~ /\s/; if($i % substr($element, 0, @-) == 0) { $oBuffer = $oBuffer . substr($element, @+ + 1, length($element)); $buffer = ""; } } if(length($buffer) > 0) { print($buffer . "\n"); } else { print($oBuffer . "\n"); } }
791General FizzBuzz
2perl
4ww5d
func isValid960Position(_ firstRank: String) -> Bool { var rooksPlaced = 0 var bishopColor = -1 for (i, piece) in firstRank.enumerated() { switch piece { case "" where rooksPlaced!= 1: return false case "": rooksPlaced += 1 case "" where bishopColor == -1: bishopColor = i & 1 case "" where bishopColor == i & 1: return false case _: continue } } return true } struct Chess960Counts { var king = 0, queen = 0, rook = 0, bishop = 0, knight = 0 subscript(_ piece: String) -> Int { get { switch piece { case "": return king case "": return queen case "": return rook case "": return bishop case "": return knight case _: fatalError() } } set { switch piece { case "": king = newValue case "": queen = newValue case "": rook = newValue case "": bishop = newValue case "": knight = newValue case _: fatalError() } } } } func get960Position() -> String { var counts = Chess960Counts() var bishopColor = -1
790Generate Chess960 starting position
17swift
9hkmj
(import '[java.awt Color Graphics] 'javax.swing.JFrame) (defn deg-to-radian [deg] (* deg Math/PI 1/180)) (defn cos-deg [angle] (Math/cos (deg-to-radian angle))) (defn sin-deg [angle] (Math/sin (deg-to-radian angle))) (defn draw-tree [^Graphics g, x y angle depth] (when (pos? depth) (let [x2 (+ x (int (* depth 10 (cos-deg angle)))) y2 (+ y (int (* depth 10 (sin-deg angle))))] (.drawLine g x y x2 y2) (draw-tree g x2 y2 (- angle 20) (dec depth)) (recur g x2 y2 (+ angle 20) (dec depth))))) (defn fractal-tree [depth] (doto (proxy [JFrame] [] (paint [g] (.setColor g Color/BLACK) (draw-tree g 400 500 -90 depth))) (.setBounds 100 100 800 600) (.setResizable false) (.setDefaultCloseOperation JFrame/DISPOSE_ON_CLOSE) (.show))) (fractal-tree 9)
804Fractal tree
6clojure
o908j
typedef struct IntArray_t { int *ptr; size_t length; } IntArray; IntArray make(size_t size) { IntArray temp; temp.ptr = calloc(size, sizeof(int)); temp.length = size; return temp; } void destroy(IntArray *ia) { if (ia->ptr != NULL) { free(ia->ptr); ia->ptr = NULL; ia->length = 0; } } void zeroFill(IntArray dst) { memset(dst.ptr, 0, dst.length * sizeof(int)); } int indexOf(const int n, const IntArray ia) { size_t i; for (i = 0; i < ia.length; i++) { if (ia.ptr[i] == n) { return i; } } return -1; } bool getDigits(int n, int le, IntArray digits) { while (n > 0) { int r = n % 10; if (r == 0 || indexOf(r, digits) >= 0) { return false; } le--; digits.ptr[le] = r; n /= 10; } return true; } int removeDigit(IntArray digits, size_t le, size_t idx) { static const int POWS[] = { 1, 10, 100, 1000, 10000 }; int sum = 0; int pow = POWS[le - 2]; size_t i; for (i = 0; i < le; i++) { if (i == idx) continue; sum += digits.ptr[i] * pow; pow /= 10; } return sum; } int main() { int lims[4][2] = { { 12, 97 }, { 123, 986 }, { 1234, 9875 }, { 12345, 98764 } }; int count[5] = { 0 }; int omitted[5][10] = { {0} }; size_t upperBound = sizeof(lims) / sizeof(lims[0]); size_t i; for (i = 0; i < upperBound; i++) { IntArray nDigits = make(i + 2); IntArray dDigits = make(i + 2); int n; for (n = lims[i][0]; n <= lims[i][1]; n++) { int d; bool nOk; zeroFill(nDigits); nOk = getDigits(n, i + 2, nDigits); if (!nOk) { continue; } for (d = n + 1; d <= lims[i][1] + 1; d++) { size_t nix; bool dOk; zeroFill(dDigits); dOk = getDigits(d, i + 2, dDigits); if (!dOk) { continue; } for (nix = 0; nix < nDigits.length; nix++) { int digit = nDigits.ptr[nix]; int dix = indexOf(digit, dDigits); if (dix >= 0) { int rn = removeDigit(nDigits, i + 2, nix); int rd = removeDigit(dDigits, i + 2, dix); if ((double)n / d == (double)rn / rd) { count[i]++; omitted[i][digit]++; if (count[i] <= 12) { printf(, n, d, rn, rd, digit); } } } } } } printf(); destroy(&nDigits); destroy(&dDigits); } for (i = 2; i <= 5; i++) { int j; printf(, count[i - 2], i); for (j = 1; j <= 9; j++) { if (omitted[i - 2][j] == 0) { continue; } printf(, omitted[i - 2][j], j); } printf(); } return 0; }
807Fraction reduction
5c
u19v4
require 'net/ftp' Net::FTP.open('ftp.ed.ac.uk', , ) do |ftp| ftp.passive = true ftp.chdir('pub/courses') puts ftp.list ftp.getbinaryfile() end
800FTP
14ruby
9h2mz
use std::{error::Error, fs::File, io::copy}; use ftp::FtpStream; fn main() -> Result<(), Box<dyn Error>> { let mut ftp = FtpStream::connect("ftp.easynet.fr:21")?; ftp.login("anonymous", "")?; ftp.cwd("debian")?; for file in ftp.list(None)? { println!("{}", file); } let mut stream = ftp.get("README")?; let mut file = File::create("README")?; copy(&mut stream, &mut file)?; Ok(()) }
800FTP
15rust
ckv9z
import java.io.{File, FileOutputStream, InputStream} import org.apache.commons.net.ftp.{FTPClient, FTPFile, FTPReply} import scala.util.{Failure, Try} object FTPconn extends App { val (server, pass) = ("ftp.ed.ac.uk", "[email protected]") val (dir, filename, ftpClient) = ("/pub/cartonet/", "readme.txt", new FTPClient()) def canConnect(host: String): Boolean = { ftpClient.connect(host) val connectionWasEstablished = ftpClient.isConnected ftpClient.disconnect() connectionWasEstablished } def downloadFileStream(remote: String): InputStream = { val stream: InputStream = ftpClient.retrieveFileStream(remote) ftpClient.completePendingCommand() stream } def uploadFile(remote: String, input: InputStream): Boolean = ftpClient.storeFile(remote, input) if (Try { def cwd(path: String): Boolean = ftpClient.changeWorkingDirectory(path) def filesInCurrentDirectory: Seq[String] = listFiles().map(_.getName) def listFiles(): List[FTPFile] = ftpClient.listFiles.toList def downloadFile(remote: String): Boolean = { val os = new FileOutputStream(new File(remote)) ftpClient.retrieveFile(remote, os) } def connectWithAuth(host: String, password: String, username: String = "anonymous", port: Int = 21): Try[Boolean] = { def connect(): Try[Unit] = Try { try { ftpClient.connect(host, port) } catch { case ex: Throwable => println(ex.getMessage) Failure } ftpClient.enterLocalPassiveMode() serverReply(ftpClient) val replyCode = ftpClient.getReplyCode if (!FTPReply.isPositiveCompletion(replyCode)) println("Failure. Server reply code: " + replyCode) } for { connection <- connect() login <- Try { ftpClient.login(username, password) } } yield login } def serverReply(ftpClient: FTPClient): Unit = for (reply <- ftpClient.getReplyStrings) println(reply) connectWithAuth(server, pass) cwd(dir) listFiles().foreach(println) downloadFile(filename) serverReply(ftpClient) ftpClient.logout }.isFailure) println(s"Failure.") }
800FTP
16scala
v142s
null
794Gaussian elimination
11kotlin
syzq7
func loweralpha() string { p := make([]byte, 26) for i := range p { p[i] = 'a' + byte(i) } return string(p) }
796Generate lower case ASCII alphabet
0go
koxhz
def lower = ('a'..'z')
796Generate lower case ASCII alphabet
7groovy
gxp46
<?php function powers($m) { for ($n = 0; ; $n++) { yield pow($n, $m); } } function filtered($s1, $s2) { while (true) { list($v, $f) = [$s1->current(), $s2->current()]; if ($v > $f) { $s2->next(); continue; } else if ($v < $f) { yield $v; } $s1->next(); } } list($squares, $cubes) = [powers(2), powers(3)]; $f = filtered($squares, $cubes); foreach (range(0, 19) as $i) { $f->next(); } foreach (range(20, 29) as $i) { echo $i, , $f->current(), ; $f->next(); } ?>
788Generator/Exponential
12php
h8njf
use strict; use warnings; use List::Util 'any'; use Time::HiRes qw(sleep); use List::AllUtils <pairwise pairs>; use utf8; binmode STDOUT, ':utf8'; my $coins = shift || 100; my $peg_lines = shift || 13; my $row_count = $peg_lines; my $peg = '^'; my @coin_icons = ("\N{UPPER HALF BLOCK}", "\N{LOWER HALF BLOCK}"); my @coins = (undef) x (3 + $row_count + 4); my @stats = (0) x ($row_count * 2); $coins[0] = 0; while (1) { my $active = 0; $stats[$coins[-1] + $row_count]++ if defined $coins[-1]; for my $line (reverse 1..(3+$row_count+3) ) { my $coinpos = $coins[$line - 1]; if (! defined $coinpos) { $coins[$line] = undef } elsif (hits_peg($coinpos, $line)) { $active = 1; $coinpos += rand() < .5 ? -1 : 1; $coins[$line] = $coinpos } else { $active = 1; $coins[$line] = $coinpos; } } if (defined $coins[0]) { $coins[0] = undef; } elsif (--$coins > 0) { $coins[0] = 0 } for (<0 1>) { display_board(\@coins, \@stats, $_); sleep .1; } exit unless $active; } sub display_board { my($p_ref, $s_ref, $halfstep) = @_; my @positions = @$p_ref; my @stats = @$s_ref; my $coin = $coin_icons[$halfstep]; my @board = do { my @tmpl; sub out { my(@stuff) = split '', shift; my @line; push @line, ord($_) for @stuff; [@line]; } push @tmpl, out(" " . " "x(2 * $row_count)) for 1..3; my @a = reverse 1..$row_count; my @b = 1..$row_count; my @pairs = pairwise { ($a, $b) } @a, @b; for ( pairs @pairs ) { my ( $spaces, $pegs ) = @$_; push @tmpl, out(" " . " "x$spaces . join(' ',($peg) x $pegs) . " "x$spaces); } push @tmpl, out(" " . " "x(2 * $row_count)) for 1..4; @tmpl; }; my $midpos = $row_count + 2; our @output; { sub printnl { my($foo) = @_; push @output, $foo . "\n" } sub printl { my($foo) = @_; push @output, $foo } printnl("") for 0..9; for my $line (0..$ my $pos = $positions[$line]; next unless defined $pos; $board[$line][$pos + $midpos] = ord($coin); } for my $line (@board) { printnl join '', map { chr($_) } @$line; } my $padding = 0; while (any {$_> 0} @stats) { $padding++; printl " "; for my $i (0..$ if ($stats[$i] == 1) { printl "\N{UPPER HALF BLOCK}"; $stats[$i]--; } elsif ($stats[$i] <= 0) { printl " "; $stats[$i] = 0 } else { printl "\N{FULL BLOCK}"; $stats[$i]--; $stats[$i]--; } } printnl(""); } printnl("") for $padding..(10-1); } print join('', @output) . "\n"; } sub hits_peg { my($x, $y) = @_; 3 <= $y && $y < (3 + $row_count) and -($y - 2) <= $x && $x <= $y - 2 ? not 0 == ($x - $y) % 2 : 0 }
798Galton box animation
2perl
5eju2
fn main() { let mut a: Vec<Vec<f64>> = vec![vec![1.0, 2.0, 3.0], vec![4.0, 1.0, 6.0], vec![7.0, 8.0, 9.0] ]; let mut b: Vec<Vec<f64>> = vec![vec![2.0, -1.0, 0.0], vec![-1.0, 2.0, -1.0], vec![0.0, -1.0, 2.0] ]; let mut ref_a = &mut a; let rref_a = &mut ref_a; let mut ref_b = &mut b; let rref_b = &mut ref_b; println!("Matrix A:\n"); print_matrix(rref_a); println!("\nInverse of Matrix A:\n"); print_matrix(&mut matrix_inverse(rref_a)); println!("\n\nMatrix B:\n"); print_matrix(rref_b); println!("\nInverse of Matrix B:\n"); print_matrix(&mut matrix_inverse(rref_b)); }
792Gauss-Jordan matrix inversion
15rust
0mysl
<?php $max = 20; $factor = array(3 => 'Fizz', 5 => 'Buzz', 7 => 'Jazz'); for ($i = 1 ; $i <= $max ; $i++) { $matched = false; foreach ($factor AS $number => $word) { if ($i % $number == 0) { echo $word; $matched = true; } } echo ($matched? '' : $i), PHP_EOL; } ?>
791General FizzBuzz
12php
illov
lower = ['a' .. 'z'] main = print lower
796Generate lower case ASCII alphabet
8haskell
n2yie
(defn compose [f g] (fn [x] (f (g x)))) (def inc2 (compose inc inc)) (println (inc2 5))
806Function composition
6clojure
rxug2
function generateGaps(start, count) local counter = 0 local i = start print(string.format("First%d Gapful numbers >=%d:", count, start)) while counter < count do local str = tostring(i) local denom = 10 * tonumber(str:sub(1, 1)) + (i % 10) if i % denom == 0 then print(string.format("%3d:%d", counter + 1, i)) counter = counter + 1 end i = i + 1 end end generateGaps(100, 30) print() generateGaps(1000000, 15) print() generateGaps(1000000000, 15) print()
793Gapful numbers
1lua
uapvl
typedef struct frac_s *frac; struct frac_s { int n, d; frac next; }; frac parse(char *s) { int offset = 0; struct frac_s h = {0}, *p = &h; while (2 == sscanf(s, , &h.n, &h.d, &offset)) { s += offset; p = p->next = malloc(sizeof *p); *p = h; p->next = 0; } return h.next; } int run(int v, char *s) { frac n, p = parse(s); mpz_t val; mpz_init_set_ui(val, v); loop: n = p; if (mpz_popcount(val) == 1) gmp_printf(, mpz_scan1(val, 0), val); else gmp_printf(, val); for (n = p; n; n = n->next) { if (!mpz_divisible_ui_p(val, n->d)) continue; mpz_divexact_ui(val, val, n->d); mpz_mul_ui(val, val, n->n); goto loop; } gmp_printf(, val); mpz_clear(val); while (p) { n = p->next; free(p); p = n; } return 0; } int main(void) { run(2, ); return 0; }
805Fractran
5c
yrz6f
package main import ( "fmt" "strconv" ) func fusc(n int) []int { if n <= 0 { return []int{} } if n == 1 { return []int{0} } res := make([]int, n) res[0] = 0 res[1] = 1 for i := 2; i < n; i++ { if i%2 == 0 { res[i] = res[i/2] } else { res[i] = res[(i-1)/2] + res[(i+1)/2] } } return res } func fuscMaxLen(n int) [][2]int { maxLen := -1 maxFusc := -1 f := fusc(n) var res [][2]int for i := 0; i < n; i++ { if f[i] <= maxFusc { continue
803Fusc sequence
0go
9h9mt
public class LowerAscii { public static void main(String[] args) { StringBuilder sb = new StringBuilder(26); for (char ch = 'a'; ch <= 'z'; ch++) sb.append(ch); System.out.printf("lower ascii:%s, length:%s", sb, sb.length()); } }
796Generate lower case ASCII alphabet
9java
q6dxa
(function (cFrom, cTo) { function cRange(cFrom, cTo) { var iStart = cFrom.charCodeAt(0); return Array.apply( null, Array(cTo.charCodeAt(0) - iStart + 1) ).map(function (_, i) { return String.fromCharCode(iStart + i); }); } return cRange(cFrom, cTo); })('a', 'z');
796Generate lower case ASCII alphabet
10javascript
il6ol
from itertools import islice, count def powers(m): for n in count(): yield n ** m def filtered(s1, s2): v, f = next(s1), next(s2) while True: if v > f: f = next(s2) continue elif v < f: yield v v = next(s1) squares, cubes = powers(2), powers(3) f = filtered(squares, cubes) print(list(islice(f, 20, 30)))
788Generator/Exponential
3python
t5rfw
class FuscSequence { static void main(String[] args) { println("Show the first 61 fusc numbers (starting at zero) in a horizontal format") for (int n = 0; n < 61; n++) { printf("%,d ", fusc[n]) } println() println() println("Show the fusc number (and its index) whose length is greater than any previous fusc number length.") int start = 0 for (int i = 0; i <= 5; i++) { int val = i != 0 ? (int) Math.pow(10, i): -1 for (int j = start; j < FUSC_MAX; j++) { if (fusc[j] > val) { printf("fusc[%,d] =%,d%n", j, fusc[j]) start = j break } } } } private static final int FUSC_MAX = 30000000 private static int[] fusc = new int[FUSC_MAX] static { fusc[0] = 0 fusc[1] = 1 for (int n = 2; n < FUSC_MAX; n++) { int n2 = (int) (n / 2) int n2m = (int) ((n - 1) / 2) int n2p = (int) ((n + 1) / 2) fusc[n] = n % 2 == 0 ? fusc[n2] : fusc[n2m] + fusc[n2p] } } }
803Fusc sequence
7groovy
z4zt5
def genfizzbuzz(factorwords, numbers): factorwords.sort(key=lambda factor_and_word: factor_and_word[0]) lines = [] for num in numbers: words = ''.join(word for factor, word in factorwords if (num% factor) == 0) lines.append(words if words else str(num)) return '\n'.join(lines) if __name__ == '__main__': print(genfizzbuzz([(5, 'Buzz'), (3, 'Fizz'), (7, 'Baxx')], range(1, 21)))
791General FizzBuzz
3python
gxx4h
print "Hello world!\n";
755Hello world/Text
2perl
4xx5d
package main import ( "fmt" "time" ) func indexOf(n int, s []int) int { for i, j := range s { if n == j { return i } } return -1 } func getDigits(n, le int, digits []int) bool { for n > 0 { r := n % 10 if r == 0 || indexOf(r, digits) >= 0 { return false } le-- digits[le] = r n /= 10 } return true } var pows = [5]int{1, 10, 100, 1000, 10000} func removeDigit(digits []int, le, idx int) int { sum := 0 pow := pows[le-2] for i := 0; i < le; i++ { if i == idx { continue } sum += digits[i] * pow pow /= 10 } return sum } func main() { start := time.Now() lims := [5][2]int{ {12, 97}, {123, 986}, {1234, 9875}, {12345, 98764}, {123456, 987653}, } var count [5]int var omitted [5][10]int for i, lim := range lims { nDigits := make([]int, i+2) dDigits := make([]int, i+2) blank := make([]int, i+2) for n := lim[0]; n <= lim[1]; n++ { copy(nDigits, blank) nOk := getDigits(n, i+2, nDigits) if !nOk { continue } for d := n + 1; d <= lim[1]+1; d++ { copy(dDigits, blank) dOk := getDigits(d, i+2, dDigits) if !dOk { continue } for nix, digit := range nDigits { if dix := indexOf(digit, dDigits); dix >= 0 { rn := removeDigit(nDigits, i+2, nix) rd := removeDigit(dDigits, i+2, dix) if float64(n)/float64(d) == float64(rn)/float64(rd) { count[i]++ omitted[i][digit]++ if count[i] <= 12 { fmt.Printf("%d/%d =%d/%d by omitting%d's\n", n, d, rn, rd, digit) } } } } } } fmt.Println() } for i := 2; i <= 6; i++ { fmt.Printf("There are%d%d-digit fractions of which:\n", count[i-2], i) for j := 1; j <= 9; j++ { if omitted[i-2][j] == 0 { continue } fmt.Printf("%6d have%d's omitted\n", omitted[i-2][j], j) } fmt.Println() } fmt.Printf("Took%s\n", time.Since(start)) }
807Fraction reduction
0go
0yesk
fusc :: Int -> Int fusc i | 1 > i = 0 | otherwise = fst $ go (pred i) where go n | 0 == n = (1, 0) | even n = (x + y, y) | otherwise = (x, x + y) where (x, y) = go (div n 2) main :: IO () main = do putStrLn "First 61 terms:" print $ fusc <$> [0 .. 60] putStrLn "\n(Index, Value):" mapM_ print $ take 5 widths widths :: [(Int, Int)] widths = fmap (\(_, i, x) -> (i, x)) (iterate nxtWidth (2, 0, 0)) nxtWidth :: (Int, Int, Int) -> (Int, Int, Int) nxtWidth (w, i, v) = (succ w, j, x) where fi = (,) <*> fusc (j, x) = until ((w <=) . length . show . snd) (fi . succ . fst) (fi i)
803Fusc sequence
8haskell
bibk2
import sys, os import random import time def print_there(x, y, text): sys.stdout.write(% (x, y, text)) sys.stdout.flush() class Ball(): def __init__(self): self.x = 0 self.y = 0 def update(self): self.x += random.randint(0,1) self.y += 1 def fall(self): self.y +=1 class Board(): def __init__(self, width, well_depth, N): self.balls = [] self.fallen = [0] * (width + 1) self.width = width self.well_depth = well_depth self.N = N self.shift = 4 def update(self): for ball in self.balls: if ball.y < self.width: ball.update() elif ball.y < self.width + self.well_depth - self.fallen[ball.x]: ball.fall() elif ball.y == self.width + self.well_depth - self.fallen[ball.x]: self.fallen[ball.x] += 1 else: pass def balls_on_board(self): return len(self.balls) - sum(self.fallen) def add_ball(self): if(len(self.balls) <= self.N): self.balls.append(Ball()) def print_board(self): for y in range(self.width + 1): for x in range(y): print_there( y + 1 ,self.width - y + 2*x + self.shift + 1, ) def print_ball(self, ball): if ball.y <= self.width: x = self.width - ball.y + 2*ball.x + self.shift else: x = 2*ball.x + self.shift y = ball.y + 1 print_there(y, x, ) def print_all(self): print(chr(27) + ) self.print_board(); for ball in self.balls: self.print_ball(ball) def main(): board = Board(width = 15, well_depth = 5, N = 10) board.add_ball() while(board.balls_on_board() > 0): board.print_all() time.sleep(0.25) board.update() board.print_all() time.sleep(0.25) board.update() board.add_ball() if __name__==: main()
798Galton box animation
3python
4wh5k
genFizzBuzz <- function(n, ...) { args <- list(...) factors <- as.integer(sapply(args, "[[", 1)) words <- sapply(args, "[[", 2) sortedPermutation <- sort.list(factors) factors <- factors[sortedPermutation] words <- words[sortedPermutation] for(i in 1:n) { isFactor <- i %% factors == 0 print(if(any(isFactor)) paste0(words[isFactor], collapse = "") else i) } } genFizzBuzz(105, c(3, "Fizz"), c(5, "Buzz"), c(7, "Baxx")) genFizzBuzz(105, c(5, "Buzz"), c(9, "Prax"), c(3, "Fizz"), c(7, "Baxx"))
791General FizzBuzz
13r
v1127
powers = function(m) {n = -1 function() {n <<- n + 1 n^m}} noncubic.squares = local( {squares = powers(2) cubes = powers(3) cube = cubes() function() {square = squares() while (1) {if (square > cube) {cube <<- cubes() next} else if (square < cube) {return(square)} else {square = squares()}}}}) for (i in 1:20) noncubic.squares() for (i in 1:10) message(noncubic.squares())
788Generator/Exponential
13r
iluo5
package main
804Fractal tree
0go
lk9cw
class FractionReduction { static void main(String[] args) { for (int size = 2; size <= 5; size++) { reduce(size) } } private static void reduce(int numDigits) { System.out.printf("Fractions with digits of length%d where cancellation is valid. Examples:%n", numDigits)
807Fraction reduction
7groovy
efkal
use strict; use warnings; use feature 'say'; sub comma { reverse ((reverse shift) =~ s/(.{3})/$1,/gr) =~ s/^,//r } sub is_gapful { my $n = shift; 0 == $n % join('', (split //, $n)[0,-1]) } use constant Inf => 1e10; for ([1e2, 30], [1e6, 15], [1e9, 10], [7123, 25]) { my($start, $count) = @$_; printf "\nFirst $count gapful numbers starting at%s:\n", comma $start; my $n = 0; my $g = ''; $g .= do { $n < $count ? (is_gapful($_) and ++$n and "$_ ") : last } for $start .. Inf; say $g; }
793Gapful numbers
2perl
0m6s4
null
796Generate lower case ASCII alphabet
11kotlin
1d0pd
import Graphics.Gloss type Model = [Picture -> Picture] fractal :: Int -> Model -> Picture -> Picture fractal n model pict = pictures $ take n $ iterate (mconcat model) pict tree1 _ = fractal 10 branches $ Line [(0,0),(0,100)] where branches = [ Translate 0 100 . Scale 0.75 0.75 . Rotate 30 , Translate 0 100 . Scale 0.5 0.5 . Rotate (-30) ] main = animate (InWindow "Tree" (800, 800) (0, 0)) white $ tree1 . (* 60)
804Fractal tree
8haskell
1nbps
import Control.Monad (guard) import Data.List (intersect, unfoldr, delete, nub, group, sort) import Text.Printf (printf) type Fraction = (Int, Int) type Reduction = (Fraction, Fraction, Int) validIntegers :: [Int] -> [Int] validIntegers xs = [x | x <- xs, not $ hasZeros x, hasUniqueDigits x] where hasZeros = elem 0 . digits 10 hasUniqueDigits n = length ds == length ul where ds = digits 10 n ul = nub ds possibleFractions :: [Int] -> [Fraction] possibleFractions = (\ys -> [(n,d) | n <- ys, d <- ys, n < d, gcd n d /= 1]) . validIntegers digits :: Integral a => a -> a -> [a] digits b = unfoldr (\n -> guard (n /= 0) >> pure (n `mod` b, n `div` b)) digitsToIntegral :: Integral a => [a] -> a digitsToIntegral = sum . zipWith (*) (iterate (*10) 1) findReductions :: Fraction -> [Reduction] findReductions z@(n1, d1) = [ (z, (n2, d2), x) | x <- digits 10 n1 `intersect` digits 10 d1, let n2 = dropDigit x n1 d2 = dropDigit x d1 decimalWithDrop = realToFrac n2 / realToFrac d2, decimalWithDrop == decimal ] where dropDigit d = digitsToIntegral . delete d . digits 10 decimal = realToFrac n1 / realToFrac d1 findGroupReductions :: [Int] -> [Reduction] findGroupReductions = (findReductions =<<) . possibleFractions showReduction :: Reduction -> IO () showReduction ((n1,d1),(n2,d2),d) = printf "%d/%d =%d/%d by dropping%d\n" n1 d1 n2 d2 d showCount :: [Reduction] -> Int -> IO () showCount xs n = do printf "There are%d%d-digit fractions of which:\n" (length xs) n mapM_ (uncurry (printf "%5d have%d's omitted\n")) (countReductions xs) >> printf "\n" where countReductions = fmap ((,) . length <*> head) . group . sort . fmap (\(_, _, x) -> x) main :: IO () main = do mapM_ (\g -> mapM_ showReduction (take 12 g) >> printf "\n") groups mapM_ (uncurry showCount) $ zip groups [2..] where groups = [ findGroupReductions [10^1..99], findGroupReductions [10^2..999] , findGroupReductions [10^3..9999], findGroupReductions [10^4..99999] ]
807Fraction reduction
8haskell
ch394
public class FuscSequence { public static void main(String[] args) { System.out.println("Show the first 61 fusc numbers (starting at zero) in a horizontal format"); for ( int n = 0 ; n < 61 ; n++ ) { System.out.printf("%,d ", fusc[n]); } System.out.printf("%n%nShow the fusc number (and its index) whose length is greater than any previous fusc number length.%n"); int start = 0; for (int i = 0 ; i <= 5 ; i++ ) { int val = i != 0 ? (int) Math.pow(10, i) : -1; for ( int j = start ; j < FUSC_MAX ; j++ ) { if ( fusc[j] > val ) { System.out.printf("fusc[%,d] =%,d%n", j, fusc[j] ); start = j; break; } } } } private static final int FUSC_MAX = 30000000; private static int[] fusc = new int[FUSC_MAX]; static { fusc[0] = 0; fusc[1] = 1; for ( int n = 2 ; n < FUSC_MAX ; n++ ) { fusc[n] = (n % 2 == 0 ? fusc[n/2] : fusc[(n-1)/2] + fusc[(n+1)/2]); } } }
803Fusc sequence
9java
gxg4m