code
stringlengths 1
46.1k
⌀ | label
class label 1.18k
classes | domain_label
class label 21
classes | index
stringlengths 4
5
|
---|---|---|---|
require 'find'
Find.find('/your/path') do |f|
puts f if f.match(/\.mp3\Z/)
end | 58Walk a directory/Recursively
| 14ruby
| jgq7x |
#![feature(fs_walk)]
use std::fs;
use std::path::Path;
fn main() {
for f in fs::walk_dir(&Path::new("/home/pavel/Music")).unwrap() {
let p = f.unwrap().path();
if p.extension().unwrap_or("".as_ref()) == "mp3" {
println!("{:?}", p);
}
}
} | 58Walk a directory/Recursively
| 15rust
| hrsj2 |
import java.io.File
object `package` {
def walkTree(file: File): Iterable[File] = {
val children = new Iterable[File] {
def iterator = if (file.isDirectory) file.listFiles.iterator else Iterator.empty
}
Seq(file) ++: children.flatMap(walkTree(_))
}
}
object Test extends App {
val dir = new File("/home/user")
for(f <- walkTree(dir)) println(f)
for(f <- walkTree(dir) if f.getName.endsWith(".mp3")) println(f)
} | 58Walk a directory/Recursively
| 16scala
| phobj |
(defn luhn? [cc]
(let [sum (->> cc
(map #(Character/digit ^char % 10))
reverse
(map * (cycle [1 2]))
(map #(+ (quot % 10) (mod % 10)))
(reduce +))]
(zero? (mod sum 10))))
(defn is-valid-isin? [isin]
(and (re-matches #"^[A-Z]{2}[A-Z0-9]{9}[0-9]$" isin)
(->> isin
(map #(Character/digit ^char % 36))
(apply str)
luhn?)))
(use 'clojure.pprint)
(doseq [isin ["US0378331005" "US0373831005" "U50378331005" "US03378331005"
"AU0000XVGZA3" "AU0000VXGZA3" "FR0000988040"]]
(cl-format *out* "~A: ~:[invalid~ | 71Validate International Securities Identification Number
| 6clojure
| gvv4f |
int main(int argc, const char *argv[]) {
const int max = 1000;
int *a = malloc(max * sizeof(int));
for (int n = 0; n < max - 1; n ++) {
for (int m = n - 1; m >= 0; m --) {
if (a[m] == a[n]) {
a[n+1] = n - m;
break;
}
}
}
printf();
for (int i = 0; i < 10; i ++) printf(, a[i]);
printf();
for (int i = 990; i < 1000; i ++) printf(, a[i]);
putchar('\n');
return 0;
} | 74Van Eck sequence
| 5c
| c6t9c |
if( @ARGV != 3 ){
printHelp();
}
map( (tr/a-z/A-Z/, s/[^A-Z]//g), @ARGV );
my $cipher_decipher = $ARGV[ 0 ];
if( $cipher_decipher !~ /ENC|DEC/ ){
printHelp();
}
print "Key: " . (my $key = $ARGV[ 2 ]) . "\n";
if( $cipher_decipher =~ /ENC/ ){
print "Plain-text: " . (my $plain = $ARGV[ 1 ]) . "\n";
print "Encrypted: " . Vigenere( 1, $key, $plain ) . "\n";
}elsif( $cipher_decipher =~ /DEC/ ){
print "Cipher-text: " . (my $cipher = $ARGV[ 1 ]) . "\n";
print "Decrypted: " . Vigenere( -1, $key, $cipher ) . "\n";
}
sub printHelp{
print "Usage:\n" .
"Encrypting:\n perl cipher.pl ENC (plain text) (key)\n" .
"Decrypting:\n perl cipher.pl DEC (cipher text) (key)\n";
exit -1;
}
sub Vigenere{
my ($direction, $key, $text) = @_;
for( my $count = 0; $count < length $text; $count ++ ){
$key_offset = $direction * ord substr( $key, $count % length $key, 1);
$char_offset = ord substr( $text, $count, 1 );
$cipher .= chr 65 + ((($char_offset % 26) + ($key_offset % 26)) % 26);
}
return $cipher;
} | 61Vigenère cipher
| 2perl
| jge7f |
(defn van-der-corput
"Get the nth element of the van der Corput sequence."
([n]
(van-der-corput n 2))
([n base]
(let [s (/ 1 base)]
(loop [sum 0
n n
scale s]
(if (zero? n)
sum
(recur (+ sum (* (rem n base) scale))
(quot n base)
(* scale s)))))))
(clojure.pprint/print-table
(cons:base (range 10))
(for [base (range 2 6)]
(into {:base base}
(for [n (range 10)]
[n (van-der-corput n base)])))) | 73Van der Corput sequence
| 6clojure
| 8xe05 |
use Devel::Size qw(size total_size);
my $var = 9384752;
my @arr = (1, 2, 3, 4, 5, 6);
print size($var);
print total_size(\@arr); | 68Variable size/Get
| 2perl
| fifd7 |
(defrecord Vector [x y z])
(defn dot
[U V]
(+ (* (:x U) (:x V))
(* (:y U) (:y V))
(* (:z U) (:z V))))
(defn cross
[U V]
(new Vector
(- (* (:y U) (:z V)) (* (:z U) (:y V)))
(- (* (:z U) (:x V)) (* (:x U) (:z V)))
(- (* (:x U) (:y V)) (* (:y U) (:x V)))))
(let [a (new Vector 3 4 5)
b (new Vector 4 3 5)
c (new Vector -5 -12 -13)]
(doseq
[prod (list
(dot a b)
(cross a b)
(dot a (cross b c))
(cross a (cross b c)))]
(println prod))) | 72Vector products
| 6clojure
| x1pwk |
package main
import (
"fmt"
"math"
)
func max(a, b uint64) uint64 {
if a > b {
return a
}
return b
}
func min(a, b uint64) uint64 {
if a < b {
return a
}
return b
}
func ndigits(x uint64) (n int) {
for ; x > 0; x /= 10 {
n++
}
return
}
func dtally(x uint64) (t uint64) {
for ; x > 0; x /= 10 {
t += 1 << (x % 10 * 6)
}
return
}
var tens [20]uint64
func init() {
tens[0] = 1
for i := 1; i < 20; i++ {
tens[i] = tens[i-1] * 10
}
}
func fangs(x uint64) (f []uint64) {
nd := ndigits(x)
if nd&1 == 1 {
return
}
nd /= 2
lo := max(tens[nd-1], (x+tens[nd]-2)/(tens[nd]-1))
hi := min(x/lo, uint64(math.Sqrt(float64(x))))
t := dtally(x)
for a := lo; a <= hi; a++ {
b := x / a
if a*b == x &&
(a%10 > 0 || b%10 > 0) &&
t == dtally(a)+dtally(b) {
f = append(f, a)
}
}
return
}
func showFangs(x uint64, f []uint64) {
fmt.Print(x)
if len(f) > 1 {
fmt.Println()
}
for _, a := range f {
fmt.Println(" =", a, "", x/a)
}
}
func main() {
for x, n := uint64(1), 0; n < 26; x++ {
if f := fangs(x); len(f) > 0 {
n++
fmt.Printf("%2d: ", n)
showFangs(x, f)
}
}
fmt.Println()
for _, x := range []uint64{16758243290880, 24959017348650, 14593825548650} {
if f := fangs(x); len(f) > 0 {
showFangs(x, f)
} else {
fmt.Println(x, "is not vampiric")
}
}
} | 70Vampire number
| 0go
| hgrjq |
func printAll(things ... string) { | 67Variadic function
| 0go
| vcu2m |
>>> from array import array
>>> argslist = [('l', []), ('c', 'hello world'), ('u', u'hello \u2641'),
('l', [1, 2, 3, 4, 5]), ('d', [1.0, 2.0, 3.14])]
>>> for typecode, initializer in argslist:
a = array(typecode, initializer)
print a, '\tSize =', a.buffer_info()[1] * a.itemsize
del a
array('l') Size = 0
array('c', 'hello world') Size = 11
array('u', u'hello \u2641') Size = 14
array('l', [1, 2, 3, 4, 5]) Size = 20
array('d', [1.0, 2.0, 3.1400000000000001]) Size = 24
>>> | 68Variable size/Get
| 3python
| tntfw |
<?php
$str = ;
$key = ;
printf(, $str);
printf(, $key);
$cod = encipher($str, $key, true); printf(, $cod);
$dec = encipher($cod, $key, false); printf(, $dec);
function encipher($src, $key, $is_encode)
{
$key = strtoupper($key);
$src = strtoupper($src);
$dest = '';
for($i = 0; $i <= strlen($src); $i++) {
$char = substr($src, $i, 1);
if(ctype_upper($char)) {
$dest .= $char;
}
}
for($i = 0; $i <= strlen($dest); $i++) {
$char = substr($dest, $i, 1);
if(!ctype_upper($char)) {
continue;
}
$dest = substr_replace($dest,
chr (
ord('A') +
($is_encode
? ord($char) - ord('A') + ord($key[$i % strlen($key)]) - ord('A')
: ord($char) - ord($key[$i % strlen($key)]) + 26
) % 26
)
, $i, 1);
}
return $dest;
}
?> | 61Vigenère cipher
| 12php
| tncf1 |
import Foundation
let fileSystem = FileManager.default
let rootPath = "/" | 58Walk a directory/Recursively
| 17swift
| 74xrq |
(defn van-eck
([] (van-eck 0 0 {}))
([val n seen]
(lazy-seq
(cons val
(let [next (- n (get seen val n))]
(van-eck next
(inc n)
(assoc seen val n)))))))
(println "First 10 terms:" (take 10 (van-eck)))
(println "Terms 991 to 1000 terms:" (take 10 (drop 990 (van-eck)))) | 74Van Eck sequence
| 6clojure
| 5lmuz |
import Data.List (sort)
import Control.Arrow ((&&&))
vampires :: [Int]
vampires = filter (not . null . fangs) [1 ..]
fangs :: Int -> [(Int, Int)]
fangs n
| odd w = []
| otherwise = ((,) <*> quot n) <$> filter isfang (integerFactors n)
where
ndigit :: Int -> Int
ndigit 0 = 0
ndigit n = 1 + ndigit (quot n 10)
w = ndigit n
xmin = 10 ^ (quot w 2 - 1)
xmax = xmin * 10
isfang x =
x > xmin &&
x < y &&
y < xmax &&
(quot x 10 /= 0 || quot y 10 /= 0) &&
sort (show n) == sort (show x ++ show y)
where
y = quot n x
integerFactors :: Int -> [Int]
integerFactors n
| n < 1 = []
| otherwise =
lows ++
(quot n <$>
(if intSquared == n
then tail
else id)
(reverse lows))
where
(intSquared, lows) =
(^ 2) &&& (filter ((0 ==) . rem n) . enumFromTo 1) $
floor (sqrt $ fromIntegral n)
main :: IO [()]
main =
mapM
(print . ((,) <*>) fangs)
(take 25 vampires ++ [16758243290880, 24959017348650, 14593825548650]) | 70Vampire number
| 8haskell
| is0or |
def printAll( Object[] args) { args.each{ arg -> println arg } }
printAll(1, 2, "three", ["3", "4"]) | 67Variadic function
| 7groovy
| m39y5 |
num <- c(1, 3, 6, 10)
object.size(num)
num2 <- 1:4
object.size(num2)
l <- list(a=c(1, 3, 6, 10), b=1:4)
object.size(l)
l2 <- list(num, num2)
object.size(l2) | 68Variable size/Get
| 13r
| i0io5 |
package Vector;
use Moose;
use feature 'say';
use overload '+' => \&add,
'-' => \&sub,
'*' => \&mul,
'/' => \&div,
'""' => \&stringify;
has 'x' => (is =>'rw', isa => 'Num', required => 1);
has 'y' => (is =>'rw', isa => 'Num', required => 1);
sub add {
my($a, $b) = @_;
Vector->new( x => $a->x + $b->x, y => $a->y + $b->y);
}
sub sub {
my($a, $b) = @_;
Vector->new( x => $a->x - $b->x, y => $a->y - $b->y);
}
sub mul {
my($a, $b) = @_;
Vector->new( x => $a->x * $b, y => $a->y * $b);
}
sub div {
my($a, $b) = @_;
Vector->new( x => $a->x / $b, y => $a->y / $b);
}
sub stringify {
my $self = shift;
"(" . $self->x . "," . $self->y . ')';
}
package main;
my $a = Vector->new(x => 5, y => 7);
my $b = Vector->new(x => 2, y => 3);
say "a: $a";
say "b: $b";
say "a+b: ",$a+$b;
say "a-b: ",$a-$b;
say "a*11: ",$a*11;
say "a/2: ",$a/2; | 66Vector
| 2perl
| dotnw |
I rewrote the driver according to good sense, my style,
and discussion.
This is file main.c on Autumn 2011 ubuntu linux release.
The emacs compile command output:
-*- mode: compilation; default-directory: -*-
Compilation started at Mon Mar 12 20:25:27
make -k CFLAGS=-Wall main.o
cc -Wall -c -o main.o main.c
Compilation finished at Mon Mar 12 20:25:27
extern int Query(char *Data, unsigned *Length);
int main(int argc, char *argv[]) {
char Buffer[1024], *pc;
unsigned Size = sizeof(Buffer);
if (!Query(Buffer, &Size))
fputs(, stdout);
else
for (pc = Buffer; Size--; ++pc)
putchar(*pc);
putchar('\n');
return EXIT_SUCCESS;
} | 75Use another language to call a function
| 5c
| lytcy |
class PrintAllType t where
process :: [String] -> t
instance PrintAllType (IO a) where
process args = do mapM_ putStrLn args
return undefined
instance (Show a, PrintAllType r) => PrintAllType (a -> r) where
process args = \a -> process (args ++ [show a])
printAll :: (PrintAllType t) => t
printAll = process []
main :: IO ()
main = do printAll 5 "Mary" "had" "a" "little" "lamb"
printAll 4 3 5
printAll "Rosetta" "Code" "Is" "Awesome!" | 67Variadic function
| 8haskell
| epwai |
require 'objspace'
p ObjectSpace.memsize_of(*23)
p ObjectSpace.memsize_of(*24)
p ObjectSpace.memsize_of(*1000) | 68Variable size/Get
| 14ruby
| 3f3z7 |
int j; | 76Variables
| 5c
| znstx |
use std::mem;
fn main() { | 68Variable size/Get
| 15rust
| 6t63l |
def nBytes(x: Double) = ((Math.log(x) / Math.log(2) + 1e-10).round + 1) / 8
val primitives: List[(Any, Long)] =
List((Byte, Byte.MaxValue),
(Short, Short.MaxValue),
(Int, Int.MaxValue),
(Long, Long.MaxValue))
primitives.foreach(t => println(f"A Scala ${t._1.toString.drop(13)}%-5s has ${nBytes(t._2)} bytes")) | 68Variable size/Get
| 16scala
| 969m5 |
sizeofValue(x) | 68Variable size/Get
| 17swift
| zdztu |
package main
import (
"fmt"
"log"
"net"
"net/url"
)
func main() {
for _, in := range []string{
"foo: | 77URL parser
| 0go
| pjubg |
char rfc3986[256] = {0};
char html5[256] = {0};
void encode(const char *s, char *enc, char *tb)
{
for (; *s; s++) {
if (tb[*s]) sprintf(enc, , tb[*s]);
else sprintf(enc, , *s);
while (*++enc);
}
}
int main()
{
const char url[] = ;
char enc[(strlen(url) * 3) + 1];
int i;
for (i = 0; i < 256; i++) {
rfc3986[i] = isalnum(i)||i == '~'||i == '-'||i == '.'||i == '_'
? i : 0;
html5[i] = isalnum(i)||i == '*'||i == '-'||i == '.'||i == '_'
? i : (i == ' ') ? '+' : 0;
}
encode(url, enc, rfc3986);
puts(enc);
return 0;
} | 78URL encoding
| 5c
| lyncy |
import java.util.Arrays;
import java.util.HashSet;
public class VampireNumbers{
private static int numDigits(long num){
return Long.toString(Math.abs(num)).length();
}
private static boolean fangCheck(long orig, long fang1, long fang2){
if(Long.toString(fang1).endsWith("0") && Long.toString(fang2).endsWith("0")) return false;
int origLen = numDigits(orig);
if(numDigits(fang1) != origLen / 2 || numDigits(fang2) != origLen / 2) return false;
byte[] origBytes = Long.toString(orig).getBytes();
byte[] fangBytes = (Long.toString(fang1) + Long.toString(fang2)).getBytes();
Arrays.sort(origBytes);
Arrays.sort(fangBytes);
return Arrays.equals(origBytes, fangBytes);
}
public static void main(String[] args){
HashSet<Long> vamps = new HashSet<Long>();
for(long i = 10; vamps.size() <= 25; i++ ){
if((numDigits(i) % 2) != 0) {i = i * 10 - 1; continue;}
for(long fang1 = 2; fang1 <= Math.sqrt(i) + 1; fang1++){
if(i % fang1 == 0){
long fang2 = i / fang1;
if(fangCheck(i, fang1, fang2) && fang1 <= fang2){
vamps.add(i);
System.out.println(i + ": [" + fang1 + ", " + fang2 +"]");
}
}
}
}
Long[] nums = {16758243290880L, 24959017348650L, 14593825548650L};
for(Long i: nums){
for(long fang1 = 2; fang1 <= Math.sqrt(i) + 1; fang1++){
if(i % fang1 == 0){
long fang2 = i / fang1;
if(fangCheck(i, fang1, fang2) && fang1 <= fang2){
System.out.println(i + ": [" + fang1 + ", " + fang2 +"]");
}
}
}
}
}
} | 70Vampire number
| 9java
| x1awy |
public static void printAll(Object... things){ | 67Variadic function
| 9java
| hrkjm |
function printAll() {
for (var i=0; i<arguments.length; i++)
print(arguments[i])
}
printAll(4, 3, 5, 6, 4, 3);
printAll(4, 3, 5);
printAll("Rosetta", "Code", "Is", "Awesome!"); | 67Variadic function
| 10javascript
| abe10 |
'''Vigenere encryption and decryption'''
from itertools import starmap, cycle
def encrypt(message, key):
'''Vigenere encryption of message using key.'''
message = filter(str.isalpha, message.upper())
def enc(c, k):
'''Single letter encryption.'''
return chr(((ord(k) + ord(c) - 2 * ord('A'))% 26) + ord('A'))
return ''.join(starmap(enc, zip(message, cycle(key))))
def decrypt(message, key):
'''Vigenere decryption of message using key.'''
def dec(c, k):
'''Single letter decryption.'''
return chr(((ord(c) - ord(k) - 2 * ord('A'))% 26) + ord('A'))
return ''.join(starmap(dec, zip(message, cycle(key))))
def main():
'''Demonstration'''
text = 'Beware the Jabberwock, my son! The jaws that bite, ' + (
'the claws that catch!'
)
key = 'VIGENERECIPHER'
encr = encrypt(text, key)
decr = decrypt(encr, key)
print(text)
print(encr)
print(decr)
if __name__ == '__main__':
main() | 61Vigenère cipher
| 3python
| hrwjw |
package main
import "regexp"
var r = regexp.MustCompile(`^[A-Z]{2}[A-Z0-9]{9}\d$`)
var inc = [2][10]int{
{0, 1, 2, 3, 4, 5, 6, 7, 8, 9},
{0, 2, 4, 6, 8, 1, 3, 5, 7, 9},
}
func ValidISIN(n string) bool {
if !r.MatchString(n) {
return false
}
var sum, p int
for i := 10; i >= 0; i-- {
p = 1 - p
if d := n[i]; d < 'A' {
sum += inc[p][d-'0']
} else {
d -= 'A'
sum += inc[p][d%10]
p = 1 - p
sum += inc[p][d/10+1]
}
}
sum += int(n[11] - '0')
return sum%10 == 0
} | 71Validate International Securities Identification Number
| 0go
| qaaxz |
#include <stdio.h>
#include "_cgo_export.h"
void Run()
{
char Buffer [1024];
size_t Size = sizeof (Buffer);
if (0 == Query (Buffer, &Size))
... | 75Use another language to call a function
| 0go
| x1hwf |
import java.net.URI
[
"foo: | 77URL parser
| 7groovy
| 759rz |
module Main (main) where
import Data.Foldable (for_)
import Network.URI
( URI
, URIAuth
, parseURI
, uriAuthority
, uriFragment
, uriPath
, uriPort
, uriQuery
, uriRegName
, uriScheme
, uriUserInfo
)
uriStrings :: [String]
uriStrings =
[ "https://bob:[email protected]/place"
, "foo://example.com:8042/over/there?name=ferret#nose"
, "urn:example:animal:ferret:nose"
, "jdbc:mysql://test_user:ouupppssss@localhost:3306/sakila?profileSQL=true"
, "ftp://ftp.is.co.za/rfc/rfc1808.txt"
, "http://www.ietf.org/rfc/rfc2396.txt#header1"
, "ldap://[2001:db8::7]/c=GB?objectClass?one"
, "mailto:[email protected]"
, "news:comp.infosystems.www.servers.unix"
, "tel:+1-816-555-1212"
, "telnet://192.0.2.16:80/"
, "urn:oasis:names:specification:docbook:dtd:xml:4.1.2"
]
trimmedUriScheme :: URI -> String
trimmedUriScheme = init . uriScheme
trimmedUriUserInfo :: URIAuth -> Maybe String
trimmedUriUserInfo uriAuth =
case uriUserInfo uriAuth of
[] -> Nothing
userInfo -> if last userInfo == '@' then Just (init userInfo) else Nothing
trimmedUriPath :: URI -> String
trimmedUriPath uri = case uriPath uri of '/': t -> t; p -> p
trimmedUriQuery :: URI -> Maybe String
trimmedUriQuery uri = case uriQuery uri of '?': t -> Just t; _ -> Nothing
trimmedUriFragment :: URI -> Maybe String
trimmedUriFragment uri = case uriFragment uri of '#': t -> Just t; _ -> Nothing
main :: IO ()
main = do
for_ uriStrings $ \uriString -> do
case parseURI uriString of
Nothing -> putStrLn $ "Could not parse" ++ uriString
Just uri -> do
putStrLn uriString
putStrLn $ " scheme = " ++ trimmedUriScheme uri
case uriAuthority uri of
Nothing -> return ()
Just uriAuth -> do
case trimmedUriUserInfo uriAuth of
Nothing -> return ()
Just userInfo -> putStrLn $ " user-info = " ++ userInfo
putStrLn $ " domain = " ++ uriRegName uriAuth
putStrLn $ " port = " ++ uriPort uriAuth
putStrLn $ " path = " ++ trimmedUriPath uri
case trimmedUriQuery uri of
Nothing -> return ()
Just query -> putStrLn $ " query = " ++ query
case trimmedUriFragment uri of
Nothing -> return ()
Just fragment -> putStrLn $ " fragment = " ++ fragment
putStrLn "" | 77URL parser
| 8haskell
| fowd1 |
(declare foo) | 76Variables
| 6clojure
| 93nma |
class Vector:
def __init__(self,m,value):
self.m = m
self.value = value
self.angle = math.degrees(math.atan(self.m))
self.x = self.value * math.sin(math.radians(self.angle))
self.y = self.value * math.cos(math.radians(self.angle))
def __add__(self,vector):
final_x = self.x + vector.x
final_y = self.y + vector.y
final_value = pytagoras(final_x,final_y)
final_m = final_y / final_x
return Vector(final_m,final_value)
def __neg__(self):
return Vector(self.m,-self.value)
def __sub__(self,vector):
return self + (- vector)
def __mul__(self,scalar):
return Vector(self.m,self.value*scalar)
def __div__(self,scalar):
return self * (1 / scalar)
def __repr__(self):
return .format(self.m.__round__(2),
self.angle.__round__(2),
self.value.__round__(2),
self.x.__round__(2),
self.y.__round__(2)) | 66Vector
| 3python
| fizde |
mod1 = function(v, n)
((v - 1)%% n) + 1
str2ints = function(s)
as.integer(Filter(Negate(is.na),
factor(levels = LETTERS, strsplit(toupper(s), "")[[1]])))
vigen = function(input, key, decrypt = F)
{input = str2ints(input)
key = rep(str2ints(key), len = length(input)) - 1
paste(collapse = "", LETTERS[
mod1(input + (if (decrypt) -1 else 1)*key, length(LETTERS))])}
message(vigen("Beware the Jabberwock, my son! The jaws that bite, the claws that catch!", "vigenerecipher"))
message(vigen("WMCEEIKLGRPIFVMEUGXQPWQVIOIAVEYXUEKFKBTALVXTGAFXYEVKPAGY", "vigenerecipher", decrypt = T)) | 61Vigenère cipher
| 13r
| gup47 |
CHARS = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ'
int checksum(String prefix) {
def digits = prefix.toUpperCase().collect { CHARS.indexOf(it).toString() }.sum()
def groups = digits.collect { CHARS.indexOf(it) }.inject([[], []]) { acc, i -> [acc[1], acc[0] + i] }
def ds = groups[1].collect { (2 * it).toString() }.sum().collect { CHARS.indexOf(it) } + groups[0]
(10 - ds.sum() % 10) % 10
}
assert checksum('AU0000VXGZA') == 3
assert checksum('GB000263494') == 6
assert checksum('US037833100') == 5
assert checksum('US037833107') == 0 | 71Validate International Securities Identification Number
| 7groovy
| 1hhp6 |
typedef struct {
char mask;
char lead;
uint32_t beg;
uint32_t end;
int bits_stored;
}utf_t;
utf_t * utf[] = {
[0] = &(utf_t){0b00111111, 0b10000000, 0, 0, 6 },
[1] = &(utf_t){0b01111111, 0b00000000, 0000, 0177, 7 },
[2] = &(utf_t){0b00011111, 0b11000000, 0200, 03777, 5 },
[3] = &(utf_t){0b00001111, 0b11100000, 04000, 0177777, 4 },
[4] = &(utf_t){0b00000111, 0b11110000, 0200000, 04177777, 3 },
&(utf_t){0},
};
int codepoint_len(const uint32_t cp);
int utf8_len(const char ch);
char *to_utf8(const uint32_t cp);
uint32_t to_cp(const char chr[4]);
int codepoint_len(const uint32_t cp)
{
int len = 0;
for(utf_t **u = utf; *u; ++u) {
if((cp >= (*u)->beg) && (cp <= (*u)->end)) {
break;
}
++len;
}
if(len > 4)
exit(1);
return len;
}
int utf8_len(const char ch)
{
int len = 0;
for(utf_t **u = utf; *u; ++u) {
if((ch & ~(*u)->mask) == (*u)->lead) {
break;
}
++len;
}
if(len > 4) {
exit(1);
}
return len;
}
char *to_utf8(const uint32_t cp)
{
static char ret[5];
const int bytes = codepoint_len(cp);
int shift = utf[0]->bits_stored * (bytes - 1);
ret[0] = (cp >> shift & utf[bytes]->mask) | utf[bytes]->lead;
shift -= utf[0]->bits_stored;
for(int i = 1; i < bytes; ++i) {
ret[i] = (cp >> shift & utf[0]->mask) | utf[0]->lead;
shift -= utf[0]->bits_stored;
}
ret[bytes] = '\0';
return ret;
}
uint32_t to_cp(const char chr[4])
{
int bytes = utf8_len(*chr);
int shift = utf[0]->bits_stored * (bytes - 1);
uint32_t codep = (*chr++ & utf[bytes]->mask) << shift;
for(int i = 1; i < bytes; ++i, ++chr) {
shift -= utf[0]->bits_stored;
codep |= ((char)*chr & utf[0]->mask) << shift;
}
return codep;
}
int main(void)
{
const uint32_t *in, input[] = {0x0041, 0x00f6, 0x0416, 0x20ac, 0x1d11e, 0x0};
printf();
printf();
char *utf8;
uint32_t codepoint;
for(in = input; *in; ++in) {
utf8 = to_utf8(*in);
codepoint = to_cp(utf8);
printf(, utf8, codepoint);
for(int i = 0; utf8[i] && i < 4; ++i) {
printf(, utf8[i]);
}
printf();
}
return 0;
} | 79UTF-8 encode and decode
| 5c
| 75yrg |
#ifdef __GLASGOW_HASKELL__
#include "Called_stub.h"
extern void __stginit_Called(void);
#endif
#include <stdio.h>
#include <HsFFI.h>
int main (int argc, char * argv [])
{
char Buffer [1024];
size_t Size = sizeof (Buffer);
hs_init(&argc, &argv);
#ifdef __GLASGOW_HASKELL__
hs_add_root(__stginit_Called);
#endif
if (0 == query_hs (Buffer, &Size))
{
printf ("failed to call Query\n");
}
else
{
char * Ptr = Buffer;
while (Size
putchar ('\n');
}
hs_exit();
return 0;
} | 75Use another language to call a function
| 8haskell
| yti66 |
(import 'java.net.URLEncoder)
(URLEncoder/encode "http://foo bar/" "UTF-8") | 78URL encoding
| 6clojure
| 4235o |
null | 70Vampire number
| 11kotlin
| pjhb6 |
null | 67Variadic function
| 11kotlin
| 4vg57 |
module ISINVerification2 where
import Data.Char (isUpper, isDigit, digitToInt)
verifyISIN :: String -> Bool
verifyISIN isin =
correctFormat isin && mod (oddsum + multiplied_even_sum) 10 == 0
where
reverted = reverse $ convertToNumber isin
theOdds = fst $ collectOddandEven reverted
theEvens = snd $ collectOddandEven reverted
oddsum = sum $ map digitToInt theOdds
multiplied_even_sum = addUpDigits $ map ((* 2) . digitToInt) theEvens
capitalLetters :: String
capitalLetters = ['A','B' .. 'Z']
numbers :: String
numbers = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9']
correctFormat :: String -> Bool
correctFormat isin =
(length isin == 12) &&
all (`elem` capitalLetters) (take 2 isin) &&
all (\c -> elem c capitalLetters || elem c numbers) (drop 2 $ take 11 isin) &&
elem (last isin) numbers
convertToNumber :: String -> String
convertToNumber = concatMap convert
where
convert :: Char -> String
convert c =
if isDigit c
then show $ digitToInt c
else show (fromEnum c - 55)
collectOddandEven :: String -> (String, String)
collectOddandEven term
| odd $ length term =
( concat
[ take 1 $ drop n term
| n <- [0,2 .. length term - 1] ]
, concat
[ take 1 $ drop d term
| d <- [1,3 .. length term - 2] ])
| otherwise =
( concat
[ take 1 $ drop n term
| n <- [0,2 .. length term - 2] ]
, concat
[ take 1 $ drop d term
| d <- [1,3 .. length term - 1] ])
addUpDigits :: [Int] -> Int
addUpDigits list =
sum $
map
(\d ->
if d > 9
then sum $ map digitToInt $ show d
else d)
list
printSolution :: String -> IO ()
printSolution str = do
putStr $ str ++ " is"
if verifyISIN str
then putStrLn " valid"
else putStrLn " not valid"
main :: IO ()
main = do
let isinnumbers =
[ "US0378331005"
, "US0373831005"
, "U50378331005"
, "US03378331005"
, "AU0000XVGZA3"
, "AU0000VXGZA3"
, "FR0000988040"
]
mapM_ printSolution isinnumbers | 71Validate International Securities Identification Number
| 8haskell
| mzzyf |
inline int ishex(int x)
{
return (x >= '0' && x <= '9') ||
(x >= 'a' && x <= 'f') ||
(x >= 'A' && x <= 'F');
}
int decode(const char *s, char *dec)
{
char *o;
const char *end = s + strlen(s);
int c;
for (o = dec; s <= end; o++) {
c = *s++;
if (c == '+') c = ' ';
else if (c == '%' && ( !ishex(*s++) ||
!ishex(*s++) ||
!sscanf(s - 2, , &c)))
return -1;
if (dec) *o = c;
}
return o - dec;
}
int main()
{
const char *url = ;
char out[strlen(url) + 1];
printf(, decode(url, 0));
puts(decode(url, out) < 0 ? : out);
return 0;
} | 80URL decoding
| 5c
| fo1d3 |
struct option
{ const char *name, *value;
int flag; };
struct option updlist[] =
{ { , NULL },
{ , },
{ , },
{ , },
{ NULL, NULL } };
int output_opt(FILE *to, struct option *opt)
{ if (opt->value == NULL)
return fprintf(to, , opt->name);
else if (opt->value[0] == 0)
return fprintf(to, , opt->name);
else
return fprintf(to, , opt->name, opt->value); }
int update(FILE *from, FILE *to, struct option *updlist)
{ char line_buf[256], opt_name[128];
int i;
for (;;)
{ size_t len, space_span, span_to_hash;
if (fgets(line_buf, sizeof line_buf, from) == NULL)
break;
len = strlen(line_buf);
space_span = strspn(line_buf, );
span_to_hash = strcspn(line_buf, );
if (space_span == span_to_hash)
goto line_out;
if (space_span == len)
goto line_out;
if ((sscanf(line_buf, , opt_name) == 1) ||
(sscanf(line_buf, , opt_name) == 1))
{ int flag = 0;
for (i = 0; updlist[i].name; i++)
{ if (strcomp(updlist[i].name, opt_name) == 0)
{ if (output_opt(to, &updlist[i]) < 0)
return -1;
updlist[i].flag = 1;
flag = 1; } }
if (flag == 0)
goto line_out; }
else
line_out:
if (fprintf(to, , line_buf) < 0)
return -1;
continue; }
{ for (i = 0; updlist[i].name; i++)
{ if (!updlist[i].flag)
if (output_opt(to, &updlist[i]) < 0)
return -1; } }
return feof(from) ? 0 : -1; }
int main(void)
{ if (update(stdin, stdout, updlist) < 0)
{ fprintf(stderr, );
return (EXIT_FAILURE); }
return 0; } | 81Update a configuration file
| 5c
| 0wrst |
void ok_hit(GtkButton *o, GtkWidget **w)
{
GtkMessageDialog *msg;
gdouble v = gtk_spin_button_get_value((GtkSpinButton *)w[1]);
const gchar *c = gtk_entry_get_text((GtkEntry *)w[0]);
msg = (GtkMessageDialog *)
gtk_message_dialog_new(NULL,
GTK_DIALOG_MODAL,
(v==75000) ? GTK_MESSAGE_INFO : GTK_MESSAGE_ERROR,
GTK_BUTTONS_OK,
,
c, (gint)v,
(v==75000) ? : );
gtk_widget_show_all(GTK_WIDGET(msg));
(void)gtk_dialog_run(GTK_DIALOG(msg));
gtk_widget_destroy(GTK_WIDGET(msg));
if ( v==75000 ) gtk_main_quit();
}
int main(int argc, char **argv)
{
GtkWindow *win;
GtkEntry *entry;
GtkSpinButton *spin;
GtkButton *okbutton;
GtkLabel *entry_l, *spin_l;
GtkHBox *hbox[2];
GtkVBox *vbox;
GtkWidget *widgs[2];
gtk_init(&argc, &argv);
win = (GtkWindow *)gtk_window_new(GTK_WINDOW_TOPLEVEL);
gtk_window_set_title(win, );
entry_l = (GtkLabel *)gtk_label_new();
spin_l = (GtkLabel *)gtk_label_new();
entry = (GtkEntry *)gtk_entry_new();
spin = (GtkSpinButton *)gtk_spin_button_new_with_range(0, 80000, 1);
widgs[0] = GTK_WIDGET(entry);
widgs[1] = GTK_WIDGET(spin);
okbutton = (GtkButton *)gtk_button_new_with_label();
hbox[0] = (GtkHBox *)gtk_hbox_new(FALSE, 1);
hbox[1] = (GtkHBox *)gtk_hbox_new(FALSE, 1);
vbox = (GtkVBox *)gtk_vbox_new(TRUE, 1);
gtk_container_add(GTK_CONTAINER(hbox[0]), GTK_WIDGET(entry_l));
gtk_container_add(GTK_CONTAINER(hbox[0]), GTK_WIDGET(entry));
gtk_container_add(GTK_CONTAINER(hbox[1]), GTK_WIDGET(spin_l));
gtk_container_add(GTK_CONTAINER(hbox[1]), GTK_WIDGET(spin));
gtk_container_add(GTK_CONTAINER(vbox), GTK_WIDGET(hbox[0]));
gtk_container_add(GTK_CONTAINER(vbox), GTK_WIDGET(hbox[1]));
gtk_container_add(GTK_CONTAINER(vbox), GTK_WIDGET(okbutton));
gtk_container_add(GTK_CONTAINER(win), GTK_WIDGET(vbox));
g_signal_connect(G_OBJECT(win), , (GCallback)gtk_main_quit, NULL);
g_signal_connect(G_OBJECT(okbutton), , (GCallback)ok_hit, widgs);
gtk_widget_show_all(GTK_WIDGET(win));
gtk_main();
return 0;
} | 82User input/Graphical
| 5c
| d8knv |
public class Query {
public static boolean call(byte[] data, int[] length)
throws java.io.UnsupportedEncodingException
{
String message = "Here am I";
byte[] mb = message.getBytes("utf-8");
if (length[0] < mb.length)
return false;
length[0] = mb.length;
System.arraycopy(mb, 0, data, 0, mb.length);
return true;
}
} | 75Use another language to call a function
| 9java
| d8xn9 |
import java.net.URI;
import java.net.URISyntaxException;
public class WebAddressParser{
public static void main(String[] args){
parseAddress("foo: | 77URL parser
| 9java
| 0wkse |
public class ISIN {
public static void main(String[] args) {
String[] isins = {
"US0378331005",
"US0373831005",
"U50378331005",
"US03378331005",
"AU0000XVGZA3",
"AU0000VXGZA3",
"FR0000988040"
};
for (String isin : isins)
System.out.printf("%s is%s\n", isin, ISINtest(isin) ? "valid" : "not valid");
}
static boolean ISINtest(String isin) {
isin = isin.trim().toUpperCase();
if (!isin.matches("^[A-Z]{2}[A-Z0-9]{9}\\d$"))
return false;
StringBuilder sb = new StringBuilder();
for (char c : isin.substring(0, 12).toCharArray())
sb.append(Character.digit(c, 36));
return luhnTest(sb.toString());
}
static boolean luhnTest(String number) {
int s1 = 0, s2 = 0;
String reverse = new StringBuffer(number).reverse().toString();
for (int i = 0; i < reverse.length(); i++){
int digit = Character.digit(reverse.charAt(i), 10); | 71Validate International Securities Identification Number
| 9java
| foodv |
(import 'javax.swing.JOptionPane)
(let [number (-> "Enter an Integer"
JOptionPane/showInputDialog
Integer/parseInt)
string (JOptionPane/showInputDialog "Enter a String")]
[number string]) | 82User input/Graphical
| 6clojure
| 6fe3q |
null | 75Use another language to call a function
| 11kotlin
| 0wpsf |
(function (lstURL) {
var e = document.createElement('a'),
lstKeys = [
'hash',
'host',
'hostname',
'origin',
'pathname',
'port',
'protocol',
'search'
],
fnURLParse = function (strURL) {
e.href = strURL;
return lstKeys.reduce(
function (dct, k) {
dct[k] = e[k];
return dct;
}, {}
);
};
return JSON.stringify(
lstURL.map(fnURLParse),
null, 2
);
})([
"foo: | 77URL parser
| 10javascript
| d8enu |
class Vector
def self.polar(r, angle=0)
new(r*Math.cos(angle), r*Math.sin(angle))
end
attr_reader :x, :y
def initialize(x, y)
raise TypeError unless x.is_a?(Numeric) and y.is_a?(Numeric)
@x, @y = x, y
end
def +(other)
raise TypeError if self.class!= other.class
self.class.new(@x + other.x, @y + other.y)
end
def -@; self.class.new(-@x, -@y) end
def -(other) self + (-other) end
def *(scalar)
raise TypeError unless scalar.is_a?(Numeric)
self.class.new(@x * scalar, @y * scalar)
end
def /(scalar)
raise TypeError unless scalar.is_a?(Numeric) and scalar.nonzero?
self.class.new(@x / scalar, @y / scalar)
end
def r; @r ||= Math.hypot(@x, @y) end
def angle; @angle ||= Math.atan2(@y, @x) end
def polar; [r, angle] end
def rect; [@x, @y] end
def to_s; end
alias inspect to_s
end
p v = Vector.new(1,1)
p w = Vector.new(3,4)
p v + w
p v - w
p -v
p w * 5
p w / 2.0
p w.x
p w.y
p v.polar
p w.polar
p z = Vector.polar(1, Math::PI/2)
p z.rect
p z.polar
p z = Vector.polar(-2, Math::PI/4)
p z.polar | 66Vector
| 14ruby
| zd6tw |
module VigenereCipher
BASE = 'A'.ord
SIZE = 'Z'.ord - BASE + 1
def encrypt(text, key)
crypt(text, key,:+)
end
def decrypt(text, key)
crypt(text, key,:-)
end
def crypt(text, key, dir)
text = text.upcase.gsub(/[^A-Z]/, '')
key_iterator = key.upcase.gsub(/[^A-Z]/, '').chars.map{|c| c.ord - BASE}.cycle
text.each_char.inject('') do |ciphertext, char|
offset = key_iterator.next
ciphertext << ((char.ord - BASE).send(dir, offset) % SIZE + BASE).chr
end
end
end | 61Vigenère cipher
| 14ruby
| bjqkq |
package main
import "fmt"
func v2(n uint) (r float64) {
p := .5
for n > 0 {
if n&1 == 1 {
r += p
}
p *= .5
n >>= 1
}
return
}
func newV(base uint) func(uint) float64 {
invb := 1 / float64(base)
return func(n uint) (r float64) {
p := invb
for n > 0 {
r += p * float64(n%base)
p *= invb
n /= base
}
return
}
}
func main() {
fmt.Println("Base 2:")
for i := uint(0); i < 10; i++ {
fmt.Println(i, v2(i))
}
fmt.Println("Base 3:")
v3 := newV(3)
for i := uint(0); i < 10; i++ {
fmt.Println(i, v3(i))
}
} | 73Van der Corput sequence
| 0go
| c6z9g |
(java.net.URLDecoder/decode "http%3A%2F%2Ffoo%20bar%2F") | 80URL decoding
| 6clojure
| ytq6b |
int main(void)
{
char str[BUFSIZ];
puts();
fgets(str, sizeof(str), stdin);
long num;
char buf[BUFSIZ];
do
{
puts();
fgets(buf, sizeof(buf), stdin);
num = strtol(buf, NULL, 10);
} while (num != 75000);
return EXIT_SUCCESS;
} | 83User input/Text
| 5c
| eblav |
import 'package:flutter/material.dart';
main() => runApp( OutputLabel() );
class OutputLabel extends StatefulWidget {
@override
_OutputLabelState createState() => _OutputLabelState();
}
class _OutputLabelState extends State<OutputLabel> {
String output = "output"; | 82User input/Graphical
| 18dart
| se4q6 |
null | 77URL parser
| 11kotlin
| ebga4 |
package main
import "fmt"
func main() {
const max = 1000
a := make([]int, max) | 74Van Eck sequence
| 0go
| wpheg |
import Data.List (elemIndex)
import Data.Maybe (maybe)
vanEck :: Int -> [Int]
vanEck n = reverse $ iterate go [] !! n
where
go [] = [0]
go xxs@(x:xs) = maybe 0 succ (elemIndex x xs): xxs
main :: IO ()
main = do
print $ vanEck 10
print $ drop 990 (vanEck 1000) | 74Van Eck sequence
| 8haskell
| 6fi3k |
use warnings;
use strict;
use feature qw(say);
sub fangs {
my $vampire = shift;
my $length = length 0 + $vampire;
return if $length % 2;
my $fang_length = $length / 2;
my $from = '1' . '0' x ($fang_length - 1);
my $to = '9' x $fang_length;
my $sorted = join q(), sort split //, $vampire;
my @fangs;
for my $f1 ($from .. 1 + sqrt $vampire) {
next if $vampire % $f1;
my $f2 = $vampire / $f1;
next if $sorted ne join q(), sort split //, $f1 . $f2;
next if 2 == grep '0' eq substr($_, -1 , 1), $f1, $f2;
push @fangs, [$f1, $f2];
}
return @fangs;
}
my $count = 0;
my $i = 9;
while ($count < 25) {
$i++;
my @f = fangs($i);
$count++, say join ' ', "$count. $i:", map "[@$_]", @f if @f;
}
say join ' ', $_, map "[@$_]", fangs($_) for 16758243290880, 24959017348650, 14593825548650; | 70Vampire number
| 2perl
| ytz6u |
function varar(...)
for i, v in ipairs{...} do print(v) end
end | 67Variadic function
| 1lua
| gur4j |
use std::fmt;
use std::ops::{Add, Div, Mul, Sub};
#[derive(Copy, Clone, Debug)]
pub struct Vector<T> {
pub x: T,
pub y: T,
}
impl<T> fmt::Display for Vector<T>
where
T: fmt::Display,
{
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
if let Some(prec) = f.precision() {
write!(f, "[{:.*}, {:.*}]", prec, self.x, prec, self.y)
} else {
write!(f, "[{}, {}]", self.x, self.y)
}
}
}
impl<T> Vector<T> {
pub fn new(x: T, y: T) -> Self {
Vector { x, y }
}
}
impl Vector<f64> {
pub fn from_polar(r: f64, theta: f64) -> Self {
Vector {
x: r * theta.cos(),
y: r * theta.sin(),
}
}
}
impl<T> Add for Vector<T>
where
T: Add<Output = T>,
{
type Output = Self;
fn add(self, other: Self) -> Self::Output {
Vector {
x: self.x + other.x,
y: self.y + other.y,
}
}
}
impl<T> Sub for Vector<T>
where
T: Sub<Output = T>,
{
type Output = Self;
fn sub(self, other: Self) -> Self::Output {
Vector {
x: self.x - other.x,
y: self.y - other.y,
}
}
}
impl<T> Mul<T> for Vector<T>
where
T: Mul<Output = T> + Copy,
{
type Output = Self;
fn mul(self, scalar: T) -> Self::Output {
Vector {
x: self.x * scalar,
y: self.y * scalar,
}
}
}
impl<T> Div<T> for Vector<T>
where
T: Div<Output = T> + Copy,
{
type Output = Self;
fn div(self, scalar: T) -> Self::Output {
Vector {
x: self.x / scalar,
y: self.y / scalar,
}
}
}
fn main() {
use std::f64::consts::FRAC_PI_3;
println!("{:?}", Vector::new(4, 5));
println!("{:.4}", Vector::from_polar(3.0, FRAC_PI_3));
println!("{}", Vector::new(2, 3) + Vector::new(4, 6));
println!("{:.4}", Vector::new(5.6, 1.3) - Vector::new(4.2, 6.1));
println!("{:.4}", Vector::new(3.0, 4.2) * 2.3);
println!("{:.4}", Vector::new(3.0, 4.2) / 2.3);
println!("{}", Vector::new(3, 4) / 2);
} | 66Vector
| 15rust
| 3fyz8 |
object Vector extends App {
case class Vector2D(x: Double, y: Double) {
def +(v: Vector2D) = Vector2D(x + v.x, y + v.y)
def -(v: Vector2D) = Vector2D(x - v.x, y - v.y)
def *(s: Double) = Vector2D(s * x, s * y)
def /(s: Double) = Vector2D(x / s, y / s)
override def toString() = s"Vector($x, $y)"
}
val v1 = Vector2D(5.0, 7.0)
val v2 = Vector2D(2.0, 3.0)
println(s"v1 = $v1")
println(s"v2 = $v2\n")
println(s"v1 + v2 = ${v1 + v2}")
println(s"v1 - v2 = ${v1 - v2}")
println(s"v1 * 11 = ${v1 * 11.0}")
println(s"11 * v2 = ${v2 * 11.0}")
println(s"v1 / 2 = ${v1 / 2.0}")
println(s"\nSuccessfully completed without errors. [total ${scala.compat.Platform.currentTime - executionStart} ms]")
} | 66Vector
| 16scala
| m3cyc |
use std::ascii::AsciiExt;
static A: u8 = 'A' as u8;
fn uppercase_and_filter(input: &str) -> Vec<u8> {
let alphabet = b"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
let mut result = Vec::new();
for c in input.chars() { | 61Vigenère cipher
| 15rust
| phsbu |
object Vigenere {
def encrypt(msg: String, key: String) : String = {
var result: String = ""
var j = 0
for (i <- 0 to msg.length - 1) {
val c = msg.charAt(i)
if (c >= 'A' && c <= 'Z') {
result += ((c + key.charAt(j) - 2 * 'A') % 26 + 'A').toChar
j = (j + 1) % key.length
}
}
return result
}
def decrypt(msg: String, key: String) : String = {
var result: String = ""
var j = 0
for (i <- 0 to msg.length - 1) {
val c = msg.charAt(i)
if (c >= 'A' && c <= 'Z') {
result += ((c - key.charAt(j) + 26) % 26 + 'A').toChar
j = (j + 1) % key.length
}
}
return result
}
}
println("Encrypt text ABC => " + Vigenere.encrypt("ABC", "KEY"))
println("Decrypt text KFA => " + Vigenere.decrypt("KFA", "KEY")) | 61Vigenère cipher
| 16scala
| epoab |
null | 71Validate International Securities Identification Number
| 11kotlin
| 8xx0q |
import Data.Ratio (Rational(..), (%), numerator, denominator)
import Data.List (unfoldr)
import Text.Printf (printf)
newtype Rat =
Rat Rational
instance Show Rat where
show (Rat n) = show (numerator n) <> ('/': show (denominator n))
digitsToNum :: Integer -> [Integer] -> Integer
digitsToNum b = foldr1 (\d acc -> b * acc + d)
numToDigits :: Integer -> Integer -> [Integer]
numToDigits _ 0 = [0]
numToDigits b n = unfoldr step n
where
step 0 = Nothing
step m =
let (q, r) = m `quotRem` b
in Just (r, q)
vdc :: Integer -> Integer -> Rat
vdc b n
| b < 2 = error "vdc: base must be 2"
| otherwise =
let ds = reverse $ numToDigits b n
in Rat (digitsToNum b ds % b ^ length ds)
printVdcRanges :: ([Integer], [Integer]) -> IO ()
printVdcRanges (bases, nums) =
mapM_
putStrLn
[ printf "Base%d:" b <> concatMap (printf "%5s" . show) rs
| b <- bases
, let rs = map (vdc b) nums ]
main :: IO ()
main = do
printVdcRanges ([2, 3, 4, 5], [0 .. 9])
putStrLn []
printVdcRanges ([123], [50,100 .. 300]) | 73Van der Corput sequence
| 8haskell
| pjrbt |
local url = require('socket.url')
local tests = {
'foo://example.com:8042/over/there?name=ferret#nose',
'urn:example:animal:ferret:nose',
'jdbc:mysql://test_user:ouupppssss@localhost:3306/sakila?profileSQL=true',
'ftp://ftp.is.co.za/rfc/rfc1808.txt',
'http://www.ietf.org/rfc/rfc2396.txt#header1',
'ldap://[2001:db8::7]/c=GB?objectClass=one&objectClass=two',
'mailto:[email protected]',
'news:comp.infosystems.www.servers.unix',
'tel:+1-816-555-1212',
'telnet://192.0.2.16:80/',
'urn:oasis:names:specification:docbook:dtd:xml:4.1.2'
}
for _, test in ipairs(tests) do
local parsed = url.parse(test)
io.write('URI: ' .. test .. '\n')
for k, v in pairs(parsed) do
io.write(string.format(' %s:%s\n', k, v))
end
io.write('\n')
end | 77URL parser
| 1lua
| wprea |
import java.util.HashMap;
import java.util.Map;
public class VanEckSequence {
public static void main(String[] args) {
System.out.println("First 10 terms of Van Eck's sequence:");
vanEck(1, 10);
System.out.println("");
System.out.println("Terms 991 to 1000 of Van Eck's sequence:");
vanEck(991, 1000);
}
private static void vanEck(int firstIndex, int lastIndex) {
Map<Integer,Integer> vanEckMap = new HashMap<>();
int last = 0;
if ( firstIndex == 1 ) {
System.out.printf("VanEck[%d] =%d%n", 1, 0);
}
for ( int n = 2 ; n <= lastIndex ; n++ ) {
int vanEck = vanEckMap.containsKey(last) ? n - vanEckMap.get(last) : 0;
vanEckMap.put(last, n);
last = vanEck;
if ( n >= firstIndex ) {
System.out.printf("VanEck[%d] =%d%n", n, vanEck);
}
}
}
} | 74Van Eck sequence
| 9java
| n0xih |
function luhn (n)
local revStr, s1, s2, digit, mod = n:reverse(), 0, 0
for pos = 1, #revStr do
digit = tonumber(revStr:sub(pos, pos))
if pos % 2 == 1 then
s1 = s1 + digit
else
digit = digit * 2
if digit > 9 then
mod = digit % 10
digit = mod + ((digit - mod) / 10)
end
s2 = s2 + digit
end
end
return (s1 + s2) % 10 == 0
end
function checkISIN (inStr)
if #inStr ~= 12 then return false end
local numStr = ""
for pos = 1, #inStr do
numStr = numStr .. tonumber(inStr:sub(pos, pos), 36)
end
return luhn(numStr)
end
local testCases = {
"US0378331005",
"US0373831005",
"US0373831005",
"US03378331005",
"AU0000XVGZA3",
"AU0000VXGZA3",
"FR0000988040"
}
for _, ISIN in pairs(testCases) do print(ISIN, checkISIN(ISIN)) end | 71Validate International Securities Identification Number
| 1lua
| oqq8h |
(import '(java.util Scanner))
(def scan (Scanner. *in*))
(def s (.nextLine scan))
(def n (.nextInt scan)) | 83User input/Text
| 6clojure
| 0w4sj |
package main
import (
"bytes"
"encoding/hex"
"fmt"
"log"
"strings"
)
var testCases = []struct {
rune
string
}{
{'A', "41"},
{'', "C3 B6"},
{'', "D0 96"},
{'', "E2 82 AC"},
{'', "F0 9D 84 9E"},
}
func main() {
for _, tc := range testCases { | 79UTF-8 encode and decode
| 0go
| d81ne |
(() => {
'use strict'; | 74Van Eck sequence
| 10javascript
| 3doz0 |
import Foundation
#if canImport(Numerics)
import Numerics
#endif
struct Vector<T: Numeric> {
var x: T
var y: T
func prettyPrinted(precision: Int = 4) -> String where T: CVarArg & FloatingPoint {
return String(format: "[%.\(precision)f,%.\(precision)f]", x, y)
}
static func +(lhs: Vector, rhs: Vector) -> Vector {
return Vector(x: lhs.x + rhs.x, y: lhs.y + rhs.y)
}
static func -(lhs: Vector, rhs: Vector) -> Vector {
return Vector(x: lhs.x - rhs.x, y: lhs.y - rhs.y)
}
static func *(lhs: Vector, scalar: T) -> Vector {
return Vector(x: lhs.x * scalar, y: lhs.y * scalar)
}
static func /(lhs: Vector, scalar: T) -> Vector where T: FloatingPoint {
return Vector(x: lhs.x / scalar, y: lhs.y / scalar)
}
static func /(lhs: Vector, scalar: T) -> Vector where T: BinaryInteger {
return Vector(x: lhs.x / scalar, y: lhs.y / scalar)
}
}
#if canImport(Numerics)
extension Vector where T: ElementaryFunctions {
static func fromPolar(radians: T, theta: T) -> Vector {
return Vector(x: radians * T.cos(theta), y: radians * T.sin(theta))
}
}
#else
extension Vector where T == Double {
static func fromPolar(radians: Double, theta: Double) -> Vector {
return Vector(x: radians * cos(theta), y: radians * sin(theta))
}
}
#endif
print(Vector(x: 4, y: 5))
print(Vector.fromPolar(radians: 3.0, theta: .pi / 3).prettyPrinted())
print((Vector(x: 2, y: 3) + Vector(x: 4, y: 6)))
print((Vector(x: 5.6, y: 1.3) - Vector(x: 4.2, y: 6.1)).prettyPrinted())
print((Vector(x: 3.0, y: 4.2) * 2.3).prettyPrinted())
print((Vector(x: 3.0, y: 4.2) / 2.3).prettyPrinted())
print(Vector(x: 3, y: 4) / 2) | 66Vector
| 17swift
| tn3fl |
public class VanDerCorput{
public static double vdc(int n){
double vdc = 0;
int denom = 1;
while(n != 0){
vdc += n % 2.0 / (denom *= 2);
n /= 2;
}
return vdc;
}
public static void main(String[] args){
for(int i = 0; i <= 10; i++){
System.out.println(vdc(i));
}
}
} | 73Van der Corput sequence
| 9java
| ru2g0 |
package main
import (
"github.com/gotk3/gotk3/gtk"
"log"
"math/rand"
"strconv"
"time"
)
func validateInput(window *gtk.Window, str1, str2 string) bool {
n, err := strconv.ParseFloat(str2, 64)
if len(str1) == 0 || err != nil || n != 75000 {
dialog := gtk.MessageDialogNew(
window,
gtk.DIALOG_MODAL,
gtk.MESSAGE_ERROR,
gtk.BUTTONS_OK,
"Invalid input",
)
dialog.Run()
dialog.Destroy()
return false
}
return true
}
func check(err error, msg string) {
if err != nil {
log.Fatal(msg, err)
}
}
func main() {
rand.Seed(time.Now().UnixNano())
gtk.Init(nil)
window, err := gtk.WindowNew(gtk.WINDOW_TOPLEVEL)
check(err, "Unable to create window:")
window.SetTitle("Rosetta Code")
window.SetPosition(gtk.WIN_POS_CENTER)
window.Connect("destroy", func() {
gtk.MainQuit()
})
vbox, err := gtk.BoxNew(gtk.ORIENTATION_VERTICAL, 1)
check(err, "Unable to create vertical box:")
vbox.SetBorderWidth(1)
hbox1, err := gtk.BoxNew(gtk.ORIENTATION_HORIZONTAL, 1)
check(err, "Unable to create first horizontal box:")
hbox2, err := gtk.BoxNew(gtk.ORIENTATION_HORIZONTAL, 1)
check(err, "Unable to create second horizontal box:")
label, err := gtk.LabelNew("Enter a string and the number 75000 \n")
check(err, "Unable to create label:")
sel, err := gtk.LabelNew("String: ")
check(err, "Unable to create string entry label:")
nel, err := gtk.LabelNew("Number: ")
check(err, "Unable to create number entry label:")
se, err := gtk.EntryNew()
check(err, "Unable to create string entry:")
ne, err := gtk.EntryNew()
check(err, "Unable to create number entry:")
hbox1.PackStart(sel, false, false, 2)
hbox1.PackStart(se, false, false, 2)
hbox2.PackStart(nel, false, false, 2)
hbox2.PackStart(ne, false, false, 2) | 82User input/Graphical
| 0go
| 75zr2 |
import java.nio.charset.StandardCharsets
class UTF8EncodeDecode {
static byte[] utf8encode(int codePoint) {
char[] characters = [codePoint]
new String(characters, 0, 1).getBytes StandardCharsets.UTF_8
}
static int utf8decode(byte[] bytes) {
new String(bytes, StandardCharsets.UTF_8).codePointAt(0)
}
static void main(String[] args) {
printf "%-7s%-43s%7s\t%s\t%7s%n", "Char", "Name", "Unicode", "UTF-8 encoded", "Decoded"
([0x0041, 0x00F6, 0x0416, 0x20AC, 0x1D11E]).each { int codePoint ->
byte[] encoded = utf8encode codePoint
Formatter formatter = new Formatter()
encoded.each { byte b ->
formatter.format "%02X ", b
}
String encodedHex = formatter.toString()
int decoded = utf8decode encoded
printf "%-7c%-43s U+%04X\t%-12s\tU+%04X%n", codePoint, Character.getName(codePoint), codePoint, encodedHex, decoded
}
}
} | 79UTF-8 encode and decode
| 7groovy
| 0wjsh |
def query(buffer_length):
message = b'Here am I'
L = len(message)
return message[0:L*(L <= buffer_length)] | 75Use another language to call a function
| 3python
| 42m5k |
package main
import (
"fmt"
"net/url"
)
func main() {
fmt.Println(url.QueryEscape("http: | 78URL encoding
| 0go
| x1rwf |
from __future__ import division
import math
from operator import mul
from itertools import product
from functools import reduce
def fac(n):
'''\
return the prime factors for n
>>> fac(600)
[5, 5, 3, 2, 2, 2]
>>> fac(1000)
[5, 5, 5, 2, 2, 2]
>>>
'''
step = lambda x: 1 + x*4 - (x
maxq = int(math.floor(math.sqrt(n)))
d = 1
q = n% 2 == 0 and 2 or 3
while q <= maxq and n% q != 0:
q = step(d)
d += 1
res = []
if q <= maxq:
res.extend(fac(n
res.extend(fac(q))
else: res=[n]
return res
def fact(n):
'''\
return the prime factors and their multiplicities for n
>>> fact(600)
[(2, 3), (3, 1), (5, 2)]
>>> fact(1000)
[(2, 3), (5, 3)]
>>>
'''
res = fac(n)
return [(c, res.count(c)) for c in set(res)]
def divisors(n):
'Returns all the divisors of n'
factors = fact(n)
primes, maxpowers = zip(*factors)
powerranges = (range(m+1) for m in maxpowers)
powers = product(*powerranges)
return (
reduce(mul,
(prime**power for prime, power in zip(primes, powergroup)),
1)
for powergroup in powers)
def vampire(n):
fangsets = set( frozenset([d, n
for d in divisors(n)
if (len(str(d)) == len(str(n))/2.
and sorted(str(d) + str(n
and (str(d)[-1] == 0) + (str(n
return sorted(tuple(sorted(fangs)) for fangs in fangsets)
if __name__ == '__main__':
print('First 25 vampire numbers')
count = n = 0
while count <25:
n += 1
fangpairs = vampire(n)
if fangpairs:
count += 1
print('%i:%r'% (n, fangpairs))
print('\nSpecific checks for fangpairs')
for n in (16758243290880, 24959017348650, 14593825548650):
fangpairs = vampire(n)
print('%i:%r'% (n, fangpairs)) | 70Vampire number
| 3python
| mz3yh |
public func convertToUnicodeScalars(
str: String,
minChar: UInt32,
maxChar: UInt32
) -> [UInt32] {
var scalars = [UInt32]()
for scalar in str.unicodeScalars {
let val = scalar.value
guard val >= minChar && val <= maxChar else {
continue
}
scalars.append(val)
}
return scalars
}
public struct Vigenere {
private let keyScalars: [UInt32]
private let smallestScalar: UInt32
private let largestScalar: UInt32
private let sizeAlphabet: UInt32
public init?(key: String, smallestCharacter: Character = "A", largestCharacter: Character = "Z") {
let smallScalars = smallestCharacter.unicodeScalars
let largeScalars = largestCharacter.unicodeScalars
guard smallScalars.count == 1, largeScalars.count == 1 else {
return nil
}
self.smallestScalar = smallScalars.first!.value
self.largestScalar = largeScalars.first!.value
self.sizeAlphabet = (largestScalar - smallestScalar) + 1
let scalars = convertToUnicodeScalars(str: key, minChar: smallestScalar, maxChar: largestScalar)
guard!scalars.isEmpty else {
return nil
}
self.keyScalars = scalars
}
public func decrypt(_ str: String) -> String? {
let txtBytes = convertToUnicodeScalars(str: str, minChar: smallestScalar, maxChar: largestScalar)
guard!txtBytes.isEmpty else {
return nil
}
var res = ""
for (i, c) in txtBytes.enumerated() where c >= smallestScalar && c <= largestScalar {
guard let char =
UnicodeScalar((c &+ sizeAlphabet &- keyScalars[i% keyScalars.count])% sizeAlphabet &+ smallestScalar)
else {
return nil
}
res += String(char)
}
return res
}
public func encrypt(_ str: String) -> String? {
let txtBytes = convertToUnicodeScalars(str: str, minChar: smallestScalar, maxChar: largestScalar)
guard!txtBytes.isEmpty else {
return nil
}
var res = ""
for (i, c) in txtBytes.enumerated() where c >= smallestScalar && c <= largestScalar {
guard let char =
UnicodeScalar((c &+ keyScalars[i% keyScalars.count] &- 2 &* smallestScalar)% sizeAlphabet &+ smallestScalar)
else {
return nil
}
res += String(char)
}
return res
}
}
let text = "Beware the Jabberwock, my son! The jaws that bite, the claws that catch!";
let key = "VIGENERECIPHER";
let cipher = Vigenere(key: key)!
print("Key: \(key)")
print("Plain Text: \(text)")
let encoded = cipher.encrypt(text.uppercased())!
print("Cipher Text: \(encoded)")
let decoded = cipher.decrypt(encoded)!
print("Decoded: \(decoded)")
print("\nLarger set:")
let key2 = "Vigenre cipher"
let text2 = "This is a nicode string "
let cipher2 = Vigenere(key: key2, smallestCharacter: " ", largestCharacter: "")!
print("Key: \(key2)")
print("Plain Text: \(text2)")
let encoded2 = cipher2.encrypt(text2)!
print("Cipher Text: \(encoded2)")
let decoded2 = cipher2.decrypt(encoded2)!
print("Decoded: \(decoded2)") | 61Vigenère cipher
| 17swift
| k7xhx |
use strict;
use English;
use POSIX;
use Test::Simple tests => 7;
ok( validate_isin('US0378331005'), 'Test 1');
ok( ! validate_isin('US0373831005'), 'Test 2');
ok( ! validate_isin('U50378331005'), 'Test 3');
ok( ! validate_isin('US03378331005'), 'Test 4');
ok( validate_isin('AU0000XVGZA3'), 'Test 5');
ok( validate_isin('AU0000VXGZA3'), 'Test 6');
ok( validate_isin('FR0000988040'), 'Test 7');
exit 0;
sub validate_isin {
my $isin = shift;
$isin =~ /\A[A-Z]{2}[A-Z\d]{9}\d\z/s or return 0;
my $base10 = join(q{}, map {scalar(POSIX::strtol($ARG, 36))}
split(//s, $isin));
return luhn_test($base10);
} | 71Validate International Securities Identification Number
| 2perl
| 4225d |
null | 73Van der Corput sequence
| 11kotlin
| v9y21 |
package main
import (
"bufio"
"fmt"
"io"
"log"
"os"
"strings"
"unicode"
) | 81Update a configuration file
| 0go
| ucnvt |
import javax.swing.JOptionPane
def number = JOptionPane.showInputDialog ("Enter an Integer") as Integer
def string = JOptionPane.showInputDialog ("Enter a String")
assert number instanceof Integer
assert string instanceof String | 82User input/Graphical
| 7groovy
| uciv9 |
module Main (main) where
import qualified Data.ByteString as ByteString (pack, unpack)
import Data.Char (chr, ord)
import Data.Foldable (for_)
import Data.List (intercalate)
import qualified Data.Text as Text (head, singleton)
import qualified Data.Text.Encoding as Text (decodeUtf8, encodeUtf8)
import Text.Printf (printf)
encodeCodepoint :: Int -> [Int]
encodeCodepoint = map fromIntegral . ByteString.unpack . Text.encodeUtf8 . Text.singleton . chr
decodeToCodepoint :: [Int] -> Int
decodeToCodepoint = ord . Text.head . Text.decodeUtf8 . ByteString.pack . map fromIntegral
main :: IO ()
main = do
putStrLn "Character Unicode UTF-8 encoding (hex) Decoded"
putStrLn "
for_ [0x0041, 0x00F6, 0x0416, 0x20AC, 0x1D11E] $ \codepoint -> do
let values = encodeCodepoint codepoint
codepoint' = decodeToCodepoint values
putStrLn $ printf "%c %-7s %-20s %c"
codepoint
(printf "U+%04X" codepoint:: String)
(intercalate " " (map (printf "%02X") values))
codepoint' | 79UTF-8 encode and decode
| 8haskell
| 5ltug |
use warnings;
use strict;
use URI;
for my $uri (do { no warnings 'qw';
qw( foo://example.com:8042/over/there?name=ferret
urn:example:animal:ferret:nose
jdbc:mysql://test_user:ouupppssss@localhost:3306/sakila?profileSQL=true
ftp://ftp.is.co.za/rfc/rfc1808.txt
http://www.ietf.org/rfc/rfc2396.txt
ldap://[2001:db8::7]/c=GB?objectClass=one&objectClass=two
mailto:[email protected]
news:comp.infosystems.www.servers.unix
tel:+1-816-555-1212
telnet://192.0.2.16:80/
urn:oasis:names:specification:docbook:dtd:xml:4.1.2
)}) {
my $u = 'URI'->new($uri);
print "$uri\n";
for my $part (qw( scheme path fragment authority host port query )) {
eval { my $parsed = $u->$part;
print "\t", $part, "\t", $parsed, "\n" if defined $parsed;
};
}
} | 77URL parser
| 2perl
| c6n9a |
def normal = "http: | 78URL encoding
| 7groovy
| pjvbo |
import qualified Data.Char as Char
import Text.Printf
encode :: Char -> String
encode c
| c == ' ' = "+"
| Char.isAlphaNum c || c `elem` "-._~" = [c]
| otherwise = printf "%%%02X" c
urlEncode :: String -> String
urlEncode = concatMap encode
main :: IO ()
main = putStrLn $ urlEncode "http://foo bar/" | 78URL encoding
| 8haskell
| yt066 |
fun main() {
println("First 10 terms of Van Eck's sequence:")
vanEck(1, 10)
println("")
println("Terms 991 to 1000 of Van Eck's sequence:")
vanEck(991, 1000)
}
private fun vanEck(firstIndex: Int, lastIndex: Int) {
val vanEckMap = mutableMapOf<Int, Int>()
var last = 0
if (firstIndex == 1) {
println("VanEck[1] = 0")
}
for (n in 2..lastIndex) {
val vanEck = if (vanEckMap.containsKey(last)) n - vanEckMap[last]!! else 0
vanEckMap[last] = n
last = vanEck
if (n >= firstIndex) {
println("VanEck[$n] = $vanEck")
}
}
} | 74Van Eck sequence
| 11kotlin
| sepq7 |
class Vigenere {
key: string
constructor(key: string) {
this.key = Vigenere.formatText(key)
}
encrypt(plainText: string): string {
return Array.prototype.map.call(Vigenere.formatText(plainText), (letter: string, index: number): string => {
return String.fromCharCode((letter.charCodeAt(0) + this.key.charCodeAt(index % this.key.length) - 130) % 26 + 65)
}).join('')
}
decrypt(cipherText: string): string {
return Array.prototype.map.call(Vigenere.formatText(cipherText), (letter: string, index: number): string => {
return String.fromCharCode((letter.charCodeAt(0) - this.key.charCodeAt(index % this.key.length) + 26) % 26 + 65)
}).join('')
}
private static formatText(text: string): string {
return text.toUpperCase().replace(/[^A-Z]/g, "")
}
}
(() => {
let original: string = "Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book."
console.log(`Original: ${original}`)
let vig: Vigenere = new Vigenere("vigenere")
let encoded: string = vig.encrypt(original)
console.log(`After encryption: ${encoded}`)
let back: string = vig.decrypt(encoded)
console.log(`After decryption: ${back}`)
})() | 61Vigenère cipher
| 20typescript
| n8yi5 |
function vdc(n, base)
local digits = {}
while n ~= 0 do
local m = math.floor(n / base)
table.insert(digits, n - m * base)
n = m
end
m = 0
for p, d in pairs(digits) do
m = m + math.pow(base, -p) * d
end
return m
end | 73Van der Corput sequence
| 1lua
| ucmvl |
typedef char const *const string;
bool consume_sentinal(bool middle, string s, size_t *pos) {
if (middle) {
if (s[*pos] == ' ' && s[*pos + 1] == '
*pos += 5;
return true;
}
} else {
if (s[*pos] == '
*pos += 3;
return true;
}
}
return false;
}
int consume_digit(bool right, string s, size_t *pos) {
const char zero = right ? '
const char one = right ? ' ' : '
size_t i = *pos;
int result = -1;
if (s[i] == zero) {
if (s[i + 1] == zero) {
if (s[i + 2] == zero) {
if (s[i + 3] == one) {
if (s[i + 4] == zero) {
if (s[i + 5] == one && s[i + 6] == one) {
result = 9;
}
} else if (s[i + 4] == one) {
if (s[i + 5] == zero && s[i + 6] == one) {
result = 0;
}
}
}
} else if (s[i + 2] == one) {
if (s[i + 3] == zero) {
if (s[i + 4] == zero && s[i + 5] == one && s[i + 6] == one) {
result = 2;
}
} else if (s[i + 3] == one) {
if (s[i + 4] == zero && s[i + 5] == zero && s[i + 6] == one) {
result = 1;
}
}
}
} else if (s[i + 1] == one) {
if (s[i + 2] == zero) {
if (s[i + 3] == zero) {
if (s[i + 4] == zero && s[i + 5] == one && s[i + 6] == one) {
result = 4;
}
} else if (s[i + 3] == one) {
if (s[i + 4] == one && s[i + 5] == one && s[i + 6] == one) {
result = 6;
}
}
} else if (s[i + 2] == one) {
if (s[i + 3] == zero) {
if (s[i + 4] == zero) {
if (s[i + 5] == zero && s[i + 6] == one) {
result = 5;
}
} else if (s[i + 4] == one) {
if (s[i + 5] == one && s[i + 6] == one) {
result = 8;
}
}
} else if (s[i + 3] == one) {
if (s[i + 4] == zero) {
if (s[i + 5] == one && s[i + 6] == one) {
result = 7;
}
} else if (s[i + 4] == one) {
if (s[i + 5] == zero && s[i + 6] == one) {
result = 3;
}
}
}
}
}
}
if (result >= 0) {
*pos += 7;
}
return result;
}
bool decode_upc(string src, char *buffer) {
const int one = 1;
const int three = 3;
size_t pos = 0;
int sum = 0;
int digit;
while (src[pos] != '
if (src[pos] == 0) {
return false;
}
pos++;
}
if (!consume_sentinal(false, src, &pos)) {
return false;
}
digit = consume_digit(false, src, &pos);
if (digit < 0) {
return false;
}
sum += three * digit;
*buffer++ = digit + '0';
*buffer++ = ' ';
digit = consume_digit(false, src, &pos);
if (digit < 0) {
return false;
}
sum += one * digit;
*buffer++ = digit + '0';
*buffer++ = ' ';
digit = consume_digit(false, src, &pos);
if (digit < 0) {
return false;
}
sum += three * digit;
*buffer++ = digit + '0';
*buffer++ = ' ';
digit = consume_digit(false, src, &pos);
if (digit < 0) {
return false;
}
sum += one * digit;
*buffer++ = digit + '0';
*buffer++ = ' ';
digit = consume_digit(false, src, &pos);
if (digit < 0) {
return false;
}
sum += three * digit;
*buffer++ = digit + '0';
*buffer++ = ' ';
digit = consume_digit(false, src, &pos);
if (digit < 0) {
return false;
}
sum += one * digit;
*buffer++ = digit + '0';
*buffer++ = ' ';
if (!consume_sentinal(true, src, &pos)) {
return false;
}
digit = consume_digit(true, src, &pos);
if (digit < 0) {
return false;
}
sum += three * digit;
*buffer++ = digit + '0';
*buffer++ = ' ';
digit = consume_digit(true, src, &pos);
if (digit < 0) {
return false;
}
sum += one * digit;
*buffer++ = digit + '0';
*buffer++ = ' ';
digit = consume_digit(true, src, &pos);
if (digit < 0) {
return false;
}
sum += three * digit;
*buffer++ = digit + '0';
*buffer++ = ' ';
digit = consume_digit(true, src, &pos);
if (digit < 0) {
return false;
}
sum += one * digit;
*buffer++ = digit + '0';
*buffer++ = ' ';
digit = consume_digit(true, src, &pos);
if (digit < 0) {
return false;
}
sum += three * digit;
*buffer++ = digit + '0';
*buffer++ = ' ';
digit = consume_digit(true, src, &pos);
if (digit < 0) {
return false;
}
sum += one * digit;
*buffer++ = digit + '0';
*buffer++ = ' ';
if (!consume_sentinal(false, src, &pos)) {
return false;
}
return sum % 10 == 0;
}
void test(string src) {
char buffer[24];
if (decode_upc(src, buffer)) {
buffer[22] = 0;
printf(, buffer);
} else {
size_t len = strlen(src);
char *rev = malloc(len + 1);
size_t i;
if (rev == NULL) {
exit(1);
}
for (i = 0; i < len; i++) {
rev[i] = src[len - i - 1];
}
rev[len] = 0;
if (decode_upc(rev, buffer)) {
buffer[22] = 0;
printf(, buffer);
} else {
printf();
}
free(rev);
}
}
int main() {
int num = 0;
printf(, ++num);
test();
printf(, ++num);
test();
printf(, ++num);
test();
printf(, ++num);
test();
printf(, ++num);
test();
printf(, ++num);
test();
printf(, ++num);
test();
printf(, ++num);
test();
printf(, ++num);
test();
printf(, ++num);
test();
return 0;
} | 84UPC
| 5c
| x12wu |
import Data.Char (toUpper)
import qualified System.IO.Strict as S | 81Update a configuration file
| 8haskell
| wpued |
import 'dart:io' show stdout, stdin;
main() {
stdout.write('Enter a string: ');
final string_input = stdin.readLineSync();
int number_input;
do {
stdout.write('Enter the number 75000: ');
var number_input_string = stdin.readLineSync();
try {
number_input = int.parse(number_input_string);
if (number_input != 75000)
stdout.writeln('$number_input is not 75000!');
} on FormatException {
stdout.writeln('$number_input_string is not a valid number!');
} catch ( e ) {
stdout.writeln(e);
}
} while ( number_input != 75000 );
stdout.writeln('input: $string_input\nnumber: $number_input');
} | 83User input/Text
| 18dart
| hg3jb |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.