Despite the fact that at the end of the game this solution is less complicated than @tim, it will do the trick:
def str = 169 as String def result = [] as SortedSet (0..<str.length()).each { i -> (i..<str.length()).each { j -> result << str[i..j].toInteger() } }
Edit:
The code works like two nested loops that iterate over the string representation of a number and extract various substrings from it.
The outer loop represents the starting index of the substring, and the inner loop represents the ending index of the substring. The outer loop will go from beginning to end of the line, while the inner loop starts from the current start index and goes from there to the end.
as SortedSet ensures that as a result there are no duplicate numbers and that numbers are sorted in ascending order.
1 6 9 ----- 0 1 2 <-- index ===== [1]6 9 (i=0; j=0) [1 6]9 (i=0; j=1) [1 6 9] (i=0; j=2) 1[6]9 (i=1; j=1) 1[6 9] (i=1; j=2) 1 6[9] (i=2; j=2)
source share