Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to generate a sequence of numbers

I want to generate a sequence of numbers in Go but I can't find any built-in functions for this.
Basically I want the equivalent of PHP's range function in Golang:

array range ( mixed $start , mixed $end [, number $step = 1 ] ) 

It would be useful when creating a slice/array of numeric types and you want to populate/initialize it with a numeric sequence.

like image 823
sepehr Avatar asked Oct 05 '16 07:10

sepehr


People also ask

What is the generator of a sequence?

sequence generator A digital logic circuit whose purpose is to produce a prescribed sequence of outputs. Each output will be one of a number of symbols or of binary or q-ary logic levels. The sequence may be of indefinite length or of predetermined fixed length. A binary counter is a special type of sequence generator.

How do you create a sequence of numbers in Python?

The built-in method: range() The range() method generates an immutable object that is a sequence of numbers. The range() object can easily be converted into a Python list by enclosing it in the list method, for example, creating a list of values between 10 (start) and 0 (stop) decreasing in increments of 2 (step).

How do I create a sequence of numbers in R?

The simplest way to create a sequence of numbers in R is by using the : operator. Type 1:20 to see how it works. That gave us every integer between (and including) 1 and 20 (an integer is a positive or negative counting number, including 0).


1 Answers

There is no equivalent to PHP's range in the Go standard library. You have to create one yourself. The simplest is to use a for loop:

func makeRange(min, max int) []int {     a := make([]int, max-min+1)     for i := range a {         a[i] = min + i     }     return a } 

Using it:

a := makeRange(10, 20) fmt.Println(a) 

Output (try it on the Go Playground):

[10 11 12 13 14 15 16 17 18 19 20] 

Also note that if the range is small, you can use a composite literal:

a := []int{1, 2, 3} fmt.Println(a) // Output is [1 2 3] 
like image 78
icza Avatar answered Oct 03 '22 03:10

icza