Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>Looks like a good problem for recursion.</p> <p>Define a function <code>f(prefix, iMin, iMax, n)</code>, that prints all combinations of <code>n</code> digits in the range [<code>iMin</code>, <code>iMax</code>] and returns the total number of combinations. For <code>n</code> = 1, it should print every digit from <code>iMin</code> to <code>iMax</code> and return <code>iMax - iMin + 1</code>.</p> <p>For your <code>iRange = 5</code> and <code>n = 3</code> case, you call <code>f("", 1, 5, 3)</code>. The output should be <code>123 - 124 - 125 - 134 - 135 - 145 - 234 - 235 - 245 - 345</code>.</p> <p>Notice that the first group of outputs are simply <code>1</code> prefixed onto the outputs of <code>f("", 2, 5, 2)</code>, i.e. <code>f("1", 2, 5, 2)</code>, followed by <code>f("2", 3, 5, 2)</code> and <code>f("3", 4, 5, 2)</code>. See how you would do that with a loop. Between this, the case for <code>n</code> = 1 above, and traps for bad inputs (best if they print nothing and return 0, it should simplify your loop), you should be able to write <code>f()</code>.</p> <p>I'm stopping short because this looks like a homework assignment. Is this enough to get you started?</p> <p>EDIT: Just for giggles, I wrote a Python version. Python has an easier time throwing around sets and lists of things and staying legible.</p> <pre><code>#!/usr/bin/env python def Combos(items, n): if n &lt;= 0 or len(items) == 0: return [] if n == 1: return [[x] for x in items] result = [] for k in range(len(items) - n + 1): for s in Combos(items[k+1:], n - 1): result.append([items[k]] + s) return result comb = Combos([str(x) for x in range(1, 6)], 3) print len(comb), " - ".join(["".join(c) for c in comb]) </code></pre> <p>Note that <code>Combos()</code> doesn't care about the types of the items in the <code>items</code> list.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload