Skip to content
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
30 changes: 29 additions & 1 deletion chapter01/1.4 - PalinPerm/palinPerm.js
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,34 @@ var palinPerm = function(string) {
return isPerm;
};

const getCharCode = (c, min = 'a'.charCodeAt(), max = 'z'.charCodeAt()) => {
cCharCode = c.charCodeAt();
return min <= cCharCode && cCharCode <= max
? cCharCode - min : -1;
};

const toggleBit = (bitVector, index) => {
if(index < 0) return bitVector;
return bitVector ^ (1 << index);
};

const getBitVector = str => {
let bitVector = 0;
for(let c of str) {
bitVector = toggleBit(bitVector, getCharCode(c));
}
return bitVector;
};

const palinPermBitVector = str => {
const bitVector = getBitVector(str);
return !(bitVector && (bitVector & (bitVector - 1)));
};

// TESTS
console.log(palinPerm('Tact Coa'), 'true');
console.log(palinPerm('Tact boa'), 'false');
console.log(palinPerm('Tact boa'), 'false');
console.log(palinPermBitVector('cviic'), 'true');
console.log(palinPermBitVector('civie'), 'false');
console.log(palinPermBitVector('damma'), 'true');
console.log(palinPermBitVector('aadmn'), 'false');