How to create unique arrays of a given size from an array in Swift? -


given array of ints, , desired array size, myfunction should return array of possible unique arrays. ints in initial array supposed unique. array considered unique if members can't found in array.

func myfunction(array : [int], arraysize : int) -> [[int]] {     //... put here? } 

if understand question correctly want create k-element subsets of given set n elements. can done recursively by

  • combining first element a[1] (k-1)-element subsets of remaining elements a[2] ... a[n], and
  • adding (k)-element subsets of a[2] ... a[n].

swift code (a bit generic can used not integers):

func allsubsetsof<t>(elements: [t], withcardinality k : uint,     combinedwith prefix : [t] = [], startingwithindex j : int = 0) -> [[t]] {          if k == 0 {             return [prefix]         }          if j < elements.count  {             let first = elements[j]             return allsubsetsof(elements, withcardinality: k-1, combinedwith: prefix + [first], startingwithindex : j+1)                 + allsubsetsof(elements, withcardinality: k, combinedwith: prefix, startingwithindex: j+1)         } else {             return []         } } 

examples:

let result1 = allsubsetsof([1, 2, 3, 4, 5], withcardinality: 3) println(result1) // [[1, 2, 3], [1, 2, 4], [1, 2, 5], [1, 3, 4], [1, 3, 5], [1, 4, 5], [2, 3, 4], [2, 3, 5], [2, 4, 5], [3, 4, 5]]  let result2 = allsubsetsof(["a", "b", "c", "d"], withcardinality: 2) println(result2) // [[a, b], [a, c], [a, d], [b, c], [b, d], [c, d]] 

Comments

Popular posts from this blog

javascript - RequestAnimationFrame not working when exiting fullscreen switching space on Safari -

jsf - How to ajax update an item in the footer of a PrimeFaces dataTable? -

jquery - Keeping Kendo Datepicker in min/max range -