code
stringlengths 1
46.1k
⌀ | label
class label 1.18k
classes | domain_label
class label 21
classes | index
stringlengths 4
5
|
---|---|---|---|
@js.annotation.JSExportTopLevel("ScalaFiddle")
object ScalaFiddle { | 748Hilbert curve
| 16scala
| 4xn50 |
use strict; use warnings;
use Date::Calc qw(:all);
my @abbr = qw( Not Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec );
my %c_hols = (
Easter=> 0,
Ascension=> 39,
Pentecost=> 49,
Trinity=> 56,
Corpus=> 60
);
sub easter {
my $year=shift;
my $ay=$year % 19;
my $by=int($year / 100);
my $cy=$year % 100;
my $dy=int($by/4);
my $ey=$by % 4;
my $fy=int(($by+8)/25);
my $gy=int(($by-$fy+1)/3);
my $hy=($ay*19+$by-$dy-$gy+15) % 30;
my $iy=int($cy/4);
my $ky=$cy % 4;
my $ly=(32+2*$ey+2*$iy-$hy-$ky) % 7;
my $m_y=int(($ay+11*$hy+22*$ly)/451);
my $month=int(($hy+$ly-7*$m_y+114)/31);
my $day=(($hy+$ly-7*$m_y+114) % 31)+1;
return ($month, $day, $year);
}
sub cholidays {
my $year=shift;
my ($emon, $eday)=easter($year);
my @fields;
printf("%4s: ", $year);
foreach my $hol (sort { $c_hols{$a}<=>$c_hols{$b} } keys %c_hols) {
my ($ye,$mo,$da)=Add_Delta_Days($year,$emon,$eday,$c_hols{$hol});
my $month=$abbr[$mo];
push @fields, sprintf("%s:%02s%s",$hol,$da,$month);
}
print join (", ",@fields);
print "\n";
}
print "Christian holidays, related to Easter, for each centennial from ",
"400 to 2100 CE:\n";
for (my $year=400; $year<=2100; $year+=100) {
cholidays($year);
}
print "Christian holidays, related to Easter, ",
"for years from 2010 to 2020 CE:\n";
cholidays($_) for(2010..2020); | 745Holidays related to Easter
| 2perl
| j8y7f |
use warnings ;
use strict ;
my $limit = 2 ** 20 ;
my @numbers = ( 0 , 1 , 1 ) ;
my $mallows ;
my $max_i ;
foreach my $i ( 3..$limit ) {
push ( @numbers , $numbers[ $numbers[ $i - 1 ]] + $numbers[ $i - $numbers[ $i - 1 ] ] ) ;
}
for ( my $rangelimit = 1 ; $rangelimit < 20 ; $rangelimit++ ) {
my $max = 0 ;
for ( my $i = 2 ** $rangelimit ; $i < ( 2 ** ( $rangelimit + 1 ) ) ; $i++ ) {
my $rat = $numbers[ $i ] / $i ;
$mallows = $i if $rat >= 0.55 ;
if ( $rat > $max ) {
$max = $rat ;
$max_i = $i ;
}
}
my $upperlimit = $rangelimit + 1 ;
print "Between 2 ^ $rangelimit and 2 ^ $upperlimit the maximum value is $max at $max_i!\n" ;
}
print "The prize would have been won at $mallows!\n" | 743Hofstadter-Conway $10,000 sequence
| 2perl
| vaf20 |
qSequence = tail qq where
qq = 0: 1: 1: map g [3..]
g n = qq !! (n - qq !! (n-1)) + qq !! (n - qq !! (n-2))
*Main> (take 10 qSequence, qSequence !! (1000-1))
([1,1,2,3,3,4,5,5,6,6],502)
(0.00 secs, 525044 bytes) | 749Hofstadter Q sequence
| 8haskell
| ue8v2 |
<?php
function horner($coeff, $x) {
$result = 0;
foreach (array_reverse($coeff) as $c)
$result = $result * $x + $c;
return $result;
}
$coeff = array(-19.0, 7, -4, 6);
$x = 3;
echo horner($coeff, $x), ;
?> | 740Horner's rule for polynomial evaluation
| 12php
| va32v |
function identity(n) {
if (n < 1) return "Not defined";
else if (n == 1) return 1;
else {
var idMatrix:number[][];
for (var i: number = 0; i < n; i++) {
for (var j: number = 0; j < n; j++) {
if (i!= j) idMatrix[i][j] = 0;
else idMatrix[i][j] = 1;
}
}
return idMatrix;
}
} | 730Identity matrix
| 20typescript
| hipjt |
import java.util.ArrayList
object Heron {
private val n = 200
fun run() {
val l = ArrayList<IntArray>()
for (c in 1..n)
for (b in 1..c)
for (a in 1..b)
if (gcd(gcd(a, b), c) == 1) {
val p = a + b + c
val s = p / 2.0
val area = Math.sqrt(s * (s - a) * (s - b) * (s - c))
if (isHeron(area))
l.add(intArrayOf(a, b, c, p, area.toInt()))
}
print("Number of primitive Heronian triangles with sides up to $n: " + l.size)
sort(l)
print("\n\nFirst ten when ordered by increasing area, then perimeter:" + header)
for (i in 0 until 10) {
print(format(l[i]))
}
val a = 210
print("\n\nArea = $a" + header)
l.filter { it[4] == a }.forEach { print(format(it)) }
}
private fun gcd(a: Int, b: Int): Int {
var leftover = 1
var dividend = if (a > b) a else b
var divisor = if (a > b) b else a
while (leftover != 0) {
leftover = dividend % divisor
if (leftover > 0) {
dividend = divisor
divisor = leftover
}
}
return divisor
}
fun sort(l: MutableList<IntArray>) {
var swapped = true
while (swapped) {
swapped = false
for (i in 1 until l.size)
if (l[i][4] < l[i - 1][4] || l[i][4] == l[i - 1][4] && l[i][3] < l[i - 1][3]) {
val temp = l[i]
l[i] = l[i - 1]
l[i - 1] = temp
swapped = true
}
}
}
private fun isHeron(h: Double) = h.rem(1) == 0.0 && h > 0
private val header = "\nSides Perimeter Area"
private fun format(a: IntArray) = "\n%3d x%3d x%3d%5d%10d".format(a[0], a[1], a[2], a[3], a[4])
}
fun main(args: Array<String>) = Heron.run() | 752Heronian triangles
| 11kotlin
| 70ir4 |
$r = [nil, 1]
$s = [nil, 2]
def buildSeq(n)
current = [ $r[-1], $s[-1] ].max
while $r.length <= n || $s.length <= n
idx = [ $r.length, $s.length ].min - 1
current += 1
if current == $r[idx] + $s[idx]
$r << current
else
$s << current
end
end
end
def ffr(n)
buildSeq(n)
$r[n]
end
def ffs(n)
buildSeq(n)
$s[n]
end
require 'set'
require 'test/unit'
class TestHofstadterFigureFigure < Test::Unit::TestCase
def test_first_ten_R_values
r10 = 1.upto(10).map {|n| ffr(n)}
assert_equal(r10, [1, 3, 7, 12, 18, 26, 35, 45, 56, 69])
end
def test_40_R_and_960_S_are_1_to_1000
rs_values = Set.new
rs_values.merge( 1.upto(40).collect {|n| ffr(n)} )
rs_values.merge( 1.upto(960).collect {|n| ffs(n)} )
assert_equal(rs_values, Set.new( 1..1000 ))
end
end | 747Hofstadter Figure-Figure sequences
| 14ruby
| dukns |
from __future__ import print_function
import math
try: raw_input
except: raw_input = input
lat = float(raw_input())
lng = float(raw_input())
ref = float(raw_input())
print()
slat = math.sin(math.radians(lat))
print(% slat)
print(% (lng-ref))
print()
print()
for h in range(-6, 7):
hra = 15 * h
hra -= lng - ref
hla = math.degrees(math.atan(slat * math.tan(math.radians(hra))))
print(% (h, hra, hla)) | 739Horizontal sundial calculations
| 3python
| 1frpc |
null | 752Heronian triangles
| 1lua
| j8n71 |
use Socket;
my $port = 8080;
my $protocol = getprotobyname( "tcp" );
socket( SOCK, PF_INET, SOCK_STREAM, $protocol ) or die "couldn't open a socket: $!";
setsockopt( SOCK, SOL_SOCKET, SO_REUSEADDR, 1 ) or die "couldn't set socket options: $!";
bind( SOCK, sockaddr_in($port, INADDR_ANY) ) or die "couldn't bind socket to port $port: $!";
listen( SOCK, SOMAXCONN ) or die "couldn't listen to port $port: $!";
while( accept(CLIENT, SOCK) ){
print CLIENT "HTTP/1.1 200 OK\r\n" .
"Content-Type: text/html; charset=UTF-8\r\n\r\n" .
"<html><head><title>Goodbye, world!</title></head><body>Goodbye, world!</body></html>\r\n";
close CLIENT;
} | 750Hello world/Web server
| 2perl
| du7nw |
use std::collections::HashMap;
struct Hffs {
sequence_r: HashMap<usize, usize>,
sequence_s: HashMap<usize, usize>,
}
impl Hffs {
fn new() -> Hffs {
Hffs {
sequence_r: HashMap::new(),
sequence_s: HashMap::new(),
}
}
fn ffr(&mut self, n: usize) -> usize { | 747Hofstadter Figure-Figure sequences
| 15rust
| f5bd6 |
object HofstadterFigFigSeq extends App {
import scala.collection.mutable.ListBuffer
val r = ListBuffer(0, 1)
val s = ListBuffer(0, 2)
def ffr(n: Int): Int = {
val ffri: Int => Unit = i => {
val nrk = r.size - 1
val rNext = r(nrk)+s(nrk)
r += rNext
(r(nrk)+2 to rNext-1).foreach{s += _}
s += rNext+1
}
(r.size to n).foreach(ffri(_))
r(n)
}
def ffs(n:Int): Int = {
while (s.size <= n) ffr(r.size)
s(n)
}
(1 to 10).map(i=>(i,ffr(i))).foreach(t=>println("r("+t._1+"): "+t._2))
println((1 to 1000).toList.filterNot(((1 to 40).map(ffr(_))++(1 to 960).map(ffs(_))).contains)==List())
} | 747Hofstadter Figure-Figure sequences
| 16scala
| 3razy |
require 'priority_queue'
def huffman_encoding(str)
char_count = Hash.new(0)
str.each_char {|c| char_count[c] += 1}
pq = CPriorityQueue.new
char_count.each {|char, count| pq.push(char, count)}
while pq.length > 1
key1, prio1 = pq.delete_min
key2, prio2 = pq.delete_min
pq.push([key1, key2], prio1 + prio2)
end
Hash[*generate_encoding(pq.min_key)]
end
def generate_encoding(ary, prefix=)
case ary
when Array
generate_encoding(ary[0], ) + generate_encoding(ary[1], )
else
[ary, prefix]
end
end
def encode(str, encoding)
str.each_char.collect {|char| encoding[char]}.join
end
def decode(encoded, encoding)
rev_enc = encoding.invert
decoded =
pos = 0
while pos < encoded.length
key =
while rev_enc[key].nil?
key << encoded[pos]
pos += 1
end
decoded << rev_enc[key]
end
decoded
end
str =
encoding = huffman_encoding(str)
encoding.to_a.sort.each {|x| p x}
enc = encode(str, encoding)
dec = decode(enc, encoding)
puts if str == dec | 736Huffman coding
| 14ruby
| pdjbh |
local http = require("socket.http")
local url = require("socket.url")
local page = http.request('http://www.google.com/m/search?q=' .. url.escape("lua"))
print(page) | 741HTTP
| 1lua
| ho2j8 |
from __future__ import division
def maxandmallows(nmaxpower2):
nmax = 2**nmaxpower2
mx = (0.5, 2)
mxpow2 = []
mallows = None
hc = [None, 1, 1]
for n in range(2, nmax + 1):
ratio = hc[n] / n
if ratio > mx[0]:
mx = (ratio, n)
if ratio >= 0.55:
mallows = n
if ratio == 0.5:
print(%
(n
mxpow2.append(mx[0])
mx = (ratio, n)
hc.append(hc[hc[n]] + hc[-hc[n]])
return hc, mallows if mxpow2 and mxpow2[-1] < 0.55 and n > 4 else None
if __name__ == '__main__':
hc, mallows = maxandmallows(20)
if mallows:
print(% mallows) | 743Hofstadter-Conway $10,000 sequence
| 3python
| uetvd |
import java.util.HashMap;
import java.util.Map;
public class HofQ {
private static Map<Integer, Integer> q = new HashMap<Integer, Integer>(){{
put(1, 1);
put(2, 1);
}};
private static int[] nUses = new int[100001]; | 749Hofstadter Q sequence
| 9java
| mheym |
use std::collections::BTreeMap;
use std::collections::binary_heap::BinaryHeap;
#[derive(Debug, Eq, PartialEq)]
enum NodeKind {
Internal(Box<Node>, Box<Node>),
Leaf(char),
}
#[derive(Debug, Eq, PartialEq)]
struct Node {
frequency: usize,
kind: NodeKind,
}
impl Ord for Node {
fn cmp(&self, rhs: &Self) -> std::cmp::Ordering {
rhs.frequency.cmp(&self.frequency)
}
}
impl PartialOrd for Node {
fn partial_cmp(&self, rhs: &Self) -> Option<std::cmp::Ordering> {
Some(self.cmp(&rhs))
}
}
type HuffmanCodeMap = BTreeMap<char, Vec<u8>>;
fn main() {
let text = "this is an example for huffman encoding";
let mut frequencies = BTreeMap::new();
for ch in text.chars() {
*frequencies.entry(ch).or_insert(0) += 1;
}
let mut prioritized_frequencies = BinaryHeap::new();
for counted_char in frequencies {
prioritized_frequencies.push(Node {
frequency: counted_char.1,
kind: NodeKind::Leaf(counted_char.0),
});
}
while prioritized_frequencies.len() > 1 {
let left_child = prioritized_frequencies.pop().unwrap();
let right_child = prioritized_frequencies.pop().unwrap();
prioritized_frequencies.push(Node {
frequency: right_child.frequency + left_child.frequency,
kind: NodeKind::Internal(Box::new(left_child), Box::new(right_child)),
});
}
let mut codes = HuffmanCodeMap::new();
generate_codes(
prioritized_frequencies.peek().unwrap(),
vec![0u8; 0],
&mut codes,
);
for item in codes {
print!("{}: ", item.0);
for bit in item.1 {
print!("{}", bit);
}
println!();
}
}
fn generate_codes(node: &Node, prefix: Vec<u8>, out_codes: &mut HuffmanCodeMap) {
match node.kind {
NodeKind::Internal(ref left_child, ref right_child) => {
let mut left_prefix = prefix.clone();
left_prefix.push(0);
generate_codes(&left_child, left_prefix, out_codes);
let mut right_prefix = prefix;
right_prefix.push(1);
generate_codes(&right_child, right_prefix, out_codes);
}
NodeKind::Leaf(ch) => {
out_codes.insert(ch, prefix);
}
}
} | 736Huffman coding
| 15rust
| 1fhpu |
f = local(
{a = c(1, 1)
function(n)
{if (is.na(a[n]))
a[n] <<- f(f(n - 1)) + f(n - f(n - 1))
a[n]}}) | 743Hofstadter-Conway $10,000 sequence
| 13r
| cbi95 |
var hofstadterQ = function() {
var memo = [1,1,1];
var Q = function (n) {
var result = memo[n];
if (typeof result !== 'number') {
result = Q(n - Q(n-1)) + Q(n - Q(n-2));
memo[n] = result;
}
return result;
};
return Q;
}();
for (var i = 1; i <=10; i += 1) {
console.log('Q('+ i +') = ' + hofstadterQ(i));
}
console.log('Q(1000) = ' + hofstadterQ(1000)); | 749Hofstadter Q sequence
| 10javascript
| va025 |
<?php
$socket = socket_create(AF_INET, SOCK_STREAM, 0) or die('Failed to create socket!');
socket_bind($socket, 0, 8080);
socket_listen($socket);
$msg = '<html><head><title>Goodbye, world!</title></head><body>Goodbye, world!</body></html>';
for (;;) {
if ($client = @socket_accept($socket)) {
socket_write($client, .
. strlen($msg) . .
.
$msg);
}
else usleep(100000);
}
?> | 750Hello world/Web server
| 12php
| j8f7z |
>>> def horner(coeffs, x):
acc = 0
for c in reversed(coeffs):
acc = acc * x + c
return acc
>>> horner( (-19, 7, -4, 6), 3)
128 | 740Horner's rule for polynomial evaluation
| 3python
| smbq9 |
horner <- function(a, x) {
y <- 0
for(c in rev(a)) {
y <- y * x + c
}
y
}
cat(horner(c(-19, 7, -4, 6), 3), "\n") | 740Horner's rule for polynomial evaluation
| 13r
| ez7ad |
include Math
DtoR = PI/180
print 'Enter latitude: '
lat = Float( gets )
print 'Enter longitude: '
lng = Float( gets )
print 'Enter legal meridian: '
ref = Float( gets )
puts
slat = sin( lat * DtoR )
puts % slat
puts % (lng-ref)
puts
puts 'Hour, sun hour angle, dial hour line angle from 6am to 6pm'
-6.upto(6) do |h|
hra = 15 * h
hra -= lng - ref
hla = atan( slat * tan( hra * DtoR ))/ DtoR
puts % [h, hra, hla]
end | 739Horizontal sundial calculations
| 14ruby
| ezjax |
object Huffman {
import scala.collection.mutable.{Map, PriorityQueue}
sealed abstract class Tree
case class Node(left: Tree, right: Tree) extends Tree
case class Leaf(c: Char) extends Tree
def treeOrdering(m: Map[Tree, Int]) = new Ordering[Tree] {
def compare(x: Tree, y: Tree) = m(y).compare(m(x))
}
def stringMap(text: String) = text groupBy (x => Leaf(x) : Tree) mapValues (_.length)
def buildNode(queue: PriorityQueue[Tree], map: Map[Tree,Int]) {
val right = queue.dequeue
val left = queue.dequeue
val node = Node(left, right)
map(node) = map(left) + map(right)
queue.enqueue(node)
}
def codify(tree: Tree, map: Map[Tree, Int]) = {
def recurse(tree: Tree, prefix: String): List[(Char, (Int, String))] = tree match {
case Node(left, right) => recurse(left, prefix+"0") ::: recurse(right, prefix+"1")
case leaf @ Leaf(c) => c -> ((map(leaf), prefix)) :: Nil
}
recurse(tree, "")
}
def encode(text: String) = {
val map = Map.empty[Tree,Int] ++= stringMap(text)
val queue = new PriorityQueue[Tree]()(treeOrdering(map)) ++= map.keysIterator
while(queue.size > 1) {
buildNode(queue, map)
}
codify(queue.dequeue, map)
}
def main(args: Array[String]) {
val text = "this is an example for huffman encoding"
val code = encode(text)
println("Char\tWeight\t\tEncoding")
code sortBy (_._2._1) foreach {
case (c, (weight, encoding)) => println("%c:\t%3d/%-3d\t\t%s" format (c, weight, text.length, encoding))
}
}
} | 736Huffman coding
| 16scala
| w3pes |
from dateutil.easter import *
import datetime, calendar
class Holiday(object):
def __init__(self, date, offset=0):
self.holiday = date + datetime.timedelta(days=offset)
def __str__(self):
dayofweek = calendar.day_name[self.holiday.weekday()][0:3]
month = calendar.month_name[self.holiday.month][0:3]
return '{0} {1:2d} {2}'.format(dayofweek, self.holiday.day, month)
def get_holiday_values(year):
holidays = {'year': year}
easterDate = easter(year)
holidays['easter'] = Holiday(easterDate)
holidays['ascension'] = Holiday(easterDate, 39)
holidays['pentecost'] = Holiday(easterDate, 49)
holidays['trinity'] = Holiday(easterDate, 56)
holidays['corpus'] = Holiday(easterDate, 60)
return holidays
def print_holidays(holidays):
print '{year:4d} Easter: {easter}, Ascension: {ascension}, Pentecost: {pentecost}, Trinity: {trinity}, Corpus: {corpus}'.format(**holidays)
if __name__ == :
print
for year in range(400, 2200, 100):
print_holidays(get_holiday_values(year))
print ''
print
for year in range(2010, 2021):
print_holidays(get_holiday_values(year)) | 745Holidays related to Easter
| 3python
| homjw |
use std::io;
struct SundialCalculation {
hour_angle: f64,
hour_line_angle: f64,
}
fn get_input(prompt: &str) -> Result<f64, Box<dyn std::error::Error>> {
println!("{}", prompt);
let mut input = String::new();
let stdin = io::stdin();
stdin.read_line(&mut input)?;
Ok(input.trim().parse::<f64>()?)
}
fn calculate_sundial(hour: i8, lat: f64, lng: f64, meridian: f64) -> SundialCalculation {
let diff = lng - meridian;
let hour_angle = f64::from(hour) * 15. - diff;
let hour_line_angle = (hour_angle.to_radians().tan() * lat.to_radians().sin())
.atan()
.to_degrees();
SundialCalculation {
hour_angle,
hour_line_angle,
}
}
fn main() -> Result<(), Box<dyn std::error::Error>> {
let lat = get_input("Enter latitude => ")?;
let lng = get_input("Enter longitude => ")?;
let meridian = get_input("Enter legal meridian => ")?;
let diff = lng - meridian;
let sine_lat = lat.to_radians().sin();
println!("Sine of latitude: {:.5}", sine_lat);
println!("Diff longitude: {}", diff);
println!(" Hrs Angle Hour Line Angle");
(-6..=6).for_each(|hour| {
let sd = calculate_sundial(hour, lat, lng, meridian);
println!(
"{:>3}{} {:>5} {:>+15.5}",
if hour == 0 { 12 } else { (hour + 12)% 12 },
if hour <= 6 { "pm" } else { "am" },
sd.hour_angle,
sd.hour_line_angle
);
});
Ok(())
} | 739Horizontal sundial calculations
| 15rust
| w3he4 |
warn "Goodbye, World!\n"; | 753Hello world/Standard error
| 2perl
| x6mw8 |
fprintf(STDERR, ); | 753Hello world/Standard error
| 12php
| 21el4 |
null | 749Hofstadter Q sequence
| 11kotlin
| t4kf0 |
library(tidyverse)
library(lubridate)
pretty_date = stamp_date("Thu, Jun 1, 2000")
tibble(year = c(seq(400, 2100, 100), 2010:2020))%>%
arrange(year)%>%
mutate(a = year%% 19,
b = year%% 4,
c = year%% 7,
k = year%/% 100,
p = (13 + 8 * k)%/% 25,
q = k%/% 4,
M = (15 - p + k - q)%% 30,
N = (4 + k - q)%% 7,
d = (19 * a + M)%% 30,
e = (2 * b + 4 * c + 6 * d + N)%% 7,
easter_mar = 22 + d + e,
easter_apr = d + e - 9,
easter_day = if_else(easter_mar <= 31, easter_mar, easter_apr),
easter_day = case_when(
d == 29 & e == 6 ~ 19,
d == 28 & e == 6 & (11 * M + 11)%% 30 < 19 ~ 18,
TRUE ~ easter_day),
easter_day = sprintf("%02d", easter_day),
easter_year = sprintf("%04d", year),
easter_mon = if_else(easter_mar <= 31, "03", "04"))%>%
unite("easter", easter_year, easter_mon, easter_day, sep = "-")%>%
mutate(Easter = parse_date(easter, format = "%Y-%m-%e"))%>%
select(Easter)%>%
mutate(Ascension = Easter + 39,
Pentecost = Ascension + 10,
Trinity = Pentecost + 7,
`Corpus Christi` = Trinity + 4,
across(.fns = pretty_date)) | 745Holidays related to Easter
| 13r
| gqz47 |
import java.util.Scanner
import scala.math.{atan2, cos, sin, toDegrees, toRadians}
object Sundial extends App {
var lat, slat,lng, ref = .0
val sc = new Scanner(System.in)
print("Enter latitude: ")
lat = sc.nextDouble
print("Enter longitude: ")
lng = sc.nextDouble
print("Enter legal meridian: ")
ref = sc.nextDouble
println()
slat = Math.sin(Math.toRadians(lat))
println(f"sine of latitude: $slat%.3f")
println(f"diff longitude: ${lng - ref}%.3f\n")
println("Hour, sun hour angle, dial hour line angle from 06h00 to 18h00")
for (h <- -6 to 6) {
val hra = 15.0 * h - lng + ref
val hraRad = toRadians(hra)
val hla = toDegrees(atan2(Math.sin(hraRad) * sin(Math.toRadians(lat)), cos(hraRad)))
println(f"HR= $h%3d;\tHRA=$hra%7.3f;\tHLA= $hla%7.3f")
}
} | 739Horizontal sundial calculations
| 16scala
| smpqo |
class HofstadterConway10000
def initialize
@sequence = [nil, 1, 1]
end
def [](n)
raise ArgumentError, if n < 1
a = @sequence
a.length.upto(n) {|i| a[i] = a[a[i-1]] + a[i-a[i-1]] }
a[n]
end
end
hc = HofstadterConway10000.new
mallows = nil
(1...20).each do |i|
j = i + 1
max_n, max_v = -1, -1
(2**i .. 2**j).each do |n|
v = hc[n].to_f / n
max_n, max_v = n, v if v > max_v
mallows = n if v >= 0.55
end
puts % [i, j, max_n, max_v]
end
puts | 743Hofstadter-Conway $10,000 sequence
| 14ruby
| 4x35p |
use strict;
use warnings;
use List::Util qw(max);
sub gcd { $_[1] == 0 ? $_[0] : gcd($_[1], $_[0] % $_[1]) }
sub hero {
my ($a, $b, $c) = @_[0,1,2];
my $s = ($a + $b + $c) / 2;
sqrt $s*($s - $a)*($s - $b)*($s - $c);
}
sub heronian_area {
my $hero = hero my ($a, $b, $c) = @_[0,1,2];
sprintf("%.0f", $hero) eq $hero ? $hero : 0
}
sub primitive_heronian_area {
my ($a, $b, $c) = @_[0,1,2];
heronian_area($a, $b, $c) if 1 == gcd $a, gcd $b, $c;
}
sub show {
print " Area Perimeter Sides\n";
for (@_) {
my ($area, $perim, $c, $b, $a) = @$_;
printf "%7d%9d %d%d%d\n", $area, $perim, $a, $b, $c;
}
}
sub main {
my $maxside = shift // 200;
my $first = shift // 10;
my $witharea = shift // 210;
my @h;
for my $c (1 .. $maxside) {
for my $b (1 .. $c) {
for my $a ($c - $b + 1 .. $b) {
if (my $area = primitive_heronian_area $a, $b, $c) {
push @h, [$area, $a+$b+$c, $c, $b, $a];
}
}
}
}
@h = sort {
$a->[0] <=> $b->[0]
or
$a->[1] <=> $b->[1]
or
max(@$a[2,3,4]) <=> max(@$b[2,3,4])
} @h;
printf "Primitive Heronian triangles with sides up to%d:%d\n",
$maxside,
scalar @h;
print "First:\n";
show @h[0 .. $first - 1];
print "Area $witharea:\n";
show grep { $_->[0] == $witharea } @h;
}
&main(); | 752Heronian triangles
| 2perl
| f5rd7 |
from wsgiref.simple_server import make_server
def app(environ, start_response):
start_response('200 OK', [('Content-Type','text/html')])
yield b
server = make_server('127.0.0.1', 8080, app)
server.serve_forever() | 750Hello world/Web server
| 3python
| f5jde |
library(httpuv)
runServer("0.0.0.0", 5000,
list(
call = function(req) {
list(status = 200L, headers = list('Content-Type' = 'text/html'), body = "Hello world!")
}
)
) | 750Hello world/Web server
| 13r
| ol484 |
struct HofstadterConway {
current: usize,
sequence: Vec<usize>,
}
impl HofstadterConway { | 743Hofstadter-Conway $10,000 sequence
| 15rust
| gq64o |
object HofstadterConway {
def pow2(n: Int): Int = (Iterator.fill(n)(2)).product
def makeHCSequence(max: Int): Seq[Int] =
(0 to max - 1).foldLeft (Vector[Int]()) { (v, idx) =>
if (idx <= 1) v :+ 1 else v :+ (v(v(idx - 1) - 1) + v(idx - v(idx - 1)))
}
val max = pow2(20)
val maxSeq = makeHCSequence(max)
def hcRatio(n: Int, seq: Seq[Int]): Double = seq(n - 1).toDouble / n
def maximumHCRatioBetween(a: Int, b: Int): (Int, Double) =
Iterator.range(a, b + 1) map (n => (n, hcRatio(n, maxSeq))) maxBy (_._2)
lazy val mallowsNumber: Int =
((max to 1 by -1) takeWhile (hcRatio(_, maxSeq) < 0.55) last) - 1
def main(args: Array[String]): Unit = {
for (n <- 1 to 19) {
val (value, ratio) = maximumHCRatioBetween(pow2(n), pow2(n+1))
val message = "Maximum of a(n)/n between 2^%s and 2^%s was%s at%s"
println(message.format(n, n+1, ratio, value))
}
println("Mallow's number =%s".format(mallowsNumber))
}
} | 743Hofstadter-Conway $10,000 sequence
| 16scala
| j897i |
import sys
print >> sys.stderr, | 753Hello world/Standard error
| 3python
| qy9xi |
def horner(coeffs, x)
coeffs.reverse.inject(0) {|acc, coeff| acc * x + coeff}
end
p horner([-19, 7, -4, 6], 3) | 740Horner's rule for polynomial evaluation
| 14ruby
| 8c101 |
cat("Goodbye, World!", file=stderr()) | 753Hello world/Standard error
| 13r
| at31z |
fn horner(v: &[f64], x: f64) -> f64 {
v.iter().rev().fold(0.0, |acc, coeff| acc*x + coeff)
}
fn main() {
let v = [-19., 7., -4., 6.];
println!("result: {}", horner(&v, 3.0));
} | 740Horner's rule for polynomial evaluation
| 15rust
| ola83 |
enum HuffmanTree<T> {
case Leaf(T)
indirect case Node(HuffmanTree<T>, HuffmanTree<T>)
func printCodes(prefix: String) {
switch(self) {
case let .Leaf(c):
print("\(c)\t\(prefix)")
case let .Node(l, r):
l.printCodes(prefix + "0")
r.printCodes(prefix + "1")
}
}
}
func buildTree<T>(freqs: [(T, Int)]) -> HuffmanTree<T> {
assert(freqs.count > 0, "must contain at least one character") | 736Huffman coding
| 17swift
| bn7kd |
STDERR.puts | 753Hello world/Standard error
| 14ruby
| 09lsu |
from __future__ import division, print_function
from math import gcd, sqrt
def hero(a, b, c):
s = (a + b + c) / 2
a2 = s * (s - a) * (s - b) * (s - c)
return sqrt(a2) if a2 > 0 else 0
def is_heronian(a, b, c):
a = hero(a, b, c)
return a > 0 and a.is_integer()
def gcd3(x, y, z):
return gcd(gcd(x, y), z)
if __name__ == '__main__':
MAXSIDE = 200
N = 1 + MAXSIDE
h = [(x, y, z)
for x in range(1, N)
for y in range(x, N)
for z in range(y, N) if (x + y > z) and
1 == gcd3(x, y, z) and
is_heronian(x, y, z)]
h.sort(key=lambda x: (hero(*x), sum(x), x[::-1]))
print(
'Primitive Heronian triangles with sides up to%i:'% MAXSIDE, len(h)
)
print('\nFirst ten when ordered by increasing area, then perimeter,',
'then maximum sides:')
print('\n'.join(' %14r perim:%3i area:%i'
% (sides, sum(sides), hero(*sides)) for sides in h[:10]))
print('\nAll with area 210 subject to the previous ordering:')
print('\n'.join(' %14r perim:%3i area:%i'
% (sides, sum(sides), hero(*sides)) for sides in h
if hero(*sides) == 210)) | 752Heronian triangles
| 3python
| t47fw |
require 'webrick'
server = WEBrick::HTTPServer.new(:Port => 8080)
server.mount_proc('/') {|request, response| response.body = }
trap() {server.shutdown}
server.start | 750Hello world/Web server
| 14ruby
| zgktw |
def horner(coeffs:List[Double], x:Double)=
coeffs.reverse.foldLeft(0.0){(a,c)=> a*x+c} | 740Horner's rule for polynomial evaluation
| 16scala
| duxng |
require 'date'
def easter_date(year)
a = year % 19
b, c = year.divmod(100)
d, e = b.divmod(4)
f = (b + 8) / 25
g = (b - f + 1) / 3
h = (19*a + b - d - g + 15) % 30
i, k = c.divmod(4)
l = (32 + 2*e + 2*i - h - k) % 7
m = (a + 11*h + 22*l) / 451
numerator = h + l - 7*m + 114
month = numerator / 31
day = (numerator % 31) + 1
Date.new(year, month, day)
end
OFFSETS = [
[:easter, 0],
[:ascension, 39],
[:pentecost, 49],
[:trinity, 56],
[:corpus, 60],
]
def emit_dates(year)
e = easter_date year
dates = OFFSETS.collect {|item, offset| (e + offset).strftime()}
puts % [year, dates.join(', ')]
end
puts + OFFSETS.collect{|item, offset| % item}.join(', ')
400.step(2100, 100).each {|year| emit_dates year}
puts
(2010 .. 2020).each {|year| emit_dates year} | 745Holidays related to Easter
| 14ruby
| bnckq |
func doSqnc(m:Int) {
var aList = [Int](count: m + 1, repeatedValue: 0)
var k1 = 2
var lg2 = 1
var amax:Double = 0
aList[0] = 1
aList[1] = 1
var v = aList[2]
for n in 2...m {
let add = aList[v] + aList[n - v]
aList[n] = add
v = aList[n]
if amax < Double(v) * 1.0 / Double(n) {
amax = Double(v) * 1.0 / Double(n)
}
if (k1 & n == 0) {
println("Maximum between 2^\(lg2) and 2^\(lg2 + 1) was \(amax)")
amax = 0
lg2++
}
k1 = n
}
}
doSqnc(1 << 20) | 743Hofstadter-Conway $10,000 sequence
| 17swift
| 5wzu8 |
fn main() {
eprintln!("Hello, {}!", "world");
} | 753Hello world/Standard error
| 15rust
| 8c207 |
Console.err.println("Goodbye, World!") | 753Hello world/Standard error
| 16scala
| nv5ic |
area <- function(a, b, c) {
s = (a + b + c) / 2
a2 = s*(s-a)*(s-b)*(s-c)
if (a2>0) sqrt(a2) else 0
}
is.heronian <- function(a, b, c) {
h = area(a, b, c)
h > 0 && 0==h%%1
}
gcd <- function(x,y) {
r <- x%%y;
ifelse(r, gcd(y, r), y)
}
gcd3 <- function(x, y, z) {
gcd(gcd(x, y), z)
}
maxside = 200
r <- NULL
for(c in 1:maxside){
for(b in 1:c){
for(a in 1:b){
if(1==gcd3(a, b, c) && is.heronian(a, b, c)) {
r <- rbind(r,c(a=a, b=b, c=c, perimeter=a+b+c, area=area(a,b,c)))
}
}
}
}
cat("There are ",nrow(r)," Heronian triangles up to a maximal side length of ",maxside,".\n", sep="")
cat("Showing the first ten ordered first by perimeter, then by area:\n")
print(head(r[order(x=r[,"perimeter"],y=r[,"area"]),],n=10)) | 752Heronian triangles
| 13r
| i25o5 |
use std::net::{Shutdown, TcpListener};
use std::thread;
use std::io::Write;
const RESPONSE: &'static [u8] = b"HTTP/1.1 200 OK\r
Content-Type: text/html; charset=UTF-8\r\n\r
<!DOCTYPE html><html><head><title>Bye-bye baby bye-bye</title>
<style>body { background-color: #111 }
h1 { font-size:4cm; text-align: center; color: black;
text-shadow: 0 0 2mm red}</style></head>
<body><h1>Goodbye, world!</h1></body></html>\r";
fn main() {
let listener = TcpListener::bind("127.0.0.1:8080").unwrap();
for stream in listener.incoming() {
thread::spawn(move || {
let mut stream = stream.unwrap();
match stream.write(RESPONSE) {
Ok(_) => println!("Response sent!"),
Err(e) => println!("Failed sending response: {}!", e),
}
stream.shutdown(Shutdown::Write).unwrap();
});
}
} | 750Hello world/Web server
| 15rust
| 3rbz8 |
use std::ops::Add;
use chrono::{prelude::*, Duration};
#[allow(clippy::cast_possible_truncation)]
#[allow(clippy::cast_sign_loss)]
#[allow(clippy::cast_possible_wrap)]
fn get_easter_day(year: u32) -> chrono::NaiveDate {
let k = (f64::from(year) / 100.).floor();
let d = (19 * (year% 19)
+ ((15 - ((13. + 8. * k) / 25.).floor() as u32 + k as u32 - (k / 4.).floor() as u32)% 30))
% 30;
let e =
(2 * (year% 4) + 4 * (year% 7) + 6 * d + ((4 + k as u32 - (k / 4.).floor() as u32)% 7))
% 7;
let (month, day) = match d {
29 if e == 6 => (4, 19),
28 if e == 6 => (4, 18),
_ if d + e < 10 => (3, 22 + d + e),
_ => (4, d + e - 9),
};
NaiveDate::from_ymd(year as i32, month, day)
}
fn main() {
let holidays = vec![
("Easter", Duration::days(0)),
("Ascension", Duration::days(39)),
("Pentecost", Duration::days(49)),
("Trinity", Duration::days(56)),
("Corpus Christi", Duration::days(60)),
];
for year in (400..=2100).step_by(100).chain(2010..=2020) {
print!("{}: ", year);
for (name, offset) in &holidays {
print!(
"{}: {}, ",
name,
get_easter_day(year).add(*offset).format("%a%d%h")
);
}
println!();
}
} | 745Holidays related to Easter
| 15rust
| pdlbu |
import java.io.PrintWriter
import java.net.ServerSocket
object HelloWorld extends App {
val text =
<HTML>
<HEAD>
<TITLE>Hello world </TITLE>
</HEAD>
<BODY LANG="en-US" BGCOLOR="#e6e6ff" DIR="LTR">
<P ALIGN="CENTER"> <FONT FACE="Arial, sans-serif" SIZE="6">Goodbye, World!</FONT> </P>
</BODY>
</HTML>
val port = 8080
val listener = new ServerSocket(port)
printf("Listening at port%1$d", port)
while (true) {
val sock = listener.accept()
new PrintWriter(sock.getOutputStream(), true).println(text)
sock.close()
}
} | 750Hello world/Web server
| 16scala
| mhayc |
import java.util._
import scala.swing._
def easter(year: Int) = { | 745Holidays related to Easter
| 16scala
| ezuab |
func horner(coefs: [Double], x: Double) -> Double {
return reduce(lazy(coefs).reverse(), 0) { $0 * x + $1 }
}
println(horner([-19, 7, -4, 6], 3)) | 740Horner's rule for polynomial evaluation
| 17swift
| 09ps6 |
import Foundation
let out = NSOutputStream(toFileAtPath: "/dev/stderr", append: true)
let err = "Goodbye, World!".dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false)
out?.open()
let success = out?.write(UnsafePointer<UInt8>(err!.bytes), maxLength: err!.length)
out?.close()
if let bytes = success {
println("\nWrote \(bytes) bytes")
} | 753Hello world/Standard error
| 17swift
| smcqt |
my @Q = (0,1,1);
push @Q, $Q[-$Q[-1]] + $Q[-$Q[-2]] for 1..100_000;
say "First 10 terms: [@Q[1..10]]";
say "Term 1000: $Q[1000]";
say "Terms less than preceding in first 100k: ",scalar(grep { $Q[$_] < $Q[$_-1] } 2..100000); | 749Hofstadter Q sequence
| 2perl
| ki3hc |
class Triangle
def self.valid?(a,b,c)
short, middle, long = [a, b, c].sort
short + middle > long
end
attr_reader :sides, :perimeter, :area
def initialize(a,b,c)
@sides = [a, b, c].sort
@perimeter = a + b + c
s = @perimeter / 2.0
@area = Math.sqrt(s * (s - a) * (s - b) * (s - c))
end
def heronian?
area == area.to_i
end
def <=>(other)
[area, perimeter, sides] <=> [other.area, other.perimeter, other.sides]
end
def to_s
% [sides.join('x'), perimeter, area]
end
end
max, area = 200, 210
prim_triangles = []
1.upto(max) do |a|
a.upto(max) do |b|
b.upto(max) do |c|
next if a.gcd(b).gcd(c) > 1
prim_triangles << Triangle.new(a, b, c) if Triangle.valid?(a, b, c)
end
end
end
sorted = prim_triangles.select(&:heronian?).sort
puts
puts
puts sorted.first(10).map(&:to_s)
puts
sorted.each{|tr| puts tr if tr.area == area} | 752Heronian triangles
| 14ruby
| 3rhz7 |
use num_integer::Integer;
use std::{f64, usize};
const MAXSIZE: usize = 200;
#[derive(Debug)]
struct HerionanTriangle {
a: usize,
b: usize,
c: usize,
area: usize,
perimeter: usize,
}
fn get_area(a: &usize, b: &usize, c: &usize) -> f64 {
let s = (a + b + c) as f64 / 2.;
(s * (s - *a as f64) * (s - *b as f64) * (s - *c as f64)).sqrt()
}
fn is_heronian(a: &usize, b: &usize, c: &usize) -> bool {
let area = get_area(a, b, c); | 752Heronian triangles
| 15rust
| 67k3l |
use strict; use warnings;
require 5.014;
use HTTP::Tiny;
print( HTTP::Tiny->new()->get( 'http://rosettacode.org')->{content} ); | 741HTTP
| 2perl
| t4qfg |
object Heron extends scala.collection.mutable.MutableList[Seq[Int]] with App {
private final val n = 200
for (c <- 1 to n; b <- 1 to c; a <- 1 to b if gcd(gcd(a, b), c) == 1) {
val p = a + b + c
val s = p / 2D
val area = Math.sqrt(s * (s - a) * (s - b) * (s - c))
if (isHeron(area))
appendElem(Seq(a, b, c, p, area.toInt))
}
print(s"Number of primitive Heronian triangles with sides up to $n: " + length)
private final val list = sortBy(i => (i(4), i(3)))
print("\n\nFirst ten when ordered by increasing area, then perimeter:" + header)
list slice (0, 10) map format foreach print
print("\n\nArea = 210" + header)
list filter { _(4) == 210 } map format foreach print
private def gcd(a: Int, b: Int) = {
var leftover = 1
var (dividend, divisor) = if (a > b) (a, b) else (b, a)
while (leftover != 0) {
leftover = dividend % divisor
if (leftover > 0) {
dividend = divisor
divisor = leftover
}
}
divisor
}
private def isHeron(h: Double) = h % 1 == 0 && h > 0
private final val header = "\nSides Perimeter Area"
private def format: Seq[Int] => String = "\n%3d x%3d x%3d%5d%10d".format
} | 752Heronian triangles
| 16scala
| 9k1m5 |
readfile(); | 741HTTP
| 12php
| kivhv |
def q(n):
if n < 1 or type(n) != int: raise ValueError()
try:
return q.seq[n]
except IndexError:
ans = q(n - q(n - 1)) + q(n - q(n - 2))
q.seq.append(ans)
return ans
q.seq = [None, 1, 1]
if __name__ == '__main__':
first10 = [q(i) for i in range(1,11)]
assert first10 == [1, 1, 2, 3, 3, 4, 5, 5, 6, 6],
print(, ', '.join(str(i) for i in first10))
assert q(1000) == 502,
print(, q(1000)) | 749Hofstadter Q sequence
| 3python
| bn6kr |
import Foundation
typealias PrimitiveHeronianTriangle = (s1:Int, s2:Int, s3:Int, p:Int, a:Int)
func heronianArea(side1 s1:Int, side2 s2:Int, side3 s3:Int) -> Int? {
let d1 = Double(s1)
let d2 = Double(s2)
let d3 = Double(s3)
let s = (d1 + d2 + d3) / 2.0
let a = sqrt(s * (s - d1) * (s - d2) * (s - d3))
if a% 1!= 0 || a <= 0 {
return nil
} else {
return Int(a)
}
}
func gcd(a:Int, b:Int) -> Int {
if b!= 0 {
return gcd(b, a% b)
} else {
return abs(a)
}
}
var triangles = [PrimitiveHeronianTriangle]()
for s1 in 1...200 {
for s2 in 1...s1 {
for s3 in 1...s2 {
if gcd(s1, gcd(s2, s3)) == 1, let a = heronianArea(side1: s1, side2: s2, side3: s3) {
triangles.append((s3, s2, s1, s1 + s2 + s3, a))
}
}
}
}
sort(&triangles) {t1, t2 in
if t1.a < t2.a || t1.a == t2.a && t1.p < t2.p {
return true
} else {
return false
}
}
println("Number of primitive Heronian triangles with sides up to 200: \(triangles.count)\n")
println("First ten sorted by area, then perimeter, then maximum side:\n")
println("Sides\t\t\tPerimeter\tArea")
for t in triangles[0...9] {
println("\(t.s1)\t\(t.s2)\t\(t.s3)\t\t\(t.p)\t\t\(t.a)")
} | 752Heronian triangles
| 17swift
| zgjtu |
cache <- vector("integer", 0)
cache[1] <- 1
cache[2] <- 1
Q <- function(n) {
if (is.na(cache[n])) {
value <- Q(n-Q(n-1)) + Q(n-Q(n-2))
cache[n] <<- value
}
cache[n]
}
for (i in 1:1e5) {
Q(i)
}
for (i in 1:10) {
cat(Q(i)," ",sep = "")
}
cat("\n")
cat(Q(1000),"\n")
count <- 0
for (i in 2:1e5) {
if (Q(i) < Q(i-1)) count <- count + 1
}
cat(count,"terms is less than its preceding term\n") | 749Hofstadter Q sequence
| 13r
| 70fry |
import urllib.request
print(urllib.request.urlopen().read()) | 741HTTP
| 3python
| zgstt |
library(RCurl)
webpage <- getURL("http://rosettacode.org")
webpage <- getURL("http://www.rosettacode.org", .opts=list(followlocation=TRUE))
webpage <- getURL("http://rosettacode.org",
.opts=list(proxy="123.123.123.123", proxyusername="domain\\username", proxypassword="mypassword", proxyport=8080)) | 741HTTP
| 13r
| nvei2 |
@cache = []
def Q(n)
if @cache[n].nil?
case n
when 1, 2 then @cache[n] = 1
else @cache[n] = Q(n - Q(n-1)) + Q(n - Q(n-2))
end
end
@cache[n]
end
puts
puts
prev = Q(1)
count = 0
2.upto(100_000) do |n|
q = Q(n)
count += 1 if q < prev
prev = q
end
puts | 749Hofstadter Q sequence
| 14ruby
| 1fmpw |
fn hofq(q: &mut Vec<u32>, x: u32) -> u32 {
let cur_len=q.len()-1;
let i=x as usize;
if i>cur_len { | 749Hofstadter Q sequence
| 15rust
| at914 |
object HofstadterQseq extends App {
val Q: Int => Int = n => {
if (n <= 2) 1
else Q(n-Q(n-1))+Q(n-Q(n-2))
}
(1 to 10).map(i=>(i,Q(i))).foreach(t=>println("Q("+t._1+") = "+t._2))
println("Q("+1000+") = "+Q(1000))
} | 749Hofstadter Q sequence
| 16scala
| x62wg |
require 'open-uri'
print open() {|f| f.read} | 741HTTP
| 14ruby
| 6783t |
let n = 100000
var q = Array(repeating: 0, count: n)
q[0] = 1
q[1] = 1
for i in 2..<n {
q[i] = q[i - q[i - 1]] + q[i - q[i - 2]]
}
print("First 10 elements of the sequence: \(q[0..<10])")
print("1000th element of the sequence: \(q[999])")
var count = 0
for i in 1..<n {
if q[i] < q[i - 1] {
count += 1
}
}
print("Number of times a member of the sequence is less than the preceding term for terms up to and including the 100,000th term: \(count)") | 749Hofstadter Q sequence
| 17swift
| pdybl |
[dependencies]
hyper = "0.6" | 741HTTP
| 15rust
| yjo68 |
import scala.io.Source
object HttpTest extends App {
System.setProperty("http.agent", "*")
Source.fromURL("http: | 741HTTP
| 16scala
| cbd93 |
package main
import "fmt"
func func1(f func(string) string) string { return f("a string") }
func func2(s string) string { return "func2 called with " + s }
func main() { fmt.Println(func1(func2)) } | 754Higher-order functions
| 0go
| hoijq |
first = { func -> func() }
second = { println "second" }
first(second) | 754Higher-order functions
| 7groovy
| 4xq5f |
func1 f = f "a string"
func2 s = "func2 called with " ++ s
main = putStrLn $ func1 func2 | 754Higher-order functions
| 8haskell
| i2vor |
import Foundation
let request = NSURLRequest(URL: NSURL(string: "http: | 741HTTP
| 17swift
| 3r0z2 |
echo "Hello world!" | 755Hello world/Text
| 4bash
| cbb96 |
public class NewClass {
public NewClass() {
first(new AnEventOrCallback() {
public void call() {
second();
}
});
}
public void first(AnEventOrCallback obj) {
obj.call();
}
public void second() {
System.out.println("Second");
}
public static void main(String[] args) {
new NewClass();
}
}
interface AnEventOrCallback {
public void call();
} | 754Higher-order functions
| 9java
| x6ywy |
function first (func) {
return func();
}
function second () {
return "second";
}
var result = first(second);
result = first(function () { return "third"; }); | 754Higher-order functions
| 10javascript
| ol286 |
fun main(args: Array<String>) {
val list = listOf(1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0, 10.0)
val a = list.map({ x -> x + 2 }).average()
val h = list.map({ x -> x * x }).average()
val g = list.map({ x -> x * x * x }).average()
println("A =%f G =%f H =%f".format(a, g, h))
} | 754Higher-order functions
| 11kotlin
| pdfb6 |
a = function() return 1 end
b = function(r) print( r() ) end
b(a) | 754Higher-order functions
| 1lua
| 1ftpo |
int main(void)
{
printf();
return EXIT_SUCCESS;
} | 755Hello world/Text
| 5c
| 211lo |
sub another {
my $func = shift;
my $val = shift;
return $func->($val);
};
sub reverser {
return scalar reverse shift;
};
print another \&reverser, 'data';
print another sub {return scalar reverse shift}, 'data';
my %dispatch = (
square => sub {return shift() ** 2},
cube => sub {return shift() ** 3},
rev => \&reverser,
);
print another $dispatch{$_}, 123 for qw(square cube rev); | 754Higher-order functions
| 2perl
| yjh6u |
function first($func) {
return $func();
}
function second() {
return 'second';
}
$result = first('second'); | 754Higher-order functions
| 12php
| atz12 |
(println "Hello world!") | 755Hello world/Text
| 6clojure
| gqq4f |
def first(function):
return function()
def second():
return
result = first(second) | 754Higher-order functions
| 3python
| mhkyh |
int main()
{
FILE *lp;
lp = fopen(,);
fprintf(lp,);
fclose(lp);
return 0;
} | 756Hello world/Line printer
| 5c
| pdnby |
f <- function(f0) f0(pi)
tf <- function(x) x^pi
print(f(sin))
print(f(cos))
print(f(tf)) | 754Higher-order functions
| 13r
| zgrth |
(ns rosetta-code.line-printer
(:import java.io.FileWriter))
(defn -main [& args]
(with-open [wr (new FileWriter "/dev/lp0")]
(.write wr "Hello, World!"))) | 756Hello world/Line printer
| 6clojure
| x63wk |
succ = proc{|x| x+1}
def to2(&f)
f[2]
end
to2(&succ)
to2{|x| x+1} | 754Higher-order functions
| 14ruby
| cbp9k |
package main
import (
"fmt"
"os"
)
func main() {
lp0, err := os.Create("/dev/lp0")
if err != nil {
panic(err)
}
defer lp0.Close()
fmt.Fprintln(lp0, "Hello World!")
} | 756Hello world/Line printer
| 0go
| 67r3p |
new File('/dev/lp0').write('Hello World!\n') | 756Hello world/Line printer
| 7groovy
| duvn3 |
fn execute_with_10<F: Fn(u64) -> u64> (f: F) -> u64 {
f(10)
}
fn square(n: u64) -> u64 {
n*n
}
fn main() {
println!("{}", execute_with_10(|n| n*n )); | 754Higher-order functions
| 15rust
| lp1cc |
def functionWithAFunctionArgument(x : int, y : int, f : (int, int) => int) = f(x,y) | 754Higher-order functions
| 16scala
| uewv8 |
import System.Process (ProcessHandle, runCommand)
main :: IO ProcessHandle
main = runCommand "echo \"Hello World!\" | lpr" | 756Hello world/Line printer
| 8haskell
| j807g |
import java.io.FileWriter;
import java.io.IOException;
public class LinePrinter {
public static void main(String[] args) {
try {
FileWriter lp0 = new FileWriter("/dev/lp0");
lp0.write("Hello World!");
lp0.close();
} catch (IOException ioe) {
ioe.printStackTrace();
}
}
} | 756Hello world/Line printer
| 9java
| ueavv |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.