Finding every second element in a repeating pattern - javascript

Data with repeated 'i's followed by 'i's and/or 't's.
data = ['i','t','t','i','i','t','t','t']
Trying to retrieve the index of the last 't' in the pattern ['i','t','t']:
[2,6] // ['i','t','t','i','i','t','t','t'] # position of the returned 't's
// _______ ^ _______ ^
I'm looking for a non-recursive solution using (pure) functions only, using ramdajs for example.
Tried to use reduce and transduce, but unsuccessful sofar.

One approach would be to use R.aperture to iterate over a 3-element sliding window of the data list, then tracking the position of any sub-list that equals the pattern ['i', 't', 't'].
const data = ['i','t','t','i','i','t','t','t']
const isPattern = R.equals(['i', 't', 't'])
const reduceWithIdx = R.addIndex(R.reduce)
const positions = reduceWithIdx((idxs, next, idx) =>
isPattern(next) ? R.append(idx + 2, idxs) : idxs
, [], R.aperture(3, data))
console.log(positions)
<script src="//cdnjs.cloudflare.com/ajax/libs/ramda/0.24.1/ramda.min.js"></script>
A point-free version of this approach could look something like the following, though whether this is preferable comes down to a preference of style/readability.
const data = ['i','t','t','i','i','t','t','t']
const isPattern = R.equals(['i', 't', 't'])
const run = R.pipe(
// create sliding window of 3 elements
R.aperture(3),
// zip sliding window with index
R.chain(R.zip, R.compose(R.range(0), R.length)),
// filter matching pattern
R.filter(R.compose(isPattern, R.nth(1))),
// extract index
R.map(R.compose(R.add(2), R.head))
)
console.log(run(data))
<script src="//cdnjs.cloudflare.com/ajax/libs/ramda/0.24.1/ramda.min.js"></script>

You could use a nested approach with a temporary array for checking the same pattern for different starting points. This proposal works with an arbitrary length of pattern and returns the index of the predefined pattern.
This solution features obviously plain Javascript.
index i t i t t i i t t t temp result comment
----- ------------------------------ ------ -------- ------------
0 <i> [0] [] match
1 i <t> [0] [] match
<-> [0] [] no match
2 i t <-> [] [] no match
<i> [2] [] match
3 i <t> [2] [] match
<-> [2] [] no match
4 i t <t> [] [4] pattern found
<-> [] [4] no match
5 <i> [5] [4] match
6 i <-> [] [4] no match
<i> [6] [4] match
7 i <t> [6] [4] match
<-> [6] [4] no match
8 i t <t> [] [4, 8] pattern found
<-> [] [4, 8] no match
9 <-> [] [4, 8] no match
<t> matches 't' at position
<-> does not match at position
function getPatternPos(array, pattern) {
var result = [];
array.reduce(function (r, a, i) {
return r.concat(i).filter(function (j) {
if (i - j === pattern.length - 1 && a === pattern[i - j]) {
result.push(i);
return false;
}
return a === pattern[i - j];
});
}, []);
return result;
}
console.log(getPatternPos(['i', 't', 't', 'i', 'i', 't', 't', 't'], ['i', 't', 't']));
// [2, 6]
console.log(getPatternPos(['i','t','i', 't', 't', 'i', 'i', 't', 't', 't'], ['i', 't', 't']));
// [4, 8]
console.log(getPatternPos(['a', 'b', 'a', 'b', 'b', 'a', 'b', 'c', 'd'], ['a', 'b', 'c']));
// [7]
.as-console-wrapper { max-height: 100% !important; top: 0; }

You can do it using Array.prototype.reduce() with a simple condition.
data = ['i','t','t','i','i','t','t','t']
var newData = data.reduce(function (acc, item, index) {
// Check if current element is `t` and the item before it is `i`, `t`
if (item === 't' && data[index - 1] === 'i' && data[index - 2] === 't') {
acc.push(item)
}
return acc;
}, []);
console.log(newData); // ['t', 't']

You can do simply by for loop and check last values of array:
var data = ['i','t','t','i','i','t','t','t'];
var positions = new Array();
for(var i=2; i< data.length; i++){
if(data[i-2] === 'i' && data[i-1] === 't' && data[i] === 't') {
positions.push(i)
}
}
console.log(positions)

data.filter((c, i, d) => c === 't' && d[i - 1] === 't' && d[i - 2] === 'I')
**No negative indexes: **
const matchMaker = () => {
let memo = [‘a’, ‘b’];
return (c, i, d) => {
memo.unshift(c);
return memo[1] + memo[2] + c === 'itt';
}
};
data.filter(matchMaker());

function getPattern(arr, p) {
var r = [],
dir = [];
for (let [i, v] of arr.entries()) {
dir = dir.concat(i).filter(function(x) {
if (v === p[i - x] && i - x === p.length - 1) {
r.push(i);
return false;
}
return v === p[i - x];
})
};
return r;
}
console.log(getPattern(['i', 't', 't', 'i', 'i', 't', 't', 't'], ['i', 't', 't']));
console.log(getPattern(['i', 't', 'i', 't', 't', 'i', 'i', 't', 't', 't'], ['i', 't', 't']));
console.log(getPattern(['a', 'b', 'a', 'b', 'b', 'a', 'b', 'c', 'd'], ['a', 'b', 'c']));
.as-console-wrapper { max-height: 100% !important; top: 0; }

In case anyone wants to see an example without using a library that does not use look ahead or behinds ("i + 1" or "i - 2'", etc.).
I think it works similarly to what the Ramda approach does, but I chose to combine the partitioning and equality check in the same loop:
For every step in reduce
Take a section of the array matching the pattern length
Check if it is equal to the pattern
If it is, add the index of the last element in the section to the result of reduce
The code, in which pattern and data are both arrays of strings:
const findPattern = (pattern, data) => data.reduce(
(results, _, i, all) =>
// Check if a slice from this index equals the pattern
arrEqual(all.slice(i, i + pattern.length), pattern)
// Add the last index of the pattern to our results
? (results.push(i + pattern.length - 1), results)
// or, return what we had
: results,
[]);
// Utility method to check array equality
const arrEqual = (arr1, arr2) =>
arr1.length === arr2.length &&
arr1.every((x, i) => x === arr2[i]);
I tested on several data sets and think it meets all requirements:
const findPattern = (pattern, data) => data.reduce(
(results, _, i, all) =>
arrEqual(all.slice(i, i + pattern.length), pattern)
? push(results, i + pattern.length - 1)
: results,
[]);
const arrEqual = (arr1, arr2) =>
arr1.length === arr2.length &&
arr1.every((x, i) => x === arr2[i]);
const push = (xs, x) => (xs.push(x), xs);
// For just string patterns we could also do:
// const arrEqual = (arr1, arr2) => arr1.join("") === arr2.join("");
// Test cases
const dataSets = [
// (i) marks a matching index
// [i] marks a last matching index that should be returned
// | marks a new start
{ pattern: ["i","t","t"], input: ['i','t','t','i','i','t','t','t'], output: [2, 6] },
// |(0) (1) [2]| 3 -(4) (5) [6]| 7
{ pattern: ["i","t"], input: ['i','t','i','t','t','i','i','t','t','t'], output: [1, 3, 7] },
// |(0) [1]|(2) [3]| 4 | 5 |(6) [7]| 8 | 9
{ pattern: ["i","t","t"], input: ['i','t','i','t','t','i','i','t','t','t'], output: [4, 8] },
// |(0) (1)|(2) (3) [4]| 5 |(6) (7) [8]| 9
{ pattern: ["i","t","i"], input: ['i','t','i','t','i','t','i','t','i','t'], output: [2, 4, 6, 8] }
// |(0) (1) [2]| |(6) (7) [8]| 9
// |(2) (3) [4]
// |(4) (5) [6]
];
dataSets.forEach(({pattern, input, output}) =>
console.log(
"| input:", input.join(" "),
"| control:", output.join(", "),
"| answer:", findPattern(pattern, input).join(", ")
)
)

Two years later, lost traveler stumbles upon this question and notices that for variable sized (and especially large pattern with even larger input array or multiple input arrays), classical KMP algorithm would be great.
I think it is worth studing this algorithm.
We will start with simple imperative implementation. Then switch to (at least for me) more intuitive (but probably slightly less optimal, and definitely less optimal when it comes to memory) version with finite automaton. At the end, we'll see something that looks like functional but it is not 100% pure. I wasn't in a mood to torture my self with pure functional implementation of KMP in JS :).
Prefix function KMP, imperative implementation:
function getPatternPos(array, pattern) {
const result = [];
// trying to explain this is a waste of time :)
function createPrefix(pattern) {
// initialize array with zeros
const prefix = Array.apply(null, Array(pattern.length)).map(Number.prototype.valueOf, 0);
let s = 0;
prefix[0] = 0;
for (let i = 1; i < pattern.length; ++i) {
while (s > 0 && pattern[s] !== pattern[i]) {
s = prefix[s - 1];
}
if (pattern[i] === pattern[s]) {
++s;
}
prefix[i] = s;
}
return prefix;
}
const prefix = createPrefix(pattern);
let s = 0;
for (let i = 0; i < array.length; ++i) {
while (s > 0 && pattern[s] !== array[i]) {
s = prefix[s - 1];
}
if (array[i] === pattern[s]) {
++s;
}
if (s === pattern.length) {
result.push(i);
s = 0;
}
}
return result;
}
console.log(getPatternPos(['i', 't', 't', 'i', 'i', 't', 't', 't'], ['i', 't', 't']));
// [2, 6]
console.log(getPatternPos(['i','t','i', 't', 't', 'i', 'i', 't', 't', 't'], ['i', 't', 't']));
// [4, 8]
console.log(getPatternPos(['a', 'b', 'a', 'b', 'b', 'a', 'b', 'c', 'd'], ['a', 'b', 'c']));
// [7]
console.log(getPatternPos("ababxabababcxxababc".split(""), "ababc".split("")));
// [11, 18]
console.log(getPatternPos("abababcx".split(""), "ababc".split("")));
.as-console-wrapper { max-height: 100% !important; top: 0; }
Finate automaton KMP implementation:
function getPatternPos(array, pattern) {
const result = [];
function patternCode(i) {
return pattern[i].charCodeAt(0);
}
function createStateMachine(pattern) {
// return single dimensional array as matrix instead of array of arrays,
// for better perfomanse (locality - cache optimizations) and memory usage.
// zero initialize matrix
const sm = Array.apply(null, Array(256 * pattern.length)).map(Number.prototype.valueOf, 0);
let s = 0;
sm[patternCode(0) * pattern.length + 0] = 1;
for (let i = 1; i < pattern.length; ++i) {
// go to same states as if we would go after backing up, so copy all
for (let code = 0; code < 256; ++code)
sm[code * pattern.length + i] = sm[code * pattern.length + s];
// only in case of current symbol go to different/next state
sm[patternCode(i) * pattern.length + i] = i + 1;
// update the state that fallows backup path
s = sm[patternCode(i) * pattern.length + s];
}
return sm;
}
const sm = createStateMachine(pattern);
numStates = pattern.length;
let s = 0;
// now simply fallow state machine
for (let i = 0; i < array.length; ++i) {
s = sm[array[i].charCodeAt(0) * numStates + s];
if (s === pattern.length) {
result.push(i);
s = 0;
}
}
return result;
}
console.log(getPatternPos(['i', 't', 't', 'i', 'i', 't', 't', 't'], ['i', 't', 't']));
// [2, 6]
console.log(getPatternPos(['i','t','i', 't', 't', 'i', 'i', 't', 't', 't'], ['i', 't', 't']));
// [4, 8]
console.log(getPatternPos(['a', 'b', 'a', 'b', 'b', 'a', 'b', 'c', 'd'], ['a', 'b', 'c']));
// [7]
console.log(getPatternPos("ababxabababcxxababc".split(""), "ababc".split("")));
// [11, 18]
console.log(getPatternPos("abababcx".split(""), "ababc".split("")));
.as-console-wrapper { max-height: 100% !important; top: 0; }
Funcational-ish KMP implementation:
function getPatternPos(array, pattern) {
// pure function that creates state machine,
// but it's implementation is not complitely pure internally.
function createStateMachine(pattern) {
const initState = Object.create(null);
initState[pattern[0]] = Object.create(initState);
const {currState: finalState} = pattern.slice(1).reduce(function(acc, cval, cidx) {
const newFallbackState = acc.fallbackState[cval] || initState;
// WARNING: non-functional/immutable part,
// to make it complitely pure we would probably need to
// complicate our lives with better data structures or
// lazy evalutaion.
acc.currState[cval] = Object.create(newFallbackState);
return {currState: acc.currState[cval], fallbackState: newFallbackState};
}, {currState: initState[pattern[0]], fallbackState: initState});
return {initState: initState, finalState: finalState};
}
const {initState, finalState} = createStateMachine(pattern);
return array.reduce(function (acc, cval, cidx, array) {
const newState = acc.currState[cval];
if (typeof newState === 'undefined') {
return {currState: initState, result: acc.result};
}
if (newState === finalState) {
// WARNING: not purly functional/immutable,
// still implemenations of JS pure functional/immutable libraries
// probaly use mutation under the hood, and just make it look pure,
// this is what happens here also :)
acc.result.push(cidx);
return {currState: initState, result: acc.result};
}
return {currState: newState, result: acc.result};
}, {currState: initState, result: []}).result;
}
console.log(getPatternPos(['i', 't', 't', 'i', 'i', 't', 't', 't'], ['i', 't', 't']));
// [2, 6]
console.log(getPatternPos(['i','t','i', 't', 't', 'i', 'i', 't', 't', 't'], ['i', 't', 't']));
// [4, 8]
console.log(getPatternPos(['a', 'b', 'a', 'b', 'b', 'a', 'b', 'c', 'd'], ['a', 'b', 'c']));
// [7]
console.log(getPatternPos("ababxabababcxxababc".split(""), "ababc".split("")));
// [11, 18]
console.log(getPatternPos("abababcx".split(""), "ababc".split("")));
.as-console-wrapper { max-height: 100% !important; top: 0; }

Related

How to validate if a letter in an array is repeated?

I want to validate that a string within an array is not repeated more than 3 times, that is:
let array = ['A', 'A', 'A', 'B']
let array2 = ['A', 'A', 'A', 'A', 'B'] <-- Not valid
That the code does not continue to work, if the array it receives has values that are repeated those times
Thank you
You can use array.some() in combination with array.filter() to check if a value only exists an x amount of times.
const array = ['A', 'A', 'A', 'B'];
const array2 = ['A', 'A', 'A', 'A', 'B'];
const isValid = (arr, limit) => {
return !arr.some((char) => (
arr.filter((ch) => ch === char).length > limit
// use the next line for a case insensitive check
// arr.filter((ch) => ch.toLowerCase() === char.toLowerCase()).length > limit
));
}
console.log(isValid(array, 3));
console.log(isValid(array2, 3));
You could take a closure over the count of the last string and check the count or reset the count to one.
const
check = array => array.every(
(c => (v, i, { [i - 1]: l }) => l === v ? c++ < 3 : (c = 1))
(0)
);
console.log(check(['A', 'A', 'A', 'B']));
console.log(check(['A', 'A', 'A', 'A', 'B']));
You can count all the letters using reduce and then check those, like so:
let array = ['A', 'A', 'A', 'B'];
let array2 = ['A', 'A', 'A', 'A', 'B'];
const allElementsExistUpToN = (arr, n) => {
const counts = arr.reduce((acc, el) => {
acc[el] = acc[el] == undefined ? 1 : acc[el] +1;
return acc;
}, {});
return !Object.values(counts).some(c => c > n);
}
console.log(allElementsExistUpToN(array, 3));
console.log(allElementsExistUpToN(array2, 3));

Find a random combination of arrays with a total length of 10, and splittable into two groups of 5

