checking pair value in array - javascript

here i wanna ask about how to check the data in the array if not same value/data on next index, push it on new array,
here is the example:
function check(arr){
let text = "";
let newArr = [];
for(let i = 0 ; i < arr.length-1 ; i++){
if(arr[i] !== arr[i+1]){
text = arr[i] + ' and ' + arr[i+1];
newArr.push(text)
}
}
return newArr
};
console.log(check([ 'A', 'A', 'M', 'Y', 'I', 'W', 'W', 'M', 'R', 'Y' ]))
// output "A and M", "A and Y", "I and W", "W and M", "R and Y"]
console.log(check([ 'a', 'b', 'j', 'j', 'i', 't' ]))
my result here is not i want, it was repeated the data which i already push . in newArr
i want the ouput like this :
["A and M", "A and Y", "I and W", "W and M", "R and Y"]
because of each array not the same initial,
i hope this question makes sense

You can do the following :
function check(arr) {
let text = "";
let newArr = [];
for (let i = 0, next = 0; i < arr.length; i++) {
if (next == 2) {
next = 0;
i += 2;
}
if (arr[i + 1] !== undefined) {
if (arr[i + 2] !== undefined) {
text = arr[i] + ' and ' + arr[i + 2];
} else {
text = arr[i] + ' and ' + arr[i + 1];
}
newArr.push(text)
}
next += 1;
}
return newArr
};
console.log(check(['A', 'A', 'M', 'Y', 'I', 'W', 'W', 'M', 'R', 'Y']))
console.log(check(['a', 'b', 'j', 'j', 'i', 't']))

Related

Grab elements from array using indexes of another array

I am working on a Codewars problem and have been able to solve the majority of this problem except the final part. The challenge is "rot13"
ROT13 is a simple letter substitution cipher that replaces a letter with the letter 13 letters after it in the alphabet. ROT13 is an example of the Caesar cipher. Create a function that takes a string and returns the string ciphered with Rot13.
function rot13(message){
message = message.split('');
let alphabet = ['a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z'];
let indexes = message.map(char => alphabet.indexOf(char));
let result = indexes.map(i => {
let val = i + 13;
let max = 26;
if (val > max) {
let temp = val - max;
val = temp;
}
return val;
});
//result = [6, 17, 5, 6];
//i want to use the elements in my result array, and
//grab the letters from my alphabet array whose indexes associate with those elements from my result array
}
rot13('test') // 'grfg'
This is my current state in this problem. I have tried checking if any of the indexes of the elements in alphabet === the elements in my result array and if so, pushing those characters from the my alphabet array into an empty array but I am receiving -1
Any suggestions for approaching this problem/altering my thought process will be helpful. Thanks!
To answer your question directly, you can just add:
return results.map(i => alphabet[i]).join('')
at the end of the function.
As a side note, instead of having an array of letters you can utilize the String.fromCharCode function. It translates a number into ASCII char equivalent (capital letters start at 65).
function rot13(message){
message = message.split('');
let alphabet = ['a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z'];
let indexes = message.map(char => alphabet.indexOf(char));
let result = indexes.map(i => {
let val = i + 13;
let max = 26;
if (val > max) {
let temp = val - max;
val = temp;
}
return val;
});
return result.map(i => alphabet[i]).join('');
}
console.log(rot13('test')) // 'grfg'
Use another map() to convert result back to characters by indexing alphabet. Then use join('') to make it a string. Then return it to the caller.
You can simplify the ROT13 calculation using modulus.
function rot13(message) {
message = message.split('');
let alphabet = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z'];
let indexes = message.map(char => alphabet.indexOf(char));
let result = indexes.map(i => {
let val = (i + 13) % 26;
return val;
});
return result.map(i => alphabet[i]).join('');
}
console.log(rot13('test'));
Note that this will only work correctly if the string only contains lowercase letters. Anything else will return -1 from indexOf, and you'll need to check for that.
Try this
function rot13(message) {
message = message.split('');
let alphabet = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z'];
return message.map(char => {
let i = alphabet.indexOf(char);
i = (i + 13) % alphabet.length;
return alphabet[i];
}).join("");
}
console.log(rot13('test')); // 'grfg'
Try this:
function rot13(message){
message = message.split('');
let finalResult = "";
const alphabet = ['a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z'];
message.forEach(item => {
const index = alphabet.indexOf(item);
let cipherIndex = index + 13;
if(cipherIndex > 25)
cipherIndex = index - 13
finalResult = finalResult + alphabet[cipherIndex]
})
return finalResult;
}

Can anyone see mistake in this javascript code? Filling 2D array

