Collections

From Rosetta Code
Revision as of 07:49, 15 September 2007 by 24.23.196.198 (talk) (Adding Lua code)
Task
Collections
You are encouraged to solve this task according to the task description, using any language you may know.

Collections are used to store objects and not primitive types. In this task, the goal is to create a collection, and add an element or two to it.

C++

C++ has a range of different collections optimized for different use cases. Note that in C++, objects of user-defined types are mostly treated just like objects of built-in types; especially there's no different treatment for copllections. Thus all collections can simply be demonstrated with the built-in type int. For user-defined types, just replace int with the user-defined type. Any type which goes into a collection must be copyable and assignable (which in general is automatically the case unless you explicitly disallow it).

Note however that C++ collections store copies of the objects given to them, so you'll lose any polymorphic behaviour. If you need polymorphism, use a collection of pointers (or smart pointers like boost::shared_ptr).

vector

A vector is basically a resizeable array. It is optimized for adding/removing elements on the end, and fast access to elements anywhere. Inserting elements at the beginning or in the middle is possible, but in general inefficient.

#include <vector>

std::vector<int> v;       // empty vector
v.push_back(5);           // insert a 5 at the end
v.insert(v.begin(), 7);   // insert a 7 at the beginning

deque

A deque is optimized for appending and removing elements on both ends ofd the array. Accessing random elements is still efficient, but slightly less than with vector.

#include <deque>

std::deque<int> d;        // empty deque
d.push_back(5);           // insert a 5 at the end
d.push_front(7);          // insert a 7 at the beginning
d.insert(v.begin()+1, 6); // insert a 6 in the middle

list

A list is optimized for insertion at an arbitrary place (provided you already have an iterator pointing to that place). Element access is efficient only in linear order.

#include <list>

std::list<int> l;         // empty list
l.push_back(5);           // insert a 5 at the end
l.push_front(7);          // insert a 7 at the beginning
std::list::iterator i = l.begin();
++l;
l.insert(i, 6);           // insert a 6 in the middle

set

A set keeps the inserted elements sorted, and also makes sure that each element occurs only once. Of course, if you want to put something into a set, it must be less-than-comparable, i.e. you must be able to compare which of two objects a and b is smaller using a<b (there's also a way to define sets with an user-defined order, in which case this restriction doesn't apply).

#include <set>

std::set<int> s;          // empty set
s.insert(5);              // insert a 5
s.insert(7);              // insert a 7 (automatically placed after the 5)
s.insert(5);              // try to insert another 5 (will not change the set)

multiset

A multiset is like a set, except the same element may occur multiple times.

#include <multiset>

std::multiset<int> m;     // empty multiset
m.insert(5);              // insert a 5
m.insert(7);              // insert a 7 (automatically placed after the 5)
m.insert(5);              // insert a second 5 (now m contains two 5s, followed by one 7)

E

E has both mutable and immutable builtin collections; the common types are list (array), map (hash table), and set (hash table). This interactive session shows mutable lists and immutable collections of all three types.

? def constList := [1,2,3,4,5]
# value: [1, 2, 3, 4, 5]

? constList.with(6)
# value: [1, 2, 3, 4, 5, 6]

? def flexList := constList.diverge()
# value: [1, 2, 3, 4, 5].diverge()

? flexList.push(6)
? flexList
# value: [1, 2, 3, 4, 5, 6].diverge()

? constList
# value: [1, 2, 3, 4, 5]
? def constMap := [1 => 2, 3 => 4]
# value: [1 => 2, 3 => 4]

? constMap[1]
# value: 2
? def constSet := [1, 2, 3, 2].asSet()
# value: [1, 2, 3].asSet()

? constSet.contains(3)
# value: true

Java

  ArrayList arrayList = new ArrayList();
  arrayList.add(new Integer(0));
  
  /*other features of ArrayList*/
  //define the type in the arraylist, you can substitute a proprietary class in the "<>"
  private ArrayList<int> myarrlist; 
  int i;
  int sum;
  myarrlist = new ArrayList<int>();
  
  //add several values to the arraylist to be summed later
  for(i=0; i<10; i++)
  {
      myarrlist.add(i);
  }
  //loop through myarrlist to sum each entry
  for(i=0; i<myarrlist.size(); i++)
  {
      sum+=myarrlist.get(i);
  }
  //remove the last entry in the ArrayList
  myarrlist.remove(myarrlist.size()-1)
  //clear the ArrayList
  myarrlist.clear();

JavaScript

var array = [];
array.push('abc');
array.push(123);
array.push(new MyClass);
alert( array[2] );
var map = {};
map['foo'] = 'xyz'; //equivalent to: map.foo = 'xyz';
map['bar'] = new MyClass; //equivalent to: map.bar = new MyClass;
map['1x; ~~:-b'] = 'text'; //no equivalent
alert( map['1x; ~~:-b'] );

Lua

Lua has only one type of collection, the table.

collection = {0, '1'}
collection = {["foo"] = 0, ["bar"] = '1'} -- a collection of key/value pairs

Objective-C

Compiler: gcc

The NSMutableArray class in Objective C provides a simple, editable array data structure.

NSMutableArray *array = [[NSMutableArray alloc] init];

[array addObject:@"String1"];
[array addObject:@"String2"];
[array insertObject:@"String3" atIndex:1];

NSLog( @"%@, %@, %@", [array lastObject], [array objectAtIndex:0], [array objectAtIndex:1] );
// prints: String2, String1, String3

Perl

Interpreter: Perl

Collections are just lists. Thus, you can use list functions to manipulate them and store them in arrays.

my @c = (IO::File->new, IO::File->new);
# start collection with two objects

push @c, IO::File->new;
# add another object to the collection

PHP

  $students = array();
  array_push($students, array('name' => 'Joe Smith', 'age' => 21, height=> '72.5', gpa => 3.42 ));

Python

Interpreter: Python 2.5

In Python practically everything is an object, so using any of the provided structures can function as a collection. http://docs.python.org/tut/node7.html

collection = [0, '1'] # Lists are mutable (editable) and can be sorted in place
collection = (0, 1) # Tuples are immutable (not editable)
collection = {0: "zero", 1: "one"} # Dictionaries (Hash)
collection = set([0, '1']) # sets (Hash)

Ruby

Ruby is a 100% object oriented language, so you can use the default Array or Hash structures as collection objects.

Scala

val l = List(1,2,3,4,-1,-2,-4)
l.filter{0<} // get the positive values  List(1,2,3,4)
l.head // 1 -- first element
l.tail // List(2,3,4,-1,-2,-4) -- the rest of the list
l.take(3) // List(1,2,3) -- the first 3 elements in the list
l.drop(4) //  List(-1,-2,-4) -- get rid of the first 4 element in the list
88 :: l.tail //  List(88,2,3,4,-1,-2,-4)
l.take(2) ::: 18 :: l.takeRight(2) //  List(1,2,18,-2,-4)

Smalltalk

| collection |
collection := #(1 2 3 4 5) asOrderedCollection.
collection add: $a; add: $b.
collection remove: $a.
collection removeIndex: 2.