Sunday 15 July 2012

sorting - Go: Sort array, dropping elements if error caught in `Less(i, j int)` -



sorting - Go: Sort array, dropping elements if error caught in `Less(i, j int)` -

given next struct

type point struct { datetimerecorded time.time } // returns true if point recorded before comparing point. // if datetime not available homecoming false , error func (p1 point) recordedbefore(p2 point) (isbefore bool, err error) { if (p1.datetimerecorded.iszero()) || (p2.datetimerecorded.iszero()) { err = errnodatetime } else { isbefore = p1.datetimerecorded.before(p2.datetimerecorded) } homecoming }

i sort []point datetimerecorded attribute.

i have next (which works):

type bydatetimerecorded []point func (a bydatetimerecorded) len() int { homecoming len(a) } func (a bydatetimerecorded) swap(i, j int) { a[i], a[j] = a[j], a[i] } func (a bydatetimerecorded) less(i, j int) bool { swap, _ := a[i].recordedbefore(a[j]) homecoming swap }

however, if datetimerecorded attribute not initialised in either comparing error caught , points not swapped (returns false).

is possible grab error , drop array? like:

func (a bydatetimerecorded) less(i, j int) bool { swap, err := a[i].recordedbefore(a[j]) if err != nil { // remove element here } homecoming swap }

edit 1

i may have more specific element drop may create more sense:

func (a bydatetimerecorded) less(i, j int) bool { if a[i].datetimerecorded.iszero() { // drop a[i] } if a[j].datetimerecorded.iszero() { // drop a[j] } swap, _ := a[i].recordedbefore(a[j]) homecoming swap }

the standard sort bundle not drop elements slice. filter 0 values out of piece before sorting.

:= 0 _, p := range points { if !p.datetimerecorded.iszero() { points[i] = p i++ } } points = points[:i] sort.sort(bydatetimerecorded(points))

arrays sorting go

No comments:

Post a Comment