64943

Picking elements from multiple arrays

Question:

How to get all the possible combinations of elements from multiple arrays in Swift?

Here is an example :

let myArray = [[2,3,4], [1,2,3,4,5], [1,2], ]

The count of myArray elements may vary, same goes for the arrays inside it.

The code should output an array by picking one element from each array at a time, seems basic but I can't see it now

Answer1:

Using the ideas from <a href="https://stackoverflow.com/a/20049365/1187415" rel="nofollow">https://stackoverflow.com/a/20049365/1187415</a>, this can be done in Swift as

// Append all elements of a2 to each element of a1 func combihelper(a1 : [[Int]], a2 : [Int]) -> [[Int]] { var result = [[Int]]() for elem1 in a1 { for elem2 in a2 { result.append(elem1 + [elem2]) } } return result } func combinations(array : [[Int]]) -> [[Int]] { // Start with the "empty combination" , then successively // add combinations with each row of array: var result : [[Int]] = [[]] for row in array { result = combihelper(result, row) } return result }

The last function can be written more Swiftly as

func combinations(array : [[Int]]) -> [[Int]] { return reduce(array, [[]]) { combihelper($0, $1) } }

Example:

let myArray = [[1], [2,3,4], [5,6], ] let result = combinations(myArray) println(result) // [[1, 2, 5], [1, 2, 6], [1, 3, 5], [1, 3, 6], [1, 4, 5], [1, 4, 6]]

(If your input is not restricted to integers, you can replace Int by Any in above functions.)

<hr />

Update for <strong>Swift 3</strong> and as a generic function, so that it can be used with any element type:

func combihelper<T>(a1 : [[T]], a2 : [T]) -> [[T]] { var result = [[T]]() for elem1 in a1 { for elem2 in a2 { result.append(elem1 + [elem2]) } } return result } func combinations<T>(of array: [[T]]) -> [[T]] { return array.reduce([[]]) { combihelper(a1: $0, a2: $1) } } let myArray = [[1], [2,3,4], [5,6], ] let result = combinations(of: myArray) print(result) // [[1, 2, 5], [1, 2, 6], [1, 3, 5], [1, 3, 6], [1, 4, 5], [1, 4, 6]]

Recommend

  • How to run a query between dates and times?
  • Making Cross Site Asynchronous HTTP Post from GWT Client
  • Connect Node.js with Oracle on Windows platform
  • How to concat Pandas dataframe columns
  • Why isn't my “Fizz Buzz” test in R working?
  • Python PIL to extract number from image
  • several dataProvider per one Test in TestNG
  • CodeIgniter URI Parameter is partially bypassing an “if” statement
  • opencv display image without x server
  • Run multiple queries from 1 SQL file showing result in multiple tables
  • wxPython: displaying multiple widgets in same frame
  • Excel's Macro-Recorder usage
  • What and where is mdimport
  • Does it make sense to call System.gc() and Thread.sleep() when working on Bitmaps?
  • RectangularRangeIndicator format like triangular using dojo
  • Get object from AWS S3 as a stream
  • How to redirect a user to a different server and include HTTP basic authentication credentials?
  • Cross-Platform Protobuf Serialization
  • Arrow is showed instead of the material design version hamburger icon. Why doesn't syncState in
  • Can a Chrome extension content script make an jQuery AJAX request for an html file that is itself a
  • what is the difference between the asp.net mvc application and asp.net web application
  • Upload files with Ajax and Jquery
  • Apache 2.4 - remove | delete | uninstall
  • Numpy divide by zero. Why?
  • php design question - will a Helper help here?
  • How to delete a row from a dynamic generate table using jquery?
  • Revoking OAuth Access Token Results in 404 Not Found
  • AngularJs get employee from factory
  • using HTMLImports.whenReady not working in chrome
  • How to get Windows thread pool to call class member function?
  • IndexOutOfRangeException on multidimensional array despite using GetLength check
  • Authorize attributes not working in MVC 4
  • EntityFramework adding new object to nested object collection
  • XCode 8, some methods disappeared ? ex: layoutAttributesClass() -> AnyClass
  • Is there any way to bind data to data.frame by some index?
  • reshape alternating columns in less time and using less memory
  • Observable and ngFor in Angular 2
  • How to Embed XSL into XML
  • UserPrincipal.Current returns apppool on IIS
  • Conditional In-Line CSS for IE and Others?