Algorithms_in_C++ 1.0.0
Set of algorithms implemented in C++.
Loading...
Searching...
No Matches
jumpgame.cpp File Reference

Implementation of an algorithm to solve the jumping game problem. More...

#include <vector>
#include <iostream>
#include <cassert>
Include dependency graph for jumpgame.cpp:

Functions

bool canJump (const std::vector< int > &nums)
 This function implements the above algorithm.
 
static void test ()
 Function to test above algorithm.
 
int main ()
 Main function.
 

Detailed Description

Implementation of an algorithm to solve the jumping game problem.

Problem statement: Given an array of non-negative integers, you are initially positioned at the first index of the array. Each element in the array represents your maximum jump length at that position. Determine if you are able to reach the last index. This solution takes in input as a vector and output as a boolean to check if you can reach the last position. We name the indices good and bad based on whether we can reach the destination if we start at that position. We initialize the last index as lastPos. Here, we start from the end of the array and check if we can ever reach the first index. We check if the sum of the index and the maximum jump count given is greater than or equal to the lastPos. If yes, then that is the last position you can reach starting from the back. After the end of the loop, if we reach the lastPos as 0, then the destination can be reached from the start position.

Author
Rakshaa Viswanathan

Function Documentation

◆ canJump()

bool canJump ( const std::vector< int > & nums)

This function implements the above algorithm.

Parameters
arrayof numbers containing the maximum jump (in steps) from that index
Returns
bool value whether final index can be reached or not
26 {
27 auto lastPos = nums.size() - 1;
28 for (auto i = nums.size() - 1; i >= 0; i--) {
29 if (i + nums[i] >= lastPos) {
30 lastPos = i;
31 }
32 }
33 return lastPos == 0;
34}
T size(T... args)
Here is the call graph for this function:

◆ main()

int main ( void )

Main function.

Returns
0 on exit
65 {
66 test();
67 return 0;
68}
static void test()
Function to test above algorithm.
Definition jumpgame.cpp:41
Here is the call graph for this function:

◆ test()

static void test ( )
static

Function to test above algorithm.

Returns
void
41 {
42 // Test 1
43 std::vector<int> num1={4,3,1,0,5};
44 assert(canJump(num1)==true);
45 std::cout<<"Input: ";
46 for(auto i: num1){
47 std::cout<<i<<" ";
48 }
49 std::cout<<"Output: true"<<std::endl;
50 // Test 2
51 std::vector<int> num2={3,2,1,0,4};
52 assert(canJump(num2)==false);
53 std::cout<<"Input: ";
54 for(auto i: num2){
55 std::cout<<i<<" ";
56 }
57 std::cout<<"Output: false"<<std::endl;
58}
T endl(T... args)
bool canJump(const std::vector< int > &nums)
This function implements the above algorithm.
Definition jumpgame.cpp:26
Here is the call graph for this function: