Merge multiple strings in Elixir

Hi all,

I need to merge two/+ strings into a single new string.
How to efficiently merge multiple strings into one string in Elixir?

merge( [ {datetime1, "foo bar"}, {datetime2, "abc"}, ... ]  )

datetime1 < datetime2: ‘abc bar’
datetime1 > datetime2: ‘foo bar’
datetime1 == datetime2: ‘foo barabc’

Thanks in advance for any help you are able to provide.

I’m not quite sure what you want, but you can use Enum.join/2 to get a list of strings into a single one.

1 Like

I assume that there is typo, and in case when datetime1 is less than datetime2 you meant abc not abc bar.

def merge([]), do: ""
def merge([{_, str}]), do: str
def merge([{datetime1, a}, {datetime2, b} | rest]) do
  cond cmp(datetime1, datetime2) do
    :eq -> merge([{datetime1, a <> b} | rest])
    :lt -> merge([{datetime2, b} | rest])
    :gt -> merge([{datetime1, a} | rest])
  end
end
1 Like

It’s a timestamp-based diff&merge algorithm.

Input data format: [ {"MM/dd/yyyy hh:mm:ss", string} ]

  • Case 1: if string1_timestamp == string2_timestamp == … == stringN_timestamp then
    • priority(string1) == priority(string2) == … == priority(stringN)
    • result_string.len <- string1.len + string2.len + … + stringN.len
    • result_string <- concat(string1, string2, …, stringN)
  • Case 2: if string1_timestamp > string2_timestamp then
    • priority(string1) > priority(string2)
    • result_string.len <- max(string1.len, string2.len)
    • result_string <- string1 (full) <> string2 (result_string.len - string1.len chars)
  • Case 3: if string1_timestamp < string2_timestamp then:
    • priority(string1) < priority(string2)
    • result_string.len <- max(string1.len, string2.len)
    • result_string <- string2 (full) <> string1 (result_string.len - string2.len chars)

Input data:

[ 
{"11/01/1978 14:00:00", "aaaaa"}, /* s1 */
{"11/01/1988 14:00:00", "7777"},  /* s2 */
{"11/01/1998 14:00:00", "ccc"},    /* s3 */
{"11/01/1978 14:00:00", "dd"}      /* s4 */
]

Case 1: timestamp(s1) == timestamp(s4) then:

  • priority(s1) == priority(s4)
  • result.length <- length(s1) + length(s4) == 5 + 2 == 7
  • result <- concat(s1, s4) == “aaaaadd”

Case 2: timestamp(s3) > timestamp(s2) then:

  • priority(s3) > priority(s2)
  • result.length <- max(length(s3), length(s2)) == max(3, 4) == 4
  • result <- s3 (full) <> s2 (4-3 = 1 chars) == “ccc7”

Case 3: timestamp(s1) < timestamp(s2) then:

  • priority(s1) < priority(s2)
  • result.length <- max (length(s1), length(s2)) == max(5, 4) = 5
  • result <- s2 (full) <> s1 (5-4= 1 chars) = “7777a”

Solved. Thank you for your comments and suggestions! :smile:

1 Like