I'm Iterating over an array list with following output:
Process finished with exit code 0
All those elements are inside my objet "Results"
my code:
def list = results[0]
list.eachWithIndex { val, idx ->
println "${idx}. ${val}" }
With this iteration I'm getting the Index and the element at the same time.
I need to know if it is possible to iterate in the array list and at the same time convert my indexes in words, by example
A. Richard
B. Collins
C. Ducati
D. 50
E. London
F. Barten
I'm implementing and automation and the system can't catch the Indexes from the elements. Maybe replacing them with words would be possible
Thank you guys!
Another way, if you want to cover the case where you run out of one-letter index values:
def values = ['Richard', 'Collins', 'Ducati', '50', 'London', 'Barten']
def alphabet = ('a'..'c')
values.indexed().each { i, v ->
def index = encode(i, alphabet)
println "${index}. $v"
}
String encode(index, alphabet) {
def result = new StringBuilder()
def s = alphabet.size()
index += s // remove if we are ok with one letter indicies
while (index >= 0) {
result.insert(0, alphabet[index % s as int])
index = (index / s as long) - 1
}
result
}
which, when run, prints:
─➤ groovy solution.groovy
aa. Richard
ab. Collins
ac. Ducati
ba. 50
bb. London
bc. Barten
where the alphabet for indicies is configurable via the ('a'..'z')
range syntax.
For a combination of upper case letters and numbers you could for example do:
def alphabet = ('A'..'Z') + ('0'..'9')
which would produce:
─➤ groovy solution.groovy
AA. Richard
AB. Collins
AC. Ducati
AD. 50
AE. London
AF. Barten
where the index values would roll over to numbers after the letter Z
.
With this you would never "run out" of index values even for a large number of input items in the values
collection. The encode
method will just produce successively longer index values the larger your input integer value is. To reduce the length of the index values for large input integers you can use a longer alphabet.