This commit is contained in:
Ingy döt Net 2013-04-10 21:29:02 -07:00
parent 764da6cbbb
commit db842d013d
19005 changed files with 197040 additions and 7 deletions

View file

@ -0,0 +1,6 @@
Write a function to flatten the nesting in an arbitrary [[wp:List (computing)|list]] of values. Your program should work on the equivalent of this list:
[[1], 2, [[3,4], 5], [[[]]], [[[6]]], 7, 8, []]
Where the correct result would be the list:
[1, 2, 3, 4, 5, 6, 7, 8]
C.f. [[Tree traversal]]

View file

@ -0,0 +1,5 @@
(defun flatten (tr)
(cond ((null tr) nil)
((atom tr) (list tr))
(t (append (flatten (first tr))
(flatten (rest tr))))))

View file

@ -0,0 +1,4 @@
main:(
[][][]INT list = ((1), 2, ((3,4), 5), ((())), (((6))), 7, 8, ());
print((list, new line))
)

View file

@ -0,0 +1,13 @@
function flatten(input:Array):Array {
var output:Array = new Array();
for (var i:uint = 0; i < input.length; i++) {
//typeof returns "object" when applied to arrays. This line recursively evaluates nested arrays,
// although it may break if the array contains objects that are not arrays.
if (typeof input[i]=="object") {
output=output.concat(flatten(input[i]));
} else {
output.push(input[i]);
}
}
return output;
}

View file

@ -0,0 +1,22 @@
function flatten (list, result) {
foreach item list {
if (typeof(item) == "vector") {
flatten (item, result)
} else {
result.append (item)
}
}
}
var l = [[1], 2, [[3,4], 5], [[[]]], [[[6]]], 7, 8, []]
var newl = []
flatten (l, newl)
// print out the nicely formatted result list
print ('[')
var comma = ""
foreach item newl {
print (comma + item)
comma = ", "
}
println("]")

View file

@ -0,0 +1,11 @@
my_flatten({{1}, 2, {{3, 4}, 5}, {{{}}}, {{{6}}}, 7, 8, {}})
on my_flatten(aList)
if class of aList is not list then
return {aList}
else if length of aList is 0 then
return aList
else
return my_flatten(first item of aList) & (my_flatten(rest of aList))
end if
end my_flatten

View file

@ -0,0 +1,52 @@
list := object(1, object(1, 1), 2, 2, 3, object(1, object(1, 3, 2, 4)
, 2, 5), 4, object(1, object(1, object(1, object()))), 5
, object(1, object(1, 6)), 6, 7, 7, 8, 9, object())
msgbox % objPrint(list) ; (( 1 ) 2 (( 3 4 ) 5 )(((())))(( 6 )) 7 8 ())
msgbox % objPrint(objFlatten(list)) ; ( 1 2 3 4 5 6 7 8 )
return
!r::reload
!q::exitapp
objPrint(ast, reserved=0)
{
if !isobject(ast)
return " " ast " "
if !reserved
reserved := object("seen" . &ast, 1) ; to keep track of unique objects within top object
enum := ast._newenum()
while enum[key, value]
{
if reserved["seen" . &value]
continue ; don't copy repeat objects (circular references)
; string .= key . ": " . objPrint(value, reserved)
string .= objPrint(value, reserved)
}
return "(" string ")"
}
objFlatten(ast)
{
if !isobject(ast)
return ast
flat := object() ; flat object
enum := ast._newenum()
while enum[key, value]
{
if !isobject(value)
flat._Insert(value)
else
{
next := objFlatten(value)
loop % next._MaxIndex()
flat._Insert(next[A_Index])
}
}
return flat
}

View file

@ -0,0 +1,7 @@
( (myList = ((1), 2, ((3,4), 5), ((())), (((6))), 7, 8, ()))
& put$("Unevaluated:")
& lst$myList
& !myList:?myList { the expression !list evaluates myList }
& put$("Flattened:")
& lst$myList
)

View file

