Created
March 7, 2009 19:57
-
-
Save chanwit/75419 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// | |
// ใช้ TreeMap เพื่อให้ key เรียงกันอัตโนมัติ | |
// | |
def result=new TreeMap() | |
// | |
// File.eachLine เป็น method ใน GDK, อ่านข้อมูลจากไฟล์เข้ามาทีละบรรทัด | |
// แล้ว bind ให้ it | |
// | |
new File("input.txt").eachLine { | |
// | |
// split แยก string ด้วย regular expression | |
// จึงต้องใช้ \| แต่ต้องเขียนเป็น \\| เพราะต้อง escape \ อีกทีนึง | |
// | |
// def l = it.split("\\|") | |
// updated: แก้เป็นใช้ tokenize แืทนจะได้น่าเกลียดน้อยลง | |
def l = it.tokenize('|') | |
// 1. | |
// split แล้วได้ array ของ String | |
// l[0] เป็น key | |
// l[1..ตัวสุดท้าย] เป็น data, range ใน Groovy ใช้ -1 แทนตัวสุดท้าย, -2 แทนตัวถัดเข้ามา | |
// ความหมายคือ l[1..(l.size()-1)] | |
// | |
// 2. | |
// เรียกใช้ sort เพื่อเรียง data | |
// แล้วผลจากการ sort เก็บเข้า TreeMap ตาม key | |
// | |
// โครงสร้างตอนนี้คือ result เป็น map เก็บ key เป็น String และ value เป็น list ของ String | |
// | |
// updated: แก้บั๊ก เพิ่ม as int เพื่อ convert String เป็น Integer จะได้ sort ถูกต้อง | |
result[l[0] as int] = l[1..-1].sort() | |
} | |
// | |
// ถ้าใช้ each บน map จะเป็นการวนรอบ บนแต่ละคู่ของ key กับ value | |
// ซึ่งแทนด้วย k และ v | |
// เนื่องจาก value (v) เป็น list จึ่งใช้ each วนรอบบนมันได้ | |
result.each { k, v -> | |
print "${k}"; v.each{ print " ${it}" } | |
println() | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment