Golang Make the output all unique 3-digit numbers

I have a task where I have to write a function that prints on a single line all unique combinations of three different digits so that, the first digit is lower than the second, and the second is lower than the third.

The output should be like that:
012, 013, 014, 015, 016, 017, 018, 019, 023, ..., 689, 789

I wrote a code that displays all the 3-digit numbers in increasing order, however, I don’t know how to:

  1. Make them all unique
  2. Put them in one line
  3. Separate them by comma

Can someone please check my code and give ideas on how to make it work?


package main

import "fmt"

func main() {
    i := 0
    j := 0
    k := 0

    for i = 0; i <= 7; i++ {
        for j = 1; j <= 8; j++ {
            for k = 2; k <= 9; k++ {
                fmt.Println(i, j, k)
            }
        }
    }
} 

>Solution :

You’re very close! The key is that j must always be greater than i, so rather than starting its loop at 1, you’ll need to start at i + 1. Similarly, k will start at j + 1. You’ll also want each number to continue incrementing j and k through 9.

Here’s a first pass that does almost what you need:

package main
import "fmt"

func main() {
  for i := 0; i < 8; i++ {
    for j := i + 1; j < 9; j++ {
      for k := j + 1; k < 10; k++ {
        fmt.Printf("%d%d%d, ", i, j, k)
      }
    }
  }
  fmt.Println("")
} 

The problem is that the line will end with an extra comma and space. At the cost of a bit of memory, we can calculate and store the numbers and then use a function to join them with commas:

package main

import (
  "fmt"
  "strings"
)

func main() {
  var nums []string
  for i := 0; i < 8; i++ {
    for j := i + 1; j < 9; j++ {
      for k := j + 1; k < 10; k++ {
        nums = append(nums, fmt.Sprintf("%d%d%d", i, j, k))
      }
    }
  }
  fmt.Println(strings.Join(nums, ", "))
}

For extra credit: what would happen if we declared var nums []int and stored each number as i * 100 + j * 10 + k?

Leave a Reply