如何编写一个函数来打印给定字符串中所有可能的字符串?
我正在尝试编写执行以下操作的代码: 1.有一个字符串“abc” 2.它打印出所有可能的字符串: abc, bac, cba, acb, cab, bca
以下是我编写的代码,但它始终给出错误:
def swap(n: Int, source: String): String = {
val new_array = source.toCharArray
if (n == 1) {
new_string
} else {
var letter = new_array(n)
letter = new_array(n-1)
new_array(n-1) = letter
var k = new String(new_array)
swap(n, source)
}
}
你能告诉我我的错误在哪里吗?
先感谢您。
I am trying to write a code that does the following:
1. there is a string "abc"
2.it prints all the possible strings from it: abc, bac, cba, acb, cab, bca
The following is the code I wrote, however it gives an error all the time:
def swap(n: Int, source: String): String = {
val new_array = source.toCharArray
if (n == 1) {
new_string
} else {
var letter = new_array(n)
letter = new_array(n-1)
new_array(n-1) = letter
var k = new String(new_array)
swap(n, source)
}
}
Can you please tell me where is my mistake?
Thank you in advance.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
不过我不会把那个上交。
I wouldn't turn that one in though.
真正明显的错误是你把名字搞混了。
我可以看到
new_array
正在初始化,但随后您尝试使用new_string
,它似乎不是来自任何地方。The really obvious mistake is you have your names all mixed up.
I can see
new_array
being initialised, but then you try to usenew_string
, which doesn't seem to be coming from anywhere.一件明显的事情是,您尝试交换两个字母,但顺序错误。应该是 可能
还有其他错误,但因为这是作业......
One obvious thing is that you try to swap two letters, but you got the order wrong. It should be
There might be other errors, but as this is homework...
正如之前所说,这是一个排列问题。使用 Scala 2.8,您可以编写类似的内容:
然后:(
不过,我不确定我的排列是最佳的。至少,退休可能是尾递归的)
As said before, it's a permutation problem. With Scala 2.8, you could write something like that :
Then :
(I'm not sure my permutation is optimal, though. At least, retire could be tail recursive'd)
您想要编写一个
next_permutation
函数,其操作可以总结如下:查找数组中按降序排列的最长后缀 - 假设它从索引 m 开始。找出索引 m-1 处的值属于该后缀的位置,然后交换这两个值。然后将后缀从 m 反转到列表末尾,使其按排序顺序排列。You want to write a
next_permutation
function, whose operation can be summed up as follows: look for the longest suffix of the array that is in descending order -- let's say it starts at index m. Figure out where the value at index m-1 belongs in that suffix, and swap the two values. Then reverse the suffix from m to the end of the list so that it is in sorted order.