Contido

# ScriptForge.ServizoMatriz

Provee unha colección de métodos para manipular e transformar formacións de unha dimensión (vectores) e de dúas (matrices). A colección inclúe operacións de conxunto, ordenación, importación e exportación a partir de arquivos de texto.

As matrices con máis de dúas dimensións non poden utilizarse cos métodos deste servizo, sendo a única excepción o método CountDims, que acepta matrices con calquera número de dimensións.

Os elementos de matrices poden conter calquera tipo de valor, incluindo(sub)matrices.

## Invocación do servizo

Antes de poder utilizar o servizo Matriz, débese cargar a biblioteca ScriptForge mediante:

        GlobalScope.BasicLibraries.loadLibrary("ScriptForge")

A carga da biblioteca creará o obxecto SF_Array, que pode utilizarse para chamar aos métodos do servizo Matriz.

Os seguintes fragmentos de código mostran as diversas formas de chamar aos métodos no servizo Matriz (o método Append úsase como exemplo):

        Dim arr : arr = Array(1, 2, 3)
        arr = SF_Array.Append(arr, 4)

        Dim arr : arr = Array(1, 2, 3)
        Dim svc : svc = SF_Array
        arr = svc.Append(arr, 4)

        Dim arr : arr = Array(1, 2, 3)
        Dim svc : svc = CreateScriptService("Array")
        arr = svc.Append(arr, 4)

Debido a que Python integra a compatibilidade para listas e tuplas, a maioría dos métodos no servizo Matriz só están dispoñíbeis para secuencias BASIC. A única excepción é ImportFromCSVFile, que se admite tanto en BASIC como en Python.

Lista de métodos no servizo Matriz
Append AppendColumn AppendRow Contains ConvertToDictionary Copy CountDims Difference ExportToTextFile ExtractColumn ExtractRow | Flatten ImportFromCSVFile IndexOf Insert InsertSorted Intersection Join2D Prepend PrependColumn PrependRow RangeInit | Reverse Shuffle Slice Sort SortColumns SortRows Transpose TrimArray Union Unique

O primeiro argumento da maioría de métodos é o obxecto matricial para considerar. Sempre se pasa por referencia e se deixa sen cambios. Métodos como Append, Prepend, etc. devolven un novo obxecto matricial despois da súa execución.

## Append

Agrega os elementos enumerados como argumentos ao final da matriz de entrada.

### Sintaxe:

svc.Append(array_1d: any[0..*], arg0: any, [arg1: any] ...): any[0..*]

### Parámetros:

array_1d: A matriz preexistente pode estar baleira.

arg0, arg1, ...: elementos que serán engadidos a array_1d

### Exemplo:

        Dim a As Variant
        a = SF_Array.Append(Array(1, 2, 3), 4, 5)
            ' (1, 2, 3, 4, 5)

## AppendColumn

Agrega unha nova columna á dereita dunha matriz bidimensional. A matriz resultante ten os mesmos límites inferiores que a matriz bidimensional incial.

### Sintaxe:

svc.AppendColumn(array_2d: any[0..*, 0..*], column: any[0..*]): any[0..*, 0..*]

### Parámetros:

array_2d: a matriz preexistente pode estar baleira. Se esta matriz só ten unha dimensión, considérase como a primeira columna da matriz bidimensional resultante.

columna: Unha matriz unidimensional con tantos elementos como filas en matriz_2d.

### Exemplo:

        Dim a As Variant, b As variant
        a = SF_Array.AppendColumn(Array(1, 2, 3), Array(4, 5, 6))
            ' ((1, 4), (2, 5), (3, 6))
        b = SF_Array.AppendColumn(a, Array(7, 8, 9))
            ' ((1, 4, 7), (2, 5, 8), (3, 6, 9))
        c = SF_Array.AppendColumn(Array(), Array(1, 2, 3))
            ' ∀ i ∈ {0 ≤ i ≤ 2} : b(0, i) ≡ i

## AppendRow

Amecer unha fila nova por debaixo dunha matriz bidimensional. A matriz resultante ten os mesmos límites inferiores que a matriz bidimensional inicial.

### Sintaxe:

svc.AppendRow(array_2d: any[0..*, 0..*], row: any[0..*]): any[0..*, 0..*])

### Parámetros:

matriz_2d: A matriz preexistente, que pode estar baleira. Se esa matriz ten unha dimensión considérase como primeira fila da matriz bidimensional resultante.

fila: Unha matriz unidimensional con tantos elementos como columnas en matriz_2d.

### Exemplo:

        Dim a As Variant, b As variant
        a = SF_Array.AppendRow(Array(1, 2, 3), Array(4, 5, 6))
            '  ((1, 2, 3), (4, 5, 6))
        b = SF_Array..AppendRow(Array(), Array(1, 2, 3))
            ' ∀ i ∈ {0 ≤ i ≤ 2} : b(i, 0) ≡ i

## Contains

Comprobe se unha matriz unidimensional contén determinado número, texto ou data. A comparación de texto pode distinguir maiúsculas de minúsculas ou non.
As matrices de entrada ordenadas teñen que ser enchidas homoxeneamente, o que significa que todos os elementos deben ser escalares do mesmo tipo (non se permiten elementos Baleiro e Null).
O resultado do método é impredicíbel se a matriz se anuncia como ordenada cando de feito non o está.
Realízase unha busca binaria cando a matriz está ordenada; caso contrario, simplemente se analiza de arriba a abaixo e se ignoran os elementos Baleiro e Null.

### Sintaxe:

svc.Contains(array_1d: any[0..*], tofind: any, casesensitive: bool = False, sortorder: str = ""): bool

### Parámetros:

matriz_1d: A matriz que se vai analizar.

paraAtopar: Un número, unha data ou unha cadea que atopar.

maiúsculasMinúsculas: Só para a comparación de cadeas (Por omisión = Falso).

tipoOrdenación: pode ser «ASC», «DESC» ou «» (sen ordenar). O valor por omisión é "".

### Exemplo:

        Dim a As Variant
        a = SF_Array.Contains(Array("A","B","c","D"), "C", SortOrder := "ASC") ' True
        SF_Array.Contains(Array("A","B","c","D"), "C", CaseSensitive := True) ' False

## ConvertToDictionary

Almacena o contido dunha matriz bidimensional non obxecto de ScriptForge.Dictionary.
A chave extráese da primeira columna, o elemento da segunda.

### Sintaxe:

svc.ConvertToDictionary(array_2d: any[0..*, 0..1]): obj

### Parámetros:

matriz_2d: Dato que se converten nun obxecto de ScriptForge.Dictioanry.

- A primeira columna debe conter exclusivamente cadeas dunha lonxitude maior que cero, en calquera orde. Estes valores empréganse como etiquetas no dicionario.

- A segunda columna contén os datos que se asociarán á etiqueta correspondente do dicionario.

### Exemplo:

        Dim a As Variant, b As Variant
        a = SF_Array.AppendColumn(Array("a", "b", "c"), Array(1, 2, 3))
        b = SF_Array.ConvertToDictionary(a)
        MsgBox b.Item("c") ' 3

## Copy

Crea unha copia dunha matriz de unha ou dúas dimensións.

### Sintaxe:

svc.Copy(array_nd: any[0..*]): any[0..*]

svc.Copy(array_nd: any[0..*, 0..*]): any[0..*, 0..*]

### Parámetros:

matriz_nd: A matriz 1D ou 2D que se vai copiar.

### Exemplo:

Unha asignación simple dun obxecto Matriz copia esta referencia no canto de crear unha copia do contido do obxecto. Vexa o exemplo aquí abaixo:

        Dim a as Variant, b as Variant
        a = Array(1, 2, 3)
        ' A asignación de abaixo faise por referencia
        b = a
        ' Logo, cambiar os valores de «b» cambiará tamén «a»
        b(0) = 10
        MsgBox a(0) ' 10

Ao empregar o método Copiar faise unha copia do obxecto Matriz enteiro. No exemplo de embaixo, a e b son obxectos diferentes e cambiar valores en b non afecta os valores de a.

        Dim a as Variant, b as Variant
        a = Array(1, 2, 3)
        ' Crea unha copia de «a» empregando o método «Copiar»
        b = SF_Array.Copy(a)
        b(0) = 10
        MsgBox a(0) ' 1

## CountDims

Conta o número de dimensións dunha matriz. O resultado pode ser maior que 2.
Se o argumento non é unha matriz devolve -1
Se a matriz non está inicializada devolve 0.

### Sintaxe:

svc.CountDims(array_nd: any): int

### Parámetros:

matriz_nd: A matriz que se examina.

### Exemplo:

        Dim a(1 To 10, -3 To 12, 5)
        MsgBox SF_Array.CountDims(a) ' 3

## Difference

Constrúa un conxunto, como matriz indexada en cero, aplicando a operador de diferenza nas dúas matrices de entrada. Os elementos resultantes orixínanse da primeira matriz e non da segunda
A matriz resultante ordénase de maneira ascendente.
Ambas as dúas matrices de entrada teñen que ser enchidas homoxeneamente, os seus elementos deben ser escalares do mesmo tipo. Os elementos Baleiro e Null están prohibidos.
A comparación de texto pode distinguir maiúsculas de minúsculas ou non.

### Sintaxe:

svc.Difference(array1_1d: any[0..*], array2_1d: any[0..*], casesensitive: bool = False): any[0..*]

### Parámetros:

matriz1_1d: Unha matriz de referencia unidimensional cuxos elementos se examinan para seren retirados.

matriz2_1d: Unha matriz unidimensional cuxos elementos se substraen da primeira matriz de entrada.

maiúsculasMinúsculas: Este argumento só se aplica se as matrices consisten en cadeas (Por omisión = Falso).

### Exemplo:

        Dim a As Variant
        a = SF_Array.Difference(Array("A", "C", "A", "b", "B"), Array("C", "Z", "b"), True)
            ' ("A", "B")

## ExportToTextFile

Escribe todos os elementos da matriz secuencialmente nun ficheiro de texto. Se o ficheiro xa existe, este será substituído sen aviso.

### Sintaxe:

svc.ExportToTextFile(array_1d: any[0..*], filename: str, [encoding: str]): bool

### Parámetros:

matriz_1d: A matriz que se exporta. Só pode contar con cadeas.

nomeDeFicheiro: O nome do ficheiro de texto no que se escriben os datos. O nome debe ser expresado conforme á propiedade NomesFicheiro do servizo SF_FileSystem.

codificación: O conxunto de caracteres que hai que empregar. Utilice un dos nomes listados en Conxuntos de caracteres de IANA. Teña en conta que o LibreOffice podería non contar con todos os conxuntos de caracteres (o predeterminado é «UTF-8»).

### Exemplo:

        SF_Array.ExportToTextFile(Array("A","B","C","D"), "C:\Temp\A short file.txt")

## ExtractColumn

Extrae unha columna específica dunha matriz bidimensional como nova matriz.
Os seus límites inferior LBound e superior UBound son idénticos ao da primeira dimensión da matriz de entrada.

### Sintaxe:

svc.ExtractColumn(array_2d: any[0..*, 0..*], columnindex: int): any[0..*, 0..*]

### Parámetros:

array_2d: A matriz da que extraer.

columnindex: O número de columna que hai que extraer . Debe estar no intervalo [LBound, UBound].

### Exemplo:

        'Crea unha matriz 3x3: |1, 2, 3|
        '                      |4, 5, 6|
        '                      |7, 8, 9|
        Dim mat as Variant, col as Variant
        mat = SF_Array.AppendRow(Array(), Array(1, 2, 3))
        mat = SF_Array.AppendRow(mat, Array(4, 5, 6))
        mat = SF_Array.AppendRow(mat, Array(7, 8, 9))
        'Extrae a terceira coluna: |3, 6, 9|
        col = SF_Array.ExtractColumn(mat, 2)

