mihalkoff

Ladybugs

Feb 13th, 2021
72
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.51 KB | None | 0 0
  1. function ladybugs(input) {
  2. let fieldSize = Number(input[0]);
  3. let ladybugsPositions = input[1].split(' ');
  4. let initialField = [];
  5.  
  6. //initial field array
  7. for(let i = 0; i < fieldSize; i++) {
  8. initialField[i] = 0;
  9. }
  10.  
  11. for(let i = 0; i < ladybugsPositions.length; i++) {
  12. let ladybugIndex = Number(ladybugsPositions[i]);
  13.  
  14. for(let j = 0; j < fieldSize; j++) {
  15. if(j == ladybugIndex) {
  16. initialField[j] = 1;
  17. }
  18. }
  19. }
  20.  
  21. //commands
  22. for(let i = 2; i < input.length; i++) {
  23. let command = input[i].split(' ');
  24. let ladybug = Number(command[0]);
  25. let direction = command[1];
  26. let path = Number(command[2]);
  27.  
  28. if(initialField[ladybug] == 1) {
  29. initialField[ladybug] = 0;
  30. let destination = 0;
  31.  
  32. if(direction == 'right') {
  33. destination = ladybug + path;
  34.  
  35. while(initialField[destination] == 1) {
  36. destination += path;
  37. }
  38. } else if(direction == 'left') {
  39. destination = ladybug - path;
  40.  
  41. while(initialField[destination] == 1) {
  42. destination -= path;
  43. }
  44. }
  45.  
  46. if(initialField[destination] == 0) {
  47. initialField[destination] = 1;
  48. }
  49. }
  50. }
  51.  
  52. console.log(initialField.join(' '));
  53. }
  54.  
  55. ladybugs([ 5, '3',
  56. '3 left 2',
  57. '1 left -2']
  58. );
Advertisement
Add Comment
Please, Sign In to add comment