Tuesday, 24 May 2022

Jumping on the Clouds problem and solution in c++

 There is a new mobile game that starts with consecutively numbered clouds. Some of the clouds are thunderheads and others are cumulus. The player can jump on any cumulus cloud having a number that is equal to the number of the current cloud plus  or . The player must avoid the thunderheads. Determine the minimum number of jumps it will take to jump from the starting postion to the last cloud. It is always possible to win the game.

For each game, you will get an array of clouds numbered  if they are safe or  if they must be avoided.

Example

Index the array from . The number on each cloud is its index in the list so the player must avoid the clouds at indices  and . They could follow these two paths:  or . The first path takes  jumps while the second takes . Return .

Function Description

Complete the jumpingOnClouds function in the editor below.

jumpingOnClouds has the following parameter(s):

  • int c[n]: an array of binary integers

Returns

  • int: the minimum number of jumps required

Input Format

The first line contains an integer , the total number of clouds. The second line contains  space-separated binary integers describing clouds  where .

Constraints

Output Format

Print the minimum number of jumps needed to win the game.

Sample Input 0

7
0 0 1 0 0 1 0

Sample Output 0

4

Explanation 0:
The player must avoid  and . The game can be won with a minimum of  jumps:

Sample Input 1

6
0 0 0 0 1 0

Sample Output 1

3

Explanation 1:
The only thundercloud to avoid is . The game can be won in  jumps:


Solution:


#include <bits/stdc++.h>


using namespace std;


string ltrim(const string &);

string rtrim(const string &);

vector<string> split(const string &);


/*

 * Complete the 'jumpingOnClouds' function below.

 *

 * The function is expected to return an INTEGER.

 * The function accepts INTEGER_ARRAY c as parameter.

 */


int jumpingOnClouds(vector<int> c) {

  //Conditions

  if((c.size()<2)||(c.size()>100))

   return 0;

   

  

  int len = c.size();

  if((c[0]!=0)&&(c[len-1]!=0))

  return 0;

  

  int jumps=0;

  for(int i=0;i<len-1;){

      if(((c[i]==0)&&(c[i+1]==1))||

      ((c[i]==0)&&(c[i+1]==0)&&(c[i+2]==0))){

        jumps++;

        i=i+2;

      }

      else{

            jumps++;

              i=i+1;

          }

  }

 return jumps;

}


int main()

{

    ofstream fout(getenv("OUTPUT_PATH"));


    string n_temp;

    getline(cin, n_temp);


    int n = stoi(ltrim(rtrim(n_temp)));


    string c_temp_temp;

    getline(cin, c_temp_temp);


    vector<string> c_temp = split(rtrim(c_temp_temp));


    vector<int> c(n);


    for (int i = 0; i < n; i++) {

        int c_item = stoi(c_temp[i]);


        c[i] = c_item;

    }


    int result = jumpingOnClouds(c);


    fout << result << "\n";


    fout.close();


    return 0;

}


string ltrim(const string &str) {

    string s(str);


    s.erase(

        s.begin(),

        find_if(s.begin(), s.end(), not1(ptr_fun<int, int>(isspace)))

    );


    return s;

}


string rtrim(const string &str) {

    string s(str);


    s.erase(

        find_if(s.rbegin(), s.rend(), not1(ptr_fun<int, int>(isspace))).base(),

        s.end()

    );


    return s;

}


vector<string> split(const string &str) {

    vector<string> tokens;


    string::size_type start = 0;

    string::size_type end = 0;


    while ((end = str.find(" ", start)) != string::npos) {

        tokens.push_back(str.substr(start, end - start));


        start = end + 1;

    }


    tokens.push_back(str.substr(start));


    return tokens;

}


Diagonal Sum difference in matrice solved using PHP

 Find the difference of diagonal sum in matrice i.e., 

[1 2 3]

[4 5 6]

[7 8 9]


First diagonal is [1 5 9] and second diagonal is [3 5 7] i.e., 1st diagonal sum is 1+5+9 =15 and second diagonal sum is 3+5+7 = 15 so, difference is 0. If it is negative number it should be converted to positive.