## ExtractRow

Extract from a two dimension array a specific row as a new array.
Its lower LBound and upper UBound boundaries are identical to that of the second dimension of the input array.

### Sintaxe:

svc.ExtractRow(array_2d: any[0..*, 0..*], rowindex: int): any[0..*, 0..*]

### Parámetros:

array_2d: A matriz da que extraer.

rowindex: The row number to extract - must be in the interval [LBound, UBound].

### Exemplo:

        'Crea unha matriz 3x3: |1, 2, 3|
        '                      |4, 5, 6|
        '                      |7, 8, 9|
        Dim mat as Variant, row as Variant
        mat = SF_Array.AppendRow(Array(), Array(1, 2, 3))
        mat = SF_Array.AppendRow(mat, Array(4, 5, 6))
        mat = SF_Array.AppendRow(mat, Array(7, 8, 9))
        'Extrae a primeira fila: |1, 2, 3|
        row = SF_Array.ExtractRow(mat, 0)

## Flatten

Stack all single items of an array and all items in its subarrays into one new array without subarrays. Empty subarrays are ignored and subarrays with a number of dimensions greater than one are not flattened.

### Sintaxe:

svc.Flatten(array_1d: any[0..*]): any[0..*]

### Parámetros:

array_1d: A matriz preexistente pode estar baleira.

### Exemplo:

        Dim a As Variant
        a = SF_Array.Flatten(Array(Array(1, 2, 3), 4, 5))
            ' (1, 2, 3, 4, 5)

You can use the Flatten method along with other methods such as Append or Prepend to concatenate a set of 1D arrays into a single 1D array.

### Exemplo:

Next is an example of how the methods Flatten and Append can be combined to concatenate three arrays.

        'Crea tres matrices para este exemplo
        Dim a as Variant, b as Variant, c as Variant
        a = Array(1, 2, 3)
        b = Array(4, 5)
        c = Array(6, 7, 8, 9)
        'Concatena as tres matrices nun único arraz de unha dimensión
        Dim arr as Variant
        arr = SF_Array.Flatten(SF_Array.Append(a, b, c))
        '(1, 2, 3, 4, 5, 6, 7, 8, 9)

## ImportFromCSVFile

Importar os datos contidos nun ficheiro de valores separados por vírgulas (CSV). A vírgula pode ser substituída por calquera carácter.

The applicable CSV format is described in IETF Common Format and MIME Type for CSV Files.

Each line in the file contains a full record (line splitting is not allowed).
However sequences like \n, \t, ... are left unchanged. Use SF_String.Unescape() method to manage them.

The method returns a two dimension array whose rows correspond to a single record read in the file and whose columns correspond to a field of the record. No check is made about the coherence of the field types across columns. A best guess will be made to identify numeric and date types.

If a line contains less or more fields than the first line in the file, an exception will be raised. Empty lines however are simply ignored. If the size of the file exceeds the number of items limit (see inside the code), a warning is raised and the array is truncated.

### Sintaxe:

svc.ImportFromCSVFile(filename: str, delimiter: str = ',', dateformat: str = ''): any[0..*]

### Parámetros:

filename: The name of the text file containing the data. The name must be expressed according to the current FileNaming property of the SF_FileSystem service.

delimiter: A single character, usually, a comma, a semicolon or a TAB character (Default = ",").

dateformat: A special mechanism handles dates when dateformat is either "YYYY-MM-DD", "DD-MM-YYYY" or "MM-DD-YYYY". The dash (-) may be replaced by a dot (.), a slash (/) or a space. Other date formats will be ignored. Dates defaulting to an empty string "" are considered as normal text.

### Exemplo:

Consider the CSV file "myFile.csv" with the following contents:

Name,DateOfBirth,Address,City

Anna,2002/03/31,"Rue de l'église, 21",Toulouse

Fred,1998/05/04,"Rue Albert Einstein, 113A",Carcassonne

