英文:
Golang Make the output all unique 3-digit numbers
问题
我有一个任务,需要编写一个函数,以单行形式打印出所有三个不同数字的唯一组合,其中第一个数字小于第二个数字,第二个数字小于第三个数字。
输出应该像这样:
012, 013, 014, 015, 016, 017, 018, 019, 023, ..., 689, 789
我写了一段代码,按递增顺序显示所有的三位数,但是我不知道如何:
- 使它们都是唯一的
- 将它们放在一行上
- 用逗号分隔它们
有人可以检查我的代码并给出让它正常工作的思路吗?
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)
}
}
}
}
英文:
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:
- Make them all unique
- Put them in one line
- 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)
}
}
}
}
答案1
得分: 2
你非常接近了!关键在于j
必须始终大于i
,所以你需要将其循环的起始值从1
改为i + 1
。同样地,k
的起始值将为j + 1
。你还希望每个数字通过j
和k
一直递增到9
。
这是一个几乎满足你需求的初步代码:
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("")
}
问题在于这行代码会以一个额外的逗号和空格结尾。为了节省一点内存,我们可以计算并存储这些数字,然后使用一个函数将它们用逗号连接起来:
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, ", "))
}
额外加分问题:如果我们声明var nums []int
并将每个数字存储为i * 100 + j * 10 + k
,会发生什么?
英文:
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
?
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论