Skip to content

Commit

Permalink
Distance Between Bus Stops
Browse files Browse the repository at this point in the history
  • Loading branch information
hikjik committed Oct 19, 2023
1 parent ceffc2c commit 8dbef9c
Show file tree
Hide file tree
Showing 4 changed files with 64 additions and 0 deletions.
1 change: 1 addition & 0 deletions CMakeLists.txt
Original file line number Diff line number Diff line change
Expand Up @@ -192,6 +192,7 @@ add_task(detonate-the-maximum-bombs)
add_task(di-string-match)
add_task(diameter-of-binary-tree)
add_task(difference-between-element-sum-and-digit-sum-of-an-array)
add_task(distance-between-bus-stops)
add_task(distinct-subsequences)
add_task(distribute-candies-to-people)
add_task(distribute-money-to-maximum-children)
Expand Down
1 change: 1 addition & 0 deletions solutions/distance-between-bus-stops/CMakeLists.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
add_catch(test_distance_between_bus_stops test.cpp)
23 changes: 23 additions & 0 deletions solutions/distance-between-bus-stops/solution.hpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
#pragma once

#include <vector>

class Solution {
public:
static int distanceBetweenBusStops(const std::vector<int> &distance,
int start, int destination) {
if (start > destination) {
std::swap(start, destination);
}

int clockwise = 0, counterclockwise = 0;
for (int i = 0; i < std::ssize(distance); ++i) {
if (i >= start && i < destination) {
clockwise += distance[i];
} else {
counterclockwise += distance[i];
}
}
return std::min(clockwise, counterclockwise);
}
};
39 changes: 39 additions & 0 deletions solutions/distance-between-bus-stops/test.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
#include <catch.hpp>

#include <solution.hpp>

TEST_CASE("Simple") {
struct TestCase {
std::vector<int> distance;
int start;
int destination;
int expected;
};

std::vector<TestCase> test_cases{
{
.distance{1, 2, 3, 4},
.start = 0,
.destination = 1,
.expected = 1,
},
{
.distance{1, 2, 3, 4},
.start = 0,
.destination = 2,
.expected = 3,
},
{
.distance{1, 2, 3, 4},
.start = 0,
.destination = 3,
.expected = 4,
},
};

for (const auto &[distance, start, destination, expected] : test_cases) {
const auto actual =
Solution::distanceBetweenBusStops(distance, start, destination);
REQUIRE(expected == actual);
}
}

0 comments on commit 8dbef9c

Please sign in to comment.