Created
April 16, 2012 06:46
-
-
Save minikomi/2396778 to your computer and use it in GitHub Desktop.
Sorting triangles with an interface in go
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
package main | |
import ( | |
"fmt" | |
"sort" | |
) | |
type Triangle struct { | |
h int | |
w int | |
} | |
type Triangles []Triangle | |
func (t *Triangle) Area() (a int) { | |
a = (t.h * t.w) / 2 | |
return | |
} | |
func (t Triangles) Less(i, j int) bool { | |
if t[i].Area() < t[j].Area() { | |
return true | |
} | |
return false | |
} | |
func (g Triangles) Swap(i, j int) { | |
g[i], g[j] = g[j], g[i] | |
} | |
func (t Triangles) Len() int { | |
return len(t) | |
} | |
func main() { | |
tg := Triangles{ | |
Triangle{2, 3}, | |
Triangle{2, 8}, | |
Triangle{3, 9}, | |
Triangle{3, 8}, | |
Triangle{3, 18}, | |
Triangle{9, 1}, | |
Triangle{3, 8}, | |
} | |
sort.Sort(tg) | |
for _, t := range tg { | |
fmt.Println(t) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment