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 := 0; i < n; i++ { r[i] = cmplx.Rect(1, 2*math.Pi*float64(i)/float64(n)) } return r }
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) { print "$total bare language tag" . ($total > 1 ? 's' : '') . ".\n\n"; while ( my ($k, $v) = each(%blanks) ) { print "$k in $v\n" } }
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 - 4 * a * c main :: IO () main = mapM_ (print . quadraticRoots) [ (3, 4, 4 / 3), (3, 2, -1), (3, 2, 1), (1, -10e5, 1), (1, -10e9, 1) ]
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]; rot13_table[p[13]] = p[0]; } for (const unsigned char *p = lower; p[13] != '\0'; p++) { rot13_table[p[0]] = p[13]; rot13_table[p[13]] = p[0]; } } static void rot13_file(FILE *fp) { int ch; while ((ch = fgetc(fp)) != EOF) { fputc(rot13_table[ch], stdout); } } int main(int argc, char *argv[]) { init_rot13_table(); if (argc > 1) { for (int i = 1; i < argc; i++) { FILE *fp = fopen(argv[i], ); if (fp == NULL) { perror(argv[i]); return EXIT_FAILURE; } rot13_file(fp); fclose(fp); } } else { rot13_file(stdin); } return EXIT_SUCCESS; }
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, xmlGetAttr, "title") ) language <- xmlInternalTreeParse( paste("http://www.rosettacode.org/w/api.php?action=query&list=categorymembers&cmtitle=Category:", lang, "&cmlimit=500&format=xml",sep="") ) lang.nodes <- getNodeSet(language,"//cm") lang.titles = as.character( sapply(lang.nodes, xmlGetAttr, "title") ) unimplemented <- setdiff(PT.titles, lang.titles) unimplemented } find.unimplemented.tasks(lang="Python") langs <- c("R","python","perl") sapply(langs, find.unimplemented.tasks)
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 %+) != 1; my $token = (keys %+)[0]; my $val = $+{$token}; if ($token eq 'lparen') { my $a = []; push @{$stack[$ push @stack, $a; } elsif ($token eq 'rparen') { pop @stack; } else { push @{$stack[$ } } return $stack[0]->[0]; } sub quote { (local $_ = $_[0]) =~ /[\s\"\(\)]/s ? do{s/\"/\\\"/gs; qq{"$_"}}: $_; } sub sexpr2txt { qq{(@{[ map { ref($_) eq ''? quote($_): ref($_) eq 'STRING'? quote($$_): ref($_) eq 'ARRAY'? sexpr2txt($_): $$_ } @{$_[0]} ]})} }
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] ); } my @attr; do { @attr = map { roll_skip_lowest(6,4) } @attr_names; } until sum(@attr) >= $min_sum and heroic(@attr) >= $hero_count_min; printf "%s =%2d\n", $attr_names[$_], $attr[$_] for 0..$ printf "Sum =%d, with%d attributes >= $hero_attr_min\n", sum(@attr), heroic(@attr);
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 ;; rockpaper) playerWon=0 ;; rockscissors) playerWon=1 ;; paperrock) playerWon=1 ;; paperpaper) isTie=1 ;; paperscissors) playerWon=0 ;; scissorsrock) playerWon=0 ;; scissorspaper) playerWon=1 ;; scissorsscissors) isTie=1 ;; esac if [[ $isTie == 1 ]]; then echo "It's a tie!" && exit 1; fi if [[ $playerWon == 0 ]]; then echo "Sorry, $aiResponse beats $response , try again.." && exit 1; fi if [[ $playerWon == 1 ]]; then echo "Good job, $response beats $aiResponse!" && exit 1; fi
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 from typing import NamedTuple from typing import Optional from typing import Tuple from urllib.parse import urlencode from urllib.parse import urlunparse from urllib.parse import quote_plus import urllib.error import urllib.request logger = logging.getLogger(__name__) logger.setLevel(logging.DEBUG) RE_SPEC = [ (, r), (, r), (, r), (, r), (, r), ] RE_BARE_LANG = re.compile( .join(rf for name, pattern in RE_SPEC), re.DOTALL | re.IGNORECASE, ) RE_MULTI_HEADER = re.compile(r, re.IGNORECASE) def find_bare_lang_section_headers(wiki_text: str) -> Iterator[str]: current_heading = for match in RE_BARE_LANG.finditer(wiki_text): kind = match.lastgroup if kind == : current_heading = RE_MULTI_HEADER.sub(, match.group()) elif kind == : yield current_heading class Error(Exception): class TagCounter: def __init__(self): self.counter = Counter() self.pages = defaultdict(set) self.total = 0 def __len__(self): return len(self.counter) @classmethod def from_section_headers( cls, page_title: str, section_headers: Iterable[str] ) -> TagCounter: counter = cls() for heading in section_headers: counter.add(page_title, heading) return counter @classmethod def from_wiki_text(cls, page_title: str, wiki_text: str) -> TagCounter: return cls.from_section_headers( page_title, find_bare_lang_section_headers(wiki_text), ) def add(self, page_title: str, section_heading: str): self.counter[section_heading] += 1 self.pages[section_heading].add(page_title) self.total += 1 def update(self, other): assert isinstance(other, TagCounter) self.counter.update(other.counter) for section_heading, pages in other.pages.items(): self.pages[section_heading].update(pages) self.total += other.total def most_common(self, n=None) -> str: buf = [f] for section_heading, count in self.counter.most_common(n=n): pages = list(self.pages[section_heading]) buf.append(f) return .join(buf) def quote_underscore(string, safe=, encoding=None, errors=None): string = quote_plus(string, safe, encoding, errors) return string.replace(, ) class URL(NamedTuple): scheme: str netloc: str path: str params: str query: str fragment: str def __str__(self): return urlunparse(self) def with_query(self, query: Mapping[str, Any]) -> URL: query_string = urlencode(query, safe=, quote_via=quote_underscore) return self._replace(query=query_string) API_BASE_URL = URL( scheme=, netloc=, path=, params=, query=, fragment=, ) UGLY_RAW_URL = URL( scheme=, netloc=, path=, params=, query=, fragment=, ) DEFAULT_HEADERS = { : f, : , : , : , } class Response(NamedTuple): headers: Mapping[str, str] body: bytes def get(url: URL, headers=DEFAULT_HEADERS) -> Response: logger.debug(f) request = urllib.request.Request(str(url), headers=headers) try: with urllib.request.urlopen(request) as response: return Response( headers=dict(response.getheaders()), body=response.read(), ) except urllib.error.HTTPError as e: logging.debug(e.code) logging.debug(gzip.decompress(e.read())) raise def raise_for_header(headers: Mapping[str, str], header: str, expect: str): got = headers.get(header) if got != expect: raise Error(f) raise_for_content_type = functools.partial(raise_for_header, header=) class CMContinue(NamedTuple): continue_: str cmcontinue: str Pages = Tuple[List[str], Optional[CMContinue]] def get_wiki_page_titles(chunk_size: int = 500, continue_: CMContinue = None) -> Pages: query = { : , : , : , : chunk_size, : , : , } if continue_: query[] = continue_.continue_ query[] = continue_.cmcontinue response = get(API_BASE_URL.with_query(query)) raise_for_content_type(response.headers, expect=) raise_for_header(response.headers, , ) data = json.loads(gzip.decompress(response.body)) page_titles = [p[] for p in data[][]] if data.get(, {}).get(): _continue = CMContinue( data[][], data[][], ) else: _continue = None return (page_titles, _continue) def get_wiki_page_markup(page_title: str) -> str: query = {: , : page_title} response = get(UGLY_RAW_URL.with_query(query)) raise_for_content_type(response.headers, expect=) return response.body.decode() def example(limit=30): page_titles, continue_ = get_wiki_page_titles() while continue_ is not None: more_page_titles, continue_ = get_wiki_page_titles(continue_=continue_) page_titles.extend(more_page_titles) counter = TagCounter() for i, page_title in enumerate(page_titles): if i > limit: break wiki_text = get_wiki_page_markup(page_title) counts = TagCounter.from_wiki_text(page_title, wiki_text) counter.update(counts) print(counter.most_common()) if __name__ == : logging.basicConfig(format=, level=logging.DEBUG) example()
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_omit << task} [programming_tasks - lang_tasks, lang_tasks_omit] end def self.created_time(title) url = get_api_url({ => , => title, => , => 500, => , => }) doc = REXML::Document.new open(url) REXML::XPath.each(doc, ).collect do |node| Time.parse( node.attribute().value ) end.min end end puts Time.now lang = ARGV[0] || unimplemented, omitted = RosettaCode.get_unimplemented(lang) unimplemented.collect {|title| [title, RosettaCode.created_time(title)]} . sort_by {|e| e[1]} . each do |title, date| puts % [ date.strftime(), omitted.include?(title)? : , title ] end
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 (!(obj instanceof Complex)) {return false;} Complex other = (Complex) obj; return (re == other.re) && (im == other.im); } @Override public String toString() { if (im == 0.0) {return String.format("%g", re);} if (re == 0.0) {return String.format("%gi", im);} return String.format("%g%c%gi", re, (im < 0.0 ? '-' : '+'), Math.abs(im)); } } private static Complex[] quadraticRoots(double a, double b, double c) { Complex[] roots = new Complex[2]; double d = b * b - 4.0 * a * c;
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 Quick Brown Fox Jumped Over The Lazy Dog!")) (let [A (into #{} "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ") Am (->> (cycle A) (drop 26) (take 52) (zipmap A))] (defn rot13 [^String in] (apply str (map #(Am % %) in)))) (rot13 "The Quick Brown Fox Jumped Over The Lazy Dog!")
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); $total = array_sum($rolls); if($total >= 15) { $count += 1; } $attributes[] = $total; } $attributesTotal = array_sum($attributes); } print_r($attributes);
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 Root(angle) ) return rs } for (var n=2; n<8; n+=1) { document.write(n, ': ') var rs=roots(n); for (var i=0; i<rs.length; i+=1) document.write( i ? ', ' : '', rs[i].toFixed(5) ) document.write('<br>') }
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/ /_/; my $response = HTTP::Tiny->new->get("$site/wiki/$slug"); my $count = () = $response->{content} =~ /toclevel-1/g; print "$_: $count examples\n"; }
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>.+)\}\}==/ =~ line num_no_langs = line.scan(/<lang\s*>/).size if num_no_langs > 0 then result[current_lang].count += num_no_langs result[current_lang].tasks << task end end end puts result.each{|k,v| puts }
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 class Solution(val x1: Any, val x2: Any) { override fun toString() = when(x1) { x2 -> "X1,2 = $x1" else -> "X1 = $x1, X2 = $x2" } } val quadraticRoots by lazy { val _2a = a + a val d = b * b - 4.0 * a * c
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)\nParsed to Python:\nThen back to: '%s'"% print_sexp(parsed))
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, 1./3, 1./3 }; while (1) { my_action = rand_idx(p,LEN); printf( ); if (!scanf(, &user_action)) { scanf(, str); if (*str == 'q') { printf(,user_rec[0],user_rec[1], user_rec[2]); return 0; } continue; } user_action --; if (user_action > 2 || user_action < 0) { printf(); continue; } printf(, names[user_action], names[my_action], winner[(my_action - user_action + 3) % 3]); user_rec[user_action]++; } }
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() var r = cos(a); if (abs(r) < 1e-6) r = 0.0 var i = sin(a); if (abs(i) < 1e-6) i = 0.0 Complex(r, i) } fun main(args: Array<String>) { (1..4).forEach { println(listOf(1) + unity_roots(it)) } println(listOf(1) + unity_roots(5.0)) }
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:]]+)\}\}==").unwrap(); for line in input.lines() { if let Some(captures) = header_re.captures(line) { if let Some(header_lang) = captures.name("lang") { language_pairs.push((language, counter)); language = Some(header_lang.as_str().to_owned()); counter = 0; } } if line.contains("<lang>") { counter += 1; } } language_pairs.push((language, counter)); language_pairs } fn main() { let stdin = io::stdin(); let mut buf = String::new(); stdin.lock().read_to_string(&mut buf).unwrap(); let results = find_bare_lang_tags(&buf); let total_bare = results.iter().map(|r| r.1).sum::<i32>(); println!("{} bare language tags.\n", total_bare); for result in &results { let num_bare = result.1; if num_bare > 0 { println!( "{} in {}", result.1, result .0 .to_owned() .unwrap_or_else(|| String::from("no language")) ); } } }
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[2] + $dy[3]) / 6; } } my $RK = runge_kutta sub { $_[0] * sqrt $_[1] }, .1; for( my ($t, $y) = (0, 1); sprintf("%.0f", $t) <= 10; ($t, $y) = $RK->($t, $y) ) { printf "y(%2.0f) =%12f %e\n", $t, $y, abs($y - ($t**2 + 4)**2 / 16) if sprintf("%.4f", $t) =~ /0000$/; }
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(rolls) largest_3 = sorted_rolls[1:] rolls_total = sum(largest_3) if rolls_total >= 15: count += 1 attributes.append(rolls_total) attributes_total = sum(attributes) print(attributes_total, attributes)
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: headers={'User-Agent': 'Mozilla/5.0'}) y = urlopen(r) tasks.append( y.read().lower().count(b'{{header|') ) print(t.replace('_', ' ') + f': {tasks[-1]} examples.') print(f'\nTotal: {sum(tasks)} examples.')
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 (i in 1:length(titles)){ headers[[i]] <- getURL( paste("http://rosettacode.org/mw/index.php?title=", gsub(" ", "_", titles[i]), "&action=raw", sep="") ) counts[[i]] <- strsplit(headers[[i]],split=" ")[[1]] counts[[i]] <- grep("\\{\\{header", counts[[i]]) cat(titles[i], ":", length(counts[[i]]), "examples\n") } cat("Total: ", length(unlist(counts)), "examples\n")
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:Programming Languages', gcmlimit => 250, prop => 'categoryinfo', gcmcontinue => $gcmcontinue } ); push @languages, values %{ $apih->{'query'}{'pages'} }; last if not $gcmcontinue = $apih->{'continue'}{'gcmcontinue'}; } for (@languages) { $_->{'title'} =~ s/Category://; $_->{'categoryinfo'}{'size'} //= 0; } my @sorted_languages = reverse sort { $a->{'categoryinfo'}{'size'} <=> $b->{'categoryinfo'}{'size'} } @languages; binmode STDOUT, ':encoding(utf8)'; my $n = 1; for (@sorted_languages) { printf "%3d.%20s -%3d\n", $n++, $_->{'title'}, $_->{'categoryinfo'}{'size'}; }
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(genStats())
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 case char when tokens << :lbr when tokens << :rbr when /\s/ when '' tokens << word state = :token_start else word << char end when :read_string_or_number case char when /\s/ tokens << symbol_or_number(word) state = :token_start when ')' tokens << symbol_or_number(word) tokens << :rbr state = :token_start else word << char end end end sexpr_tokens_to_array(tokens) end def symbol_or_number(word) Integer(word) rescue ArgumentError begin Float(word) rescue ArgumentError word.to_sym end end def sexpr_tokens_to_array(tokens, idx = 0) result = [] while idx < tokens.length case tokens[idx] when :lbr tmp, idx = sexpr_tokens_to_array(tokens, idx + 1) result << tmp when :rbr return [result, idx] else result << tokens[idx] end idx += 1 end result[0] end end class Object def to_sexpr self end end class String def to_sexpr self.match(/[\s()]/)? self.inspect: self end end class Symbol alias :to_sexpr :to_s end class Array def to_sexpr % inject([]) {|a, elem| a << elem.to_sexpr}.join() end end sexpr = SExpr.new <<END ((data 123 4.5) (data (!@ END puts puts puts
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,v| % [CGI.escape(k.to_s), CGI.escape(v.to_s)]}.join() end url = p url if $DEBUG url end def self.get_api_url(query) get_url , query end def self.category_members(category) query = { => , => , => , => , => 500, } while true url = get_api_url query doc = REXML::Document.new open(url) REXML::XPath.each(doc, ) do |task| yield task.attribute().value end continue = REXML::XPath.first(doc, ) break if continue.nil? cm = REXML::XPath.first(continue, ) query[] = cm.attribute().value end end end
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 = h * f(x + h, y + k3) vx[i] = x = x0 + i * h vy[i] = y = y + (k1 + k2 + k2 + k3 + k3 + k4) / 6 return vx, vy def f(x, y): return x * sqrt(y) vx, vy = rk4(f, 0, 1, 10, 100) for x, y in list(zip(vx, vy))[::10]: print(% (x, y, y - (4 + x * x)**2 / 16)) 0.0 1.00000 +0.0000e+00 1.0 1.56250 -1.4572e-07 2.0 4.00000 -9.1948e-07 3.0 10.56250 -2.9096e-06 4.0 24.99999 -6.2349e-06 5.0 52.56249 -1.0820e-05 6.0 99.99998 -1.6595e-05 7.0 175.56248 -2.3518e-05 8.0 288.99997 -3.1565e-05 9.0 451.56246 -4.0723e-05 10.0 675.99995 -5.0983e-05
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 + 1] <- x <- x0 + i*h vy[i + 1] <- y <- y + (k1 + k2 + k2 + k3 + k3 + k4)/6 } cbind(vx, vy) } sol <- rk4(function(x, y) x*sqrt(y), 0, 1, 10, 100) cbind(sol, sol[, 2] - (4 + sol[, 1]^2)^2/16)[seq(1, 101, 10), ] vx vy [1,] 0 1.000000 0.000000e+00 [2,] 1 1.562500 -1.457219e-07 [3,] 2 3.999999 -9.194792e-07 [4,] 3 10.562497 -2.909562e-06 [5,] 4 24.999994 -6.234909e-06 [6,] 5 52.562489 -1.081970e-05 [7,] 6 99.999983 -1.659460e-05 [8,] 7 175.562476 -2.351773e-05 [9,] 8 288.999968 -3.156520e-05 [10,] 9 451.562459 -4.072316e-05 [11,] 10 675.999949 -5.098329e-05
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, members) in enumerate(sorted(members, key=lambda x: -int(x[1]))[:15]): if language in languages: print(.format(cnt+1, int(members), language))
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) { language <- xml_node %>% html_attr("title") language <- sub("^Category:", "", language) npages <- xml_node %>% html_nodes('categoryinfo') %>% html_attr("pages") c(language, npages) } tbl <- ldply(sapply(langs, ff), rbind) names(tbl) <- c("language", "n") tbl %>% mutate(n=as.integer(n)) %>% arrange(desc(n)) %>% head
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, upper) r, status := secant(f, x0, x1) if status != "" && r >= x0 && r < x1 { fmt.Printf(" %6.3f%s\n", r, status) } } } func secant(f func(float64) float64, x0, x1 float64) (float64, string) { var f0 float64 f1 := f(x0) for i := 0; i < 100; i++ { f0, f1 = f1, f(x1) switch { case f1 == 0: return x1, "exact" case math.Abs(x1-x0) < 1e-6: return x1, "approximate" } x0, x1 = x1, x1-f1*(x1-x0)/(f1-f0) } return 0, "" }
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 ))}.call( dt * f.call( t , y ))} end TIME_MAXIMUM, WHOLE_TOLERANCE = 10.0, 1.0e-5 T_START, Y_START, DT = 0.0, 1.0, 0.10 def my_diff_eqn(t,y); t * Math.sqrt(y) ; end def my_solution(t ); (t**2 + 4)**2 / 16 ; end def find_error(t,y); (y - my_solution(t)).abs ; end def is_whole?(t ); (t.round - t).abs < WHOLE_TOLERANCE; end dy = calc_rk4( ->(t,y){my_diff_eqn(t,y)} ) t, y = T_START, Y_START while t <= TIME_MAXIMUM printf(,t,y,find_error(t,y)) if is_whole?(t) t, y = t + DT, y + dy.call(t,y,DT) end
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.mkString("[",",", "]")) (attrs.sum, attrs.filter(_>15).size) match { case (a, b) if (a < 75 || b < 2) => getCharacter case _ => attrs } } println("picked => " + getCharacter.mkString("[", ",", "]"))
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); bigger = roman; while (VALUE(*bigger) <= current && *++bigger != '\0'); if (*bigger == '\0') arabic += current; else { arabic += VALUE(*bigger); while (roman < bigger) arabic -= VALUE(* (roman++) ); } roman ++; } return arabic; } int main() { const char * romans[] = { , , , }; int i; for (i = 0; i < 4; i++) printf(, romans[i], decode(romans[i])); return 0; }
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) -> f64 { x * y.sqrt() } fn actual(x: f64) -> f64 { (1.0 / 16.0) * (x * x + 4.0).powi(2) } fn main() { let mut y = 1.0; let mut x = 0.0; let step = 0.1; let max_steps = 101; let sample_every_n = 10; for steps in 0..max_steps { if steps% sample_every_n == 0 { println!("y({}):\t{:.10}\t\t {:E}", x, y, actual(x) - y) } y = runge_kutta4(&f, x, y, step); x = ((x * 10.0) + (step * 10.0)) / 10.0; } }
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' if ( self.pureImag() and self.pureReal() ) else rp + conj + ip def pureImag(self): return abs(self.real) < 0.000005 def pureReal(self): return abs(self.imag) < 0.000005 def croots(n): if n <= 0: return None return (Complex(cmath.rect(1, 2 * k * cmath.pi / n)) for k in range(n)) for nr in range(2, 11): print(nr, list(croots(nr)))
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: return , abs(root1), abs(root1) if discriminant > 0: return , root1.real, root2.real return , root1, root2 def middlebrook(a, b, c): try: q = math.sqrt(a*c)/b f = .5+ math.sqrt(1-4*q*q)/2 except ValueError: q = cmath.sqrt(a*c)/b f = .5+ cmath.sqrt(1-4*q*q)/2 return (-b/a)*f, -c/(b*f) def whatevery(a, b, c): try: d = math.sqrt(b*b-4*a*c) except ValueError: d = cmath.sqrt(b*b-4*a*c) if b > 0: return div(2*c, (-b-d)), div((-b-d), 2*a) else: return div((-b+d), 2*a), div(2*c, (-b+d)) def div(n, d): try: return n/d except ZeroDivisionError: if n: return n*float('inf') return float('nan') testcases = [ (3, 4, 4/3), (3, 2, -1), (3, 2, 1), (1, -1e9, 1), (1, -1e100, 1), (1, -1e200, 1), (1, -1e300, 1), ] print('Naive:') for c in testcases: print(.format(*quad_discriminating_roots(*c))) print('\nMiddlebrook:') for c in testcases: print((*2).format(*middlebrook(*c))) print('\nWhat Every...') for c in testcases: print((*2).format(*whatevery(*c))) print('\nNumpy:') for c in testcases: print((*2).format(*numpy.roots(c)))
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; double y = f.f(x), oy = y; int s = sign(y), os = s; for (; x <= upperBound ; x += step) { s = sign(y = f.f(x)); if (s == 0) { System.out.println(x); } else if (s != os) { double dx = x - ox; double dy = y - oy; double cx = x - dx * (y / dy); System.out.println("~" + cx); } ox = x; oy = y; os = s; } } public static void main(String[] args) { Function poly = new Function () { public double f(double x) { return x*x*x - 3*x*x + 2*x; } }; printRoots(poly, -1.0, 4, 0.002); } }
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]); N -= arabic[i]; } } return 0; }
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] (->> s .toUpperCase (map numerals) (reduce (fn [[sum lastv] curr] [(+ sum curr (if (< lastv curr) (* -2 lastv) 0)) curr]) [0,0]) first))
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 -> decoded.append(matcher[2] * Integer.parseInt(matcher[1])) } decoded.toString() }
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 = [Double]() var x: Double = 0.0 var y2: Double = 0.0 var x0: Double = 0.0 var x1: Double = 10.0 var dx: Double = 0.1 var i = 0 var n = Int(1 + (x1 - x0) / dx) y.append(1) for i in 1..<n { y.append(rk4(dx, x: x0 + dx * (Double(i) - 1), y: y[i - 1]) { (x: Double, y: Double) -> Double in return x * sqrt(y) }) } print(" x y rel. err.") print("------------------------------") for (var i = 0; i < n; i += 10) { x = x0 + dx * Double(i) y2 = pow(x * x / 4 + 1, 2) print(String(format: "%2g %11.6g %11.5g", x, y[i], y[i]/y2 - 1)) }
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 = page.attribute().value info = REXML::XPath.first(page, ) langcount[lang] = info.nil?? 0: info.attribute().value.to_i end end puts Time.now puts puts langcount.sort_by {|key,val| val}.reverse[0,25].each_with_index do |(lang, count), i| puts end
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 s as your play. Anything else ends the game.") fmt.Println("Running score shown as <your wins>:<my wins>") var pi string
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 = "WWWWWWWWWWWWBWWWWWWWWWWWWBBBWWWWWWWWWWWWWWWWWWWWWWWWBWWWWWWWWWWWWWW" encoded = rlencode input decoded = rldecode encoded putStrLn $ "Encoded: " <> show encoded <> "\nDecoded: " <> show decoded
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"; } else { print "$needle is not in haystack\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 x | x <= s = Rock | x <= s + r = Paper | otherwise = Scissors rand = randomRIO (1, r + p + s) :: IO Int getrps :: IO Choice getrps = rps <$> getLine where rps "scissors" = Scissors rps "rock" = Rock rps "paper" = Paper rps _ = error "invalid input" game :: (Int, Int, Int) -> IO a game (r, p, s) = do putStrLn "rock, paper or scissors?" h <- getrps c <- genrps (r, p, s) putStrLn ("Player: " ++ show h ++ " Computer: " ++ show c) putStrLn (if beats h c then "player wins\n" else if beats c h then "player loses\n" else "draw\n") let rr = if h == Rock then r + 1 else r pp = if h == Paper then p + 1 else p ss = if h == Scissors then s + 1 else s game (rr, pp, ss) main :: IO a main = game (1, 1, 1)
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, 15) p quadratic(1, -2, 1) p quadratic(1, 3, 3)
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() && source.charAt(i) == source.charAt(i+1)) { runLength++; i++; } dest.append(runLength); dest.append(source.charAt(i)); } return dest.toString(); } public static String decode(String source) { StringBuffer dest = new StringBuffer(); Pattern pattern = Pattern.compile("[0-9]+|[a-zA-Z]"); Matcher matcher = pattern.matcher(source); while (matcher.find()) { int number = Integer.parseInt(matcher.group()); matcher.find(); while (number-- != 0) { dest.append(matcher.group()); } } return dest.toString(); } public static void main(String[] args) { String example = "WWWWWWWWWWWWBWWWWWWWWWWWWBBBWWWWWWWWWWWWWWWWWWWWWWWWBWWWWWWWWWWWWWW"; System.out.println(encode(example)); System.out.println(decode("1W1B1W1B1W1B1W1B1W1B1W1B1W1B")); } }
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 ++; } encoding.push([count, prev]); return encoding; }
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(other); } static { SCISSORS.losesToList = Arrays.asList(ROCK); ROCK.losesToList = Arrays.asList(PAPER); PAPER.losesToList = Arrays.asList(SCISSORS); } }
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.choice].w === PlayerTwo.choice; } } const p1 = new Player('Chris'); const p2 = new Player('John'); p1.setChoice('rock'); p2.setChoice('scissor'); p1.challengeOther(p2);
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<String>) { assert(runLengthEncoding("TTESSST") == "2T1E3S1T") assert(runLengthEncoding("WWWWWWWWWWWWBWWWWWWWWWWWWBBBWWWWWWWWWWWWWWWWWWWWWWWWBWWWWWWWWWWWWWW") == "12W1B12W3B24W1B14W") }
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(rot13char, s) } func main() { fmt.Println(rot13("nowhere ABJURER")) }
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 t = ret return table.concat(ret) end q = io.read() print(compress(astable:match(q))) undo = Ct((Cf(Cc"0" * C(R"09")^1, function(a, b) return 10 * a + b end) * C(R"AZ"))^0) function decompress(s) t = undo:match(s) local ret = "" for i = 1, #t - 1, 2 do for _ = 1, t[i] do ret = ret .. t[i+1] end end return ret 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 ) { $value = &f($x); if ( 0 == $value ) { print "Root found at $x\n"; } elsif ( ( $value > 0 ) != $sign ) { print "Root found near $x\n"; } $sign = ( $value > 0 ); }
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 } }.inject ("") { string, ch -> string += 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