SuperCollider CLASSES

# Array

fixed size collection
Source: /usr/local/share/SuperCollider/SCClassLibrary/Common/Collections/Array.sc

## Description

Arrays are ArrayedCollections whose slots may contain any object. Arrays have a fixed maximum size beyond which they cannot grow. For expandable arrays, use the List class.

Literal Arrays can be created at compile time, and are very efficient. See Literals for information.

For handling multidimensional arrays, there are specific methods which are covered in the helpfile J concepts in SC.

NOTE: For Arrays, the add method may or may not return the same Array object. It will add the argument to the receiver if there is space, otherwise it returns a new Array object with the argument added. Thus the proper usage of add with an Array is to always assign the result as follows:
    z = z.add(obj);

This allows an efficient use of resources, only growing the array when it needs to. The List class manages the Array internally, and in many cases is more suitable.

Elements can be put into an existing slot with a.put(2,obj) and accessed with a.at(2) or a[2]

See ArrayedCollection for the principal methods: at, put, clipAt, wrapAt, etc...

## Class Methods

### *new (maxSize: 0)

From superclass: Object

Create a new array with size 0 that can grow up to the fixed size.

#### Arguments:

 maxSize The maximum size of the array.

### *newClear (indexedSize: 0)

From superclass: ArrayedCollection

Create a new array with all slots filled with nils.

#### Arguments:

 indexedSize The size of the array.

### *with ( ... args)

Create a new Array whose slots are filled with the given arguments. This is the same as the method in ArrayedCollection, but is reimplemented here to be more efficient.

Array.with(7, 'eight',  9).postln;

### *fill (size, function)

From superclass: Collection

Creates a Collection of the given size, the elements of which are determined by evaluation the given function. The function is passed the index as an argument.

Array.fill(4, { arg i; i * 2 });
Bag.fill(14, { arg i; i.rand });

#### Arguments:

 size The size of the collection which is returned. If nil, it returns an empty collection. If an array of sizes is given, the resulting collection has the appropriate dimensions (see: *fillND).Array.fill([2, 2, 3], { arg i, j, k; i * 100 + (j * 10) + k }); function The function which is called for each new element - the index is passed in as a first argument. The function be anything that responds to the message "value".Array.fill(10, { arg i; 2 ** i }); Array.fill(10, Pxrand([0, 1, 2], inf).iter); Array.fill(10, 7); // an object that doesn't respond with a new value is just repeatedly added.

### *fill2D (rows, cols, function)

From superclass: Collection

Creates a 2 dimensional Collection of the given sizes. The items are determined by evaluation of the supplied function. The function is passed row and column indexes as arguments. See J concepts in SC

Array.fill2D(2, 4, 0);
Array.fill2D(3, 4, { arg r, c; r*c+c; });

### *fillND (dimensions, function, args: [ ])

From superclass: Collection

Creates a N dimensional Collection where N is the size of the array dimensions. The items are determined by evaluation of the supplied function. The function is passed N number of indexes as arguments. See J concepts in SC

Array.fillND([4, 4], { arg a, b; a+b; });                // 2D
Array.fillND([4, 4, 4], { arg a, b, c; a+b*c; });        // 3D
Array.fillND([1, 2, 3, 4], { arg a, b, c, d; b+d; });    // 4D

### *newFrom (aCollection)

From superclass: Collection

Creates a new Collection from another collection. This supports the interface for the method "as".

Array.newFrom(Set[4, 2, 1]);
Set.newFrom(Array[4, 2, 1]);
[1, 2, 3, 4, 3, 2].as(Set); // as(someClass) calls someClass.newFrom(this)

### *geom (size, start, grow)

From superclass: SequenceableCollection

Fill an ArrayedCollection with a geometric series.

Array.geom(5, 1, 3).postln;

### *series (size, start: 0, step: 1)

From superclass: SequenceableCollection

Fill an ArrayedCollection with an arithmetic series.

Array.series(5, 10, 2).postln;

### *iota ( ... sizes)

From superclass: ArrayedCollection

Fills an ArrayedCollection with a counter. See J concepts in SC for more examples.

Array.iota(2, 3);
Array.iota(2, 3, 4);

## Instance Methods

### -at (index)

From superclass: ArrayedCollection

Return the item at index.

The index can also be an Array of indices to extract specified elements. Example:

x = [10,20,30];
y = [0,0,2,2,1];
x[y]; // returns [ 10, 10, 30, 30, 20 ]

### -put (index, item)

From superclass: ArrayedCollection

Put item at index, replacing what is there.

### -insert (index, item)

From superclass: ArrayedCollection

Inserts the item into the contents of the receiver. This method may return a new ArrayedCollection. For this reason, you should always assign the result of insert to a variable - never depend on add changing the receiver.

(
// in this case a new object is returned
var y, z;
z = [1, 2, 3, 4];
y = z.insert(1, 999);
z.postln;
y.postln;
)

### -clipAt (index)

From superclass: ArrayedCollection

Same as -at, but values for index greater than the size of the ArrayedCollection will be clipped to the last index.

y = [ 1, 2, 3 ];
y.clipAt(13).postln;

### -wrapAt (index)

From superclass: ArrayedCollection

Same as -at, but values for index greater than the size of the ArrayedCollection will be wrapped around to 0.

y = [ 1, 2, 3 ];
y.wrapAt(3).postln; // this returns the value at index 0
y.wrapAt(4).postln; // this returns the value at index 1
y.wrapAt([-2, 1])   // index can also be a collection or negative numbers

### -foldAt (index)

From superclass: ArrayedCollection

Same as -at, but values for index greater than the size of the ArrayedCollection will be folded back.

y = [ 1, 2, 3 ];
y.foldAt(3).postln; // this returns the value at index 1
y.foldAt(4).postln; // this returns the value at index 0
y.foldAt(5).postln; // this returns the value at index 1

### -clipPut (index, item)

From superclass: ArrayedCollection

Same as -put, but values for index greater than the size of the ArrayedCollection will be clipped to the last index.

### -wrapPut (index, item)

From superclass: ArrayedCollection

Same as -put, but values for index greater than the size of the ArrayedCollection will be wrapped around to 0.

### -foldPut (index, item)

From superclass: ArrayedCollection

Same as -put, but values for index greater than the size of the ArrayedCollection will be folded back.

### -swap (i, j)

From superclass: ArrayedCollection

Swap the values at indices i and j.

[ 1, 2, 3 ].swap(0, 2).postln;

### -replace (find, replace)

From superclass: ArrayedCollection

Return a new array in which a number of elements have been replaced by another.

a = (0..10) ++ (0..10);
a.replace([4, 5, 6], 100);
a.replace([4, 5, 6], [1734, 1985, 1860]);

this method is inherited by String :

a = "hello world";
a.replace("world", "word");

### -++ (anArray)

From superclass: ArrayedCollection

Concatenate the contents of the two collections into a new ArrayedCollection.

(
var y, z;
z = [1, 2, 3, 4];
y = z ++ [7, 8, 9];
z.postln;
y.postln;
)

From superclass: ArrayedCollection

Adds an item to an ArrayedCollection if there is space. This method may return a new ArrayedCollection. For this reason, you should always assign the result of add to a variable - never depend on add changing the receiver.

(
// z and y are the same object
var y, z;
z = [1, 2, 3];
z.postln;
y.postln;
)

(
// in this case a new object is returned
var y, z;
z = [1, 2, 3, 4];
z.postln;
y.postln;
)

From superclass: ArrayedCollection

Adds all the elements of aCollection to the contents of the receiver. This method may return a new ArrayedCollection. For this reason, you should always assign the result of addAll to a variable - never depend on add changing the receiver.

(
// in this case a new object is returned
var y, z;
z = [1, 2, 3, 4];
z.postln;
y.postln;
)

From superclass: ArrayedCollection

Inserts the item before the contents of the receiver, possibly returning a new collection.

(
// in this case a new object is returned
var y, z;
z = [1, 2, 3, 4];
z.postln;
y.postln;
)

### -removeAt (index)

From superclass: ArrayedCollection

Remove and return the element at index, shrinking the size of the ArrayedCollection.

y = [ 1, 2, 3 ];
y.removeAt(1);
y.postln;

### -collect (function)

From superclass: Collection

Answer a new collection which consists of the results of function evaluated for each item in the collection. The function is passed two arguments, the item and an integer index. See Collection helpfile for examples.

### -do (function)

From superclass: ArrayedCollection

Iterate over the elements in order, calling the function for each element. The function is passed two arguments, the element and an index.

['a', 'b', 'c'].do({ arg item, i; [i, item].postln; });

### -reverseDo (function)

From superclass: ArrayedCollection

Iterate over the elements in reverse order, calling the function for each element. The function is passed two arguments, the element and an index.

['a', 'b', 'c'].reverseDo({ arg item, i; [i, item].postln; });

### -deepCollect (depth: 1, function, index: 0, rank: 0)

From superclass: ArrayedCollection

The same as -collect, but can look inside sub-arrays up to the specified depth.

a = [99, [4,6,5], [[32]]];
a.deepCollect(1, {|item| item.isArray}).postln;
a.deepCollect(2, {|item| item.isArray}).postln;
a.deepCollect(3, {|item| item.isArray}).postln;

### -reshape ( ... shape)

From superclass: ArrayedCollection

For a multidimensional array, rearranges the data using the desired number of elements along each dimension. The data may be extended using wrapExtend if needed.

a = [4,7,6,8];
a.reshape(2,2);
a.reshape(2,3);

### -windex

From superclass: ArrayedCollection

Interprets the array as a list of probabilities which should sum to 1.0 and returns a random index value based on those probabilities.

(
Array.fill(10, {
[0.1, 0.6, 0.3].windex;
}).postln;
)

### -size

From superclass: ArrayedCollection

Return the number of elements the ArrayedCollection.

### -normalize (min: 0, max: 1)

From superclass: ArrayedCollection

Returns a new Array with the receiver items normalized between min and max.

[1, 2, 3].normalize;            //default min=0, max= 1
[1, 2, 3].normalize(-20, 10);

### -normalizeSum

From superclass: ArrayedCollection

Returns the Array resulting from :

(this / this.sum)

so that the array will sum to 1.0.

This is useful for using with windex or wchoose.

[1, 2, 3].normalizeSum.postln;

### -plot (name, bounds, discrete: false, numChannels, minval, maxval)

From superclass: ArrayedCollection

Plot data in a GUI window. See plot for more details.

### -reverse

Returns a new Array whose elements are reversed. The receiver is unchanged.

x = [1, 2, 3];
z = x.reverse;
x.postln;
z.postln;

### -scramble

Returns a new Array whose elements have been scrambled. The receiver is unchanged.

[1, 2, 3, 4, 5, 6].scramble.postln;

### -mirror

[1, 2, 3, 4].mirror.postln;

### -mirror1

Return a new Array which is the receiver made into a palindrome with the last element removed. This is useful if the list will be repeated cyclically, the first element will not get played twice. The receiver is unchanged.

[1, 2, 3, 4].mirror1.postln;

### -mirror2

Return a new Array which is the receiver concatenated with a reversal of itself. The center element is duplicated. The receiver is unchanged.

[1, 2, 3, 4].mirror2.postln;

### -stutter (n: 2)

Return a new Array whose elements are repeated n times. The receiver is unchanged.

[1, 2, 3].stutter(2).postln;

#### Arguments:

 n Number of repeats.

### -rotate (n: 1)

Return a new Array whose elements are in rotated order. The receiver is unchanged.

[1, 2, 3, 4, 5].rotate(1).postln;
[1, 2, 3, 4, 5].rotate(-1).postln;
[1, 2, 3, 4, 5].rotate(3).postln;

#### Arguments:

 n Number of elements to rotate. Negative n values rotate left, postive n values rotate right.

### -pyramid (patternType: 1)

Return a new Array whose elements have been reordered via one of 10 "counting" algorithms. Run the examples to see the algorithms.

10.do({ arg i;
[1, 2, 3, 4].pyramid(i + 1).postcs;
});

#### Arguments:

 patternType Choose counting algorithm. The algorithms are numbered 1 through 10.

### -pyramidg (patternType: 1)

Like pyramid, but keep the resulting values grouped in subarrays.

// compare:
[1, 2, 3, 4].pyramid(1).postln;
[1, 2, 3, 4].pyramidg(1).postln;

### -sputter (probability: 0.25, maxlen: 100)

Return a new Array of length maxlen with the items partly repeated (random choice of given probability).

// compare:
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10].sputter(0.5, 16).postln;
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10].sputter(0.8, 8).postln;

#### Arguments:

 probability Probability of repeat. maxlen The length of the new Array.

### -lace (length)

Returns a new Array whose elements are interlaced sequences of the elements of the receiver's subcollections, up to size length. The receiver is unchanged.

x = [ [1, 2, 3], 6, List["foo", 'bar']];
y = x.lace(12);
x.postln;
y.postln;

### -permute (nthPermutation)

Returns a new Array whose elements are the nthPermutation of the elements of the receiver. The receiver is unchanged.

x = [ 1, 2, 3];
6.do({|i| x.permute(i).postln;});

### -allTuples (maxTuples: 16384)

Returns a new Array whose elements contain all possible combinations of the receiver's subcollections.

[[1, 2, 3, 4, 5], [10, 20, 30]].allTuples;
[[1, 2, 3, 4, 5], [10, 20, 30], [5, 6]].allTuples;

### -wrapExtend (length)

Returns a new Array whose elements are repeated sequences of the receiver, up to size length. The receiver is unchanged.

x = [ 1, 2, 3, "foo", 'bar' ];
y = x.wrapExtend(9);
x.postln;
y.postln;

### -foldExtend (length)

Same as wrapExtend but the sequences fold back on the list elements.

x = [ 1, 2, "foo"];
y = x.foldExtend(9);
x.postln;
y.postln;

### -clipExtend (length)

Same as wrapExtend but the sequences "clip" (return their last element) rather than wrapping.

x = [ 1, 2, "foo"];
y = x.clipExtend(9);
x.postln;
y.postln;

### -slide (windowLength: 3, stepSize: 1)

Return a new Array whose elements are repeated subsequences from the receiver. Easier to demonstrate than explain.

[1, 2, 3, 4, 5, 6].slide(3, 1).postcs;
[1, 2, 3, 4, 5, 6].slide(3, 2).postcs;
[1, 2, 3, 4, 5, 6].slide(4, 1).postcs;

### -shift (n, filler: 0)

Shift the values of the array n steps to the right (n positive) or to the left(n negative), dropping the excess and filling empty space with zero.

[1, 2, 3, 4, 5, 6].shift(3).postln;
[1, 2, 3, 4, 5, 6].shift(-3).postln;

### -containsSeqColl

Returns true if the receiver Array contains any instance of SequenceableCollection

[1, 2, 3, 4].containsSeqColl.postln
[1, 2, [3], 4].containsSeqColl.postln

### -powerset

Returns all possible combinations of the array's elements.

[1, 2, 3].powerset.postln
[1, 2, 3].powerset.sort({ |a, b| a.size > b.size }); // sort by size, big first
[1, 2, 3].powerset.sort({ |a, b| a.size > b.size }).reverse; // by size, small first

powerset is also supported in Collection:

Set[1, 2, 3].powerset;
List[1, 2, 3].powerset
(a: 1, b: 2, c: 3).powerset;

### -envirPairs

Given an array of symbols, this returns an array of pairs of (symbol, value) from the current environment. This can then be used as arguments for a Synth, or in an OSC message.

e = (freq: 340, amp: 0.001, strangeness: 0.85);
e.use {
[\amp, \taste, \strangeness].envirPairs;
}

### -flop

Invert rows and colums in a two dimensional Array (turn inside out). See also: Function, SequenceableCollection.

[[1, 2, 3], [4, 5, 6]].flop;
[[1, 2, 3], [4, 5, 6], [7, 8]].flop; // shorter array wraps
[].flop; // result is always 2-d.

### -multiChannelExpand

Used by UGens to perform multi channel expansion. Same as flop.

### -source

Some UGens return Arrays of OutputProxy when instantiated. This method allows you to get at the source UGen.

z = Pan2.ar;
z.postln;
z.source.postln;

### -fork (join, clock, quant: 0, stackSize: 64)

Used within Routines and assumes an array of functions, from which subroutines are created. The subroutines are played while the outer Routine carries on. The join parameter expresses after how many subroutines complete the outer Routine is allowed to go on. By default this happens after all subroutines have completed.

// an array of routine functions:
(
a = [
{ 1.wait; \done_one.postln },
{ 0.5.wait; \done_two.postln },
{ 0.2.wait; \done_three.postln }
];
)
// join after 0
(
Routine {
"join = 0.".postcln;
a.fork(0); \doneAll.postln;
}.play;
)
// join after 1
(
Routine {
"join = 1.".postcln;
a.fork(1); \doneAll.postln;
}.play;
)
// join after all
(
Routine {
"join = a.size (default).".postcln;
a.fork; \doneAll.postln;
}.play;
)

poll(trig, label, trigid)
apply an array of Poll units to an array of UGens (see those helpfiles for more details).

s.boot;
(
x = {
SinOsc.ar([0.1, 0.2], 0).poll * 0.1
}.play;
)
x.trace; // By tracing the Synth you can see the two Poll units we created
x.free

### -dpoll (label, run: 1, trigid: -1)

apply an array of Dpoll units to an array of UGens (see those helpfiles for more details).

### -atIdentityHash (argKey)

This method is used by IdentitySet to search for a key among its members.

### -atIdentityHashInPairs (argKey)

This method is used by IdentityDictionary to search for a key among its members.

### -asString (limit: 512)

From superclass: Object

Returns a string representing the Array. May not be compileable due to ellision (...) of excessive arguments.

### -asCompileString

From superclass: Object

Returns a string that will compile to return an Array equal to the receiver.

### -isValidUGenInput

Returns true. Arrays are valid UGen inputs.

### -asRawOSC

Returns the OSC measse as an Int8Array. Receiver must be a bundle.

[0.1, [\s_new, \default, -1, 1, 1, \freq, 1961]].asRawOSC;