Advertisement
Guest User

Untitled

a guest
Jan 6th, 2015
260
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.35 KB | None | 0 0
  1. function solve(input){
  2.  
  3. var soccerTeams = {};
  4. var pattern = /([A-Za-z ]+)\s*\/\s*([A-Za-z ]+)\s*:\s*([0-9]+)\s*-\s*([0-9]+)/;
  5.  
  6. for(var i = 0; i < input.length; i++) {
  7. var currentLine = pattern.exec(input[i]);
  8.  
  9. var curHomeTeam = currentLine[1].trim();
  10. var curOpponent = currentLine[2].trim();
  11. var curHomeResult = Number(currentLine[3]);
  12. var curOpponentResult = Number(currentLine[4]);
  13.  
  14. if(!soccerTeams[curHomeTeam]){
  15. soccerTeams[curHomeTeam] = {
  16. 'goalsScored': curHomeResult,
  17. 'goalsConceded': curOpponentResult,
  18. 'matchesPlayedWith': []
  19. };
  20. } else{
  21. soccerTeams[curHomeTeam].goalsScored += curHomeResult;
  22. soccerTeams[curHomeTeam].goalsConceded += curOpponentResult;
  23. }
  24. if(!soccerTeams[curOpponent]){
  25. soccerTeams[curOpponent] = {
  26. 'goalsScored': curOpponentResult,
  27. 'goalsConceded': curHomeResult,
  28. 'matchesPlayedWith': []
  29. };
  30. } else {
  31. soccerTeams[curOpponent].goalsScored += curOpponentResult;
  32. soccerTeams[curOpponent].goalsConceded += curHomeResult;
  33. }
  34.  
  35. if(soccerTeams[curHomeTeam].matchesPlayedWith.indexOf(curOpponent) < 0){
  36. soccerTeams[curHomeTeam].matchesPlayedWith.push(curOpponent);
  37. }
  38.  
  39. if(soccerTeams[curOpponent].matchesPlayedWith.indexOf(curHomeTeam) < 0){
  40. soccerTeams[curOpponent].matchesPlayedWith.push(curHomeTeam);
  41. }
  42.  
  43. }
  44.  
  45.  
  46. soccerTeams = sortObjectProperties(soccerTeams);
  47.  
  48. for(var team in soccerTeams){
  49. soccerTeams[team].matchesPlayedWith.sort();
  50.  
  51. }
  52.  
  53. console.log(JSON.stringify(soccerTeams));
  54.  
  55. function sortObjectProperties(obj) {
  56. var keysSorted = Object.keys(obj).sort();
  57. var sortedObj = {};
  58. for (var i = 0; i < keysSorted.length; i++) {
  59. var key = keysSorted[i];
  60. sortedObj[key] = obj[key];
  61. }
  62. return sortedObj;
  63. }
  64.  
  65. }
  66.  
  67. solve(['Germany / Argentina: 1-0',
  68. 'Brazil / Netherlands: 0-3',
  69. 'Netherlands / Argentina: 0-0',
  70. 'Brazil / Germany: 1-7',
  71. 'Argentina / Belgium: 1-0',
  72. 'Netherlands / Costa Rica: 0-0',
  73. 'France / Germany: 0-1',
  74. 'Brazil / Colombia: 2-1'
  75. ]);
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement