Как получить самые длинные последовательности одинаковых символов и сколько их, если их больше одного? - PullRequest
0 голосов
/ 03 сентября 2018

Примеры:

  • 11ADD = 2 равных, 2 последовательности
  • 115222 3 равно, 1 последовательность
  • ABCDEF10 = 1 равно, 8 последовательностей

Результат должен содержать

  1. Длина максимального числа последовательных повторений символов.
  2. Количество повторяющихся последовательностей символов, соответствующих максимальному количеству длины

Вот что я пытаюсь: преобразовать dec в Hex, а затем найти равный seq. и сколько их

let n = [1, 26, 221];
let arr = [];
let hex = '';
let maxSequence = 0;
let currentCounter = 0;
let sequences = 0;


arr.forEach(element => {
  hex += element.toString(16).toLocaleUpperCase();
});
let newarr = [];
const hexSplit = [...hex];

hexSplit.forEach((element, x) => {
  if (hexSplit[x + 1] === hexSplit[x]) {
    currentCounter++;
    newarr.push(hexSplit[x])
  }
  if (currentCounter > maxSequence) {
    maxSequence = currentCounter;
    sequences += 1;

  } else if (maxSequence === 0) {
    maxSequence = 1;
    sequences = hexSplit.length;
  }
});

console.log(maxSequence, sequences)

Ответы [ 3 ]

0 голосов
/ 03 сентября 2018

Вы можете получить список самых длинных последовательностей одинаковых символов с помощью простого регулярного выражения, отсортировав его по длине в порядке убывания и отфильтровав по длине первого (который является самым длинным):

function getLongestSeqList(input) {
  return input
          .match(/(.)\1*/g)
          .sort((a,b) => b.length - a.length)
          .filter((a,i,arr) => a.length === arr[0].length)
}

console.log(getLongestSeqList('11ADD')); // ["11", "DD"]
console.log(getLongestSeqList('115222')); // ["222"]
console.log(getLongestSeqList('ABCDEF10')); // ["A", "B", "C", "D", "E", "F", "1", "0"]
0 голосов
/ 03 сентября 2018

ВСЕ кредиты здесь идут на ДРУГОЙ ответ здесь. https://stackoverflow.com/a/52152057/125981 Я просто адаптировал его, чтобы он возвращал результаты для массива значений. Пожалуйста, проголосуйте / примите это, возможно.

var sequences = ['11ADD', '115222', 'ABCDEF10'];

function getLongestSeqList(input) {
  return input
    .match(/(.)\1*/g)
    .sort((a, b) => b.length - a.length)
    .filter((a, i, arr) => a.length === arr[0].length)
}

function getValues(s) {
  let seq = getLongestSeqList(s);
  return {
    Count: seq.length,
    Len: seq[0].length
  };
}
sequences.forEach(function(s) {
  console.log(getValues(s));
});
0 голосов
/ 03 сентября 2018

    const getLongest = seq => seq.reduce(({
  longest,
  currentItem,
  currentLength,
  items
}, item) => {

  const newCurrentLength = currentItem === item ? currentLength + 1 : 1;
  if (newCurrentLength > longest) {
    // we have a new longest sequence, assign new values
    // to longest and items
    return {
      currentItem: item,
      currentLength: newCurrentLength,
      longest: newCurrentLength, 
      items: 1,
    };
  } else if (newCurrentLength === longest) {
    // we match the previously longest,
    // add the item to the sequence list
    return {
      currentItem: item,
      currentLength: longest,
      longest, 
      items: items + 1,
    };
  } else {
    // this is still a shorter sequence,
    // just update the local state
    return {
      currentItem: item,
      currentLength: newCurrentLength,
      longest,
      items
    }
  }


  return ;

}, {
  longest: 0,
  currentItem: undefined,
  currentLength: 0,
  items: 0
});

const values = ["11ADD", "115222", "ABCDEF10"];

const res = values.map(s => s.split("")).map(getLongest);

console.log(res);

Обратите внимание, что с помощью этой организации вы можете легко добавлять данные к своему результату, например, какое значение было самой длинной последовательностью, где оно началось и т. Д. *

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...