@ -0,0 +1,12 @@
array.prototype.flatten = {
true? my.empty?
{ [] }
{ true? my.first.array?
{ my.first.flatten + my.rest.flatten }
{ [my.first] + my.rest.flatten }
}
}
list = [[1], 2, [[3,4], 5], [[[]]], [[[6]]], 7, 8, []]
p "List: #{list}"
p "Flattened: #{list.flatten}"

View file

@ -0,0 +1,2 @@
blsq ) {{1} 2 {{3 4} 5} {{{}}} {{{6}}} 7 8 {}}{\[}{)to{"Block"==}ay}w!
{1 2 3 4 5 6 7 8}

View file

@ -0,0 +1,23 @@
#include <list>
#include <boost/any.hpp>
typedef std::list<boost::any> anylist;
void flatten(std::list<boost::any>& list)
{
typedef anylist::iterator iterator;
iterator current = list.begin();
while (current != list.end())
{
if (current->type() == typeid(anylist))
{
iterator next = current;
++next;
list.splice(next, boost::any_cast<anylist&>(*current));
current = list.erase(current);
}
else
++current;
}
}

View file

@ -0,0 +1,104 @@
#include <cctype>
#include <iostream>
// *******************
// * the list parser *
// *******************
void skipwhite(char const** s)
{
while (**s && std::isspace((unsigned char)**s))
{
++*s;
}
}
anylist create_anylist_i(char const** s)
{
anylist result;
skipwhite(s);
if (**s != '[')
throw "Not a list";
++*s;
while (true)
{
skipwhite(s);
if (!**s)
throw "Error";
else if (**s == ']')
{
++*s;
return result;
}
else if (**s == '[')
result.push_back(create_anylist_i(s));
else if (std::isdigit((unsigned char)**s))
{
int i = 0;
while (std::isdigit((unsigned char)**s))
{
i = 10*i + (**s - '0');
++*s;
}
result.push_back(i);
}
else
throw "Error";
skipwhite(s);
if (**s != ',' && **s != ']')
throw "Error";
if (**s == ',')
++*s;
}
}
anylist create_anylist(char const* i)
{
return create_anylist_i(&i);
}
// *************************
// * printing nested lists *
// *************************
void print_list(anylist const& list);
void print_item(boost::any const& a)
{
if (a.type() == typeid(int))
std::cout << boost::any_cast<int>(a);
else if (a.type() == typeid(anylist))
print_list(boost::any_cast<anylist const&>(a));
else
std::cout << "???";
}
void print_list(anylist const& list)
{
std::cout << '[';
anylist::const_iterator iter = list.begin();
while (iter != list.end())
{
print_item(*iter);
++iter;
if (iter != list.end())
std::cout << ", ";
}
std::cout << ']';
}
// ***************************
// * The actual test program *
// ***************************
int main()
{
anylist list =
create_anylist("[[1], 2, [[3,4], 5], [[[]]], [[[6]]], 7, 8, []]");
print_list(list);
std::cout << "\n";
flatten(list);
print_list(list);
std::cout << "\n";
}

View file

@ -0,0 +1,118 @@
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct list_t list_t, *list;
struct list_t{
int is_list, ival; /* ival is either the integer value or list length */
list *lst;
};
list new_list()
{
list x = malloc(sizeof(list_t));
x->ival = 0;
x->is_list = 1;
x->lst = 0;
return x;
}
void append(list parent, list child)
{
parent->lst = realloc(parent->lst, sizeof(list) * (parent->ival + 1));
parent->lst[parent->ival++] = child;
}
list from_string(char *s, char **e, list parent)
{
list ret = 0;
if (!parent) parent = new_list();
while (*s != '\0') {
if (*s == ']') {
if (e) *e = s + 1;
return parent;
}
if (*s == '[') {
ret = new_list();
ret->is_list = 1;
ret->ival = 0;
append(parent, ret);
from_string(s + 1, &s, ret);
continue;
}
if (*s >= '0' && *s <= '9') {
ret = new_list();
ret->is_list = 0;
ret->ival = strtol(s, &s, 10);
append(parent, ret);
continue;
}
s++;
}
if (e) *e = s;
return parent;
}
void show_list(list l)
{
int i;
if (!l) return;
if (!l->is_list) {
printf("%d", l->ival);
return;
}
printf("[");
for (i = 0; i < l->ival; i++) {
show_list(l->lst[i]);
if (i < l->ival - 1) printf(", ");
}
printf("]");
}
list flatten(list from, list to)
{
int i;
list t;
if (!to) to = new_list();
if (!from->is_list) {
t = new_list();
*t = *from;
append(to, t);
} else
for (i = 0; i < from->ival; i++)
flatten(from->lst[i], to);
return to;
}
void delete_list(list l)
{
int i;
if (!l) return;
if (l->is_list && l->ival) {
for (i = 0; i < l->ival; i++)
delete_list(l->lst[i]);
free(l->lst);
}
free(l);
}
int main()
{
list l = from_string("[1], 2, [[3,4], 5], [[[]]], [[[6]]], 7, 8, []", 0, 0);
printf("Nested: ");
show_list(l);
printf("\n");
list flat = flatten(l, 0);
printf("Flattened: ");
show_list(flat);
/* delete_list(l); delete_list(flat); */
return 0;
}

