Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /* You are given n numbers in format (a1) (a2) … (an). Write a program to find the longest odd-even alternating
- sub-sequence inside the input sequence. Such subsequence starts at some position with odd number and
- continues with even number, then again odd number, etc. The opposite is also allowed: start with even number,
- then odd number, then even number, etc. The special number 0 (zero) is considered odd and even in the same time.
- The input consists of a single line holding the input sequence of numbers. All numbers are in brackets.
- Spaces can be put anywhere between the numbers, even at the sequence start and at the sequence end.
- Print the length of the longest alternating sub-sequence at the console. */
- "use strict";
- function findTheLongestOddEvenSequence(args) {
- var numbers = args[0].split(/[)(\s]+/).filter(Boolean);
- var longestSeqLength = 0;
- var sequenceLength = 0;
- var oddOrder = (Number(numbers[0]) % 2) != 0;
- for (var i = 0; i < numbers.length; i += 1) {
- var isOdd = (Number(numbers[i]) % 2) != 0;
- if (isOdd == oddOrder || Number(numbers[i] == 0)) {
- sequenceLength++;
- } else {
- oddOrder = isOdd;
- sequenceLength = 1;
- }
- oddOrder = !oddOrder;
- if (sequenceLength > longestSeqLength) {
- longestSeqLength = sequenceLength;
- }
- }
- console.log(longestSeqLength);
- }
- findTheLongestOddEvenSequence(["(3) (22) (-18) (55) (44) (3) (21)"]);
- findTheLongestOddEvenSequence(["(1)(2)(3)(4)(5)(6)(7)(8)(9)(10)"]);
- findTheLongestOddEvenSequence(["( 2 ) ( 33 ) (1) (4) ( -1 ) "]);
- findTheLongestOddEvenSequence(["(102)(103)(0)(105) (107)(1)"]);
- findTheLongestOddEvenSequence(["(2) (2) (2) (2) (2)"]);
- findTheLongestOddEvenSequence(["(2) (5) (4) (0) (6) (0) (0) (5) (0) (0) (0) (1)"]);
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement