The Immortal
The Immortal

Reputation: 83

Checking if each element of array is in multiple arrays

I am having difficulty coming with a solution for this.

Lets say there are 6 arrays of colors with 1-3 colors in each, and colors can be repeated:

['white', 'blue']
['green', 'yellow']
['black']
['yellow', 'blue', 'pink']
['orange', 'red']
['brown', 'white']

And a user inputs 6 colors, for example: white, blue, pink, black, orange, yellow. How do I check that all of those colors are part of the arrays AND all of them can be chosen, assuming only one can be chosen from each array.

I hope my question is understandable.

EDIT: rephrasing the question

there are 6 arrays of colors, as seen above and the user has to select 1 from each array. how do i check that the user's input is correct, assuming that the order he submits it is not the order of the arrays.

Upvotes: 3

Views: 86

Answers (1)

freakish
freakish

Reputation: 56477

This looks like a job for a recursion (might not be the most efficient but definitely the easiest solution and if your data is this small it shouldn't matter):

var check = function(input, colors) {
    if (!input.length) {
        return true;
    }
    var input_color = input.pop();
    var ok = false;
    for (var i = 0; i < colors.length; i++) {
        var color = colors[i];
        if (!color) {
            break;
        }
        if (color.indexOf(input_color) !== -1) {
            colors.splice(i, 1);
            ok = check(input, colors);
            if (!ok) {
                colors.splice(i, 0, color);
            } else {
                break;
            }
        }
    }
    if (!ok) {
        input.push(input_color);
    }
    return ok;
};

and the usage:

var colors = [
  ['white', 'blue'],
  ['green', 'yellow'],
  ['black'],
  ['yellow', 'blue', 'pink'],
  ['orange', 'red'],
  ['brown', 'white']
];
check(['white', 'blue', 'pink', 'black', 'orange', 'yellow'], colors);

Note that it will alter both colors and inputs arrays (you have to make a copy of them each time you call check).

Actually this problem is pretty similar to path finding problem. And this is a brute force solution.

Upvotes: 2

Related Questions