Home > other >  Sum of elements of two integer array in a single string array in Swift
Sum of elements of two integer array in a single string array in Swift

Time:10-13

Have a function Arr(strArr) read the array of strings stored in strArr which will contain only two elements, both of which will represent an array of positive integers. For example of strArr is ["[1, 2, 5, 6]", "[5, 2, 8, 11]"], and goal for this is to add the elements in corresponding locations from both arrays. For the example input, the program should do the following additions: [(1 5), (2 2), (5 8), (6 11)] which then equals [6, 4, 13, 17]. Return this resulting array in a string format with each element separated by a hyphen: 6-4-13-17.

If the two arrays do not have the same amount of elements, then simply append the remaining elements onto the new array.

Examples

Input: ["[5, 2, 3]", "[2, 2, 3, 10, 6]"]
Output: 7-4-6-10-6
Input: ["[1, 2, 1]", "[2, 1, 5, 2]"]
Output: 3-3-6-2

Thank you for your help.

CodePudding user response:

The question seems obviously a homework exercise, and as was pointed out in comments that's not what StackOverflow is for; however, I know a lot of students who struggle to know even how to approach a problem. I think helping with that is a good thing, so I won't give a solution to the problem, but rather advice about approaching it.

The general formula that works for most problems is simple: Break the problem into smaller sub-problems, and solve each of those independently, then combine the sub-solutions. If any of those sub-problems are too complicated, repeat the process for those, and so on.

Homework problems, and a lot of real world problems, usually break down into three main sub-problems:

    1. Transform some input into a more conveniently computable form.
    1. Process the transformed input into some computed outputs.
    1. Transform the computed outputs into a specified format.

Applied to your problem, you have:

    1. How to parse a specially formatted string into an array of integers.
    1. How to sum corresponding elements of two arrays, taking into account they may be of different lengths, to produce an array of sums.
    1. How to transform an array of integers into a specially delimited string output.

The solution to your top-level problem will involve applying the sub-solutions in that order, but you don't have to solve them in that order. If you're having difficulty with getting started with the first one, solve one of the easier sub-solutions first to get some momentum. Psychology is actually quite important in problem solving. Believing you can solve it is half of actually solving it, so solve the easier problems first to get that factor working in your favor.

Maybe you regard the sub-problem 3 as the easiest to solve: So write a function place-holder for it (aka, a "stub function"), and make up some input data to test it. This would lead you to write something like this:

func formatOutput(from intArray: [Int]) -> String
{
    // Your implementation will go here
}

let actual = formatOutput(from: [1, 2, 3, 4])
let expected = "1-2-3-4"

// If you're doing this in a playground, app, or command line tool 
if actual != expected { 
    fatalError("FAILED: \"\(actual)\" != \"\(expected)\"")
}
else { print("Yay! Passed!") }

// If you're using XCTest
XCTAssertEqual(actual, expected)

That won't even compile yet, because formatOutput has to return something, and it doesn't yet. The key thing is that you've written your usage code first, and expressed in code what you expect. Now focus on the guts of formatOutput. If you want to take a Test Driven Development approach (TDD), maybe at first just return an empty string from formatOutput so you can be sure the code compiles and you see a failing test. Then implement it correctly if you know how, or in small steps if you're not clear on what to do. As you get the exact thing you're testing for working, you can keep adding more tests and improving formatOutput until you've verifiably got it doing everything it's supposed to do. Remember the KISS principle: "Keep It Simple, Stupid!" Don't over-think the solution, and save doing it "cleverly" for another day, which often never comes because the simple thing was sufficient.

At that point you have one of the sub-problems solved, so you move on to the next, following the same pattern. And the next, until all the parts are solved. Then put them together.

You'll note that sub-problem 2 has a bit of an extended description, especially the part specifying that the arrays may be of different lengths. Unless you already know how to solve that problem as stated, that sort of thing indicates it's a good candidate to be broken into yet simpler problems:

  • 2a. How to sum corresponding elements of two arrays of the same length.
  • 2b. How to modify 2a to handle arrays of different lengths.

2b can be done a few different ways:

  • 2.b.1. Apply 2.a to sub-arrays of common length, then handle the remaining part of the longer one separately

OR

  • 2.b.2. Enlarge the shorter array so that it is the same length as the longer one, so 2.a can be applied unmodified.

OR

  • 2.b.3. Modify 2.a so that it can treat the shorter array as though it were the same length as the longer one, without actually copying or adding new elements.

OR

  • 2.b.4. Modify 2.a so that it doesn't have to do anything special for different lengths at all. Hint: think more about the output and its length than the inputs.

When faced with alternatives like that, in the absence of any external constraints that would make one option preferred over the others, pick the one that seems simplest to you (or the most interesting, or the one you think you'd learn the most from). Or if you have time, and want to get the most out of the exercise, implement all of them so you can learn how they are all done, and then pick the one you like best for your final code.

CodePudding user response:

func getResult(strArr: [String]) -> String {
    let intArray1 = (try? JSONDecoder().decode([Int].self, from: Data(strArr[0].utf8))) ?? []
    let intArray2 = (try? JSONDecoder().decode([Int].self, from: Data(strArr[1].utf8))) ?? []
    var arrayResult = zip(intArray1,intArray2).map( )
    let commonCount = arrayResult.count
    arrayResult.append(contentsOf: intArray1.dropFirst(commonCount))
    arrayResult.append(contentsOf: intArray2.dropFirst(commonCount))
    return arrayResult.map(String.init).joined(separator: "-")
}

let result1 = getResult(strArr : ["[5, 2, 3]", "[2, 2, 3, 10, 6]"])
let result2 = getResult(strArr : ["[1, 2, 1]", "[2, 1, 5, 2]"])

You can use this function to get your desired result.

  • Related