Last active
December 30, 2015 21:39
-
-
Save joshy/7888600 to your computer and use it in GitHub Desktop.
santa.dart
A try to learn dart, solution to the "santa problem" https://plus.google.com/118397406534237711570/posts/XjgFRvqtVA4
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
import 'dart:io'; | |
import 'dart:async'; | |
import 'dart:convert'; | |
import 'dart:collection'; | |
void main() { | |
print("Please, enter 'first name' and 'last name' finish with a empty line\n"); | |
Stream cmdLine = stdin | |
.transform(UTF8.decoder) | |
.transform(new LineSplitter()); | |
List<Person> persons = []; | |
List<SantaPair> santaPairs = []; | |
cmdLine.listen((data) { | |
switch(data) { | |
case '': | |
createSantaPairs(persons, santaPairs); | |
print(santaPairs); | |
exit(1); | |
break; | |
default: | |
addPerson(persons, data); | |
} | |
}); | |
} | |
createSantaPairs(List<Person> persons, List<SantaPair> santaPairs) { | |
persons.sort((e1, e2) => e1.lastName.compareTo(e2.lastName)); | |
Queue q = new Queue.from(persons); | |
while (q.isNotEmpty && q.length >= 2) { | |
var first = q.removeFirst(); | |
var last = q.removeLast(); | |
if (first.lastName == last.lastName) { | |
print("No combination possible"); | |
exit(0); | |
} | |
santaPairs.add(new SantaPair(first, last)); | |
} | |
} | |
addPerson(List<Person> persons, String data) { | |
var fullName = data.split(' '); | |
persons.add(new Person(fullName[0], fullName[1])); | |
} | |
class SantaPair { | |
var person1; | |
var person2; | |
SantaPair(this.person1, this.person2); | |
toString() => "(${person1}, ${person2})"; | |
} | |
class Person { | |
var firstName; | |
var lastName; | |
Person(this.firstName, this.lastName); | |
toString() => "${firstName} ${lastName}"; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment