Last active
November 13, 2021 20:29
-
-
Save captain-yossarian/1ea79f96206172ca4e5e8522ed98e267 to your computer and use it in GitHub Desktop.
permutations, bit manipulations
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// string permutation | |
function permut(str: string): string[] | string { | |
if (str.length === 1) { | |
return str | |
} | |
let result: string[] = []; | |
for (let i = 0; i < str.length; i++) { | |
const char = str[i]; // a | |
const remaining = str.slice(0, i) + str.slice(i + 1, str.length) | |
for (const subPermutation of permut(remaining)) { | |
result.push(char + subPermutation) | |
} | |
} | |
return result; | |
} | |
// BIT MASK | |
enum Mask { | |
edit = 1 << 1, | |
update = 1 << 2, | |
remove = 1 << 3 | |
} | |
const admin = | |
Mask.edit | |
| Mask.update | |
| Mask.remove | |
const user = | |
Mask.edit | |
| Mask.update | |
const result = user & Mask.edit | |
const isBitSet=(num: number, nth: number) => num & 1 << nth; | |
const subset = (set: number[]): any => { | |
let allsubsets: number[][] = [] | |
let max = 1 << set.length; | |
for (let k = 0; k < max; k++) { | |
let subset: number[] = convertIntToSet(k, set); | |
allsubsets.push(subset) | |
} | |
return allsubsets | |
} | |
const convertIntToSet = (x: number, set: number[]) => { | |
let subset: number[] = []; | |
let index = 0; | |
for (let k = x; k > 0; k >>= 1) { | |
if ((k & 1) == 1) { | |
subset.push(set[index]) | |
} | |
index++ | |
} | |
return subset | |
} | |
console.log(subset([1, 2, 3, 4])) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment