Microbiological systems evolve to fulfill their tasks with maximal efficiency. The immune system is a remarkable example, where self-non self distinction is accomplished by means of molecular interaction between self proteins and antigens, triggering affinity-dependent systemic actions. Specificity of this binding and the infinitude of potential antigenic patterns call for novel mechanisms to generate antibody diversity. Inspired by this problem, we develop a genetic algorithm where agents evolve their strings in the presence of random antigenic strings and reproduce with affinity-dependent rates. We ask what is the best strategy to generate diversity if agents can rearrange their strings a finite number of times. We find that endowing each agent with an inheritable cellular automaton rule for performing rearrangements makes the system more efficient in pattern-matching than if transformations are totally random. In the former implementation, the population evolves to a stationary state where agents with different automata rules coexist.