0

I have a problem similar to someone elses - however, its slightly different and I could use some help.

I have two arrays:

var array1=["A","B","C"];
var array2=["1","2"];

Please note they can be of different sizes. How can I produce another array to contain every UNIQUE set of the combined arrays above, so that the elements of each array do not repeat for the set as follows?

var combos=[
   ["A1","B2"],
   ["A1","C2"],
   ["B1","C2"],
   ["A2","B1"],
   ["A2","C1"],
   ["B2","C1"]
]

note: ["C1","A2"] (and similar) is a repeat and would not be included in the set.

furthermore -> if array2=["1","2","3"]

then

var combos=[
   [A1, B2, C3],
   [A1, B3, C2],
   [A2, B1, C3],
   [A2, B3, C1],
   [A3, B1, C2],
   [A3, B2, C1]
]

I believe this is a form of permutation, but I need help in how to implement the set merge in node.js. Thanks in advance!

Dolph
  • 1
  • 1

1 Answers1

0

I made something in Rust that can do this, however it's only with a numerical list. [[0, 0], [0, 1], [1, 0], [1, 1]] and it's horribly slow, I hope it helps though!

fn add_unique(combos: &mut Vec<Vec<u8>>, val: &mut [u8]) -> bool {
    if !combos.contains(&val.iter().cloned().collect()) {
        println!("Size: {:>5} || Adding: {:?}", combos.len(), val);
        combos.push(Vec::from(val));
        true
    } else {
        false
    }
}

fn main() {
    let mut all_combos: Vec<Vec<u8>> = Vec::new();
    let max_check: usize = 5;

    for _ in 0..max_check.pow(2) {
        let mut push = [0u8; 2];
        let mut unique_added = false;

        for val in 0..push.len() {
            for i in 0..max_check {
                push[val] = i as u8;

                for other in 0..push.len() {
                    if other == val {
                        continue;
                    }

                    for i in 0..max_check {
                        push[other] = i as u8;

                        unique_added = add_unique(&mut all_combos, &mut push);

                        if unique_added {
                            push = [0u8; 2];
                            break;
                        }
                    }

                    if unique_added {
                        break;
                    }
                }

                if unique_added {
                    break;
                }
            }
        }
    }

    println!("{:?}", all_combos);
}
  • Hey Luna! I actually figured it out myself and coded it accordingly. Thanks for your response! – Dolph Dec 14 '20 at 04:49