Skip to content

Instantly share code, notes, and snippets.

@alenthomas
Last active September 19, 2017 20:31
Show Gist options
  • Save alenthomas/7fa7eedf67e44730a60c49b4b7b61eb7 to your computer and use it in GitHub Desktop.
Save alenthomas/7fa7eedf67e44730a60c49b4b7b61eb7 to your computer and use it in GitHub Desktop.
A function which takes an array(ary) and an array of indexes(< ary.length) and sets 'X' for the for ary[indexes] else sets 'O'
// in js using for-loop
function swap(ary, indexes) {
var visited = [];
var newAry = Array(ary.length).fill(null);
for(let i=0; i<indexes.length; i++) {
newAry[indexes[i]] = 'X';
visited.push(indexes[i]);
}
for(let i=0; i<newAry.length; i++) {
if(newAry[i] === null) {
newAry[i] = 'O';
}
}
return newAry;
}
// in js using map and filter
let swapp = (ary, indexes) => {
let newAry = ary.map((aryX, aryI) => {
let filVal = indexes.filter((indexesX) => {
return indexesX === aryI ? true : false;
});
return filVal[0] === undefined ? 'O' : 'X';
});
return newAry;
}
// using python list comprehensions
['X' if index in indexes else 'O' for index, element in enumerate(ary)]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment