Skip to content

Latest commit

 

History

History
93 lines (65 loc) · 2.32 KB

24_exercises.md

File metadata and controls

93 lines (65 loc) · 2.32 KB

< Back

24. Lambdas and Function Templates

Exercise 240

Use Algorithms for PacManAI::optimalDirection

Rewrite optimalDirection in PacManAI.cpp to use algorithms.

Direction PacManAI::optimalDirection(const std::array<Move, 4> & moves) {
  return Direction::NONE;
}
Hint 1

You can use std::min_element to find the closest pellet

Solution
Direction PacManAI::optimalDirection(const std::array<Move, 4> & moves) {
  const auto optimalMove = std::min_element(moves.begin(), moves.end(), [](const auto & a, const auto & b) {
    return a.distanceToTarget < b.distanceToTarget;
  });

  return optimalMove->direction;
}

Exercise 241

Use Lambdas and Algorithms for PacManAI::pelletClosestToPacman

Rewrite pelletClosestToPacman in PacManAI.cpp using lambdas and algorithms. One implementation could be to sort the vector of pellets by the distance they have to PacMan, and then return the first one.

GridPosition PacManAI::pelletClosestToPacman(GridPosition pacmanGridPosition,
                                             std::vector<GridPosition> & pellets) {
  return {0, 0};
}
Hint 1

Use the std::sort function to sort the vector.

Hint 2

std::sort third parameter should be a lambda taking 2 GridPosition as parameter, and return true if the first parameter is closer from PacMan than the second.

Solution
GridPosition PacManAI::pelletClosestToPacman(GridPosition pacmanGridPosition,
                                             std::vector<GridPosition> & pellets) {
  auto pelletSort = [&pacmanGridPosition](GridPosition pelletA, GridPosition pelletB) {
    double distanceA = positionDistance(pacmanGridPosition, pelletA);
    double distanceB = positionDistance(pacmanGridPosition, pelletB);
    return distanceA < distanceB;
  };
  std::sort(pellets.begin(), pellets.end(), pelletSort);

  return pellets[0];
}