JSFiddle - React, Tailwind, and code Playground
by Tim Ko
JavaScript
// Goal: Remove min weighted cost per iteration given an array of positive integers and an integer k iterations in nlogn
function removeMinimum(vals) {
var costs = calculateCosts(vals);
var min = findMin(costs);
vals.splice(costs.indexOf(min), 1);
return vals;
}
function calculateCosts(vals) {
var costs = [];
for (var i = 0; i < vals.length; i++) {
if (i == 0 || i == vals.length-1) {
costs.push('#');
} else {
var cost = vals[i-1] + vals[i] + vals[i+1];
costs.push(cost);
}
}
return costs;
}
function findMin(costs) {
if (!costs) {
return null;
}
var min;
for (var i = 1; i < costs.length; i++) {
if (costs[i] == '#') {
continue;
} else if (!min) {
min = costs[i];
} else if (costs[i] < min) {
min = costs[i];
}
}
return min;
}
function bruteForceSolution(vals, iterations) {
var result = vals;
console.log("iterations:", 0, "result:", result);
for (var i = 0; i < iterations; i++) {
if (result.length < 3) {
break;
}
result = removeMinimum(vals);
console.log("iterations:", i + 1, "result:", result);
}
return result;
}
function buildDoublyLinkedList(vals) {
// Initialize nodes array
var nodes = vals.map((val, index) => {
return {
value: val,
index: index,
prev: null,
next: null
}
});
// Set prev and next pointers
for (var i = 0; i < nodes.length; i++) {
if (i != 0) {
nodes[i].prev = nodes[i-1];
}
if (i != nodes.length-1) {
nodes[i].next = nodes[i+1];
}
}
return nodes;
}
function buildBinarySearchTree(costs) {
var tree = {};
var insert = function(tree, val) {
var node = {
cost: val.cost,
indexes: [val.index],
left: null,
right: null
}
// find position
// if exists, add index
// if doesn't exist, remove index
//TODO
}
costs.map((cost, index) => {
return {
cost: cost,
index: index
}
}).forEach(val =>...