Let's say I have an array with arrays, such as:
const array = [
['a', 'b', 'c'],
['d', 'e'],
['f', 'g', 'h', 'i', 'j'],
['k'],
['l'],
['m'],
['n', 'o', 'p'],
['q', 'r', 's'],
['t', 'u', 'v'],
['x']
];
I want to select any combination at random that respects the following rules:
The total length of all the selected combinations must always be 10. A possible result could be the first 3 items of the array
The selected combinations must be able to be split into two groups of 5. Again, the first 3 items would respect that condition: the length of ['a', 'b, 'c'] + the length of ['d', 'e'] equals 5, and at the same time, the length of ['f', 'g', 'h', 'i', 'j']equals 5. That's two groups of 5. The last 4 elements of the array, on the other hand, wouldn't be able to fulfill this condition, even though they respect the first one (total length = 10).
It might help to know the purpose of this: I have a little multiplayer game. Games need 2 teams of 5 players. And players can enter the game with a friend to play on the same team (or even 5 friends, instantly filling an entire team).
The idea: players would press 'Start'. Then my function would push them into an array like the one above. Each time a push happened, the player/team function (which I'm asking for your help) would run. If a match were found, the game would start.
I have a feeling that this would be best accomplished with some kind of recursive function, but my head is having trouble figuring it out.
After a long couple of hours here's the solution I came up with. Passed all my tests.
//const { shuffle, flatten } = require('lodash');
const pool = [
['a', 'b', 'c'],
['d', 'e'],
['f', 'g', 'h', 'i', 'j'],
['k'],
['l'],
['m'],
['n', 'o', 'p'],
['q', 'r', 's'],
['t', 'u', 'v'],
['x']
];
function getMaxPickSize ( draw ) {
let x = 5;
let y = 5;
draw.forEach( pick => {
if ( x - pick.length >= 0 ) {
x -= pick.length;
} else if ( y - pick.length >= 0 ) {
y -= pick.length;
}
});
return Math.max(x,y);
}
function doDraw( pool ) {
//no need to move further if there arent even 10 players
if ( _.flatten(pool).length < 10 ) {
return false;
}
// keep register of all draws and pools, and items. if we
// figure out an attempt doesnt work, we can go back anytime
// and skip picks that dont work
let prevs = [
// array of objects that will look like this.
// {
// pool: [],
// draw: [],
// skip: []
// }
// ...
];
//let's try. First step, shuffle the pool;
pool = _.shuffle(pool);
function doIt( curr_pool, curr_draw = [], skip_items_w_length ) {
let new_pool = [...curr_pool];
let new_draw = [...curr_draw];
let pick;
if ( skip_items_w_length == undefined ) {
//in first loop it starts here
//if we happen to have luck and fill the draw in
//one go, the else statement below will never execute
pick = new_pool.shift();
} else {
let to_skip = prevs[prevs.length - 1].skip;
to_skip.push(skip_items_w_length);
pick = _.find(new_pool, item => !to_skip.includes(item.length) );
if ( pick ) {
new_pool.splice(new_pool.indexOf(pick), 1);
} else {
if ( !prevs.length ) {
return false;
}
let prev = prevs.pop();
let prev_pool = prev.pool;
let prev_draw = prev.draw;
let last_item_in_prev_draw = prev_draw.pop();
return doIt(prev_pool, prev_draw, last_item_in_prev_draw.length );
}
}
new_draw = [...curr_draw, pick];
//if draw is complete, return it
if ( _.flatten(new_draw).length === 10 ) {
return new_draw;
}
//else draw process continues
//find items in pool that can still fit into draw
const max_pick_size = getMaxPickSize(new_draw);
new_pool = new_pool.filter(item => item.length <= max_pick_size);
//if items dont contain enough players to fill remaining spots,
//repeat this exact step, ignoring items without pick's length
//as none of the remaining picks can follow. if we discover in
// later repeats that no pick allows other picks to follow
// we'll go back 1 step, using previous pool and draw, and
// ignoring all picks with the associated picks length
if ( _.flatten(new_pool).length < 10 - _.flatten(new_draw).length ) {
return doIt(curr_pool, curr_draw, pick.length);
}
prevs.push({
pool: curr_pool,
draw: curr_draw,
skip: []
});
return doIt(new_pool, new_draw);
}
return doIt(pool);
}
const draw = doDraw( pool );
Thank you guys!
Shuffle the array, then take out unique groups till you reach five:
const array = [
['a', 'b', 'c'],
['d', 'e'],
['f', 'g', 'h', 'i', 'j'],
['k'],
['l'],
['m'],
['n', 'o', 'p'],
['q', 'r', 's'],
['t', 'u', 'v'],
['x']
];
function shuffle(arr) { /* Shuffling algorithm here */ }
shuffle(array);
// Extracts arrays with exactly "count" elements, excluding all elements in "exclude" and starting at "start" in the array
// If no combination was found, return undefined
function takeOut(array, count, start = 0, exclude = []) {
// Base case: Count wasn't reached exactly, abort here
if(count < 0) return;
// Base case: Combination was found, go up
if(count === 0) return [];
// Go over the array to find a matching combination
for(let i = start; i < array.length; i++) {
const current = array[i];
// Skip elements that should be excluded
if(exclude.includes(current)) continue;
// Recursive call: Find more elements so that a group of "count" gets reached
const rest = takeOut(array, count - current.length, i + 1, exclude);
if(!rest) continue; // If this element can't be matched up, go on
return [current, ...rest];
}
}
// Our two teams:
const first = takeOut(array, 5);
const second = takeOut(array, 5, 0, first); // all from the first team can't be in the second one
console.log(first, second);
if(first && second)
console.log("The game can start");
I came up with the solution that may not be exactly what you wanted. Anyway I think that it may help you. It finds all possible compositions and if you need only one you can choose it randomly. I also used slightly different data model: object where keys represent team sizes and values are arrays of arrays of teams with according sizes.
const UNITS_NUMBER = 2
// object format: { [number]: how-many-times-this-number-should-be-used }
const COMPOSE_VARIATIONS = [{1: 5}, {1: 3, 2: 1}, {1: 2, 3: 1}, {1: 1, 4: 1}, {1: 1, 2: 2}, {2: 1, 3: 1}, {5: 1}]
const parts = {
1: [['k'], ['l'], ['m'], ['x']],
2: [['d', 'e']],
3: [['a', 'b', 'c'], ['n', 'o', 'p'], ['q', 'r', 's'], ['t', 'u', 'v']],
4: [],
5: [['f', 'g', 'h', 'i', 'j']],
}
function getAllCompositions(allParts, unitsNumber, composeVariations) {
const result = []
const usedPartsStack = []
let units = []
let currentIndex = 0
let unitsComposed = 0
while (currentIndex < composeVariations.length) {
const variation = composeVariations[currentIndex]
if (canCreateUnit(allParts, variation)) {
const unit = getPartsForUnit(allParts, variation)
units.push(flatten(unit))
if (unitsComposed + 1 < unitsNumber) {
usedPartsStack.push({ index: currentIndex, partsUsedForUnit: unit })
allParts = removeUsedParts(allParts, variation)
unitsComposed++
} else {
result.push([...units])
units.pop()
currentIndex++
}
} else {
currentIndex++
}
while (currentIndex === composeVariations.length && usedPartsStack.length) {
const { index, partsUsedForUnit } = usedPartsStack.pop()
currentIndex = index + 1
allParts = restoreUsedParts(allParts, partsUsedForUnit)
unitsComposed--
units.pop()
}
}
return result
}
// checks if passed variation can be used to create unit from parts from allParts object
// unit is a group of parts that forms an array with total length of 5)
function canCreateUnit(allParts, variation) {
return Object.entries(variation).every(([length, count]) => allParts[length].length >= count)
}
// get real parts from allParts object according to variation passed
function getPartsForUnit(allParts, variation) {
const result = []
Object.entries(variation).forEach(([length, count]) => {
result.push(allParts[length].slice(0, count))
})
return result
}
// removes parts that were used for unit creation
function removeUsedParts(allParts, variation) {
const result = { ...allParts }
Object.entries(variation).forEach(([length, count]) => {
result[length] = result[length].slice(count)
})
return result
}
// add parts to allParts object
function restoreUsedParts(allParts, parts) {
const result = { ...allParts }
parts.forEach((item) => {
result[item[0].length] = [...item, ...result[item[0].length]]
})
return result
}
// removes one level of nesting in array
function flatten(partsForUnit) {
const result = []
partsForUnit.forEach(item => {
result.push(...item)
})
return result
}
function print(compositions) {
compositions.forEach(composition => {
composition.forEach(unit => {
console.log(unit)
})
console.log('=======================================')
})
}
print(getAllCompositions(parts, UNITS_NUMBER, COMPOSE_VARIATIONS))

How do I easily combine elements from two arrays in Javascript, alternating elements?

I have two arrays in JavaScript, of potentially different lengths:
var x = ['a', 'b', 'c'];
var y = ['g', 'h', 'i', 'j'];
I'd like to combine them into one array:
var z = ['a', 'g', 'b', 'h', 'c', 'i', 'j'];
How can I do that in JavaScript?
I see you answered your question at the same time as asking it. That's fine, but it's now clear that you were looking for a solution that leverages a library (eg, lodash) and not necessarily one that teaches you how to build such a procedure. In retrospect, I would've answered this differently, but nevertheless I think you can learn something from this answer.
I would recommend calling this something other than zip just because zip is used as name for a procedure that does something quite different from what you're looking for.
Here's a simple recursive definition of interleave -
const interleave = ([ x, ...xs ], ys = []) =>
x === undefined
? ys // base: no x
: [ x, ...interleave (ys, xs) ] // inductive: some x
const xs = [ 'a', 'b', 'c' ]
const ys = [ 'g', 'h', 'i', 'j' ]
console .log (interleave (xs, ys))
// [ a, g, b, h, c, i, j ]
And another variation that supports any number of input arrays -
const interleave = ([ x, ...xs ], ...rest) =>
x === undefined
? rest.length === 0
? [] // base: no x, no rest
: interleave (...rest) // inductive: no x, some rest
: [ x, ...interleave (...rest, xs) ] // inductive: some x, some rest
const ws = [ '0', '1', '2', '3' ]
const xs = [ 'a', 'b', 'c' ]
const ys = [ 'd', 'e', 'f' ]
const zs = [ 'g', 'h', 'i', 'j' ]
console .log (interleave (ws, xs, ys, zs))
// [ 0, a, d, g, 1, b, e, h, 2, c, f, i, 3, j ]
tl;dr: z = _.flatten(_.zip(x, y)).filter(element => element), as long as you don't care about null elements in the original arrays.
Some of the libraries providing functional tools, such as Lodash, provide enough mechanics to easily do this. For example, you can do this:
var z1 = _.zip(x, y);
// z1 is now [["a","g"],["b","h"],["c","i"],[null,"j"]]
var z2 = _.flatten(z1);
// z2 is now ["a","g","b","h","c","i",null,"j"]
var z3 = z2.filter(element => element)
// z3 is now ["a","g","b","h","c","i","j"]
Note that this will only work if the original arrays do not contain any null elements, as they are filtered out by the last step.
A simple implementation that will stitch the arrays:
function stitch(x, y) {
var arr = [];
var length = Math.max(x.length, y.length);
for(var i = 0; i < length; i++) {
i < x.length && arr.push(x[i]);
i < y.length && arr.push(y[i]);
}
return arr;
}
var x = ['a', 'b', 'c'];
var y = ['g', 'h', 'i', 'j'];
console.log(stitch(x, y));
This is the functional way to address the problem:
var x = ['a', 'b', 'c'];
var y = ['g', 'h', 'i', 'j'];
function stitch(x,y) {
var a = x.length > y.length ? x : y;
var b = x.length > y.length ? y : x;
var c = a.map(function (e, i) {
return b.length<i ? [e, b[i]] : [];
});
return [].concat.apply([],c)
}
Here's a very simple recursive solution:
const interlace = (xxs, ys) => {
if (xxs.length === 0) return ys;
const [x, ...xs] = xxs;
return [x, ...interlace(ys, xs)];
};
const xs = ['a', 'b', 'c'];
const ys = ['g', 'h', 'i', 'j'];
console.log(JSON.stringify(interlace(xs, ys)));
In addition, you can easily generalize this algorithm to an arbitrary number of arrays:
const interlace = (...xss) => xss.length > 0 ? interleave(...xss) : [];
const interleave = (xxs, ...yss) => {
if (xxs.length === 0) return interlace(...yss);
const [x, ...xs] = xxs;
return [x, ...interleave(...yss, xs)];
};
const xs = ['a', 'b', 'c'];
const ys = ['g', 'h', 'i', 'j'];
const zs = ['d', 'e', 'f'];
console.log(JSON.stringify(interlace()));
console.log(JSON.stringify(interlace(xs)));
console.log(JSON.stringify(interlace(xs, ys)));
console.log(JSON.stringify(interlace(xs, ys, zs)));
Hope that helps.
This can be done in regular Javascript. No need for fancy tricks:
function splicer(array, element, index) {
array.splice(index * 2, 0, element);
return array;
}
function weave(array1, array2) {
return array1.reduce(splicer, array2.slice());
}
var x = ['a', 'b', 'c'];
var y = ['g', 'h', 'i', 'j'];
var z = weave(x, y);
console.log(z);
var x = ['a', 'b', 'c'];
var y = ['g', 'h', 'i', 'j'];
var z=[];
if(y.length>=x.length){
for(var i=0;i<x.length;i++){
z.push(x[i]);
z.push(y[i]);
}
while(i<y.length)
z.push(y[i++]);
}else{
for(var i=0;i<y.length;i++){
z.push(x[i]);
z.push(y[i]);
}
while(i<x.length)
z.push(x[i++]);
}
window.alert(JSON.stringify(z)); // print ["a","g","b","h","c","i","j"]

Fetching JavaScript array elements after consecutive occurrence of an element

I have a JavaScript array like:
var myArray = ['a', 'x', 'b', 'x', 'x', 'p', 'y', 'x', 'x', 'b', 'x', 'x'];
I want to fetch only those elements of the array that come after 2 consequent occurrences of a particular element.
i.e. in the above array, I want to fetch all the elements that come after consequent 'x', 'x'
So my output should be:
'p'
'b'
I have a solution like :
var arrLength = myArray.length;
for (var i = 0; i < arrLength; i++) {
if(i+2 < arrLength && myArray[i] == 'x' && myArray[i+1] == 'x') {
console.log(myArray[i+2]);
}
};
This satisfies my needs, but it is not so generic.
For eg. if I have to check for 3 consequent occurrences, then again I have to add a condition inside if for myArray[i+2] == 'x' and so on.
Could anyone provide a better way to fetch the elements?
The functional way would be to use recursion. With an ES6 spread, you can pretty much emulate the terseness of a truly 'functional' language :-)
var myArray = ['a', 'x', 'b', 'x', 'x', 'p', 'y', 'x', 'x', 'b', 'x', 'x'];
function reducer(acc, xs) {
if (xs.length > 2) {
if (xs[0] === xs[1]) {
// add the third element to accumulator
// remove first three elements from xs
// return reducer([xs[2], ...acc], xs.slice(3));
// or per Nina's question below
return reducer([xs[2], ...acc], xs.slice(1));
} else {
// remove first element from xs and recurse
return reducer(acc, xs.slice(1))
}
} else {
return acc;
}
}
console.log(reducer([], myArray));
A generic straight forward approach for any comparable content.
function getParts(array, pattern) {
return array.reduce(function (r, a, i) {
i >= pattern.length && pattern.every(function (b, j) {
return b === array[i + j - pattern.length];
}) && r.push(a);
return r;
}, []);
}
function p(o) {
document.write('<pre>' + JSON.stringify(o, 0, 4) + '</pre>');
}
p(getParts(['a', 'x', 'x', 'x', 'x', 'p', 'y', 'x', 'x', 'b', 'x', 'x'], ['x', 'x']));
p(getParts(['a', 'x', 'b', 'x', 'x', 'p', 'y', 'x', 'x', 'b', 'x', 'x'], ['a', 'x', 'b']));
p(getParts(['a', 'b', 'c', 'd', 'z', 'y', 'a', 'b', 'c', 'd', 'x', 'x'], ['a', 'b', 'c', 'd']));
p(getParts([41, 23, 3, 7, 8, 11, 56, 33, 7, 8, 11, 2, 5], [7, 8, 11]));
You can try following logic
var myArray = ['a', 'x', 'b', 'x', 'x', 'p', 'y', 'x', 'x', 'b', 'x', 'x'];
function search(ch, times) {
var splitStr = "";
for(var i = 0; i < times; i++) {
splitStr += ch;
} // Generate the split string xx in the above case.
var str = myArray.join(''); // Join array items into a string
var array = str.split(splitStr); // Split the string based on split string
var result = {};
// iterate on the array starting from index 1 as at index 0 will be string before split str
for (var i = 1 ; i < array.length; i++) {
if(array[i] !== "") {
result[array[i].substring(0,1)] = ''; // A map in order to avoid duplicate values
}
}
return Object.keys(result); // return the keys
}
console.dir(search('x',2));
Here is a straightforward iterative solution. We maintain an array consecutive of consecutive elements. If that array gets to length 2, then the next element is printed and consecutive is reset.
var arr = ['a', 'x', 'b', 'x', 'x', 'p', 'y', 'x', 'x', 'b', 'x', 'x'];
var REPEATS_NEEDED = 2;
var consecutive = [arr[0]];
for (var i = 1; i < arr.length; i++) {
if (consecutive.length === REPEATS_NEEDED) {
console.log(arr[i]);
consecutive = [arr[i]];
continue;
}
// either add to or reset 'consecutive'
if (arr[i] === consecutive[0]) {
consecutive.push(arr[i]);
} else {
consecutive = [arr[i]];
}
};
You can create an additional function isItGood like this:
var myArray = ['a', 'x', 'b', 'x', 'x', 'p', 'y', 'x', 'x', 'b', 'x', 'x'];
var arrLength = myArray.length;
for (var i = 0; i < arrLength; i++) {
isItGood(myArray, i, 'x', 2);
};
function isItGood(arr, i, elem, total) {
for ( var j = 0 ; j < total ; j++ ) {
if ( i + total >= arr.length || arr[i+j] != elem ) {
return;
}
}
console.log(arr[i+total]);
// just to see the result (no need to open a console)
document.getElementById('p').innerHTML+=("<br/>"+arr[i+total]);
}
<p id="p">Result: </p>
If I had to write this in Scala instead of JavaScript I could just do it in one line.
myArray.sliding(3).filter(l => l(0) == 'x' && l(1) == 'x').map(l => l(2))
So I guess I could do it the same way in JS if I implement the sliding function myself.
e.g.
function sliding(array, n, step) {
if(!step) step = 1;
var r = [];
for(var i = 0; i < array.length - n + 1; i += step) {
r.push(array.slice(i, i + n));
}
return r;
}
var result = sliding(myArray, 3).filter(l => l[0] === "x" && l[1] === "x").map(l => l[2]);
The only downside here is that this runs slower than a more iterative approach. But that only matters for very big arrays.
Try using for loop using variables referencing previous index, current index, next index of array
var myArray = ["a", "x", "b", "x", "x", "p", "y", "x", "x", "b", "x", "x"];
for (var res = [], curr = 0, prev = curr - 1, match = curr + 1
; curr < myArray.length - 1; curr++, prev++, match++) {
if (myArray[curr] === myArray[prev]) res.push(myArray[match]);
};
console.log(res);
document.body.textContent = res;

Finding All Combinations (Cartesian product) of JavaScript array values

How can I produce all of the combinations of the values in N number of JavaScript arrays of variable lengths?
Let's say I have N number of JavaScript arrays, e.g.
var first = ['a', 'b', 'c', 'd'];
var second = ['e'];
var third = ['f', 'g', 'h', 'i', 'j'];
(Three arrays in this example, but its N number of arrays for the problem.)
And I want to output all the combinations of their values, to produce
aef
aeg
aeh
aei
aej
bef
beg
....
dej
EDIT: Here's the version I got working, using ffriend's accepted answer as the basis.
var allArrays = [['a', 'b'], ['c', 'z'], ['d', 'e', 'f']];
function allPossibleCases(arr) {
if (arr.length === 0) {
return [];
}
else if (arr.length ===1){
return arr[0];
}
else {
var result = [];
var allCasesOfRest = allPossibleCases(arr.slice(1)); // recur with the rest of array
for (var c in allCasesOfRest) {
for (var i = 0; i < arr[0].length; i++) {
result.push(arr[0][i] + allCasesOfRest[c]);
}
}
return result;
}
}
var results = allPossibleCases(allArrays);
//outputs ["acd", "bcd", "azd", "bzd", "ace", "bce", "aze", "bze", "acf", "bcf", "azf", "bzf"]
This is not permutations, see permutations definitions from Wikipedia.
But you can achieve this with recursion:
var allArrays = [
['a', 'b'],
['c'],
['d', 'e', 'f']
]
function allPossibleCases(arr) {
if (arr.length == 1) {
return arr[0];
} else {
var result = [];
var allCasesOfRest = allPossibleCases(arr.slice(1)); // recur with the rest of array
for (var i = 0; i < allCasesOfRest.length; i++) {
for (var j = 0; j < arr[0].length; j++) {
result.push(arr[0][j] + allCasesOfRest[i]);
}
}
return result;
}
}
console.log(allPossibleCases(allArrays))
You can also make it with loops, but it will be a bit tricky and will require implementing your own analogue of stack.
I suggest a simple recursive generator function as follows:
// Generate cartesian product of given iterables:
function* cartesian(head, ...tail) {
let remainder = tail.length ? cartesian(...tail) : [[]];
for (let r of remainder) for (let h of head) yield [h, ...r];
}
// Example:
const first = ['a', 'b', 'c', 'd'];
const second = ['e'];
const third = ['f', 'g', 'h', 'i', 'j'];
console.log(...cartesian(first, second, third));
You don't need recursion, or heavily nested loops, or even to generate/store the whole array of permutations in memory.
Since the number of permutations is the product of the lengths of each of the arrays (call this numPerms), you can create a function getPermutation(n) that returns a unique permutation between index 0 and numPerms - 1 by calculating the indices it needs to retrieve its characters from, based on n.
How is this done? If you think of creating permutations on arrays each containing: [0, 1, 2, ... 9] it's very simple... the 245th permutation (n=245) is "245", rather intuitively, or:
arrayHundreds[Math.floor(n / 100) % 10]
+ arrayTens[Math.floor(n / 10) % 10]
+ arrayOnes[Math.floor(n / 1) % 10]
The complication in your problem is that array sizes differ. We can work around this by replacing the n/100, n/10, etc... with other divisors. We can easily pre-calculate an array of divisors for this purpose. In the above example, the divisor of 100 was equal to arrayTens.length * arrayOnes.length. Therefore we can calculate the divisor for a given array to be the product of the lengths of the remaining arrays. The very last array always has a divisor of 1. Also, instead of modding by 10, we mod by the length of the current array.
Example code is below:
var allArrays = [first, second, third, ...];
// Pre-calculate divisors
var divisors = [];
for (var i = allArrays.length - 1; i >= 0; i--) {
divisors[i] = divisors[i + 1] ? divisors[i + 1] * allArrays[i + 1].length : 1;
}
function getPermutation(n) {
var result = "", curArray;
for (var i = 0; i < allArrays.length; i++) {
curArray = allArrays[i];
result += curArray[Math.floor(n / divisors[i]) % curArray.length];
}
return result;
}
Provided answers looks too difficult for me. So my solution is:
var allArrays = new Array(['a', 'b'], ['c', 'z'], ['d', 'e', 'f']);
function getPermutation(array, prefix) {
prefix = prefix || '';
if (!array.length) {
return prefix;
}
var result = array[0].reduce(function(result, value) {
return result.concat(getPermutation(array.slice(1), prefix + value));
}, []);
return result;
}
console.log(getPermutation(allArrays));
You could take a single line approach by generating a cartesian product.
result = items.reduce(
(a, b) => a.reduce(
(r, v) => r.concat(b.map(w => [].concat(v, w))),
[]
)
);
var items = [['a', 'b', 'c', 'd'], ['e'], ['f', 'g', 'h', 'i', 'j']],
result = items.reduce((a, b) => a.reduce((r, v) => r.concat(b.map(w => [].concat(v, w))), []));
console.log(result.map(a => a.join(' ')));
.as-console-wrapper { max-height: 100% !important; top: 0; }
Copy of le_m's Answer to take Array of Arrays directly:
function *combinations(arrOfArr) {
let [head, ...tail] = arrOfArr
let remainder = tail.length ? combinations(tail) : [[]];
for (let r of remainder) for (let h of head) yield [h, ...r];
}
Hope it saves someone's time.
You can use a typical backtracking:
function cartesianProductConcatenate(arr) {
var data = new Array(arr.length);
return (function* recursive(pos) {
if(pos === arr.length) yield data.join('');
else for(var i=0; i<arr[pos].length; ++i) {
data[pos] = arr[pos][i];
yield* recursive(pos+1);
}
})(0);
}
I used generator functions to avoid allocating all the results simultaneously, but if you want you can
[...cartesianProductConcatenate([['a', 'b'], ['c', 'z'], ['d', 'e', 'f']])];
// ["acd","ace","acf","azd","aze","azf","bcd","bce","bcf","bzd","bze","bzf"]
Easiest way to find the Combinations
const arr1= [ 'a', 'b', 'c', 'd' ];
const arr2= [ '1', '2', '3' ];
const arr3= [ 'x', 'y', ];
const all = [arr1, arr2, arr3];
const output = all.reduce((acc, cu) => {
let ret = [];
acc.map(obj => {
cu.map(obj_1 => {
ret.push(obj + '-' + obj_1)
});
});
return ret;
})
console.log(output);
If you're looking for a flow-compatible function that can handle two dimensional arrays with any item type, you can use the function below.
const getUniqueCombinations = <T>(items : Array<Array<T>>, prepend : Array<T> = []) : Array<Array<T>> => {
if(!items || items.length === 0) return [prepend];
let out = [];
for(let i = 0; i < items[0].length; i++){
out = [...out, ...getUniqueCombinations(items.slice(1), [...prepend, items[0][i]])];
}
return out;
}
A visualisation of the operation:
in:
[
[Obj1, Obj2, Obj3],
[Obj4, Obj5],
[Obj6, Obj7]
]
out:
[
[Obj1, Obj4, Obj6 ],
[Obj1, Obj4, Obj7 ],
[Obj1, Obj5, Obj6 ],
[Obj1, Obj5, Obj7 ],
[Obj2, Obj4, Obj6 ],
[Obj2, Obj4, Obj7 ],
[Obj2, Obj5, Obj6 ],
[Obj2, Obj5, Obj7 ],
[Obj3, Obj4, Obj6 ],
[Obj3, Obj4, Obj7 ],
[Obj3, Obj5, Obj6 ],
[Obj3, Obj5, Obj7 ]
]
You could create a 2D array and reduce it. Then use flatMap to create combinations of strings in the accumulator array and the current array being iterated and concatenate them.
const data = [ ['a', 'b', 'c', 'd'], ['e'], ['f', 'g', 'h', 'i', 'j'] ]
const output = data.reduce((acc, cur) => acc.flatMap(c => cur.map(n => c + n)) )
console.log(output)
2021 version of David Tang's great answer
Also inspired with Neil Mountford's answer
const getAllCombinations = (arraysToCombine) => {
const divisors = [];
let permsCount = 1;
for (let i = arraysToCombine.length - 1; i >= 0; i--) {
divisors[i] = divisors[i + 1] ? divisors[i + 1] * arraysToCombine[i + 1].length : 1;
permsCount *= (arraysToCombine[i].length || 1);
}
const getCombination = (n, arrays, divisors) => arrays.reduce((acc, arr, i) => {
acc.push(arr[Math.floor(n / divisors[i]) % arr.length]);
return acc;
}, []);
const combinations = [];
for (let i = 0; i < permsCount; i++) {
combinations.push(getCombination(i, arraysToCombine, divisors));
}
return combinations;
};
console.log(getAllCombinations([['a', 'b'], ['c', 'z'], ['d', 'e', 'f']]));
Benchmarks: https://jsbench.me/gdkmxhm36d/1
Here's a version adapted from the above couple of answers, that produces the results in the order specified in the OP, and returns strings instead of arrays:
function *cartesianProduct(...arrays) {
if (!arrays.length) yield [];
else {
const [tail, ...head] = arrays.reverse();
const beginning = cartesianProduct(...head.reverse());
for (let b of beginning) for (let t of tail) yield b + t;
}
}
const first = ['a', 'b', 'c', 'd'];
const second = ['e'];
const third = ['f', 'g', 'h', 'i', 'j'];
console.log([...cartesianProduct(first, second, third)])
You could use this function too:
const result = (arrayOfArrays) => arrayOfArrays.reduce((t, i) => { let ac = []; for (const ti of t) { for (const ii of i) { ac.push(ti + '/' + ii) } } return ac })
result([['a', 'b', 'c', 'd'], ['e'], ['f', 'g', 'h', 'i', 'j']])
// which will output [ 'a/e/f', 'a/e/g', 'a/e/h','a/e/i','a/e/j','b/e/f','b/e/g','b/e/h','b/e/i','b/e/j','c/e/f','c/e/g','c/e/h','c/e/i','c/e/j','d/e/f','d/e/g','d/e/h','d/e/i','d/e/j']
Of course you can remove the + '/' in ac.push(ti + '/' + ii) to eliminate the slash from the final result. And you can replace those for (... of ...) with forEach functions (plus respective semicolon before return ac), whatever of those you are more comfortable with.
An array approach without recursion:
const combinations = [['1', '2', '3'], ['4', '5', '6'], ['7', '8']];
let outputCombinations = combinations[0]
combinations.slice(1).forEach(row => {
outputCombinations = outputCombinations.reduce((acc, existing) =>
acc.concat(row.map(item => existing + item))
, []);
});
console.log(outputCombinations);
let arr1 = [`a`, `b`, `c`];
let arr2 = [`p`, `q`, `r`];
let arr3 = [`x`, `y`, `z`];
let result = [];
arr1.forEach(e1 => {
arr2.forEach(e2 => {
arr3.forEach(e3 => {
result[result.length] = e1 + e2 + e3;
});
});
});
console.log(result);
/*
output:
[
'apx', 'apy', 'apz', 'aqx',
'aqy', 'aqz', 'arx', 'ary',
'arz', 'bpx', 'bpy', 'bpz',
'bqx', 'bqy', 'bqz', 'brx',
'bry', 'brz', 'cpx', 'cpy',
'cpz', 'cqx', 'cqy', 'cqz',
'crx', 'cry', 'crz'
]
*/
A solution without recursion, which also includes a function to retrieve a single combination by its id:
function getCombination(data, i) {
return data.map(group => {
let choice = group[i % group.length]
i = (i / group.length) | 0;
return choice;
});
}
function* combinations(data) {
let count = data.reduce((sum, {length}) => sum * length, 1);
for (let i = 0; i < count; i++) {
yield getCombination(data, i);
}
}
let data = [['a', 'b', 'c', 'd'], ['e'], ['f', 'g', 'h', 'i', 'j']];
for (let combination of combinations(data)) {
console.log(...combination);
}

Categories