Algorithm Hacks
const table = [
[0, 0],
[0, 1],
[1, 0],
[1, 1]
];
const singleColumnTable = [0, 1];
const binaryOps = {
"AND": (a, b) => a & b,
"OR": (a, b) => a | b,
"XOR": (a, b) => a ^ b,
}
const unaryOps = {
"NOT": (a) => +!a
}
let s = ""
for (const [op, fn] of Object.entries(binaryOps)) {
s += `<h1>${op}</h1>\n`
for (const [a, b] of table) {
s += `<p>${a} ${op} ${b} = ${fn(a, b)}</p>\n`
}
}
for (const [op, fn] of Object.entries(unaryOps)) {
s += `<h1>${op}</h1>\n`
for (const a of singleColumnTable) {
s += `<p>${op} ${a} = ${fn(a)}</p>\n`
}
}
document.getElementById("table").innerHTML = s;
const binaryString = "11101011101";
const hexValue = (bin) => parseInt(bin, 2).toString(16);
const decValue = (bin) => parseInt(bin, 2).toString(10);
console.log(hexValue(binaryString));
console.log(decValue(binaryString));
binaryString = "11101011101"
def hexValue(bin):
return hex(int(bin, 2))
def decValue(bin):
return str(int(bin, 2))
print(hexValue(binaryString))
print(decValue(binaryString))
const fib = (n) => {
if (n === 0 || n === 1) return n
return fib(n - 1) + fib(n - 2)
}
for (let i = 0; i< 10; i++) {
console.log(fib(i))
}
def fib(n):
if n == 0 or n == 1:
return n
return fib(n - 1) + fib(n - 2)
for i in range(10):
print(fib(i))
const revString = (str) => str.split("").reverse().join("")
const isPalindrome = (str) => str === revString(str.split("").reverse().join(""));
const createPalindrome = (str) => str + revString(str)
console.log(revString("abcd"))
console.log(isPalindrome("abba"))
console.log(createPalindrome("abcdef"))
def rev_string(str):
return str[::-1]
def is_palindrome(str):
return rev_string(str) == str
def create_palindrome(str):
return str + rev_string(str)
print(rev_string("abcd"))
print(is_palindrome("abba"))
print(create_palindrome("abcdef"))
const binarySearch1 = (xs, x, start, end) => {
if (start > end) return -1;
const mid = Math.floor((start+end) / 2);
if (xs[mid] === x) return mid;
if (xs[mid] > x) return binarySearch1(xs, x, start, mid-1);
if (xs[mid] < x) return binarySearch1(xs, x, mid+1, end);
}
const binarySearch = (xs, x) => binarySearch1(xs, x, 0, xs.length - 1)
const arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
const needle = 4
console.log(`found ${needle} at idx ${binarySearch(arr, needle)}`)
import math
def binary_search1(xs, x, start, end):
if start > end: return -1
mid = math.floor((start + end) / 2)
if xs[mid] == x: return mid
if xs[mid] > x: return binary_search1(xs, x, start, mid-1)
if xs[mid] < x: return binary_search1(xs, x, mid+1, end)
def binary_search(xs, x):
return binary_search1(xs, x, 0, len(xs) - 1)
arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
needle = 4
print("found {} at idx {}".format(needle, binary_search(arr, needle)))