code
stringlengths
1
46.1k
label
class label
1.18k classes
domain_label
class label
21 classes
index
stringlengths
4
5
import Data.Numbers.Primes (isPrime) import Data.List (intercalate) import Data.List.Split (chunksOf) import Text.Printf (printf) cubans :: [Int] cubans = filter isPrime . map (\x -> (succ x ^ 3) - (x ^ 3)) $ [1 ..] main :: IO () main = do mapM_ (\row -> mapM_ (printf "%10s" . thousands) row >> printf "\n") $ rows cubans printf "\nThe 100,000th cuban prime is:%10s\n" $ thousands $ cubans !! 99999 where rows = chunksOf 10 . take 200 thousands = reverse . intercalate "," . chunksOf 3 . reverse . show
981Cuban primes
8haskell
woped
require 'bigdecimal/util' before_tax = 4000000000000000 * 5.50.to_d + 2 * 2.86.to_d tax = (before_tax * 0.0765.to_d).round(2) total = before_tax + tax puts
978Currency
14ruby
r1rgs
extern crate num_bigint;
978Currency
15rust
7a7rc
sub curry{ my ($func, @args) = @_; sub { &$func(@args, @_); } } sub plusXY{ $_[0] + $_[1]; } my $plusXOne = curry(\&plusXY, 1); print &$plusXOne(3), "\n";
975Currying
2perl
5kru2
import datetime def mt(): datime1= formatting = datime2 = datime1[:-3] tdelta = datetime.timedelta(hours=12) s3 = datetime.datetime.strptime(datime2, formatting) datime2 = s3+tdelta print datime2.strftime() + datime1[-3:] mt()
970Date manipulation
3python
m54yh
time <- strptime("March 7 2009 7:30pm EST", "%B%d%Y%I:%M%p%Z") isotime <- ISOdatetime(1900 + time$year, time$mon, time$mday, time$hour, time$min, time$sec, "EST") twelvehourslater <- isotime + 12 * 60 * 60 timeincentraleurope <- format(isotime, tz="CET", usetz=TRUE)
970Date manipulation
13r
zl2th
import java.util.Calendar; import java.util.GregorianCalendar; import java.text.DateFormatSymbols; import java.text.DateFormat; public class Dates{ public static void main(String[] args){ Calendar now = new GregorianCalendar();
977Date format
9java
0t8se
public class CubanPrimes { private static int MAX = 1_400_000; private static boolean[] primes = new boolean[MAX]; public static void main(String[] args) { preCompute(); cubanPrime(200, true); for ( int i = 1 ; i <= 5 ; i++ ) { int max = (int) Math.pow(10, i); System.out.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 ) { System.out.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
9java
kwrhm
import java.text.NumberFormat import java.util.Locale object SizeMeUp extends App { val menu: Map[String, (String, Double)] = Map("burg" ->("Hamburger XL", 5.50), "milk" ->("Milkshake", 2.86)) val order = List((4000000000000000L, "burg"), (2L, "milk")) Locale.setDefault(new Locale("ru", "RU")) val (currSymbol, tax) = (NumberFormat.getInstance().getCurrency.getSymbol, 0.0765) def placeOrder(order: List[(Long, String)]) = { val totals = for ((qty, article) <- order) yield { val (desc, itemPrize) = menu(article) val (items, post) = (qty, qty * BigDecimal(itemPrize)) println(f"$qty%16d\t$desc%-16s\t$currSymbol%4s$itemPrize%6.2f\t$post%,25.2f") (items, post) } totals.foldLeft((0L, BigDecimal(0))) { (acc, n) => (acc._1 + n._1, acc._2 + n._2)} } val (items, beforeTax) = placeOrder(order) println(f"$items%16d\t${"ordered items"}%-16s${'\t' + " Subtotal" + '\t'}$beforeTax%,25.2f") val taxation = beforeTax * tax println(f"${" " * 16 + '\t' + " " * 16 + '\t' + f"${tax * 100}%5.2f%% tax" + '\t'}$taxation%,25.2f") println(f"${" " * 16 + '\t' + " " * 16 + '\t' + "Amount due" + '\t'}${beforeTax + taxation}%,25.2f") }
978Currency
16scala
kxkhk
<?php function curry($callable) { if (_number_of_required_params($callable) === 0) { return _make_function($callable); } if (_number_of_required_params($callable) === 1) { return _curry_array_args($callable, _rest(func_get_args())); } return _curry_array_args($callable, _rest(func_get_args())); } function _curry_array_args($callable, $args, $left = true) { return function () use ($callable, $args, $left) { if (_is_fullfilled($callable, $args)) { return _execute($callable, $args, $left); } $newArgs = array_merge($args, func_get_args()); if (_is_fullfilled($callable, $newArgs)) { return _execute($callable, $newArgs, $left); } return _curry_array_args($callable, $newArgs, $left); }; } function _number_of_required_params($callable) { if (is_array($callable)) { $refl = new \ReflectionClass($callable[0]); $method = $refl->getMethod($callable[1]); return $method->getNumberOfRequiredParameters(); } $refl = new \ReflectionFunction($callable); return $refl->getNumberOfRequiredParameters(); } function _make_function($callable) { if (is_array($callable)) return function() use($callable) { return call_user_func_array($callable, func_get_args()); }; return $callable; } function _execute($callable, $args, $left) { if (! $left) { $args = array_reverse($args); } $placeholders = _placeholder_positions($args); if (0 < count($placeholders)) { $n = _number_of_required_params($callable); if ($n <= _last($placeholders[count($placeholders) - 1])) { throw new \Exception('Argument Placeholder found on unexpected position!'); } foreach ($placeholders as $i) { $args[$i] = $args[$n]; array_splice($args, $n, 1); } } return call_user_func_array($callable, $args); } function _placeholder_positions($args) { return array_keys(array_filter($args, '_is_placeholder')); } function _is_fullfilled($callable, $args) { $args = array_filter($args, function($arg) { return ! _is_placeholder($arg); }); return count($args) >= _number_of_required_params($callable); } function _is_placeholder($arg) { return $arg instanceof Placeholder; } function _rest(array $args) { return array_slice($args, 1); } function product($a, $b) { return $a * $b; } echo json_encode(array_map(curry('product', 7), [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]));
975Currying
12php
o3d85
import math def cusip_check(cusip): if len(cusip) != 9: raise ValueError('CUSIP must be 9 characters') cusip = cusip.upper() total = 0 for i in range(8): c = cusip[i] if c.isdigit(): v = int(c) elif c.isalpha(): p = ord(c) - ord('A') + 1 v = p + 9 elif c == '*': v = 36 elif c == '@': v = 37 elif c == ' v = 38 if i% 2 != 0: v *= 2 total += int(v / 10) + v% 10 check = (10 - (total% 10))% 10 return str(check) == cusip[-1] if __name__ == '__main__': codes = [ '037833100', '17275R102', '38259P508', '594918104', '68389X106', '68389X105' ] for code in codes: print(f'{code} -> {cusip_check(code)}')
973CUSIP
3python
8zf0o
var now = new Date(), weekdays = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'], months = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'], fmt1 = now.getFullYear() + '-' + (1 + now.getMonth()) + '-' + now.getDate(), fmt2 = weekdays[now.getDay()] + ', ' + months[now.getMonth()] + ' ' + now.getDate() + ', ' + now.getFullYear(); console.log(fmt1); console.log(fmt2);
977Date format
10javascript
dmfnu
sub damm { my(@digits) = split '', @_[0]; my @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 >] ); my $row = 0; for my $col (@digits) { $row = $tbl[$row][$col] } not $row } for (5724, 5727, 112946) { print "$_:\tChecksum digit @{[damm($_)? '': 'in']}correct.\n" }
974Damm algorithm
2perl
uhrvr
require("date") for year=2008,2121 do if date(year, 12, 25):getweekday() == 1 then print(year) end end
971Day of the week
1lua
o338h
import kotlin.math.ceil import kotlin.math.sqrt fun main() { val primes = mutableListOf(3L, 5L) val cutOff = 200 val bigUn = 100_000 val chunks = 50 val little = bigUn / chunks println("The first $cutOff cuban primes:") var showEach = true var c = 0 var u = 0L var v = 1L var i = 1L while (i > 0) { var found = false u += 6 v += u val mx = ceil(sqrt(v.toDouble())).toInt() for (item in primes) { if (item > mx) break if (v % item == 0L) { found = true break } } if (!found) { c++ if (showEach) { var z = primes.last() + 2 while (z <= v - 2) { var fnd = false for (item in primes) { if (item > mx) break if (z % item == 0L) { fnd = true break } } if (!fnd) { primes.add(z) } z += 2 } primes.add(v) print("%11d".format(v)) if (c % 10 == 0) println() if (c == cutOff) { showEach = false print("\nProgress to the ${bigUn}th cuban prime: ") } } if (c % little == 0) { print(".") if (c == bigUn) break } } i++ } println("\nThe%dth cuban prime is%17d".format(c, v)) }
981Cuban primes
11kotlin
gbv4d
import Foundation extension Decimal { func rounded(_ scale: Int, _ roundingMode: NSDecimalNumber.RoundingMode) -> Decimal { var result = Decimal() var localCopy = self NSDecimalRound(&result, &localCopy, scale, roundingMode) return result } } let costHamburgers = Decimal(4000000000000000) * Decimal(5.50) let costMilkshakes = Decimal(2) * Decimal(2.86) let totalBeforeTax = costMilkshakes + costHamburgers let taxesToBeCollected = (Decimal(string: "0.0765")! * totalBeforeTax).rounded(2, .bankers) print("Price before tax: $\(totalBeforeTax)") print("Total tax to be collected: $\(taxesToBeCollected)") print("Total with taxes: $\(totalBeforeTax + taxesToBeCollected)")
978Currency
17swift
gpg49
def addN(n): def adder(x): return x + n return adder
975Currying
3python
4b75k
null
977Date format
11kotlin
eowa4
typedef struct { int n; double **elems; } SquareMatrix; SquareMatrix init_square_matrix(int n, double elems[n][n]) { SquareMatrix A = { .n = n, .elems = malloc(n * sizeof(double *)) }; for(int i = 0; i < n; ++i) { A.elems[i] = malloc(n * sizeof(double)); for(int j = 0; j < n; ++j) A.elems[i][j] = elems[i][j]; } return A; } SquareMatrix copy_square_matrix(SquareMatrix src) { SquareMatrix dest; dest.n = src.n; dest.elems = malloc(dest.n * sizeof(double *)); for(int i = 0; i < dest.n; ++i) { dest.elems[i] = malloc(dest.n * sizeof(double)); for(int j = 0; j < dest.n; ++j) dest.elems[i][j] = src.elems[i][j]; } return dest; } double det(SquareMatrix A) { double det = 1; for(int j = 0; j < A.n; ++j) { int i_max = j; for(int i = j; i < A.n; ++i) if(A.elems[i][j] > A.elems[i_max][j]) i_max = i; if(i_max != j) { for(int k = 0; k < A.n; ++k) { double tmp = A.elems[i_max][k]; A.elems[i_max][k] = A.elems[j][k]; A.elems[j][k] = tmp; } det *= -1; } if(abs(A.elems[j][j]) < 1e-12) { puts(); return NAN; } for(int i = j + 1; i < A.n; ++i) { double mult = -A.elems[i][j] / A.elems[j][j]; for(int k = 0; k < A.n; ++k) A.elems[i][k] += mult * A.elems[j][k]; } } for(int i = 0; i < A.n; ++i) det *= A.elems[i][i]; return det; } void deinit_square_matrix(SquareMatrix A) { for(int i = 0; i < A.n; ++i) free(A.elems[i]); free(A.elems); } double cramer_solve(SquareMatrix A, double det_A, double *b, int var) { SquareMatrix tmp = copy_square_matrix(A); for(int i = 0; i < tmp.n; ++i) tmp.elems[i][var] = b[i]; double det_tmp = det(tmp); deinit_square_matrix(tmp); return det_tmp / det_A; } int main(int argc, char **argv) { double elems[N][N] = { { 2, -1, 5, 1}, { 3, 2, 2, -6}, { 1, 3, 3, -1}, { 5, -2, -3, 3} }; SquareMatrix A = init_square_matrix(N, elems); SquareMatrix tmp = copy_square_matrix(A); int det_A = det(tmp); deinit_square_matrix(tmp); double b[] = {-3, -32, -47, 49}; for(int i = 0; i < N; ++i) printf(, cramer_solve(A, det_A, b, i)); deinit_square_matrix(A); return EXIT_SUCCESS; }
985Cramer's rule
5c
yvi6f
<?php function lookup($r,$c) { $table = array( array(0, 3, 1, 7, 5, 9, 8, 6, 4, 2), array(7, 0, 9, 2, 1, 5, 4, 8, 6, 3), array(4, 2, 0, 6, 8, 7, 1, 3, 5, 9), array(1, 7, 5, 0, 9, 8, 3, 4, 2, 6), array(6, 1, 2, 3, 0, 4, 5, 9, 7, 8), array(3, 6, 7, 4, 2, 0, 9, 5, 8, 1), array(5, 8, 6, 9, 7, 2, 0, 1, 3, 4), array(8, 9, 4, 5, 3, 6, 2, 0, 1, 7), array(9, 4, 3, 8, 6, 1, 7, 2, 0, 5), array(2, 5, 8, 1, 4, 3, 6, 7, 9, 0), ); return $table[$r][$c]; } function isDammValid($input) { return array_reduce(str_split($input), , 0) == 0; } foreach(array(, , , ) as $i) { echo .(isDammValid($i)? : ).; } ?>
974Damm algorithm
12php
8zd0m
local primes = {3, 5} local cutOff = 200 local bigUn = 100000 local chunks = 50 local little = math.floor(bigUn / chunks) local tn = " cuban prime" print(string.format("The first%d%ss", cutOff, tn)) local showEach = true local c = 0 local u = 0 local v = 1 for i=1,10000000000000 do local found = false u = u + 6 v = v + u local mx = math.ceil(math.sqrt(v))
981Cuban primes
1lua
rpuga
require 'time' d = t = Time.parse(d) puts t.rfc2822 puts t.zone new = t + 12*3600 puts new.rfc2822 puts new.zone require 'rubygems' require 'active_support' zone = ActiveSupport::TimeZone['Beijing'] remote = zone.at(new) puts remote.rfc2822 puts remote.zone
970Date manipulation
14ruby
cgr9k
int main(int argc, char **argv) { int user1 = 0, user2 = 0; printf(); scanf(,&user1, &user2); int array[user1][user2]; array[user1/2][user2/2] = user1 + user2; printf(,user1/2,user2/2,array[user1/2][user2/2]); return 0; }
986Create a two-dimensional array at runtime
5c
v7z2o
b = proc {|x, y, z| (x||0) + (y||0) + (z||0) } p b.curry[1][2][3] p b.curry[1, 2][3, 4] p b.curry(5)[1][2][3][4][5] p b.curry(5)[1, 2][3, 4][5] p b.curry(1)[1] b = proc {|x, y, z, *w| (x||0) + (y||0) + (z||0) + w.inject(0, &:+) } p b.curry[1][2][3] p b.curry[1, 2][3, 4] p b.curry(5)[1][2][3][4][5] p b.curry(5)[1, 2][3, 4][5] p b.curry(1)[1]
975Currying
14ruby
r1hgs
use chrono::prelude::*; use chrono::Duration; fn main() {
970Date manipulation
15rust
lr7cc
def check_cusip(cusip) abort('CUSIP must be 9 characters') if cusip.size!= 9 sum = 0 cusip.split('').each_with_index do |char, i| next if i == cusip.size - 1 case when char.scan(/\D/).empty? v = char.to_i when char.scan(/\D/).any? pos = char.upcase.ord - 'A'.ord + 1 v = pos + 9 when char == '*' v = 36 when char == '@' v = 37 when char == ' v = 38 end v *= 2 unless (i % 2).zero? sum += (v/10).to_i + (v % 10) end check = (10 - (sum % 10)) % 10 return 'VALID' if check.to_s == cusip.split('').last 'INVALID' end CUSIPs = %w[ 037833100 17275R102 38259P508 594918104 68389X106 68389X105 ] CUSIPs.each do |cusip| puts end
973CUSIP
14ruby
i6zoh
fn add_n(n: i32) -> impl Fn(i32) -> i32 { move |x| n + x } fn main() { let adder = add_n(40); println!("The answer to life is {}.", adder(2)); }
975Currying
15rust
7akrc
def add(a: Int)(b: Int) = a + b val add5 = add(5) _ add5(2)
975Currying
16scala
kx1hk
import java.text.SimpleDateFormat import java.util.{Calendar, Locale, TimeZone} object DateManipulation { def main(args: Array[String]): Unit = { val input="March 7 2009 7:30pm EST" val df=new SimpleDateFormat("MMMM d yyyy h:mma z", Locale.ENGLISH) val c=Calendar.getInstance() c.setTime(df.parse(input)) c.add(Calendar.HOUR_OF_DAY, 12) println(df.format(c.getTime)) df.setTimeZone(TimeZone.getTimeZone("GMT")) println(df.format(c.getTime)) } }
970Date manipulation
16scala
uhkv8
fn cusip_check(cusip: &str) -> bool { if cusip.len()!= 9 { return false; } let mut v = 0; let capital_cusip = cusip.to_uppercase(); let char_indices = capital_cusip.as_str().char_indices().take(7); let total = char_indices.fold(0, |total, (i, c)| { v = match c { '*' => 36, '@' => 37, '#' => 38, _ if c.is_digit(10) => c.to_digit(10).unwrap() as u8, _ if c.is_alphabetic() => (c as u8) - b'A' + 1 + 9, _ => v, }; if i% 2!= 0 { v *= 2 } total + (v / 10) + v% 10 }); let check = (10 - (total% 10))% 10; (check.to_string().chars().nth(0).unwrap()) == cusip.chars().nth(cusip.len() - 1).unwrap() } fn main() { let codes = [ "037833100", "17275R102", "38259P508", "594918104", "68389X106", "68389X105", ]; for code in &codes { println!("{} -> {}", code, cusip_check(code)) } }
973CUSIP
15rust
ny3i4
object Cusip extends App { val candidates = Seq("037833100", "17275R102", "38259P508", "594918104", "68389X106", "68389X105") for (candidate <- candidates) printf(f"$candidate%s -> ${if (isCusip(candidate)) "correct" else "incorrect"}%s%n") private def isCusip(s: String): Boolean = { if (s.length != 9) false else { var sum = 0 for (i <- 0 until 7) { val c = s(i) var v = 0 if (c >= '0' && c <= '9') v = c - 48 else if (c >= 'A' && c <= 'Z') v = c - 55
973CUSIP
16scala
tcmfb
const char *input = ; int main() { const char *s; printf(); for (s = input; *s; s++) { switch(*s) { case '\n': printf(); break; case ',': printf(); break; case '<': printf(); break; case '>': printf(); break; case '&': printf(); break; default: putchar(*s); } } puts(); return 0; }
987CSV to HTML translation
5c
ujzv4
use feature 'say'; use ntheory 'is_prime'; sub cuban_primes { my ($n) = @_; my @primes; for (my $k = 1 ; ; ++$k) { my $p = 3 * $k * ($k + 1) + 1; if (is_prime($p)) { push @primes, $p; last if @primes >= $n; } } return @primes; } sub commify { scalar reverse join ',', unpack '(A3)*', reverse shift; } my @c = cuban_primes(200); while (@c) { say join ' ', map { sprintf "%9s", commify $_ } splice(@c, 0, 10); } say ''; for my $n (1 .. 6) { say "10^$n-th cuban prime is: ", commify((cuban_primes(10**$n))[-1]); }
981Cuban primes
2perl
n60iw
func addN(n:Int)->Int->Int { return {$0 + n} } var add2 = addN(2) println(add2)
975Currying
17swift
gpj49
struct CUSIP { var value: String private static let alphabet = Array("ABCDEFGHIJKLMNOPQRSTUVWXYZ") init?(value: String) { if value.count == 9 && String(value.last!) == CUSIP.checkDigit(cusipString: String(value.dropLast())) { self.value = value } else if value.count == 8, let checkDigit = CUSIP.checkDigit(cusipString: value) { self.value = value + checkDigit } else { return nil } } static func checkDigit(cusipString: String) -> String? { guard cusipString.count == 8, cusipString.allSatisfy({ $0.isASCII }) else { return nil } let sum = cusipString.uppercased().enumerated().reduce(0, {sum, pair in let (i, char) = pair var v: Int switch char { case "*": v = 36 case "@": v = 37 case "#": v = 38 case _ where char.isNumber: v = char.wholeNumberValue! case _: v = Int(char.asciiValue! - 65) + 10 } if i & 1 == 1 { v *= 2 } return sum + (v / 10) + (v% 10) }) return String((10 - (sum% 10))% 10) } } let testCases = [ "037833100", "17275R102", "38259P508", "594918104", "68389X106", "68389X105" ] for potentialCUSIP in testCases { print("\(potentialCUSIP) -> ", terminator: "") switch CUSIP(value: potentialCUSIP) { case nil: print("Invalid") case _: print("Valid") } }
973CUSIP
17swift
o3t8k
(let [rows (Integer/parseInt (read-line)) cols (Integer/parseInt (read-line)) a (to-array-2d (repeat rows (repeat cols nil)))] (aset a 0 0 12) (println "Element at 0,0:" (aget a 0 0)))
986Create a two-dimensional array at runtime
6clojure
rp9g2
print( os.date( "%Y-%m-%d" ) ) print( os.date( "%A,%B%d,%Y" ) )
977Date format
1lua
wixea
package main import ( "encoding/csv" "log" "os" "strconv" ) func main() { rows := readSample() appendSum(rows) writeChanges(rows) } func readSample() [][]string { f, err := os.Open("sample.csv") if err != nil { log.Fatal(err) } rows, err := csv.NewReader(f).ReadAll() f.Close() if err != nil { log.Fatal(err) } return rows } func appendSum(rows [][]string) { rows[0] = append(rows[0], "SUM") for i := 1; i < len(rows); i++ { rows[i] = append(rows[i], sum(rows[i])) } } func sum(row []string) string { sum := 0 for _, s := range row { x, err := strconv.Atoi(s) if err != nil { return "NA" } sum += x } return strconv.Itoa(sum) } func writeChanges(rows [][]string) { f, err := os.Create("output.csv") if err != nil { log.Fatal(err) } err = csv.NewWriter(f).WriteAll(rows) f.Close() if err != nil { log.Fatal(err) } }
983CSV data manipulation
0go
95tmt
def damm(num: int) -> bool: row = 0 for digit in str(num): row = _matrix[row][int(digit)] return row == 0 _matrix = ( (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) ) if __name__ == '__main__': for test in [5724, 5727, 112946]: print(f'{test}\t Validates as: {damm(test)}')
974Damm algorithm
3python
5k7ux
package main import ( "fmt" "hash/crc32" ) func main() { s := []byte("The quick brown fox jumps over the lazy dog") result := crc32.ChecksumIEEE(s) fmt.Printf("%X\n", result) }
984CRC-32
0go
lgzcw
def crc32(byte[] bytes) { new java.util.zip.CRC32().with { update bytes; value } }
984CRC-32
7groovy
62i3o
int main() { FILE *fh = fopen(, ); fclose(fh); return 0; }
988Create a file
5c
gb645
def csv = [] def loadCsv = { source -> source.splitEachLine(/,/) { csv << it.collect { it } } } def saveCsv = { target -> target.withWriter { writer -> csv.each { writer.println it.join(',') } } } loadCsv new File('csv.txt') csv[0][0] = 'Column0' (1..4).each { i -> csv[i][i] = i * 100 } saveCsv new File('csv_out.txt')
983CSV data manipulation
7groovy
zcot5
Damm_algo <- function(number){ row_i = 0 iterable = strsplit(toString(number), "")[[1]] validation_matrix = matrix( c( 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), nrow = 10, ncol = 10, byrow = T ) for(digit in as.integer(iterable)){ row_i = validation_matrix[row_i + 1, digit + 1] } test <- ifelse(row_i == 0, "VALID", "NOT VALID") message(paste("Number", number, "is", test)) } for(number in c(5724, 5727, 112946, 112949)){ Damm_algo(number) }
974Damm algorithm
13r
lr5ce
import datetime import math primes = [ 3, 5 ] cutOff = 200 bigUn = 100_000 chunks = 50 little = bigUn / chunks tn = print (.format(cutOff, tn)) c = 0 showEach = True u = 0 v = 1 st = datetime.datetime.now() for i in range(1, int(math.pow(2,20))): found = False u += 6 v += u mx = int(math.sqrt(v)) for item in primes: if (item > mx): break if (v% item == 0): found = True break if (found == 0): c += 1 if (showEach): z = primes[-1] while (z <= v - 2): z += 2 fnd = False for item in primes: if (item > mx): break if (z% item == 0): fnd = True break if (not fnd): primes.append(z) primes.append(v) print(.format(v), end='') if (c% 10 == 0): print(); if (c == cutOff): showEach = False print (.format(bigUn, tn), end='') if (c% little == 0): print('.', end='') if (c == bigUn): break print(); print (.format(c, tn, v)) print(.format((datetime.datetime.now() - st).seconds))
981Cuban primes
3python
dy8n1
-- March 7 2009 7:30pm EST SELECT TO_TIMESTAMP_TZ( 'March 7 2009 7:30pm EST', 'MONTH DD YYYY HH:MIAM TZR' ) at TIME zone 'US/Eastern' orig_dt_time FROM dual; -- 12 hours later DST change SELECT (TO_TIMESTAMP_TZ( 'March 7 2009 7:30pm EST', 'MONTH DD YYYY HH:MIAM TZR' )+ INTERVAL '12' HOUR) at TIME zone 'US/Eastern' plus_12_dst FROM dual; -- 12 hours later no DST change -- Arizona time, always MST SELECT (TO_TIMESTAMP_TZ( 'March 7 2009 7:30pm EST', 'MONTH DD YYYY HH:MIAM TZR' )+ INTERVAL '12' HOUR) at TIME zone 'US/Arizona' plus_12_nodst FROM dual;
970Date manipulation
19sql
gp14k
import Data.Bits ((.&.), complement, shiftR, xor) import Data.Word (Word32) import Numeric (showHex) crcTable :: Word32 -> Word32 crcTable = (table !!) . fromIntegral where table = ((!! 8) . iterate xf) <$> [0 .. 255] shifted x = shiftR x 1 xf r | r .&. 1 == 1 = xor (shifted r) 0xedb88320 | otherwise = shifted r charToWord :: Char -> Word32 charToWord = fromIntegral . fromEnum calcCrc :: String -> Word32 calcCrc = complement . foldl cf (complement 0) where cf crc x = xor (shiftR crc 8) (crcTable $ xor (crc .&. 0xff) (charToWord x)) crc32 :: String -> String crc32 = flip showHex [] . calcCrc main :: IO () main = putStrLn $ crc32 "The quick brown fox jumps over the lazy dog"
984CRC-32
8haskell
1srps
typedef struct { uint64_t x[2]; } i128; void show(i128 v) { uint32_t x[4] = {v.x[0], v.x[0] >> 32, v.x[1], v.x[1] >> 32}; int i, j = 0, len = 4; char buf[100]; do { uint64_t c = 0; for (i = len; i--; ) { c = (c << 32) + x[i]; x[i] = c / 10, c %= 10; } buf[j++] = c + '0'; for (len = 4; !x[len - 1]; len--); } while (len); while (j--) putchar(buf[j]); putchar('\n'); } i128 count(int sum, int *coins) { int n, i, k; for (n = 0; coins[n]; n++); i128 **v = malloc(sizeof(int*) * n); int *idx = malloc(sizeof(int) * n); for (i = 0; i < n; i++) { idx[i] = coins[i]; v[i] = calloc(sizeof(i128), coins[i]); } v[0][coins[0] - 1] = (i128) {{1, 0}}; for (k = 0; k <= sum; k++) { for (i = 0; i < n; i++) if (!idx[i]--) idx[i] = coins[i] - 1; i128 c = v[0][ idx[0] ]; for (i = 1; i < n; i++) { i128 *p = v[i] + idx[i]; p->x[0] += c.x[0]; p->x[1] += c.x[1]; if (p->x[0] < c.x[0]) p->x[1] ++; c = *p; } } i128 r = v[n - 1][idx[n-1]]; for (i = 0; i < n; i++) free(v[i]); free(v); free(idx); return r; } int count2(int sum, int *coins) { if (!*coins || sum < 0) return 0; if (!sum) return 1; return count2(sum - *coins, coins) + count2(sum, coins + 1); } int main(void) { int us_coins[] = { 100, 50, 25, 10, 5, 1, 0 }; int eu_coins[] = { 200, 100, 50, 20, 10, 5, 2, 1, 0 }; show(count( 100, us_coins + 2)); show(count( 1000, us_coins)); show(count( 1000 * 100, us_coins)); show(count( 10000 * 100, us_coins)); show(count(100000 * 100, us_coins)); putchar('\n'); show(count( 1 * 100, eu_coins)); show(count( 1000 * 100, eu_coins)); show(count( 10000 * 100, eu_coins)); show(count(100000 * 100, eu_coins)); return 0; }
989Count the coins
5c
2rnlo
Character,Speech The multitude,The messiah! Show us the messiah! Brians mother,<angry>Now you listen here! He's not the messiah The multitude,Who are you? Brians mother,I'm his mother The multitude,Behold his mother! Behold his mother!
987CSV to HTML translation
6clojure
719r0
import Data.Array (Array(..), (//), bounds, elems, listArray) import Data.List (intercalate) import Control.Monad (when) import Data.Maybe (isJust) delimiters :: String delimiters = ",;:" fields :: String -> [String] fields [] = [] fields xs = let (item, rest) = break (`elem` delimiters) xs (_, next) = break (`notElem` delimiters) rest in item: fields next unfields :: Maybe (Array (Int, Int) String) -> [String] unfields Nothing = [] unfields (Just a) = every fieldNumber $ elems a where ((_, _), (_, fieldNumber)) = bounds a every _ [] = [] every n xs = let (y, z) = splitAt n xs in intercalate "," y: every n z fieldArray :: [[String]] -> Maybe (Array (Int, Int) String) fieldArray [] = Nothing fieldArray xs = Just $ listArray ((1, 1), (length xs, length $ head xs)) $ concat xs fieldsFromFile :: FilePath -> IO (Maybe (Array (Int, Int) String)) fieldsFromFile = fmap (fieldArray . map fields . lines) . readFile fieldsToFile :: FilePath -> Maybe (Array (Int, Int) String) -> IO () fieldsToFile f = writeFile f . unlines . unfields someChanges :: Maybe (Array (Int, Int) String) -> Maybe (Array (Int, Int) String) someChanges = fmap (// [((1, 1), "changed"), ((3, 4), "altered"), ((5, 2), "modified")]) main :: IO () main = do a <- fieldsFromFile "example.txt" when (isJust a) $ fieldsToFile "output.txt" $ someChanges a
983CSV data manipulation
8haskell
bxgk2
import Foundation let formatter = DateFormatter() formatter.dateFormat = "MMMM dd yyyy hh:mma zzz" guard let date = formatter.date(from: "March 7 2009 7:30pm EST") else { fatalError() } print(formatter.string(from: date)) print(formatter.string(from: date + 60 * 60 * 12))
970Date manipulation
17swift
94gmj
package main import ( "fmt" "math" ) func newRsdv() func(float64) float64 { var n, a, q float64 return func(x float64) float64 { n++ a1 := a+(x-a)/n q, a = q+(x-a)*(x-a1), a1 return math.Sqrt(q/n) } } func main() { r := newRsdv() for _, x := range []float64{2,4,4,4,5,5,7,9} { fmt.Println(r(x)) } }
982Cumulative standard deviation
0go
71ur2
(import '(java.io File)) (.createNewFile (new File "output.txt")) (.mkdir (new File "docs")) (.createNewFile (File. (str (File/separator) "output.txt"))) (.mkdir (File. (str (File/separator) "docs")))
988Create a file
6clojure
kwlhs
List samples = [] def stdDev = { def sample -> samples << sample def sum = samples.sum() def sumSq = samples.sum { it * it } def count = samples.size() (sumSq/count - (sum/count)**2)**0.5 } [2,4,4,4,5,5,7,9].each { println "${stdDev(it)}" }
982Cumulative standard deviation
7groovy
uj9v9
import java.util.zip.* ; public class CRCMaker { public static void main( String[ ] args ) { String toBeEncoded = new String( "The quick brown fox jumps over the lazy dog" ) ; CRC32 myCRC = new CRC32( ) ; myCRC.update( toBeEncoded.getBytes( ) ) ; System.out.println( "The CRC-32 value is: " + Long.toHexString( myCRC.getValue( ) ) + "!" ) ; } }
984CRC-32
9java
712rj
package main import ( "fmt" "gonum.org/v1/gonum/mat" ) var m = mat.NewDense(4, 4, []float64{ 2, -1, 5, 1, 3, 2, 2, -6, 1, 3, 3, -1, 5, -2, -3, 3, }) var v = []float64{-3, -32, -47, 49} func main() { x := make([]float64, len(v)) b := make([]float64, len(v)) d := mat.Det(m) for c := range v { mat.Col(b, c, m) m.SetCol(c, v) x[c] = mat.Det(m) / d m.SetCol(c, b) } fmt.Println(x) }
985Cramer's rule
0go
1sgp5
import java.io.*; import java.awt.Point; import java.util.HashMap; import java.util.Scanner; public class CSV { private HashMap<Point, String> _map = new HashMap<Point, String>(); private int _cols; private int _rows; public void open(File file) throws FileNotFoundException, IOException { open(file, ','); } public void open(File file, char delimiter) throws FileNotFoundException, IOException { Scanner scanner = new Scanner(file); scanner.useDelimiter(Character.toString(delimiter)); clear(); while(scanner.hasNextLine()) { String[] values = scanner.nextLine().split(Character.toString(delimiter)); int col = 0; for ( String value: values ) { _map.put(new Point(col, _rows), value); _cols = Math.max(_cols, ++col); } _rows++; } scanner.close(); } public void save(File file) throws IOException { save(file, ','); } public void save(File file, char delimiter) throws IOException { FileWriter fw = new FileWriter(file); BufferedWriter bw = new BufferedWriter(fw); for (int row = 0; row < _rows; row++) { for (int col = 0; col < _cols; col++) { Point key = new Point(col, row); if (_map.containsKey(key)) { bw.write(_map.get(key)); } if ((col + 1) < _cols) { bw.write(delimiter); } } bw.newLine(); } bw.flush(); bw.close(); } public String get(int col, int row) { String val = ""; Point key = new Point(col, row); if (_map.containsKey(key)) { val = _map.get(key); } return val; } public void put(int col, int row, String value) { _map.put(new Point(col, row), value); _cols = Math.max(_cols, col+1); _rows = Math.max(_rows, row+1); } public void clear() { _map.clear(); _cols = 0; _rows = 0; } public int rows() { return _rows; } public int cols() { return _cols; } public static void main(String[] args) { try { CSV csv = new CSV(); csv.open(new File("test_in.csv")); csv.put(0, 0, "Column0"); csv.put(1, 1, "100"); csv.put(2, 2, "200"); csv.put(3, 3, "300"); csv.put(4, 4, "400"); csv.save(new File("test_out.csv")); } catch (Exception e) { } } }
983CSV data manipulation
9java
gbl4m
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] ] def damm_valid?(n) = n.digits.reverse.inject(0){|idx, a| TABLE[idx][a] } == 0 [5724, 5727, 112946].each{|n| puts in}
974Damm algorithm
14ruby
gph4q
require RE = /(\d)(?=(\d\d\d)+(?!\d))/ cuban_primes = Enumerator.new do |y| (1..).each do |n| cand = 3*n*(n+1) + 1 y << cand if OpenSSL::BN.new(cand).prime? end end def commatize(num) num.to_s.gsub(RE, ) end cbs = cuban_primes.take(200) formatted = cbs.map{|cb| commatize(cb).rjust(10) } puts formatted.each_slice(10).map(&:join) t0 = Time.now puts
981Cuban primes
14ruby
t9if2
import Data.List (foldl') import Data.STRef import Control.Monad.ST data Pair a b = Pair !a !b sumLen :: [Double] -> Pair Double Double sumLen = fiof2 . foldl' (\(Pair s l) x -> Pair (s+x) (l+1)) (Pair 0.0 0) where fiof2 (Pair s l) = Pair s (fromIntegral l) divl :: Pair Double Double -> Double divl (Pair _ 0.0) = 0.0 divl (Pair s l) = s / l sd :: [Double] -> Double sd xs = sqrt $ foldl' (\a x -> a+(x-m)^2) 0 xs / l where p@(Pair s l) = sumLen xs m = divl p mkSD :: ST s (Double -> ST s Double) mkSD = go <$> newSTRef [] where go acc x = modifySTRef acc (x:) >> (sd <$> readSTRef acc) main = mapM_ print $ runST $ mkSD >>= forM [2.0, 4.0, 4.0, 4.0, 5.0, 5.0, 7.0, 9.0]
982Cumulative standard deviation
8haskell
8tw0z
(() => { 'use strict';
984CRC-32
10javascript
pqgb7
(def denomination-kind [1 5 10 25]) (defn- cc [amount denominations] (cond (= amount 0) 1 (or (< amount 0) (empty? denominations)) 0 :else (+ (cc amount (rest denominations)) (cc (- amount (first denominations)) denominations)))) (defn count-change "Calculates the number of times you can give change with the given denominations." [amount denominations] (cc amount denominations)) (count-change 15 denomination-kind)
989Count the coins
6clojure
gb34f
class CramersRule { static void main(String[] args) { Matrix mat = new Matrix(Arrays.asList(2d, -1d, 5d, 1d), Arrays.asList(3d, 2d, 2d, -6d), Arrays.asList(1d, 3d, 3d, -1d), Arrays.asList(5d, -2d, -3d, 3d)) List<Double> b = Arrays.asList(-3d, -32d, -47d, 49d) println("Solution = " + cramersRule(mat, b)) } private static List<Double> cramersRule(Matrix matrix, List<Double> b) { double denominator = matrix.determinant() List<Double> result = new ArrayList<>() for (int i = 0; i < b.size(); i++) { result.add(matrix.replaceColumn(b, i).determinant() / denominator) } return result } private static class Matrix { private List<List<Double>> matrix @Override String toString() { return matrix.toString() } @SafeVarargs Matrix(List<Double>... lists) { matrix = new ArrayList<>() for (List<Double> list: lists) { matrix.add(list) } } Matrix(List<List<Double>> mat) { matrix = mat } double determinant() { if (matrix.size() == 1) { return get(0, 0) } if (matrix.size() == 2) { return get(0, 0) * get(1, 1) - get(0, 1) * get(1, 0) } double sum = 0 double sign = 1 for (int i = 0; i < matrix.size(); i++) { sum += sign * get(0, i) * coFactor(0, i).determinant() sign *= -1 } return sum } private Matrix coFactor(int row, int col) { List<List<Double>> mat = new ArrayList<>() for (int i = 0; i < matrix.size(); i++) { if (i == row) { continue } List<Double> list = new ArrayList<>() for (int j = 0; j < matrix.size(); j++) { if (j == col) { continue } list.add(get(i, j)) } mat.add(list) } return new Matrix(mat) } private Matrix replaceColumn(List<Double> b, int column) { List<List<Double>> mat = new ArrayList<>() for (int row = 0; row < matrix.size(); row++) { List<Double> list = new ArrayList<>() for (int col = 0; col < matrix.size(); col++) { double value = get(row, col) if (col == column) { value = b.get(row) } list.add(value) } mat.add(list) } return new Matrix(mat) } private double get(int row, int col) { return matrix.get(row).get(col) } } }
985Cramer's rule
7groovy
ja27o
(function () { 'use strict';
983CSV data manipulation
10javascript
kw4hq
fn damm(number: &str) -> u8 { static TABLE: [[u8; 10]; 10] = [ [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], ]; number.chars().fold(0, |row, digit| { let digit = digit.to_digit(10).unwrap(); TABLE[row as usize][digit as usize] }) } fn damm_validate(number: &str) -> bool { damm(number) == 0 } fn main() { let numbers = &["5724", "5727", "112946"]; for number in numbers { let is_valid = damm_validate(number); if is_valid { println!("{:>6} is valid", number); } else { println!("{:>6} is invalid", number); } } }
974Damm algorithm
15rust
r1kg5
import scala.annotation.tailrec object DammAlgorithm extends App { private val numbers = Seq(5724, 5727, 112946, 112949) @tailrec private def damm(s: String, interim: Int): String = { def table = Vector( Vector(0, 3, 1, 7, 5, 9, 8, 6, 4, 2), Vector(7, 0, 9, 2, 1, 5, 4, 8, 6, 3), Vector(4, 2, 0, 6, 8, 7, 1, 3, 5, 9), Vector(1, 7, 5, 0, 9, 8, 3, 4, 2, 6), Vector(6, 1, 2, 3, 0, 4, 5, 9, 7, 8), Vector(3, 6, 7, 4, 2, 0, 9, 5, 8, 1), Vector(5, 8, 6, 9, 7, 2, 0, 1, 3, 4), Vector(8, 9, 4, 5, 3, 6, 2, 0, 1, 7), Vector(9, 4, 3, 8, 6, 1, 7, 2, 0, 5), Vector(2, 5, 8, 1, 4, 3, 6, 7, 9, 0) ) if (s.isEmpty) if (interim == 0) "" else "" else damm(s.tail, table(interim)(s.head - '0')) } for (number <- numbers) println(f"$number%6d is ${damm(number.toString, 0)}.") }
974Damm algorithm
16scala
hw1ja
use std::time::Instant; use separator::Separatable; const NUMBER_OF_CUBAN_PRIMES: usize = 200; const COLUMNS: usize = 10; const LAST_CUBAN_PRIME: usize = 100_000; fn main() { println!("Calculating the first {} cuban primes and the {}th cuban prime...", NUMBER_OF_CUBAN_PRIMES, LAST_CUBAN_PRIME); let start = Instant::now(); let mut i: u64 = 0; let mut j: u64 = 1; let mut index: usize = 0; let mut cuban_primes = Vec::new(); let mut cuban: u64 = 0; while index < 100_000 { cuban = {j += 1; j}.pow(3) - {i += 1; i}.pow(3); if primal::is_prime(cuban) { if index < NUMBER_OF_CUBAN_PRIMES { cuban_primes.push(cuban); } index += 1; } } let elapsed = start.elapsed(); println!("THE {} FIRST CUBAN PRIMES:", NUMBER_OF_CUBAN_PRIMES); cuban_primes .chunks(COLUMNS) .map(|chunk| { chunk.iter() .map(|item| { print!("{}\t", item) }) .for_each(drop); println!(""); }) .for_each(drop); println!("The {}th cuban prime number is {}", LAST_CUBAN_PRIME, cuban.separated_string()); println!("Elapsed time: {:?}", elapsed); }
981Cuban primes
15rust
zcnto
import spire.math.SafeLong import spire.implicits._ import scala.annotation.tailrec import scala.collection.parallel.immutable.ParVector object CubanPrimes { def main(args: Array[String]): Unit = { println(formatTable(cubanPrimes.take(200).toVector, 10)) println(f"The 100,000th cuban prime is: ${getNthCubanPrime(100000).toBigInt}%,d") } def cubanPrimes: LazyList[SafeLong] = cubans.filter(isPrime) def cubans: LazyList[SafeLong] = LazyList.iterate(SafeLong(0))(_ + 1).map(n => (n + 1).pow(3) - n.pow(3)) def isPrime(num: SafeLong): Boolean = (num > 1) && !(SafeLong(2) #:: LazyList.iterate(SafeLong(3)){n => n + 2}).takeWhile(n => n*n <= num).exists(num%_ == 0) def getNthCubanPrime(num: Int): SafeLong = { @tailrec def nHelper(rem: Int, src: LazyList[SafeLong]): SafeLong = { val cprimes = src.take(100000).to(ParVector).filter(isPrime) if(cprimes.size < rem) nHelper(rem - cprimes.size, src.drop(100000)) else cprimes.toVector.sortWith(_<_)(rem - 1) } nHelper(num, cubans) } def formatTable(lst: Vector[SafeLong], rlen: Int): String = { @tailrec def fHelper(ac: Vector[String], src: Vector[String]): String = { if(src.nonEmpty) fHelper(ac :+ src.take(rlen).mkString, src.drop(rlen)) else ac.mkString("\n") } val maxLen = lst.map(n => f"${n.toBigInt}%,d".length).max val formatted = lst.map(n => s"%,${maxLen + 2}d".format(n.toInt)) fHelper(Vector[String](), formatted) } }
981Cuban primes
16scala
yvt63
int main() { int i; printf(text-align:center; border: 1px solid\ ); for (i = 0; i < 4; i++) { printf(, i, rand() % 10000, rand() % 10000, rand() % 10000); } printf(); return 0; }
990Create an HTML table
5c
n6bi6
import Data.Matrix solveCramer :: (Ord a, Fractional a) => Matrix a -> Matrix a -> Maybe [a] solveCramer a y | da == 0 = Nothing | otherwise = Just $ map (\i -> d i / da) [1..n] where da = detLU a d i = detLU $ submatrix 1 n 1 n $ switchCols i (n+1) ay ay = a <|> y n = ncols a task = solveCramer a y where a = fromLists [[2,-1, 5, 1] ,[3, 2, 2,-6] ,[1, 3, 3,-1] ,[5,-2,-3, 3]] y = fromLists [[-3], [-32], [-47], [49]]
985Cramer's rule
8haskell
t9sf7
null
984CRC-32
11kotlin
ujyvc
import java.util.ArrayList; import java.util.Arrays; import java.util.List; public class CramersRule { public static void main(String[] args) { Matrix mat = new Matrix(Arrays.asList(2d, -1d, 5d, 1d), Arrays.asList(3d, 2d, 2d, -6d), Arrays.asList(1d, 3d, 3d, -1d), Arrays.asList(5d, -2d, -3d, 3d)); List<Double> b = Arrays.asList(-3d, -32d, -47d, 49d); System.out.println("Solution = " + cramersRule(mat, b)); } private static List<Double> cramersRule(Matrix matrix, List<Double> b) { double denominator = matrix.determinant(); List<Double> result = new ArrayList<>(); for ( int i = 0 ; i < b.size() ; i++ ) { result.add(matrix.replaceColumn(b, i).determinant() / denominator); } return result; } private static class Matrix { private List<List<Double>> matrix; @Override public String toString() { return matrix.toString(); } @SafeVarargs public Matrix(List<Double> ... lists) { matrix = new ArrayList<>(); for ( List<Double> list : lists) { matrix.add(list); } } public Matrix(List<List<Double>> mat) { matrix = mat; } public double determinant() { if ( matrix.size() == 1 ) { return get(0, 0); } if ( matrix.size() == 2 ) { return get(0, 0) * get(1, 1) - get(0, 1) * get(1, 0); } double sum = 0; double sign = 1; for ( int i = 0 ; i < matrix.size() ; i++ ) { sum += sign * get(0, i) * coFactor(0, i).determinant(); sign *= -1; } return sum; } private Matrix coFactor(int row, int col) { List<List<Double>> mat = new ArrayList<>(); for ( int i = 0 ; i < matrix.size() ; i++ ) { if ( i == row ) { continue; } List<Double> list = new ArrayList<>(); for ( int j = 0 ; j < matrix.size() ; j++ ) { if ( j == col ) { continue; } list.add(get(i, j)); } mat.add(list); } return new Matrix(mat); } private Matrix replaceColumn(List<Double> b, int column) { List<List<Double>> mat = new ArrayList<>(); for ( int row = 0 ; row < matrix.size() ; row++ ) { List<Double> list = new ArrayList<>(); for ( int col = 0 ; col < matrix.size() ; col++ ) { double value = get(row, col); if ( col == column ) { value = b.get(row); } list.add(value); } mat.add(list); } return new Matrix(mat); } private double get(int row, int col) { return matrix.get(row).get(col); } } }
985Cramer's rule
9java
8t106
null
983CSV data manipulation
11kotlin
2r6li
local compute=require"zlib".crc32() local sum=compute("The quick brown fox jumps over the lazy dog") print(string.format("0x%x", sum))
984CRC-32
1lua
5hmu6
typedef unsigned long long ULONG; ULONG get_prime(int idx) { static long n_primes = 0, alloc = 0; static ULONG *primes = 0; ULONG last, p; int i; if (idx >= n_primes) { if (n_primes >= alloc) { alloc += 16; primes = realloc(primes, sizeof(ULONG) * alloc); } if (!n_primes) { primes[0] = 2; primes[1] = 3; n_primes = 2; } last = primes[n_primes-1]; while (idx >= n_primes) { last += 2; for (i = 0; i < n_primes; i++) { p = primes[i]; if (p * p > last) { primes[n_primes++] = last; break; } if (last % p == 0) break; } } } return primes[idx]; } int main() { ULONG n, x, p; int i, first; for (x = 1; ; x++) { printf(, n = x); for (i = 0, first = 1; ; i++) { p = get_prime(i); while (n % p == 0) { n /= p; if (!first) printf(); first = 0; printf(, p); } if (n <= p * p) break; } if (first) printf(, n); else if (n > 1) printf(, n); else printf(); } return 0; }
991Count in factors
5c
ja670
var matrix = [ [2, -1, 5, 1], [3, 2, 2, -6], [1, 3, 3, -1], [5, -2, -3, 3] ]; var freeTerms = [-3, -32, -47, 49]; var result = cramersRule(matrix,freeTerms); console.log(result); function cramersRule(matrix,freeTerms) { var det = detr(matrix), returnArray = [], i, tmpMatrix; for(i=0; i < matrix[0].length; i++) { var tmpMatrix = insertInTerms(matrix, freeTerms,i) returnArray.push(detr(tmpMatrix)/det) } return returnArray; } function insertInTerms(matrix, ins, at) { var tmpMatrix = clone(matrix), i; for(i=0; i < matrix.length; i++) { tmpMatrix[i][at] = ins[i]; } return tmpMatrix; } function detr(m) { var ret = 1, k, A=clone(m), n=m[0].length, alpha; for(var j =0; j < n-1; j++) { k=j; for(i=j+1;i<n;i++) { if(Math.abs(A[i][j]) > Math.abs(A[k][j])) { k = i; } } if(k !== j) { temp = A[k]; A[k] = A[j]; A[j] = temp; ret *= -1; } Aj = A[j]; for(i=j+1;i<n;i++) { Ai = A[i]; alpha = Ai[j]/Aj[j]; for(k=j+1;k<n-1;k+=2) { k1 = k+1; Ai[k] -= Aj[k]*alpha; Ai[k1] -= Aj[k1]*alpha; } if(k!==n) { Ai[k] -= Aj[k]*alpha; } } if(Aj[j] === 0) { return 0; } ret *= Aj[j]; } return Math.round(ret*A[j][j]*100)/100; } function clone(m) { return m.map(function(a){return a.slice();}); }
985Cramer's rule
10javascript
fmqdg
local csv={} for line in io.lines('file.csv') do table.insert(csv, {}) local i=1 for j=1,#line do if line:sub(j,j) == ',' then table.insert(csv[#csv], line:sub(i,j-1)) i=j+1 end end table.insert(csv[#csv], line:sub(i,j)) end table.insert(csv[1], 'SUM') for i=2,#csv do local sum=0 for j=1,#csv[i] do sum=sum + tonumber(csv[i][j]) end if sum>0 then table.insert(csv[i], sum) end end local newFileData = '' for i=1,#csv do newFileData=newFileData .. table.concat(csv[i], ',') .. '\n' end local file=io.open('file.csv', 'w') file:write(newFileData)
983CSV data manipulation
1lua
v7y2x
use Time::Local; use strict; foreach my $i (2008 .. 2121) { my $time = timelocal(0,0,0,25,11,$i); my ($s,$m,$h,$md,$mon,$y,$wd,$yd,$is) = localtime($time); if ( $wd == 0 ) { print "25 Dec $i is Sunday\n"; } } exit 0;
971Day of the week
2perl
4bb5d
int match(const char *s, const char *p, int overlap) { int c = 0, l = strlen(p); while (*s != '\0') { if (strncmp(s++, p, l)) continue; if (!overlap) s += l - 1; c++; } return c; } int main() { printf(, match(, , 0)); printf(, match(, , 1)); printf(, match(, , 0)); return 0; }
992Count occurrences of a substring
5c
a0l11
(ns rosettacode.html-table (:use 'hiccup.core)) (defn <tr> [el sq] [:tr (map vector (cycle [el]) sq)]) (html [:table (<tr>:th ["" \X \Y \Z]) (for [n (range 1 4)] (->> #(rand-int 10000) (repeatedly 3) (cons n) (<tr>:td)))])
990Create an HTML table
6clojure
3lwzr
<?php for($i=2008; $i<2121; $i++) { $datetime = new DateTime(); if ( $datetime->format() == 0 ) { echo ; } } ?>
971Day of the week
12php
i66ov
var cache = new Map(); main() { var stopwatch = new Stopwatch()..start();
989Count the coins
18dart
62q34
int main() { unsigned int i = 0; do { printf(, i++); } while(i); return 0; }
993Count in octal
5c
i37o2
null
985Cramer's rule
11kotlin
wojek
public class StdDev { int n = 0; double sum = 0; double sum2 = 0; public double sd(double x) { n++; sum += x; sum2 += x*x; return Math.sqrt(sum2/n - sum*sum/n/n); } public static void main(String[] args) { double[] testData = {2,4,4,4,5,5,7,9}; StdDev sd = new StdDev(); for (double x : testData) { System.out.println(sd.sd(x)); } } }
982Cumulative standard deviation
9java
e8ka5
(defn re-quote "Produces a string that can be used to create a Pattern that would match the string text as if it were a literal pattern. Metacharacters or escape sequences in text will be given no special meaning" [text] (java.util.regex.Pattern/quote text)) (defn count-substring [txt sub] (count (re-seq (re-pattern (re-quote sub)) txt)))
992Count occurrences of a substring
6clojure
sd4qr
(doseq [i (range)] (println (format "%o" i)))
993Count in octal
6clojure
zcptj
(ns listfactors (:gen-class)) (defn factors "Return a list of factors of N." ([n] (factors n 2 ())) ([n k acc] (cond (= n 1) (if (empty? acc) [n] (sort acc)) (>= k n) (if (empty? acc) [n] (sort (cons n acc))) (= 0 (rem n k)) (recur (quot n k) k (cons k acc)) :else (recur n (inc k) acc)))) (doseq [q (range 1 26)] (println q " = " (clojure.string/join " x "(factors q))))
991Count in factors
6clojure
1slpy
use POSIX; print strftime('%Y-%m-%d', 0, 0, 0, 10, 10, 107), "\n"; print strftime('%A,%B%d,%Y', 0, 0, 0, 10, 10, 107), "\n";
977Date format
2perl
cgl9a
local matrix = require "matrix"
985Cramer's rule
1lua
xihwz
function running_stddev() { var n = 0; var sum = 0.0; var sum_sq = 0.0; return function(num) { n++; sum += num; sum_sq += num*num; return Math.sqrt( (sum_sq / n) - Math.pow(sum / n, 2) ); } } var sd = running_stddev(); var nums = [2,4,4,4,5,5,7,9]; var stddev = []; for (var i in nums) stddev.push( sd(nums[i]) );
982Cumulative standard deviation
10javascript
0fesz
<?php echo date('Y-m-d', time()).; echo date('l, F j, Y', time()).; ?>
977Date format
12php
xnqw5
package main import "fmt" func main() { var row, col int fmt.Print("enter rows cols: ") fmt.Scan(&row, &col)
986Create a two-dimensional array at runtime
0go
sdkqa
from calendar import weekday, SUNDAY [year for year in range(2008, 2122) if weekday(year, 12, 25) == SUNDAY]
971Day of the week
3python
gpp4h
def make2d = { nrows, ncols -> (0..<nrows).collect { [0]*ncols } }
986Create a two-dimensional array at runtime
7groovy
a0g1p
import Data.Array doit n m = a!(0,0) where a = array ((0,0),(n,m)) [((0,0),42)]
986Create a two-dimensional array at runtime
8haskell
95nmo
use Math::Matrix; sub cramers_rule { my ($A, $terms) = @_; my @solutions; my $det = $A->determinant; foreach my $i (0 .. $ my $Ai = $A->clone; foreach my $j (0 .. $ $Ai->[$j][$i] = $terms->[$j]; } push @solutions, $Ai->determinant / $det; } @solutions; } my $matrix = Math::Matrix->new( [2, -1, 5, 1], [3, 2, 2, -6], [1, 3, 3, -1], [5, -2, -3, 3], ); my $free_terms = [-3, -32, -47, 49]; my ($w, $x, $y, $z) = cramers_rule($matrix, $free_terms); print "w = $w\n"; print "x = $x\n"; print "y = $y\n"; print "z = $z\n";
985Cramer's rule
2perl
lgtc5
years <- 2008:2121 xmas <- as.POSIXlt(paste0(years, '/12/25')) years[xmas$wday==0] xmas=seq(as.Date("2008/12/25"), as.Date("2121/12/25"), by="year") as.numeric(format(xmas[weekdays(xmas)== 'Sunday'], "%Y")) with(list(years=2008:2121), years[weekdays(ISOdate(years, 12, 25)) == "Sunday"]) subset(data.frame(years=2008:2121), weekdays(ISOdate(years, 12, 25)) == "Sunday")$years Sys.setlocale(cat="LC_ALL", "en") Sys.setlocale("LC_ALL", "English")
971Day of the week
13r
vjj27
null
982Cumulative standard deviation
11kotlin
kwgh3
use 5.010 ; use strict ; use warnings ; use Digest::CRC qw( crc32 ) ; my $crc = Digest::CRC->new( type => "crc32" ) ; $crc->add ( "The quick brown fox jumps over the lazy dog" ) ; say "The checksum is " . $crc->hexdigest( ) ;
984CRC-32
2perl
8ta0w