The examples below in Basic and Python read the contents of the CSV file into an Array object.

##### In Basic

        Dim arr As Variant
        arr = SF_Array.ImportFromCSVFile("C:\Temp\myFile.csv", DateFormat := "YYYY/MM/DD")
        MsgBox arr(0, 3) ' City
        MsgBox arr(1, 2) ' Rue de l'église, 21
        MsgBox arr(1, 3) ' Toulouse

##### In Python

        from scriptforge import CreateScriptService
        svc = CreateScriptService("Array")
        bas = CreateScriptService("Basic")
        arr = svc.ImportFromCSVFile(r"C:\Temp\myFile.csv", dateformat = "YYYY/MM/DD")
        bas.MsgBox(arr[0][3]) # City
        bas.MsgBox(arr[1][2]) # Rue de l'église, 21
        bas.MsgBox(arr[1][3]) # Toulouse

## IndexOf

Look in a one dimension array for a number, a string or a date. Text comparison can be case-sensitive or not.
If the array is sorted it must be filled homogeneously, which means that all items must be scalars of the same type (Empty and Null items are forbidden).
The result of the method is unpredictable when the array is announced as sorted and actually is not.
A binary search is performed on sorted arrays. Otherwise, arrays are simply scanned from top to bottom and Empty and Null items are ignored.
The method returns LBound(input array) - 1 if the search was not successful.

### Sintaxe:

svc.IndexOf(array_1d: any[0..*], tofind: any, casesensitive: bool = False, sortorder: str = ''): int

### Parámetros:

array_1d: The array to scan.

tofind: A number, a date or a string to find.

casesensitive: Only for string comparisons (Default = False).

sortorder: It can be either "ASC", "DESC" or "" (not sorted). The default value is "".

### Exemplo:

        MsgBox SF_Array.IndexOf(Array("A","B","c","D"), "C", SortOrder := "ASC") ' 2
        MsgBox SF_Array.IndexOf(Array("A","B","c","D"), "C", CaseSensitive := True) ' -1

## Insert

Insert before a given index of the input array the items listed as arguments.
Arguments are inserted blindly. Each of them might be either a scalar of any type or a subarray.

### Sintaxe:

svc.Insert(array_1d: any[0..*], before: int, arg0: any, [arg1: any] ...): any[0..*]

### Parámetros:

array_1d: The pre-existing array, may be empty.

before: The index before which to insert; must be in the interval [LBound, UBound + 1].

arg0, arg1, ...: Items that will be inserted into array_1d.

### Exemplo:

        Dim a As Variant
        a = SF_Array.Insert(Array(1, 2, 3), 2, "a", "b")
            ' (1, 2, "a", "b", 3)

## InsertSorted

Inserts into a sorted array a new item on its place.
The array must be filled homogeneously, meaning that all items must be scalars of the same type.
Empty and Null items are forbidden.

### Sintaxe:

svc.InsertSorted(array_1d: any[0..*], item: any, sortorder: str = 'ASC', casesensitive: bool = False): any[0..*]

### Parámetros:

array_1d: The array into which the value will be inserted.

item: The scalar value to insert, of the same type as the existing array items.

sortorder: It can be either "ASC" (default) or "DESC".

casesensitive: Only for string comparisons (Default = False).

### Exemplo:

        Dim a As Variant
        a = SF_Array.InsertSorted(Array("A", "C", "a", "b"), "B", CaseSensitive := True)
            ' ("A", "B", "C", "a", "b")

## Intersection

Build a set, as a zero-based array, by applying the intersection set operator on the two input arrays. Resulting items are contained in both arrays.
The resulting array is sorted in ascending order.
Both input arrays must be filled homogeneously, in other words all items must be scalars of the same type. Empty and Null items are forbidden.
Text comparison can be case sensitive or not.

### Sintaxe:

svc.Intersection(array1_1d: any[0..*], array2_1d: any[0..*], casesensitive: bool = False): any[0..*]

### Parámetros:

array1_1d: The first input array.

array2_1d: The second input array.

casesensitive: Applies to arrays populated with text items (Default = False).

### Exemplo:

        Dim a As Variant
        a = SF_Array.Intersection(Array("A", "C", "A", "b", "B"), Array("C", "Z", "b"), True)
            ' ("C", "b")

## Join2D

Join a two-dimensional array with two delimiters, one for the columns, one for the rows.

### Sintaxe:

svc.Join2D(array_2d: any [0..*, 0..*], [columndelimiter: str], [rowdelimiter: str], [quote: str]): str

### Parámetros:

array_2d: Each item must be either text, a number, a date or a boolean.
Dates are transformed into the YYYY-MM-DD hh:mm:ss format.
Invalid items are replaced by a zero-length string.

columndelimiter: Delimits each column (default = Tab/Chr(9)).

rowdelimiter: Delimits each row (default = LineFeed/Chr(10))

quote: If True, protect strings with double quotes. The default is False.

### Exemplo:

        ' arr = | 1, 2, "A", [2020-02-29], 51, 2, "A", [2020-02-29], 5           |
        '       | 6, 7, "this is a string", 9, 106, 7, "this is a string", 9, 10 |
        Dim arr as Variant : arr = Array()
        arr = SF_Array.AppendRow(arr, Array(1, 2, "A", [2020-02-29], 51, 2, "A", [2020-02-29], 5))
        arr = SF_Array.AppendRow(arr, Array(6, 7, "this is a string", 9, 106, 7, "this is a string", 9, 10))
        Dim arrText as String
        arrText = SF_Array.Join2D(arr, ",", "/", False)
        ' 1,2,A,,51,2,A,,5/6,7,this is a string,9,106,7,this is a string,9,10

## Prepend

Prepend at the beginning of the input array the items listed as arguments.

### Sintaxe:

svc.Prepend(array_1d: any[0..*], arg0: any, [arg1: any] ...): any[0..*]

### Parámetros:

array_1d: The pre-existing array, may be empty.

arg0, arg1, ...: A list of items to prepend to array_1d.

### Exemplo:

        Dim a As Variant
        a = SF_Array.Prepend(Array(1, 2, 3), 4, 5)
            ' (4, 5, 1, 2, 3)

## PrependColumn

Prepend to the left side of a two dimension array a new column. The resulting array has the same lower boundaries as the initial two dimension array.

### Sintaxe:

svc.PrependColumn(array_2d: any[0..*, 0..*], column: any[0..*]): any[0..*, 0..*]

### Parámetros:

array_2d: The pre-existing array, may be empty. If that array has 1 dimension, it is considered as the last column of the resulting 2 dimension array.

column: A 1-dimensional array with as many items as there are rows in array_2d.

### Exemplo:

        Dim a As Variant, b As variant
        a = SF_Array.PrependColumn(Array(1, 2, 3), Array(4, 5, 6))
            ' ((4, 1), (5, 2), (6, 3))
        b = SF_Array.PrependColumn(Array(), Array(1, 2, 3))
            ' ∀ i ∈ {0 ≤ i ≤ 2} : b(0, i) ≡ i

## PrependRow

Prepend a new row at the beginning of a 2-dimensional array. The resulting array has the same lower boundaries as the initial 2-dimensional array.

### Sintaxe:

svc.PrependRow(array_2d: any[0..*, 0..*], row: any[0..*]): any[0..*, 0..*]

### Parámetros:

array_2d: The pre-existing array, may be empty. If that array has 1 dimension, it is considered as the last row of the resulting 2-dimensional array.

row: A 1-dimensional array containing as many items as there are columns in array_2d.

### Exemplo:

        Dim a As Variant, b As variant
        a = SF_Array.PrependRow(Array(1, 2, 3), Array(4, 5, 6))
            ' ((4, 5, 6), (1, 2, 3))
        b = SF_Array.PrependRow(Array(), Array(1, 2, 3))
            ' ∀ i ∈ {0 ≤ i ≤ 2} : b(i, 0) ≡ i

## RangeInit

