|
|
Topic: ruby code that will sort your pgn by occurences of first move
| |
|
Author
| Message |
|
I need to pick up Ruby for my new job. So this morning I wrote the following program to begin to familiarize my self with Ruby syntax. It will index your games from a PGN file by opening move.
games = [] file = File.new("jemptymethod.pgn", "r")
is_header = false is_score = false
Game = Struct::new(:header, :score)
while (line = file.gets) if !line.chomp.empty? if !is_score && !is_header game = Game::new('','') end if /^\[/.match(line) is_header = true game.header << line else is_score = true game.score << line end else if is_score is_score = false is_header = false games << game end end end
file.close puts "# Games: " + games.length.to_s moves_index = {} first_moves = {}
games.each { |gm| #the following output should essentially be lossless #with the possible exception of beginning or ending newlines # #puts gm.header + "\n" #puts gm.score + "\n" score_tokens = gm.score.split(/\s+/); game_moves = [] score_tokens.each_index{|i| if i%3 != 0 move_token = score_tokens if !moves_index.has_key?(move_token) moves_index[move_token] = moves_index.keys.length end game_moves << moves_index[move_token] end } first_move = moves_index.index(game_moves[0]) if !first_moves.has_key?(first_move) first_moves[first_move] = 1 else first_moves[first_move] = 1 + first_moves[first_move] end }
# sorting hashes by value: http://nhw.pl/wp/2007/06/11/sorting-hash-by-values first_moves.sort{|a,b| -1*(a[1]<=>b[1])}.each{|k,v| puts "1. #{k} occurred #{v} times" }
|
|
|
|
|