code
stringlengths
1
46.1k
label
class label
1.18k classes
domain_label
class label
21 classes
index
stringlengths
4
5
findCullen :: Int -> Integer findCullen n = toInteger ( n * 2 ^ n + 1 ) cullens :: [Integer] cullens = map findCullen [1 .. 20] woodalls :: [Integer] woodalls = map (\i -> i - 2 ) cullens main :: IO ( ) main = do putStrLn "First 20 Cullen numbers:" print cullens putStrLn "First 20 Woodall numbers:" print woodalls
976Cullen and Woodall numbers
8haskell
nyfie
function T(t) return setmetatable(t, {__index=table}) end table.range = function(t,n) local s=T{} for i=1,n do s[i]=i end return s end table.map = function(t,f) local s=T{} for i=1,#t do s[i]=f(t[i]) end return s end function cullen(n) return (n<<n)+1 end print("First 20 Cullen numbers:") print(T{}:range(20):map(cullen):concat(" ")) function woodall(n) return (n<<n)-1 end print("First 20 Woodall numbers:") print(T{}:range(20):map(woodall):concat(" "))
976Cullen and Woodall numbers
1lua
a8w1v
(def tbl [[0 3 1 7 5 9 8 6 4 2] [7 0 9 2 1 5 4 8 6 3] [4 2 0 6 8 7 1 3 5 9] [1 7 5 0 9 8 3 4 2 6] [6 1 2 3 0 4 5 9 7 8] [3 6 7 4 2 0 9 5 8 1] [5 8 6 9 7 2 0 1 3 4] [8 9 4 5 3 6 2 0 1 7] [9 4 3 8 6 1 7 2 0 5] [2 5 8 1 4 3 6 7 9 0]]) (defn damm? [digits] (= 0 (reduce #(nth (nth tbl %1) %2) 0 (map #(Character/getNumericValue %) (seq digits)))))
974Damm algorithm
6clojure
5k7uz
(def plus-a-hundred (partial + 100)) (assert (= (plus-a-hundred 1) 101))
975Currying
6clojure
4b75o
function array1D(w, d) local t = {} for i=1,w do table.insert(t, d) end return t end function array2D(h, w, d) local t = {} for i=1,h do table.insert(t, array1D(w, d)) end return t end function push(s, v) s[#s + 1] = v end function pop(s) return table.remove(s, #s) end function empty(s) return #s == 0 end DIRS = { {0, -1}, {-1, 0}, {0, 1}, {1, 0} } function printResult(aa) for i,u in pairs(aa) do io.write("[") for j,v in pairs(u) do if j > 1 then io.write(", ") end io.write(v) end print("]") end end function cutRectangle(w, h) if w % 2 == 1 and h % 2 == 1 then return nil end local grid = array2D(h, w, 0) local stack = {} local half = math.floor((w * h) / 2) local bits = 2 ^ half - 1 while bits > 0 do for i=1,half do local r = math.floor((i - 1) / w) local c = (i - 1) % w if (bits & (1 << (i - 1))) ~= 0 then grid[r + 1][c + 1] = 1 else grid[r + 1][c + 1] = 0 end grid[h - r][w - c] = 1 - grid[r + 1][c + 1] end push(stack, 0) grid[1][1] = 2 local count = 1 while not empty(stack) do local pos = pop(stack) local r = math.floor(pos / w) local c = pos % w for i,dir in pairs(DIRS) do local nextR = r + dir[1] local nextC = c + dir[2] if nextR >= 0 and nextR < h and nextC >= 0 and nextC < w then if grid[nextR + 1][nextC + 1] == 1 then push(stack, nextR * w + nextC) grid[nextR + 1][nextC + 1] = 2 count = count + 1 end end end end if count == half then printResult(grid) print() end
968Cut a rectangle
1lua
jeq71
int main(void) { char buf[MAX_BUF]; time_t seconds = time(NULL); struct tm *now = localtime(&seconds); const char *months[] = {, , , , , , , , , , , }; const char *days[] = {, , , ,,,}; (void) printf(, now->tm_year + 1900, now->tm_mon + 1, now->tm_mday); (void) printf(,days[now->tm_wday], months[now->tm_mon], now->tm_mday, now->tm_year + 1900); (void) strftime(buf, MAX_BUF, , now); (void) printf(, buf); return EXIT_SUCCESS; }
977Date format
5c
6vy32
use strict; use warnings; use bigint; use ntheory 'is_prime'; use constant Inf => 1e10; sub cullen { my($n,$c) = @_; ($n * 2**$n) + $c; } my($m,$n); ($m,$n) = (20,0); print "First $m Cullen numbers:\n"; print do { $n < $m ? (++$n and cullen($_,1) . ' ') : last } for 1 .. Inf; ($m,$n) = (20,0); print "\n\nFirst $m Woodall numbers:\n"; print do { $n < $m ? (++$n and cullen($_,-1) . ' ') : last } for 1 .. Inf; ($m,$n) = (5,0); print "\n\nFirst $m Cullen primes: (in terms of n)\n"; print do { $n < $m ? (!!is_prime(cullen $_,1) and ++$n and "$_ ") : last } for 1 .. Inf; ($m,$n) = (12,0); print "\n\nFirst $m Woodall primes: (in terms of n)\n"; print do { $n < $m ? (!!is_prime(cullen $_,-1) and ++$n and "$_ ") : last } for 1 .. Inf;
976Cullen and Woodall numbers
2perl
m5cyz
import java.util.TreeMap import kotlin.math.abs import kotlin.math.pow import kotlin.math.sqrt private const val algorithm = 2 fun main() { println("Task 1: cyclotomic polynomials for n <= 30:") for (i in 1..30) { val p = cyclotomicPolynomial(i) println("CP[$i] = $p") } println() println("Task 2: Smallest cyclotomic polynomial with n or -n as a coefficient:") var n = 0 for (i in 1..10) { while (true) { n++ val cyclo = cyclotomicPolynomial(n) if (cyclo!!.hasCoefficientAbs(i)) { println("CP[$n] has coefficient with magnitude = $i") n-- break } } } } private val COMPUTED: MutableMap<Int, Polynomial> = HashMap() private fun cyclotomicPolynomial(n: Int): Polynomial? { if (COMPUTED.containsKey(n)) { return COMPUTED[n] } if (n == 1) {
972Cyclotomic polynomial
11kotlin
945mh
use strict; use warnings; my @grid = 0; my ($w, $h, $len); my $cnt = 0; my @next; my @dir = ([0, -1], [-1, 0], [0, 1], [1, 0]); sub walk { my ($y, $x) = @_; if (!$y || $y == $h || !$x || $x == $w) { $cnt += 2; return; } my $t = $y * ($w + 1) + $x; $grid[$_]++ for $t, $len - $t; for my $i (0 .. 3) { if (!$grid[$t + $next[$i]]) { walk($y + $dir[$i]->[0], $x + $dir[$i]->[1]); } } $grid[$_]-- for $t, $len - $t; } sub solve { my ($hh, $ww, $recur) = @_; my ($t, $cx, $cy, $x); ($h, $w) = ($hh, $ww); if ($h & 1) { ($t, $w, $h) = ($w, $h, $w); } if ($h & 1) { return 0; } if ($w == 1) { return 1; } if ($w == 2) { return $h; } if ($h == 2) { return $w; } { use integer; ($cy, $cx) = ($h / 2, $w / 2); } $len = ($h + 1) * ($w + 1); @grid = (); $grid[$len--] = 0; @next = (-1, -$w - 1, 1, $w + 1); if ($recur) { $cnt = 0; } for ($x = $cx + 1; $x < $w; $x++) { $t = $cy * ($w + 1) + $x; @grid[$t, $len - $t] = (1, 1); walk($cy - 1, $x); } $cnt++; if ($h == $w) { $cnt *= 2; } elsif (!($w & 1) && $recur) { solve($w, $h); } return $cnt; } sub MAIN { print "ok\n"; my ($y, $x); for my $y (1 .. 10) { for my $x (1 .. $y) { if (!($x & 1) || !($y & 1)) { printf("%d x%d:%d\n", $y, $x, solve($y, $x, 1)); } } } } MAIN();
968Cut a rectangle
2perl
f92d7
package main import ( "fmt" "time" ) const taskDate = "March 7 2009 7:30pm EST" const taskFormat = "January 2 2006 3:04pm MST" func main() { if etz, err := time.LoadLocation("US/Eastern"); err == nil { time.Local = etz } fmt.Println("Input: ", taskDate) t, err := time.Parse(taskFormat, taskDate) if err != nil { fmt.Println(err) return } t = t.Add(12 * time.Hour) fmt.Println("+12 hrs: ", t) if _, offset := t.Zone(); offset == 0 { fmt.Println("No time zone info.") return } atz, err := time.LoadLocation("US/Arizona") if err == nil { fmt.Println("+12 hrs in Arizona:", t.In(atz)) } }
970Date manipulation
0go
hwxjq
begin games = ARGV.map {|s| Integer(s)} rescue => err $stderr.puts err.inspect $stderr.puts abort end games.empty? and games = [rand(32000)] orig_deck = %w{A 2 3 4 5 6 7 8 9 T J Q K}.product(%w{C D H S}).map(&:join) games.each do |seed| deck = orig_deck.dup state = seed 52.downto(2) do |len| state = ((214013 * state) + 2531011) & 0x7fff_ffff index = (state >> 16) % len last = len - 1 deck[index], deck[last] = deck[last], deck[index] end deck.reverse! puts deck.each_slice(8) {|row| puts + row.join()} puts end
964Deal cards for FreeCell
14ruby
27alw
(let [now (.getTime (java.util.Calendar/getInstance)) f1 (java.text.SimpleDateFormat. "yyyy-MM-dd") f2 (java.text.SimpleDateFormat. "EEEE, MMMM dd, yyyy")] (println (.format f1 now)) (println (.format f2 now)))
977Date format
6clojure
lr2cb
print() print() for n in range(1,20): num = n*pow(2,n)+1 print(str(num),end= ) print() print() for n in range(1,20): num = n*pow(2,n)-1 print(str(num),end=) print() print()
976Cullen and Woodall numbers
3python
94lmf
import org.joda.time.* import java.text.* def dateString = 'March 7 2009 7:30pm EST' def sdf = new SimpleDateFormat('MMMM d yyyy h:mma zzz') DateTime dt = new DateTime(sdf.parse(dateString)) println (dt) println (dt.plusHours(12)) println (dt.plusHours(12).withZone(DateTimeZone.UTC))
970Date manipulation
7groovy
4bp5f
import qualified Data.Time.Clock.POSIX as P import qualified Data.Time.Format as F main :: IO () main = print t2 where t1 = F.parseTimeOrError True F.defaultTimeLocale "%B%e%Y%l:%M%P%Z" "March 7 2009 7:30pm EST" t2 = P.posixSecondsToUTCTime $ 12 * 60 * 60 + P.utcTimeToPOSIXSeconds t1
970Date manipulation
8haskell
i6yor
null
964Deal cards for FreeCell
15rust
vje2t
null
976Cullen and Woodall numbers
15rust
27ult
Floating point number or Float for short, is an arbitrary precision mantissa with a limited precision exponent. The C data type for such objects is mpf_t. For example: mpf_t fp;
978Currency
5c
lrlcy
int main() { int intspace; int *address; address = &intspace; *address = 65535; printf(, address, *address, intspace); *((char*)address) = 0x00; *((char*)address+1) = 0x00; *((char*)address+2) = 0xff; *((char*)address+3) = 0xff; printf(, address, *address, intspace); return 0; }
979Create an object at a given address
5c
71grg
def cut_it(h, w): dirs = ((1, 0), (-1, 0), (0, -1), (0, 1)) if h% 2: h, w = w, h if h% 2: return 0 if w == 1: return 1 count = 0 next = [w + 1, -w - 1, -1, 1] blen = (h + 1) * (w + 1) - 1 grid = [False] * (blen + 1) def walk(y, x, count): if not y or y == h or not x or x == w: return count + 1 t = y * (w + 1) + x grid[t] = grid[blen - t] = True if not grid[t + next[0]]: count = walk(y + dirs[0][0], x + dirs[0][1], count) if not grid[t + next[1]]: count = walk(y + dirs[1][0], x + dirs[1][1], count) if not grid[t + next[2]]: count = walk(y + dirs[2][0], x + dirs[2][1], count) if not grid[t + next[3]]: count = walk(y + dirs[3][0], x + dirs[3][1], count) grid[t] = grid[blen - t] = False return count t = h if w% 2: grid[t] = grid[t + 1] = True count = walk(h res = count count = 0 count = walk(h return res + count * 2 else: grid[t] = True count = walk(h if h == w: return count * 2 count = walk(h return count def main(): for w in xrange(1, 10): for h in xrange(1, w + 1): if not((w * h)% 2): print % (w, h, cut_it(w, h)) main()
968Cut a rectangle
3python
tcvfw
object Shuffler extends App { private val suits = Array("C", "D", "H", "S") private val values = Array("A", "2", "3", "4", "5", "6", "7", "8", "9", "T", "J", "Q", "K") private val deck = values.flatMap(v => suits.map(s => s"$v$s")) private var seed: Int = _ private def random() = { seed = (214013 * seed + 2531011) & Integer.MAX_VALUE seed >> 16 } private def getShuffledDeck = { val d = deck.map(c => c) for(i <- deck.length - 1 until 0 by -1) { val r = random() % (i + 1) val card = d(r) d(r) = d(i) d(i) = card } d.reverse } def deal(seed: Int): Unit = { this.seed = seed getShuffledDeck.grouped(8).foreach(e => println(e.mkString(" "))) } deal(1) println deal(617) }
964Deal cards for FreeCell
16scala
4bq50
(require '[clojurewerkz.money.amounts :as ma]) (require '[clojurewerkz.money.currencies:as mc]) (require '[clojurewerkz.money.format :as mf]) (let [burgers (ma/multiply (ma/amount-of mc/USD 5.50) 4000000000000000) milkshakes (ma/multiply (ma/amount-of mc/USD 2.86) 2) pre-tax (ma/plus burgers milkshakes) tax (ma/multiply pre-tax 0.0765:up)] (println "Total before tax: " (mf/format pre-tax)) (println " Tax: " (mf/format tax)) (println " Total with tax: " (mf/format (ma/plus pre-tax tax))))
978Currency
6clojure
4b45o
enum Suit: String, CustomStringConvertible, CaseIterable { case clubs = "C", diamonds = "D", hearts = "H", spades = "S" var description: String { return self.rawValue } } enum Rank: Int, CustomStringConvertible, CaseIterable { case ace=1, two, three, four, five, six, seven case eight, nine, ten, jack, queen, king var description: String { let d: [Rank:String] = [.ace:"A", .king:"K", .queen:"Q", .jack:"J", .ten:"T"] return d[self]?? String(self.rawValue) } } struct Card: CustomStringConvertible { let rank: Rank, suit: Suit var description: String { return String(describing:self.rank) + String(describing:self.suit) } init(rank:Rank, suit:Suit) { self.rank = rank; self.suit = suit } init(sequence n:Int) { self.init(rank:Rank.allCases[n/4], suit:Suit.allCases[n%4]) } } struct Deck: CustomStringConvertible { var cards = [Card]() init(seed:Int) { for i in (0..<52).reversed() { self.cards.append(Card(sequence:i)) } struct MicrosoftLinearCongruentialGenerator { var seed: Int mutating func next() -> Int { self.seed = (self.seed * 214013 + 2531011)% (Int(Int32.max)+1) return self.seed >> 16 } } var r = MicrosoftLinearCongruentialGenerator(seed: seed) for i in 0..<51 { self.cards.swapAt(i, 51-r.next()%(52-i)) } } var description: String { var s = "" for (ix,c) in self.cards.enumerated() { s.write(String(describing:c)) s.write(ix% 8 == 7? "\n": " ") } return s } } let d1 = Deck(seed: 1) print(d1) let d617 = Deck(seed: 617) print(d617)
964Deal cards for FreeCell
17swift
lr1c2
use feature 'say'; use List::Util qw(first); use Math::Polynomial::Cyclotomic qw(cyclo_poly_iterate); say 'First 30 cyclotomic polynomials:'; my $it = cyclo_poly_iterate(1); say "$_: " . $it->() for 1 .. 30; say "\nSmallest cyclotomic polynomial with n or -n as a coefficient:"; $it = cyclo_poly_iterate(1); for (my ($n, $k) = (1, 1) ; $n <= 10 ; ++$k) { my $poly = $it->(); while (my $c = first { abs($_) == $n } $poly->coeff) { say "CP $k has coefficient with magnitude = $n"; $n++; } }
972Cyclotomic polynomial
2perl
wioe6
import java.time.*; import java.time.format.*; class Main { public static void main(String args[]) { String dateStr = "March 7 2009 7:30pm EST"; DateTimeFormatter df = new DateTimeFormatterBuilder() .parseCaseInsensitive() .appendPattern("MMMM d yyyy h:mma zzz") .toFormatter(); ZonedDateTime after12Hours = ZonedDateTime.parse(dateStr, df).plusHours(12); System.out.println("Date: " + dateStr); System.out.println("+12h: " + after12Hours.format(df)); ZonedDateTime after12HoursInCentralEuropeTime = after12Hours.withZoneSameInstant(ZoneId.of("CET")); System.out.println("+12h (in Central Europe): " + after12HoursInCentralEuropeTime.format(df)); } }
970Date manipulation
9java
xndwy
package main import "fmt" func isCusip(s string) bool { if len(s) != 9 { return false } sum := 0 for i := 0; i < 8; i++ { c := s[i] var v int switch { case c >= '0' && c <= '9': v = int(c) - 48 case c >= 'A' && c <= 'Z': v = int(c) - 55 case c == '*': v = 36 case c == '@': v = 37 case c == '#': v = 38 default: return false } if i % 2 == 1 { v *= 2 }
973CUSIP
0go
cg59g
package main import( "fmt" "unsafe" "reflect" ) func pointer() { fmt.Printf("Pointer:\n")
979Create an object at a given address
0go
dyine
function add12hours(dateString) {
970Date manipulation
10javascript
o3686
class Cusip { private static Boolean isCusip(String s) { if (s.length() != 9) return false int sum = 0 for (int i = 0; i <= 7; i++) { char c = s.charAt(i) int v if (c >= ('0' as char) && c <= ('9' as char)) { v = c - 48 } else if (c >= ('A' as char) && c <= ('Z' as char)) { v = c - 55
973CUSIP
7groovy
32czd
int main() { FILE* fp = fopen(,); fprintf(fp,); fprintf(fp,); fprintf(fp,); fprintf(fp,); fprintf(fp,); fprintf(fp,); fprintf(fp,); fprintf(fp,); fclose(fp); return 0; }
980Create a file on magnetic tape
5c
fmid3
(spit "/dev/tape" "Hello, World!")
980Create a file on magnetic tape
6clojure
yvz6b
package main import ( "fmt" "log" "math/big" )
978Currency
0go
xnxwf
package main import ( "fmt" "math" ) func PowN(b float64) func(float64) float64 { return func(e float64) float64 { return math.Pow(b, e) } } func PowE(e float64) func(float64) float64 { return func(b float64) float64 { return math.Pow(b, e) } } type Foo int func (f Foo) Method(b int) int { return int(f) + b } func main() { pow2 := PowN(2) cube := PowE(3) fmt.Println("2^8 =", pow2(8)) fmt.Println("4 =", cube(4)) var a Foo = 2 fn1 := a.Method
975Currying
0go
xn0wf
null
979Create an object at a given address
11kotlin
zcfts
local a = {10} local b = a print ("address a:"..tostring(a), "value a:"..a[1]) print ("address b:"..tostring(b), "value b:"..b[1]) b[1] = 42 print ("address a:"..tostring(a), "value a:"..a[1]) print ("address b:"..tostring(b), "value b:"..b[1])
979Create an object at a given address
1lua
3ltzo
from itertools import count, chain from collections import deque def primes(_cache=[2, 3]): yield from _cache for n in count(_cache[-1]+2, 2): if isprime(n): _cache.append(n) yield n def isprime(n): for p in primes(): if n%p == 0: return False if p*p > n: return True def factors(n): for p in primes(): if p*p > n: if n > 1: yield(n, 1, 1) break if n%p == 0: cnt = 0 while True: n, cnt = n if n%p != 0: break yield p, cnt, n def cyclotomic(n): def poly_div(num, den): return (num[0] + den[1], num[1] + den[0]) def elevate(poly, n): powerup = lambda p, n: [a*n for a in p] return poly if n == 1 else (powerup(poly[0], n), powerup(poly[1], n)) if n == 0: return ([], []) if n == 1: return ([1], []) p, m, r = next(factors(n)) poly = cyclotomic(r) return elevate(poly_div(elevate(poly, p), poly), p**(m-1)) def to_text(poly): def getx(c, e): if e == 0: return '1' elif e == 1: return 'x' return 'x' + (''.join(''[i] for i in map(int, str(e)))) parts = [] for (c,e) in (poly): if c < 0: coef = ' - ' if c == -1 else f' - {-c} ' else: coef = (parts and ' + ' or '') if c == 1 else f' + {c}' parts.append(coef + getx(c,e)) return ''.join(parts) def terms(poly): def merge(a, b): while a or b: l = a[0] if a else (0, -1) r = b[0] if b else (0, -1) if l[1] > r[1]: a.popleft() elif l[1] < r[1]: b.popleft() l = r else: a.popleft() b.popleft() l = (l[0] + r[0], l[1]) yield l def mul(poly, p): poly = list(poly) return merge(deque((c, e+p) for c,e in poly), deque((-c, e) for c,e in poly)) def div(poly, p): q = deque() for c,e in merge(deque(poly), q): if c: q.append((c, e - p)) yield (c, e - p) if e == p: break p = [(1, 0)] for x in poly[0]: p = mul(p, x) for x in sorted(poly[1], reverse=True): p = div(p, x) return p for n in chain(range(11), [2]): print(f'{n}: {to_text(terms(cyclotomic(n)))}') want = 1 for n in count(): c = [c for c,_ in terms(cyclotomic(n))] while want in c or -want in c: print(f'C[{want}]: {n}') want += 1
972Cyclotomic polynomial
3python
xniwr
def cut_it(h, w) if h.odd? return 0 if w.odd? h, w = w, h end return 1 if w == 1 nxt = [[w+1, 1, 0], [-w-1, -1, 0], [-1, 0, -1], [1, 0, 1]] blen = (h + 1) * (w + 1) - 1 grid = [false] * (blen + 1) walk = lambda do |y, x, count=0| return count+1 if y==0 or y==h or x==0 or x==w t = y * (w + 1) + x grid[t] = grid[blen - t] = true nxt.each do |nt, dy, dx| count += walk[y + dy, x + dx] unless grid[t + nt] end grid[t] = grid[blen - t] = false count end t = h / 2 * (w + 1) + w / 2 if w.odd? grid[t] = grid[t + 1] = true count = walk[h / 2, w / 2 - 1] count + walk[h / 2 - 1, w / 2] * 2 else grid[t] = true count = walk[h / 2, w / 2 - 1] return count * 2 if h == w count + walk[h / 2 - 1, w / 2] end end for w in 1..9 for h in 1..w puts % [w, h, cut_it(w, h)] if (w * h).even? end end
968Cut a rectangle
14ruby
325z7
import Data.List(elemIndex) data Result = Valid | BadCheck | TooLong | TooShort | InvalidContent deriving Show allMaybe :: [Maybe a] -> Maybe [a] allMaybe = sequence toValue :: Char -> Maybe Int toValue c = elemIndex c $ ['0'..'9'] ++ ['A'..'Z'] ++ "*@#" valid :: [Int] -> Bool valid ns0 = let ns1 = zipWith (\i n -> (if odd i then n else 2*n)) [1..] $ take 8 ns0 sm = sum $ fmap (\s -> ( s `div` 10 ) + s `mod` 10) ns1 in ns0!!8 == (10 - (sm `mod` 10)) `mod` 10 checkCUSIP :: String -> Result checkCUSIP cs | l < 9 = TooShort | l > 9 = TooLong | otherwise = case allMaybe (fmap toValue cs) of Nothing -> InvalidContent Just ns -> if valid ns then Valid else BadCheck where l = length cs testData = [ "037833100" , "17275R102" , "38259P508" , "594918104" , "68389X106" , "68389X105" ] main = mapM_ putStrLn (fmap (\s -> s ++ ": " ++ show (checkCUSIP s)) testData)
973CUSIP
8haskell
psxbt
package main import "fmt" var table = [10][10]byte{ {0, 3, 1, 7, 5, 9, 8, 6, 4, 2}, {7, 0, 9, 2, 1, 5, 4, 8, 6, 3}, {4, 2, 0, 6, 8, 7, 1, 3, 5, 9}, {1, 7, 5, 0, 9, 8, 3, 4, 2, 6}, {6, 1, 2, 3, 0, 4, 5, 9, 7, 8}, {3, 6, 7, 4, 2, 0, 9, 5, 8, 1}, {5, 8, 6, 9, 7, 2, 0, 1, 3, 4}, {8, 9, 4, 5, 3, 6, 2, 0, 1, 7}, {9, 4, 3, 8, 6, 1, 7, 2, 0, 5}, {2, 5, 8, 1, 4, 3, 6, 7, 9, 0}, } func damm(input string) bool { var interim byte for _, c := range []byte(input) { interim = table[interim][c-'0'] } return interim == 0 } func main() { for _, s := range []string{"5724", "5727", "112946", "112949"} { fmt.Printf("%6s %t\n", s, damm(s)) } }
974Damm algorithm
0go
wi0eg
import Data.Fixed import Text.Printf type Percent = Centi type Dollars = Centi tax :: Percent -> Dollars -> Dollars tax rate = MkFixed . round . (rate *) printAmount :: String -> Dollars -> IO () printAmount name = printf "%-10s%20s\n" name . showFixed False main :: IO () main = do let subtotal = 4000000000000000 * 5.50 + 2 * 2.86 tx = tax 7.65 subtotal total = subtotal + tx printAmount "Subtotal" subtotal printAmount "Tax" tx printAmount "Total" total
978Currency
8haskell
yuy66
def divide = { Number x, Number y -> x / y } def partsOf120 = divide.curry(120) println "120: half: ${partsOf120(2)}, third: ${partsOf120(3)}, quarter: ${partsOf120(4)}"
975Currying
7groovy
psebo
\ ->
975Currying
8haskell
yuc66
use strict; use warnings; print "Here is an integer : ", my $target = 42, "\n"; print "And its reference is : ", my $targetref = \$target, "\n"; print "Now assigns a new value to it : ", $$targetref = 69, "\n"; print "Then compare with the referent: ", $target, "\n";
979Create an object at a given address
2perl
bxhk4
fn cwalk(mut vis: &mut Vec<Vec<bool>>, count: &mut isize, w: usize, h: usize, y: usize, x: usize, d: usize) { if x == 0 || y == 0 || x == w || y == h { *count += 1; return; } vis[y][x] = true; vis[h - y][w - x] = true; if x!= 0 &&! vis[y][x - 1] { cwalk(&mut vis, count, w, h, y, x - 1, d | 1); } if d & 1!= 0 && x < w &&! vis[y][x+1] { cwalk(&mut vis, count, w, h, y, x + 1, d | 1); } if y!= 0 &&! vis[y - 1][x] { cwalk(&mut vis, count, w, h, y - 1, x, d | 2); } if d & 2!= 0 && y < h &&! vis[y + 1][x] { cwalk(&mut vis, count, w, h, y + 1, x, d | 2); } vis[y][x] = false; vis[h - y][w - x] = false; } fn count_only(x: usize, y: usize) -> isize { let mut count = 0; let mut w = x; let mut h = y; if (h * w) & 1!= 0 { return count; } if h & 1!= 0 { std::mem::swap(&mut w, &mut h); } let mut vis = vec![vec![false; w + 1]; h + 1]; vis[h / 2][w / 2] = true; if w & 1!= 0 { vis[h / 2][w / 2 + 1] = true; } let mut res; if w > 1 { cwalk(&mut vis, &mut count, w, h, h / 2, w / 2 - 1, 1); res = 2 * count - 1; count = 0; if w!= h { cwalk(&mut vis, &mut count, w, h, h / 2 + 1, w / 2, if w & 1!= 0 { 3 } else { 2 }); } res += 2 * count - if w & 1 == 0 { 1 } else { 0 }; } else { res = 1; } if w == h { res = 2 * res + 2; } res } fn main() { for y in 1..10 { for x in 1..y + 1 { if x & 1 == 0 || y & 1 == 0 { println!("{} x {}: {}", y, x, count_only(x, y)); } } } }
968Cut a rectangle
15rust
6v43l
null
970Date manipulation
11kotlin
ps0b6
class DammAlgorithm { private static final int[][] TABLE = [ [0, 3, 1, 7, 5, 9, 8, 6, 4, 2], [7, 0, 9, 2, 1, 5, 4, 8, 6, 3], [4, 2, 0, 6, 8, 7, 1, 3, 5, 9], [1, 7, 5, 0, 9, 8, 3, 4, 2, 6], [6, 1, 2, 3, 0, 4, 5, 9, 7, 8], [3, 6, 7, 4, 2, 0, 9, 5, 8, 1], [5, 8, 6, 9, 7, 2, 0, 1, 3, 4], [8, 9, 4, 5, 3, 6, 2, 0, 1, 7], [9, 4, 3, 8, 6, 1, 7, 2, 0, 5], [2, 5, 8, 1, 4, 3, 6, 7, 9, 0], ] private static boolean damm(String s) { int interim = 0 for (char c: s.toCharArray()) interim = TABLE[interim][c - ('0' as Character)] return interim == 0 } static void main(String[] args) { int[] numbers = [5724, 5727, 112946, 112949] for (Integer number: numbers) { boolean isValid = damm(number.toString()) if (isValid) { System.out.printf("%6d is valid\n", number) } else { System.out.printf("%6d is invalid\n", number) } } } }
974Damm algorithm
7groovy
bqeky
typedef long long llong_t; struct PrimeArray { llong_t *ptr; size_t size; size_t capacity; }; struct PrimeArray allocate() { struct PrimeArray primes; primes.size = 0; primes.capacity = 10; primes.ptr = malloc(primes.capacity * sizeof(llong_t)); return primes; } void deallocate(struct PrimeArray *primes) { free(primes->ptr); primes->ptr = NULL; } void push_back(struct PrimeArray *primes, llong_t p) { if (primes->size >= primes->capacity) { size_t new_capacity = (3 * primes->capacity) / 2 + 1; llong_t *temp = realloc(primes->ptr, new_capacity * sizeof(llong_t)); if (NULL == temp) { fprintf(stderr, ); exit(1); } else { primes->ptr = temp; primes->capacity = new_capacity; } } primes->ptr[primes->size++] = p; } int main() { const int cutOff = 200, bigUn = 100000, chunks = 50, little = bigUn / chunks; struct PrimeArray primes = allocate(); int c = 0; bool showEach = true; llong_t u = 0, v = 1, i; push_back(&primes, 3); push_back(&primes, 5); printf(, cutOff); for (i = 1; i < LLONG_MAX; ++i) { bool found = false; llong_t mx = ceil(sqrt(v += (u += 6))); llong_t j; for (j = 0; j < primes.size; ++j) { if (primes.ptr[j] > mx) { break; } if (v % primes.ptr[j] == 0) { found = true; break; } } if (!found) { c += 1; if (showEach) { llong_t z; for (z = primes.ptr[primes.size - 1] + 2; z <= v - 2; z += 2) { bool fnd = false; for (j = 0; j < primes.size; ++j) { if (primes.ptr[j] > mx) { break; } if (z % primes.ptr[j] == 0) { fnd = true; break; } } if (!fnd) { push_back(&primes, z); } } push_back(&primes, v); printf(, v); if (c % 10 == 0) { printf(); } if (c == cutOff) { showEach = false; printf(, bigUn); } } if (c % little == 0) { printf(); if (c == bigUn) { break; } } } } printf(, c, v); deallocate(&primes); return 0; }
981Cuban primes
5c
0fwst
package main import ( "archive/tar" "compress/gzip" "flag" "io" "log" "os" "time" ) func main() { filename := flag.String("file", "TAPE.FILE", "filename within TAR") data := flag.String("data", "", "data for file") outfile := flag.String("out", "", "output file or device (e.g. /dev/tape)") gzipFlag := flag.Bool("gzip", false, "use gzip compression") flag.Parse() var w io.Writer = os.Stdout if *outfile != "" { f, err := os.Create(*outfile) if err != nil { log.Fatalf("opening/creating%q:%v", *outfile, err) } defer f.Close() w = f } if *gzipFlag { zw := gzip.NewWriter(w) defer zw.Close() w = zw } tw := tar.NewWriter(w) defer tw.Close() w = tw tw.WriteHeader(&tar.Header{ Name: *filename, Mode: 0660, Size: int64(len(*data)), ModTime: time.Now(), Typeflag: tar.TypeReg, Uname: "guest", Gname: "guest", }) _, err := w.Write([]byte(*data)) if err != nil { log.Fatal("writing data:", err) } }
980Create a file on magnetic tape
0go
jag7d
import java.math.*; import java.util.*; public class Currency { final static String taxrate = "7.65"; enum MenuItem { Hamburger("5.50"), Milkshake("2.86"); private MenuItem(String p) { price = new BigDecimal(p); } public final BigDecimal price; } public static void main(String[] args) { Locale.setDefault(Locale.ENGLISH); MathContext mc = MathContext.DECIMAL128; Map<MenuItem, BigDecimal> order = new HashMap<>(); order.put(MenuItem.Hamburger, new BigDecimal("4000000000000000")); order.put(MenuItem.Milkshake, new BigDecimal("2")); BigDecimal subtotal = BigDecimal.ZERO; for (MenuItem it : order.keySet()) subtotal = subtotal.add(it.price.multiply(order.get(it), mc)); BigDecimal tax = new BigDecimal(taxrate, mc); tax = tax.divide(new BigDecimal("100"), mc); tax = subtotal.multiply(tax, mc); System.out.printf("Subtotal:%20.2f%n", subtotal); System.out.printf(" Tax:%20.2f%n", tax); System.out.printf(" Total:%20.2f%n", subtotal.add(tax)); } }
978Currency
9java
dmdn9
import java.util.List; public class Cusip { private static Boolean isCusip(String s) { if (s.length() != 9) return false; int sum = 0; for (int i = 0; i <= 7; i++) { char c = s.charAt(i); int v; if (c >= '0' && c <= '9') { v = c - 48; } else if (c >= 'A' && c <= 'Z') { v = c - 55;
973CUSIP
9java
r1bg0
typedef enum Action { STDDEV, MEAN, VAR, COUNT } Action; typedef struct stat_obj_struct { double sum, sum2; size_t num; Action action; } sStatObject, *StatObject; StatObject NewStatObject( Action action ) { StatObject so; so = malloc(sizeof(sStatObject)); so->sum = 0.0; so->sum2 = 0.0; so->num = 0; so->action = action; return so; } free(so); so = NULL double stat_obj_value(StatObject so, Action action) { double num, mean, var, stddev; if (so->num == 0.0) return 0.0; num = so->num; if (action==COUNT) return num; mean = so->sum/num; if (action==MEAN) return mean; var = so->sum2/num - mean*mean; if (action==VAR) return var; stddev = sqrt(var); if (action==STDDEV) return stddev; return 0; } double stat_object_add(StatObject so, double v) { so->num++; so->sum += v; so->sum2 += v*v; return stat_obj_value(so, so->action); }
982Cumulative standard deviation
5c
dy0nv
typedef struct { char * delim; unsigned int rows; unsigned int cols; char ** table; } CSV; int trim(char ** str) { int trimmed; int n; int len; len = strlen(*str); n = len - 1; while((n>=0) && isspace((*str)[n])) { (*str)[n] = '\0'; trimmed += 1; n--; } n = 0; while((n < len) && (isspace((*str)[0]))) { (*str)[0] = '\0'; *str = (*str)+1; trimmed += 1; n++; } return trimmed; } int csv_destroy(CSV * csv) { if (csv == NULL) { return 0; } if (csv->table != NULL) { free(csv->table); } if (csv->delim != NULL) { free(csv->delim); } free(csv); return 0; } CSV * csv_create(unsigned int cols, unsigned int rows) { CSV * csv; csv = malloc(sizeof(CSV)); csv->rows = rows; csv->cols = cols; csv->delim = strdup(); csv->table = malloc(sizeof(char *) * cols * rows); if (csv->table == NULL) { goto error; } memset(csv->table, 0, sizeof(char *) * cols * rows); return csv; error: csv_destroy(csv); return NULL; } char * csv_get(CSV * csv, unsigned int col, unsigned int row) { unsigned int idx; idx = col + (row * csv->cols); return csv->table[idx]; } int csv_set(CSV * csv, unsigned int col, unsigned int row, char * value) { unsigned int idx; idx = col + (row * csv->cols); csv->table[idx] = value; return 0; } void csv_display(CSV * csv) { int row, col; char * content; if ((csv->rows == 0) || (csv->cols==0)) { printf(); return ; } printf(, csv->cols, csv->rows); for (row=0; row<csv->rows; row++) { printf(); for (col=0; col<csv->cols; col++) { content = csv_get(csv, col, row); printf(, content); } printf(); } printf(); } int csv_resize(CSV * old_csv, unsigned int new_cols, unsigned int new_rows) { unsigned int cur_col, cur_row, max_cols, max_rows; CSV * new_csv; char * content; bool in_old, in_new; new_csv = csv_create(new_cols, new_rows); if (new_csv == NULL) { goto error; } new_csv->rows = new_rows; new_csv->cols = new_cols; max_cols = (new_cols > old_csv->cols)? new_cols : old_csv->cols; max_rows = (new_rows > old_csv->rows)? new_rows : old_csv->rows; for (cur_col=0; cur_col<max_cols; cur_col++) { for (cur_row=0; cur_row<max_rows; cur_row++) { in_old = (cur_col < old_csv->cols) && (cur_row < old_csv->rows); in_new = (cur_col < new_csv->cols) && (cur_row < new_csv->rows); if (in_old && in_new) { content = csv_get(old_csv, cur_col, cur_row); csv_set(new_csv, cur_col, cur_row, content); } else if (in_old) { content = csv_get(old_csv, cur_col, cur_row); free(content); } else { } } } free(old_csv->table); old_csv->rows = new_rows; old_csv->cols = new_cols; old_csv->table = new_csv->table; new_csv->table = NULL; csv_destroy(new_csv); return 0; error: printf(, errno, strerror(errno)); return -1; } int csv_open(CSV * csv, char * filename) { FILE * fp; unsigned int m_rows; unsigned int m_cols, cols; char line[2048]; char * lineptr; char * token; fp = fopen(filename, ); if (fp == NULL) { goto error; } m_rows = 0; m_cols = 0; while(fgets(line, sizeof(line), fp) != NULL) { m_rows += 1; cols = 0; lineptr = line; while ((token = strtok(lineptr, csv->delim)) != NULL) { lineptr = NULL; trim(&token); cols += 1; if (cols > m_cols) { m_cols = cols; } csv_resize(csv, m_cols, m_rows); csv_set(csv, cols-1, m_rows-1, strdup(token)); } } fclose(fp); csv->rows = m_rows; csv->cols = m_cols; return 0; error: fclose(fp); printf(, filename); return -1; } int csv_save(CSV * csv, char * filename) { FILE * fp; int row, col; char * content; fp = fopen(filename, ); for (row=0; row<csv->rows; row++) { for (col=0; col<csv->cols; col++) { content = csv_get(csv, col, row); fprintf(fp, , content, ((col == csv->cols-1) ? : csv->delim) ); } fprintf(fp, ); } fclose(fp); return 0; } int main(int argc, char ** argv) { CSV * csv; printf(,TITLE, URL); csv = csv_create(0, 0); csv_open(csv, ); csv_display(csv); csv_set(csv, 0, 0, ); csv_set(csv, 1, 1, ); csv_set(csv, 2, 2, ); csv_set(csv, 3, 3, ); csv_set(csv, 4, 4, ); csv_display(csv); csv_save(csv, ); csv_destroy(csv); return 0; }
983CSV data manipulation
5c
e8hav
import Data.Char (digitToInt) import Text.Printf (printf) damm :: String -> Bool damm = (==0) . foldl (\r -> (table !! r !!) . digitToInt) 0 where table = [ [0, 3, 1, 7, 5, 9, 8, 6, 4, 2] , [7, 0, 9, 2, 1, 5, 4, 8, 6, 3] , [4, 2, 0, 6, 8, 7, 1, 3, 5, 9] , [1, 7, 5, 0, 9, 8, 3, 4, 2, 6] , [6, 1, 2, 3, 0, 4, 5, 9, 7, 8] , [3, 6, 7, 4, 2, 0, 9, 5, 8, 1] , [5, 8, 6, 9, 7, 2, 0, 1, 3, 4] , [8, 9, 4, 5, 3, 6, 2, 0, 1, 7] , [9, 4, 3, 8, 6, 1, 7, 2, 0, 5] , [2, 5, 8, 1, 4, 3, 6, 7, 9, 0] ] main :: IO () main = mapM_ (uncurry(printf "%6s is valid:%s\n") . ((,) <*> show . damm) . show) [5724, 5727, 112946, 112949]
974Damm algorithm
8haskell
6vc3k
import java.nio.file.Files import java.nio.file.Path import java.nio.file.Paths class CreateFile { static void main(String[] args) throws IOException { String os = System.getProperty("os.name") if (os.contains("Windows")) { Path path = Paths.get("tape.file") Files.write(path, Collections.singletonList("Hello World!")) } else { Path path = Paths.get("/dev/tape") Files.write(path, Collections.singletonList("Hello World!")) } } }
980Create a file on magnetic tape
7groovy
5h2uv
module Main (main) where main :: IO () main = writeFile "/dev/tape" "Hello from Rosetta Code!"
980Create a file on magnetic tape
8haskell
ozs8p
import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.util.Collections; public class CreateFile { public static void main(String[] args) throws IOException { String os = System.getProperty("os.name"); if (os.contains("Windows")) { Path path = Paths.get("tape.file"); Files.write(path, Collections.singletonList("Hello World!")); } else { Path path = Paths.get("/dev/tape"); Files.write(path, Collections.singletonList("Hello World!")); } } }
980Create a file on magnetic tape
9java
wo1ej
const money = require('money-math') let hamburgers = 4000000000000000 let hamburgerPrice = 5.50 let shakes = 2 let shakePrice = 2.86 let tax = 7.65 let hamburgerTotal = money.mul(hamburgers.toFixed(0), money.floatToAmount(hamburgerPrice)) let shakeTotal = money.mul(shakes.toFixed(0), money.floatToAmount(shakePrice)) let subTotal = money.add(hamburgerTotal, shakeTotal) let taxTotal = money.percent(subTotal, tax) let total = money.add(subTotal, taxTotal) console.log('Hamburger Total:', hamburgerTotal) console.log('Shake Total:', shakeTotal) console.log('Sub Total:', subTotal) console.log('Tax:', taxTotal) console.log('Total:', total)
978Currency
10javascript
6v638
str = string.lower( "March 7 2009 7:30pm EST" ) month = string.match( str, "%a+" ) if month == "january" then month = 1 elseif month == "february" then month = 2 elseif month == "march" then month = 3 elseif month == "april" then month = 4 elseif month == "may" then month = 5 elseif month == "june" then month = 6 elseif month == "july" then month = 7 elseif month == "august" then month = 8 elseif month == "september" then month = 9 elseif month == "october" then month = 10 elseif month == "november" then month = 11 elseif month == "december" then month = 12 end strproc = string.gmatch( str, "%d+" ) day = strproc() year = strproc() hour = strproc() min = strproc() if string.find( str, "pm" ) then hour = hour + 12 end print( os.date( "%c", os.time{ year=year, month=month, day=day, hour=hour, min=min, sec=0 } + 12 * 3600 ) )
970Date manipulation
1lua
108po
(() => { 'use strict';
973CUSIP
10javascript
bqwki
null
980Create a file on magnetic tape
11kotlin
bxjkb
require "lfs" local out if lfs.attributes('/dev/tape') then out = '/dev/tape' else out = 'tape.file' end file = io.open(out, 'w') file:write('Hello world') io.close(file)
980Create a file on magnetic tape
1lua
pqhbw
null
978Currency
11kotlin
0t0sf
public class Currier<ARG1, ARG2, RET> { public interface CurriableFunctor<ARG1, ARG2, RET> { RET evaluate(ARG1 arg1, ARG2 arg2); } public interface CurriedFunctor<ARG2, RET> { RET evaluate(ARG2 arg); } final CurriableFunctor<ARG1, ARG2, RET> functor; public Currier(CurriableFunctor<ARG1, ARG2, RET> fn) { functor = fn; } public CurriedFunctor<ARG2, RET> curry(final ARG1 arg1) { return new CurriedFunctor<ARG2, RET>() { public RET evaluate(ARG2 arg2) { return functor.evaluate(arg1, arg2); } }; } public static void main(String[] args) { Currier.CurriableFunctor<Integer, Integer, Integer> add = new Currier.CurriableFunctor<Integer, Integer, Integer>() { public Integer evaluate(Integer arg1, Integer arg2) { return new Integer(arg1.intValue() + arg2.intValue()); } }; Currier<Integer, Integer, Integer> currier = new Currier<Integer, Integer, Integer>(add); Currier.CurriedFunctor<Integer, Integer> add5 = currier.curry(new Integer(5)); System.out.println(add5.evaluate(new Integer(2))); } }
975Currying
9java
dmzn9
use std::{mem,ptr}; fn main() { let mut data: i32;
979Create an object at a given address
15rust
e81aj
package require critcl # A command to 'make an integer object' and couple it to a Tcl variable critcl::cproc linkvar {Tcl_Interp* interp char* var1} int { int *intPtr = (int *) ckalloc(sizeof(int)); *intPtr = 0; Tcl_LinkVar(interp, var1, (void *) intPtr, TCL_LINK_INT); return (int) intPtr; } # A command to couple another Tcl variable to an 'integer object'; UNSAFE! critcl::cproc linkagain(Tcl_Interp* interp int addr char* var2} void { int *intPtr = (int *) addr; Tcl_LinkVar(interp, var2, (void *) intPtr, TCL_LINK_INT); } # Conventionally, programs that use critcl structure in packages # This is used to prevent recompilation, especially on systems like Windows package provide machAddrDemo 1
979Create an object at a given address
16scala
qnwxw
package main import "fmt" import "time" func main() { for year := 2008; year <= 2121; year++ { if time.Date(year, 12, 25, 0, 0, 0, 0, time.UTC).Weekday() == time.Sunday { fmt.Printf("25 December%d is Sunday\n", year) } } }
971Day of the week
0go
qddxz
null
973CUSIP
11kotlin
vjr21
public class DammAlgorithm { private static final int[][] table = { {0, 3, 1, 7, 5, 9, 8, 6, 4, 2}, {7, 0, 9, 2, 1, 5, 4, 8, 6, 3}, {4, 2, 0, 6, 8, 7, 1, 3, 5, 9}, {1, 7, 5, 0, 9, 8, 3, 4, 2, 6}, {6, 1, 2, 3, 0, 4, 5, 9, 7, 8}, {3, 6, 7, 4, 2, 0, 9, 5, 8, 1}, {5, 8, 6, 9, 7, 2, 0, 1, 3, 4}, {8, 9, 4, 5, 3, 6, 2, 0, 1, 7}, {9, 4, 3, 8, 6, 1, 7, 2, 0, 5}, {2, 5, 8, 1, 4, 3, 6, 7, 9, 0}, }; private static boolean damm(String s) { int interim = 0; for (char c : s.toCharArray()) interim = table[interim][c - '0']; return interim == 0; } public static void main(String[] args) { int[] numbers = {5724, 5727, 112946, 112949}; for (Integer number : numbers) { boolean isValid = damm(number.toString()); if (isValid) { System.out.printf("%6d is valid\n", number); } else { System.out.printf("%6d is invalid\n", number); } } } }
974Damm algorithm
9java
nyzih
>>> with open('/dev/tape', 'w') as t: t.write('Hi Tape!\n') ... >>>
980Create a file on magnetic tape
3python
yvz6q
C = setmetatable(require("bc"), {__call=function(t,...) return t.new(...) end}) C.digits(6)
978Currency
1lua
8z80e
function addN(n) { var curry = function(x) { return x + n; }; return curry; } add2 = addN(2); alert(add2); alert(add2(7));
975Currying
10javascript
6v938
def yuletide = { start, stop -> (start..stop).findAll { Date.parse("yyyy-MM-dd", "${it}-12-25").format("EEE") == "Sun" } }
971Day of the week
7groovy
100p6
import Data.Time (fromGregorian) import Data.Time.Calendar.WeekDate (toWeekDate) isXmasSunday :: Integer -> Bool isXmasSunday year = 7 == weekDay where (_, _, weekDay) = toWeekDate $ fromGregorian year 12 25 main :: IO () main = mapM_ putStrLn [ "Sunday 25 December " <> show year | year <- [2008 .. 2121], isXmasSunday year ]
971Day of the week
8haskell
m55yf
function checkDigit (cusip) if #cusip ~= 8 then return false end local sum, c, v, p = 0 for i = 1, 8 do c = cusip:sub(i, i) if c:match("%d") then v = tonumber(c) elseif c:match("%a") then p = string.byte(c) - 55 v = p + 9 elseif c == "*" then v = 36 elseif c == "@" then v = 37 elseif c == "#" then v = 38 end if i % 2 == 0 then v = v * 2 end sum = sum + math.floor(v / 10) + v % 10 end return tostring((10 - (sum % 10)) % 10) end local testCases = { "037833100", "17275R102", "38259P508", "594918104", "68389X106", "68389X105" } for _, CUSIP in pairs(testCases) do io.write(CUSIP .. ": ") if checkDigit(CUSIP:sub(1, 8)) == CUSIP:sub(9, 9) then print("VALID") else print("INVALID") end end
973CUSIP
1lua
uh7vl
(defn stateful-std-deviation[x] (letfn [(std-dev[x] (let [v (deref (find-var (symbol (str *ns* "/v"))))] (swap! v conj x) (let [m (/ (reduce + @v) (count @v))] (Math/sqrt (/ (reduce + (map #(* (- m %) (- m %)) @v)) (count @v))))))] (when (nil? (resolve 'v)) (intern *ns* 'v (atom []))) (std-dev x)))
982Cumulative standard deviation
6clojure
62d3q
(require '[clojure.data.csv:as csv] '[clojure.java.io:as io]) (defn add-sum-column [coll] (let [titles (first coll) values (rest coll)] (cons (conj titles "SUM") (map #(conj % (reduce + (map read-string %))) values)))) (with-open [in-file (io/reader "test_in.csv")] (doall (let [out-data (add-sum-column (csv/read-csv in-file))] (with-open [out-file (io/writer "test_out.csv")] (csv/write-csv out-file out-data)))))
983CSV data manipulation
6clojure
0fasj
const table = [ [0, 3, 1, 7, 5, 9, 8, 6, 4, 2], [7, 0, 9, 2, 1, 5, 4, 8, 6, 3], [4, 2, 0, 6, 8, 7, 1, 3, 5, 9], [1, 7, 5, 0, 9, 8, 3, 4, 2, 6], [6, 1, 2, 3, 0, 4, 5, 9, 7, 8], [3, 6, 7, 4, 2, 0, 9, 5, 8, 1], [5, 8, 6, 9, 7, 2, 0, 1, 3, 4], [8, 9, 4, 5, 3, 6, 2, 0, 1, 7], [9, 4, 3, 8, 6, 1, 7, 2, 0, 5], [2, 5, 8, 1, 4, 3, 6, 7, 9, 0], ]; const lookup = (p, c) => table[p][parseInt(c, 10)] const damm = input => [...input].reduce(lookup, 0) === 0;
974Damm algorithm
10javascript
329z0
File.open(, ) do |fh| fh.syswrite() end
980Create a file on magnetic tape
14ruby
956mz
use std::io::Write; use std::fs::File; fn main() -> std::io::Result<()> { File::open("/dev/tape")?.write_all(b"Hello from Rosetta Code!") }
980Create a file on magnetic tape
15rust
c4y9z
object LinePrinter extends App { import java.io.{ FileWriter, IOException } { val lp0 = new FileWriter("/dev/tape") lp0.write("Hello, world!") lp0.close() } }
980Create a file on magnetic tape
16scala
v7c2s
null
975Currying
11kotlin
0tisf
use Math::Decimal qw(dec_canonise dec_add dec_mul dec_rndiv_and_rem); @check = ( [<Hamburger 5.50 4000000000000000>], [<Milkshake 2.86 2>] ); my $fmt = "%-10s%8s%18s%22s\n"; printf $fmt, <Item Price Quantity Extension>; my $subtotal = dec_canonise(0); for $line (@check) { ($item,$price,$quant) = @$line; $dp = dec_canonise($price); $dq = dec_canonise($quant); my $extension = dec_mul($dp,$dq); $subtotal = dec_add($subtotal, $extension); printf $fmt, $item, $price, $quant, rnd($extension); } my $rate = dec_canonise(0.0765); my $tax = dec_mul($subtotal,$rate); my $total = dec_add($subtotal,$tax); printf $fmt, '', '', '', '-----------------'; printf $fmt, '', '', 'Subtotal ', rnd($subtotal); printf $fmt, '', '', 'Tax ', rnd($tax); printf $fmt, '', '', 'Total ', rnd($total); sub rnd { ($q, $r) = dec_rndiv_and_rem("FLR", @_[0], 1); $q . substr((sprintf "%.2f", $r), 1, 3); }
978Currency
2perl
5k5u2
null
974Damm algorithm
11kotlin
sfiq7
use DateTime; use DateTime::Format::Strptime 'strptime'; use feature 'say'; my $input = 'March 7 2009 7:30pm EST'; $input =~ s{EST}{America/New_York}; say strptime('%b%d%Y%I:%M%p%O', $input) ->add(hours => 12) ->set_time_zone('America/Edmonton') ->format_cldr('MMMM d yyyy h:mma zzz');
970Date manipulation
2perl
yu56u
import java.util.Calendar; import java.util.Date; import java.util.GregorianCalendar; public class Yuletide{ public static void main(String[] args) { for(int i = 2008;i<=2121;i++){ Calendar cal = new GregorianCalendar(i, Calendar.DECEMBER, 25); if(cal.get(Calendar.DAY_OF_WEEK)==Calendar.SUNDAY){ System.out.println(cal.getTime()); } } } }
971Day of the week
9java
f99dv
local tab = { {0,3,1,7,5,9,8,6,4,2}, {7,0,9,2,1,5,4,8,6,3}, {4,2,0,6,8,7,1,3,5,9}, {1,7,5,0,9,8,3,4,2,6}, {6,1,2,3,0,4,5,9,7,8}, {3,6,7,4,2,0,9,5,8,1}, {5,8,6,9,7,2,0,1,3,4}, {8,9,4,5,3,6,2,0,1,7}, {9,4,3,8,6,1,7,2,0,5}, {2,5,8,1,4,3,6,7,9,0} } function check( n ) local idx, a = 0, tonumber( n:sub( 1, 1 ) ) for i = 1, #n do a = tonumber( n:sub( i, i ) ) if a == nil then return false end idx = tab[idx + 1][a + 1] end return idx == 0 end local n, r while( true ) do io.write( "Enter the number to check: " ) n = io.read(); if n == "0" then break end r = check( n ); io.write( n, " is " ) if not r then io.write( "in" ) end io.write( "valid!\n" ) end
974Damm algorithm
1lua
0tnsd
from decimal import Decimal as D from collections import namedtuple Item = namedtuple('Item', 'price, quant') items = dict( hamburger=Item(D('5.50'), D('4000000000000000')), milkshake=Item(D('2.86'), D('2')) ) tax_rate = D('0.0765') fmt = print(fmt% tuple('Item Price Quantity Extension'.upper().split())) total_before_tax = 0 for item, (price, quant) in sorted(items.items()): ext = price * quant print(fmt% (item, price, quant, ext)) total_before_tax += ext print(fmt% ('', '', '', '--------------------')) print(fmt% ('', '', 'subtotal', total_before_tax)) tax = (tax_rate * total_before_tax).quantize(D('0.00')) print(fmt% ('', '', 'Tax', tax)) total = total_before_tax + tax print(fmt% ('', '', '', '--------------------')) print(fmt% ('', '', 'Total', total))
978Currency
3python
4b45k
function curry2(f) return function(x) return function(y) return f(x,y) end end end function add(x,y) return x+y end local adder = curry2(add) assert(adder(3)(4) == 3+4) local add2 = adder(2) assert(add2(3) == 2+3) assert(add2(5) == 2+5)
975Currying
1lua
8zn0e
<?php $time = new DateTime('March 7 2009 7:30pm EST'); $time->modify('+12 hours'); echo $time->format('c'); ?>
970Date manipulation
12php
a8o12
for (var year = 2008; year <= 2121; year++){ var xmas = new Date(year, 11, 25) if ( xmas.getDay() === 0 ) console.log(year) }
971Day of the week
10javascript
yuu6r
$cv{$_} = $i++ for '0'..'9', 'A'..'Z', '*', '@', ' sub cusip_check_digit { my @cusip = split m{}xms, shift; my $sum = 0; for $i (0..7) { return 'Invalid character found' unless $cusip[$i] =~ m{\A [[:digit:][:upper:]*@ $v = $cv{ $cusip[$i] }; $v *= 2 if $i%2; $sum += int($v/10) + $v%10; } $check_digit = (10 - ($sum%10)) % 10; $check_digit == $cusip[8] ? '' : ' (incorrect)'; } my %test_data = ( '037833100' => 'Apple Incorporated', '17275R102' => 'Cisco Systems', '38259P508' => 'Google Incorporated', '594918104' => 'Microsoft Corporation', '68389X106' => 'Oracle Corporation', '68389X105' => 'Oracle Corporation', ); print "$_ $test_data{$_}" . cusip_check_digit($_) . "\n" for sort keys %test_data;
973CUSIP
2perl
0tds4
int main() { const char *s = ; printf(, crc32(0, (const void*)s, strlen(s))); return 0; }
984CRC-32
5c
xikwu
package main import "time" import "fmt" func main() { fmt.Println(time.Now().Format("2006-01-02")) fmt.Println(time.Now().Format("Monday, January 2, 2006")) }
977Date format
0go
ps1bg
def isoFormat = { date -> date.format("yyyy-MM-dd") } def longFormat = { date -> date.format("EEEE, MMMM dd, yyyy") }
977Date format
7groovy
7ajrz
package main import ( "fmt" "math/big" ) 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() { var z big.Int var cube1, cube2, cube100k, diff uint64 cubans := make([]string, 200) cube1 = 1 count := 0 for i := 1; ; i++ { j := i + 1 cube2 = uint64(j * j * j) diff = cube2 - cube1 z.SetUint64(diff) if z.ProbablyPrime(0) {
981Cuban primes
0go
ujcvt
import Data.Time (FormatTime, formatTime, defaultTimeLocale, utcToLocalTime, getCurrentTimeZone, getCurrentTime) formats :: FormatTime t => [t -> String] formats = (formatTime defaultTimeLocale) <$> ["%F", "%A,%B%d,%Y"] main :: IO () main = do t <- pure utcToLocalTime <*> getCurrentTimeZone <*> getCurrentTime putStrLn $ unlines (formats <*> pure t)
977Date format
8haskell
f9td1
class CubanPrimes { private static int MAX = 1_400_000 private static boolean[] primes = new boolean[MAX] static void main(String[] args) { preCompute() cubanPrime(200, true) for (int i = 1; i <= 5; i++) { int max = (int) Math.pow(10, i) printf("%,d-th cuban prime =%,d%n", max, cubanPrime(max, false)) } } private static long cubanPrime(int n, boolean display) { int count = 0 long result = 0 for (long i = 0; count < n; i++) { long test = 1l + 3 * i * (i + 1) if (isPrime(test)) { count++ result = test if (display) { printf("%10s%s", String.format("%,d", test), count % 10 == 0 ? "\n": "") } } } return result } private static boolean isPrime(long n) { if (n < MAX) { return primes[(int) n] } int max = (int) Math.sqrt(n) for (int i = 3; i <= max; i++) { if (primes[i] && n % i == 0) { return false } } return true } private static final void preCompute() {
981Cuban primes
7groovy
953m4
null
971Day of the week
11kotlin
8zz0q
function IsCusip(string $s) { if (strlen($s) != 9) return false; $sum = 0; for ($i = 0; $i <= 7; $i++) { $c = $s[$i]; if (ctype_digit($c)) { $v = intval($c); } elseif (ctype_alpha($c)) { $position = ord(strtoupper($c)) - ord('A') + 1; $v = $position + 9; } elseif ($c == ) { $v = 36; } elseif ($c == ) { $v = 37; } elseif ($c == ) { $v = 38; } else { return false; } if ($i % 2 == 1) { $v *= 2; } $sum += floor($v / 10 ) + ( $v % 10 ); } return ord($s[8]) - 48 == (10 - ($sum % 10)) % 10; } $cusips = array(, , , , , ); foreach ($cusips as $cusip) echo $cusip . . (IsCusip($cusip)? : ) . ;
973CUSIP
12php
5kjus
(let [crc (new java.util.zip.CRC32) str "The quick brown fox jumps over the lazy dog"] (. crc update (. str getBytes)) (printf "CRC-32('%s') =%s\n" str (Long/toHexString (. crc getValue))))
984CRC-32
6clojure
oze8j