code
stringlengths
1
46.1k
label
class label
1.18k classes
domain_label
class label
21 classes
index
stringlengths
4
5
require 'mathn' require 'rubygems' require 'gd2' include GD2 def hough_transform(img) mx, my = img.w*0.5, img.h*0.5 max_d = Math.sqrt(mx**2 + my**2) min_d = max_d * -1 hough = Hash.new(0) (0..img.w).each do |x| puts (0..img.h).each do |y| if img.pixel2color(img.get_pixel(x,y)).g > 32 (0...180).each do |a| rad = a * (Math::PI / 180.0) d = (x-mx) * Math.cos(rad) + (y-my) * Math.sin(rad) hough[] = hough[] + 1 end end end end heat = GD2::Image.import 'heatmap.png' out = GD2::Image::TrueColor.new(180,max_d*2) max = hough.values.max p max hough.each_pair do |k,v| a,d = k.split('_').map(&:to_i) c = (v / max) * 255 c = heat.get_pixel(c,0) out.set_pixel(a, max_d + d, c) end out end
734Hough transform
14ruby
j8r7x
next = str(int('123') + 1)
727Increment a numerical string
3python
pfqbm
use strict; use LWP::UserAgent; my $url = 'https://www.rosettacode.org'; my $response = LWP::UserAgent->new->get( $url ); $response->is_success or die "Failed to GET '$url': ", $response->status_line; print $response->as_string;
733HTTPS
2perl
l1lc5
printf(, TXT); \ scanf(, &VM); \ } while(0); int main() { double lat, slat, lng, ref; int h; PICKVALUE(, lat); PICKVALUE(, lng); PICKVALUE(, ref); printf(); slat = sin(DR(lat)); printf(, slat); printf(, lng - ref); printf(); for(h = -6; h <= 6; h++) { double hla, hra; hra = 15.0*h; hra = hra - lng + ref; hla = RD(atan(slat * tan(DR(hra)))); printf(, h, hra, hla); } return 0; }
739Horizontal sundial calculations
5c
j8v70
null
735Host introspection
11kotlin
i20o4
ffi = require("ffi") print("size of int (in bytes): " .. ffi.sizeof(ffi.new("int"))) print("size of pointer (in bytes): " .. ffi.sizeof(ffi.new("int*"))) print((ffi.abi("le") and "little" or "big") .. " endian")
735Host introspection
1lua
nv8i8
import java.net.*; class DiscoverHostName { public static void main(final String[] args) { try { System.out.println(InetAddress.getLocalHost().getHostName()); } catch (UnknownHostException e) {
737Hostname
9java
f58dv
var network = new ActiveXObject('WScript.Network'); var hostname = network.computerName; WScript.echo(hostname);
737Hostname
10javascript
yjf6r
null
734Hough transform
15rust
ho7j2
import java.awt.image._ import java.io.File import javax.imageio._ object HoughTransform extends App { override def main(args: Array[String]) { val inputData = readDataFromImage(args(0)) val minContrast = if (args.length >= 4) 64 else args(4).toInt inputData(args(2).toInt, args(3).toInt, minContrast).writeOutputImage(args(1)) } private def readDataFromImage(filename: String) = { val image = ImageIO.read(new File(filename)) val width = image.getWidth val height = image.getHeight val rgbData = image.getRGB(0, 0, width, height, null, 0, width) val arrayData = new ArrayData(width, height) for (y <- 0 until height; x <- 0 until width) { var rgb = rgbData(y * width + x) rgb = (((rgb & 0xFF0000) >>> 16) * 0.30 + ((rgb & 0xFF00) >>> 8) * 0.59 + (rgb & 0xFF) * 0.11).toInt arrayData(x, height - 1 - y) = rgb } arrayData } } class ArrayData(val width: Int, val height: Int) { def update(x: Int, y: Int, value: Int) { dataArray(x)(y) = value } def apply(thetaAxisSize: Int, rAxisSize: Int, minContrast: Int) = { val maxRadius = Math.ceil(Math.hypot(width, height)).toInt val halfRAxisSize = rAxisSize >>> 1 val outputData = new ArrayData(thetaAxisSize, rAxisSize) val sinTable = Array.ofDim[Double](thetaAxisSize) val cosTable = sinTable.clone() for (theta <- thetaAxisSize - 1 until -1 by -1) { val thetaRadians = theta * Math.PI / thetaAxisSize sinTable(theta) = Math.sin(thetaRadians) cosTable(theta) = Math.cos(thetaRadians) } for (y <- height - 1 until -1 by -1; x <- width - 1 until -1 by -1) if (contrast(x, y, minContrast)) for (theta <- thetaAxisSize - 1 until -1 by -1) { val r = cosTable(theta) * x + sinTable(theta) * y val rScaled = Math.round(r * halfRAxisSize / maxRadius).toInt + halfRAxisSize outputData.dataArray(theta)(rScaled) += 1 } outputData } def writeOutputImage(filename: String) { var max = Int.MinValue for (y <- 0 until height; x <- 0 until width) { val v = dataArray(x)(y) if (v > max) max = v } val image = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB) for (y <- 0 until height; x <- 0 until width) { val n = Math.min(Math.round(dataArray(x)(y) * 255.0 / max).toInt, 255) image.setRGB(x, height - 1 - y, (n << 16) | (n << 8) | 0x90 | -0x01000000) } ImageIO.write(image, "PNG", new File(filename)) } private def contrast(x: Int, y: Int, minContrast: Int): Boolean = { val centerValue = dataArray(x)(y) for (i <- 8 until -1 by -1 if i != 4) { val newx = x + (i % 3) - 1 val newy = y + (i / 3) - 1 if (newx >= 0 && newx < width && newy >= 0 && newy < height && Math.abs(dataArray(newx)(newy) - centerValue) >= minContrast) return true } false } private val dataArray = Array.ofDim[Int](width, height) }
734Hough transform
16scala
pdkbj
s = "12345" s <- as.character(as.numeric(s) + 1)
727Increment a numerical string
13r
joa78
echo file_get_contents('https:
733HTTPS
12php
qmqx3
null
737Hostname
11kotlin
8cw0q
import urllib.request print(urllib.request.urlopen().read())
733HTTPS
3python
2a2lz
double horner(double *coeffs, int s, double x) { int i; double res = 0.0; for(i=s-1; i >= 0; i--) { res = res * x + coeffs[i]; } return res; } int main() { double coeffs[] = { -19.0, 7.0, -4.0, 6.0 }; printf(, horner(coeffs, sizeof(coeffs)/sizeof(double), 3.0)); return 0; }
740Horner's rule for polynomial evaluation
5c
atr11
library(RCurl) webpage <- getURL("https://sourceforge.net/", .opts=list(followlocation=TRUE, ssl.verifyhost=FALSE, ssl.verifypeer=FALSE))
733HTTPS
13r
mkmy4
package main import ( "container/heap" "fmt" ) type HuffmanTree interface { Freq() int } type HuffmanLeaf struct { freq int value rune } type HuffmanNode struct { freq int left, right HuffmanTree } func (self HuffmanLeaf) Freq() int { return self.freq } func (self HuffmanNode) Freq() int { return self.freq } type treeHeap []HuffmanTree func (th treeHeap) Len() int { return len(th) } func (th treeHeap) Less(i, j int) bool { return th[i].Freq() < th[j].Freq() } func (th *treeHeap) Push(ele interface{}) { *th = append(*th, ele.(HuffmanTree)) } func (th *treeHeap) Pop() (popped interface{}) { popped = (*th)[len(*th)-1] *th = (*th)[:len(*th)-1] return } func (th treeHeap) Swap(i, j int) { th[i], th[j] = th[j], th[i] } func buildTree(symFreqs map[rune]int) HuffmanTree { var trees treeHeap for c, f := range symFreqs { trees = append(trees, HuffmanLeaf{f, c}) } heap.Init(&trees) for trees.Len() > 1 {
736Huffman coding
0go
i2sog
int main(void) { CURL *curl; char buffer[CURL_ERROR_SIZE]; if ((curl = curl_easy_init()) != NULL) { curl_easy_setopt(curl, CURLOPT_URL, ); curl_easy_setopt(curl, CURLOPT_FOLLOWLOCATION, 1); curl_easy_setopt(curl, CURLOPT_ERRORBUFFER, buffer); if (curl_easy_perform(curl) != CURLE_OK) { fprintf(stderr, , buffer); return EXIT_FAILURE; } curl_easy_cleanup(curl); } return EXIT_SUCCESS; }
741HTTP
5c
i2ao2
(defn horner [coeffs x] (reduce #(-> %1 (* x) (+ %2)) (reverse coeffs))) (println (horner [-19 7 -4 6] 3))
740Horner's rule for polynomial evaluation
6clojure
smbqr
import groovy.transform.* @Canonical @Sortable(includes = ['freq', 'letter']) class Node { String letter int freq Node left Node right boolean isLeaf() { left == null && right == null } } Map correspondance(Node n, Map corresp = [:], String prefix = '') { if (n.isLeaf()) { corresp[n.letter] = prefix ?: '0' } else { correspondance(n.left, corresp, prefix + '0') correspondance(n.right, corresp, prefix + '1') } return corresp } Map huffmanCode(String message) { def queue = message.toList().countBy { it }
736Huffman coding
7groovy
qyaxp
socket = require "socket" print( socket.dns.gethostname() )
737Hostname
1lua
olx8h
'1234'.succ '99'.succ
727Increment a numerical string
14ruby
az01s
require 'net/https' require 'uri' require 'pp' uri = URI.parse('https: http = Net::HTTP.new(uri.host,uri.port) http.use_ssl = true http.verify_mode = OpenSSL::SSL::VERIFY_NONE http.start do content = http.get(uri) p [content.code, content.message] pp content.to_hash puts content.body end
733HTTPS
14ruby
uwuvz
extern crate reqwest; fn main() { let response = match reqwest::blocking::get("https:
733HTTPS
15rust
5x5uq
static GdkPixbuf*create_pixbuf(const gchar*filename) { GdkPixbuf*pixbuf; GError*error = NULL; pixbuf = gdk_pixbuf_new_from_file(filename, &error); if(!pixbuf) { fprintf(stderr,, error->message); g_error_free(error); } return pixbuf; } NGON { double Cx,Cy, r; int sides, selected; char c; }; GRand*random_numbers = NULL; static void initialize_hexagons(NGON*hs,size_t n) { NGON*h; gint i,broken; GQueue*shuffler = g_queue_new(); if (NULL == shuffler) { fputs(,stderr); exit(EXIT_FAILURE); } if ((broken = (NULL == random_numbers))) random_numbers = g_rand_new(); for (i = 'A'; i <= 'Z'; ++i) g_queue_push_head(shuffler,GINT_TO_POINTER(i)); memset(hs,0,n*(sizeof(NGON))); hs[n-1].sides = -1; for (h = hs; !h->sides; ++h) { int div = (h-hs)/4, mod = (h-hs)%4; h->sides = 6; h->c = GPOINTER_TO_INT( g_queue_pop_nth( shuffler, g_rand_int_range( random_numbers, (gint32)0, (gint32)g_queue_get_length(shuffler)))); fputc(h->c,stderr); h->r = R; h->Cx = R*(2+div*OFFSET_X), h->Cy = R*(2*(1+mod*OFFSET_Y)+ODD(div)*OFFSET_Y); fprintf(stderr,,h->Cx,h->Cy); } fputc('\n',stderr); g_queue_free(shuffler); if (broken) g_rand_free(random_numbers); } static void add_loop(cairo_t*cr,NGON*hs,int select) { NGON*h; double r,Cx,Cy,x,y; int i, sides; for (h = hs; 0 < (sides = h->sides); ++h) if ((select && h->selected) || (select == h->selected)) { r = h->r, Cx = h->Cx, Cy = h->Cy; i = 0; x = Cx+r*cos(TAU*i/sides), y = Cy+r*sin(TAU*i/sides), cairo_move_to(cr,x,y); for (i = 1; i < sides; ++i) x = Cx+r*cos(TAU*i/sides), y = Cy+r*sin(TAU*i/sides), cairo_line_to(cr,x,y); cairo_close_path(cr); } } static int make_labels(cairo_t*cr,NGON*hs,int select) { NGON*h; int i = 0; char text[2]; text[1] = 0; for (h = hs; 0 < h->sides; ++h) if ((select && h->selected) || (select == h->selected)) *text = h->c, cairo_move_to(cr,h->Cx,h->Cy), cairo_show_text(cr,text), ++i; return i; } static int archive(int a) { static GQueue*q = NULL; if ((NULL == q) && (NULL == (q = g_queue_new()))) { fputs(,stderr); exit(EXIT_FAILURE); } if (a < -1) return g_queue_free(q), q = NULL, 0; if (-1 == a) return g_queue_is_empty(q) ? 0 : GPOINTER_TO_INT(g_queue_pop_tail(q)); if (!a) return g_queue_is_empty(q) ? 0 : GPOINTER_TO_INT(g_queue_peek_head(q)); g_queue_push_head(q,GINT_TO_POINTER(a)); return a; } static gboolean draw(GtkWidget*widget,cairo_t*cr,gpointer data) { cairo_set_source_rgba(cr,0.8,0.8,0,1), add_loop(cr,(NGON*)data,0); cairo_fill(cr); cairo_set_source_rgba(cr,0.8,0,0.8,1); add_loop(cr,(NGON*)data,1); cairo_fill_preserve(cr); cairo_set_line_width (cr, 3.0); cairo_set_source_rgba(cr,0.7,0.7,0.7,0.7); add_loop(cr,(NGON*)data,0); cairo_stroke(cr); cairo_set_source_rgba(cr,0,1,0,1); make_labels(cr,(NGON*)data,1); cairo_stroke(cr); cairo_set_source_rgba(cr,1,0,0,1); if (!make_labels(cr,(NGON*)data,0)) { int c; putchar('\n'); while ((c = archive(-1))) putchar(c); puts(); archive(-2); exit(EXIT_SUCCESS); } cairo_stroke(cr); return TRUE; } static gboolean button_press_event(GtkWidget*widget,const GdkEvent*event,gpointer data) { NGON*h,*hs = (NGON*)data; gdouble x_win, y_win; if (!gdk_event_get_coords(event,&x_win,&y_win)) fputs(,stderr); else { fprintf(stderr,,(double)x_win,(double)y_win); for (h = hs; 0 < h->sides; ++h) if ((pow((x_win-h->Cx),2)+pow((y_win-h->Cy),2)) < pow((h->r*cos(TAU/(180/h->sides))),2)) { ++h->selected; archive(h->c); gdk_window_invalidate_rect(gtk_widget_get_window(widget),(const GdkRectangle*)NULL,TRUE); break; } } return TRUE; } static gboolean key_press_event(GtkWidget*widget,const GdkEvent*event,gpointer data) { NGON*h,*hs = (NGON*)data; guint keyval; int unicode; if (!gdk_event_get_keyval(event,&keyval)) fputs(,stderr); else { unicode = (int)gdk_keyval_to_unicode(gdk_keyval_to_upper(keyval)); fprintf(stderr,,unicode); for (h = hs; 0 < h->sides; ++h) if (h->c == unicode) { ++(h->selected); archive(h->c); gdk_window_invalidate_rect(gtk_widget_get_window(widget),(const GdkRectangle*)NULL,TRUE); break; } } return TRUE; } int main(int argc,char*argv[]) { GtkWidget *window, *vbox, *drawing_area; NGON ngons[21]; gtk_init(&argc, &argv); fprintf(stderr,,GTK_MAJOR_VERSION,GTK_MINOR_VERSION,GTK_MICRO_VERSION); window = gtk_window_new(GTK_WINDOW_TOPLEVEL); gtk_window_set_title(GTK_WINDOW(window), ); gtk_window_set_default_size(GTK_WINDOW(window), 308, 308+12+8); g_signal_connect_swapped(G_OBJECT(window),,G_CALLBACK(gtk_main_quit),NULL); gtk_window_set_icon(GTK_WINDOW(window),create_pixbuf()); vbox = gtk_vbox_new(TRUE,1); gtk_container_add(GTK_CONTAINER(window),vbox); label = gtk_label_new(); gtk_widget_set_size_request(label,308,20); gtk_box_pack_end(GTK_BOX(vbox),label,FALSE,TRUE,4); drawing_area = gtk_drawing_area_new(); gtk_widget_set_events(drawing_area,GDK_BUTTON_PRESS_MASK|GDK_KEY_PRESS_MASK|GDK_EXPOSURE_MASK); random_numbers = g_rand_new(); initialize_hexagons(ngons,G_N_ELEMENTS(ngons)); g_signal_connect(G_OBJECT(drawing_area),,G_CALLBACK(draw),(gpointer)ngons); g_signal_connect(G_OBJECT(drawing_area),,G_CALLBACK(button_press_event),(gpointer)ngons); g_signal_connect(G_OBJECT(drawing_area),,G_CALLBACK(key_press_event),(gpointer)ngons); gtk_widget_set_size_request(drawing_area, 308, 308); gtk_box_pack_start(GTK_BOX(vbox),drawing_area,TRUE,TRUE,4); gtk_widget_set_can_focus(drawing_area,TRUE); gtk_widget_show_all(window); gtk_main(); g_rand_free(random_numbers); return EXIT_SUCCESS; }
742Honeycombs
5c
vat2o
import Data.List (group, insertBy, sort, sortBy) import Control.Arrow ((&&&), second) import Data.Ord (comparing) data HTree a = Leaf a | Branch (HTree a) (HTree a) deriving (Show, Eq, Ord) test :: String -> IO () test = mapM_ (\(a, b) -> putStrLn ('\'': a: ("': " ++ b))) . serialize . huffmanTree . freq serialize :: HTree a -> [(a, String)] serialize (Branch l r) = (second ('0':) <$> serialize l) ++ (second ('1':) <$> serialize r) serialize (Leaf x) = [(x, "")] huffmanTree :: (Ord w, Num w) => [(w, a)] -> HTree a huffmanTree = snd . head . until (null . tail) hstep . sortBy (comparing fst) . fmap (second Leaf) hstep :: (Ord a, Num a) => [(a, HTree b)] -> [(a, HTree b)] hstep ((w1, t1):(w2, t2):wts) = insertBy (comparing fst) (w1 + w2, Branch t1 t2) wts freq :: Ord a => [a] -> [(Int, a)] freq = fmap (length &&& head) . group . sort main :: IO () main = test "this is an example for huffman encoding"
736Huffman coding
8haskell
va92k
use Config; print "UV size: $Config{uvsize}, byte order: $Config{byteorder}\n";
735Host introspection
2perl
rs5gd
fn next_string(input: &str) -> String { (input.parse::<i64>().unwrap() + 1).to_string() } fn main() { let s = "-1"; let s2 = next_string(s); println!("{:?}", s2); }
727Increment a numerical string
15rust
e38aj
implicit def toSucc(s: String) = new { def succ = BigDecimal(s) + 1 toString }
727Increment a numerical string
16scala
qmnxw
import scala.io.Source object HttpsTest extends App { System.setProperty("http.agent", "*") Source.fromURL("https:
733HTTPS
16scala
r0rgn
use strict; use warnings; use feature 'say'; sub identity_matrix { my($n) = shift() - 1; map { [ (0) x $_, 1, (0) x ($n - $_) ] } 0..$n } for (<4 5 6>) { say "\n$_:"; say join ' ', @$_ for identity_matrix $_; }
730Identity matrix
2perl
37mzs
sub test_num { my $f = shift; my $s = shift; if ($f < $s){ return -1; } elsif ($f > $s) { return 1; } elsif ($f == $s) { return 0; }; };
725Integer comparison
2perl
cpr9a
import Foundation
733HTTPS
17swift
vev2r
int a_list[1<<20 + 1]; int doSqnc( int m) { int max_df = 0; int p2_max = 2; int v, n; int k1 = 2; int lg2 = 1; double amax = 0; a_list[0] = -50000; a_list[1] = a_list[2] = 1; v = a_list[2]; for (n=3; n <= m; n++) { v = a_list[n] = a_list[v] + a_list[n-v]; if ( amax < v*1.0/n) amax = v*1.0/n; if ( 0 == (k1&n)) { printf(, lg2,lg2+1, amax); amax = 0; lg2++; } k1 = n; } return 1; }
743Hofstadter-Conway $10,000 sequence
5c
9kom1
(def a (ref 0)) (def a-history (atom [@a])) (add-watch a:hist (fn [key ref old new] (swap! a-history conj new)))
744History variables
6clojure
vad2f
typedef int year_t, month_t, week_t, day_t; typedef struct{ year_t year; month_t month; day_t month_day; day_t week_day; } date_t; const char *mon_fmt[] = {0, , , , , , , , , , , , }; const char *week_day_fmt[] = {0, , , , , , , }; day_t month_days(year_t year, month_t month) { day_t days[]={0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31}; return (month==2) ? 28 + (( year % 4 == 0 && year % 100 != 0 ) || year % 400 == 0) : days[month]; } day_t year_days(year_t year) { return (month_days(year, 2) == 28) ? 365 : 366; } month_t year_months = 12; week_t week_days = 7; date_t plusab(date_t *date, day_t days) { while(days < 0){ date->year -= 1; days += year_days(date->year); }; while(days > year_days(date->year)){ days -= year_days(date->year); date->year += 1; }; date->month_day += days; while(date->month_day > month_days(date->year, date->month)){ date->month_day -= month_days(date->year, date->month); date->month += 1; if(date->month > year_months){ date->month -= year_months; date->year += 1; } } date->week_day = week_day(*date); return *date; } date_t easter (year_t year) { date_t date; date.year = year; int c = year / 100, n = year % 19; int i = (c - c / 4 - (c - (c - 17) / 25) / 3 + 19 * n + 15) % 30; i -= (i / 28) * (1 - (i / 28) * (29 / (i + 1)) * ((21 - n) / 11)); int l = i - (year + year / 4 + i + 2 - c + c / 4) % 7; date.month = 3 + (l + 40) / 44; date.month_day = l + 28 - 31 * (date.month / 4); date.week_day = week_day(date); return date; } day_t week_day (date_t date) { int year = date.year, month = date.month, month_day = date.month_day, c; if(month <= 2){month += 12; year -= 1;} c = year / 100; year %= 100; return 1 + ((month_day + ((month + 1) * 26) / 10 + year + year / 4 + c / 4 - 2 * c) % 7 + 7) % 7; } typedef struct{date_t easter, ascension, pentecost, trinity, corpus_christi;}easter_related_t; easter_related_t easter_related_init (year_t year) { date_t date; easter_related_t holidays; holidays.easter = date = easter(year); holidays.ascension = plusab(&date, 39); holidays.pentecost = plusab(&date, 10); holidays.trinity = plusab(&date, 7); holidays.corpus_christi = plusab(&date, 4); return holidays; } wdmdm_fmtwdmdm_fmtwdmdm_fmt void easter_related_print(year_t year) { easter_related_t holidays = easter_related_init(year); printf(easter_related_fmt, year, wdmdm(holidays.easter), wdmdm(holidays.ascension), wdmdm(holidays.pentecost), wdmdm(holidays.trinity), wdmdm(holidays.corpus_christi)); } int main(){ year_t year; printf (); for(year=400; year<=2100; year+=100){ easter_related_print(year); } printf (); for(year=2010; year<=2020; year++){ easter_related_print(year); } return 0; }
745Holidays related to Easter
5c
4xt5t
>>> import platform, sys, socket >>> platform.architecture() ('64bit', 'ELF') >>> platform.machine() 'x86_64' >>> platform.node() 'yourhostname' >>> platform.system() 'Linux' >>> sys.byteorder little >>> socket.gethostname() 'yourhostname' >>>
735Host introspection
3python
704rm
(defn get-http [url] (let [sc (java.util.Scanner. (.openStream (java.net.URL. url)))] (while (.hasNext sc) (println (.nextLine sc))))) (get-http "http://www.rosettacode.org")
741HTTP
6clojure
zgstj
void h(int n) { MPFR_DECL_INIT(a, 200); MPFR_DECL_INIT(b, 200); mpfr_fac_ui(a, n, MPFR_RNDD); mpfr_set_ui(b, 2, MPFR_RNDD); mpfr_log(b, b, MPFR_RNDD); mpfr_pow_ui(b, b, n + 1, MPFR_RNDD); mpfr_div(a, a, b, MPFR_RNDD); mpfr_div_ui(a, a, 2, MPFR_RNDD); mpfr_frac(b, a, MPFR_RNDD); mpfr_printf(, n, a, mpfr_cmp_d(b, .1) * mpfr_cmp_d(b, .9) > 0 ? 'Y' : 'N'); } int main(void) { int n; for (n = 1; n <= 17; n++) h(n); return 0; }
746Hickerson series of almost integers
5c
5wduk
typedef unsigned long long xint; typedef struct { size_t len, alloc; xint *buf; } xarray; xarray rs, ss; void setsize(xarray *a, size_t size) { size_t n = a->alloc; if (!n) n = 1; while (n < size) n <<= 1; if (a->alloc < n) { a->buf = realloc(a->buf, sizeof(xint) * n); if (!a->buf) abort(); a->alloc = n; } } void push(xarray *a, xint v) { while (a->alloc <= a->len) setsize(a, a->alloc * 2); a->buf[a->len++] = v; } void RS_append(void); xint R(int n) { while (n > rs.len) RS_append(); return rs.buf[n - 1]; } xint S(int n) { while (n > ss.len) RS_append(); return ss.buf[n - 1]; } void RS_append() { int n = rs.len; xint r = R(n) + S(n); xint s = S(ss.len); push(&rs, r); while (++s < r) push(&ss, s); push(&ss, r + 1); } int main(void) { push(&rs, 1); push(&ss, 2); int i; printf(); for (i = 1; i <= 10; i++) printf(, R(i)); char seen[1001] = { 0 }; for (i = 1; i <= 40; i++) seen[ R(i) ] = 1; for (i = 1; i <= 960; i++) seen[ S(i) ] = 1; for (i = 1; i <= 1000 && seen[i]; i++); if (i <= 1000) { fprintf(stderr, , i); abort(); } puts(); return 0; }
747Hofstadter Figure-Figure sequences
5c
qy5xc
typedef struct { int x; int y; } point; void rot(int n, point *p, int rx, int ry) { int t; if (!ry) { if (rx == 1) { p->x = n - 1 - p->x; p->y = n - 1 - p->y; } t = p->x; p->x = p->y; p->y = t; } } void d2pt(int n, int d, point *p) { int s = 1, t = d, rx, ry; p->x = 0; p->y = 0; while (s < n) { rx = 1 & (t / 2); ry = 1 & (t ^ rx); rot(s, p, rx, ry); p->x += s * rx; p->y += s * ry; t /= 4; s *= 2; } } int main() { int d, x, y, cx, cy, px, py; char pts[MAX][MAX]; point curr, prev; for (x = 0; x < MAX; ++x) for (y = 0; y < MAX; ++y) pts[x][y] = ' '; prev.x = prev.y = 0; pts[0][0] = '.'; for (d = 1; d < N * N; ++d) { d2pt(N, d, &curr); cx = curr.x * K; cy = curr.y * K; px = prev.x * K; py = prev.y * K; pts[cx][cy] = '.'; if (cx == px ) { if (py < cy) for (y = py + 1; y < cy; ++y) pts[cx][y] = '|'; else for (y = cy + 1; y < py; ++y) pts[cx][y] = '|'; } else { if (px < cx) for (x = px + 1; x < cx; ++x) pts[x][cy] = '_'; else for (x = cx + 1; x < px; ++x) pts[x][cy] = '_'; } prev = curr; } for (x = 0; x < MAX; ++x) { for (y = 0; y < MAX; ++y) printf(, pts[y][x]); printf(); } return 0; }
748Hilbert curve
5c
3r1za
package main import ( rl "github.com/gen2brain/raylib-go/raylib" "math" "strings" ) type hexagon struct { x, y float32 letter rune selected bool } func (h hexagon) points(r float32) []rl.Vector2 { res := make([]rl.Vector2, 7) for i := 0; i < 7; i++ { fi := float64(i) res[i].X = h.x + r*float32(math.Cos(math.Pi*fi/3)) res[i].Y = h.y + r*float32(math.Sin(math.Pi*fi/3)) } return res } func inHexagon(pts []rl.Vector2, pt rl.Vector2) bool { rec := rl.NewRectangle(pts[4].X, pts[4].Y, pts[5].X-pts[4].X, pts[2].Y-pts[4].Y) if rl.CheckCollisionPointRec(pt, rec) { return true } if rl.CheckCollisionPointTriangle(pt, pts[2], pts[3], pts[4]) { return true } if rl.CheckCollisionPointTriangle(pt, pts[0], pts[1], pts[5]) { return true } return false } func DrawLineStrip(points []rl.Vector2, pointsCount int32, color rl.Color) { for i := int32(0); i < pointsCount - 1; i++ { rl.DrawLineV(points[i], points[i+1], color) } } func main() { screenWidth := int32(600) screenHeight := int32(600) rl.InitWindow(screenWidth, screenHeight, "Honeycombs") rl.SetTargetFPS(60) letters := "LRDGITPFBVOKANUYCESM" runes := []rune(letters) var combs [20]hexagon var pts [20][]rl.Vector2 x1, y1 := 150, 100 x2, y2 := 225, 143 w, h := 150, 87 r := float32(w / 3) for i := 0; i < 20; i++ { var x, y int if i < 12 { x = x1 + (i%3)*w y = y1 + (i/3)*h } else { x = x2 + (i%2)*w y = y2 + (i-12)/2*h } combs[i] = hexagon{float32(x), float32(y), runes[i], false} pts[i] = combs[i].points(r) } nChosen := 0 sChosen := "Chosen: " lChosen := "Last chosen: " for !rl.WindowShouldClose() { rl.BeginDrawing() rl.ClearBackground(rl.RayWhite) for i, c := range combs { ctr := pts[i][0] ctr.X -= r index := -1 if key := rl.GetKeyPressed(); key > 0 { if key >= 97 && key <= 122 { key -= 32 } index = strings.IndexRune(letters, key) } else if rl.IsMouseButtonPressed(rl.MouseLeftButton) { pt := rl.Vector2{float32(rl.GetMouseX()), float32(rl.GetMouseY())} for i := 0; i < 20; i++ { if inHexagon(pts[i], pt) { index = i break } } } if index >= 0 { if !combs[index].selected { combs[index].selected = true nChosen++ s := string(combs[index].letter) sChosen += s lChosen = "Last chosen: " + s if nChosen == 20 { lChosen += " (All 20 Chosen!)" } } } if !c.selected { rl.DrawPoly(ctr, 6, r-1, 30, rl.Yellow) } else { rl.DrawPoly(ctr, 6, r-1, 30, rl.Magenta) } rl.DrawText(string(c.letter), int32(c.x)-5, int32(c.y)-10, 32, rl.Black) DrawLineStrip(pts[i], 7, rl.Black) rl.DrawText(sChosen, 100, 525, 24, rl.Black) rl.DrawText(lChosen, 100, 565, 24, rl.Black) } rl.EndDrawing() } rl.CloseWindow() }
742Honeycombs
0go
smhqa
import java.util.*; abstract class HuffmanTree implements Comparable<HuffmanTree> { public final int frequency;
736Huffman coding
9java
yjt6g
8 * .Machine$sizeof.long
735Host introspection
13r
5w2uy
function identity($length) { return array_map(function($key, $value) {$value[$key] = 1; return $value;}, range(0, $length-1), array_fill(0, $length, array_fill(0,$length, 0))); } function print_identity($identity) { echo implode(PHP_EOL, array_map(function ($value) {return implode(' ', $value);}, $identity)); } print_identity(identity(10));
730Identity matrix
12php
pfeba
<?php echo ; fscanf(STDIN, , $int1); if(!is_numeric($int1)) { echo ; exit(1); } echo ; fscanf(STDIN, , $int2); if(!is_numeric($int2)) { echo ; exit(1); } if($int1 < $int2) echo ; if($int1 == $int2) echo ; if($int1 > $int2) echo ; ?>
725Integer comparison
12php
xydw5
import Data.Char (toUpper) import Data.Function (on) import Data.List (zipWith4) import System.Exit import System.Random import Graphics.Gloss import Graphics.Gloss.Data.Vector import Graphics.Gloss.Geometry import Graphics.Gloss.Interface.IO.Game import System.Random.Shuffle data Hex = Hex { hLetter :: Char , hSelected :: Bool , hPath :: Path , hCenter :: Point } data World = World { wHexes :: [Hex] , wString :: String } addV, subV :: Vector -> Vector -> Vector addV (a, b) (x, y) = (a + x, b + y) subV (a, b) (x, y) = (a - x, b - y) translateP :: Vector -> Path -> Path translateP v = map (addV v) translateV :: Vector -> Picture -> Picture translateV (x, y) p = translate x y p lightblue, darkblue :: Color lightblue = makeColor 0.5 0.5 1.0 1.0 darkblue = makeColor 0.0 0.0 0.5 1.0 ngon :: Int -> Float -> Path ngon n radius = let angle = 2 * pi / fromIntegral n in map (mulSV radius . unitVectorAtAngle . (* angle) . fromIntegral) [0..(n - 1)] inPolygon :: Point -> Path -> Bool inPolygon point path = all (>= 0) $ zipWith detV vas vbs where vas = zipWith subV (drop 1 $ cycle path) path vbs = map (subV point) path mkHexes :: RandomGen g => g -> Float -> World mkHexes gen radius = World hexes "" where letters = take 20 $ shuffle' ['A'..'Z'] 26 gen xs = concatMap (replicate 4) [-2..2] ys = cycle [-2..1] inRad = radius * (cos $ degToRad 30) yOff x = if ((floor x):: Int) `mod` 2 == 0 then inRad else 0 yStep = inRad * 2 xStep = radius * 1.5 centers = zipWith (\x y -> (x * xStep, yOff x + y * yStep)) xs ys paths = map (flip translateP $ ngon 6 radius) centers hexes = zipWith4 Hex letters (repeat False) paths centers drawHex:: Hex -> Picture drawHex (Hex letter selected path center) = pictures [hex, outline, letterPic] where hex = color hcolor $ polygon path outline = color blue $ lineLoop path letterPic = color lcolor $ translateV (addV (-10, -10) center) $ scale 0.25 0.25 $ text [letter] (hcolor, lcolor) = if selected then (darkblue, white) else (lightblue, black) drawWorld:: World -> Picture drawWorld (World hexes string) = pictures [pictures $ map drawHex hexes ,pictures $ map drawHighHex hexes ,color (light lightblue) $ textPic ,scale 1.05 1.05 $ textPic] where drawHighHex hex = color black $ scale 1.05 1.05 $ lineLoop $ hPath hex textPic = translateV (-130, -175) $ scale 0.15 0.15 $ text string handleInput:: Event -> World -> IO World handleInput event world@(World hexes string) = case event of EventKey key Down _ point -> case key of SpecialKey KeyEsc -> exitSuccess Char char -> hCond (\hex -> hLetter hex == toUpper char) MouseButton _ -> hCond (\hex -> inPolygon point $ hPath hex) _ -> return world _ -> return world where checkWorld w = if all hSelected $ wHexes w then exitSuccess else return w hCond cond = checkWorld $ World newHexes newString where newHexes = flip map hexes (\hex -> if cond hex then hex {hSelected = True} else hex) diff = map fst $ filter (uncurry ((/=) `on` hSelected)) $ zip hexes newHexes newString = case diff of [] -> string (hex:_) -> string ++ [hLetter hex] main:: IO () main = do stdGen <- getStdGen playIO (InWindow "Honeycombs" (500, 500) (100, 100)) white 60 (mkHexes stdGen 30) (return . drawWorld) handleInput (\_ x -> return x)
742Honeycombs
8haskell
9kimo
function HuffmanEncoding(str) { this.str = str; var count_chars = {}; for (var i = 0; i < str.length; i++) if (str[i] in count_chars) count_chars[str[i]] ++; else count_chars[str[i]] = 1; var pq = new BinaryHeap(function(x){return x[0];}); for (var ch in count_chars) pq.push([count_chars[ch], ch]); while (pq.size() > 1) { var pair1 = pq.pop(); var pair2 = pq.pop(); pq.push([pair1[0]+pair2[0], [pair1[1], pair2[1]]]); } var tree = pq.pop(); this.encoding = {}; this._generate_encoding(tree[1], ""); this.encoded_string = "" for (var i = 0; i < this.str.length; i++) { this.encoded_string += this.encoding[str[i]]; } } HuffmanEncoding.prototype._generate_encoding = function(ary, prefix) { if (ary instanceof Array) { this._generate_encoding(ary[0], prefix + "0"); this._generate_encoding(ary[1], prefix + "1"); } else { this.encoding[ary] = prefix; } } HuffmanEncoding.prototype.inspect_encoding = function() { for (var ch in this.encoding) { print("'" + ch + "': " + this.encoding[ch]) } } HuffmanEncoding.prototype.decode = function(encoded) { var rev_enc = {}; for (var ch in this.encoding) rev_enc[this.encoding[ch]] = ch; var decoded = ""; var pos = 0; while (pos < encoded.length) { var key = "" while (!(key in rev_enc)) { key += encoded[pos]; pos++; } decoded += rev_enc[key]; } return decoded; }
736Huffman coding
10javascript
21mlr
word_size = 42.size * 8 puts bytes = [1].pack('S').unpack('C*') byte_order = (bytes[0] == 0? 'big': 'little') + ' endian' puts
735Host introspection
14ruby
horjx
(ns rosettacode.hofstader-conway (:use [clojure.math.numeric-tower:only [expt]])) (def conway (memoize (fn [x] (if (< x 3) 1 (+ (-> x dec conway conway) (->> x dec conway (- x) conway)))))) (let [N (drop 1 (range)) pow2 (map #(expt 2 %) N) groups (partition-by (fn [x] (filter #(> % x) pow2)) N) maxima (->> (map #(map conway %) groups) (map #(map / %2 %1) groups) (map #(apply max %))) m20 (take 20 maxima)] (println (take 4 maxima) "\n" (apply >= m20) "\n" (map double m20)))
743Hofstadter-Conway $10,000 sequence
6clojure
uetvi
(defn hickerson "Hickerson number, calculated with BigDecimals and manually-entered high-precision value for ln(2)." [n] (let [n! (apply *' (range 1M (inc n)))] (.divide n! (*' 2 (.pow 0.693147180559945309417232121458M (inc n))) 30 BigDecimal/ROUND_HALF_UP))) (defn almost-integer? "Tests whether the first digit after the decimal is 0 or 9." [x] (let [first-digit (int (mod (.divide (*' x 10) 1.0M 0 BigDecimal/ROUND_DOWN) 10))] (or (= 0 first-digit) (= 9 first-digit)))) (doseq [n (range 1 18):let [h (hickerson n)]] (println (format "%2d%24.5f" n h) (if (almost-integer? h) "almost integer" "NOT almost integer")))
746Hickerson series of almost integers
6clojure
j867m
#[derive(Copy, Clone, Debug)] enum Endianness { Big, Little, } impl Endianness { fn target() -> Self { #[cfg(target_endian = "big")] { Endianness::Big } #[cfg(not(target_endian = "big"))] { Endianness::Little } } } fn main() { println!("Word size: {} bytes", std::mem::size_of::<usize>()); println!("Endianness: {:?}", Endianness::target()); }
735Host introspection
15rust
ki7h5
import java.nio.ByteOrder object ShowByteOrder extends App { println(ByteOrder.nativeOrder()) println(s"Word size: ${System.getProperty("sun.arch.data.model")}") println(s"Endianness: ${System.getProperty("sun.cpu.endian")}") }
735Host introspection
16scala
1fkpf
use Sys::Hostname; $name = hostname;
737Hostname
2perl
4xl5d
import java.util.* abstract class HuffmanTree(var freq: Int): Comparable<HuffmanTree> { override fun compareTo(other: HuffmanTree) = freq - other.freq } class HuffmanLeaf(freq: Int, var value: Char): HuffmanTree(freq) class HuffmanNode(var left: HuffmanTree, var right: HuffmanTree): HuffmanTree(left.freq + right.freq) fun buildTree(charFreqs: IntArray): HuffmanTree { val trees = PriorityQueue<HuffmanTree>() charFreqs.forEachIndexed { index, freq -> if(freq > 0) trees.offer(HuffmanLeaf(freq, index.toChar())) } assert(trees.size > 0) while (trees.size > 1) { val a = trees.poll() val b = trees.poll() trees.offer(HuffmanNode(a, b)) } return trees.poll() } fun printCodes(tree: HuffmanTree, prefix: StringBuffer) { when(tree) { is HuffmanLeaf -> println("${tree.value}\t${tree.freq}\t$prefix") is HuffmanNode -> {
736Huffman coding
11kotlin
f5odo
echo $_SERVER['HTTP_HOST'];
737Hostname
12php
i2qov
let s = "1234" if let x = Int(s) { print("\(x + 1)") }
727Increment a numerical string
17swift
1tspt
import 'dart:io'; void main(){ var url = 'http:
741HTTP
18dart
x6jwh
int main() { int i, flip, *q = (int*)malloc(sizeof(int) * N) - 1; q[1] = q[2] = 1; for (i = 3; i <= N; i++) q[i] = q[i - q[i - 1]] + q[i - q[i - 2]]; for (i = 1; i <= 10; i++) printf(, q[i], i == 10 ? '\n' : ' '); printf(, q[1000]); for (flip = 0, i = 1; i < N; i++) flip += q[i] > q[i + 1]; printf(, flip); return 0; }
749Hofstadter Q sequence
5c
rsdg7
package main import ( "fmt" "sort" "sync" "time" )
744History variables
0go
atu1f
import java.awt.*; import java.awt.event.*; import javax.swing.*; public class Honeycombs extends JFrame { public static void main(String[] args) { SwingUtilities.invokeLater(() -> { JFrame f = new Honeycombs(); f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); f.setVisible(true); }); } public Honeycombs() { add(new HoneycombsPanel(), BorderLayout.CENTER); setTitle("Honeycombs"); setResizable(false); pack(); setLocationRelativeTo(null); } } class HoneycombsPanel extends JPanel { Hexagon[] comb; public HoneycombsPanel() { setPreferredSize(new Dimension(600, 500)); setBackground(Color.white); setFocusable(true); addMouseListener(new MouseAdapter() { @Override public void mousePressed(MouseEvent e) { for (Hexagon hex : comb) if (hex.contains(e.getX(), e.getY())) { hex.setSelected(); break; } repaint(); } }); addKeyListener(new KeyAdapter() { @Override public void keyPressed(KeyEvent e) { for (Hexagon hex : comb) if (hex.letter == Character.toUpperCase(e.getKeyChar())) { hex.setSelected(); break; } repaint(); } }); char[] letters = "LRDGITPFBVOKANUYCESM".toCharArray(); comb = new Hexagon[20]; int x1 = 150, y1 = 100, x2 = 225, y2 = 143, w = 150, h = 87; for (int i = 0; i < comb.length; i++) { int x, y; if (i < 12) { x = x1 + (i % 3) * w; y = y1 + (i / 3) * h; } else { x = x2 + (i % 2) * w; y = y2 + ((i - 12) / 2) * h; } comb[i] = new Hexagon(x, y, w / 3, letters[i]); } requestFocus(); } @Override public void paintComponent(Graphics gg) { super.paintComponent(gg); Graphics2D g = (Graphics2D) gg; g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); g.setFont(new Font("SansSerif", Font.BOLD, 30)); g.setStroke(new BasicStroke(3)); for (Hexagon hex : comb) hex.draw(g); } } class Hexagon extends Polygon { final Color baseColor = Color.yellow; final Color selectedColor = Color.magenta; final char letter; private boolean hasBeenSelected; Hexagon(int x, int y, int halfWidth, char c) { letter = c; for (int i = 0; i < 6; i++) addPoint((int) (x + halfWidth * Math.cos(i * Math.PI / 3)), (int) (y + halfWidth * Math.sin(i * Math.PI / 3))); getBounds(); } void setSelected() { hasBeenSelected = true; } void draw(Graphics2D g) { g.setColor(hasBeenSelected ? selectedColor : baseColor); g.fillPolygon(this); g.setColor(Color.black); g.drawPolygon(this); g.setColor(hasBeenSelected ? Color.black : Color.red); drawCenteredString(g, String.valueOf(letter)); } void drawCenteredString(Graphics2D g, String s) { FontMetrics fm = g.getFontMetrics(); int asc = fm.getAscent(); int dec = fm.getDescent(); int x = bounds.x + (bounds.width - fm.stringWidth(s)) / 2; int y = bounds.y + (asc + (bounds.height - (asc + dec)) / 2); g.drawString(s, x, y); } }
742Honeycombs
9java
t4xf9
package main import ( "fmt" "math" "os" ) func getnum(prompt string) (r float64) { fmt.Print(prompt) if _, err := fmt.Scan(&r); err != nil { fmt.Println(err) os.Exit(-1) } return } func main() { lat := getnum("Enter latitude => ") lng := getnum("Enter longitude => ") ref := getnum("Enter legal meridian => ") slat := math.Sin(lat * math.Pi / 180) diff := lng - ref fmt.Println("\n sine of latitude: ", slat) fmt.Println(" diff longitude: ", diff) fmt.Println("\nHour, sun hour angle, dial hour line angle from 6am to 6pm") for h := -6.; h <= 6; h++ { hra := 15*h - diff s, c := math.Sincos(hra * math.Pi / 180) hla := math.Atan2(slat*s, c) * 180 / math.Pi fmt.Printf("%2.0f%8.3f%8.3f\n", h, hra, hla) } }
739Horizontal sundial calculations
0go
f5sd0
local build_freqtable = function (data) local freq = { } for i = 1, #data do local cur = string.sub (data, i, i) local count = freq [cur] or 0 freq [cur] = count + 1 end local nodes = { } for w, f in next, freq do nodes [#nodes + 1] = { word = w, freq = f } end table.sort (nodes, function (a, b) return a.freq > b.freq end)
736Huffman coding
1lua
t4ifn
import Data.IORef newtype HVar a = HVar (IORef [a]) newHVar :: a -> IO (HVar a) newHVar value = fmap HVar (newIORef [value]) readHVar :: HVar a -> IO a readHVar (HVar ref) = fmap head (readIORef ref) writeHVar :: a -> HVar a -> IO () writeHVar value (HVar ref) = modifyIORef ref (value:) undoHVar :: HVar a -> IO () undoHVar (HVar ref) = do (_: history) <- readIORef ref writeIORef ref history getHistory :: HVar a -> IO [a] getHistory (HVar ref) = readIORef ref main :: IO () main = do var <- newHVar 0 writeHVar 1 var writeHVar 2 var writeHVar 3 var getHistory var >>= print undoHVar var undoHVar var undoHVar var
744History variables
8haskell
zgwt0
null
742Honeycombs
11kotlin
olp8z
a = input('Enter value of a: ') b = input('Enter value of b: ') if a < b: print 'a is less than b' elif a > b: print 'a is greater than b' elif a == b: print 'a is equal to b'
725Integer comparison
3python
l17cv
import java.util.Collections; import java.util.LinkedList; import java.util.List; public class IntegerWithHistory { private final List<Integer> history; public IntegerWithHistory(Integer value) { history = new LinkedList<>(); history.add(value); } public void set(Integer value) {
744History variables
9java
olk8d
roundDec :: Int -> Double -> Double roundDec d = (/ 10.0 ^ d) . fromIntegral . round . (* 10.0 ^ d) radToDegr = ((180 / pi) *) degrToRad = ((pi / 180) *) main = do let lat = -4.95 long = -150.5 legalMerid = -150 sinOfLat = sin $ degrToRad lat diff = legalMerid - long (putStrLn . unlines) [ "Latitude " ++ show lat , "Longitude " ++ show long , "Legal meridian " ++ show legalMerid , "Sine of latitude " ++ show (roundDec 6 sinOfLat) , "Diff longitude " ++ show (-diff) , "hour sun hour angle dial hour line angle" ] mapM_ (\h -> let sha = diff + 15 * h dhla = radToDegr . atan . (sinOfLat *) . tan $ degrToRad sha in putStrLn $ take 7 (show h ++ repeat ' ') ++ take 16 (show (roundDec 3 sha) ++ repeat ' ') ++ " " ++ show (roundDec 3 dhla)) [-6,-5 .. 6]
739Horizontal sundial calculations
8haskell
4x95s
import socket host = socket.gethostname()
737Hostname
3python
gq24h
Sys.info()[["nodename"]]
737Hostname
13r
vam27
def identity(size): matrix = [[0]*size for i in range(size)] for i in range(size): matrix[i][i] = 1 for rows in matrix: for elements in rows: print elements, print
730Identity matrix
3python
6j93w
print("insert number a") a <- scan(what=numeric(0), nmax=1) print("insert number b") b <- scan(what=numeric(0), nmax=1) if ( a < b ) { print("a is less than b") } else if ( a > b ) { print("a is greater than b") } else if ( a == b ) { print("a and b are the same") }
725Integer comparison
13r
yh56h
(defn qs [q] (let [n (count q)] (condp = n 0 [1] 1 [1 1] (conj q (+ (q (- n (q (- n 1)))) (q (- n (q (- n 2))))))))) (defn qfirst [n] (-> (iterate qs []) (nth n))) (println "first 10:" (qfirst 10)) (println "1000th:" (last (qfirst 1000))) (println "extra credit:" (->> (qfirst 100000) (partition 2 1) (filter #(apply > %)) count))
749Hofstadter Q sequence
6clojure
bn6kz
package main import ( "fmt" "math/big" ) func main() { ln2, _ := new(big.Rat).SetString("0.6931471805599453094172") h := big.NewRat(1, 2) h.Quo(h, ln2) var f big.Rat var w big.Int for i := int64(1); i <= 17; i++ { h.Quo(h.Mul(h, f.SetInt64(i)), ln2) w.Quo(h.Num(), h.Denom()) f.Sub(h, f.SetInt(&w)) y, _ := f.Float64() d := fmt.Sprintf("%.3f", y) fmt.Printf("n:%2d h:%18d%s Nearly integer:%t\n", i, &w, d[1:], d[2] == '0' || d[2] == '9') } }
746Hickerson series of almost integers
0go
8c70g
char response[] = ; int main() { int one = 1, client_fd; struct sockaddr_in svr_addr, cli_addr; socklen_t sin_len = sizeof(cli_addr); int sock = socket(AF_INET, SOCK_STREAM, 0); if (sock < 0) err(1, ); setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, &one, sizeof(int)); int port = 8080; svr_addr.sin_family = AF_INET; svr_addr.sin_addr.s_addr = INADDR_ANY; svr_addr.sin_port = htons(port); if (bind(sock, (struct sockaddr *) &svr_addr, sizeof(svr_addr)) == -1) { close(sock); err(1, ); } listen(sock, 5); while (1) { client_fd = accept(sock, (struct sockaddr *) &cli_addr, &sin_len); printf(); if (client_fd == -1) { perror(); continue; } write(client_fd, response, sizeof(response) - 1); close(client_fd); } }
750Hello world/Web server
5c
8c504
null
744History variables
11kotlin
x6gws
null
744History variables
1lua
qyrx0
package main import "fmt" func horner(x int64, c []int64) (acc int64) { for i := len(c) - 1; i >= 0; i-- { acc = acc*x + c[i] } return } func main() { fmt.Println(horner(3, []int64{-19, 7, -4, 6})) }
740Horner's rule for polynomial evaluation
0go
mhnyi
def hornersRule = { coeff, x -> coeff.reverse().inject(0) { accum, c -> (accum * x) + c } }
740Horner's rule for polynomial evaluation
7groovy
t4sfh
package main import "github.com/fogleman/gg" var points []gg.Point const width = 64 func hilbert(x, y, lg, i1, i2 int) { if lg == 1 { px := float64(width-x) * 10 py := float64(width-y) * 10 points = append(points, gg.Point{px, py}) return } lg >>= 1 hilbert(x+i1*lg, y+i1*lg, lg, i1, 1-i2) hilbert(x+i2*lg, y+(1-i2)*lg, lg, i1, i2) hilbert(x+(1-i1)*lg, y+(1-i1)*lg, lg, i1, i2) hilbert(x+(1-i2)*lg, y+i2*lg, lg, 1-i1, i2) } func main() { hilbert(0, 0, width, 0, 0) dc := gg.NewContext(650, 650) dc.SetRGB(0, 0, 0)
748Hilbert curve
0go
bnykh
require 'socket' host = Socket.gethostname
737Hostname
14ruby
70uri
diag(3)
730Identity matrix
13r
f43dc
import Data.Number.CReal import qualified Data.Number.CReal as C hickerson :: Int -> C.CReal hickerson n = (fromIntegral $ product [1..n]) / (2 * (log 2 ^ (n + 1))) charAfter :: Char -> String -> Char charAfter ch string = ( dropWhile (/= ch) string ) !! 1 isAlmostInteger :: C.CReal -> Bool isAlmostInteger = (`elem` ['0', '9']) . charAfter '.' . show checkHickerson :: Int -> String checkHickerson n = show $ (n, hickerson n, isAlmostInteger $ hickerson n) main :: IO () main = mapM_ putStrLn $ map checkHickerson [1..18]
746Hickerson series of almost integers
8haskell
lp8ch
myDoc = ''' Single-quoted heredocs allows no '#{foo}' interpolation. This behavior is similar to single-quoted strings. ''' doc2 = """ However, double-quoted heredocs *do* allow these. See it in action: Content: "#{myDoc}" """ console.log doc2
751Here document
6clojure
nvgik
horner :: (Num a) => a -> [a] -> a horner x = foldr (\a b -> a + b*x) 0 main = print $ horner 3 [-19, 7, -4, 6]
740Horner's rule for polynomial evaluation
8haskell
kiuh0
import Data.Bool (bool) import Data.Tree rule :: Char -> String rule c = case c of 'a' -> "daab" 'b' -> "cbba" 'c' -> "bccd" 'd' -> "addc" _ -> [] vectors :: Char -> [(Int, Int)] vectors c = case c of '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)] _ -> [] main :: IO () main = do let w = 1024 putStrLn $ svgFromPoints w $ hilbertPoints w (hilbertTree 6) hilbertTree :: Int -> Tree Char hilbertTree n = let go tree = let c = rootLabel tree xs = subForest tree in Node c (bool (go <$> xs) (flip Node [] <$> rule c) (null xs)) seed = Node 'a' [] in bool seed (iterate go seed !! pred n) (0 < n) hilbertPoints :: Int -> Tree Char -> [(Int, Int)] hilbertPoints w tree = let go r xy tree = let d = quot r 2 f g x = g xy + (d * g x) centres = ((,) . f fst) <*> f snd <$> vectors (rootLabel tree) xs = subForest tree in bool (concat $ zipWith (go d) centres xs) centres (null xs) r = quot w 2 in go r (r, r) tree svgFromPoints :: Int -> [(Int, Int)] -> String svgFromPoints w xys = let sw = show w points = (unwords . fmap (((++) . show . fst) <*> ((' ':) . show . snd))) xys in unlines [ "<svg xmlns=\"http://www.w3.org/2000/svg\"" , unwords ["width=\"512\" height=\"512\" viewBox=\"5 5", sw, sw, "\"> "] , "<path d=\"M" ++ points ++ "\" " , "stroke-width=\"2\" stroke=\"red\" fill=\"transparent\"/>" , "</svg>" ]
748Hilbert curve
8haskell
duhn4
use warnings; use strict; use Tk; use List::Util qw(shuffle); sub altitude { sqrt(3/4) * shift; } sub polygon_coordinates { my ($x, $y, $size) = @_; my $alt = altitude($size); return ($x - $size, $y, $x - ($size / 2), $y - $alt, $x + ($size / 2), $y - $alt, $x + $size, $y, $x + ($size / 2), $y + $alt, $x - ($size / 2), $y + $alt, ); } { my %changed; sub change { my ($canvas, $id, $letter_id) = @_; return sub { $canvas->itemconfigure($id, -fill => 'magenta'); $canvas->itemconfigure($letter_id, -fill => 'black'); undef $changed{$id}; if (20 == keys %changed) { print "All letters pressed.\n"; $canvas->MainWindow->after(10, sub { exit }); } } } } { my @letters = (shuffle('A' .. 'Z'))[1 .. 20]; sub comb { my ($canvas, $fromx, $fromy, $size, $count) = @_; for (my $x = $fromx; $x < 3 * $count * $size; $x += 3 * $size) { for (my $y = $fromy; $y < 7.5 * $size; $y += 2 * altitude($size)) { my $id = $canvas->createPolygon( polygon_coordinates($x, $y, $size), -outline => 'black', -fill => 'yellow', -width => 2, ); my $letter = shift @letters; my $letter_id = $canvas->createText($x, $y, -fill => 'red', -text => $letter, -font => "{sans} " . ($size * 0.9), ); $canvas->MainWindow->bind('all', lc $letter, change($canvas, $id, $letter_id)); $canvas->bind($_, '<Button-1>', change($canvas, $id, $letter_id)) for $id, $letter_id; } } } } my $size = 36; my $mw = 'MainWindow'->new(-title => "Honeycombs"); my $canvas = $mw->Canvas(-width => 8 * $size, -height => 8 * $size, )->pack; comb($canvas, $size, $size, $size, 3); comb($canvas, $size * 2.5, $size + altitude($size), $size, 2); my $btn = $mw->Button(-text => 'Quit', -underline => 0, -command => sub { exit }, )->pack; $mw->bind('<Alt-q>', sub { $btn->invoke }); MainLoop();
742Honeycombs
2perl
gqy4e
fn main() { match hostname::get_hostname() { Some(host) => println!("hostname: {}", host), None => eprintln!("Could not get hostname!"), } }
737Hostname
15rust
j8572
println(java.net.InetAddress.getLocalHost.getHostName)
737Hostname
16scala
bnrk6
import java.math.*; public class Hickerson { final static String LN2 = "0.693147180559945309417232121458"; public static void main(String[] args) { for (int n = 1; n <= 17; n++) System.out.printf("%2s is almost integer:%s%n", n, almostInteger(n)); } static boolean almostInteger(int n) { BigDecimal a = new BigDecimal(LN2); a = a.pow(n + 1).multiply(BigDecimal.valueOf(2)); long f = n; while (--n > 1) f *= n; BigDecimal b = new BigDecimal(f); b = b.divide(a, MathContext.DECIMAL128); BigInteger c = b.movePointRight(1).toBigInteger().mod(BigInteger.TEN); return c.toString().matches("0|9"); } }
746Hickerson series of almost integers
9java
3rezg
typedef struct{ int a,b,c; int perimeter; double area; }triangle; typedef struct elem{ triangle t; struct elem* next; }cell; typedef cell* list; void addAndOrderList(list *a,triangle t){ list iter,temp; int flag = 0; if(*a==NULL){ *a = (list)malloc(sizeof(cell)); (*a)->t = t; (*a)->next = NULL; } else{ temp = (list)malloc(sizeof(cell)); iter = *a; while(iter->next!=NULL){ if(((iter->t.area<t.area)||(iter->t.area==t.area && iter->t.perimeter<t.perimeter)||(iter->t.area==t.area && iter->t.perimeter==t.perimeter && iter->t.a<=t.a)) && (iter->next==NULL||(t.area<iter->next->t.area || t.perimeter<iter->next->t.perimeter || t.a<iter->next->t.a))){ temp->t = t; temp->next = iter->next; iter->next = temp; flag = 1; break; } iter = iter->next; } if(flag!=1){ temp->t = t; temp->next = NULL; iter->next = temp; } } } int gcd(int a,int b){ if(b!=0) return gcd(b,a%b); return a; } void calculateArea(triangle *t){ (*t).perimeter = (*t).a + (*t).b + (*t).c; (*t).area = sqrt(0.5*(*t).perimeter*(0.5*(*t).perimeter - (*t).a)*(0.5*(*t).perimeter - (*t).b)*(0.5*(*t).perimeter - (*t).c)); } list generateTriangleList(int maxSide,int *count){ int a,b,c; triangle t; list herons = NULL; *count = 0; for(a=1;a<=maxSide;a++){ for(b=1;b<=a;b++){ for(c=1;c<=b;c++){ if(c+b > a && gcd(gcd(a,b),c)==1){ t = (triangle){a,b,c}; calculateArea(&t); if(t.area/(int)t.area == 1){ addAndOrderList(&herons,t); (*count)++; } } } } } return herons; } void printList(list a,int limit,int area){ list iter = a; int count = 1; printf(); while(iter!=NULL && count!=limit+1){ if(area==-1 ||(area==iter->t.area)){ printf(,iter->t.a,iter->t.b,iter->t.c,iter->t.perimeter,(int)iter->t.area); count++; } iter = iter->next; } } int main(int argC,char* argV[]) { int count; list herons = NULL; if(argC!=4) printf(,argV[0]); else{ herons = generateTriangleList(atoi(argV[1]),&count); printf(,count); (atoi(argV[3])==-1)?printf(,argV[2]):printf(,argV[3]); printList(herons,atoi(argV[2]),atoi(argV[3])); free(herons); } return 0; }
752Heronian triangles
5c
olu80
(ns goodbye-world.handler (:require [compojure.core:refer:all] [compojure.handler:as handler] [compojure.route:as route])) (defroutes app-routes (GET "/" [] "Goodbye, World!") (route/resources "/") (route/not-found "Not Found")) (def app (handler/site app-routes))
750Hello world/Web server
6clojure
f5jdm
package main import "fmt" var ffr, ffs func(int) int
747Hofstadter Figure-Figure sequences
0go
218l7
import java.util.Scanner; public class Sundial { public static void main(String[] args) { double lat, slat, lng, ref; Scanner sc = new Scanner(System.in); System.out.print("Enter latitude: "); lat = sc.nextDouble(); System.out.print("Enter longitude: "); lng = sc.nextDouble(); System.out.print("Enter legal meridian: "); ref = sc.nextDouble(); System.out.println(); slat = Math.sin(Math.toRadians(lat)); System.out.printf("sine of latitude:%.3f\n", slat); System.out.printf("diff longitude:%.3f\n\n", lng - ref); System.out.printf("Hour, sun hour angle, dial hour line angle from 6am to 6pm\n"); for (int h = -6; h <= 6; h++) { double hla, hra, hraRad; hra = 15.0 * h; hra = hra - lng + ref; hraRad = Math.toRadians(hra); hla = Math.toDegrees(Math.atan2(Math.sin(hraRad)*Math.sin(Math.toRadians(lat)), Math.cos(hraRad))); System.out.printf("HR=%3d; \t HRA=%7.3f; \t HLA=%7.3f\n", h, hra, hla); } } }
739Horizontal sundial calculations
9java
cbt9h
int main() { fprintf(stderr, ); fputs(, stderr); return 0; }
753Hello world/Standard error
5c
1fzpj
import Data.List (delete, sort) ffr :: Int -> Int ffr n = rl !! (n - 1) where rl = 1: fig 1 [2 ..] fig n (x:xs) = n_: fig n_ (delete n_ xs) where n_ = n + x ffs :: Int -> Int ffs n = rl !! n where rl = 2: figDiff 1 [2 ..] figDiff n (x:xs) = x: figDiff n_ (delete n_ xs) where n_ = n + x main :: IO () main = do print $ ffr <$> [1 .. 10] let i1000 = sort (fmap ffr [1 .. 40] ++ fmap ffs [1 .. 960]) print (i1000 == [1 .. 1000])
747Hofstadter Figure-Figure sequences
8haskell
atl1g
import java.util.ArrayList; import java.util.Collections; import java.util.List; public class Horner { public static void main(String[] args){ List<Double> coeffs = new ArrayList<Double>(); coeffs.add(-19.0); coeffs.add(7.0); coeffs.add(-4.0); coeffs.add(6.0); System.out.println(polyEval(coeffs, 3)); } public static double polyEval(List<Double> coefficients, double x) { Collections.reverse(coefficients); Double accumulator = coefficients.get(0); for (int i = 1; i < coefficients.size(); i++) { accumulator = (accumulator * x) + (Double) coefficients.get(i); } return accumulator; } }
740Horner's rule for polynomial evaluation
9java
4xm58
null
748Hilbert curve
9java
sm5q0
import java.lang.Math.atan2 import java.lang.Math.cos import java.lang.Math.sin import java.lang.Math.toDegrees import java.lang.Math.toRadians
739Horizontal sundial calculations
11kotlin
3roz5
SELECT host_name FROM v$instance;
737Hostname
19sql
ath1t