iterative process from SICP :)
Θ(n) steps and Θ(1) memory.
function factorial(n) { return factIter(1, 1, n) } function factIter(product, counter, max) { if (counter > max) { return product; } else { return factIter((counter * product), (counter + 1), max) } }
function factorial (n) {if (n === 0 || n === 1) {return 1;- function factorial(n) {
- return factIter(1, 1, n)
- }
- function factIter(product, counter, max) {
- if (counter > max) {
- return product;
- } else {
return n * factorial(n - 1);- return factIter((counter * product), (counter + 1), max)
- }
- }
factorial with stack, for big int
function factorial (n) { const stack = [[n, 1]]; while (stack.length > 0) { const [curr, result] = stack.pop(); if(curr === 0 || curr === 1) { return result; } stack.push([curr - 1, result * curr]); } }
- function factorial (n) {
if (n === 0 || n === 1) {return 1;} else {return n * factorial(n - 1);- const stack = [[n, 1]];
- while (stack.length > 0) {
- const [curr, result] = stack.pop();
- if(curr === 0 || curr === 1) {
- return result;
- }
- stack.push([curr - 1, result * curr]);
- }
- }
It's binarySearch implementation on JS. This returns the index number that contains the value. If the value is not in the array, it will return -1
function binarySearch(arr, el) {
let left = -1;
let right = arr.length;
while (right - left > 1) {
const mid = Math.floor((left + right) / 2);
if (arr[mid] === el) {
return mid;
}
if (arr[mid] > el) {
right = mid;
} else {
left = mid;
}
}
return -1;
}
const chai = require("chai");
const assert = chai.assert;
describe("Solution", function() {
it("return index of searching element", function() {
assert.strictEqual(binarySearch([1, 2, 3, 4, 5, 6, 7], 4), 3);
assert.strictEqual(binarySearch([1, 2, 3, 4, 5, 6, 7], 2), 1);
assert.strictEqual(binarySearch([1, 2, 3, 4, 5, 6, 7], 8), -1);
});
});
:)
Hi! This is a recursive factorial function)
function insertionSort(arr) { function sortingValues(a, b) { if (a > b) return 1; if (a == b) return 0; if (a < b) return -1; } return arr.sort(sortingValues); }
- function insertionSort(arr) {
// return sorted array- function sortingValues(a, b) {
- if (a > b) return 1;
- if (a == b) return 0;
- if (a < b) return -1;
- }
- return arr.sort(sortingValues);
- }