code stringlengths 1 46.1k ⌀ | label class label 1.18k
classes | domain_label class label 21
classes | index stringlengths 4 5 |
|---|---|---|---|
public struct Point: Equatable, Hashable {
public var x: Double
public var y: Double
public init(fromTuple t: (Double, Double)) {
self.x = t.0
self.y = t.1
}
}
public func calculateConvexHull(fromPoints points: [Point]) -> [Point] {
guard points.count >= 3 else {
return points
}
var hull = ... | 1,002Convex hull | 17swift | t9ufl |
use threads;
use Time::HiRes qw(sleep);
$_->join for map {
threads->create(sub {
sleep rand;
print shift, "\n";
}, $_)
} qw(Enjoy Rosetta Code); | 1,006Concurrent computing | 2perl | yvu6u |
my $tenfactorial;
print "$tenfactorial\n";
BEGIN
{$tenfactorial = 1;
$tenfactorial *= $_ foreach 1 .. 10;} | 1,008Compile-time calculation | 2perl | wo8e6 |
data class Point(var x: Int, var y: Int)
fun main(args: Array<String>) {
val p = Point(1, 2)
println(p)
p.x = 3
p.y = 4
println(p)
} | 1,007Compound data type | 11kotlin | 8tt0q |
original =
reference = original
copy1 = original.dup
copy2 = String.new(original)
original <<
p reference
p copy1
p copy2 | 997Copy a string | 14ruby | bxtkq |
fn main() {
let s1 = "A String";
let mut s2 = s1;
s2 = "Another String";
println!("s1 = {}, s2 = {}", s1, s2);
} | 997Copy a string | 15rust | pqzbu |
val src = "Hello" | 997Copy a string | 16scala | e8yab |
import asyncio
async def print_(string: str) -> None:
print(string)
async def main():
strings = ['Enjoy', 'Rosetta', 'Code']
coroutines = map(print_, strings)
await asyncio.gather(*coroutines)
if __name__ == '__main__':
asyncio.run(main()) | 1,006Concurrent computing | 3python | mu5yh |
a = {x = 1; y = 2}
b = {x = 3; y = 4}
c = {
x = a.x + b.x;
y = a.y + b.y
}
print(a.x, a.y) | 1,007Compound data type | 1lua | ozz8h |
fn factorial(n: i64) -> i64 {
let mut total = 1;
for i in 1..n+1 {
total *= i;
}
return total;
}
fn main() {
println!("Factorial of 10 is {}.", factorial(10));
} | 1,008Compile-time calculation | 15rust | 0fdsl |
object Main extends {
val tenFactorial = 10 * 9 * 8 * 7 * 6 * 5 * 4 * 3 * 2
def tenFac = 10 * 9 * 8 * 7 * 6 * 5 * 4 * 3 * 2
println(s"10! = $tenFactorial", tenFac)
} | 1,008Compile-time calculation | 16scala | i3zox |
>>> from collections import defaultdict
>>> from random import choice
>>> world = defaultdict(int)
>>> possiblepoints = [(x,y) for x in range(-15,16)
for y in range(-15,16)
if 10 <= abs(x+y*1j) <= 15]
>>> for i in range(100): world[choice(possiblepoints)] += 1
>>> for x in range(-15,16):
print(''.join(str(min... | 1,003Constrained random points on a circle | 3python | n6ciz |
%w{Enjoy Rosetta Code}.map do |x|
Thread.new do
sleep rand
puts x
end
end.each do |t|
t.join
end | 1,006Concurrent computing | 14ruby | c4g9k |
int _qy_
int _qy_
name = realloc(name, (_qy_
typedef enum {
nd_Ident, nd_String, nd_Integer, nd_Sequence, nd_If, nd_Prtc, nd_Prts, nd_Prti, nd_While,
nd_Assign, nd_Negate, nd_Not, nd_Mul, nd_Div, nd_Mod, nd_Add, nd_Sub, nd_Lss, nd_Leq,
nd_... | 1,009Compiler/AST interpreter | 5c | wo0ec |
RMin <- 10
RMax <- 15
NPts <- 100
nBlock <- NPts * ((RMax/RMin) ^ 2)
nValid <- 0
while (nValid < NPts) {
X <- round(runif(nBlock, -RMax - 1, RMax + 1))
Y <- round(runif(nBlock, -RMax - 1, RMax + 1))
R <- sqrt(X^2 + Y^2)
Valid <- ( (R >= RMin) & (R <= RMax) )
nValid <- sum(Valid)
nBlock <- 2 * nBlock
}
plot(X[... | 1,003Constrained random points on a circle | 13r | 0f6sg |
extern crate rand;
use std::thread;
use rand::thread_rng;
use rand::distributions::{Range, IndependentSample};
fn main() {
let mut rng = thread_rng();
let rng_range = Range::new(0u32, 100);
for word in "Enjoy Rosetta Code".split_whitespace() {
let snooze_time = rng_range.ind_sample(&mut rng);
... | 1,006Concurrent computing | 15rust | lgrcc |
import scala.actors.Futures
List("Enjoy", "Rosetta", "Code").map { x =>
Futures.future {
Thread.sleep((Math.random * 1000).toInt)
println(x)
}
}.foreach(_()) | 1,006Concurrent computing | 16scala | ujhv8 |
import Foundation
let myList = ["Enjoy", "Rosetta", "Code"]
for word in myList {
dispatch_async(dispatch_get_global_queue(0, 0)) {
NSLog(word)
}
}
dispatch_main() | 1,006Concurrent computing | 17swift | 954mj |
var src = "Hello"
var dst = src | 997Copy a string | 17swift | kwfhx |
typedef enum {
tk_EOI, tk_Mul, tk_Div, tk_Mod, tk_Add, tk_Sub, tk_Negate, tk_Not, tk_Lss, tk_Leq, tk_Gtr,
tk_Geq, tk_Eql, tk_Neq, tk_Assign, tk_And, tk_Or, tk_If, tk_Else, tk_While, tk_Print,
tk_Putc, tk_Lparen, tk_Rparen, tk_Lbrace, tk_Rbrace, tk_Semi, tk_Comma, tk_Ident,
tk_Integer, tk_String
} TokenT... | 1,010Compiler/syntax analyzer | 5c | c4v9c |
package main
import (
"bufio"
"fmt"
"log"
"os"
"strconv"
"strings"
)
type NodeType int
const (
ndIdent NodeType = iota
ndString
ndInteger
ndSequence
ndIf
ndPrtc
ndPrts
ndPrti
ndWhile
ndAssign
ndNegate
ndNot
ndMul
ndDiv
ndMod
ndAd... | 1,009Compiler/AST interpreter | 0go | c4u9g |
points = (1..100).map do
angle = rand * 2.0 * Math::PI
rad = rand * 5.0 + 10.0
[rad * Math::cos(angle), rad * Math::sin(angle)].map(&:round)
end
(-15..15).each do |row|
puts (-15..15).map { |col| points.include?([row, col])? : }.join
end
load 'raster_graphics.rb'
pixmap = Pixmap.new(321,321)
pixmap.... | 1,003Constrained random points on a circle | 14ruby | fm2dr |
int _qy_
int _qy_
name = realloc(name, (_qy_
typedef unsigned char uchar;
typedef uchar code;
typedef enum { FETCH, STORE, PUSH, ADD, SUB, MUL, DIV, MOD, LT, GT, LE, GE, EQ, NE, AND,
OR, NEG, NOT, JMP, JZ, PRTC, PRTS, PRTI, HALT
} Code_t;
typed... | 1,011Compiler/virtual machine interpreter | 5c | lgvcy |
import java.util.Scanner;
import java.io.File;
import java.util.List;
import java.util.ArrayList;
import java.util.Map;
import java.util.HashMap;
class Interpreter {
static Map<String, Integer> globals = new HashMap<>();
static Scanner s;
static List<Node> list = new ArrayList<>();
static Map<String, NodeType> str... | 1,009Compiler/AST interpreter | 9java | rpkg0 |
extern crate rand;
use rand::Rng;
const POINTS_N: usize = 100;
fn generate_point<R: Rng>(rng: &mut R) -> (i32, i32) {
loop {
let x = rng.gen_range(-15, 16); | 1,003Constrained random points on a circle | 15rust | t9vfd |
void setfillconst(double c);
void fillwithconst(double *v, int n);
void fillwithrrange(double *v, int n);
void shuffledrange(double *v, int n); | 1,012Compare sorting algorithms' performance | 5c | zc3tx |
int cmp(const int* a, const int* b)
{
return *b - *a;
}
void compareAndReportStringsLength(const char* strings[], const int n)
{
if (n > 0)
{
char* has_length = ;
char* predicate_max = ;
char* predicate_min = ;
char* predicate_ave = ;
int* si = malloc(2 * n * sizeo... | 1,013Compare length of two strings | 5c | 62632 |
package main
import (
"bufio"
"fmt"
"log"
"os"
"strconv"
"strings"
)
type TokenType int
const (
tkEOI TokenType = iota
tkMul
tkDiv
tkMod
tkAdd
tkSub
tkNegate
tkNot
tkLss
tkLeq
tkGtr
tkGeq
tkEql
tkNeq
tkAssign
tkAnd
tkOr
t... | 1,010Compiler/syntax analyzer | 0go | woseg |
import java.awt.{ Color, geom,Graphics2D ,Rectangle}
import scala.math.hypot
import scala.swing.{MainFrame,Panel,SimpleSwingApplication}
import scala.swing.Swing.pair2Dimension
import scala.util.Random
object CirculairConstrainedRandomPoints extends SimpleSwingApplication { | 1,003Constrained random points on a circle | 16scala | 62431 |
use strict;
use warnings;
use integer;
my %variables;
tree()->run;
sub tree
{
my $line = <> // die "incomplete tree\n";
(local $_, my $arg) = $line =~ /^(\w+|;)\s+(.*)/ or die "bad input $line";
/String/ ? bless [$arg =~ tr/""//dr =~ s/\\(.)/$1 eq 'n' ? "\n" : $1/ger], $_ :
/Identifier|Integer/ ? ble... | 1,009Compiler/AST interpreter | 2perl | 0fns4 |
void show(void *u, int w, int h)
{
int (*univ)[w] = u;
printf();
for_y {
for_x printf(univ[y][x] ? : );
printf();
}
fflush(stdout);
}
void evolve(void *u, int w, int h)
{
unsigned (*univ)[w] = u;
unsigned new[h][w];
for_y for_x {
int n = 0;
for (int y1 = y - 1; y1 <= y + 1; y1++)
for (int x1 = x -... | 1,014Conway's Game of Life | 5c | l49cy |
my @point = (3, 8); | 1,007Compound data type | 2perl | 4kk5d |
typedef unsigned char uchar;
typedef enum {
nd_Ident, nd_String, nd_Integer, nd_Sequence, nd_If, nd_Prtc, nd_Prts, nd_Prti, nd_While,
nd_Assign, nd_Negate, nd_Not, nd_Mul, nd_Div, nd_Mod, nd_Add, nd_Sub, nd_Lss, nd_Leq,
nd_Gtr, nd_Geq, nd_Eql, nd_Neq, nd_And, nd_Or
} NodeType;
typedef enum { FETCH, STORE,... | 1,015Compiler/code generator | 5c | 7p4rg |
$point = pack(, 1, 2);
$u = unpack(, $point);
echo $x;
echo $y;
list($x,$y) = unpack(, $point);
echo $x;
echo $y; | 1,007Compound data type | 12php | i33ov |
package main
import (
"log"
"math/rand"
"testing"
"time"
"github.com/gonum/plot"
"github.com/gonum/plot/plotter"
"github.com/gonum/plot/plotutil"
"github.com/gonum/plot/vg"
) | 1,012Compare sorting algorithms' performance | 0go | kwbhz |
from __future__ import print_function
import sys, shlex, operator
nd_Ident, nd_String, nd_Integer, nd_Sequence, nd_If, nd_Prtc, nd_Prts, nd_Prti, nd_While, \
nd_Assign, nd_Negate, nd_Not, nd_Mul, nd_Div, nd_Mod, nd_Add, nd_Sub, nd_Lss, nd_Leq, \
nd_Gtr, nd_Geq, nd_Eql, nd_Neq, nd_And, nd_Or = range(25)
all_syms =... | 1,009Compiler/AST interpreter | 3python | 8td0o |
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
import java.util.StringTokenizer;
import java.util.List;
import java.util.ArrayList;
import java.util.Map;
import java.util.HashMap;
class Parser {
private List<Token> source;
private Token token;
private int position;
static cla... | 1,010Compiler/syntax analyzer | 9java | n6tih |
let nPoints = 100
func generatePoint() -> (Int, Int) {
while true {
let x = Int.random(in: -15...16)
let y = Int.random(in: -15...16)
let r2 = x * x + y * y
if r2 >= 100 && r2 <= 225 {
return (x, y)
}
}
}
func filteringMethod() {
var rows = [[String]](repeating: Array(repeating: " ", ... | 1,003Constrained random points on a circle | 17swift | dylnh |
package main
import (
"bufio"
"encoding/binary"
"fmt"
"log"
"math"
"os"
"strconv"
"strings"
)
type code = byte
const (
fetch code = iota
store
push
add
sub
mul
div
mod
lt
gt
le
ge
eq
ne
and
or
neg
not
jmp
... | 1,011Compiler/virtual machine interpreter | 0go | xiswf |
import Data.Time.Clock
import Data.List
type Time = Integer
type Sorter a = [a] -> [a]
timed :: IO a -> IO (a, Time)
timed prog = do
t0 <- getCurrentTime
x <- prog
t1 <- x `seq` getCurrentTime
return (x, ceiling $ 1000000 * diffUTCTime t1 t0)
test :: [a] -> Sorter a -> IO [(Int, Time)]
test set srt = mapM ... | 1,012Compare sorting algorithms' performance | 8haskell | n6die |
package xyz.hyperreal.rosettacodeCompiler
import scala.collection.mutable
import scala.io.Source
object ASTInterpreter {
def fromStdin = fromSource(Source.stdin)
def fromString(src: String) = fromSource(Source.fromString(src))
def fromSource(s: Source) = {
val lines = s.getLines
def load: Node =
... | 1,009Compiler/AST interpreter | 16scala | t9yfb |
(defn moore-neighborhood [[x y]]
(for [dx [-1 0 1]
dy [-1 0 1]
:when (not (= [dx dy] [0 0]))]
[(+ x dx) (+ y dy)]))
(defn step [set-of-cells]
(set (for [[cell count] (frequencies (mapcat moore-neighborhood set-of-cells))
:when (or (= 3 count)
(and (= 2 count)... | 1,014Conway's Game of Life | 6clojure | 4hu5o |
package main
import (
"fmt"
"regexp"
"strings"
)
var reg = regexp.MustCompile(`(\.[0-9]+|[1-9]([0-9]+)?(\.[0-9]+)?)`)
func reverse(s string) string {
r := []rune(s)
for i, j := 0, len(r)-1; i < len(r)/2; i, j = i+1, j-1 {
r[i], r[j] = r[j], r[i]
}
return string(r)
}
func commatiz... | 1,016Commatizing numbers | 0go | j147d |
package main
import (
"bufio"
"encoding/binary"
"fmt"
"log"
"os"
"strconv"
"strings"
)
type NodeType int
const (
ndIdent NodeType = iota
ndString
ndInteger
ndSequence
ndIf
ndPrtc
ndPrts
ndPrti
ndWhile
ndAssign
ndNegate
ndNot
ndMul
nd... | 1,015Compiler/code generator | 0go | d6one |
function swap(a, i, j){
var t = a[i]
a[i] = a[j]
a[j] = t
} | 1,012Compare sorting algorithms' performance | 10javascript | i3nol |
task s1 s2 = do
let strs = if length s1 > length s2 then [s1, s2] else [s2, s1]
mapM_ (\s -> putStrLn $ show (length s) ++ "\t" ++ show s) strs | 1,013Compare length of two strings | 8haskell | fmfd1 |
X, Y = 0, 1
p = (3, 4)
p = [3, 4]
print p[X] | 1,007Compound data type | 3python | gbb4h |
#!/usr/bin/env runhaskell
import Control.Monad (forM_)
import Data.Char (isDigit)
import Data.List (intercalate)
import Data.Maybe (fromMaybe)
isDigitOrPeriod :: Char -> Bool
isDigitOrPeriod '.' = True
isDigitOrPeriod c = isDigit c
chopUp :: Int -> String -> [String]
chopUp _ [] = []
chopUp by str
| by < 1 = [st... | 1,016Commatizing numbers | 8haskell | otq8p |
null | 1,012Compare sorting algorithms' performance | 11kotlin | 1sapd |
package stringlensort;
import java.io.PrintStream;
import java.util.Arrays;
import java.util.Comparator;
public class ReportStringLengths {
public static void main(String[] args) {
String[] list = {"abcd", "123456789", "abcdef", "1234567"};
String[] strings = args.length > 0 ? args : list;
... | 1,013Compare length of two strings | 9java | 0f0se |
import java.io.File;
import java.util.*;
import java.util.regex.*;
public class CommatizingNumbers {
public static void main(String[] args) throws Exception {
commatize("pi=3.14159265358979323846264338327950288419716939937510582"
+ "097494459231", 6, 5, " ");
commatize("The author... | 1,016Commatizing numbers | 9java | w8pej |
static bool
strings_are_equal(const char **strings, size_t nstrings)
{
for (size_t i = 1; i < nstrings; i++)
if (strcmp(strings[0], strings[i]) != 0)
return false;
return true;
}
static bool
strings_are_in_ascending_order(const char **strings, size_t nstrings)
{
for (size_t i = 1; i < n... | 1,017Compare a list of strings | 5c | 0dest |
void perm(mpz_t out, int n, int k)
{
mpz_set_ui(out, 1);
k = n - k;
while (n > k) mpz_mul_ui(out, out, n--);
}
void comb(mpz_t out, int n, int k)
{
perm(out, n, k);
while (k) mpz_divexact_ui(out, out, k--);
}
int main(void)
{
mpz_t x;
mpz_init(x);
perm(x, 1000, 969);
gmp_printf(, x);
comb(x, 1000, 969);
... | 1,018Combinations and permutations | 5c | d6snv |
package codegenerator;
import java.io.File;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Scanner;
public class CodeGenerator {
final static int WORDSIZE = 4;
static byte[] code = {};
static Map<String, NodeTy... | 1,015Compiler/code generator | 9java | 9u6mu |
function compareStringsLength(input, output) { | 1,013Compare length of two strings | 10javascript | dydnu |
use strict;
use warnings;
my $h = qr/\G\s*\d+\s+\d+\s+/;
sub error { die "*** Expected @_ at " . (/\G(.*\n)/ ?
$1 =~ s/^\s*(\d+)\s+(\d+)\s+/line $1 character $2 got /r : "EOF\n") }
sub want { /$h \Q$_[1]\E.*\n/gcx ? shift : error "'$_[1]'" }
local $_ = join '', <>;
print want stmtlist(), 'End_of_input';
su... | 1,010Compiler/syntax analyzer | 2perl | ujgvr |
mypoint <- list(x=3.4, y=6.7)
mypoint$x
list(a=1:10, b="abc", c=runif(10), d=list(e=1L, f=TRUE)) | 1,007Compound data type | 13r | v7727 |
null | 1,016Commatizing numbers | 11kotlin | bw7kb |
(every? (fn [[a nexta]] (= a nexta)) (map vector strings (rest strings))))
(every? (fn [[a nexta]] (<= (compare a nexta) 0)) (map vector strings (rest strings)))) | 1,017Compare a list of strings | 6clojure | d60nb |
int _qy_
int _qy_
name = realloc(name, (_qy_
typedef enum {
tk_EOI, tk_Mul, tk_Div, tk_Mod, tk_Add, tk_Sub, tk_Negate, tk_Not, tk_Lss, tk_Leq,
tk_Gtr, tk_Geq, tk_Eq, tk_Neq, tk_Assign, tk_And, tk_Or, tk_If, tk_Else, tk_While,
tk_Print, tk_P... | 1,019Compiler/lexical analyzer | 5c | e0jav |
class State {
const State(this.symbol);
static final ALIVE = const State('#');
static final DEAD = const State(' ');
final String symbol;
}
class Rule {
Rule(this.cellState);
reactToNeighbours(int neighbours) {
if (neighbours == 3) {
cellState = State.ALIVE;
} else if (neighbours!= 2) {
... | 1,014Conway's Game of Life | 18dart | 3ctzz |
@input = (
['pi=3.14159265358979323846264338327950288419716939937510582097494459231', ' ', 5],
['The author has two Z$100000000000000 Zimbabwe notes (100 trillion).', '.'],
['-in Aus$+1411.8millions'],
['===US$0017440 millions=== (in 2000 dollars)'],
['123.e8000 is pretty big.'],
['The land area... | 1,016Commatizing numbers | 2perl | 6lf36 |
def builtinsort(x):
x.sort()
def partition(seq, pivot):
low, middle, up = [], [], []
for x in seq:
if x < pivot:
low.append(x)
elif x == pivot:
middle.append(x)
else:
up.append(x)
return low, middle, up
import random
def qsortranpart(seq):
size = le... | 1,012Compare sorting algorithms' performance | 3python | 95cmf |
function test(list)
table.sort(list, function(a,b) return #a > #b end)
for _,s in ipairs(list) do print(#s, s) end
end
test{"abcd", "123456789", "abcdef", "1234567"} | 1,013Compare length of two strings | 1lua | wowea |
from __future__ import print_function
import sys, shlex, operator
tk_EOI, tk_Mul, tk_Div, tk_Mod, tk_Add, tk_Sub, tk_Negate, tk_Not, tk_Lss, tk_Leq, tk_Gtr, \
tk_Geq, tk_Eql, tk_Neq, tk_Assign, tk_And, tk_Or, tk_If, tk_Else, tk_While, tk_Print, \
tk_Putc, tk_Lparen, tk_Rparen, tk_Lbrace, tk_Rbrace, tk_Semi, tk_Co... | 1,010Compiler/syntax analyzer | 3python | 5hrux |
Point = Struct.new(:x,:y)
pt = Point.new(6,7)
puts pt.x
pt.y = 3
puts pt
pt = Point[2,3]
puts pt[:x]
pt['y'] = 5
puts pt
pt.each_pair{|member, value| puts } | 1,007Compound data type | 14ruby | 711ri |
import re as RegEx
def Commatize( _string, _startPos=0, _periodLen=3, _separator= ):
outString =
strPos = 0
matches = RegEx.findall( , _string )
for match in matches[:-1]:
if not match:
outString += _string[ strPos ]
strPos += 1
else:
if len(match) > _periodLen:
leadIn = match[:_startPos]
p... | 1,016Commatizing numbers | 3python | y2t6q |
class Array
def radix_sort(base=10)
ary = dup
rounds = (Math.log(ary.max)/Math.log(base)).ceil
rounds.times do |i|
buckets = Array.new(base){[]}
base_i = base**i
ary.each do |n|
digit = (n/base_i) % base
buckets[digit] << n
end
ary = buckets.flatten
... | 1,012Compare sorting algorithms' performance | 14ruby | lg2cl |
null | 1,007Compound data type | 15rust | jaa72 |
case class Point(x: Int = 0, y: Int = 0)
val p = Point(1, 2)
println(p.y) | 1,007Compound data type | 16scala | bxxk6 |
int main(int argc, char* argv[])
{
int i;
(void) printf(, argv[0]);
for (i = 1; i < argc; ++i)
(void) printf(, i, argv[i]);
return EXIT_SUCCESS;
} | 1,020Command-line arguments | 5c | xohwu |
use strict;
use warnings;
use integer;
my ($binary, $pc, @stack, @data) = ('', 0);
<> =~ /Strings: (\d+)/ or die "bad header";
my @strings = map <> =~ tr/\n""//dr =~ s/\\(.)/$1 eq 'n' ? "\n" : $1/ger, 1..$1;
sub value { unpack 'l', substr $binary, ($pc += 4) - 4, 4 }
my @ops = (
[ halt => sub { exit } ],
[ ad... | 1,011Compiler/virtual machine interpreter | 2perl | 5hgu2 |
use strict;
use warnings;
my $stringcount = my $namecount = my $pairsym = my $pc = 0;
my (%strings, %names);
my %opnames = qw( Less lt LessEqual le Multiply mul Subtract sub Divide div
GreaterEqual ge Equal eq Greater gt NotEqual ne Negate neg );
sub tree
{
my ($A, $B) = ( '_' . ++$pairsym, '_' . ++$pairsym... | 1,015Compiler/code generator | 2perl | bwjk4 |
package xyz.hyperreal.rosettacodeCompiler
import scala.io.Source
object SyntaxAnalyzer {
val symbols =
Map[String, (PrefixOperator, InfixOperator)](
"Op_or" -> (null, InfixOperator(10, LeftAssoc, BranchNode("Or", _, _))),
"Op_and" -> (null, InfixOperator(20, LeftAssoc, BranchNode... | 1,010Compiler/syntax analyzer | 16scala | hepja |
const char *donuts[] = {, , ,
};
int pos[] = {0, 0, 0, 0};
void printDonuts(int k) {
for (size_t i = 1; i < k + 1; i += 1)
printf(, donuts[pos[i]]);
printf();
}
void combination_with_repetiton(int n, int k) {
while (1) {
for (int i = k; i > 0; i -= 1) {
if (pos[i] > ... | 1,021Combinations with repetitions | 5c | y2o6f |
use strict;
use warnings;
for ( 'shorter thelonger', 'abcd 123456789 abcdef 1234567' )
{
print "\nfor strings => $_\n";
printf "length%d:%s\n", length(), $_
for sort { length $b <=> length $a } split;
} | 1,013Compare length of two strings | 2perl | c4c9a |
import java.io.File
import java.util.Scanner
import java.util.regex.Pattern
object CommatizingNumbers extends App {
def commatize(s: String): Unit = commatize(s, 0, 3, ",")
def commatize(s: String, start: Int, step: Int, ins: String): Unit = {
if (start >= 0 && start <= s.length && step >= 1 && step <= s.len... | 1,016Commatizing numbers | 16scala | vr92s |
import Foundation
extension String {
private static let commaReg = try! NSRegularExpression(pattern: "(\\.[0-9]+|[1-9]([0-9]+)?(\\.[0-9]+)?)")
public func commatize(start: Int = 0, period: Int = 3, separator: String = ",") -> String {
guard separator!= "" else {
return self
}
let sep = Array(se... | 1,016Commatizing numbers | 17swift | mvzyk |
(dorun (map println *command-line-args*)) | 1,020Command-line arguments | 6clojure | ota8j |
from __future__ import print_function
import sys, struct, shlex, operator
nd_Ident, nd_String, nd_Integer, nd_Sequence, nd_If, nd_Prtc, nd_Prts, nd_Prti, nd_While, \
nd_Assign, nd_Negate, nd_Not, nd_Mul, nd_Div, nd_Mod, nd_Add, nd_Sub, nd_Lss, nd_Leq, \
nd_Gtr, nd_Geq, nd_Eql, nd_Neq, nd_And, nd_Or = range(25)
al... | 1,015Compiler/code generator | 3python | pxhbm |
<?php
function retrieveStrings()
{
if (isset($_POST['input'])) {
$strings = explode(, $_POST['input']);
} else {
$strings = ['abcd', '123456789', 'abcdef', '1234567'];
}
return $strings;
}
function setInput()
{
echo join(, retrieveStrings());
}
function setOutput()
{
$strin... | 1,013Compare length of two strings | 12php | xixw5 |
package main
import (
"fmt"
"math/big"
)
func main() {
var n, p int64
fmt.Printf("A sample of permutations from 1 to 12:\n")
for n = 1; n < 13; n++ {
p = n / 3
fmt.Printf("P(%d,%d) =%d\n", n, p, perm(big.NewInt(n), big.NewInt(p)))
}
fmt.Printf("\nA sample of combinations from 10 to 60:\n")
for n = 10; n <... | 1,018Combinations and permutations | 0go | 7pvr2 |
from __future__ import print_function
import sys, struct
FETCH, STORE, PUSH, ADD, SUB, MUL, DIV, MOD, LT, GT, LE, GE, EQ, NE, AND, OR, NEG, NOT, \
JMP, JZ, PRTC, PRTS, PRTI, HALT = range(24)
code_map = {
: FETCH,
: STORE,
: PUSH,
: ADD,
: SUB,
: MUL,
: DIV,
: MOD,
: L... | 1,011Compiler/virtual machine interpreter | 3python | 4kr5k |
A = 'I am string'
B = 'I am string too'
if len(A) > len(B):
print('', 'has length', len(A), 'and is the longest of the two strings')
print('', 'has length', len(B), 'and is the shortest of the two strings')
elif len(A) < len(B):
print('', 'has length', len(B), 'and is the longest of the two strings')
p... | 1,013Compare length of two strings | 3python | lglcv |
null | 1,007Compound data type | 17swift | rppgg |
char *quib(const char **strs, size_t size)
{
size_t len = 3 + ((size > 1) ? (2 * size + 1) : 0);
size_t i;
for (i = 0; i < size; i++)
len += strlen(strs[i]);
char *s = malloc(len * sizeof(*s));
if (!s)
{
perror();
exit(EXIT_FAILURE);
}
strcpy(s, );
switch ... | 1,022Comma quibbling | 5c | vrt2o |
(defn combinations [coll k]
(when-let [[x & xs] coll]
(if (= k 1)
(map list coll)
(concat (map (partial cons x) (combinations coll (dec k)))
(combinations xs k))))) | 1,021Combinations with repetitions | 6clojure | 2gtl1 |
perm :: Integer -> Integer -> Integer
perm n k = product [n-k+1..n]
comb :: Integer -> Integer -> Integer
comb n k = perm n k `div` product [1..k]
main :: IO ()
main = do
let showBig maxlen b =
let st = show b
stlen = length st
in if stlen < maxlen then st e... | 1,018Combinations and permutations | 8haskell | 8fe0z |
main(List<String> args) {
for(var arg in args)
print(arg);
} | 1,020Command-line arguments | 18dart | bw5k1 |
package xyz.hyperreal.rosettacodeCompiler
import scala.collection.mutable.{ArrayBuffer, HashMap}
import scala.io.Source
object CodeGenerator {
def fromStdin = fromSource(Source.stdin)
def fromString(src: String) = fromSource(Source.fromString(src))
def fromSource(ast: Source) = {
val vars = ... | 1,015Compiler/code generator | 16scala | qiexw |
package cmp
func AllEqual(strings []string) bool {
for _, s := range strings {
if s != strings[0] {
return false
}
}
return true
}
func AllLessThan(strings []string) bool {
for i := 1; i < len(strings); i++ {
if !(strings[i - 1] < s) {
return false
}
}
return true
} | 1,017Compare a list of strings | 0go | u79vt |
import java.math.BigInteger;
public class CombinationsAndPermutations {
public static void main(String[] args) {
System.out.println(Double.MAX_VALUE);
System.out.println("A sample of permutations from 1 to 12 with exact Integer arithmetic:");
for ( int n = 1 ; n <= 12 ; n++ ) {
... | 1,018Combinations and permutations | 9java | e0ha5 |
a, b = ,
[a,b].sort_by{|s| - s.size }.each{|s| puts s + }
list = [,,,]
puts list.sort_by{|s|- s.size} | 1,013Compare length of two strings | 14ruby | v7v2n |
fn compare_and_report<T: ToString>(string1: T, string2: T) -> String {
let strings = [string1.to_string(), string2.to_string()];
let difference = strings[0].len() as i32 - strings[1].len() as i32;
if difference == 0 { | 1,013Compare length of two strings | 15rust | ujuvj |
allEqual :: Eq a => [a] -> Bool
allEqual xs = and $ zipWith (==) xs (tail xs)
allIncr :: Ord a => [a] -> Bool
allIncr xs = and $ zipWith (<) xs (tail xs) | 1,017Compare a list of strings | 8haskell | w8bed |
(defn quibble [sq]
(let [sep (if (pos? (count sq)) " and " "")]
(apply str
(concat "{" (interpose ", " (butlast sq)) [sep (last sq)] "}"))))
(defn quibble-f [& args]
(clojure.pprint/cl-format nil "{~{~a~#[~
(def test
#(doseq [sq [[]
["ABC"]
["ABC", "DEF"]
... | 1,022Comma quibbling | 6clojure | rbmg2 |
package xyz.hyperreal.rosettacodeCompiler
import java.io.{BufferedReader, FileReader, Reader, StringReader}
import scala.collection.mutable
import scala.collection.mutable.ArrayBuffer
object VirtualMachine {
private object Opcodes {
val FETCH: Byte = 0
val STORE: Byte = 1
val PUSH: Byte = 2
val J... | 1,011Compiler/virtual machine interpreter | 16scala | kwphk |
import java.util.Arrays;
public class CompareListOfStrings {
public static void main(String[] args) {
String[][] arr = {{"AA", "AA", "AA", "AA"}, {"AA", "ACB", "BB", "CC"}};
for (String[] a: arr) {
System.out.println(Arrays.toString(a));
System.out.println(Arrays.stream(a).... | 1,017Compare a list of strings | 9java | keghm |
null | 1,018Combinations and permutations | 11kotlin | ke4h3 |
function allEqual(a) {
var out = true, i = 0;
while (++i<a.length) {
out = out && (a[i-1] === a[i]);
} return out;
}
function azSorted(a) {
var out = true, i = 0;
while (++i<a.length) {
out = out && (a[i-1] < a[i]);
} return out;
}
var e = ['AA', 'AA', 'AA', 'AA'], s = ['AA', 'ACB', 'BB', 'CC'], e... | 1,017Compare a list of strings | 10javascript | e0kao |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.