////////////////////////////////////////////////////////////////////// // LibFile: arrays.scad // List and Array manipulation functions. // To use, add the following lines to the beginning of your file: // ``` // use // ``` ////////////////////////////////////////////////////////////////////// // Section: Terminology // - **List**: An ordered collection of zero or more items. ie: ["a", "b", "c"] // - **Vector**: A list of numbers. ie: [4, 5, 6] // - **Array**: A nested list of lists, or list of lists of lists, or deeper. ie: [[2,3], [4,5], [6,7]] // - **Dimension**: The depth of nesting of lists in an array. A List is 1D. A list of lists is 2D. etc. // Section: List Operations // Function: replist() // Usage: // replist(val, n) // Description: // Generates a list or array of `n` copies of the given `list`. // If the count `n` is given as a list of counts, then this creates a // multi-dimensional array, filled with `val`. // Arguments: // val = The value to repeat to make the list or array. // n = The number of copies to make of `val`. // Example: // replist(1, 4); // Returns [1,1,1,1] // replist(8, [2,3]); // Returns [[8,8,8], [8,8,8]] // replist(0, [2,2,3]); // Returns [[[0,0,0],[0,0,0]], [[0,0,0],[0,0,0]]] // replist([1,2,3],3); // Returns [[1,2,3], [1,2,3], [1,2,3]] function replist(val, n, i=0) = is_num(n)? [for(j=[1:1:n]) val] : (i>=len(n))? val : [for (j=[1:1:n[i]]) replist(val, n, i+1)]; // Function: in_list() // Description: Returns true if value `x` is in list `l`. // Arguments: // x = The value to search for. // l = The list to search. // idx = If given, searches the given subindexes for matches for `x`. // Example: // in_list("bar", ["foo", "bar", "baz"]); // Returns true. // in_list("bee", ["foo", "bar", "baz"]); // Returns false. // in_list("bar", [[2,"foo"], [4,"bar"], [3,"baz"]], idx=1); // Returns true. function in_list(x,l,idx=undef) = search([x], l, num_returns_per_match=1, index_col_num=idx) != [[]]; // Function: slice() // Description: // Returns a slice of a list. The first item is index 0. // Negative indexes are counted back from the end. The last item is -1. // Arguments: // arr = The array/list to get the slice of. // st = The index of the first item to return. // end = The index after the last item to return, unless negative, in which case the last item to return. // Example: // slice([3,4,5,6,7,8,9], 3, 5); // Returns [6,7] // slice([3,4,5,6,7,8,9], 2, -1); // Returns [5,6,7,8,9] // slice([3,4,5,6,7,8,9], 1, 1); // Returns [] // slice([3,4,5,6,7,8,9], 6, -1); // Returns [9] // slice([3,4,5,6,7,8,9], 2, -2); // Returns [5,6,7,8] function slice(arr,st,end) = let( s=st<0?(len(arr)+st):st, e=end<0?(len(arr)+end+1):end ) [for (i=[s:1:e-1]) if (e>s) arr[i]]; // Function: select() // Description: // Returns a portion of a list, wrapping around past the beginning, if end=len(list) ? dflt : list[j]], [values[sortind[0]]], [for(i=[1:1:len(sortind)-1]) each assert(indices[sortind[i]]!=indices[sortind[i-1]],"Repeated index") concat( [for(j=[1+indices[sortind[i-1]]:1:indices[sortind[i]]-1]) j>=len(list) ? dflt : list[j]], [values[sortind[i]]] ) ], slice(list,1+lastind, len(list)), replist(dflt, minlen-lastind-1) ); // Function: list_remove() // Usage: // list_remove(list, elements) // Description: // Remove all items from `list` whose indexes are in `elements`. // Arguments: // list = The list to remove items from. // elements = The list of indexes of items to remove. // Example: // list_insert([3,6,9,12],1); // Returns: [3,9,12] // list_insert([3,6,9,12],[1,3]); // Returns: [3,9] function list_remove(list, elements) = !is_list(elements) ? list_remove(list,[elements]) : len(elements)==0 ? list : let( sortind = list_increasing(elements) ? list_range(len(elements)) : sortidx(elements), lastind = elements[select(sortind,-1)] ) assert(lastindp.y) true])==0; // Function: list_decreasing() // Usage: // list_decreasing(list) // Description: // Returns true if the list is (non-strictly) decreasing // Example: // list_decreasing([1,2,3,4]); // Returns: false // list_decreasing([4,2,3,1]); // Returns: false // list_decreasing([4,3,2,1]); // Returns: true function list_decreasing(list) = len([for (p=pair(list)) if(p.xlength)? list_trim(v,length) : list_pad(v,length,fill); // Function: idx() // Usage: // i = idx(list); // for(i=idx(list)) ... // Description: // Returns the range of indexes for the given list. // Arguments: // list = The list to returns the index range of. // step = The step size to stride through the list. Default: 1 // end = The delta from the end of the list. Default: -1 // start = The starting index. Default: 0 // Example(2D): // colors = ["red", "green", "blue"]; // for (i=idx(colors)) right(20*i) color(colors[i]) circle(d=10); function idx(list, step=1, end=-1,start=0) = [start : step : len(list)+end]; // Function: enumerate() // Description: // Returns a list, with each item of the given list `l` numbered in a sublist. // Something like: `[[0,l[0]], [1,l[1]], [2,l[2]], ...]` // Arguments: // l = List to enumerate. // idx = If given, enumerates just the given subindex items of `l`. // Example: // enumerate(["a","b","c"]); // Returns: [[0,"a"], [1,"b"], [2,"c"]] // enumerate([[88,"a"],[76,"b"],[21,"c"]], idx=1); // Returns: [[0,"a"], [1,"b"], [2,"c"]] // enumerate([["cat","a",12],["dog","b",10],["log","c",14]], idx=[1:2]); // Returns: [[0,"a",12], [1,"b",10], [2,"c",14]] // Example(2D): // colors = ["red", "green", "blue"]; // for (p=enumerate(colors)) right(20*p[0]) color(p[1]) circle(d=10); function enumerate(l,idx=undef) = (idx==undef)? [for (i=[0:1:len(l)-1]) [i,l[i]]] : [for (i=[0:1:len(l)-1]) concat([i], [for (j=idx) l[i][j]])]; // Function: shuffle() // Description: // Shuffles the input list into random order. function shuffle(list) = len(list)<=1 ? list : let ( rval = rands(0,1,len(list)), left = [for (i=[0:len(list)-1]) if (rval[i]< 0.5) list[i]], right = [for (i=[0:len(list)-1]) if (rval[i]>=0.5) list[i]] ) concat(shuffle(left), shuffle(right)); // Sort a vector of scalar values function _sort_scalars(arr) = len(arr)<=1 ? arr : let( pivot = arr[floor(len(arr)/2)], lesser = [ for (y = arr) if (y < pivot) y ], equal = [ for (y = arr) if (y == pivot) y ], greater = [ for (y = arr) if (y > pivot) y ] ) concat( _sort_scalars(lesser), equal, _sort_scalars(greater) ); // Sort a vector of vectors based on the first entry only of each vector function _sort_vectors1(arr) = len(arr)<=1 ? arr : !(len(arr)>0) ? [] : let( pivot = arr[floor(len(arr)/2)], lesser = [ for (y = arr) if (y[0] < pivot[0]) y ], equal = [ for (y = arr) if (y[0] == pivot[0]) y ], greater = [ for (y = arr) if (y[0] > pivot[0]) y ] ) concat( _sort_vectors1(lesser), equal, _sort_vectors1(greater) ); // Sort a vector of vectors based on the first two entries of each vector // Lexicographic order, remaining entries of vector ignored function _sort_vectors2(arr) = len(arr)<=1 ? arr : !(len(arr)>0) ? [] : let( pivot = arr[floor(len(arr)/2)], lesser = [ for (y = arr) if (y[0] < pivot[0] || (y[0]==pivot[0] && y[1] pivot[0] || (y[0]==pivot[0] && y[1]>pivot[1])) y ] ) concat( _sort_vectors2(lesser), equal, _sort_vectors2(greater) ); // Sort a vector of vectors based on the first three entries of each vector // Lexicographic order, remaining entries of vector ignored function _sort_vectors3(arr) = len(arr)<=1 ? arr : let( pivot = arr[floor(len(arr)/2)], lesser = [ for (y = arr) if ( y[0] < pivot[0] || ( y[0]==pivot[0] && ( y[1] pivot[0] || ( y[0]==pivot[0] && ( y[1]>pivot[1] || ( y[1]==pivot[1] && y[2]>pivot[2] ) ) ) ) y ] ) concat( _sort_vectors3(lesser), equal, _sort_vectors3(greater) ); // Sort a vector of vectors based on the first four entries of each vector // Lexicographic order, remaining entries of vector ignored function _sort_vectors4(arr) = len(arr)<=1 ? arr : let( pivot = arr[floor(len(arr)/2)], lesser = [ for (y = arr) if ( y[0] < pivot[0] || ( y[0]==pivot[0] && ( y[1] pivot[0] || ( y[0]==pivot[0] && ( y[1]>pivot[1] || ( y[1]==pivot[1] && ( y[2]>pivot[2] || ( y[2]==pivot[2] && y[3]>pivot[3] ) ) ) ) ) ) y ] ) concat( _sort_vectors4(lesser), equal, _sort_vectors4(greater) ); function _sort_general(arr, idx=undef) = (len(arr)<=1) ? arr : let( pivot = arr[floor(len(arr)/2)], pivotval = idx==undef? pivot : [for (i=idx) pivot[i]], compare = [ for (entry = arr) let( val = idx==undef? entry : [for (i=idx) entry[i]], cmp = compare_vals(val, pivotval) ) cmp ], lesser = [ for (i = [0:1:len(arr)-1]) if (compare[i] < 0) arr[i] ], equal = [ for (i = [0:1:len(arr)-1]) if (compare[i] ==0) arr[i] ], greater = [ for (i = [0:1:len(arr)-1]) if (compare[i] > 0) arr[i] ] ) concat(_sort_general(lesser,idx), equal, _sort_general(greater,idx)); // Function: sort() // Usage: // sort(list, [idx]) // Description: // Sorts the given list using `compare_vals()`, sorting in lexicographic order, with types ordered according to // `undef < boolean < number < string < list`. Comparison of lists is recursive. // If the list is a list of vectors whose length is from 1 to 4 and the `idx` parameter is not passed, then // `sort` uses a much more efficient method for comparisons and will run much faster. In this case, all entries // in the data are compared using the native comparison operator, so comparisons between types will fail. // Arguments: // list = The list to sort. // idx = If given, do the comparison based just on the specified index, range or list of indices. // Example: // l = [45,2,16,37,8,3,9,23,89,12,34]; // sorted = sort(l); // Returns [2,3,8,9,12,16,23,34,37,45,89] function sort(list, idx=undef) = !is_list(list) || len(list)<=1 ? list : is_def(idx) ? _sort_general(list,idx) : let(size = array_dim(list)) len(size)==1 ? _sort_scalars(list) : len(size)==2 && size[1] <=4 ? ( size[1]==0 ? list : size[1]==1 ? _sort_vectors1(list) : size[1]==2 ? _sort_vectors2(list) : size[1]==3 ? _sort_vectors3(list) : /*size[1]==4*/ _sort_vectors4(list) ) : _sort_general(list); // Function: sortidx() // Description: // Given a list, calculates the sort order of the list, and returns // a list of indexes into the original list in that sorted order. // If you iterate the returned list in order, and use the list items // to index into the original list, you will be iterating the original // values in sorted order. // Example: // lst = ["d","b","e","c"]; // idxs = sortidx(lst); // Returns: [1,3,0,2] // ordered = select(lst, idxs); // Returns: ["b", "c", "d", "e"] // Example: // lst = [ // ["foo", 88, [0,0,1], false], // ["bar", 90, [0,1,0], true], // ["baz", 89, [1,0,0], false], // ["qux", 23, [1,1,1], true] // ]; // idxs1 = sortidx(lst, idx=1); // Returns: [3,0,2,1] // idxs2 = sortidx(lst, idx=0); // Returns: [1,2,0,3] // idxs3 = sortidx(lst, idx=[1,3]); // Returns: [3,0,2,1] function sortidx(list, idx=undef) = list==[] ? [] : let( size = array_dim(list), aug = is_undef(idx) && (len(size) == 1 || (len(size) == 2 && size[1]<=4))? zip(list, list_range(len(list))) : enumerate(list,idx=idx) ) is_undef(idx) && len(size) == 1? subindex(_sort_vectors1(aug),1) : is_undef(idx) && len(size) == 2 && size[1] <=4? ( size[1]==0? list_range(len(arr)) : size[1]==1? subindex(_sort_vectors1(aug),1) : size[1]==2? subindex(_sort_vectors2(aug),2) : size[1]==3? subindex(_sort_vectors3(aug),3) : /*size[1]==4*/ subindex(_sort_vectors4(aug),4) ) : // general case subindex(_sort_general(aug, idx=list_range(s=1,n=len(aug)-1)), 0); // Function: unique() // Usage: // unique(arr); // Description: // Returns a sorted list with all repeated items removed. // Arguments: // arr = The list to uniquify. function unique(arr) = len(arr)<=1? arr : let( sorted = sort(arr) ) [ for (i=[0:1:len(sorted)-1]) if (i==0 || (sorted[i] != sorted[i-1])) sorted[i] ]; // Section: Array Manipulation // Function: subindex() // Description: // For each array item, return the indexed subitem. // Returns a list of the values of each vector at the specfied // index list or range. If the index list or range has // only one entry the output list is flattened. // Arguments: // v = The given list of lists. // idx = The index, list of indices, or range of indices to fetch. // Example: // v = [[[1,2,3,4],[5,6,7,8],[9,10,11,12],[13,14,15,16]]; // subindex(v,2); // Returns [3, 7, 11, 15] // subindex(v,[2,1]); // Returns [[3, 2], [7, 6], [11, 10], [15, 14]] // subindex(v,[1:3]); // Returns [[2, 3, 4], [6, 7, 8], [10, 11, 12], [14, 15, 16]] function subindex(v, idx) = [ for(val=v) let(value=[for(i=idx) val[i]]) len(value)==1 ? value[0] : value ]; // Function: pair() // Usage: // pair(v) // Description: // Takes a list, and returns a list of adjacent pairs from it. // Example: // l = ["A","B","C",D"]; // echo([for (p=pair(l)) str(p.y,p.x)]); // Outputs: ["BA", "CB", "DC"] function pair(v) = [for (i=[0:1:len(v)-2]) [v[i],v[i+1]]]; // Function: pair_wrap() // Usage: // pair_wrap(v) // Description: // Takes a list, and returns a list of adjacent pairss from it, wrapping around from the end to the start of the list. // Example: // l = ["A","B","C","D"]; // echo([for (p=pair_wrap(l)) str(p.y,p.x)]); // Outputs: ["BA", "CB", "DC", "AD"] function pair_wrap(v) = [for (i=[0:1:len(v)-1]) [v[i],v[(i+1)%len(v)]]]; // Function: triplet() // Usage: // triplet(v) // Description: // Takes a list, and returns a list of adjacent triplets from it. // Example: // l = ["A","B","C","D","E"]; // echo([for (p=triplet(l)) str(p.z,p.y,p.x)]); // Outputs: ["CBA", "DCB", "EDC"] function triplet(v) = [for (i=[0:1:len(v)-3]) [v[i],v[i+1],v[i+2]]]; // Function: triplet_wrap() // Usage: // triplet_wrap(v) // Description: // Takes a list, and returns a list of adjacent triplets from it, wrapping around from the end to the start of the list. // Example: // l = ["A","B","C","D"]; // echo([for (p=triplet_wrap(l)) str(p.z,p.y,p.x)]); // Outputs: ["CBA", "DCB", "ADC", "BAD"] function triplet_wrap(v) = [for (i=[0:1:len(v)-1]) [v[i],v[(i+1)%len(v)],v[(i+2)%len(v)]]]; // Function: zip() // Usage: // zip(v1, v2, v3, [fit], [fill]); // zip(vecs, [fit], [fill]); // Description: // Zips together corresponding items from two or more lists. // Returns a list of lists, where each sublist contains corresponding // items from each of the input lists. `[[A1, B1, C1], [A2, B2, C2], ...]` // Arguments: // vecs = A list of two or more lists to zipper together. // fit = If `fit=="short"`, the zips together up to the length of the shortest list in vecs. If `fit=="long"`, then pads all lists to the length of the longest, using the value in `fill`. If `fit==false`, then requires all lists to be the same length. Default: false. // fill = The default value to fill in with if one or more lists if short. Default: undef // Example: // v1 = [1,2,3,4]; // v2 = [5,6,7]; // v3 = [8,9,10,11]; // zip(v1,v3); // returns [[1,8], [2,9], [3,10], [4,11]] // zip([v1,v3]); // returns [[1,8], [2,9], [3,10], [4,11]] // zip([v1,v2], fit="short"); // returns [[1,5], [2,6], [3,7]] // zip([v1,v2], fit="long"); // returns [[1,5], [2,6], [3,7], [4,undef]] // zip([v1,v2], fit="long, fill=0); // returns [[1,5], [2,6], [3,7], [4,0]] // zip([v1,v2,v3], fit="long"); // returns [[1,5,8], [2,6,9], [3,7,10], [4,undef,11]] // Example: // v1 = [[1,2,3], [4,5,6], [7,8,9]]; // v2 = [[20,19,18], [17,16,15], [14,13,12]]; // zip(v1,v2); // Returns [[1,2,3,20,19,18], [4,5,6,17,16,15], [7,8,9,14,13,12]] function zip(vecs, v2, v3, fit=false, fill=undef) = (v3!=undef)? zip([vecs,v2,v3], fit=fit, fill=fill) : (v2!=undef)? zip([vecs,v2], fit=fit, fill=fill) : let( dummy1 = assert_in_list("fit", fit, [false, "short", "long"]), minlen = list_shortest(vecs), maxlen = list_longest(vecs), dummy2 = (fit==false)? assert(minlen==maxlen, "Input vectors must have the same length") : 0 ) (fit == "long")? [for(i=[0:1:maxlen-1]) [for(v=vecs) for(x=(i len(dimlist))? 0 : dimlist[depth-1] ); // Function: transpose() // Description: Returns the transposition of the given array. // Example: // arr = [ // ["a", "b", "c"], // ["d", "e", "f"], // ["g", "h", "i"] // ]; // t = transpose(arr); // // Returns: // // [ // // ["a", "d", "g"], // // ["b", "e", "h"], // // ["c", "f", "i"], // // ] // Example: // arr = [ // ["a", "b", "c"], // ["d", "e", "f"] // ]; // t = transpose(arr); // // Returns: // // [ // // ["a", "d"], // // ["b", "e"], // // ["c", "f"], // // ] // Example: // transpose([3,4,5]); // Returns: [3,4,5] function transpose(arr) = is_list(arr[0])? [for (i=[0:1:len(arr[0])-1]) [for (j=[0:1:len(arr)-1]) arr[j][i]]] : arr; // vim: noexpandtab tabstop=4 shiftwidth=4 softtabstop=4 nowrap