我在试着用药剂数字符串上的复写字母。我确实尝试过一些尝试,但直到现在都没有成功。
让我们以这个字符串为例:"AAABBAAC"
所需的输出将是"3A2B2A1C"。
将此字符串转换为List,我能够计数每个字母,从而得到"5A2B1C",但我必须按照顺序进行计数。
这就是我正在做的代码:
string
|> String.graphemes
|> Enum.reduce([], fn(letter, acc) -> Keyword.update(acc, letter, 1, &(&1 + 1)) end)但是,在我的测试中,我试图生成一个列表,比如这个["AAA", "BB", "AA", "C"],这样我就可以轻松地使用String.lenght进行计数。
看起来像使用Enum.chunk_by,我越来越接近一个解决方案。
有办法制造这个吗?
发布于 2016-04-04 05:47:35
如果使用递归方法实现这一点,则可以很容易地跟踪上次发生的字符及其当前计数,以及到目前为止保存结果的累加器。如果当前字符等于最后一个字符,则只需增加计数。如果两者不同,则将最后一个字符及其计数添加到累加器中,然后继续进行下一个字符,直到字符串为空。最后,对最终值进行编码并返回结果。
defmodule RunLengthEncoding do
# public interface, take first char and remember it as the current value
def encode(<<char::utf8, rest::binary>>) do
do_encode(rest, char, 1, "")
end
# current == last, increase the count and proceed
defp do_encode(<<char::utf8, rest::binary>>, char, count, acc) do
do_encode(rest, char, count + 1, acc)
end
# current != last, reset count, encode previous values and proceed
defp do_encode(<<char::utf8, rest::binary>>, last, count, acc) do
do_encode(rest, char, 1, acc <> to_string(count) <> <<last::utf8>>)
end
# input empty, encode final values and return
defp do_encode("", last, count, acc) do
acc <> to_string(count) <> <<last::utf8>>
end
end发布于 2016-04-04 11:50:32
根据Help Center > Answering的说法,我确实解决了这个问题:
string
|> String.graphemes
|> Enum.chunk_by(fn arg -> arg end)
|> Enum.map(fn arg -> to_string(arg) end)
|> Enum.reduce("", fn(arg, acc) -> acc <> to_string(String.length(arg)) <> String.first(arg) end)现在,解释如下:
String.graphemes将string转换为包含每个字母的List:
["A", "A", "A", "B", "B", "A", "A", "C"]Enum.chunk_by(fn arg -> arg end)将每个重复的字母分组到新的列表中:
[["A", "A", "A"], ["B", "B"], ["A", "A"], ["C"]]Enum.map(fn arg -> to_string(arg) end)再次将其结合在一起:
["AAA", "BB", "AA", "C"]Enum.reduce("", fn(arg, acc) -> acc <> to_string(String.length(arg)) <> String.first(arg) end)最后将计数(String.length)和第一个字母(String.first)连接到初始化所有累加器(""):
"3A2B2A1C"发布于 2020-08-06 08:58:22
你也可以在下面这样做
"AAABBAAC"
|> String.graphemes
|> Enum.chunk_by(fn x -> x end)
|> Enum.map(fn x -> [Enum.at(x,0), Enum.count(x)] end)
|> List.flatten
|> Enum.joinhttps://stackoverflow.com/questions/36392742
复制相似问题