const fs = require('fs');

const createSlots = slotSpells =>
  slotSpells.map(spell => ({spell, numGolems: 1}));

const applySpell = (slots, [slotSpell, dir]) => {
  for (let i = 0; i < slots.length; i++) {
    const slot = slots[i];
    if (slot.spell === slotSpell) {
      slots = movGolem(slots, i, dir);
    }
  }

  return slots;
};

const movGolem = (slots, idx, dir) => {
  if ((idx === slots.length - 1 && dir === 'R') || (idx === 0 && dir === 'L')) {
    return setNumGolems(slots, idx, 0);
  } else {
    const destIdx = dir === 'R' ? idx + 1 : idx - 1;
    const numGolems = slots[idx].numGolems;
    return numGolems > 0
      ? setNumGolems(
          setNumGolems(slots, idx, 0),
          destIdx,
          slots[destIdx].numGolems + numGolems,
        )
      : slots;
  }
};

const setNumGolems = (slots, idx, numGolems) => {
  return [
    ...slots.slice(0, idx),
    {...slots[idx], numGolems},
    ...slots.slice(idx + 1),
  ];
};

const solve = (slotSpells, spells) => {
  const slots = createSlots(slotSpells);
  return spells
    .reduce((prev, cur) => applySpell(prev, cur), slots)
    .reduce((prev, {numGolems}) => prev + numGolems, 0);
};

const splitLines = s =>
  s
    .split('\n')
    .map(s => s.trim())
    .filter(s => !!s);

const parseInput = input => {
  const [, slotSpells, ...spells] = splitLines(input);
  return {
    slotSpells: slotSpells.split(''),
    spells: spells.map(s => s.split(' ')),
  };
};

const {slotSpells, spells} = parseInput(fs.readFileSync('/dev/stdin', 'UTF-8'));
console.log(solve(slotSpells, spells));