<?php


/*

 * Complete the 'diagonalDifference' function below.

 *

 * The function is expected to return an INTEGER.

 * The function accepts 2D_INTEGER_ARRAY arr as parameter.

 */


function diagonalDifference($arr) {

    // Write your code here

    $n=count($arr);

    

    $firstD =0;

    $secondD=0;

    

    for($i=0;$i<$n;$i++){

        $firstD+=$arr[$i][$i];

        $secondD+=$arr[$n-$i-1][$i];

    }

    

    return abs($firstD - $secondD);


}


$fptr = fopen(getenv("OUTPUT_PATH"), "w");


$n = intval(trim(fgets(STDIN)));


$arr = array();


for ($i = 0; $i < $n; $i++) {

    $arr_temp = rtrim(fgets(STDIN));


    $arr[] = array_map('intval', preg_split('/ /', $arr_temp, -1, PREG_SPLIT_NO_EMPTY));

}


$result = diagonalDifference($arr);


fwrite($fptr, $result . "\n");


fclose($fptr);


Counting Valleys Problem and solution in python

 Counting Valleys Problem: 

Gary is an avid hiker. He tracks his hikes meticulously, paying close attention to small details like topography. During his last hike he took exactly steps. For every step he took, he noted if it was an uphill, , or a downhill, step. Gary's hikes start and end at sea level and each step up or down represents a unit change in altitude. We define the following terms: A mountain is a sequence of consecutive steps above sea level, starting with a step up from sea level and ending with a step down to sea level. A valley is a sequence of consecutive steps below sea level, starting with a step down from sea level and ending with a step up to sea level. Given Gary's sequence of up and down steps during his last hike, find and print the number of valleys he walked through. For example, if Gary's path is , he first enters a valley units deep. Then he climbs out an up onto a mountain units high. Finally, he returns to sea level and ends his hike.

Function Description Complete the countingValleys function in the editor below. It must return an integer that denotes the number of valleys Gary traversed.


Solution in Python:


#!/bin/python

import math
import os
import random
import re
import sys

#
# Complete the 'countingValleys' function below.
#
# The function is expected to return an INTEGER.
# The function accepts following parameters:
#  1. INTEGER steps
#  2. STRING path
#

def returnCode(step):
        if step=='U':
            return 1;
        return -1;

def countingValleys(steps, path):
    # Write your code here
     
    level=valley=0
    for element in path:
        code = returnCode(element)
        if level0 and level+code == 0:
            valley=valley+1
        level = level+code
    return valley

if __name__ == '__main__':
    fptr = open(os.environ['OUTPUT_PATH'], 'w')

    steps = int(raw_input().strip())

    path = raw_input()

    result = countingValleys(steps, path)

    fptr.write(str(result) + '\n')

    fptr.close()


In C++ the solution is:

#include <cmath>
#include <cstdio>
#include <vector>
#include <iostream>
#include <algorithm>
using namespace std;


int main() {
    int l;
    string str; 
    cin>>l>>str;
    int height = 0;
    int count = 0;
    for(int i=0;i<l;i++){
        if (str[i]=='U') height++;
        else {
            if (height==0) count++;
            height--;
        }
    }
    if (height<0) 
      count--;
    cout<<count<<endl;
       
    return 0;
}

Example

 

The hiker first enters a valley  units deep. Then they climb out and up onto a mountain  units high. Finally, the hiker returns to sea level and ends the hike.

Function Description

Complete the countingValleys function in the editor below.

countingValleys has the following parameter(s):

  • int steps: the number of steps on the hike
  • string path: a string describing the path

Returns

  • int: the number of valleys traversed

Input Format

The first line contains an integer , the number of steps in the hike.
The second line contains a single string , of  characters that describe the path.

Constraints

Sample Input

8
UDDDUDUU

Sample Output

1

Explanation

If we represent _ as sea level, a step up as /, and a step down as \, the hike can be drawn as:

_/\      _
   \    /
    \/\/

The hiker enters and leaves one valley.