You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
// For this challenge you will search in an array for an enemy.
2
+
/*
3
+
have the function ClosestEnemy(arr) take the array of numbers stored in arr and from the position in the array where a 1 is, return the number of spaces either left or right you must move to reach an enemy which is represented by a 2. For example: if arr is [0, 0, 1, 0, 0, 2, 0, 2] then your program should return 3 because the closest enemy (2) is 3 spaces away from the 1. The array will contain any number of 0's and 2's, but only a single 1. It may not contain any 2's at all as well, where in that case your program should return a 0.
4
+
*/
5
+
6
+
#include<iostream>
7
+
#include<algorithm>
8
+
usingnamespacestd;
9
+
10
+
11
+
/*
12
+
Locate the one index
13
+
iterate to the left and search for any enemies
14
+
If found keep track of its distance
15
+
iterate to the right and search for any enemies and keep distance
16
+
report the closest enemy
17
+
if none found return 0
18
+
*/
19
+
20
+
intClosestEnemy(int arr[], int size)
21
+
{
22
+
int enemy = size * 100;
23
+
24
+
// Locate the index of our position
25
+
int start = distance(arr,find(arr, size+arr, 1));
26
+
27
+
// Locating the enemy to the left
28
+
// We increment the length to use as a boundary check
29
+
// If is equal to that boundary check length than we know the value was not found
30
+
int left = distance(arr, find(arr, (start + arr)+1, 2));
31
+
32
+
// Loop condition in the case we have multiples enemies before the start location
33
+
// We have to increase our index from the start each time to ensure we reach the closest enemy
0 commit comments