B
B
Borodean2015-01-24 05:22:17
Programming languages
Borodean, 2015-01-24 05:22:17

How to search and replace sequences of elements in arrays?

Most programming languages ​​have tools for finding and replacing sequences of characters in strings. But how to do the same, but with elements in arrays?
For example, there is an array of hashes:

[
  { type: 1, content: "lorem" },
  { type: 2, content: "ipsum" },
  { type: 3, content: "dolor" },
  { type: 4, content: "sit" },
  { type: 2, content: "amet" },
  { type: 1, content: "consectetur" },
  { type: 2, content: "adipisicing" },
  { type: 3, content: "elit" },
]

You need to combine all elements that have types from 1 to 3 in sequence into one element with type 1 with the `content` field glued together:
[
  { type: 1, content: "loremipsumdolor" },
  { type: 4, content: "sit" },
  { type: 2, content: "amet" },
  { type: 1, content: "consecteturadipisicingelit" },
]

In addition, all sequences from an element of type 4 and any other element must be replaced by an element of type 5 and a `content` field containing the string "woohoo":
[
  { type: 1, content: "loremipsumdolor" },
  { type: 5, content: "woohoo" },
  { type: 1, content: "consecteturadipisicingelit" },
]

What tools for solving such problems do programming languages ​​offer? How exactly are they used? If there are no such tools, then what is the algorithm?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Armenian Radio, 2015-01-24
@gbg

First, the Aho-Korasik algorithm to find the desired sequences. Then perform actions.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question