Initialize a new zero-based array with numeric values.

### Sintaxe:

svc.RangeInit(from: num, upto: num, [bystep: num]): num[0..*]

### Parámetros:

from: Value of the first item.

upto: The last item should not exceed UpTo.

bystep: The difference between two successive items (Default = 1).

### Exemplo:

        Dim a As Variant
        a = SF_Array.RangeInit(10, 1, -1)
            ' (10, 9, 8, 7, 6, 5, 4, 3, 2, 1)

## Reverse

Return the reversed one dimension input array.

### Sintaxe:

svc.Reverse(array_1d: any[0..*]): any[0..*]

### Parámetros:

array_1d: The array to reverse.

### Exemplo:

        Dim a As Variant
        a = SF_Array.Reverse(Array("a", 2, 3, 4))
            ' (4, 3, 2, "a")

## Shuffle

Returns a random permutation of a one-dimensional array.

### Sintaxe:

svc.Shuffle(array_1d: any[0..*]): any[0..*]

### Parámetros:

array_1d: The array to shuffle.

### Exemplo:

        Dim a As Variant
        a = SF_Array.Shuffle(Array(1, 2, 3, 4))
            ' Array "a" is now in random order, f.i. (2, 3, 1, 4)

## Slice

Returns a subset of a one-dimensional array.

### Sintaxe:

svc.Slice(array_1d: any[0..*], from: int, [upto: int]): any[0..*]

### Parámetros:

array_1d: The array to slice.

from: The lower index in array_1d of the subarray to extract (from included)

upto: The upper index in array_1d of the subarray to extract (upto included). The default value is the upper bound of array_1d. If upto < from then the returned array is empty.

### Exemplo:

        Dim a As Variant
        a = SF_Array.Slice(Array(1, 2, 3, 4, 5), 1, 3) ' (2, 3, 4)

## Sort

Sort a one dimension array in ascending or descending order. Text comparisons can be case-sensitive or not.
The array must be filled homogeneously, which means that items must be scalars of the same type.
Empty and Null items are allowed. Conventionally Empty < Null < any other scalar value.

### Sintaxe:

svc.Sort(array_1d: any[0..*], sortorder: str, casesensitive: bool = False): any[0..*]

### Parámetros:

array_1d: The array to sort.

sortorder: It can be either "ASC" (default) or "DESC".

casesensitive: Only for string comparisons (Default = False).

### Exemplo:

        Dim a As Variant
        a = SF_Array.Sort(Array("a", "A", "b", "B", "C"), CaseSensitive := True)
            ' ("A", "B", "C", "a", "b")

## SortColumns

Return a permutation of the columns of a two dimension array, sorted on the values of a given row.
The row must be filled homogeneously, which means that all items must be scalars of the same type.
Empty and Null items are allowed. Conventionally Empty < Null < any other scalar value.

### Sintaxe:

svc.SortColumns(array_2d: any[0..*, 0..*], rowindex: int, sortorder: str, casesensitive: bool = False): any[0..*, 0..*]

### Parámetros:

array_2d: The 2-dimensional array to sort.

rowindex: The index of the row that will be used as reference to sort the columns.

sortorder: It can be either "ASC" (default) or "DESC".

casesensitive: Only for string comparisons (Default = False).

### Exemplo:

        ' arr = | 5, 7, 3 |
        '       | 1, 9, 5 |
        '       | 6, 1, 8 |
        Dim arr as Variant : arr = Array(5, 7, 3)
        arr = SF_Array.AppendRow(arr, Array(1, 9, 5))
        arr = SF_Array.AppendRow(arr, Array(6, 1, 8))
        arr = SF_Array.SortColumns(arr, 2, "ASC")
        ' arr = | 7, 5, 3 |
        '       | 9, 1, 5 |
        '       | 1, 6, 8 |

## SortRows

Return a permutation of the rows of a two dimension array, sorted on the values of a given column.
The column must be filled homogeneously, therefore all items must be scalars of the same type.
Empty and Null items are allowed. Conventionally Empty < Null < any other scalar value.

### Sintaxe:

svc.SortRows(array_2d: any[0..*, 0..*], columnindex: int, sortorder: str, casesensitive: bool = False): any[0..*, 0..*]

### Parámetros:

array_2d: The array to sort.

columnindex: The index of the column that will be used as reference to sort the rows.

sortorder: It can be either "ASC" (default) or "DESC".

casesensitive: Only for string comparisons (Default = False).

### Exemplo:

        ' arr = | 5, 7, 3 |
        '       | 1, 9, 5 |
        '       | 6, 1, 8 |
        Dim arr as Variant : arr = Array(5, 7, 3)
        arr = SF_Array.AppendRow(arr, Array(1, 9, 5))
        arr = SF_Array.AppendRow(arr, Array(6, 1, 8))
        arr = SF_Array.SortRows(arr, 0, "ASC")
        ' arr = | 1, 9, 5 |
        '       | 5, 7, 3 |
        '       | 6, 1, 8 |

## Transpose

Swaps rows and columns in a two-dimensional array.

### Sintaxe:

svc.Transpose(array_2d: any[0..*, 0..*]): any[0..*, 0..*]

### Parámetros:

array_2d: The 2-dimensional array to transpose.

### Exemplo:

        ' arr1 = | 1, 2 |
        '        | 3, 4 |
        '        | 5, 6 |
        arr1 = Array(1, 2)
        arr1 = SF_Array.AppendRow(arr1, Array(3, 4))
        arr1 = SF_Array.AppendRow(arr1, Array(5, 6))
        arr2 = SF_Array.Transpose(arr1)
        ' arr2 = | 1, 3, 5 |
        '        | 2, 4, 6 |
        MsgBox arr2(0, 2) ' 5

## TrimArray

Remove from a one dimension array all Null, Empty and zero-length entries.
String items are trimmed with LibreOffice Basic Trim() function.

### Sintaxe:

svc.TrimArray(array_1d: any[0..*]): any[0..*]

### Parámetros:

array_1d: The array to trim.

### Exemplo:

        Dim a As Variant
        a = SF_Array.TrimArray(Array("A", "B", Null, " D "))
            ' ("A", "B", "D")

## Union

Builds a set, as a zero-based array, by applying the union operator on the two input arrays. Resulting items originate from any of both arrays.
The resulting array is sorted in ascending order.
Both input arrays must be filled homogeneously, their items must be scalars of the same type. Empty and Null items are forbidden.
Text comparison can be case sensitive or not.

### Sintaxe:

svc.Union(array1_1d: any[0..*], array2_1d: any[0..*], casesensitive: bool = False): any[0..*]

### Parámetros:

array1_1d: The first input array.

array2_1d: The second input array.

casesensitive: Applicable only if the arrays are populated with strings (Default = False).

### Exemplo:

        Dim a As Variant
        a = SF_Array.Union(Array("A", "C", "A", "b", "B"), Array("C", "Z", "b"), True)
            ' ("A", "B", "C", "Z", "b")

## Unique

Build a set of unique values derived from the input array.
The input array must be filled homogeneously, its items must be scalars of the same type. Empty and Null items are forbidden.
Text comparison can be case sensitive or not.

### Sintaxe:

svc.Unique(array_1d: any[0..*], casesensitive: bool = False): any[0..*]

### Parámetros:

array_1d: The input array.

casesensitive: Applicable only if the array is populated with strings (Default = False).

### Exemplo:

        Dim a As Variant
        a = SF_Array.Unique(Array("A", "C", "A", "b", "B"), CaseSensitive := True)
            '  ("A", "B", "C", "b")

Todas as rutinas ou identificadores BASIC ScriptForge que están precedidas por un carácter de guión baixo «_» están reservadas para uso interno. Non se deben utilizar en macros BASIC ou scripts de Python.

Temas relacionados

Funcións de matriz

Using Calc Functions in Macros

ScriptForge.Dictionary service

Precisamos da súa axuda!