code
stringlengths
1
46.1k
label
class label
1.18k classes
domain_label
class label
21 classes
index
stringlengths
4
5
haystack = %w(Zig Zag Wally Ronald Bush Krusty Charlie Bush Bozo) %w(Bush Washington).each do |needle| if (i = haystack.index(needle)) puts else raise end end
323Search a list
14ruby
7mmri
f = lambda x: x * x * x - 3 * x * x + 2 * x step = 0.001 start = -1 stop = 3 sign = f(start) > 0 x = start while x <= stop: value = f(x) if value == 0: print , x elif (value > 0) != sign: print , x sign = value > 0 x += step
337Roots of a function
3python
2dblz
use 5.012; use warnings; use utf8; use open qw(:encoding(utf-8) :std); use Getopt::Long; package Game { use List::Util qw(shuffle first); my $turns = 0; my %human_choice = ( rock => 0, paper => 0, scissors => 0, ); my %comp_choice = ( rock => 0, paper => 0, scissors => 0, ); my %what_beats = ( rock => 'paper', paper => 'scissors', scissors => 'rock', ); my $comp_wins = 0; my $human_wins = 0; my $draws = 0; sub save_human_choice { my $ch = lc pop; if ( exists $human_choice{ $ch } ) { ++$human_choice{ $ch }; } else { die __PACKAGE__ . ":: wrong choice: '$ch'"; } } sub get_comp_choice { my @keys = shuffle keys %human_choice; my $ch; my ( $prob, $rand ) = ( 0, rand ); $ch = ( first { $rand <= ( $prob += ( $human_choice{ $_ } / $turns ) ) } @keys ) if $turns > 0; $ch //= $keys[0]; $ch = $what_beats{ $ch }; ++$comp_choice{ $ch }; return $ch; } sub make_turn { my ( $comp_ch, $human_ch ) = ( pop(), pop() ); ++$turns; if ( $what_beats{ $human_ch } eq $comp_ch ) { ++$comp_wins; return 'I win!'; } elsif ( $what_beats{ $comp_ch } eq $human_ch ) { ++$human_wins; return 'You win!'; } else { ++$draws; return 'Draw!'; } } sub get_final_report { my $report = "You chose:\n" . " rock = $human_choice{rock} times,\n" . " paper = $human_choice{paper} times,\n" . " scissors = $human_choice{scissors} times,\n" . "I chose:\n" . " rock = $comp_choice{rock} times,\n" . " paper = $comp_choice{paper} times,\n" . " scissors = $comp_choice{scissors} times,\n" . "Turns: $turns\n" . "I won: $comp_wins, you won: $human_wins, draws: $draws\n"; return $report; } } sub main { GetOptions( 'quiet' => \my $quiet ); greet() if !$quiet; while (1) { print_next_line() if !$quiet; my $input = get_input(); last unless $input; if ( $input eq 'error' ) { print "I don't understand!\n" if !$quiet; redo; } my $comp_choice = Game::get_comp_choice(); Game::save_human_choice($input); my $result = Game::make_turn( $input, $comp_choice ); describe_turn_result( $input, $comp_choice, $result ) if !$quiet; } print Game::get_final_report(); } sub greet { print "Welcome to the Rock-Paper-Scissors game!\n" . "Choose 'rock', 'paper' or 'scissors'\n" . "Enter empty line or 'quit' to quit\n"; } sub print_next_line { print 'Your choice: '; } sub get_input { my $input = <>; print "\n" and return if !$input; chomp $input; return if !$input or $input =~ m/\A \s* q/xi; return ( $input =~ m/\A \s* r/xi ) ? 'rock' : ( $input =~ m/\A \s* p/xi ) ? 'paper' : ( $input =~ m/\A \s* s/xi ) ? 'scissors' : 'error'; } sub describe_turn_result { my ( $human_ch, $comp_ch, $result ) = @_; print "You chose \u$human_ch, I chose \u$comp_ch. $result\n"; } main();
339Rock-paper-scissors
2perl
ryegd
f <- function(x) x^3 -3*x^2 + 2*x findroots <- function(f, begin, end, tol = 1e-20, step = 0.001) { se <- ifelse(sign(f(begin))==0, 1, sign(f(begin))) x <- begin while ( x <= end ) { v <- f(x) if ( abs(v) < tol ) { print(sprintf("root at%f", x)) } else if ( ifelse(sign(v)==0, 1, sign(v))!= se ) { print(sprintf("root near%f", x)) } se <- ifelse( sign(v) == 0 , 1, sign(v)) x <- x + step } } findroots(f, -1, 3)
337Roots of a function
13r
m87y4
fn main() { let haystack=vec!["Zig", "Zag", "Wally", "Ronald", "Bush", "Krusty", "Charlie", "Bush", "Boz", "Zag"]; println!("First occurence of 'Bush' at {:?}",haystack.iter().position(|s| *s=="Bush")); println!("Last occurence of 'Bush' at {:?}",haystack.iter().rposition(|s| *s=="Bush")); println!("First occurence of 'Rob' at {:?}",haystack.iter().position(|s| *s=="Rob")); }
323Search a list
15rust
j9972
import java.io.*; public class Rot13 { public static void main(String[] args) throws IOException { if (args.length >= 1) { for (String file : args) { try (InputStream in = new BufferedInputStream(new FileInputStream(file))) { rot13(in, System.out); } } } else { rot13(System.in, System.out); } } private static void rot13(InputStream in, OutputStream out) throws IOException { int ch; while ((ch = in.read()) != -1) { out.write(rot13((char) ch)); } } private static char rot13(char ch) { if (ch >= 'A' && ch <= 'Z') { return (char) (((ch - 'A') + 13) % 26 + 'A'); } if (ch >= 'a' && ch <= 'z') { return (char) (((ch - 'a') + 13) % 26 + 'a'); } return ch; } }
338Rot-13
9java
twvf9
<?php echo . . ; echo ; echo ; $player = strtoupper( $_GET[] ); $wins = [ 'ROCK' => 'SCISSORS', 'PAPER' => 'ROCK', 'SCISSORS' => 'PAPER' ]; $a_i = array_rand($wins); echo ; echo . color:blue\ . $player . ; echo ; echo . . color:red\ . $a_i . ; $results = ; if ($player == $a_i){ $results = ; } else if($wins[$a_i] == $player ){ $results = ; } else { $results = ; } echo . $results; ?>
339Rock-paper-scissors
12php
dacn8
function rot13(c) { return c.replace(/([a-m])|([n-z])/ig, function($0,$1,$2) { return String.fromCharCode($1 ? $1.charCodeAt(0) + 13 : $2 ? $2.charCodeAt(0) - 13 : 0) || $0; }); } rot13("ABJURER nowhere")
338Rot-13
10javascript
m8ryv
def findNeedles(needle: String, haystack: Seq[String]) = haystack.zipWithIndex.filter(_._1 == needle).map(_._2) def firstNeedle(needle: String, haystack: Seq[String]) = findNeedles(needle, haystack).head def lastNeedle(needle: String, haystack: Seq[String]) = findNeedles(needle, haystack).last
323Search a list
16scala
b22k6
package main import ( "errors" "fmt" ) var m = map[rune]int{ 'I': 1, 'V': 5, 'X': 10, 'L': 50, 'C': 100, 'D': 500, 'M': 1000, } func parseRoman(s string) (r int, err error) { if s == "" { return 0, errors.New("Empty string") } is := []rune(s)
340Roman numerals/Decode
0go
ipyog
def sign(x) x <=> 0 end def find_roots(f, range, step=0.001) sign = sign(f[range.begin]) range.step(step) do |x| value = f[x] if value == 0 puts elsif sign(value) == -sign puts end sign = sign(value) end end f = lambda { |x| x**3 - 3*x**2 + 2*x } find_roots(f, -1..3)
337Roots of a function
14ruby
ut1vz
enum RomanDigits { I(1), V(5), X(10), L(50), C(100), D(500), M(1000); private magnitude; private RomanDigits(magnitude) { this.magnitude = magnitude } String toString() { super.toString() + "=${magnitude}" } static BigInteger parse(String numeral) { assert numeral != null && !numeral.empty def digits = (numeral as List).collect { RomanDigits.valueOf(it) } def L = digits.size() (0..<L).inject(0g) { total, i -> def sign = (i == L - 1 || digits[i] >= digits[i+1]) ? 1: -1 total + sign * digits[i].magnitude } } }
340Roman numerals/Decode
7groovy
q7fxp
null
337Roots of a function
15rust
5zauq
module Main where decodeDigit :: Char -> Int decodeDigit 'I' = 1 decodeDigit 'V' = 5 decodeDigit 'X' = 10 decodeDigit 'L' = 50 decodeDigit 'C' = 100 decodeDigit 'D' = 500 decodeDigit 'M' = 1000 decodeDigit _ = error "invalid digit" decode roman = decodeRoman startValue startValue rest where (first:rest) = reverse roman startValue = decodeDigit first decodeRoman :: Int -> Int -> [Char] -> Int decodeRoman lastSum _ [] = lastSum decodeRoman lastSum lastValue (digit:rest) = decodeRoman updatedSum digitValue rest where digitValue = decodeDigit digit updatedSum = (if digitValue < lastValue then (-) else (+)) lastSum digitValue main = do test "MCMXC" 1990 test "MMVIII" 2008 test "MDCLXVI" 1666 test roman expected = putStrLn (roman ++ " = " ++ (show (arabic)) ++ remark) where arabic = decode roman remark = " (" ++ (if arabic == expected then "PASS" else ("FAIL, expected " ++ (show expected))) ++ ")"
340Roman numerals/Decode
8haskell
vfh2k
object Roots extends App { val poly = (x: Double) => x * x * x - 3 * x * x + 2 * x private def printRoots(f: Double => Double, lowerBound: Double, upperBound: Double, step: Double): Unit = { val y = f(lowerBound) var (ox, oy, os) = (lowerBound, y, math.signum(y)) for (x <- lowerBound to upperBound by step) { val y = f(x) val s = math.signum(y) if (s == 0) println(x) else if (s != os) println(s"~${x - (x - ox) * (y / (y - oy))}") ox = x oy = y os = s } } printRoots(poly, -1.0, 4, 0.002) }
337Roots of a function
16scala
ryxgn
from random import choice rules = {'rock': 'paper', 'scissors': 'rock', 'paper': 'scissors'} previous = ['rock', 'paper', 'scissors'] while True: human = input('\nchoose your weapon: ') computer = rules[choice(previous)] if human in ('quit', 'exit'): break elif human in rules: previous.append(human) print('the computer played', computer, end='; ') if rules[computer] == human: print('yay you win!') elif rules[human] == computer: print('the computer beat you...:(') else: print() else: print()
339Rock-paper-scissors
3python
7mwrm
sub encode { shift =~ s/(.)\1*/length($&).$1/grse; } sub decode { shift =~ s/(\d+)(.)/$2 x $1/grse; }
336Run-length encoding
2perl
8k90w
import java.io.* fun String.rot13() = map { when { it.isUpperCase() -> { val x = it + 13; if (x > 'Z') x - 26 else x } it.isLowerCase() -> { val x = it + 13; if (x > 'z') x - 26 else x } else -> it } }.toCharArray() fun InputStreamReader.println() = try { BufferedReader(this).forEachLine { println(it.rot13()) } } catch (e: IOException) { e.printStackTrace() } fun main(args: Array<String>) { if (args.any()) args.forEach { FileReader(it).println() } else InputStreamReader(System.`in`).println() }
338Rot-13
11kotlin
obm8z
play <- function() { bias <- c(r = 1, p = 1, s = 1) repeat { playerChoice <- readline(prompt = "Rock (r), Paper (p), Scissors (s), or Quit (q)? ") if(playerChoice == "q") break rps <- c(Rock = "r", Paper = "p", Scissors = "s") if(!playerChoice %in% rps) next compChoice <- sample(rps, 1, prob = bias / sum(bias)) cat("I choose", names(compChoice), "\n", c("We draw!", "I win!", "I lose!")[1 + (which(compChoice == rps) - which(playerChoice == rps)) %% 3], "\n") bias <- bias + (playerChoice == c("s", "r", "p")) } } play()
339Rock-paper-scissors
13r
5zpuy
let haystack = ["Zig","Zag","Wally","Ronald","Bush","Krusty","Charlie","Bush","Bozo"] for needle in ["Washington","Bush"] { if let index = haystack.indexOf(needle) { print("\(index) \(needle)") } else { print("\(needle) is not in haystack") } }
323Search a list
17swift
ryygg
<?php function encode($str) { return preg_replace_callback('/(.)\1*/', function ($match) { return strlen($match[0]) . $match[1]; }, $str); } function decode($str) { return preg_replace_callback('/(\d+)(\D)/', function($match) { return str_repeat($match[2], $match[1]); }, $str); } echo encode('WWWWWWWWWWWWBWWWWWWWWWWWWBBBWWWWWWWWWWWWWWWWWWWWWWWWBWWWWWWWWWWWWWW'), PHP_EOL; echo decode('12W1B12W3B24W1B14W'), PHP_EOL; ?>
336Run-length encoding
12php
43w5n
public class Roman { private static int decodeSingle(char letter) { switch(letter) { case 'M': return 1000; case 'D': return 500; case 'C': return 100; case 'L': return 50; case 'X': return 10; case 'V': return 5; case 'I': return 1; default: return 0; } } public static int decode(String roman) { int result = 0; String uRoman = roman.toUpperCase();
340Roman numerals/Decode
9java
y056g
package main import "fmt" var ( m0 = []string{"", "I", "II", "III", "IV", "V", "VI", "VII", "VIII", "IX"} m1 = []string{"", "X", "XX", "XXX", "XL", "L", "LX", "LXX", "LXXX", "XC"} m2 = []string{"", "C", "CC", "CCC", "CD", "D", "DC", "DCC", "DCCC", "CM"} m3 = []string{"", "M", "MM", "MMM", "IV", "V", "VI", "VII", "VIII", "IX"} m4 = []string{"", "X", "XX", "XXX", "XL", "L", "LX", "LXX", "LXXX", "XC"} m5 = []string{"", "C", "CC", "CCC", "CD", "D", "DC", "DCC", "DCCC", "CM"} m6 = []string{"", "M", "MM", "MMM"} ) func formatRoman(n int) (string, bool) { if n < 1 || n >= 4e6 { return "", false }
341Roman numerals/Encode
0go
q7dxz
var Roman = { Values: [['CM', 900], ['CD', 400], ['XC', 90], ['XL', 40], ['IV', 4], ['IX', 9], ['V', 5], ['X', 10], ['L', 50], ['C', 100], ['M', 1000], ['I', 1], ['D', 500]], UnmappedStr : 'Q', parse: function(str) { var result = 0 for (var i=0; i<Roman.Values.length; ++i) { var pair = Roman.Values[i] var key = pair[0] var value = pair[1] var regex = RegExp(key) while (str.match(regex)) { result += value str = str.replace(regex, Roman.UnmappedStr) } } return result } } var test_data = ['MCMXC', 'MDCLXVI', 'MMVIII'] for (var i=0; i<test_data.length; ++i) { var test_datum = test_data[i] print(test_datum + ": " + Roman.parse(test_datum)) }
340Roman numerals/Decode
10javascript
2djlr
symbols = [ 1:'I', 4:'IV', 5:'V', 9:'IX', 10:'X', 40:'XL', 50:'L', 90:'XC', 100:'C', 400:'CD', 500:'D', 900:'CM', 1000:'M' ] def roman(arabic) { def result = "" symbols.keySet().sort().reverse().each { while (arabic >= it) { arabic-=it result+=symbols[it] } } return result } assert roman(1) == 'I' assert roman(2) == 'II' assert roman(4) == 'IV' assert roman(8) == 'VIII' assert roman(16) == 'XVI' assert roman(32) == 'XXXII' assert roman(25) == 'XXV' assert roman(64) == 'LXIV' assert roman(128) == 'CXXVIII' assert roman(256) == 'CCLVI' assert roman(512) == 'DXII' assert roman(954) == 'CMLIV' assert roman(1024) == 'MXXIV' assert roman(1666) == 'MDCLXVI' assert roman(1990) == 'MCMXC' assert roman(2008) == 'MMVIII'
341Roman numerals/Encode
7groovy
1u0p6
digit :: Char -> Char -> Char -> Integer -> String digit x y z k = [[x], [x, x], [x, x, x], [x, y], [y], [y, x], [y, x, x], [y, x, x, x], [x, z]] !! (fromInteger k - 1) toRoman :: Integer -> String toRoman 0 = "" toRoman x | x < 0 = error "Negative roman numeral" toRoman x | x >= 1000 = 'M': toRoman (x - 1000) toRoman x | x >= 100 = digit 'C' 'D' 'M' q ++ toRoman r where (q, r) = x `divMod` 100 toRoman x | x >= 10 = digit 'X' 'L' 'C' q ++ toRoman r where (q, r) = x `divMod` 10 toRoman x = digit 'I' 'V' 'X' x main :: IO () main = print $ toRoman <$> [1999, 25, 944]
341Roman numerals/Encode
8haskell
m85yf
package main import ( "fmt" "rcu" "strconv" ) func contains(a []int, n int) bool { for _, e := range a { if e == n { return true } } return false } func main() { for b := 2; b <= 36; b++ { if rcu.IsPrime(b) { continue } count := 0 var rhonda []int for n := 1; count < 15; n++ { digits := rcu.Digits(n, b) if !contains(digits, 0) { var anyEven = false for _, d := range digits { if d%2 == 0 { anyEven = true break } } if b != 10 || (contains(digits, 5) && anyEven) { calc1 := 1 for _, d := range digits { calc1 *= d } calc2 := b * rcu.SumInts(rcu.PrimeFactors(n)) if calc1 == calc2 { rhonda = append(rhonda, n) count++ } } } } if len(rhonda) > 0 { fmt.Printf("\nFirst 15 Rhonda numbers in base%d:\n", b) rhonda2 := make([]string, len(rhonda)) counts2 := make([]int, len(rhonda)) for i, r := range rhonda { rhonda2[i] = fmt.Sprintf("%d", r) counts2[i] = len(rhonda2[i]) } rhonda3 := make([]string, len(rhonda)) counts3 := make([]int, len(rhonda)) for i, r := range rhonda { rhonda3[i] = strconv.FormatInt(int64(r), b) counts3[i] = len(rhonda3[i]) } maxLen2 := rcu.MaxInts(counts2) maxLen3 := rcu.MaxInts(counts3) maxLen := maxLen2 if maxLen3 > maxLen { maxLen = maxLen3 } maxLen++ fmt.Printf("In base 10:%*s\n", maxLen, rhonda2) fmt.Printf("In base%-2d:%*s\n", b, maxLen, rhonda3) } } }
342Rhonda numbers
0go
rypgm
class RockPaperScissorsGame CHOICES = %w[rock paper scissors quit] BEATS = { 'rock' => 'paper', 'paper' => 'scissors', 'scissors' => 'rock', } def initialize() @plays = { 'rock' => 1, 'paper' => 1, 'scissors' => 1, } @score = [0, 0, 0] play end def humanPlay loop do print answer = STDIN.gets.strip.downcase next if answer.empty? idx = CHOICES.find_index {|choice| choice.match(/^ return CHOICES[idx] if idx puts end end def computerPlay total = @plays.values.reduce(:+) r = rand(total) + 1 sum = 0 CHOICES.each do |choice| sum += @plays[choice] return BEATS[choice] if r <= sum end end def play loop do h = humanPlay break if h == c = computerPlay print @plays[h] += 1 if h == c puts @score[2] += 1 elsif h == BEATS[c] puts @score[0] += 1 else puts @score[1] += 1 end puts % [*@score] end @plays.each_key{|k| @plays[k] -= 1} puts end end RockPaperScissorsGame.new
339Rock-paper-scissors
14ruby
hcqjx
void searchChatLogs(char* searchString){ char* baseURL = ; time_t t; struct tm* currentDate; char dateString[30],dateStringFile[30],lineData[MAX_LEN],targetURL[100]; int i,flag; FILE *fp; CURL *curl; CURLcode res; time(&t); currentDate = localtime(&t); strftime(dateString, 30, , currentDate); printf(,dateString); if((curl = curl_easy_init())!=NULL){ for(i=0;i<=10;i++){ flag = 0; sprintf(targetURL,,baseURL,dateString); strcpy(dateStringFile,dateString); printf(,targetURL); if((fp = fopen(,))==0){ printf(,targetURL); } else{ curl_easy_setopt(curl, CURLOPT_URL, targetURL); curl_easy_setopt(curl, CURLOPT_WRITEDATA, fp); res = curl_easy_perform(curl); if(res == CURLE_OK){ while(fgets(lineData,MAX_LEN,fp)!=NULL){ if(strstr(lineData,searchString)!=NULL){ flag = 1; fputs(lineData,stdout); } } if(flag==0) printf(); } fflush(fp); fclose(fp); } currentDate->tm_mday--; mktime(currentDate); strftime(dateString, 30, , currentDate); } curl_easy_cleanup(curl); } } int main(int argC,char* argV[]) { if(argC!=2) printf( if it contains spaces>",argV[0]); else searchChatLogs(argV[1]); return 0; }
343Retrieve and search chat history
5c
j9170
public class RhondaNumbers { public static void main(String[] args) { final int limit = 15; for (int base = 2; base <= 36; ++base) { if (isPrime(base)) continue; System.out.printf("First%d Rhonda numbers to base%d:\n", limit, base); int numbers[] = new int[limit]; for (int n = 1, count = 0; count < limit; ++n) { if (isRhonda(base, n)) numbers[count++] = n; } System.out.printf("In base 10:"); for (int i = 0; i < limit; ++i) System.out.printf("%d", numbers[i]); System.out.printf("\nIn base%d:", base); for (int i = 0; i < limit; ++i) System.out.printf("%s", Integer.toString(numbers[i], base)); System.out.printf("\n\n"); } } private static int digitProduct(int base, int n) { int product = 1; for (; n != 0; n /= base) product *= n % base; return product; } private static int primeFactorSum(int n) { int sum = 0; for (; (n & 1) == 0; n >>= 1) sum += 2; for (int p = 3; p * p <= n; p += 2) for (; n % p == 0; n /= p) sum += p; if (n > 1) sum += n; return sum; } private static boolean isPrime(int n) { if (n < 2) return false; if (n % 2 == 0) return n == 2; if (n % 3 == 0) return n == 3; for (int p = 5; p * p <= n; p += 4) { if (n % p == 0) return false; p += 2; if (n % p == 0) return false; } return true; } private static boolean isRhonda(int base, int n) { return digitProduct(base, n) == base * primeFactorSum(n); } }
342Rhonda numbers
9java
a501y
null
340Roman numerals/Decode
11kotlin
fecdo
extern crate rand; #[macro_use] extern crate rand_derive; use std::io; use rand::Rng; use Choice::*; #[derive(PartialEq, Clone, Copy, Rand, Debug)] enum Choice { Rock, Paper, Scissors, } fn beats(c1: Choice, c2: Choice) -> bool { (c1 == Rock && c2 == Scissors) || (c1 == Scissors && c2 == Paper) || (c1 == Paper && c2 == Rock) } fn ai_move<R: Rng>(rng: &mut R, v: [usize; 3]) -> Choice {
339Rock-paper-scissors
15rust
klsh5
use strict; use warnings; use feature 'say'; use ntheory qw<is_prime factor vecsum vecprod todigitstring todigits>; sub rhonda { my($b, $cnt) = @_; my(@r,$n); while (++$n) { push @r, $n if ($b * vecsum factor($n)) == vecprod todigits($n,$b); return @r if $cnt == @r; } } for my $b (grep { ! is_prime $_ } 2..36) { my @Rb = map { todigitstring($_,$b) } my @R = rhonda($b, 15); say <<~EOT; First 15 Rhonda numbers to base $b: In base $b: @Rb In base 10: @R EOT }
342Rhonda numbers
2perl
zxctb
object RockPaperScissors extends App { import scala.collection.mutable.LinkedHashMap def play(beats: LinkedHashMap[Symbol,Set[Symbol]], played: scala.collection.Map[Symbol,Int]) { val h = readLine(s"""Your move (${beats.keys mkString ", "}): """) match { case null => println; return case "" => return case s => Symbol(s) } beats get h match { case Some(losers) => def weighted(todo: Iterator[(Symbol,Int)], rand: Int, accum: Int = 0): Symbol = todo.next match { case (s, i) if rand <= (accum + i) => s case (_, i) => weighted(todo, rand, accum + i) } val c = weighted(played.toIterator, 1 + scala.util.Random.nextInt(played.values.sum)) match {
339Rock-paper-scissors
16scala
1uopf
package main import ( "fmt" "io/ioutil" "log" "net/http" "os" "strings" "time" ) func get(url string) (res string, err error) { resp, err := http.Get(url) if err != nil { return "", err } buf, err := ioutil.ReadAll(resp.Body) if err != nil { return "", err } return string(buf), nil } func grep(needle string, haystack string) (res []string) { for _, line := range strings.Split(haystack, "\n") { if strings.Contains(line, needle) { res = append(res, line) } } return res } func genUrl(i int, loc *time.Location) string { date := time.Now().In(loc).AddDate(0, 0, i) return date.Format("http:
343Retrieve and search chat history
0go
feyd0
function rot13(s) local a = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz" local b = "NOPQRSTUVWXYZABCDEFGHIJKLMnopqrstuvwxyzabcdefghijklm" return (s:gsub("%a", function(c) return b:sub(a:find(c)) end)) end
338Rot-13
1lua
ip9ot
def encode(input_string): count = 1 prev = None lst = [] for character in input_string: if character != prev: if prev: entry = (prev, count) lst.append(entry) count = 1 prev = character else: count += 1 else: try: entry = (character, count) lst.append(entry) return (lst, 0) except Exception as e: print(.format(e=e)) return (e, 1) def decode(lst): q = [] for character, count in lst: q.append(character * count) return ''.join(q) value = encode() if value[1] == 0: print(.format(value[0])) decode(value[0])
336Run-length encoding
3python
obc81
use strict; use warnings; use Time::Piece; use IO::Socket::INET; use HTTP::Tiny; use feature 'say'; my $needle = shift @ARGV // ''; my @haystack = (); my $page = ''; my $begin = Time::Piece->new - 10 * Time::Piece::ONE_DAY; say " Executed at: ", Time::Piece->new; say "Begin searching from: $begin"; for (my $date = $begin ; Time::Piece->new > $date ; $date += Time::Piece::ONE_DAY) { $page .= HTTP::Tiny->new()->get( 'http://tclers.tk/conferences/tcl/'.$date->strftime('%Y-%m-%d').'.tcl')->{content}; } my @lines = split /\n/, $page; for (@lines) { push @haystack, $_ if substr($_, 0, 13) =~ m/^m \d\d\d\d-\d\d-\d\dT/ } say "First and last lines of the haystack:"; say $haystack[0] and say $haystack[-1]; say "Needle: ", $needle; say '-' x 79; for (@haystack) { say $_ if (index($_, $needle) != -1) }
343Retrieve and search chat history
2perl
pvxb0
null
342Rhonda numbers
15rust
m8uya
func digitProduct(base: Int, num: Int) -> Int { var product = 1 var n = num while n!= 0 { product *= n% base n /= base } return product } func primeFactorSum(_ num: Int) -> Int { var sum = 0 var n = num while (n & 1) == 0 { sum += 2 n >>= 1 } var p = 3 while p * p <= n { while n% p == 0 { sum += p n /= p } p += 2 } if n > 1 { sum += n } return sum } func isPrime(_ n: Int) -> Bool { if n < 2 { return false } if n% 2 == 0 { return n == 2 } if n% 3 == 0 { return n == 3 } var p = 5 while p * p <= n { if n% p == 0 { return false } p += 2 if n% p == 0 { return false } p += 4 } return true } func isRhonda(base: Int, num: Int) -> Bool { return digitProduct(base: base, num: num) == base * primeFactorSum(num) } let limit = 15 for base in 2...36 { if isPrime(base) { continue } print("First \(limit) Rhonda numbers to base \(base):") let numbers = Array((1...).lazy.filter{ isRhonda(base: base, num: $0) }.prefix(limit)) print("In base 10:", terminator: "") for n in numbers { print(" \(n)", terminator: "") } print("\nIn base \(base):", terminator: "") for n in numbers { print(" \(String(n, radix: base))", terminator: "") } print("\n") }
342Rhonda numbers
17swift
6s23j
public class RN { enum Numeral { I(1), IV(4), V(5), IX(9), X(10), XL(40), L(50), XC(90), C(100), CD(400), D(500), CM(900), M(1000); int weight; Numeral(int weight) { this.weight = weight; } }; public static String roman(long n) { if( n <= 0) { throw new IllegalArgumentException(); } StringBuilder buf = new StringBuilder(); final Numeral[] values = Numeral.values(); for (int i = values.length - 1; i >= 0; i--) { while (n >= values[i].weight) { buf.append(values[i]); n -= values[i].weight; } } return buf.toString(); } public static void test(long n) { System.out.println(n + " = " + roman(n)); } public static void main(String[] args) { test(1999); test(25); test(944); test(0); } }
341Roman numerals/Encode
9java
fe9dv
runlengthencoding <- function(x) { splitx <- unlist(strsplit(input, "")) rlex <- rle(splitx) paste(with(rlex, as.vector(rbind(lengths, values))), collapse="") } input <- "WWWWWWWWWWWWBWWWWWWWWWWWWBBBWWWWWWWWWWWWWWWWWWWWWWWWBWWWWWWWWWWWWWW" runlengthencoding(input)
336Run-length encoding
13r
q76xs
var roman = { map: [ 1000, 'M', 900, 'CM', 500, 'D', 400, 'CD', 100, 'C', 90, 'XC', 50, 'L', 40, 'XL', 10, 'X', 9, 'IX', 5, 'V', 4, 'IV', 1, 'I', ], int_to_roman: function(n) { var value = ''; for (var idx = 0; n > 0 && idx < this.map.length; idx += 2) { while (n >= this.map[idx]) { value += this.map[idx + 1]; n -= this.map[idx]; } } return value; } } roman.int_to_roman(1999);
341Roman numerals/Encode
10javascript
y0u6r
function ToNumeral( roman ) local Num = { ["M"] = 1000, ["D"] = 500, ["C"] = 100, ["L"] = 50, ["X"] = 10, ["V"] = 5, ["I"] = 1 } local numeral = 0 local i = 1 local strlen = string.len(roman) while i < strlen do local z1, z2 = Num[ string.sub(roman,i,i) ], Num[ string.sub(roman,i+1,i+1) ] if z1 < z2 then numeral = numeral + ( z2 - z1 ) i = i + 2 else numeral = numeral + z1 i = i + 1 end end if i <= strlen then numeral = numeral + Num[ string.sub(roman,i,i) ] end return numeral end print( ToNumeral( "MCMXC" ) ) print( ToNumeral( "MMVIII" ) ) print( ToNumeral( "MDCLXVI" ) )
340Roman numerals/Decode
1lua
twlfn
enum Choice: CaseIterable { case rock case paper case scissors case lizard case spock } extension Choice { var weaknesses: Set<Choice> { switch self { case .rock: return [.paper, .spock] case .paper: return [.scissors, .lizard] case .scissors: return [.rock, .spock] case .lizard: return [.rock, .scissors] case .spock: return [.paper, .lizard] } } } struct Game { private(set) var history: [(Choice, Choice)] = [] private(set) var p1Score: Int = 0 private(set) var p2Score: Int = 0 mutating func play(_ p1Choice: Choice, against p2Choice: Choice) { history.append((p1Choice, p2Choice)) if p2Choice.weaknesses.contains(p1Choice) { p1Score += 1 } else if p1Choice.weaknesses.contains(p2Choice) { p2Score += 1 } } } func aiChoice(for game: Game) -> Choice { if let weightedWeekness = game.history.flatMap({ $0.0.weaknesses }).randomElement() { return weightedWeekness } else {
339Rock-paper-scissors
17swift
j9x74
import datetime import re import urllib.request import sys def get(url): with urllib.request.urlopen(url) as response: html = response.read().decode('utf-8') if re.match(r'<!Doctype HTML[\s\S]*<Title>URL Not Found</Title>', html): return None return html def main(): template = 'http: today = datetime.datetime.utcnow() back = 10 needle = sys.argv[1] for i in range(-back, 2): day = today + datetime.timedelta(days=i) url = day.strftime(template) haystack = get(url) if haystack: mentions = [x for x in haystack.split('\n') if needle in x] if mentions: print('{}\n------\n{}\n------\n' .format(url, '\n'.join(mentions))) main()
343Retrieve and search chat history
3python
1uqpc
null
344RIPEMD-160
5c
a5q11
require 'net/http' require 'time' def gen_url(i) day = Time.now + i*60*60*24 old_tz = ENV['TZ'] ENV['TZ'] = 'Europe/Berlin' url = day.strftime('http: ENV['TZ'] = old_tz url end def main back = 10 needle = ARGV[0] (-back..0).each do |i| url = gen_url(i) haystack = Net::HTTP.get(URI(url)).split() mentions = haystack.select { |x| x.include? needle } if!mentions.empty? puts \n end end end main
343Retrieve and search chat history
14ruby
e40ax
val romanNumerals = mapOf( 1000 to "M", 900 to "CM", 500 to "D", 400 to "CD", 100 to "C", 90 to "XC", 50 to "L", 40 to "XL", 10 to "X", 9 to "IX", 5 to "V", 4 to "IV", 1 to "I" ) fun encode(number: Int): String? { if (number > 5000 || number < 1) { return null } var num = number var result = "" for ((multiple, numeral) in romanNumerals.entries) { while (num >= multiple) { num -= multiple result += numeral } } return result } fun main(args: Array<String>) { println(encode(1990)) println(encode(1666)) println(encode(2008)) }
341Roman numerals/Encode
11kotlin
8kz0q
import java.net.Socket import java.net.URL import java.time import java.time.format import java.time.ZoneId import java.util.Scanner import scala.collection.JavaConverters._ def get(rawUrl: String): List[String] = { val url = new URL(rawUrl) val port = if (url.getPort > -1) url.getPort else 80 val sock = new Socket(url.getHost, port) sock.getOutputStream.write( s"GET /${url.getPath()} HTTP/1.0\n\n".getBytes("UTF-8") ) new Scanner(sock.getInputStream).useDelimiter("\n").asScala.toList } def genUrl(n: Long) = { val date = java.time.ZonedDateTime .now(ZoneId.of("Europe/Berlin")) .plusDays(n) .format(java.time.format.DateTimeFormatter.ISO_LOCAL_DATE) s"http:
343Retrieve and search chat history
16scala
sjnqo
def run_encode(string) string .chars .chunk{|i| i} .map {|kind, array| [kind, array.length]} end def run_decode(char_counts) char_counts .map{|char, count| char * count} .join end
336Run-length encoding
14ruby
n12it
(use 'pandect.core) (ripemd160 "Rosetta Code")
344RIPEMD-160
6clojure
sjiqr
fn encode(s: &str) -> String { s.chars()
336Run-length encoding
15rust
davny
package main import ( "fmt" big "github.com/ncw/gmp" "rcu" "strings" ) func main() { limit := 2700 primes := rcu.Primes(limit) s := new(big.Int) for b := 2; b <= 36; b++ { var rPrimes []int for _, p := range primes { s.SetString(strings.Repeat("1", p), b) if s.ProbablyPrime(15) { rPrimes = append(rPrimes, p) } } fmt.Printf("Base%2d:%v\n", b, rPrimes) } }
345Repunit primes
0go
g6j4n
use strict; use warnings; use ntheory <is_prime fromdigits>; my $limit = 1000; print "Repunit prime digits (up to $limit) in:\n"; for my $base (2..16) { printf "Base%2d:%s\n", $base, join ' ', grep { is_prime $_ and is_prime fromdigits(('1'x$_), $base) and " $_" } 1..$limit }
345Repunit primes
2perl
tw6fg
def encode(s: String) = (1 until s.size).foldLeft((1, s(0), new StringBuilder)) { case ((len, c, sb), index) if c != s(index) => sb.append(len); sb.append(c); (1, s(index), sb) case ((len, c, sb), _) => (len + 1, c, sb) } match { case (len, c, sb) => sb.append(len); sb.append(c); sb.toString } def decode(s: String) = { val sb = new StringBuilder val Code = """(\d+)([A-Z])""".r for (Code(len, c) <- Code findAllIn s) sb.append(c * len.toInt) sb.toString }
336Run-length encoding
16scala
zx4tr
package main import ( "golang.org/x/crypto/ripemd160" "fmt" ) func main() { h := ripemd160.New() h.Write([]byte("Rosetta Code")) fmt.Printf("%x\n", h.Sum(nil)) }
344RIPEMD-160
0go
m82yi
import Data.Char (ord) import Crypto.Hash.RIPEMD160 (hash) import Data.ByteString (unpack, pack) import Text.Printf (printf) main = putStrLn $ concatMap (printf "%02x") $ unpack $ hash $ pack $ map (fromIntegral.ord) "Rosetta Code"
344RIPEMD-160
8haskell
klah0
from sympy import isprime for b in range(2, 17): print(b, [n for n in range(2, 1001) if isprime(n) and isprime(int('1'*n, base=b))])
345Repunit primes
3python
zxytt
import org.bouncycastle.crypto.digests.RIPEMD160Digest; import org.bouncycastle.util.encoders.Hex; public class RosettaRIPEMD160 { public static void main (String[] argv) throws Exception { byte[] r = "Rosetta Code".getBytes("US-ASCII"); RIPEMD160Digest d = new RIPEMD160Digest(); d.update (r, 0, r.length); byte[] o = new byte[d.getDigestSize()]; d.doFinal (o, 0); Hex.encode (o, System.out); System.out.println(); } }
344RIPEMD-160
9java
43j58
package main import ( "fmt" "reflect" ) type example struct{} func (example) Foo() int { return 42 }
346Respond to an unknown method call
0go
sj8qa
class MyObject { def foo() { println 'Invoked foo' } def methodMissing(String name, args) { println "Invoked missing method $name$args" } }
346Respond to an unknown method call
7groovy
a5w1p
import org.bouncycastle.crypto.digests.RIPEMD160Digest import org.bouncycastle.util.encoders.Hex import kotlin.text.Charsets.US_ASCII fun RIPEMD160Digest.inOneGo(input : ByteArray) : ByteArray { val output = ByteArray(digestSize) update(input, 0, input.size) doFinal(output, 0) return output } fun main(args: Array<String>) { val input = "Rosetta Code".toByteArray(US_ASCII) val output = RIPEMD160Digest().inOneGo(input) Hex.encode(output, System.out) System.out.flush() }
344RIPEMD-160
11kotlin
ln5cp
typedef struct { double v; int fixed; } node; node **alloc2(int w, int h) { int i; node **a = calloc(1, sizeof(node*)*h + sizeof(node)*w*h); each(i, h) a[i] = i ? a[i-1] + w : (node*)(a + h); return a; } void set_boundary(node **m) { m[1][1].fixed = 1; m[1][1].v = 1; m[6][7].fixed = -1; m[6][7].v = -1; } double calc_diff(node **m, node **d, int w, int h) { int i, j, n; double v, total = 0; each(i, h) each(j, w) { v = 0; n = 0; if (i) v += m[i-1][j].v, n++; if (j) v += m[i][j-1].v, n++; if (i+1 < h) v += m[i+1][j].v, n++; if (j+1 < w) v += m[i][j+1].v, n++; d[i][j].v = v = m[i][j].v - v / n; if (!m[i][j].fixed) total += v * v; } return total; } double iter(node **m, int w, int h) { node **d = alloc2(w, h); int i, j; double diff = 1e10; double cur[] = {0, 0, 0}; while (diff > 1e-24) { set_boundary(m); diff = calc_diff(m, d, w, h); each(i,h) each(j, w) m[i][j].v -= d[i][j].v; } each(i, h) each(j, w) cur[ m[i][j].fixed + 1 ] += d[i][j].v * (!!i + !!j + (i < h-1) + (j < w -1)); free(d); return (cur[2] - cur[0])/2; } int main() { node **mesh = alloc2(S, S); printf(, 2 / iter(mesh, S, S)); return 0; }
347Resistor mesh
5c
9ocm1
obj = new Proxy({}, { get : function(target, prop) { if(target[prop] === undefined) return function() { console.log('an otherwise undefined function!!'); }; else return target[prop]; } }); obj.f()
346Respond to an unknown method call
10javascript
m8cyv
romans = { {1000, "M"}, {900, "CM"}, {500, "D"}, {400, "CD"}, {100, "C"}, {90, "XC"}, {50, "L"}, {40, "XL"}, {10, "X"}, {9, "IX"}, {5, "V"}, {4, "IV"}, {1, "I"} } k = io.read() + 0 for _, v in ipairs(romans) do
341Roman numerals/Encode
1lua
ob38h
use 5.10.0; { my @trans = ( [M => 1000], [CM => 900], [D => 500], [CD => 400], [C => 100], [XC => 90], [L => 50], [XL => 40], [X => 10], [IX => 9], [V => 5], [IV => 4], [I => 1], ); sub from_roman { my $r = shift; my $n = 0; foreach my $pair (@trans) { my ($k, $v) = @$pair; $n += $v while $r =~ s/^$k//i; } return $n } } say "$_: ", from_roman($_) for qw(MCMXC MDCLXVI MMVIII);
340Roman numerals/Decode
2perl
hcxjl
#!/usr/bin/lua require "crypto" print(crypto.digest("ripemd160", "Rosetta Code"))
344RIPEMD-160
1lua
2d4l3
null
346Respond to an unknown method call
11kotlin
obn8z
local object={print=print} setmetatable(object,{__index=function(t,k)return function() print("You called the method",k)end end}) object.print("Hi")
346Respond to an unknown method call
1lua
ipdot
-- variable table DROP TABLE IF EXISTS var; CREATE temp TABLE var ( VALUE VARCHAR(1000) ); INSERT INTO var(VALUE) SELECT 'WWWWWWWWWWWWBWWWWWWWWWWWWBBBWWWWWWWWWWWWWWWWWWWWWWWWBWWWWWWWWWWWWWW'; -- select WITH recursive ints(num) AS ( SELECT 1 UNION ALL SELECT num+1 FROM ints WHERE num+1 <= LENGTH((SELECT VALUE FROM var)) ) , chars(num,chr,nextChr,isGroupEnd) AS ( SELECT tmp.*, CASE WHEN tmp.nextChr <> tmp.chr THEN 1 ELSE 0 END groupEnds FROM ( SELECT num, SUBSTRING((SELECT VALUE FROM var), num, 1) chr, (SELECT SUBSTRING((SELECT VALUE FROM var), num+1, 1)) nextChr FROM ints ) tmp ) SELECT (SELECT VALUE FROM var) plain_text, ( SELECT string_agg(concat(CAST(maxNoWithinGroup AS VARCHAR(10)) , chr), '' ORDER BY num) FROM ( SELECT *, MAX(noWithinGroup) OVER (partition BY chr, groupNo) maxNoWithinGroup FROM ( SELECT num, chr, groupNo, ROW_NUMBER() OVER( partition BY chr, groupNo ORDER BY num) noWithinGroup FROM ( SELECT *, (SELECT COUNT(*) FROM chars chars2 WHERE chars2.isGroupEnd = 1 AND chars2.chr = chars.chr AND chars2.num < chars.num) groupNo FROM chars ) tmp ) sub ) final WHERE noWithinGroup = 1 ) Rle_Compressed
336Run-length encoding
19sql
y076x
<?php $roman_to_decimal = array( 'I' => 1, 'V' => 5, 'X' => 10, 'L' => 50, 'C' => 100, 'D' => 500, 'M' => 1000, ); function roman2decimal($number) { global $roman_to_decimal; $digits = str_split($number); $lastIndex = count($digits)-1; $sum = 0; foreach($digits as $index => $digit) { if(!isset($digits[$index])) { continue; } if(isset($roman_to_decimal[$digit])) { if($index < $lastIndex) { $left = $roman_to_decimal[$digits[$index]]; $right = $roman_to_decimal[$digits[$index+1]]; if($left < $right) { $sum += ($right - $left); unset($digits[$index+1],$left, $right); continue; } unset($left, $right); } } $sum += $roman_to_decimal[$digit]; } return $sum; } header('Content-Type: text/plain'); $tests = array( => array(roman2decimal('I'), 1), => array(roman2decimal('II'), 2), => array(roman2decimal('III'), 3), => array(roman2decimal('IV'), 4), => array(roman2decimal('V'), 5), => array(roman2decimal('VI'), 6), => array(roman2decimal('VII'), 7), => array(roman2decimal('IX'), 9), => array(roman2decimal('X'), 10), => array(roman2decimal('XI'), 11), => array(roman2decimal('XIV'), 14), => array(roman2decimal('XV'), 15), => array(roman2decimal('XVI'), 16), => array(roman2decimal('XVIV'), 19), => array(roman2decimal('XIX'), 19), => array(roman2decimal('MDCLXVI'), 1666), => array(roman2decimal('MCMXC'), 1990), => array(roman2decimal('MMVIII'), 2008), => array(roman2decimal('MMMCLIX'), 3159), => array(roman2decimal('MCMLXXVII'), 1977), ); foreach($tests as $key => $value) { echo . ($value[0] === $value[1]? : ) . ; }
340Roman numerals/Decode
12php
zx2t1
import Foundation
336Run-length encoding
17swift
iplo0
use Crypt::RIPEMD160; say unpack "H*", Crypt::RIPEMD160->hash("Rosetta Code");
344RIPEMD-160
2perl
q7ox6
package main import "fmt" const ( S = 10 ) type node struct { v float64 fixed int } func alloc2(w, h int) [][]node { a := make([][]node, h) for i := range a { a[i] = make([]node, w) } return a } func set_boundary(m [][]node) { m[1][1].fixed = 1 m[1][1].v = 1 m[6][7].fixed = -1 m[6][7].v = -1 } func calc_diff(m [][]node, d [][]node, w, h int) float64 { total := 0.0 for i := 0; i < h; i++ { for j := 0; j < w; j++ { v := 0.0 n := 0 if i != 0 { v += m[i-1][j].v n++ } if j != 0 { v += m[i][j-1].v n++ } if i+1 < h { v += m[i+1][j].v n++ } if j+1 < w { v += m[i][j+1].v n++ } v = m[i][j].v - v/float64(n) d[i][j].v = v if m[i][j].fixed == 0 { total += v * v } } } return total } func iter(m [][]node, w, h int) float64 { d := alloc2(w, h) diff := 1.0e10 cur := []float64{0, 0, 0} for diff > 1e-24 { set_boundary(m) diff = calc_diff(m, d, w, h) for i := 0; i < h; i++ { for j := 0; j < w; j++ { m[i][j].v -= d[i][j].v } } } for i := 0; i < h; i++ { for j := 0; j < w; j++ { t := 0 if i != 0 { t += 1 } if j != 0 { t += 1 } if i < h-1 { t += 1 } if j < w-1 { t += 1 } cur[m[i][j].fixed+1] += d[i][j].v * float64(t) } } return (cur[2] - cur[0]) / 2 } func main() { mesh := alloc2(S, S) fmt.Printf("R =%g\n", 2/iter(mesh, S, S)) }
347Resistor mesh
0go
e4wa6
Python 3.3.0 (v3.3.0:bd8afb90ebf2, Sep 29 2012, 10:57:17) [MSC v.1600 64 bit (AMD64)] on win32 Type , or for more information. >>> import hashlib >>> h = hashlib.new('ripemd160') >>> h.update(b) >>> h.hexdigest() 'b3be159860842cebaa7174c8fff0aa9e50a5199f' >>>
344RIPEMD-160
3python
sjiq9
import Numeric.LinearAlgebra (linearSolve, toDense, (!), flatten) import Data.Monoid ((<>), Sum(..)) rMesh n (ar, ac) (br, bc) | n < 2 = Nothing | any (\x -> x < 1 || x > n) [ar, ac, br, bc] = Nothing | otherwise = between a b <$> voltage where a = (ac - 1) + n*(ar - 1) b = (bc - 1) + n*(br - 1) between x y v = abs (v ! a - v ! b) voltage = flatten <$> linearSolve matrixG current matrixG = toDense $ concat [ element row col node | row <- [1..n], col <- [1..n] | node <- [0..] ] element row col node = let (Sum c, elements) = (Sum 1, [((node, node-n), -1)]) `when` (row > 1) <> (Sum 1, [((node, node+n), -1)]) `when` (row < n) <> (Sum 1, [((node, node-1), -1)]) `when` (col > 1) <> (Sum 1, [((node, node+1), -1)]) `when` (col < n) in [((node, node), c)] <> elements x `when` p = if p then x else mempty current = toDense [ ((a, 0), -1) , ((b, 0), 1) , ((n^2-1, 0), 0) ]
347Resistor mesh
8haskell
3q6zj
package Example; sub new { bless {} } sub foo { print "this is foo\n"; } sub bar { print "this is bar\n"; } sub AUTOLOAD { my $name = $Example::AUTOLOAD; my ($self, @args) = @_; print "tried to handle unknown method $name\n"; if (@args) { print "it had arguments: @args\n"; } } sub DESTROY {} package main; my $example = Example->new; $example->foo; $example->bar; $example->grill; $example->ding("dong");
346Respond to an unknown method call
2perl
g674e
typedef struct{ int integer; float decimal; char letter; char string[100]; double bigDecimal; }Composite; Composite example() { Composite C = {1, 2.3, 'a', , 45.678}; return C; } int main() { Composite C = example(); printf(, C.integer, C.decimal, C.letter, C.string, C.bigDecimal); return 0; }
348Return multiple values
5c
m8mys
<?php class Example { function foo() { echo ; } function bar() { echo ; } function __call($name, $args) { echo ; if ($args) echo , implode(', ', $args), ; } } $example = new Example(); $example->foo(); $example->bar(); $example->grill(); $example->ding(); ?>
346Respond to an unknown method call
12php
n1fig
void rev_print(char *s, int n) { for (; *s && isspace(*s); s++); if (*s) { char *e; for (e = s; *e && !isspace(*e); e++); rev_print(e, 0); printf(, (int)(e - s), s, + n); } if (n) putchar('\n'); } int main(void) { char *s[] = { , , , , , , , , , , 0 }; int i; for (i = 0; s[i]; i++) rev_print(s[i], 1); return 0; }
349Reverse words in a string
5c
4zu5t
require 'digest' puts Digest::RMD160.hexdigest('Rosetta Code')
344RIPEMD-160
14ruby
8kd01
use ripemd160::{Digest, Ripemd160};
344RIPEMD-160
15rust
obf83
import java.util.ArrayList; import java.util.List; public class ResistorMesh { private static final int S = 10; private static class Node { double v; int fixed; Node(double v, int fixed) { this.v = v; this.fixed = fixed; } } private static void setBoundary(List<List<Node>> m) { m.get(1).get(1).v = 1.0; m.get(1).get(1).fixed = 1; m.get(6).get(7).v = -1.0; m.get(6).get(7).fixed = -1; } private static double calcDiff(List<List<Node>> m, List<List<Node>> d, int w, int h) { double total = 0.0; for (int i = 0; i < h; ++i) { for (int j = 0; j < w; ++j) { double v = 0.0; int n = 0; if (i > 0) { v += m.get(i - 1).get(j).v; n++; } if (j > 0) { v += m.get(i).get(j - 1).v; n++; } if (i + 1 < h) { v += m.get(i + 1).get(j).v; n++; } if (j + 1 < w) { v += m.get(i).get(j + 1).v; n++; } v = m.get(i).get(j).v - v / n; d.get(i).get(j).v = v; if (m.get(i).get(j).fixed == 0) { total += v * v; } } } return total; } private static double iter(List<List<Node>> m, int w, int h) { List<List<Node>> d = new ArrayList<>(h); for (int i = 0; i < h; ++i) { List<Node> t = new ArrayList<>(w); for (int j = 0; j < w; ++j) { t.add(new Node(0.0, 0)); } d.add(t); } double[] cur = new double[3]; double diff = 1e10; while (diff > 1e-24) { setBoundary(m); diff = calcDiff(m, d, w, h); for (int i = 0; i < h; ++i) { for (int j = 0; j < w; ++j) { m.get(i).get(j).v -= d.get(i).get(j).v; } } } for (int i = 0; i < h; ++i) { for (int j = 0; j < w; ++j) { int k = 0; if (i != 0) k++; if (j != 0) k++; if (i < h - 1) k++; if (j < w - 1) k++; cur[m.get(i).get(j).fixed + 1] += d.get(i).get(j).v * k; } } return (cur[2] - cur[0]) / 2.0; } public static void main(String[] args) { List<List<Node>> mesh = new ArrayList<>(S); for (int i = 0; i < S; ++i) { List<Node> t = new ArrayList<>(S); for (int j = 0; j < S; ++j) { t.add(new Node(0.0, 0)); } mesh.add(t); } double r = 2.0 / iter(mesh, S, S); System.out.printf("R =%.15f", r); } }
347Resistor mesh
9java
ipnos
typedef struct rendezvous { pthread_mutex_t lock; pthread_cond_t cv_entering; pthread_cond_t cv_accepting; pthread_cond_t cv_done; int (*accept_func)(void*); int entering; int accepting; int done; } rendezvous_t; .lock = PTHREAD_MUTEX_INITIALIZER, \ .cv_entering = PTHREAD_COND_INITIALIZER, \ .cv_accepting = PTHREAD_COND_INITIALIZER, \ .cv_done = PTHREAD_COND_INITIALIZER, \ .accept_func = accept_function, \ .entering = 0, \ .accepting = 0, \ .done = 0, \ } int enter_rendezvous(rendezvous_t *rv, void* data) { pthread_mutex_lock(&rv->lock); rv->entering++; pthread_cond_signal(&rv->cv_entering); while (!rv->accepting) { pthread_cond_wait(&rv->cv_accepting, &rv->lock); } int ret = rv->accept_func(data); rv->done = 1; pthread_cond_signal(&rv->cv_done); rv->entering--; rv->accepting = 0; pthread_mutex_unlock(&rv->lock); return ret; } void accept_rendezvous(rendezvous_t *rv) { pthread_mutex_lock(&rv->lock); rv->accepting = 1; while (!rv->entering) { pthread_cond_wait(&rv->cv_entering, &rv->lock); } pthread_cond_signal(&rv->cv_accepting); while (!rv->done) { pthread_cond_wait(&rv->cv_done, &rv->lock); } rv->done = 0; rv->accepting = 0; pthread_mutex_unlock(&rv->lock); } typedef struct printer { rendezvous_t rv; struct printer *backup; int id; int remaining_lines; } printer_t; typedef struct print_args { struct printer *printer; const char* line; } print_args_t; int print_line(printer_t *printer, const char* line) { print_args_t args; args.printer = printer; args.line = line; return enter_rendezvous(&printer->rv, &args); } int accept_print(void* data) { print_args_t *args = (print_args_t*)data; printer_t *printer = args->printer; const char* line = args->line; if (printer->remaining_lines) { printf(, printer->id); while (*line != '\0') { putchar(*line++); } putchar('\n'); printer->remaining_lines--; return 1; } else if (printer->backup) { return print_line(printer->backup, line); } else { return -1; } } printer_t backup_printer = { .rv = RENDEZVOUS_INITILIZER(accept_print), .backup = NULL, .id = 2, .remaining_lines = 5, }; printer_t main_printer = { .rv = RENDEZVOUS_INITILIZER(accept_print), .backup = &backup_printer, .id = 1, .remaining_lines = 5, }; void* printer_thread(void* thread_data) { printer_t *printer = (printer_t*) thread_data; while (1) { accept_rendezvous(&printer->rv); } } typedef struct poem { char* name; char* lines[]; } poem_t; poem_t humpty_dumpty = { .name = , .lines = { , , , , }, }; poem_t mother_goose = { .name = , .lines = { , , , , , , , , }, }; void* poem_thread(void* thread_data) { poem_t *poem = (poem_t*)thread_data; for (unsigned i = 0; poem->lines[i] != ; i++) { int ret = print_line(&main_printer, poem->lines[i]); if (ret < 0) { printf(, poem->name); exit(1); } } return NULL; } int main(void) { pthread_t threads[4]; pthread_create(&threads[0], NULL, poem_thread, &humpty_dumpty); pthread_create(&threads[1], NULL, poem_thread, &mother_goose); pthread_create(&threads[2], NULL, printer_thread, &main_printer); pthread_create(&threads[3], NULL, printer_thread, &backup_printer); pthread_join(threads[0], NULL); pthread_join(threads[1], NULL); pthread_cancel(threads[2]); pthread_cancel(threads[3]); return 0; }
350Rendezvous
5c
5t2uk
import org.bouncycastle.crypto.digests.RIPEMD160Digest object RosettaRIPEMD160 extends App { val (raw, messageDigest) = ("Rosetta Code".getBytes("US-ASCII"), new RIPEMD160Digest()) messageDigest.update(raw, 0, raw.length) val out = Array.fill[Byte](messageDigest.getDigestSize())(0) messageDigest.doFinal(out, 0) assert(out.map("%02x".format(_)).mkString == "b3be159860842cebaa7174c8fff0aa9e50a5199f") }
344RIPEMD-160
16scala
da3ng
null
347Resistor mesh
11kotlin
q7sx1
class Example(object): def foo(self): print() def bar(self): print() def __getattr__(self, name): def method(*args): print( + name) if args: print( + str(args)) return method example = Example() example.foo() example.bar() example.grill() example.ding()
346Respond to an unknown method call
3python
ryjgq
null
344RIPEMD-160
17swift
0hns6
class Example def foo puts end def bar puts end def method_missing(name, *args, &block) puts % name unless args.empty? puts % [args] end end end example = Example.new example.foo example.bar example.grill example.ding()
346Respond to an unknown method call
14ruby
j9k7x
(def poem "---------- Ice and Fire ------------ fire, in end will world the say Some ice. in say Some desire of tasted I've what From fire. favor who those with hold I ... elided paragraph last ... Frost Robert -----------------------") (dorun (map println (map #(apply str (interpose " " (reverse (re-seq #"[^\s]+" %)))) (clojure.string/split poem #"\n"))))
349Reverse words in a string
6clojure
h97jr
sub rot13 { shift =~ tr/A-Za-z/N-ZA-Mn-za-m/r; } print rot13($_) while (<>);
338Rot-13
2perl
g6e4e
(defn quot-rem [m n] [(quot m n) (rem m n)]) (let [[q r] (quot-rem 11 3)] (println q) (println r))
348Return multiple values
6clojure
vfv2f
class DynamicTest extends Dynamic { def foo()=println("this is foo") def bar()=println("this is bar") def applyDynamic(name: String)(args: Any*)={ println("tried to handle unknown method "+name) if(!args.isEmpty) println(" it had arguments: "+args.mkString(",")) } } object DynamicTest { def main(args: Array[String]): Unit = { val d=new DynamicTest() d.foo() d.bar() d.grill() d.ding("dong") } }
346Respond to an unknown method call
16scala
pvabj
_rdecode = dict(zip('MDCLXVI', (1000, 500, 100, 50, 10, 5, 1))) def decode( roman ): result = 0 for r, r1 in zip(roman, roman[1:]): rd, rd1 = _rdecode[r], _rdecode[r1] result += -rd if rd < rd1 else rd return result + _rdecode[roman[-1]] if __name__ == '__main__': for r in 'MCMXC MMVIII MDCLXVI'.split(): print( r, decode(r) )
340Roman numerals/Decode
3python
klqhf
echo str_rot13('foo'), ;
338Rot-13
12php
n1cig
(source println) (meta #'println)
351Reflection/Get source
6clojure
ibsom
package main import ( "errors" "fmt" "strings" "sync" ) var hdText = `Humpty Dumpty sat on a wall. Humpty Dumpty had a great fall. All the king's horses and all the king's men, Couldn't put Humpty together again.` var mgText = `Old Mother Goose, When she wanted to wander, Would ride through the air, On a very fine gander. Jack's mother came in, And caught the goose soon, And mounting its back, Flew up to the moon.` func main() { reservePrinter := startMonitor(newPrinter(5), nil) mainPrinter := startMonitor(newPrinter(5), reservePrinter) var busy sync.WaitGroup busy.Add(2) go writer(mainPrinter, "hd", hdText, &busy) go writer(mainPrinter, "mg", mgText, &busy) busy.Wait() }
350Rendezvous
0go
8hq0g
void repeat(void (*f)(void), unsigned int n) { while (n-->0) (*f)(); } void example() { printf(); } int main(int argc, char *argv[]) { repeat(example, 4); return 0; }
352Repeat
5c
3xnza
package main import ( "fmt" "path" "reflect" "runtime" ) func someFunc() { fmt.Println("someFunc called") } func main() { pc := reflect.ValueOf(someFunc).Pointer() f := runtime.FuncForPC(pc) name := f.Name() file, line := f.FileLine(pc) fmt.Println("Name of function:", name) fmt.Println("Name of file :", path.Base(file)) fmt.Println("Line number :", line) }
351Reflection/Get source
0go
2nml7