code
stringlengths
1
46.1k
label
class label
1.18k classes
domain_label
class label
21 classes
index
stringlengths
4
5
void draw_line_antialias( image img, unsigned int x0, unsigned int y0, unsigned int x1, unsigned int y1, color_component r, color_component g, color_component b );
33Xiaolin Wu's line algorithm
5c
11pj
import System.IO import Text.Printf import Control.Monad writeDat filename x y xprec yprec = withFile filename WriteMode $ \h -> let writeLine = hPrintf h $ "%." ++ show xprec ++ "g\t%." ++ show yprec ++ "g\n" in zipWithM_ writeLine x y
30Write float arrays to a text file
8haskell
x0w4
require("LuaXML") local dom = xml.new("root") local element = xml.new("element") table.insert(element, "Some text here") dom:append(element) dom:save("dom.xml")
31XML/DOM serialization
1lua
g74j
package main import ( "fmt" "sort" "strconv" ) var games = [6]string{"12", "13", "14", "23", "24", "34"} var results = "000000" func nextResult() bool { if results == "222222" { return false } res, _ := strconv.ParseUint(results, 3, 32) results = fmt.Sprintf("%06s", strconv.FormatUint(res+1, 3)) return true } func main() { var points [4][10]int for { var records [4]int for i := 0; i < len(games); i++ { switch results[i] { case '2': records[games[i][0]-'1'] += 3 case '1': records[games[i][0]-'1']++ records[games[i][1]-'1']++ case '0': records[games[i][1]-'1'] += 3 } } sort.Ints(records[:]) for i := 0; i < 4; i++ { points[i][records[i]]++ } if !nextResult() { break } } fmt.Println("POINTS 0 1 2 3 4 5 6 7 8 9") fmt.Println("-------------------------------------------------------------") places := [4]string{"1st", "2nd", "3rd", "4th"} for i := 0; i < 4; i++ { fmt.Print(places[i], " place ") for j := 0; j < 10; j++ { fmt.Printf("%-5d", points[3-i][j]) } fmt.Println() } }
32World Cup group stage
0go
4g52
open(fname, 'w'){|f| f.write(str) }
29Write entire file
14ruby
1xpw
use std::fs::File; use std::io::Write; fn main() -> std::io::Result<()> { let data = "Sample text."; let mut file = File::create("filename.txt")?; write!(file, "{}", data)?; Ok(()) }
29Write entire file
15rust
aq14
import java.io.{File, PrintWriter} object Main extends App { val pw = new PrintWriter(new File("Flumberboozle.txt"),"UTF8"){ print("My zirconconductor short-circuited and I'm having trouble fixing this issue.\nI researched" + " online and they said that I need to connect my flumberboozle to the XKG virtual port, but I was" + " wondering if I also needed a galvanized tungsten retrothruster array? Maybe it'd help the" + " frictional radial anti-stabilizer vectronize from the flumberboozle to the XKG virtual port?") close()} }
29Write entire file
16scala
x8wg
const char *names[] = { , , , NULL }; const char *remarks[] = { , When chapman billies leave the street ...\, , NULL }; int main() { xmlDoc *doc = NULL; xmlNode *root = NULL, *node; const char **next; int a; doc = xmlNewDoc(); root = xmlNewNode(NULL, ); xmlDocSetRootElement(doc, root); for(next = names, a = 0; *next != NULL; next++, a++) { node = xmlNewNode(NULL, ); (void)xmlNewProp(node, , *next); xmlAddChild(node, xmlNewText(remarks[a])); xmlAddChild(root, node); } xmlElemDump(stdout, doc, root); xmlFreeDoc(doc); xmlCleanupParser(); return EXIT_SUCCESS; }
34XML/Output
5c
tndf4
import java.util.Arrays; public class GroupStage{
32World Cup group stage
9java
p1b3
import java.io.*; public class FloatArray { public static void writeDat(String filename, double[] x, double[] y, int xprecision, int yprecision) throws IOException { assert x.length == y.length; PrintWriter out = new PrintWriter(filename); for (int i = 0; i < x.length; i++) out.printf("%."+xprecision+"g\t%."+yprecision+"g\n", x[i], y[i]); out.close(); } public static void main(String[] args) { double[] x = {1, 2, 3, 1e11}; double[] y = new double[x.length]; for (int i = 0; i < x.length; i++) y[i] = Math.sqrt(x[i]); try { writeDat("sqrt.dat", x, y, 3, 5); } catch (IOException e) { System.err.println("writeDat: exception: "+e); } try { BufferedReader br = new BufferedReader(new FileReader("sqrt.dat")); String line; while ((line = br.readLine()) != null) System.out.println(line); } catch (IOException e) { } } }
30Write float arrays to a text file
9java
bak3
static void print_names(xmlNode *node) { xmlNode *cur_node = NULL; for (cur_node = node; cur_node; cur_node = cur_node->next) { if (cur_node->type == XML_ELEMENT_NODE) { if ( strcmp(cur_node->name, ) == 0 ) { xmlAttr *prop = NULL; if ( (prop = xmlHasProp(cur_node, )) != NULL ) { printf(, prop->children->content); } } } print_names(cur_node->children); } } const char *buffer = April\F\1989-01-02\ Bob\M\1990-03-04\ Chad\M\1991-05-06\ Dave\M\1992-07-08\ dog\Rover\ 1993-09-10\F\& ; int main() { xmlDoc *doc = NULL; xmlNode *root = NULL; doc = xmlReadMemory(buffer, strlen(buffer), NULL, NULL, 0); if ( doc != NULL ) { root = xmlDocGetRootElement(doc); print_names(root); xmlFreeDoc(doc); } xmlCleanupParser(); return 0; }
35XML/Input
5c
299lo
null
32World Cup group stage
11kotlin
7jr4
use strict; use warnings; use feature 'say'; use List::Util 'min'; my %cache; sub leven { my ($s, $t) = @_; return length($t) if $s eq ''; return length($s) if $t eq ''; $cache{$s}{$t} //= do { my ($s1, $t1) = (substr($s, 1), substr($t, 1)); (substr($s, 0, 1) eq substr($t, 0, 1)) ? leven($s1, $t1) : 1 + min( leven($s1, $t1), leven($s, $t1), leven($s1, $t ), ); }; } print "What is your name?"; my $name = <STDIN>; $name = 'Number 6'; say "What is your quest? Never mind that, I will call you '$name'"; say 'Hey! I am not a number, I am a free man!'; my @starters = grep { length() < 6 } my @words = grep { /.{2,}/ } split "\n", `cat unixdict.txt`; my(%used,@possibles,$guess); my $rounds = 0; my $word = say $starters[ rand $ while () { say "Word in play: $word"; $used{$word} = 1; @possibles = (); for my $w (@words) { next if abs(length($word) - length($w)) > 1; push @possibles, $w if leven($word, $w) == 1 and ! defined $used{$w}; } print "Your word? "; $guess = <STDIN>; chomp $guess; last unless grep { $guess eq $_ } @possibles; $rounds++; $word = $guess; } my $already = defined $used{$guess} ? " '$guess' was already played but" : ''; if (@possibles) { say "\nSorry $name,${already} one of <@possibles> would have continued the game." } else { say "\nGood job $name,${already} there were no possible words to play." } say "You made it through $rounds rounds.";
36Wordiff
2perl
w1pe6
function array1D(a, d) local m = {} for i=1,a do table.insert(m, d) end return m end function array2D(a, b, d) local m = {} for i=1,a do table.insert(m, array1D(b, d)) end return m end function fromBase3(num) local out = 0 for i=1,#num do local c = num:sub(i,i) local d = tonumber(c) out = 3 * out + d end return out end function toBase3(num) local ss = "" while num > 0 do local rem = num % 3 num = math.floor(num / 3) ss = ss .. tostring(rem) end return string.reverse(ss) end games = { "12", "13", "14", "23", "24", "34" } results = "000000" function nextResult() if results == "222222" then return false end local res = fromBase3(results) results = string.format("%06s", toBase3(res + 1)) return true end points = array2D(4, 10, 0) repeat local records = array1D(4, 0) for i=1,#games do if results:sub(i,i) == '2' then local j = tonumber(games[i]:sub(1,1)) records[j] = records[j] + 3 elseif results:sub(i,i) == '1' then local j = tonumber(games[i]:sub(1,1)) records[j] = records[j] + 1 j = tonumber(games[i]:sub(2,2)) records[j] = records[j] + 1 elseif results:sub(i,i) == '0' then local j = tonumber(games[i]:sub(2,2)) records[j] = records[j] + 3 end end table.sort(records) for i=1,#records do points[i][records[i]+1] = points[i][records[i]+1] + 1 end until not nextResult() print("POINTS 0 1 2 3 4 5 6 7 8 9") print("
32World Cup group stage
1lua
jh71
null
30Write float arrays to a text file
11kotlin
rhgo
from typing import List, Tuple, Dict, Set from itertools import cycle, islice from collections import Counter import re import random import urllib dict_fname = 'unixdict.txt' dict_url1 = 'http: dict_url2 = 'https: word_regexp = re.compile(r'^[a-z]{3,}$') def load_dictionary(fname: str=dict_fname) -> Set[str]: with open(fname) as f: return {lcase for lcase in (word.strip().lower() for word in f) if word_regexp.match(lcase)} def load_web_dictionary(url: str) -> Set[str]: words = urllib.request.urlopen(url).read().decode().strip().lower().split() return {word for word in words if word_regexp.match(word)} def get_players() -> List[str]: names = input('Space separated list of contestants: ') return [n.capitalize() for n in names.strip().split()] def is_wordiff(wordiffs: List[str], word: str, dic: Set[str], comment=True) -> bool: if word not in dic: if comment: print('That word is not in my dictionary') return False if word in wordiffs: if comment: print('That word was already used.') return False if len(word) < len(wordiffs[-1]): return is_wordiff_removal(word, wordiffs[-1], comment) elif len(word) > len(wordiffs[-1]): return is_wordiff_insertion(word, wordiffs[-1], comment) return is_wordiff_change(word, wordiffs[-1], comment) def is_wordiff_removal(word: str, prev: str, comment=True) -> bool: ... ans = word in {prev[:i] + prev[i+1:] for i in range(len(prev))} if not ans: if comment: print('Word is not derived from previous by removal of one letter.') return ans def is_wordiff_insertion(word: str, prev: str, comment=True) -> bool: diff = Counter(word) - Counter(prev) diffcount = sum(diff.values()) if diffcount != 1: if comment: print('More than one character insertion difference.') return False insert = list(diff.keys())[0] ans = word in {prev[:i] + insert + prev[i:] for i in range(len(prev) + 1)} if not ans: if comment: print('Word is not derived from previous by insertion of one letter.') return ans def is_wordiff_change(word: str, prev: str, comment=True) -> bool: ... diffcount = sum(w != p for w, p in zip(word, prev)) if diffcount != 1: if comment: print('More or less than exactly one character changed.') return False return True def could_have_got(wordiffs: List[str], dic: Set[str]): return (word for word in (dic - set(wordiffs)) if is_wordiff(wordiffs, word, dic, comment=False)) if __name__ == '__main__': dic = load_web_dictionary(dict_url2) dic_3_4 = [word for word in dic if len(word) in {3, 4}] start = random.choice(dic_3_4) wordiffs = [start] players = get_players() for name in cycle(players): word = input(f).strip() if is_wordiff(wordiffs, word, dic): wordiffs.append(word) else: print(f'YOU HAVE LOST {name}!') print(, ', '.join(islice(could_have_got(wordiffs, dic), 10)), '...') break
36Wordiff
3python
xa1wr
package raster import "math" func ipart(x float64) float64 { return math.Floor(x) } func round(x float64) float64 { return ipart(x + .5) } func fpart(x float64) float64 { return x - ipart(x) } func rfpart(x float64) float64 { return 1 - fpart(x) }
33Xiaolin Wu's line algorithm
0go
yy64
(use 'clojure.xml) (defn character-remarks-xml [characters remarks] (with-out-str (emit-element {:tag :CharacterRemarks, :attrs nil, :content (vec (for [item (map vector characters remarks)] {:tag :Character, :attrs {:name (item 0)}, :content [(item 1)]}) )})))
34XML/Output
6clojure
m36yq
use Math::Cartesian::Product; @scoring = (0, 1, 3); push @histo, [(0) x 10] for 1..4; push @aoa, [(0,1,2)] for 1..6; for $results (cartesian {@_} @aoa) { my @s; my @g = ([0,1],[0,2],[0,3],[1,2],[1,3],[2,3]); for (0..$ $r = $results->[$_]; $s[$g[$_][0]] += $scoring[$r]; $s[$g[$_][1]] += $scoring[2 - $r]; } my @ss = sort @s; $histo[$_][$ss[$_]]++ for 0..$ } $fmt = ('%3d ') x 10 . "\n"; printf $fmt, @$_ for reverse @histo;
32World Cup group stage
2perl
ftd7
filename = "file.txt" x = { 1, 2, 3, 1e11 } y = { 1, 1.4142135623730951, 1.7320508075688772, 316227.76601683791 }; xprecision = 3; yprecision = 5; fstr = "%."..tostring(xprecision).."f ".."%."..tostring(yprecision).."f\n" fp = io.open( filename, "w+" ) for i = 1, #x do fp:write( string.format( fstr, x[i], y[i] ) ) end io.close( fp )
30Write float arrays to a text file
1lua
7kru
use XML::Simple; print XMLout( { root => { element => "Some text here" } }, NoAttr => 1, RootName => "" );
31XML/DOM serialization
2perl
ido3
module Main (main) where import Codec.Picture (writePng) import Codec.Picture.Types (Image, MutableImage(..), Pixel, PixelRGB8(..), createMutableImage, unsafeFreezeImage, writePixel) import Control.Monad (void) import Control.Monad.Primitive (PrimMonad, PrimState) import Data.Foldable (foldlM) type MImage m px = MutableImage (PrimState m) px withMutableImage :: (Pixel px, PrimMonad m) => Int -> Int -> px -> (MImage m px -> m ()) -> m (Image px) withMutableImage w h px f = createMutableImage w h px >>= \m -> f m >> unsafeFreezeImage m plot :: (Pixel px, PrimMonad m) => MImage m px -> Int -> Int -> px -> m () plot = writePixel drawAntialiasedLine :: forall px m . (Pixel px, PrimMonad m) => MImage m px -> Int -> Int -> Int -> Int -> (Double -> px) -> m () drawAntialiasedLine m p1x p1y p2x p2y colour = do let steep = abs (p2y - p1y) > abs (p2x - p1x) ((p3x, p4x), (p3y, p4y)) = swapIf steep ((p1x, p2x), (p1y, p2y)) ((ax, ay), (bx, by)) = swapIf (p3x > p4x) ((p3x, p3y), (p4x, p4y)) dx = bx - ax dy = by - ay gradient = if dx == 0 then 1.0 else fromIntegral dy / fromIntegral dx let xpxl1 = ax yend1 = fromIntegral ay + gradient * fromIntegral (xpxl1 - ax) xgap1 = rfpart (fromIntegral ax + 0.5) endpoint steep xpxl1 yend1 xgap1 let xpxl2 = bx yend2 = fromIntegral by + gradient * fromIntegral (xpxl2 - bx) xgap2 = fpart (fromIntegral bx + 0.5) endpoint steep xpxl2 yend2 xgap2 let intery = yend1 + gradient void $ if steep then foldlM (\i x -> do plot m (ipart i) x (colour (rfpart i)) plot m (ipart i + 1) x (colour (fpart i)) pure $ i + gradient) intery [xpxl1 + 1..xpxl2 - 1] else foldlM (\i x -> do plot m x (ipart i) (colour (rfpart i)) plot m x (ipart i + 1) (colour (fpart i)) pure $ i + gradient) intery [xpxl1 + 1..xpxl2 - 1] where endpoint :: Bool -> Int -> Double -> Double -> m () endpoint True xpxl yend xgap = do plot m ypxl xpxl (colour (rfpart yend * xgap)) plot m (ypxl + 1) xpxl (colour (fpart yend * xgap)) where ypxl = ipart yend endpoint False xpxl yend xgap = do plot m xpxl ypxl (colour (rfpart yend * xgap)) plot m xpxl (ypxl + 1) (colour (fpart yend * xgap)) where ypxl = ipart yend swapIf :: Bool -> (a, a) -> (a, a) swapIf False p = p swapIf True (x, y) = (y, x) ipart :: Double -> Int ipart = truncate fpart :: Double -> Double fpart x | x > 0 = x - temp | otherwise = x - (temp + 1) where temp = fromIntegral (ipart x) rfpart :: Double -> Double rfpart x = 1 - fpart x main :: IO () main = do img <- withMutableImage 640 480 (PixelRGB8 0 0 0) $ \m@(MutableImage w h _) -> drawAntialiasedLine m 2 2 (w - 2) (h - 2) (\brightness -> let level = round (brightness * 255) in PixelRGB8 level level level) writePng "xiaolin-wu-algorithm.png" img
33Xiaolin Wu's line algorithm
8haskell
hhju
<?php $dom = new DOMDocument(); $dom->formatOutput = true; $root = $dom->createElement('root'); $element = $dom->createElement('element'); $element->appendChild($dom->createTextNode('Some text here')); $root->appendChild($element); $dom->appendChild($root); $xmlstring = $dom->saveXML();
31XML/DOM serialization
12php
rjge
const char*s = ; int main(){ puts(s); return 0; }
37Write language name in 3D ASCII
5c
w1bec
(import '(java.io ByteArrayInputStream)) (use 'clojure.xml) (def xml-text "<Students> <Student Name='April' Gender='F' DateOfBirth='1989-01-02' /> <Student Name='Bob' Gender='M' DateOfBirth='1990-03-04' /> <Student Name='Chad' Gender='M' DateOfBirth='1991-05-06' /> <Student Name='Dave' Gender='M' DateOfBirth='1992-07-08'> <Pet Type='dog' Name='Rover' /> </Student> <Student DateOfBirth='1993-09-10' Gender='F' Name='&#x00C9 </Students>") (def students (parse (-> xml-text .getBytes ByteArrayInputStream.)))
35XML/Input
6clojure
guu4f
from itertools import product, combinations, izip scoring = [0, 1, 3] histo = [[0] * 10 for _ in xrange(4)] for results in product(range(3), repeat=6): s = [0] * 4 for r, g in izip(results, combinations(range(4), 2)): s[g[0]] += scoring[r] s[g[1]] += scoring[2 - r] for h, v in izip(histo, sorted(s)): h[v] += 1 for x in reversed(histo): print x
32World Cup group stage
3python
tzfw
bool is_letter(char c) { return c >= 'a' && c <= 'z'; } int index(char c) { return c - 'a'; } void word_wheel(const char* letters, char central, int min_length, FILE* dict) { int max_count[LETTERS] = { 0 }; for (const char* p = letters; *p; ++p) { char c = *p; if (is_letter(c)) ++max_count[index(c)]; } char word[MAX_WORD + 1] = { 0 }; while (fgets(word, MAX_WORD, dict)) { int count[LETTERS] = { 0 }; for (const char* p = word; *p; ++p) { char c = *p; if (c == '\n') { if (p >= word + min_length && count[index(central)] > 0) printf(, word); } else if (is_letter(c)) { int i = index(c); if (++count[i] > max_count[i]) { break; } } else { break; } } } } int main(int argc, char** argv) { const char* dict = argc == 2 ? argv[1] : ; FILE* in = fopen(dict, ); if (in == NULL) { perror(dict); return 1; } word_wheel(, 'k', 3, in); fclose(in); return 0; }
38Word wheel
5c
cyz9c
import java.awt.*; import static java.lang.Math.*; import javax.swing.*; public class XiaolinWu extends JPanel { public XiaolinWu() { Dimension dim = new Dimension(640, 640); setPreferredSize(dim); setBackground(Color.white); } void plot(Graphics2D g, double x, double y, double c) { g.setColor(new Color(0f, 0f, 0f, (float)c)); g.fillOval((int) x, (int) y, 2, 2); } int ipart(double x) { return (int) x; } double fpart(double x) { return x - floor(x); } double rfpart(double x) { return 1.0 - fpart(x); } void drawLine(Graphics2D g, double x0, double y0, double x1, double y1) { boolean steep = abs(y1 - y0) > abs(x1 - x0); if (steep) drawLine(g, y0, x0, y1, x1); if (x0 > x1) drawLine(g, x1, y1, x0, y0); double dx = x1 - x0; double dy = y1 - y0; double gradient = dy / dx;
33Xiaolin Wu's line algorithm
9java
55uf
from xml.dom.minidom import getDOMImplementation dom = getDOMImplementation() document = dom.createDocument(None, , None) topElement = document.documentElement firstElement = document.createElement() topElement.appendChild(firstElement) textNode = document.createTextNode() firstElement.appendChild(textNode) xmlString = document.toprettyxml( * 4)
31XML/DOM serialization
3python
nfiz
null
33Xiaolin Wu's line algorithm
11kotlin
cc98
(use 'clj-figlet.core) (println (render-to-string (load-flf "ftp://ftp.figlet.org/pub/figlet/fonts/contributed/larry3d.flf") "Clojure"))
37Write language name in 3D ASCII
6clojure
8qw05
package main import ( "bytes" "fmt" "io/ioutil" "log" "strings" ) func contains(a []string, s string) bool { for _, e := range a { if e == s { return true } } return false } func oneAway(a, b string) bool { sum := 0 for i := 0; i < len(a); i++ { if a[i] != b[i] { sum++ } } return sum == 1 } func wordLadder(words []string, a, b string) { l := len(a) var poss []string for _, word := range words { if len(word) == l { poss = append(poss, word) } } todo := [][]string{{a}} for len(todo) > 0 { curr := todo[0] todo = todo[1:] var next []string for _, word := range poss { if oneAway(word, curr[len(curr)-1]) { next = append(next, word) } } if contains(next, b) { curr = append(curr, b) fmt.Println(strings.Join(curr, " -> ")) return } for i := len(poss) - 1; i >= 0; i-- { if contains(next, poss[i]) { copy(poss[i:], poss[i+1:]) poss[len(poss)-1] = "" poss = poss[:len(poss)-1] } } for _, s := range next { temp := make([]string, len(curr)) copy(temp, curr) temp = append(temp, s) todo = append(todo, temp) } } fmt.Println(a, "into", b, "cannot be done.") } func main() { b, err := ioutil.ReadFile("unixdict.txt") if err != nil { log.Fatal("Error reading file") } bwords := bytes.Fields(b) words := make([]string, len(bwords)) for i, bword := range bwords { words[i] = string(bword) } pairs := [][]string{ {"boy", "man"}, {"girl", "lady"}, {"john", "jane"}, {"child", "adult"}, } for _, pair := range pairs { wordLadder(words, pair[0], pair[1]) } }
39Word ladder
0go
xakwf
teams = [:a, :b, :c, :d] matches = teams.combination(2).to_a outcomes = [:win, :draw, :loss] gains = {win:[3,0], draw:[1,1], loss:[0,3]} places_histogram = Array.new(4) {Array.new(10,0)} outcomes.repeated_permutation(6).each do |outcome| results = Hash.new(0) outcome.zip(matches).each do |decision, (team1, team2)| results[team1] += gains[decision][0] results[team2] += gains[decision][1] end results.values.sort.reverse.each_with_index do |points, place| places_histogram[place][points] += 1 end end fmt = + *10 puts fmt % [, *0..9] puts fmt % [, *[]*10] places_histogram.each.with_index(1) {|hist,place| puts fmt % [place, *hist]}
32World Cup group stage
14ruby
36z7
require() include REXML (doc = Document.new) << XMLDecl.new root = doc.add_element('root') element = root.add_element('element') element.add_text('Some text here') serialized = String.new doc.write(serialized, 4) puts serialized
31XML/DOM serialization
14ruby
fzdr
val xml = <root><element>Some text here</element></root> scala.xml.XML.save(filename="output.xml", node=xml, enc="UTF-8", xmlDecl=true, doctype=null)
31XML/DOM serialization
16scala
6m31
import System.IO (readFile) import Control.Monad (foldM) import Data.List (intercalate) import qualified Data.Set as S distance :: String -> String -> Int distance s1 s2 = length $ filter not $ zipWith (==) s1 s2 wordLadders :: [String] -> String -> String -> [[String]] wordLadders dict start end | length start /= length end = [] | otherwise = [wordSpace] >>= expandFrom start >>= shrinkFrom end where wordSpace = S.fromList $ filter ((length start ==) . length) dict expandFrom s = go [[s]] where go (h:t) d | S.null d || S.null f = [] | end `S.member` f = [h:t] | otherwise = go (S.elems f:h:t) (d S.\\ f) where f = foldr (\w -> S.union (S.filter (oneStepAway w) d)) mempty h shrinkFrom = scanM (filter . oneStepAway) oneStepAway x = (1 ==) . distance x scanM f x = fmap snd . foldM g (x,[x]) where g (b, r) a = (\x -> (x, x:r)) <$> f b a wordLadder :: [String] -> String -> String -> [String] wordLadder d s e = case wordLadders d s e of [] -> [] h:_ -> h showChain [] = putStrLn "No chain" showChain ch = putStrLn $ intercalate " -> " ch main = do dict <- lines <$> readFile "unixdict.txt" showChain $ wordLadder dict "boy" "man" showChain $ wordLadder dict "girl" "lady" showChain $ wordLadder dict "john" "jane" showChain $ wordLadder dict "alien" "drool" showChain $ wordLadder dict "child" "adult"
39Word ladder
8haskell
yzn66
null
13Arrays
17swift
v82r
object GroupStage extends App {
32World Cup group stage
16scala
9cm5
use autodie; sub writedat { my ($filename, $x, $y, $xprecision, $yprecision) = @_; open my $fh, ">", $filename; for my $i (0 .. $ printf $fh "%.*g\t%.*g\n", $xprecision||3, $x->[$i], $yprecision||5, $y->[$i]; } close $fh; } my @x = (1, 2, 3, 1e11); my @y = map sqrt, @x; writedat("sqrt.dat", \@x, \@y);
30Write float arrays to a text file
2perl
dznw
import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.PriorityQueue; import java.util.Set; import java.util.stream.IntStream; public class WordLadder { private static int distance(String s1, String s2) { assert s1.length() == s2.length(); return (int) IntStream.range(0, s1.length()) .filter(i -> s1.charAt(i) != s2.charAt(i)) .count(); } private static void wordLadder(Map<Integer, Set<String>> words, String fw, String tw) { wordLadder(words, fw, tw, 8); } private static void wordLadder(Map<Integer, Set<String>> words, String fw, String tw, int limit) { if (fw.length() != tw.length()) { throw new IllegalArgumentException("From word and to word must have the same length"); } Set<String> ws = words.get(fw.length()); if (ws.contains(fw)) { List<String> primeList = new ArrayList<>(); primeList.add(fw); PriorityQueue<List<String>> queue = new PriorityQueue<>((chain1, chain2) -> { int cmp1 = Integer.compare(chain1.size(), chain2.size()); if (cmp1 == 0) { String last1 = chain1.get(chain1.size() - 1); int d1 = distance(last1, tw); String last2 = chain2.get(chain2.size() - 1); int d2 = distance(last2, tw); return Integer.compare(d1, d2); } return cmp1; }); queue.add(primeList); while (queue.size() > 0) { List<String> curr = queue.remove(); if (curr.size() > limit) { continue; } String last = curr.get(curr.size() - 1); for (String word : ws) { if (distance(last, word) == 1) { if (word.equals(tw)) { curr.add(word); System.out.println(String.join(" -> ", curr)); return; } if (!curr.contains(word)) { List<String> cp = new ArrayList<>(curr); cp.add(word); queue.add(cp); } } } } } System.err.printf("Cannot turn `%s` into `%s`%n", fw, tw); } public static void main(String[] args) throws IOException { Map<Integer, Set<String>> words = new HashMap<>(); for (String line : Files.readAllLines(Path.of("unixdict.txt"))) { Set<String> wl = words.computeIfAbsent(line.length(), HashSet::new); wl.add(line); } wordLadder(words, "boy", "man"); wordLadder(words, "girl", "lady"); wordLadder(words, "john", "jane"); wordLadder(words, "child", "adult"); wordLadder(words, "cat", "dog"); wordLadder(words, "lead", "gold"); wordLadder(words, "white", "black"); wordLadder(words, "bubble", "tickle", 12); } }
39Word ladder
9java
doqn9
package main import ( "bytes" "fmt" "io/ioutil" "log" "sort" "strings" ) func main() { b, err := ioutil.ReadFile("unixdict.txt") if err != nil { log.Fatal("Error reading file") } letters := "deegklnow" wordsAll := bytes.Split(b, []byte{'\n'})
38Word wheel
0go
w1keg
use strict; use warnings; sub plot { my ($x, $y, $c) = @_; printf "plot%d%d%.1f\n", $x, $y, $c if $c; } sub ipart { int shift; } sub round { int( 0.5 + shift ); } sub fpart { my $x = shift; $x - int $x; } sub rfpart { 1 - fpart(shift); } sub drawLine { my ($x0, $y0, $x1, $y1) = @_; my $plot = \&plot; if( abs($y1 - $y0) > abs($x1 - $x0) ) { $plot = sub { plot( @_[1, 0, 2] ) }; ($x0, $y0, $x1, $y1) = ($y0, $x0, $y1, $x1); } if( $x0 > $x1 ) { ($x0, $x1, $y0, $y1) = ($x1, $x0, $y1, $y0); } my $dx = $x1 - $x0; my $dy = $y1 - $y0; my $gradient = $dy / $dx; my @xends; my $intery; for my $xy ([$x0, $y0], [$x1, $y1]) { my ($x, $y) = @$xy; my $xend = round($x); my $yend = $y + $gradient * ($xend - $x); my $xgap = rfpart($x + 0.5); my $x_pixel = $xend; my $y_pixel = ipart($yend); push @xends, $x_pixel; $plot->($x_pixel, $y_pixel , rfpart($yend) * $xgap); $plot->($x_pixel, $y_pixel+1, fpart($yend) * $xgap); next if defined $intery; $intery = $yend + $gradient; } for my $x ( $xends[0] + 1 .. $xends[1] - 1 ) { $plot->($x, ipart ($intery), rfpart($intery)); $plot->($x, ipart ($intery)+1, fpart($intery)); $intery += $gradient; } } if( $0 eq __FILE__ ) { drawLine( 0, 1, 10, 2 ); } __END__
33Xiaolin Wu's line algorithm
2perl
xxw8
void main(){ print(""" XXX XX XXX XXXX X X X X X X X X X XXXX XXX X XXX X X X X X """.replaceAll('X','_/')); }
37Write language name in 3D ASCII
18dart
k7ghj
const char g_szClassName[] = ; LRESULT CALLBACK WndProc(HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam) { switch(msg) { case WM_CLOSE: DestroyWindow(hwnd); break; case WM_DESTROY: PostQuitMessage(0); break; default: return DefWindowProc(hwnd, msg, wParam, lParam); } return 0; } int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShow) { WNDCLASSEX wc; HWND hwnd[3]; MSG Msg; int i,x=0,y=0; char str[3][100]; int maxX = GetSystemMetrics(SM_CXSCREEN), maxY = GetSystemMetrics(SM_CYSCREEN); char messages[15][180] = {, , , , , , , , , , , , , }; wc.cbSize = sizeof(WNDCLASSEX); wc.style = 0; wc.lpfnWndProc = WndProc; wc.cbClsExtra = 0; wc.cbWndExtra = 0; wc.hInstance = hInstance; wc.hIcon = LoadIcon(NULL, IDI_APPLICATION); wc.hCursor = LoadCursor(NULL, IDC_ARROW); wc.hbrBackground = (HBRUSH)(COLOR_WINDOW+1); wc.lpszMenuName = NULL; wc.lpszClassName = g_szClassName; wc.hIconSm = LoadIcon(NULL, IDI_APPLICATION); if(!RegisterClassEx(&wc)) { MessageBox(NULL, , ,MB_ICONEXCLAMATION | MB_OK); return 0; } for(i=0;i<2;i++){ sprintf(str[i],,i+1); hwnd[i] = CreateWindow(g_szClassName,str[i],WS_OVERLAPPEDWINDOW,i*maxX/2 , 0, maxX/2-10, maxY/2-10,NULL, NULL, hInstance, NULL); if(hwnd[i] == NULL) { MessageBox(NULL, , ,MB_ICONEXCLAMATION | MB_OK); return 0; } ShowWindow(hwnd[i], nCmdShow); UpdateWindow(hwnd[i]); } for(i=0;i<6;i++){ MessageBox(NULL, messages[i], ,MB_APPLMODAL| MB_ICONINFORMATION | MB_OK); } if(hwnd[0]==hwnd[1]) MessageBox(NULL, , ,MB_APPLMODAL| MB_ICONINFORMATION | MB_OK); else MessageBox(NULL, , ,MB_APPLMODAL| MB_ICONINFORMATION | MB_OK); MessageBox(NULL, messages[6], ,MB_APPLMODAL| MB_ICONINFORMATION | MB_OK); ShowWindow(hwnd[0], SW_HIDE); MessageBox(NULL, messages[7], ,MB_APPLMODAL| MB_ICONINFORMATION | MB_OK); ShowWindow(hwnd[0], SW_SHOW); MessageBox(NULL, messages[8], ,MB_APPLMODAL| MB_ICONINFORMATION | MB_OK); ShowWindow(hwnd[1], SW_HIDE); MessageBox(NULL, messages[9], ,MB_APPLMODAL| MB_ICONINFORMATION | MB_OK); ShowWindow(hwnd[0], SW_MINIMIZE); MessageBox(NULL, messages[10], ,MB_APPLMODAL| MB_ICONINFORMATION | MB_OK); ShowWindow(hwnd[0], SW_MAXIMIZE); MessageBox(NULL, messages[11], ,MB_APPLMODAL| MB_ICONINFORMATION | MB_OK); ShowWindow(hwnd[0], SW_RESTORE); while(x!=maxX/2||y!=maxY/2){ if(x<maxX/2) x++; if(y<maxY/2) y++; MoveWindow(hwnd[0],x,y,maxX/2-10, maxY/2-10,0); sleep(10); } MessageBox(NULL, messages[12], ,MB_APPLMODAL| MB_ICONINFORMATION | MB_OK); MoveWindow(hwnd[0],0,0,maxX, maxY,0); MessageBox(NULL, messages[13], ,MB_APPLMODAL| MB_ICONINFORMATION | MB_OK); while(GetMessage(&Msg, NULL, 0, 0) > 0) { TranslateMessage(&Msg); DispatchMessage(&Msg); } return Msg.wParam; }
40Window management
5c
zd0tx
package main import ( "bufio" "fmt" "log" "math/rand" "os" "regexp" "strings" "time" ) var dirs = [][]int{{1, 0}, {0, 1}, {1, 1}, {1, -1}, {-1, 0}, {0, -1}, {-1, -1}, {-1, 1}} const ( nRows = 10 nCols = nRows gridSize = nRows * nCols minWords = 25 ) var ( re1 = regexp.MustCompile(fmt.Sprintf("^[a-z]{3,%d}$", nRows)) re2 = regexp.MustCompile("[^A-Z]") ) type grid struct { numAttempts int cells [nRows][nCols]byte solutions []string } func check(err error) { if err != nil { log.Fatal(err) } } func readWords(fileName string) []string { file, err := os.Open(fileName) check(err) defer file.Close() var words []string scanner := bufio.NewScanner(file) for scanner.Scan() { word := strings.ToLower(strings.TrimSpace(scanner.Text())) if re1.MatchString(word) { words = append(words, word) } } check(scanner.Err()) return words } func createWordSearch(words []string) *grid { var gr *grid outer: for i := 1; i < 100; i++ { gr = new(grid) messageLen := gr.placeMessage("Rosetta Code") target := gridSize - messageLen cellsFilled := 0 rand.Shuffle(len(words), func(i, j int) { words[i], words[j] = words[j], words[i] }) for _, word := range words { cellsFilled += gr.tryPlaceWord(word) if cellsFilled == target { if len(gr.solutions) >= minWords { gr.numAttempts = i break outer } else {
41Word search
0go
ph5bg
use strict; use warnings; my %dict; open my $handle, '<', 'unixdict.txt'; while (my $word = <$handle>) { chomp($word); my $len = length $word; if (exists $dict{$len}) { push @{ $dict{ $len } }, $word; } else { my @words = ( $word ); $dict{$len} = \@words; } } close $handle; sub distance { my $w1 = shift; my $w2 = shift; my $dist = 0; for my $i (0 .. length($w1) - 1) { my $c1 = substr($w1, $i, 1); my $c2 = substr($w2, $i, 1); if (not ($c1 eq $c2)) { $dist++; } } return $dist; } sub contains { my $aref = shift; my $needle = shift; for my $v (@$aref) { if ($v eq $needle) { return 1; } } return 0; } sub word_ladder { my $fw = shift; my $tw = shift; if (exists $dict{length $fw}) { my @poss = @{ $dict{length $fw} }; my @queue = ([$fw]); while (scalar @queue > 0) { my $curr_ref = shift @queue; my $last = $curr_ref->[-1]; my @next; for my $word (@poss) { if (distance($last, $word) == 1) { push @next, $word; } } if (contains(\@next, $tw)) { push @$curr_ref, $tw; print join (' -> ', @$curr_ref), "\n"; return; } for my $word (@next) { for my $i (0 .. scalar @poss - 1) { if ($word eq $poss[$i]) { splice @poss, $i, 1; last; } } } for my $word (@next) { my @temp = @$curr_ref; push @temp, $word; push @queue, \@temp; } } } print STDERR "Cannot change $fw into $tw\n"; } word_ladder('boy', 'man'); word_ladder('girl', 'lady'); word_ladder('john', 'jane'); word_ladder('child', 'adult'); word_ladder('cat', 'dog'); word_ladder('lead', 'gold'); word_ladder('white', 'black'); word_ladder('bubble', 'tickle');
39Word ladder
2perl
52mu2
import Data.Char (toLower) import Data.List (sort) import System.IO (readFile) gridWords :: [String] -> [String] -> [String] gridWords grid = filter ( ((&&) . (2 <) . length) <*> (((&&) . elem mid) <*> wheelFit wheel) ) where cs = toLower <$> concat grid wheel = sort cs mid = cs !! 4 wheelFit :: String -> String -> Bool wheelFit wheel = go wheel . sort where go _ [] = True go [] _ = False go (w: ws) ccs@(c: cs) | w == c = go ws cs | otherwise = go ws ccs main :: IO () main = readFile "unixdict.txt" >>= ( mapM_ putStrLn . gridWords ["NDE", "OKG", "ELW"] . lines )
38Word wheel
8haskell
6tn3k
int main(void) { Display *d; Window w; XEvent e; const char *msg = ; int s; d = XOpenDisplay(NULL); if (d == NULL) { fprintf(stderr, ); exit(1); } s = DefaultScreen(d); w = XCreateSimpleWindow(d, RootWindow(d, s), 10, 10, 100, 100, 1, BlackPixel(d, s), WhitePixel(d, s)); XSelectInput(d, w, ExposureMask | KeyPressMask); XMapWindow(d, w); while (1) { XNextEvent(d, &e); if (e.type == Expose) { XFillRectangle(d, w, DefaultGC(d, s), 20, 20, 10, 10); XDrawString(d, w, DefaultGC(d, s), 10, 50, msg, strlen(msg)); } if (e.type == KeyPress) break; } XCloseDisplay(d); return 0; }
42Window creation/X11
5c
lmdcy
(() => { "use strict";
38Word wheel
10javascript
3fiz0
package main import ( "encoding/xml" "fmt" )
34XML/Output
0go
hr7jq
package main import ( "encoding/xml" "fmt" ) const XML_Data = ` <Students> <Student Name="April" Gender="F" DateOfBirth="1989-01-02" /> <Student Name="Bob" Gender="M" DateOfBirth="1990-03-04" /> <Student Name="Chad" Gender="M" DateOfBirth="1991-05-06" /> <Student Name="Dave" Gender="M" DateOfBirth="1992-07-08"> <Pet Type="dog" Name="Rover" /> </Student> <Student DateOfBirth="1993-09-10" Gender="F" Name="&#x00C9;mily" /> </Students> ` type Students struct { Student []Student } type Student struct { Name string `xml:",attr"`
35XML/Input
0go
qeexz
import itertools def writedat(filename, x, y, xprecision=3, yprecision=5): with open(filename,'w') as f: for a, b in itertools.izip(x, y): print >> f, % (xprecision, a, yprecision, b)
30Write float arrays to a text file
3python
f3de
writexy <- function(file, x, y, xprecision=3, yprecision=3) { fx <- formatC(x, digits=xprecision, format="g", flag="-") fy <- formatC(y, digits=yprecision, format="g", flag="-") dfr <- data.frame(fx, fy) write.table(dfr, file=file, sep="\t", row.names=F, col.names=F, quote=F) } x <- c(1, 2, 3, 1e11) y <- sqrt(x) writexy("test.txt", x, y, yp=5)
30Write float arrays to a text file
13r
od84
package main import ( "github.com/gotk3/gotk3/gtk" "log" "time" ) func check(err error, msg string) { if err != nil { log.Fatal(msg, err) } } func main() { gtk.Init(nil) window, err := gtk.WindowNew(gtk.WINDOW_TOPLEVEL) check(err, "Unable to create window:") window.SetResizable(true) window.SetTitle("Window management") window.SetBorderWidth(5) window.Connect("destroy", func() { gtk.MainQuit() }) stackbox, err := gtk.BoxNew(gtk.ORIENTATION_VERTICAL, 10) check(err, "Unable to create stack box:") bmax, err := gtk.ButtonNewWithLabel("Maximize") check(err, "Unable to create maximize button:") bmax.Connect("clicked", func() { window.Maximize() }) bunmax, err := gtk.ButtonNewWithLabel("Unmaximize") check(err, "Unable to create unmaximize button:") bunmax.Connect("clicked", func() { window.Unmaximize() }) bicon, err := gtk.ButtonNewWithLabel("Iconize") check(err, "Unable to create iconize button:") bicon.Connect("clicked", func() { window.Iconify() }) bdeicon, err := gtk.ButtonNewWithLabel("Deiconize") check(err, "Unable to create deiconize button:") bdeicon.Connect("clicked", func() { window.Deiconify() }) bhide, err := gtk.ButtonNewWithLabel("Hide") check(err, "Unable to create hide button:") bhide.Connect("clicked", func() {
40Window management
0go
k7uhz
package main import ( "fmt" "math/big" "rcu" ) func main() { const LIMIT = 11000 primes := rcu.Primes(LIMIT) facts := make([]*big.Int, LIMIT) facts[0] = big.NewInt(1) for i := int64(1); i < LIMIT; i++ { facts[i] = new(big.Int) facts[i].Mul(facts[i-1], big.NewInt(i)) } sign := int64(1) f := new(big.Int) zero := new(big.Int) fmt.Println(" n: Wilson primes") fmt.Println("--------------------") for n := 1; n < 12; n++ { fmt.Printf("%2d: ", n) sign = -sign for _, p := range primes { if p < n { continue } f.Mul(facts[n-1], facts[p-n]) f.Sub(f, big.NewInt(sign)) p2 := int64(p * p) bp2 := big.NewInt(p2) if f.Rem(f, bp2).Cmp(zero) == 0 { fmt.Printf("%d ", p) } } fmt.Println() } }
43Wilson primes of order n
0go
doane
import java.io.*; import static java.lang.String.format; import java.util.*; public class WordSearch { static class Grid { int numAttempts; char[][] cells = new char[nRows][nCols]; List<String> solutions = new ArrayList<>(); } final static int[][] dirs = {{1, 0}, {0, 1}, {1, 1}, {1, -1}, {-1, 0}, {0, -1}, {-1, -1}, {-1, 1}}; final static int nRows = 10; final static int nCols = 10; final static int gridSize = nRows * nCols; final static int minWords = 25; final static Random rand = new Random(); public static void main(String[] args) { printResult(createWordSearch(readWords("unixdict.txt"))); } static List<String> readWords(String filename) { int maxLen = Math.max(nRows, nCols); List<String> words = new ArrayList<>(); try (Scanner sc = new Scanner(new FileReader(filename))) { while (sc.hasNext()) { String s = sc.next().trim().toLowerCase(); if (s.matches("^[a-z]{3," + maxLen + "}$")) words.add(s); } } catch (FileNotFoundException e) { System.out.println(e); } return words; } static Grid createWordSearch(List<String> words) { Grid grid = null; int numAttempts = 0; outer: while (++numAttempts < 100) { Collections.shuffle(words); grid = new Grid(); int messageLen = placeMessage(grid, "Rosetta Code"); int target = gridSize - messageLen; int cellsFilled = 0; for (String word : words) { cellsFilled += tryPlaceWord(grid, word); if (cellsFilled == target) { if (grid.solutions.size() >= minWords) { grid.numAttempts = numAttempts; break outer; } else break;
41Word search
9java
0xbse
const char *string = ; typedef struct word_t { const char *s; int len; } *word; word make_word_list(const char *s, int *n) { int max_n = 0; word words = 0; *n = 0; while (1) { while (*s && isspace(*s)) s++; if (!*s) break; if (*n >= max_n) { if (!(max_n *= 2)) max_n = 2; words = realloc(words, max_n * sizeof(*words)); } words[*n].s = s; while (*s && !isspace(*s)) s++; words[*n].len = s - words[*n].s; (*n) ++; } return words; } int greedy_wrap(word words, int count, int cols, int *breaks) { int score = 0, line, i, j, d; i = j = line = 0; while (1) { if (i == count) { breaks[j++] = i; break; } if (!line) { line = words[i++].len; continue; } if (line + words[i].len < cols) { line += words[i++].len + 1; continue; } breaks[j++] = i; if (i < count) { d = cols - line; if (d > 0) score += PENALTY_SHORT * d * d; else if (d < 0) score += PENALTY_LONG * d * d; } line = 0; } breaks[j++] = 0; return score; } int balanced_wrap(word words, int count, int cols, int *breaks) { int *best = malloc(sizeof(int) * (count + 1)); int best_score = greedy_wrap(words, count, cols, breaks); void test_wrap(int line_no, int start, int score) { int line = 0, current_score = -1, d; while (start <= count) { if (line) line ++; line += words[start++].len; d = cols - line; if (start < count || d < 0) { if (d > 0) current_score = score + PENALTY_SHORT * d * d; else current_score = score + PENALTY_LONG * d * d; } else { current_score = score; } if (current_score >= best_score) { if (d <= 0) return; continue; } best[line_no] = start; test_wrap(line_no + 1, start, current_score); } if (current_score >= 0 && current_score < best_score) { best_score = current_score; memcpy(breaks, best, sizeof(int) * (line_no)); } } test_wrap(0, 0, 0); free(best); return best_score; } void show_wrap(word list, int count, int *breaks) { int i, j; for (i = j = 0; i < count && breaks[i]; i++) { while (j < breaks[i]) { printf(, list[j].len, list[j].s); if (j < breaks[i] - 1) putchar(' '); j++; } if (breaks[i]) putchar('\n'); } } int main(void) { int len, score, cols; word list = make_word_list(string, &len); int *breaks = malloc(sizeof(int) * (len + 1)); cols = 80; score = greedy_wrap(list, len, cols, breaks); printf(, cols, score); show_wrap(list, len, breaks); score = balanced_wrap(list, len, cols, breaks); printf(, cols, score); show_wrap(list, len, breaks); cols = 32; score = greedy_wrap(list, len, cols, breaks); printf(, cols, score); show_wrap(list, len, breaks); score = balanced_wrap(list, len, cols, breaks); printf(, cols, score); show_wrap(list, len, breaks); return 0; }
44Word wrap
5c
fiad3
import os,sys,zlib,urllib.request def h ( str,x=9 ): for c in str: x = ( x*33 + ord( c )) & 0xffffffffff return x def cache ( func,*param ): n = 'cache_%x.bin'%abs( h( repr( param ))) try : return eval( zlib.decompress( open( n,'rb' ).read())) except: pass s = func( *param ) open( n,'wb' ).write( zlib.compress( bytes( repr( s ),'ascii' ))) return s dico_url = 'https: read_url = lambda url : urllib.request.urlopen( url ).read() load_dico = lambda url : tuple( cache( read_url,url ).split( b'\n')) isnext = lambda w1,w2: len( w1 ) == len( w2 ) and len( list( filter( lambda l: l[0]!=l[1] , zip( w1,w2 )))) == 1 def build_map ( words ): map = [(w.decode('ascii'),[]) for w in words] for i1,(w1,n1) in enumerate( map ): for i2,(w2,n2) in enumerate( map[i1+1:],i1+1 ): if isnext( w1,w2 ): n1.append( i2 ) n2.append( i1 ) return map def find_path ( words,w1,w2 ): i = [w[0] for w in words].index( w1 ) front,done,res = [i],{i:-1},[] while front: i = front.pop(0) word,next = words[i] for n in next: if n in done: continue done[n] = i if words[n][0] == w2: while n >= 0: res = [words[n][0]] + res n = done[n] return ' '.join( res ) front.append( n ) return '%s can not be turned into%s'%( w1,w2 ) for w in ('boy man','girl lady','john jane','alien drool','child adult'): print( find_path( cache( build_map,load_dico( dico_url )),*w.split()))
39Word ladder
3python
4v95k
LetterCounter = { new = function(self, word) local t = { word=word, letters={} } for ch in word:gmatch(".") do t.letters[ch] = (t.letters[ch] or 0) + 1 end return setmetatable(t, self) end, contains = function(self, other) for k,v in pairs(other.letters) do if (self.letters[k] or 0) < v then return false end end return true end } LetterCounter.__index = LetterCounter grid = "ndeokgelw" midl = grid:sub(5,5) ltrs = LetterCounter:new(grid) file = io.open("unixdict.txt", "r") for word in file:lines() do if #word >= 3 and word:find(midl) and ltrs:contains(LetterCounter:new(word)) then print(word) end end
38Word wheel
1lua
0xasd
from __future__ import division import sys from PIL import Image def _fpart(x): return x - int(x) def _rfpart(x): return 1 - _fpart(x) def putpixel(img, xy, color, alpha=1): compose_color = lambda bg, fg: int(round(alpha * fg + (1-alpha) * bg)) c = compose_color(img.getpixel(xy), color) img.putpixel(xy, c) def draw_line(img, p1, p2, color): x1, y1 = p1 x2, y2 = p2 dx, dy = x2-x1, y2-y1 steep = abs(dx) < abs(dy) p = lambda px, py: ((px,py), (py,px))[steep] if steep: x1, y1, x2, y2, dx, dy = y1, x1, y2, x2, dy, dx if x2 < x1: x1, x2, y1, y2 = x2, x1, y2, y1 grad = dy/dx intery = y1 + _rfpart(x1) * grad def draw_endpoint(pt): x, y = pt xend = round(x) yend = y + grad * (xend - x) xgap = _rfpart(x + 0.5) px, py = int(xend), int(yend) putpixel(img, p(px, py), color, _rfpart(yend) * xgap) putpixel(img, p(px, py+1), color, _fpart(yend) * xgap) return px xstart = draw_endpoint(p(*p1)) + 1 xend = draw_endpoint(p(*p2)) for x in range(xstart, xend): y = int(intery) putpixel(img, p(x, y), color, _rfpart(intery)) putpixel(img, p(x, y+1), color, _fpart(intery)) intery += grad if __name__ == '__main__': if len(sys.argv) != 2: print 'usage: python xiaolinwu.py [output-file]' sys.exit(-1) blue = (0, 0, 255) yellow = (255, 255, 0) img = Image.new(, (500,500), blue) for a in range(10, 431, 60): draw_line(img, (10, 10), (490, a), yellow) draw_line(img, (10, 10), (a, 490), yellow) draw_line(img, (10, 10), (490, 490), yellow) filename = sys.argv[1] img.save(filename) print 'image saved to', filename
33Xiaolin Wu's line algorithm
3python
qqxi
def writer = new StringWriter() def builder = new groovy.xml.MarkupBuilder(writer) def names = ["April", "Tam O'Shanter", "Emily"] def remarks = ["Bubbly: I'm > Tam and <= Emily", 'Burns: "When chapman billies leave the street ..."', "Short & shrift"] builder.CharacterRemarks() { names.eachWithIndex() { n, i -> Character(name:n, remarks[i]) }; } println writer.toString()
34XML/Output
7groovy
4vu5f
def input = """<Students> <Student Name="April" Gender="F" DateOfBirth="1989-01-02" /> <Student Name="Bob" Gender="M" DateOfBirth="1990-03-04" /> <Student Name="Chad" Gender="M" DateOfBirth="1991-05-06" /> <Student Name="Dave" Gender="M" DateOfBirth="1992-07-08"> <Pet Type="dog" Name="Rover" /> </Student> <Student DateOfBirth="1993-09-10" Gender="F" Name="&#x00C9;mily" /> </Students>""" def students = new XmlParser().parseText(input) students.each { println it.'@Name' }
35XML/Input
7groovy
1kkp6
null
41Word search
11kotlin
epra4
import Text.XML.Light characterRemarks :: [String] -> [String] -> String characterRemarks names remarks = showElement $ Element (unqual "CharacterRemarks") [] (zipWith character names remarks) Nothing where character name remark = Elem $ Element (unqual "Character") [Attr (unqual "name") name] [Text $ CData CDataText remark Nothing] Nothing
34XML/Output
8haskell
i08or
import Data.Maybe import Text.XML.Light students="<Students>"++ " <Student Name=\"April\" Gender=\"F\" DateOfBirth=\"1989-01-02\" />"++ " <Student Name=\"Bob\" Gender=\"M\" DateOfBirth=\"1990-03-04\" />"++ " <Student Name=\"Chad\" Gender=\"M\" DateOfBirth=\"1991-05-06\"/>"++ " <Student Name=\"Dave\" Gender=\"M\" DateOfBirth=\"1992-07-08\">"++ " <Pet Type=\"dog\" Name=\"Rover\" /> </Student>"++ " <Student DateOfBirth=\"1993-09-10\" Gender=\"F\" Name=\"&#x00C9;mily\" />"++ "</Students>" xmlRead elm name = mapM_ putStrLn . concatMap (map (fromJust.findAttr (unqual name)).filterElementsName (== unqual elm)) . onlyElems. parseXML
35XML/Input
8haskell
m33yf
static bool PRIMES[LIMIT]; static void prime_sieve() { uint64_t p; int i; PRIMES[0] = false; PRIMES[1] = false; for (i = 2; i < LIMIT; i++) { PRIMES[i] = true; } for (i = 4; i < LIMIT; i += 2) { PRIMES[i] = false; } for (p = 3;; p += 2) { uint64_t q = p * p; if (q >= LIMIT) { break; } if (PRIMES[p]) { uint64_t inc = 2 * p; for (; q < LIMIT; q += inc) { PRIMES[q] = false; } } } } uint64_t modpow(uint64_t base, uint64_t exp, uint64_t mod) { uint64_t result = 1; if (mod == 1) { return 0; } base %= mod; for (; exp > 0; exp >>= 1) { if ((exp & 1) == 1) { result = (result * base) % mod; } base = (base * base) % mod; } return result; } void wieferich_primes() { uint64_t p; for (p = 2; p < LIMIT; ++p) { if (PRIMES[p] && modpow(2, p - 1, p * p) == 1) { printf(, p); } } } int main() { prime_sieve(); printf(, LIMIT); wieferich_primes(); return 0; }
45Wieferich primes
5c
0x7st
package main
42Window creation/X11
0go
xa7wf
import java.math.BigInteger; import java.util.*; public class WilsonPrimes { public static void main(String[] args) { final int limit = 11000; BigInteger[] f = new BigInteger[limit]; f[0] = BigInteger.ONE; BigInteger factorial = BigInteger.ONE; for (int i = 1; i < limit; ++i) { factorial = factorial.multiply(BigInteger.valueOf(i)); f[i] = factorial; } List<Integer> primes = generatePrimes(limit); System.out.printf(" n | Wilson primes\n--------------------\n"); BigInteger s = BigInteger.valueOf(-1); for (int n = 1; n <= 11; ++n) { System.out.printf("%2d |", n); for (int p : primes) { if (p >= n && f[n - 1].multiply(f[p - n]).subtract(s) .mod(BigInteger.valueOf(p * p)) .equals(BigInteger.ZERO)) System.out.printf("%d", p); } s = s.negate(); System.out.println(); } } private static List<Integer> generatePrimes(int limit) { boolean[] sieve = new boolean[limit >> 1]; Arrays.fill(sieve, true); for (int p = 3, s = 9; s < limit; p += 2) { if (sieve[p >> 1]) { for (int q = s; q < limit; q += p << 1) sieve[q >> 1] = false; } s += (p + 1) << 2; } List<Integer> primes = new ArrayList<>(); if (limit > 2) primes.add(2); for (int i = 1; i < sieve.length; ++i) { if (sieve[i]) primes.add((i << 1) + 1); } return primes; } }
43Wilson primes of order n
9java
96omu
use strict; use warnings; use Path::Tiny; use List::Util qw( shuffle ); my $size = 10; my $s1 = $size + 1; $_ = <<END; .....R.... ......O... .......S.. ........E. T........T .A........ ..C....... ...O...... ....D..... .....E.... END my @words = shuffle path('/usr/share/dict/words')->slurp =~ /^[a-z]{3,7}$/gm; my @played; my %used; for my $word ( (@words) x 5 ) { my ($pat, $start, $end, $mask, $nulls) = find( $word ); defined $pat or next; $used{$word}++ and next; $nulls //= ''; my $expand = $word =~ s/\B/$nulls/gr; my $pos = $start; if( $start > $end ) { $pos = $end; $expand = reverse $expand; } substr $_, $pos, length $mask, (substr( $_, $pos, length $mask ) & ~ "$mask") | "$expand"; push @played, join ' ', $word, $start, $end; tr/.// > 0 or last; } print " 0 1 2 3 4 5 6 7 8 9\n\n"; my $row = 0; print s/(?<=.)(?=.)/ /gr =~ s/^/ $row++ . ' ' /gemr; print "\nNumber of words: ", @played . "\n\n"; my @where = map { my ($word, $start, $end) = split; sprintf "%11s%s", $word, $start < $end ? "(@{[$start% $s1]},@{[int $start / $s1]})->" . "(@{[$end% $s1 - 1]},@{[int $end / $s1]})" : "(@{[$start% $s1 - 1]},@{[int $start / $s1]})->" . "(@{[$end% $s1]},@{[int $end / $s1]})"; } sort @played; print splice(@where, 0, 3), "\n" while @where; tr/.// and die "incomplete"; sub find { my ($word) = @_; my $n = length $word; my $nm1 = $n - 1; my %pats; for my $space ( 0, $size - 1 .. $size + 1 ) { my $nulls = "\0" x $space; my $mask = "\xff" . ($nulls . "\xff") x $nm1; my $gap = qr/.{$space}/s; while( /(?=(.(?:$gap.){$nm1}))/g ) { my $pat = ($1 & $mask) =~ tr/\0//dr; $pat =~ tr/.// or next; my $pos = "$-[1] $+[1]"; $word =~ /$pat/ or reverse($word) =~ /$pat/ or next; push @{ $pats{$pat} }, "$pos $mask $nulls"; } } for my $key ( sort keys %pats ) { if( $word =~ /^$key$/ ) { my @all = @{ $pats{$key} }; return $key, split ' ', $all[ rand @all ]; } elsif( (reverse $word) =~ /^$key$/ ) { my @all = @{ $pats{$key} }; my @parts = split ' ', $all[ rand @all ]; return $key, @parts[ 1, 0, 2, 3] } } return undef; }
41Word search
2perl
cyd9a
require Words = File.open().read.split(). group_by { |w| w.length }.map { |k, v| [k, Set.new(v)] }. to_h def word_ladder(from, to) raise unless from.length == to.length sized_words = Words[from.length] work_queue = [[from]] used = Set.new [from] while work_queue.length > 0 new_q = [] work_queue.each do |words| last_word = words[-1] new_tails = Enumerator.new do |enum| (..).each do |replacement_letter| last_word.length.times do |i| new_word = last_word.clone new_word[i] = replacement_letter next unless sized_words.include? new_word and not used.include? new_word enum.yield new_word used.add new_word return words + [new_word] if new_word == to end end end new_tails.each do |t| new_q.push(words + [t]) end end work_queue = new_q end end [%w<boy man>, %w<girl lady>, %w<john jane>, %w<child adult>].each do |from, to| if ladder = word_ladder(from, to) puts ladder.join else puts end end
39Word ladder
14ruby
r5lgs
package main import ( "fmt" "strings" ) var lean = font{ height: 5, slant: 1, spacing: 2, m: map[rune][]string{ 'G': []string{ ` _/_/_/`, `_/ `, `_/ _/_/`, `_/ _/`, ` _/_/_/`, }, 'o': []string{ ` `, ` _/_/ `, `_/ _/`, `_/ _/`, ` _/_/ `, }, }} var smallKeyboard = font{ height: 4, slant: 0, spacing: -1, m: map[rune][]string{ 'G': []string{ ` ____ `, `||G ||`, `||__||`, `|/__\|`, }, 'o': []string{ ` ____ `, `||o ||`, `||__||`, `|/__\|`, }, }} type font struct { height int slant int spacing int m map[rune][]string } func render(s string, f font) string { rows := make([]string, f.height) if f.slant != 0 { start := 0 if f.slant > 0 { start = f.height } for i := range rows { rows[i] = strings.Repeat(" ", (start-i)*f.slant) } } if f.spacing >= 0 { spacing := strings.Repeat(" ", f.spacing) for j, c := range s { for i, r := range f.m[c] { if j > 0 { r = spacing + r } rows[i] += r } } } else { overlap := -f.spacing for j, c := range s { for i, r := range f.m[c] { if j > 0 { r = r[overlap:] } rows[i] += r } } } return strings.Join(rows, "\n") } func main() { fmt.Println(render("Go", lean)) fmt.Println(render("Go", smallKeyboard)) }
37Write language name in 3D ASCII
0go
cy39g
import java.awt.BorderLayout; import java.awt.EventQueue; import java.awt.Frame; import java.awt.GridLayout; import java.awt.event.ActionEvent; import java.lang.reflect.InvocationTargetException; import javax.swing.AbstractAction; import javax.swing.JButton; import javax.swing.JComboBox; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JOptionPane; import javax.swing.JPanel; import javax.swing.border.EmptyBorder; public class WindowController extends JFrame {
40Window management
9java
qekxa
groovy WindowCreation.groovy
42Window creation/X11
7groovy
phubo
use strict; use warnings; use ntheory <primes factorial>; my @primes = @{primes( 10500 )}; for my $n (1..11) { printf "%3d:%s\n", $n, join ' ', grep { $_ >= $n && 0 == (factorial($n-1) * factorial($_-$n) - (-1)**$n) % $_**2 } @primes }
43Wilson primes of order n
2perl
bj2k4
int main() { SDL_Surface *screen; if (SDL_Init(SDL_INIT_VIDEO) != 0) { fprintf(stderr, , SDL_GetError()); return 1; } atexit(SDL_Quit); screen = SDL_SetVideoMode( 800, 600, 16, SDL_SWSURFACE | SDL_HWPALETTE ); return 0; }
46Window creation
5c
dobnv
(defn wrap-line [size text] (loop [left size line [] lines [] words (clojure.string/split text #"\s+")] (if-let [word (first words)] (let [wlen (count word) spacing (if (== left size) "" " ") alen (+ (count spacing) wlen)] (if (<= alen left) (recur (- left alen) (conj line spacing word) lines (next words)) (recur (- size wlen) [word] (conj lines (apply str line)) (next words)))) (when (seq line) (conj lines (apply str line))))))
44Word wrap
6clojure
yzs6b
import Foundation func oneAway(string1: [Character], string2: [Character]) -> Bool { if string1.count!= string2.count { return false } var result = false var i = 0 while i < string1.count { if string1[i]!= string2[i] { if result { return false } result = true } i += 1 } return result } func wordLadder(words: [[Character]], from: String, to: String) { let fromCh = Array(from) let toCh = Array(to) var poss = words.filter{$0.count == fromCh.count} var queue: [[[Character]]] = [[fromCh]] while!queue.isEmpty { var curr = queue[0] let last = curr[curr.count - 1] queue.removeFirst() let next = poss.filter{oneAway(string1: $0, string2: last)} if next.contains(toCh) { curr.append(toCh) print(curr.map{String($0)}.joined(separator: " -> ")) return } poss.removeAll(where: {next.contains($0)}) for str in next { var temp = curr temp.append(str) queue.append(temp) } } print("\(from) into \(to) cannot be done.") } do { let words = try String(contentsOfFile: "unixdict.txt", encoding: String.Encoding.ascii) .components(separatedBy: "\n") .filter{!$0.isEmpty} .map{Array($0)} wordLadder(words: words, from: "man", to: "boy") wordLadder(words: words, from: "girl", to: "lady") wordLadder(words: words, from: "john", to: "jane") wordLadder(words: words, from: "child", to: "adult") wordLadder(words: words, from: "cat", to: "dog") wordLadder(words: words, from: "lead", to: "gold") wordLadder(words: words, from: "white", to: "black") wordLadder(words: words, from: "bubble", to: "tickle") } catch { print(error.localizedDescription) }
39Word ladder
17swift
guc49
use strict; use warnings; $_ = <<END; N D E O K G E L W END my $file = do { local(@ARGV, $/) = 'unixdict.txt'; <> }; my $length = my @letters = lc =~ /\w/g; my $center = $letters[@letters / 2]; my $toomany = (join '', sort @letters) =~ s/(.)\1*/ my $count = length "$1$&"; "(?!(?:.*$1){$count})" /ger; my $valid = qr/^(?=.*$center)$toomany([@letters]{3,$length}$)$/m; my @words = $file =~ /$valid/g; print @words . " words for\n$_\n@words\n" =~ s/.{60}\K /\n/gr;
38Word wheel
2perl
ulmvr
def ipart(n); n.truncate; end def fpart(n); n - ipart(n); end def rfpart(n); 1.0 - fpart(n); end class Pixmap def draw_line_antialised(p1, p2, colour) x1, y1 = p1.x, p1.y x2, y2 = p2.x, p2.y steep = (y2 - y1).abs > (x2 - x1).abs if steep x1, y1 = y1, x1 x2, y2 = y2, x2 end if x1 > x2 x1, x2 = x2, x1 y1, y2 = y2, y1 end deltax = x2 - x1 deltay = (y2 - y1).abs gradient = 1.0 * deltay / deltax xend = x1.round yend = y1 + gradient * (xend - x1) xgap = rfpart(x1 + 0.5) xpxl1 = xend ypxl1 = ipart(yend) put_colour(xpxl1, ypxl1, colour, steep, rfpart(yend)*xgap) put_colour(xpxl1, ypxl1 + 1, colour, steep, fpart(yend)*xgap) itery = yend + gradient xend = x2.round yend = y2 + gradient * (xend - x2) xgap = rfpart(x2 + 0.5) xpxl2 = xend ypxl2 = ipart(yend) put_colour(xpxl2, ypxl2, colour, steep, rfpart(yend)*xgap) put_colour(xpxl2, ypxl2 + 1, colour, steep, fpart(yend)*xgap) (xpxl1 + 1).upto(xpxl2 - 1).each do |x| put_colour(x, ipart(itery), colour, steep, rfpart(itery)) put_colour(x, ipart(itery) + 1, colour, steep, fpart(itery)) itery = itery + gradient end end def put_colour(x, y, colour, steep, c) x, y = y, x if steep self[x, y] = anti_alias(colour, self[x, y], c) end def anti_alias(new, old, ratio) blended = new.values.zip(old.values).map {|n, o| (n*ratio + o*(1.0 - ratio)).round} RGBColour.new(*blended) end end bitmap = Pixmap.new(500, 500) bitmap.fill(RGBColour::BLUE) 10.step(430, 60) do |a| bitmap.draw_line_antialised(Pixel[10, 10], Pixel[490,a], RGBColour::YELLOW) bitmap.draw_line_antialised(Pixel[10, 10], Pixel[a,490], RGBColour::YELLOW) end bitmap.draw_line_antialised(Pixel[10, 10], Pixel[490,490], RGBColour::YELLOW)
33Xiaolin Wu's line algorithm
14ruby
00su
import java.io.StringWriter; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.transform.Result; import javax.xml.transform.Source; import javax.xml.transform.Transformer; import javax.xml.transform.TransformerFactory; import javax.xml.transform.dom.DOMSource; import javax.xml.transform.stream.StreamResult; import org.w3c.dom.Document; import org.w3c.dom.Element; public class XmlCreation { private static final String[] names = {"April", "Tam O'Shanter", "Emily"}; private static final String[] remarks = {"Bubbly: I'm > Tam and <= Emily", "Burns: \"When chapman billies leave the street ...\"", "Short & shrift"}; public static void main(String[] args) { try {
34XML/Output
9java
xaewy
x = [1, 2, 3, 1e11] y = x.collect { |xx| Math.sqrt xx } xprecision = 3 yprecision = 5 open('sqrt.dat', 'w') do |f| x.zip(y) { |xx, yy| f.printf(, xprecision, xx, yprecision, yy) } end open('sqrt.dat', 'r') { |f| puts f.read }
30Write float arrays to a text file
14ruby
zytw
struct int_a { int *ptr; size_t size; }; struct int_a divisors(int n) { int *divs, *divs2, *out; int i, j, c1 = 0, c2 = 0; struct int_a array; divs = malloc(n * sizeof(int) / 2); divs2 = malloc(n * sizeof(int) / 2); divs[c1++] = 1; for (i = 2; i * i <= n; i++) { if (n % i == 0) { j = n / i; divs[c1++] = i; if (i != j) { divs2[c2++] = j; } } } out = malloc((c1 + c2) * sizeof(int)); for (int i = 0; i < c2; i++) { out[i] = divs2[i]; } for (int i = 0; i < c1; i++) { out[c2 + i] = divs[c1 - i - 1]; } array.ptr = out; array.size = c1 + c2; free(divs); free(divs2); return array; } bool abundant(int n, struct int_a divs) { int sum = 0; int i; for (i = 0; i < divs.size; i++) { sum += divs.ptr[i]; } return sum > n; } bool semiperfect(int n, struct int_a divs) { if (divs.size > 0) { int h = *divs.ptr; int *t = divs.ptr + 1; struct int_a ta; ta.ptr = t; ta.size = divs.size - 1; if (n < h) { return semiperfect(n, ta); } else { return n == h || semiperfect(n - h, ta) || semiperfect(n, ta); } } else { return false; } } bool *sieve(int limit) { bool *w = calloc(limit, sizeof(bool)); struct int_a divs; int i, j; for (i = 2; i < limit; i += 2) { if (w[i]) continue; divs = divisors(i); if (!abundant(i, divs)) { w[i] = true; } else if (semiperfect(i, divs)) { for (j = i; j < limit; j += i) { w[j] = true; } } } free(divs.ptr); return w; } int main() { bool *w = sieve(17000); int count = 0; int max = 25; int n; printf(); for (n = 2; count < max; n += 2) { if (!w[n]) { printf(, n); count++; } } printf(); free(w); return 0; }
47Weird numbers
5c
ep2av
println """\ _|_|_| _| _| _|_| _|_| _|_| _| _| _| _| _| _|_| _|_| _| _| _| _| _| _| _| _| _| _| _| _| _| _| _| _| _| _| _| _|_|_| _| _|_| _|_| _| _|_|_| _| _|_|"""
37Write language name in 3D ASCII
7groovy
3fnzd
module Main where ascii3d :: String ascii3d = " __ __ __ ___ ___ \n" ++ "/\\ \\/\\ \\ /\\ \\ /\\_ \\ /\\_ \\ \n" ++ "\\ \\ \\_\\ \\ __ ____\\ \\ \\/'\\ __\\//\\ \\ \\//\\ \\ \n" ++ " \\ \\ _ \\ /'__`\\ /',__\\\\ \\ , < /'__`\\\\ \\ \\ \\ \\ \\ \n" ++ " \\ \\ \\ \\ \\/\\ \\L\\.\\_/\\__, `\\\\ \\ \\\\`\\ /\\ __/ \\_\\ \\_ \\_\\ \\_ \n" ++ " \\ \\_\\ \\_\\ \\__/.\\_\\/\\____/ \\ \\_\\ \\_\\ \\____\\/\\____\\/\\____\\\n" ++ " \\/_/\\/_/\\/__/\\/_/\\/___/ \\/_/\\/_/\\/____/\\/____/\\/____/" main = putStrLn ascii3d
37Write language name in 3D ASCII
8haskell
ph7bt
import Graphics.X11.Xlib import Control.Concurrent (threadDelay) main = do display <- openDisplay "" let defScr = defaultScreen display rw <- rootWindow display defScr xwin <- createSimpleWindow display rw 0 0 400 200 1 (blackPixel display defScr) (whitePixel display defScr) setTextProperty display xwin "Rosetta Code: X11 simple window" wM_NAME mapWindow display xwin sync display False threadDelay (5000000) destroyWindow display xwin closeDisplay display
42Window creation/X11
8haskell
yz866
(import '(javax.swing JFrame)) (let [frame (JFrame. "A Window")] (doto frame (.setSize 600 800) (.setVisible true)))
46Window creation
6clojure
6tw3q
import re from random import shuffle, randint dirs = [[1, 0], [0, 1], [1, 1], [1, -1], [-1, 0], [0, -1], [-1, -1], [-1, 1]] n_rows = 10 n_cols = 10 grid_size = n_rows * n_cols min_words = 25 class Grid: def __init__(self): self.num_attempts = 0 self.cells = [['' for _ in range(n_cols)] for _ in range(n_rows)] self.solutions = [] def read_words(filename): max_len = max(n_rows, n_cols) words = [] with open(filename, ) as file: for line in file: s = line.strip().lower() if re.match(r'^[a-z]{3,' + re.escape(str(max_len)) + r'}$', s) is not None: words.append(s) return words def place_message(grid, msg): msg = re.sub(r'[^A-Z]', , msg.upper()) message_len = len(msg) if 0 < message_len < grid_size: gap_size = grid_size for i in range(0, message_len): pos = i * gap_size + randint(0, gap_size) grid.cells[pos return message_len return 0 def try_location(grid, word, direction, pos): r = pos c = pos% n_cols length = len(word) if (dirs[direction][0] == 1 and (length + c) > n_cols) or \ (dirs[direction][0] == -1 and (length - 1) > c) or \ (dirs[direction][1] == 1 and (length + r) > n_rows) or \ (dirs[direction][1] == -1 and (length - 1) > r): return 0 rr = r cc = c i = 0 overlaps = 0 while i < length: if grid.cells[rr][cc] != '' and grid.cells[rr][cc] != word[i]: return 0 cc += dirs[direction][0] rr += dirs[direction][1] i += 1 rr = r cc = c i = 0 while i < length: if grid.cells[rr][cc] == word[i]: overlaps += 1 else: grid.cells[rr][cc] = word[i] if i < length - 1: cc += dirs[direction][0] rr += dirs[direction][1] i += 1 letters_placed = length - overlaps if letters_placed > 0: grid.solutions.append(.format(word, c, r, cc, rr)) return letters_placed def try_place_word(grid, word): rand_dir = randint(0, len(dirs)) rand_pos = randint(0, grid_size) for direction in range(0, len(dirs)): direction = (direction + rand_dir)% len(dirs) for pos in range(0, grid_size): pos = (pos + rand_pos)% grid_size letters_placed = try_location(grid, word, direction, pos) if letters_placed > 0: return letters_placed return 0 def create_word_search(words): grid = None num_attempts = 0 while num_attempts < 100: num_attempts += 1 shuffle(words) grid = Grid() message_len = place_message(grid, ) target = grid_size - message_len cells_filled = 0 for word in words: cells_filled += try_place_word(grid, word) if cells_filled == target: if len(grid.solutions) >= min_words: grid.num_attempts = num_attempts return grid else: break return grid def print_result(grid): if grid is None or grid.num_attempts == 0: print() return size = len(grid.solutions) print(.format(grid.num_attempts)) print(.format(size)) print() for r in range(0, n_rows): print(.format(r), end='') for c in range(0, n_cols): print(% grid.cells[r][c], end='') print() print() for i in range(0, size - 1, 2): print(.format(grid.solutions[i], grid.solutions[i+1])) if size% 2 == 1: print(grid.solutions[size - 1]) if __name__ == : print_result(create_word_search(read_words()))
41Word search
3python
lmfcv
import java.awt.Color import math.{floor => ipart, round, abs} case class Point(x: Double, y: Double) {def swap = Point(y, x)} def plotter(bm: RgbBitmap, c: Color)(x: Double, y: Double, v: Double) = { val X = round(x).toInt val Y = round(y).toInt val V = v.toFloat
33Xiaolin Wu's line algorithm
16scala
nnic
import java.io.IOException; import java.io.StringReader; import org.xml.sax.Attributes; import org.xml.sax.InputSource; import org.xml.sax.SAXException; import org.xml.sax.XMLReader; import org.xml.sax.helpers.DefaultHandler; import org.xml.sax.helpers.XMLReaderFactory; public class StudentHandler extends DefaultHandler { public static void main(String[] args)throws Exception{ String xml = "<Students>\n"+ "<Student Name=\"April\" Gender=\"F\" DateOfBirth=\"1989-01-02\" />\n"+ "<Student Name=\"Bob\" Gender=\"M\" DateOfBirth=\"1990-03-04\" />\n"+ "<Student Name=\"Chad\" Gender=\"M\" DateOfBirth=\"1991-05-06\" />\n"+ "<Student Name=\"Dave\" Gender=\"M\" DateOfBirth=\"1992-07-08\">\n"+ " <Pet Type=\"dog\" Name=\"Rover\" />\n"+ "</Student>\n"+ "<Student DateOfBirth=\"1993-09-10\" Gender=\"F\" Name=\"&#x00C9;mily\" />\n"+ "</Students>"; StudentHandler handler = new StudentHandler(); handler.parse(new InputSource(new StringReader(xml))); } public void parse(InputSource src) throws SAXException, IOException { XMLReader parser = XMLReaderFactory.createXMLReader(); parser.setContentHandler(this); parser.parse(src); } @Override public void characters(char[] ch, int start, int length) throws SAXException {
35XML/Input
9java
fiidv
import java.io.{File, FileWriter, IOException} object FloatArray extends App { val x: List[Float] = List(1f, 2f, 3f, 1e11f) def writeStringToFile(file: File, data: String, appending: Boolean = false) = using(new FileWriter(file, appending))(_.write(data)) def using[A <: {def close() : Unit}, B](resource: A)(f: A => B): B = try f(resource) finally resource.close() try { val file = new File("sqrt.dat") using(new FileWriter(file))(writer => x.foreach(x => writer.write(f"$x%.3g\t${math.sqrt(x)}%.5g\n"))) } catch { case e: IOException => println(s"Running Example failed: ${e.getMessage}") } }
30Write float arrays to a text file
16scala
mlyc
char world_7x14[2][512] = { { } }; void next_world(const char *in, char *out, int w, int h) { int i; for (i = 0; i < w*h; i++) { switch (in[i]) { case ' ': out[i] = ' '; break; case 't': out[i] = '.'; break; case 'H': out[i] = 't'; break; case '.': { int hc = (in[i-w-1] == 'H') + (in[i-w] == 'H') + (in[i-w+1] == 'H') + (in[i-1] == 'H') + (in[i+1] == 'H') + (in[i+w-1] == 'H') + (in[i+w] == 'H') + (in[i+w+1] == 'H'); out[i] = (hc == 1 || hc == 2) ? 'H' : '.'; break; } default: out[i] = in[i]; } } out[i] = in[i]; } int main() { int f; for (f = 0; ; f = 1 - f) { puts(world_7x14[f]); next_world(world_7x14[f], world_7x14[1-f], 14, 7); printf(, 8); printf(, 14); { static const struct timespec ts = { 0, 100000000 }; nanosleep(&ts, 0); } } return 0; }
48Wireworld
5c
xavwu
javac WindowExample.java
42Window creation/X11
9java
doen9
null
42Window creation/X11
11kotlin
0xksf
import urllib.request from collections import Counter GRID = def getwords(url='http: words = urllib.request.urlopen(url).read().decode().strip().lower().split() return (w for w in words if 2 < len(w) < 10) def solve(grid, dictionary): gridcount = Counter(grid) mid = grid[4] return [word for word in dictionary if mid in word and not (Counter(word) - gridcount)] if __name__ == '__main__': chars = ''.join(GRID.strip().lower().split()) found = solve(chars, dictionary=getwords()) print('\n'.join(found))
38Word wheel
3python
529ux
null
34XML/Output
11kotlin
phkb6
var xmlstr = '<Students>' + '<Student Name="April" Gender="F" DateOfBirth="1989-01-02" />' + '<Student Name="Bob" Gender="M" DateOfBirth="1990-03-04" />' + '<Student Name="Chad" Gender="M" DateOfBirth="1991-05-06" />' + '<Student Name="Dave" Gender="M" DateOfBirth="1992-07-08">' + '<Pet Type="dog" Name="Rover" />' + '</Student>' + '<Student DateOfBirth="1993-09-10" Gender="F" Name="&#x00C9;mily" />' + '</Students>'; if (window.DOMParser) { parser=new DOMParser(); xmlDoc=parser.parseFromString(xmlstr,"text/xml"); } else
35XML/Input
10javascript
yzz6r
public class F5{ char[]z={' ',' ','_','/',}; long[][]f={ {87381,87381,87381,87381,87381,87381,87381,}, {349525,375733,742837,742837,375733,349525,349525,}, {742741,768853,742837,742837,768853,349525,349525,}, {349525,375733,742741,742741,375733,349525,349525,}, {349621,375733,742837,742837,375733,349525,349525,}, {349525,375637,768949,742741,375733,349525,349525,}, {351157,374101,768949,374101,374101,349525,349525,}, {349525,375733,742837,742837,375733,349621,351157,}, {742741,768853,742837,742837,742837,349525,349525,}, {181,85,181,181,181,85,85,}, {1461,1365,1461,1461,1461,1461,2901,}, {742741,744277,767317,744277,742837,349525,349525,}, {181,181,181,181,181,85,85,}, {1431655765,3149249365L,3042661813L,3042661813L,3042661813L,1431655765,1431655765,}, {349525,768853,742837,742837,742837,349525,349525,}, {349525,375637,742837,742837,375637,349525,349525,}, {349525,768853,742837,742837,768853,742741,742741,}, {349525,375733,742837,742837,375733,349621,349621,}, {349525,744373,767317,742741,742741,349525,349525,}, {349525,375733,767317,351157,768853,349525,349525,}, {374101,768949,374101,374101,351157,349525,349525,}, {349525,742837,742837,742837,375733,349525,349525,}, {5592405,11883957,11883957,5987157,5616981,5592405,5592405,}, {366503875925L,778827027893L,778827027893L,392374737749L,368114513237L,366503875925L,366503875925L,}, {349525,742837,375637,742837,742837,349525,349525,}, {349525,742837,742837,742837,375733,349621,375637,}, {349525,768949,351061,374101,768949,349525,349525,}, {375637,742837,768949,742837,742837,349525,349525,}, {768853,742837,768853,742837,768853,349525,349525,}, {375733,742741,742741,742741,375733,349525,349525,}, {192213,185709,185709,185709,192213,87381,87381,}, {1817525,1791317,1817429,1791317,1817525,1398101,1398101,}, {768949,742741,768853,742741,742741,349525,349525,}, {375733,742741,744373,742837,375733,349525,349525,}, {742837,742837,768949,742837,742837,349525,349525,}, {48053,23381,23381,23381,48053,21845,21845,}, {349621,349621,349621,742837,375637,349525,349525,}, {742837,744277,767317,744277,742837,349525,349525,}, {742741,742741,742741,742741,768949,349525,349525,}, {11883957,12278709,11908533,11883957,11883957,5592405,5592405,}, {11883957,12277173,11908533,11885493,11883957,5592405,5592405,}, {375637,742837,742837,742837,375637,349525,349525,}, {768853,742837,768853,742741,742741,349525,349525,}, {6010197,11885397,11909973,11885397,6010293,5592405,5592405,}, {768853,742837,768853,742837,742837,349525,349525,}, {375733,742741,375637,349621,768853,349525,349525,}, {12303285,5616981,5616981,5616981,5616981,5592405,5592405,}, {742837,742837,742837,742837,375637,349525,349525,}, {11883957,11883957,11883957,5987157,5616981,5592405,5592405,}, {3042268597L,3042268597L,3042661813L,1532713813,1437971797,1431655765,1431655765,}, {11883957,5987157,5616981,5987157,11883957,5592405,5592405,}, {11883957,5987157,5616981,5616981,5616981,5592405,5592405,}, {12303285,5593941,5616981,5985621,12303285,5592405,5592405,},}; public static void main(String[]a){ new F5(a.length>0?a[0]:"Java");} private F5(String s){ StringBuilder[]o=new StringBuilder[7]; for(int i=0;i<7;i++)o[i]=new StringBuilder(); for(int i=0,l=s.length();i<l;i++){ int c=s.charAt(i); if(65<=c&&c<=90)c-=39; else if(97<=c&&c<=122)c-=97; else c=-1; long[]d=f[++c]; for(int j=0;j<7;j++){ StringBuilder b=new StringBuilder(); long v=d[j]; while(v>0){ b.append(z[(int)(v&3)]); v>>=2;} o[j].append(b.reverse().toString());}} for(int i=0;i<7;i++){ for(int j=0;j<7-i;j++) System.out.print(' '); System.out.println(o[i]);}}}
37Write language name in 3D ASCII
9java
r5vg0
use strict; use warnings; use Tk; my $mw; my $win; my $lab; sub openWin { if( $win ) { $win->deiconify; $win->wm('state', 'normal'); } else { eval { $win->destroy } if $win; $win = $mw->Toplevel; $win->Label(-text => "This is the window being manipulated") ->pack(-fill => 'both', -expand => 1); $lab->configure(-text => "The window object is:\n$win"); } } sub closeWin { return unless $win; $win->destroy; $lab->configure(-text => ''); undef $win; } sub minimizeWin { return unless $win; $win->iconify; } sub maximizeWin { return unless $win; $win->wm('state', 'zoomed'); eval { $win->wmAttribute(-zoomed => 1) }; } sub moveWin { return unless $win; my ($x, $y) = $win->geometry() =~ /\+(\d+)\+(\d+)\z/ or die; $_ += 10 for $x, $y; $win->geometry("+$x+$y"); } sub resizeWin { return unless $win; my ($w, $h) = $win->geometry() =~ /^(\d+)x(\d+)/ or die; $_ += 10 for $w, $h; $win->geometry($w . "x" . $h); } $mw = MainWindow->new; for my $label0 ($mw->Label(-text => 'Window handle:')) { $lab = $mw->Label(-text => ''); $label0->grid($lab); } my @binit = ('Open/Restore' => \&openWin, Close => \&closeWin, Minimize => \&minimizeWin, Maximize => \&maximizeWin, Move => \&moveWin, Resize => \&resizeWin); while( my ($text, $callback) = splice @binit, 0, 2 ) { $mw->Button(-text => $text, -command => $callback)->grid('-'); } MainLoop(); __END__
40Window management
2perl
m3nyz
package main import ( "fmt" "math/big" "rcu" ) func main() { primes := rcu.Primes(5000) zero := new(big.Int) one := big.NewInt(1) num := new(big.Int) fmt.Println("Wieferich primes < 5,000:") for _, p := range primes { num.Set(one) num.Lsh(num, uint(p-1)) num.Sub(num, one) den := big.NewInt(int64(p * p)) if num.Rem(num, den).Cmp(zero) == 0 { fmt.Println(rcu.Commatize(p)) } } }
45Wieferich primes
0go
uldvt
import Darwin
33Xiaolin Wu's line algorithm
17swift
ssqt