Skip to content

Instantly share code, notes, and snippets.

@nin-jin
Last active October 9, 2015 14:59
Show Gist options
  • Save nin-jin/5f6969cb9063b1977769 to your computer and use it in GitHub Desktop.
Save nin-jin/5f6969cb9063b1977769 to your computer and use it in GitHub Desktop.
Sorting comparison
import vibe.core.core;
import core.time;
import std.stdio;
int counter;
void say( string name ) {
for ( int i = 0 ; i < 3; i++ ) {
sleep( 100.msecs );
writeln( ++counter , " " , name );
}
}
shared static this() {
runWorkerTask({ say( "fiber" ); }); // syntax can be better: go!say( "fiber" );
say( "main" );
}
// 1 main
// 1 fiber
// 2 main
// 2 fiber
// 3 main
// 3 fiber
package main
import (
"fmt"
"time"
)
var counter = 0
func say( name string ) {
for i := 0 ; i < 3 ; i++ {
time.Sleep( 100 * time.Millisecond )
counter += 1
fmt.Println( counter , " " , name )
}
}
func main() {
go say( "fiber" )
say( "main" )
}
// 1 fiber
// 2 main
// 3 main
// 4 fiber
// 5 fiber
// 6 main
unittest {
import std.algorithm;
struct Person {
string Name;
int Age;
}
auto people = [
Person( "Bob" , 31 ),
Person( "John" , 42 ),
Person( "Michael" , 17 ),
Person( "Jenny" , 26 )
];
people.sort!q{ a.Age < b.Age };
assert( people[0].Name == "Michael" );
assert( people[3].Name == "John" );
people.sort!q{ a.Name < b.Name };
assert( people[0].Name == "Bob" );
assert( people[3].Name == "Michael" );
}
package main
import (
"fmt"
"sort"
)
type Person struct {
Name string
Age int
}
var people = []Person{
Person{"Bob", 31},
Person{"John", 42},
Person{"Michael", 17},
Person{"Jenny", 26},
}
func main() {
sort.Sort(ByAge(people))
fmt.Println(people[0].Name == "Michael")
fmt.Println(people[3].Name == "John")
sort.Sort(ByName(people))
fmt.Println(people[0].Name == "Bob")
fmt.Println(people[3].Name == "Michael")
}
type ByAge []Person
func (b ByAge) Len() int {return len(b)}
func (b ByAge) Swap(i, j int) { b[i], b[j] = b[j], b[i] }
func (b ByAge) Less(i, j int) bool { return b[i].Age < b[j].Age }
type ByName []Person
func (b ByName) Len() int {return len(b)}
func (b ByName) Swap(i, j int) { b[i], b[j] = b[j], b[i] }
func (b ByName) Less(i, j int) bool { return b[i].Name < b[j].Name }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment