加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 大数据 > 正文

Groovy序列的一个数字

发布时间:2020-12-14 16:26:28 所属栏目:大数据 来源:网络整理
导读:如何在Groovy中获取给定数字的序列,例如: def number = 169// need a method in groovy to find the consecutive numbers that is,1,6,9,16,69,169// not 19! Groovy中有一个名为subsequences()的方法,但这并没有完全做好这项工作.谁能说我怎么能用Groovier
如何在Groovy中获取给定数字的序列,例如:

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

Groovy中有一个名为subsequences()的方法,但这并没有完全做好这项工作.谁能说我怎么能用Groovier方式做到这一点?或者有内置方法吗?

解决方法

虽然在游戏后期,这里的解决方案不如@ tim的复杂,但也可以解决问题:

def str = 169 as String
def result = [] as SortedSet
(0..<str.length()).each { i ->
    (i..<str.length()).each { j ->
        result << str[i..j].toInteger()
    }
}

编辑:

代码就像两个嵌套循环一样,迭代数字的String表示并从中提取各种子字符串.

外部循环表示子字符串的起始索引,内部循环表示子字符串的结束索引.外部循环将从String的开头到结尾,而内部循环从当前的起始索引开始并从那里开始到结束.

as SortedSet确保结果中没有重复的数字,并且数字按升序排序.

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)

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读