code
stringlengths
1
46.1k
label
class label
1.18k classes
domain_label
class label
21 classes
index
stringlengths
4
5
from collections import defaultdict from heapq import nlargest data = [('Employee Name', 'Employee ID', 'Salary', 'Department'), ('Tyler Bennett', 'E10297', 32000, 'D101'), ('John Rappl', 'E21437', 47000, 'D050'), ('George Woltman', 'E00127', 53500, 'D101'), ('Adam Smith', 'E63535', 18000, 'D202'), ('Claire Buckman', 'E39876', 27800, 'D202'), ('David McClellan', 'E04242', 41500, 'D101'), ('Rich Holcomb', 'E01234', 49500, 'D202'), ('Nathan Adams', 'E41298', 21900, 'D050'), ('Richard Potter', 'E43128', 15900, 'D101'), ('David Motsinger', 'E27002', 19250, 'D202'), ('Tim Sampair', 'E03033', 27000, 'D101'), ('Kim Arlich', 'E10001', 57000, 'D190'), ('Timothy Grove', 'E16398', 29900, 'D190')] departments = defaultdict(list) for rec in data[1:]: departments[rec[-1]].append(rec) N = 3 format = * len(data[0]) for department, recs in sorted(departments.items()): print (% department) print (format% data[0]) for rec in nlargest(N, recs, key=lambda rec: rec[-2]): print (format% rec) print('')
115Top rank per group
3python
p7lbm
Python 3.2.2 (default, Sep 4 2011, 09:51:08) [MSC v.1500 32 bit (Intel)] on win32 Type , or for more information. >>> from math import degrees, radians, sin, cos, tan, asin, acos, atan, pi >>> rad, deg = pi/4, 45.0 >>> print(, sin(rad), sin(radians(deg))) Sine: 0.7071067811865475 0.7071067811865475 >>> print(, cos(rad), cos(radians(deg))) Cosine: 0.7071067811865476 0.7071067811865476 >>> print(, tan(rad), tan(radians(deg))) Tangent: 0.9999999999999999 0.9999999999999999 >>> arcsine = asin(sin(rad)) >>> print(, arcsine, degrees(arcsine)) Arcsine: 0.7853981633974482 44.99999999999999 >>> arccosine = acos(cos(rad)) >>> print(, arccosine, degrees(arccosine)) Arccosine: 0.7853981633974483 45.0 >>> arctangent = atan(tan(rad)) >>> print(, arctangent, degrees(arctangent)) Arctangent: 0.7853981633974483 45.0 >>>
111Trigonometric functions
3python
4ly5k
dfr <- read.csv(tc <- textConnection( "Employee Name,Employee ID,Salary,Department Tyler Bennett,E10297,32000,D101 John Rappl,E21437,47000,D050 George Woltman,E00127,53500,D101 Adam Smith,E63535,18000,D202 Claire Buckman,E39876,27800,D202 David McClellan,E04242,41500,D101 Rich Holcomb,E01234,49500,D202 Nathan Adams,E41298,21900,D050 Richard Potter,E43128,15900,D101 David Motsinger,E27002,19250,D202 Tim Sampair,E03033,27000,D101 Kim Arlich,E10001,57000,D190 Timothy Grove,E16398,29900,D190")); close(tc)
115Top rank per group
13r
j5y78
deg <- function(radians) 180*radians/pi rad <- function(degrees) degrees*pi/180 sind <- function(ang) sin(rad(ang)) cosd <- function(ang) cos(rad(ang)) tand <- function(ang) tan(rad(ang)) asind <- function(v) deg(asin(v)) acosd <- function(v) deg(acos(v)) atand <- function(v) deg(atan(v)) r <- pi/3 rd <- deg(r) print( c( sin(r), sind(rd)) ) print( c( cos(r), cosd(rd)) ) print( c( tan(r), tand(rd)) ) S <- sin(pi/4) C <- cos(pi/3) T <- tan(pi/4) print( c( asin(S), asind(S) ) ) print( c( acos(C), acosd(C) ) ) print( c( atan(T), atand(T) ) )
111Trigonometric functions
13r
2ytlg
<?php $str = 'Hello,How,Are,You,Today'; echo implode('.', explode(',', $str)); ?>
116Tokenize a string
12php
1jlpq
module TicTacToe LINES = [[1,2,3],[4,5,6],[7,8,9],[1,4,7],[2,5,8],[3,6,9],[1,5,9],[3,5,7]] class Game def initialize(player_1_class, player_2_class) @board = Array.new(10) @current_player_id = 0 @players = [player_1_class.new(self, ), player_2_class.new(self, )] puts end attr_reader :board, :current_player_id def play loop do place_player_marker(current_player) if player_has_won?(current_player) puts print_board return elsif board_full? puts print_board return end switch_players! end end def free_positions (1..9).select {|position| @board[position].nil?} end def place_player_marker(player) position = player.select_position! puts @board[position] = player.marker end def player_has_won?(player) LINES.any? do |line| line.all? {|position| @board[position] == player.marker} end end def board_full? free_positions.empty? end def other_player_id 1 - @current_player_id end def switch_players! @current_player_id = other_player_id end def current_player @players[current_player_id] end def opponent @players[other_player_id] end def turn_num 10 - free_positions.size end def print_board col_separator, row_separator = , label_for_position = lambda{|position| @board[position]? @board[position]: position} row_for_display = lambda{|row| row.map(&label_for_position).join(col_separator)} row_positions = [[1,2,3], [4,5,6], [7,8,9]] rows_for_display = row_positions.map(&row_for_display) puts rows_for_display.join( + row_separator + ) end end class Player def initialize(game, marker) @game = game @marker = marker end attr_reader :marker end class HumanPlayer < Player def select_position! @game.print_board loop do print selection = gets.to_i return selection if @game.free_positions.include?(selection) puts end end def to_s end end class ComputerPlayer < Player DEBUG = false def group_positions_by_markers(line) markers = line.group_by {|position| @game.board[position]} markers.default = [] markers end def select_position! opponent_marker = @game.opponent.marker winning_or_blocking_position = look_for_winning_or_blocking_position(opponent_marker) return winning_or_blocking_position if winning_or_blocking_position if corner_trap_defense_needed? return corner_trap_defense_position(opponent_marker) end return random_prioritized_position end def look_for_winning_or_blocking_position(opponent_marker) for line in LINES markers = group_positions_by_markers(line) next if markers[nil].length!= 1 if markers[self.marker].length == 2 log_debug return markers[nil].first elsif markers[opponent_marker].length == 2 log_debug blocking_position = markers[nil].first end end if blocking_position log_debug return blocking_position end end def corner_trap_defense_needed? corner_positions = [1, 3, 7, 9] opponent_chose_a_corner = corner_positions.any?{|pos| @game.board[pos]!= nil} return @game.turn_num == 2 && opponent_chose_a_corner end def corner_trap_defense_position(opponent_marker) log_debug opponent_position = @game.board.find_index {|marker| marker == opponent_marker} safe_responses = {1=>[2,4], 3=>[2,6], 7=>[4,8], 9=>[6,8]} return safe_responses[opponent_position].sample end def random_prioritized_position log_debug ([5] + [1,3,7,9].shuffle + [2,4,6,8].shuffle).find do |pos| @game.free_positions.include?(pos) end end def log_debug(message) puts if DEBUG end def to_s end end end include TicTacToe Game.new(ComputerPlayer, ComputerPlayer).play puts players_with_human = [HumanPlayer, ComputerPlayer].shuffle Game.new(*players_with_human).play
117Tic-tac-toe
14ruby
topf2
from collections import namedtuple Node = namedtuple('Node', 'data, left, right') tree = Node(1, Node(2, Node(4, Node(7, None, None), None), Node(5, None, None)), Node(3, Node(6, Node(8, None, None), Node(9, None, None)), None)) def printwithspace(i): print(i, end=' ') def dfs(order, node, visitor): if node is not None: for action in order: if action == 'N': visitor(node.data) elif action == 'L': dfs(order, node.left, visitor) elif action == 'R': dfs(order, node.right, visitor) def preorder(node, visitor = printwithspace): dfs('NLR', node, visitor) def inorder(node, visitor = printwithspace): dfs('LNR', node, visitor) def postorder(node, visitor = printwithspace): dfs('LRN', node, visitor) def ls(node, more, visitor, order='TB'): if node: if more is None: more = [] more += [node.left, node.right] for action in order: if action == 'B' and more: ls(more[0], more[1:], visitor, order) elif action == 'T' and node: visitor(node.data) def levelorder(node, more=None, visitor = printwithspace): ls(node, more, visitor, 'TB') def reverse_preorder(node, visitor = printwithspace): dfs('RLN', node, visitor) def bottom_up_order(node, more=None, visitor = printwithspace, order='BT'): ls(node, more, visitor, 'BT') if __name__ == '__main__': w = 10 for traversal in [preorder, inorder, postorder, levelorder, reverse_preorder, bottom_up_order]: if traversal == reverse_preorder: w = 20 print('\nThe generalisation of function dfs allows:') if traversal == bottom_up_order: print('The generalisation of function ls allows:') print(f, end=' ') traversal(tree) print()
113Tree traversal
3python
l6ncv
public void move(int n, int from, int to, int via) { if (n == 1) { System.out.println("Move disk from pole " + from + " to pole " + to); } else { move(n - 1, from, via, to); move(1, from, to, via); move(n - 1, via, to, from); } }
119Towers of Hanoi
9java
g2n4m
use GameState::{ComputerWin, Draw, PlayerWin, Playing}; use rand::prelude::*; #[derive(PartialEq, Debug)] enum GameState { PlayerWin, ComputerWin, Draw, Playing, } type Board = [[char; 3]; 3]; fn main() { let mut rng = StdRng::from_entropy(); let mut board: Board = [['1', '2', '3'], ['4', '5', '6'], ['7', '8', '9']]; draw_board(board); loop { player_turn(&mut board); if check_win(board)!= Playing { break; } computer_turn(&mut rng, &mut board); if check_win(board)!= Playing { break; } draw_board(board); } draw_board(board); let announcement = match check_win(board) { PlayerWin => "The Player has won!", ComputerWin => "The Computer has won!", Draw => "Draw!", Playing => unreachable!(), }; println!("{}", announcement); } fn is_empty(cell: &char) -> bool { *cell!= 'X' && *cell!= 'O' } fn check_win(board: Board) -> GameState {
117Tic-tac-toe
15rust
zi1to
function move(n, a, b, c) { if (n > 0) { move(n-1, a, c, b); console.log("Move disk from " + a + " to " + c); move(n-1, b, a, c); } } move(4, "A", "B", "C");
119Towers of Hanoi
10javascript
kg3hq
package object tictactoe { val Human = 'X' val Computer = 'O' val BaseBoard = ('1' to '9').toList val WinnerLines = List((0,1,2), (3,4,5), (6,7,8), (0,3,6), (1,4,7), (2,5,8), (0,4,8), (2,4,6)) val randomGen = new util.Random(System.currentTimeMillis) } package tictactoe { class Board(aBoard : List[Char] = BaseBoard) { def availableMoves = aBoard.filter(c => c != Human && c != Computer) def availableMovesIdxs = for ((c,i) <- aBoard.zipWithIndex if c != Human && c != Computer) yield i def computerPlays = new Board(aBoard.updated(availableMovesIdxs(randomGen.nextInt(availableMovesIdxs.length)), Computer)) def humanPlays(move : Char) = new Board(aBoard.updated(aBoard.indexOf(move), Human)) def isDraw = aBoard.forall(c => c == Human || c == Computer) def isWinner(winner : Char) = WinnerLines.exists{case (i,j,k) => aBoard(i) == winner && aBoard(j) == winner && aBoard(k) == winner} def isOver = isWinner(Computer) || isWinner(Human) || isDraw def print { aBoard.grouped(3).foreach(row => println(row(0) + " " + row(1) + " " + row(2))) } def printOverMessage { if (isWinner(Human)) println("You win.") else if (isWinner(Computer)) println("Computer wins.") else if (isDraw) println("It's a draw.") else println("Not over yet, or something went wrong.") } } object TicTacToe extends App { def play(board : Board, turn : Char) {
117Tic-tac-toe
16scala
yfw63
require data = <<EOS Employee Name,Employee ID,Salary,Department Tyler Bennett,E10297,32000,D101 John Rappl,E21437,47000,D050 George Woltman,E00127,53500,D101 Adam Smith,E63535,18000,D202 Claire Buckman,E39876,27800,D202 David McClellan,E04242,41500,D101 Rich Holcomb,E01234,49500,D202 Nathan Adams,E41298,21900,D050 Richard Potter,E43128,15900,D101 David Motsinger,E27002,19250,D202 Tim Sampair,E03033,27000,D101 Kim Arlich,E10001,57000,D190 Timothy Grove,E16398,29900,D190 EOS def show_top_salaries_per_group(data, n) table = CSV.parse(data, :headers=>true, :header_converters=>:symbol) groups = table.group_by{|emp| emp[:department]}.sort groups.each do |dept, emps| puts dept emps.max_by(n) {|emp| emp[:salary].to_i}.each do |e| puts % [e[:employee_name], e[:employee_id], e[:salary]] end puts end end show_top_salaries_per_group(data, 3)
115Top rank per group
14ruby
ahv1s
radians = Math::PI / 4 degrees = 45.0 def deg2rad(d) d * Math::PI / 180 end def rad2deg(r) r * 180 / Math::PI end puts puts puts arcsin = Math.asin(Math.sin(radians)) puts arccos = Math.acos(Math.cos(radians)) puts arctan = Math.atan(Math.tan(radians)) puts
111Trigonometric functions
14ruby
rv9gs
--Setup DROP TABLE IF EXISTS board; CREATE TABLE board (p CHAR, r INTEGER, c INTEGER); INSERT INTO board VALUES('.', 0, 0),('.', 0, 1),('.', 0, 2),('.', 1, 0),('.', 1, 1),('.', 1, 2),('.', 2, 0),('.', 2, 1),('.', 2, 2); -- Use a trigger for move events DROP TRIGGER IF EXISTS after_moved; CREATE TRIGGER after_moved after UPDATE ON board FOR each ROW WHEN NEW.p <> '.' AND NEW.p <> 'O' BEGIN -- Verify move is valid SELECT CASE WHEN (SELECT v FROM msg) LIKE '%Wins!' THEN raise(ABORT, 'The game is already over.') WHEN (SELECT OLD.p FROM board WHERE rowid = rid) <> '.' THEN raise(ABORT, 'That position has already been taken. Please choose an available position.') WHEN NEW.p <> 'X' THEN raise(ABORT, 'Please place an ''X''') END FROM ( SELECT rowid rid FROM board WHERE p = NEW.p EXCEPT SELECT p FROM board WHERE p = OLD.p ); -- Check for game over UPDATE msg SET v = ( SELECT CASE WHEN MAX(num) >= 3 THEN 'X Wins!' WHEN (SELECT COUNT(*) FROM board WHERE p = '.') = 0 THEN 'Cat Wins!' ELSE 'Move made' END FROM ( -- Is Game Over SELECT COUNT(*) num FROM board WHERE p = 'X' GROUP BY r UNION -- Horz SELECT COUNT(*) num FROM board WHERE p = 'X' GROUP BY c UNION -- Vert SELECT COUNT(*) num FROM board WHERE p = 'X' AND r = c UNION -- Diag TL->BR SELECT COUNT(*) num FROM board WHERE p = 'X' AND (2-r) = c -- Diag TR->BL ) ); --Have computer player make a random move UPDATE board SET p = 'O' WHERE rowid = (SELECT rid FROM (SELECT MAX(rnd),rid FROM (SELECT rowid rid, random() rnd FROM board WHERE p = '.'))) AND (SELECT v FROM msg) NOT LIKE '%Wins!'; --NOTE: SQLite doesn't allow update order by in triggers, otherwise we could just use this beautiful line: -- update board set p = 'O' where p = '.' order by random() limit 1; --Check to see if the computer player won UPDATE msg SET v = ( SELECT CASE WHEN MAX(num) >= 3 THEN 'O Wins!' ELSE v END FROM ( -- Is Game Over SELECT COUNT(*) num FROM board WHERE p = 'O' GROUP BY r UNION -- Horz SELECT COUNT(*) num FROM board WHERE p = 'O' GROUP BY c UNION -- Vert SELECT COUNT(*) num FROM board WHERE p = 'O' AND r = c UNION -- Diag TL->BR SELECT COUNT(*) num FROM board WHERE p = 'O' AND (2-r) = c -- Diag TR->BL ) ); END; -- UI to display the logical board as a grid DROP VIEW IF EXISTS ui; CREATE VIEW ui AS SELECT CASE WHEN p = '.' THEN col0.rowid ELSE p END c0, c1, c2 FROM board AS col0 JOIN (SELECT CASE WHEN p = '.' THEN board.rowid ELSE p END c1, r FROM board WHERE c = 1) AS col1 ON col0.r = col1.r JOIN (SELECT CASE WHEN p = '.' THEN board.rowid ELSE p END c2, r FROM board WHERE c = 2) AS col2 ON col0.r = col2.r WHERE c = 0; DROP TABLE IF EXISTS msg; CREATE TABLE msg (v text); INSERT INTO msg VALUES(''); -- Readme SELECT * FROM ui; .print .print '
117Tic-tac-toe
19sql
c3s9p
text = tokens = text.split(',') print ('.'.join(tokens))
116Tokenize a string
3python
yfx6q
#[derive(Debug)] struct Employee<S> {
115Top rank per group
15rust
ekuaj
import Darwin enum Token: CustomStringConvertible { case cross, circle func matches(tokens: [Token?]) -> Bool { for token in tokens { guard let t = token, t == self else { return false } } return true } func emptyCell(in tokens: [Token?]) -> Int? { if tokens[0] == nil && tokens[1] == self && tokens[2] == self { return 0 } else if tokens[0] == self && tokens[1] == nil && tokens[2] == self { return 1 } else if tokens[0] == self && tokens[1] == self && tokens[2] == nil { return 2 } return nil } var description: String { switch self { case .cross: return "x" case .circle: return "o" } } } struct Board { var cells: [Token?] = [nil, nil, nil, nil, nil, nil, nil, nil, nil] func cells(atCol col: Int) -> [Token?] { return [cells[col], cells[col + 3], cells[col + 6]] } func cells(atRow row: Int) -> [Token?] { return [cells[row * 3], cells[row * 3 + 1], cells[row * 3 + 2]] } func cellsTopLeft() -> [Token?] { return [cells[0], cells[4], cells[8]] } func cellsBottomLeft() -> [Token?] { return [cells[6], cells[4], cells[2]] } func winner() -> Token? { let r0 = cells(atRow: 0) let r1 = cells(atRow: 1) let r2 = cells(atRow: 2) let c0 = cells(atCol: 0) let c1 = cells(atCol: 1) let c2 = cells(atCol: 2) let tl = cellsTopLeft() let bl = cellsBottomLeft() if Token.cross.matches(tokens: r0) || Token.cross.matches(tokens: r1) || Token.cross.matches(tokens: r2) || Token.cross.matches(tokens: c0) || Token.cross.matches(tokens: c1) || Token.cross.matches(tokens: c2) || Token.cross.matches(tokens: tl) || Token.cross.matches(tokens: bl) { return .cross } else if Token.circle.matches(tokens: r0) || Token.circle.matches(tokens: r1) || Token.circle.matches(tokens: r2) || Token.circle.matches(tokens: c0) || Token.circle.matches(tokens: c1) || Token.circle.matches(tokens: c2) || Token.circle.matches(tokens: tl) || Token.circle.matches(tokens: bl) { return .circle } return nil } func atCapacity() -> Bool { return cells.filter { $0 == nil }.count == 0 } mutating func play(token: Token, at location: Int) { cells[location] = token } func findBestLocation(for player: Token) -> Int? { let r0 = cells(atRow: 0) let r1 = cells(atRow: 1) let r2 = cells(atRow: 2) let c0 = cells(atCol: 0) let c1 = cells(atCol: 1) let c2 = cells(atCol: 2) let tl = cellsTopLeft() let bl = cellsBottomLeft() if let cell = player.emptyCell(in: r0) { return cell } else if let cell = player.emptyCell(in: r1) { return cell + 3 } else if let cell = player.emptyCell(in: r2) { return cell + 6 } else if let cell = player.emptyCell(in: c0) { return cell * 3 } else if let cell = player.emptyCell(in: c1) { return cell * 3 + 1 } else if let cell = player.emptyCell(in: c2) { return cell * 3 + 2 } else if let cell = player.emptyCell(in: tl) { return cell == 0? 0: (cell == 1? 4: 8) } else if let cell = player.emptyCell(in: bl) { return cell == 0? 6: (cell == 1? 4: 2) } return nil } func findMove() -> Int { let empties = cells.enumerated().filter { $0.1 == nil } let r = Int(arc4random())% empties.count return empties[r].0 } } extension Board: CustomStringConvertible { var description: String { var result = "\n---------------\n" for (idx, cell) in cells.enumerated() { if let cell = cell { result += "| \(cell) |" } else { result += "| \(idx) |" } if (idx + 1)% 3 == 0 { result += "\n---------------\n" } } return result } } while true { var board = Board() print("Who do you want to play as ('o' or 'x'): ", separator: "", terminator: "") let answer = readLine()?.characters.first?? "x" var player: Token = answer == "x"? .cross: .circle var pc: Token = player == .cross? .circle: .cross print(board) while true { print("Choose cell to play on: ", separator: "", terminator: "") var pos = Int(readLine()?? "0")?? 0 while!board.atCapacity() && board.cells[pos]!= nil { print("Invalid move. Choose cell to play on: ", separator: "", terminator: "") pos = Int(readLine()?? "0")?? 0 } if board.atCapacity() { print("Draw") break } board.play(token: player, at: pos) print(board) if let winner = board.winner() { print("winner is \(winner)") break } else if board.atCapacity() { print("Draw") break } if let win = board.findBestLocation(for: pc) { board.play(token: pc, at: win) } else if let def = board.findBestLocation(for: player) { board.play(token: pc, at: def) } else { board.play(token: pc, at: board.findMove()) } print(board) if let winner = board.winner() { print("winner is \(winner)") break } } }
117Tic-tac-toe
17swift
f8bdk
null
111Trigonometric functions
15rust
7ucrc
import scala.io.Source import scala.language.implicitConversions import scala.language.reflectiveCalls import scala.collection.immutable.TreeMap object TopRank extends App { val topN = 3 val rawData = """Employee Name;Employee ID;Salary;Department |Tyler Bennett;E10297;32000;D101 |John Rappl;E21437;47000;D050 |George Woltman;E00127;53500;D101 |Adam Smith;E63535;18000;D202 |Claire Buckman;E39876;27800;D202 |David McClellan;E04242;41500;D101 |Rich Holcomb;E01234;49500;D202 |Nathan Adams;E41298;21900;D050 |Richard Potter;E43128;15900;D101 |David Motsinger;E27002;19250;D202 |Tim Sampair;E03033;27000;D101 |Kim Arlich;E10001;57000;D190 |Timothy Grove;E16398;29900;D190""".stripMargin class Employee(name: String, id: String, val salary: Int, val department: String) { override def toString = s"$id\t$salary\t$name" }
115Top rank per group
16scala
q1gxw
import scala.math._ object Gonio extends App {
111Trigonometric functions
16scala
kgvhk
BinaryTreeNode = Struct.new(:value, :left, :right) do def self.from_array(nested_list) value, left, right = nested_list if value self.new(value, self.from_array(left), self.from_array(right)) end end def walk_nodes(order, &block) order.each do |node| case node when :left then left && left.walk_nodes(order, &block) when:self then yield self when :right then right && right.walk_nodes(order, &block) end end end def each_preorder(&b) walk_nodes([:self, :left, :right], &b) end def each_inorder(&b) walk_nodes([:left,:self, :right], &b) end def each_postorder(&b) walk_nodes([:left, :right,:self], &b) end def each_levelorder queue = [self] until queue.empty? node = queue.shift yield node queue << node.left if node.left queue << node.right if node.right end end end root = BinaryTreeNode.from_array [1, [2, [4, 7], [5]], [3, [6, [8], [9]]]] BinaryTreeNode.instance_methods.select{|m| m=~/.+order/}.each do |mthd| printf , mthd[5..-1] + ':' root.send(mthd) {|node| print } puts end
113Tree traversal
14ruby
vmf2n
text <- "Hello,How,Are,You,Today" junk <- strsplit(text, split=",") print(paste(unlist(junk), collapse="."))
116Tokenize a string
13r
to1fz
null
119Towers of Hanoi
11kotlin
2ysli
#![feature(box_syntax, box_patterns)] use std::collections::VecDeque; #[derive(Debug)] struct TreeNode<T> { value: T, left: Option<Box<TreeNode<T>>>, right: Option<Box<TreeNode<T>>>, } enum TraversalMethod { PreOrder, InOrder, PostOrder, LevelOrder, } impl<T> TreeNode<T> { pub fn new(arr: &[[i8; 3]]) -> TreeNode<i8> { let l = match arr[0][1] { -1 => None, i @ _ => Some(Box::new(TreeNode::<i8>::new(&arr[(i - arr[0][0]) as usize..]))), }; let r = match arr[0][2] { -1 => None, i @ _ => Some(Box::new(TreeNode::<i8>::new(&arr[(i - arr[0][0]) as usize..]))), }; TreeNode { value: arr[0][0], left: l, right: r, } } pub fn traverse(&self, tr: &TraversalMethod) -> Vec<&TreeNode<T>> { match tr { &TraversalMethod::PreOrder => self.iterative_preorder(), &TraversalMethod::InOrder => self.iterative_inorder(), &TraversalMethod::PostOrder => self.iterative_postorder(), &TraversalMethod::LevelOrder => self.iterative_levelorder(), } } fn iterative_preorder(&self) -> Vec<&TreeNode<T>> { let mut stack: Vec<&TreeNode<T>> = Vec::new(); let mut res: Vec<&TreeNode<T>> = Vec::new(); stack.push(self); while!stack.is_empty() { let node = stack.pop().unwrap(); res.push(node); match node.right { None => {} Some(box ref n) => stack.push(n), } match node.left { None => {} Some(box ref n) => stack.push(n), } } res }
113Tree traversal
15rust
u9tvj
case class IntNode(value: Int, left: Option[IntNode] = None, right: Option[IntNode] = None) { def preorder(f: IntNode => Unit) { f(this) left.map(_.preorder(f))
113Tree traversal
16scala
g264i
CREATE TABLE EMP ( EMP_ID varchar2(6 CHAR), EMP_NAMEvarchar2(20 CHAR), DEPT_ID varchar2(4 CHAR), SALARY NUMBER(10,2) ); INSERT INTO EMP (EMP_ID, EMP_NAME, DEPT_ID, SALARY) VALUES ('E21437','John Rappl','D050',47000); INSERT INTO EMP (EMP_ID, EMP_NAME, DEPT_ID, SALARY) VALUES ('E10297','Tyler Bennett','D101',32000); INSERT INTO EMP (EMP_ID, EMP_NAME, DEPT_ID, SALARY) VALUES ('E00127','George Woltman','D101',53500); INSERT INTO EMP (EMP_ID, EMP_NAME, DEPT_ID, SALARY) VALUES ('E63535','Adam Smith','D202',18000); INSERT INTO EMP (EMP_ID, EMP_NAME, DEPT_ID, SALARY) VALUES ('E39876','Claire Buckman','D202',27800); INSERT INTO EMP (EMP_ID, EMP_NAME, DEPT_ID, SALARY) VALUES ('E04242','David McClellan','D101',41500); INSERT INTO EMP (EMP_ID, EMP_NAME, DEPT_ID, SALARY) VALUES ('E41298','Nathan Adams','D050',21900); INSERT INTO EMP (EMP_ID, EMP_NAME, DEPT_ID, SALARY) VALUES ('E43128','Richard Potter','D101',15900); INSERT INTO EMP (EMP_ID, EMP_NAME, DEPT_ID, SALARY) VALUES ('E27002','David Motsinger','D202',19250); INSERT INTO EMP (EMP_ID, EMP_NAME, DEPT_ID, SALARY) VALUES ('E03033','Tim Sampair','D101',27000); INSERT INTO EMP (EMP_ID, EMP_NAME, DEPT_ID, SALARY) VALUES ('E10001','Kim Arlich','D190',57000); INSERT INTO EMP (EMP_ID, EMP_NAME, DEPT_ID, SALARY) VALUES ('E16398','Timothy Grove','D190',29900); INSERT INTO EMP (EMP_ID, EMP_NAME, DEPT_ID, SALARY) VALUES ('E01234','Rich Holcomb','D202',49500); INSERT INTO EMP (EMP_ID, EMP_NAME, DEPT_ID, SALARY) VALUES ('E16399','Timothy Grave','D190',29900); INSERT INTO EMP (EMP_ID, EMP_NAME, DEPT_ID, SALARY) VALUES ('E16400','Timothy Grive','D190',29900); COMMIT;
115Top rank per group
19sql
8wj02
puts .split(',').join('.')
116Tokenize a string
14ruby
9zsmz
fn main() { let s = "Hello,How,Are,You,Today"; let tokens: Vec<&str> = s.split(",").collect(); println!("{}", tokens.join(".")); }
116Tokenize a string
15rust
c309z
struct Employee { var name: String var id: String var salary: Int var department: String } let employees = [ Employee(name: "Tyler Bennett", id: "E10297", salary: 32000, department: "D101"), Employee(name: "John Rappl", id: "E21437", salary: 47000, department: "D050"), Employee(name: "George Woltman", id: "E00127", salary: 53500, department: "D101"), Employee(name: "Adam Smith", id: "E63535", salary: 18000, department: "D202"), Employee(name: "Claire Buckman", id: "E39876", salary: 27800, department: "D202"), Employee(name: "David McClellan", id: "E04242", salary: 41500, department: "D101"), Employee(name: "Rich Holcomb", id: "E01234", salary: 49500, department: "D202"), Employee(name: "Nathan Adams", id: "E41298", salary: 21900, department: "D050"), Employee(name: "Richard Potter", id: "E43128", salary: 15900, department: "D101"), Employee(name: "David Motsinger", id: "E27002", salary: 19250, department: "D202"), Employee(name: "Tim Sampair", id: "E03033", salary: 27000, department: "D101"), Employee(name: "Kim Arlich", id: "E10001", salary: 57000, department: "D190"), Employee(name: "Timothy Grove", id: "E16398", salary: 29900, department: "D190") ] func highestSalaries(employees: [Employee], n: Int = 1) -> [String: [Employee]] { return employees.reduce(into: [:], {acc, employee in guard var cur = acc[employee.department] else { acc[employee.department] = [employee] return } if cur.count < n { cur.append(employee) } else if cur.last!.salary < employee.salary { cur[n - 1] = employee } acc[employee.department] = cur.sorted(by: { $0.salary > $1.salary }) }) } for (dept, employees) in highestSalaries(employees: employees, n: 3) { let employeeString = employees.map({ "\($0.name): \($0.salary)" }).joined(separator: "\n\t") print("\(dept)'s highest paid employees are: \n\t\(employeeString)") }
115Top rank per group
17swift
1j2pt
println("Hello,How,Are,You,Today" split "," mkString ".")
116Tokenize a string
16scala
vmi2s
function move(n, src, dst, via) if n > 0 then move(n - 1, src, via, dst) print(src, 'to', dst) move(n - 1, via, dst, src) end end move(4, 1, 2, 3)
119Towers of Hanoi
1lua
vm02x
class TreeNode<T> { let value: T let left: TreeNode? let right: TreeNode? init(value: T, left: TreeNode? = nil, right: TreeNode? = nil) { self.value = value self.left = left self.right = right } func preOrder(function: (T) -> Void) { function(value) if left!= nil { left!.preOrder(function: function) } if right!= nil { right!.preOrder(function: function) } } func inOrder(function: (T) -> Void) { if left!= nil { left!.inOrder(function: function) } function(value) if right!= nil { right!.inOrder(function: function) } } func postOrder(function: (T) -> Void) { if left!= nil { left!.postOrder(function: function) } if right!= nil { right!.postOrder(function: function) } function(value) } func levelOrder(function: (T) -> Void) { var queue: [TreeNode] = [] queue.append(self) while queue.count > 0 { let node = queue.removeFirst() function(node.value) if node.left!= nil { queue.append(node.left!) } if node.right!= nil { queue.append(node.right!) } } } } typealias Node = TreeNode<Int> let n = Node(value: 1, left: Node(value: 2, left: Node(value: 4, left: Node(value: 7)), right: Node(value: 5)), right: Node(value: 3, left: Node(value: 6, left: Node(value: 8), right: Node(value: 9)))) let fn = { print($0, terminator: " ") } print("pre-order: ", terminator: "") n.preOrder(function: fn) print() print("in-order: ", terminator: "") n.inOrder(function: fn) print() print("post-order: ", terminator: "") n.postOrder(function: fn) print() print("level-order: ", terminator: "") n.levelOrder(function: fn) print()
113Tree traversal
17swift
2ydlj
let text = "Hello,How,Are,You,Today" let tokens = text.components(separatedBy: ",")
116Tokenize a string
17swift
mtqyk
sub hanoi { my ($n, $from, $to, $via) = (@_, 1, 2, 3); if ($n == 1) { print "Move disk from pole $from to pole $to.\n"; } else { hanoi($n - 1, $from, $via, $to); hanoi(1, $from, $to, $via); hanoi($n - 1, $via, $to, $from); }; };
119Towers of Hanoi
2perl
sauq3
function move($n,$from,$to,$via) { if ($n === 1) { print(); } else { move($n-1,$from,$via,$to); move(1,$from,$to,$via); move($n-1,$via,$to,$from); } }
119Towers of Hanoi
12php
u98v5
def hanoi(ndisks, startPeg=1, endPeg=3): if ndisks: hanoi(ndisks-1, startPeg, 6-startPeg-endPeg) print % (ndisks, startPeg, endPeg) hanoi(ndisks-1, 6-startPeg-endPeg, endPeg) hanoi(ndisks=4)
119Towers of Hanoi
3python
0e5sq
hanoimove <- function(ndisks, from, to, via) { if (ndisks == 1) { cat("move disk from", from, "to", to, "\n") } else { hanoimove(ndisks - 1, from, via, to) hanoimove(1, from, to, via) hanoimove(ndisks - 1, via, to, from) } } hanoimove(4, 1, 2, 3)
119Towers of Hanoi
13r
wble5
def move(num_disks, start=0, target=1, using=2) if num_disks == 1 @towers[target] << @towers[start].pop puts else move(num_disks-1, start, using, target) move(1, start, target, using) move(num_disks-1, using, target, start) end end n = 5 @towers = [[*1..n].reverse, [], []] move(n)
119Towers of Hanoi
14ruby
oxg8v
fn move_(n: i32, from: i32, to: i32, via: i32) { if n > 0 { move_(n - 1, from, via, to); println!("Move disk from pole {} to pole {}", from, to); move_(n - 1, via, to, from); } } fn main() { move_(4, 1,2,3); }
119Towers of Hanoi
15rust
iqrod
def move(n: Int, from: Int, to: Int, via: Int) : Unit = { if (n == 1) { Console.println("Move disk from pole " + from + " to pole " + to) } else { move(n - 1, from, via, to) move(1, from, to, via) move(n - 1, via, to, from) } }
119Towers of Hanoi
16scala
f8hd4
func hanoi(n:Int, a:String, b:String, c:String) { if (n > 0) { hanoi(n - 1, a, c, b) println("Move disk from \(a) to \(c)") hanoi(n - 1, b, a, c) } } hanoi(4, "A", "B", "C")
119Towers of Hanoi
17swift
8w40v
int main(void) { int nprimes = 1000000; int nmax = ceil(nprimes*(log(nprimes)+log(log(nprimes))-0.9385)); int i, j, m, k; int *a; k = (nmax-2)/2; a = (int *)calloc(k + 1, sizeof(int)); for(i = 0; i <= k; i++)a[i] = 2*i+1; for (i = 1; (i+1)*i*2 <= k; i++) for (j = i; j <= (k-i)/(2*i+1); j++) { m = i + j + 2*i*j; if(a[m]) a[m] = 0; } for (i = 1, j = 0; i <= k; i++) if (a[i]) { if(j%10 == 0 && j <= 100)printf(); j++; if(j <= 100)printf(, a[i]); else if(j == nprimes){ printf(,j,a[i]); break; } } }
120The sieve of Sundaram
5c
xplwu
package main import ( "fmt" "math" "rcu" "time" ) func sos(n int) []int { if n < 3 { return []int{} } var primes []int k := (n-3)/2 + 1 marked := make([]bool, k)
120The sieve of Sundaram
0go
l6xcw
import Data.List (intercalate, transpose) import Data.List.Split (chunksOf) import qualified Data.Set as S import Text.Printf (printf) sundaram :: Integral a => a -> [a] sundaram n = [ succ (2 * x) | x <- [1 .. m], x `S.notMember` excluded ] where m = div (pred n) 2 excluded = S.fromList [ 2 * i * j + i + j | let fm = fromIntegral m, i <- [1 .. floor (sqrt (fm / 2))], let fi = fromIntegral i, j <- [i .. floor ((fm - fi) / succ (2 * fi))] ] nSundaramPrimes :: (Integral a1, RealFrac a2, Floating a2) => a2 -> [a1] nSundaramPrimes n = sundaram $ floor $ (2.4 * n * log n) / 2 main :: IO () main = do putStrLn "First 100 Sundaram primes (starting at 3):\n" (putStrLn . table " " . chunksOf 10) $ show <$> nSundaramPrimes 100 table :: String -> [[String]] -> String table gap rows = let ws = maximum . fmap length <$> transpose rows pw = printf . flip intercalate ["%", "s"] . show in unlines $ intercalate gap . zipWith pw ws <$> rows
120The sieve of Sundaram
8haskell
1jyps
(() => { "use strict";
120The sieve of Sundaram
10javascript
p76b7
use strict; use warnings; use feature 'say'; my @sieve; my $nth = 1_000_000; my $k = 2.4 * $nth * log($nth) / 2; $sieve[$k] = 0; for my $i (1 .. $k) { my $j = $i; while ((my $l = $i + $j + 2 * $i * $j) < $k) { $sieve[$l] = 1; $j++ } } $sieve[0] = 1; my @S = (grep { $_ } map { ! $sieve[$_] and 1+$_*2 } 0..@sieve)[0..99]; say "First 100 Sundaram primes:\n" . (sprintf "@{['%5d' x 100]}", @S) =~ s/(.{50})/$1\n/gr; my ($count, $index); for (@sieve) { $count += !$_; (say "One millionth: " . (1+2*$index)) and last if $count == $nth; ++$index; }
120The sieve of Sundaram
2perl
8w50w
from numpy import log def sieve_of_Sundaram(nth, print_all=True): assert nth > 0, k = int((2.4 * nth * log(nth)) integers_list = [True] * k for i in range(1, k): j = i while i + j + 2 * i * j < k: integers_list[i + j + 2 * i * j] = False j += 1 pcount = 0 for i in range(1, k + 1): if integers_list[i]: pcount += 1 if print_all: print(f, end=' ') if pcount% 10 == 0: print() if pcount == nth: print(f) break sieve_of_Sundaram(100, True) sieve_of_Sundaram(1000000, False)
120The sieve of Sundaram
3python
ox481
def sieve_of_sundaram(upto) n = (2.4 * upto * Math.log(upto)) / 2 k = (n - 3) / 2 + 1 bools = [true] * k (0..(Integer.sqrt(n) - 3) / 2 + 1).each do |i| p = 2*i + 3 s = (p*p - 3) / 2 (s..k).step(p){|j| bools[j] = false} end bools.filter_map.each_with_index {|b, i| (i + 1) * 2 + 1 if b } end p sieve_of_sundaram(100) n = 1_000_000 puts
120The sieve of Sundaram
14ruby
nsrit
double xval[N], t_sin[N], t_cos[N], t_tan[N]; double r_sin[N2], r_cos[N2], r_tan[N2]; double rho(double *x, double *y, double *r, int i, int n) { if (n < 0) return 0; if (!n) return y[i]; int idx = (N - 1 - n) * (N - n) / 2 + i; if (r[idx] != r[idx]) r[idx] = (x[i] - x[i + n]) / (rho(x, y, r, i, n - 1) - rho(x, y, r, i + 1, n - 1)) + rho(x, y, r, i + 1, n - 2); return r[idx]; } double thiele(double *x, double *y, double *r, double xin, int n) { if (n > N - 1) return 1; return rho(x, y, r, 0, n) - rho(x, y, r, 0, n - 2) + (xin - x[n]) / thiele(x, y, r, xin, n + 1); } int main() { int i; for (i = 0; i < N; i++) { xval[i] = i * STEP; t_sin[i] = sin(xval[i]); t_cos[i] = cos(xval[i]); t_tan[i] = t_sin[i] / t_cos[i]; } for (i = 0; i < N2; i++) r_sin[i] = r_cos[i] = r_tan[i] = 0/0.; printf(, 6 * i_sin(.5)); printf(, 3 * i_cos(.5)); printf(, 4 * i_tan(1.)); return 0; }
121Thiele's interpolation formula
5c
yfp6f
package main import ( "fmt" "math" ) func main() {
121Thiele's interpolation formula
0go
1j6p5
thiele :: [Double] -> [Double] -> Double -> Double thiele xs ys = f rho1 (tail xs) where f _ [] _ = 1 f r@(r0:r1:r2:rs) (x:xs) v = r2 - r0 + (v - x) / f (tail r) xs v rho1 = (!! 1) . (++ [0]) <$> rho rho = repeat 0: repeat 0: ys: rnext (tail rho) xs (tail xs) where rnext _ _ [] = [] rnext r@(r0:r1:rs) x xn = let z_ = zipWith in z_ (+) (tail r0) (z_ (/) (z_ (-) x xn) (z_ (-) r1 (tail r1))): rnext (tail r) x (tail xn) invInterp :: (Double -> Double) -> [Double] -> Double -> Double invInterp f xs = thiele (map f xs) xs main :: IO () main = mapM_ print [ 3.21 * inv_sin (sin (pi / 3.21)) , pi / 1.2345 * inv_cos (cos 1.2345) , 7 * inv_tan (tan (pi / 7)) ] where [inv_sin, inv_cos, inv_tan] = uncurry ((. div_pi) . invInterp) <$> [(sin, (2, 31)), (cos, (2, 100)), (tan, (4, 1000))] div_pi (d, n) = (* (pi / (d * n))) <$> [0 .. n]
121Thiele's interpolation formula
8haskell
tojf7
import static java.lang.Math.*; public class Test { final static int N = 32; final static int N2 = (N * (N - 1) / 2); final static double STEP = 0.05; static double[] xval = new double[N]; static double[] t_sin = new double[N]; static double[] t_cos = new double[N]; static double[] t_tan = new double[N]; static double[] r_sin = new double[N2]; static double[] r_cos = new double[N2]; static double[] r_tan = new double[N2]; static double rho(double[] x, double[] y, double[] r, int i, int n) { if (n < 0) return 0; if (n == 0) return y[i]; int idx = (N - 1 - n) * (N - n) / 2 + i; if (r[idx] != r[idx]) r[idx] = (x[i] - x[i + n]) / (rho(x, y, r, i, n - 1) - rho(x, y, r, i + 1, n - 1)) + rho(x, y, r, i + 1, n - 2); return r[idx]; } static double thiele(double[] x, double[] y, double[] r, double xin, int n) { if (n > N - 1) return 1; return rho(x, y, r, 0, n) - rho(x, y, r, 0, n - 2) + (xin - x[n]) / thiele(x, y, r, xin, n + 1); } public static void main(String[] args) { for (int i = 0; i < N; i++) { xval[i] = i * STEP; t_sin[i] = sin(xval[i]); t_cos[i] = cos(xval[i]); t_tan[i] = t_sin[i] / t_cos[i]; } for (int i = 0; i < N2; i++) r_sin[i] = r_cos[i] = r_tan[i] = Double.NaN; System.out.printf("%16.14f%n", 6 * thiele(t_sin, xval, r_sin, 0.5, 0)); System.out.printf("%16.14f%n", 3 * thiele(t_cos, xval, r_cos, 0.5, 0)); System.out.printf("%16.14f%n", 4 * thiele(t_tan, xval, r_tan, 1.0, 0)); } }
121Thiele's interpolation formula
9java
8wu06
null
121Thiele's interpolation formula
11kotlin
wb9ek
use strict; use warnings; use feature 'say'; use Math::Trig; use utf8; sub thiele { my($x, $y) = @_; my @; push @, [($$y[$_]) x (@$y-$_)] for 0 .. @$y-1; for my $i (0 .. @ - 2) { $[$i][1] = (($$x[$i] - $$x[$i+1]) / ($[$i][0] - $[$i+1][0])) } for my $i (2 .. @ - 2) { for my $j (0 .. (@ - 2) - $i) { $[$j][$i] = ((($$x[$j]-$$x[$j+$i]) / ($[$j][$i-1]-$[$j+1][$i-1])) + $[$j+1][$i-2]) } } my @0 = @{$[0]}; return sub { my($xin) = @_; my $a = 0; for my $i (reverse 2 .. @0 - 2) { $a = (($xin - $$x[$i-1]) / ($0[$i] - $0[$i-2] + $a)) } $$y[0] + (($xin - $$x[0]) / ($0[1] + $a)) } } my(@x,@sin_table,@cos_table,@tan_table); push @x, .05 * $_ for 0..31; push @sin_table, sin($_) for @x; push @cos_table, cos($_) for @x; push @tan_table, tan($_) for @x; my $sin_inverse = thiele(\@sin_table, \@x); my $cos_inverse = thiele(\@cos_table, \@x); my $tan_inverse = thiele(\@tan_table, \@x); say 6 * &$sin_inverse(0.5); say 3 * &$cos_inverse(0.5); say 4 * &$tan_inverse(1.0);
121Thiele's interpolation formula
2perl
l6wc5
import math def thieleInterpolator(x, y): = [[yi]*(len(y)-i) for i, yi in enumerate(y)] for i in range(len()-1): [i][1] = (x[i] - x[i+1]) / ([i][0] - [i+1][0]) for i in range(2, len()): for j in range(len()-i): [j][i] = (x[j]-x[j+i]) / ([j][i-1]-[j+1][i-1]) + [j+1][i-2] 0 = [0] def t(xin): a = 0 for i in range(len(0)-1, 1, -1): a = (xin - x[i-1]) / (0[i] - 0[i-2] + a) return y[0] + (xin-x[0]) / (0[1]+a) return t xVal = [i*.05 for i in range(32)] tSin = [math.sin(x) for x in xVal] tCos = [math.cos(x) for x in xVal] tTan = [math.tan(x) for x in xVal] iSin = thieleInterpolator(tSin, xVal) iCos = thieleInterpolator(tCos, xVal) iTan = thieleInterpolator(tTan, xVal) print('{:16.14f}'.format(6*iSin(.5))) print('{:16.14f}'.format(3*iCos(.5))) print('{:16.14f}'.format(4*iTan(1)))
121Thiele's interpolation formula
3python
2yxlz
void print_verse(const char *name) { char *x, *y; int b = 1, f = 1, m = 1, i = 1; x = strdup(name); x[0] = toupper(x[0]); for (; x[i]; ++i) x[i] = tolower(x[i]); if (strchr(, x[0])) { y = strdup(x); y[0] = tolower(y[0]); } else { y = x + 1; } switch(x[0]) { case 'B': b = 0; break; case 'F': f = 0; break; case 'M': m = 0; break; default : break; } printf(, x, x, (b) ? : , y); printf(, (f) ? : , y); printf(, (m) ? : , y); printf(, x); } int main() { int i; const char *names[6] = {, , , , , }; for (i = 0; i < 6; ++i) print_verse(names[i]); return 0; }
122The Name Game
5c
vmx2o
char text_char(char c) { switch (c) { case 'a': case 'b': case 'c': return '2'; case 'd': case 'e': case 'f': return '3'; case 'g': case 'h': case 'i': return '4'; case 'j': case 'k': case 'l': return '5'; case 'm': case 'n': case 'o': return '6'; case 'p': case 'q': case 'r': case 's': return '7'; case 't': case 'u': case 'v': return '8'; case 'w': case 'x': case 'y': case 'z': return '9'; default: return 0; } } bool text_string(const GString* word, GString* text) { g_string_set_size(text, word->len); for (size_t i = 0; i < word->len; ++i) { char c = text_char(g_ascii_tolower(word->str[i])); if (c == 0) return false; text->str[i] = c; } return true; } typedef struct textonym_tag { const char* text; size_t length; GPtrArray* words; } textonym_t; int compare_by_text_length(const void* p1, const void* p2) { const textonym_t* t1 = p1; const textonym_t* t2 = p2; if (t1->length > t2->length) return -1; if (t1->length < t2->length) return 1; return strcmp(t1->text, t2->text); } int compare_by_word_count(const void* p1, const void* p2) { const textonym_t* t1 = p1; const textonym_t* t2 = p2; if (t1->words->len > t2->words->len) return -1; if (t1->words->len < t2->words->len) return 1; return strcmp(t1->text, t2->text); } void print_words(GPtrArray* words) { for (guint i = 0, n = words->len; i < n; ++i) { if (i > 0) printf(); printf(, g_ptr_array_index(words, i)); } printf(); } void print_top_words(GArray* textonyms, guint top) { for (guint i = 0; i < top; ++i) { const textonym_t* t = &g_array_index(textonyms, textonym_t, i); printf(, t->text); print_words(t->words); } } void free_strings(gpointer ptr) { g_ptr_array_free(ptr, TRUE); } bool find_textonyms(const char* filename, GError** error_ptr) { GError* error = NULL; GIOChannel* channel = g_io_channel_new_file(filename, , &error); if (channel == NULL) { g_propagate_error(error_ptr, error); return false; } GHashTable* ht = g_hash_table_new_full(g_str_hash, g_str_equal, g_free, free_strings); GString* word = g_string_sized_new(64); GString* text = g_string_sized_new(64); guint count = 0; gsize term_pos; while (g_io_channel_read_line_string(channel, word, &term_pos, &error) == G_IO_STATUS_NORMAL) { g_string_truncate(word, term_pos); if (!text_string(word, text)) continue; GPtrArray* words = g_hash_table_lookup(ht, text->str); if (words == NULL) { words = g_ptr_array_new_full(1, g_free); g_hash_table_insert(ht, g_strdup(text->str), words); } g_ptr_array_add(words, g_strdup(word->str)); ++count; } g_io_channel_unref(channel); g_string_free(word, TRUE); g_string_free(text, TRUE); if (error != NULL) { g_propagate_error(error_ptr, error); g_hash_table_destroy(ht); return false; } GArray* words = g_array_new(FALSE, FALSE, sizeof(textonym_t)); GHashTableIter iter; gpointer key, value; g_hash_table_iter_init(&iter, ht); while (g_hash_table_iter_next(&iter, &key, &value)) { GPtrArray* v = value; if (v->len > 1) { textonym_t textonym; textonym.text = key; textonym.length = strlen(key); textonym.words = v; g_array_append_val(words, textonym); } } printf(, count, filename); guint size = g_hash_table_size(ht); printf(, size); guint textonyms = words->len; printf(, textonyms); guint top = 5; if (textonyms < top) top = textonyms; printf(, top); g_array_sort(words, compare_by_word_count); print_top_words(words, top); printf(, top); g_array_sort(words, compare_by_text_length); print_top_words(words, top); g_array_free(words, TRUE); g_hash_table_destroy(ht); return true; } int main(int argc, char** argv) { if (argc != 2) { fprintf(stderr, , argv[0]); return EXIT_FAILURE; } GError* error = NULL; if (!find_textonyms(argv[1], &error)) { if (error != NULL) { fprintf(stderr, , argv[1], error->message); g_error_free(error); } return EXIT_FAILURE; } return EXIT_SUCCESS; }
123Textonyms
5c
u9xv4
const N: usize = 32; const STEP: f64 = 0.05; fn main() { let x: Vec<f64> = (0..N).map(|i| i as f64 * STEP).collect(); let sin = x.iter().map(|x| x.sin()).collect::<Vec<_>>(); let cos = x.iter().map(|x| x.cos()).collect::<Vec<_>>(); let tan = x.iter().map(|x| x.tan()).collect::<Vec<_>>(); println!( "{}\n{}\n{}", 6. * thiele(&sin, &x, 0.5), 3. * thiele(&cos, &x, 0.5), 4. * thiele(&tan, &x, 1.) ); } fn thiele(x: &[f64], y: &[f64], xin: f64) -> f64 { let mut p: Vec<Vec<f64>> = (0..N).map(|i| (i..N).map(|_| 0.0).collect()).collect(); (0..N).for_each(|i| p[i][0] = y[i]); (0..N - 1).for_each(|i| p[i][1] = (x[i] - x[i + 1]) / (p[i][0] - p[i + 1][0])); (2..N).for_each(|i| { (0..N - i).for_each(|j| { p[j][i] = (x[j] - x[j + i]) / (p[j][i - 1] - p[j + 1][i - 1]) + p[j + 1][i - 2]; }) }); let mut a = 0.; (2..N).rev().for_each(|i| { a = (xin - x[i - 1]) / (p[0][i] - p[0][i - 2] + a); }); y[0] + (xin - x[0]) / (p[0][1] + a) }
121Thiele's interpolation formula
15rust
5c0uq
typedef struct { const char *s; int ln, bad; } rec_t; int cmp_rec(const void *aa, const void *bb) { const rec_t *a = aa, *b = bb; return a->s == b->s ? 0 : !a->s ? 1 : !b->s ? -1 : strncmp(a->s, b->s, 10); } int read_file(const char *fn) { int fd = open(fn, O_RDONLY); if (fd == -1) return 0; struct stat s; fstat(fd, &s); char *txt = malloc(s.st_size); read(fd, txt, s.st_size); close(fd); int i, j, lines = 0, k, di, bad; for (i = lines = 0; i < s.st_size; i++) if (txt[i] == '\n') { txt[i] = '\0'; lines++; } rec_t *rec = calloc(sizeof(rec_t), lines); const char *ptr, *end; rec[0].s = txt; rec[0].ln = 1; for (i = 0; i < lines; i++) { if (i + 1 < lines) { rec[i + 1].s = rec[i].s + strlen(rec[i].s) + 1; rec[i + 1].ln = i + 2; } if (sscanf(rec[i].s, , &di, &di, &di) != 3) { printf(, i, rec[i].s); rec[i].s = 0; continue; } ptr = rec[i].s + 10; for (j = k = 0; j < 25; j++) { if (!strtod(ptr, (char**)&end) && end == ptr) break; k++, ptr = end; if (!(di = strtol(ptr, (char**)&end, 10)) && end == ptr) break; k++, ptr = end; if (di < 1) rec[i].bad = 1; } if (k != 48) { printf(, i, rec[i].s); rec[i].s = 0; } } qsort(rec, lines, sizeof(rec_t), cmp_rec); for (i = 1, bad = rec[0].bad, j = 0; i < lines && rec[i].s; i++) { if (rec[i].bad) bad++; if (strncmp(rec[i].s, rec[j].s, 10)) { j = i; } else printf(, rec[i].ln, rec[i].s); } free(rec); free(txt); printf(, lines - bad, lines); return 0; } int main() { read_file(); return 0; }
124Text processing/2
5c
g2s45
let N = 32 let N2 = N * (N - 1) / 2 let step = 0.05 var xval = [Double](repeating: 0, count: N) var tsin = [Double](repeating: 0, count: N) var tcos = [Double](repeating: 0, count: N) var ttan = [Double](repeating: 0, count: N) var rsin = [Double](repeating: .nan, count: N2) var rcos = [Double](repeating: .nan, count: N2) var rtan = [Double](repeating: .nan, count: N2) func rho(_ x: [Double], _ y: [Double], _ r: inout [Double], _ i: Int, _ n: Int) -> Double { guard n >= 0 else { return 0 } guard n!= 0 else { return y[i] } let idx = (N - 1 - n) * (N - n) / 2 + i if r[idx]!= r[idx] { r[idx] = (x[i] - x[i + n]) / (rho(x, y, &r, i, n - 1) - rho(x, y, &r, i + 1, n - 1)) + rho(x, y, &r, i + 1, n - 2) } return r[idx] } func thiele(_ x: [Double], _ y: [Double], _ r: inout [Double], _ xin: Double, _ n: Int) -> Double { guard n <= N - 1 else { return 1 } return rho(x, y, &r, 0, n) - rho(x, y, &r, 0, n - 2) + (xin - x[n]) / thiele(x, y, &r, xin, n + 1) } for i in 0..<N { xval[i] = Double(i) * step tsin[i] = sin(xval[i]) tcos[i] = cos(xval[i]) ttan[i] = tsin[i] / tcos[i] } print(String(format: "%16.14f", 6 * thiele(tsin, xval, &rsin, 0.5, 0))) print(String(format: "%16.14f", 3 * thiele(tcos, xval, &rcos, 0.5, 0))) print(String(format: "%16.14f", 4 * thiele(ttan, xval, &rtan, 1.0, 0)))
121Thiele's interpolation formula
17swift
vmq2r
(def table {\a 2 \b 2 \c 2 \A 2 \B 2 \C 2 \d 3 \e 3 \f 3 \D 3 \E 3 \F 3 \g 4 \h 4 \i 4 \G 4 \H 4 \I 4 \j 5 \k 5 \l 5 \J 5 \K 5 \L 5 \m 6 \n 6 \o 6 \M 6 \N 6 \O 6 \p 7 \q 7 \r 7 \s 7 \P 7 \Q 7 \R 7 \S 7 \t 8 \u 8 \v 8 \T 8 \U 8 \V 8 \w 9 \x 9 \y 9 \z 9 \W 9 \X 9 \Y 9 \Z 9}) (def words-url "http://www.puzzlers.org/pub/wordlists/unixdict.txt") (def words (-> words-url slurp clojure.string/split-lines)) (def digits (partial map table)) (let [textable (filter #(every? table %) words) mapping (group-by digits textable) textonyms (filter #(< 1 (count (val %))) mapping)] (print (str "There are " (count textable) " words in " \' words-url \' " which can be represented by the digit key mapping. They require " (count mapping) " digit combinations to represent them. " (count textonyms) " digit combinations represent Textonyms.")))
123Textonyms
6clojure
7uor0
(defn parse-line [s] (let [[date & data-toks] (str/split s #"\s+") data-fields (map read-string data-toks) valid-date? (fn [s] (re-find #"\d{4}-\d{2}-\d{2}" s)) valid-line? (and (valid-date? date) (= 48 (count data-toks)) (every? number? data-fields)) readings (for [[v flag] (partition 2 data-fields)] {:val v:flag flag})] (when (not valid-line?) (println "Malformed Line: " s)) {:date date :no-missing-readings? (and (= 48 (count data-toks)) (every? pos? (map:flag readings)))})) (defn analyze-file [path] (reduce (fn [m line] (let [{:keys [all-dates dupl-dates n-full-recs invalid-lines]} m this-date (:date line) dupl? (contains? all-dates this-date) full? (:no-missing-readings? line)] (cond-> m dupl? (update-in [:dupl-dates] conj this-date) full? (update-in [:n-full-recs] inc) true (update-in [:all-dates] conj this-date)))) {:dupl-dates #{}:all-dates #{}:n-full-recs 0} (->> (slurp path) clojure.string/split-lines (map parse-line)))) (defn report-summary [path] (let [m (analyze-file path)] (println (format "%d unique dates" (count (:all-dates m)))) (println (format "%d duplicated dates [%s]" (count (:dupl-dates m)) (clojure.string/join " " (sort (:dupl-dates m))))) (println (format "%d lines with no missing data" (:n-full-recs m)))))
124Text processing/2
6clojure
kgnhs
package main import ( "bufio" "flag" "fmt" "io" "log" "os" "strings" "unicode" ) func main() { log.SetFlags(0) log.SetPrefix("textonyms: ") wordlist := flag.String("wordlist", "wordlist", "file containing the list of words to check") flag.Parse() if flag.NArg() != 0 { flag.Usage() os.Exit(2) } t := NewTextonym(phoneMap) _, err := ReadFromFile(t, *wordlist) if err != nil { log.Fatal(err) } t.Report(os.Stdout, *wordlist) }
123Textonyms
0go
0elsk
import Data.Char (toUpper) import Data.Function (on) import Data.List (groupBy, sortBy) import Data.Maybe (fromMaybe, isJust, isNothing) toKey :: Char -> Maybe Char toKey ch | ch < 'A' = Nothing | ch < 'D' = Just '2' | ch < 'G' = Just '3' | ch < 'J' = Just '4' | ch < 'M' = Just '5' | ch < 'P' = Just '6' | ch < 'T' = Just '7' | ch < 'W' = Just '8' | ch <= 'Z' = Just '9' | otherwise = Nothing toKeyString :: String -> Maybe String toKeyString st | any isNothing mch = Nothing | otherwise = Just $ map (fromMaybe '!') mch where mch = map (toKey . toUpper) st showTextonym :: [(String, String)] -> String showTextonym ts = fst (head ts) ++ " => " ++ concat [ w ++ " " | (_, w) <- ts ] main :: IO () main = do let src = "unixdict.txt" contents <- readFile src let wordList = lines contents keyedList = [ (key, word) | (Just key, word) <- filter (isJust . fst) $ zip (map toKeyString wordList) wordList ] groupedList = groupBy ((==) `on` fst) $ sortBy (compare `on` fst) keyedList textonymList = filter ((> 1) . length) groupedList mapM_ putStrLn $ [ "There are " ++ show (length keyedList) ++ " words in " ++ src ++ " which can be represented by the digit key mapping.", "They require " ++ show (length groupedList) ++ " digit combinations to represent them.", show (length textonymList) ++ " digit combinations represent Textonyms.", "", "Top 5 in ambiguity:" ] ++ fmap showTextonym ( take 5 $ sortBy (flip compare `on` length) textonymList ) ++ ["", "Top 5 in length:"] ++ fmap showTextonym (take 5 $ sortBy (flip compare `on` (length . fst . head)) textonymList)
123Textonyms
8haskell
c3194
package main import ( "fmt" "strings" ) func printVerse(name string) { x := strings.Title(strings.ToLower(name)) y := x[1:] if strings.Contains("AEIOU", x[:1]) { y = strings.ToLower(x) } b := "b" + y f := "f" + y m := "m" + y switch x[0] { case 'B': b = y case 'F': f = y case 'M': m = y } fmt.Printf("%s,%s, bo-%s\n", x, x, b) fmt.Printf("Banana-fana fo-%s\n", f) fmt.Printf("Fee-fi-mo-%s\n", m) fmt.Printf("%s!\n\n", x) } func main() { names := [6]string{"gARY", "Earl", "Billy", "Felix", "Mary", "SHIRley"} for _, name := range names { printVerse(name) } }
122The Name Game
0go
salqa
char inout[INOUT_LEN]; char time[TIME_LEN]; uint jobnum; char maxtime[MAX_MAXOUT][TIME_LEN]; int main(int argc, char **argv) { FILE *in = NULL; int l_out = 0, maxout=-1, maxcount=0; if ( argc > 1 ) { in = fopen(argv[1], ); if ( in == NULL ) { fprintf(stderr, , argv[1]); exit(1); } } else { in = stdin; } while( fscanf(in, , inout, time, &jobnum) != EOF ) { if ( strcmp(inout, ) == 0 ) l_out++; else l_out--; if ( l_out > maxout ) { maxout = l_out; maxcount=0; maxtime[0][0] = '\0'; } if ( l_out == maxout ) { if ( maxcount < MAX_MAXOUT ) { strncpy(maxtime[maxcount], time, TIME_LEN); maxcount++; } else { fprintf(stderr, , MAX_MAXOUT); exit(1); } } } printf(, maxout); for(l_out=0; l_out < maxcount; l_out++) { printf(, maxtime[l_out]); } if ( in != stdin ) fclose(in); exit(0); }
125Text processing/Max licenses in use
5c
2y1lo
import Data.Char isVowel :: Char -> Bool isVowel c | char == 'A' = True | char == 'E' = True | char == 'I' = True | char == 'O' = True | char == 'U' = True | otherwise = False where char = toUpper c isSpecial :: Char -> Bool isSpecial c | char == 'B' = True | char == 'F' = True | char == 'M' = True | otherwise = False where char = toUpper c shorten :: String -> String shorten name | isVowel $ head name = map toLower name | otherwise = map toLower $ tail name line :: String -> Char -> String -> String line prefix letter name | letter == char = prefix ++ shorten name ++ "\n" | otherwise = prefix ++ letter:[] ++ shorten name ++ "\n" where char = toLower $ head name theNameGame :: String -> String theNameGame name = line (name ++ ", " ++ name ++ ", bo-") 'b' name ++ line "Banana-fana fo-" 'f' name ++ line "Fee-fi-mo-" 'm' name ++ name ++ "!\n" main = mapM_ (putStrLn . theNameGame) ["Gary", "Earl", "Billy", "Felix", "Mike", "Steve"]
122The Name Game
8haskell
9z1mo
import java.util.stream.Stream; public class NameGame { private static void printVerse(String name) { StringBuilder sb = new StringBuilder(name.toLowerCase()); sb.setCharAt(0, Character.toUpperCase(sb.charAt(0))); String x = sb.toString(); String y = "AEIOU".indexOf(x.charAt(0)) > -1 ? x.toLowerCase() : x.substring(1); String b = "b" + y; String f = "f" + y; String m = "m" + y; switch (x.charAt(0)) { case 'B': b = y; break; case 'F': f = y; break; case 'M': m = y; break; default:
122The Name Game
9java
to7f9
import java.io.IOException; import java.nio.charset.StandardCharsets; import java.nio.file.Path; import java.nio.file.Paths; import java.util.Arrays; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Scanner; import java.util.Vector; public class RTextonyms { private static final Map<Character, Character> mapping; private int total, elements, textonyms, max_found; private String filename, mappingResult; private Vector<String> max_strings; private Map<String, Vector<String>> values; static { mapping = new HashMap<Character, Character>(); mapping.put('A', '2'); mapping.put('B', '2'); mapping.put('C', '2'); mapping.put('D', '3'); mapping.put('E', '3'); mapping.put('F', '3'); mapping.put('G', '4'); mapping.put('H', '4'); mapping.put('I', '4'); mapping.put('J', '5'); mapping.put('K', '5'); mapping.put('L', '5'); mapping.put('M', '6'); mapping.put('N', '6'); mapping.put('O', '6'); mapping.put('P', '7'); mapping.put('Q', '7'); mapping.put('R', '7'); mapping.put('S', '7'); mapping.put('T', '8'); mapping.put('U', '8'); mapping.put('V', '8'); mapping.put('W', '9'); mapping.put('X', '9'); mapping.put('Y', '9'); mapping.put('Z', '9'); } public RTextonyms(String filename) { this.filename = filename; this.total = this.elements = this.textonyms = this.max_found = 0; this.values = new HashMap<String, Vector<String>>(); this.max_strings = new Vector<String>(); return; } public void add(String line) { String mapping = ""; total++; if (!get_mapping(line)) { return; } mapping = mappingResult; if (values.get(mapping) == null) { values.put(mapping, new Vector<String>()); } int num_strings; num_strings = values.get(mapping).size(); textonyms += num_strings == 1 ? 1 : 0; elements++; if (num_strings > max_found) { max_strings.clear(); max_strings.add(mapping); max_found = num_strings; } else if (num_strings == max_found) { max_strings.add(mapping); } values.get(mapping).add(line); return; } public void results() { System.out.printf("Read%,d words from%s%n%n", total, filename); System.out.printf("There are%,d words in%s which can be represented by the digit key mapping.%n", elements, filename); System.out.printf("They require%,d digit combinations to represent them.%n", values.size()); System.out.printf("%,d digit combinations represent Textonyms.%n", textonyms); System.out.printf("The numbers mapping to the most words map to%,d words each:%n", max_found + 1); for (String key : max_strings) { System.out.printf("%16s maps to:%s%n", key, values.get(key).toString()); } System.out.println(); return; } public void match(String key) { Vector<String> match; match = values.get(key); if (match == null) { System.out.printf("Key%s not found%n", key); } else { System.out.printf("Key%s matches:%s%n", key, match.toString()); } return; } private boolean get_mapping(String line) { mappingResult = line; StringBuilder mappingBuilder = new StringBuilder(); for (char cc : line.toCharArray()) { if (Character.isAlphabetic(cc)) { mappingBuilder.append(mapping.get(Character.toUpperCase(cc))); } else if (Character.isDigit(cc)) { mappingBuilder.append(cc); } else { return false; } } mappingResult = mappingBuilder.toString(); return true; } public static void main(String[] args) { String filename; if (args.length > 0) { filename = args[0]; } else { filename = "./unixdict.txt"; } RTextonyms tc; tc = new RTextonyms(filename); Path fp = Paths.get(filename); try (Scanner fs = new Scanner(fp, StandardCharsets.UTF_8.name())) { while (fs.hasNextLine()) { tc.add(fs.nextLine()); } } catch (IOException ex) { ex.printStackTrace(); } List<String> numbers = Arrays.asList( "001", "228", "27484247", "7244967473642", "." ); tc.results(); for (String number : numbers) { if (number.equals(".")) { System.out.println(); } else { tc.match(number); } } return; } }
123Textonyms
9java
zi7tq
function singNameGame(name) {
122The Name Game
10javascript
mtpyv
(defn delta [entry] (case (second (re-find #"\ (.*)\ @" entry)) "IN " -1 "OUT" 1 (throw (Exception. (str "Invalid entry:" entry))))) (defn t [entry] (second (re-find #"@\ (.*)\ f" entry))) (let [entries (clojure.string/split (slurp "mlijobs.txt") #"\n") in-use (reductions + (map delta entries)) m (apply max in-use) times (map #(nth (map t entries) %) (keep-indexed #(when (= m %2) %1) in-use))] (println "Maximum simultaneous license use is" m "at the following times:") (map println times))
125Text processing/Max licenses in use
6clojure
g2q4f
null
122The Name Game
11kotlin
oxu8z
null
123Textonyms
11kotlin
iquo4
package main import ( "bufio" "fmt" "log" "os" "strconv" "strings" "time" ) const ( filename = "readings.txt" readings = 24
124Text processing/2
0go
iqvog
function printVerse(name) local sb = string.lower(name) sb = sb:gsub("^%l", string.upper) local x = sb local x0 = x:sub(1,1) local y if x0 == 'A' or x0 == 'E' or x0 == 'I' or x0 == 'O' or x0 == 'U' then y = string.lower(x) else y = x:sub(2) end local b = "b" .. y local f = "f" .. y local m = "m" .. y if x0 == 'B' then b = y elseif x0 == 'F' then f = y elseif x0 == 'M' then m = y end print(x .. ", " .. x .. ", bo-" .. b) print("Banana-fana fo-" .. f) print("Fee-fi-mo-" .. m) print(x .. "!") print() return nil end local nameList = { "Gary", "Earl", "Billy", "Felix", "Mary", "Steve" } for _,name in pairs(nameList) do printVerse(name) end
122The Name Game
1lua
iq5ot
null
123Textonyms
1lua
ns5i8
import Data.List (nub, (\\)) data Record = Record {date :: String, recs :: [(Double, Int)]} duplicatedDates rs = rs \\ nub rs goodRecords = filter ((== 24) . length . filter ((>= 1) . snd) . recs) parseLine l = let ws = words l in Record (head ws) (mapRecords (tail ws)) mapRecords [] = [] mapRecords [_] = error "invalid data" mapRecords (value:flag:tail) = (read value, read flag): mapRecords tail main = do inputs <- (map parseLine . lines) `fmap` readFile "readings.txt" putStr (unlines ("duplicated dates:": duplicatedDates (map date inputs))) putStrLn ("number of good records: " ++ show (length $ goodRecords inputs))
124Text processing/2
8haskell
vme2k
my $src = 'unixdict.txt'; open $fh, "<", $src; @words = grep { /^[a-zA-Z]+$/ } <$fh>; map { tr/A-Z/a-z/ } @words; map { tr/abcdefghijklmnopqrstuvwxyz/22233344455566677778889999/ } @dials = @words; @dials = grep {!$h{$_}++} @dials; @textonyms = grep { $h{$_} > 1 } @dials; print "There are @{[scalar @words]} words in '$src' which can be represented by the digit key mapping. They require @{[scalar @dials]} digit combinations to represent them. @{[scalar @textonyms]} digit combinations represent Textonyms.";
123Textonyms
2perl
rv8gd
import java.util.*; import java.util.regex.*; import java.io.*; public class DataMunging2 { public static final Pattern e = Pattern.compile("\\s+"); public static void main(String[] args) { try { BufferedReader infile = new BufferedReader(new FileReader(args[0])); List<String> duplicates = new ArrayList<String>(); Set<String> datestamps = new HashSet<String>();
124Text processing/2
9java
yfh6g
sub printVerse { $x = ucfirst lc shift; $x0 = substr $x, 0, 1; $y = $x0 =~ /[AEIOU]/ ? lc $x : substr $x, 1; $b = $x0 eq 'B' ? $y : 'b' . $y; $f = $x0 eq 'F' ? $y : 'f' . $y; $m = $x0 eq 'M' ? $y : 'm' . $y; print "$x, $x, bo-$b\n" . "Banana-fana fo-$f\n" . "Fee-fi-mo-$m\n" . "$x!\n\n"; } printVerse($_) for <Gary Earl Billy Felix Mary Steve>;
122The Name Game
2perl
g284e
null
124Text processing/2
10javascript
2yalr
from collections import defaultdict import urllib.request CH2NUM = {ch: str(num) for num, chars in enumerate('abc def ghi jkl mno pqrs tuv wxyz'.split(), 2) for ch in chars} URL = 'http: def getwords(url): return urllib.request.urlopen(url).read().decode().lower().split() def mapnum2words(words): number2words = defaultdict(list) reject = 0 for word in words: try: number2words[''.join(CH2NUM[ch] for ch in word)].append(word) except KeyError: reject += 1 return dict(number2words), reject def interactiveconversions(): global inp, ch, num while True: inp = input().strip().lower() if inp: if all(ch in '23456789' for ch in inp): if inp in num2words: print(.format(inp, ', '.join( num2words[inp]))) else: print(.format(inp)) elif all(ch in CH2NUM for ch in inp): num = ''.join(CH2NUM[ch] for ch in inp) print(.format( inp, ('' if inp in wordset else ), num, ', '.join(num2words[num]))) else: print(% inp) else: print() break if __name__ == '__main__': words = getwords(URL) print(% (len(words), URL)) wordset = set(words) num2words, reject = mapnum2words(words) morethan1word = sum(1 for w in num2words if len(num2words[w]) > 1) maxwordpernum = max(len(values) for values in num2words.values()) print(.format(len(words) - reject, URL, len(num2words), morethan1word)) print(% maxwordpernum) maxwpn = sorted((key, val) for key, val in num2words.items() if len(val) == maxwordpernum) for num, wrds in maxwpn: print(% (num, ', '.join(wrds))) interactiveconversions()
123Textonyms
3python
7uorm
null
124Text processing/2
11kotlin
f84do
filename = "readings.txt" io.input( filename ) dates = {} duplicated, bad_format = {}, {} num_good_records, lines_total = 0, 0 while true do line = io.read( "*line" ) if line == nil then break end lines_total = lines_total + 1 date = string.match( line, "%d+%-%d+%-%d+" ) if dates[date] ~= nil then duplicated[#duplicated+1] = date end dates[date] = 1 count_pairs, bad_values = 0, false for v, w in string.gmatch( line, "%s(%d+[%.%d+]*)%s(%-?%d)" ) do count_pairs = count_pairs + 1 if tonumber(w) <= 0 then bad_values = true end end if count_pairs ~= 24 then bad_format[#bad_format+1] = date end if not bad_values then num_good_records = num_good_records + 1 end end print( "Lines read:", lines_total ) print( "Valid records: ", num_good_records ) print( "Duplicate dates:" ) for i = 1, #duplicated do print( " ", duplicated[i] ) end print( "Bad format:" ) for i = 1, #bad_format do print( " ", bad_format[i] ) end
124Text processing/2
1lua
togfn
int main () { int i; char *str = getenv (); for (i = 0; str[i + 2] != 00; i++) { if ((str[i] == 'u' && str[i + 1] == 't' && str[i + 2] == 'f') || (str[i] == 'U' && str[i + 1] == 'T' && str[i + 2] == 'F')) { printf (); i = -1; break; } } if (i != -1) printf (); return 0; }
126Terminal control/Unicode output
5c
ns2i6
def print_verse(n): l = ['b', 'f', 'm'] s = n[1:] if str.lower(n[0]) in l: l[l.index(str.lower(n[0]))] = '' elif n[0] in ['A', 'E', 'I', 'O', 'U']: s = str.lower(n) print('{0}, {0}, bo-{2}{1}\nBanana-fana fo-{3}{1}\nFee-fi-mo-{4}{1}\n{0}!\n'.format(n, s, *l)) for n in ['Gary', 'Earl', 'Billy', 'Felix', 'Mary']: print_verse(n)
122The Name Game
3python
rvogq
CHARS = NUMS = * 2 dict = textonyms = File.open(dict){|f| f.map(&:chomp).group_by {|word| word.tr(CHARS, NUMS) } } puts puts 25287876746242,
123Textonyms
14ruby
h4njx
use std::collections::HashMap; use std::fs::File; use std::io::{self, BufRead}; fn text_char(ch: char) -> Option<char> { match ch { 'a' | 'b' | 'c' => Some('2'), 'd' | 'e' | 'f' => Some('3'), 'g' | 'h' | 'i' => Some('4'), 'j' | 'k' | 'l' => Some('5'), 'm' | 'n' | 'o' => Some('6'), 'p' | 'q' | 'r' | 's' => Some('7'), 't' | 'u' | 'v' => Some('8'), 'w' | 'x' | 'y' | 'z' => Some('9'), _ => None, } } fn text_string(s: &str) -> Option<String> { let mut text = String::with_capacity(s.len()); for c in s.chars() { if let Some(t) = text_char(c) { text.push(t); } else { return None; } } Some(text) } fn print_top_words(textonyms: &Vec<(&String, &Vec<String>)>, top: usize) { for (text, words) in textonyms.iter().take(top) { println!("{} = {}", text, words.join(", ")); } } fn find_textonyms(filename: &str) -> std::io::Result<()> { let file = File::open(filename)?; let mut table = HashMap::new(); let mut count = 0; for line in io::BufReader::new(file).lines() { let mut word = line?; word.make_ascii_lowercase(); if let Some(text) = text_string(&word) { let words = table.entry(text).or_insert(Vec::new()); words.push(word); count += 1; } } let mut textonyms: Vec<(&String, &Vec<String>)> = table.iter().filter(|x| x.1.len() > 1).collect(); println!( "There are {} words in '{}' which can be represented by the digit key mapping.", count, filename ); println!( "They require {} digit combinations to represent them.", table.len() ); println!( "{} digit combinations represent Textonyms.", textonyms.len() ); let top = std::cmp::min(5, textonyms.len()); textonyms.sort_by_key(|x| (std::cmp::Reverse(x.1.len()), x.0)); println!("\nTop {} by number of words:", top); print_top_words(&textonyms, top); textonyms.sort_by_key(|x| (std::cmp::Reverse(x.0.len()), x.0)); println!("\nTop {} by length:", top); print_top_words(&textonyms, top); Ok(()) } fn main() { let args: Vec<String> = std::env::args().collect(); if args.len()!= 2 { eprintln!("usage: {} word-list", args[0]); std::process::exit(1); } match find_textonyms(&args[1]) { Ok(()) => {} Err(error) => eprintln!("{}: {}", args[1], error), } }
123Textonyms
15rust
kgdh5
(if-not (empty? (filter #(and (not (nil? %)) (.contains (.toUpperCase %) "UTF")) (map #(System/getenv %) ["LANG" "LC_ALL" "LC_CTYPE"]))) "Unicode is supported on this terminal and U+25B3 is: \u25b3" "Unicode is not supported on this terminal.")
126Terminal control/Unicode output
6clojure
3ngzr
package main import ( "fmt" "os" "strings" ) func main() { lang := strings.ToUpper(os.Getenv("LANG")) if strings.Contains(lang, "UTF") { fmt.Printf("This terminal supports unicode and U+25b3 is:%c\n", '\u25b3') } else { fmt.Println("This terminal does not support unicode") } }
126Terminal control/Unicode output
0go
rvqgm
import Foundation func textCharacter(_ ch: Character) -> Character? { switch (ch) { case "a", "b", "c": return "2" case "d", "e", "f": return "3" case "g", "h", "i": return "4" case "j", "k", "l": return "5" case "m", "n", "o": return "6" case "p", "q", "r", "s": return "7" case "t", "u", "v": return "8" case "w", "x", "y", "z": return "9" default: return nil } } func textString(_ string: String) -> String? { var result = String() result.reserveCapacity(string.count) for ch in string { if let tch = textCharacter(ch) { result.append(tch) } else { return nil } } return result } func compareByWordCount(pair1: (key: String, value: [String]), pair2: (key: String, value: [String])) -> Bool { if pair1.value.count == pair2.value.count { return pair1.key < pair2.key } return pair1.value.count > pair2.value.count } func compareByTextLength(pair1: (key: String, value: [String]), pair2: (key: String, value: [String])) -> Bool { if pair1.key.count == pair2.key.count { return pair1.key < pair2.key } return pair1.key.count > pair2.key.count } func findTextonyms(_ path: String) throws { var dict = Dictionary<String, [String]>() let contents = try String(contentsOfFile: path, encoding: String.Encoding.ascii) var count = 0 for line in contents.components(separatedBy: "\n") { if line.isEmpty { continue } let word = line.lowercased() if let text = textString(word) { dict[text, default: []].append(word) count += 1 } } var textonyms = Array(dict.filter{$0.1.count > 1}) print("There are \(count) words in '\(path)' which can be represented by the digit key mapping.") print("They require \(dict.count) digit combinations to represent them.") print("\(textonyms.count) digit combinations represent Textonyms.") let top = min(5, textonyms.count) print("\nTop \(top) by number of words:") textonyms.sort(by: compareByWordCount) for (text, words) in textonyms.prefix(top) { print("\(text) = \(words.joined(separator: ", "))") } print("\nTop \(top) by length:") textonyms.sort(by: compareByTextLength) for (text, words) in textonyms.prefix(top) { print("\(text) = \(words.joined(separator: ", "))") } } do { try findTextonyms("unixdict.txt") } catch { print(error.localizedDescription) }
123Textonyms
17swift
j5i74
import System.Environment import Data.List import Data.Char import Data.Maybe main = do x <- mapM lookupEnv ["LANG", "LC_ALL", "LC_CTYPE"] if any (isInfixOf "UTF". map toUpper) $ catMaybes x then putStrLn "UTF supported: \x25b3" else putStrLn "UTF not supported"
126Terminal control/Unicode output
8haskell
0ems7
def print_verse(name) first_letter_and_consonants_re = /^.[^aeiyou]*/i full_name = name.capitalize suffixed = case full_name[0] when 'A','E','I','O','U' name.downcase else full_name.sub(first_letter_and_consonants_re, '') end b_name = f_name = m_name = case full_name[0] when 'B' b_name = suffixed when 'F' f_name = suffixed when 'M' m_name = suffixed end puts <<~END_VERSE Banana-fana fo- Fee-fi-mo- END_VERSE end %w[Gary Earl Billy Felix Mary Steve Chris Byron].each do |name| print_verse name end
122The Name Game
14ruby
j5n7x
package main import ( "bufio" "bytes" "fmt" "log" "os" ) const ( filename = "mlijobs.txt" inoutField = 1 timeField = 3 numFields = 7 ) func main() { file, err := os.Open(filename) if err != nil { log.Fatal(err) } defer file.Close() var ml, out int var mlTimes []string in := []byte("IN") s := bufio.NewScanner(file) for s.Scan() { f := bytes.Fields(s.Bytes()) if len(f) != numFields { log.Fatal("unexpected format,", len(f), "fields.") } if bytes.Equal(f[inoutField], in) { out-- if out < 0 { log.Fatalf("negative license use at%s", f[timeField]) } continue } out++ if out < ml { continue } if out > ml { ml = out mlTimes = mlTimes[:0] } mlTimes = append(mlTimes, string(f[timeField])) } if err = s.Err(); err != nil { log.Fatal(err) } fmt.Println("max licenses:", ml) fmt.Println("at:") for _, t := range mlTimes { fmt.Println(" ", t) } }
125Text processing/Max licenses in use
0go
q1yxz
null
126Terminal control/Unicode output
11kotlin
h48j3
object NameGame extends App { private def printVerse(name: String): Unit = { val x = name.toLowerCase.capitalize val y = if ("AEIOU" contains x.head) x.toLowerCase else x.tail val (b, f, m) = x.head match { case 'B' => (y, "f" + y, "m" + y) case 'F' => ("b" + y, y, "m" + y) case 'M' => ("b" + y, "f" + y, y) case _ => ("b" + y, "f" + y, "m" + y) } printf("%s,%s, bo-%s\n", x, x, b) printf("Banana-fana fo-%s\n", f) println(s"Fee-fi-mo-$m") println(s"$x!\n") } Stream("gAry", "earl", "Billy", "Felix", "Mary", "Steve").foreach(printVerse) }
122The Name Game
16scala
p7zbj
def max = 0 def dates = [] def licenses = [:] new File('licenseFile.txt').eachLine { line -> (line =~ /License (\w+)\s+@ ([\d\/_:]+) for job (\d+)/).each { matcher, action, date, job -> switch (action) { case 'IN': assert licenses[job] != null: "License has not been checked out for $job" licenses.remove job break case 'OUT': assert licenses[job] == null: "License has already been checked out for $job" licenses[job] = date def count = licenses.keySet().size() if (count > max) { max = count dates = [ date ] } else if (count == max) { dates << date } break default: throw new IllegalArgumentException("Unsupported license action $action") } } } println "Maximum Licenses $max" dates.each { date -> println " $date" }
125Text processing/Max licenses in use
7groovy
1jfp6
use List::MoreUtils 'natatime'; use constant FIELDS => 49; binmode STDIN, ':crlf'; my ($line, $good_records, %dates) = (0, 0); while (<>) {++$line; my @fs = split /\s+/; @fs == FIELDS or die "$line: Bad number of fields.\n"; for (shift @fs) {/\d{4}-\d{2}-\d{2}/ or die "$line: Bad date format.\n"; ++$dates{$_};} my $iterator = natatime 2, @fs; my $all_flags_okay = 1; while ( my ($val, $flag) = $iterator->() ) {$val =~ /\d+\.\d+/ or die "$line: Bad value format.\n"; $flag =~ /\A-?\d+/ or die "$line: Bad flag format.\n"; $flag < 1 and $all_flags_okay = 0;} $all_flags_okay and ++$good_records;} print "Good records: $good_records\n", "Repeated timestamps:\n", map {" $_\n"} grep {$dates{$_} > 1} sort keys %dates;
124Text processing/2
2perl
h4ijl
import Data.List main = do f <- readFile "./../Puzzels/Rosetta/inout.txt" let (ioo,dt) = unzip. map ((\(_:io:_:t:_)-> (io,t)). words) . lines $ f cio = drop 1 . scanl (\c io -> if io == "IN" then pred c else succ c) 0 $ ioo mo = maximum cio putStrLn $ "Maximum simultaneous license use is " ++ show mo ++ " at:" mapM_ (putStrLn . (dt!!)) . elemIndices mo $ cio
125Text processing/Max licenses in use
8haskell
mthyf
die "Terminal can't handle UTF-8" unless $ENV{LC_ALL} =~ /utf-8/i or $ENV{LC_CTYPE} =~ /utf-8/i or $ENV{LANG} =~ /utf-8/i; print " \n";
126Terminal control/Unicode output
2perl
zi4tb