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 = [Point]()
let (leftPointIdx, _) = points.enumerated().min(by: { $0.element.x < $1.element.x })!
var p = leftPointIdx
var q = 0
repeat {
hull.append(points[p])
q = (p + 1)% points.count
for i in 0..<points.count where calculateOrientation(points[p], points[i], points[q]) == .counterClockwise {
q = i
}
p = q
} while p!= leftPointIdx
return hull
}
private func calculateOrientation(_ p: Point, _ q: Point, _ r: Point) -> Orientation {
let val = (q.y - p.y) * (r.x - q.x) - (q.x - p.x) * (r.y - q.y)
if val == 0 {
return .straight
} else if val > 0 {
return .clockwise
} else {
return .counterClockwise
}
}
private enum Orientation {
case straight, clockwise, counterClockwise
}
let points = [
(16,3),
(12,17),
(0,6),
(-4,-6),
(16,6),
(16,-7),
(16,-3),
(17,-4),
(5,19),
(19,-8),
(3,16),
(12,13),
(3,-4),
(17,5),
(-3,15),
(-3,-9),
(0,11),
(-9,-3),
(-4,-2),
(12,10)
].map(Point.init(fromTuple:))
print("Input: \(points)")
print("Output: \(calculateConvexHull(fromPoints: points))") | 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([9, world[(x,y)]])) if world[(x,y)] else ' '
for y in range(-15,16)))
1 1
1 1
11 1 1 1 1
111 1 1211
1 2 1 1 11
1 11 21
1 1 11 1
1 2 1 1
1 2
1 1 1
1 1
2 11
1 1
1
1 1
1
2
1
1 1 1
1 2 1
1 3 11 2
11 1 1 1 2
1 1 2
1 1
1 1 1
2 2 1
1 | 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_Gtr, nd_Geq, nd_Eql, nd_Neq, nd_And, nd_Or
} NodeType;
typedef struct Tree Tree;
struct Tree {
NodeType node_type;
Tree *left;
Tree *right;
int value;
};
struct {
char *enum_text;
NodeType node_type;
} atr[] = {
{ , 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, },
};
FILE *source_fp;
da_dim(string_pool, const char *);
da_dim(global_names, const char *);
da_dim(global_values, int);
void error(const char *fmt, ... ) {
va_list ap;
char buf[1000];
va_start(ap, fmt);
vsprintf(buf, fmt, ap);
printf(, buf);
exit(1);
}
Tree *make_node(NodeType node_type, Tree *left, Tree *right) {
Tree *t = calloc(sizeof(Tree), 1);
t->node_type = node_type;
t->left = left;
t->right = right;
return t;
}
Tree *make_leaf(NodeType node_type, int value) {
Tree *t = calloc(sizeof(Tree), 1);
t->node_type = node_type;
t->value = value;
return t;
}
int interp(Tree *x) {
if (!x) return 0;
switch(x->node_type) {
case nd_Integer: return x->value;
case nd_Ident: return global_values[x->value];
case nd_String: return x->value;
case nd_Assign: return global_values[x->left->value] = interp(x->right);
case nd_Add: return interp(x->left) + interp(x->right);
case nd_Sub: return interp(x->left) - interp(x->right);
case nd_Mul: return interp(x->left) * interp(x->right);
case nd_Div: return interp(x->left) / interp(x->right);
case nd_Mod: return interp(x->left) % interp(x->right);
case nd_Lss: return interp(x->left) < interp(x->right);
case nd_Gtr: return interp(x->left) > interp(x->right);
case nd_Leq: return interp(x->left) <= interp(x->right);
case nd_Eql: return interp(x->left) == interp(x->right);
case nd_Neq: return interp(x->left) != interp(x->right);
case nd_And: return interp(x->left) && interp(x->right);
case nd_Or: return interp(x->left) || interp(x->right);
case nd_Negate: return -interp(x->left);
case nd_Not: return !interp(x->left);
case nd_If: if (interp(x->left))
interp(x->right->left);
else
interp(x->right->right);
return 0;
case nd_While: while (interp(x->left))
interp(x->right);
return 0;
case nd_Prtc: printf(, interp(x->left));
return 0;
case nd_Prti: printf(, interp(x->left));
return 0;
case nd_Prts: printf(, string_pool[interp(x->left)]);
return 0;
case nd_Sequence: interp(x->left);
interp(x->right);
return 0;
default: error(, x->node_type);
}
return 0;
}
void init_in(const char fn[]) {
if (fn[0] == '\0')
source_fp = stdin;
else {
source_fp = fopen(fn, );
if (source_fp == NULL)
error(, fn);
}
}
NodeType get_enum_value(const char name[]) {
for (size_t i = 0; i < sizeof(atr) / sizeof(atr[0]); i++) {
if (strcmp(atr[i].enum_text, name) == 0) {
return atr[i].node_type;
}
}
error(, name);
return -1;
}
char *read_line(int *len) {
static char *text = NULL;
static int textmax = 0;
for (*len = 0; ; (*len)++) {
int ch = fgetc(source_fp);
if (ch == EOF || ch == '\n') {
if (*len == 0)
return NULL;
break;
}
if (*len + 1 >= textmax) {
textmax = (textmax == 0 ? 128 : textmax * 2);
text = realloc(text, textmax);
}
text[*len] = ch;
}
text[*len] = '\0';
return text;
}
char *rtrim(char *text, int *len) {
for (; *len > 0 && isspace(text[*len - 1]); --(*len))
;
text[*len] = '\0';
return text;
}
int fetch_string_offset(char *st) {
int len = strlen(st);
st[len - 1] = '\0';
++st;
char *p, *q;
p = q = st;
while ((*p++ = *q++) != '\0') {
if (q[-1] == '\\') {
if (q[0] == 'n') {
p[-1] = '\n';
++q;
} else if (q[0] == '\\') {
++q;
}
}
}
for (int i = 0; i < da_len(string_pool); ++i) {
if (strcmp(st, string_pool[i]) == 0) {
return i;
}
}
da_add(string_pool);
int n = da_len(string_pool) - 1;
string_pool[n] = strdup(st);
return da_len(string_pool) - 1;
}
int fetch_var_offset(const char *name) {
for (int i = 0; i < da_len(global_names); ++i) {
if (strcmp(name, global_names[i]) == 0)
return i;
}
da_add(global_names);
int n = da_len(global_names) - 1;
global_names[n] = strdup(name);
da_append(global_values, 0);
return n;
}
Tree *load_ast() {
int len;
char *yytext = read_line(&len);
yytext = rtrim(yytext, &len);
char *tok = strtok(yytext, );
if (tok[0] == ';') {
return NULL;
}
NodeType node_type = get_enum_value(tok);
char *p = tok + strlen(tok);
if (p != &yytext[len]) {
int n;
for (++p; isspace(*p); ++p)
;
switch (node_type) {
case nd_Ident: n = fetch_var_offset(p); break;
case nd_Integer: n = strtol(p, NULL, 0); break;
case nd_String: n = fetch_string_offset(p); break;
default: error(, p);
}
return make_leaf(node_type, n);
}
Tree *left = load_ast();
Tree *right = load_ast();
return make_node(node_type, left, right);
}
int main(int argc, char *argv[]) {
init_in(argc > 1 ? argv[1] : );
Tree *x = load_ast();
interp(x);
return 0;
} | 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[Valid][1:NPts],Y[Valid][1:NPts], pch=19, cex=0.25, col="blue",
xlab="x",ylab="y",main="Fuzzy circle", xlim=c(-RMax,RMax), ylim=c(-RMax,RMax) ) | 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);
let local_word = word.to_owned();
std::thread::spawn(move || {
thread::sleep_ms(snooze_time);
println!("{}", local_word);
});
}
thread::sleep_ms(1000);
} | 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
} TokenType;
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 struct {
TokenType tok;
int err_ln;
int err_col;
char *text;
} tok_s;
typedef struct Tree {
NodeType node_type;
struct Tree *left;
struct Tree *right;
char *value;
} Tree;
struct {
char *text, *enum_text;
TokenType tok;
bool right_associative, is_binary, is_unary;
int precedence;
NodeType node_type;
} atr[] = {
{, , tk_EOI, false, false, false, -1, -1 },
{, , tk_Mul, false, true, false, 13, nd_Mul },
{, , tk_Div, false, true, false, 13, nd_Div },
{, , tk_Mod, false, true, false, 13, nd_Mod },
{, , tk_Add, false, true, false, 12, nd_Add },
{, , tk_Sub, false, true, false, 12, nd_Sub },
{, , tk_Negate, false, false, true, 14, nd_Negate },
{, , tk_Not, false, false, true, 14, nd_Not },
{, , tk_Lss, false, true, false, 10, nd_Lss },
{, , tk_Leq, false, true, false, 10, nd_Leq },
{, , tk_Gtr, false, true, false, 10, nd_Gtr },
{, , tk_Geq, false, true, false, 10, nd_Geq },
{, , tk_Eql, false, true, false, 9, nd_Eql },
{, , tk_Neq, false, true, false, 9, nd_Neq },
{, , tk_Assign, false, false, false, -1, nd_Assign },
{, , tk_And, false, true, false, 5, nd_And },
{, , tk_Or, false, true, false, 4, nd_Or },
{, , tk_If, false, false, false, -1, nd_If },
{, , tk_Else, false, false, false, -1, -1 },
{, , tk_While, false, false, false, -1, nd_While },
{, , tk_Print, false, false, false, -1, -1 },
{, , tk_Putc, false, false, false, -1, -1 },
{, , tk_Lparen, false, false, false, -1, -1 },
{, , tk_Rparen, false, false, false, -1, -1 },
{, , tk_Lbrace, false, false, false, -1, -1 },
{, , tk_Rbrace, false, false, false, -1, -1 },
{, , tk_Semi, false, false, false, -1, -1 },
{, , tk_Comma, false, false, false, -1, -1 },
{, , tk_Ident, false, false, false, -1, nd_Ident },
{, , tk_Integer, false, false, false, -1, nd_Integer},
{, , tk_String, false, false, false, -1, nd_String },
};
char *Display_nodes[] = {, , , , , ,
, , , , , , , , ,
, , , , , , ,
, , };
static tok_s tok;
static FILE *source_fp, *dest_fp;
Tree *paren_expr();
void error(int err_line, int err_col, const char *fmt, ... ) {
va_list ap;
char buf[1000];
va_start(ap, fmt);
vsprintf(buf, fmt, ap);
va_end(ap);
printf(, err_line, err_col, buf);
exit(1);
}
char *read_line(int *len) {
static char *text = NULL;
static int textmax = 0;
for (*len = 0; ; (*len)++) {
int ch = fgetc(source_fp);
if (ch == EOF || ch == '\n') {
if (*len == 0)
return NULL;
break;
}
if (*len + 1 >= textmax) {
textmax = (textmax == 0 ? 128 : textmax * 2);
text = realloc(text, textmax);
}
text[*len] = ch;
}
text[*len] = '\0';
return text;
}
char *rtrim(char *text, int *len) {
for (; *len > 0 && isspace(text[*len - 1]); --(*len))
;
text[*len] = '\0';
return text;
}
TokenType get_enum(const char *name) {
for (size_t i = 0; i < NELEMS(atr); i++) {
if (strcmp(atr[i].enum_text, name) == 0)
return atr[i].tok;
}
error(0, 0, , name);
return 0;
}
tok_s gettok() {
int len;
tok_s tok;
char *yytext = read_line(&len);
yytext = rtrim(yytext, &len);
tok.err_ln = atoi(strtok(yytext, ));
tok.err_col = atoi(strtok(NULL, ));
char *name = strtok(NULL, );
tok.tok = get_enum(name);
char *p = name + strlen(name);
if (p != &yytext[len]) {
for (++p; isspace(*p); ++p)
;
tok.text = strdup(p);
}
return tok;
}
Tree *make_node(NodeType node_type, Tree *left, Tree *right) {
Tree *t = calloc(sizeof(Tree), 1);
t->node_type = node_type;
t->left = left;
t->right = right;
return t;
}
Tree *make_leaf(NodeType node_type, char *value) {
Tree *t = calloc(sizeof(Tree), 1);
t->node_type = node_type;
t->value = strdup(value);
return t;
}
void expect(const char msg[], TokenType s) {
if (tok.tok == s) {
tok = gettok();
return;
}
error(tok.err_ln, tok.err_col, , msg, atr[s].text, atr[tok.tok].text);
}
Tree *expr(int p) {
Tree *x = NULL, *node;
TokenType op;
switch (tok.tok) {
case tk_Lparen:
x = paren_expr();
break;
case tk_Sub: case tk_Add:
op = tok.tok;
tok = gettok();
node = expr(atr[tk_Negate].precedence);
x = (op == tk_Sub) ? make_node(nd_Negate, node, NULL) : node;
break;
case tk_Not:
tok = gettok();
x = make_node(nd_Not, expr(atr[tk_Not].precedence), NULL);
break;
case tk_Ident:
x = make_leaf(nd_Ident, tok.text);
tok = gettok();
break;
case tk_Integer:
x = make_leaf(nd_Integer, tok.text);
tok = gettok();
break;
default:
error(tok.err_ln, tok.err_col, , atr[tok.tok].text);
}
while (atr[tok.tok].is_binary && atr[tok.tok].precedence >= p) {
TokenType op = tok.tok;
tok = gettok();
int q = atr[op].precedence;
if (!atr[op].right_associative)
q++;
node = expr(q);
x = make_node(atr[op].node_type, x, node);
}
return x;
}
Tree *paren_expr() {
expect(, tk_Lparen);
Tree *t = expr(0);
expect(, tk_Rparen);
return t;
}
Tree *stmt() {
Tree *t = NULL, *v, *e, *s, *s2;
switch (tok.tok) {
case tk_If:
tok = gettok();
e = paren_expr();
s = stmt();
s2 = NULL;
if (tok.tok == tk_Else) {
tok = gettok();
s2 = stmt();
}
t = make_node(nd_If, e, make_node(nd_If, s, s2));
break;
case tk_Putc:
tok = gettok();
e = paren_expr();
t = make_node(nd_Prtc, e, NULL);
expect(, tk_Semi);
break;
case tk_Print:
tok = gettok();
for (expect(, tk_Lparen); ; expect(, tk_Comma)) {
if (tok.tok == tk_String) {
e = make_node(nd_Prts, make_leaf(nd_String, tok.text), NULL);
tok = gettok();
} else
e = make_node(nd_Prti, expr(0), NULL);
t = make_node(nd_Sequence, t, e);
if (tok.tok != tk_Comma)
break;
}
expect(, tk_Rparen);
expect(, tk_Semi);
break;
case tk_Semi:
tok = gettok();
break;
case tk_Ident:
v = make_leaf(nd_Ident, tok.text);
tok = gettok();
expect(, tk_Assign);
e = expr(0);
t = make_node(nd_Assign, v, e);
expect(, tk_Semi);
break;
case tk_While:
tok = gettok();
e = paren_expr();
s = stmt();
t = make_node(nd_While, e, s);
break;
case tk_Lbrace:
for (expect(, tk_Lbrace); tok.tok != tk_Rbrace && tok.tok != tk_EOI;)
t = make_node(nd_Sequence, t, stmt());
expect(, tk_Rbrace);
break;
case tk_EOI:
break;
default: error(tok.err_ln, tok.err_col, , atr[tok.tok].text);
}
return t;
}
Tree *parse() {
Tree *t = NULL;
tok = gettok();
do {
t = make_node(nd_Sequence, t, stmt());
} while (t != NULL && tok.tok != tk_EOI);
return t;
}
void prt_ast(Tree *t) {
if (t == NULL)
printf();
else {
printf(, Display_nodes[t->node_type]);
if (t->node_type == nd_Ident || t->node_type == nd_Integer || t->node_type == nd_String) {
printf(, t->value);
} else {
printf();
prt_ast(t->left);
prt_ast(t->right);
}
}
}
void init_io(FILE **fp, FILE *std, const char mode[], const char fn[]) {
if (fn[0] == '\0')
*fp = std;
else if ((*fp = fopen(fn, mode)) == NULL)
error(0, 0, , fn);
}
int main(int argc, char *argv[]) {
init_io(&source_fp, stdin, , argc > 1 ? argv[1] : );
init_io(&dest_fp, stdout, , argc > 2 ? argv[2] : );
prt_ast(parse());
} | 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
ndAdd
ndSub
ndLss
ndLeq
ndGtr
ndGeq
ndEql
ndNeq
ndAnd
ndOr
)
type Tree struct {
nodeType NodeType
left *Tree
right *Tree
value int
} | 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.draw_circle(Pixel.new(160,160),90,RGBColour::BLACK)
pixmap.draw_circle(Pixel.new(160,160),160,RGBColour::BLACK)
points.each {|(x,y)| pixmap[10*(x+16),10*(y+16)] = RGBColour::BLACK}
pngfile = __FILE__
pngfile[/\.rb/] =
pixmap.save_as_png(pngfile) | 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;
typedef struct Code_map {
char *text;
Code_t op;
} Code_map;
Code_map code_map[] = {
{, FETCH},
{, STORE},
{, PUSH },
{, ADD },
{, SUB },
{, MUL },
{, DIV },
{, MOD },
{, LT },
{, GT },
{, LE },
{, GE },
{, EQ },
{, NE },
{, AND },
{, OR },
{, NEG },
{, NOT },
{, JMP },
{, JZ },
{, PRTC },
{, PRTS },
{, PRTI },
{, HALT },
};
FILE *source_fp;
da_dim(object, code);
void error(const char *fmt, ... ) {
va_list ap;
char buf[1000];
va_start(ap, fmt);
vsprintf(buf, fmt, ap);
va_end(ap);
printf(, buf);
exit(1);
}
void run_vm(const code obj[], int32_t data[], int g_size, char **string_pool) {
int32_t *sp = &data[g_size + 1];
const code *pc = obj;
again:
switch (*pc++) {
case FETCH: *sp++ = data[*(int32_t *)pc]; pc += sizeof(int32_t); goto again;
case STORE: data[*(int32_t *)pc] = *--sp; pc += sizeof(int32_t); goto again;
case PUSH: *sp++ = *(int32_t *)pc; pc += sizeof(int32_t); goto again;
case ADD: sp[-2] += sp[-1]; --sp; goto again;
case SUB: sp[-2] -= sp[-1]; --sp; goto again;
case MUL: sp[-2] *= sp[-1]; --sp; goto again;
case DIV: sp[-2] /= sp[-1]; --sp; goto again;
case MOD: sp[-2] %= sp[-1]; --sp; goto again;
case LT: sp[-2] = sp[-2] < sp[-1]; --sp; goto again;
case GT: sp[-2] = sp[-2] > sp[-1]; --sp; goto again;
case LE: sp[-2] = sp[-2] <= sp[-1]; --sp; goto again;
case GE: sp[-2] = sp[-2] >= sp[-1]; --sp; goto again;
case EQ: sp[-2] = sp[-2] == sp[-1]; --sp; goto again;
case NE: sp[-2] = sp[-2] != sp[-1]; --sp; goto again;
case AND: sp[-2] = sp[-2] && sp[-1]; --sp; goto again;
case OR: sp[-2] = sp[-2] || sp[-1]; --sp; goto again;
case NEG: sp[-1] = -sp[-1]; goto again;
case NOT: sp[-1] = !sp[-1]; goto again;
case JMP: pc += *(int32_t *)pc; goto again;
case JZ: pc += (*--sp == 0) ? *(int32_t *)pc : (int32_t)sizeof(int32_t); goto again;
case PRTC: printf(, sp[-1]); --sp; goto again;
case PRTS: printf(, string_pool[sp[-1]]); --sp; goto again;
case PRTI: printf(, sp[-1]); --sp; goto again;
case HALT: break;
default: error(, *(pc - 1));
}
}
char *read_line(int *len) {
static char *text = NULL;
static int textmax = 0;
for (*len = 0; ; (*len)++) {
int ch = fgetc(source_fp);
if (ch == EOF || ch == '\n') {
if (*len == 0)
return NULL;
break;
}
if (*len + 1 >= textmax) {
textmax = (textmax == 0 ? 128 : textmax * 2);
text = realloc(text, textmax);
}
text[*len] = ch;
}
text[*len] = '\0';
return text;
}
char *rtrim(char *text, int *len) {
for (; *len > 0 && isspace(text[*len - 1]); --(*len))
;
text[*len] = '\0';
return text;
}
char *translate(char *st) {
char *p, *q;
if (st[0] == ' if there
++st;
p = q = st;
while ((*p++ = *q++) != '\0') {
if (q[-1] == '\\') {
if (q[0] == 'n') {
p[-1] = '\n';
++q;
} else if (q[0] == '\\') {
++q;
}
}
if (q[0] == ' if there
++q;
}
return st;
}
int findit(const char text[], int offset) {
for (size_t i = 0; i < sizeof(code_map) / sizeof(code_map[0]); i++) {
if (strcmp(code_map[i].text, text) == 0)
return code_map[i].op;
}
error(, text, offset);
return -1;
}
void emit_byte(int c) {
da_append(object, (uchar)c);
}
void emit_int(int32_t n) {
union {
int32_t n;
unsigned char c[sizeof(int32_t)];
} x;
x.n = n;
for (size_t i = 0; i < sizeof(x.n); ++i) {
emit_byte(x.c[i]);
}
}
char **load_code(int *ds) {
int line_len, n_strings;
char **string_pool;
char *text = read_line(&line_len);
text = rtrim(text, &line_len);
strtok(text, );
*ds = atoi(strtok(NULL, ));
strtok(NULL, );
n_strings = atoi(strtok(NULL, ));
string_pool = malloc(n_strings * sizeof(char *));
for (int i = 0; i < n_strings; ++i) {
text = read_line(&line_len);
text = rtrim(text, &line_len);
text = translate(text);
string_pool[i] = strdup(text);
}
for (;;) {
int len;
text = read_line(&line_len);
if (text == NULL)
break;
text = rtrim(text, &line_len);
int offset = atoi(strtok(text, ));
char *instr = strtok(NULL, );
int opcode = findit(instr, offset);
emit_byte(opcode);
char *operand = strtok(NULL, );
switch (opcode) {
case JMP: case JZ:
operand++;
len = strlen(operand);
operand[len - 1] = '\0';
emit_int(atoi(operand));
break;
case PUSH:
emit_int(atoi(operand));
break;
case FETCH: case STORE:
operand++;
len = strlen(operand);
operand[len - 1] = '\0';
emit_int(atoi(operand));
break;
}
}
return string_pool;
}
void init_io(FILE **fp, FILE *std, const char mode[], const char fn[]) {
if (fn[0] == '\0')
*fp = std;
else if ((*fp = fopen(fn, mode)) == NULL)
error(0, 0, , fn);
}
int main(int argc, char *argv[]) {
init_io(&source_fp, stdin, , argc > 1 ? argv[1] : );
int data_size;
char **string_pool = load_code(&data_size);
int data[1000 + data_size];
run_vm(object, data, data_size, string_pool);
} | 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_to_nodes = new HashMap<>();
static class Node {
public NodeType nt;
public Node left, right;
public String value;
Node() {
this.nt = null;
this.left = null;
this.right = null;
this.value = null;
}
Node(NodeType node_type, Node left, Node right, String value) {
this.nt = node_type;
this.left = left;
this.right = right;
this.value = value;
}
public static Node make_node(NodeType nodetype, Node left, Node right) {
return new Node(nodetype, left, right, "");
}
public static Node make_node(NodeType nodetype, Node left) {
return new Node(nodetype, left, null, "");
}
public static Node make_leaf(NodeType nodetype, String value) {
return new Node(nodetype, null, null, value);
}
}
static enum NodeType {
nd_None(";"), nd_Ident("Identifier"), nd_String("String"), nd_Integer("Integer"),
nd_Sequence("Sequence"), nd_If("If"),
nd_Prtc("Prtc"), nd_Prts("Prts"), nd_Prti("Prti"), nd_While("While"),
nd_Assign("Assign"), nd_Negate("Negate"), nd_Not("Not"), nd_Mul("Multiply"), nd_Div("Divide"),
nd_Mod("Mod"), nd_Add("Add"),
nd_Sub("Subtract"), nd_Lss("Less"), nd_Leq("LessEqual"),
nd_Gtr("Greater"), nd_Geq("GreaterEqual"), nd_Eql("Equal"), nd_Neq("NotEqual"), nd_And("And"), nd_Or("Or");
private final String name;
NodeType(String name) { this.name = name; }
@Override
public String toString() { return this.name; }
}
static String str(String s) {
String result = "";
int i = 0;
s = s.replace("\"", "");
while (i < s.length()) {
if (s.charAt(i) == '\\' && i + 1 < s.length()) {
if (s.charAt(i + 1) == 'n') {
result += '\n';
i += 2;
} else if (s.charAt(i) == '\\') {
result += '\\';
i += 2;
}
} else {
result += s.charAt(i);
i++;
}
}
return result;
}
static boolean itob(int i) {
return i != 0;
}
static int btoi(boolean b) {
return b ? 1 : 0;
}
static int fetch_var(String name) {
int result;
if (globals.containsKey(name)) {
result = globals.get(name);
} else {
globals.put(name, 0);
result = 0;
}
return result;
}
static Integer interpret(Node n) throws Exception {
if (n == null) {
return 0;
}
switch (n.nt) {
case nd_Integer:
return Integer.parseInt(n.value);
case nd_Ident:
return fetch_var(n.value);
case nd_String:
return 1; | 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 * sizeof(int));
if (si != NULL)
{
for (int i = 0; i < n; i++)
{
si[2 * i] = strlen(strings[i]);
si[2 * i + 1] = i;
}
qsort(si, n, 2 * sizeof(int), cmp);
int max = si[0];
int min = si[2 * (n - 1)];
for (int i = 0; i < n; i++)
{
int length = si[2 * i];
char* string = strings[si[2 * i + 1]];
char* predicate;
if (length == max)
predicate = predicate_max;
else if (length == min)
predicate = predicate_min;
else
predicate = predicate_ave;
printf(%s\,
string, has_length, length, predicate);
}
free(si);
}
else
{
fputs(, stderr);
}
}
}
int main(int argc, char* argv[])
{
char* list[] = { , , , };
compareAndReportStringsLength(list, 4);
return EXIT_SUCCESS;
} | 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
tkIf
tkElse
tkWhile
tkPrint
tkPutc
tkLparen
tkRparen
tkLbrace
tkRbrace
tkSemi
tkComma
tkIdent
tkInteger
tkString
)
type NodeType int
const (
ndIdent NodeType = iota
ndString
ndInteger
ndSequence
ndIf
ndPrtc
ndPrts
ndPrti
ndWhile
ndAssign
ndNegate
ndNot
ndMul
ndDiv
ndMod
ndAdd
ndSub
ndLss
ndLeq
ndGtr
ndGeq
ndEql
ndNeq
ndAnd
ndOr
)
type tokS struct {
tok TokenType
errLn int
errCol int
text string | 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/ ? bless [ $arg ], $_ :
/;/ ? bless [], 'Null' :
bless [ tree(), tree() ], $_;
}
sub Add::run { $_[0][0]->run + $_[0][1]->run }
sub And::run { $_[0][0]->run && $_[0][1]->run }
sub Assign::run { $variables{$_[0][0][0]} = $_[0][1]->run }
sub Divide::run { $_[0][0]->run / $_[0][1]->run }
sub Equal::run { $_[0][0]->run == $_[0][1]->run ? 1 : 0 }
sub Greater::run { $_[0][0]->run > $_[0][1]->run ? 1 : 0 }
sub GreaterEqual::run { $_[0][0]->run >= $_[0][1]->run ? 1 : 0 }
sub Identifier::run { $variables{$_[0][0]} // 0 }
sub If::run { $_[0][0]->run ? $_[0][1][0]->run : $_[0][1][1]->run }
sub Integer::run { $_[0][0] }
sub Less::run { $_[0][0]->run < $_[0][1]->run ? 1 : 0 }
sub LessEqual::run { $_[0][0]->run <= $_[0][1]->run ? 1 : 0 }
sub Mod::run { $_[0][0]->run % $_[0][1]->run }
sub Multiply::run { $_[0][0]->run * $_[0][1]->run }
sub Negate::run { - $_[0][0]->run }
sub Not::run { $_[0][0]->run ? 0 : 1 }
sub NotEqual::run { $_[0][0]->run != $_[0][1]->run ? 1 : 0 }
sub Null::run {}
sub Or::run { $_[0][0]->run || $_[0][1]->run }
sub Prtc::run { print chr $_[0][0]->run }
sub Prti::run { print $_[0][0]->run }
sub Prts::run { print $_[0][0][0] }
sub Sequence::run { $_->run for $_[0]->@* }
sub Subtract::run { $_[0][0]->run - $_[0][1]->run }
sub While::run { $_[0][1]->run while $_[0][0]->run } | 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; x1 <= x + 1; x1++)
if (univ[(y1 + h) % h][(x1 + w) % w])
n++;
if (univ[y][x]) n--;
new[y][x] = (n == 3 || (n == 2 && univ[y][x]));
}
for_y for_x univ[y][x] = new[y][x];
}
void game(int w, int h)
{
unsigned univ[h][w];
for_xy univ[y][x] = rand() < RAND_MAX / 10 ? 1 : 0;
while (1) {
show(univ, w, h);
evolve(univ, w, h);
usleep(200000);
}
}
int main(int c, char **v)
{
int w = 0, h = 0;
if (c > 1) w = atoi(v[1]);
if (c > 2) h = atoi(v[2]);
if (w <= 0) w = 30;
if (h <= 0) h = 30;
game(w, h);
} | 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, PUSH, ADD, SUB, MUL, DIV, MOD, LT, GT, LE, GE, EQ, NE, AND,
OR, NEG, NOT, JMP, JZ, PRTC, PRTS, PRTI, HALT
} Code_t;
typedef uchar code;
typedef struct Tree {
NodeType node_type;
struct Tree *left;
struct Tree *right;
char *value;
} Tree;
int _qy_
int _qy_
name = realloc(name, (_qy_
FILE *source_fp, *dest_fp;
static int here;
da_dim(object, code);
da_dim(globals, const char *);
da_dim(string_pool, const char *);
struct {
char *enum_text;
NodeType node_type;
Code_t opcode;
} atr[] = {
{ , nd_Ident, -1 },
{ , nd_String, -1 },
{ , nd_Integer, -1 },
{ , nd_Sequence, -1 },
{ , nd_If, -1 },
{ , nd_Prtc, -1 },
{ , nd_Prts, -1 },
{ , nd_Prti, -1 },
{ , nd_While, -1 },
{ , nd_Assign, -1 },
{ , nd_Negate, NEG},
{ , nd_Not, NOT},
{ , nd_Mul, MUL},
{ , nd_Div, DIV},
{ , nd_Mod, MOD},
{ , nd_Add, ADD},
{ , nd_Sub, SUB},
{ , nd_Lss, LT },
{ , nd_Leq, LE },
{ , nd_Gtr, GT },
{, nd_Geq, GE },
{ , nd_Eql, EQ },
{ , nd_Neq, NE },
{ , nd_And, AND},
{ , nd_Or, OR },
};
void error(const char *fmt, ... ) {
va_list ap;
char buf[1000];
va_start(ap, fmt);
vsprintf(buf, fmt, ap);
va_end(ap);
printf(, buf);
exit(1);
}
Code_t type_to_op(NodeType type) {
return atr[type].opcode;
}
Tree *make_node(NodeType node_type, Tree *left, Tree *right) {
Tree *t = calloc(sizeof(Tree), 1);
t->node_type = node_type;
t->left = left;
t->right = right;
return t;
}
Tree *make_leaf(NodeType node_type, char *value) {
Tree *t = calloc(sizeof(Tree), 1);
t->node_type = node_type;
t->value = strdup(value);
return t;
}
void emit_byte(int c) {
da_append(object, (uchar)c);
++here;
}
void emit_int(int32_t n) {
union {
int32_t n;
unsigned char c[sizeof(int32_t)];
} x;
x.n = n;
for (size_t i = 0; i < sizeof(x.n); ++i) {
emit_byte(x.c[i]);
}
}
int hole() {
int t = here;
emit_int(0);
return t;
}
void fix(int src, int dst) {
*(int32_t *)(object + src) = dst-src;
}
int fetch_var_offset(const char *id) {
for (int i = 0; i < da_len(globals); ++i) {
if (strcmp(id, globals[i]) == 0)
return i;
}
da_add(globals);
int n = da_len(globals) - 1;
globals[n] = strdup(id);
return n;
}
int fetch_string_offset(const char *st) {
for (int i = 0; i < da_len(string_pool); ++i) {
if (strcmp(st, string_pool[i]) == 0)
return i;
}
da_add(string_pool);
int n = da_len(string_pool) - 1;
string_pool[n] = strdup(st);
return n;
}
void code_gen(Tree *x) {
int p1, p2, n;
if (x == NULL) return;
switch (x->node_type) {
case nd_Ident:
emit_byte(FETCH);
n = fetch_var_offset(x->value);
emit_int(n);
break;
case nd_Integer:
emit_byte(PUSH);
emit_int(atoi(x->value));
break;
case nd_String:
emit_byte(PUSH);
n = fetch_string_offset(x->value);
emit_int(n);
break;
case nd_Assign:
n = fetch_var_offset(x->left->value);
code_gen(x->right);
emit_byte(STORE);
emit_int(n);
break;
case nd_If:
code_gen(x->left);
emit_byte(JZ);
p1 = hole();
code_gen(x->right->left);
if (x->right->right != NULL) {
emit_byte(JMP);
p2 = hole();
}
fix(p1, here);
if (x->right->right != NULL) {
code_gen(x->right->right);
fix(p2, here);
}
break;
case nd_While:
p1 = here;
code_gen(x->left);
emit_byte(JZ);
p2 = hole();
code_gen(x->right);
emit_byte(JMP);
fix(hole(), p1);
fix(p2, here);
break;
case nd_Sequence:
code_gen(x->left);
code_gen(x->right);
break;
case nd_Prtc:
code_gen(x->left);
emit_byte(PRTC);
break;
case nd_Prti:
code_gen(x->left);
emit_byte(PRTI);
break;
case nd_Prts:
code_gen(x->left);
emit_byte(PRTS);
break;
case nd_Lss: case nd_Gtr: case nd_Leq: case nd_Geq: case nd_Eql: case nd_Neq:
case nd_And: case nd_Or: case nd_Sub: case nd_Add: case nd_Div: case nd_Mul:
case nd_Mod:
code_gen(x->left);
code_gen(x->right);
emit_byte(type_to_op(x->node_type));
break;
case nd_Negate: case nd_Not:
code_gen(x->left);
emit_byte(type_to_op(x->node_type));
break;
default:
error(, x->node_type);
}
}
void code_finish() {
emit_byte(HALT);
}
void list_code() {
fprintf(dest_fp, , da_len(globals), da_len(string_pool));
for (int i = 0; i < da_len(string_pool); ++i)
fprintf(dest_fp, , string_pool[i]);
code *pc = object;
again: fprintf(dest_fp, , (int)(pc - object));
switch (*pc++) {
case FETCH: fprintf(dest_fp, , *(int32_t *)pc);
pc += sizeof(int32_t); goto again;
case STORE: fprintf(dest_fp, , *(int32_t *)pc);
pc += sizeof(int32_t); goto again;
case PUSH : fprintf(dest_fp, , *(int32_t *)pc);
pc += sizeof(int32_t); goto again;
case ADD : fprintf(dest_fp, ); goto again;
case SUB : fprintf(dest_fp, ); goto again;
case MUL : fprintf(dest_fp, ); goto again;
case DIV : fprintf(dest_fp, ); goto again;
case MOD : fprintf(dest_fp, ); goto again;
case LT : fprintf(dest_fp, ); goto again;
case GT : fprintf(dest_fp, ); goto again;
case LE : fprintf(dest_fp, ); goto again;
case GE : fprintf(dest_fp, ); goto again;
case EQ : fprintf(dest_fp, ); goto again;
case NE : fprintf(dest_fp, ); goto again;
case AND : fprintf(dest_fp, ); goto again;
case OR : fprintf(dest_fp, ); goto again;
case NOT : fprintf(dest_fp, ); goto again;
case NEG : fprintf(dest_fp, ); goto again;
case JMP : fprintf(dest_fp, ,
*(int32_t *)pc, (int32_t)(pc + *(int32_t *)pc - object));
pc += sizeof(int32_t); goto again;
case JZ : fprintf(dest_fp, ,
*(int32_t *)pc, (int32_t)(pc + *(int32_t *)pc - object));
pc += sizeof(int32_t); goto again;
case PRTC : fprintf(dest_fp, ); goto again;
case PRTI : fprintf(dest_fp, ); goto again;
case PRTS : fprintf(dest_fp, ); goto again;
case HALT : fprintf(dest_fp, ); break;
default:error(, *(pc - 1));
}
}
void init_io(FILE **fp, FILE *std, const char mode[], const char fn[]) {
if (fn[0] == '\0')
*fp = std;
else if ((*fp = fopen(fn, mode)) == NULL)
error(0, 0, , fn);
}
NodeType get_enum_value(const char name[]) {
for (size_t i = 0; i < sizeof(atr) / sizeof(atr[0]); i++) {
if (strcmp(atr[i].enum_text, name) == 0) {
return atr[i].node_type;
}
}
error(, name);
return -1;
}
char *read_line(int *len) {
static char *text = NULL;
static int textmax = 0;
for (*len = 0; ; (*len)++) {
int ch = fgetc(source_fp);
if (ch == EOF || ch == '\n') {
if (*len == 0)
return NULL;
break;
}
if (*len + 1 >= textmax) {
textmax = (textmax == 0 ? 128 : textmax * 2);
text = realloc(text, textmax);
}
text[*len] = ch;
}
text[*len] = '\0';
return text;
}
char *rtrim(char *text, int *len) {
for (; *len > 0 && isspace(text[*len - 1]); --(*len))
;
text[*len] = '\0';
return text;
}
Tree *load_ast() {
int len;
char *yytext = read_line(&len);
yytext = rtrim(yytext, &len);
char *tok = strtok(yytext, );
if (tok[0] == ';') {
return NULL;
}
NodeType node_type = get_enum_value(tok);
char *p = tok + strlen(tok);
if (p != &yytext[len]) {
for (++p; isspace(*p); ++p)
;
return make_leaf(node_type, p);
}
Tree *left = load_ast();
Tree *right = load_ast();
return make_node(node_type, left, right);
}
int main(int argc, char *argv[]) {
init_io(&source_fp, stdin, , argc > 1 ? argv[1] : );
init_io(&dest_fp, stdout, , argc > 2 ? argv[2] : );
code_gen(load_ast());
code_finish();
list_code();
return 0;
} | 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 = {
: 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}
input_file = None
globals = {}
def error(msg):
print(% (msg))
exit(1)
class Node:
def __init__(self, node_type, left = None, right = None, value = None):
self.node_type = node_type
self.left = left
self.right = right
self.value = value
def make_node(oper, left, right = None):
return Node(oper, left, right)
def make_leaf(oper, n):
return Node(oper, value = n)
def fetch_var(var_name):
n = globals.get(var_name, None)
if n == None:
globals[var_name] = n = 0
return n
def interp(x):
global globals
if x == None: return None
elif x.node_type == nd_Integer: return int(x.value)
elif x.node_type == nd_Ident: return fetch_var(x.value)
elif x.node_type == nd_String: return x.value
elif x.node_type == nd_Assign:
globals[x.left.value] = interp(x.right)
return None
elif x.node_type == nd_Add: return interp(x.left) + interp(x.right)
elif x.node_type == nd_Sub: return interp(x.left) - interp(x.right)
elif x.node_type == nd_Mul: return interp(x.left) * interp(x.right)
elif x.node_type == nd_Div: return int(float(interp(x.left)) / interp(x.right))
elif x.node_type == nd_Mod: return int(float(interp(x.left))% interp(x.right))
elif x.node_type == nd_Lss: return interp(x.left) < interp(x.right)
elif x.node_type == nd_Gtr: return interp(x.left) > interp(x.right)
elif x.node_type == nd_Leq: return interp(x.left) <= interp(x.right)
elif x.node_type == nd_Geq: return interp(x.left) >= interp(x.right)
elif x.node_type == nd_Eql: return interp(x.left) == interp(x.right)
elif x.node_type == nd_Neq: return interp(x.left) != interp(x.right)
elif x.node_type == nd_And: return interp(x.left) and interp(x.right)
elif x.node_type == nd_Or: return interp(x.left) or interp(x.right)
elif x.node_type == nd_Negate: return -interp(x.left)
elif x.node_type == nd_Not: return not interp(x.left)
elif x.node_type == nd_If:
if (interp(x.left)):
interp(x.right.left)
else:
interp(x.right.right)
return None
elif x.node_type == nd_While:
while (interp(x.left)):
interp(x.right)
return None
elif x.node_type == nd_Prtc:
print(% (interp(x.left)), end='')
return None
elif x.node_type == nd_Prti:
print(% (interp(x.left)), end='')
return None
elif x.node_type == nd_Prts:
print(interp(x.left), end='')
return None
elif x.node_type == nd_Sequence:
interp(x.left)
interp(x.right)
return None
else:
error(% (x.node_type))
def str_trans(srce):
dest =
i = 0
srce = srce[1:-1]
while i < len(srce):
if srce[i] == '\\' and i + 1 < len(srce):
if srce[i + 1] == 'n':
dest += '\n'
i += 2
elif srce[i + 1] == '\\':
dest += '\\'
i += 2
else:
dest += srce[i]
i += 1
return dest
def load_ast():
line = input_file.readline()
line_list = shlex.split(line, False, False)
text = line_list[0]
value = None
if len(line_list) > 1:
value = line_list[1]
if value.isdigit():
value = int(value)
if text == :
return None
node_type = all_syms[text]
if value != None:
if node_type == nd_String:
value = str_trans(value)
return make_leaf(node_type, value)
left = load_ast()
right = load_ast()
return make_node(node_type, left, right)
input_file = sys.stdin
if len(sys.argv) > 1:
try:
input_file = open(sys.argv[1], , 4096)
except IOError as e:
error(0, 0, % sys.argv[1])
n = load_ast()
interp(n) | 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 class Node {
public NodeType nt;
public Node left, right;
public String value;
Node() {
this.nt = null;
this.left = null;
this.right = null;
this.value = null;
}
Node(NodeType node_type, Node left, Node right, String value) {
this.nt = node_type;
this.left = left;
this.right = right;
this.value = value;
}
public static Node make_node(NodeType nodetype, Node left, Node right) {
return new Node(nodetype, left, right, "");
}
public static Node make_node(NodeType nodetype, Node left) {
return new Node(nodetype, left, null, "");
}
public static Node make_leaf(NodeType nodetype, String value) {
return new Node(nodetype, null, null, value);
}
}
static class Token {
public TokenType tokentype;
public String value;
public int line;
public int pos;
Token(TokenType token, String value, int line, int pos) {
this.tokentype = token; this.value = value; this.line = line; this.pos = pos;
}
@Override
public String toString() {
return String.format("%5d %5d%-15s%s", this.line, this.pos, this.tokentype, this.value);
}
}
static enum TokenType {
End_of_input(false, false, false, -1, NodeType.nd_None),
Op_multiply(false, true, false, 13, NodeType.nd_Mul),
Op_divide(false, true, false, 13, NodeType.nd_Div),
Op_mod(false, true, false, 13, NodeType.nd_Mod),
Op_add(false, true, false, 12, NodeType.nd_Add),
Op_subtract(false, true, false, 12, NodeType.nd_Sub),
Op_negate(false, false, true, 14, NodeType.nd_Negate),
Op_not(false, false, true, 14, NodeType.nd_Not),
Op_less(false, true, false, 10, NodeType.nd_Lss),
Op_lessequal(false, true, false, 10, NodeType.nd_Leq),
Op_greater(false, true, false, 10, NodeType.nd_Gtr),
Op_greaterequal(false, true, false, 10, NodeType.nd_Geq),
Op_equal(false, true, true, 9, NodeType.nd_Eql),
Op_notequal(false, true, false, 9, NodeType.nd_Neq),
Op_assign(false, false, false, -1, NodeType.nd_Assign),
Op_and(false, true, false, 5, NodeType.nd_And),
Op_or(false, true, false, 4, NodeType.nd_Or),
Keyword_if(false, false, false, -1, NodeType.nd_If),
Keyword_else(false, false, false, -1, NodeType.nd_None),
Keyword_while(false, false, false, -1, NodeType.nd_While),
Keyword_print(false, false, false, -1, NodeType.nd_None),
Keyword_putc(false, false, false, -1, NodeType.nd_None),
LeftParen(false, false, false, -1, NodeType.nd_None),
RightParen(false, false, false, -1, NodeType.nd_None),
LeftBrace(false, false, false, -1, NodeType.nd_None),
RightBrace(false, false, false, -1, NodeType.nd_None),
Semicolon(false, false, false, -1, NodeType.nd_None),
Comma(false, false, false, -1, NodeType.nd_None),
Identifier(false, false, false, -1, NodeType.nd_Ident),
Integer(false, false, false, -1, NodeType.nd_Integer),
String(false, false, false, -1, NodeType.nd_String);
private final int precedence;
private final boolean right_assoc;
private final boolean is_binary;
private final boolean is_unary;
private final NodeType node_type;
TokenType(boolean right_assoc, boolean is_binary, boolean is_unary, int precedence, NodeType node) {
this.right_assoc = right_assoc;
this.is_binary = is_binary;
this.is_unary = is_unary;
this.precedence = precedence;
this.node_type = node;
}
boolean isRightAssoc() { return this.right_assoc; }
boolean isBinary() { return this.is_binary; }
boolean isUnary() { return this.is_unary; }
int getPrecedence() { return this.precedence; }
NodeType getNodeType() { return this.node_type; }
}
static enum NodeType {
nd_None(""), nd_Ident("Identifier"), nd_String("String"), nd_Integer("Integer"), nd_Sequence("Sequence"), nd_If("If"),
nd_Prtc("Prtc"), nd_Prts("Prts"), nd_Prti("Prti"), nd_While("While"),
nd_Assign("Assign"), nd_Negate("Negate"), nd_Not("Not"), nd_Mul("Multiply"), nd_Div("Divide"), nd_Mod("Mod"), nd_Add("Add"),
nd_Sub("Subtract"), nd_Lss("Less"), nd_Leq("LessEqual"),
nd_Gtr("Greater"), nd_Geq("GreaterEqual"), nd_Eql("Equal"), nd_Neq("NotEqual"), nd_And("And"), nd_Or("Or");
private final String name;
NodeType(String name) {
this.name = name;
}
@Override
public String toString() { return this.name; }
}
static void error(int line, int pos, String msg) {
if (line > 0 && pos > 0) {
System.out.printf("%s in line%d, pos%d\n", msg, line, pos);
} else {
System.out.println(msg);
}
System.exit(1);
}
Parser(List<Token> source) {
this.source = source;
this.token = null;
this.position = 0;
}
Token getNextToken() {
this.token = this.source.get(this.position++);
return this.token;
}
Node expr(int p) {
Node result = null, node;
TokenType op;
int q;
if (this.token.tokentype == TokenType.LeftParen) {
result = paren_expr();
} else if (this.token.tokentype == TokenType.Op_add || this.token.tokentype == TokenType.Op_subtract) {
op = (this.token.tokentype == TokenType.Op_subtract) ? TokenType.Op_negate : TokenType.Op_add;
getNextToken();
node = expr(TokenType.Op_negate.getPrecedence());
result = (op == TokenType.Op_negate) ? Node.make_node(NodeType.nd_Negate, node) : node;
} else if (this.token.tokentype == TokenType.Op_not) {
getNextToken();
result = Node.make_node(NodeType.nd_Not, expr(TokenType.Op_not.getPrecedence()));
} else if (this.token.tokentype == TokenType.Identifier) {
result = Node.make_leaf(NodeType.nd_Ident, this.token.value);
getNextToken();
} else if (this.token.tokentype == TokenType.Integer) {
result = Node.make_leaf(NodeType.nd_Integer, this.token.value);
getNextToken();
} else {
error(this.token.line, this.token.pos, "Expecting a primary, found: " + this.token.tokentype);
}
while (this.token.tokentype.isBinary() && this.token.tokentype.getPrecedence() >= p) {
op = this.token.tokentype;
getNextToken();
q = op.getPrecedence();
if (!op.isRightAssoc()) {
q++;
}
node = expr(q);
result = Node.make_node(op.getNodeType(), result, node);
}
return result;
}
Node paren_expr() {
expect("paren_expr", TokenType.LeftParen);
Node node = expr(0);
expect("paren_expr", TokenType.RightParen);
return node;
}
void expect(String msg, TokenType s) {
if (this.token.tokentype == s) {
getNextToken();
return;
}
error(this.token.line, this.token.pos, msg + ": Expecting '" + s + "', found: '" + this.token.tokentype + "'");
}
Node stmt() {
Node s, s2, t = null, e, v;
if (this.token.tokentype == TokenType.Keyword_if) {
getNextToken();
e = paren_expr();
s = stmt();
s2 = null;
if (this.token.tokentype == TokenType.Keyword_else) {
getNextToken();
s2 = stmt();
}
t = Node.make_node(NodeType.nd_If, e, Node.make_node(NodeType.nd_If, s, s2));
} else if (this.token.tokentype == TokenType.Keyword_putc) {
getNextToken();
e = paren_expr();
t = Node.make_node(NodeType.nd_Prtc, e);
expect("Putc", TokenType.Semicolon);
} else if (this.token.tokentype == TokenType.Keyword_print) {
getNextToken();
expect("Print", TokenType.LeftParen);
while (true) {
if (this.token.tokentype == TokenType.String) {
e = Node.make_node(NodeType.nd_Prts, Node.make_leaf(NodeType.nd_String, this.token.value));
getNextToken();
} else {
e = Node.make_node(NodeType.nd_Prti, expr(0), null);
}
t = Node.make_node(NodeType.nd_Sequence, t, e);
if (this.token.tokentype != TokenType.Comma) {
break;
}
getNextToken();
}
expect("Print", TokenType.RightParen);
expect("Print", TokenType.Semicolon);
} else if (this.token.tokentype == TokenType.Semicolon) {
getNextToken();
} else if (this.token.tokentype == TokenType.Identifier) {
v = Node.make_leaf(NodeType.nd_Ident, this.token.value);
getNextToken();
expect("assign", TokenType.Op_assign);
e = expr(0);
t = Node.make_node(NodeType.nd_Assign, v, e);
expect("assign", TokenType.Semicolon);
} else if (this.token.tokentype == TokenType.Keyword_while) {
getNextToken();
e = paren_expr();
s = stmt();
t = Node.make_node(NodeType.nd_While, e, s);
} else if (this.token.tokentype == TokenType.LeftBrace) {
getNextToken();
while (this.token.tokentype != TokenType.RightBrace && this.token.tokentype != TokenType.End_of_input) {
t = Node.make_node(NodeType.nd_Sequence, t, stmt());
}
expect("LBrace", TokenType.RightBrace);
} else if (this.token.tokentype == TokenType.End_of_input) {
} else {
error(this.token.line, this.token.pos, "Expecting start of statement, found: " + this.token.tokentype);
}
return t;
}
Node parse() {
Node t = null;
getNextToken();
while (this.token.tokentype != TokenType.End_of_input) {
t = Node.make_node(NodeType.nd_Sequence, t, stmt());
}
return t;
}
void printAST(Node t) {
int i = 0;
if (t == null) {
System.out.println(";");
} else {
System.out.printf("%-14s", t.nt);
if (t.nt == NodeType.nd_Ident || t.nt == NodeType.nd_Integer || t.nt == NodeType.nd_String) {
System.out.println(" " + t.value);
} else {
System.out.println();
printAST(t.left);
printAST(t.right);
}
}
}
public static void main(String[] args) {
if (args.length > 0) {
try {
String value, token;
int line, pos;
Token t;
boolean found;
List<Token> list = new ArrayList<>();
Map<String, TokenType> str_to_tokens = new HashMap<>();
str_to_tokens.put("End_of_input", TokenType.End_of_input);
str_to_tokens.put("Op_multiply", TokenType.Op_multiply);
str_to_tokens.put("Op_divide", TokenType.Op_divide);
str_to_tokens.put("Op_mod", TokenType.Op_mod);
str_to_tokens.put("Op_add", TokenType.Op_add);
str_to_tokens.put("Op_subtract", TokenType.Op_subtract);
str_to_tokens.put("Op_negate", TokenType.Op_negate);
str_to_tokens.put("Op_not", TokenType.Op_not);
str_to_tokens.put("Op_less", TokenType.Op_less);
str_to_tokens.put("Op_lessequal", TokenType.Op_lessequal);
str_to_tokens.put("Op_greater", TokenType.Op_greater);
str_to_tokens.put("Op_greaterequal", TokenType.Op_greaterequal);
str_to_tokens.put("Op_equal", TokenType.Op_equal);
str_to_tokens.put("Op_notequal", TokenType.Op_notequal);
str_to_tokens.put("Op_assign", TokenType.Op_assign);
str_to_tokens.put("Op_and", TokenType.Op_and);
str_to_tokens.put("Op_or", TokenType.Op_or);
str_to_tokens.put("Keyword_if", TokenType.Keyword_if);
str_to_tokens.put("Keyword_else", TokenType.Keyword_else);
str_to_tokens.put("Keyword_while", TokenType.Keyword_while);
str_to_tokens.put("Keyword_print", TokenType.Keyword_print);
str_to_tokens.put("Keyword_putc", TokenType.Keyword_putc);
str_to_tokens.put("LeftParen", TokenType.LeftParen);
str_to_tokens.put("RightParen", TokenType.RightParen);
str_to_tokens.put("LeftBrace", TokenType.LeftBrace);
str_to_tokens.put("RightBrace", TokenType.RightBrace);
str_to_tokens.put("Semicolon", TokenType.Semicolon);
str_to_tokens.put("Comma", TokenType.Comma);
str_to_tokens.put("Identifier", TokenType.Identifier);
str_to_tokens.put("Integer", TokenType.Integer);
str_to_tokens.put("String", TokenType.String);
Scanner s = new Scanner(new File(args[0]));
String source = " ";
while (s.hasNext()) {
String str = s.nextLine();
StringTokenizer st = new StringTokenizer(str);
line = Integer.parseInt(st.nextToken());
pos = Integer.parseInt(st.nextToken());
token = st.nextToken();
value = "";
while (st.hasMoreTokens()) {
value += st.nextToken() + " ";
}
found = false;
if (str_to_tokens.containsKey(token)) {
found = true;
list.add(new Token(str_to_tokens.get(token), value, line, pos));
}
if (found == false) {
throw new Exception("Token not found: '" + token + "'");
}
}
Parser p = new Parser(list);
p.printAST(p.parse());
} catch (FileNotFoundException e) {
error(-1, -1, "Exception: " + e.getMessage());
} catch (Exception e) {
error(-1, -1, "Exception: " + e.getMessage());
}
} else {
error(-1, -1, "No args");
}
}
} | 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: " ", count: 62), count: 31)
for _ in 0..<nPoints {
let (x, y) = generatePoint()
rows[y + 15][x + 15 * 2] = "*"
}
for row in rows {
print(row.joined())
}
}
func precalculatingMethod() {
var possiblePoints = [(Int, Int)]()
for y in -15...15 {
for x in -15...15 {
let r2 = x * x + y * y
if r2 >= 100 && r2 <= 225 {
possiblePoints.append((x, y))
}
}
}
possiblePoints.shuffle()
var rows = [[String]](repeating: Array(repeating: " ", count: 62), count: 31)
for (x, y) in possiblePoints {
rows[y + 15][x + 15 * 2] = "*"
}
for row in rows {
print(row.joined())
}
}
print("Filtering method:")
filteringMethod()
print("Precalculating method:")
precalculatingMethod() | 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
jz
prtc
prts
prti
halt
)
var codeMap = map[string]code{
"fetch": fetch,
"store": store,
"push": push,
"add": add,
"sub": sub,
"mul": mul,
"div": div,
"mod": mod,
"lt": lt,
"gt": gt,
"le": le,
"ge": ge,
"eq": eq,
"ne": ne,
"and": and,
"or": or,
"neg": neg,
"not": not,
"jmp": jmp,
"jz": jz,
"prtc": prtc,
"prts": prts,
"prti": prti,
"halt": halt,
}
var (
err error
scanner *bufio.Scanner
object []code
stringPool []string
)
func reportError(msg string) {
log.Fatalf("error:%s\n", msg)
}
func check(err error) {
if err != nil {
log.Fatal(err)
}
}
func btoi(b bool) int32 {
if b {
return 1
}
return 0
}
func itob(i int32) bool {
if i != 0 {
return true
}
return false
}
func emitByte(c code) {
object = append(object, c)
}
func emitWord(n int) {
bs := make([]byte, 4)
binary.LittleEndian.PutUint32(bs, uint32(n))
for _, b := range bs {
emitByte(code(b))
}
}
func runVM(dataSize int) {
stack := make([]int32, dataSize+1)
pc := int32(0)
for {
op := object[pc]
pc++
switch op {
case fetch:
x := int32(binary.LittleEndian.Uint32(object[pc : pc+4]))
stack = append(stack, stack[x])
pc += 4
case store:
x := int32(binary.LittleEndian.Uint32(object[pc : pc+4]))
ln := len(stack)
stack[x] = stack[ln-1]
stack = stack[:ln-1]
pc += 4
case push:
x := int32(binary.LittleEndian.Uint32(object[pc : pc+4]))
stack = append(stack, x)
pc += 4
case add:
ln := len(stack)
stack[ln-2] += stack[ln-1]
stack = stack[:ln-1]
case sub:
ln := len(stack)
stack[ln-2] -= stack[ln-1]
stack = stack[:ln-1]
case mul:
ln := len(stack)
stack[ln-2] *= stack[ln-1]
stack = stack[:ln-1]
case div:
ln := len(stack)
stack[ln-2] = int32(float64(stack[ln-2]) / float64(stack[ln-1]))
stack = stack[:ln-1]
case mod:
ln := len(stack)
stack[ln-2] = int32(math.Mod(float64(stack[ln-2]), float64(stack[ln-1])))
stack = stack[:ln-1]
case lt:
ln := len(stack)
stack[ln-2] = btoi(stack[ln-2] < stack[ln-1])
stack = stack[:ln-1]
case gt:
ln := len(stack)
stack[ln-2] = btoi(stack[ln-2] > stack[ln-1])
stack = stack[:ln-1]
case le:
ln := len(stack)
stack[ln-2] = btoi(stack[ln-2] <= stack[ln-1])
stack = stack[:ln-1]
case ge:
ln := len(stack)
stack[ln-2] = btoi(stack[ln-2] >= stack[ln-1])
stack = stack[:ln-1]
case eq:
ln := len(stack)
stack[ln-2] = btoi(stack[ln-2] == stack[ln-1])
stack = stack[:ln-1]
case ne:
ln := len(stack)
stack[ln-2] = btoi(stack[ln-2] != stack[ln-1])
stack = stack[:ln-1]
case and:
ln := len(stack)
stack[ln-2] = btoi(itob(stack[ln-2]) && itob(stack[ln-1]))
stack = stack[:ln-1]
case or:
ln := len(stack)
stack[ln-2] = btoi(itob(stack[ln-2]) || itob(stack[ln-1]))
stack = stack[:ln-1]
case neg:
ln := len(stack)
stack[ln-1] = -stack[ln-1]
case not:
ln := len(stack)
stack[ln-1] = btoi(!itob(stack[ln-1]))
case jmp:
x := int32(binary.LittleEndian.Uint32(object[pc : pc+4]))
pc += x
case jz:
ln := len(stack)
v := stack[ln-1]
stack = stack[:ln-1]
if v != 0 {
pc += 4
} else {
x := int32(binary.LittleEndian.Uint32(object[pc : pc+4]))
pc += x
}
case prtc:
ln := len(stack)
fmt.Printf("%c", stack[ln-1])
stack = stack[:ln-1]
case prts:
ln := len(stack)
fmt.Printf("%s", stringPool[stack[ln-1]])
stack = stack[:ln-1]
case prti:
ln := len(stack)
fmt.Printf("%d", stack[ln-1])
stack = stack[:ln-1]
case halt:
return
default:
reportError(fmt.Sprintf("Unknown opcode%d\n", op))
}
}
}
func translate(s string) string {
var d strings.Builder
for i := 0; i < len(s); i++ {
if s[i] == '\\' && (i+1) < len(s) {
if s[i+1] == 'n' {
d.WriteByte('\n')
i++
} else if s[i+1] == '\\' {
d.WriteByte('\\')
i++
}
} else {
d.WriteByte(s[i])
}
}
return d.String()
}
func loadCode() int {
var dataSize int
firstLine := true
for scanner.Scan() {
line := strings.TrimRight(scanner.Text(), " \t")
if len(line) == 0 {
if firstLine {
reportError("empty line")
} else {
break
}
}
lineList := strings.Fields(line)
if firstLine {
dataSize, err = strconv.Atoi(lineList[1])
check(err)
nStrings, err := strconv.Atoi(lineList[3])
check(err)
for i := 0; i < nStrings; i++ {
scanner.Scan()
s := strings.Trim(scanner.Text(), "\"\n")
stringPool = append(stringPool, translate(s))
}
firstLine = false
continue
}
offset, err := strconv.Atoi(lineList[0])
check(err)
instr := lineList[1]
opCode, ok := codeMap[instr]
if !ok {
reportError(fmt.Sprintf("Unknown instruction%s at%d", instr, opCode))
}
emitByte(opCode)
switch opCode {
case jmp, jz:
p, err := strconv.Atoi(lineList[3])
check(err)
emitWord(p - offset - 1)
case push:
value, err := strconv.Atoi(lineList[2])
check(err)
emitWord(value)
case fetch, store:
value, err := strconv.Atoi(strings.Trim(lineList[2], "[]"))
check(err)
emitWord(value)
}
}
check(scanner.Err())
return dataSize
}
func main() {
codeGen, err := os.Open("codegen.txt")
check(err)
defer codeGen.Close()
scanner = bufio.NewScanner(codeGen)
runVM(loadCode())
} | 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 (timed . run) ns
where
ns = take 15 $ iterate (\x -> (x * 5) `div` 3) 10
run n = pure $ length $ srt (take n set)
constant = repeat 1
presorted = [1..]
random = (`mod` 100) <$> iterate step 42
where
step x = (x * a + c) `mod` m
(a, c, m) = (1103515245, 12345, 2^31-1) | 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 =
if (!lines.hasNext)
TerminalNode
else
lines.next.split(" +", 2) match {
case Array(name, value) => LeafNode(name, value)
case Array(";") => TerminalNode
case Array(name) => BranchNode(name, load, load)
}
val vars = new mutable.HashMap[String, Any]
def interpInt(n: Node) = interp(n).asInstanceOf[Int]
def interpBoolean(n: Node) = interp(n).asInstanceOf[Boolean]
def interp(n: Node): Any =
n match {
case TerminalNode => null
case LeafNode("Identifier", name) =>
vars get name match {
case None =>
vars(name) = 0
0
case Some(v) => v
}
case LeafNode("Integer", "'\\n'") => '\n'.toInt
case LeafNode("Integer", "'\\\\'") => '\\'.toInt
case LeafNode("Integer", value: String) if value startsWith "'" => value(1).toInt
case LeafNode("Integer", value: String) => value.toInt
case LeafNode("String", value: String) => unescape(value.substring(1, value.length - 1))
case BranchNode("Assign", LeafNode(_, name), exp) => vars(name) = interp(exp)
case BranchNode("Sequence", l, r) => interp(l); interp(r)
case BranchNode("Prts" | "Prti", a, _) => print(interp(a))
case BranchNode("Prtc", a, _) => print(interpInt(a).toChar)
case BranchNode("Add", l, r) => interpInt(l) + interpInt(r)
case BranchNode("Subtract", l, r) => interpInt(l) - interpInt(r)
case BranchNode("Multiply", l, r) => interpInt(l) * interpInt(r)
case BranchNode("Divide", l, r) => interpInt(l) / interpInt(r)
case BranchNode("Mod", l, r) => interpInt(l) % interpInt(r)
case BranchNode("Negate", a, _) => -interpInt(a)
case BranchNode("Less", l, r) => interpInt(l) < interpInt(r)
case BranchNode("LessEqual", l, r) => interpInt(l) <= interpInt(r)
case BranchNode("Greater", l, r) => interpInt(l) > interpInt(r)
case BranchNode("GreaterEqual", l, r) => interpInt(l) >= interpInt(r)
case BranchNode("Equal", l, r) => interpInt(l) == interpInt(r)
case BranchNode("NotEqual", l, r) => interpInt(l) != interpInt(r)
case BranchNode("And", l, r) => interpBoolean(l) && interpBoolean(r)
case BranchNode("Or", l, r) => interpBoolean(l) || interpBoolean(r)
case BranchNode("Not", a, _) => !interpBoolean(a)
case BranchNode("While", l, r) => while (interpBoolean(l)) interp(r)
case BranchNode("If", cond, BranchNode("If", yes, no)) => if (interpBoolean(cond)) interp(yes) else interp(no)
}
interp(load)
}
abstract class Node
case class BranchNode(name: String, left: Node, right: Node) extends Node
case class LeafNode(name: String, value: String) extends Node
case object TerminalNode extends 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) (contains? set-of-cells cell)))]
cell)))
(defn print-world
([set-of-cells] (print-world set-of-cells 10))
([set-of-cells world-size]
(let [r (range 0 (+ 1 world-size))]
(pprint (for [y r] (apply str (for [x r] (if (set-of-cells [x y]) \# \.))))))))
(defn run-life [world-size num-steps set-of-cells]
(loop [s num-steps
cells set-of-cells]
(print-world cells world-size)
(when (< 0 s)
(recur (- s 1) (step cells)))))
(def *blinker* #{[1 2] [2 2] [3 2]})
(def *glider* #{[1 0] [2 1] [0 2] [1 2] [2 2]}) | 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 commatize(s string, startIndex, period int, sep string) string {
if startIndex < 0 || startIndex >= len(s) || period < 1 || sep == "" {
return s
}
m := reg.FindString(s[startIndex:]) | 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
ndDiv
ndMod
ndAdd
ndSub
ndLss
ndLeq
ndGtr
ndGeq
ndEql
ndNeq
ndAnd
ndOr
)
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
jz
prtc
prts
prti
halt
)
type Tree struct {
nodeType NodeType
left *Tree
right *Tree
value string
} | 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 = [str]
| otherwise = let (pfx, sfx) = splitAt by str
in pfx: chopUp by sfx
addSeps :: String -> Char -> Int -> (String -> String) -> String
addSeps str sep by rev =
let (leading, number) = span (== '0') str
number2 = rev $ intercalate [sep] $ chopUp by $ rev number
in leading ++ number2
processNumber :: String -> Char -> Int -> String
processNumber str sep by =
let (beforeDecimal, rest) = span isDigit str
(decimal, afterDecimal) = splitAt 1 rest
beforeDecimal2 = addSeps beforeDecimal sep by reverse
afterDecimal2 = addSeps afterDecimal sep by id
in beforeDecimal2 ++ decimal ++ afterDecimal2
commatize2 :: String -> Char -> Int -> String
commatize2 [] _ _ = []
commatize2 str sep by =
let (pfx, sfx) = break isDigitOrPeriod str
(number, sfx2) = span isDigitOrPeriod sfx
in pfx ++ processNumber number sep by ++ sfx2
commatize :: String -> Maybe Char -> Maybe Int -> String
commatize str sep by = commatize2 str (fromMaybe ',' sep) (fromMaybe 3 by)
input :: [(String, Maybe Char, Maybe Int)]
input =
[ ("pi=3.14159265358979323846264338327950288419716939937510582097494459231", Just ' ', Just 5)
, ("The author has two Z$100000000000000 Zimbabwe notes (100 trillion).", Just '.', Nothing)
, ("\"-in Aus$+1411.8millions\"", Nothing, Nothing)
, ("===US$0017440 millions=== (in 2000 dollars)", Nothing, Nothing)
, ("123.e8000 is pretty big.", Nothing, Nothing)
, ("The land area of the earth is 57268900(29% of the surface) square miles.", Nothing, Nothing)
, ("Ain't no numbers in this here words, nohow, no way, Jose.", Nothing, Nothing)
, ("James was never known as 0000000007", Nothing, Nothing)
, ("Arthur Eddington wrote: I believe there are 15747724136275002577605653961181555468044717914527116709366231425076185631031296 protons in the universe.", Nothing, Nothing)
, (" $-140000100 millions.", Nothing, Nothing)
, ("6/9/1946 was a good year for some.", Nothing, Nothing)
]
main :: IO ()
main =
forM_ input $ \(str, by, sep) -> do
putStrLn str
putStrLn $ commatize str by sep
putStrLn "" | 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;
compareAndReportStringsLength(strings);
}
public static void compareAndReportStringsLength(String[] strings) {
compareAndReportStringsLength(strings, System.out);
}
public static void compareAndReportStringsLength(String[] strings, PrintStream stream) {
if (strings.length > 0) {
strings = strings.clone();
final String QUOTE = "\"";
Arrays.sort(strings, Comparator.comparing(String::length));
int min = strings[0].length();
int max = strings[strings.length - 1].length();
for (int i = strings.length - 1; i >= 0; i--) {
int length = strings[i].length();
String predicate;
if (length == max) {
predicate = "is the longest string";
} else if (length == min) {
predicate = "is the shortest string";
} else {
predicate = "is neither the longest nor the shortest string";
} | 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 has two Z$100000000000000 Zimbabwe notes (100 "
+ "trillion).", 0, 3, ".");
try (Scanner sc = new Scanner(new File("input.txt"))) {
while(sc.hasNext())
commatize(sc.nextLine());
}
}
static void commatize(String s) {
commatize(s, 0, 3, ",");
}
static void commatize(String s, int start, int step, String ins) {
if (start < 0 || start > s.length() || step < 1 || step > s.length())
return;
Matcher m = Pattern.compile("([1-9][0-9]*)").matcher(s.substring(start));
StringBuffer result = new StringBuffer(s.substring(0, start));
if (m.find()) {
StringBuilder sb = new StringBuilder(m.group(1)).reverse();
for (int i = step; i < sb.length(); i += step)
sb.insert(i++, ins);
m.appendReplacement(result, sb.reverse().toString());
}
System.out.println(m.appendTail(result));
}
} | 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 < nstrings; i++)
if (strcmp(strings[i - 1], strings[i]) >= 0)
return false;
return true;
} | 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);
gmp_printf(, x);
return 0;
} | 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, NodeType> str_to_nodes = new HashMap<>();
static List<String> string_pool = new ArrayList<>();
static List<String> variables = new ArrayList<>();
static int string_count = 0;
static int var_count = 0;
static Scanner s;
static NodeType[] unary_ops = {
NodeType.nd_Negate, NodeType.nd_Not
};
static NodeType[] operators = {
NodeType.nd_Mul, NodeType.nd_Div, NodeType.nd_Mod, NodeType.nd_Add, NodeType.nd_Sub,
NodeType.nd_Lss, NodeType.nd_Leq, NodeType.nd_Gtr, NodeType.nd_Geq,
NodeType.nd_Eql, NodeType.nd_Neq, NodeType.nd_And, NodeType.nd_Or
};
static enum Mnemonic {
NONE, FETCH, STORE, PUSH, ADD, SUB, MUL, DIV, MOD, LT, GT, LE, GE, EQ, NE, AND, OR, NEG, NOT,
JMP, JZ, PRTC, PRTS, PRTI, HALT
}
static class Node {
public NodeType nt;
public Node left, right;
public String value;
Node() {
this.nt = null;
this.left = null;
this.right = null;
this.value = null;
}
Node(NodeType node_type, Node left, Node right, String value) {
this.nt = node_type;
this.left = left;
this.right = right;
this.value = value;
}
public static Node make_node(NodeType nodetype, Node left, Node right) {
return new Node(nodetype, left, right, "");
}
public static Node make_node(NodeType nodetype, Node left) {
return new Node(nodetype, left, null, "");
}
public static Node make_leaf(NodeType nodetype, String value) {
return new Node(nodetype, null, null, value);
}
}
static enum NodeType {
nd_None("", Mnemonic.NONE), nd_Ident("Identifier", Mnemonic.NONE), nd_String("String", Mnemonic.NONE), nd_Integer("Integer", Mnemonic.NONE), nd_Sequence("Sequence", Mnemonic.NONE),
nd_If("If", Mnemonic.NONE),
nd_Prtc("Prtc", Mnemonic.NONE), nd_Prts("Prts", Mnemonic.NONE), nd_Prti("Prti", Mnemonic.NONE), nd_While("While", Mnemonic.NONE),
nd_Assign("Assign", Mnemonic.NONE),
nd_Negate("Negate", Mnemonic.NEG), nd_Not("Not", Mnemonic.NOT), nd_Mul("Multiply", Mnemonic.MUL), nd_Div("Divide", Mnemonic.DIV), nd_Mod("Mod", Mnemonic.MOD), nd_Add("Add", Mnemonic.ADD),
nd_Sub("Subtract", Mnemonic.SUB), nd_Lss("Less", Mnemonic.LT), nd_Leq("LessEqual", Mnemonic.LE),
nd_Gtr("Greater", Mnemonic.GT), nd_Geq("GreaterEqual", Mnemonic.GE), nd_Eql("Equal", Mnemonic.EQ),
nd_Neq("NotEqual", Mnemonic.NE), nd_And("And", Mnemonic.AND), nd_Or("Or", Mnemonic.OR);
private final String name;
private final Mnemonic m;
NodeType(String name, Mnemonic m) {
this.name = name;
this.m = m;
}
Mnemonic getMnemonic() { return this.m; }
@Override
public String toString() { return this.name; }
}
static void appendToCode(int b) {
code = Arrays.copyOf(code, code.length + 1);
code[code.length - 1] = (byte) b;
}
static void emit_byte(Mnemonic m) {
appendToCode(m.ordinal());
}
static void emit_word(int n) {
appendToCode(n >> 24);
appendToCode(n >> 16);
appendToCode(n >> 8);
appendToCode(n);
}
static void emit_word_at(int pos, int n) {
code[pos] = (byte) (n >> 24);
code[pos + 1] = (byte) (n >> 16);
code[pos + 2] = (byte) (n >> 8);
code[pos + 3] = (byte) n;
}
static int get_word(int pos) {
int result;
result = ((code[pos] & 0xff) << 24) + ((code[pos + 1] & 0xff) << 16) + ((code[pos + 2] & 0xff) << 8) + (code[pos + 3] & 0xff) ;
return result;
}
static int fetch_var_offset(String name) {
int n;
n = variables.indexOf(name);
if (n == -1) {
variables.add(name);
n = var_count++;
}
return n;
}
static int fetch_string_offset(String str) {
int n;
n = string_pool.indexOf(str);
if (n == -1) {
string_pool.add(str);
n = string_count++;
}
return n;
}
static int hole() {
int t = code.length;
emit_word(0);
return t;
}
static boolean arrayContains(NodeType[] a, NodeType n) {
boolean result = false;
for (NodeType test: a) {
if (test.equals(n)) {
result = true;
break;
}
}
return result;
}
static void code_gen(Node x) throws Exception {
int n, p1, p2;
if (x == null) return;
switch (x.nt) {
case nd_None: return;
case nd_Ident:
emit_byte(Mnemonic.FETCH);
n = fetch_var_offset(x.value);
emit_word(n);
break;
case nd_Integer:
emit_byte(Mnemonic.PUSH);
emit_word(Integer.parseInt(x.value));
break;
case nd_String:
emit_byte(Mnemonic.PUSH);
n = fetch_string_offset(x.value);
emit_word(n);
break;
case nd_Assign:
n = fetch_var_offset(x.left.value);
code_gen(x.right);
emit_byte(Mnemonic.STORE);
emit_word(n);
break;
case nd_If:
p2 = 0; | 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';
sub stmtlist
{
/(?=$h (RightBrace|End_of_input))/gcx and return ";\n";
my ($stmt, $stmtlist) = (stmt(), stmtlist());
$stmtlist eq ";\n" ? $stmt : "Sequence\n$stmt$stmtlist";
}
sub stmt
{
/$h Semicolon\n/gcx ? ";\n" :
/$h Identifier \s+ (\w+) \n/gcx ? want("Assign\nIdentifier\t$1\n",
'Op_assign') . want expr(0), 'Semicolon' :
/$h Keyword_while \n/gcx ? "While\n" . parenexp() . stmt() :
/$h Keyword_if \n/gcx ? "If\n" . parenexp() . "If\n" . stmt() .
(/$h Keyword_else \n/gcx ? stmt() : ";\n") :
/$h Keyword_print \n/gcx ? want('', 'LeftParen') .
want want(printlist(), 'RightParen'), 'Semicolon' :
/$h Keyword_putc \n/gcx ? want "Prtc\n" . parenexp() . ";\n", 'Semicolon' :
/$h LeftBrace \n/gcx ? want stmtlist(), 'RightBrace' :
error 'A STMT';
}
sub parenexp { want('', 'LeftParen') . want expr(0), 'RightParen' }
sub printlist
{
my $ast = /$h String \s+ (".*") \n/gcx ?
"Prts\nString\t\t$1\n;\n" : "Prti\n" . expr(0) . ";\n";
/$h Comma \n/gcx ? "Sequence\n$ast" . printlist() : $ast;
}
sub expr
{
my $ast =
/$h Integer \s+ (\d+) \n/gcx ? "Integer\t\t$1\n" :
/$h Identifier \s+ (\w+) \n/gcx ? "Identifier\t$1\n" :
/$h LeftParen \n/gcx ? want expr(0), 'RightParen' :
/$h Op_(negate|subtract) \n/gcx ? "Negate\n" . expr(8) . ";\n" :
/$h Op_not \n/gcx ? "Not\n" . expr(8) . ";\n" :
/$h Op_add \n/gcx ? expr(8) :
error "A PRIMARY";
$ast =
$_[0] <= 7 && /$h Op_multiply \n/gcx ? "Multiply\n$ast" . expr(8) :
$_[0] <= 7 && /$h Op_divide \n/gcx ? "Divide\n$ast" . expr(8) :
$_[0] <= 7 && /$h Op_mod \n/gcx ? "Mod\n$ast" . expr(8) :
$_[0] <= 6 && /$h Op_add \n/gcx ? "Add\n$ast" . expr(7) :
$_[0] <= 6 && /$h Op_subtract \n/gcx ? "Subtract\n$ast" . expr(7) :
$_[0] == 5 && /(?=$h Op_(less|greater)(equal)? \n)/gcx ? error 'NO ASSOC' :
$_[0] <= 5 && /$h Op_lessequal \n/gcx ? "LessEqual\n$ast" . expr(5) :
$_[0] <= 5 && /$h Op_less \n/gcx ? "Less\n$ast" . expr(5) :
$_[0] <= 5 && /$h Op_greater \n/gcx ? "Greater\n$ast" . expr(5) :
$_[0] <= 5 && /$h Op_greaterequal \n/gcx ? "GreaterEqual\n$ast" . expr(5) :
$_[0] == 3 && /(?=$h Op_(not)?equal \n)/gcx ? error 'NO ASSOC' :
$_[0] <= 3 && /$h Op_equal \n/gcx ? "Equal\n$ast" . expr(3) :
$_[0] <= 3 && /$h Op_notequal \n/gcx ? "NotEqual\n$ast" . expr(3) :
$_[0] <= 1 && /$h Op_and \n/gcx ? "And\n$ast" . expr(2) :
$_[0] <= 0 && /$h Op_or \n/gcx ? "Or\n$ast" . expr(1) :
return $ast while 1;
} | 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_Putc, tk_Lparen, tk_Rparen, tk_Lbrace, tk_Rbrace, tk_Semi, tk_Comma,
tk_Ident, tk_Integer, tk_String
} TokenType;
typedef struct {
TokenType tok;
int err_ln, err_col;
union {
int n;
char *text;
};
} tok_s;
static FILE *source_fp, *dest_fp;
static int line = 1, col = 0, the_ch = ' ';
da_dim(text, char);
tok_s gettok(void);
static void error(int err_line, int err_col, const char *fmt, ... ) {
char buf[1000];
va_list ap;
va_start(ap, fmt);
vsprintf(buf, fmt, ap);
va_end(ap);
printf(, err_line, err_col, buf);
exit(1);
}
static int next_ch(void) {
the_ch = getc(source_fp);
++col;
if (the_ch == '\n') {
++line;
col = 0;
}
return the_ch;
}
static tok_s char_lit(int n, int err_line, int err_col) {
if (the_ch == '\'')
error(err_line, err_col, );
if (the_ch == '\\') {
next_ch();
if (the_ch == 'n')
n = 10;
else if (the_ch == '\\')
n = '\\';
else error(err_line, err_col, , the_ch);
}
if (next_ch() != '\'')
error(err_line, err_col, );
next_ch();
return (tok_s){tk_Integer, err_line, err_col, {n}};
}
static tok_s div_or_cmt(int err_line, int err_col) {
if (the_ch != '*')
return (tok_s){tk_Div, err_line, err_col, {0}};
next_ch();
for (;;) {
if (the_ch == '*') {
if (next_ch() == '/') {
next_ch();
return gettok();
}
} else if (the_ch == EOF)
error(err_line, err_col, );
else
next_ch();
}
}
static tok_s string_lit(int start, int err_line, int err_col) {
da_rewind(text);
while (next_ch() != start) {
if (the_ch == '\n') error(err_line, err_col, );
if (the_ch == EOF) error(err_line, err_col, );
da_append(text, (char)the_ch);
}
da_append(text, '\0');
next_ch();
return (tok_s){tk_String, err_line, err_col, {.text=text}};
}
static int kwd_cmp(const void *p1, const void *p2) {
return strcmp(*(char **)p1, *(char **)p2);
}
static TokenType get_ident_type(const char *ident) {
static struct {
const char *s;
TokenType sym;
} kwds[] = {
{, tk_Else},
{, tk_If},
{, tk_Print},
{, tk_Putc},
{, tk_While},
}, *kwp;
return (kwp = bsearch(&ident, kwds, NELEMS(kwds), sizeof(kwds[0]), kwd_cmp)) == NULL ? tk_Ident : kwp->sym;
}
static tok_s ident_or_int(int err_line, int err_col) {
int n, is_number = true;
da_rewind(text);
while (isalnum(the_ch) || the_ch == '_') {
da_append(text, (char)the_ch);
if (!isdigit(the_ch))
is_number = false;
next_ch();
}
if (da_len(text) == 0)
error(err_line, err_col, , the_ch, the_ch);
da_append(text, '\0');
if (isdigit(text[0])) {
if (!is_number)
error(err_line, err_col, , text);
n = strtol(text, NULL, 0);
if (n == LONG_MAX && errno == ERANGE)
error(err_line, err_col, );
return (tok_s){tk_Integer, err_line, err_col, {n}};
}
return (tok_s){get_ident_type(text), err_line, err_col, {.text=text}};
}
static tok_s follow(int expect, TokenType ifyes, TokenType ifno, int err_line, int err_col) {
if (the_ch == expect) {
next_ch();
return (tok_s){ifyes, err_line, err_col, {0}};
}
if (ifno == tk_EOI)
error(err_line, err_col, , the_ch, the_ch);
return (tok_s){ifno, err_line, err_col, {0}};
}
tok_s gettok(void) {
while (isspace(the_ch))
next_ch();
int err_line = line;
int err_col = col;
switch (the_ch) {
case '{': next_ch(); return (tok_s){tk_Lbrace, err_line, err_col, {0}};
case '}': next_ch(); return (tok_s){tk_Rbrace, err_line, err_col, {0}};
case '(': next_ch(); return (tok_s){tk_Lparen, err_line, err_col, {0}};
case ')': next_ch(); return (tok_s){tk_Rparen, err_line, err_col, {0}};
case '+': next_ch(); return (tok_s){tk_Add, err_line, err_col, {0}};
case '-': next_ch(); return (tok_s){tk_Sub, err_line, err_col, {0}};
case '*': next_ch(); return (tok_s){tk_Mul, err_line, err_col, {0}};
case '%': next_ch(); return (tok_s){tk_Mod, err_line, err_col, {0}};
case ';': next_ch(); return (tok_s){tk_Semi, err_line, err_col, {0}};
case ',': next_ch(); return (tok_s){tk_Comma,err_line, err_col, {0}};
case '/': next_ch(); return div_or_cmt(err_line, err_col);
case '\'': next_ch(); return char_lit(the_ch, err_line, err_col);
case '<': next_ch(); return follow('=', tk_Leq, tk_Lss, err_line, err_col);
case '>': next_ch(); return follow('=', tk_Geq, tk_Gtr, err_line, err_col);
case '=': next_ch(); return follow('=', tk_Eq, tk_Assign, err_line, err_col);
case '!': next_ch(); return follow('=', tk_Neq, tk_Not, err_line, err_col);
case '&': next_ch(); return follow('&', tk_And, tk_EOI, err_line, err_col);
case '|': next_ch(); return follow('|', tk_Or, tk_EOI, err_line, err_col);
case '%5d %5d%.15sEnd_of_input Op_multiply Op_divide Op_mod Op_add Op_subtract Op_negate Op_not Op_less Op_lessequal Op_greater Op_greaterequal Op_equal Op_notequal Op_assign Op_and Op_or Keyword_if Keyword_else Keyword_while Keyword_print Keyword_putc LeftParen RightParen LeftBrace RightBrace Semicolon Comma Identifier Integer String %4d%s \\nCan't open%s\nrwb");
run();
return 0;
} | 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) {
cellState = State.DEAD;
}
}
var cellState;
}
class Point {
const Point(this.x, this.y);
operator +(other) => new Point(x + other.x, y + other.y);
final int x;
final int y;
}
class Neighbourhood {
List<Point> points() {
return [
new Point(LEFT, UP), new Point(MIDDLE, UP), new Point(RIGHT, UP),
new Point(LEFT, SAME), new Point(RIGHT, SAME),
new Point(LEFT, DOWN), new Point(MIDDLE, DOWN), new Point(RIGHT, DOWN)
];
}
static final LEFT = -1;
static final MIDDLE = 0;
static final RIGHT = 1;
static final UP = -1;
static final SAME = 0;
static final DOWN = 1;
}
class Grid {
Grid(this.xCount, this.yCount) {
_field = new Map();
_neighbours = new Neighbourhood().points();
}
set(point, state) {
_field[_pos(point)] = state;
}
State get(point) {
var state = _field[_pos(point)];
return state!= null? state: State.DEAD;
}
int countLiveNeighbours(point) =>
_neighbours.filter((offset) => get(point + offset) == State.ALIVE).length;
_pos(point) => '${(point.x + xCount)% xCount}:${(point.y + yCount)% yCount}';
print() {
var sb = new StringBuffer();
iterate((point) { sb.add(get(point).symbol); }, (x) { sb.add("\n"); });
return sb.toString();
}
iterate(eachCell, [finishedRow]) {
for (var x = 0; x < xCount; x++) {
for (var y = 0; y < yCount; y++) {
eachCell(new Point(x, y));
}
if(finishedRow!= null) {
finishedRow(x);
}
}
}
final xCount, yCount;
List<Point> _neighbours;
Map<String, State> _field;
}
class Game {
Game(this.grid);
tick() {
var newGrid = createNewGrid();
grid.iterate((point) {
var rule = new Rule(grid.get(point));
rule.reactToNeighbours(grid.countLiveNeighbours(point));
newGrid.set(point, rule.cellState);
});
grid = newGrid;
}
createNewGrid() => new Grid(grid.xCount, grid.yCount);
printGrid() => print(grid.print());
Grid grid;
}
main() { | 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 of the earth is 57268900(29% of the surface) square miles.'],
['Ain\'t no numbers in this here words, nohow, no way, Jose.'],
['James was never known as 0000000007'],
['Arthur Eddington wrote: I believe there are 15747724136275002577605653961181555468044717914527116709366231425076185631031296 protons in the universe.'],
[' $-140000100 millions.'],
['5/9/1946 was a good year for some.']
);
for $i (@input) {
$old = @$i[0];
$new = commatize(@$i);
printf("%s\n%s\n\n", $old, $new) if $old ne $new;
}
sub commatize {
my($str,$sep,$by) = @_;
$sep = ',' unless $sep;
$by = 3 unless $by;
$str =~ s/
(?<![eE\/])
([1-9]\d{$by,})
/c_ins($1,$by,$sep)/ex;
return $str;
}
sub c_ins {
my($s,$by,$sep) = @_;
($c = reverse $s) =~ s/(.{$by})/$1$sep/g;
$c =~ s/$sep$//;
return reverse $c;
} | 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 = len(seq)
if size < 2: return seq
low, middle, up = partition(seq, random.choice(seq))
return qsortranpart(low) + middle + qsortranpart(up) | 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_Comma, tk_Ident, \
tk_Integer, tk_String = range(31)
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)
Tokens = [
[ , False, False, False, -1, -1 ],
[ , False, True, False, 13, nd_Mul ],
[ , False, True, False, 13, nd_Div ],
[ , False, True, False, 13, nd_Mod ],
[ , False, True, False, 12, nd_Add ],
[ , False, True, False, 12, nd_Sub ],
[ , False, False, True, 14, nd_Negate ],
[ , False, False, True, 14, nd_Not ],
[ , False, True, False, 10, nd_Lss ],
[ , False, True, False, 10, nd_Leq ],
[ , False, True, False, 10, nd_Gtr ],
[ , False, True, False, 10, nd_Geq ],
[ , False, True, False, 9, nd_Eql ],
[ , False, True, False, 9, nd_Neq ],
[ , False, False, False, -1, nd_Assign ],
[ , False, True, False, 5, nd_And ],
[ , False, True, False, 4, nd_Or ],
[ , False, False, False, -1, nd_If ],
[ , False, False, False, -1, -1 ],
[ , False, False, False, -1, nd_While ],
[ , False, False, False, -1, -1 ],
[ , False, False, False, -1, -1 ],
[ , False, False, False, -1, -1 ],
[ , False, False, False, -1, -1 ],
[ , False, False, False, -1, -1 ],
[ , False, False, False, -1, -1 ],
[ , False, False, False, -1, -1 ],
[ , False, False, False, -1, -1 ],
[ , False, False, False, -1, nd_Ident ],
[ , False, False, False, -1, nd_Integer],
[ , False, False, False, -1, nd_String ]
]
all_syms = { : 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}
Display_nodes = [, , , , , , ,
, , , , , , , , ,
, , , , , , ,
, ]
TK_NAME = 0
TK_RIGHT_ASSOC = 1
TK_IS_BINARY = 2
TK_IS_UNARY = 3
TK_PRECEDENCE = 4
TK_NODE = 5
input_file = None
err_line = None
err_col = None
tok = None
tok_text = None
def error(msg):
print(% (int(err_line), int(err_col), msg))
exit(1)
def gettok():
global err_line, err_col, tok, tok_text, tok_other
line = input_file.readline()
if len(line) == 0:
error()
line_list = shlex.split(line, False, False)
err_line = line_list[0]
err_col = line_list[1]
tok_text = line_list[2]
tok = all_syms.get(tok_text)
if tok == None:
error(% (tok_text))
tok_other = None
if tok in [tk_Integer, tk_Ident, tk_String]:
tok_other = line_list[3]
class Node:
def __init__(self, node_type, left = None, right = None, value = None):
self.node_type = node_type
self.left = left
self.right = right
self.value = value
def make_node(oper, left, right = None):
return Node(oper, left, right)
def make_leaf(oper, n):
return Node(oper, value = n)
def expect(msg, s):
if tok == s:
gettok()
return
error(% (msg, Tokens[s][TK_NAME], Tokens[tok][TK_NAME]))
def expr(p):
x = None
if tok == tk_Lparen:
x = paren_expr()
elif tok in [tk_Sub, tk_Add]:
op = (tk_Negate if tok == tk_Sub else tk_Add)
gettok()
node = expr(Tokens[tk_Negate][TK_PRECEDENCE])
x = (make_node(nd_Negate, node) if op == tk_Negate else node)
elif tok == tk_Not:
gettok()
x = make_node(nd_Not, expr(Tokens[tk_Not][TK_PRECEDENCE]))
elif tok == tk_Ident:
x = make_leaf(nd_Ident, tok_other)
gettok()
elif tok == tk_Integer:
x = make_leaf(nd_Integer, tok_other)
gettok()
else:
error(% (Tokens[tok][TK_NAME]))
while Tokens[tok][TK_IS_BINARY] and Tokens[tok][TK_PRECEDENCE] >= p:
op = tok
gettok()
q = Tokens[op][TK_PRECEDENCE]
if not Tokens[op][TK_RIGHT_ASSOC]:
q += 1
node = expr(q)
x = make_node(Tokens[op][TK_NODE], x, node)
return x
def paren_expr():
expect(, tk_Lparen)
node = expr(0)
expect(, tk_Rparen)
return node
def stmt():
t = None
if tok == tk_If:
gettok()
e = paren_expr()
s = stmt()
s2 = None
if tok == tk_Else:
gettok()
s2 = stmt()
t = make_node(nd_If, e, make_node(nd_If, s, s2))
elif tok == tk_Putc:
gettok()
e = paren_expr()
t = make_node(nd_Prtc, e)
expect(, tk_Semi)
elif tok == tk_Print:
gettok()
expect(, tk_Lparen)
while True:
if tok == tk_String:
e = make_node(nd_Prts, make_leaf(nd_String, tok_other))
gettok()
else:
e = make_node(nd_Prti, expr(0))
t = make_node(nd_Sequence, t, e)
if tok != tk_Comma:
break
gettok()
expect(, tk_Rparen)
expect(, tk_Semi)
elif tok == tk_Semi:
gettok()
elif tok == tk_Ident:
v = make_leaf(nd_Ident, tok_other)
gettok()
expect(, tk_Assign)
e = expr(0)
t = make_node(nd_Assign, v, e)
expect(, tk_Semi)
elif tok == tk_While:
gettok()
e = paren_expr()
s = stmt()
t = make_node(nd_While, e, s)
elif tok == tk_Lbrace:
gettok()
while tok != tk_Rbrace and tok != tk_EOI:
t = make_node(nd_Sequence, t, stmt())
expect(, tk_Rbrace)
elif tok == tk_EOI:
pass
else:
error(% (Tokens[tok][TK_NAME]))
return t
def parse():
t = None
gettok()
while True:
t = make_node(nd_Sequence, t, stmt())
if tok == tk_EOI or t == None:
break
return t
def prt_ast(t):
if t == None:
print()
else:
print(% (Display_nodes[t.node_type]), end='')
if t.node_type in [nd_Ident, nd_Integer]:
print(% (t.value))
elif t.node_type == nd_String:
print(%(t.value))
else:
print()
prt_ast(t.left)
prt_ast(t.right)
input_file = sys.stdin
if len(sys.argv) > 1:
try:
input_file = open(sys.argv[1], , 4096)
except IOError as e:
error(0, 0, % sys.argv[1])
t = parse()
prt_ast(t) | 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]
periods = [ match [ i:i + _periodLen ] for i in range ( _startPos, len ( match ), _periodLen ) ]
outString += leadIn + _separator.join( periods )
else:
outString += match
strPos += len( match )
return outString
print ( Commatize( , 0, 5, ) )
print ( Commatize( , 0, 3, ))
print ( Commatize( -in Aus$+1411.8millions\ ))
print ( Commatize( ))
print ( Commatize( ))
print ( Commatize( ))
print ( Commatize( ))
print ( Commatize( ))
print ( Commatize( ))
print ( Commatize( ))
print ( Commatize( )) | 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
end
ary
end
def quick_sort
return self if size <= 1
pivot = sample
g = group_by{|x| x<=>pivot}
g.default = []
g[-1].quick_sort + g[0] + g[1].quick_sort
end
def shell_sort
inc = size / 2
while inc > 0
(inc...size).each do |i|
value = self[i]
while i >= inc and self[i - inc] > value
self[i] = self[i - inc]
i -= inc
end
self[i] = value
end
inc = (inc == 2? 1: (inc * 5.0 / 11).to_i)
end
self
end
def insertion_sort
(1...size).each do |i|
value = self[i]
j = i - 1
while j >= 0 and self[j] > value
self[j+1] = self[j]
j -= 1
end
self[j+1] = value
end
self
end
def bubble_sort
(1...size).each do |i|
(0...size-i).each do |j|
self[j], self[j+1] = self[j+1], self[j] if self[j] > self[j+1]
end
end
self
end
end
data_size = [1000, 10000, 100000, 1000000]
data = []
data_size.each do |size|
ary = *1..size
data << [ [1]*size, ary, ary.shuffle, ary.reverse ]
end
data = data.transpose
data_type = [, , , ]
print
puts data_size.map{|size| % size}.join
data.each_with_index do |arys,i|
puts
[:sort, :radix_sort, :quick_sort, :shell_sort, :insertion_sort, :bubble_sort].each do |m|
printf , m
flag = true
arys.each do |ary|
if flag
t0 = Time.now
ary.dup.send(m)
printf , (t1 = Time.now - t0)
flag = false if t1 > 2
else
print
end
end
puts
end
end | 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 } ],
[ add => sub { $stack[-2] += pop @stack } ],
[ sub => sub { $stack[-2] -= pop @stack } ],
[ mul => sub { $stack[-2] *= pop @stack } ],
[ div => sub { $stack[-2] /= pop @stack } ],
[ mod => sub { $stack[-2] %= pop @stack } ],
[ not => sub { $stack[-1] = $stack[-1] ? 0 : 1 } ],
[ neg => sub { $stack[-1] = - $stack[-1] } ],
[ and => sub { $stack[-2] &&= $stack[-1]; pop @stack } ],
[ or => sub { $stack[-2] ||= $stack[-1]; pop @stack } ],
[ lt => sub { $stack[-1] = $stack[-2] < pop @stack ? 1 : 0 } ],
[ gt => sub { $stack[-1] = $stack[-2] > pop @stack ? 1 : 0 } ],
[ le => sub { $stack[-1] = $stack[-2] <= pop @stack ? 1 : 0 } ],
[ ge => sub { $stack[-1] = $stack[-2] >= pop @stack ? 1 : 0 } ],
[ ne => sub { $stack[-1] = $stack[-2] != pop @stack ? 1 : 0 } ],
[ eq => sub { $stack[-1] = $stack[-2] == pop @stack ? 1 : 0 } ],
[ prts => sub { print $strings[pop @stack] } ],
[ prti => sub { print pop @stack } ],
[ prtc => sub { print chr pop @stack } ],
[ store => sub { $data[value()] = pop @stack } ],
[ fetch => sub { push @stack, $data[value()] // 0 } ],
[ push => sub { push @stack, value() } ],
[ jmp => sub { $pc += value() - 4 } ],
[ jz => sub { $pc += pop @stack ? 4 : value() - 4 } ],
);
my %op2n = map { $ops[$_][0], $_ } 0..$
while(<>)
{
/^ *\d+ +(\w+)/ or die "bad line $_";
$binary .= chr( $op2n{$1} // die "$1 not defined" ) .
(/\((-?\d+)\)|(\d+)]?$/ and pack 'l', $+);
}
$ops[vec($binary, $pc++, 8)][1]->() while 1; | 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 );
my $line = <> // return '';
(local $_, my $arg) = $line =~ /^(\w+|;)\s+(.*)/ or die "bad input $line";
/Identifier/ ? "fetch [@{[ $names{$arg} //= $namecount++ ]}]\n" :
/Sequence/ ? tree() . tree() :
/Integer/ ? "push $arg\n" :
/String/ ? "push @{[ $strings{$arg} //= $stringcount++ ]}\n" :
/Assign/ ? join '', reverse tree() =~ s/fetch/store/r, tree() :
/While/ ? "$A:\n@{[ tree() ]}jz $B\n@{[ tree() ]}jmp $A\n$B:\n" :
/If/ ? tree() . "jz $A\n@{[!<> .
tree() ]}jmp $B\n$A:\n@{[ tree() ]}$B:\n" :
/;/ ? '' :
tree() . tree() . ($opnames{$_} // lc) . "\n";
}
$_ = tree() . "halt\n";
s/^jmp\s+(\S+)\n(_\d+:\n)\1:\n/$2/gm;
s/^(?=[a-z]\w*(.*))/
(sprintf("%4d ", $pc), $pc += $1 ? 5 : 1)[0] /gem;
my %labels = /^(_\d+):(?=(?:\n_\d+:)*\n *(\d+) )/gm;
s/^ *(\d+) j(?:z|mp) *\K(_\d+)$/ (@{[
$labels{$2} - $1 - 1]}) $labels{$2}/gm;
s/^_\d+.*\n//gm;
print "Datasize: $namecount Strings: $stringcount\n";
print "$_\n" for sort { $strings{$a} <=> $strings{$b} } keys %strings;
print; | 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("And", _, _))),
"Op_equal" -> (null, InfixOperator(30, LeftAssoc, BranchNode("Equal", _, _))),
"Op_notequal" -> (null, InfixOperator(30, LeftAssoc, BranchNode("NotEqual", _, _))),
"Op_less" -> (null, InfixOperator(40, LeftAssoc, BranchNode("Less", _, _))),
"Op_lessequal" -> (null, InfixOperator(40, LeftAssoc, BranchNode("LessEqual", _, _))),
"Op_greater" -> (null, InfixOperator(40, LeftAssoc, BranchNode("Greater", _, _))),
"Op_greaterequal" -> (null, InfixOperator(40, LeftAssoc, BranchNode("GreaterEqual", _, _))),
"Op_add" -> (PrefixOperator(30, identity), InfixOperator(50, LeftAssoc, BranchNode("Add", _, _))),
"Op_minus" -> (PrefixOperator(70, BranchNode("Negate", _, TerminalNode)), InfixOperator(
50,
LeftAssoc,
BranchNode("Subtract", _, _))),
"Op_multiply" -> (null, InfixOperator(60, LeftAssoc, BranchNode("Multiply", _, _))),
"Op_divide" -> (null, InfixOperator(60, LeftAssoc, BranchNode("Divide", _, _))),
"Op_mod" -> (null, InfixOperator(60, RightAssoc, BranchNode("Mod", _, _))),
"Op_not" -> (PrefixOperator(70, BranchNode("Not", _)), null),
"LeftParen" -> null,
"RightParen" -> null
)
def apply = new SyntaxAnalyzer(symbols)
abstract class Node
case class LeafNode(name: String, value: String) extends Node
case class BranchNode(name: String, left: Node, right: Node = TerminalNode) extends Node
case object TerminalNode extends Node
abstract class Assoc
case object LeftAssoc extends Assoc
case object RightAssoc extends Assoc
abstract class Operator
case class InfixOperator(prec: Int, assoc: Assoc, compute: (Node, Node) => Node) extends Operator
case class PrefixOperator(prec: Int, compute: Node => Node) extends Operator
}
class SyntaxAnalyzer(symbols: Map[String, (SyntaxAnalyzer.PrefixOperator, SyntaxAnalyzer.InfixOperator)]) {
import SyntaxAnalyzer.{BranchNode, InfixOperator, LeafNode, LeftAssoc, Node, PrefixOperator, TerminalNode}
def fromStdin = fromSource(Source.stdin)
def fromString(src: String) = fromSource(Source.fromString(src))
def fromSource(s: Source) = {
val tokens = ((s.getLines map (_.trim.split(" +", 4)) map {
case Array(line, col, name) =>
symbols get name match {
case None | Some(null) => SimpleToken(line.toInt, col.toInt, name)
case Some(operators) => OperatorToken(line.toInt, col.toInt, name, operators)
}
case Array(line, col, name, value) => ValueToken(line.toInt, col.toInt, name, value)
}) toStream)
flatten(parse(tokens))
}
def flatten(n: Node): Unit =
n match {
case TerminalNode => println(";")
case LeafNode(name, value) => println(s"$name $value")
case BranchNode(name, left, right) =>
println(name)
flatten(left)
flatten(right)
}
def parse(toks: Stream[Token]) = {
var cur = toks
def next = cur = cur.tail
def token = cur.head
def consume = {
val res = token
next
res
}
def accept(name: String) =
if (token.name == name) {
next
true
} else
false
def expect(name: String, error: String = null) =
if (token.name != name)
sys.error(if (error eq null) s"expected $name, found ${token.name}" else s"$error: $token")
else
next
def expression(minPrec: Int): Node = {
def infixOperator = token.asInstanceOf[OperatorToken].operators._2
def isInfix = token.isInstanceOf[OperatorToken] && infixOperator != null
var result =
consume match {
case SimpleToken(_, _, "LeftParen") =>
val result = expression(0)
expect("RightParen", "expected closing parenthesis")
result
case ValueToken(_, _, name, value) => LeafNode(name, value)
case OperatorToken(_, _, _, (prefix, _)) if prefix ne null => prefix.compute(expression(prefix.prec))
case OperatorToken(_, _, _, (_, infix)) if infix ne null =>
sys.error(s"expected a primitive expression, not an infix operator: $token")
}
while (isInfix && infixOperator.prec >= minPrec) {
val InfixOperator(prec, assoc, compute) = infixOperator
val nextMinPrec = if (assoc == LeftAssoc) prec + 1 else prec
next
result = compute(result, expression(nextMinPrec))
}
result
}
def parenExpression = {
expect("LeftParen")
val e = expression(0)
expect("RightParen")
e
}
def statement: Node = {
var stmt: Node = TerminalNode
if (accept("Keyword_if"))
stmt = BranchNode("If",
parenExpression,
BranchNode("If", statement, if (accept("Keyword_else")) statement else TerminalNode))
else if (accept("Keyword_putc")) {
stmt = BranchNode("Prtc", parenExpression)
expect("Semicolon")
} else if (accept("Keyword_print")) {
expect("LeftParen")
do {
val e =
if (token.name == "String")
BranchNode("Prts", LeafNode("String", consume.asInstanceOf[ValueToken].value))
else
BranchNode("Prti", expression(0))
stmt = BranchNode("Sequence", stmt, e)
} while (accept("Comma"))
expect("RightParen")
expect("Semicolon")
} else if (token.name == "Semicolon")
next
else if (token.name == "Identifier") {
val ident = LeafNode("Identifier", consume.asInstanceOf[ValueToken].value)
expect("Op_assign")
stmt = BranchNode("Assign", ident, expression(0))
expect("Semicolon")
} else if (accept("Keyword_while"))
stmt = BranchNode("While", parenExpression, statement)
else if (accept("LeftBrace")) {
while (token.name != "RightBrace" && token.name != "End_of_input") {
stmt = BranchNode("Sequence", stmt, statement)
}
expect("RightBrace")
} else
sys.error(s"syntax error: $token")
stmt
}
var tree: Node = TerminalNode
do {
tree = BranchNode("Sequence", tree, statement)
} while (token.name != "End_of_input")
expect("End_of_input")
tree
}
abstract class Token {
val line: Int;
val col: Int;
val name: String
}
case class SimpleToken(line: Int, col: Int, name: String) extends Token
case class ValueToken(line: Int, col: Int, name: String, value: String) extends Token
case class OperatorToken(line: Int, col: Int, name: String, operators: (PrefixOperator, InfixOperator)) extends Token
} | 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] > n - 1)
{
pos[i - 1] += 1;
for (int j = i; j <= k; j += 1)
pos[j] = pos[j - 1];
}
}
if (pos[0] > 0)
break;
printDonuts(k);
pos[k] += 1;
}
}
int main() {
combination_with_repetiton(3, 2);
return 0;
} | 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.length) {
val m = Pattern.compile("([1-9][0-9]*)").matcher(s.substring(start))
val result = new StringBuffer(s.substring(0, start))
if (m.find) {
val sb = new StringBuilder(m.group(1)).reverse
for (i <- step until sb.length by step) sb.insert(i, ins)
m.appendReplacement(result, sb.reverse.toString)
}
println(m.appendTail(result))
}
}
commatize("pi=3.14159265358979323846264338327950288419716939937510582" + "097494459231", 6, 5, " ")
commatize("The author has two Z$100000000000000 Zimbabwe notes (100 " + "trillion).", 0, 3, ".")
val sc = new Scanner(new File("input.txt"))
while (sc.hasNext) commatize(sc.nextLine)
} | 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(separator)
let startIdx = index(startIndex, offsetBy: start)
let matches = String.commaReg.matches(in: self, range: NSRange(startIdx..., in: self))
guard!matches.isEmpty else {
return self
}
let fullMatch = String(self[Range(matches.first!.range(at: 0), in: self)!])
let splits = fullMatch.components(separatedBy: ".")
var ip = splits[0]
if ip.count > period {
var builder = Array(ip.reversed())
for i in stride(from: (ip.count - 1) / period * period, through: period, by: -period) {
builder.insert(contentsOf: sep, at: i)
}
ip = String(builder.reversed())
}
if fullMatch.contains(".") {
var dp = splits[1]
if dp.count > period {
var builder = Array(dp)
for i in stride(from: (dp.count - 1) / period * period, through: period, by: -period) {
builder.insert(contentsOf: sep, at: i)
}
dp = String(builder)
}
ip += "." + dp
}
return String(prefix(start)) + String(dropFirst(start)).replacingOccurrences(of: fullMatch, with: ip)
}
}
let tests = [
"123456789.123456789",
".123456789",
"57256.1D-4",
"pi=3.14159265358979323846264338327950288419716939937510582097494459231",
"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 of the earth is 57268900(29% of the surface) square miles.",
"Ain't no numbers in this here words, nohow, no way, Jose.",
"James was never known as 0000000007",
"Arthur Eddington wrote: I believe there are " +
"15747724136275002577605653961181555468044717914527116709366231425076185631031296" +
" protons in the universe.",
" $-140000100 millions.",
"6/9/1946 was a good year for some."
]
print(tests[0].commatize(period: 2, separator: "*"))
print(tests[1].commatize(period: 3, separator: "-"))
print(tests[2].commatize(period: 4, separator: "__"))
print(tests[3].commatize(period: 5, separator: " "))
print(tests[4].commatize(separator: "."))
for testCase in tests.dropFirst(5) {
print(testCase.commatize())
} | 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)
all_syms = {
: 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}
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)
operators = {nd_Lss: LT, nd_Gtr: GT, nd_Leq: LE, nd_Geq: GE, nd_Eql: EQ, nd_Neq: NE,
nd_And: AND, nd_Or: OR, nd_Sub: SUB, nd_Add: ADD, nd_Div: DIV, nd_Mul: MUL, nd_Mod: MOD}
unary_operators = {nd_Negate: NEG, nd_Not: NOT}
input_file = None
code = bytearray()
string_pool = {}
globals = {}
string_n = 0
globals_n = 0
word_size = 4
def error(msg):
print(% (msg))
exit(1)
def int_to_bytes(val):
return struct.pack(, val)
def bytes_to_int(bstr):
return struct.unpack(, bstr)
class Node:
def __init__(self, node_type, left = None, right = None, value = None):
self.node_type = node_type
self.left = left
self.right = right
self.value = value
def make_node(oper, left, right = None):
return Node(oper, left, right)
def make_leaf(oper, n):
return Node(oper, value = n)
def emit_byte(x):
code.append(x)
def emit_word(x):
s = int_to_bytes(x)
for x in s:
code.append(x)
def emit_word_at(at, n):
code[at:at+word_size] = int_to_bytes(n)
def hole():
t = len(code)
emit_word(0)
return t
def fetch_var_offset(name):
global globals_n
n = globals.get(name, None)
if n == None:
globals[name] = globals_n
n = globals_n
globals_n += 1
return n
def fetch_string_offset(the_string):
global string_n
n = string_pool.get(the_string, None)
if n == None:
string_pool[the_string] = string_n
n = string_n
string_n += 1
return n
def code_gen(x):
if x == None: return
elif x.node_type == nd_Ident:
emit_byte(FETCH)
n = fetch_var_offset(x.value)
emit_word(n)
elif x.node_type == nd_Integer:
emit_byte(PUSH)
emit_word(x.value)
elif x.node_type == nd_String:
emit_byte(PUSH)
n = fetch_string_offset(x.value)
emit_word(n)
elif x.node_type == nd_Assign:
n = fetch_var_offset(x.left.value)
code_gen(x.right)
emit_byte(STORE)
emit_word(n)
elif x.node_type == nd_If:
code_gen(x.left)
emit_byte(JZ)
p1 = hole()
code_gen(x.right.left)
if (x.right.right != None):
emit_byte(JMP)
p2 = hole()
emit_word_at(p1, len(code) - p1)
if (x.right.right != None):
code_gen(x.right.right)
emit_word_at(p2, len(code) - p2)
elif x.node_type == nd_While:
p1 = len(code)
code_gen(x.left)
emit_byte(JZ)
p2 = hole()
code_gen(x.right)
emit_byte(JMP)
emit_word(p1 - len(code))
emit_word_at(p2, len(code) - p2)
elif x.node_type == nd_Sequence:
code_gen(x.left)
code_gen(x.right)
elif x.node_type == nd_Prtc:
code_gen(x.left)
emit_byte(PRTC)
elif x.node_type == nd_Prti:
code_gen(x.left)
emit_byte(PRTI)
elif x.node_type == nd_Prts:
code_gen(x.left)
emit_byte(PRTS)
elif x.node_type in operators:
code_gen(x.left)
code_gen(x.right)
emit_byte(operators[x.node_type])
elif x.node_type in unary_operators:
code_gen(x.left)
emit_byte(unary_operators[x.node_type])
else:
error(% (x.node_type))
def code_finish():
emit_byte(HALT)
def list_code():
print(% (len(globals), len(string_pool)))
for k in sorted(string_pool, key=string_pool.get):
print(k)
pc = 0
while pc < len(code):
print(% (pc), end='')
op = code[pc]
pc += 1
if op == FETCH:
x = bytes_to_int(code[pc:pc+word_size])[0]
print(% (x));
pc += word_size
elif op == STORE:
x = bytes_to_int(code[pc:pc+word_size])[0]
print(% (x));
pc += word_size
elif op == PUSH:
x = bytes_to_int(code[pc:pc+word_size])[0]
print(% (x));
pc += word_size
elif op == ADD: print()
elif op == SUB: print()
elif op == MUL: print()
elif op == DIV: print()
elif op == MOD: print()
elif op == LT: print()
elif op == GT: print()
elif op == LE: print()
elif op == GE: print()
elif op == EQ: print()
elif op == NE: print()
elif op == AND: print()
elif op == OR: print()
elif op == NEG: print()
elif op == NOT: print()
elif op == JMP:
x = bytes_to_int(code[pc:pc+word_size])[0]
print(% (x, pc + x));
pc += word_size
elif op == JZ:
x = bytes_to_int(code[pc:pc+word_size])[0]
print(% (x, pc + x));
pc += word_size
elif op == PRTC: print()
elif op == PRTI: print()
elif op == PRTS: print()
elif op == HALT: print()
else: error(, (op));
def load_ast():
line = input_file.readline()
line_list = shlex.split(line, False, False)
text = line_list[0]
if text == :
return None
node_type = all_syms[text]
if len(line_list) > 1:
value = line_list[1]
if value.isdigit():
value = int(value)
return make_leaf(node_type, value)
left = load_ast()
right = load_ast()
return make_node(node_type, left, right)
input_file = sys.stdin
if len(sys.argv) > 1:
try:
input_file = open(sys.argv[1], , 4096)
except IOError as e:
error(% sys.argv[1])
n = load_ast()
code_gen(n)
code_finish()
list_code() | 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()
{
$strings = retrieveStrings();
$strings = array_map('trim', $strings);
$strings = array_filter($strings);
if (!empty($strings)) {
usort($strings, function ($a, $b) {
return strlen($b) - strlen($a);
});
$max_len = strlen($strings[0]);
$min_len = strlen($strings[count($strings) - 1]);
foreach ($strings as $s) {
$length = strlen($s);
if ($length == $max_len) {
$predicate = ;
} elseif ($length == $min_len) {
$predicate = ;
} else {
$predicate = ;
}
echo ;
}
}
}
?>
<!DOCTYPE html>
<html lang=>
<head>
<style>
div {
margin-top: 4ch;
margin-bottom: 4ch;
}
label {
display: block;
margin-bottom: 1ch;
}
textarea {
display: block;
}
input {
display: block;
margin-top: 4ch;
margin-bottom: 4ch;
}
</style>
</head>
<body>
<main>
<form action=<?php echo $_SERVER['SCRIPT_NAME'] ?> method= accept-charset=>
<div>
<label for=>Input:
</label>
<textarea rows='20' cols='80' name='input'><?php setInput(); ?></textarea>
</label>
</div>
<input type= value=>
</input>
<div>
<label for=>Output:
</label>
<textarea rows='20' cols='80' name='output'><?php setOutput(); ?></textarea>
</div>
</form>
</main>
</body>
</html> | 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 < 61; n += 10 {
p = n / 3
fmt.Printf("C(%d,%d) =%d\n", n, p, comb(big.NewInt(n), big.NewInt(p)))
}
fmt.Printf("\nA sample of permutations from 5 to 15000:\n")
nArr := [...]int64{5, 50, 500, 1000, 5000, 15000}
for _, n = range nArr {
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 100 to 1000:\n")
for n = 100; n < 1001; n += 100 {
p = n / 3
fmt.Printf("C(%d,%d) =%d\n", n, p, comb(big.NewInt(n), big.NewInt(p)))
}
}
func fact(n *big.Int) *big.Int {
if n.Sign() < 1 {
return big.NewInt(0)
}
r := big.NewInt(1)
i := big.NewInt(2)
for i.Cmp(n) < 1 {
r.Mul(r, i)
i.Add(i, big.NewInt(1))
}
return r
}
func perm(n, k *big.Int) *big.Int {
r := fact(n)
r.Div(r, fact(n.Sub(n, k)))
return r
}
func comb(n, r *big.Int) *big.Int {
if r.Cmp(n) == 1 {
return big.NewInt(0)
}
if r.Cmp(n) == 0 {
return big.NewInt(1)
}
c := fact(n)
den := fact(n.Sub(n, r))
den.Mul(den, fact(r))
c.Div(c, den)
return c
} | 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,
: LT,
: GT,
: LE,
: GE,
: EQ,
: NE,
: AND,
: OR,
: NOT,
: NEG,
: JMP,
: JZ,
: PRTC,
: PRTS,
: PRTI,
: HALT
}
input_file = None
code = bytearray()
string_pool = []
word_size = 4
def error(msg):
print(% (msg))
exit(1)
def int_to_bytes(val):
return struct.pack(, val)
def bytes_to_int(bstr):
return struct.unpack(, bstr)
def emit_byte(x):
code.append(x)
def emit_word(x):
s = int_to_bytes(x)
for x in s:
code.append(x)
def run_vm(data_size):
stack = [0 for i in range(data_size + 1)]
pc = 0
while True:
op = code[pc]
pc += 1
if op == FETCH:
stack.append(stack[bytes_to_int(code[pc:pc+word_size])[0]]);
pc += word_size
elif op == STORE:
stack[bytes_to_int(code[pc:pc+word_size])[0]] = stack.pop();
pc += word_size
elif op == PUSH:
stack.append(bytes_to_int(code[pc:pc+word_size])[0]);
pc += word_size
elif op == ADD: stack[-2] += stack[-1]; stack.pop()
elif op == SUB: stack[-2] -= stack[-1]; stack.pop()
elif op == MUL: stack[-2] *= stack[-1]; stack.pop()
elif op == DIV: stack[-2] = int(float(stack[-2]) / stack[-1]); stack.pop()
elif op == MOD: stack[-2] = int(float(stack[-2])% stack[-1]); stack.pop()
elif op == LT: stack[-2] = stack[-2] < stack[-1]; stack.pop()
elif op == GT: stack[-2] = stack[-2] > stack[-1]; stack.pop()
elif op == LE: stack[-2] = stack[-2] <= stack[-1]; stack.pop()
elif op == GE: stack[-2] = stack[-2] >= stack[-1]; stack.pop()
elif op == EQ: stack[-2] = stack[-2] == stack[-1]; stack.pop()
elif op == NE: stack[-2] = stack[-2] != stack[-1]; stack.pop()
elif op == AND: stack[-2] = stack[-2] and stack[-1]; stack.pop()
elif op == OR: stack[-2] = stack[-2] or stack[-1]; stack.pop()
elif op == NEG: stack[-1] = -stack[-1]
elif op == NOT: stack[-1] = not stack[-1]
elif op == JMP: pc += bytes_to_int(code[pc:pc+word_size])[0]
elif op == JZ:
if stack.pop():
pc += word_size
else:
pc += bytes_to_int(code[pc:pc+word_size])[0]
elif op == PRTC: print(% (stack[-1]), end=''); stack.pop()
elif op == PRTS: print(% (string_pool[stack[-1]]), end=''); stack.pop()
elif op == PRTI: print(% (stack[-1]), end=''); stack.pop()
elif op == HALT: break
def str_trans(srce):
dest =
i = 0
while i < len(srce):
if srce[i] == '\\' and i + 1 < len(srce):
if srce[i + 1] == 'n':
dest += '\n'
i += 2
elif srce[i + 1] == '\\':
dest += '\\'
i += 2
else:
dest += srce[i]
i += 1
return dest
def load_code():
global string_pool
line = input_file.readline()
if len(line) == 0:
error()
line_list = line.split()
data_size = int(line_list[1])
n_strings = int(line_list[3])
for i in range(n_strings):
string_pool.append(str_trans(input_file.readline().strip('Unknown instruction%s at%drCan't open%s"% sys.argv[1])
data_size = load_code()
run_vm(data_size) | 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')
print('', 'has length', len(A), 'and is the shortest of the two strings')
else:
print('', 'has length', len(A), 'and it is as long as the second string')
print('', 'has length', len(B), 'and it is as long as the second string') | 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 (size) {
case 0: break;
case 1: strcat(s, strs[0]);
break;
default: for (i = 0; i < size - 1; i++)
{
strcat(s, strs[i]);
if (i < size - 2)
strcat(s, );
else
strcat(s, );
}
strcat(s, strs[i]);
break;
}
strcat(s, );
return s;
}
int main(void)
{
const char *test[] = {, , , };
char *s;
for (size_t i = 0; i < 5; i++)
{
s = quib(test, i);
printf(, s);
free(s);
}
return EXIT_SUCCESS;
} | 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 else take maxlen st ++ "... (" ++ show (stlen-maxlen) ++ " more digits)"
let showPerm pr =
putStrLn $ "perm(" ++ show n ++ "," ++ show k ++ ") = " ++ showBig 40 (perm n k)
where n = fst pr
k = snd pr
let showComb pr =
putStrLn $ "comb(" ++ show n ++ "," ++ show k ++ ") = " ++ showBig 40 (comb n k)
where n = fst pr
k = snd pr
putStrLn "A sample of permutations from 1 to 12:"
mapM_ showPerm [(n, n `div` 3) | n <- [1..12] ]
putStrLn ""
putStrLn "A sample of combinations from 10 to 60:"
mapM_ showComb [(n, n `div` 3) | n <- [10,20..60] ]
putStrLn ""
putStrLn "A sample of permutations from 5 to 15000:"
mapM_ showPerm [(n, n `div` 3) | n <- [5,50,500,1000,5000,15000] ]
putStrLn ""
putStrLn "A sample of combinations from 100 to 1000:"
mapM_ showComb [(n, n `div` 3) | n <- [100,200..1000] ] | 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 = new HashMap[String, Int]
val strings = new ArrayBuffer[String]
val code = new ArrayBuffer[String]
var s: Stream[String] = ast.getLines.toStream
def line =
if (s.nonEmpty) {
val n = s.head
s = s.tail
n.split(" +", 2) match {
case Array(n) => n
case a => a
}
} else
sys.error("unexpected end of AST")
def variableIndex(name: String) =
vars get name match {
case None =>
val idx = vars.size
vars(name) = idx
idx
case Some(idx) => idx
}
def stringIndex(s: String) =
strings indexOf s match {
case -1 =>
val idx = strings.length
strings += s
idx
case idx => idx
}
var loc = 0
def addSimple(inst: String) = {
code += f"$loc%4d $inst"
loc += 1
}
def addOperand(inst: String, operand: String) = {
code += f"$loc%4d $inst%-5s $operand"
loc += 5
}
def fixup(inst: String, idx: Int, at: Int) = code(idx) = f"$at%4d $inst%-5s (${loc - at - 1}) $loc"
generate
addSimple("halt")
println(s"Datasize: ${vars.size} Strings: ${strings.length}")
for (s <- strings)
println(s)
println(code mkString "\n")
def generate: Unit =
line match {
case "Sequence" =>
generate
generate
case ";" =>
case "Assign" =>
val idx =
line match {
case Array("Identifier", name: String) =>
variableIndex(name)
case l => sys.error(s"expected identifier: $l")
}
generate
addOperand("store", s"[$idx]")
case Array("Identifier", name: String) => addOperand("fetch", s"[${variableIndex(name)}]")
case Array("Integer", n: String) => addOperand("push", s"$n")
case Array("String", s: String) => addOperand("push", s"${stringIndex(s)}")
case "If" =>
generate
val cond = loc
val condidx = code.length
addOperand("", "")
s = s.tail
generate
if (s.head == ";") {
s = s.tail
fixup("jz", condidx, cond)
} else {
val jump = loc
val jumpidx = code.length
addOperand("", "")
fixup("jz", condidx, cond)
generate
fixup("jmp", jumpidx, jump)
}
case "While" =>
val start = loc
generate
val cond = loc
val condidx = code.length
addOperand("", "")
generate
addOperand("jmp", s"(${start - loc - 1}) $start")
fixup("jz", condidx, cond)
case op =>
generate
generate
addSimple(
op match {
case "Prti" => "prti"
case "Prts" => "prts"
case "Prtc" => "prtc"
case "Add" => "add"
case "Subtract" => "sub"
case "Multiply" => "mul"
case "Divide" => "div"
case "Mod" => "mod"
case "Less" => "lt"
case "LessEqual" => "le"
case "Greater" => "gt"
case "GreaterEqual" => "ge"
case "Equal" => "eq"
case "NotEqual" => "ne"
case "And" => "and"
case "Or" => "or"
case "Negate" => "neg"
case "Not" => "not"
}
)
}
}
} | 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++ ) {
int k = n / 2;
System.out.printf("%d P%d =%s%n", n, k, permutation(n, k));
}
System.out.println();
System.out.println("A sample of combinations from 10 to 60 with exact Integer arithmetic:");
for ( int n = 10 ; n <= 60 ; n += 5 ) {
int k = n / 2;
System.out.printf("%d C%d =%s%n", n, k, combination(n, k));
}
System.out.println();
System.out.println("A sample of permutations from 5 to 15000 displayed in floating point arithmetic:");
System.out.printf("%d P%d =%s%n", 5, 2, display(permutation(5, 2), 50));
for ( int n = 1000 ; n <= 15000 ; n += 1000 ) {
int k = n / 2;
System.out.printf("%d P%d =%s%n", n, k, display(permutation(n, k), 50));
}
System.out.println();
System.out.println("A sample of combinations from 100 to 1000 displayed in floating point arithmetic:");
for ( int n = 100 ; n <= 1000 ; n += 100 ) {
int k = n / 2;
System.out.printf("%d C%d =%s%n", n, k, display(combination(n, k), 50));
}
}
private static String display(BigInteger val, int precision) {
String s = val.toString();
precision = Math.min(precision, s.length());
StringBuilder sb = new StringBuilder();
sb.append(s.substring(0, 1));
sb.append(".");
sb.append(s.substring(1, precision));
sb.append(" * 10^");
sb.append(s.length()-1);
return sb.toString();
}
public static BigInteger combination(int n, int k) { | 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"]
["ABC", "DEF", "G", "H"]]]
((comp println %) sq)))
(test quibble)
(test quibble-f) | 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 JMP: Byte = 3
val JZ: Byte = 4
val ADD: Byte = 5
val SUB: Byte = 6
val MUL: Byte = 7
val DIV: Byte = 8
val MOD: Byte = 9
val LT: Byte = 10
val GT: Byte = 11
val LE: Byte = 12
val GE: Byte = 13
val EQ: Byte = 14
val NE: Byte = 15
val AND: Byte = 16
val OR: Byte = 17
val NEG: Byte = 18
val NOT: Byte = 19
val PRTC: Byte = 20
val PRTI: Byte = 21
val PRTS: Byte = 22
val HALT: Byte = 23
}
import Opcodes._
private val HEADER_REGEX = "Datasize: ([0-9]+) Strings: ([0-9]+)" r
private val STRING_REGEX = "\"([^\"]*)\"" r
private val PUSH_REGEX = " *[0-9]+ push +([0-9]+|'(?:[^'\\n]|\\\\n|\\\\\\\\)')" r
private val PRTS_REGEX = " *[0-9]+ prts" r
private val PRTI_REGEX = " *[0-9]+ prti" r
private val PRTC_REGEX = " *[0-9]+ prtc" r
private val HALT_REGEX = " *[0-9]+ halt" r
private val STORE_REGEX = " *[0-9]+ store +\\[([0-9]+)\\]" r
private val FETCH_REGEX = " *[0-9]+ fetch +\\[([0-9]+)\\]" r
private val LT_REGEX = " *[0-9]+ lt" r
private val GT_REGEX = " *[0-9]+ gt" r
private val LE_REGEX = " *[0-9]+ le" r
private val GE_REGEX = " *[0-9]+ ge" r
private val NE_REGEX = " *[0-9]+ ne" r
private val EQ_REGEX = " *[0-9]+ eq" r
private val JZ_REGEX = " *[0-9]+ jz +\\((-?[0-9]+)\\) [0-9]+" r
private val ADD_REGEX = " *[0-9]+ add" r
private val SUB_REGEX = " *[0-9]+ sub" r
private val MUL_REGEX = " *[0-9]+ mul" r
private val DIV_REGEX = " *[0-9]+ div" r
private val MOD_REGEX = " *[0-9]+ mod" r
private val AND_REGEX = " *[0-9]+ and" r
private val OR_REGEX = " *[0-9]+ or" r
private val NOT_REGEX = " *[0-9]+ not" r
private val NEG_REGEX = " *[0-9]+ neg" r
private val JMP_REGEX = " *[0-9]+ jmp +\\((-?[0-9]+)\\) [0-9]+" r
def fromStdin = fromReader(Console.in)
def fromFile(file: String) = fromReader(new FileReader(file))
def fromString(src: String) = fromReader(new StringReader(src))
def fromReader(r: Reader) = {
val in = new BufferedReader(r)
val vm =
in.readLine match {
case HEADER_REGEX(datasize, stringsize) =>
val strings =
for (_ <- 1 to stringsize.toInt)
yield
in.readLine match {
case STRING_REGEX(s) => unescape(s)
case null => sys.error("expected string constant but encountered end of input")
case s => sys.error(s"expected string constant: $s")
}
var line: String = null
val code = new ArrayBuffer[Byte]
def addShort(a: Int) = {
code += (a >> 8).toByte
code += a.toByte
}
def addInstIntOperand(opcode: Byte, operand: Int) = {
code += opcode
addShort(operand >> 16)
addShort(operand)
}
def addInst(opcode: Byte, operand: String) = addInstIntOperand(opcode, operand.toInt)
while ({ line = in.readLine; line ne null }) line match {
case PUSH_REGEX(n) if n startsWith "'" =>
addInstIntOperand(PUSH, unescape(n.substring(1, n.length - 1)).head)
case PUSH_REGEX(n) => addInst(PUSH, n)
case PRTS_REGEX() => code += PRTS
case PRTI_REGEX() => code += PRTI
case PRTC_REGEX() => code += PRTC
case HALT_REGEX() => code += HALT
case STORE_REGEX(idx) => addInst(STORE, idx)
case FETCH_REGEX(idx) => addInst(FETCH, idx)
case LT_REGEX() => code += LT
case GT_REGEX() => code += GT
case LE_REGEX() => code += LE
case GE_REGEX() => code += GE
case NE_REGEX() => code += NE
case EQ_REGEX() => code += EQ
case JZ_REGEX(disp) => addInst(JZ, disp)
case ADD_REGEX() => code += ADD
case SUB_REGEX() => code += SUB
case MUL_REGEX() => code += MUL
case DIV_REGEX() => code += DIV
case MOD_REGEX() => code += MOD
case AND_REGEX() => code += AND
case OR_REGEX() => code += OR
case NOT_REGEX() => code += NOT
case NEG_REGEX() => code += NEG
case JMP_REGEX(disp) => addInst(JMP, disp)
}
new VirtualMachine(code, datasize.toInt, strings)
case _ => sys.error("expected header")
}
in.close
vm
}
}
class VirtualMachine(code: IndexedSeq[Byte], datasize: Int, strings: IndexedSeq[String]) {
import VirtualMachine.Opcodes._
var pc = 0
val stack = new mutable.ArrayStack[Int]
val data = new Array[Int](datasize)
var running = false
def getByte = {
val byte = code(pc) & 0xFF
pc += 1
byte
}
def getShort = getByte << 8 | getByte
def getInt = getShort << 16 | getShort
def pushBoolean(b: Boolean) = stack push (if (b) 1 else 0)
def popBoolean = if (stack.pop != 0) true else false
def operator(f: (Int, Int) => Int) = {
val y = stack.pop
stack.push(f(stack.pop, y))
}
def relation(r: (Int, Int) => Boolean) = {
val y = stack.pop
pushBoolean(r(stack.pop, y))
}
def connective(c: (Boolean, Boolean) => Boolean) = pushBoolean(c(popBoolean, popBoolean))
def execute: Unit =
getByte match {
case FETCH => stack push data(getInt)
case STORE => data(getInt) = stack.pop
case PUSH => stack push getInt
case JMP => pc = pc + getInt
case JZ => if (stack.pop == 0) pc = pc + getInt else pc += 4
case ADD => operator(_ + _)
case SUB => operator(_ - _)
case MUL => operator(_ * _)
case DIV => operator(_ / _)
case MOD => operator(_ % _)
case LT => relation(_ < _)
case GT => relation(_ > _)
case LE => relation(_ <= _)
case GE => relation(_ >= _)
case EQ => relation(_ == _)
case NE => relation(_ != _)
case AND => connective(_ && _)
case OR => connective(_ || _)
case NEG => stack push -stack.pop
case NOT => pushBoolean(!popBoolean)
case PRTC => print(stack.pop.toChar)
case PRTI => print(stack.pop)
case PRTS => print(strings(stack.pop))
case HALT => running = false
}
def run = {
pc = 0
stack.clear
running = true
for (i <- data.indices) data(i) = 0
while (running) execute
}
} | 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).distinct().count() < 2);
System.out.println(Arrays.equals(Arrays.stream(a).distinct().sorted().toArray(), 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'], empty = [], single = ['AA'];
console.log(allEqual(e)); | 1,017Compare a list of strings
| 10javascript
| e0kao |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.