Home | History | Annotate | Download | only in kotlin
      1 /*
      2  * Copyright 2018 The Android Open Source Project
      3  *
      4  * Licensed under the Apache License, Version 2.0 (the "License");
      5  * you may not use this file except in compliance with the License.
      6  * You may obtain a copy of the License at
      7  *
      8  *      http://www.apache.org/licenses/LICENSE-2.0
      9  *
     10  * Unless required by applicable law or agreed to in writing, software
     11  * distributed under the License is distributed on an "AS IS" BASIS,
     12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
     13  * See the License for the specific language governing permissions and
     14  * limitations under the License.
     15  */
     16 
     17 package com.android.tools.build.jetifier.processor
     18 
     19 /**
     20  * Creates a cartesian product from the given lists.
     21  *
     22  * Example: ((1, 2), (a, b))
     23  * Result: ((1, a), (1, b), (2, a), (2,b))
     24  */
     25 fun <T> List<List<T>>.cartesianProduct(): List<List<T>> {
     26     return cartesianProductInternal(this.size - 1, this)
     27 }
     28 
     29 private fun <T> cartesianProductInternal(index: Int, lists: List<List<T>>): List<MutableList<T>> {
     30     val result = mutableListOf<MutableList<T>>()
     31     if (index == -1) {
     32         result.add(mutableListOf())
     33     } else {
     34         for (obj in lists[index]) {
     35             for (set in cartesianProductInternal(index - 1, lists)) {
     36                 set.add(obj)
     37                 result.add(set)
     38             }
     39         }
     40     }
     41     return result
     42 }