-1

Can anyone match this with any Algorithm problem? or what's the best way to solve this?

I have two arrays

arr1 = [A, B] 
arr2 = [1, 2]
Result: [A1, A2, B1, B2]

Scenario 2:
arr1 = [] 
arr2 = [1, 2]
Result: [1, 2]

Scenario 3:
arr1 = [A, B] 
arr2 = []
Result: [A, B]

Scenario 4:
arr1 = [] 
arr2 = []
Result: []

I have started with the below but that is not covering all the scenarios above

array1.flatMap(d => array2.map(v => d + v))  // Not covering scenario 2 and 3

Scenario 4 can be covered easily with a 0-length check in the beginning.  
Rohit
  • 51
  • 1
  • 9
  • 1
    From the [javascript tag info](https://stackoverflow.com/tags/javascript/info): "*[JavaScript] is unrelated to the Java programming language and shares only superficial similarities. ...*" – Turing85 Aug 03 '22 at 20:49
  • 1
    When you tried to solve this, what problems did you have? We're not here to do the work for you, we're here to empower your to be able to do it yourself. Please read [How to ask](https://stackoverflow.com/help/how-to-ask) and provide the details of your attempt to solve this problem. – Alex Wayne Aug 03 '22 at 20:55
  • 1
    You might wnat to start writing some algorithm and we'll help you find what's wrong. This site is not meat todo student's homework. – Matthieu Riegler Aug 03 '22 at 21:01
  • 1
    https://stackoverflow.com/questions/8936610/how-can-i-create-every-combination-possible-for-the-contents-of-two-arrays – epascarello Aug 03 '22 at 21:11

1 Answers1

1

const algorithm = (first: string[], second: number[]) => {
    const result: (string | number)[] = [];
    const max = Math.max(first.length, second.length);
    for(let i = 0; i < max; i++) {
        const fromFrist = first[i];
        const fromSecond = second[i];

        // Don't convert number to string if we have only number
        result.push(fromFrist ? `${fromFrist}${fromSecond ?? ''}` : fromSecond);
    }
    return result;
}

console.log(algorithm(["A", "B"], [1, 2])); // ["A1", "B1"]
console.log(algorithm([], [1, 2]));  // [1, 2]
console.log(algorithm(["A", "B"], [])); // ["A", "B"]
console.log(algorithm([], [])); // []

// Different length
console.log(algorithm(["A"], [1, 2])); // ["A1", 2]
  • that's not correct -- the output should be in the first scenario is ["A1", "A2", "B1", "B2"] not ["A1", "B1"] – Rohit Aug 04 '22 at 21:42