View file

@ -0,0 +1,6 @@
(defn flatten [coll]
(lazy-seq
(when-let [s (seq coll)]
(if (coll? (first s))
(concat (flatten (first s)) (flatten (rest s)))
(cons (first s) (flatten (rest s)))))))

View file

@ -0,0 +1,3 @@
(defn flatten [x]
(filter (complement sequential?)
(rest (tree-seq sequential? seq x))))

View file

@ -0,0 +1,10 @@
flatten = (arr) ->
arr.reduce ((xs, el) ->
if Array.isArray el
xs.concat flatten el
else
xs.concat [el]), []
# test
list = [[1], 2, [[3,4], 5], [[[]]], [[[6]]], 7, 8, []]
console.log flatten list

View file

@ -0,0 +1,2 @@
> coffee foo.coffee
[ 1, 2, 3, 4, 5, 6, 7, 8 ]

View file

@ -0,0 +1,4 @@
(defun flatten (structure)
(cond ((null structure) nil)
((atom structure) `(,structure))
(t (mapcan #'flatten structure))))

View file

@ -0,0 +1,43 @@
import std.stdio, std.algorithm, std.conv, std.range;
struct TreeList(T) {
union { // A tagged union
TreeList[] arr; // it's a node
T data; // it's a leaf
}
bool isArray = true; // = contains an arr on default.
static TreeList opCall(A...)(A items) /*const*/ pure nothrow {
TreeList result;
foreach (i, el; items)
static if (is(A[i] == T)) {
TreeList item;
item.isArray = false;
item.data = el;
result.arr ~= item;
} else
result.arr ~= el;
return result;
}
string toString() const {
return isArray ? text(arr) : text(data);
}
}
T[] flatten(T)(in TreeList!T t) /*pure nothrow*/ {
if (t.isArray)
return t.arr.map!flatten().join();
else
return [t.data];
}
void main() {
alias TreeList!int L;
static assert(L.sizeof == 12);
auto l = L(L(1), 2, L(L(3,4), 5), L(L(L())), L(L(L(6))),7,8,L());
writeln(l);
writeln(flatten(l));
}

View file

@ -0,0 +1,19 @@
import std.stdio, std.variant, std.range, std.algorithm;
alias T = Algebraic!(int, This[]);
int[] flatten(T t) {
return t.peek!int ? [t.get!int] : t.get!(T[])().map!flatten.join;
}
void main() {
T([T([ T(1) ]),
T(2),
T([ T([ T(3), T(4) ]), T(5) ]),
T([ T([ T( T[].init ) ]) ]),
T([ T([ T([ T(6) ]) ]) ]),
T(7),
T(8),
T( T[].init )
]).flatten.writeln;
}

View file

@ -0,0 +1,11 @@
def flatten(nested) {
def flat := [].diverge()
def recur(x) {
switch (x) {
match list :List { for elem in list { recur(elem) } }
match other { flat.push(other) }
}
}
recur(nested)
return flat.snapshot()
}

View file

@ -0,0 +1,2 @@
? flatten([[1], 2, [[3,4], 5], [[[]]], [[[6]]], 7, 8, []])
# value: [1, 2, 3, 4, 5, 6, 7, 8]

View file

@ -0,0 +1,9 @@
xs = [[1], 2, [[3,4], 5], [[[]]], [[[6]]], 7, 8, []]
flat = flat' []
where flat' n [] = n
flat' n (x::xs)
| x is List = flat' (flat' n xs) x
| else = x :: flat' n xs
flat xs

View file

@ -0,0 +1,4 @@
flat [] = []
flat (x::xs)
| x is List = flat x ++ flat xs
| else = x :: flat xs

View file

@ -0,0 +1,6 @@
(defun flatten (mylist)
(cond
((null mylist) nil)
((atom mylist) (list mylist))
(t
(append (flatten (car mylist)) (flatten (cdr mylist))))))

View file

@ -0,0 +1,3 @@
flatten([]) -> [];
flatten([H|T]) -> flatten(H) ++ flatten(T);
flatten(H) -> [H].

View file

@ -0,0 +1,21 @@
sequence a = {{1}, 2, {{3, 4}, 5}, {{{}}}, {{{6}}}, 7, 8, {}}
function flatten( object s )
sequence res = {}
if sequence( s ) then
for i = 1 to length( s ) do
sequence c = flatten( s[ i ] )
if length( c ) > 0 then
res &= c
end if
end for
else
if length( s ) > 0 then
res = { s }
end if
end if
return res
end function
? a
? flatten(a)

View file

@ -0,0 +1,25 @@
class Main
{
// uses recursion to flatten a list
static List myflatten (List items)
{
List result := [,]
items.each |item|
{
if (item is List)
result.addAll (myflatten(item))
else
result.add (item)
}
return result
}
public static Void main ()
{
List sample := [[1], 2, [[3,4], 5], [[[,]]], [[[6]]], 7, 8, [,]]
// there is a built-in flatten method for lists
echo ("Flattened list 1: " + sample.flatten)
// or use the function 'myflatten'
echo ("Flattened list 2: " + myflatten (sample))
}
}

View file

@ -0,0 +1,2 @@
a = [[1], 2, [[3,4], 5], [[[]]], [[[6]]], 7, 8, []]
println[flatten[a]]

View file

@ -0,0 +1 @@
Flat([[1], 2, [[3,4], 5], [[[]]], [[[6]]], 7, 8, []]);

View file

@ -0,0 +1,33 @@
package main
import "fmt"
func list(s ...interface{}) []interface{} {
return s
}
func main() {
s := list(list(1),
2,
list(list(3, 4), 5),
list(list(list())),
list(list(list(6))),
7,
8,
list(),
)
fmt.Println(s)
fmt.Println(flatten(s))
}
func flatten(s []interface{}) (r []int) {
for _, e := range s {
switch i := e.(type) {
case int:
r = append(r, i)
case []interface{}:
r = append(r, flatten(i)...)
}
}
return
}

View file

@ -0,0 +1,10 @@
func flatten(s []interface{}) (r []interface{}) {
for _, e := range s {
if i, ok := e.([]interface{}); ok {
r = append(r, flatten(i)...)
} else {
r = append(r, e)
}
}
return
}

View file

@ -0,0 +1 @@
assert [[1], 2, [[3,4], 5], [[[]]], [[[6]]], 7, 8, []].flatten() == [1, 2, 3, 4, 5, 6, 7, 8]

View file

@ -0,0 +1,24 @@
import Data.Tree
-- [[1], 2, [[3,4], 5], [[[]]], [[[6]]], 7, 8, []]
-- implemented as multiway tree:
-- Data.Tree represents trees where nodes have values too, unlike the trees in our problem.
-- so we use a list as that value, where a node will have an empty list value,
-- and a leaf will have a one-element list value and no subtrees
list :: Tree [Int]
list = Node [] [
Node [] [Node [1] []],
Node [2] [],
Node [] [
Node [] [ Node [3] [],Node [4] []],
Node [5] []
],
Node [] [Node [] [Node [] []]],
Node [] [Node [] [Node [6] []]],
Node [7] [],
Node [8] [],
Node [] []
]
flattenList = concat.flatten

View file

@ -0,0 +1,16 @@
data Tree a = Leaf a | Node [Tree a]
flatten :: Tree a -> [a]
flatten (Leaf x) = [x]
flatten (Node xs) = concatMap flatten xs
main = print $ flatten $ Node [Node [Leaf 1],
Leaf 2,
Node [Node [Leaf 3, Leaf 4], Leaf 5],
Node [Node [Node []]],
Node [Node [Node [Leaf 6]]],
Leaf 7,
Leaf 8,
Node []]
-- output: [1,2,3,4,5,6,7,8]

View file

@ -0,0 +1,17 @@
data NestedList a = NList [NestedList a] | Entry a
flatten :: NestedList a -> [a]
flatten nl = flatten' nl []
where
-- By passing through a list which the results will be preprended to we allow efficient lazy evaluation
flatten' :: NestedList a -> [a] -> [a]
flatten' (Entry a) cont = a:cont
flatten' (NList entries) cont = foldr flatten' cont entries
example :: NestedList Int
example = NList [ NList [Entry 1], Entry 2, NList [NList [Entry 3, Entry 4], Entry 5], NList [NList [NList []]], NList [ NList [ NList [Entry 6]]], Entry 7, Entry 8, NList []]
main :: IO ()
main = print $ flatten example
-- output [1,2,3,4,5,6,7,8]

View file

@ -0,0 +1,5 @@
link strings # for compress,deletec,pretrim
procedure sflatten(s) # uninteresting string solution
return pretrim(trim(compress(deletec(s,'[ ]'),',') ,','),',')
end

View file

@ -0,0 +1,9 @@
procedure flatten(L) # in the spirt of the problem a structure
local l,x
l := []
every x := !L do
if type(x) == "list" then l |||:= flatten(x)
else put(l,x)
return l
end

View file

@ -0,0 +1,11 @@
procedure main()
write(sflatten(" [[1], 2, [[3,4], 5], [[[]]], [[[6]]], 7, 8, []]"))
writelist(flatten( [[1], 2, [[3,4], 5], [[[]]], [[[6]]], 7, 8, []]))
end
procedure writelist(L)
writes("[")
every writes(" ",image(!L))
write(" ]")
return
end

View file

@ -0,0 +1,3 @@
iik> [[1], 2, [[3,4], 5], [[[]]], [[[6]]], 7, 8, []] flatten
[[1], 2, [[3,4], 5], [[[]]], [[[6]]], 7, 8, []] flatten
+> [1, 2, 3, 4, 5, 6, 7, 8]

View file

@ -0,0 +1 @@
flatten =: [: ; <S:0

View file

@ -0,0 +1,14 @@
NB. create and display nested noun li
]li =. (<1) ; 2; ((<3; 4); 5) ; ((<a:)) ; ((<(<6))) ; 7; 8; <a:
+---+-+-----------+----+-----+-+-+--+
|+-+|2|+-------+-+|+--+|+---+|7|8|++|
||1|| ||+-----+|5|||++|||+-+|| | ||||
|+-+| |||+-+-+|| |||||||||6||| | |++|
| | ||||3|4||| |||++|||+-+|| | | |
| | |||+-+-+|| ||+--+|+---+| | | |
| | ||+-----+| || | | | | |
| | |+-------+-+| | | | | |
+---+-+-----------+----+-----+-+-+--+
flatten li
1 2 3 4 5 6 7 8

View file

@ -0,0 +1 @@
flatten2 =: [: ; <@,S:0

View file

@ -0,0 +1,15 @@
]li2 =. (<1) ; 2; ((<3;4); 5 + i.3 4) ; ((<a:)) ; ((<(<17))) ; 18; 19; <a:
+---+-+---------------------+----+------+--+--+--+
|+-+|2|+-------+-----------+|+--+|+----+|18|19|++|
||1|| ||+-----+| 5 6 7 8|||++|||+--+|| | ||||
|+-+| |||+-+-+|| 9 10 11 12|||||||||17||| | |++|
| | ||||3|4|||13 14 15 16|||++|||+--+|| | | |
| | |||+-+-+|| ||+--+|+----+| | | |
| | ||+-----+| || | | | | |
| | |+-------+-----------+| | | | | |
+---+-+---------------------+----+------+--+--+--+
flatten2 li
1 2 3 4 5 6 7 8
flatten2 li2
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19

View file

@ -0,0 +1,22 @@
import java.util.LinkedList;
import java.util.List;
public final class FlattenUtil {
public static List<Object> flatten(List<?> list) {
List<Object> retVal = new LinkedList<Object>();
flatten(list, retVal);
return retVal;
}
public static void flatten(List<?> fromTreeList, List<Object> toFlatList) {
for (Object item : fromTreeList) {
if (item instanceof List<?>) {
flatten((List<?>) item, toFlatList);
} else {
toFlatList.add(item);
}
}
}
}

View file

@ -0,0 +1,16 @@
import static java.util.Arrays.asList;
import java.util.List;
public final class FlattenTestMain {
public static void main(String[] args) {
List<Object> treeList = a(a(1), 2, a(a(3, 4), 5), a(a(a())), a(a(a(6))), 7, 8, a());
List<Object> flatList = FlattenUtil.flatten(treeList);
System.out.println(treeList);
System.out.println("flatten: " + flatList);
}
private static List<Object> a(Object... a) {
return asList(a);
}
}

View file

@ -0,0 +1,5 @@
function flatten(arr){
return arr.reduce(function(acc, val){
return acc.concat(val.constructor === Array ? flatten(val) : val);
},[]);
}

View file

@ -0,0 +1,10 @@
julia> t = [[1], 2, [[3,4], 5], [[[]]], [[[6]]], 7, 8, []]
8-element Int32 Array:
1
2
3
4
5
6
7
8

View file

@ -0,0 +1 @@
,//((1); 2; ((3;4); 5); ((())); (((6))); 7; 8; ())

View file

@ -0,0 +1,13 @@
to flatten :l
if not list? :l [output :l]
if empty? :l [output []]
output sentence flatten first :l flatten butfirst :l
end
; using a template iterator (map combining results into a sentence)
to flatten :l
output map.se [ifelse or not list? ? empty? ? [?] [flatten ?]] :l
end
make "a [[1] 2 [[3 4] 5] [[[]]] [[[6]]] 7 8 []]
show flatten :a

View file

@ -0,0 +1,13 @@
flatten(List, Flatted) :-
flatten(List, [], Flatted).
flatten(Var, Tail, [Var| Tail]) :-
var(Var),
!.
flatten([], Flatted, Flatted) :-
!.
flatten([Head| Tail], List, Flatted) :-
!,
flatten(Tail, List, Aux),
flatten(Head, Aux, Flatted).
flatten(Head, Tail, [Head| Tail]).

View file

@ -0,0 +1,14 @@
function flatten(list)
if type(list) ~= "table" then return {list} end
local flat_list = {}
for _, elem in ipairs(list) do
for _, val in ipairs(flatten(elem)) do
flat_list[#flat_list + 1] = val
end
end
return flat_list
end
test_list = {{1}, 2, {{3,4}, 5}, {{{}}}, {{{6}}}, 7, 8, {}}
print(table.concat(flatten(test_list), ","))

View file

@ -0,0 +1 @@
Flatten[{{1}, 2, {{3, 4}, 5}, {{{}}}, {{{6}}}, 7, 8, {}}]

View file

@ -0,0 +1,2 @@
flatten([[[1, 2, 3], 4, [5, [6, 7]], 8], [[9, 10], 11], 12]);
/* [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12] */

View file

@ -0,0 +1,24 @@
import java.util.ArrayList
import java.util.List
import java.util.Collection
def flatten(list: Collection)
flatten(list, ArrayList.new)
end
def flatten(source: Collection, result: List)
source.each do |x|
if x.kind_of?(Collection)
flatten(Collection(x), result)
else
result.add(x)
result # if branches must return same type
end
end
result
end
# creating a list-of-list-of-list fails currently, so constructor calls are needed
source = [[1], 2, [[3, 4], 5], [[ArrayList.new]], [[[6]]], 7, 8, ArrayList.new]
puts flatten(source)

View file

@ -0,0 +1,4 @@
/* Note: This code is only for PHP 4.
It won't work on PHP 5 due to the change in behavior of array_merge(). */
while (array_filter($lst, 'is_array'))
$lst = call_user_func_array('array_merge', $lst);

View file

@ -0,0 +1,16 @@
<?php
function flatten($ary) {
$result = array();
foreach ($ary as $x) {
if (is_array($x))
// append flatten($x) onto $result
array_splice($result, count($result), 0, flatten($x));
else
$result[] = $x;
}
return $result;
}
$lst = array(array(1), 2, array(array(3, 4), 5), array(array(array())), array(array(array(6))), 7, 8, array());
var_dump(flatten($lst));
?>

View file

@ -0,0 +1,10 @@
<?php
function flatten($ary) {
$result = array();
array_walk_recursive($ary, function($x, $k) use (&$result) { $result[] = $x; });
return $result;
}
$lst = array(array(1), 2, array(array(3, 4), 5), array(array(array())), array(array(array(6))), 7, 8, array());
var_dump(flatten($lst));
?>

View file

@ -0,0 +1,14 @@
<?php
function flatten_helper($x, $k, $obj) {
$obj->flattened[] = $x;
}
function flatten($ary) {
$obj = (object)array('flattened' => array());
array_walk_recursive($ary, 'flatten_helper', $obj);
return $obj->flattened;
}
$lst = array(array(1), 2, array(array(3, 4), 5), array(array(array())), array(array(array(6))), 7, 8, array());
var_dump(flatten($lst));
?>

View file

@ -0,0 +1,5 @@
<?php
$lst = array(array(1), 2, array(array(3, 4), 5), array(array(array())), array(array(array(6))), 7, 8, array());
$result = iterator_to_array(new RecursiveIteratorIterator(new RecursiveArrayIterator($lst)), false);
var_dump($result);
?>

View file

@ -0,0 +1,13 @@
<?php
function flat(&$ary) { // argument must be by reference or array will just be copied
for ($i = 0; $i < count($ary); $i++) {
while (is_array($ary[$i])) {
array_splice($ary, $i, 1, $ary[$i]);
}
}
}
$lst = array(array(1), 2, array(array(3, 4), 5), array(array(array())), array(array(array(6))), 7, 8, array());
flat($lst);
var_dump($lst);
?>

View file

@ -0,0 +1,6 @@
sub flatten {
map { ref eq 'ARRAY' ? flatten(@$_) : $_ } @_
}
my @lst = ([1], 2, [[3,4], 5], [[[]]], [[[6]]], 7, 8, []);
print flatten(@lst), "\n";

View file

@ -0,0 +1,6 @@
(de flatten (X)
(make # Build a list
(recur (X) # recursively over 'X'
(if (atom X)
(link X) # Put atoms into the result
(mapc recurse X) ) ) ) ) # or recurse on sub-lists

View file

@ -0,0 +1,2 @@
(de flatten (X)
(fish atom X) )

View file

@ -0,0 +1,11 @@
flatten(List, FlatList) :-
flatten(List, [], FlatList).
flatten(Var, T, [Var|T]) :-
var(Var), !.
flatten([], T, T) :- !.
flatten([H|T], TailList, List) :- !,
flatten(H, FlatTail, List),
flatten(T, TailList, FlatTail).
flatten(NonList, T, [NonList|T]).

View file

@ -0,0 +1,7 @@
>>> def flatten(lst):
return sum( ([x] if not isinstance(x, list) else flatten(x)
for x in lst), [] )
>>> lst = [[1], 2, [[3,4], 5], [[[]]], [[[6]]], 7, 8, []]
>>> flatten(lst)
[1, 2, 3, 4, 5, 6, 7, 8]

View file

@ -0,0 +1,14 @@
>>> def flat(lst):
i=0
while i<len(lst):
while True:
try:
lst[i:i+1] = lst[i]
except (TypeError, IndexError):
break
i += 1
>>> lst = [[1], 2, [[3,4], 5], [[[]]], [[[6]]], 7, 8, []]
>>> flat(lst)
>>> lst
[1, 2, 3, 4, 5, 6, 7, 8]

View file

@ -0,0 +1,12 @@
>>> def flatten(lst):
for x in lst:
if isinstance(x, list):
for x in flatten(x):
yield x
else:
yield x
>>>lst = [[1], 2, [[3,4], 5], [[[]]], [[[6]]], 7, 8, []]
>>>print list(flatten(lst))
[1, 2, 3, 4, 5, 6, 7, 8]

View file

@ -0,0 +1,3 @@
x <- list(list(1), 2, list(list(3, 4), 5), list(list(list())), list(list(list(6))), 7, 8, list())
unlist(x)

View file

@ -0,0 +1,9 @@
/*REXX program to demonstrate how to flatten a list. */
y = '[[1], 2, [[3,4], 5], [[[]]], [[[6]]], 7, 8, []]'
z = '['changestr(' ',space(translate(y,,'[,]')),", ")']'
say ' input =' y
say 'output =' z
/*stick a fork in it, we're done.*/

View file

@ -0,0 +1,12 @@
/*REXX program to demonstrate how to flatten a list. */
y = '[[1], 2, [[3,4], 5], [[[]]], [[[6]]], 7, 8, []]'
z=translate(y,,'[,]') /*change brackets & commas to blanks*/
z=space(z) /*remove extraneous blanks*/
z=changestr(' ',z,", ") /*change blanks to "comma blank"*/
z='['z"]" /*add brackets*/
say ' input =' y
say 'output =' z
/*stick a fork in it, we're done.*/

View file

@ -0,0 +1,2 @@
#lang racket
(flatten '(1 (2 (3 4 5) (6 7)) 8 9))

View file

@ -0,0 +1 @@
'(1 2 3 4 5 6 7 8 9)

View file

@ -0,0 +1,6 @@
#lang racket
(define (flatten l)
(cond [(empty? l) null]
[(not (list? l)) (list l)]
[else (append (flatten (first l)) (flatten (rest l)))]))
(flatten '(1 (2 (3 4 5) (6 7)) 8 9))

View file

@ -0,0 +1,2 @@
flat = [[1], 2, [[3,4], 5], [[[]]], [[[6]]], 7, 8, []].flatten
p flat # => [1, 2, 3, 4, 5, 6, 7, 8]

View file

@ -0,0 +1,5 @@
def flatList(l: List[_]): List[Any] = l match {
case Nil => Nil
case (head: List[_]) :: tail => flatList(head) ::: flatList(tail)
case head :: tail => head :: flatList(tail)
}

View file

@ -0,0 +1,8 @@
> (define (flatten x)
(cond ((null? x) '())
((not (pair? x)) (list x))
(else (append (flatten (car x))
(flatten (cdr x))))))
> (flatten '((1) 2 ((3 4) 5) ((())) (((6))) 7 8 ()))
(1 2 3 4 5 6 7 8)

View file

@ -0,0 +1,22 @@
OrderedCollection extend [
flatten [ |f|
f := OrderedCollection new.
self do: [ :i |
i isNumber
ifTrue: [ f add: i ]
ifFalse: [ |t|
t := (OrderedCollection withAll: i) flatten.
f addAll: t
]
].
^ f
]
].
|list|
list := OrderedCollection
withAll: { {1} . 2 . { {3 . 4} . 5 } .
{{{}}} . {{{6}}} . 7 . 8 . {} }.
(list flatten) printNl.

View file

@ -0,0 +1,10 @@
proc flatten list {
for {set old {}} {$old ne $list} {} {
set old $list
set list [join $list]
}
return $list
}
puts [flatten {{1} 2 {{3 4} 5} {{{}}} {{{6}}} 7 8 {}}]
# ===> 1 2 3 4 5 6 7 8

View file

@ -0,0 +1,6 @@
proc flatten {data} {
while { $data != [set data [join $data]] } { }
return $data
}
puts [flatten {{1} 2 {{3 4} 5} {{{}}} {{{6}}} 7 8 {}}]
# ===> 1 2 3 4 5 6 7 8