Loading...
More JavaScript Posts
// Orconst randomColor = () => `#${(~~(Math.random()*(1<<24))).toString(16)}`;console.log(randomColor);
let nums = [1,2,3,1]var containsDuplicate = function(nums) {let obj = {};for(let i =0; i< nums.length; i++){if(obj[nums[i]]){obj[nums[i]] += 1;return true;}else{obj[nums[i]] = 1;}}return false;};console.log(containsDuplicate(nums));
const binarySearch = (arr, item) => {let l = 0,r = arr.length - 1;while (l <= r) {const mid = Math.floor((l + r) / 2);const guess = arr[mid];if (guess === item) return mid;if (guess > item) r = mid - 1;else l = mid + 1;}return -1;};binarySearch([1, 2, 3, 4, 5], 1); // 0binarySearch([1, 2, 3, 4, 5], 5); // 4binarySearch([1, 2, 3, 4, 5], 6); // -1
class SequentialQueue{ //if you want it to go backwards, too badnext(){return this.i++;}constructor(start = 0){this.i = start;}}const que = new SequentialQueue(0);for(let i = 0; i < 10; i++){console.log(que.next());}
//QM Helper by Leif Messinger//Groups numbers by number of bits and shows their binary representations.//To be used on x.comconst minterms = prompt("Enter your minterms separated by commas").split(",").map(x => parseInt(x.trim()));const maxNumBits = minterms.reduce(function(a, b) {return Math.max(a, Math.log2(b));});const bitGroups = [];for(let i = 0; i < maxNumBits; ++i){bitGroups.push([]);}for(const minterm of minterms){let outputString = (minterm+" ");//Count the bitslet count = 0;for (var i = maxNumBits; i >= 0; --i) {if((minterm >> i) & 1){++count;outputString += "1";}else{outputString += "0";}}bitGroups[count].push(outputString);}document.body.textContent = "";document.body.style.setProperty("white-space", "pre");for(const group of bitGroups){for(const outputString of group){document.body.textContent += outputString + "\r\n";}}
/*** @param {number[]} nums* @return {number[]}*/var productExceptSelf = function(nums) {var output = [];var leftMult = 1;var rightMult = 1;for (var i=nums.length - 1; i >= 0; i--) {output[i] = rightMult;rightMult *= nums[i];console.log({output: JSON.stringify(output), i})}for (var j=0; j < nums.length; j++) {output[j] *= leftMult;leftMult *= nums[j];console.log({output: JSON.stringify(output), j})}return output;};console.log(productExceptSelf([1, 2, 3, 4]))