SumProduct multi dimensional array using mathJS - javascript

I have some working code, which I wrote a while ago, where I created my own sumProduct functions, for performing this operation on singe and multi dimensional arrays:
function sumProduct1D(m1, m2) {
var result = 0;
var len = m1.length;
for (var i = 0; i < len; i++) {
result += m1[i] * m2[i];
}
return result;
}
function sumProduct2D(m1, m2) {
var result = 0;
var len1 = m1.length;
for (var i1 = 0; i1 < len1; i1++) {
var len2 = m1[i1].length;
for (var i2 = 0; i2 < len2; i2++) {
result += m1[i1][i2] * m2[i1][i2];
}
}
return result;
}
(These functions go through both arrays multiplying associated indexes and adding the total all together - in case you're not familiar with sumProduct).
At some point I started using mathJS for some of its matrix/array manipulation methods and I realised that my sumProduct1D is the same as math.dot
var a = [1,2,3];
var b = [3,2,1];
console.log(sumProduct1D(a,b));
console.log(math.dot(a,b));
function sumProduct1D(m1, m2) {
var result = 0;
var len = m1.length;
for (var i = 0; i < len; i++) {
result += m1[i] * m2[i];
}
return result;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/mathjs/3.8.0/math.js"></script>
The above code gives the same result for mine and using math.dot - perfect!
My question is around my other method - it sums a multidimensional array, and mathJS doesnt like it - I get an error Uncaught RangeError: Vector expected.
var c = [[1,2,3],[1,2,3]];
var d = [[3,2,1],[3,2,1]];
console.log(sumProduct2D(c,d))
console.log(math.dot(c,d))
function sumProduct2D(m1, m2) {
var result = 0;
var len1 = m1.length;
for (var i1 = 0; i1 < len1; i1++) {
var len2 = m1[i1].length;
for (var i2 = 0; i2 < len2; i2++) {
result += m1[i1][i2] * m2[i1][i2];
}
}
return result;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/mathjs/3.8.0/math.js"></script>
I have had a look through the mathJS docs, and I cannot for the life of me put together the combination of calls which duplicate my sumProduct2D. But there must be a way.
Can anyone replicate my sumProduct method using mathJS functions?

In case this helps anyone else, I found the answer eventually. It was math.sum(math.dotMultiply(c,d)) I was after.
var c = [[1,2,3],[1,2,3]];
var d = [[3,2,1],[3,2,1]];
console.log(sumProduct2D(c,d))
console.log(math.sum(math.dotMultiply(c,d)))
function sumProduct2D(m1, m2) {
var result = 0;
var len1 = m1.length;
for (var i1 = 0; i1 < len1; i1++) {
var len2 = m1[i1].length;
for (var i2 = 0; i2 < len2; i2++) {
result += m1[i1][i2] * m2[i1][i2];
}
}
return result;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/mathjs/3.8.0/math.js"></script>

Related

JavaScript permutations function - why isn't this working?

I'm trying to write a function in JavaScript to generate an array of permutations of a given array by porting the code in the Python documentation for itertools.permutations. (I am aware that the actual function is written in C) This is what I have, and it outputs an array with the correct length - n!/(n-r)!, n being the length of the array - but each element is just the original array, not rearranged. I'd appreciate a fresh pair of eyes on my code, as I'm stumped:
function permutations(array, r) {
if (r === undefined) r = array.length;
if (r > array.length) return;
var indices = range(array.length);
var cycles = range(array.length, array.length - r, -1);
var result = [[]];
for (var i = 0; i < r; i++) {
result[0].push(array[i]);
}
while (1) {
var exhausted = true;
for (var i = r - 1; i >= 0; i--) {
cycles[i] -= 1;
if (cycles[i] == 0) {
indices = indices.slice(0, i).concat(
indices.slice(i + 1)
).concat([indices[i]]);
cycles[i] = array.length - i;
}
else {
var j = cycles[i];
swap(indices, i, indices.length - j);
var p = [];
for (var i = 0; i < r; i++) {
p.push(array[i]);
}
result.push(p);
exhausted = false;
break;
}
}
if (exhausted) break;
}
return result;
}
The python code has (near the bottom):
yield tuple(pool[i] for i in indices[:r])
You translated that to:
for (var i = 0; i < r; i++) {
p.push(array[i]);
}
result.push(p);
But it should be:
for (var i = 0; i < r; i++) {
p.push(array[indices[i]]);
}
result.push(p);
Without that, indices is never used, which should be a clue.

I'm having trouble adding these elements of my array together. the dash seems to inhibit the addition of each variable

I'm trying to get the following code to add each number in the element separately and not the whole array together but the dash seems to stop the loop from calculating the total sum of each element. I can't seem to make it so it'll except any length of number for the variable. Any help is greatly appreciated!
var creditNum = [];
creditNum[0] = ('4916-2600-1804-0530');
creditNum[1] = ('4779-252888-3972');
creditNum[2] = ('4252-278893-7978');
creditNum[3] = ('4556-4242-9283-2260');
var allNum = [];
var total = 0;
var num = 0;
var cnt = 0;
for (var i = 0; i < creditNum.length; i++) {
num = creditNum[i];
for (var j = 1; j <= num.length; j++) {
var num = creditNum[i].substring(cnt, j);
console.log(creditNum[i].charAt(cnt));
console.log(cnt, j);
cnt = cnt + 1;
}
if (num != "-") j = j++;
console.log(parseInt(num));
}
console.log(total);
Assuming the intent is to add '4916-2600-1804-0530' and output the value as 49, then the following modification will achieve that.
var creditNum = ['4916-2600-1804-0530', '4779-252888-3972', '4252-278893-7978','4556-4242-9283-2260'];
for (var i = 0; i < creditNum.length; i++) {
var num = creditNum[i].replace(/\-/g, '');
var total = 0;
for (var j = 0; j < num.length; j++) {
total += Number(num[j]);
}
console.log(creditNum[i], total);
}
Using native array methods, the code can be refactored as the following.
var creditNumbers = ['4916-2600-1804-0530', '4779-252888-3972', '4252-278893-7978','4556-4242-9283-2260'];
creditNumbers.forEach(function(creditNumber) {
var num = creditNumber.replace(/\-/g, '').split('');
var total = num.reduce(function(tally, val) {
return tally += Number(val);
}, 0);
console.log(creditNumber, total);
});

Sum of Primes using Sieve of Eratosthenes can't find bug

I'm working in JavaScript and this is a bit confusing because the code is returning the correct sum of primes. It is working with larger numbers. There is a bug where for 977 it returns the sum of primes for 976, which is 72179, instead of the sum for 977 which is 73156. Everything I've test so far has come back correctly.
function sumPrimes(num) {
var sum = 0;
var count = 0;
var array = [];
var upperLimit = Math.sqrt(num);
var output = [];
for (var i = 0; i < num; i++) {
array.push(true);
}
for (var j = 2; j <= upperLimit; j++) {
if (array[j]) {
for (var h = j * j; h < num; h += j) {
array[h] = false;
}
}
}
for (var k = 2; k < num; k++) {
if (array[k]) {
output.push(k);
}
}
for (var a = 0; a < output.length; a++) {
sum += output[a];
count++;
}
return sum;
}
sumPrimes(977);
The problem stems from the fact that your "seive" Array is indexed from 0, but your algorithm assumes that array[n] represents the number n.
Since you want array[n]===true to mean that n is prime, you need an Array of length 978 if you want the last item to be indexed as array[977] and mean the number 977.
The issue seems to be fixed when I change all instances of < num to < num+1.

Binary to Decimal Javascript

This code is supposed to take in a string ("100101") and output the result in decimal.I'm not quite sure why it's not working.Any help would be appreciated.
function BinaryConverter(str) {
var num=str.split("");
var powers=[];
var sum=0;
for(var i=0;i<num.length;i++){
powers.push(i);
}
for(var i=powers.length-1;i>=0;i--){
for(var j=0;j<num.length;i++){
sum+=Math.pow(2,i)*num[j];
}
}
return sum;
};
Here's my updated code below .For an input "011" it should do( 2^2*0 +2^1*1 +2^0*1)to =3 but it returns 14.Anybody know where I'm going wrong?
function BinaryConverter(str) {
var num=str.split("");
var powers=[];
var sum=0;
for(var i=0;i<num.length;i++){
powers.push(i);
}
for(var i=powers.length-1;i>=0;i--){
for(var j=0;j<num.length;j++){
sum+=Math.pow(2,i)*num[j];
}
}
return sum;
};
The two nested for loops have a problem. The first one subtracts an i, while the second adds an i forever creating a never ending loop.
ALSO your code should be this:
function BinaryConverter(str) {
var num=str.split("");
var powers=[];
var sum=0;
var numlength=num.length;
for(var i=0;i<num.length;i++){
powers.push(i);
}
for(var i=powers.length-1;i>=0;i--){
sum+=Math.pow(2,i)*num[numlength-i-1];
}
return sum;
};
I don't think you need the nested for loop
If you don't want to do that with parseInt() for some reason (like, because the homework problem says you can't), you can do this without the complexity and expense of calling Math.pow() for each digit:
function parseBinary(str) {
var i, value = 0;
for (i = 0; i < str.length; ++i)
value = value * 2 + +str[i];
return value;
}
That doesn't check for invalid input strings.
ace040686 only inverted the pow(2,i) and num[len-1-i] in his answer, otherwise it would be correct. Also you're pushing 0..str.length-1 unnecessarily to powers, those are implicit indices.
function convertNaive(str) {
var num = str.split("");
var len = num.length;
var sum = 0;
for(var i = len - 1; i >= 0; --i)
sum += Math.pow(2, len - 1 - i) * num[i];
return sum;
}
You can improve this a bit to avoid the unnecessary array and especially Math.pow:
function convertImproved(str) {
var len = str.length;
var sum = 0;
for(var i = 0, fac = 1; i < len; ++i, fac *= 2)
sum += fac * str[len - 1 - i];
return sum;
}
Try it yourself:
var input = "100101";
var logNode = document.getElementById("log");
function log(line) {
var text = document.createTextNode(line);
var node = document.createElement("p");
node.appendChild(text);
logNode.appendChild(node);
}
function convertNaive(str) {
var num = str.split("");
var len = num.length;
var sum = 0;
for(var i = len - 1; i >= 0; --i)
sum += Math.pow(2, len - 1 - i) * num[i];
return sum;
}
function convertImproved(str) {
var len = str.length;
var sum = 0;
for(var i = 0, fac = 1; i < len; ++i, fac *= 2)
sum += fac * str[len - 1 - i];
return sum;
}
log("input: " + input);
log("parseInt(input, 2): " + parseInt(input, 2));
log("convertNaive(input): " + convertNaive(input));
log("convertImproved(input): " + convertImproved(input));
<div id="log" />
Here is the simple implementation of binary to decimal in javascript.
main();
function main() {
let binaryInput = 10000100111;
let decimalOutput = binaryTodecimal(binaryInput);
console.log(decimalOutput);
}
function binaryTodecimal(input) {
let inputString = input.toString();
let result = 0;
let exponent = 1;
let currentBit = 0;
for (let i = inputString.length - 1; i >= 0; i--) {
currentBit = parseInt(inputString[i]);
currentBit *= exponent;
result += currentBit;
exponent *= 2;
}
return result;
}

detecting range overlaps in Google Calendar-Style event list

I need help fixing my existing code to accomplish what I am trying to do.
with the following sample data:
var SAMPLE_DATA = [{start: 30, end: 150}, {start: 540, end: 600}, {start: 560, end: 620}, {start: 610, end: 670}];
I need to do the following:
iterate through each sample object
determine if the current objects range (obj.start:obj.end) overlaps with any other object ranges.
record the total number of overlaps for that object into totalSlots property
determine the "index" of the object (used for it's left-to-right positioning)
mockup of what I am trying to accomplish:
As you can see in the mockup, slotIndex is used to determine the left-to-right ordering of the display. totalSlots is how many objects it shares space with (1 meaning it is the only object). 100 / totalSlots tells me how wide the square can be (i.e. totalSlots=2, means it is 100 / 2, or 50% container width).
Current Output from my code
Obj[0] slotIndex=0, totalSlots=0
Obj[1] slotIndex=1, totalSlots=1
Obj[2] slotIndex=1, totalSlots=2
Obj[3] slotIndex=0, totalSlots=1
expected/desired output from my code:
Obj[0] slotIndex=0, totalSlots=0
Obj[1] slotIndex=0, totalSlots=1
Obj[2] slotIndex=1, totalSlots=2
Obj[3] slotIndex=0, totalSlots=1
the code:
detectSlots: function(oldEventArr) {
oldEventArr.sort(this.eventSorter);
var newEventArr = [],
n = oldEventArr.length;
for (var i = 0; i < n; i++) {
var currObj = oldEventArr[i];
if ('undefined' == typeof currObj.totalSlots) {
currObj.slotIndex = 0;
currObj.totalSlots = 0;
}
for (var x = 0; x < n; x++) {
if (i == x) {
continue;
}
var nextObj = oldEventArr[x];
if (currObj.start <= nextObj.end && nextObj.start <= currObj.end) {
currObj.totalSlots++;
nextObj.slotIndex++;
}
}
newEventArr.push(currObj);
}
return newEventArr;
}
Please help me figure out what is going wrong in my code. I'm about 90% sure the problem lies in the if(currObj.start <= nextObj.end && nextObj.start <= currObj.end) statement where I am assigning/incrementing the values but I could use an extra set of eyes on this.
The slotIndex value can be calculated by using graph colouring algorithm. Note that brute force algorithm is exponential in time and will only be a viable solution for a small set of overlapping slots. Other algorithms are heuristics and you won't be guaranteed the least slot possible.
Here is an example of heuristic for your problem:
...
// init
var newEventArr = [], n = oldEventArr.length;
for (var i = 0; i < n; i+=1) {
var currObj = oldEventArr[i];
newEventArr.push({"start":currObj.start,"end":currObj.end,"slotIndex":undefined,"totalSlots":0});
}
var link = {};
// create link lists and totals
for (var i = 0; i < n; i+=1) {
var currObj = newEventArr[i];
if (!link.hasOwnProperty(""+i))
link[""+i] = {};
for (var j = i+1; j < n; j+=1) {
var nextObj = newEventArr[j];
var not_overlap = (currObj.end <= nextObj.start || nextObj.end <= currObj.start);
if (!not_overlap) {
currObj.totalSlots+=1;
nextObj.totalSlots+=1;
link[""+i][""+j] = 1;
if (!link.hasOwnProperty(""+j))
link[""+j] = {};
link[""+j][""+i] = 1;
}
}
}
var arrities = [];
for (var i = 0; i < n; i+=1) {
arrities.push( {"arrity":newEventArr[i].totalSlots, "indx":i} );
}
// sort by arrities [a better solution is using a priority queue]
for (var i = 0; i < n-1; i+=1) {
var current_arrity = -1, indx = -1;
for (var j = i; j < n; j+=1) {
if (arrities[j].arrity > current_arrity) {
indx = j;
current_arrity = arrities[j].arrity;
}
}
var temp = arrities[i];
arrities[i] = arrities[indx];
arrities[indx] = temp;
}
for (var i = 0; i < n; i+=1) {
var nodeIndex = arrities[i].indx;
// init used colors
var colors = [];
for (var j = 0; j < n; j+=1) {
colors.push(0);
}
//find used colors on links
for (var k in link[""+nodeIndex]) {
var color = newEventArr[k].slotIndex;
if (color || color === 0)
colors[color] += 1;
}
//find the first unused color
for (var j = 0; j < n; j+=1) {
if (colors[j] <= 0) {
// color the node
newEventArr[nodeIndex].slotIndex = j;
break;
}
}
}
return newEventArr;
...
like this
var not_overlap = (currObj.end <= nextObj.start || nextObj.end <= currObj.start);
if (!not_overlap) { ...
or
var overlap = (currObj.end > nextObj.start && nextObj.end < currObj.start);
if (overlap) { ...

Categories