Get possible array combinations

后端 未结 3 2067
悲&欢浪女
悲&欢浪女 2021-01-01 00:05

SO,

The problem

From SQL I\'m getting an array with strings (flat array) - let it be

$rgData = [\'foo\', \'bar\', \'baz\', \'bee\         


        
3条回答
  •  旧时难觅i
    2021-01-01 00:33

    I'm sorry for not providing a PHP solution, because I didn't program in PHP for quite a long time now, but let me show you a quick Scala solution. Maybe it will inspire you:

    val array = Vector("foo", "bar", "baz", "bee", "feo")
    for (i <- 0 until array.size; 
         j <- i + 1 until array.size; 
         k <- j + 1 until array.size)      
        yield (array(i), array(j), array(k))
    

    Result:

    Vector((foo,bar,baz), (foo,bar,bee), (foo,bar,feo), (foo,baz,bee), (foo,baz,feo), (foo,bee,feo), (bar,baz,bee), (bar,baz,feo), (bar,bee,feo), (baz,bee,feo))
    

    Universal code for generating k-combinations:

    def combinations(array: Vector[String], k: Int, start: Int = 0): Iterable[List[String]] = { 
      if (k == 1 || start == array.length) 
        for (i <- start until array.length) yield List(array(i))
      else 
        for (i <- start until array.length; c <- combinations(array, k - 1, i + 1)) yield array(i) :: c 
    }
    

    Results:

    scala> combinations(Vector("a", "b", "c", "d", "e"), 1)
    res8: Iterable[List[String]] = Vector(List(a), List(b), List(c), List(d), List(e))
    
    scala> combinations(Vector("a", "b", "c", "d", "e"), 2)
    res9: Iterable[List[String]] = Vector(List(a, b), List(a, c), List(a, d), List(a, e), List(b, c), List(b, d), List(b, e), List(c, d), List(c, e), List(d, e))
    
    scala> combinations(Vector("a", "b", "c", "d", "e"), 3)
    res10: Iterable[List[String]] = Vector(List(a, b, c), List(a, b, d), List(a, b, e), List(a, c, d), List(a, c, e), List(a, d, e), List(b, c, d), List(b, c, e), List(b, d, e), List(c, d, e))
    
    scala> combinations(Vector("a", "b", "c", "d", "e"), 4)
    res11: Iterable[List[String]] = Vector(List(a, b, c, d), List(a, b, c, e), List(a, b, d, e), List(a, c, d, e), List(b, c, d, e))
    
    scala> combinations(Vector("a", "b", "c", "d", "e"), 5)
    res12: Iterable[List[String]] = Vector(List(a, b, c, d, e))
    

    Of course, real scala code should be much more generic with regard to accepted type of elements and type of collections, but I just wanted to show the basic idea, not the most beautiful Scala code possible.

提交回复
热议问题