-
-
Save gauravssnl/9c6878097dc8e7fa6acbd31be9eda72e to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
func combinations(n, m int, f func([]int)) { | |
// For each combination of m elements out of n | |
// call the function f passing a list of m integers in 0-n | |
// without repetitions | |
// TODO: switch to iterative algo | |
s := make([]int, m) | |
last := m - 1 | |
var rc func(int, int) | |
rc = func(i, next int) { | |
for j := next; j < n; j++ { | |
s[i] = j | |
if i == last { | |
f(s) | |
} else { | |
rc(i+1, j+1) | |
} | |
} | |
return | |
} | |
rc(0, 0) | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
func combinations_with_replacement(n, m int, f func([]int)) { | |
// For each combination of m elements out of n | |
// call the function f passing a list of m integers in 0-n | |
// with repetitions | |
indices := make([]int, m) | |
f(indices) | |
for { | |
var i int | |
for i = m - 1; i >= 0; i-- { | |
if indices[i] != n-1 { | |
break | |
} | |
} | |
if i < 0 { | |
break | |
} | |
indices_i := indices[i] | |
for k := i; k < m; k++ { | |
indices[k] = indices_i + 1 | |
} | |
f(indices) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment