code
stringlengths
1
46.1k
label
class label
1.18k classes
domain_label
class label
21 classes
index
stringlengths
4
5
if (condition) { } if (condition) { } else if (condition2) { } else { }
1,023Conditional structures
5c
u7tv4
package main import ( "bufio" "fmt" "log" "os" ) type TokenType int const ( tkEOI TokenType = iota tkMul tkDiv tkMod tkAdd tkSub tkNegate tkNot tkLss tkLeq tkGtr tkGeq tkEq tkNeq tkAssign tkAnd tkOr tkIf tkElse tkWhile tkPrint tkPutc tkLparen tkRparen tkLbrace tkRbrace tkSemi tkComma tkIdent tkInteger tkString ) type Symbol struct { name string tok TokenType }
1,019Compiler/lexical analyzer
0go
9ufmt
package main import "fmt" func combrep(n int, lst []string) [][]string { if n == 0 { return [][]string{nil} } if len(lst) == 0 { return nil } r := combrep(n, lst[1:]) for _, x := range combrep(n-1, lst) { r = append(r, append(x, lst[0])) } return r } func main() { fmt.Println(combrep(2, []string{"iced", "jam", "plain"})) fmt.Println(len(combrep(3, []string{"1", "2", "3", "4", "5", "6", "7", "8", "9", "10"}))) }
1,021Combinations with repetitions
0go
1q4p5
import Control.Applicative hiding (many, some) import Control.Monad.State.Lazy import Control.Monad.Trans.Maybe (MaybeT, runMaybeT) import Data.Char (isAsciiLower, isAsciiUpper, isDigit, ord) import Data.Foldable (asum) import Data.Functor (($>)) import Data.Text (Text) import qualified Data.Text as T import Prelude hiding (lex) import System.Environment (getArgs) import System.IO import Text.Printf data Val = IntVal Int | TextVal String Text | SymbolVal String | Skip | LexError String data Token = Token Val Int Int instance Show Val where show (IntVal value) = printf "%-18s%d\n" "Integer" value show (TextVal "String" value) = printf "%-18s%s\n" "String" (show $ T.unpack value) show (TextVal name value) = printf "%-18s%s\n" name (T.unpack value) show (SymbolVal name ) = printf "%s\n" name show (LexError msg ) = printf "%-18s%s\n" "Error" msg show Skip = printf "" instance Show Token where show (Token val line column) = printf "%2d %2d %s" line column (show val) printTokens :: [Token] -> String printTokens tokens = "Location Token name Value\n" ++ " (concatMap show tokens) makeToken :: Lexer Val -> Lexer Token makeToken lexer = do (t, l, c) <- get val <- lexer case val of Skip -> nextToken LexError msg -> do (_, l', c') <- get let code = T.unpack $ T.take (c' - c + 1) t let str = printf "%s\n%s(%d,%d):%s" msg (replicate 27 ' ') l' c' code ch <- peek unless (ch == '\0') $ advance 1 return $ Token (LexError str) l c _ -> return $ Token val l c simpleToken:: String -> String -> Lexer Val simpleToken lexeme name = lit lexeme $> SymbolVal name makeTokenizers:: [(String, String)] -> Lexer Val makeTokenizers = asum . map (uncurry simpleToken) keywords:: Lexer Val keywords = makeTokenizers [("if", "Keyword_if"), ("else", "Keyword_else"), ("while", "Keyword_while"), ("print", "Keyword_print"), ("putc", "Keyword_putc")] operators:: Lexer Val operators = makeTokenizers [("*", "Op_multiply"), ("/", "Op_divide"), ("%", "Op_mod"), ("+", "Op_add"), ("-", "Op_subtract"), ("<=", "Op_lessequal"), ("<", "Op_less"), (">=", "Op_greaterequal"), (">", "Op_greater"), ("==", "Op_equal"), ("!=", "Op_notequal"), ("!", "Op_not"), ("=", "Op_assign"), ("&&", "Op_and"), ("||", "Op_or")] symbols:: Lexer Val symbols = makeTokenizers [("(", "LeftParen"), (")", "RightParen"), ("{", "LeftBrace"), ("}", "RightBrace"), (";", "Semicolon"), (",", "Comma")] isIdStart:: Char -> Bool isIdStart ch = isAsciiLower ch || isAsciiUpper ch || ch == '_' isIdEnd:: Char -> Bool isIdEnd ch = isIdStart ch || isDigit ch identifier:: Lexer Val identifier = TextVal "Identifier" <$> lexeme where lexeme = T.cons <$> (one isIdStart) <*> (many isIdEnd) integer:: Lexer Val integer = do lexeme <- some isDigit next_ch <- peek if (isIdStart next_ch) then return $ LexError "Invalid number. Starts like a number, but ends in non-numeric characters." else do let num = read (T.unpack lexeme):: Int return $ IntVal num character:: Lexer Val character = do lit "'" str <- lookahead 3 case str of (ch: '\'': _) -> advance 2 $> IntVal (ord ch) "\\n'" -> advance 3 $> IntVal 10 "\\\\'" -> advance 3 $> IntVal 92 ('\\': ch: "\'") -> advance 2 $> LexError (printf "Unknown escape sequence \\%c" ch) ('\'': _) -> return $ LexError "Empty character constant" _ -> advance 2 $> LexError "Multi-character constant" string :: Lexer Val string = do lit "\"" loop (T.pack "") =<< peek where loop t ch = case ch of '\\' -> do next_ch <- next case next_ch of 'n' -> loop (T.snoc t '\n') =<< next '\\' -> loop (T.snoc t '\\') =<< next _ -> return $ LexError $ printf "Unknown escape sequence \\%c" next_ch '"' -> next $> TextVal "String" t '\n' -> return $ LexError $ "End-of-line while scanning string literal." ++ " Closing string character not found before end-of-line." '\0' -> return $ LexError $ "End-of-file while scanning string literal." ++ " Closing string character not found." _ -> loop (T.snoc t ch) =<< next skipComment :: Lexer Val skipComment = do lit "/*" loop =<< peek where loop ch = case ch of '\0' -> return $ LexError "End-of-file in comment. Closing comment characters not found." '*' -> do next_ch <- next case next_ch of '/' -> next $> Skip _ -> loop next_ch _ -> loop =<< next nextToken :: Lexer Token nextToken = do skipWhitespace makeToken $ skipComment <|> keywords <|> identifier <|> integer <|> character <|> string <|> operators <|> symbols <|> simpleToken "\0" "End_of_input" <|> (return $ LexError "Unrecognized character.") main :: IO () main = do args <- getArgs (hin, hout) <- getIOHandles args withHandles hin hout $ printTokens . (lex nextToken) getIOHandles :: [String] -> IO (Handle, Handle) getIOHandles [] = return (stdin, stdout) getIOHandles [infile] = do inhandle <- openFile infile ReadMode return (inhandle, stdout) getIOHandles (infile: outfile: _) = do inhandle <- openFile infile ReadMode outhandle <- openFile outfile WriteMode return (inhandle, outhandle) withHandles :: Handle -> Handle -> (String -> String) -> IO () withHandles in_handle out_handle f = do contents <- hGetContents in_handle let contents' = contents ++ "\0" hPutStr out_handle $ f contents' unless (in_handle == stdin) $ hClose in_handle unless (out_handle == stdout) $ hClose out_handle type LexerState = (Text, Int, Int) type Lexer = MaybeT (State LexerState) lexerAdvance :: Int -> LexerState -> LexerState lexerAdvance 0 ctx = ctx lexerAdvance 1 (t, l, c) | ch == '\n' = (rest, l + 1, 1 ) | otherwise = (rest, l, c + 1) where (ch, rest) = (T.head t, T.tail t) lexerAdvance n ctx = lexerAdvance (n - 1) $ lexerAdvance 1 ctx advance :: Int -> Lexer () advance n = modify $ lexerAdvance n peek :: Lexer Char peek = gets $ \(t, _, _) -> T.head t lookahead :: Int -> Lexer String lookahead n = gets $ \(t, _, _) -> T.unpack $ T.take n t next :: Lexer Char next = advance 1 >> peek skipWhitespace :: Lexer () skipWhitespace = do ch <- peek when (ch `elem` " \n") (next >> skipWhitespace) lit :: String -> Lexer () lit lexeme = do (t, _, _) <- get guard $ T.isPrefixOf (T.pack lexeme) t advance $ length lexeme one :: (Char -> Bool) -> Lexer Char one f = do ch <- peek guard $ f ch next return ch lexerMany :: (Char -> Bool) -> LexerState -> (Text, LexerState) lexerMany f (t, l, c) = (lexeme, (t', l', c')) where (lexeme, _) = T.span f t (t', l', c') = lexerAdvance (T.length lexeme) (t, l, c) many :: (Char -> Bool) -> Lexer Text many f = state $ lexerMany f some :: (Char -> Bool) -> Lexer Text some f = T.cons <$> (one f) <*> (many f) lex :: Lexer a -> String -> [a] lex lexer str = loop lexer (T.pack str, 1, 1) where loop lexer s | T.null txt = [t] | otherwise = t: loop lexer s' where (Just t, s') = runState (runMaybeT lexer) s (txt, _, _) = s'
1,019Compiler/lexical analyzer
8haskell
bw4k2
null
1,017Compare a list of strings
11kotlin
gk24d
combsWithRep :: Int -> [a] -> [[a]] combsWithRep 0 _ = [[]] combsWithRep _ [] = [] combsWithRep k xxs@(x:xs) = (x:) <$> combsWithRep (k - 1) xxs ++ combsWithRep k xs binomial n m = f n `div` f (n - m) `div` f m where f n = if n == 0 then 1 else n * f (n - 1) countCombsWithRep :: Int -> [a] -> Int countCombsWithRep k lst = binomial (k - 1 + length lst) k main :: IO () main = do print $ combsWithRep 2 ["iced", "jam", "plain"] print $ countCombsWithRep 3 [1 .. 10]
1,021Combinations with repetitions
8haskell
tmqf7
use strict; use warnings; showoff( "Permutations", \&P, "P", 1 .. 12 ); showoff( "Combinations", \&C, "C", map $_*10, 1..6 ); showoff( "Permutations", \&P_big, "P", 5, 50, 500, 1000, 5000, 15000 ); showoff( "Combinations", \&C_big, "C", map $_*100, 1..10 ); sub showoff { my ($text, $code, $fname, @n) = @_; print "\nA sample of $text from $n[0] to $n[-1]\n"; for my $n ( @n ) { my $k = int( $n / 3 ); print $n, " $fname $k = ", $code->($n, $k), "\n"; } } sub P { my ($n, $k) = @_; my $x = 1; $x *= $_ for $n - $k + 1 .. $n ; $x; } sub P_big { my ($n, $k) = @_; my $x = 0; $x += log($_) for $n - $k + 1 .. $n ; eshow($x); } sub C { my ($n, $k) = @_; my $x = 1; $x *= ($n - $_ + 1) / $_ for 1 .. $k; $x; } sub C_big { my ($n, $k) = @_; my $x = 0; $x += log($n - $_ + 1) - log($_) for 1 .. $k; exp($x); } sub eshow { my ($x) = @_; my $e = int( $x / log(10) ); sprintf "%.8Fe%+d", exp($x - $e * log(10)), $e; }
1,018Combinations and permutations
2perl
3cizs
null
1,024Comments
5c
gk345
function identical(t_str) _, fst = next(t_str) if fst then for _, i in pairs(t_str) do if i ~= fst then return false end end end return true end function ascending(t_str) prev = false for _, i in ipairs(t_str) do if prev and prev >= i then return false end prev = i end return true end function check(str) t_str = {} for i in string.gmatch(str, "[%a_]+") do table.insert(t_str, i) end str = str .. ": " if not identical(t_str) then str = str .. "not " end str = str .. "identical and " if not ascending(t_str) then str = str .. "not " end print(str .. "ascending.") end check("ayu dab dog gar panda tui yak") check("oy oy oy oy oy oy oy oy oy oy") check("somehow somewhere sometime") check("Hoosiers") check("AA,BB,CC") check("AA,AA,AA") check("AA,CC,BB") check("AA,ACB,BB,CC") check("single_element")
1,017Compare a list of strings
1lua
rbvga
import com.objectwave.utility.*; public class MultiCombinationsTester { public MultiCombinationsTester() throws CombinatoricException { Object[] objects = {"iced", "jam", "plain"};
1,021Combinations with repetitions
9java
8fp06
from __future__ import print_function from scipy.misc import factorial as fact from scipy.misc import comb def perm(N, k, exact=0): return comb(N, k, exact) * fact(k, exact) exact=True print('Sample Perms 1..12') for N in range(1, 13): k = max(N-2, 1) print('%iP%i ='% (N, k), perm(N, k, exact), end=', ' if N% 5 else '\n') print('\n\nSample Combs 10..60') for N in range(10, 61, 10): k = N-2 print('%iC%i ='% (N, k), comb(N, k, exact), end=', ' if N% 50 else '\n') exact=False print('\n\nSample Perms 5..1500 Using FP approximations') for N in [5, 15, 150, 1500, 15000]: k = N-2 print('%iP%i ='% (N, k), perm(N, k, exact)) print('\nSample Combs 100..1000 Using FP approximations') for N in range(100, 1001, 100): k = N-2 print('%iC%i ='% (N, k), comb(N, k, exact))
1,018Combinations and permutations
3python
6ln3w
null
1,019Compiler/lexical analyzer
9java
gkc4m
(if (= 1 1):yes:no) (if (= 1 2):yes:no) (if (= 1 2):yes)
1,023Conditional structures
6clojure
7pmr0
<html><head><title>Donuts</title></head> <body><pre id='x'></pre><script type="application/javascript"> function disp(x) { var e = document.createTextNode(x + '\n'); document.getElementById('x').appendChild(e); } function pick(n, got, pos, from, show) { var cnt = 0; if (got.length == n) { if (show) disp(got.join(' ')); return 1; } for (var i = pos; i < from.length; i++) { got.push(from[i]); cnt += pick(n, got, i, from, show); got.pop(); } return cnt; } disp(pick(2, [], 0, ["iced", "jam", "plain"], true) + " combos"); disp("pick 3 out of 10: " + pick(3, [], 0, "a123456789".split(''), false) + " combos"); </script></body></html>
1,021Combinations with repetitions
10javascript
fyxdg
perm <- function(n, k) choose(n, k) * factorial(k) print(perm(seq(from = 3, to = 12, by = 3), seq(from = 2, to = 8, by = 2))) print(choose(seq(from = 10, to = 60, by = 10), seq(from = 3, to = 18, by = 3))) print(perm(seq(from = 1500, to = 15000, by = 1500), seq(from = 55, to = 100, by = 5))) print(choose(seq(from = 100, to = 1000, by = 150), seq(from = 70, to = 100, by = 5)))
1,018Combinations and permutations
13r
fy0dc
const TokenType = { Keyword_if: 1, Keyword_else: 2, Keyword_print: 3, Keyword_putc: 4, Keyword_while: 5, Op_add: 6, Op_and: 7, Op_assign: 8, Op_divide: 9, Op_equal: 10, Op_greater: 11, Op_greaterequal: 12, Op_less: 13, Op_Lessequal: 14, Op_mod: 15, Op_multiply: 16, Op_not: 17, Op_notequal: 18, Op_or: 19, Op_subtract: 20, Integer: 21, String: 22, Identifier: 23, Semicolon: 24, Comma: 25, LeftBrace: 26, RightBrace: 27, LeftParen: 28, RightParen: 29, End_of_input: 99 } class Lexer { constructor(source) { this.source = source this.pos = 1
1,019Compiler/lexical analyzer
10javascript
ke5hq
(defn foo [] 123)
1,024Comments
6clojure
kechs
package main import ( "fmt" "os" ) func main() { for i, x := range os.Args[1:] { fmt.Printf("the argument #%d is%s\n", i, x) } }
1,020Command-line arguments
0go
l4tcw
println args
1,020Command-line arguments
7groovy
6lo3o
package main import ( "bytes" "fmt" "math/rand" "time" ) type Field struct { s [][]bool w, h int } func NewField(w, h int) Field { s := make([][]bool, h) for i := range s { s[i] = make([]bool, w) } return Field{s: s, w: w, h: h} } func (f Field) Set(x, y int, b bool) { f.s[y][x] = b } func (f Field) Next(x, y int) bool { on := 0 for i := -1; i <= 1; i++ { for j := -1; j <= 1; j++ { if f.State(x+i, y+j) && !(j == 0 && i == 0) { on++ } } } return on == 3 || on == 2 && f.State(x, y) } func (f Field) State(x, y int) bool { for y < 0 { y += f.h } for x < 0 { x += f.w } return f.s[y%f.h][x%f.w] } type Life struct { w, h int a, b Field } func NewLife(w, h int) *Life { a := NewField(w, h) for i := 0; i < (w * h / 2); i++ { a.Set(rand.Intn(w), rand.Intn(h), true) } return &Life{ a: a, b: NewField(w, h), w: w, h: h, } } func (l *Life) Step() { for y := 0; y < l.h; y++ { for x := 0; x < l.w; x++ { l.b.Set(x, y, l.a.Next(x, y)) } } l.a, l.b = l.b, l.a } func (l *Life) String() string { var buf bytes.Buffer for y := 0; y < l.h; y++ { for x := 0; x < l.w; x++ { b := byte(' ') if l.a.State(x, y) { b = '*' } buf.WriteByte(b) } buf.WriteByte('\n') } return buf.String() } func main() { l := NewLife(80, 15) for i := 0; i < 300; i++ { l.Step() fmt.Print("\x0c") fmt.Println(l) time.Sleep(time.Second / 30) } }
1,014Conway's Game of Life
0go
xoewf
null
1,021Combinations with repetitions
11kotlin
w87ek
null
1,019Compiler/lexical analyzer
11kotlin
2g3li
import System main = getArgs >>= print
1,020Command-line arguments
8haskell
1qgps
class GameOfLife { int generations int dimensions def board GameOfLife(generations = 5, dimensions = 5) { this.generations = generations this.dimensions = dimensions this.board = createBlinkerBoard() } static def createBlinkerBoard() { [ [].withDefault{0}, [0,0,1].withDefault{0}, [0,0,1].withDefault{0}, [0,0,1].withDefault{0} ].withDefault{[]} } static def createGliderBoard() { [ [].withDefault{0}, [0,0,1].withDefault{0}, [0,0,0,1].withDefault{0}, [0,1,1,1].withDefault{0} ].withDefault{[]} } static def getValue(board, point) { def x,y (x,y) = point if(x < 0 || y < 0) { return 0 } board[x][y] ? 1: 0 } static def countNeighbors(board, point) { def x,y (x,y) = point def neighbors = 0 neighbors += getValue(board, [x-1,y-1]) neighbors += getValue(board, [x-1,y]) neighbors += getValue(board, [x-1,y+1]) neighbors += getValue(board, [x,y-1]) neighbors += getValue(board, [x,y+1]) neighbors += getValue(board, [x+1,y-1]) neighbors += getValue(board, [x+1,y]) neighbors += getValue(board, [x+1,y+1]) neighbors } static def conwaysRule(currentValue, neighbors) { def newValue = 0 if(neighbors == 3 || (currentValue && neighbors == 2)) { newValue = 1 } newValue } static def createNextGeneration(currentBoard, dimensions) { def newBoard = [].withDefault{[].withDefault{0}} (0..(dimensions-1)).each { row -> (0..(dimensions-1)).each { column -> def point = [row, column] def currentValue = getValue(currentBoard, point) def neighbors = countNeighbors(currentBoard, point) newBoard[row][column] = conwaysRule(currentValue, neighbors) } } newBoard } static def printBoard(generationCount, board, dimensions) { println "Generation ${generationCount}" println '*' * 80 (0..(dimensions-1)).each { row -> (0..(dimensions-1)).each { column -> print board[row][column] ? 'X': '.' } print System.getProperty('line.separator') } println '' } def start() { (1..generations).each { generation -> printBoard(generation, this.board, this.dimensions) this.board = createNextGeneration(this.board, this.dimensions) } } }
1,014Conway's Game of Life
7groovy
pxkbo
include Math class Integer def permutation(k) (self-k+1 .. self).inject(:*) end def combination(k) self.permutation(k) / (1 .. k).inject(:*) end def big_permutation(k) exp( lgamma_plus(self) - lgamma_plus(self -k)) end def big_combination(k) exp( lgamma_plus(self) - lgamma_plus(self - k) - lgamma_plus(k)) end private def lgamma_plus(n) lgamma(n+1)[0] end end p 12.permutation(9) p 12.big_permutation(9) p 60.combination(53) p 145.big_permutation(133) p 900.big_combination(450) p 1000.big_combination(969) p 15000.big_permutation(73) p 15000.big_permutation(74) p 15000.permutation(74)
1,018Combinations and permutations
14ruby
mvfyj
null
1,019Compiler/lexical analyzer
1lua
vr62x
import Data.Array.Unboxed type Grid = UArray (Int,Int) Bool life :: Int -> Int -> Grid -> Grid life w h old = listArray b (map f (range b)) where b@((y1,x1),(y2,x2)) = bounds old f (y, x) = ( c && (n == 2 || n == 3) ) || ( not c && n == 3 ) where c = get x y n = count [get (x + x') (y + y') | x' <- [-1, 0, 1], y' <- [-1, 0, 1], not (x' == 0 && y' == 0)] get x y | x < x1 || x > x2 = False | y < y1 || y > y2 = False | otherwise = old ! (y, x) count :: [Bool] -> Int count = length . filter id
1,014Conway's Game of Life
8haskell
y2366
function GenerateCombinations(tList, nMaxElements, tOutput, nStartIndex, nChosen, tCurrentCombination) if not nStartIndex then nStartIndex = 1 end if not nChosen then nChosen = 0 end if not tOutput then tOutput = {} end if not tCurrentCombination then tCurrentCombination = {} end if nChosen == nMaxElements then
1,021Combinations with repetitions
1lua
xojwz
null
1,024Comments
18dart
l4ict
use List::Util 1.33 qw(all); all { $strings[0] eq $strings[$_] } 1..$ all { $strings[$_-1] lt $strings[$_] } 1..$
1,017Compare a list of strings
2perl
n3siw
public class Arguments { public static void main(String[] args) { System.out.println("There are " + args.length + " arguments given."); for(int i = 0; i < args.length; i++) System.out.println("The argument #" + (i+1) + " is " + args[i] + " and is at index " + i); } }
1,020Command-line arguments
9java
7plrj
process.argv.forEach((val, index) => { console.log(`${index}: ${val}`); });
1,020Command-line arguments
10javascript
px4b7
import BigInt func permutations(n: Int, k: Int) -> BigInt { let l = n - k + 1 guard l <= n else { return 1 } return (l...n).reduce(BigInt(1), { $0 * BigInt($1) }) } func combinations(n: Int, k: Int) -> BigInt { let fact = {() -> BigInt in guard k > 1 else { return 1 } return (2...k).map({ BigInt($0) }).reduce(1, *) }() return permutations(n: n, k: k) / fact } print("Sample of permutations from 1 to 12") for i in 1...12 { print("\(i) P \(i / 3) = \(permutations(n: i, k: i / 3))") } print("\nSample of combinations from 10 to 60") for i in stride(from: 10, through: 60, by: 10) { print("\(i) C \(i / 3) = \(combinations(n: i, k: i / 3))") } print("\nSample of permutations from 5 to 15,000") for i in [5, 50, 500, 1000, 5000, 15000] { let k = i / 3 let res = permutations(n: i, k: k).description let extra = res.count > 40? "... (\(res.count - 40) more digits)": "" print("\(i) P \(k) = \(res.prefix(40))\(extra)") } print("\nSample of combinations from 100 to 1000") for i in stride(from: 100, through: 1000, by: 100) { let k = i / 3 let res = combinations(n: i, k: k).description let extra = res.count > 40? "... (\(res.count - 40) more digits)": "" print("\(i) C \(k) = \(res.prefix(40))\(extra)") }
1,018Combinations and permutations
17swift
y2d6e
package main import ( "fmt" "strings" ) func q(s []string) string { switch len(s) { case 0: return "{}" case 1: return "{" + s[0] + "}" case 2: return "{" + s[0] + " and " + s[1] + "}" default: return "{" + strings.Join(s[:len(s)-1], ", ") + " and " + s[len(s)-1] + "}" } } func main() { fmt.Println(q([]string{})) fmt.Println(q([]string{"ABC"})) fmt.Println(q([]string{"ABC", "DEF"})) fmt.Println(q([]string{"ABC", "DEF", "G", "H"})) }
1,022Comma quibbling
0go
snhqa
fun main(args: Array<String>) { println("There are " + args.size + " arguments given.") args.forEachIndexed { i, a -> println("The argument #${i+1} is $a and is at index $i") } }
1,020Command-line arguments
11kotlin
u76vc
def commaQuibbling = { it.size() < 2 ? "{${it.join(', ')}}": "{${it[0..-2].join(', ')} and ${it[-1]}}" }
1,022Comma quibbling
7groovy
as41p
quibble ws = "{" ++ quibbles ws ++ "}" where quibbles [] = "" quibbles [a] = a quibbles [a,b] = a ++ " and " ++ b quibbles (a:bs) = a ++ ", " ++ quibbles bs main = mapM_ (putStrLn . quibble) $ [[], ["ABC"], ["ABC", "DEF"], ["ABC", "DEF", "G", "H"]] ++ (map words ["One two three four", "Me myself I", "Jack Jill", "Loner" ])
1,022Comma quibbling
8haskell
9uimo
sub p { $_[0] ? map p($_[0] - 1, [@{$_[1]}, $_[$_]], @_[$_ .. $ sub f { $_[0] ? $_[0] * f($_[0] - 1) : 1 } sub pn{ f($_[0] + $_[1] - 1) / f($_[0]) / f($_[1] - 1) } for (p(2, [], qw(iced jam plain))) { print "@$_\n"; } printf "\nThere are%d ways to pick 7 out of 10\n", pn(7,10);
1,021Combinations with repetitions
2perl
l4fc5
public class GameOfLife{ public static void main(String[] args){ String[] dish= { "_#_", "_#_", "_#_",}; int gens= 3; for(int i= 0;i < gens;i++){ System.out.println("Generation " + i + ":"); print(dish); dish= life(dish); } } public static String[] life(String[] dish){ String[] newGen= new String[dish.length]; for(int row= 0;row < dish.length;row++){
1,014Conway's Game of Life
9java
d6in9
public class Quibbler { public static String quibble(String[] words) { String qText = "{"; for(int wIndex = 0; wIndex < words.length; wIndex++) { qText += words[wIndex] + (wIndex == words.length-1 ? "" : wIndex == words.length-2 ? " and " : ", "; } qText += "}"; return qText; } public static void main(String[] args) { System.out.println(quibble(new String[]{})); System.out.println(quibble(new String[]{"ABC"})); System.out.println(quibble(new String[]{"ABC", "DEF"})); System.out.println(quibble(new String[]{"ABC", "DEF", "G"})); System.out.println(quibble(new String[]{"ABC", "DEF", "G", "H"})); } }
1,022Comma quibbling
9java
tmxf9
<?php function combos($arr, $k) { if ($k == 0) { return array(array()); } if (count($arr) == 0) { return array(); } $head = $arr[0]; $combos = array(); $subcombos = combos($arr, $k-1); foreach ($subcombos as $subcombo) { array_unshift($subcombo, $head); $combos[] = $subcombo; } array_shift($arr); $combos = array_merge($combos, combos($arr, $k)); return $combos; } $arr = array(, , ); $result = combos($arr, 2); foreach($result as $combo) { echo implode(' ', $combo), ; } $donuts = range(1, 10); $num_donut_combos = count(combos($donuts, 3)); echo ; ?>
1,021Combinations with repetitions
12php
qihx3
use strict; use warnings; no warnings 'once'; my @tokens = ( ['Op_multiply' , '*' , ], ['Op_divide' , '/' , ], ['Op_mod' , '%' , ], ['Op_add' , '+' , ], ['Op_subtract' , '-' , ], ['Op_lessequal' , '<=' , ], ['Op_less' , '<' , ], ['Op_greaterequal', '>=' , ], ['Op_greater' , '>' , ], ['Op_equal' , '==' , ], ['Op_assign' , '=' , ], ['Op_not' , '!' , ], ['Op_notequal' , '!=' , ], ['Op_and' , '&&' , ], ['Op_or' , '||' , ], ['Keyword_else' , qr/else\b/ , ], ['Keyword_if' , qr/if\b/ , ], ['Keyword_while' , qr/while\b/ , ], ['Keyword_print' , qr/print\b/ , ], ['Keyword_putc' , qr/putc\b/ , ], ['LeftParen' , '(' , ], ['RightParen' , ')' , ], ['LeftBrace' , '{' , ], ['RightBrace' , '}' , ], ['Semicolon' , ';' , ], ['Comma' , ',' , ], ['Identifier' , qr/[_a-z][_a-z0-9]*/i, \&raw ], ['Integer' , qr/[0-9]+\b/ , \&raw ], ['Integer' , qr/'([^']*)(')?/ , \&char_val ], ['String' , qr/"([^"]*)(")?/ , \&string_raw], ['End_of_input' , qr/$/ , ], ); my $comment = qr/\/\* .+? (?: \*\/ | $ (?{die "End-of-file in comment\n"}) )/xs; my $whitespace = qr/(?: \s | $comment)*/x; my $unrecognized = qr/\w+ | ./x; sub char_val { my $str = string_val(); die "Multiple characters\n" if length $str > 1; die "No character\n" if length $str == 0; ord $str; } sub string_val { my ($str, $end) = ($1, $2); die "End-of-file\n" if not defined $end; die "End-of-line\n" if $str =~ /\n/; $str =~ s/\\(.)/ $1 eq 'n' ? "\n" : $1 eq '\\' ? $1 : $1 eq $end ? $1 : die "Unknown escape sequence \\$1\n" /rge; } sub raw { $& } sub string_raw { string_val(); $&; } my $tokens = join "|", map { my $format = $tokens[$_][1]; "\n".(ref $format ? $format : quotemeta $format)." (*MARK:$_) "; } 0..$ my $regex = qr/ \G (?| $whitespace \K (?| $tokens ) | $whitespace? \K ($unrecognized) (*MARK:!) ) /x; my $input = do { local $/ = undef; <STDIN> }; my $pos = 0; my $linecol = linecol_accumulator(); while ($input =~ /$regex/g) { my ($line, $col) = $linecol->(substr $input, $pos, $-[0] - $pos); $pos = $-[0]; my $type = $main::REGMARK; die "Unrecognized token $1 at line $line, col $col\n" if $type eq '!'; my ($name, $evaluator) = @{$tokens[$type]}[0, 2]; my $value; if ($evaluator) { eval { $value = $evaluator->() }; if ($@) { chomp $@; die "$@ in $name at line $line, col $col\n" } } print "$line\t$col\t$name".($value ? "\t$value" : '')."\n"; } sub linecol_accumulator { my ($line, $col) = (1, 1); sub { my $str = shift; my @lines = split "\n", $str, -1; my ($l, $c) = @lines ? (@lines - 1, length $lines[-1]) : (0, 0); if ($l) { $line += $l; $col = 1 + $c } else { $col += $c } ($line, $col) } }
1,019Compiler/lexical analyzer
2perl
snpq3
print( "Program name:", arg[0] ) print "Arguments:" for i = 1, #arg do print( i," ", arg[i] ) end
1,020Command-line arguments
1lua
5jyu6
function GameOfLife () { this.init = function (turns,width,height) { this.board = new Array(height); for (var x = 0; x < height; x++) { this.board[x] = new Array(width); for (var y = 0; y < width; y++) { this.board[x][y] = Math.round(Math.random()); } } this.turns = turns; } this.nextGen = function() { this.boardNext = new Array(this.board.length); for (var i = 0; i < this.board.length; i++) { this.boardNext[i] = new Array(this.board[i].length); } for (var x = 0; x < this.board.length; x++) { for (var y = 0; y < this.board[x].length; y++) { var n = 0; for (var dx = -1; dx <= 1; dx++) { for (var dy = -1; dy <= 1; dy++) { if ( dx == 0 && dy == 0){} else if (typeof this.board[x+dx] !== 'undefined' && typeof this.board[x+dx][y+dy] !== 'undefined' && this.board[x+dx][y+dy]) { n++; } } } var c = this.board[x][y]; switch (n) { case 0: case 1: c = 0; break; case 2: break; case 3: c = 1; break; default: c = 0; } this.boardNext[x][y] = c; } } this.board = this.boardNext.slice(); } this.print = function() { for (var x = 0; x < this.board.length; x++) { var l = ""; for (var y = 0; y < this.board[x].length; y++) { if (this.board[x][y]) l += "X"; else l += " "; } print(l); } } this.start = function() { for (var t = 0; t < this.turns; t++) { print("---\nTurn "+(t+1)); this.print(); this.nextGen() } } } var game = new GameOfLife(); print("---\n3x3 Blinker over three turns."); game.init(3); game.board = [ [0,0,0], [1,1,1], [0,0,0]]; game.start(); print("---\n10x6 Glider over five turns."); game.init(5); game.board = [ [0,0,0,0,0,0,0,0,0,0], [0,0,1,0,0,0,0,0,0,0], [0,0,0,1,0,0,0,0,0,0], [0,1,1,1,0,0,0,0,0,0], [0,0,0,0,0,0,0,0,0,0], [0,0,0,0,0,0,0,0,0,0]]; game.start(); print("---\nRandom 5x10"); game.init(5,5,10); game.start();
1,014Conway's Game of Life
10javascript
6lz38
function quibble(words) { return "{" + words.slice(0, words.length-1).join(",") + (words.length > 1 ? " and " : "") + (words[words.length-1] || '') + "}"; } [[], ["ABC"], ["ABC", "DEF"], ["ABC", "DEF", "G", "H"]].forEach( function(s) { console.log(quibble(s)); } );
1,022Comma quibbling
10javascript
mvoyv
all(a == nexta for a, nexta in zip(strings, strings[1:])) all(a < nexta for a, nexta in zip(strings, strings[1:])) len(set(strings)) == 1 sorted(strings, reverse=True) == strings
1,017Compare a list of strings
3python
d60n1
chunks <- function (compare, xs) { starts = which(c(T,!compare(head(xs, -1), xs[-1]), T)) lapply(seq(1,length(starts)-1), function(i) xs[starts[i]:(starts[i+1]-1)] ) }
1,017Compare a list of strings
13r
8fw0x
null
1,022Comma quibbling
11kotlin
otp8z
>>> from itertools import combinations_with_replacement >>> n, k = 'iced jam plain'.split(), 2 >>> list(combinations_with_replacement(n,k)) [('iced', 'iced'), ('iced', 'jam'), ('iced', 'plain'), ('jam', 'jam'), ('jam', 'plain'), ('plain', 'plain')] >>> >>> len(list(combinations_with_replacement(range(10), 3))) 220 >>>
1,021Combinations with repetitions
3python
2gtlz
from __future__ import print_function import sys tk_EOI, tk_Mul, tk_Div, tk_Mod, tk_Add, tk_Sub, tk_Negate, tk_Not, tk_Lss, tk_Leq, tk_Gtr, \ tk_Geq, tk_Eq, tk_Neq, tk_Assign, tk_And, tk_Or, tk_If, tk_Else, tk_While, tk_Print, \ tk_Putc, tk_Lparen, tk_Rparen, tk_Lbrace, tk_Rbrace, tk_Semi, tk_Comma, tk_Ident, \ tk_Integer, tk_String = range(31) all_syms = [, , , , , , , , , , , , , , , , , , , , , , , , , , , , , , ] symbols = { '{': tk_Lbrace, '}': tk_Rbrace, '(': tk_Lparen, ')': tk_Rparen, '+': tk_Add, '-': tk_Sub, '*': tk_Mul, '%': tk_Mod, ';': tk_Semi, ',': tk_Comma } key_words = {'if': tk_If, 'else': tk_Else, 'print': tk_Print, 'putc': tk_Putc, 'while': tk_While} the_ch = the_col = 0 the_line = 1 input_file = None def error(line, col, msg): print(line, col, msg) exit(1) def next_ch(): global the_ch, the_col, the_line the_ch = input_file.read(1) the_col += 1 if the_ch == '\n': the_line += 1 the_col = 0 return the_ch def char_lit(err_line, err_col): n = ord(next_ch()) if the_ch == '\'': error(err_line, err_col, ) elif the_ch == '\\': next_ch() if the_ch == 'n': n = 10 elif the_ch == '\\': n = ord('\\') else: error(err_line, err_col, % (the_ch)) if next_ch() != '\'': error(err_line, err_col, ) next_ch() return tk_Integer, err_line, err_col, n def div_or_cmt(err_line, err_col): if next_ch() != '*': return tk_Div, err_line, err_col next_ch() while True: if the_ch == '*': if next_ch() == '/': next_ch() return gettok() elif len(the_ch) == 0: error(err_line, err_col, ) else: next_ch() def string_lit(start, err_line, err_col): global the_ch text = while next_ch() != start: if len(the_ch) == 0: error(err_line, err_col, ) if the_ch == '\n': error(err_line, err_col, ) if the_ch == '\\': next_ch() if the_ch != 'n': error(err_line, err_col, % the_ch) the_ch = '\n' text += the_ch next_ch() return tk_String, err_line, err_col, text def ident_or_int(err_line, err_col): is_number = True text = while the_ch.isalnum() or the_ch == '_': text += the_ch if not the_ch.isdigit(): is_number = False next_ch() if len(text) == 0: error(err_line, err_col, % (ord(the_ch), the_ch)) if text[0].isdigit(): if not is_number: error(err_line, err_col, % (text)) n = int(text) return tk_Integer, err_line, err_col, n if text in key_words: return key_words[text], err_line, err_col return tk_Ident, err_line, err_col, text def follow(expect, ifyes, ifno, err_line, err_col): if next_ch() == expect: next_ch() return ifyes, err_line, err_col if ifno == tk_EOI: error(err_line, err_col, % (ord(the_ch), the_ch)) return ifno, err_line, err_col def gettok(): while the_ch.isspace(): next_ch() err_line = the_line err_col = the_col if len(the_ch) == 0: return tk_EOI, err_line, err_col elif the_ch == '/': return div_or_cmt(err_line, err_col) elif the_ch == '\'': return char_lit(err_line, err_col) elif the_ch == '<': return follow('=', tk_Leq, tk_Lss, err_line, err_col) elif the_ch == '>': return follow('=', tk_Geq, tk_Gtr, err_line, err_col) elif the_ch == '=': return follow('=', tk_Eq, tk_Assign, err_line, err_col) elif the_ch == '!': return follow('=', tk_Neq, tk_Not, err_line, err_col) elif the_ch == '&': return follow('&', tk_And, tk_EOI, err_line, err_col) elif the_ch == '|': return follow('|', tk_Or, tk_EOI, err_line, err_col) elif the_ch == 'rCan't open%s%5d %5d %-14s %5d %s%s") if tok == tk_EOI: break
1,019Compiler/lexical analyzer
3python
0d1sq
library(gtools) combinations(3, 2, c("iced", "jam", "plain"), set = FALSE, repeats.allowed = TRUE) nrow(combinations(10, 3, repeats.allowed = TRUE))
1,021Combinations with repetitions
13r
mviy4
null
1,014Conway's Game of Life
11kotlin
0dqsf
function quibble (strTab) local outString, join = "{" for strNum = 1, #strTab do if strNum == #strTab then join = "" elseif strNum == #strTab - 1 then join = " and " else join = ", " end outString = outString .. strTab[strNum] .. join end return outString .. '}' end local testCases = { {}, {"ABC"}, {"ABC", "DEF"}, {"ABC", "DEF", "G", "H"} } for _, input in pairs(testCases) do print(quibble(input)) end
1,022Comma quibbling
1lua
iz1ot
local function T2D(w,h) local t={} for y=1,h do t[y]={} for x=1,w do t[y][x]=0 end end return t end local Life = { new = function(self,w,h) return setmetatable({ w=w, h=h, gen=1, curr=T2D(w,h), next=T2D(w,h)}, {__index=self}) end, set = function(self, coords) for i = 1, #coords, 2 do self.curr[coords[i+1]][coords[i]] = 1 end end, evolve = function(self) local curr, next = self.curr, self.next local ym1, y, yp1 = self.h-1, self.h, 1 for i = 1, self.h do local xm1, x, xp1 = self.w-1, self.w, 1 for j = 1, self.w do local sum = curr[ym1][xm1] + curr[ym1][x] + curr[ym1][xp1] + curr[y][xm1] + curr[y][xp1] + curr[yp1][xm1] + curr[yp1][x] + curr[yp1][xp1] next[y][x] = ((sum==2) and curr[y][x]) or ((sum==3) and 1) or 0 xm1, x, xp1 = x, xp1, xp1+1 end ym1, y, yp1 = y, yp1, yp1+1 end self.curr, self.next, self.gen = self.next, self.curr, self.gen+1 end, render = function(self) print("Generation "..self.gen..":") for y = 1, self.h do for x = 1, self.w do io.write(self.curr[y][x]==0 and " " or " ") end print() end end }
1,014Conway's Game of Life
1lua
8fs0e
strings.uniq.one? strings == strings.uniq.sort
1,017Compare a list of strings
14ruby
tmof2
fn strings_are_equal(seq: &[&str]) -> bool { match seq { &[] | &[_] => true, &[x, y, ref tail@ ..] if x == y => strings_are_equal(&[&[y], tail].concat()), _ => false } } fn asc_strings(seq: &[&str]) -> bool { match seq { &[] | &[_] => true, &[x, y, ref tail @ ..] if x < y => asc_strings(&[&[y], tail].concat()), _ => false } }
1,017Compare a list of strings
15rust
z9ito
possible_doughnuts = ['iced', 'jam', 'plain'].repeated_combination(2) puts possible_doughnuts.each{|doughnut_combi| puts doughnut_combi.join(' and ')} possible_doughnuts = [*1..1000].repeated_combination(30) puts ,
1,021Combinations with repetitions
14ruby
u73vz
def strings_are_equal(seq:List[String]):Boolean = seq match { case Nil => true case s::Nil => true case el1 :: el2 :: tail => el1==el2 && strings_are_equal(el2::tail) } def asc_strings(seq:List[String]):Boolean = seq match { case Nil => true case s::Nil => true case el1 :: el2 :: tail => el1.compareTo(el2) < 0 }
1,017Compare a list of strings
16scala
y2f63
null
1,021Combinations with repetitions
15rust
5j6uq
object CombinationsWithRepetition { def multi[A](as: List[A], k: Int): List[List[A]] = (List.fill(k)(as)).flatten.combinations(k).toList def main(args: Array[String]): Unit = { val doughnuts = multi(List("iced", "jam", "plain"), 2) for (combo <- doughnuts) println(combo.mkString(",")) val bonus = multi(List(0,1,2,3,4,5,6,7,8,9), 3).size println("There are "+bonus+" ways to choose 3 items from 10 choices") } }
1,021Combinations with repetitions
16scala
rb9gn
package xyz.hyperreal.rosettacodeCompiler import scala.io.Source import scala.util.matching.Regex object LexicalAnalyzer { private val EOT = '\u0004' val symbols = Map( "*" -> "Op_multiply", "/" -> "Op_divide", "%" -> "Op_mod", "+" -> "Op_add", "-" -> "Op_minus", "<" -> "Op_less", "<=" -> "Op_lessequal", ">" -> "Op_greater", ">=" -> "Op_greaterequal", "==" -> "Op_equal", "!=" -> "Op_notequal", "!" -> "Op_not", "=" -> "Op_assign", "&&" -> "Op_and", "" -> "Op_or", "(" -> "LeftParen", ")" -> "RightParen", "{" -> "LeftBrace", "}" -> "RightBrace", ";" -> "Semicolon", "," -> "Comma" ) val keywords = Map( "if" -> "Keyword_if", "else" -> "Keyword_else", "while" -> "Keyword_while", "print" -> "Keyword_print", "putc" -> "Keyword_putc" ) val alpha = ('a' to 'z' toSet) ++ ('A' to 'Z') val numeric = '0' to '9' toSet val alphanumeric = alpha ++ numeric val identifiers = StartRestToken("Identifier", alpha + '_', alphanumeric + '_') val integers = SimpleToken("Integer", numeric, alpha, "alpha characters may not follow right after a number") val characters = DelimitedToken("Integer", '\'', "[^'\\n]|\\\\n|\\\\\\\\" r, "invalid character literal", "unclosed character literal") val strings = DelimitedToken("String", '"', "[^\"\\n]*" r, "invalid string literal", "unclosed string literal") def apply = new LexicalAnalyzer(4, symbols, keywords, "End_of_input", identifiers, integers, characters, strings) abstract class Token case class StartRestToken(name: String, start: Set[Char], rest: Set[Char]) extends Token case class SimpleToken(name: String, chars: Set[Char], exclude: Set[Char], excludeError: String) extends Token case class DelimitedToken(name: String, delimiter: Char, pattern: Regex, patternError: String, unclosedError: String) extends Token } class LexicalAnalyzer(tabs: Int, symbols: Map[String, String], keywords: Map[String, String], endOfInput: String, identifier: LexicalAnalyzer.Token, tokens: LexicalAnalyzer.Token*) { import LexicalAnalyzer._ private val symbolStartChars = symbols.keys map (_.head) toSet private val symbolChars = symbols.keys flatMap (_.toList) toSet private var curline: Int = _ private var curcol: Int = _ def fromStdin = fromSource(Source.stdin) def fromString(src: String) = fromSource(Source.fromString(src)) def fromSource(ast: Source) = { curline = 1 curcol = 1 var s = (ast ++ Iterator(EOT)) map (new Chr(_)) toStream tokenize def token(name: String, first: Chr) = println(f"${first.line}%5d ${first.col}%6d $name") def value(name: String, v: String, first: Chr) = println(f"${first.line}%5d ${first.col}%6d $name%-14s $v") def until(c: Char) = { val buf = new StringBuilder def until: String = if (s.head.c == EOT || s.head.c == c) buf.toString else { buf += getch until } until } def next = s = s.tail def getch = { val c = s.head.c next c } def consume(first: Char, cs: Set[Char]) = { val buf = new StringBuilder def consume: String = if (s.head.c == EOT || !cs(s.head.c)) buf.toString else { buf += getch consume } buf += first consume } def comment(start: Chr): Unit = { until('*') if (s.head.c == EOT || s.tail.head.c == EOT) sys.error(s"unclosed comment ${start.at}") else if (s.tail.head.c != '/') { next comment(start) } else { next next } } def recognize(t: Token): Option[(String, String)] = { val first = s next t match { case StartRestToken(name, start, rest) => if (start(first.head.c)) Some((name, consume(first.head.c, rest))) else { s = first None } case SimpleToken(name, chars, exclude, excludeError) => if (chars(first.head.c)) { val m = consume(first.head.c, chars) if (exclude(s.head.c)) sys.error(s"$excludeError ${s.head.at}") else Some((name, m)) } else { s = first None } case DelimitedToken(name, delimiter, pattern, patternError, unclosedError) => if (first.head.c == delimiter) { val m = until(delimiter) if (s.head.c != delimiter) sys.error(s"$unclosedError ${first.head.at}") else if (pattern.pattern.matcher(m).matches) { next Some((name, s"$delimiter$m$delimiter")) } else sys.error(s"$patternError ${s.head.at}") } else { s = first None } } } def tokenize: Unit = if (s.head.c == EOT) token(endOfInput, s.head) else { if (s.head.c.isWhitespace) next else if (s.head.c == '/' && s.tail.head.c == '*') comment(s.head) else if (symbolStartChars(s.head.c)) { val first = s.head val buf = new StringBuilder while (!symbols.contains(buf.toString) && s.head.c != EOT && symbolChars(s.head.c)) buf += getch while (symbols.contains(buf.toString :+ s.head.c) && s.head.c != EOT && symbolChars(s.head.c)) buf += getch symbols get buf.toString match { case Some(name) => token(name, first) case None => sys.error(s"unrecognized symbol: '${buf.toString}' ${first.at}") } } else { val first = s.head recognize(identifier) match { case None => find(0) @scala.annotation.tailrec def find(t: Int): Unit = if (t == tokens.length) sys.error(s"unrecognized character ${first.at}") else recognize(tokens(t)) match { case None => find(t + 1) case Some((name, v)) => value(name, v, first) } case Some((name, ident)) => keywords get ident match { case None => value(name, ident, first) case Some(keyword) => token(keyword, first) } } } tokenize } } private class Chr(val c: Char) { val line = curline val col = curcol if (c == '\n') { curline += 1 curcol = 1 } else if (c == '\r') curcol = 1 else if (c == '\t') curcol += tabs - (curcol - 1) % tabs else curcol += 1 def at = s"[${line}, ${col}]" override def toString: String = s"<$c, $line, $col>" } }
1,019Compiler/lexical analyzer
16scala
fysd4
my @params = @ARGV; my $params_size = @ARGV; my $second = $ARGV[1]; my $fifth = $ARGV[4];
1,020Command-line arguments
2perl
8f10w
<?php $program_name = $argv[0]; $second_arg = $argv[2]; $all_args_without_program_name = array_shift($argv);
1,020Command-line arguments
12php
4hm5n
func combosWithRep<T>(var objects: [T], n: Int) -> [[T]] { if n == 0 { return [[]] } else { var combos = [[T]]() while let element = objects.last { combos.appendContentsOf(combosWithRep(objects, n: n - 1).map{ $0 + [element] }) objects.removeLast() } return combos } } print(combosWithRep(["iced", "jam", "plain"], n: 2).map {$0.joinWithSeparator(" and ")}.joinWithSeparator("\n"))
1,021Combinations with repetitions
17swift
vrz2r
import sys program_name = sys.argv[0] arguments = sys.argv[1:] count = len(arguments)
1,020Command-line arguments
3python
ota81
R CMD BATCH --vanilla --slave '--args a=1 b=c(2,5,6)' test.r test.out
1,020Command-line arguments
13r
qikxs
sub comma_quibbling(@) { return "{$_}" for @_ < 2 ? "@_" : join(', ', @_[0..@_-2]) . ' and ' . $_[-1]; } print comma_quibbling(@$_), "\n" for [], [qw(ABC)], [qw(ABC DEF)], [qw(ABC DEF G H)];
1,022Comma quibbling
2perl
gky4e
p ARGV
1,020Command-line arguments
14ruby
n3wit
use std::env; fn main(){ let args: Vec<_> = env::args().collect(); println!("{:?}", args); }
1,020Command-line arguments
15rust
d6xny
<?php function quibble($arr){ $words = count($arr); if($words == 0){ return '{}'; }elseif($words == 1){ return '{'.$arr[0].'}'; }elseif($words == 2){ return '{'.$arr[0].' and '.$arr[1].'}'; }else{ return '{'.implode(', ', array_splice($arr, 0, -1) ). ' and '.$arr[0].'}'; } } $tests = [ [], [], [, ], [, , , ] ]; foreach ($tests as $test) { echo quibble($test) . PHP_EOL; }
1,022Comma quibbling
12php
n3aig
object CommandLineArguments extends App { println(s"Received the following arguments: + ${args.mkString("", ", ", ".")}") }
1,020Command-line arguments
16scala
z90tr
null
1,024Comments
0go
izbog
100 REM Standard BASIC comments begin with "REM" (remark) and extend to the end of the line 110 PRINT "this is code": REM comment after statement
1,024Comments
7groovy
qirxp
let args = Process.arguments println("This program is named \(args[0]).") println("There are \(args.count-1) arguments.") for i in 1..<args.count { println("the argument #\(i) is \(args[i])") }
1,020Command-line arguments
17swift
izeo0
i code = True let u x = x x (this code not compiled) Are you? -} i code = True i code = True
1,024Comments
8haskell
vrd2k
life.pl numrows numcols numiterations life.pl 5 10 15
1,014Conway's Game of Life
2perl
5jvu2
if booleanExpression { statements }
1,023Conditional structures
0go
0dhsk
>>> def strcat(sequence): return '{%s}'% ', '.join(sequence)[::-1].replace(',', 'dna ', 1)[::-1] >>> for seq in ([], [], [, ], [, , , ]): print('Input:%-24r -> Output:%r'% (seq, strcat(seq))) Input: [] -> Output: '{}' Input: ['ABC'] -> Output: '{ABC}' Input: ['ABC', 'DEF'] -> Output: '{ABC and DEF}' Input: ['ABC', 'DEF', 'G', 'H'] -> Output: '{ABC, DEF, G and H}' >>>
1,022Comma quibbling
3python
rbmgq
fac x = if x==0 then 1 else x * fac (x - 1)
1,023Conditional structures
8haskell
c5i94
quib <- function(vect) { vect <- vect[nchar(vect) != 0] len <- length(vect) allButLastWord <- if(len >= 2) paste0(vect[seq_len(len - 1)], collapse = ", ") else "" paste0("{", if(nchar(allButLastWord) == 0) vect else paste0(allButLastWord, " and ", vect[len]), "}") } quib(character(0)) quib("") quib(" ") quib(c("", "")) quib(rep("", 10)) quib("ABC") quib(c("ABC", "")) quib(c("ABC", "DEF")) quib(c("ABC", "DEF", "G", "H")) quib(c("ABC", "DEF", "G", "H", "I", "J", ""))
1,022Comma quibbling
13r
u7zvx
null
1,024Comments
9java
y2s6g
n = n + 1;
1,024Comments
10javascript
2gnlr
def comma_quibbling(a) %w<{ }>.join(a.length < 2? a.first: ) end [[], %w<ABC>, %w<ABC DEF>, %w<ABC DEF G H>].each do |a| puts comma_quibbling(a) end
1,022Comma quibbling
14ruby
j1c7x
fn quibble(seq: &[&str]) -> String { match seq.len() { 0 => "{}".to_string(), 1 => format!("{{{}}}", seq[0]), _ => { format!("{{{} and {}}}", seq[..seq.len() - 1].join(", "), seq.last().unwrap()) } } } fn main() { println!("{}", quibble(&[])); println!("{}", quibble(&["ABC"])); println!("{}", quibble(&["ABC", "DEF"])); println!("{}", quibble(&["ABC", "DEF", "G", "H"])); }
1,022Comma quibbling
15rust
halj2
def quibble( s:List[String] ) = s match { case m if m.isEmpty => "{}" case m if m.length < 3 => m.mkString("{", " and ", "}") case m => "{" + m.init.mkString(", ") + " and " + m.last + "}" }
1,022Comma quibbling
16scala
pxubj
null
1,024Comments
11kotlin
fyado
import random from collections import defaultdict printdead, printlive = '- maxgenerations = 3 cellcount = 3,3 celltable = defaultdict(int, { (1, 2): 1, (1, 3): 1, (0, 3): 1, } ) u = universe = defaultdict(int) u[(1,0)], u[(1,1)], u[(1,2)] = 1,1,1 for i in range(maxgenerations): print(% ( i, )) for row in range(cellcount[1]): print(, ''.join(str(universe[(row,col)]) for col in range(cellcount[0])).replace( '0', printdead).replace('1', printlive)) nextgeneration = defaultdict(int) for row in range(cellcount[1]): for col in range(cellcount[0]): nextgeneration[(row,col)] = celltable[ ( universe[(row,col)], -universe[(row,col)] + sum(universe[(r,c)] for r in range(row-1,row+2) for c in range(col-1, col+2) ) ) ] universe = nextgeneration
1,014Conway's Game of Life
3python
4hu5k
gen.board <- function(type="random", nrow=3, ncol=3, seeds=NULL) { if(type=="random") { return(matrix(runif(nrow*ncol) > 0.5, nrow=nrow, ncol=ncol)) } else if(type=="blinker") { seeds <- list(c(2,1),c(2,2),c(2,3)) } else if(type=="glider") { seeds <- list(c(1,2),c(2,3),c(3,1), c(3,2), c(3,3)) } board <- matrix(FALSE, nrow=nrow, ncol=ncol) for(k in seq_along(seeds)) { board[seeds[[k]][1],seeds[[k]][2]] <- TRUE } board } count.neighbours <- function(x,i,j) { sum(x[max(1,i-1):min(nrow(x),i+1),max(1,j-1):min(ncol(x),j+1)]) - x[i,j] } determine.new.state <- function(board, i, j) { N <- count.neighbours(board,i,j) (N == 3 || (N ==2 && board[i,j])) } evolve <- function(board) { newboard <- board for(i in seq_len(nrow(board))) { for(j in seq_len(ncol(board))) { newboard[i,j] <- determine.new.state(board,i,j) } } newboard } game.of.life <- function(board, nsteps=50, timebetweensteps=0.25, graphicaloutput=TRUE) { if(!require(lattice)) stop("lattice package could not be loaded") nr <- nrow(board) for(i in seq_len(nsteps)) { if(graphicaloutput) { print(levelplot(t(board[nr:1,]), colorkey=FALSE)) } else print(board) Sys.sleep(timebetweensteps) newboard <- evolve(board) if(all(newboard==board)) { message("board is static") break } else if(sum(newboard) < 1) { message("everything is dead") break } else board <- newboard } invisible(board) } game.of.life(gen.board("blinker")) game.of.life(gen.board("glider", 18, 20)) game.of.life(gen.board(, 50, 50))
1,014Conway's Game of Life
13r
2gclg
let inputs = [[], ["ABC"], ["ABC", "DEF"], ["ABC", "DEF", "G", "H"]] func quibbling(var words:[String]) { if words.count == 0 { println("{}") } else if words.count == 1 { println("{\(words[0])}") } else if words.count == 2 { println("{\(words[0]) and \(words[1])}") } else { var output = "{" while words.count!= 2 { output += words.removeAtIndex(0) + ", " } output += "\(words.removeAtIndex(0)) and \(words.removeAtIndex(0))}" println(output) } } for word in inputs { quibbling(word) }
1,022Comma quibbling
17swift
7p9rq
if(s.equals("Hello World")) { foo(); } else if(s.equals("Bye World")) bar();
1,023Conditional structures
9java
z9xtq
if( s == "Hello World" ) { foo(); } else if( s == "Bye World" ) { bar(); } else { deusEx(); }
1,023Conditional structures
10javascript
9uoml
def game_of_life(name, size, generations, initial_life=nil) board = new_board size seed board, size, initial_life print_board board, name, 0 reason = generations.times do |gen| new = evolve board, size print_board new, name, gen+1 break :all_dead if barren? new, size break :static if board == new board = new end if reason == :all_dead then puts elsif reason == :static then puts else puts end puts end def new_board(n) Array.new(n) {Array.new(n, 0)} end def seed(board, n, points=nil) if points.nil? indices = [] n.times {|x| n.times {|y| indices << [x,y] }} indices.shuffle[0,10].each {|x,y| board[y][x] = 1} else points.each {|x, y| board[y][x] = 1} end end def evolve(board, n) new = new_board n n.times {|i| n.times {|j| new[i][j] = fate board, i, j, n}} new end def fate(board, i, j, n) i1 = [0, i-1].max; i2 = [i+1, n-1].min j1 = [0, j-1].max; j2 = [j+1, n-1].min sum = 0 for ii in (i1..i2) for jj in (j1..j2) sum += board[ii][jj] if not (ii == i and jj == j) end end (sum == 3 or (sum == 2 and board[i][j] == 1))? 1: 0 end def barren?(board, n) n.times {|i| n.times {|j| return false if board[i][j] == 1}} true end def print_board(m, name, generation) puts m.each {|row| row.each {|val| print }; puts} end game_of_life , 3, 2, [[1,0],[1,1],[1,2]] game_of_life , 4, 4, [[1,0],[2,1],[0,2],[1,2],[2,2]] game_of_life , 5, 10
1,014Conway's Game of Life
14ruby
rb4gs
use std::collections::HashMap; use std::collections::HashSet; type Cell = (i32, i32); type Colony = HashSet<Cell>; fn print_colony(col: &Colony, width: i32, height: i32) { for y in 0..height { for x in 0..width { print!("{} ", if col.contains(&(x, y)) {"O"} else {"."} ); } println!(); } } fn neighbours(&(x,y): &Cell) -> Vec<Cell> { vec![ (x-1,y-1), (x,y-1), (x+1,y-1), (x-1,y), (x+1,y), (x-1,y+1), (x,y+1), (x+1,y+1), ] } fn neighbour_counts(col: &Colony) -> HashMap<Cell, i32> { let mut ncnts = HashMap::new(); for cell in col.iter().flat_map(neighbours) { *ncnts.entry(cell).or_insert(0) += 1; } ncnts } fn generation(col: Colony) -> Colony { neighbour_counts(&col) .into_iter() .filter_map(|(cell, cnt)| match (cnt, col.contains(&cell)) { (2, true) | (3, ..) => Some(cell), _ => None }) .collect() } fn life(init: Vec<Cell>, iters: i32, width: i32, height: i32) { let mut col: Colony = init.into_iter().collect(); for i in 0..iters+1 { println!("({})", &i); if i!= 0 { col = generation(col); } print_colony(&col, width, height); } } fn main() { let blinker = vec![ (1,0), (1,1), (1,2)]; life(blinker, 3, 3, 3); let glider = vec![ (1,0), (2,1), (0,2), (1,2), (2,2)]; life(glider, 20, 8, 8); }
1,014Conway's Game of Life
15rust
7pgrc
bool colorful(int n) { if (n < 0 || n > 98765432) return false; int digit_count[10] = {}; int digits[8] = {}; int num_digits = 0; for (int m = n; m > 0; m /= 10) { int d = m % 10; if (n > 9 && (d == 0 || d == 1)) return false; if (++digit_count[d] > 1) return false; digits[num_digits++] = d; } int products[36] = {}; for (int i = 0, product_count = 0; i < num_digits; ++i) { for (int j = i, p = 1; j < num_digits; ++j) { p *= digits[j]; for (int k = 0; k < product_count; ++k) { if (products[k] == p) return false; } products[product_count++] = p; } } return true; } static int count[8]; static bool used[10]; static int largest = 0; void count_colorful(int taken, int n, int digits) { if (taken == 0) { for (int d = 0; d < 10; ++d) { used[d] = true; count_colorful(d < 2 ? 9 : 1, d, 1); used[d] = false; } } else { if (colorful(n)) { ++count[digits - 1]; if (n > largest) largest = n; } if (taken < 9) { for (int d = 2; d < 10; ++d) { if (!used[d]) { used[d] = true; count_colorful(taken + 1, n * 10 + d, digits + 1); used[d] = false; } } } } } int main() { setlocale(LC_ALL, ); clock_t start = clock(); printf(); for (int n = 0, count = 0; n < 100; ++n) { if (colorful(n)) printf(, n, ++count % 10 == 0 ? '\n' : ' '); } count_colorful(0, 0, 0); printf(, largest); printf(); int total = 0; for (int d = 0; d < 8; ++d) { printf(, d + 1, count[d]); total += count[d]; } printf(, total); clock_t end = clock(); printf(, (end - start + 0.0) / CLOCKS_PER_SEC); return 0; }
1,025Colorful numbers
5c
2gilo
null
1,024Comments
1lua
tmefn
;;An R6RS Scheme implementation of Conway's Game of Life --- assumes ;;all cells outside the defined grid are dead ;if n is outside bounds of list, return 0 else value at n (define (nth n lst) (cond ((> n (length lst)) 0) ((< n 1) 0) ((= n 1) (car lst)) (else (nth (- n 1) (cdr lst))))) ;return the next state of the supplied universe (define (next-universe universe) ;value at (x, y) (define (cell x y) (if (list? (nth y universe)) (nth x (nth y universe)) 0)) ;sum of the values of the cells surrounding (x, y) (define (neighbor-sum x y) (+ (cell (- x 1) (- y 1)) (cell (- x 1) y) (cell (- x 1) (+ y 1)) (cell x (- y 1)) (cell x (+ y 1)) (cell (+ x 1) (- y 1)) (cell (+ x 1) y) (cell (+ x 1) (+ y 1)))) ;next state of the cell at (x, y) (define (next-cell x y) (let ((cur (cell x y)) (ns (neighbor-sum x y))) (cond ((and (= cur 1) (or (< ns 2) (> ns 3))) 0) ((and (= cur 0) (= ns 3)) 1) (else cur)))) ;next state of row n (define (row n out) (let ((w (length (car universe)))) (if (= (length out) w) out (row n (cons (next-cell (- w (length out)) n) out))))) ;a range of ints from bot to top (define (int-range bot top) (if (> bot top) '() (cons bot (int-range (+ bot 1) top)))) (map (lambda (n) (row n '())) (int-range 1 (length universe)))) ;represent the universe as a string (define (universe->string universe) (define (prettify row) (apply string-append (map (lambda (b) (if (= b 1) "#" "-")) row))) (if (null? universe) "" (string-append (prettify (car universe)) "\n" (universe->string (cdr universe))))) ;starting with seed, show reps states of the universe (define (conway seed reps) (when (> reps 0) (display (universe->string seed)) (newline) (conway (next-universe seed) (- reps 1)))) ;; --- Example Universes ---;; ;blinker in a 3x3 universe (conway '((0 1 0) (0 1 0) (0 1 0)) 5) ;glider in an 8x8 universe (conway '((0 0 1 0 0 0 0 0) (0 0 0 1 0 0 0 0) (0 1 1 1 0 0 0 0) (0 0 0 0 0 0 0 0) (0 0 0 0 0 0 0 0) (0 0 0 0 0 0 0 0) (0 0 0 0 0 0 0 0) (0 0 0 0 0 0 0 0)) 30)
1,014Conway's Game of Life
16scala
kejhk
package main import ( "fmt" "rcu" "strconv" ) func isColorful(n int) bool { if n < 0 { return false } if n < 10 { return true } digits := rcu.Digits(n, 10) for _, d := range digits { if d == 0 || d == 1 { return false } } set := make(map[int]bool) for _, d := range digits { set[d] = true } dc := len(digits) if len(set) < dc { return false } for k := 2; k <= dc; k++ { for i := 0; i <= dc-k; i++ { prod := 1 for j := i; j <= i+k-1; j++ { prod *= digits[j] } if ok := set[prod]; ok { return false } set[prod] = true } } return true } var count = make([]int, 9) var used = make([]bool, 11) var largest = 0 func countColorful(taken int, n string) { if taken == 0 { for digit := 0; digit < 10; digit++ { dx := digit + 1 used[dx] = true t := 1 if digit < 2 { t = 9 } countColorful(t, string(digit+48)) used[dx] = false } } else { nn, _ := strconv.Atoi(n) if isColorful(nn) { ln := len(n) count[ln]++ if nn > largest { largest = nn } } if taken < 9 { for digit := 2; digit < 10; digit++ { dx := digit + 1 if !used[dx] { used[dx] = true countColorful(taken+1, n+string(digit+48)) used[dx] = false } } } } } func main() { var cn []int for i := 0; i < 100; i++ { if isColorful(i) { cn = append(cn, i) } } fmt.Println("The", len(cn), "colorful numbers less than 100 are:") for i := 0; i < len(cn); i++ { fmt.Printf("%2d ", cn[i]) if (i+1)%10 == 0 { fmt.Println() } } countColorful(0, "") fmt.Println("\n\nThe largest possible colorful number is:") fmt.Println(rcu.Commatize(largest)) fmt.Println("\nCount of colorful numbers for each order of magnitude:") pow := 10 for dc := 1; dc < len(count); dc++ { cdc := rcu.Commatize(count[dc]) pc := 100 * float64(count[dc]) / float64(pow) fmt.Printf(" %d digit colorful number count:%6s -%7.3f%%\n", dc, cdc, pc) if pow == 10 { pow = 90 } else { pow *= 10 } } sum := 0 for _, c := range count { sum += c } fmt.Printf("\nTotal colorful numbers:%s\n", rcu.Commatize(sum)) }
1,025Colorful numbers
0go
qigxz
null
1,023Conditional structures
11kotlin
izpo4
import Data.List ( nub ) import Data.List.Split ( divvy ) import Data.Char ( digitToInt ) isColourful :: Integer -> Bool isColourful n |n >= 0 && n <= 10 = True |n > 10 && n < 100 = ((length s) == (length $ nub s)) && (not $ any (\c -> elem c "01") s) |n >= 100 = ((length s) == (length $ nub s)) && (not $ any (\c -> elem c "01") s) && ((length products) == (length $ nub products)) where s :: String s = show n products :: [Int] products = map (\p -> (digitToInt $ head p) * (digitToInt $ last p)) $ divvy 2 1 s solution1 :: [Integer] solution1 = filter isColourful [0 .. 100] solution2 :: Integer solution2 = head $ filter isColourful [98765432, 98765431 ..]
1,025Colorful numbers
8haskell
mvsyf
public class ColorfulNumbers { private int count[] = new int[8]; private boolean used[] = new boolean[10]; private int largest = 0; public static void main(String[] args) { System.out.printf("Colorful numbers less than 100:\n"); for (int n = 0, count = 0; n < 100; ++n) { if (isColorful(n)) System.out.printf("%2d%c", n, ++count % 10 == 0 ? '\n' : ' '); } ColorfulNumbers c = new ColorfulNumbers(); System.out.printf("\n\nLargest colorful number:%,d\n", c.largest); System.out.printf("\nCount of colorful numbers by number of digits:\n"); int total = 0; for (int d = 0; d < 8; ++d) { System.out.printf("%d %,d\n", d + 1, c.count[d]); total += c.count[d]; } System.out.printf("\nTotal:%,d\n", total); } private ColorfulNumbers() { countColorful(0, 0, 0); } public static boolean isColorful(int n) {
1,025Colorful numbers
9java
fy1dv