Skip to content

Instantly share code, notes, and snippets.

@mheap
Created June 11, 2014 16:36
Show Gist options
  • Save mheap/9d6be84682fe5b0702f2 to your computer and use it in GitHub Desktop.
Save mheap/9d6be84682fe5b0702f2 to your computer and use it in GitHub Desktop.
func oddNumberGenerator(n int) []int {
vals := make([]int, n);
origN := n;
// In PHP I'd do while count($arr) < $n, but as we initialise
// an array of size n that won't work in go
for i := 0; n > 0; i++ {
if (i % 2 == 1) {
vals[(origN - n)] = i;
n--;
}
}
return vals;
}
@caius
Copy link

caius commented Jun 11, 2014

Another possible way of doing it (I don't profess to be a good Gopher, but I find it easier to grok than yours)

func oddNumberGenerator(n int) []int {
    generatedNumbers := make([]int, n)

    // Every sequence starts with one
    generatedNumbers[0] = 1

    // Every other index is the previous one, plus 2
    for i := 1; i < n; i++ {
        generatedNumbers[i] = generatedNumbers[i - 1] + 2
    }

    return generatedNumbers
}

@mheap
Copy link
Author

mheap commented Jun 12, 2014

@caius: Aye, that's easier to read than me. I was thinking more generally about the problem though.

e.g.: I need an array of N items that satisfy condition X. Odd numbers seemed like an easy condition to test with, but obviously that can be simplified to [i-1]+2, so doesn't really show off the whole condition based side of pushing into the array

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment