code stringlengths 1 46.1k ⌀ | label class label 1.18k
classes | domain_label class label 21
classes | index stringlengths 4 5 |
|---|---|---|---|
package main
import (
"fmt"
"math"
"math/cmplx"
)
func main() {
for n := 2; n <= 5; n++ {
fmt.Printf("%d roots of 1:\n", n)
for _, r := range roots(n) {
fmt.Printf(" %18.15f\n", r)
}
}
}
func roots(n int) []complex128 {
r := make([]complex128, n)
for i ... | 333Roots of unity | 0go | utxvt |
def rootsOfUnity = { n ->
(0..<n).collect {
Complex.fromPolar(1, 2 * Math.PI * it / n)
}
} | 333Roots of unity | 7groovy | 9opm4 |
my $lang = 'no language';
my $total = 0;
my %blanks = ();
while (<>) {
if (m/<lang>/) {
if (exists $blanks{lc $lang}) {
$blanks{lc $lang}++
} else {
$blanks{lc $lang} = 1
}
$total++
} elsif (m/==\s*\{\{\s*header\s*\|\s*([^\s\}]+)\s*\}\}\s*==/) {
$lang = lc $1
}
}
if ($total) {
pr... | 335Rosetta Code/Find bare lang tags | 2perl | sjmq3 |
import Data.Complex (Complex, realPart)
type CD = Complex Double
quadraticRoots :: (CD, CD, CD) -> (CD, CD)
quadraticRoots (a, b, c)
| 0 < realPart b =
( (2 * c) / (- b - d),
(- b - d) / (2 * a)
)
| otherwise =
( (- b + d) / (2 * a),
(2 * c) / (- b + d)
)
where
d = sqrt $ b ^ 2 -... | 334Roots of a quadratic function | 8haskell | 8kl0z |
static char rot13_table[UCHAR_MAX + 1];
static void init_rot13_table(void) {
static const unsigned char upper[] = ;
static const unsigned char lower[] = ;
for (int ch = '\0'; ch <= UCHAR_MAX; ch++) {
rot13_table[ch] = ch;
}
for (const unsigned char *p = upper; p[13] != '\0'; p++) {
rot13_table[p[0]] = p[13];... | 338Rot-13 | 5c | vfb2o |
library(XML)
find.unimplemented.tasks <- function(lang="R"){
PT <- xmlInternalTreeParse( paste("http://www.rosettacode.org/w/api.php?action=query&list=categorymembers&cmtitle=Category:Programming_Tasks&cmlimit=500&format=xml",sep="") )
PT.nodes <- getNodeSet(PT,"//cm")
PT.titles = as.character( sapply(PT.nodes, xmlG... | 331Rosetta Code/Find unimplemented tasks | 13r | j9d78 |
use strict;
use warnings;
sub sexpr
{
my @stack = ([]);
local $_ = $_[0];
while (m{
\G
\s*+
(?<lparen>\() |
(?<rparen>\)) |
(?<FLOAT>[0-9]*+\.[0-9]*+) |
(?<INT>[0-9]++) |
(?:"(?<STRING>([^\"\\]|\\.)*+)") |
(?<IDENTIFIER>[^\s()]++)
}gmsx)
{
die "match error" if 0+(keys %... | 327S-expressions | 2perl | 5znu2 |
import Data.Complex (Complex, cis)
rootsOfUnity :: (Enum a, Floating a) => a -> [Complex a]
rootsOfUnity n =
[ cis (2 * pi * k / n)
| k <- [0 .. n - 1] ]
main :: IO ()
main = mapM_ print $ rootsOfUnity 3 | 333Roots of unity | 8haskell | wgyed |
use strict;
use List::Util 'sum';
my ($min_sum, $hero_attr_min, $hero_count_min) = <75 15 3>;
my @attr_names = <Str Int Wis Dex Con Cha>;
sub heroic { scalar grep { $_ >= $hero_attr_min } @_ }
sub roll_skip_lowest {
my($dice, $sides) = @_;
sum( (sort map { 1 + int rand($sides) } 1..$dice)[1..$dice-1] );
}
m... | 328RPG attributes generator | 2perl | m8wyz |
(defn findRoots [f start stop step eps]
(filter #(-> (f %) Math/abs (< eps)) (range start stop step))) | 337Roots of a function | 6clojure | 2dbl1 |
echo "What will you choose? [rock/paper/scissors]"
read response
aiThought=$(echo $[ 1 + $[ RANDOM % 3 ]])
case $aiThought in
1) aiResponse="rock" ;;
2) aiResponse="paper" ;;
3) aiResponse="scissors" ;;
esac
echo "AI - $aiResponse"
responses="$response$aiResponse"
case $responses in
rockrock) isTie=1 ;... | 339Rock-paper-scissors | 4bash | 2dhl0 |
from __future__ import annotations
import functools
import gzip
import json
import logging
import platform
import re
from collections import Counter
from collections import defaultdict
from typing import Any
from typing import Iterator
from typing import Iterable
from typing import List
from typing import Mapping
fr... | 335Rosetta Code/Find bare lang tags | 3python | 0h9sq |
require 'rosettacode'
require 'time'
module RosettaCode
def self.get_unimplemented(lang)
programming_tasks = []
category_members() {|task| programming_tasks << task}
lang_tasks = []
category_members(lang) {|task| lang_tasks << task}
lang_tasks_omit = []
category_members() {|task| lang_tasks... | 331Rosetta Code/Find unimplemented tasks | 14ruby | a5y1s |
import java.util.Locale;
public class Test {
public static void main(String[] a) {
for (int n = 2; n < 6; n++)
unity(n);
}
public static void unity(int n) {
System.out.printf("%n%d: ", n); | 333Roots of unity | 9java | kldhm |
public class QuadraticRoots {
private static class Complex {
double re, im;
public Complex(double re, double im) {
this.re = re;
this.im = im;
}
@Override
public boolean equals(Object obj) {
if (obj == this) {return true;}
if ... | 334Roots of a quadratic function | 9java | e43a5 |
(ns rosettacode.rot-13)
(let [a (int \a) m (int \m) A (int \A) M (int \M)
n (int \n) z (int \z) N (int \N) Z (int \Z)]
(defn rot-13 [^Character c]
(char (let [i (int c)]
(cond-> i
(or (<= a i m) (<= A i M)) (+ 13)
(or (<= n i z) (<= N i Z)) (- 13))))))
(apply str (map rot-13 "The Qui... | 338Rot-13 | 6clojure | rywg2 |
use std::collections::{BTreeMap, HashSet};
use reqwest::Url;
use serde::Deserialize;
use serde_json::Value; | 331Rosetta Code/Find unimplemented tasks | 15rust | e4maj |
<?php
$attributesTotal = 0;
$count = 0;
while($attributesTotal < 75 || $count < 2) {
$attributes = [];
foreach(range(0, 5) as $attribute) {
$rolls = [];
foreach(range(0, 3) as $roll) {
$rolls[] = rand(1, 6);
}
sort($rolls);
array_shift($rolls);
$... | 328RPG attributes generator | 12php | e4la9 |
function Root(angle) {
with (Math) { this.r = cos(angle); this.i = sin(angle) }
}
Root.prototype.toFixed = function(p) {
return this.r.toFixed(p) + (this.i >= 0 ? '+' : '') + this.i.toFixed(p) + 'i'
}
function roots(n) {
var rs = [], teta = 2*Math.PI/n
for (var angle=0, i=0; i<n; angle+=teta, i+=1) rs.push( new R... | 333Roots of unity | 10javascript | e46ao |
libraryDependencies ++= Seq(
"org.json4s"%%"json4s-native"%"3.6.0",
"com.softwaremill.sttp"%%"core"%"1.5.11",
"com.softwaremill.sttp"%%"json4s"%"1.5.11") | 331Rosetta Code/Find unimplemented tasks | 16scala | q7lxw |
use HTTP::Tiny;
my $site = "http://rosettacode.org";
my $list_url = "/mw/api.php?action=query&list=categorymembers&cmtitle=Category:Programming_Tasks&cmlimit=500&format=xml";
my $response = HTTP::Tiny->new->get("$site$list_url");
for ($response->{content} =~ /cm.*?title="(.*?)"/g) {
(my $slug = $_) =~ tr/ /_/;
... | 332Rosetta Code/Count examples | 2perl | 6sk36 |
list = {"mouse", "hat", "cup", "deodorant", "television", "soap", "methamphetamine", "severed cat heads"} | 323Search a list | 1lua | obb8h |
require
require
tasks = [, , ]
part_uri =
Report = Struct.new(:count, :tasks)
result = Hash.new{|h,k| h[k] = Report.new(0, [])}
tasks.each do |task|
puts
current_lang =
open(part_uri + CGI.escape(task)).each_line do |line|
current_lang = Regexp.last_match[] if /==\{\{header\|(?<lang>.+)\}\}==/ =~ li... | 335Rosetta Code/Find bare lang tags | 14ruby | obl8v |
import java.lang.Math.*
data class Equation(val a: Double, val b: Double, val c: Double) {
data class Complex(val r: Double, val i: Double) {
override fun toString() = when {
i == 0.0 -> r.toString()
r == 0.0 -> "${i}i"
else -> "$r + ${i}i"
}
}
data clas... | 334Roots of a quadratic function | 11kotlin | klnh3 |
import re
dbg = False
term_regex = r'''(?mx)
\s*(?:
(?P<brackl>\()|
(?P<brackr>\))|
(?P<num>\-?\d+\.\d+|\-?\d+)|
(?P<sq>]*%-6s%-14s%-44s%-sterm value out stack%-7s%-14s%-44r%-rTrouble with nesting of bracketsError:%rTrouble with nesting of brackets%s', '\quoted data(moredata)\nPars... | 327S-expressions | 3python | 43d5k |
double fn(double x) => x * x * x - 3 * x * x + 2 * x;
findRoots(Function(double) f, double start, double stop, double step, double epsilon) sync* {
for (double x = start; x < stop; x = x + step) {
if (fn(x).abs() < epsilon) yield x;
}
}
main() { | 337Roots of a function | 18dart | da2nj |
int rand_idx(double *p, int n)
{
double s = rand() / (RAND_MAX + 1.0);
int i;
for (i = 0; i < n - 1 && (s -= p[i]) >= 0; i++);
return i;
}
int main()
{
int user_action, my_action;
int user_rec[] = {0, 0, 0};
const char *names[] = { , , };
char str[2];
const char *winner[] = { , , };
double p[LEN] = { 1./3... | 339Rock-paper-scissors | 5c | utbv4 |
import java.lang.Math.*
data class Complex(val r: Double, val i: Double) {
override fun toString() = when {
i == 0.0 -> r.toString()
r == 0.0 -> i.toString() + 'i'
else -> "$r + ${i}i"
}
}
fun unity_roots(n: Number) = (1..n.toInt() - 1).map {
val a = it * 2 * PI / n.toDouble()
... | 333Roots of unity | 11kotlin | g604d |
extern crate regex;
use std::io;
use std::io::prelude::*;
use regex::Regex;
fn find_bare_lang_tags(input: &str) -> Vec<(Option<String>, i32)> {
let mut language_pairs = vec![];
let mut language = None;
let mut counter = 0_i32;
let header_re = Regex::new(r"==\{\{header\|(?P<lang>[[:alpha:]]+)\}\}==")... | 335Rosetta Code/Find bare lang tags | 15rust | ip2od |
null | 335Rosetta Code/Find bare lang tags | 16scala | fe5d4 |
sub runge_kutta {
my ($yp, $dt) = @_;
sub {
my ($t, $y) = @_;
my @dy = $dt * $yp->( $t , $y );
push @dy, $dt * $yp->( $t + $dt/2, $y + $dy[0]/2 );
push @dy, $dt * $yp->( $t + $dt/2, $y + $dy[1]/2 );
push @dy, $dt * $yp->( $t + $dt , $y + $dy[2] );
return $t + $dt, $y + ($dy[0] + 2*$dy[1] + 2*$dy[... | 326Runge-Kutta method | 2perl | utnvr |
import random
random.seed()
attributes_total = 0
count = 0
while attributes_total < 75 or count < 2:
attributes = []
for attribute in range(0, 6):
rolls = []
for roll in range(0, 4):
result = random.randint(1, 6)
rolls.append(result)
sorted_rolls = sorted(roll... | 328RPG attributes generator | 3python | 9oxmf |
from urllib.request import urlopen, Request
import xml.dom.minidom
r = Request(
'https:
headers={'User-Agent': 'Mozilla/5.0'})
x = urlopen(r)
tasks = []
for i in xml.dom.minidom.parseString(x.read()).getElementsByTagName('cm'):
t = i.getAttribute('title').replace(' ', '_')
r = Request(f'https:
head... | 332Rosetta Code/Count examples | 3python | y0b6q |
library(XML)
library(RCurl)
doc <- xmlInternalTreeParse("http://www.rosettacode.org/w/api.php?action=query&list=categorymembers&cmtitle=Category:Programming_Tasks&cmlimit=500&format=xml")
nodes <- getNodeSet(doc,"//cm")
titles = as.character( sapply(nodes, xmlGetAttr, "title") )
headers <- list()
counts <- list()
for (... | 332Rosetta Code/Count examples | 13r | tw7fz |
use 5.010;
use MediaWiki::API;
my $api =
MediaWiki::API->new( { api_url => 'http://rosettacode.org/mw/api.php' } );
my @languages;
my $gcmcontinue;
while (1) {
my $apih = $api->api(
{
action => 'query',
generator => 'categorymembers',
gcmtitle => 'Category:P... | 329Rosetta Code/Rank languages by popularity | 2perl | cix9a |
function qsolve(a, b, c)
if b < 0 then return qsolve(-a, -b, -c) end
val = b + (b^2 - 4*a*c)^(1/2) | 334Roots of a quadratic function | 1lua | b2dka |
genStats <- function()
{
stats <- c(STR = 0, DEX = 0, CON = 0, INT = 0, WIS = 0, CHA = 0)
for(i in seq_along(stats))
{
results <- sample(6, 4, replace = TRUE)
stats[i] <- sum(results[-which.min(results)])
}
if(sum(stats >= 15) < 2 || (stats["TOT"] <- sum(stats)) < 75) Recall() else stats
}
print(genS... | 328RPG attributes generator | 13r | 3q1zt |
import Foundation | 309Sieve of Eratosthenes | 17swift | 3s9z2 |
$ lein trampoline run | 339Rock-paper-scissors | 6clojure | 7mwr0 |
null | 333Roots of unity | 1lua | ry8ga |
class SExpr
def initialize(str)
@original = str
@data = parse_sexpr(str)
end
attr_reader :data, :original
def to_sexpr
@data.to_sexpr
end
private
def parse_sexpr(str)
state = :token_start
tokens = []
word =
str.each_char do |char|
case state
when :token_start
... | 327S-expressions | 14ruby | rytgs |
require 'open-uri'
require 'rexml/document'
module RosettaCode
URL_ROOT =
def self.get_url(page, query)
begin
pstr = URI.encode_www_form_component(page)
qstr = URI.encode_www_form(query)
rescue NoMethodError
require 'cgi'
pstr = CGI.escape(page)
qstr = query.map {|k,... | 332Rosetta Code/Count examples | 14ruby | 9o1mz |
from math import sqrt
def rk4(f, x0, y0, x1, n):
vx = [0] * (n + 1)
vy = [0] * (n + 1)
h = (x1 - x0) / float(n)
vx[0] = x = x0
vy[0] = y = y0
for i in range(1, n + 1):
k1 = h * f(x, y)
k2 = h * f(x + 0.5 * h, y + 0.5 * k1)
k3 = h * f(x + 0.5 * h, y + 0.5 * k2)
k4... | 326Runge-Kutta method | 3python | 5zdux |
null | 327S-expressions | 15rust | 7mzrc |
extern crate reqwest;
extern crate url;
extern crate rustc_serialize;
use std::io::Read;
use self::url::Url;
use rustc_serialize::json::{self, Json};
pub struct Task {
page_id: u64,
pub title: String,
}
#[derive(Debug)]
enum ParseError { | 332Rosetta Code/Count examples | 15rust | cia9z |
rk4 <- function(f, x0, y0, x1, n) {
vx <- double(n + 1)
vy <- double(n + 1)
vx[1] <- x <- x0
vy[1] <- y <- y0
h <- (x1 - x0)/n
for(i in 1:n) {
k1 <- h*f(x, y)
k2 <- h*f(x + 0.5*h, y + 0.5*k1)
k3 <- h*f(x + 0.5*h, y + 0.5*k2)
k4 <- h*f(x + h, y + k3)
vx[i +... | 326Runge-Kutta method | 13r | ln8ce |
import scala.language.postfixOps
object TaskCount extends App {
import java.net.{ URL, URLEncoder }
import scala.io.Source.fromURL
System.setProperty("http.agent", "*")
val allTasksURL =
"http: | 332Rosetta Code/Count examples | 16scala | vfx2s |
res = []
until res.sum >= 75 && res.count{|n| n >= 15} >= 2 do
res = Array.new(6) do
a = Array.new(4){rand(1..6)}
a.sum - a.min
end
end
p res
puts | 328RPG attributes generator | 14ruby | lnscl |
import requests
import re
response = requests.get().text
languages = re.findall('title=>',response)[:-3]
response = requests.get().text
response = re.sub('(\d+),(\d+)',r'\1'+r'\2',response)
members = re.findall('<li><a[^>]+>([^<]+)</a>[^(]*[(](\\d+) member[s]*[)]</li>',response)
for cnt, (language, mem... | 329Rosetta Code/Rank languages by popularity | 3python | lnqcv |
use rand::distributions::Uniform;
use rand::prelude::{thread_rng, ThreadRng};
use rand::Rng;
fn main() {
for _ in 0..=10 {
attributes_engine();
}
}
#[derive(Copy, Clone, Debug)]
pub struct Dice {
amount: i32,
range: Uniform<i32>,
rng: ThreadRng,
}
impl Dice { | 328RPG attributes generator | 15rust | 2d0lt |
library(rvest)
library(plyr)
library(dplyr)
options(stringsAsFactors=FALSE)
langUrl <- "http://rosettacode.org/mw/api.php?format=xml&action=query&generator=categorymembers&gcmtitle=Category:Programming%20Languages&prop=categoryinfo&gcmlimit=5000"
langs <- html(langUrl) %>%
html_nodes('page')
ff <- function(xml_node... | 329Rosetta Code/Rank languages by popularity | 13r | y0a6h |
package main
import (
"fmt"
"math"
)
func main() {
example := func(x float64) float64 { return x*x*x - 3*x*x + 2*x }
findroots(example, -.5, 2.6, 1)
}
func findroots(f func(float64) float64, lower, upper, step float64) {
for x0, x1 := lower, lower+step; x0 < upper; x0, x1 = x1, x1+step {
x1 = math.Min(x1, upp... | 337Roots of a function | 0go | 1unp5 |
def calc_rk4(f)
return ->(t,y,dt){
->(dy1 ){
->(dy2 ){
->(dy3 ){
->(dy4 ){ ( dy1 + 2*dy2 + 2*dy3 + dy4 ) / 6 }.call(
dt * f.call( t + dt , y + dy3 ))}.call(
dt * f.call( t + dt/2, y + dy2/2 ))}.call(
dt * f.call( t + dt/2, y + dy1/2 ))}.c... | 326Runge-Kutta method | 14ruby | g6t4q |
import scala.util.Random
Random.setSeed(1)
def rollDice():Int = {
val v4 = Stream.continually(Random.nextInt(6)+1).take(4)
v4.sum - v4.min
}
def getAttributes():Seq[Int] = Stream.continually(rollDice()).take(6)
def getCharacter():Seq[Int] = {
val attrs = getAttributes()
println("generated => " + attrs.mkStri... | 328RPG attributes generator | 16scala | 5ziut |
int digits[26] = { 0, 0, 100, 500, 0, 0, 0, 0, 1, 1, 0, 50, 1000, 0, 0, 0, 0, 0, 0, 0, 5, 5, 0, 10, 0, 0 };
int decode(const char * roman)
{
const char *bigger;
int current;
int arabic = 0;
while (*roman != '\0') {
current = VALUE(*roman);
... | 340Roman numerals/Decode | 5c | g6145 |
f x = x^3-3*x^2+2*x
findRoots start stop step eps =
[x | x <- [start, start+step .. stop], abs (f x) < eps] | 337Roots of a function | 8haskell | twuf7 |
use Math::Complex;
foreach my $n (2 .. 10) {
printf "%2d", $n;
my @roots = root(1,$n);
foreach my $root (@roots) {
$root->display_format(style => 'cartesian', format => '%.3f');
print " $root";
}
print "\n";
} | 333Roots of unity | 2perl | n15iw |
use Math::Complex;
($x1,$x2) = solveQuad(1,2,3);
print "x1 = $x1, x2 = $x2\n";
sub solveQuad
{
my ($a,$b,$c) = @_;
my $root = sqrt($b**2 - 4*$a*$c);
return ( -$b + $root )/(2*$a), ( -$b - $root )/(2*$a);
} | 334Roots of a quadratic function | 2perl | 3q7zs |
fn runge_kutta4(fx: &dyn Fn(f64, f64) -> f64, x: f64, y: f64, dx: f64) -> f64 {
let k1 = dx * fx(x, y);
let k2 = dx * fx(x + dx / 2.0, y + k1 / 2.0);
let k3 = dx * fx(x + dx / 2.0, y + k2 / 2.0);
let k4 = dx * fx(x + dx, y + k3);
y + (k1 + 2.0 * k2 + 2.0 * k3 + k4) / 6.0
}
fn f(x: f64, y: f64) -> ... | 326Runge-Kutta method | 15rust | ryzg5 |
object Main extends App {
val f = (t: Double, y: Double) => t * Math.sqrt(y) | 326Runge-Kutta method | 16scala | hcyja |
import cmath
class Complex(complex):
def __repr__(self):
rp = '%7.5f'% self.real if not self.pureImag() else ''
ip = '%7.5fj'% self.imag if not self.pureReal() else ''
conj = '' if (
self.pureImag() or self.pureReal() or self.imag < 0.0
) else '+'
return '0.0' i... | 333Roots of unity | 3python | da4n1 |
import math
import cmath
import numpy
def quad_discriminating_roots(a,b,c, entier = 1e-5):
discriminant = b*b - 4*a*c
a,b,c,d =complex(a), complex(b), complex(c), complex(discriminant)
root1 = (-b + cmath.sqrt(d))/2./a
root2 = (-b - cmath.sqrt(d))/2./a
if abs(discriminant) < entier:
re... | 334Roots of a quadratic function | 3python | 6sj3w |
public class Roots {
public interface Function {
public double f(double x);
}
private static int sign(double x) {
return (x < 0.0) ? -1 : (x > 0.0) ? 1 : 0;
}
public static void printRoots(Function f, double lowerBound,
double upperBound, double step) {
double x = lowerBound, ox = x;
dou... | 337Roots of a function | 9java | 8km06 |
package main
import "fmt" | 336Run-length encoding | 0go | lnbcw |
for(j in 2:10) {
r <- sprintf("%d: ", j)
for(n in 1:j) {
r <- paste(r, format(exp(2i*pi*n/j), digits=4), ifelse(n<j, ",", ""))
}
print(r)
} | 333Roots of unity | 13r | 8k20x |
qroots <- function(a, b, c) {
r <- sqrt(b * b - 4 * a * c + 0i)
if (abs(b - r) > abs(b + r)) {
z <- (-b + r) / (2 * a)
} else {
z <- (-b - r) / (2 * a)
}
c(z, c / (z * a))
}
qroots(1, 0, 2i)
[1] -1+1i 1-1i
qroots(1, -1e9, 1)
[1] 1e+09+0i 1e-09+0i | 334Roots of a quadratic function | 13r | fe4dc |
int main() {
int arabic[] = {1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1};
char roman[13][3] = {, , , , , , , , , , , , };
int N;
printf();
scanf(, &N);
printf();
for (int i = 0; i < 13; i++) {
while (N >= arabic[i]) {
printf(, roman[i]);
... | 341Roman numerals/Encode | 5c | 2d7lo |
(defn ro2ar [r]
(->> (reverse (.toUpperCase r))
(map {\M 1000 \D 500 \C 100 \L 50 \X 10 \V 5 \I 1})
(partition-by identity)
(map (partial apply +))
(reduce #(if (< %1 %2) (+ %1 %2) (- %1 %2)))))
(def numerals { \I 1, \V 5, \X 10, \L 50, \C 100, \D 500, \M 1000})
(defn from-roman [s]
(... | 340Roman numerals/Decode | 6clojure | klqhs |
null | 337Roots of a function | 10javascript | fevdg |
def rleEncode(text) {
def encoded = new StringBuilder()
(text =~ /(([A-Z])\2*)/).each { matcher ->
encoded.append(matcher[1].size()).append(matcher[2])
}
encoded.toString()
}
def rleDecode(text) {
def decoded = new StringBuilder()
(text =~ /([0-9]+)([A-Z])/).each { matcher ->
de... | 336Run-length encoding | 7groovy | 6sr3o |
import Foundation
func rk4(dx: Double, x: Double, y: Double, f: (Double, Double) -> Double) -> Double {
let k1 = dx * f(x, y)
let k2 = dx * f(x + dx / 2, y + k1 / 2)
let k3 = dx * f(x + dx / 2, y + k2 / 2)
let k4 = dx * f(x + dx, y + k3)
return y + (k1 + 2 * k2 + 2 * k3 + k4) / 6
}
var y = [Doubl... | 326Runge-Kutta method | 17swift | 43f5g |
require 'rosettacode'
langs = []
RosettaCode.category_members() {|lang| langs << lang}
langcount = {}
langs.each_slice(20) do |sublist|
url = RosettaCode.get_api_url({
=> ,
=> ,
=> ,
=> sublist.join(),
})
doc = REXML::Document.new open(url)
REXML::XPath.each(doc, ) do |page|
lang = ... | 329Rosetta Code/Rank languages by popularity | 14ruby | vf02n |
package main
import (
"fmt"
"math/rand"
"strings"
"time"
)
const rps = "rps"
var msg = []string{
"Rock breaks scissors",
"Paper covers rock",
"Scissors cut paper",
}
func main() {
rand.Seed(time.Now().UnixNano())
fmt.Println("Rock Paper Scissors")
fmt.Println("Enter r, p, or ... | 339Rock-paper-scissors | 0go | 0h3sk |
import Data.List (group)
type Encoded = [(Int, Char)]
type Decoded = String
rlencode :: Decoded -> Encoded
rlencode = fmap ((,) <$> length <*> head) . group
rldecode :: Encoded -> Decoded
rldecode = concatMap (uncurry replicate)
main :: IO ()
main = do
let input = "WWWWWWWWWWWWBWWWWWWWWWWWWBBBWWWWWWWWWWWWWWW... | 336Run-length encoding | 8haskell | 1udps |
use List::Util qw(first);
my @haystack = qw(Zig Zag Wally Ronald Bush Krusty Charlie Bush Bozo);
foreach my $needle (qw(Washington Bush)) {
my $index = first { $haystack[$_] eq $needle } (0 .. $
if (defined $index) {
print "$index $needle\n"... | 323Search a list | 2perl | 4335d |
import System.Random (randomRIO)
data Choice
= Rock
| Paper
| Scissors
deriving (Show, Eq)
beats :: Choice -> Choice -> Bool
beats Paper Rock = True
beats Scissors Paper = True
beats Rock Scissors = True
beats _ _ = False
genrps :: (Int, Int, Int) -> IO Choice
genrps (r, p, s) = rps <$> rand
where
rps ... | 339Rock-paper-scissors | 8haskell | ci794 |
def roots_of_unity(n)
(0...n).map {|k| Complex.polar(1, 2 * Math::PI * k / n)}
end
p roots_of_unity(3) | 333Roots of unity | 14ruby | twrf2 |
require 'cmath'
def quadratic(a, b, c)
sqrt_discriminant = CMath.sqrt(b**2 - 4*a*c)
[(-b + sqrt_discriminant) / (2.0*a), (-b - sqrt_discriminant) / (2.0*a)]
end
p quadratic(3, 4, 4/3.0)
p quadratic(3, 2, -1)
p quadratic(3, 2, 1)
p quadratic(1, 0, 1)
p quadratic(1, -1e6, 1)
p quadratic(-2, 7... | 334Roots of a quadratic function | 14ruby | m8kyj |
import akka.actor.{Actor, ActorSystem, Props}
import scala.collection.immutable.TreeSet
import scala.xml.XML | 329Rosetta Code/Rank languages by popularity | 16scala | g6n4i |
null | 337Roots of a function | 11kotlin | wgtek |
use num::Complex;
fn main() {
let n = 8;
let z = Complex::from_polar(&1.0,&(1.0*std::f64::consts::PI/n as f64));
for k in 0..=n-1 {
println!("e^{:2}i/{} {:>14.3}",2*k,n,z.powf(2.0*k as f64));
}
} | 333Roots of unity | 15rust | zx7to |
def rootsOfUnity(n:Int)=for(k <- 0 until n) yield Complex.fromPolar(1.0, 2*math.Pi*k/n) | 333Roots of unity | 16scala | y0k63 |
import ArithmeticComplex._
object QuadraticRoots {
def solve(a:Double, b:Double, c:Double)={
val d = b*b-4.0*a*c
val aa = a+a
if (d < 0.0) { | 334Roots of a quadratic function | 16scala | 2dalb |
(def arabic->roman
(partial clojure.pprint/cl-format nil "~@R"))
(arabic->roman 147)
(arabic->roman 99) | 341Roman numerals/Encode | 6clojure | g6p4f |
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class RunLengthEncoding {
public static String encode(String source) {
StringBuffer dest = new StringBuffer();
for (int i = 0; i < source.length(); i++) {
int runLength = 1;
while (i+1 < source.length() &... | 336Run-length encoding | 9java | 7msrj |
$haystack = array(,,,,,,,,);
foreach (array(,) as $needle) {
$i = array_search($needle, $haystack);
if ($i === FALSE)
echo ;
else
echo ;
} | 323Search a list | 12php | ippov |
function encode(input) {
var encoding = [];
var prev, count, i;
for (count = 1, prev = input[0], i = 1; i < input.length; i++) {
if (input[i] != prev) {
encoding.push([count, prev]);
count = 1;
prev = input[i];
}
else
count ++;
}
... | 336Run-length encoding | 10javascript | pvnb7 |
null | 337Roots of a function | 1lua | xrzwz |
import java.util.Arrays;
import java.util.EnumMap;
import java.util.List;
import java.util.Map;
import java.util.Scanner;
import java.util.Random;
public class RPS {
public enum Item{
ROCK, PAPER, SCISSORS, ;
public List<Item> losesToList;
public boolean losesTo(Item other) {
return losesToList.contains(othe... | 339Rock-paper-scissors | 9java | zxvtq |
const logic = {
rock: { w: 'scissor', l: 'paper'},
paper: {w:'rock', l:'scissor'},
scissor: {w:'paper', l:'rock'},
}
class Player {
constructor(name){
this.name = name;
}
setChoice(choice){
this.choice = choice;
}
challengeOther(PlayerTwo){
return logic[this.choi... | 339Rock-paper-scissors | 10javascript | 9orml |
null | 339Rock-paper-scissors | 11kotlin | ipmo4 |
tailrec fun runLengthEncoding(text:String,prev:String=""):String {
if (text.isEmpty()){
return prev
}
val initialChar = text.get(0)
val count = text.takeWhile{ it==initialChar }.count()
return runLengthEncoding(text.substring(count),prev + "$count$initialChar" )
}
fun main(args: Array<Strin... | 336Run-length encoding | 11kotlin | utavc |
function cpuMove()
local totalChance = record.R + record.P + record.S
if totalChance == 0 then | 339Rock-paper-scissors | 1lua | n19i8 |
package main
import (
"fmt"
"strings"
)
func rot13char(c rune) rune {
if c >= 'a' && c <= 'm' || c >= 'A' && c <= 'M' {
return c + 13
} else if c >= 'n' && c <= 'z' || c >= 'N' && c <= 'Z' {
return c - 13
}
return c
}
func rot13(s string) string {
return strings.Map(rot13c... | 338Rot-13 | 0go | sj3qa |
haystack=[,,,,,,,,]
for needle in (,):
try:
print haystack.index(needle), needle
except ValueError, value_error:
print needle, | 323Search a list | 3python | g664h |
local C, Ct, R, Cf, Cc = lpeg.C, lpeg.Ct, lpeg.R, lpeg.Cf, lpeg.Cc
astable = Ct(C(1)^0)
function compress(t)
local ret = {}
for i, v in ipairs(t) do
if t[i-1] and v == t[i-1] then
ret[#ret - 1] = ret[#ret - 1] + 1
else
ret[#ret + 1] = 1
ret[#ret + 1] = v
end
end
... | 336Run-length encoding | 1lua | 5zeu6 |
find.needle <- function(haystack, needle="needle", return.last.index.too=FALSE)
{
indices <- which(haystack%in% needle)
if(length(indices)==0) stop("no needles in the haystack")
if(return.last.index.too) range(indices) else min(indices)
} | 323Search a list | 13r | vff27 |
sub f
{
my $x = shift;
return ($x * $x * $x - 3*$x*$x + 2*$x);
}
my $step = 0.001;
my $start = -1;
my $stop = 3;
my $value = &f($start);
my $sign = $value > 0;
print "Root found at $start\n" if ( 0 == $value );
for( my $x = $start + $step;
$x <= $stop;
$x += $step )
{
$... | 337Roots of a function | 2perl | lnkc5 |
def rot13 = { String s ->
(s as List).collect { ch ->
switch (ch) {
case ('a'..'m') + ('A'..'M'):
return (((ch as char) + 13) as char)
case ('n'..'z') + ('N'..'Z'):
return (((ch as char) - 13) as char)
default:
return ch
... | 338Rot-13 | 7groovy | a5n1p |
import Data.Char (chr, isAlpha, ord, toLower)
import Data.Bool (bool)
rot13 :: Char -> Char
rot13 c
| isAlpha c = chr $ bool (-) (+) ('m' >= toLower c) (ord c) 13
| otherwise = c
main :: IO ()
main = print $ rot13 <$> "Abjurer nowhere" | 338Rot-13 | 8haskell | 9o7mo |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.