3

If I have two int arrays such as

var array1 = [1,2,3]
var array2 = [1,2,3,5]

I'd like to be able to add the first element of the first array with the first element of the second array, and so on. However if an array has a different length than the other I'd like to keep the element that was not added in the return array. For this example my return array would be [2,4,6,5].

I tried using zip(array1,array2).map(+) but it would exclude the 5 from array2.

2
  • 1
    "I tried using zip(array1,array2).map(+) but it would exclude the 5 from array2" And what about a manual for loop?
    – Larme
    Feb 3, 2021 at 18:53
  • Although SO is not a code writing service, I do appreciate that you took SOME time to actually ask the question and attempt a solution. In the future, it is more appropriate to come up with multiple attempts (especially an easy task such as this) if at all possible. ziping is obviously not the ONLY solution; others would be more inclined to help if you exhaustively tried all solutions that you could think of. Feb 4, 2021 at 15:41

5 Answers 5

5

After adding the elements at the index positions which are common to both arrays (what you already did with zip and map) just append the remaining elements from both arrays (using append(contentsOf:) and dropFirst):

let array1 = [1, 2, 3]
let array2 = [1, 2, 3, 5]

var combined = zip(array1, array2).map(+)
let commonCount = combined.count
combined.append(contentsOf: array1.dropFirst(commonCount))
combined.append(contentsOf: array2.dropFirst(commonCount))

print(combined) // [2, 4, 6, 5]
1
  • 1
    Very elegant approach
    – Leo Dabus
    Feb 4, 2021 at 1:17
0
AnySequence(zip: (1...3, [1, 2, 3, 5])).map {
  Optional($0).map(+) ?? firstNonNil($0)!
}
public extension AnySequence {
  /// Like `zip`, but with `nil` elements for the shorter sequence after it is exhausted.
  init<Sequence0: Sequence, Sequence1: Sequence>(
    zip zipped: (Sequence0, Sequence1)
  ) where Element == (Sequence0.Element?, Sequence1.Element?) {
    self.init(
      sequence(
        state: (zipped.0.makeIterator(), zipped.1.makeIterator())
      ) { iterators in
        ((iterators.0.next(), iterators.1.next()) as Optional)
          .filter { $0 != nil || $1 != nil }
      }
    )
  }
}
public extension Optional {
  /// Exchange two optionals for a single optional tuple.
  /// - Returns: `nil` if either tuple element is `nil`.
  init<Wrapped0, Wrapped1>(_ optionals: (Wrapped0?, Wrapped1?))
  where Wrapped == (Wrapped0, Wrapped1) {
    switch optionals {
    case let (wrapped0?, wrapped1?):
      self = (wrapped0, wrapped1)
    default:
      self = nil
    }
  }
  
  /// Transform `.some` into `.none`, if a condition fails.
  /// - Parameters:
  ///   - isSome: The condition that will result in `nil`, when evaluated to `false`.
  func filter(_ isSome: (Wrapped) throws -> Bool) rethrows -> Self {
    try flatMap { try isSome($0) ? $0 : nil }
  }
}
public func firstNonNil<Element>(_ tuple: (Element?, Element?)) -> Element? {
  switch tuple {
  case (let _0?, _):
    return _0
  case (nil, let _1?):
    return _1
  case (nil, nil):
    return nil
  }
}
-1
func combine2Arrays(array1:[Int], array2:[Int]) -> [Int] {
    var finalArray:[Int] = []
    let maxSize = max(array1.count, array2.count)
    
    for i in 0..<maxSize {
        let valToAdd1 = (array1.count > i ? array1[i] : 0)
        let valToAdd2 = (array2.count > i ? array2[i] : 0)
        let finalVal = valToAdd1 + valToAdd2
        finalArray.append(finalVal)
    }
    return finalArray
}

print(combine2Arrays(array1: [1,2,3], array2: [1,2,3,5]))

OR

func combine2Arrays(array1:[Int], array2:[Int]) -> [Int] {
    var finalArray:[Int] = zip(array1,array2).map(+)
    let largerArray = array1.count > array2.count ? array1 : array2
    let smallerArray = array1.count > array2.count ? array2 : array1
    let min = smallerArray.count
    let max = largerArray.count
    for i in min..<max {
        finalArray.append(largerArray[i])
    }
    return finalArray
}

print(combine2Arrays(array1: [1,2,3], array2: [1,2,3,5]))
3
  • I don't think your critique of the question is justified: this is a valid question, absolutely suitable for SO. Feb 3, 2021 at 20:22
  • I disagree - he didn't show his code for his solution - only stated an attempt at it. Additionally, this is almost as if someone posted a question and provided skeleton code for a homework problem. This question definitely needs to include their attempts, providing their code, so we can reproduce their problem. As it is stated at this editing stage, it is a "I have this problem - here is the skeleton code - I need you to code this". As I gave him credit for his parts that he DID complete, I noted it could be more SO appropriate - if you would like, I can include the SO question guide @KirilS. Feb 3, 2021 at 20:25
  • 1
    Everyone is entitled to their opinion. Except you are also violating the SO rules: your opinion about the question doesn't belong in the answer. Things like that belong in the comments section under the question. Feb 3, 2021 at 22:25
-1

You can fill your smaller array with zeroes, then use zip. inout means that arrays are mutable, or you can make the copy of function parameters inside the function to make them mutable.

private func combineArrays(array1: inout [Int], array2: inout [Int]) -> [Int] {
    let maxSize = max(array1.count, array2.count)

    if (array1.count > array2.count) {
        array2.append(contentsOf: [Int](repeating: 0, count: maxSize - array2.count))
    } else if (array2.count > array1.count) {
        array1.append(contentsOf: [Int](repeating: 0, count: maxSize - array1.count))
    }

    return zip(array1, array2).map(+)
}
-1
//javaScript
var array1 = [1,2,3,4,5];
var array2 = [9,7,8,6,5,6,7];

let a= array1.length;
let b = array2.length;

var array3 = [];

let c = a>b?a:b;

for(let i=0; i<c; i++){
    if(i < a && i < b){
        array3.push(array1[i] + array2[i]);
    } else if(i >= a){
        array3.push(array2[i])
    } else{
        array3.push(array1[i])
    }
}

console.log(array3)
1
  • As it’s currently written, your answer is unclear. Please edit to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers in the help center.
    – Community Bot
    Dec 1, 2021 at 23:13

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.