How to concatenate one vector into the other elegantly in ADVPL?

Asked

Viewed 408 times

2

I have two number vectors, aBuffer and aCandidato. Depending on a condition (external to the vector), I need aBuffer receive the content of aCandidato to work on it afterwards. aBuffer will be used by a function that is already ready to receive a number array, so I would not like to change it.

In Java, I would do something like this:

ArrayList<Integer> aBuffer = ...;
ArrayList<Integer> aCandidato = ...;

...

if (condicaoMisteriosa()) {
  aBuffer.addAll(aCandidato);
}

However, in ADVPL, I only know the aadd, that adds an element at the end of the array. The code I can do is:

local aBuffer := {}
local aCandidato := {}
local lCondicaoMisteriosa := ...
local i

...

If lCondicaoMisteriosa
  For i := 1 len(aCandidato)
    aadd(aBuffer, aCandidato[i])
  Next i
EndIf

The Java equivalent of this code would be:

ArrayList<Integer> aBuffer = ...;
ArrayList<Integer> aCandidato = ...;

...

if (condicaoMisteriosa()) {
  for (int i = 0; i < aCandidato.size(); i++) {
    aBuffer.add(aCandidato.get(i));
  }
}

The alternative of concatenating the vectors into an intermediate vector, to then do the flatten (playing the result in aBuffer) similarly to this answer in Python, but I don’t see it as being elegant.

1 answer

3


I believe this does what you want, elegant is relative, but it seems simpler and probably faster (in ADVPL without testing I never doubt it may not be):

tamanhoAtual = len(aBuffer)
asize(aBuffer, tamanhoAtual + len(aCandidato))
acopy(aCandidato, aBuffer, 1, len(aCandidato), tamanhoAtual + 1)

I put in the Github for future reference.

I increased the size of the destination to fit the elements of the array source, there I invoked the copy of the source from element 1 to the last and added from the next to the last element before being increased. If you do not increase the array will give error, unless it already had enough space, but it will be running the risk of overlapping something that should remain there.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.