Advertisement
dimipan80

Bigger Than Neighbors

Nov 15th, 2014
204
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. /* Write a JavaScript function biggerThanNeighbors(index,  arr) that accept a number and an integer array
  2. as parameters. The function should return a Boolean number: whether the element at the given position
  3. in the array is bigger than its two neighbors (when such exist). It should return undefined when
  4. the index doesn't exist. Write a JS program that invokes the function with the sample data below
  5. and prints the result at the console. */
  6.  
  7. "use strict";
  8.  
  9. function biggerThanNeighbors(index,  arr) {
  10.     if (index != Number(index) || index % 1 != 0 || index < 0 || index >= arr.length) {
  11.         return undefined + ' - invalid index!';
  12.     }
  13.  
  14.     for (var i = 0; i < arr.length; i += 1) {
  15.         if (arr[i] != Number(parseInt(arr[i])) || arr[i] % 1 !== 0) {
  16.             return undefined + ' - invalid element!';
  17.         }
  18.     }
  19.  
  20.     if (!index || index == arr.length - 1) {
  21.         return 'only one neighbor';
  22.     }
  23.  
  24.     if (arr[index] > arr[index - 1] && arr[index] > arr[index + 1]) {
  25.         return 'bigger';
  26.     } else {
  27.         return 'not bigger';
  28.     }
  29. }
  30.  
  31. console.log(biggerThanNeighbors(2, [1, 2, 3, 3, 5]));
  32. console.log(biggerThanNeighbors(2, [1, 2, 5, 3, 4]));
  33. console.log(biggerThanNeighbors(5, [1, 2, 5, 3, 4]));
  34. console.log(biggerThanNeighbors(0, [1, 2, 5, 3, 4]));
  35. console.log(biggerThanNeighbors(4, [3, 4, 5, 6, 7]));
  36. console.log(biggerThanNeighbors(2, [4, 5.4, 6, 1, 2]));
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement