cherokee

Odd-Even-Sequence

Jul 26th, 2014
239
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. function solve(args) {
  2.     var input,
  3.         maxOddEven = 0,
  4.         len,
  5.         index,
  6.         count,
  7.         expected;
  8.  
  9.  
  10.     input = args[0].split(/[\(\)\s]+/g).filter(function (a) {
  11.         return !(a == "")
  12.     });
  13.  
  14.     len = input.length;
  15.     if (len === 1) {
  16.         return '1';
  17.     }
  18.  
  19.     input.forEach(function (el, indx, arr) {
  20.         if (+el !== 0) {
  21.             arr[indx] = (+el % 2 !== 0);
  22.         }
  23.     });
  24.  
  25.     count = 1;
  26.     expected = input[0] !== '0' ? !input[0] : '0';
  27.  
  28.     for (index = 1; index < len; index += 1) {
  29.         if (expected === '0' && input[index] !== '0') {
  30.             expected = input[index];
  31.         }
  32.  
  33.  
  34.         if (input[index] === expected || input[index] === '0') {
  35.             count += 1;
  36.             if (expected !== '0') {
  37.                 expected = !expected;
  38.             }
  39.         } else {
  40.             if (count > maxOddEven) {
  41.                 maxOddEven = count;
  42.  
  43.             }
  44.  
  45.             // hack to solve problem when last number in a sequence is '0'
  46.             // it is hack as we modify the index of for-loop, which is not good
  47.             if(index > 0 && input[index-1] === '0'){
  48.                 expected = '0';
  49.                 index -= 1;
  50.             } else {
  51.                 expected = !input[index];
  52.             }
  53.  
  54.             count = 1;
  55.         }
  56.     }
  57.  
  58.     if (count > maxOddEven) {
  59.         maxOddEven = count;
  60.     }
  61.  
  62.     return maxOddEven + "";
  63. }
  64. //
  65. console.log(solve(['(3) (22) (-18) (55) (44) (3) (21)']));
  66. console.log(solve(['(1)(2)(3)(4)(5)(6)(7)(8)(9)(10)']));
  67. console.log(solve(['  ( 2 )  ( 33 ) (1) (4)   (  -1  ) ']));
  68. console.log(solve(['(102)(103)(0)(105)  (107)(1)']));
  69. console.log(solve(['(2) (2) (2) (2) (2)']));
  70. console.log(solve(['(0) (0) (0) (0) (0)']));
  71. console.log(solve(['(0) (0) (5) (0) (0) (5)']));
  72.  
  73. // problem with the last number in a sequence to be '0'
  74. console.log(solve(['(102)(103)(0)(106)  (107)(108)(109)']));
RAW Paste Data