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... | 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 )... | 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=="... | 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);
... | 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... | 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.empt... | 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)... | 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) = ... | 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.app... | 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).f... | 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 =... | 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 ... | 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 ... | 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",
... | 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.leng... | 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]
}
}
re... | 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)... | 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... | 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... | 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(,dat... | 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[] =... | 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) || (c... | 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... | 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 "" => retur... | 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(need... | 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
e... | 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... | 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 ... | 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) {
... | 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 ... | 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)... | 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, .s... | 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:
... | 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)... | 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... | 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 = n... | 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)
... | 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: Stri... | 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 $ ... | 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.upda... | 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 ma... | 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;
}
do... | 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[p... | 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],
... | 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 FRO... | 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($di... | 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
}
f... | 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)
b... | 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";
}
}
su... | 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)
{
... | 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... | 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;
... | 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... | 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() ... | 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
exam... | 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 " " (re... | 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 ma... | 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 MMVII... | 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,
... | 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)
... | 351Reflection/Get source | 0go | 2nml7 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.