Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /* Write a JavaScript function findMaxSequence(arr) that finds the maximal sequence of equal elements in
- an array and returns the result as an array. If there is more than one sequence with the same maximal length,
- print the rightmost one. Write JS program sequenceFinder.js that invokes your function with the sample
- input data below and prints the output at the console. */
- "use strict";
- function findMaxSequence(arr) {
- if (arr.length > 1) {
- var equalsElements = 0;
- var currentEquals = 1;
- var repeatElement = arr[0];
- var i;
- for (i = 1; i < arr.length; i += 1) {
- if (arr[i] === arr[i - 1]) {
- currentEquals += 1;
- } else {
- if (currentEquals >= equalsElements) {
- repeatElement = arr[i - 1];
- equalsElements = currentEquals;
- }
- currentEquals = 1;
- }
- }
- if (currentEquals >= equalsElements) {
- repeatElement = arr[arr.length - 1];
- equalsElements = currentEquals;
- }
- var resultArr = [];
- do {
- resultArr.push(repeatElement);
- equalsElements -= 1;
- } while (equalsElements);
- return resultArr;
- } else {
- return arr;
- }
- }
- console.log(findMaxSequence([2, 1, 1, 2, 3, 3, 2, 2, 2, 1]));
- console.log(findMaxSequence(['happy']));
- console.log(findMaxSequence([2, 'qwe', 'qwe', 3, 3, '3']));
- console.log(findMaxSequence([2, 1, 1, 2, 2, 2, 2, 1, 3, 3, 3, 3, 2, 2, 2, 1]));
- console.log(findMaxSequence([]));
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement