code
stringlengths 1
46.1k
⌀ | label
class label 1.18k
classes | domain_label
class label 21
classes | index
stringlengths 4
5
|
---|---|---|---|
package main
import (
"bytes"
"encoding/csv"
"fmt"
"html/template"
"strings"
)
var c = `Character,Speech
The multitude,The messiah! Show us the messiah!
Brians mother,<angry>Now you listen here! He's not the messiah; he's a very naughty boy! Now go away!</angry>
The multitude,Who are you?
Brians mother,I'm his mother; that's who!
The multitude,Behold his mother! Behold his mother!`
func main() {
if h, err := csvToHtml(c); err != nil {
fmt.Println(err)
} else {
fmt.Print(h)
}
}
func csvToHtml(c string) (string, error) {
data, err := csv.NewReader(bytes.NewBufferString(c)).ReadAll()
if err != nil {
return "", err
}
var b strings.Builder
err = template.Must(template.New("").Parse(`<table>
{{range .}} <tr>{{range .}}<td>{{.}}</td>{{end}}</tr>
{{end}}</table>
`)).Execute(&b, data)
return b.String(), err
} | 987CSV to HTML translation
| 0go
| 0fksk |
printf(, crc32()); | 984CRC-32
| 12php
| 4k95n |
import datetime
today = datetime.date.today()
today.isoformat()
today.strftime()
.format(d)
.format(date=d)
f | 977Date format
| 3python
| lr2cv |
now <- Sys.time()
strftime(now, "%Y-%m-%d")
strftime(now, "%A,%B%d,%Y") | 977Date format
| 13r
| yum6h |
def formatCell = { cell ->
"<td>${cell.replaceAll('&','&').replaceAll('<','<')}</td>"
}
def formatRow = { row ->
"""<tr>${row.split(',').collect { cell -> formatCell(cell) }.join('')}</tr>
"""
}
def formatTable = { csv, header=false ->
def rows = csv.split('\n').collect { row -> formatRow(row) }
header \
? """
<table>
<thead>
${rows[0]}</thead>
<tbody>
${rows[1..-1].join('')}</tbody>
</table>
""" \
: """
<table>
${rows.join('')}</table>
"""
}
def formatPage = { title, csv, header=false ->
"""<html>
<head>
<title>${title}</title>
<style type="text/css">
td {background-color:#ddddff; }
thead td {background-color:#ddffdd; text-align:center; }
</style>
</head>
<body>${formatTable(csv, header)}</body>
</html>"""
} | 987CSV to HTML translation
| 7groovy
| e8gal |
use warnings;
use strict;
use List::Util 'sum';
my @header = split /,/, <>;
chomp $header[-1];
my %column_number;
for my $i (0 .. $
$column_number{$header[$i]} = $i;
}
my @rows = map [ split /,/ ], <>;
chomp $_->[-1] for @rows;
$_->[1]++ for @rows;
$_->[ $column_number{C4} ] += $_->[ $column_number{C1} ] for @rows;
push @header, 'Sum';
$column_number{Sum} = $
push @$_, sum(@$_) for @rows;
push @rows, [
map {
my $col = $_;
sum(map $_->[ $column_number{$col} ], @rows);
} @header
];
print join(',' => @header), "\n";
print join(',' => @$_), "\n" for @rows; | 983CSV data manipulation
| 2perl
| sd1q3 |
import java.util.Scanner;
public class twoDimArray {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int nbr1 = in.nextInt();
int nbr2 = in.nextInt();
double[][] array = new double[nbr1][nbr2];
array[0][0] = 42.0;
System.out.println("The number at place [0 0] is " + array[0][0]);
}
} | 986Create a two-dimensional array at runtime
| 9java
| t9qf9 |
package main
import "fmt"
func main() {
amount := 100
fmt.Println("amount, ways to make change:", amount, countChange(amount))
}
func countChange(amount int) int64 {
return cc(amount, 4)
}
func cc(amount, kindsOfCoins int) int64 {
switch {
case amount == 0:
return 1
case amount < 0 || kindsOfCoins == 0:
return 0
}
return cc(amount, kindsOfCoins-1) +
cc(amount - firstDenomination(kindsOfCoins), kindsOfCoins)
}
func firstDenomination(kindsOfCoins int) int {
switch kindsOfCoins {
case 1:
return 1
case 2:
return 5
case 3:
return 10
case 4:
return 25
}
panic(kindsOfCoins)
} | 989Count the coins
| 0go
| qnrxz |
def det(m,n):
if n==1: return m[0][0]
z=0
for r in range(n):
k=m[:]
del k[r]
z+=m[r][0]*(-1)**r*det([p[1:]for p in k],n-1)
return z
w=len(t)
d=det(h,w)
if d==0:r=[]
else:r=[det([r[0:i]+[s]+r[i+1:]for r,s in zip(h,t)],w)/d for i in range(w)]
print(r) | 985Cramer's rule
| 3python
| 2rzlz |
package main
import (
"fmt"
"os"
)
func createFile(fn string) {
f, err := os.Create(fn)
if err != nil {
fmt.Println(err)
return
}
fmt.Println("file", fn, "created!")
f.Close()
}
func createDir(dn string) {
err := os.Mkdir(dn, 0666)
if err != nil {
fmt.Println(err)
return
}
fmt.Println("directory", dn, "created!")
}
func main() {
createFile("input.txt")
createFile("/input.txt")
createDir("docs")
createDir("/docs")
} | 988Create a file
| 0go
| i3pog |
splitOn :: Char -> String -> [String]
splitOn delim = foldr (\x rest ->
if x == delim then "": rest
else (x:head rest):tail rest) [""]
htmlEscape :: String -> String
htmlEscape = concatMap escapeChar
where escapeChar '<' = "<"
escapeChar '>' = ">"
escapeChar '&' = "&"
escapeChar '"' = """
escapeChar c = [c]
toHtmlRow :: [String] -> String
toHtmlRow [] = "<tr></tr>"
toHtmlRow cols = let htmlColumns = concatMap toHtmlCol cols
in "<tr>\n" ++ htmlColumns ++ "</tr>"
where toHtmlCol x = " <td>" ++ htmlEscape x ++ "</td>\n"
csvToTable :: String -> String
csvToTable csv = let rows = map (splitOn ',') $ lines csv
html = unlines $ map toHtmlRow rows
in "<table>\n" ++ html ++ "</table>"
main = interact csvToTable | 987CSV to HTML translation
| 8haskell
| c4n94 |
var width = Number(prompt("Enter width: "));
var height = Number(prompt("Enter height: ")); | 986Create a two-dimensional array at runtime
| 10javascript
| muiyv |
function stdev()
local sum, sumsq, k = 0,0,0
return function(n)
sum, sumsq, k = sum + n, sumsq + n^2, k+1
return math.sqrt((sumsq / k) - (sum/k)^2)
end
end
ldev = stdev()
for i, v in ipairs{2,4,4,4,5,5,7,9} do
print(ldev(v))
end | 982Cumulative standard deviation
| 1lua
| bxrka |
def ccR
ccR = { BigInteger tot, List<BigInteger> coins ->
BigInteger n = coins.size()
switch ([tot:tot, coins:coins]) {
case { it.tot == 0 }:
return 1g
case { it.tot < 0 || coins == [] }:
return 0g
default:
return ccR(tot, coins[1..<n]) +
ccR(tot - coins[0], coins)
}
} | 989Count the coins
| 7groovy
| 1svp6 |
new File("output.txt").createNewFile()
new File(File.separator + "output.txt").createNewFile()
new File("docs").mkdir()
new File(File.separator + "docs").mkdir() | 988Create a file
| 7groovy
| qn7xp |
import System.Directory
createFile name = writeFile name ""
main = do
createFile "output.txt"
createDirectory "docs"
createFile "/output.txt"
createDirectory "/docs" | 988Create a file
| 8haskell
| v7f2k |
<?php
$handle = fopen('data_in.csv','r');
$handle_output = fopen('data_out.csv','w');
$row = 0;
$arr = array();
while ($line = fgetcsv($handle))
{
$arr[] = $line;
}
$arr[1][0] = 0;
$arr[2][1] = 0;
foreach ($arr as $line)
{
if ($row==0)
{
array_push($line,);
}
else
{
array_push($line,array_sum($line));
}
fputcsv($handle_output, $line);
$row++;
}
?> | 983CSV data manipulation
| 12php
| ujmv5 |
require 'date'
(2008..2121).each {|year| puts if Date.new(year, 12, 25).sunday? } | 971Day of the week
| 14ruby
| 7aari |
>>> s = 'The quick brown fox jumps over the lazy dog'
>>> import zlib
>>> hex(zlib.crc32(s))
'0x414fa339'
>>> import binascii
>>> hex(binascii.crc32(s))
'0x414fa339' | 984CRC-32
| 3python
| oze81 |
count :: (Integral t, Integral a) => t -> [t] -> a
count 0 _ = 1
count _ [] = 0
count x (c:coins) =
sum
[ count (x - (n * c)) coins
| n <- [0 .. (quot x c)] ]
main :: IO ()
main = print (count 100 [1, 5, 10, 25]) | 989Count the coins
| 8haskell
| mu0yf |
extern crate chrono;
use chrono::prelude::*;
fn main() {
let years = (2008..2121).filter(|&y| Local.ymd(y, 12, 25).weekday() == Weekday::Sun).collect::<Vec<i32>>();
println!("Years = {:?}", years);
} | 971Day of the week
| 15rust
| jee72 |
fun main(args: Array<String>) { | 986Create a two-dimensional array at runtime
| 11kotlin
| oz18z |
digest("The quick brown fox jumps over the lazy dog","crc32", serialize=F) | 984CRC-32
| 13r
| qnbxs |
puts Time.now
puts Time.now.strftime('%Y-%m-%d')
puts Time.now.strftime('%F')
puts Time.now.strftime('%A,%B%d,%Y') | 977Date format
| 14ruby
| vju2n |
require 'matrix'
def cramers_rule(a, terms)
raise ArgumentError, unless a.square?
cols = a.to_a.transpose
cols.each_index.map do |i|
c = cols.dup
c[i] = terms
Matrix.columns(c).det / a.det
end
end
matrix = Matrix[
[2, -1, 5, 1],
[3, 2, 2, -6],
[1, 3, 3, -1],
[5, -2, -3, 3],
]
vector = [-3, -32, -47, 49]
puts cramers_rule(matrix, vector) | 985Cramer's rule
| 14ruby
| uj6vz |
use std::ops::{Index, IndexMut};
fn main() {
let m = matrix(
vec![
2., -1., 5., 1., 3., 2., 2., -6., 1., 3., 3., -1., 5., -2., -3., 3.,
],
4,
);
let mm = m.solve(&vec![-3., -32., -47., 49.]);
println!("{:?}", mm);
}
#[derive(Clone)]
struct Matrix {
elts: Vec<f64>,
dim: usize,
}
impl Matrix { | 985Cramer's rule
| 15rust
| 5hyuq |
String csv = "..."; | 987CSV to HTML translation
| 9java
| zcqtq |
import java.util.{ Calendar, GregorianCalendar }
import Calendar.{ DAY_OF_WEEK, DECEMBER, SUNDAY }
object DayOfTheWeek extends App {
val years = 2008 to 2121
val yuletide =
years.filter(year => (new GregorianCalendar(year, DECEMBER, 25)).get(DAY_OF_WEEK) == SUNDAY) | 971Day of the week
| 16scala
| bqqk6 |
function multiply(n, a, b) if a <= b then return n, multiply(n, a + 1, b) end end
a, b = io.read() + 0, io.read() + 0
matrix = {multiply({multiply(1, 1, b)}, 1, a)}
matrix[a][b] = 5
print(matrix[a][b])
print(matrix[1][1]) | 986Create a two-dimensional array at runtime
| 1lua
| i3aot |
fn main() {
let now = chrono::Utc::now();
println!("{}", now.format("%Y-%m-%d"));
println!("{}", now.format("%A,%B%d,%Y"));
} | 977Date format
| 15rust
| uh5vj |
import java.io.*;
public class CreateFileTest {
public static void main(String args[]) {
try {
new File("output.txt").createNewFile();
new File(File.separator + "output.txt").createNewFile();
new File("docs").mkdir();
new File(File.separator + "docs").mkdir();
} catch (IOException e) {
System.err.println(e.getMessage());
}
}
} | 988Create a file
| 9java
| yv06g |
var csv = "Character,Speech\n" +
"The multitude,The messiah! Show us the messiah!\n" +
"Brians mother,<angry>Now you listen here! He's not the messiah; he's a very naughty boy! Now go away!</angry>\n" +
"The multitude,Who are you?\n" +
"Brians mother,I'm his mother; that's who!\n" +
"The multitude,Behold his mother! Behold his mother!";
var lines = csv.replace(/&/g, '&')
.replace(/</g, '<')
.replace(/>/g, '>')
.replace(/"/g, '"')
.split(/[\n\r]/)
.map(function(line) { return line.split(',')})
.map(function(row) {return '\t\t<tr><td>' + row[0] + '</td><td>' + row[1] + '</td></tr>';});
console.log('<table>\n\t<thead>\n' + lines[0] +
'\n\t</thead>\n\t<tbody>\n' + lines.slice(1).join('\n') +
'\t</tbody>\n</table>'); | 987CSV to HTML translation
| 10javascript
| 95iml |
import java.util.Arrays;
import java.math.BigInteger;
class CountTheCoins {
private static BigInteger countChanges(int amount, int[] coins){
final int n = coins.length;
int cycle = 0;
for (int c: coins)
if (c <= amount && c >= cycle)
cycle = c + 1;
cycle *= n;
BigInteger[] table = new BigInteger[cycle];
Arrays.fill(table, 0, n, BigInteger.ONE);
Arrays.fill(table, n, cycle, BigInteger.ZERO);
int pos = n;
for (int s = 1; s <= amount; s++) {
for (int i = 0; i < n; i++) {
if (i == 0 && pos >= cycle)
pos = 0;
if (coins[i] <= s) {
final int q = pos - (coins[i] * n);
table[pos] = (q >= 0) ? table[q]: table[q + cycle];
}
if (i != 0)
table[pos] = table[pos].add(table[pos - 1]);
pos++;
}
}
return table[pos - 1];
}
public static void main(String[] args) {
final int[][] coinsUsEu = {{100, 50, 25, 10, 5, 1},
{200, 100, 50, 20, 10, 5, 2, 1}};
for (int[] coins: coinsUsEu) {
System.out.println(countChanges( 100,
Arrays.copyOfRange(coins, 2, coins.length)));
System.out.println(countChanges( 100000, coins));
System.out.println(countChanges( 1000000, coins));
System.out.println(countChanges(10000000, coins) + "\n");
}
}
} | 989Count the coins
| 9java
| fmadv |
package main
import (
"fmt"
"strings"
)
func main() {
fmt.Println(strings.Count("the three truths", "th")) | 992Count occurrences of a substring
| 0go
| muxyi |
val now=new Date()
println("%tF".format(now))
println("%1$tA,%1$tB%1$td,%1$tY".format(now)) | 977Date format
| 16scala
| gpr4i |
const fs = require('fs');
function fct(err) {
if (err) console.log(err);
}
fs.writeFile("output.txt", "", fct);
fs.writeFile("/output.txt", "", fct);
fs.mkdir("docs", fct);
fs.mkdir("/docs", fct); | 988Create a file
| 10javascript
| 2rdlr |
require 'zlib'
printf , Zlib.crc32('The quick brown fox jumps over the lazy dog') | 984CRC-32
| 14ruby
| n6xit |
fn crc32_compute_table() -> [u32; 256] {
let mut crc32_table = [0; 256];
for n in 0..256 {
crc32_table[n as usize] = (0..8).fold(n as u32, |acc, _| {
match acc & 1 {
1 => 0xedb88320 ^ (acc >> 1),
_ => acc >> 1,
}
});
}
crc32_table
}
fn crc32(buf: &str) -> u32 {
let crc_table = crc32_compute_table();
!buf.bytes().fold(!0, |acc, octet| {
(acc >> 8) ^ crc_table[((acc & 0xff) ^ octet as u32) as usize]
})
}
fn main() {
println!("{:x}", crc32("The quick brown fox jumps over the lazy dog"));
} | 984CRC-32
| 15rust
| dyqny |
function countcoins(t, o) {
'use strict';
var targetsLength = t + 1;
var operandsLength = o.length;
t = [1];
for (var a = 0; a < operandsLength; a++) {
for (var b = 1; b < targetsLength; b++) { | 989Count the coins
| 10javascript
| yvs6r |
println (('the three truths' =~ /th/).count)
println (('ababababab' =~ /abab/).count)
println (('abaabba*bbaba*bbab' =~ /a*b/).count)
println (('abaabba*bbaba*bbab' =~ /a\*b/).count) | 992Count occurrences of a substring
| 7groovy
| t9pfh |
import Data.Text hiding (length)
countSubStrs str sub = length $ breakOnAll (pack sub) (pack str)
main = do
print $ countSubStrs "the three truths" "th"
print $ countSubStrs "ababababab" "abab" | 992Count occurrences of a substring
| 8haskell
| kwyh0 |
package main
import (
"fmt"
"math"
)
func main() {
for i := int8(0); ; i++ {
fmt.Printf("%o\n", i)
if i == math.MaxInt8 {
break
}
}
} | 993Count in octal
| 0go
| gbd4n |
println 'decimal octal'
for (def i = 0; i <= Integer.MAX_VALUE; i++) {
printf ('%7d %#5o\n', i, i)
} | 993Count in octal
| 7groovy
| 2r0lv |
import fileinput
changerow, changecolumn, changevalue = 2, 4, ''
with fileinput.input('csv_data_manipulation.csv', inplace=True) as f:
for line in f:
if fileinput.filelineno() == changerow:
fields = line.rstrip().split(',')
fields[changecolumn-1] = changevalue
line = ','.join(fields) + '\n'
print(line, end='') | 983CSV data manipulation
| 3python
| 0fasq |
import java.util.zip.CRC32
val crc=new CRC32
crc.update("The quick brown fox jumps over the lazy dog".getBytes)
println(crc.getValue.toHexString) | 984CRC-32
| 16scala
| zc8tr |
import Numeric (showOct)
main :: IO ()
main =
mapM_
(putStrLn . flip showOct "")
[1 ..] | 993Count in octal
| 8haskell
| sd5qk |
package main
import (
"fmt"
"html/template"
"os"
)
type row struct {
X, Y, Z int
}
var tmpl = `<table>
<tr><th></th><th>X</th><th>Y</th><th>Z</th></tr>
{{range $ix, $row:= .}} <tr><td>{{$ix}}</td>
<td>{{$row.X}}</td>
<td>{{$row.Y}}</td>
<td>{{$row.Z}}</td></tr>
{{end}}</table>
`
func main() { | 990Create an HTML table
| 0go
| rp3gm |
import java.io.File
fun main(args: Array<String>) {
val filePaths = arrayOf("output.txt", "c:\\output.txt")
val dirPaths = arrayOf("docs", "c:\\docs")
var f: File
for (path in filePaths) {
f = File(path)
if (f.createNewFile())
println("$path successfully created")
else
println("$path already exists")
}
for (path in dirPaths) {
f = File(path)
if (f.mkdir())
println("$path successfully created")
else
println("$path already exists")
}
} | 988Create a file
| 11kotlin
| fmedo |
df <- read.csv(textConnection(
"C1,C2,C3,C4,C5
1,5,9,13,17
2,6,10,14,18
3,7,11,15,19
4,8,12,16,20"))
df$sum <- rowSums(df)
write.csv(df,row.names = FALSE) | 983CSV data manipulation
| 13r
| woke5 |
SELECT EXTRACT(YEAR FROM dt) AS year_with_xmas_on_sunday
FROM (
SELECT add_months(DATE '2008-12-25', 12 * (level - 1)) AS dt
FROM dual
CONNECT BY level <= 2121 - 2008 + 1
)
WHERE to_char(dt, 'Dy', 'nls_date_language=English') = 'Sun'
ORDER BY 1
; | 971Day of the week
| 19sql
| a881t |
null | 989Count the coins
| 11kotlin
| 8th0q |
public class CountSubstring {
public static int countSubstring(String subStr, String str){
return (str.length() - str.replace(subStr, "").length()) / subStr.length();
}
public static void main(String[] args){
System.out.println(countSubstring("th", "the three truths"));
System.out.println(countSubstring("abab", "ababababab"));
System.out.println(countSubstring("a*b", "abaabba*bbaba*bbab"));
}
} | 992Count occurrences of a substring
| 9java
| 4kd58 |
function countSubstring(str, subStr) {
var matches = str.match(new RegExp(subStr, "g"));
return matches ? matches.length : 0;
} | 992Count occurrences of a substring
| 10javascript
| he6jh |
public class Count{
public static void main(String[] args){
for(int i = 0;i >= 0;i++){
System.out.println(Integer.toOctalString(i)); | 993Count in octal
| 9java
| 1s9p2 |
package main
import "fmt"
func main() {
fmt.Println("1: 1")
for i := 2; ; i++ {
fmt.Printf("%d: ", i)
var x string
for n, f := i, 2; n != 1; f++ {
for m := n % f; m == 0; m = n % f {
fmt.Print(x, f)
x = ""
n /= f
}
}
fmt.Println()
}
} | 991Count in factors
| 0go
| fmpd0 |
import groovy.xml.MarkupBuilder
def createTable(columns, rowCount) {
def writer = new StringWriter()
new MarkupBuilder(writer).table(style: 'border:1px solid;text-align:center;') {
tr {
th()
columns.each { title -> th(title)}
}
(1..rowCount).each { row ->
tr {
td(row)
columns.each { td((Math.random() * 9999) as int ) }
}
}
}
writer.toString()
}
println createTable(['X', 'Y', 'Z'], 3) | 990Create an HTML table
| 7groovy
| v7n28 |
SELECT to_char(sysdate,'YYYY-MM-DD') date_fmt_1 FROM dual;
SELECT to_char(sysdate,'fmDay, Month DD, YYYY') date_fmt_2 FROM dual; | 977Date format
| 19sql
| jeh7e |
null | 987CSV to HTML translation
| 11kotlin
| i31o4 |
import Foundation
let strData = "The quick brown fox jumps over the lazy dog".dataUsingEncoding(NSUTF8StringEncoding,
allowLossyConversion: false)
let crc = crc32(uLong(0), UnsafePointer<Bytef>(strData!.bytes), uInt(strData!.length))
println(NSString(format:"%2X", crc)) | 984CRC-32
| 17swift
| i3wo0 |
function countSums (amount, values)
local t = {}
for i = 1, amount do t[i] = 0 end
t[0] = 1
for k, val in pairs(values) do
for i = val, amount do t[i] = t[i] + t[i - val] end
end
return t[amount]
end
print(countSums(100, {1, 5, 10, 25}))
print(countSums(100000, {1, 5, 10, 25, 50, 100})) | 989Count the coins
| 1lua
| ozk8h |
for (var n = 0; n < 1e14; n++) { | 993Count in octal
| 10javascript
| qnux8 |
def factors(number) {
if (number == 1) {
return [1]
}
def factors = []
BigInteger value = number
BigInteger possibleFactor = 2
while (possibleFactor <= value) {
if (value % possibleFactor == 0) {
factors << possibleFactor
value /= possibleFactor
} else {
possibleFactor++
}
}
factors
}
Number.metaClass.factors = { factors(delegate) }
((1..10) + (6351..6359)).each { number ->
println "$number = ${number.factors().join(' x ')}"
} | 991Count in factors
| 7groovy
| 8t70b |
import Data.List (unfoldr)
import Control.Monad (forM_)
import qualified Text.Blaze.Html5 as B
import Text.Blaze.Html.Renderer.Pretty (renderHtml)
import System.Random (RandomGen, getStdGen, randomRs, split)
makeTable
:: RandomGen g
=> [String] -> Int -> g -> B.Html
makeTable headings nRows gen =
B.table $
do B.thead $ B.tr $ forM_ (B.toHtml <$> headings) B.th
B.tbody $
forM_
(zip [1 .. nRows] $ unfoldr (Just . split) gen)
(\(x, g) ->
B.tr $
forM_
(take (length headings) (x: randomRs (1000, 9999) g))
(B.td . B.toHtml))
main :: IO ()
main = do
g <- getStdGen
putStrLn $ renderHtml $ makeTable ["", "X", "Y", "Z"] 3 g | 990Create an HTML table
| 8haskell
| 0f7s7 |
import Cocoa
var year=2008
let formatter=NSDateFormatter()
formatter.dateFormat = "yyyy-MM-dd"
let gregorian:NSCalendar! = NSCalendar(calendarIdentifier: NSCalendarIdentifierGregorian)
while (year<2122){
var date:NSDate!=formatter.dateFromString(String(year)+"-12-25")
var components=gregorian.components(NSCalendarUnit.CalendarUnitWeekday, fromDate: date)
var dayOfWeek:NSInteger=components.weekday
if(dayOfWeek==1){
println(year)
}
year++
} | 971Day of the week
| 17swift
| r11gg |
null | 993Count in octal
| 11kotlin
| jaz7r |
import Data.List (intercalate)
showFactors n = show n ++ " = " ++ (intercalate " * " . map show . factorize) n
showFactors = ((++) . show) <*> ((" = " ++) . intercalate " * " . map show . factorize) | 991Count in factors
| 8haskell
| 4kf5s |
import Foundation
extension String {
func toStandardDateWithDateFormat(format: String) -> String {
let dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = format
dateFormatter.dateStyle = .LongStyle
return dateFormatter.stringFromDate(dateFormatter.dateFromString(self)!)
}
}
let date = "2015-08-28".toStandardDateWithDateFormat("yyyy-MM-dd") | 977Date format
| 17swift
| 27vlj |
require 'csv'
ar = CSV.table().to_a
ar.first <<
ar[1..-1].each{|row| row << row.sum}
CSV.open(, 'w') do |csv|
ar.each{|line| csv << line}
end | 983CSV data manipulation
| 14ruby
| ozw8v |
null | 992Count occurrences of a substring
| 11kotlin
| lg0cp |
io.open("output.txt", "w"):close()
io.open("\\output.txt", "w"):close() | 988Create a file
| 1lua
| t9wfn |
FS = "," | 987CSV to HTML translation
| 1lua
| n6ai8 |
use std::error::Error;
use std::num::ParseIntError;
use csv::{Reader, Writer};
fn main() -> Result<(), Box<dyn Error>> {
let mut reader = Reader::from_path("data.csv")?;
let mut writer = Writer::from_path("output.csv")?; | 983CSV data manipulation
| 15rust
| i3xod |
null | 971Day of the week
| 20typescript
| 0tts3 |
public class CountingInFactors{
public static void main(String[] args){
for(int i = 1; i<= 10; i++){
System.out.println(i + " = "+ countInFactors(i));
}
for(int i = 9991; i <= 10000; i++){
System.out.println(i + " = "+ countInFactors(i));
}
}
private static String countInFactors(int n){
if(n == 1) return "1";
StringBuilder sb = new StringBuilder();
n = checkFactor(2, n, sb);
if(n == 1) return sb.toString();
n = checkFactor(3, n, sb);
if(n == 1) return sb.toString();
for(int i = 5; i <= n; i+= 2){
if(i % 3 == 0)continue;
n = checkFactor(i, n, sb);
if(n == 1)break;
}
return sb.toString();
}
private static int checkFactor(int mult, int n, StringBuilder sb){
while(n % mult == 0 ){
if(sb.length() > 0) sb.append(" x ");
sb.append(mult);
n /= mult;
}
return n;
}
} | 991Count in factors
| 9java
| c409h |
public class HTML {
public static String array2HTML(Object[][] array){
StringBuilder html = new StringBuilder(
"<table>");
for(Object elem:array[0]){
html.append("<th>" + elem.toString() + "</th>");
}
for(int i = 1; i < array.length; i++){
Object[] row = array[i];
html.append("<tr>");
for(Object elem:row){
html.append("<td>" + elem.toString() + "</td>");
}
html.append("</tr>");
}
html.append("</table>");
return html.toString();
}
public static void main(String[] args){
Object[][] ints = {{"","X","Y","Z"},{1,1,2,3},{2,4,5,6},{3,7,8,9},{4,10,11,12}};
System.out.println(array2HTML(ints));
}
} | 990Create an HTML table
| 9java
| a0v1y |
import scala.io.Source
object parseCSV extends App {
val rawData = """|C1,C2,C3,C4,C5
|1,5,9,13,17
|2,6,10,14,18
|3,7,11,15,19
|20,21,22,23,24""".stripMargin
val data = Seq((Source.fromString(rawData).getLines()).map(_.split(",")).toSeq: _*)
val output = ((data.take(1).flatMap(x => x) :+ "SUM").mkString(",") +: | 983CSV data manipulation
| 16scala
| fm0d4 |
for l=1,2147483647 do
print(string.format("%o",l))
end | 993Count in octal
| 1lua
| he3j8 |
for(i = 1; i <= 10; i++)
console.log(i + ": " + factor(i).join(" x "));
function factor(n) {
var factors = [];
if (n == 1) return [1];
for(p = 2; p <= n; ) {
if((n % p) == 0) {
factors[factors.length] = p;
n /= p;
}
else p++;
}
return factors;
} | 991Count in factors
| 10javascript
| 5hdur |
<html><head><title>Table maker</title><script type="application/javascript"> | 990Create an HTML table
| 10javascript
| sdrqz |
sub make_array($ $){
my $x = ($_[0] =~ /^\d+$/) ? shift : 0;
my $y = ($_[0] =~ /^\d+$/) ? shift : 0;
my @array;
$array[0][0] = 'X ';
$array[5][7] = 'X ' if (5 <= $y and 7 <= $x);
$array[12][15] = 'X ' if (12 <= $y and 15 <= $x);
foreach my $dy (0 .. $y){
foreach my $dx (0 .. $x){
(defined $array[$dy][$dx]) ? (print $array[$dy][$dx]) : (print '. ');
}
print "\n";
}
} | 986Create a two-dimensional array at runtime
| 2perl
| gbm4e |
use 5.01;
use Memoize;
sub cc {
my $amount = shift;
return 0 if !@_ || $amount < 0;
return 1 if $amount == 0;
my $first = shift;
cc( $amount, @_ ) + cc( $amount - $first, $first, @_ );
}
memoize 'cc';
sub cc_optimized {
my $amount = shift;
cc( $amount, sort { $b <=> $a } @_ );
}
say 'Ways to change $ 1 with common coins: ',
cc_optimized( 100, 1, 5, 10, 25 );
say 'Ways to change $ 1000 with addition of less common coins: ',
cc_optimized( 1000 * 100, 1, 5, 10, 25, 50, 100 ); | 989Count the coins
| 2perl
| 4kz5d |
function countSubstring(s1, s2)
return select(2, s1:gsub(s2, ""))
end
print(countSubstring("the three truths", "th"))
print(countSubstring("ababababab", "abab")) | 992Count occurrences of a substring
| 1lua
| 2r8l3 |
{
package SDAccum;
sub new {
my $class = shift;
my $self = {};
$self->{sum} = 0.0;
$self->{sum2} = 0.0;
$self->{num} = 0;
bless $self, $class;
return $self;
}
sub count {
my $self = shift;
return $self->{num};
}
sub mean {
my $self = shift;
return ($self->{num}>0) ? $self->{sum}/$self->{num} : 0.0;
}
sub variance {
my $self = shift;
my $m = $self->mean;
return ($self->{num}>0) ? $self->{sum2}/$self->{num} - $m * $m : 0.0;
}
sub stddev {
my $self = shift;
return sqrt($self->variance);
}
sub value {
my $self = shift;
my $v = shift;
$self->{sum} += $v;
$self->{sum2} += $v * $v;
$self->{num}++;
return $self->stddev;
}
} | 982Cumulative standard deviation
| 2perl
| 3lnzs |
null | 991Count in factors
| 11kotlin
| 3lez5 |
function factorize( n )
if n == 1 then return {1} end
local k = 2
res = {}
while n > 1 do
while n % k == 0 do
res[#res+1] = k
n = n / k
end
k = k + 1
end
return res
end
for i = 1, 22 do
io.write( i, ": " )
fac = factorize( i )
io.write( fac[1] )
for j = 2, #fac do
io.write( " * ", fac[j] )
end
print ""
end | 991Count in factors
| 1lua
| 62w39 |
null | 990Create an HTML table
| 11kotlin
| hemj3 |
<?php
class sdcalc {
private $cnt, $sumup, $square;
function __construct() {
$this->reset();
}
function reset() {
$this->cnt=0; $this->sumup=0; $this->square=0;
}
function add($f) {
$this->cnt++;
$this->sumup += $f;
$this->square += pow($f, 2);
return $this->calc();
}
function calc() {
if ($this->cnt==0 || $this->sumup==0) {
return 0;
} else {
return sqrt($this->square / $this->cnt - pow(($this->sumup / $this->cnt),2));
}
}
}
$c = new sdcalc();
foreach ([2,4,4,4,5,5,7,9] as $v) {
printf('Adding%g: result%g%s', $v, $c->add($v), PHP_EOL);
} | 982Cumulative standard deviation
| 12php
| pq7ba |
def changes(amount, coins):
ways = [0] * (amount + 1)
ways[0] = 1
for coin in coins:
for j in xrange(coin, amount + 1):
ways[j] += ways[j - coin]
return ways[amount]
print changes(100, [1, 5, 10, 25])
print changes(100000, [1, 5, 10, 25, 50, 100]) | 989Count the coins
| 3python
| gb34h |
width = int(raw_input())
height = int(raw_input())
myarray = [[0] * width for i in range(height)]
myarray[0][0] = 3.5
print (myarray[0][0]) | 986Create a two-dimensional array at runtime
| 3python
| rp9gq |
input <- readline("Enter two integers. Space delimited, please: ")
dims <- as.numeric(strsplit(input, " ")[[1]])
arr <- array(dim=dims)
ii <- ceiling(dims[1]/2)
jj <- ceiling(dims[2]/2)
arr[ii, jj] <- sum(dims)
cat("array[", ii, ",", jj, "] is ", arr[ii, jj], "\n", sep="") | 986Create a two-dimensional array at runtime
| 13r
| uj3vx |
use POSIX;
printf "%o\n", $_ for (0 .. POSIX::UINT_MAX); | 993Count in octal
| 2perl
| t9bfg |
function htmlTable (data)
local html = "<table>\n<tr>\n<th></th>\n"
for _, heading in pairs(data[1]) do
html = html .. "<th>" .. heading .. "</th>" .. "\n"
end
html = html .. "</tr>\n"
for row = 2, #data do
html = html .. "<tr>\n<th>" .. row - 1 .. "</th>\n"
for _, field in pairs(data[row]) do
html = html .. "<td>" .. field .. "</td>\n"
end
html = html .. "</tr>\n"
end
return html .. "</table>"
end
local tableData = {
{"X", "Y", "Z"},
{"1", "2", "3"},
{"4", "5", "6"},
{"7", "8", "9"}
}
print(htmlTable(tableData)) | 990Create an HTML table
| 1lua
| kw9h2 |
use File::Spec::Functions qw(catfile rootdir);
{
open my $fh, '>', 'output.txt';
mkdir 'docs';
};
{
open my $fh, '>', catfile rootdir, 'output.txt';
mkdir catfile rootdir, 'docs';
}; | 988Create a file
| 2perl
| hecjl |
>>> from math import sqrt
>>> def sd(x):
sd.sum += x
sd.sum2 += x*x
sd.n += 1.0
sum, sum2, n = sd.sum, sd.sum2, sd.n
return sqrt(sum2/n - sum*sum/n/n)
>>> sd.sum = sd.sum2 = sd.n = 0
>>> for value in (2,4,4,4,5,5,7,9):
print (value, sd(value))
(2, 0.0)
(4, 1.0)
(4, 0.94280904158206258)
(4, 0.8660254037844386)
(5, 0.97979589711327075)
(5, 1.0)
(7, 1.3997084244475311)
(9, 2.0)
>>> | 982Cumulative standard deviation
| 3python
| 62d3w |
def make_change(amount, coins)
@cache = Array.new(amount+1){|i| Array.new(coins.size, i.zero?? 1: nil)}
@coins = coins
do_count(amount, @coins.length - 1)
end
def do_count(n, m)
if n < 0 || m < 0
0
elsif @cache[n][m]
@cache[n][m]
else
@cache[n][m] = do_count(n-@coins[m], m) + do_count(n, m-1)
end
end
p make_change( 1_00, [1,5,10,25])
p make_change(1000_00, [1,5,10,25,50,100]) | 989Count the coins
| 14ruby
| 71yri |
<?php
for ($n = 0; is_int($n); $n++) {
echo decoct($n), ;
}
?> | 993Count in octal
| 12php
| kw6hv |
<?php
touch('output.txt');
mkdir('docs');
touch('/output.txt');
mkdir('/docs');
?> | 988Create a file
| 12php
| zcxt1 |
puts 'Enter width and height: '
w=gets.to_i
arr = Array.new(gets.to_i){Array.new(w)}
arr[1][3] = 5
p arr[1][3] | 986Create a two-dimensional array at runtime
| 14ruby
| jal7x |
cumsd <- function(x) {
n <- seq_along(x)
sqrt(cumsum(x^2) / n - (cumsum(x) / n)^2)
}
set.seed(12345L)
x <- rnorm(10)
cumsd(x)
Vectorize(function(k) sd(x[1:k]) * sqrt((k - 1) / k))(seq_along(x)) | 982Cumulative standard deviation
| 13r
| fm8dc |
fn make_change(coins: &[usize], cents: usize) -> usize {
let size = cents + 1;
let mut ways = vec![0; size];
ways[0] = 1;
for &coin in coins {
for amount in coin..size {
ways[amount] += ways[amount - coin];
}
}
ways[cents]
}
fn main() {
println!("{}", make_change(&[1,5,10,25], 100));
println!("{}", make_change(&[1,5,10,25,50,100], 100_000));
} | 989Count the coins
| 15rust
| jam72 |
Subsets and Splits