code
stringlengths
1
46.1k
label
class label
1.18k classes
domain_label
class label
21 classes
index
stringlengths
4
5
val src = io.Source fromURL "http:
1,152Anagrams
16scala
idnox
var deficients = 0
1,161Abundant, deficient and perfect number classifications
17swift
ftxdk
from itertools import zip_longest txt = parts = [line.rstrip().split() for line in txt.splitlines()] widths = [max(len(word) for word in col) for col in zip_longest(*parts, fillvalue='')] for justify in .split(): j, jtext = justify.split('_') print(f) for line in parts: print(' '.join(f for wdth, wrd in zip(widths, line))) print( * 52)
1,160Align columns
3python
ymi6q
function integer_classification(){ var sum:number=0, i:number,j:number; var try:number=0; var number_list:number[]={1,0,0}; for(i=2;i<=20000;i++){ try=i/2; sum=1; for(j=2;j<try;j++){ if (i%j) continue; try=i/j; sum+=j; if (j!=try) sum+=try; } if (sum<i){ number_list[d]++; continue; } else if (sum>i){ number_list[a]++; continue; } number_list[p]++; } console.log('There are '+number_list[d]+ ' deficient , ' + 'number_list[p] + ' perfect and '+ number_list[a]+ ' abundant numbers between 1 and 20000'); }
1,161Abundant, deficient and perfect number classifications
20typescript
4gy53
lines <- readLines(tc <- textConnection("Given$a$text$file$of$many$lines,$where$fields$within$a$line$ are$delineated$by$a$single$'dollar'$character,$write$a$program that$aligns$each$column$of$fields$by$ensuring$that$words$in$each$ column$are$separated$by$at$least$one$space. Further,$allow$for$each$word$in$a$column$to$be$either$left$ justified,$right$justified,$or$center$justified$within$its$column.")); close(tc) words <- strsplit(lines, "\\$") maxlen <- max(sapply(words, length)) words <- lapply(words, function(x) {length(x) <- maxlen; x}) block <- matrix(unlist(words), byrow=TRUE, ncol=maxlen) block[is.na(block)] <- "" leftjust <- format(block) rightjust <- format(block, justify="right") centrejust <- format(block, justify="centre") print0 <- function(x) invisible(apply(x, 1, function(x) cat(x, "\n"))) print0(leftjust) print0(rightjust) print0(centrejust)
1,160Align columns
13r
tzsfz
import Foundation let wordsURL = NSURL(string: "http:
1,152Anagrams
17swift
q0sxg
J2justifier = {Left: :ljust, Right: :rjust, Center: :center} =begin Justify columns of textual tabular input where the record separator is the newline and the field separator is a 'dollar' character. justification can be Symbol; (:Left,:Right, or:Center). Return the justified output as a string =end def aligner(infile, justification = :Left) fieldsbyrow = infile.map {|line| line.strip.split('$')} maxfields = fieldsbyrow.map(&:length).max fieldsbyrow.map! {|row| row + ['']*(maxfields - row.length)} colwidths = fieldsbyrow.transpose.map {|column| column.map(&:length).max } justifier = J2justifier[justification] fieldsbyrow.map {|row| row.zip(colwidths).map {|field, width| field.send(justifier, width) }.join() }.join() end require 'stringio' textinfile = <<END Given$a$text$file$of$many$lines,$where$fields$within$a$line$ are$delineated$by$a$single$'dollar'$character,$write$a$program that$aligns$each$column$of$fields$by$ensuring$that$words$in$each$ column$are$separated$by$at$least$one$space. Further,$allow$for$each$word$in$a$column$to$be$either$left$ justified,$right$justified,$or$center$justified$within$its$column. END for align in [:Left, :Right, :Center] infile = StringIO.new(textinfile) puts % align puts aligner(infile, align) end
1,160Align columns
14ruby
9cdmz
use std::iter::{repeat, Extend}; enum AlignmentType { Left, Center, Right, } fn get_column_widths(text: &str) -> Vec<usize> { let mut widths = Vec::new(); for line in text .lines() .map(|s| s.trim_matches(' ').trim_end_matches('$')) { let lens = line.split('$').map(|s| s.chars().count()); for (idx, len) in lens.enumerate() { if idx < widths.len() { widths[idx] = std::cmp::max(widths[idx], len); } else { widths.push(len); } } } widths } fn align_columns(text: &str, alignment: AlignmentType) -> String { let widths = get_column_widths(text); let mut result = String::new(); for line in text .lines() .map(|s| s.trim_matches(' ').trim_end_matches('$')) { for (s, w) in line.split('$').zip(widths.iter()) { let blank_count = w - s.chars().count(); let (pre, post) = match alignment { AlignmentType::Left => (0, blank_count), AlignmentType::Center => (blank_count / 2, (blank_count + 1) / 2), AlignmentType::Right => (blank_count, 0), }; result.extend(repeat(' ').take(pre)); result.push_str(s); result.extend(repeat(' ').take(post)); result.push(' '); } result.push_str("\n"); } result } fn main() { let text = r#"Given$a$text$file$of$many$lines,$where$fields$within$a$line$ are$delineated$by$a$single$'dollar'$character,$write$a$program that$aligns$each$column$of$fields$by$ensuring$that$words$in$each$ column$are$separated$by$at$least$one$space. Further,$allow$for$each$word$in$a$column$to$be$either$left$ justified,$right$justified,$or$center$justified$within$its$column."#; println!("{}", align_columns(text, AlignmentType::Left)); println!("{}", repeat('-').take(110).collect::<String>()); println!("{}", align_columns(text, AlignmentType::Center)); println!("{}", repeat('-').take(110).collect::<String>()); println!("{}", align_columns(text, AlignmentType::Right)); }
1,160Align columns
15rust
clf9z
func Ackermann(m, n uint) uint { switch 0 { case m: return n + 1 case n: return Ackermann(m - 1, 1) } return Ackermann(m - 1, Ackermann(m, n - 1)) }
1,162Ackermann function
0go
7j9r2
object ColumnAligner { val eol = System.getProperty("line.separator") def getLines(filename: String) = scala.io.Source.fromPath(filename).getLines(eol) def splitter(line: String) = line split '$' def getTable(filename: String) = getLines(filename) map splitter def fieldWidths(fields: Array[String]) = fields map (_ length) def columnWidths(txt: Iterator[Array[String]]) = (txt map fieldWidths).toList.transpose map (_ max) def alignField(alignment: Char)(width: Int)(field: String) = alignment match { case 'l' | 'L' => "%-"+width+"s" format field case 'r' | 'R' => "%"+width+"s" format field case 'c' | 'C' => val padding = (width - field.length) / 2; " "*padding+"%-"+(width-padding)+"s" format field case _ => throw new IllegalArgumentException } def align(aligners: List[String => String])(fields: Array[String]) = aligners zip fields map Function.tupled(_ apply _) def alignFile(filename: String, alignment: Char) = { def table = getTable(filename) val aligners = columnWidths(table) map alignField(alignment) table map align(aligners) map (_ mkString " ") } def printAlignedFile(filename: String, alignment: Char) { alignFile(filename, alignment) foreach println } }
1,160Align columns
16scala
vu32s
def ack ( m, n ) { assert m >= 0 && n >= 0: 'both arguments must be non-negative' m == 0 ? n + 1: n == 0 ? ack(m-1, 1): ack(m-1, ack(m, n-1)) }
1,162Ackermann function
7groovy
u5zv9
ack :: Int -> Int -> Int ack 0 n = succ n ack m 0 = ack (pred m) 1 ack m n = ack (pred m) (ack m (pred n)) main :: IO () main = mapM_ print $ uncurry ack <$> [(0, 0), (3, 4)]
1,162Ackermann function
8haskell
8ob0z
import Foundation extension String { func dropLastIf(_ char: Character) -> String { if last == char { return String(dropLast()) } else { return self } } } enum Align { case left, center, right } func getLines(input: String) -> [String] { input .components(separatedBy: "\n") .map({ $0.replacingOccurrences(of: " ", with: "").dropLastIf("$") }) } func getColWidths(from: String) -> [Int] { var widths = [Int]() let lines = getLines(input: from) for line in lines { let lens = line.components(separatedBy: "$").map({ $0.count }) for (i, len) in lens.enumerated() { if i < widths.count { widths[i] = max(widths[i], len) } else { widths.append(len) } } } return widths } func alignCols(input: String, align: Align = .left) -> String { let widths = getColWidths(from: input) let lines = getLines(input: input) var res = "" for line in lines { for (str, width) in zip(line.components(separatedBy: "$"), widths) { let blanks = width - str.count let pre: Int, post: Int switch align { case .left: (pre, post) = (0, blanks) case .center: (pre, post) = (blanks / 2, (blanks + 1) / 2) case .right: (pre, post) = (blanks, 0) } res += String(repeating: " ", count: pre) res += str res += String(repeating: " ", count: post) res += " " } res += "\n" } return res } let input = """ Given$a$text$file$of$many$lines,$where$fields$within$a$line$ are$delineated$by$a$single$'dollar'$character,$write$a$program that$aligns$each$column$of$fields$by$ensuring$that$words$in$each$ column$are$separated$by$at$least$one$space. Further,$allow$for$each$word$in$a$column$to$be$either$left$ justified,$right$justified,$or$center$justified$within$its$column. """ print(alignCols(input: input)) print() print(alignCols(input: input, align: .center)) print() print(alignCols(input: input, align: .right))
1,160Align columns
17swift
m9nyk
import java.math.BigInteger; public static BigInteger ack(BigInteger m, BigInteger n) { return m.equals(BigInteger.ZERO) ? n.add(BigInteger.ONE) : ack(m.subtract(BigInteger.ONE), n.equals(BigInteger.ZERO) ? BigInteger.ONE : ack(m, n.subtract(BigInteger.ONE))); }
1,162Ackermann function
9java
ewga5
function ack(m, n) { return m === 0 ? n + 1 : ack(m - 1, n === 0 ? 1 : ack(m, n - 1)); }
1,162Ackermann function
10javascript
08ksz
tailrec fun A(m: Long, n: Long): Long { require(m >= 0L) { "m must not be negative" } require(n >= 0L) { "n must not be negative" } if (m == 0L) { return n + 1L } if (n == 0L) { return A(m - 1L, 1L) } return A(m - 1L, A(m, n - 1L)) } inline fun<T> tryOrNull(block: () -> T): T? = try { block() } catch (e: Throwable) { null } const val N = 10L const val M = 4L fun main() { (0..M) .map { it to 0..N } .map { (m, Ns) -> (m to Ns) to Ns.map { n -> tryOrNull { A(m, n) } } } .map { (input, output) -> "A(${input.first}, ${input.second})" to output.map { it?.toString() ?: "?" } } .map { (input, output) -> "$input = $output" } .forEach(::println) }
1,162Ackermann function
11kotlin
kb2h3
function ack(M,N) if M == 0 then return N + 1 end if N == 0 then return ack(M-1,1) end return ack(M-1,ack(M, N-1)) end
1,162Ackermann function
1lua
bpvka
int main(int argc, char** argv) { int i,j,sandPileEdge, centerPileHeight, processAgain = 1,top,down,left,right; int** sandPile; char* fileName; static unsigned char colour[3]; if(argc!=3){ printf(,argv[0]); return 0; } sandPileEdge = atoi(argv[1]); centerPileHeight = atoi(argv[2]); if(sandPileEdge<=0 || centerPileHeight<=0){ printf(); return 0; } sandPile = (int**)malloc(sandPileEdge * sizeof(int*)); for(i=0;i<sandPileEdge;i++){ sandPile[i] = (int*)calloc(sandPileEdge,sizeof(int)); } sandPile[sandPileEdge/2][sandPileEdge/2] = centerPileHeight; printf(); for(i=0;i<sandPileEdge;i++){ for(j=0;j<sandPileEdge;j++){ printf(,sandPile[i][j]); } printf(); } while(processAgain == 1){ processAgain = 0; top = 0; down = 0; left = 0; right = 0; for(i=0;i<sandPileEdge;i++){ for(j=0;j<sandPileEdge;j++){ if(sandPile[i][j]>=4){ if(i-1>=0){ top = 1; sandPile[i-1][j]+=1; if(sandPile[i-1][j]>=4) processAgain = 1; } if(i+1<sandPileEdge){ down = 1; sandPile[i+1][j]+=1; if(sandPile[i+1][j]>=4) processAgain = 1; } if(j-1>=0){ left = 1; sandPile[i][j-1]+=1; if(sandPile[i][j-1]>=4) processAgain = 1; } if(j+1<sandPileEdge){ right = 1; sandPile[i][j+1]+=1; if(sandPile[i][j+1]>=4) processAgain = 1; } sandPile[i][j] -= (top + down + left + right); if(sandPile[i][j]>=4) processAgain = 1; } } } } printf(); for(i=0;i<sandPileEdge;i++){ for(j=0;j<sandPileEdge;j++){ printf(,sandPile[i][j]); } printf(); } fileName = (char*)malloc((strlen(argv[1]) + strlen(argv[2]) + 23)*sizeof(char)); strcpy(fileName,); strcat(fileName,argv[1]); strcat(fileName,); strcat(fileName,argv[2]); strcat(fileName,); FILE *fp = fopen(fileName,); fprintf(fp,,sandPileEdge,sandPileEdge); for(i=0;i<sandPileEdge;i++){ for(j=0;j<sandPileEdge;j++){ colour[0] = (sandPile[i][j] + i)%256; colour[1] = (sandPile[i][j] + j)%256; colour[2] = (sandPile[i][j] + i*j)%256; fwrite(colour,1,3,fp); } } fclose(fp); printf(,fileName); return 0; }
1,163Abelian sandpile model
5c
ew4av
const char* command_table = ; typedef struct command_tag { char* cmd; size_t length; size_t min_len; struct command_tag* next; } command_t; bool command_match(const command_t* command, const char* str) { size_t olen = strlen(str); return olen >= command->min_len && olen <= command->length && strncmp(str, command->cmd, olen) == 0; } char* uppercase(char* str, size_t n) { for (size_t i = 0; i < n; ++i) str[i] = toupper((unsigned char)str[i]); return str; } void fatal(const char* message) { fprintf(stderr, , message); exit(1); } void* xmalloc(size_t n) { void* ptr = malloc(n); if (ptr == NULL) fatal(); return ptr; } void* xrealloc(void* p, size_t n) { void* ptr = realloc(p, n); if (ptr == NULL) fatal(); return ptr; } char** split_into_words(const char* str, size_t* count) { size_t size = 0; size_t capacity = 16; char** words = xmalloc(capacity * sizeof(char*)); size_t len = strlen(str); for (size_t begin = 0; begin < len; ) { size_t i = begin; for (; i < len && isspace((unsigned char)str[i]); ++i) {} begin = i; for (; i < len && !isspace((unsigned char)str[i]); ++i) {} size_t word_len = i - begin; if (word_len == 0) break; char* word = xmalloc(word_len + 1); memcpy(word, str + begin, word_len); word[word_len] = 0; begin += word_len; if (capacity == size) { capacity *= 2; words = xrealloc(words, capacity * sizeof(char*)); } words[size++] = word; } *count = size; return words; } command_t* make_command_list(const char* table) { command_t* cmd = NULL; size_t count = 0; char** words = split_into_words(table, &count); for (size_t i = 0; i < count; ++i) { char* word = words[i]; command_t* new_cmd = xmalloc(sizeof(command_t)); size_t word_len = strlen(word); new_cmd->length = word_len; new_cmd->min_len = word_len; new_cmd->cmd = uppercase(word, word_len); if (i + 1 < count) { char* eptr = 0; unsigned long min_len = strtoul(words[i + 1], &eptr, 10); if (min_len > 0 && *eptr == 0) { free(words[i + 1]); new_cmd->min_len = min_len; ++i; } } new_cmd->next = cmd; cmd = new_cmd; } free(words); return cmd; } void free_command_list(command_t* cmd) { while (cmd != NULL) { command_t* next = cmd->next; free(cmd->cmd); free(cmd); cmd = next; } } const command_t* find_command(const command_t* commands, const char* word) { for (const command_t* cmd = commands; cmd != NULL; cmd = cmd->next) { if (command_match(cmd, word)) return cmd; } return NULL; } void test(const command_t* commands, const char* input) { printf(, input); printf(); size_t count = 0; char** words = split_into_words(input, &count); for (size_t i = 0; i < count; ++i) { char* word = words[i]; uppercase(word, strlen(word)); const command_t* cmd_ptr = find_command(commands, word); printf(, cmd_ptr ? cmd_ptr->cmd : ); free(word); } free(words); printf(); } int main() { command_t* commands = make_command_list(command_table); const char* input = ; test(commands, input); free_command_list(commands); return 0; }
1,164Abbreviations, simple
5c
xqgwu
(defn words "Split string into words" [^String str] (.split (.stripLeading str) "\\s+")) (defn join-words "Join words into a single string" ^String [strings] (String/join " " strings)) (defn starts-with-ignore-case "Does string start with prefix (ignoring case)?" ^Boolean [^String string, ^String prefix] (.regionMatches string true 0 prefix 0 (count prefix))) (defrecord CommandWord [^String word, ^long min-abbr-size]) (defn parse-cmd-table "Parse list of strings in command table into list of words and numbers If number is missing for any word, then the word is not included" ([cmd-table] (parse-cmd-table cmd-table 0 [])) ([cmd-table i ans] (let [cmd-count (count cmd-table)] (if (= i cmd-count) ans (let [word (nth cmd-table i), [i num] (try [(+ i 2) (Integer/parseInt ^String (nth cmd-table (inc i)))] (catch NumberFormatException _ [(inc i) 0]))] (recur cmd-table i (conj ans (CommandWord. word num)))))))) (def cmd-table (-> "add 1 alter 3 backup 2 bottom 1 Cappend 2 change 1 Schange Cinsert 2 Clast 3 compress 4 copy 2 count 3 Coverlay 3 cursor 3 delete 3 Cdelete 2 down 1 duplicate 3 xEdit 1 expand 3 extract 3 find 1 Nfind 2 Nfindup 6 NfUP 3 Cfind 2 findUP 3 fUP 2 forward 2 get help 1 hexType 4 input 1 powerInput 3 join 1 split 2 spltJOIN load locate 1 Clocate 2 lowerCase 3 upperCase 3 Lprefix 2 macro merge 2 modify 3 move 2 msg next 1 overlay 1 parse preserve 4 purge 3 put putD query 1 quit read recover 3 refresh renum 3 repeat 3 replace 1 Creplace 2 reset 3 restore 4 rgtLEFT right 2 left 2 save set shift 2 si sort sos stack 3 status 4 top transfer 3 type 1 up 1" words parse-cmd-table)) (defn abbr? "Is abbr a valid abbreviation of this command?" ^Boolean [^String abbr, ^CommandWord cmd] (let [{:keys [word min-abbr-size]} cmd] (and (<= min-abbr-size (count abbr) (count word)) (starts-with-ignore-case word abbr)))) (defn solution "Find word matching each abbreviation in input (or *error* if not found), and join results into a string" ^String [^String str] (join-words (for [abbr (words str)] (if-let [{:keys [word]} (first (filter #(abbr? abbr %) cmd-table))] (.toUpperCase ^String word) "*error*")))) (println (solution "riG rePEAT copies put mo rest types fup. 6 poweRin"))
1,164Abbreviations, simple
6clojure
oik8j
const char* command_table = ; typedef struct command_tag { char* cmd; size_t length; size_t min_len; struct command_tag* next; } command_t; bool command_match(const command_t* command, const char* str) { size_t olen = strlen(str); return olen >= command->min_len && olen <= command->length && strncmp(str, command->cmd, olen) == 0; } char* uppercase(char* str, size_t n) { for (size_t i = 0; i < n; ++i) str[i] = toupper((unsigned char)str[i]); return str; } size_t get_min_length(const char* str, size_t n) { size_t len = 0; while (len < n && isupper((unsigned char)str[len])) ++len; return len; } void fatal(const char* message) { fprintf(stderr, , message); exit(1); } void* xmalloc(size_t n) { void* ptr = malloc(n); if (ptr == NULL) fatal(); return ptr; } void* xrealloc(void* p, size_t n) { void* ptr = realloc(p, n); if (ptr == NULL) fatal(); return ptr; } char** split_into_words(const char* str, size_t* count) { size_t size = 0; size_t capacity = 16; char** words = xmalloc(capacity * sizeof(char*)); size_t len = strlen(str); for (size_t begin = 0; begin < len; ) { size_t i = begin; for (; i < len && isspace((unsigned char)str[i]); ++i) {} begin = i; for (; i < len && !isspace((unsigned char)str[i]); ++i) {} size_t word_len = i - begin; if (word_len == 0) break; char* word = xmalloc(word_len + 1); memcpy(word, str + begin, word_len); word[word_len] = 0; begin += word_len; if (capacity == size) { capacity *= 2; words = xrealloc(words, capacity * sizeof(char*)); } words[size++] = word; } *count = size; return words; } command_t* make_command_list(const char* table) { command_t* cmd = NULL; size_t count = 0; char** words = split_into_words(table, &count); for (size_t i = 0; i < count; ++i) { char* word = words[i]; command_t* new_cmd = xmalloc(sizeof(command_t)); size_t word_len = strlen(word); new_cmd->length = word_len; new_cmd->min_len = get_min_length(word, word_len); new_cmd->cmd = uppercase(word, word_len); new_cmd->next = cmd; cmd = new_cmd; } free(words); return cmd; } void free_command_list(command_t* cmd) { while (cmd != NULL) { command_t* next = cmd->next; free(cmd->cmd); free(cmd); cmd = next; } } const command_t* find_command(const command_t* commands, const char* word) { for (const command_t* cmd = commands; cmd != NULL; cmd = cmd->next) { if (command_match(cmd, word)) return cmd; } return NULL; } void test(const command_t* commands, const char* input) { printf(, input); printf(); size_t count = 0; char** words = split_into_words(input, &count); for (size_t i = 0; i < count; ++i) { char* word = words[i]; uppercase(word, strlen(word)); const command_t* cmd_ptr = find_command(commands, word); printf(, cmd_ptr ? cmd_ptr->cmd : ); free(word); } free(words); printf(); } int main() { command_t* commands = make_command_list(command_table); const char* input = ; test(commands, input); free_command_list(commands); return 0; }
1,165Abbreviations, easy
5c
ymq6f
(defn words [str] "Split string into words" (.split str "\\s+")) (defn join-words [strings] "Join words into a single string" (clojure.string/join " " strings)) (def cmd-table "Command Table - List of words to match against" (words "Add ALTer BAckup Bottom CAppend Change SCHANGE CInsert CLAst COMPress COpy COUnt COVerlay CURsor DELete CDelete Down DUPlicate Xedit EXPand EXTract Find NFind NFINDUp NFUp CFind FINdup FUp FOrward GET Help HEXType Input POWerinput Join SPlit SPLTJOIN LOAD Locate CLocate LOWercase UPPercase LPrefix MACRO MErge MODify MOve MSG Next Overlay PARSE PREServe PURge PUT PUTD Query QUIT READ RECover REFRESH RENum REPeat Replace CReplace RESet RESTore RGTLEFT RIght LEft SAVE SET SHift SI SORT SOS STAck STATus TOP TRAnsfer Type Up")) (defn abbr-valid? "Is abbr abbreviation of word?" [abbr word] (and (.startsWith (.toLowerCase word) (.toLowerCase abbr)) (<= (count (filter #(Character/isUpperCase %) word)) (count abbr) (count word)))) (defn find-word-for-abbr "Find first word matching abbreviation, or nil if not found" [abbr] (first (filter #(abbr-valid? abbr %) cmd-table))) (defn solution "Find word matching each abbreviation in input (or *error* if not found), and join results into a string" [str] (join-words (for [abbr (words str)] (if-let [word (find-word-for-abbr abbr)] (.toUpperCase word) "*error*")))) (print (solution "riG rePEAT copies put mo rest types fup. 6 poweRin"))
1,165Abbreviations, easy
6clojure
2vil1
package main import ( "fmt" "log" "os" "strings" ) const dim = 16
1,163Abelian sandpile model
0go
9comt
module Rosetta.AbelianSandpileModel.ST ( simulate , test , toPGM ) where import Control.Monad.Reader (asks, MonadReader (..), ReaderT, runReaderT) import Control.Monad.ST (runST, ST) import Control.Monad.State (evalStateT, forM_, lift, MonadState (..), StateT, modify, when) import Data.Array.ST (freeze, readArray, STUArray, thaw, writeArray) import Data.Array.Unboxed (array, assocs, bounds, UArray, (!)) import Data.Word (Word32) import System.IO (hPutStr, hPutStrLn, IOMode (WriteMode), withFile) import Text.Printf (printf) type Point = (Int, Int) type ArrayST s = STUArray s Point Word32 type ArrayU = UArray Point Word32 newtype M s a = M (ReaderT (S s) (StateT [Point] (ST s)) a) deriving (Functor, Applicative, Monad, MonadReader (S s), MonadState [Point]) data S s = S { bMin :: !Point , bMax :: !Point , arr :: !(ArrayST s) } runM :: M s a -> S s -> [Point]-> ST s a runM (M m) = evalStateT . runReaderT m liftST :: ST s a -> M s a liftST = M . lift . lift simulate :: ArrayU -> ArrayU simulate a = runST $ simulateST a simulateST :: forall s. ArrayU -> ST s ArrayU simulateST a = do let (p1, p2) = bounds a s = [p | (p, c) <- assocs a, c >= 4] b <- thaw a :: ST s (ArrayST s) let st = S { bMin = p1 , bMax = p2 , arr = b } runM simulateM st s simulateM :: forall s. M s ArrayU simulateM = do ps <- get case ps of [] -> asks arr >>= liftST . freeze p: ps' -> do c <- changeArr p $ \x -> x - 4 when (c < 4) $ put ps' forM_ [north, east, south, west] $ inc . ($ p) simulateM changeArr :: Point -> (Word32 -> Word32) -> M s Word32 changeArr p f = do a <- asks arr oldC <- liftST $ readArray a p let newC = f oldC liftST $ writeArray a p newC return newC inc :: Point -> M s () inc p = do b <- inBounds p when b $ do c <- changeArr p succ when (c == 4) $ modify $ (p:) inBounds :: Point -> M s Bool inBounds p = do st <- ask return $ p >= bMin st && p <= bMax st north, east, south, west :: Point -> Point north (x, y) = (x, y + 1) east (x, y) = (x + 1, y) south (x, y) = (x, y - 1) west (x, y) = (x - 1, y) toPGM :: ArrayU -> FilePath -> IO () toPGM a fp = withFile fp WriteMode $ \h -> do let ((x1, y1), (x2, y2)) = bounds a width = x2 - x1 + 1 height = y2 - y1 + 1 hPutStrLn h "P2" hPutStrLn h $ show width ++ " " ++ show height hPutStrLn h "3" forM_ [y1 .. y2] $ \y -> do forM_ [x1 .. x2] $ \x -> do let c = min 3 $ a ! (x, y) hPutStr h $ show c ++ " " hPutStrLn h "" initArray :: Int -> Word32 -> ArrayU initArray size height = array ((-size, -size), (size, size)) [((x, y), if x == 0 && y == 0 then height else 0) | x <- [-size .. size], y <- [-size .. size]] test :: Int -> Word32 -> IO () test size height = do printf "size =%d, height =%d\n" size height let a = initArray size height b = simulate a fp = printf "sandpile_%d_%d.pgm" size height toPGM b fp putStrLn $ "wrote image to " ++ fp
1,163Abelian sandpile model
8haskell
bp2k2
package main import ( "fmt" "strings" ) var table = "Add ALTer BAckup Bottom CAppend Change SCHANGE CInsert CLAst COMPress COpy " + "COUnt COVerlay CURsor DELete CDelete Down DUPlicate Xedit EXPand EXTract Find " + "NFind NFINDUp NFUp CFind FINdup FUp FOrward GET Help HEXType Input POWerinput " + "Join SPlit SPLTJOIN LOAD Locate CLocate LOWercase UPPercase LPrefix MACRO " + "MErge MODify MOve MSG Next Overlay PARSE PREServe PURge PUT PUTD Query QUIT " + "READ RECover REFRESH RENum REPeat Replace CReplace RESet RESTore RGTLEFT " + "RIght LEft SAVE SET SHift SI SORT SOS STAck STATus TOP TRAnsfer Type Up " func validate(commands, words []string, minLens []int) []string { results := make([]string, 0) if len(words) == 0 { return results } for _, word := range words { matchFound := false wlen := len(word) for i, command := range commands { if minLens[i] == 0 || wlen < minLens[i] || wlen > len(command) { continue } c := strings.ToUpper(command) w := strings.ToUpper(word) if strings.HasPrefix(c, w) { results = append(results, c) matchFound = true break } } if !matchFound { results = append(results, "*error*") } } return results } func main() { table = strings.TrimSpace(table) commands := strings.Fields(table) clen := len(commands) minLens := make([]int, clen) for i := 0; i < clen; i++ { count := 0 for _, c := range commands[i] { if c >= 'A' && c <= 'Z' { count++ } } minLens[i] = count } sentence := "riG rePEAT copies put mo rest types fup. 6 poweRin" words := strings.Fields(sentence) results := validate(commands, words, minLens) fmt.Print("user words: ") for j := 0; j < len(words); j++ { fmt.Printf("%-*s ", len(results[j]), words[j]) } fmt.Print("\nfull words: ") fmt.Println(strings.Join(results, " ")) }
1,165Abbreviations, easy
0go
1a2p5
typedef struct sAbstractCls *AbsCls; typedef struct sAbstractMethods { int (*method1)(AbsCls c, int a); const char *(*method2)(AbsCls c, int b); void (*method3)(AbsCls c, double d); } *AbstractMethods, sAbsMethods; struct sAbstractCls { AbstractMethods klass; void *instData; }; static sAbsMethods cName AbsCls cName AbsCls ac = malloc(sizeof(struct sAbstractCls)); \ if (ac) { \ ac->klass = &cName ac->instData = clInst; \ }\ return ac; } do { if (c) { free((c)->instData); free(c); } } while(0);
1,166Abstract type
5c
vui2o
import java.awt.*; import java.awt.event.*; import javax.swing.*; public class AbelianSandpile { public static void main(String[] args) { SwingUtilities.invokeLater(new Runnable() { public void run() { Frame frame = new Frame(); frame.setVisible(true); } }); } private static class Frame extends JFrame { private Frame() { super("Abelian Sandpile Model"); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); Container contentPane = getContentPane(); JPanel controlPanel = new JPanel(new FlowLayout(FlowLayout.LEFT)); JButton start = new JButton("Restart Simulation"); start.addActionListener(e -> restartSimulation()); JButton stop = new JButton("Stop Simulation"); stop.addActionListener(e -> stopSimulation()); controlPanel.add(start); controlPanel.add(stop); contentPane.add(controlPanel, BorderLayout.NORTH); contentPane.add(canvas = new Canvas(), BorderLayout.CENTER); timer = new Timer(100, e -> canvas.runAndDraw()); timer.start(); pack(); } private void restartSimulation() { timer.stop(); canvas.initGrid(); timer.start(); } private void stopSimulation() { timer.stop(); } private Timer timer; private Canvas canvas; } private static class Canvas extends JComponent { private Canvas() { setBorder(BorderFactory.createEtchedBorder()); setPreferredSize(new Dimension(600, 600)); } public void paintComponent(Graphics g) { int width = getWidth(); int height = getHeight(); g.setColor(Color.WHITE); g.fillRect(0, 0, width, height); int cellWidth = width/GRID_LENGTH; int cellHeight = height/GRID_LENGTH; for (int i = 0; i < GRID_LENGTH; ++i) { for (int j = 0; j < GRID_LENGTH; ++j) { if (grid[i][j] > 0) { g.setColor(COLORS[grid[i][j]]); g.fillRect(i * cellWidth, j * cellHeight, cellWidth, cellHeight); } } } } private void initGrid() { for (int i = 0; i < GRID_LENGTH; ++i) { for (int j = 0; j < GRID_LENGTH; ++j) { grid[i][j] = 0; } } } private void runAndDraw() { for (int i = 0; i < 100; ++i) addSand(GRID_LENGTH/2, GRID_LENGTH/2); repaint(); } private void addSand(int i, int j) { int grains = grid[i][j]; if (grains < 3) { grid[i][j]++; } else { grid[i][j] = grains - 3; if (i > 0) addSand(i - 1, j); if (i < GRID_LENGTH - 1) addSand(i + 1, j); if (j > 0) addSand(i, j - 1); if (j < GRID_LENGTH - 1) addSand(i, j + 1); } } private int[][] grid = new int[GRID_LENGTH][GRID_LENGTH]; } private static final Color[] COLORS = { Color.WHITE, new Color(0x00, 0xbf, 0xff), new Color(0xff, 0xd7, 0x00), new Color(0xb0, 0x30, 0x60) }; private static final int GRID_LENGTH = 300; }
1,163Abelian sandpile model
9java
gr64m
package main import ( "io" "os" "strconv" "strings" "text/tabwriter" ) func readTable(table string) ([]string, []int) { fields := strings.Fields(table) var commands []string var minLens []int for i, max := 0, len(fields); i < max; { cmd := fields[i] cmdLen := len(cmd) i++ if i < max { num, err := strconv.Atoi(fields[i]) if err == nil && 1 <= num && num < cmdLen { cmdLen = num i++ } } commands = append(commands, cmd) minLens = append(minLens, cmdLen) } return commands, minLens } func validateCommands(commands []string, minLens []int, words []string) []string { var results []string for _, word := range words { matchFound := false wlen := len(word) for i, command := range commands { if minLens[i] == 0 || wlen < minLens[i] || wlen > len(command) { continue } c := strings.ToUpper(command) w := strings.ToUpper(word) if strings.HasPrefix(c, w) { results = append(results, c) matchFound = true break } } if !matchFound { results = append(results, "*error*") } } return results } func printResults(words []string, results []string) { wr := tabwriter.NewWriter(os.Stdout, 0, 1, 1, ' ', 0) io.WriteString(wr, "user words:") for _, word := range words { io.WriteString(wr, "\t"+word) } io.WriteString(wr, "\n") io.WriteString(wr, "full words:\t"+strings.Join(results, "\t")+"\n") wr.Flush() } func main() { const table = "" + "add 1 alter 3 backup 2 bottom 1 Cappend 2 change 1 Schange Cinsert 2 Clast 3 " + "compress 4 copy 2 count 3 Coverlay 3 cursor 3 delete 3 Cdelete 2 down 1 duplicate " + "3 xEdit 1 expand 3 extract 3 find 1 Nfind 2 Nfindup 6 NfUP 3 Cfind 2 findUP 3 fUP 2 " + "forward 2 get help 1 hexType 4 input 1 powerInput 3 join 1 split 2 spltJOIN load " + "locate 1 Clocate 2 lowerCase 3 upperCase 3 Lprefix 2 macro merge 2 modify 3 move 2 " + "msg next 1 overlay 1 parse preserve 4 purge 3 put putD query 1 quit read recover 3 " + "refresh renum 3 repeat 3 replace 1 Creplace 2 reset 3 restore 4 rgtLEFT right 2 left " + "2 save set shift 2 si sort sos stack 3 status 4 top transfer 3 type 1 up 1 " const sentence = "riG rePEAT copies put mo rest types fup. 6 poweRin" commands, minLens := readTable(table) words := strings.Fields(sentence) results := validateCommands(commands, minLens, words) printResults(words, results) }
1,164Abbreviations, simple
0go
l2icw
import Data.Maybe (fromMaybe) import Data.List (find, isPrefixOf) import Data.Char (toUpper, isUpper) isAbbreviationOf :: String -> String -> Bool isAbbreviationOf abbreviation command = minimumPrefix `isPrefixOf` normalizedAbbreviation && normalizedAbbreviation `isPrefixOf` normalizedCommand where normalizedAbbreviation = map toUpper abbreviation normalizedCommand = map toUpper command minimumPrefix = takeWhile isUpper command expandAbbreviation :: String -> String -> Maybe String expandAbbreviation commandTable abbreviation = do command <- find (isAbbreviationOf abbreviation) (words commandTable) return $ map toUpper command commandTable = unwords [ "Add ALTer BAckup Bottom CAppend Change SCHANGE CInsert CLAst COMPress COpy", "COUnt COVerlay CURsor DELete CDelete Down DUPlicate Xedit EXPand EXTract Find", "NFind NFINDUp NFUp CFind FINdup FUp FOrward GET Help HEXType Input POWerinput", "Join SPlit SPLTJOIN LOAD Locate CLocate LOWercase UPPercase LPrefix MACRO", "MErge MODify MOve MSG Next Overlay PARSE PREServe PURge PUT PUTD Query QUIT", "READ RECover REFRESH RENum REPeat Replace CReplace RESet RESTore RGTLEFT", "RIght LEft SAVE SET SHift SI SORT SOS STAck STATus TOP TRAnsfer Type Up"] main :: IO () main = do input <- getLine let abbreviations = words input let commands = map (fromMaybe "*error*" . expandAbbreviation commandTable) abbreviations putStrLn $ unwords results
1,165Abbreviations, easy
8haskell
tzaf7
package main import ( "fmt" "strconv" "strings" ) type sandpile struct{ a [9]int } var neighbors = [][]int{ {1, 3}, {0, 2, 4}, {1, 5}, {0, 4, 6}, {1, 3, 5, 7}, {2, 4, 8}, {3, 7}, {4, 6, 8}, {5, 7}, }
1,167Abelian sandpile model/Identity
0go
08gsk
local sandpile = { init = function(self, dim, val) self.cell, self.dim = {}, dim for r = 1, dim do self.cell[r] = {} for c = 1, dim do self.cell[r][c] = 0 end end self.cell[math.floor(dim/2)+1][math.floor(dim/2)+1] = val end, iter = function(self) local dim, cel, more = self.dim, self.cell repeat more = false for r = 1, dim do for c = 1, dim do if cel[r][c] >= 4 then cel[r][c] = cel[r][c] - 4 if c > 1 then cel[r][c-1], more = cel[r][c-1]+1, more or cel[r][c-1]>=3 end if c < dim then cel[r][c+1], more = cel[r][c+1]+1, more or cel[r][c+1]>=3 end if r > 1 then cel[r-1][c], more = cel[r-1][c]+1, more or cel[r-1][c]>=3 end if r < dim then cel[r+1][c], more = cel[r+1][c]+1, more or cel[r+1][c]>=3 end end more = more or cel[r][c] >= 4 end end until not more end, draw = function(self) for r = 1, self.dim do print(table.concat(self.cell[r]," ")) end end, } sandpile:init(15, 256) sandpile:iter() sandpile:draw()
1,163Abelian sandpile model
1lua
vuf2x
import Data.List (find, isPrefixOf) import Data.Char (isDigit, toUpper) import Data.Maybe (maybe) withExpansions :: [(String, Int)] -> String -> String withExpansions tbl s = unwords $ expanded tbl <$> words s expanded :: [(String, Int)] -> String -> String expanded tbl k = maybe "*error" fst (expand k) where expand [] = Just ([], 0) expand s = let u = toUpper <$> s lng = length s in find (\(w, n) -> lng >= n && isPrefixOf u w) tbl cmdsFromString :: String -> [(String, Int)] cmdsFromString s = let go w@(x:_) (xs, n) | isDigit x = (xs, read w :: Int) | otherwise = ((toUpper <$> w, n): xs, 0) in fst $ foldr go ([], 0) (words s) table :: [(String, Int)] table = cmdsFromString "add 1 alter 3 backup 2 bottom 1 Cappend 2 change 1 \ \Schange Cinsert 2 Clast 3 compress 4 copy 2 count 3 Coverlay 3 \ \cursor 3 delete 3 Cdelete 2 down 1 duplicate 3 xEdit 1 expand 3 \ \extract 3 find 1 Nfind 2 Nfindup 6 NfUP 3 Cfind 2 findUP 3 fUP 2 \ \forward 2 get help 1 hexType 4 input 1 powerInput 3 join 1 \ \split 2 spltJOIN load locate 1 Clocate 2 lowerCase 3 upperCase 3 \ \Lprefix 2 macro merge 2 modify 3 move 2 msg next 1 overlay 1 \ \parse preserve 4 purge 3 put putD query 1 quit read recover 3 \ \refresh renum 3 repeat 3 replace 1 Creplace 2 reset 3 restore 4 \ \rgtLEFT right 2 left 2 save set shift 2 si sort sos stack 3 \ \status 4 top transfer 3 type 1 up 1" main :: IO () main = do let unAbbrev = withExpansions table print $ unAbbrev "riG rePEAT copies put mo rest types fup. 6 poweRin" print $ unAbbrev ""
1,164Abbreviations, simple
8haskell
1avps
import java.util.HashMap; import java.util.Map; import java.util.Scanner; public class AbbreviationsEasy { private static final Scanner input = new Scanner(System.in); private static final String COMMAND_TABLE = " Add ALTer BAckup Bottom CAppend Change SCHANGE CInsert CLAst COMPress COpy\n" + " COUnt COVerlay CURsor DELete CDelete Down DUPlicate Xedit EXPand EXTract Find\n" + " NFind NFINDUp NFUp CFind FINdup FUp FOrward GET Help HEXType Input POWerinput\n" + " Join SPlit SPLTJOIN LOAD Locate CLocate LOWercase UPPercase LPrefix MACRO\n" + " MErge MODify MOve MSG Next Overlay PARSE PREServe PURge PUT PUTD Query QUIT\n" + " READ RECover REFRESH RENum REPeat Replace CReplace RESet RESTore RGTLEFT\n" + " RIght LEft SAVE SET SHift SI SORT SOS STAck STATus TOP TRAnsfer Type Up"; public static void main(String[] args) { String[] cmdTableArr = COMMAND_TABLE.split("\\s+"); Map<String, Integer> cmd_table = new HashMap<String, Integer>(); for (String word : cmdTableArr) {
1,165Abbreviations, easy
9java
8oj06
import Data.List (findIndex, transpose) import Data.List.Split (chunksOf) main :: IO () main = do let s0 = [[4, 3, 3], [3, 1, 2], [0, 2, 3]] s1 = [[1, 2, 0], [2, 1, 1], [0, 1, 3]] s2 = [[2, 1, 3], [1, 0, 1], [0, 1, 0]] s3_id = [[2, 1, 2], [1, 0, 1], [2, 1, 2]] s3 = replicate 3 (replicate 3 3) x:xs = reverse $ cascade s0 mapM_ putStrLn [ "Cascade:" , showCascade $ ([], x): fmap ("->", ) xs , "s1 + s2 == s2 + s1 -> " <> show (addSand s1 s2 == addSand s2 s1) , showCascade [([], s1), (" +", s2), (" =", addSand s1 s2)] , showCascade [([], s2), (" +", s1), (" =", addSand s2 s1)] , "s3 + s3_id == s3 -> " <> show (addSand s3 s3_id == s3) , showCascade [([], s3), (" +", s3_id), (" =", addSand s3 s3_id)] , "s3_id + s3_id == s3_id -> " <> show (addSand s3_id s3_id == s3_id) , showCascade [([], s3_id), (" +", s3_id), (" =", addSand s3_id s3_id)] ] addSand :: [[Int]] -> [[Int]] -> [[Int]] addSand xs ys = (head . cascade . chunksOf (length xs)) $ zipWith (+) (concat xs) (concat ys) cascade :: [[Int]] -> [[[Int]]] cascade xs = chunksOf w <$> convergence (==) (iterate (tumble w) (concat xs)) where w = length xs convergence :: (a -> a -> Bool) -> [a] -> [a] convergence p = go where go (x:ys@(y:_)) | p x y = [x] | otherwise = go ys <> [x] tumble :: Int -> [Int] -> [Int] tumble w xs = maybe xs go $ findIndex (w <) xs where go i = zipWith f [0 ..] xs where neighbours = indexNeighbours w i f j x | j `elem` neighbours = succ x | i == j = x - succ w | otherwise = x indexNeighbours :: Int -> Int -> [Int] indexNeighbours w = go where go i = concat [ [ j | j <- [i - w, i + w] , -1 < j , wSqr > j ] , [ pred i | 0 /= col ] , [ succ i | pred w /= col ] ] where wSqr = w * w col = rem i w showCascade :: [(String, [[Int]])] -> String showCascade pairs = unlines $ fmap unwords $ transpose $ fmap (\(pfx, xs) -> unwords <$> transpose (centered pfx: transpose (fmap (fmap show) xs))) pairs centered :: String -> [String] centered s = [pad, s, pad <> replicate r ' '] where lng = length s pad = replicate lng ' ' (q, r) = quotRem (2 + lng) 2
1,167Abelian sandpile model/Identity
8haskell
cls94
(defprotocol Foo (foo [this]))
1,166Abstract type
6clojure
r7zg2
var abr=`Add ALTer BAckup Bottom CAppend Change SCHANGE CInsert CLAst COMPress COpy COUnt COVerlay CURsor DELete CDelete Down DUPlicate Xedit EXPand EXTract Find NFind NFINDUp NFUp CFind FINdup FUp FOrward GET Help HEXType Input POWerinput Join SPlit SPLTJOIN LOAD Locate CLocate LOWercase UPPercase LPrefix MACRO MErge MODify MOve MSG Next Overlay PARSE PREServe PURge PUT PUTD Query QUIT READ RECover REFRESH RENum REPeat Replace CReplace RESet RESTore RGTLEFT RIght LEft SAVE SET SHift SI SORT SOS STAck STATus TOP TRAnsfer Type Up` .split(/\W+/).map(_=>_.trim()) function escapeRegex(string) { return string.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&'); } var input = prompt(); console.log(input.length==0?null:input.trim().split(/\s+/) .map( (s=>abr.filter( a=>(new RegExp('^'+escapeRegex(s),'i')) .test(a)&&s.length>=a.match(/^[A-Z]+/)[0].length )[0]) ) .map(_=>typeof _=="undefined"?"*error*":_).join(' ') )
1,165Abbreviations, easy
10javascript
ft1dg
import java.util.*; public class Abbreviations { public static void main(String[] args) { CommandList commands = new CommandList(commandTable); String input = "riG rePEAT copies put mo rest types fup. 6 poweRin"; System.out.println(" input: " + input); System.out.println("output: " + test(commands, input)); } private static String test(CommandList commands, String input) { StringBuilder output = new StringBuilder(); Scanner scanner = new Scanner(input); while (scanner.hasNext()) { String word = scanner.next(); if (output.length() > 0) output.append(' '); Command cmd = commands.findCommand(word); if (cmd != null) output.append(cmd.cmd); else output.append("*error*"); } return output.toString(); } private static String commandTable = "add 1 alter 3 backup 2 bottom 1 Cappend 2 change 1 Schange Cinsert 2 Clast 3 " + "compress 4 copy 2 count 3 Coverlay 3 cursor 3 delete 3 Cdelete 2 down 1 duplicate " + "3 xEdit 1 expand 3 extract 3 find 1 Nfind 2 Nfindup 6 NfUP 3 Cfind 2 findUP 3 fUP 2 " + "forward 2 get help 1 hexType 4 input 1 powerInput 3 join 1 split 2 spltJOIN load " + "locate 1 Clocate 2 lowerCase 3 upperCase 3 Lprefix 2 macro merge 2 modify 3 move 2 " + "msg next 1 overlay 1 parse preserve 4 purge 3 put putD query 1 quit read recover 3 " + "refresh renum 3 repeat 3 replace 1 Creplace 2 reset 3 restore 4 rgtLEFT right 2 left " + "2 save set shift 2 si sort sos stack 3 status 4 top transfer 3 type 1 up 1"; private static class Command { private Command(String cmd, int minLength) { this.cmd = cmd; this.minLength = minLength; } private boolean match(String str) { int olen = str.length(); return olen >= minLength && olen <= cmd.length() && cmd.regionMatches(true, 0, str, 0, olen); } private String cmd; private int minLength; } private static Integer parseInteger(String word) { try { return Integer.valueOf(word); } catch (NumberFormatException ex) { return null; } } private static class CommandList { private CommandList(String table) { Scanner scanner = new Scanner(table); List<String> words = new ArrayList<>(); while (scanner.hasNext()) { String word = scanner.next(); words.add(word.toUpperCase()); } for (int i = 0, n = words.size(); i < n; ++i) { String word = words.get(i);
1,164Abbreviations, simple
9java
7jyrj
use strict; use warnings; my ($high, $wide) = split ' ', qx(stty size); my $mask = "\0" x $wide . ("\0" . "\177" x ($wide - 2) . "\0") x ($high - 5) . "\0" x $wide; my $pile = $mask =~ s/\177/ rand() < 0.02 ? chr 64 + rand 20 : "\0" /ger; for ( 1 .. 1e6 ) { print "\e[H", $pile =~ tr/\0-\177/ 1-~/r, "\n$_"; my $add = $pile =~ tr/\1-\177/\0\0\0\200/r; $add =~ /\200/ or last; $pile =~ tr/\4-\177/\0-\173/; for ("\0$add", "\0" x $wide . $add, substr($add, 1), substr $add, $wide) { $pile |= $_; $pile =~ tr/\200-\377/\1-\176/; $pile &= $mask; } select undef, undef, undef, 0.1; }
1,163Abelian sandpile model
2perl
s0jq3
(() => { 'use strict';
1,164Abbreviations, simple
10javascript
p12b7
null
1,165Abbreviations, easy
11kotlin
wx5ek
sandpile.__index = sandpile sandpile.new = function(self, vals) local inst = setmetatable({},sandpile) inst.cell, inst.dim = {}, #vals for r = 1, inst.dim do inst.cell[r] = {} for c = 1, inst.dim do inst.cell[r][c] = vals[r][c] end end return inst end sandpile.add = function(self, other) local vals = {} for r = 1, self.dim do vals[r] = {} for c = 1, self.dim do vals[r][c] = self.cell[r][c] + other.cell[r][c] end end local inst = sandpile:new(vals) inst:iter() return inst end local s1 = sandpile:new{{1,2,0},{2,1,1},{0,1,3}} local s2 = sandpile:new{{2,1,3},{1,0,1},{0,1,0}} print("s1 =") s1:draw() print("\ns2 =") s2:draw() local s1ps2 = s1:add(s2) print("\ns1 + s2 =") s1ps2:draw() local s2ps1 = s2:add(s1) print("\ns2 + s1 =") s2ps1:draw() local topple = sandpile:new{{4,3,3},{3,1,2},{0,2,3}} print("\ntopple, before =") topple:draw() topple:iter() print("\ntopple, after =") topple:draw() local s3 = sandpile:new{{3,3,3},{3,3,3},{3,3,3}} print("\ns3 =") s3:draw() local s3_id = sandpile:new{{2,1,2},{1,0,1},{2,1,2}} print("\ns3_id =") s3_id:draw() local s3ps3_id = s3:add(s3_id) print("\ns3 + s3_id =") s3ps3_id:draw() local s3_idps3_id = s3_id:add(s3_id) print("\ns3_id + s3_id =") s3_idps3_id:draw()
1,167Abelian sandpile model/Identity
1lua
ndhi8
#!/usr/bin/lua local list1 = [[ Add ALTer BAckup Bottom CAppend Change SCHANGE CInsert CLAst COMPress COpy COUnt COVerlay CURsor DELete CDelete Down DUPlicate Xedit EXPand EXTract Find NFind NFINDUp NFUp CFind FINdup FUp FOrward GET Help HEXType Input POWerinput Join SPlit SPLTJOIN LOAD Locate CLocate LOWercase UPPercase LPrefix MACRO MErge MODify MOve MSG Next Overlay PARSE PREServe PURge PUT PUTD Query QUIT READ RECover REFRESH RENum REPeat Replace CReplace RESet RESTore RGTLEFT RIght LEft SAVE SET SHift SI SORT SOS STAck STATus TOP TRAnsfer Type Up ]] local indata1 = [[riG rePEAT copies put mo rest types fup. 6 poweRin]] local indata2 = [[ALT aLt ALTE ALTER AL ALF ALTERS TER A]] local indata3 = [[o ov oVe over overL overla]] local function split(text) local result = {} for w in string.gmatch(text, "%g+") do result[#result+1]=w
1,165Abbreviations, easy
1lua
xq4wz
import numpy as np import matplotlib.pyplot as plt def iterate(grid): changed = False for ii, arr in enumerate(grid): for jj, val in enumerate(arr): if val > 3: grid[ii, jj] -= 4 if ii > 0: grid[ii - 1, jj] += 1 if ii < len(grid)-1: grid[ii + 1, jj] += 1 if jj > 0: grid[ii, jj - 1] += 1 if jj < len(grid)-1: grid[ii, jj + 1] += 1 changed = True return grid, changed def simulate(grid): while True: grid, changed = iterate(grid) if not changed: return grid if __name__ == '__main__': start_grid = np.zeros((10, 10)) start_grid[4:5, 4:5] = 64 final_grid = simulate(start_grid.copy()) plt.figure() plt.gray() plt.imshow(start_grid) plt.figure() plt.gray() plt.imshow(final_grid)
1,163Abelian sandpile model
3python
08hsq
import java.util.Locale private const val table = "" + "add 1 alter 3 backup 2 bottom 1 Cappend 2 change 1 Schange Cinsert 2 Clast 3 " + "compress 4 copy 2 count 3 Coverlay 3 cursor 3 delete 3 Cdelete 2 down 1 duplicate " + "3 xEdit 1 expand 3 extract 3 find 1 Nfind 2 Nfindup 6 NfUP 3 Cfind 2 findUP 3 fUP 2 " + "forward 2 get help 1 hexType 4 input 1 powerInput 3 join 1 split 2 spltJOIN load " + "locate 1 Clocate 2 lowerCase 3 upperCase 3 Lprefix 2 macro merge 2 modify 3 move 2 " + "msg next 1 overlay 1 parse preserve 4 purge 3 put putD query 1 quit read recover 3 " + "refresh renum 3 repeat 3 replace 1 Creplace 2 reset 3 restore 4 rgtLEFT right 2 left " + "2 save set shift 2 si sort sos stack 3 status 4 top transfer 3 type 1 up 1 " private data class Command(val name: String, val minLen: Int) private fun parse(commandList: String): List<Command> { val commands = mutableListOf<Command>() val fields = commandList.trim().split(" ") var i = 0 while (i < fields.size) { val name = fields[i++] var minLen = name.length if (i < fields.size) { val num = fields[i].toIntOrNull() if (num!= null && num in 1..minLen) { minLen = num i++ } } commands.add(Command(name, minLen)) } return commands } private fun get(commands: List<Command>, word: String): String? { for ((name, minLen) in commands) { if (word.length in minLen..name.length && name.startsWith(word, true)) { return name.toUpperCase(Locale.ROOT) } } return null } fun main(args: Array<String>) { val commands = parse(table) val sentence = "riG rePEAT copies put mo rest types fup. 6 poweRin" val words = sentence.trim().split(" ") val results = words.map { word -> get(commands, word)?: "*error*" } val paddedUserWords = words.mapIndexed { i, word -> word.padEnd(results[i].length) } println("user words: ${paddedUserWords.joinToString(" ")}") println("full words: ${results.joinToString(" ")}") }
1,164Abbreviations, simple
11kotlin
u5fvc
{ my @memo; sub A { my( $m, $n ) = @_; $memo[ $m ][ $n ] and return $memo[ $m ][ $n ]; $m or return $n + 1; return $memo[ $m ][ $n ] = ( $n ? A( $m - 1, A( $m, $n - 1 ) ) : A( $m - 1, 1 ) ); } }
1,162Ackermann function
2perl
36szs
abbr = { define = function(self, cmdstr) local cmd self.hash = {} for word in cmdstr:upper():gmatch("%S+") do if cmd then local n = tonumber(word) for len = n or #cmd, #cmd do self.hash[cmd:sub(1,len)] = cmd end cmd = n==nil and word or nil else cmd = word end end end, expand = function(self, input) local output = {} for word in input:upper():gmatch("%S+") do table.insert(output, self.hash[word] or "*error*") end return table.concat(output, " ") end } abbr:define[[ add 1 alter 3 backup 2 bottom 1 Cappend 2 change 1 Schange Cinsert 2 Clast 3 compress 4 copy 2 count 3 Coverlay 3 cursor 3 delete 3 Cdelete 2 down 1 duplicate 3 xEdit 1 expand 3 extract 3 find 1 Nfind 2 Nfindup 6 NfUP 3 Cfind 2 findUP 3 fUP 2 forward 2 get help 1 hexType 4 input 1 powerInput 3 join 1 split 2 spltJOIN load locate 1 Clocate 2 lowerCase 3 upperCase 3 Lprefix 2 macro merge 2 modify 3 move 2 msg next 1 overlay 1 parse preserve 4 purge 3 put putD query 1 quit read recover 3 refresh renum 3 repeat 3 replace 1 Creplace 2 reset 3 restore 4 rgtLEFT right 2 left 2 save set shift 2 si sort sos stack 3 status 4 top transfer 3 type 1 up 1 ]] local input = "riG rePEAT copies put mo rest types fup. 6 poweRin" print("Input:", input) print("Output:", abbr:expand(input))
1,164Abbreviations, simple
1lua
54tu6
null
1,163Abelian sandpile model
15rust
inpod
from itertools import product from collections import defaultdict class Sandpile(): def __init__(self, gridtext): array = [int(x) for x in gridtext.strip().split()] self.grid = defaultdict(int, {(i for i, x in enumerate(array)}) _border = set((r, c) for r, c in product(range(-1, 4), repeat=2) if not 0 <= r <= 2 or not 0 <= c <= 2 ) _cell_coords = list(product(range(3), repeat=2)) def topple(self): g = self.grid for r, c in self._cell_coords: if g[(r, c)] >= 4: g[(r - 1, c)] += 1 g[(r + 1, c)] += 1 g[(r, c - 1)] += 1 g[(r, c + 1)] += 1 g[(r, c)] -= 4 return True return False def stabilise(self): while self.topple(): pass g = self.grid for row_col in self._border.intersection(g.keys()): del g[row_col] return self __pos__ = stabilise def __eq__(self, other): g = self.grid return all(g[row_col] == other.grid[row_col] for row_col in self._cell_coords) def __add__(self, other): g = self.grid ans = Sandpile() for row_col in self._cell_coords: ans.grid[row_col] = g[row_col] + other.grid[row_col] return ans.stabilise() def __str__(self): g, txt = self.grid, [] for row in range(3): txt.append(' '.join(str(g[(row, col)]) for col in range(3))) return '\n'.join(txt) def __repr__(self): return f'{self.__class__.__name__}()' unstable = Sandpile() s1 = Sandpile() s2 = Sandpile() s3 = Sandpile() s3_id = Sandpile()
1,167Abelian sandpile model/Identity
3python
7jzrm
function ackermann( $m , $n ) { if ( $m==0 ) { return $n + 1; } elseif ( $n==0 ) { return ackermann( $m-1 , 1 ); } return ackermann( $m-1, ackermann( $m , $n-1 ) ); } echo ackermann( 3, 4 );
1,162Ackermann function
12php
p1uba
@c = (join ' ', qw< Add ALTer BAckup Bottom CAppend Change SCHANGE CInsert CLAst COMPress COpy COUnt COVerlay CURsor DELete CDelete Down DUPlicate Xedit EXPand EXTract Find NFind NFINDUp NFUp CFind FINdup FUp FOrward GET Help HEXType Input POWerinput Join SPlit SPLTJOIN LOAD Locate CLocate LOWercase UPPercase LPrefix MACRO MErge MODify MOve MSG Next Overlay PARSE PREServe PURge PUT PUTD Query QUIT READ RECover REFRESH RENum Replace REPeat CReplace RESet RESTore RGTLEFT RIght LEft SAVE SET SHift SI SORT SOS STAck STATus TOP TRAnsfer Type Up >) =~ /([A-Z]+)([a-z]*)(?:\s+|$)/g; my %abr = ('' => '', ' ' => ''); for ($i = 0; $i < @c; $i += 2) { $sl = length($s = $c[$i] ); $ll = length($l = uc $c[$i+1]); $abr{$s} = $w = $s.$l; map { $abr{substr($w, 0, $_)} = $w } $sl .. $ll; $abr{$w} = $w; } $fmt = "%-10s"; $inp = sprintf $fmt, 'Input:'; $out = sprintf $fmt, 'Output:'; for $str ('', qw<riG rePEAT copies put mo rest types fup. 6 poweRin>) { $inp .= sprintf $fmt, $str; $out .= sprintf $fmt, $abr{uc $str} // '*error*'; } print "$inp\n$out\n"
1,165Abbreviations, easy
2perl
l2oc5
void process(int lineNum, char buffer[]) { char days[7][64]; int i = 0, d = 0, j = 0; while (buffer[i] != 0) { if (buffer[i] == ' ') { days[d][j] = '\0'; ++d; j = 0; } else if (buffer[i] == '\n' || buffer[i] == '\r') { days[d][j] = '\0'; ++d; break; } else { days[d][j] = buffer[i]; ++j; } if (d >= 7) { printf(, lineNum); return; } ++i; } if (buffer[i] == '\0') { days[d][j] = '\0'; ++d; } if (d < 7) { printf(, lineNum); return; } else { int len = 0; for (len = 1; len < 64; ++len) { int d1; for (d1 = 0; d1 < 7; ++d1) { int d2; for (d2 = d1 + 1; d2 < 7; ++d2) { int unique = 0; for (i = 0; i < len; ++i) { if (days[d1][i] != days[d2][i]) { unique = 1; break; } } if (!unique) { goto next_length; } } } printf(, len); for (i = 0; i < 7; ++i) { printf(, days[i]); } printf(); return; next_length: {} } } printf(); } int main() { char buffer[1024]; int lineNum = 1, len; FILE *fp; fp = fopen(, ); while (1) { memset(buffer, 0, sizeof(buffer)); fgets(buffer, sizeof(buffer), fp); len = strlen(buffer); if (len == 0 || buffer[len - 1] == '\0') { break; } process(lineNum++, buffer); } fclose(fp); return 0; }
1,168Abbreviations, automatic
5c
grd45
package main import "fmt" type Beast interface { Kind() string Name() string Cry() string } type Dog struct { kind string name string } func (d Dog) Kind() string { return d.kind } func (d Dog) Name() string { return d.name } func (d Dog) Cry() string { return "Woof" } type Cat struct { kind string name string } func (c Cat) Kind() string { return c.kind } func (c Cat) Name() string { return c.name } func (c Cat) Cry() string { return "Meow" } func bprint(b Beast) { fmt.Printf("%s, who's a%s, cries:%q.\n", b.Name(), b.Kind(), b.Cry()) } func main() { d := Dog{"labrador", "Max"} c := Cat{"siamese", "Sammy"} bprint(d) bprint(c) }
1,166Abstract type
0go
s0gqa
$commands = 'Add ALTer BAckup Bottom CAppend Change SCHANGE CInsert CLAst COMPress COpy COUnt COVerlay CURsor DELete CDelete Down DUPlicate Xedit EXPand EXTract Find NFind NFINDUp NFUp CFind FINdup FUp FOrward GET Help HEXType Input POWerinput Join SPlit SPLTJOIN LOAD Locate CLocate LOWercase UPPercase LPrefix MACRO MErge MODify MOve MSG Next Overlay PARSE PREServe PURge PUT PUTD Query QUIT READ RECover REFRESH RENum REPeat Replace CReplace RESet RESTore RGTLEFT RIght LEft SAVE SET SHift SI SORT SOS STAck STATus TOP TRAnsfer Type Up'; $input = 'riG rePEAT copies put mo rest types fup. 6 poweRin'; $expect = 'RIGHT REPEAT *error* PUT MOVE RESTORE *error* *error* *error* POWERINPUT'; $table = makeCommandTable($commands); $table_keys = array_keys($table); $inputTable = processInput($input); foreach ($inputTable as $word) { $rs = searchCommandTable($word, $table); if ($rs) { $output[] = $rs; } else { $output[] = '*error*'; } } echo 'Input: '. $input. PHP_EOL; echo 'Output: '. implode(' ', $output). PHP_EOL; function searchCommandTable($search, $table) { foreach ($table as $key => $value) { if ((strtoupper(substr($value['word'], 0, strlen($search))) === strtoupper($search)) && (strlen($search) >= $value['min_length'])) { return $key; } } return false; } function processInput($input) { $input = preg_replace('!\s+!', ' ', $input); $pieces = explode(' ', trim($input)); return $pieces; } function makeCommandTable($commands) { $commands = preg_replace('!\s+!', ' ', $commands); $pieces = explode(' ', trim($commands)); foreach ($pieces as $word) { $rs[strtoupper($word)] = ['word'=>$word, 'min_length' => preg_match_all(, $word)]; } return $rs; }
1,165Abbreviations, easy
12php
qsgx3
public interface Interface { int method1(double value) int method2(String name) int add(int a, int b) }
1,166Abstract type
7groovy
ae21p
class Eq a where (==) :: a -> a -> Bool (/=) :: a -> a -> Bool
1,166Abstract type
8haskell
9csmo
@c = (uc join ' ', qw< add 1 alter 3 backup 2 bottom 1 Cappend 2 change 1 Schange Cinsert 2 Clast 3 compress 4 copy 2 count 3 Coverlay 3 cursor 3 delete 3 Cdelete 2 down 1 duplicate 3 xEdit 1 expand 3 extract 3 find 1 Nfind 2 Nfindup 6 NfUP 3 Cfind 2 findUP 3 fUP 2 forward 2 get help 1 hexType 4 input 1 powerInput 3 join 1 split 2 spltJOIN load locate 1 Clocate 2 lowerCase 3 upperCase 3 Lprefix 2 macro merge 2 modify 3 move 2 msg next 1 overlay 1 parse preserve 4 purge 3 put putD query 1 quit read recover 3 refresh renum 3 repeat 3 replace 1 Creplace 2 reset 3 restore 4 rgtLEFT right 2 left 2 save set shift 2 si sort sos stack 3 status 4 top transfer 3 type 1 up 1 >) =~ /([a-zA-Z]+(?:\s+\d+)?)(?=\s+[a-zA-Z]|$)/g; my %abr = ('' => '', ' ' => ''); for (@c) { ($w,$sl) = split ' ', $_; $ll = length($w); $sl = $ll unless $sl; $abr{substr($w,0,$sl)} = $w; map { $abr{substr($w, 0, $_)} = $w } $sl .. $ll; } $fmt = "%-10s"; $inp = sprintf $fmt, 'Input:'; $out = sprintf $fmt, 'Output:'; for $str ('', qw<riG rePEAT copies put mo rest types fup. 6 poweRin>) { $inp .= sprintf $fmt, $str; $out .= sprintf $fmt, $abr{uc $str} // '*error*'; } print "$inp\n$out\n";
1,164Abbreviations, simple
2perl
8oh0w
class Sandpile def initialize(ar) = @grid = ar def to_a = @grid.dup def + (other) res = self.to_a.zip(other.to_a).map{|row1, row2| row1.zip(row2).map(&:sum) } Sandpile.new(res) end def stable? = @grid.flatten.none?{|v| v > 3} def avalanche topple until stable? self end def == (other) = self.avalanche.to_a == other.avalanche.to_a def topple a = @grid a.each_index do |row| a[row].each_index do |col| next if a[row][col] < 4 a[row+1][col] += 1 unless row == a.size-1 a[row-1][col] += 1 if row > 0 a[row][col+1] += 1 unless col == a.size-1 a[row][col-1] += 1 if col > 0 a[row][col] -= 4 end end self end def to_s = + @grid.map {|row| row.join() }.join() end puts puts demo = Sandpile.new( [[4,3,3], [3,1,2],[0,2,3]] ) puts puts demo.avalanche puts * 30, s1 = Sandpile.new([[1, 2, 0], [2, 1, 1], [0, 1, 3]] ) puts s2 = Sandpile.new([[2, 1, 3], [1, 0, 1], [0, 1, 0]] ) puts puts puts * 30, s3 = Sandpile.new([[3, 3, 3], [3, 3, 3], [3, 3, 3]] ) s3_id = Sandpile.new([[2, 1, 2], [1, 0, 1], [2, 1, 2]] ) puts puts
1,167Abelian sandpile model/Identity
14ruby
hk6jx
public abstract class Abs { public abstract int method1(double value); protected abstract int method2(String name); int add(int a, int b) { return a + b; } }
1,166Abstract type
9java
tz1f9
command_table_text = user_words = def find_abbreviations_length(command_table_text): command_table = dict() input_iter = iter(command_table_text.split()) word = None try: while True: if word is None: word = next(input_iter) abbr_len = next(input_iter, len(word)) try: command_table[word] = int(abbr_len) word = None except ValueError: command_table[word] = len(word) word = abbr_len except StopIteration: pass return command_table def find_abbreviations(command_table): abbreviations = dict() for command, min_abbr_len in command_table.items(): for l in range(min_abbr_len, len(command)+1): abbr = command[:l].lower() abbreviations[abbr] = command.upper() return abbreviations def parse_user_string(user_string, abbreviations): user_words = [word.lower() for word in user_string.split()] commands = [abbreviations.get(user_word, ) for user_word in user_words] return .join(commands) command_table = find_abbreviations_length(command_table_text) abbreviations_table = find_abbreviations(command_table) full_words = parse_user_string(user_words, abbreviations_table) print(, user_words) print(, full_words)
1,164Abbreviations, simple
3python
oik81
command_table_text = \ user_words = def find_abbreviations_length(command_table_text): command_table = dict() for word in command_table_text.split(): abbr_len = sum(1 for c in word if c.isupper()) if abbr_len == 0: abbr_len = len(word) command_table[word] = abbr_len return command_table def find_abbreviations(command_table): abbreviations = dict() for command, min_abbr_len in command_table.items(): for l in range(min_abbr_len, len(command)+1): abbr = command[:l].lower() abbreviations[abbr] = command.upper() return abbreviations def parse_user_string(user_string, abbreviations): user_words = [word.lower() for word in user_string.split()] commands = [abbreviations.get(user_word, ) for user_word in user_words] return .join(commands) command_table = find_abbreviations_length(command_table_text) abbreviations_table = find_abbreviations(command_table) full_words = parse_user_string(user_words, abbreviations_table) print(, user_words) print(, full_words)
1,165Abbreviations, easy
3python
2vilz
unsigned sum_proper_divisors(const unsigned n) { unsigned sum = 1; for (unsigned i = 3, j; i < sqrt(n)+1; i += 2) if (n % i == 0) sum += i + (i == (j = n / i) ? 0 : j); return sum; } int main(int argc, char const *argv[]) { unsigned n, c; for (n = 1, c = 0; c < 25; n += 2) if (n < sum_proper_divisors(n)) printf(, ++c, n); for ( ; c < 1000; n += 2) if (n < sum_proper_divisors(n)) c ++; printf(, n); for (n = 1000000001 ;; n += 2) if (n < sum_proper_divisors(n)) break; printf(, n); return 0; }
1,169Abundant odd numbers
5c
2vslo
null
1,166Abstract type
11kotlin
oij8z
#[derive(Clone)] struct Box { piles: [[u8; 3]; 3], } impl Box { fn init(piles: [[u8; 3]; 3]) -> Box { let a = Box { piles }; if a.piles.iter().any(|&row| row.iter().any(|&pile| pile >= 4)) { return a.avalanche(); } else { return a; } } fn avalanche(&self) -> Box { let mut a = self.clone(); for (i, row) in self.piles.iter().enumerate() { for (j, pile) in row.iter().enumerate() { if *pile >= 4u8 { if i > 0 { a.piles[i - 1][j] += 1u8 } if i < 2 { a.piles[i + 1][j] += 1u8 } if j > 0 { a.piles[i][j - 1] += 1u8 } if j < 2 { a.piles[i][j + 1] += 1u8 } a.piles[i][j] -= 4; } } } Box::init(a.piles) } fn add(&self, a: &Box) -> Box { let mut b = Box { piles: [[0u8; 3]; 3], }; for (row, columns) in b.piles.iter_mut().enumerate() { for (col, pile) in columns.iter_mut().enumerate() { *pile = self.piles[row][col] + a.piles[row][col] } } Box::init(b.piles) } } fn main() { println!( "The piles demonstration avalanche starts as:\n{:?}\n{:?}\n{:?}", [4, 3, 3], [3, 1, 2], [0, 2, 3] ); let s0 = Box::init([[4u8, 3u8, 3u8], [3u8, 1u8, 2u8], [0u8, 2u8, 3u8]]); println!( "And ends as:\n{:?}\n{:?}\n{:?}", s0.piles[0], s0.piles[1], s0.piles[2] ); let s1 = Box::init([[1u8, 2u8, 0u8], [2u8, 1u8, 1u8], [0u8, 1u8, 3u8]]); let s2 = Box::init([[2u8, 1u8, 3u8], [1u8, 0u8, 1u8], [0u8, 1u8, 0u8]]); let s1_2 = s1.add(&s2); let s2_1 = s2.add(&s1); println!( "The piles in s1 + s2 are:\n{:?}\n{:?}\n{:?}", s1_2.piles[0], s1_2.piles[1], s1_2.piles[2] ); println!( "The piles in s2 + s1 are:\n{:?}\n{:?}\n{:?}", s2_1.piles[0], s2_1.piles[1], s2_1.piles[2] ); let s3 = Box::init([[3u8; 3]; 3]); let s3_id = Box::init([[2u8, 1u8, 2u8], [1u8, 0u8, 1u8], [2u8, 1u8, 2u8]]); let s4 = s3.add(&s3_id); println!( "The piles in s3 + s3_id are:\n{:?}\n{:?}\n{:?}", s4.piles[0], s4.piles[1], s4.piles[2] ); let s5 = s3_id.add(&s3_id); println!( "The piles in s3_id + s3_id are:\n{:?}\n{:?}\n{:?}", s5.piles[0], s5.piles[1], s5.piles[2] ); }
1,167Abelian sandpile model/Identity
15rust
kbyh5
BaseClass = {} function class ( baseClass ) local new_class = {} local class_mt = { __index = new_class } function new_class:new() local newinst = {} setmetatable( newinst, class_mt ) return newinst end if not baseClass then baseClass = BaseClass end setmetatable( new_class, { __index = baseClass } ) return new_class end function abstractClass ( self ) local new_class = {} local class_mt = { __index = new_class } function new_class:new() error("Abstract classes cannot be instantiated") end if not baseClass then baseClass = BaseClass end setmetatable( new_class, { __index = baseClass } ) return new_class end BaseClass.class = class BaseClass.abstractClass = abstractClass
1,166Abstract type
1lua
inhot
cmd_table = File.read(ARGV[0]).split user_str = File.read(ARGV[1]).split user_str.each do |abbr| candidate = cmd_table.find do |cmd| cmd.count('A-Z') <= abbr.length && abbr.casecmp(cmd[0...abbr.length]).zero? end print candidate.nil?? '*error*': candidate.upcase print ' ' end puts
1,165Abbreviations, easy
14ruby
u5dvz
use std::collections::HashMap; fn main() { let commands = " Add ALTer BAckup Bottom CAppend Change SCHANGE CInsert CLAst COMPress COpy \ COUnt COVerlay CURsor DELete CDelete Down DUPlicate Xedit EXPand EXTract Find \ NFind NFINDUp NFUp CFind FINdup FUp FOrward GET Help HEXType Input POWerinput \ Join SPlit SPLTJOIN LOAD Locate CLocate LOWercase UPPercase LPrefix MACRO \ MErge MODify MOve MSG Next Overlay PARSE PREServe PURge PUT PUTD Query QUIT \ READ RECover REFRESH RENum REPeat Replace CReplace RESet RESTore RGTLEFT \ RIght LEft SAVE SET SHift SI SORT SOS STAck STATus TOP TRAnsfer Type Up \ "; let split = commands.split_ascii_whitespace(); let count_hashtable: HashMap<&str, usize> = split.map(|word| { (word, word.chars().take_while(|c| c.is_ascii_uppercase()).count()) }).collect(); let line = "riG rePEAT copies put mo rest types fup. 6 poweRin"; let mut words_vec: Vec<String> = vec![]; for word in line.split_ascii_whitespace() { let split = commands.split_ascii_whitespace(); let abbr = split.filter(|x| { x.to_ascii_lowercase().starts_with(&word.to_ascii_lowercase()) && word.len() >= *count_hashtable.get(x).unwrap() }).next(); words_vec.push(match abbr { Some(word) => word.to_ascii_uppercase(), None => String::from("*error*"), }); } let corrected_line = words_vec.join(" "); println!("{}", corrected_line); }
1,165Abbreviations, easy
15rust
54fuq
str = RE = /(?<word1>[a-zA-Z]+)\s+(?<word2>[a-zA-Z]+)/ str = str.upcase 2.times{ str.gsub!(RE){ [ $~[:word1], $~[:word1].size, $~[:word2] ].join()} } table = Hash[*str.split].transform_values(&:to_i) test = ar = test.split.map do |w| (res = table.detect{|k,v| k.start_with?(w.upcase) && w.size >= v})? res[0]: end puts ar.join()
1,164Abbreviations, simple
14ruby
ndpit
object Main extends App { implicit class StrOps(i: String) { def isAbbreviationOf(target: String): Boolean = { @scala.annotation.tailrec def checkPAsPrefixOfM(p: List[Char], m: List[Char]): Boolean = (p, m) match { case (Nil, _) => true
1,165Abbreviations, easy
16scala
r73gn
package main import( "bufio" "fmt" "os" "strings" ) func distinctStrings(strs []string) []string { len := len(strs) set := make(map[string]bool, len) distinct := make([]string, 0, len) for _, str := range strs { if !set[str] { distinct = append(distinct, str) set[str] = true } } return distinct } func takeRunes(s string, n int) string { i := 0 for j := range s { if i == n { return s[:j] } i++ } return s } func main() { file, err := os.Open("days_of_week.txt") if err != nil { fmt.Println("Unable to open file.") return } defer file.Close() reader := bufio.NewReader(file) lineCount := 0 for { line, err := reader.ReadString('\n') if err != nil {
1,168Abbreviations, automatic
0go
in7og
use std::collections::HashMap;
1,164Abbreviations, simple
15rust
df1ny
class Abbreviations { static void main(String[] args) throws IOException { BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream("days_of_week.txt"), "utf-8")) List<String> readAllLines = br.readLines() for (int i = 0; i < readAllLines.size(); i++) { String line = readAllLines.get(i) if (line.length() == 0) continue String[] days = line.split(" ") if (days.length != 7) throw new RuntimeException("There aren't 7 days on line " + (i + 1)) Map<String, Integer> temp = new HashMap<>() for (String day: days) { Integer count = temp.getOrDefault(day, 0) temp.put(day, count + 1) } if (temp.size() < 7) { System.out.print(" ") System.out.println(line) continue } int len = 1 while (true) { temp.clear() for (String day: days) { String sd if (len >= day.length()) { sd = day } else { sd = day.substring(0, len) } Integer count = temp.getOrDefault(sd, 0) temp.put(sd, count + 1) } if (temp.size() == 7) { System.out.printf("%2d %s\n", len, line) break } len++ } } } }
1,168Abbreviations, automatic
7groovy
qsuxp
object Main extends App { implicit class StrOps(i: String) { def isAbbreviationOf(target: String, targetMinLength: Int): Boolean = { @scala.annotation.tailrec def checkPAsPrefixOfM(p: List[Char], m: List[Char]): Boolean = (p, m) match { case (Nil, _) => true
1,164Abbreviations, simple
16scala
z3wtr
mpz_t p[N + 1]; void calc(int n) { mpz_init_set_ui(p[n], 0); for (int k = 1; k <= n; k++) { int d = n - k * (3 * k - 1) / 2; if (d < 0) break; if (k&1)mpz_add(p[n], p[n], p[d]); else mpz_sub(p[n], p[n], p[d]); d -= k; if (d < 0) break; if (k&1)mpz_add(p[n], p[n], p[d]); else mpz_sub(p[n], p[n], p[d]); } } int main(void) { int idx[] = { 23, 123, 1234, 12345, 20000, 30000, 40000, 50000, N, 0 }; int at = 0; mpz_init_set_ui(p[0], 1); for (int i = 1; idx[at]; i++) { calc(i); if (i != idx[at]) continue; gmp_printf(, i, p[i]); at++; } }
1,1709 billion names of God the integer
5c
ndri6
import Data.List (inits, intercalate, transpose) import qualified Data.Set as S minAbbrevnLength :: [String] -> Int minAbbrevlnLength [] = 0 minAbbrevnLength xs = length . head . S.toList . head $ dropWhile ((< n) . S.size) $ S.fromList <$> transpose (inits <$> xs) where n = length xs main :: IO () main = do s <- readFile "./weekDayNames.txt" mapM_ putStrLn $ take 10 $ intercalate "\t" . (<*>) [ show . minAbbrevnLength . words, id ] . return <$> lines s
1,168Abbreviations, automatic
8haskell
vu82k
import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.util.HashMap; import java.util.List; import java.util.Map; public class Abbreviations { public static void main(String[] args) throws IOException { Path path = Paths.get("days_of_week.txt"); List<String> readAllLines = Files.readAllLines(path); for (int i = 0; i < readAllLines.size(); i++) { String line = readAllLines.get(i); if (line.length() == 0) continue; String[] days = line.split(" "); if (days.length != 7) throw new RuntimeException("There aren't 7 days on line " + (i + 1)); Map<String, Integer> temp = new HashMap<>(); for (String day : days) { Integer count = temp.getOrDefault(day, 0); temp.put(day, count + 1); } if (temp.size() < 7) { System.out.print(" "); System.out.println(line); continue; } int len = 1; while (true) { temp.clear(); for (String day : days) { String sd; if (len >= day.length()) { sd = day; } else { sd = day.substring(0, len); } Integer count = temp.getOrDefault(sd, 0); temp.put(sd, count + 1); } if (temp.size() == 7) { System.out.printf("%2d %s\n", len, line); break; } len++; } } } }
1,168Abbreviations, automatic
9java
yme6g
(defn nine-billion-names [row column] (cond (<= row 0) 0 (<= column 0) 0 (< row column) 0 (= row 1) 1 :else (let [addend (nine-billion-names (dec row) (dec column)) augend (nine-billion-names (- row column) column)] (+ addend augend)))) (defn print-row [row] (doseq [x (range 1 (inc row))] (print (nine-billion-names row x) \space)) (println)) (defn print-triangle [rows] (doseq [x (range 1 (inc rows))] (print-row x))) (print-triangle 25)
1,1709 billion names of God the integer
6clojure
36bzr
Array.prototype.hasDoubles = function() { let arr = this.slice(); while (arr.length > 1) { let cur = arr.shift(); if (arr.includes(cur)) return true; } return false; } function getMinAbbrLen(arr) { if (arr.length <= 1) return ''; let testArr = [], len = 0, i; do { len++; for (i = 0; i < arr.length; i++) testArr[i] = arr[i].substr(0, len); } while (testArr.hasDoubles()); return len; }
1,168Abbreviations, automatic
10javascript
2v0lr
def ack1(M, N): return (N + 1) if M == 0 else ( ack1(M-1, 1) if N == 0 else ack1(M-1, ack1(M, N-1)))
1,162Ackermann function
3python
6y03w
null
1,168Abbreviations, automatic
11kotlin
ftkdo
function split(line) local wa = {} for i in string.gmatch(line, "%S+") do table.insert(wa, i) end return wa end
1,168Abbreviations, automatic
1lua
tzbfn
package main import ( "fmt" "strconv" ) func divisors(n int) []int { divs := []int{1} divs2 := []int{} for i := 2; i*i <= n; i++ { if n%i == 0 { j := n / i divs = append(divs, i) if i != j { divs2 = append(divs2, j) } } } for i := len(divs2) - 1; i >= 0; i-- { divs = append(divs, divs2[i]) } return divs } func sum(divs []int) int { tot := 0 for _, div := range divs { tot += div } return tot } func sumStr(divs []int) string { s := "" for _, div := range divs { s += strconv.Itoa(div) + " + " } return s[0 : len(s)-3] } func abundantOdd(searchFrom, countFrom, countTo int, printOne bool) int { count := countFrom n := searchFrom for ; count < countTo; n += 2 { divs := divisors(n) if tot := sum(divs); tot > n { count++ if printOne && count < countTo { continue } s := sumStr(divs) if !printOne { fmt.Printf("%2d.%5d <%s =%d\n", count, n, s, tot) } else { fmt.Printf("%d <%s =%d\n", n, s, tot) } } } return n } func main() { const max = 25 fmt.Println("The first", max, "abundant odd numbers are:") n := abundantOdd(1, 0, 25, false) fmt.Println("\nThe one thousandth abundant odd number is:") abundantOdd(n, 25, 1000, true) fmt.Println("\nThe first abundant odd number above one billion is:") abundantOdd(1e9+1, 0, 1, true) }
1,169Abundant odd numbers
0go
qsvxz
import 'dart:math'; List<BigInt> partitions(int n) { var cache = List<List<BigInt>>.filled(1, List<BigInt>.filled(1, BigInt.from(1)), growable: true); for(int length = cache.length; length < n + 1; length++) { var row = List<BigInt>.filled(1, BigInt.from(0), growable: true); for(int index = 1; index < length + 1; index++) { var partAtIndex = row[row.length - 1] + cache[length - index][min(index, length - index)]; row.add(partAtIndex); } cache.add(row); } return cache[n]; } List<BigInt> row(int n) { var parts = partitions(n); return List<BigInt>.generate(n, (int index) => parts[index + 1] - parts[index]); } void printRows({int min = 1, int max = 11}) { int maxDigits = max.toString().length; print('Rows:'); for(int i in List.generate(max - min, (int index) => index + min)) { print((' ' * (maxDigits - i.toString().length)) + '$i: ${row(i)}'); } } void printSums(List<int> args) { print('Sums:'); for(int i in args) { print('$i: ${partitions(i)[i]}'); } }
1,1709 billion names of God the integer
18dart
qs2xo
package AbstractFoo; use strict; sub frob { die "abstract" } sub baz { die "abstract" } sub frob_the_baz { my $self = shift; $self->frob($self->baz()); } 1;
1,166Abstract type
2perl
grt4e
ackermann <- function(m, n) { if ( m == 0 ) { n+1 } else if ( n == 0 ) { ackermann(m-1, 1) } else { ackermann(m-1, ackermann(m, n-1)) } }
1,162Ackermann function
13r
ftwdc
class Abundant { static List<Integer> divisors(int n) { List<Integer> divs = new ArrayList<>() divs.add(1) List<Integer> divs2 = new ArrayList<>() int i = 2 while (i * i < n) { if (n % i == 0) { int j = (int) (n / i) divs.add(i) if (i != j) { divs2.add(j) } } i++ } Collections.reverse(divs2) divs.addAll(divs2) return divs } static int abundantOdd(int searchFrom, int countFrom, int countTo, boolean printOne) { int count = countFrom int n = searchFrom while (count < countTo) { List<Integer> divs = divisors(n) int tot = divs.stream().reduce(Integer.&sum).orElse(0) if (tot > n) { count++ if (!printOne || count >= countTo) { String s = divs.stream() .map(Integer.&toString) .reduce { a, b -> a + " + " + b } .orElse("") if (printOne) { System.out.printf("%d <%s =%d\n", n, s, tot) } else { System.out.printf("%2d.%5d <%s =%d\n", count, n, s, tot) } } } n += 2 } return n } static void main(String[] args) { int max = 25 System.out.printf("The first%d abundant odd numbers are:\n", max) int n = abundantOdd(1, 0, 25, false) System.out.println("\nThe one thousandth abundant odd number is:") abundantOdd(n, 25, 1000, true) System.out.println("\nThe first abundant odd number above one billion is:") abundantOdd((int) (1e9 + 1), 0, 1, true) } }
1,169Abundant odd numbers
7groovy
1amp6
abstract class Abs { abstract public function method1($value); abstract protected function method2($name); function add($a, $b){ return a + b; } }
1,166Abstract type
12php
ndkig
import Data.List (nub) divisorSum :: Integral a => a -> a divisorSum n = sum . map (\i -> sum $ nub [i, n `quot` i]) . filter ((== 0) . (n `rem`)) $ takeWhile ((<= n) . (^ 2)) [1 ..] oddAbundants :: Integral a => a -> [(a, a)] oddAbundants n = [ (i, divisorSum i) | i <- [n ..], odd i, divisorSum i > i * 2 ] printAbundant :: (Int, Int) -> IO () printAbundant (n, s) = putStrLn $ show n ++ " with " ++ show s ++ " as the sum of all proper divisors." main :: IO () main = do putStrLn "The first 25 odd abundant numbers are:" mapM_ printAbundant . take 25 $ oddAbundants 1 putStrLn "The 1000th odd abundant number is:" printAbundant $ oddAbundants 1 !! 1000 putStrLn "The first odd abundant number above 1000000000 is:" printAbundant . head . oddAbundants $ 10 ^ 9
1,169Abundant odd numbers
8haskell
m9eyf
use strict; use utf8; binmode STDOUT, ":utf8"; sub auto_abbreviate { my($string) = @_; my @words = split ' ', $string; my $max = 0; return '' unless @words; map { $max = length($_) if length($_) > $max } @words; for $i (1..$max) { my %seen; return $i if @words == grep {!$seen{substr($_,0,$i)}++} @words; } return ''; } open $fh, '<:encoding(UTF-8)', 'DoWAKA.txt'; while ($_ = <$fh>) { print "$.) " . auto_abbreviate($_) . ' ' . $_; }
1,168Abbreviations, automatic
2perl
hk3jl
class BaseQueue(object): def __init__(self): self.contents = list() raise NotImplementedError def Enqueue(self, item): raise NotImplementedError def Dequeue(self): raise NotImplementedError def Print_Contents(self): for i in self.contents: print i,
1,166Abstract type
3python
r7zgq
import java.util.ArrayList; import java.util.List; public class AbundantOddNumbers { private static List<Integer> list = new ArrayList<>(); private static List<Integer> result = new ArrayList<>(); public static void main(String[] args) { System.out.println("First 25: "); abundantOdd(1,100000, 25, false); System.out.println("\n\nThousandth: "); abundantOdd(1,2500000, 1000, true); System.out.println("\n\nFirst over 1bn:"); abundantOdd(1000000001, 2147483647, 1, false); } private static void abundantOdd(int start, int finish, int listSize, boolean printOne) { for (int oddNum = start; oddNum < finish; oddNum += 2) { list.clear(); for (int toDivide = 1; toDivide < oddNum; toDivide+=2) { if (oddNum % toDivide == 0) list.add(toDivide); } if (sumList(list) > oddNum) { if(!printOne) System.out.printf("%5d <=%5d \n",oddNum, sumList(list) ); result.add(oddNum); } if(printOne && result.size() >= listSize) System.out.printf("%5d <=%5d \n",oddNum, sumList(list) ); if(result.size() >= listSize) break; } } private static int sumList(List list) { int sum = 0; for (int i = 0; i < list.size(); i++) { String temp = list.get(i).toString(); sum += Integer.parseInt(temp); } return sum; } }
1,169Abundant odd numbers
9java
fthdv
int a,b,c,d,e,f,g; int lo,hi,unique,show; int solutions; void bf() { for (f = lo;f <= hi; f++) if ((!unique) || ((f != a) && (f != c) && (f != d) && (f != g) && (f != e))) { b = e + f - c; if ((b >= lo) && (b <= hi) && ((!unique) || ((b != a) && (b != c) && (b != d) && (b != g) && (b != e) && (b != f)))) { solutions++; if (show) printf(,a,b,c,d,e,f,g); } } } void ge() { for (e = lo;e <= hi; e++) if ((!unique) || ((e != a) && (e != c) && (e != d))) { g = d + e; if ((g >= lo) && (g <= hi) && ((!unique) || ((g != a) && (g != c) && (g != d) && (g != e)))) bf(); } } void acd() { for (c = lo;c <= hi; c++) for (d = lo;d <= hi; d++) if ((!unique) || (c != d)) { a = c + d; if ((a >= lo) && (a <= hi) && ((!unique) || ((c != 0) && (d != 0)))) ge(); } } void foursquares(int plo,int phi, int punique,int pshow) { lo = plo; hi = phi; unique = punique; show = pshow; solutions = 0; printf(); acd(); if (unique) printf(,solutions,lo,hi); else printf(,solutions,lo,hi); } main() { foursquares(1,7,TRUE,TRUE); foursquares(3,9,TRUE,TRUE); foursquares(0,9,FALSE,FALSE); }
1,1714-rings or 4-squares puzzle
5c
jhd70
(() => { 'use strict'; const main = () => {
1,169Abundant odd numbers
10javascript
yma6r
package main import ( "fmt" "math/big" ) func main() { intMin := func(a, b int) int { if a < b { return a } else { return b } } var cache = [][]*big.Int{{big.NewInt(1)}} cumu := func(n int) []*big.Int { for y := len(cache); y <= n; y++ { row := []*big.Int{big.NewInt(0)} for x := 1; x <= y; x++ { cacheValue := cache[y-x][intMin(x, y-x)] row = append(row, big.NewInt(0).Add(row[len(row)-1], cacheValue)) } cache = append(cache, row) } return cache[n] } row := func(n int) { e := cumu(n) for i := 0; i < n; i++ { fmt.Printf("%v ", (big.NewInt(0).Sub(e[i+1], e[i])).Text(10)) } fmt.Println() } fmt.Println("rows:") for x := 1; x < 11; x++ { row(x) } fmt.Println() fmt.Println("sums:") for _, num := range [...]int{23, 123, 1234, 12345} { r := cumu(num) fmt.Printf("%d%v\n", num, r[len(r)-1].Text(10)) } }
1,1709 billion names of God the integer
0go
r7ngm
def partitions(c) { def p=[]; int k = 0; p[k] = c; int counter=0; def counts=[]; for (i in 0..c-1) {counts[i]=0;} while (true) { counter++; counts[p[0]-1]=counts[p[0]-1]+1; int rem_val = 0; while (k >= 0 && p[k] == 1) { rem_val += p[k]; k--;} if (k < 0) { break;} p[k]--; rem_val++; while (rem_val > p[k]) { p[k+1] = p[k]; rem_val = rem_val - p[k]; k++; } p[k+1] = rem_val; k++; } println counts; return counter; } static void main(String[] args) { for( i in 1..25 ) {partitions(i);} }
1,1709 billion names of God the integer
7groovy
vus28
(use '[clojure.math.combinatorics] (defn rings [r & {:keys [unique]:or {unique true}}] (if unique (apply concat (map permutations (combinations r 7))) (selections r 7))) (defn four-rings [low high & {:keys [unique]:or {unique true}}] (for [[a b c d e f g] (rings (range low (inc high)):unique unique) :when (= (+ a b) (+ b c d) (+ d e f) (+ f g))] [a b c d e f g]))
1,1714-rings or 4-squares puzzle
6clojure
1a6py
import Data.List (mapAccumL) cumu :: [[Integer]] cumu = [1]: map (scanl (+) 0) rows rows :: [[Integer]] rows = snd $ mapAccumL f [] cumu where f r row = (rr, new_row) where new_row = map head rr rr = map tailKeepOne (row:r) tailKeepOne [x] = [x] tailKeepOne (_:xs) = xs sums n = cumu !! n !! n main :: IO () main = do mapM_ print $ take 10 rows mapM_ (print.sums) [23, 123, 1234, 12345]
1,1709 billion names of God the integer
8haskell
08us7
require 'abstraction' class AbstractQueue abstract def enqueue(object) raise NotImplementedError end def dequeue raise NotImplementedError end end class ConcreteQueue < AbstractQueue def enqueue(object) puts end end
1,166Abstract type
14ruby
jh67x
def shortest_abbreviation_length(line, list_size): words = line.split() word_count = len(words) if word_count != list_size: raise ValueError(f'Not enough entries, expected {list_size} found {word_count}') abbreviation_length = 1 abbreviations = set() while(True): abbreviations = {word[:abbreviation_length] for word in words} if len(abbreviations) == list_size: return abbreviation_length abbreviation_length += 1 abbreviations.clear() def automatic_abbreviations(filename, words_per_line): with open(filename) as file: for line in file: line = line.rstrip() if len(line) > 0: length = shortest_abbreviation_length(line, words_per_line) print(f'{length:2} {line}') else: print() automatic_abbreviations('daysOfWeek.txt', 7)
1,168Abbreviations, automatic
3python
kb6hf
fun divisors(n: Int): List<Int> { val divs = mutableListOf(1) val divs2 = mutableListOf<Int>() var i = 2 while (i * i <= n) { if (n % i == 0) { val j = n / i divs.add(i) if (i != j) { divs2.add(j) } } i++ } divs.addAll(divs2.reversed()) return divs } fun abundantOdd(searchFrom: Int, countFrom: Int, countTo: Int, printOne: Boolean): Int { var count = countFrom var n = searchFrom while (count < countTo) { val divs = divisors(n) val tot = divs.sum() if (tot > n) { count++ if (!printOne || count >= countTo) { val s = divs.joinToString(" + ") if (printOne) { println("$n < $s = $tot") } else { println("%2d.%5d <%s =%d".format(count, n, s, tot)) } } } n += 2 } return n } fun main() { val max = 25 println("The first $max abundant odd numbers are:") val n = abundantOdd(1, 0, 25, false) println("\nThe one thousandth abundant odd number is:") abundantOdd(n, 25, 1000, true) println("\nThe first abundant odd number above one billion is:") abundantOdd((1e9 + 1).toInt(), 0, 1, true) }
1,169Abundant odd numbers
11kotlin
8o40q
trait Shape { fn area(self) -> i32; }
1,166Abstract type
15rust
hkyj2