code
stringlengths 1
46.1k
⌀ | label
class label 1.18k
classes | domain_label
class label 21
classes | index
stringlengths 4
5
|
---|---|---|---|
package main
import (
"fmt"
)
func main() {
a := []int{0, 1, 1} | 743Hofstadter-Conway $10,000 sequence
| 0go
| ez4a6 |
(binding [*out* *err*]
(println "Goodbye, world!")) | 753Hello world/Standard error
| 6clojure
| qy9xt |
null | 746Hickerson series of almost integers
| 11kotlin
| nvkij |
import 'dart:io';
main() async {
var server = await HttpServer.bind('127.0.0.1', 8080);
await for (HttpRequest request in server) {
request.response
..write('Hello, world')
..close();
}
} | 750Hello world/Web server
| 18dart
| ez9an |
function horner(coeffs, x) {
return coeffs.reduceRight( function(acc, coeff) { return(acc * x + coeff) }, 0);
}
console.log(horner([-19,7,-4,6],3)); | 740Horner's rule for polynomial evaluation
| 10javascript
| hovjh |
const hilbert = (width, spacing, points) => (x, y, lg, i1, i2, f) => {
if (lg === 1) {
const px = (width - x) * spacing;
const py = (width - y) * spacing;
points.push(px, py);
return;
}
lg >>= 1;
f(x + i1 * lg, y + i1 * lg, lg, i1, 1 - i2, f);
f(x + i2 * lg, y + (1 - i2) * lg, lg, i1, i2, f);
f(x + (1 - i1) * lg, y + (1 - i1) * lg, lg, i1, i2, f);
f(x + (1 - i2) * lg, y + i2 * lg, lg, 1 - i1, i2, f);
return points;
};
const drawHilbert = order => {
if (!order || order < 1) {
throw 'You need to give a valid positive integer';
} else {
order = Math.floor(order);
} | 748Hilbert curve
| 10javascript
| nvjiy |
(struct Hex (x y letter clicked?)
(define hexes
(let* ([A (char->integer
[letters (take (shuffle (map (compose string integer->char)
(range A (+ A 26))))
20)])
(for*/list ([row 4] [column 5])
(Hex (* 3/2 column) (* 2 (+ row (if (odd? column) 1/2 0)))
(list-ref letters (+ (* 5 row) column))
false))))
(require 2htdp/image)
(define (blank width height) (rectangle width height 'outline (color 0 0 0 0)))
(define (hexagon mode color) (regular-polygon 1 6 mode color))
(define aspect-ratio (sin (/ pi 3)))
(define (board _)
(scale 100
(for/fold ([the-board (blank 8 (* aspect-ratio 9))])
([hex hexes])
(define-values (letter-color hex-color)
(if (Hex-clicked? hex) (values 'black 'purple) (values 'red 'yellow)))
(underlay/align/offset
'left 'top the-board
(Hex-x hex) (* aspect-ratio (Hex-y hex))
(overlay (scale 1/10 (text (Hex-letter hex) 10 letter-color))
(hexagon 'outline 'black)
(hexagon 'solid hex-color))))))
(define (hex-at x y)
(argmin ( (hex) (+ (sqr (- x (* 100 (add1 (Hex-x hex)))))
(sqr (- y (* aspect-ratio 100 (add1 (Hex-y hex)))))))
hexes))
(define letters-chosen '())
(define (choose hex)
(set-Hex-clicked?! hex true)
(define letter (Hex-letter hex))
(when (not (member letter letters-chosen))
(set! letters-chosen (list* (Hex-letter hex) letters-chosen))))
(require 2htdp/universe)
(void (big-bang
(void)
[to-draw board]
[stop-when ( (_) (andmap Hex-clicked? hexes)) board]
[on-key ( (_ k)
(define hex (findf ( (hex) (key=? k (string-downcase (Hex-letter hex))))
hexes))
(when hex (choose hex)))]
[on-mouse ( (_ x y event-type)
(when (equal? event-type)
(choose (hex-at x y))))]))
(displayln )
(for-each display (add-between (reverse letters-chosen) )) | 742Honeycombs
| 3python
| rsmgq |
package main
import (
"fmt"
"time"
)
type holiday struct {
time.Time
}
func easter(y int) holiday {
c := y / 100
n := mod(y, 19)
i := mod(c-c/4-(c-(c-17)/25)/3+19*n+15, 30)
i -= (i / 28) * (1 - (i/28)*(29/(i+1))*((21-n)/11))
l := i - mod(y+y/4+i+2-c+c/4, 7)
m := 3 + (l+40)/44
d := l + 28 - 31*(m/4)
return holiday{time.Date(y, time.Month(m), d, 0, 0, 0, 0, time.UTC)}
}
func mod(a, n int) int {
r := a % n
if r < 0 {
return r + n
}
return r
}
func (h holiday) addDays(d int) holiday {
return holiday{h.Add(time.Duration(d) * 24 * time.Hour)}
}
type easterRelated struct {
easter, ascension, pentecost, trinity, corpusChristi holiday
}
func newEasterRelated(y int) (er easterRelated) {
er.easter = easter(y)
er.ascension = er.easter.addDays(39)
er.pentecost = er.ascension.addDays(10)
er.trinity = er.pentecost.addDays(7)
er.corpusChristi = er.trinity.addDays(4)
return
}
func (er easterRelated) print() {
const wdmdm = ": Mon _2 Jan"
fmt.Printf("%4d%s,%s,%s,%s,%s\n",
er.easter.Year(),
er.easter.Format("Easter"+wdmdm),
er.ascension.Format("Ascension"+wdmdm),
er.pentecost.Format("Pentecost"+wdmdm),
er.trinity.Format("Trinity"+wdmdm),
er.corpusChristi.Format("Corpus"+wdmdm))
}
func main() {
fmt.Println("Christian holidays, related to Easter, " +
"for each centennial from 400 to 2100 CE:")
for y := 400; y <= 2100; y += 100 {
newEasterRelated(y).print()
}
fmt.Println("\nChristian holidays, related to Easter, " +
"for years from 2010 to 2020 CE:")
for y := 2010; y <= 2020; y++ {
newEasterRelated(y).print()
}
} | 745Holidays related to Easter
| 0go
| olh8q |
print(ProcessInfo.processInfo.hostName) | 737Hostname
| 17swift
| rsvgg |
import Data.List
import Data.Ord
import Data.Array
import Text.Printf
hc :: Int -> Array Int Int
hc n = arr
where arr = listArray (1, n) $ 1: 1: map (f (arr!)) [3 .. n]
f a i = a (a $ i - 1) + a (i - a (i - 1))
printMaxima :: (Int, (Int, Double)) -> IO ()
printMaxima (n, (pos, m)) =
printf "Max between 2^%-2d and 2^%-2d is%1.5f at n =%6d\n"
n (n + 1) m pos
main = do
mapM_ printMaxima maxima
printf "Mallows's number is%d\n" mallows
where
hca = hc $ 2^20
hc' n = fromIntegral (hca!n) / fromIntegral n
maxima = zip [0..] $ map max powers
max seq = maximumBy (comparing snd) $ zip seq (map hc' seq)
powers = map (\n -> [2^n .. 2^(n + 1) - 1]) [0 .. 19]
mallows = last.takeWhile ((< 0.55) . hc') $ [2^20, 2^20 - 1 .. 1] | 743Hofstadter-Conway $10,000 sequence
| 8haskell
| 3rqzj |
package History;
sub TIESCALAR {
my $cls = shift;
my $cur_val = shift;
return bless [];
}
sub FETCH {
return shift->[-1]
}
sub STORE {
my ($var, $val) = @_;
push @$var, $val;
return $val;
}
sub get(\$) { @{tied ${+shift}} }
sub on(\$) { tie ${+shift}, __PACKAGE__ }
sub off(\$) { untie ${+shift} }
sub undo(\$) { pop @{tied ${+shift}} }
package main;
my $x = 0;
History::on($x);
for ("a" .. "d") { $x = $_ }
print "History: @{[History::get($x)]}\n";
for (1 .. 3) {
print "undo $_, ";
History::undo($x);
print "current value: $x\n";
}
History::off($x);
print "\$x is: $x\n"; | 744History variables
| 2perl
| 21nlf |
import java.util.*;
class Hofstadter
{
private static List<Integer> getSequence(int rlistSize, int slistSize)
{
List<Integer> rlist = new ArrayList<Integer>();
List<Integer> slist = new ArrayList<Integer>();
Collections.addAll(rlist, 1, 3, 7);
Collections.addAll(slist, 2, 4, 5, 6);
List<Integer> list = (rlistSize > 0) ? rlist : slist;
int targetSize = (rlistSize > 0) ? rlistSize : slistSize;
while (list.size() > targetSize)
list.remove(list.size() - 1);
while (list.size() < targetSize)
{
int lastIndex = rlist.size() - 1;
int lastr = rlist.get(lastIndex).intValue();
int r = lastr + slist.get(lastIndex).intValue();
rlist.add(Integer.valueOf(r));
for (int s = lastr + 1; (s < r) && (list.size() < targetSize); s++)
slist.add(Integer.valueOf(s));
}
return list;
}
public static int ffr(int n)
{ return getSequence(n, 0).get(n - 1).intValue(); }
public static int ffs(int n)
{ return getSequence(0, n).get(n - 1).intValue(); }
public static void main(String[] args)
{
System.out.print("R():");
for (int n = 1; n <= 10; n++)
System.out.print(" " + ffr(n));
System.out.println();
Set<Integer> first40R = new HashSet<Integer>();
for (int n = 1; n <= 40; n++)
first40R.add(Integer.valueOf(ffr(n)));
Set<Integer> first960S = new HashSet<Integer>();
for (int n = 1; n <= 960; n++)
first960S.add(Integer.valueOf(ffs(n)));
for (int i = 1; i <= 1000; i++)
{
Integer n = Integer.valueOf(i);
if (first40R.contains(n) == first960S.contains(n))
System.out.println("Integer " + i + " either in both or neither set");
}
System.out.println("Done");
}
} | 747Hofstadter Figure-Figure sequences
| 9java
| j837c |
null | 740Horner's rule for polynomial evaluation
| 11kotlin
| lptcp |
Shoes.app(title: , height: 700, width: 700) do
C = Math::cos(Math::PI/3)
S = Math::sin(Math::PI/3)
Radius = 60.0
letters = [
%w[L A R N D 1 2],
%w[G U I Y T 3 4],
%w[P C F E B 5 6],
%w[V S O M K 7 8],
%w[Q X J Z H 9 0],
]
def highlight(hexagon)
hexagon.style(fill: magenta)
end
def unhighlight(hexagon)
hexagon.style(fill: yellow)
end
def choose(hexagon)
hexagon.choose
highlight hexagon
chosen = @hexagons.find_all {|h| h.chosen?}.map {|h| h.letter}
if chosen.size == @hexagons.size
@chosen.text = 'Every hexagon has been chosen.'
else
@chosen.text = +
end
end
width = 20 + (Radius*(7*letters[0].size - 3)/4.0).ceil
height = 60 + (Radius*(1 + 2*S*letters.size)).ceil
@hexagons = []
letter_to_hex = {}
stack(height: height, width: width) do
@chosen = para()
letters.each_index do |row|
letters[0].each_index do |column|
x = 60 + column * Radius * 0.75 + (1-S) * Radius
y = 80 + row * S * Radius + (column.odd?? S * Radius * 0.5: 0)
h = shape(x-Radius, y-S*Radius) do
strokewidth 3
move_to(x-C*Radius, y-S*Radius)
line_to(x+C*Radius, y-S*Radius)
line_to(x+Radius, y)
line_to(x+C*Radius, y+S*Radius)
line_to(x-C*Radius, y+S*Radius)
line_to(x-Radius, y)
line_to(x-C*Radius, y-S*Radius)
end
class << h
attr_accessor:x,:y,:state,:letter
def chosen?
not @state.nil?
end
def choose
@state =:chosen
end
def contains?(px, py)
if @x-Radius < px and px <= @x-C*Radius
ratio = (px - @x + Radius)/(Radius*(1-C))
@y - ratio*S*Radius < py and py <= @y + ratio*S*Radius
elsif @x-C*Radius < px and px <= @x+C*Radius
@y - S*Radius < py and py < @y + S*Radius
elsif @x+C*Radius < px and px <= @x+Radius
ratio = (@x + Radius - px)/(Radius*(1-C))
@y - ratio*S*Radius < py and py <= @y + ratio*S*Radius
else
false
end
end
def inspect
%q(<%s,,%s,%d@%d>) % [self.class, letter, chosen?, x, y]
end
end
h.x = x + x - Radius
h.y = y + y - S*Radius
h.letter = letters[row][column]
unhighlight h
@hexagons << h
letter_to_hex[h.letter.downcase] = h
letter_to_hex[h.letter.upcase] = h
para(h.letter).style(size:56, stroke:red) \
.move(h.x - C*Radius, h.y - S*Radius)
end
end
hex_over = nil
motion do |x, y|
hex = @hexagons.find {|h| h.contains?(x,y)}
unless hex.nil? or hex.chosen?
highlight hex
end
unless hex_over == hex or hex_over.nil? or hex_over.chosen?
unhighlight hex_over
end
hex_over = hex
end
click do |button, x, y|
info()
hexagon = @hexagons.find {|h| h.contains?(x,y)}
if hexagon
info()
choose hexagon
end
end
keypress do |key|
if key ==
exit
elsif key ==
info @hexagons.collect {|h| h.inspect}.join()
elsif letter_to_hex.has_key?(key)
info()
choose letter_to_hex[key]
end
end
end
end | 742Honeycombs
| 14ruby
| j8c7x |
use 5.10.0;
use strict;
sub walk {
my ($node, $code, $h, $rev_h) = @_;
my $c = $node->[0];
if (ref $c) { walk($c->[$_], $code.$_, $h, $rev_h) for 0,1 }
else { $h->{$c} = $code; $rev_h->{$code} = $c }
$h, $rev_h
}
sub mktree {
my (%freq, @nodes);
$freq{$_}++ for split '', shift;
@nodes = map([$_, $freq{$_}], keys %freq);
do {
@nodes = sort {$a->[1] <=> $b->[1]} @nodes;
my ($x, $y) = splice @nodes, 0, 2;
push @nodes, [[$x, $y], $x->[1] + $y->[1]]
} while (@nodes > 1);
walk($nodes[0], '', {}, {})
}
sub encode {
my ($str, $dict) = @_;
join '', map $dict->{$_}//die("bad char $_"), split '', $str
}
sub decode {
my ($str, $dict) = @_;
my ($seg, @out) = ("");
for (split '', $str) {
$seg .= $_;
my $x = $dict->{$seg} // next;
push @out, $x;
$seg = '';
}
die "bad code" if length($seg);
join '', @out
}
my $txt = 'this is an example for huffman encoding';
my ($h, $rev_h) = mktree($txt);
for (keys %$h) { print "'$_': $h->{$_}\n" }
my $enc = encode($txt, $h);
print "$enc\n";
print decode($enc, $rev_h), "\n"; | 736Huffman coding
| 2perl
| hogjl |
def identity(size)
Array.new(size){|i| Array.new(size){|j| i==j? 1: 0}}
end
[4,5,6].each do |size|
puts size, identity(size).map {|r| r.to_s},
end | 730Identity matrix
| 14ruby
| mklyj |
int Q(int n) => n>2? Q(n-Q(n-1))+Q(n-Q(n-2)): 1;
main() {
for(int i=1;i<=10;i++) {
print("Q($i)=${Q(i)}");
}
print("Q(1000)=${Q(1000)}");
} | 749Hofstadter Q sequence
| 18dart
| 21slp |
var m = ` leading spaces
and blank lines` | 751Here document
| 0go
| vaq2m |
println '''
Time's a strange fellow;
more he gives than takes
(and he takes all) nor any marvel finds
quite disappearance but some keener makes
losing, gaining
--love! if a world ends
''' | 751Here document
| 7groovy
| mh1y5 |
var R = [null, 1];
var S = [null, 2];
var extend_sequences = function (n) {
var current = Math.max(R[R.length-1],S[S.length-1]);
var i;
while (R.length <= n || S.length <= n) {
i = Math.min(R.length, S.length) - 1;
current += 1;
if (current === R[i] + S[i]) {
R.push(current);
} else {
S.push(current);
}
}
}
var ffr = function(n) {
extend_sequences(n);
return R[n];
};
var ffs = function(n) {
extend_sequences(n);
return S[n];
};
for (var i = 1; i <=10; i += 1) {
console.log('R('+ i +') = ' + ffr(i));
}
var int_array = [];
for (var i = 1; i <= 40; i += 1) {
int_array.push(ffr(i));
}
for (var i = 1; i <= 960; i += 1) {
int_array.push(ffs(i));
}
int_array.sort(function(a,b){return a-b;});
for (var i = 1; i <= 1000; i += 1) {
if (int_array[i-1] !== i) {
throw "Something's wrong!"
} else { console.log("1000 integer check ok."); }
} | 747Hofstadter Figure-Figure sequences
| 10javascript
| 1fcp7 |
null | 748Hilbert curve
| 11kotlin
| atc13 |
import java.awt.{BasicStroke, BorderLayout, Color, Dimension,
Font, FontMetrics, Graphics, Graphics2D, Point, Polygon, RenderingHints}
import java.awt.event.{KeyAdapter, KeyEvent, MouseAdapter, MouseEvent}
import javax.swing.{JFrame, JPanel}
import scala.math.{Pi, cos, sin}
object Honeycombs extends App {
private val (letters, x1, y1, x2, y2, h, w) = ("LRDGITPFBVOKANUYCESM", 150, 100, 225, 143, 87, 150)
private class HoneycombsPanel() extends JPanel {
private val comb: IndexedSeq[Hexagon] =
for {i <- 0 until 20
(x: Int, y: Int) =
if (i < 12) (x1 + (i % 3) * w, y1 + (i / 3) * h)
else (x2 + (i % 2) * w, y2 + ((i - 12) / 2) * h)
} yield Hexagon(x, y, w / 3, letters(i))
override def paintComponent(gg: Graphics): Unit = {
super.paintComponent(gg)
val g = gg.asInstanceOf[Graphics2D]
g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON)
g.setFont(new Font("SansSerif", Font.BOLD, 30))
g.setStroke(new BasicStroke(3))
comb.foreach(_.draw(g))
}
case class Hexagon(x: Int, y: Int, halfWidth: Int, letter: Char,
var hasBeenSelected: Boolean = false) extends Polygon {
private val (baseColor, selectedColor) = (Color.yellow, Color.magenta)
def setSelected(): Unit = hasBeenSelected = true
def draw(g: Graphics2D): Unit = {
val fm: FontMetrics = g.getFontMetrics
val (asc, dec) = (fm.getAscent, fm.getDescent)
def drawCenteredString(g: Graphics2D, s: String): Unit = {
val x: Int = bounds.x + (bounds.width - fm.stringWidth(s)) / 2
val y: Int = bounds.y + (asc + (bounds.height - (asc + dec)) / 2)
g.drawString(s, x, y)
}
g.setColor(if (hasBeenSelected) selectedColor else baseColor)
g.fillPolygon(this)
g.setColor(Color.black)
g.drawPolygon(this)
g.setColor(if (hasBeenSelected) Color.black else Color.red)
drawCenteredString(g, letter.toString)
}
for (i <- 0 until 6)
addPoint((x + halfWidth * cos(i * Pi / 3)).toInt, (y + halfWidth * sin(i * Pi / 3)).toInt)
getBounds
}
addKeyListener(new KeyAdapter() {
override def keyPressed(e: KeyEvent): Unit = {
val key = e.getKeyChar.toUpper
comb.find(_.letter == key).foreach(_.setSelected())
repaint()
}
})
addMouseListener(new MouseAdapter() {
override def mousePressed(e: MouseEvent): Unit = {
val mousePos: Point = e.getPoint
comb.find(h => h.contains(mousePos)).foreach(_.setSelected())
repaint()
}
})
setBackground(Color.white)
setPreferredSize(new Dimension(600, 500))
setFocusable(true)
requestFocus()
}
new JFrame("Honeycombs") {
add(new HoneycombsPanel(), BorderLayout.CENTER)
pack()
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE)
setLocationRelativeTo(null)
setResizable(false)
setVisible(true)
}
} | 742Honeycombs
| 16scala
| pdubj |
io.write("Enter latitude => ")
lat = tonumber(io.read())
io.write("Enter longitude => ")
lng = tonumber(io.read())
io.write("Enter legal meridian => ")
ref = tonumber(io.read())
print()
slat = math.sin(math.rad(lat))
print(string.format(" sine of latitude: %.3f", slat))
print(string.format(" diff longitude: %.3f", lng-ref))
print()
print("Hour, sun hour angle, dial hour line angle from 6am to 6pm")
for h = -6, 6 do
hra = 15 * h
hra = hra - (lng - ref)
hla = math.deg(math.atan(slat * math.tan(math.rad(hra))))
print(string.format("HR=%3d; HRA=%7.3f; HLA=%7.3f", h, hra, hla))
end | 739Horizontal sundial calculations
| 1lua
| 67i39 |
a = (print ; gets).to_i
b = (print ; gets).to_i
puts if a < b
puts if a > b
puts if a == b | 725Integer comparison
| 14ruby
| veh2n |
import 'dart:io';
void main() {
stderr.writeln('Goodbye, World!');
} | 753Hello world/Standard error
| 18dart
| 70or7 |
use strict;
use warnings;
use Math::BigFloat;
my $iln2 = 1 / Math::BigFloat->new(2)->blog;
my $h = $iln2 / 2;
for my $n ( 1 .. 17 ) {
$h *= $iln2;
$h *= $n;
my $s = $h->copy->bfround(-3)->bstr;
printf "h(%2d) =%22s is%s almost an integer.\n",
$n, $s, ($s =~ /\.[09]/ ? "" : " NOT");
} | 746Hickerson series of almost integers
| 2perl
| 703rh |
main :: IO ()
main = do
putStrLn "Hello\
\ World!\n"
putStrLn $ unwords ["This", "is", "an", "example", "text!\n"]
putStrLn $ unlines [
unwords ["This", "is", "the", "first" , "line."]
, unwords ["This", "is", "the", "second", "line."]
, unwords ["This", "is", "the", "third" , "line."]
] | 751Here document
| 8haskell
| ezmai |
function horners_rule( coeff, x )
local res = 0
for i = #coeff, 1, -1 do
res = res * x + coeff[i]
end
return res
end
x = 3
coefficients = { -19, 7, -4, 6 }
print( horners_rule( coefficients, x ) ) | 740Horner's rule for polynomial evaluation
| 1lua
| 21zl3 |
import java.text.DateFormatSymbols;
import java.util.*;
public class EasterRelatedHolidays {
final static Map<String, Integer> holidayOffsets;
static {
holidayOffsets = new LinkedHashMap<>();
holidayOffsets.put("Easter", 0);
holidayOffsets.put("Ascension", 39);
holidayOffsets.put("Pentecost", 10);
holidayOffsets.put("Trinity", 7);
holidayOffsets.put("Corpus", 4);
}
public static void main(String[] args) {
System.out.println("Christian holidays, related to Easter,"
+ " for each centennial from 400 to 2100 CE:");
for (int y = 400; y <= 2100; y += 100)
printEasterRelatedHolidays(y);
System.out.println("\nChristian holidays, related to Easter,"
+ " for years from 2010 to 2020 CE:");
for (int y = 2010; y < 2021; y++)
printEasterRelatedHolidays(y);
}
static void printEasterRelatedHolidays(int year) {
final int a = year % 19;
final int b = year / 100;
final int c = year % 100;
final int d = b / 4;
final int e = b % 4;
final int f = (b + 8) / 25;
final int g = (b - f + 1) / 3;
final int h = (19 * a + b - d - g + 15) % 30;
final int i = c / 4;
final int k = c % 4;
final int l = (32 + 2 * e + 2 * i - h - k) % 7;
final int m = (a + 11 * h + 22 * l) / 451;
final int n = h + l - 7 * m + 114;
final int month = n / 31 - 1;
final int day = (n % 31) + 1;
Calendar date = new GregorianCalendar(year, month, day);
String[] months = new DateFormatSymbols(Locale.US).getShortMonths();
System.out.printf("%4d ", year);
for (String hd : holidayOffsets.keySet()) {
date.add(Calendar.DATE, holidayOffsets.get(hd));
System.out.printf("%s:%2d%s ", hd,
date.get(Calendar.DAY_OF_MONTH),
months[date.get(Calendar.MONTH)]);
}
System.out.println();
}
} | 745Holidays related to Easter
| 9java
| 67x3z |
<?php
function encode($symb2freq) {
$heap = new SplPriorityQueue;
$heap->setExtractFlags(SplPriorityQueue::EXTR_BOTH);
foreach ($symb2freq as $sym => $wt)
$heap->insert(array($sym => ''), -$wt);
while ($heap->count() > 1) {
$lo = $heap->extract();
$hi = $heap->extract();
foreach ($lo['data'] as &$x)
$x = '0'.$x;
foreach ($hi['data'] as &$x)
$x = '1'.$x;
$heap->insert($lo['data'] + $hi['data'],
$lo['priority'] + $hi['priority']);
}
$result = $heap->extract();
return $result['data'];
}
$txt = 'this is an example for huffman encoding';
$symb2freq = array_count_values(str_split($txt));
$huff = encode($symb2freq);
echo ;
foreach ($huff as $sym => $code)
echo ;
?> | 736Huffman coding
| 12php
| zgnt1 |
extern crate num;
struct Matrix<T> {
data: Vec<T>,
size: usize,
}
impl<T> Matrix<T>
where
T: num::Num + Clone + Copy,
{
fn new(size: usize) -> Self {
Self {
data: vec![T::zero(); size * size],
size: size,
}
}
fn get(&mut self, x: usize, y: usize) -> T {
self.data[x + self.size * y]
}
fn identity(&mut self) {
for (i, item) in self.data.iter_mut().enumerate() {
*item = if i% (self.size + 1) == 0 {
T::one()
} else {
T::zero()
}
}
}
}
fn main() {
let size = std::env::args().nth(1).unwrap().parse().unwrap();
let mut matrix = Matrix::<i32>::new(size);
matrix.identity();
for y in 0..size {
for x in 0..size {
print!("{} ", matrix.get(x, y));
}
println!();
}
} | 730Identity matrix
| 15rust
| 9b2mm |
use std::io::{self, BufRead};
fn main() {
let mut reader = io::stdin();
let mut buffer = String::new();
let mut lines = reader.lock().lines().take(2);
let nums: Vec<i32>= lines.map(|string|
string.unwrap().trim().parse().unwrap()
).collect();
let a: i32 = nums[0];
let b: i32 = nums[1];
if a < b {
println!("{} is less than {}" , a , b)
} else if a == b {
println!("{} equals {}" , a , b)
} else if a > b {
println!("{} is greater than {}" , a , b)
};
} | 725Integer comparison
| 15rust
| uwkvj |
package main
import (
"io"
"log"
"net/http"
"os"
)
func main() {
r, err := http.Get("http: | 741HTTP
| 0go
| gqm4n |
null | 743Hofstadter-Conway $10,000 sequence
| 9java
| i2pos |
const myVar = 123;
const tempLit = `Here is some
multi-line string. And here is
the value of "myVar": ${myVar}
That's all.`;
console.log(tempLit) | 751Here document
| 10javascript
| aty10 |
null | 751Here document
| 11kotlin
| 4x857 |
import sys
HIST = {}
def trace(frame, event, arg):
for name,val in frame.f_locals.items():
if name not in HIST:
HIST[name] = []
else:
if HIST[name][-1] is val:
continue
HIST[name].append(val)
return trace
def undo(name):
HIST[name].pop(-1)
return HIST[name][-1]
def main():
a = 10
a = 20
for i in range(5):
c = i
print , c, ,
c = undo('c')
c = undo('c')
c = undo('c')
print c
print 'HIST:', HIST
sys.settrace(trace)
main() | 744History variables
| 3python
| vad29 |
fun ffr(n: Int) = get(n, 0)[n - 1]
fun ffs(n: Int) = get(0, n)[n - 1]
internal fun get(rSize: Int, sSize: Int): List<Int> {
val rlist = arrayListOf(1, 3, 7)
val slist = arrayListOf(2, 4, 5, 6)
val list = if (rSize > 0) rlist else slist
val targetSize = if (rSize > 0) rSize else sSize
while (list.size > targetSize)
list.removeAt(list.size - 1)
while (list.size < targetSize) {
val lastIndex = rlist.lastIndex
val lastr = rlist[lastIndex]
val r = lastr + slist[lastIndex]
rlist += r
var s = lastr + 1
while (s < r && list.size < targetSize)
slist += s++
}
return list
}
fun main(args: Array<String>) {
print("R():")
(1..10).forEach { print(" " + ffr(it)) }
println()
val first40R = (1..40).map { ffr(it) }
val first960S = (1..960).map { ffs(it) }
val indices = (1..1000).filter { it in first40R == it in first960S }
indices.forEach { println("Integer $it either in both or neither set") }
println("Done")
} | 747Hofstadter Figure-Figure sequences
| 11kotlin
| 5wnua |
null | 748Hilbert curve
| 1lua
| ezlac |
const = => {
let = ( % 19 * 19 + 15) % 30;
+= ( % 4 * 2 + % 7 * 4 + 6 * + 6) % 7;
if ( >= 1918) += ( / 100 | 0) - ( / 400 | 0) - 2;
return new Date(, 2, 22 + );
};
for (let = 400; <= 2100; += < 2000 ? 100 : >= 2020 ? 80 : < 2010 ? 10 : 1) {
const _ = ();
document.write(
+ ": " +
[ ["Easter", 1], ["Ascension", 40], ["Trinity (Pentecost)", 50], ["All Saints' Sunday", 57] ].map( => {
let = new Date(_);
.setDate(.getDate() + [1] - 1);
return [0] + ": " + new Intl.DateTimeFormat("ru", { month: "numeric", day: "numeric" }).format();
}).join("; ") + ".<br />"
);
} | 745Holidays related to Easter
| 10javascript
| lpocf |
def identityMatrix(n:Int)=Array.tabulate(n,n)((x,y) => if(x==y) 1 else 0)
def printMatrix[T](m:Array[Array[T]])=m map (_.mkString("[", ", ", "]")) mkString "\n"
printMatrix(identityMatrix(5)) | 730Identity matrix
| 16scala
| 2a5lb |
new URL("http: | 741HTTP
| 7groovy
| 21tlv |
var hofst_10k = function(n) {
var memo = [1, 1];
var a = function(n) {
var result = memo[n-1];
if (typeof result !== 'number') {
result = a(a(n-1))+a(n-a(n-1));
memo[n-1] = result;
}
return result;
}
return a;
}();
var maxima_between_twos = function(exp) {
var current_max = 0;
for(var i = Math.pow(2,exp)+1; i < Math.pow(2,exp+1); i += 1) {
current_max = Math.max(current_max, hofst_10k(i)/i);
}
return current_max;
}
for(var i = 1; i <= 20; i += 1) {
console.log("Maxima between 2^"+i+"-2^"+(i+1)+" is: "+maxima_between_twos(i)+"\n");
} | 743Hofstadter-Conway $10,000 sequence
| 10javascript
| zgxt2 |
print([[
This is a long paragraph of text
it is the simplest while using it
with lua, however it will have the
same line breaks and spacing as
you set in this block.
]])
print([=[by using equals signs, ]] may be embedded.]=])
local msg = [[this is a message that spans
multiple lines and will have the next lines
preserved as they were entered, so be careful
when using this]]
print(msg) | 751Here document
| 1lua
| gqo4j |
object IntCompare {
def main(args: Array[String]): Unit = {
val a=Console.readInt
val b=Console.readInt
if (a < b)
printf("%d is less than%d\n", a, b)
if (a == b)
printf("%d is equal to%d\n", a, b)
if (a > b)
printf("%d is greater than%d\n", a, b)
}
} | 725Integer comparison
| 16scala
| gs14i |
from decimal import Decimal
import math
def h(n):
'Simple, reduced precision calculation'
return math.factorial(n) / (2 * math.log(2) ** (n + 1))
def h2(n):
'Extended precision Hickerson function'
return Decimal(math.factorial(n)) / (2 * Decimal(2).ln() ** (n + 1))
for n in range(18):
x = h2(n)
norm = str(x.normalize())
almostinteger = (' Nearly integer'
if 'E' not in norm and ('.0' in norm or '.9' in norm)
else ' NOT nearly integer!')
print('n:%2i h:%s%s'% (n, norm, almostinteger)) | 746Hickerson series of almost integers
| 3python
| j867p |
package main
import (
"fmt"
"log"
"net/http"
)
func main() {
http.HandleFunc("/", func(w http.ResponseWriter, req *http.Request) {
fmt.Fprintln(w, "Goodbye, World!")
})
log.Fatal(http.ListenAndServe(":8080", nil))
} | 750Hello world/Web server
| 0go
| 5w8ul |
import Data.ByteString.Char8 ()
import Data.Conduit ( ($$), yield )
import Data.Conduit.Network ( ServerSettings(..), runTCPServer )
main :: IO ()
main = runTCPServer (ServerSettings 8080 "127.0.0.1") $ const (yield response $$)
where response = "HTTP/1.0 200 OK\nContent-Length: 16\n\nGoodbye, World!\n" | 750Hello world/Web server
| 8haskell
| x6lw4 |
foo_hist = []
trace_var(:$foo){|v| foo_hist.unshift(v)}
$foo =
$foo =
$foo =
p foo_hist | 744History variables
| 14ruby
| 5wtuj |
use SVG;
use List::Util qw(max min);
use constant pi => 2 * atan2(1, 0);
%rules = (
A => '-BF+AFA+FB-',
B => '+AF-BFB-FA+'
);
$hilbert = 'A';
$hilbert =~ s/([AB])/$rules{$1}/eg for 1..6;
($x, $y) = (0, 0);
$theta = pi/2;
$r = 5;
for (split //, $hilbert) {
if (/F/) {
push @X, sprintf "%.0f", $x;
push @Y, sprintf "%.0f", $y;
$x += $r * cos($theta);
$y += $r * sin($theta);
}
elsif (/\+/) { $theta += pi/2; }
elsif (/\-/) { $theta -= pi/2; }
}
$max = max(@X,@Y);
$xt = -min(@X)+10;
$yt = -min(@Y)+10;
$svg = SVG->new(width=>$max+20, height=>$max+20);
$points = $svg->get_path(x=>\@X, y=>\@Y, -type=>'polyline');
$svg->rect(width=>"100%", height=>"100%", style=>{'fill'=>'black'});
$svg->polyline(%$points, style=>{'stroke'=>'orange', 'stroke-width'=>1}, transform=>"translate($xt,$yt)");
open $fh, '>', 'hilbert_curve.svg';
print $fh $svg->xmlify(-namespace=>'svg');
close $fh; | 748Hilbert curve
| 2perl
| 9kxmn |
null | 745Holidays related to Easter
| 11kotlin
| dupnz |
import Network.Browser
import Network.HTTP
import Network.URI
main = do
rsp <- Network.Browser.browse $ do
setAllowRedirects True
setOutHandler $ const (return ())
request $ getRequest "http://www.rosettacode.org/"
putStrLn $ rspBody $ snd rsp | 741HTTP
| 8haskell
| smkqk |
null | 743Hofstadter-Conway $10,000 sequence
| 11kotlin
| qy7x1 |
#[derive(Clone, Debug)]
struct HVar<T> {
history: Vec<T>,
current: T,
}
impl<T> HVar<T> {
fn new(val: T) -> Self {
HVar {
history: Vec::new(),
current: val,
}
}
fn get(&self) -> &T {
&self.current
}
fn set(&mut self, val: T) {
self.history.push(std::mem::replace(&mut self.current, val));
}
fn history(&self) -> (&[T], &T) {
(&self.history, &self.current)
}
fn revert(&mut self) -> Option<T> {
self.history
.pop()
.map(|val| std::mem::replace(&mut self.current, val))
}
}
fn main() {
let mut var = HVar::new(0);
var.set(1);
var.set(2);
println!("{:?}", var.history());
println!("{:?}", var.revert());
println!("{:?}", var.revert());
println!("{:?}", var.revert());
println!("{:?}", var.get());
} | 744History variables
| 15rust
| 4xz5u |
class HVar[A](initialValue: A) extends Proxy {
override def self = !this
override def toString = "HVar(" + !this + ")"
def history = _history
private var _history = List(initialValue)
def unary_! = _history.head
def :=(newValue: A): Unit = {
_history = newValue :: _history
}
def modify(f: A => A): Unit = {
_history = f(!this) :: _history
}
def undo: A = {
val v = !this
_history = _history.tail
v
}
} | 744History variables
| 16scala
| 70yr9 |
use strict;
use warnings;
my @r = ( undef, 1 );
my @s = ( undef, 2 );
sub ffsr {
my $n = shift;
while( $
push @r, $s[$
push @s, grep { $s[-1]<$_ } $s[-1]+1..$r[-1]-1, $r[-1]+1;
}
return $n;
}
sub ffr { $r[ffsr shift] }
sub ffs { $s[ffsr shift] }
printf " i: R(i) S(i)\n";
printf "==============\n";
printf "%3d: %3d %3d\n", $_, ffr($_), ffs($_) for 1..10;
printf "\nR(40)=%3d S(960)=%3d R(41)=%3d\n", ffr(40), ffs(960), ffr(41);
my %seen;
$seen{ffr($_)}++ for 1 .. 40;
$seen{ffs($_)}++ for 1 .. 960;
if( 1000 == keys %seen and grep $seen{$_}, 1 .. 1000 ) {
print "All occured exactly once.\n";
} else {
my @missed = grep !$seen{$_}, 1 .. 1000;
my @dupped = sort { $a <=> $b} grep $seen{$_}>1, keys %seen;
print "These were missed: @missed\n";
print "These were duplicated: @dupped\n";
} | 747Hofstadter Figure-Figure sequences
| 2perl
| ol78x |
local Time = require("time")
function div (x, y) return math.floor(x / y) end
function easter (year)
local G = year % 19
local C = div(year, 100)
local H = (C - div(C, 4) - div((8 * C + 13), 25) + 19 * G + 15) % 30
local I = H - div(H, 28) * (1 - div(29, H + 1)) * (div(21 - G, 11))
local J = (year + div(year, 4) + I + 2 - C + div(C, 4)) % 7
local L = I - J
local month = 3 + div(L + 40, 44)
return month, L + 28 - 31 * div(month, 4)
end
function holidays (year)
local dates = {}
dates.easter = Time.date(year, easter(year))
dates.ascension = dates.easter + Time.days(39)
dates.pentecost = dates.easter + Time.days(49)
dates.trinity = dates.easter + Time.days(56)
dates.corpus = dates.easter + Time.days(60)
return dates
end
function puts (...)
for k, v in pairs{...} do io.write(tostring(v):sub(6, 10), "\t") end
end
function show (year, d)
io.write(year, "\t")
puts(d.easter, d.ascension, d.pentecost, d.trinity, d.corpus)
print()
end
print("Year\tEaster\tAscen.\tPent.\tTrinity\tCorpus")
for year = 1600, 2100, 100 do show(year, holidays(year)) end
for year = 2010, 2020 do show(year, holidays(year)) end | 745Holidays related to Easter
| 1lua
| f51dp |
local fmt, write=string.format,io.write
local hof=coroutine.wrap(function()
local yield=coroutine.yield
local a={1,1}
yield(a[1], 1)
yield(a[2], 2)
local n=a[#a]
repeat
n=a[n]+a[1+#a-n]
a[#a+1]=n
yield(n, #a)
until false
end)
local mallows, mdiv=0,0
for p=1,20 do
local max, div, num, last, fdiv=0,0,0,0,0
for i=2^(p-1),2^p-1 do
h,n=hof()
div=h/n
if div>max then
max=div
num=n
end
if div>0.55 then
last=n
fdiv=div
end
end
write(fmt("From 2^%-2d to 2^%-2d the max is%.4f the%6dth Hofstadter number.\n",
p-1, p, max, num))
if max>.55 and p>4 then
mallows, mdiv=last, fdiv
end
end
write("So Mallows number is ", mallows, " with ", fmt("%.4f",mdiv), ", yay, just wire me my $10000 now!\n") | 743Hofstadter-Conway $10,000 sequence
| 1lua
| smjq8 |
package main
func main() { println("Goodbye, World!") } | 753Hello world/Standard error
| 0go
| yjk64 |
require
LN2 = BigMath::log(2,16)
FACTORIALS = Hash.new{|h,k| h[k] = k * h[k-1]}
FACTORIALS[0] = 1
def hickerson(n)
FACTORIALS[n] / (2 * LN2 ** (n+1))
end
def nearly_int?(n)
int = n.round
n.between?(int - 0.1, int + 0.1)
end
1.upto(17) do |n|
h = hickerson(n)
str = nearly_int?(h)? :
puts % [n, h.to_s('F')[0,25], str]
end | 746Hickerson series of almost integers
| 14ruby
| kimhg |
import java.io.IOException;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
public class HelloWorld{
public static void main(String[] args) throws IOException{
ServerSocket listener = new ServerSocket(8080);
while(true){
Socket sock = listener.accept();
new PrintWriter(sock.getOutputStream(), true).
println("Goodbye, World!");
sock.close();
}
}
} | 750Hello world/Web server
| 9java
| bn3k3 |
var http = require('http');
http.createServer(function (req, res) {
res.writeHead(200, {'Content-Type': 'text/plain'});
res.end('Goodbye, World!\n');
}).listen(8080, '127.0.0.1'); | 750Hello world/Web server
| 10javascript
| w3ce2 |
$address = <<END;
1, High Street,
$town_name,
West Midlands.
WM4 5HD.
END | 751Here document
| 2perl
| i24o3 |
$address = <<<END
1, High Street,
$town_name,
West Midlands.
WM4 5HD.
END; | 751Here document
| 12php
| rsige |
System.err.println("Goodbye, World!") | 753Hello world/Standard error
| 7groovy
| f5gdn |
import System.IO
main = hPutStrLn stderr "Goodbye, World!" | 753Hello world/Standard error
| 8haskell
| honju |
use decimal::d128;
use factorial::Factorial;
fn hickerson(n: u64) -> d128 {
d128::from(n.factorial()) / (d128!(2) * (d128!(2).ln().pow(d128::from(n + 1))))
} | 746Hickerson series of almost integers
| 15rust
| bn9kx |
import scala.annotation.tailrec
object Hickerson extends App {
def almostInteger(n: Int): Boolean = {
def ln2 = BigDecimal("0.69314718055994530941723212145818")
def div: BigDecimal = ln2.pow(n + 1) * 2
def factorial(num: Int): Long = {
@tailrec
def accumulated(acc: Long, n: Long): Long =
if (n <= 0) acc else accumulated(acc * n, n - 1)
accumulated(1, num)
}
((BigDecimal(factorial(n)) / div * 10).toBigInt() % 10).toString.matches("0|9")
}
val aa = (1 to 17).map(n => n -> almostInteger(n))
println(s"Function h(n) gives a almost integer with a n of ${aa.filter(_._2).map(_._1).mkString(", ")}.")
println(s"While h(n) gives NOT an almost integer with a n of ${aa.filter(!_._2).map(_._1).mkString(", ")}.")
} | 746Hickerson series of almost integers
| 16scala
| at21n |
package main
import (
"fmt"
"math"
"sort"
)
const (
n = 200
header = "\nSides P A"
)
func gcd(a, b int) int {
leftover := 1
var dividend, divisor int
if (a > b) { dividend, divisor = a, b } else { dividend, divisor = b, a }
for (leftover != 0) {
leftover = dividend % divisor
if (leftover > 0) {
dividend, divisor = divisor, leftover
}
}
return divisor
}
func is_heron(h float64) bool {
return h > 0 && math.Mod(h, 1) == 0.0
} | 752Heronian triangles
| 0go
| 4x052 |
void myFuncSimple( void (*funcParameter)(void) )
{
(*funcParameter)();
funcParameter();
} | 754Higher-order functions
| 5c
| t4gf4 |
print() | 751Here document
| 3python
| nvgiz |
var historyOfHistory = [Int]()
var history:Int = 0 {
willSet {
historyOfHistory.append(history)
}
}
history = 2
history = 3
history = 4
println(historyOfHistory) | 744History variables
| 17swift
| uefvg |
'''Hilbert curve'''
from itertools import (chain, islice)
def hilbertCurve(n):
'''An SVG string representing a
Hilbert curve of degree n.
'''
w = 1024
return svgFromPoints(w)(
hilbertPoints(w)(
hilbertTree(n)
)
)
def hilbertTree(n):
'''Nth application of a rule to a seedling tree.'''
rule = {
'a': ['d', 'a', 'a', 'b'],
'b': ['c', 'b', 'b', 'a'],
'c': ['b', 'c', 'c', 'd'],
'd': ['a', 'd', 'd', 'c']
}
def go(tree):
c = tree['root']
xs = tree['nest']
return Node(c)(
map(go, xs) if xs else map(
flip(Node)([]),
rule[c]
)
)
seed = Node('a')([])
return list(islice(
iterate(go)(seed), n
))[-1] if 0 < n else seed
def hilbertPoints(w):
'''Serialization of a tree to a list of points
bounded by a square of side w.
'''
vectors = {
'a': [(-1, 1), (-1, -1), (1, -1), (1, 1)],
'b': [(1, -1), (-1, -1), (-1, 1), (1, 1)],
'c': [(1, -1), (1, 1), (-1, 1), (-1, -1)],
'd': [(-1, 1), (1, 1), (1, -1), (-1, -1)]
}
def points(d):
'''Size -> Centre of a Hilbert subtree -> All subtree points
'''
def go(xy, tree):
r = d
def deltas(v):
return (
xy[0] + (r * v[0]),
xy[1] + (r * v[1])
)
centres = map(deltas, vectors[tree['root']])
return chain.from_iterable(
map(points(r), centres, tree['nest'])
) if tree['nest'] else centres
return go
d = w
return lambda tree: list(points(d)((d, d), tree))
def svgFromPoints(w):
'''Width of square canvas -> Point list -> SVG string'''
def go(xys):
def points(xy):
return str(xy[0]) + ' ' + str(xy[1])
xs = ' '.join(map(points, xys))
return '\n'.join(
['<svg xmlns=',
f'width= height= viewBox=>',
f'<path d= ',
'stroke-width= stroke= fill=/>',
'</svg>'
]
)
return go
def main():
'''Testing generation of the SVG for a Hilbert curve'''
print(
hilbertCurve(6)
)
def Node(v):
'''Contructor for a Tree node which connects a
value of some kind to a list of zero or
more child trees.'''
return lambda xs: {'type': 'Node', 'root': v, 'nest': xs}
def flip(f):
'''The (curried or uncurried) function f with its
arguments reversed.
'''
return lambda a: lambda b: f(b)(a)
def iterate(f):
'''An infinite list of repeated
applications of f to x.
'''
def go(x):
v = x
while True:
yield v
v = f(v)
return go
if __name__ == '__main__':
main() | 748Hilbert curve
| 3python
| cbq9q |
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.nio.charset.Charset;
public class Main {
public static void main(String[] args) {
var request = HttpRequest.newBuilder(URI.create("https: | 741HTTP
| 9java
| 1f4p2 |
public class Err{
public static void main(String[] args){
System.err.println("Goodbye, World!");
}
} | 753Hello world/Standard error
| 9java
| 5wquf |
WScript.StdErr.WriteLine("Goodbye, World!"); | 753Hello world/Standard error
| 10javascript
| j8i7n |
import qualified Data.List as L
import Data.Maybe
import Data.Ord
import Text.Printf
perfectSqrt :: Integral a => a -> Maybe a
perfectSqrt n
| n == 1 = Just 1
| n < 4 = Nothing
| otherwise =
let search low high =
let guess = (low + high) `div` 2
square = guess ^ 2
next
| square == n = Just guess
| low == guess = Nothing
| square < n = search guess high
| otherwise = search low guess
in next
in search 0 n
heronTri :: Integral a => a -> a -> a -> Maybe a
heronTri a b c =
let
areaSq16 = (a + b + c) * (b + c - a) * (a + c - b) * (a + b - c)
(areaSq, r) = areaSq16 `divMod` 16
in if r == 0
then perfectSqrt areaSq
else Nothing
isPrimitive :: Integral a => a -> a -> a -> a
isPrimitive a b c = gcd a (gcd b c)
third (_, _, x, _, _) = x
fourth (_, _, _, x, _) = x
fifth (_, _, _, _, x) = x
orders :: Ord b => [(a -> b)] -> a -> a -> Ordering
orders [f] a b = comparing f a b
orders (f:fx) a b =
case comparing f a b of
EQ -> orders fx a b
n -> n
main :: IO ()
main = do
let range = [1 .. 200]
tris :: [(Integer, Integer, Integer, Integer, Integer)]
tris = L.sortBy (orders [fifth, fourth, third])
$ map (\(a, b, c, d, e) -> (a, b, c, d, fromJust e))
$ filter (isJust . fifth)
[(a, b, c, a + b + c, heronTri a b c)
| a <- range, b <- range, c <- range
, a <= b, b <= c, isPrimitive a b c == 1]
printTri (a, b, c, d, e) = printf "%3d%3d%3d%9d%4d\n" a b c d e
printf "Heronian triangles found:%d\n\n" $ length tris
putStrLn " Sides Perimeter Area"
mapM_ printTri $ take 10 tris
putStrLn ""
mapM_ printTri $ filter ((== 210) . fifth) tris | 752Heronian triangles
| 8haskell
| qycx9 |
import java.io.PrintWriter
import java.net.ServerSocket
fun main(args: Array<String>) {
val listener = ServerSocket(8080)
while(true) {
val sock = listener.accept()
PrintWriter(sock.outputStream, true).println("Goodbye, World!")
sock.close()
}
} | 750Hello world/Web server
| 11kotlin
| rsngo |
address = <<END
1, High Street,
West Midlands.
WM4 5HD.
END | 751Here document
| 14ruby
| f57dr |
from heapq import heappush, heappop, heapify
from collections import defaultdict
def encode(symb2freq):
heap = [[wt, [sym, ]] for sym, wt in symb2freq.items()]
heapify(heap)
while len(heap) > 1:
lo = heappop(heap)
hi = heappop(heap)
for pair in lo[1:]:
pair[1] = '0' + pair[1]
for pair in hi[1:]:
pair[1] = '1' + pair[1]
heappush(heap, [lo[0] + hi[0]] + lo[1:] + hi[1:])
return sorted(heappop(heap)[1:], key=lambda p: (len(p[-1]), p))
txt =
symb2freq = defaultdict(int)
for ch in txt:
symb2freq[ch] += 1
huff = encode(symb2freq)
print
for p in huff:
print % (p[0], symb2freq[p[0]], p[1]) | 736Huffman coding
| 3python
| kirhf |
DROP TABLE test;
CREATE TABLE test(a INTEGER, b INTEGER);
INSERT INTO test VALUES (1,2);
INSERT INTO test VALUES (2,2);
INSERT INTO test VALUES (2,1);
SELECT to_char(a)||' is less than '||to_char(b) less_than
FROM test
WHERE a < b;
SELECT to_char(a)||' is equal to '||to_char(b) equal_to
FROM test
WHERE a = b;
SELECT to_char(a)||' is greater than '||to_char(b) greater_than
FROM test
WHERE a > b; | 725Integer comparison
| 19sql
| jow7e |
var req = new XMLHttpRequest();
req.onload = function() {
console.log(this.responseText);
};
req.open('get', 'http: | 741HTTP
| 10javascript
| qyhx8 |
fun main(args: Array<String>) {
System.err.println("Goodbye, World!")
} | 753Hello world/Standard error
| 11kotlin
| cb198 |
local socket = require "socket"
local headers = "HTTP/1.1 200 OK\r\nContent-Type: text/html; charset=UTF-8\r\nContent-Length:%d\r\n\r\n%s"
local content = "<!doctype html><html><title>Goodbye, World!</title><h1>Goodbye, World!"
local server = assert(socket.bind("localhost", 8080))
repeat
local client = server:accept()
local ok = client:send(string.format(headers, #content, content))
client:close()
until not client or not ok
server:close() | 750Hello world/Web server
| 1lua
| 70dru |
let x = r#"
This is a "raw string literal," roughly equivalent to a heredoc.
"#;
let y = r##"
This string contains a #.
"##; | 751Here document
| 15rust
| t4jfd |
object temp {
val MemoriesOfHolland=
"""Thinking of Holland
|I see broad rivers
|slowly chuntering
|through endless lowlands,
|rows of implausibly
|airy poplars
|standing like tall plumes
|against the horizon;
|and sunk in the unbounded
|vastness of space
|homesteads and boweries
|dotted across the land,
|copses, villages,
|couchant towers,
|churches and elm-trees,
|bound in one great unity.
|There the sky hangs low,
|and steadily the sun
|is smothered in a greyly
|iridescent smirr,
|and in every province
|the voice of water
|with its lapping disasters
|is feared and hearkened.""".stripMargin
} | 751Here document
| 16scala
| 67b31 |
def ffr(n):
if n < 1 or type(n) != int: raise ValueError()
try:
return ffr.r[n]
except IndexError:
r, s = ffr.r, ffs.s
ffr_n_1 = ffr(n-1)
lastr = r[-1]
s += list(range(s[-1] + 1, lastr))
if s[-1] < lastr: s += [lastr + 1]
len_s = len(s)
ffs_n_1 = s[n-1] if len_s > n else (n - len_s) + s[-1]
ans = ffr_n_1 + ffs_n_1
r.append(ans)
return ans
ffr.r = [None, 1]
def ffs(n):
if n < 1 or type(n) != int: raise ValueError()
try:
return ffs.s[n]
except IndexError:
r, s = ffr.r, ffs.s
for i in range(len(r), n+2):
ffr(i)
if len(s) > n:
return s[n]
raise Exception()
ffs.s = [None, 2]
if __name__ == '__main__':
first10 = [ffr(i) for i in range(1,11)]
assert first10 == [1, 3, 7, 12, 18, 26, 35, 45, 56, 69],
print(, first10)
bin = [None] + [0]*1000
for i in range(40, 0, -1):
bin[ffr(i)] += 1
for i in range(960, 0, -1):
bin[ffs(i)] += 1
if all(b == 1 for b in bin[1:1000]):
print()
else:
print() | 747Hofstadter Figure-Figure sequences
| 3python
| i2jof |
use utf8;
binmode STDOUT, ":utf8";
use constant => 3.14159265;
sub d2r { $_[0] * / 180 }
sub r2d { $_[0] * 180 / }
print 'Enter latitude => '; $latitude = <>;
print 'Enter longitude => '; $longitude = <>;
print 'Enter legal meridian => '; $meridian = <>;
$lat_sin = sin( d2r($latitude) );
$offset = $meridian - $longitude;
print 'Sine of latitude: ' . sprintf "%.4f\n", $lat_sin;
print 'Longitude offset: ' . $offset . "\n";
print '=' x 48 . "\n";
print " Hour: Sun hour angle: Dial hour line angle\n";
for $hour (-6 .. 6) {
my $sun_deg = $hour * 15 + $offset;
my $line_deg = r2d atan2( ( sin(d2r($sun_deg)) * $lat_sin ), cos(d2r($sun_deg)) );
printf "%2d%s %8.3f %8.3f\n",
($hour + 12) % 12 || 12, ($hour < 0 ? 'AM' : 'PM'), $sun_deg, $line_deg;
} | 739Horizontal sundial calculations
| 2perl
| pdgb0 |
package main
import "fmt"
var m map[int]int
func initMap() {
m = make(map[int]int)
m[1] = 1
m[2] = 1
}
func q(n int) (r int) {
if r = m[n]; r == 0 {
r = q(n-q(n-1)) + q(n-q(n-2))
m[n] = r
}
return
}
func main() {
initMap() | 749Hofstadter Q sequence
| 0go
| nv7i1 |
import java.util.ArrayList;
public class Heron {
public static void main(String[] args) {
ArrayList<int[]> list = new ArrayList<>();
for (int c = 1; c <= 200; c++) {
for (int b = 1; b <= c; b++) {
for (int a = 1; a <= b; a++) {
if (gcd(gcd(a, b), c) == 1 && isHeron(heronArea(a, b, c))){
int area = (int) heronArea(a, b, c);
list.add(new int[]{a, b, c, a + b + c, area});
}
}
}
}
sort(list);
System.out.printf("Number of primitive Heronian triangles with sides up "
+ "to 200:%d\n\nFirst ten when ordered by increasing area, then"
+ " perimeter:\nSides Perimeter Area", list.size());
for (int i = 0; i < 10; i++) {
System.out.printf("\n%d x%d x%d %d %d",
list.get(i)[0], list.get(i)[1], list.get(i)[2],
list.get(i)[3], list.get(i)[4]);
}
System.out.printf("\n\nArea = 210\nSides Perimeter Area");
for (int i = 0; i < list.size(); i++) {
if (list.get(i)[4] == 210)
System.out.printf("\n%d x%d x%d %d %d",
list.get(i)[0], list.get(i)[1], list.get(i)[2],
list.get(i)[3], list.get(i)[4]);
}
}
public static double heronArea(int a, int b, int c) {
double s = (a + b + c) / 2f;
return Math.sqrt(s * (s - a) * (s - b) * (s - c));
}
public static boolean isHeron(double h) {
return h % 1 == 0 && h > 0;
}
public static int gcd(int a, int b) {
int leftover = 1, dividend = a > b ? a : b, divisor = a > b ? b : a;
while (leftover != 0) {
leftover = dividend % divisor;
if (leftover > 0) {
dividend = divisor;
divisor = leftover;
}
}
return divisor;
}
public static void sort(ArrayList<int[]> list) {
boolean swapped = true;
int[] temp;
while (swapped) {
swapped = false;
for (int i = 1; i < list.size(); i++) {
if (list.get(i)[4] < list.get(i - 1)[4] ||
list.get(i)[4] == list.get(i - 1)[4] &&
list.get(i)[3] < list.get(i - 1)[3]) {
temp = list.get(i);
list.set(i, list.get(i - 1));
list.set(i - 1, temp);
swapped = true;
}
}
}
}
} | 752Heronian triangles
| 9java
| pdzb3 |
rValues <- 1
sValues <- 2
ffr <- function(n)
{
if(!is.na(rValues[n])) rValues[n] else (rValues[n] <<- ffr(n-1) + ffs(n-1))
}
ffs <- function(n)
{
if(!is.na(sValues[n])) sValues[n] else (sValues[n] <<- setdiff(seq_len(1 + ffr(n)), rValues)[n])
}
invisible(ffr(10))
print(rValues)
invisible(ffs(500))
invisible(ffs(960))
This gives an output of length 960, which clearly cannot contain 1000 different values.
print(table(c(rValues[1:40], sValues[1:960]))) | 747Hofstadter Figure-Figure sequences
| 13r
| sm4qy |
load_library :grammar
attr_reader :hilbert
def settings
size 600, 600
end
def setup
sketch_title '2D Hilbert'
@hilbert = Hilbert.new
hilbert.create_grammar 5
no_loop
end
def draw
background 0
hilbert.render
end
Turtle = Struct.new(:x, :y, :theta)
class Hilbert
include Processing::Proxy
attr_reader :grammar, :axiom, :draw_length, :production, :turtle
DELTA = 90.radians
def initialize
@axiom = 'FL'
@grammar = Grammar.new(
axiom,
'L' => '+RF-LFL-FR+',
'R' => '-LF+RFR+FL-'
)
@draw_length = 200
stroke 0, 255, 0
stroke_weight 2
@turtle = Turtle.new(width / 9, height / 9, 0)
end
def render
production.scan(/./) do |element|
case element
when 'F'
draw_line(turtle)
when '+'
turtle.theta += DELTA
when '-'
turtle.theta -= DELTA
when 'L'
when 'R'
else puts 'Grammar not recognized'
end
end
end
def draw_line(turtle)
x_temp = turtle.x
y_temp = turtle.y
turtle.x += draw_length * Math.cos(turtle.theta)
turtle.y += draw_length * Math.sin(turtle.theta)
line(x_temp, y_temp, turtle.x, turtle.y)
end
def create_grammar(gen)
@draw_length *= 0.6**gen
@production = @grammar.generate gen
end
end | 748Hilbert curve
| 14ruby
| 210lw |
func identityMatrix(size: Int) -> [[Int]] {
return (0..<size).map({i in
return (0..<size).map({ $0 == i? 1: 0})
})
}
print(identityMatrix(size: 5)) | 730Identity matrix
| 17swift
| yhc6e |
import Cocoa
var input = NSFileHandle.fileHandleWithStandardInput()
println("Enter two integers separated by a space: ")
let data = input.availableData
let stringArray = NSString(data: data, encoding: NSUTF8StringEncoding)?.componentsSeparatedByString(" ")
var a:Int!
var b:Int!
if (stringArray?.count == 2) {
a = stringArray![0].integerValue
b = stringArray![1].integerValue
}
if (a==b) {println("\(a) equals \(b)")}
if (a < b) {println("\(a) is less than \(b)")}
if (a > b) {println("\(a) is greater than \(b)")} | 725Integer comparison
| 17swift
| 2ajlj |
null | 741HTTP
| 11kotlin
| j8l7r |
io.stderr:write("Goodbye, World!\n") | 753Hello world/Standard error
| 1lua
| lpack |
window.onload = function(){
var list = [];
var j = 0;
for(var c = 1; c <= 200; c++)
for(var b = 1; b <= c; b++)
for(var a = 1; a <= b; a++)
if(gcd(gcd(a, b), c) == 1 && isHeron(heronArea(a, b, c)))
list[j++] = new Array(a, b, c, a + b + c, heronArea(a, b, c));
sort(list);
document.write("<h2>Primitive Heronian triangles with sides up to 200: " + list.length + "</h2><h3>First ten when ordered by increasing area, then perimeter:</h3><table><tr><th>Sides</th><th>Perimeter</th><th>Area</th><tr>");
for(var i = 0; i < 10; i++)
document.write("<tr><td>" + list[i][0] + " x " + list[i][1] + " x " + list[i][2] + "</td><td>" + list[i][3] + "</td><td>" + list[i][4] + "</td></tr>");
document.write("</table><h3>Area = 210</h3><table><tr><th>Sides</th><th>Perimeter</th><th>Area</th><tr>");
for(var i = 0; i < list.length; i++)
if(list[i][4] == 210)
document.write("<tr><td>" + list[i][0] + " x " + list[i][1] + " x " + list[i][2] + "</td><td>" + list[i][3] + "</td><td>" + list[i][4] + "</td></tr>");
function heronArea(a, b, c){
var s = (a + b + c)/ 2;
return Math.sqrt(s *(s -a)*(s - b)*(s - c));
}
function isHeron(h){
return h % 1 == 0 && h > 0;
}
function gcd(a, b){
var leftover = 1, dividend = a > b ? a : b, divisor = a > b ? b : a;
while(leftover != 0){
leftover = dividend % divisor;
if(leftover > 0){
dividend = divisor;
divisor = leftover;
}
}
return divisor;
}
function sort(list){
var swapped = true;
var temp = [];
while(swapped){
swapped = false;
for(var i = 1; i < list.length; i++){
if(list[i][4] < list[i - 1][4] || list[i][4] == list[i - 1][4] && list[i][3] < list[i - 1][3]){
temp = list[i];
list[i] = list[i - 1];
list[i - 1] = temp;
swapped = true;
}
}
}
}
} | 752Heronian triangles
| 10javascript
| x69w9 |
(defn append-hello [s]
(str "Hello " s))
(defn modify-string [f s]
(f s))
(println (modify-string append-hello "World!")) | 754Higher-order functions
| 6clojure
| mhkyq |
use 5.10.0;
use strict;
use warnings;
sub horner(\@$){
my ($coef, $x) = @_;
my $result = 0;
$result = $result * $x + $_ for reverse @$coef;
return $result;
}
my @coeff = (-19.0, 7, -4, 6);
my $x = 3;
say horner @coeff, $x; | 740Horner's rule for polynomial evaluation
| 2perl
| qykx6 |
null | 748Hilbert curve
| 15rust
| va82t |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.