showing results for - "counting valleys hackerrank solution javascript"
Ivan
21 Oct 2016
1'use strict';
2 
3const processData = input => {
4    const lines = input.split('\n');
5    const steps = lines[1];
6    let valleys = 0;
7    let seaLevel = 0;
8 
9    for(let i = 0; i < steps.length; i++) {
10        let c = steps.charAt(i);
11        if(c == 'D') {
12            seaLevel -= 1;
13        } else {
14            seaLevel += 1;
15        }
16        if(seaLevel == 0 && c == 'U') {
17            valleys += 1;
18        }
19    }
20    console.log(valleys);
21 
22};
23 
24process.stdin.resume();
25process.stdin.setEncoding("ascii");
26 
27let _input = "";
28process.stdin.on("data", input => _input += input);
29process.stdin.on("end", () => processData(_input));
30
Pietro
05 Nov 2016
1function countingValleys(n, s) {     
2  const min = 2;     
3  const max = 1000000;     
4  let isInValley = false;     
5  let valleys = 0;     
6  s = (typeof s === "string") ? s.split('') : s; 
7  
8  if (s.length >= min          
9      && s.length <= max          
10      && n === parseInt(n, 0)          
11      && n >= min          
12      && n <= max           
13      && n === s.length) {                    
14    
15    s.map(steps => ((steps === "U") ? 1 : -1))               
16      .reduce((prev, next) => {                    
17      if (prev < 0 && !isInValley) {                         
18        isInValley = true;                    
19      }                    
20      if ((prev + next) === 0 && isInValley) {                         
21        valleys++;                         
22        isInValley = false;                    
23      }            
24      
25      return prev + next;                   
26    });     
27  }    
28  
29  return valleys; 
30}