Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
469 views
in Technique[技术] by (71.8m points)

arrays - Generating list of every other pair of integers in Julia

I need to generate an array in Julia that contains all integers up to some number N, excluding the pair which is two integers apart. I assume that N itself is a multiple of 4. For example, if N=4, the list is

[1 4]

If N=8,

[1 4 5 8]

If N=16,

[1 4 5 8 9 12 13 16]

And so on. Is there an easy, efficient way of doing this in Julia? I tried a solution with collect, but I wasn't sure how to implement it correctly.

question from:https://stackoverflow.com/questions/65865830/generating-list-of-every-other-pair-of-integers-in-julia

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Try:

vals = Iterators.flatten( ((i-1)*4+1, i*4) for i in 1:N÷4)

This generates an iterator so will work with huge N values.

If you want the actual values use collect, here is for N=16:

julia> collect(vals)
8-element Vector{Int64}:
  1
  4
  5
  8
  9
 12
 13
 16

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...