Given 2 arrays and both have same number of elements, construct all the hashed maps and return

118 Views Asked by At

For example two arrays:

var names = ['Tom','Jerry','Sam'];
var hobbies = ['Eat','Sleep','Laugh'];

Is there a function can construct the two arrays as maps like:

{'Tome':'Eat','Jerry':'Sleep','Sam':'Laugh'}
{'Tome':'Sleep','Jerry':'Eat','Sam':'Laugh'}
{'Tome':'Laugh','Jerry':'Eat','Sam':'Laugh'}

and other 3 more... Totally as given the two arrays the returned maps number should be A33 = 6. By javascript or python any can do it. Any ideas?


After searching from web, this is an assignment problem and the way to resolve it is called Hungarian Method. Now I am looking for a Hungarian Algorithm implementation by javascript or python.

3

There are 3 best solutions below

0
On BEST ANSWER

I got an answer from this link Permutations in JavaScript?.

After that the method can be done like this:

function permute(input) {
var permArr = [],
usedChars = [];
function main(){
    var i, ch;
    for (i = 0; i < input.length; i++) {
        ch = input.splice(i, 1)[0];
        usedChars.push(ch);
        if (input.length == 0) {
            permArr.push(usedChars.slice());
        }
        main();
        input.splice(i, 0, ch);
        usedChars.pop();
    }
    return permArr;
}
return main();

}

function mapFromArrays(source,target){
var targets = permute(target);
var returns = [];

for(var t in targets){
    var map = {};
    for(var i=0;i<source.length;i++){
        map[source[i]] = targets[t][i];
    }
    returns.push(map);
}

return returns;

}

0
On

You want to map the names to every possible permutation of the second array:

from itertools import permutations

hashmaps = [dict(zip(names, perm)) for perm in permutations(hobbies)]

Note that permutations returns a list that is N! in length, which is going to be huge even with very small lengths.

0
On

well, this is not permutation, but product of 2 vectors. In Python Itertools, there's a function product can deal with this.

import itertools as itls
names = ['Tom','Jerry','Sam']
hobbies = ['Eat','Sleep','Laugh']
print list(itls.product(names, hobbies))

the result is: [('Tom', 'Eat'), ('Tom', 'Sleep'), ('Tom', 'Laugh'), ('Jerry', 'Eat'), ('Jerry', 'Sleep'), ('Jerry', 'Laugh'), ('Sam', 'Eat'), ('Sam', 'Sleep'), ('Sam', 'Laugh')]

Actually, product of 2 vectors is to do some 'op' for each one of vector1 with each one of vector2, in this case, the 'op' is to make a tuple. The product operation is equiverlent to:

for i = 0; i<length(vector1); ++i
    for j = 0; j<length(vector2); ++j
        vector1[i] 'op' vector2[j];