The issue with my code is that it should return 26x26 matrix filled with a-z on every row, although I tried many ways to initialize or fill the matrix, I always got error or matrix filled with empty strings(current code state).
Can somebody help me? In other words I need function fill2DMatrix() to return matrix where every row contains letters from initArray, so far it doesn't change values and stays as empty Array
<script>
var rawInput = document.getElementById("input");
var initArray = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z'];
/* Returns filled alphabet 2D array */
function init2DMatrix() {
var twoDimArr = [];
for (i = 0; i < 26; i++) {
twoDimArr[i] = "";
for(j = 0; j < 26; j++){
twoDimArr[i][j] = "";
}
}
return twoDimArr;
}
function fill2DMatrix() {
var counter = 0;
var blankSpacesArr = [];
blankSpacesArr = init2DMatrix();
for (var i = 0; i < 26; i++) {
for(var j = 0; j < 26; j++){
blankSpacesArr[i][j] = initArray[j];
}
}
return blankSpacesArr;
}
function print() {
var beaufortMatrix = fill2DMatrix();
for (i = 0; i < initArray.length; i++) {
document.getElementById("output").innerHTML += beaufortMatrix[i] + "<br>";
}
}
</script>
Please Try like this.
function init2DMatrix()
{
var arr = [];
for (var i=0; i<26; i++) {
arr[i] = [];
}
return arr;
}
function fill2DMatrix() {
var blankSpacesArr = [];
blankSpacesArr = init2DMatrix();
for (var i = 0; i < 26; i++) {
for(var j = 0; j < 26; j++){
blankSpacesArr[i][j] = initArray[j];
}
}
return blankSpacesArr;
}
You already have a array of 26 alphabets. All you need to do is loop it 26 times into a new array.
Try this -
var initArray = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z'];
var myarray=new Array(26)
for (i=0; i <26; i++) {
myarray[i]=new Array(initArray);
}
console.log(myarray);

Finding every second element in a repeating pattern

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; }

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;

Implementing MergeSort on an array of two-element arrays in JavaScript

I'm trying to use merge sort to sort an array of edge sets, which themselves are represented as 2-element arrays, i.e. the edge EC is ['E', 'C'].
The array I'm trying to sort is [['D', 'F'], ['A', 'D'], ['F', 'I'], ['B', 'E'], ['B', 'J'], ['A', 'C'], ['E', 'G'], ['A', 'J'], ['G', 'H']]. And I want it to sort by the 'from' edge first, and then if two edges have the same 'from' edge, by the 'to' (second) edge.
When I run the following in Firebug, it looks like it's working (from the things I'm printing to the console), but then at the end it gives ['AC', 'AC', 'AC', 'AC', 'AC', ...].
Array.prototype.toString = function(){
var s = "[";
if(this.length > 0){
s += this[0].toString();
for(var i = 1; i < this.length; i++){
s += ", " + this[i].toString();
}
}
s += "]";
return s;
}
var edges = [['D', 'F'], ['A', 'D'], ['F', 'I'], ['B', 'E'], ['B', 'J'],
['A', 'C'], ['E', 'G'], ['A', 'J'], ['G', 'H']];
function sortEdges(edges){
// mergesort
// split up
if(edges.length < 2){
return edges;
} else {
var fH = edges.slice(0, Math.floor(edges.length / 2)); // fH: firstHalf
var sH = edges.slice(Math.floor(edges.length / 2), edges.length); // sH: firstHalf
console.log(fH.toString());
console.log(sH.toString());
fH = sortEdges(fH);
sH = sortEdges(sH);
// merge
var fHC = 0; // fHC: firstHalfCounter
var sHC = 0; // sHC: secondHalfCounter
var bothHalves = new Array();
for(var i = 0; i < edges.length; i++){
console.log("fHC: " + fHC + ", sHC: " + sHC + ", bothHalves: " + bothHalves.toString());
if(fHC < fH.length && (sHC >= sH.length || fH[fHC][0] < sH[sHC][0])){
// compare 'from' vertex
bothHalves.push(fH[fHC]);
fHC++;
} else if(fHC < fH.length && fH[fHC][0] == sH[sHC][0]){
// if tied, compare 'to' vertex
if(fH[fHC][1] <= sH[sHC][1]){
bothHalves.push(fH[fHC]);
fHC++;
} else {
bothHalves.push(sH[sHC]);
sHC;
}
} else {
bothHalves.push(sH[sHC]);
sHC++;
}
}
return bothHalves;
}
}
edges = sortEdges(edges);
console.log(edges.toString());
You left out an increment:
Array.prototype.toString = function(){
var s = "[";
if(this.length > 0){
s += this[0].toString();
for(var i = 1; i < this.length; i++){
s += ", " + this[i].toString();
}
}
s += "]";
return s;
}
var edges = [['D', 'F'], ['A', 'D'], ['F', 'I'], ['B', 'E'], ['B', 'J'],
['A', 'C'], ['E', 'G'], ['A', 'J'], ['G', 'H']];
function sortEdges(edges){
// mergesort
// split up
if(edges.length < 2){
return edges;
} else {
var fH = edges.slice(0, Math.floor(edges.length / 2)); // fH: firstHalf
var sH = edges.slice(Math.floor(edges.length / 2), edges.length); // sH: firstHalf
console.log(fH.toString());
console.log(sH.toString());
fH = sortEdges(fH);
sH = sortEdges(sH);
// merge
var fHC = 0; // fHC: firstHalfCounter
var sHC = 0; // sHC: secondHalfCounter
var bothHalves = new Array();
for(var i = 0; i < edges.length; i++){
console.log("fHC: " + fHC + ", sHC: " + sHC + ", bothHalves: " + bothHalves.toString());
if(fHC < fH.length && (sHC >= sH.length || fH[fHC][0] < sH[sHC][0])){
// compare 'from' vertex
bothHalves.push(fH[fHC]);
fHC++;
} else if(fHC < fH.length && fH[fHC][0] == sH[sHC][0]){
// if tied, compare 'to' vertex
if(fH[fHC][1] <= sH[sHC][1]){
bothHalves.push(fH[fHC]);
fHC++;
} else {
bothHalves.push(sH[sHC]);
sHC++;
// ^^ You left out this increment <--------------HERE----------------
}
} else {
bothHalves.push(sH[sHC]);
sHC++;
}
}
return bothHalves;
}
}
edges = sortEdges(edges);
console.log(edges.toString());

Categories