Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Groovy Sequence of a number

Tags:

groovy

How do I get a sequence of a given number in Groovy, for example:

def number = 169
// need a method in groovy to find the consecutive numbers that is, 1,6,9,16,69,169
// not 19!

There is a method in Groovy called subsequences(), but that is not doing this job exactly. Can anyone say me how can I do this in Groovier way? Or is there any built-in method?

like image 953
Ant's Avatar asked Dec 27 '22 18:12

Ant's


2 Answers

Run this in the Groovy console

def number = 169
number = number.toString() as List

def results = []

0.upto(number.size()) {numDigits ->

  for(int startPos = 0; startPos + numDigits < number.size(); startPos++) {
    def result = number[startPos..startPos + numDigits]
    results << result.join().toInteger()
  }
}

assert results == [1, 6, 9, 16, 69, 169]
like image 194
Dónal Avatar answered Jan 04 '23 17:01

Dónal


Although late to the game, here's a solution that is less sophisticated than @tim's, but also 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 the number and extracting the various substrings from it.

The outer loop represents the start index of the substring and the inner loop the end index of the substring. The outer loop will go from the beginning to the end of the String, whereas the inner loop starts at the current start index and goes from there to the end.

The as SortedSet ensures that there are no duplicate numbers in the result and that the 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)
like image 35
Christoph Metzendorf Avatar answered Jan 04 '23 19:01

Christoph Metzendorf