Skip to content

Instantly share code, notes, and snippets.

@cagataycali
Last active November 7, 2021 13:29
Show Gist options
  • Select an option

  • Save cagataycali/5aee66cac454795fef98e1cc5aa63d90 to your computer and use it in GitHub Desktop.

Select an option

Save cagataycali/5aee66cac454795fef98e1cc5aa63d90 to your computer and use it in GitHub Desktop.
[JavaScript] Max compartment finding
const assert = require("assert");
// S is a compartment.
// * is an Item
// We want to count how many item exists in closed compartment.
// Closed compartment means in range like as;
// s = "*|*|*|***|";
// 1, 3 => *|* = any item exists in closed compartment
// 1, 5 => *|*|*|* = 1 item exists in closed compartment.
function numberOfItems(s, startIndicies /* [1, 1] */, endIndicies /* [3, 10] */) {
let calculated = []
// console.log("INPUT: ", s, startIndicies, endIndicies)
/* S = *|*|*|***|*|*|*|***|*|*|*|***|*|*|*|***|*|*|*|***|*|*|*|***| */
for (let i = 0; i < startIndicies.length; i++) {
const sub = s.substr(startIndicies[i] - 1, endIndicies[i]);
let left = 0, right = sub.length;
while (left != sub.length && sub[left] != "|")
left++;
while (right != 0 && sub[right] != "|")
right--;
// console.log("SUB: ", sub, sub.length)
// console.log("RANGE: ", left, right)
let count = 0
while (left != right)
count += (sub[left++] == "*")
// console.log("COUNT: ", count)
calculated.push(count)
}
return calculated;
}
var s = "*|*|*|***|";
var startIndices = [1, 1];
var endIndices = [3, 10];
var expected = [0, 5];
assert.deepStrictEqual(numberOfItems(s, startIndices, endIndices), expected);
var s = "*|*|**|**|*|*|**|**|*|*|**|**|*|*|**|**|";
var startIndices = [1, 22, 5, 6, 7];
var endIndices = [5, 25, 14, 29, 8];
var expected = [1, 11, 6, 16, 4];
assert.deepStrictEqual(numberOfItems(s, startIndices, endIndices), expected);
s = "*|*|**|**|*|*|**|**|*|*|**|**|*|*|**|**|";
var startIndices = [1, 22, 5, 6, 7];
var endIndices = [5, 25, 14, 29, 8];
var expected = [1, 11, 6, 16, 4];
assert.deepStrictEqual(numberOfItems(s, startIndices, endIndices), expected);
s = "";
var startIndices = [1];
var endIndices = [999999999999999999999999999999999];
var expected = [0];
assert.deepStrictEqual(numberOfItems(s, startIndices, endIndices), expected);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment