Skip to content

Instantly share code, notes, and snippets.

@davengeo
Last active February 25, 2017 16:26
Show Gist options
  • Save davengeo/91ab535df00bed0bc390148c15f1ea3a to your computer and use it in GitHub Desktop.
Save davengeo/91ab535df00bed0bc390148c15f1ea3a to your computer and use it in GitHub Desktop.
Small sorting kata with Deniss Borisov
package main
import (
"fmt"
"strconv"
"reflect"
)
/* TODO:
1. Fill the array from lines in a file
2. Try to define the big O of the current algorithm using different files
3. Beat the bubble-sort with a better performing algorithm
4. Unit-test the implementation
*/
type Whatever struct {
value interface{}
}
func newWhatever(value interface{}) Whatever {
whatever := new(Whatever)
whatever.value = value
return *whatever
}
func (first Whatever) compare (second Whatever) int {
firstValue:= coerce2String(first)
secondValue:= coerce2String(second)
if (firstValue > secondValue) {
return 1
} else if (firstValue < secondValue){
return -1
} else {
return 0
}
}
func coerce2String(v Whatever) string {
if (reflect.TypeOf(v.value).Name() == "int") {
return strconv.Itoa(v.value.(int))
} else {
return v.value.(string)
}
}
func addToArray(pos int, value Whatever, arr []Whatever) {
arr[pos] = value
}
func sortFinally(arr []Whatever) ([]Whatever, int) {
var result = make([]Whatever, len(arr))
copy(result[:], arr)
needsMoreIter := true
numberOfIter := 0
for needsMoreIter {
numberOfIter++;
needsMoreIter = false
for i := 0; i < (len(result) - 1); i++ {
if (result[i].compare(result[i+1]) == 1) {
needsMoreIter = true
temp := result[i+1]
result[i+1] = result[i]
result[i]= temp
}
}
}
return result, numberOfIter
}
func main() {
var theArray [6]Whatever
addToArray(0, newWhatever(3), theArray[:])
addToArray(1, newWhatever(2), theArray[:])
addToArray(2, newWhatever("b"), theArray[:])
addToArray(3, newWhatever(0), theArray[:])
addToArray(4, newWhatever("a"), theArray[:])
addToArray(5, newWhatever("a23"), theArray[:])
resultArray, numberOfIter := sortFinally(theArray[:])
printArray(resultArray)
fmt.Println(numberOfIter)
}
func printArray(arr []Whatever) {
for i := 0; i < len(arr); i++ {
fmt.Println(arr[i].value)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment