code
stringlengths
1
46.1k
label
class label
1.18k classes
domain_label
class label
21 classes
index
stringlengths
4
5
expr1 <- quote(a+b*c) expr2 <- parse(text="a+b*c")[[1]] expr3 <- call("+", quote(`a`), call("*", quote(`b`), quote(`c`)))
321Runtime evaluation
13r
a5g1z
function evalWithX(expr, a, b) { var x = a; var atA = eval(expr); x = b; var atB = eval(expr); return atB - atA; }
322Runtime evaluation/In an environment
10javascript
obp86
cities = [ {name: , population: 21}, {name: , population: 15.2}, {name: , population: 11.3}, {name: , population: 7.55}, {name: , population: 5.85}, {name: , population: 4.98}, {name: , population: 4.7}, {name: , population: 4.58}, {name: , population: 4.4}, {name: , population: 3.98}, ] puts cities.index{|city| city[:name] == } puts cities.find {|city| city[:population] < 5.0}[:name] puts cities.find {|city| city[:name][0] == }[:population]
317Search a list of records
14ruby
1ujpw
import Foundation class PrimeSieve { var composite: [Bool] init(size: Int) { composite = Array(repeating: false, count: size/2) var p = 3 while p * p <= size { if!composite[p/2 - 1] { let inc = p * 2 var q = p * p while q <= size { composite[q/2 - 1] = true q += inc } } p += 2 } } func isPrime(number: Int) -> Bool { if number < 2 { return false } if (number & 1) == 0 { return number == 2 } return!composite[number/2 - 1] } } func commatize(_ number: Int) -> String { let n = NSNumber(value: number) return NumberFormatter.localizedString(from: n, number: .decimal) } let limit1 = 1000000 let limit2 = 10000000 class PrimeInfo { let maxPrint: Int var count1: Int var count2: Int var primes: [Int] init(maxPrint: Int) { self.maxPrint = maxPrint count1 = 0 count2 = 0 primes = [] } func addPrime(prime: Int) { count2 += 1 if prime < limit1 { count1 += 1 } if count2 <= maxPrint { primes.append(prime) } } func printInfo(name: String) { print("First \(maxPrint) \(name) primes: \(primes)") print("Number of \(name) primes below \(commatize(limit1)): \(commatize(count1))") print("Number of \(name) primes below \(commatize(limit2)): \(commatize(count2))") } } var safePrimes = PrimeInfo(maxPrint: 35) var unsafePrimes = PrimeInfo(maxPrint: 40) let sieve = PrimeSieve(size: limit2) for prime in 2..<limit2 { if sieve.isPrime(number: prime) { if sieve.isPrime(number: (prime - 1)/2) { safePrimes.addPrime(prime: prime) } else { unsafePrimes.addPrime(prime: prime) } } } safePrimes.printInfo(name: "safe") unsafePrimes.printInfo(name: "unsafe")
319Safe primes and unsafe primes
17swift
daqnh
null
322Runtime evaluation/In an environment
11kotlin
pvub6
struct City { name: &'static str, population: f64, } fn main() { let cities = [ City { name: "Lagos", population: 21.0, }, City { name: "Cairo", population: 15.2, }, City { name: "Kinshasa-Brazzaville", population: 11.3, }, City { name: "Greater Johannesburg", population: 7.55, }, City { name: "Mogadishu", population: 5.85, }, City { name: "Khartoum-Omdurman", population: 4.98, }, City { name: "Dar Es Salaam", population: 4.7, }, City { name: "Alexandria", population: 4.58, }, City { name: "Abidjan", population: 4.4, }, City { name: "Casablanca", population: 3.98, }, ]; println!( "{:?}", cities.iter().position(|city| city.name == "Dar Es Salaam") ); println!( "{:?}", cities .iter() .find(|city| city.population < 5.0) .map(|city| city.name) ); println!( "{:?}", cities .iter() .find(|city| city.name.starts_with('A')) .map(|city| city.population) ); }
317Search a list of records
15rust
a5h14
object SearchListOfRecords extends App { val cities = Vector( City("Lagos", 21.0e6), City("Cairo", 15.2e6), City("Kinshasa-Brazzaville", 11.3e6), City("Greater Johannesburg", 7.55e6), City("Mogadishu", 5.85e6), City("Khartoum-Omdurman", 4.98e6), City("Dar Es Salaam", 4.7e6), City("Alexandria", 4.58e6), City("Abidjan", 4.4e6), City("Casablanca", 3.98e6) ) def index = cities.indexWhere((_: City).name == "Dar Es Salaam") def name = cities.find(_.pop < 5.0e6).map(_.name) def pop = cities.find(_.name(0) == 'A').map(_.pop) case class City(name: String, pop: Double) println( s"Index of first city whose name is 'Dar Es Salaam' = $index\n" + s"Name of first city whose population is less than 5 million = ${name.get}\n" + f"Population of first city whose name starts with 'A' = ${pop.get}%,.0f") }
317Search a list of records
16scala
xrpwg
a, b = 5, -7 ans = eval
321Runtime evaluation
14ruby
0hbsu
code = loadstring"return x^2"
322Runtime evaluation/In an environment
1lua
1u5po
package main import ( "fmt" "math/big" ) func main() { var n, e, d, bb, ptn, etn, dtn big.Int pt := "Rosetta Code" fmt.Println("Plain text: ", pt)
324RSA code
0go
6sq3p
CREATE TABLE african_capitals(name varchar2(100), population_in_millions NUMBER(3,2));
317Search a list of records
19sql
0hes1
package main import ( "fmt" "io/ioutil" "net/http" "regexp" "sort" "strconv" ) type Result struct { lang string users int } func main() { const minimum = 25 ex := `"Category:(.+?)( User)?"(\}|,"categoryinfo":\{"size":(\d+),)` re := regexp.MustCompile(ex) page := "http:
325Rosetta Code/Rank languages by number of users
0go
ci89g
module RSAMaker where import Data.Char ( chr ) encode :: String -> [Integer] encode s = map (toInteger . fromEnum ) s rsa_encode :: Integer -> Integer -> [Integer] -> [Integer] rsa_encode n e numbers = map (\num -> mod ( num ^ e ) n ) numbers rsa_decode :: Integer -> Integer -> [Integer] -> [Integer] rsa_decode d n ciphers = map (\c -> mod ( c ^ d ) n ) ciphers decode :: [Integer] -> String decode encoded = map ( chr . fromInteger ) encoded divisors :: Integer -> [Integer] divisors n = [m | m <- [1..n] , mod n m == 0 ] isPrime :: Integer -> Bool isPrime n = divisors n == [1,n] totient :: Integer -> Integer -> Integer totient prime1 prime2 = (prime1 - 1 ) * ( prime2 - 1 ) myE :: Integer -> Integer myE tot = head [n | n <- [2..tot - 1] , gcd n tot == 1] myD :: Integer -> Integer -> Integer -> Integer myD e n phi = head [d | d <- [1..n] , mod ( d * e ) phi == 1] main = do putStrLn "Enter a test text!" text <- getLine let primes = take 90 $ filter isPrime [1..] p1 = last primes p2 = last $ init primes tot = totient p1 p2 e = myE tot n = p1 * p2 rsa_encoded = rsa_encode n e $ encode text d = myD e n tot encrypted = concatMap show rsa_encoded decrypted = decode $ rsa_decode d n rsa_encoded putStrLn ("Encrypted: " ++ encrypted ) putStrLn ("And now decrypted: " ++ decrypted )
324RSA code
8haskell
j9m7g
struct Place { var name: String var population: Double } let places = [ Place(name: "Lagos", population: 21.0), Place(name: "Cairo", population: 15.2), Place(name: "Kinshasa-Brazzaville", population: 11.3), Place(name: "Greater Johannesburg", population: 7.55), Place(name: "Mogadishu", population: 5.85), Place(name: "Khartoum-Omdurman", population: 4.98), Place(name: "Dar Es Salaam", population: 4.7), Place(name: "Alexandria", population: 4.58), Place(name: "Abidjan", population: 4.4), Place(name: "Casablanca", population: 3.98) ]
317Search a list of records
17swift
pv7bl
double rk4(double(*f)(double, double), double dx, double x, double y) { double k1 = dx * f(x, y), k2 = dx * f(x + dx / 2, y + k1 / 2), k3 = dx * f(x + dx / 2, y + k2 / 2), k4 = dx * f(x + dx, y + k3); return y + (k1 + 2 * k2 + 2 * k3 + k4) / 6; } double rate(double x, double y) { return x * sqrt(y); } int main(void) { double *y, x, y2; double x0 = 0, x1 = 10, dx = .1; int i, n = 1 + (x1 - x0)/dx; y = (double *)malloc(sizeof(double) * n); for (y[0] = 1, i = 1; i < n; i++) y[i] = rk4(rate, dx, x0 + dx * (i - 1), y[i-1]); printf(); for (i = 0; i < n; i += 10) { x = x0 + dx * i; y2 = pow(x * x / 4 + 1, 2); printf(, x, y[i], y[i]/y2 - 1); } return 0; }
326Runge-Kutta method
5c
ci09c
use strict; use warnings; use JSON; use URI::Escape; use LWP::UserAgent; my $client = LWP::UserAgent->new; $client->agent("Rosettacode Perl task solver"); my $url = 'http://rosettacode.org/mw'; my $minimum = 100; sub uri_query_string { my(%fields) = @_; 'action=query&format=json&formatversion=2&' . join '&', map { $_ . '=' . uri_escape($fields{$_}) } keys %fields } sub mediawiki_query { my($site, $type, %query) = @_; my $url = "$site/api.php?" . uri_query_string(%query); my %languages = (); my $req = HTTP::Request->new( GET => $url ); my $response = $client->request($req); $response->is_success or die "Failed to GET '$url': ", $response->status_line; my $data = decode_json($response->content); for my $row ( @{${$data}{query}{pages}} ) { next unless defined $$row{categoryinfo} && $$row{title} =~ /User/; my($title) = $$row{title} =~ /Category:(.*?) User/; my($count) = $$row{categoryinfo}{pages}; $languages{$title} = $count; } %languages; } my %table = mediawiki_query( $url, 'pages', ( generator => 'categorymembers', gcmtitle => 'Category:Language users', gcmlimit => '999', prop => 'categoryinfo', rawcontinue => '', ) ); for my $k (sort { $table{$b} <=> $table{$a} } keys %table) { printf "%4d%s\n", $table{$k}, $k if $table{$k} > $minimum; }
325Rosetta Code/Rank languages by number of users
2perl
0h7s4
sub eval_with_x {my $code = shift; my $x = shift; my $first = eval $code; $x = shift; return eval($code) - $first;} print eval_with_x('3 * $x', 5, 10), "\n";
322Runtime evaluation/In an environment
2perl
y086u
import requests URL = PARAMS = { : , : , : 2, : , : , : 500, : , } def fetch_data(): counts = {} continue_ = {: } while continue_: resp = requests.get(URL, params={**PARAMS, **continue_}) resp.raise_for_status() data = resp.json() counts.update( { p[]: p.get(, {}).get(, 0) for p in data[][] } ) continue_ = data.get(, {}) return counts if __name__ == : counts = fetch_data() at_least_100 = [(lang, count) for lang, count in counts.items() if count >= 100] top_languages = sorted(at_least_100, key=lambda x: x[1], reverse=True) for i, lang in enumerate(top_languages): print(f)
325Rosetta Code/Rank languages by number of users
3python
8kj0o
<?php function eval_with_x($code, $a, $b) { $x = $a; $first = eval($code); $x = $b; $second = eval($code); return $second - $first; } echo eval_with_x('return 3 * $x;', 5, 10), ; ?>
322Runtime evaluation/In an environment
12php
a5412
enum { S_NONE, S_LIST, S_STRING, S_SYMBOL }; typedef struct { int type; size_t len; void *buf; } s_expr, *expr; void whine(const char *s) { fprintf(stderr, , s); } expr parse_string(const char *s, char **e) { expr ex = calloc(sizeof(s_expr), 1); char buf[256] = {0}; int i = 0; while (*s) { if (i >= 256) { fprintf(stderr, ); whine(s); goto fail; } switch (*s) { case '\\': switch (*++s) { case '\\': case '': goto success; default: buf[i++] = *s++; } } fail: free(ex); return 0; success: *(const char **)e = s + 1; ex->type = S_STRING; ex->buf = strdup(buf); ex->len = strlen(buf); return ex; } expr parse_symbol(const char *s, char **e) { expr ex = calloc(sizeof(s_expr), 1); char buf[256] = {0}; int i = 0; while (*s) { if (i >= 256) { fprintf(stderr, ); whine(s); goto fail; } if (isspace(*s)) goto success; if (*s == ')' || *s == '(') { s--; goto success; } switch (*s) { case '\\': switch (*++s) { case '\\': case '': whine(s); goto success; default: buf[i++] = *s++; } } fail: free(ex); return 0; success: *(const char **)e = s + 1; ex->type = S_SYMBOL; ex->buf = strdup(buf); ex->len = strlen(buf); return ex; } void append(expr list, expr ele) { list->buf = realloc(list->buf, sizeof(expr) * ++list->len); ((expr*)(list->buf))[list->len - 1] = ele; } expr parse_list(const char *s, char **e) { expr ex = calloc(sizeof(s_expr), 1), chld; char *next; ex->len = 0; while (*s) { if (isspace(*s)) { s++; continue; } switch (*s) { case '': return parse_string(s+1, e); default: return parse_symbol(s+1, e); } } return 0; } void print_expr(expr e, int depth) { int i; if (!e) return; switch(e->type) { case S_LIST: sep(); puts(); for (i = 0; i < e->len; i++) print_expr(((expr*)e->buf)[i], depth + 1); sep(); puts(); return; case S_SYMBOL: case S_STRING: sep(); if (e->type == S_STRING) putchar('': case '\\': putchar('\\'); break; case ')': case '(': if (e->type == S_SYMBOL) putchar('\\'); } putchar(((char*)e->buf)[i]); } if (e->type == S_STRING) putchar('((data da\\(\\)ta \ 123 4.5)\n (\ (!@ expr x = parse_term(in, &next); printf(, in); printf(); print_expr(x, 0); return 0; }
327S-expressions
5c
ln0cy
public static void main(String[] args) { BigInteger n = new BigInteger("9516311845790656153499716760847001433441357"); BigInteger e = new BigInteger("65537"); BigInteger d = new BigInteger("5617843187844953170308463622230283376298685"); Charset c = Charsets.UTF_8; String plainText = "Rosetta Code"; System.out.println("PlainText: " + plainText); byte[] bytes = plainText.getBytes(); BigInteger plainNum = new BigInteger(bytes); System.out.println("As number: " + plainNum); BigInteger Bytes = new BigInteger(bytes); if (Bytes.compareTo(n) == 1) { System.out.println("Plaintext is too long"); return; } BigInteger enc = plainNum.modPow(e, n); System.out.println("Encoded: " + enc); BigInteger dec = enc.modPow(d, n); System.out.println("Decoded: " + dec); String decText = new String(dec.toByteArray(), c); System.out.println("As text: " + decText); }
324RSA code
9java
utfvv
int compareInts(const void *i1, const void *i2) { int a = *((int *)i1); int b = *((int *)i2); return a - b; } int main() { int i, j, nsum, vsum, vcount, values[6], numbers[4]; srand(time(NULL)); for (;;) { vsum = 0; for (i = 0; i < 6; ++i) { for (j = 0; j < 4; ++j) { numbers[j] = 1 + rand() % 6; } qsort(numbers, 4, sizeof(int), compareInts); nsum = 0; for (j = 1; j < 4; ++j) { nsum += numbers[j]; } values[i] = nsum; vsum += values[i]; } if (vsum < 75) continue; vcount = 0; for (j = 0; j < 6; ++j) { if (values[j] >= 15) vcount++; } if (vcount < 2) continue; printf(); printf(); for (j = 0; j < 6; ++j) printf(, values[j]); printf(); printf(, vsum, vcount); break; } return 0; }
328RPG attributes generator
5c
zxptx
>>> def eval_with_x(code, a, b): return eval(code, {'x':b}) - eval(code, {'x':a}) >>> eval_with_x('2 ** x', 3, 5) 24
322Runtime evaluation/In an environment
3python
m8oyh
null
324RSA code
11kotlin
9o8mh
evalWithAB <- function(expr, var, a, b) { env <- new.env() assign(var, a, envir=env) atA <- eval(parse(text=expr), env) assign(var, b, envir=env) atB <- eval(parse(text=expr), env) return(atB - atA) } print(evalWithAB("2*x+1", "x", 5, 3)) print(evalWithAB("2*y+1", "y", 5, 3)) print(evalWithAB("2*y+1", "x", 5, 3))
322Runtime evaluation/In an environment
13r
zxqth
const char * lang_url = ; const char * cat_url = ; char *get_page(const char *url) { char cmd[1024]; char *ptr, *buf; int bytes_read = 1, len = 0; sprintf(cmd, %s\, url); FILE *fp = popen(cmd, ); if (!fp) return 0; for (ptr = buf = 0; bytes_read > 0; ) { buf = realloc(buf, 1 + (len += BLOCK)); if (!ptr) ptr = buf; bytes_read = fread(ptr, 1, BLOCK, fp); if (bytes_read <= 0) break; ptr += bytes_read; } *++ptr = '\0'; return buf; } char ** get_langs(char *buf, int *l) { char **arr = 0; for (*l = 0; (buf = strstr(buf, )) && (buf += 9); ++*l) for ( (*l)[arr = realloc(arr, sizeof(char*)*(1 + *l))] = buf; *buf != '/wiki/Category:%s</a> (%4d%s\n", cats[clen].count, cats[clen].name); return 0; }
329Rosetta Code/Rank languages by popularity
5c
6s132
package main import "fmt" import "io/ioutil" import "log" import "os" import "regexp" import "strings" func main() { err := fix() if err != nil { log.Fatalln(err) } } func fix() (err error) { buf, err := ioutil.ReadAll(os.Stdin) if err != nil { return err } out, err := Lang(string(buf)) if err != nil { return err } fmt.Println(out) return nil } func Lang(in string) (out string, err error) { reg := regexp.MustCompile("<[^>]+>") out = reg.ReplaceAllStringFunc(in, repl) return out, nil } func repl(in string) (out string) { if in == "</code>" {
330Rosetta Code/Fix code tags
0go
xrlwf
use bigint; $n = 9516311845790656153499716760847001433441357; $e = 65537; $d = 5617843187844953170308463622230283376298685; package Message { my @alphabet; push @alphabet, $_ for 'A' .. 'Z', ' '; my $rad = +@alphabet; $code{$alphabet[$_]} = $_ for 0..$rad-1; sub encode { my($t) = @_; my $cnt = my $sum = 0; for (split '', reverse $t) { $sum += $code{$_} * $rad**$cnt; $cnt++; } $sum; } sub decode { my($n) = @_; my(@i); while () { push @i, $n % $rad; last if $n < $rad; $n = int $n / $rad; } reverse join '', @alphabet[@i]; } sub expmod { my($a, $b, $n) = @_; my $c = 1; do { ($c *= $a) %= $n if $b % 2; ($a *= $a) %= $n; } while ($b = int $b/2); $c; } } my $secret_message = "ROSETTA CODE"; $numeric_message = Message::encode $secret_message; $numeric_cipher = Message::expmod $numeric_message, $e, $n; $text_cipher = Message::decode $numeric_cipher; $numeric_cipher2 = Message::encode $text_cipher; $numeric_message2 = Message::expmod $numeric_cipher2, $d, $n; $secret_message2 = Message::decode $numeric_message2; print <<"EOT"; Secret message is $secret_message Secret message in integer form is $numeric_message After exponentiation with public exponent we get: $numeric_cipher This turns into the string $text_cipher If we re-encode it in integer form we get $numeric_cipher2 After exponentiation with SECRET exponent we get: $numeric_message2 This turns into the string $secret_message2 EOT
324RSA code
2perl
wg4e6
def eratosthenes2(n): multiples = set() for i in range(2, n+1): if i not in multiples: yield i multiples.update(range(i*i, n+1, i)) print(list(eratosthenes2(100)))
309Sieve of Eratosthenes
3python
zqmtt
import 'dart:math' as Math; num RungeKutta4(Function f, num t, num y, num dt){ num k1 = dt * f(t,y); num k2 = dt * f(t+0.5*dt, y + 0.5*k1); num k3 = dt * f(t+0.5*dt, y + 0.5*k2); num k4 = dt * f(t + dt, y + k3); return y + (1/6) * (k1 + 2*k2 + 2*k3 + k4); } void main(){ num t = 0; num dt = 0.1; num tf = 10; num totalPoints = ((tf-t)/dt).floor()+1; num y = 1; Function f = (num t, num y) => t * Math.sqrt(y); Function actual = (num t) => (1/16) * (t*t+4)*(t*t+4); for (num i = 0; i <= totalPoints; i++){ num relativeError = (actual(t) - y)/actual(t); if (i%10 == 0){ print('y(${t.round().toStringAsPrecision(3)}) = ${y.toStringAsPrecision(11)} Error = ${relativeError.toStringAsPrecision(11)}'); } y = RungeKutta4(f, t, y, dt); t += dt; } }
326Runge-Kutta method
18dart
zxate
def bind_x_to_value(x) binding end def eval_with_x(code, a, b) eval(code, bind_x_to_value(b)) - eval(code, bind_x_to_value(a)) end puts eval_with_x('2 ** x', 3, 5)
322Runtime evaluation/In an environment
14ruby
cin9k
object Eval extends App { def evalWithX(expr: String, a: Double, b: Double)= {val x = b; eval(expr)} - {val x = a; eval(expr)} println(evalWithX("Math.exp(x)", 0.0, 1.0)) }
322Runtime evaluation/In an environment
16scala
utzv8
import java.io.BufferedReader; import java.io.File; import java.io.FileReader; import java.io.FileWriter; public class FixCodeTags { public static void main(String[] args) { String sourcefile=args[0]; String convertedfile=args[1]; convert(sourcefile,convertedfile); } static String[] languages = {"abap", "actionscript", "actionscript3", "ada", "apache", "applescript", "apt_sources", "asm", "asp", "autoit", "avisynth", "bar", "bash", "basic4gl", "bf", "blitzbasic", "bnf", "boo", "c", "caddcl", "cadlisp", "cfdg", "cfm", "cil", "c_mac", "cobol", "cpp", "cpp-qt", "csharp", "css", "d", "delphi", "diff", "_div", "dos", "dot", "eiffel", "email", "foo", "fortran", "freebasic", "genero", "gettext", "glsl", "gml", "gnuplot", "go", "groovy", "haskell", "hq9plus", "html4strict", "idl", "ini", "inno", "intercal", "io", "java", "java5", "javascript", "kixtart", "klonec", "klonecpp", "latex", "lisp", "lolcode", "lotusformulas", "lotusscript", "lscript", "lua", "m68k", "make", "matlab", "mirc", "modula3", "mpasm", "mxml", "mysql", "nsis", "objc", "ocaml", "ocaml-brief", "oobas", "oracle11", "oracle8", "pascal", "per", "perl", "php", "php-brief", "pic16", "pixelbender", "plsql", "povray", "powershell", "progress", "prolog", "providex", "python", "qbasic", "rails", "reg", "robots", "ruby", "sas", "scala", "scheme", "scilab", "sdlbasic", "smalltalk", "smarty", "sql", "tcl", "teraterm", "text", "thinbasic", "tsql", "typoscript", "vb", "vbnet", "verilog", "vhdl", "vim", "visualfoxpro", "visualprolog", "whitespace", "winbatch", "xml", "xorg_conf", "xpp", "z80"}; static void convert(String sourcefile,String convertedfile) { try { BufferedReader br=new BufferedReader(new FileReader(sourcefile));
330Rosetta Code/Fix code tags
9java
da7n9
var langs = ['foo', 'bar', 'baz'];
330Rosetta Code/Fix code tags
10javascript
6sp38
sieve <- function(n) { if (n < 2) integer(0) else { primes <- rep(T, n) primes[[1]] <- F for(i in seq(sqrt(n))) { if(primes[[i]]) { primes[seq(i * i, n, i)] <- F } } which(primes) } } sieve(1000)
309Sieve of Eratosthenes
13r
nazi2
null
330Rosetta Code/Fix code tags
1lua
8k50e
import binascii n = 9516311845790656153499716760847001433441357 e = 65537 d = 5617843187844953170308463622230283376298685 message='Rosetta Code!' print('message ', message) hex_data = binascii.hexlify(message.encode()) print('hex data ', hex_data) plain_text = int(hex_data, 16) print('plain text integer ', plain_text) if plain_text > n: raise Exception('plain text too large for key') encrypted_text = pow(plain_text, e, n) print('encrypted text integer ', encrypted_text) decrypted_text = pow(encrypted_text, d, n) print('decrypted text integer ', decrypted_text) print('message ', binascii.unhexlify(hex(decrypted_text)[2:]).decode())
324RSA code
3python
xrgwr
(require '[clojure.xml:as xml] '[clojure.set:as set] '[clojure.string:as string]) (import '[java.net URLEncoder])
331Rosetta Code/Find unimplemented tasks
6clojure
pv3bd
package main var haystack = []string{"Zig", "Zag", "Wally", "Ronald", "Bush", "Krusty", "Charlie", "Bush", "Bozo", "Zag", "mouse", "hat", "cup", "deodorant", "television", "soap", "methamphetamine", "severed cat heads", "foo", "bar", "baz", "quux", "quuux", "quuuux", "bazola", "ztesch", "foo", "bar", "thud", "grunt", "foo", "bar", "bletch", "foo", "bar", "fum", "fred", "jim", "sheila", "barney", "flarp", "zxc", "spqr", ";wombat", "shme", "foo", "bar", "baz", "bongo", "spam", "eggs", "snork", "foo", "bar", "zot", "blarg", "wibble", "toto", "titi", "tata", "tutu", "pippo", "pluto", "paperino", "aap", "noot", "mies", "oogle", "foogle", "boogle", "zork", "gork", "bork", "sodium", "phosphorous", "californium", "copernicium", "gold", "thallium", "carbon", "silver", "gold", "copper", "helium", "sulfur"}
323Search a list
0go
q77xz
require 'openssl' require 'prime' def rsa_encode blocks, e, n blocks.map{|b| b.to_bn.mod_exp(e, n).to_i} end def rsa_decode ciphers, d, n rsa_encode ciphers, d, n end def text_to_blocks text, blocksize=64 text.each_byte.reduce(){|acc,b| acc << b.to_s(16).rjust(2, )} .each_char.each_slice(blocksize).to_a .map{|a| a.join().to_i(16)} end def blocks_to_text blocks blocks.map{|d| d.to_s(16)}.join() .each_char.each_slice(2).to_a .map{|s| s.join().to_i(16)} .flatten.pack() .force_encoding(Encoding::default_external) end def generate_keys p1, p2 n = p1 * p2 t = (p1 - 1) * (p2 - 1) e = 2.step.each do |i| break i if i.gcd(t) == 1 end d = 1.step.each do |i| break i if (i * e) % t == 1 end return e, d, n end p1, p2 = Prime.take(100).last(2) public_key, private_key, modulus = generate_keys p1, p2 print message = gets blocks = text_to_blocks message, 4 print ; p blocks encoded = rsa_encode(blocks, public_key, modulus) print ; p encoded decoded = rsa_decode(encoded, private_key, modulus) print ; p decoded final = blocks_to_text(decoded) print ; puts final
324RSA code
14ruby
sj7qw
def haystack = ["Zig","Zag","Wally","Ronald","Bush","Krusty","Charlie","Bush","Bozo"] def needles = ["Washington","Bush","Wally"] needles.each { needle -> def index = haystack.indexOf(needle) def lastindex = haystack.lastIndexOf(needle) if (index < 0) { assert lastindex < 0 println needle + " is not in haystack" } else { println "First index: " + index + " " + needle println "Last index: " + lastindex + " " + needle } }
323Search a list
7groovy
1uup6
package main import ( "fmt" "math" ) type ypFunc func(t, y float64) float64 type ypStepFunc func(t, y, dt float64) float64
326Runge-Kutta method
0go
wgueg
package main import ( "encoding/xml" "fmt" "io" "net/http" "net/url" ) const language = "Go" var baseQuery = "http:
331Rosetta Code/Find unimplemented tasks
0go
darne
my @langs = qw(ada cpp-qt pascal lscript z80 visualprolog html4strict cil objc asm progress teraterm hq9plus genero tsql email pic16 tcl apt_sources io apache vhdl avisynth winbatch vbnet ini scilab ocaml-brief sas actionscript3 qbasic perl bnf cobol powershell php kixtart visualfoxpro mirc make javascript cpp sdlbasic cadlisp php-brief rails verilog xml csharp actionscript nsis bash typoscript freebasic dot applescript haskell dos oracle8 cfdg glsl lotusscript mpasm latex sql klonec ruby ocaml smarty python oracle11 caddcl robots groovy smalltalk diff fortran cfm lua modula3 vb autoit java text scala lotusformulas pixelbender reg _div whitespace providex asp css lolcode lisp inno mysql plsql matlab oobas vim delphi xorg_conf gml prolog bf per scheme mxml d basic4gl m68k gnuplot idl abap intercal c_mac thinbasic java5 xpp boo klonecpp blitzbasic eiffel povray c gettext); my $text = join "", <STDIN>; my $slang="/lang"; for (@langs) { $text =~ s|<$_>|<lang $_>|g; $text =~ s|</$_>|<$slang>|g; } $text =~ s|<code (.+?)>(.*?)</code>|<lang $1>$2<$slang>|sg; print $text;
330Rosetta Code/Fix code tags
2perl
5z8u2
extern crate num; use num::bigint::BigUint; use num::integer::Integer; use num::traits::{One, Zero}; fn mod_exp(b: &BigUint, e: &BigUint, n: &BigUint) -> Result<BigUint, &'static str> { if n.is_zero() { return Err("modulus is zero"); } if b >= n {
324RSA code
15rust
0hjsl
object RSA_saket{ val d = BigInt("5617843187844953170308463622230283376298685") val n = BigInt("9516311845790656153499716760847001433441357") val e = 65537 val text = "Rosetta Code" val encode = (msg:BigInt) => pow_mod(msg,e,n) val decode = (msg:BigInt) => pow_mod(msg,d,n) val getmsg = (txt:String) => BigInt(txt.map(x => "%03d".format(x.toInt)).reduceLeft(_+_)) def pow_mod(p:BigInt, q:BigInt, n:BigInt):BigInt = { if(q==0) BigInt(1) else if(q==1) p else if(q%2 == 1) pow_mod(p,q-1,n)*p % n else pow_mod(p*p % n,q/2,n) } def gettxt(num:String) = { if(num.size%3==2) ("0" + num).grouped(3).toList.foldLeft("")(_ + _.toInt.toChar) else num.grouped(3).toList.foldLeft("")(_ + _.toInt.toChar) } def main(args: Array[String]): Unit = { println(f"Original String \t: "+text) val msg = getmsg(text) println(f"Converted Signal \t: "+msg) val enc_sig = encode(msg) println("Encoded Signal \t\t: "+ enc_sig) val dec_sig = decode(enc_sig) println("Decoded String \t\t: "+ dec_sig) val rec_msg = gettxt(dec_sig.toString) println("Retrieved Signal \t: "+rec_msg) } }
324RSA code
16scala
ipbox
(ns count-examples (:import [java.net URLEncoder]) (:use [clojure.contrib.http.agent:only (http-agent string)] [clojure.contrib.json:only (read-json)] [clojure.contrib.string:only (join)])) (defn url-encode [v] (URLEncoder/encode (str v) "utf-8")) (defn rosettacode-get [path params] (let [param-string (join "&" (for [[n v] params] (str (name n) "=" (url-encode v))))] (string (http-agent (format "http://www.rosettacode.org/w/%s?%s" path param-string))))) (defn rosettacode-query [params] (read-json (rosettacode-get "api.php" (merge {:action "query":format "json"} params)))) (defn list-cm ([params] (list-cm params nil)) ([params continue] (let [cm-params (merge {:list "categorymembers"} params (or continue {})) result (rosettacode-query cm-params)] (concat (-> result (:query) (:categorymembers)) (if-let [cmcontinue (-> result (:query-continue) (:categorymembers))] (list-cm params cmcontinue)))))) (defn programming-tasks [] (let [result (list-cm {:cmtitle "Category:Programming_Tasks":cmlimit 50})] (map #(:title %) result))) (defn task-count [task] [task (count (re-seq #"==\{\{header" (rosettacode-get "index.php" {:action "raw":title task})))]) (defn print-result [] (let [task-counts (map task-count (programming-tasks))] (doseq [[task count] task-counts] (println (str task ":") count) (flush)) (println "Total: " (reduce #(+ %1 (second %2)) 0 task-counts))))
332Rosetta Code/Count examples
6clojure
y0b6b
import Data.List haystack=["Zig","Zag","Wally","Ronald","Bush","Krusty","Charlie","Bush","Bozo"] needles = ["Washington","Bush"]
323Search a list
8haskell
m88yf
class Runge_Kutta{ static void main(String[] args){ def y=1.0,t=0.0,counter=0; def dy1,dy2,dy3,dy4; def real; while(t<=10) {if(counter%10==0) {real=(t*t+4)*(t*t+4)/16; println("y("+t+")="+ y+ " Error:"+ (real-y)); } dy1=dy(dery(y,t)); dy2=dy(dery(y+dy1/2,t+0.05)); dy3=dy(dery(y+dy2/2,t+0.05)); dy4=dy(dery(y+dy3,t+0.1)); y=y+(dy1+2*dy2+2*dy3+dy4)/6; t=t+0.1; counter++; } } static def dery(def y,def t){return t*(Math.sqrt(y));} static def dy(def x){return x*0.1;} }
326Runge-Kutta method
7groovy
b29ky
import Network.Browser import Network.HTTP import Network.URI import Data.List import Data.Maybe import Text.XML.Light import Control.Arrow import Data.Char getRespons url = do rsp <- Network.Browser.browse $ do setAllowRedirects True setOutHandler $ const (return ()) request $ getRequest url return $ rspBody $ snd rsp replaceWithSpace c = (\x -> if c==x then ' ' else x) encl = chr 34 unimpTasks lang = do allTasks <- getRespons "http://www.rosettacode.org/w/api.php?action=query&list=categorymembers&cmtitle=Category:Programming_Tasks&cmlimit=500&format=xml" impl <- getRespons ( "http://rosettacode.org/json/isb/" ++ lang ++ ".json") let langxx = map (map(replaceWithSpace '_')) $ filter (/=",") $ words $ map (replaceWithSpace encl ) $ init $ drop 1 impl xml = onlyElems $ parseXML allTasks allxx = concatMap (map (fromJust.findAttr (unqual "title")). filterElementsName (== unqual "cm")) xml mapM_ putStrLn $ sort $ allxx \\ langxx
331Rosetta Code/Find unimplemented tasks
8haskell
5z0ug
package main import ( "errors" "fmt" "reflect" "strconv" "strings" "unicode" ) var input = `((data "quoted data" 123 4.5) (data (!@# (4.5) "(more" "data)")))` func main() { fmt.Println("input:") fmt.Println(input) s, err := parseSexp(input) if err != nil { fmt.Println("error:", err) return } fmt.Println("\nparsed:") fmt.Println(s) fmt.Println("\nrepresentation:") s.dump(0) }
327S-expressions
0go
xruwf
package main import ( "fmt" "math/rand" "sort" "time" ) func main() { s := rand.NewSource(time.Now().UnixNano()) r := rand.New(s) for { var values [6]int vsum := 0 for i := range values { var numbers [4]int for j := range numbers { numbers[j] = 1 + r.Intn(6) } sort.Ints(numbers[:]) nsum := 0 for _, n := range numbers[1:] { nsum += n } values[i] = nsum vsum += values[i] } if vsum < 75 { continue } vcount := 0 for _, v := range values { if v >= 15 { vcount++ } } if vcount < 2 { continue } fmt.Println("The 6 random numbers generated are:") fmt.Println(values) fmt.Println("\nTheir sum is", vsum, "and", vcount, "of them are >= 15") break } }
328RPG attributes generator
0go
kl6hz
package main import ( "encoding/xml" "fmt" "io" "io/ioutil" "log" "net/http" "net/url" "regexp" "sort" "strconv" "strings" ) var baseQuery = "http:
329Rosetta Code/Rank languages by popularity
0go
pvybg
int main() { double a, c, s, PI2 = atan2(1, 1) * 8; int n, i; for (n = 1; n < 10; n++) for (i = 0; i < n; i++) { c = s = 0; if (!i ) c = 1; else if(n == 4 * i) s = 1; else if(n == 2 * i) c = -1; else if(3 * n == 4 * i) s = -1; else a = i * PI2 / n, c = cos(a), s = sin(a); if (c) printf(, c); printf(s == 1 ? : s == -1 ? : s ? : , s); printf(i == n - 1 ?:); } return 0; }
333Roots of unity
5c
0hlst
typedef double complex cplx; void quad_root (double a, double b, double c, cplx * ra, cplx *rb) { double d, e; if (!a) { *ra = b ? -c / b : 0; *rb = 0; return; } if (!c) { *ra = 0; *rb = -b / a; return; } b /= 2; if (fabs(b) > fabs(c)) { e = 1 - (a / b) * (c / b); d = sqrt(fabs(e)) * fabs(b); } else { e = (c > 0) ? a : -a; e = b * (b / fabs(c)) - e; d = sqrt(fabs(e)) * sqrt(fabs(c)); } if (e < 0) { e = fabs(d / a); d = -b / a; *ra = d + I * e; *rb = d - I * e; return; } d = (b >= 0) ? d : -d; e = (d - b) / a; d = e ? (c / e) / a : 0; *ra = d; *rb = e; return; } int main() { cplx ra, rb; quad_root(1, 1e12 + 1, 1e12, &ra, &rb); printf(, creal(ra), cimag(ra), creal(rb), cimag(rb)); quad_root(1e300, -1e307 + 1, 1e300, &ra, &rb); printf(, creal(ra), cimag(ra), creal(rb), cimag(rb)); return 0; }
334Roots of a quadratic function
5c
da5nv
import qualified Data.Functor.Identity as F import qualified Text.Parsec.Prim as Prim import Text.Parsec ((<|>), (<?>), many, many1, char, try, parse, sepBy, choice, between) import Text.Parsec.Token (integer, float, whiteSpace, stringLiteral, makeTokenParser) import Text.Parsec.Char (noneOf) import Text.Parsec.Language (haskell) data Val = Int Integer | Float Double | String String | Symbol String | List [Val] deriving (Eq, Show) tProg :: Prim.ParsecT String a F.Identity [Val] tProg = many tExpr <?> "program" where tExpr = between ws ws (tList <|> tAtom) <?> "expression" ws = whiteSpace haskell tAtom = (try (Float <$> float haskell) <?> "floating point number") <|> (try (Int <$> integer haskell) <?> "integer") <|> (String <$> stringLiteral haskell <?> "string") <|> (Symbol <$> many1 (noneOf "()\"\t\n\r ") <?> "symbol") <?> "atomic expression" tList = List <$> between (char '(') (char ')') (many tExpr) <?> "list" p :: String -> IO () p = either print (putStrLn . unwords . map show) . parse tProg "" main :: IO () main = do let expr = "((data \"quoted data\" 123 4.5)\n (data (!@# (4.5) \"(more\" \"data)\")))" putStrLn ("The input:\n" ++ expr ++ "\n\nParsed as:") p expr
327S-expressions
8haskell
y0w66
import sys import re langs = ['ada', 'cpp-qt', 'pascal', 'lscript', 'z80', 'visualprolog', 'html4strict', 'cil', 'objc', 'asm', 'progress', 'teraterm', 'hq9plus', 'genero', 'tsql', 'email', 'pic16', 'tcl', 'apt_sources', 'io', 'apache', 'vhdl', 'avisynth', 'winbatch', 'vbnet', 'ini', 'scilab', 'ocaml-brief', 'sas', 'actionscript3', 'qbasic', 'perl', 'bnf', 'cobol', 'powershell', 'php', 'kixtart', 'visualfoxpro', 'mirc', 'make', 'javascript', 'cpp', 'sdlbasic', 'cadlisp', 'php-brief', 'rails', 'verilog', 'xml', 'csharp', 'actionscript', 'nsis', 'bash', 'typoscript', 'freebasic', 'dot', 'applescript', 'haskell', 'dos', 'oracle8', 'cfdg', 'glsl', 'lotusscript', 'mpasm', 'latex', 'sql', 'klonec', 'ruby', 'ocaml', 'smarty', 'python', 'oracle11', 'caddcl', 'robots', 'groovy', 'smalltalk', 'diff', 'fortran', 'cfm', 'lua', 'modula3', 'vb', 'autoit', 'java', 'text', 'scala', 'lotusformulas', 'pixelbender', 'reg', '_div', 'whitespace', 'providex', 'asp', 'css', 'lolcode', 'lisp', 'inno', 'mysql', 'plsql', 'matlab', 'oobas', 'vim', 'delphi', 'xorg_conf', 'gml', 'prolog', 'bf', 'per', 'scheme', 'mxml', 'd', 'basic4gl', 'm68k', 'gnuplot', 'idl', 'abap', 'intercal', 'c_mac', 'thinbasic', 'java5', 'xpp', 'boo', 'klonecpp', 'blitzbasic', 'eiffel', 'povray', 'c', 'gettext'] slang = '/lang' code='code' text = sys.stdin.read() for i in langs: text = text.replace(% i,% i) text = text.replace(% i, % slang) text = re.sub(%(code,code), r% slang, text) sys.stdout.write(text)
330Rosetta Code/Fix code tags
3python
43o5k
import Control.Monad (replicateM) import System.Random (randomRIO) import Data.Bool (bool) import Data.List (sort) character :: IO [Int] character = discardUntil (((&&) . (75 <) . sum) <*> ((2 <=) . length . filter (15 <=))) (replicateM 6 $ sum . tail . sort <$> replicateM 4 (randomRIO (1, 6 :: Int))) discardUntil :: ([Int] -> Bool) -> IO [Int] -> IO [Int] discardUntil p throw = go where go = throw >>= (<*>) (bool go . return) p main :: IO () main = replicateM 10 character >>= mapM_ (print . (sum >>= (,)))
328RPG attributes generator
8haskell
n1jie
def html = new URL('http:
329Rosetta Code/Rank languages by popularity
7groovy
7mfrz
dv :: Floating a => a -> a -> a dv = (. sqrt) . (*) fy t = 1 / 16 * (4 + t ^ 2) ^ 2 rk4 :: (Enum a, Fractional a) => (a -> a -> a) -> a -> a -> a -> [(a, a)] rk4 fd y0 a h = zip ts $ scanl (flip fc) y0 ts where ts = [a,h ..] fc t y = sum . (y:) . zipWith (*) [1 / 6, 1 / 3, 1 / 3, 1 / 6] $ scanl (\k f -> h * fd (t + f * h) (y + f * k)) (h * fd t y) [1 / 2, 1 / 2, 1] task = mapM_ (print . (\(x, y) -> (truncate x, y, fy x - y))) (filter (\(x, _) -> 0 == mod (truncate $ 10 * x) 10) $ take 101 $ rk4 dv 1.0 0 0.1)
326Runge-Kutta method
8haskell
6sw3k
fixtags <- function(page) { langs <- c("c", "c-sharp", "r") langs <- paste(langs, collapse="|") page <- gsub(paste("<(", langs, ")>", sep=""), "<lang \\1>", page) page <- gsub(paste("</(", langs, ")>", sep=""), "</ page <- gsub(paste("<code(", langs, ")>", sep=""), "<lang \\1>", page) page <- gsub(paste("</code>", sep=""), "</ page } page <- "lorem ipsum <c>some c code</c>dolor sit amet,<c-sharp>some c-sharp code</c-sharp> consectetur adipisicing elit,<code r>some r code</code>sed do eiusmod tempor incididunt" fixtags(page)
330Rosetta Code/Fix code tags
13r
2dqlg
def eratosthenes(n) nums = [nil, nil, *2..n] (2..Math.sqrt(n)).each do |i| (i**2..n).step(i){|m| nums[m] = nil} if nums[i] end nums.compact end p eratosthenes(100)
309Sieve of Eratosthenes
14ruby
60c3t
import Data.Aeson import Network.HTTP.Base (urlEncode) import Network.HTTP.Conduit (simpleHttp) import Data.List (sortBy, groupBy) import Data.Function (on) import Data.Map (Map, toList) data Language = Language { name :: String, quantity :: Int } deriving (Show) instance FromJSON Language where parseJSON (Object p) = do categoryInfo <- p .:? "categoryinfo" let quantity = case categoryInfo of Just ob -> ob .: "size" Nothing -> return 0 name = p .: "title" Language <$> name <*> quantity data Report = Report { continue :: Maybe String, languages :: Map String Language } deriving (Show) instance FromJSON Report where parseJSON (Object p) = do querycontinue <- p .:? "query-continue" let continue = case querycontinue of Just ob -> fmap Just $ (ob .: "categorymembers") >>= ( .: "gcmcontinue") Nothing -> return Nothing languages = (p .: "query") >>= (.: "pages") Report <$> continue <*> languages showLanguage :: Int -> Bool -> Language -> IO () showLanguage rank tie (Language languageName languageQuantity) = let rankStr = show rank in putStrLn $ rankStr ++ "." ++ replicate (4 - length rankStr) ' ' ++ (if tie then " (tie)" else " ") ++ " " ++ drop 9 languageName ++ " - " ++ show languageQuantity showRanking :: (Int, [Language]) -> IO () showRanking (ranking, languages) = mapM_ (showLanguage ranking $ length languages > 1) languages showLanguages :: [Language] -> IO () showLanguages allLanguages = mapM_ showRanking $ zip [1..] $ groupBy ((==) `on` quantity) $ sortBy (flip compare `on` quantity) allLanguages queryStr = "http://rosettacode.org/mw/api.php?" ++ "format=json" ++ "&action=query" ++ "&generator=categorymembers" ++ "&gcmtitle=Category:Programming%20Languages" ++ "&gcmlimit=100" ++ "&prop=categoryinfo" runQuery :: [Language] -> String -> IO () runQuery ls query = do Just (Report continue langs) <- decode <$> simpleHttp query let accLanguages = ls ++ map snd (toList langs) case continue of Nothing -> showLanguages accLanguages Just continueStr -> do let continueQueryStr = queryStr ++ "&gcmcontinue=" ++ urlEncode continueStr runQuery accLanguages continueQueryStr main :: IO () main = runQuery [] queryStr
329Rosetta Code/Rank languages by popularity
8haskell
fehd1
package main import ( "fmt" "io/ioutil" "log" "os" "regexp" "strings" ) type header struct { start, end int lang string } type data struct { count int names *[]string } func newData(count int, name string) *data { return &data{count, &[]string{name}} } var bmap = make(map[string]*data) func add2bmap(lang, name string) { pd := bmap[lang] if pd != nil { pd.count++ *pd.names = append(*pd.names, name) } else { bmap[lang] = newData(1, name) } } func check(err error) { if err != nil { log.Fatal(err) } } func main() { expr := `==\s*{{\s*header\s*\|\s*([^\s\}]+)\s*}}\s*==` expr2 := fmt.Sprintf("<%s>.*?</%s>", "lang", "lang") r := regexp.MustCompile(expr) r2 := regexp.MustCompile(expr2) fileNames := []string{"example.txt", "example2.txt", "example3.txt"} for _, fileName := range fileNames { f, err := os.Open(fileName) check(err) b, err := ioutil.ReadAll(f) check(err) f.Close() text := string(b) fmt.Printf("Contents of%s:\n\n%s\n\n", fileName, text) m := r.FindAllStringIndex(text, -1) headers := make([]header, len(m)) if len(m) > 0 { for i, p := range m { headers[i] = header{p[0], p[1] - 1, ""} } m2 := r.FindAllStringSubmatch(text, -1) for i, s := range m2 { headers[i].lang = strings.ToLower(s[1]) } } last := len(headers) - 1 if last == -1 {
335Rosetta Code/Find bare lang tags
0go
9okmt
(function (strXPath) { var xr = document.evaluate( strXPath, document, null, 0, 0 ), oNode = xr.iterateNext(), lstTasks = []; while (oNode) { lstTasks.push(oNode.title); oNode = xr.iterateNext(); } return [ lstTasks.length + " items found in " + document.title, '' ].concat(lstTasks).join('\n') })( '
331Rosetta Code/Find unimplemented tasks
10javascript
utsvb
text = DATA.read slash_lang = '/lang' langs = %w(foo bar baz) for lang in langs text.gsub!(Regexp.new()) {} text.gsub!(Regexp.new(), ) end text.gsub!(/<code (.*?)>/, '<lang \1>') text.gsub!(/<\/code>/, ) print text __END__ Lorem ipsum <code foo>saepe audire</code> elaboraret ne quo, id equidem atomorum inciderint usu. <foo>In sit inermis deleniti percipit</foo>, ius ex tale civibus omittam. <barf>Vix ut doctus cetero invenire</barf>, his eu altera electram. Tota adhuc altera te sea, <code bar>soluta appetere ut mel</bar>. Quo quis graecis vivendo te, <baz>posse nullam lobortis ex usu</code>. Eam volumus perpetua constituto id, mea an omittam fierent vituperatoribus.
330Rosetta Code/Fix code tags
14ruby
ryngs
import java.util.List; import java.util.Random; import java.util.stream.Stream; import static java.util.stream.Collectors.toList; public class Rpg { private static final Random random = new Random(); public static int genAttribute() { return random.ints(1, 6 + 1)
328RPG attributes generator
9java
q7uxa
package main import ( "bytes" "encoding/xml" "fmt" "io" "io/ioutil" "net/http" "net/url" "strings" ) func req(u string, foundCm func(string)) string { resp, err := http.Get(u) if err != nil { fmt.Println(err)
332Rosetta Code/Count examples
0go
j9n7d
typedef struct stream_t stream_t, *stream; struct stream_t { int (*get)(stream); int (*put)(stream, int); }; typedef struct { int (*get)(stream); int (*put)(stream, int); char *string; int pos; } string_stream; typedef struct { int (*get)(stream); int (*put)(stream, int); FILE *fp; } file_stream; int sget(stream in) { int c; string_stream* s = (string_stream*) in; c = (unsigned char)(s->string[s->pos]); if (c == '\0') return -1; s->pos++; return c; } int sput(stream out, int c) { string_stream* s = (string_stream*) out; s->string[s->pos++] = (c == -1) ? '\0' : c; if (c == -1) s->pos = 0; return 0; } int file_put(stream out, int c) { file_stream *f = (file_stream*) out; return fputc(c, f->fp); } void output(stream out, unsigned char* buf, int len) { int i; out->put(out, 128 + len); for (i = 0; i < len; i++) out->put(out, buf[i]); } void encode(stream in, stream out) { unsigned char buf[256]; int len = 0, repeat = 0, end = 0, c; int (*get)(stream) = in->get; int (*put)(stream, int) = out->put; while (!end) { end = ((c = get(in)) == -1); if (!end) { buf[len++] = c; if (len <= 1) continue; } if (repeat) { if (buf[len - 1] != buf[len - 2]) repeat = 0; if (!repeat || len == 129 || end) { put(out, end ? len : len - 1); put(out, buf[0]); buf[0] = buf[len - 1]; len = 1; } } else { if (buf[len - 1] == buf[len - 2]) { repeat = 1; if (len > 2) { output(out, buf, len - 2); buf[0] = buf[1] = buf[len - 1]; len = 2; } continue; } if (len == 128 || end) { output(out, buf, len); len = 0; repeat = 0; } } } put(out, -1); } void decode(stream in, stream out) { int c, i, cnt; while (1) { c = in->get(in); if (c == -1) return; if (c > 128) { cnt = c - 128; for (i = 0; i < cnt; i++) out->put(out, in->get(in)); } else { cnt = c; c = in->get(in); for (i = 0; i < cnt; i++) out->put(out, c); } } } int main() { char buf[256]; string_stream str_in = { sget, 0, , 0}; string_stream str_out = { sget, sput, buf, 0 }; file_stream file = { 0, file_put, stdout }; encode((stream)&str_in, (stream)&str_out); decode((stream)&str_out, (stream)&file); return 0; }
336Run-length encoding
5c
xr3wu
import java.util.function.Predicate import java.util.regex.Matcher import java.util.regex.Pattern class FindBareTags { private static final Pattern TITLE_PATTERN = Pattern.compile("\"title\": \"([^\"]+)\"") private static final Pattern HEADER_PATTERN = Pattern.compile("==\\{\\{header\\|([^}]+)}}==") private static final Predicate<String> BARE_PREDICATE = Pattern.compile("<lang>").asPredicate() static String download(URL target) { URLConnection connection = target.openConnection() connection.setRequestProperty("User-Agent", "Firefox/2.0.0.4") InputStream is = connection.getInputStream() return is.getText("UTF-8") } static void main(String[] args) { URI titleUri = URI.create("http:
335Rosetta Code/Find bare lang tags
7groovy
zxgt5
(defn quadratic "Compute the roots of a quadratic in the form ax^2 + bx + c = 1. Returns any of nil, a float, or a vector." [a b c] (let [sq-d (Math/sqrt (- (* b b) (* 4 a c))) f #(/ (% b sq-d) (* 2 a))] (cond (neg? sq-d) nil (zero? sq-d) (f +) (pos? sq-d) [(f +) (f -)] :else nil)))
334Roots of a quadratic function
6clojure
6sj3q
import static java.lang.Math.*; import java.util.function.BiFunction; public class RungeKutta { static void runge(BiFunction<Double, Double, Double> yp_func, double[] t, double[] y, double dt) { for (int n = 0; n < t.length - 1; n++) { double dy1 = dt * yp_func.apply(t[n], y[n]); double dy2 = dt * yp_func.apply(t[n] + dt / 2.0, y[n] + dy1 / 2.0); double dy3 = dt * yp_func.apply(t[n] + dt / 2.0, y[n] + dy2 / 2.0); double dy4 = dt * yp_func.apply(t[n] + dt, y[n] + dy3); t[n + 1] = t[n] + dt; y[n + 1] = y[n] + (dy1 + 2.0 * (dy2 + dy3) + dy4) / 6.0; } } static double calc_err(double t, double calc) { double actual = pow(pow(t, 2.0) + 4.0, 2) / 16.0; return abs(actual - calc); } public static void main(String[] args) { double dt = 0.10; double[] t_arr = new double[101]; double[] y_arr = new double[101]; y_arr[0] = 1.0; runge((t, y) -> t * sqrt(y), t_arr, y_arr, dt); for (int i = 0; i < t_arr.length; i++) if (i % 10 == 0) System.out.printf("y(%.1f) =%.8f Error:%.6f%n", t_arr[i], y_arr[i], calc_err(t_arr[i], y_arr[i])); } }
326Runge-Kutta method
9java
n1kih
local requests = require('requests') local lang = arg[1] local function merge_tables(existing, from_req) local result = existing for _, v in ipairs(from_req) do result[v.title] = true end return result end local function get_task_list(category) local url = 'http://www.rosettacode.org/mw/api.php' local query = { action = 'query', list = 'categorymembers', cmtitle = string.format('Category:%s', category), cmlimit = 500, cmtype = 'page', format = 'json' } local categories = {} while true do local resp = assert(requests.get({ url, params = query }).json()) categories = merge_tables(categories, resp.query.categorymembers) if resp.continue then query.cmcontinue = resp.continue.cmcontinue else break end end return categories end local function get_open_tasks(lang) if not lang then error('Language missing!') end local all_tasks = get_task_list('Programming_Tasks') local lang_tasks = get_task_list(lang) local task_list = {} for t, _ in pairs(all_tasks) do if not lang_tasks[t] then table.insert(task_list, t) end end table.sort(task_list) return task_list end local open_tasks = get_open_tasks(lang) io.write(string.format('%s has%d unimplemented programming tasks: \n', lang, #open_tasks)) for _, t in ipairs(open_tasks) do io.write(string.format(' %s\n', t)) end
331Rosetta Code/Find unimplemented tasks
1lua
3qkzo
package jfkbits; import java.io.BufferedReader; import java.io.IOException; import java.io.Reader; import java.io.StreamTokenizer; import java.io.StringReader; import java.util.Iterator; public class LispTokenizer implements Iterator<Token> {
327S-expressions
9java
dakn9
extern crate regex; use std::io; use std::io::prelude::*; use regex::Regex; const LANGUAGES: &str = "_div abap actionscript actionscript3 ada apache applescript apt_sources asm asp autoit \ avisynth bash basic4gl bf blitzbasic bnf boo c c_mac caddcl cadlisp cfdg cfm cil cobol cpp \ cpp-qt csharp css d delphi diff dos dot eiffel email fortran freebasic genero gettext glsl \ gml gnuplot groovy haskell hq9plus html4strict idl ini inno intercal io java java5 \ javascript kixtart klonec klonecpp latex lisp lolcode lotusformulas lotusscript lscript lua \ m68k make matlab mirc modula3 mpasm mxml mysql nsis objc ocaml ocaml-brief oobas oracle11 \ oracle8 pascal per perl php php-brief pic16 pixelbender plsql povray powershell progress \ prolog providex python qbasic rails reg robots ruby rust sas scala scheme scilab sdlbasic \ smalltalk smarty sql tcl teraterm text thinbasic tsql typoscript vb vbnet verilog vhdl vim \ visualfoxpro visualprolog whitespace winbatch xml xorg_conf xpp z80"; fn fix_tags(languages: &[&str], text: &str) -> String { let mut replaced_text = text.to_owned(); for lang in languages.iter() { let bad_open = Regex::new(&format!("<{lang}>|<code {lang}>", lang = lang)).unwrap(); let bad_close = Regex::new(&format!("</{lang}>|</code>", lang = lang)).unwrap(); let open = format!("<lang {}>", lang); let close = "&lt;/lang&gt;"; replaced_text = bad_open.replace_all(&replaced_text, &open[..]).into_owned(); replaced_text = bad_close .replace_all(&replaced_text, &close[..]) .into_owned(); } replaced_text } fn main() { let stdin = io::stdin(); let mut buf = String::new(); stdin.lock().read_to_string(&mut buf).unwrap(); println!( "{}", fix_tags(&LANGUAGES.split_whitespace().collect::<Vec<_>>(), &buf) ); }
330Rosetta Code/Fix code tags
15rust
7mdrc
object FixCodeTags extends App { val rx =
330Rosetta Code/Fix code tags
16scala
klzhk
function roll() { const stats = { total: 0, rolls: [] } let count = 0; for(let i=0;i<=5;i++) { let d6s = []; for(let j=0;j<=3;j++) { d6s.push(Math.ceil(Math.random() * 6)) } d6s.sort().splice(0, 1); rollTotal = d6s.reduce((a, b) => a+b, 0); stats.rolls.push(rollTotal); stats.total += rollTotal; } return stats; } let rolledCharacter = roll(); while(rolledCharacter.total < 75 || rolledCharacter.rolls.filter(a => a >= 15).length < 2){ rolledCharacter = roll(); } console.log(`The 6 random numbers generated are: ${rolledCharacter.rolls.join(', ')} Their sum is ${rolledCharacter.total} and ${rolledCharacter.rolls.filter(a => a >= 15).length} of them are >= 15`);
328RPG attributes generator
10javascript
ip7ol
fn primes(n: usize) -> impl Iterator<Item = usize> { const START: usize = 2; if n < START { Vec::new() } else { let mut is_prime = vec![true; n + 1 - START]; let limit = (n as f64).sqrt() as usize; for i in START..limit + 1 { let mut it = is_prime[i - START..].iter_mut().step_by(i); if let Some(true) = it.next() { it.for_each(|x| *x = false); } } is_prime } .into_iter() .enumerate() .filter_map(|(e, b)| if b { Some(e + START) } else { None }) }
309Sieve of Eratosthenes
15rust
y8l68
import Network.Browser import Network.HTTP import Network.URI import Data.List import Data.Maybe import Text.XML.Light import Control.Arrow justifyR w = foldl ((.return).(++).tail) (replicate w ' ') showFormatted t n = t ++ ": " ++ justifyR 4 (show n) getRespons url = do rsp <- Network.Browser.browse $ do setAllowRedirects True setOutHandler $ const (return ()) request $ getRequest url return $ rspBody $ snd rsp getNumbOfExampels p = do let pg = intercalate "_" $ words p rsp <- getRespons $ "http://www.rosettacode.org/w/index.php?title=" ++ pg ++ "&action=raw" let taskPage = rsp countEx = length $ filter (=="=={{header|") $ takeWhile(not.null) $ unfoldr (Just. (take 11 &&& drop 1)) taskPage return countEx progTaskExamples = do rsp <- getRespons "http://www.rosettacode.org/w/api.php?action=query&list=categorymembers&cmtitle=Category:Programming_Tasks&cmlimit=500&format=xml" let xmls = onlyElems $ parseXML $ rsp tasks = concatMap (map (fromJust.findAttr (unqual "title")). filterElementsName (== unqual "cm")) xmls taskxx <- mapM getNumbOfExampels tasks let ns = taskxx tot = sum ns mapM_ putStrLn $ zipWith showFormatted tasks ns putStrLn $ ("Total: " ++) $ show tot
332Rosetta Code/Count examples
8haskell
obu8p
import java.util.List; import java.util.Arrays; List<String> haystack = Arrays.asList("Zig","Zag","Wally","Ronald","Bush","Krusty","Charlie","Bush","Bozo"); for (String needle : new String[]{"Washington","Bush"}) { int index = haystack.indexOf(needle); if (index < 0) System.out.println(needle + " is not in haystack"); else System.out.println(index + " " + needle); }
323Search a list
9java
feedv
import System.Environment import Network.HTTP import Text.Printf import Text.Regex.TDFA import Data.List import Data.Array import qualified Data.Map as Map splitByMatches :: String -> [MatchText String] -> [String] splitByMatches str matches = foldr splitHead [str] matches where splitHead match acc = before:after:(tail acc) where before = take (matchOffset).head$ acc after = drop (matchOffset + matchLen).head$ acc matchOffset = fst.snd.(!0)$ match matchLen = snd.snd.(!0)$ match countBareLangTags :: String -> Int countBareLangTags = matchCount (makeRegex "<lang[[:space:]]*>" :: Regex) countByLanguage :: String -> Map.Map String Int countByLanguage str = Map.fromList.filter ((>0).snd)$ zip langs counts where counts = map countBareLangTags.splitByMatches str$ allMatches langs = "":(map (fst.(!1)) allMatches) allMatches = matchAllText (makeRegex headerRegex :: Regex) str headerRegex = "==[[:space:]]*{{[[:space:]]*header[[:space:]]*\\|[[:space:]]*([^ }]*)[[:space:]]*}}[^=]*==" main = do args <- getArgs (contents, files) <- if length args == 0 then do content <- getContents return ([content],[""]) else if length args == 1 then do content <- readFile (head args) return ([content],[""]) else if (args !! 0) == "-w" then do contents <- mapM getPageContent.tail$ args return (contents, if length args > 2 then tail args else [""]) else do contents <- mapM readFile args return (contents, args) let tagsPerLang = map countByLanguage contents let tagsWithFiles = zipWith addFileToTags files tagsPerLang let combinedFiles = Map.unionsWith combine tagsWithFiles printBareTags combinedFiles where addFileToTags file = Map.map (flip (,) [file]) combine cur next = (fst cur + fst next, snd cur ++ snd next) printBareTags :: Map.Map String (Int,[String]) -> IO () printBareTags tags = do let numBare = Map.foldr ((+).fst) 0 tags printf "%d bare language tags:\n\n" numBare mapM_ (\(lang,(count,files)) -> printf "%d in%s%s\n" count (if lang == "" then "no language" else lang) (filesString files) ) (Map.toAscList tags) filesString :: [String] -> String filesString [] = "" filesString ("":rest) = filesString rest filesString files = " ("++listString files++")" where listString [file] = "[["++file++"]]" listString (file:files) = "[["++file++"]], "++listString files getPageContent :: String -> IO String getPageContent title = do response <- simpleHTTP.getRequest$ url getResponseBody response where url = "http://rosettacode.org/mw/index.php?action=raw&title="++title
335Rosetta Code/Find bare lang tags
8haskell
b2nk2
function rk4(y, x, dx, f) { var k1 = dx * f(x, y), k2 = dx * f(x + dx / 2.0, +y + k1 / 2.0), k3 = dx * f(x + dx / 2.0, +y + k2 / 2.0), k4 = dx * f(x + dx, +y + k3); return y + (k1 + 2.0 * k2 + 2.0 * k3 + k4) / 6.0; } function f(x, y) { return x * Math.sqrt(y); } function actual(x) { return (1/16) * (x*x+4)*(x*x+4); } var y = 1.0, x = 0.0, step = 0.1, steps = 0, maxSteps = 101, sampleEveryN = 10; while (steps < maxSteps) { if (steps%sampleEveryN === 0) { console.log("y(" + x + ") = \t" + y + "\t " + (actual(x) - y).toExponential()); } y = rk4(y, x, step, f);
326Runge-Kutta method
10javascript
3qez0
String.prototype.parseSexpr = function() { var t = this.match(/\s*("[^"]*"|\(|\)|"|[^\s()"]+)/g) for (var o, c=0, i=t.length-1; i>=0; i--) { var n, ti = t[i].trim() if (ti == '"') return else if (ti == '(') t[i]='[', c+=1 else if (ti == ')') t[i]=']', c-=1 else if ((n=+ti) == ti) t[i]=n else t[i] = '\'' + ti.replace('\'', '\\\'') + '\'' if (i>0 && ti!=']' && t[i-1].trim()!='(' ) t.splice(i,0, ',') if (!c) if (!o) o=true; else return } return c ? undefined : eval(t.join('')) } Array.prototype.toString = function() { var s=''; for (var i=0, e=this.length; i<e; i++) s+=(s?' ':'')+this[i] return '('+s+')' } Array.prototype.toPretty = function(s) { if (!s) s = '' var r = s + '(<br>' var s2 = s + Array(6).join('&nbsp;') for (var i=0, e=this.length; i<e; i+=1) { var ai = this[i] r += ai.constructor != Array ? s2+ai+'<br>' : ai.toPretty(s2) } return r + s + ')<br>' } var str = '((data "quoted data" 123 4.5)\n (data (!@# (4.5) "(more" "data)")))' document.write('text:<br>', str.replace(/\n/g,'<br>').replace(/ /g,'&nbsp;'), '<br><br>') var sexpr = str.parseSexpr() if (sexpr === undefined) document.write('Invalid s-expr!', '<br>') else document.write('s-expr:<br>', sexpr, '<br><br>', sexpr.constructor != Array ? '' : 'pretty print:<br>' + sexpr.toPretty())
327S-expressions
10javascript
6se38
var haystack = ['Zig', 'Zag', 'Wally', 'Ronald', 'Bush', 'Krusty', 'Charlie', 'Bush', 'Bozo'] var needles = ['Bush', 'Washington'] for (var i in needles) { var found = false; for (var j in haystack) { if (haystack[j] == needles[i]) { found = true; break; } } if (found) print(needles[i] + " appears at index " + j + " in the haystack"); else throw needles[i] + " does not appear in the haystack" }
323Search a list
10javascript
y006r
import kotlin.random.Random fun main() { while (true) { val values = List(6) { val rolls = generateSequence { 1 + Random.nextInt(6) }.take(4) rolls.sorted().take(3).sum() } val vsum = values.sum() val vcount = values.count { it >= 15 } if (vsum < 75 || vcount < 2) continue println("The 6 random numbers generated are: $values") println("Their sum is $vsum and $vcount of them are >= 15") break } }
328RPG attributes generator
11kotlin
1u9pd
import java.net.URL; import java.net.URLConnection; import java.io.*; import java.util.*; public class GetRCLanguages {
329Rosetta Code/Rank languages by popularity
9java
0h5se
import java.net.URI; import java.net.http.HttpClient; import java.net.http.HttpRequest; import java.net.http.HttpResponse; import java.util.HashMap; import java.util.Map; import java.util.concurrent.atomic.AtomicReference; import java.util.function.Predicate; import java.util.regex.Pattern; import java.util.stream.Collectors; public class FindBareTags { private static final String BASE = "http:
335Rosetta Code/Find bare lang tags
9java
g6q4m
null
326Runge-Kutta method
11kotlin
sjgq7
use LWP::UserAgent; my $ua = LWP::UserAgent->new; $ua->agent(''); sub enc { join '', map {sprintf '%%%02x', ord} split //, shift } sub get { $ua->request( HTTP::Request->new( GET => shift))->content } sub tasks { my($category) = shift; my $fmt = 'http://www.rosettacode.org/mw/api.php?' . 'action=query&generator=categorymembers&gcmtitle=Category:%s&gcmlimit=500&format=json&rawcontinue='; my @tasks; my $json = get(sprintf $fmt, $category); while (1) { push @tasks, $json =~ /"title":"(.+?)"\}/g; $json =~ /"gcmcontinue":"(.+?)"\}/ or last; $json = get(sprintf $fmt . '&gcmcontinue=%s', $category, enc $1); } @tasks; } my %language = map {$_, 1} tasks shift || 'perl'; $language{$_} or print "$_\n" foreach tasks('Programming_Tasks'), tasks('Draft_Programming_Tasks');
331Rosetta Code/Find unimplemented tasks
2perl
b2zk4
null
327S-expressions
11kotlin
0hgsf
import java.util.ArrayList; import ScreenScrape; public class CountProgramExamples { private static final String baseURL = "http:
332Rosetta Code/Count examples
9java
wgmej
(defn compress [s] (->> (partition-by identity s) (mapcat (juxt count first)) (apply str))) (defn extract [s] (->> (re-seq #"(\d+)([A-Z])" s) (mapcat (fn [[_ n ch]] (repeat (Integer/parseInt n) ch))) (apply str)))
336Run-length encoding
6clojure
obc8j
import java.net.URI import java.net.http.HttpClient import java.net.http.HttpRequest import java.net.http.HttpResponse import java.util.regex.Pattern import java.util.stream.Collectors const val BASE = "http:
335Rosetta Code/Find bare lang tags
11kotlin
2d1li
lpeg = require 'lpeg'
327S-expressions
1lua
8kr0e
import scala.annotation.tailrec import scala.collection.parallel.mutable import scala.compat.Platform object GenuineEratosthenesSieve extends App { def sieveOfEratosthenes(limit: Int) = { val (primes: mutable.ParSet[Int], sqrtLimit) = (mutable.ParSet.empty ++ (2 to limit), math.sqrt(limit).toInt) @tailrec def prim(candidate: Int): Unit = { if (candidate <= sqrtLimit) { if (primes contains candidate) primes --= candidate * candidate to limit by candidate prim(candidate + 1) } } prim(2) primes }
309Sieve of Eratosthenes
16scala
cnu93
null
323Search a list
11kotlin
8kk0q
import java.net.URL import java.io.* object Popularity { fun ofLanguages(): List<String> { val languages = mutableListOf<String>() var gcm = "" do { val path = url + (if (gcm == "") "" else "&gcmcontinue=" + gcm) + "&prop=categoryinfo" + "&format=txt" try { val rc = URL(path).openConnection()
329Rosetta Code/Rank languages by popularity
11kotlin
e4ca4
double f(double x) { return x*x*x-3.0*x*x +2.0*x; } double secant( double xA, double xB, double(*f)(double) ) { double e = 1.0e-12; double fA, fB; double d; int i; int limit = 50; fA=(*f)(xA); for (i=0; i<limit; i++) { fB=(*f)(xB); d = (xB - xA) / (fB - fA) * fB; if (fabs(d) < e) break; xA = xB; fA = fB; xB -= d; } if (i==limit) { printf(, xA,xB); return -99.0; } return xB; } int main(int argc, char *argv[]) { double step = 1.0e-2; double e = 1.0e-12; double x = -1.032; double xx, value; int s = (f(x)> 0.0); while (x < 3.0) { value = f(x); if (fabs(value) < e) { printf(, x); s = (f(x+.0001)>0.0); } else if ((value > 0.0) != s) { xx = secant(x-step, x,&f); if (xx != -99.0) printf(, xx); else printf(, x); s = (f(x+.0001)>0.0); } x += step; } return 0; }
337Roots of a function
5c
y0r6f
package main import ( "fmt" "math" ) func qr(a, b, c float64) ([]float64, []complex128) { d := b*b-4*a*c switch { case d == 0:
334Roots of a quadratic function
0go
7m8r2
from operator import attrgetter from typing import Iterator import mwclient URL = 'www.rosettacode.org' API_PATH = '/mw/' def unimplemented_tasks(language: str, *, url: str, api_path: str) -> Iterator[str]: site = mwclient.Site(url, path=api_path) all_tasks = site.categories['Programming Tasks'] language_tasks = site.categories[language] name = attrgetter('name') all_tasks_names = map(name, all_tasks) language_tasks_names = set(map(name, language_tasks)) for task in all_tasks_names: if task not in language_tasks_names: yield task if __name__ == '__main__': tasks = unimplemented_tasks('Python', url=URL, api_path=API_PATH) print(*tasks, sep='\n')
331Rosetta Code/Find unimplemented tasks
3python
pv3bm