Showing posts with label array. Show all posts
Showing posts with label array. Show all posts

Tuesday, February 21, 2017

Array Initialization - Dynamic!

Java:
// anArray = new int[10];
int[] anArray = { 
    100, 200, 300,
    400, 500, 600, 
    700, 800, 900, 1000
};

anArray[0] = 100; // initialize first element
anArray[1] = 200; // initialize second element
anArray[2] = 300; // and so forth

System.out.println("Element 1 at index 0: " + anArray[0]);
System.out.println("Element 2 at index 1: " + anArray[1]);
System.out.println("Element 3 at index 2: " + anArray[2]);


Python:
#!/usr/bin/env python
# set, list, tuple, dict, deque, heapq, OrderedDict, defaultDict, Counter
 
x = set(["Postcard", "Radio", "Telegram"])
print(x)
# % set(['Postcard', 'Radio', 'Telegram'])

y = {"Postcard","Radio","Telegram"}
print(y)
# %  

myList=[i*i for i in range(10)]
myArray=[[1,2],[3,4]]

cnt = Counter()
for word in ['red', 'blue', 'red', 'green', 'blue', 'blue']:
   cnt[word] += 1
print(cnt)
# % Counter({'blue': 3, 'red': 2, 'green': 1})

c = Counter(a=4, b=2, c=0, d=-2)
list(c.elements())

# This is tuple
b = ("Bob", 19, "CS")       # tuple packing
(name, age, studies) = b    # tuple unpacking

def pairwise_sum (list1, list2):
   result = []
   for i in range (len(list1)):
      result.append(list1[i] + list2[i])
   return result


Perl:
# sum up two equal-sized lists of numbers and return the pairwise sum 
#
sub pairwise_sum {
   my ($arg1, $arg2) = @_;
   my (@result) = ();
   @list1 = @$arg1;
   @list2 = @$arg2;
   $len = @list1; # same as length(@list1)
   $max_index = $#list1;
   for ($i=0; $i < length(@list1); $i++) {
      push (@result, $list1[$i] + $list2[$i]);
   }
   return (\@result);
}


Ruby:
names = Array.new(20)
puts names.size  # This returns 20
puts names.length 

names = Array.new(4, "mac")
puts "#{names}"  # This returns "["mac", "mac", "mac", "mac"]"

nums = Array.new(10) { |e| e = e * 2 }
puts "#{nums}"   # This returns "[0, 2, 4, 6, 8, 10, 12, 14, 16, 18]"

nums = Array.[](1, 2, 3, 4,5)
nums = Array[1, 2, 3, 4,5]

digits = Array(0..9)
num = digits.at(6)


JavaScript:
var cars = ["Saab", "Volvo", "BMW"];
var cars = new Array("Saab", "Volvo", "BMW");
var name = cars[0];
document.getElementById("demo").innerHTML = cars[0];

// This is array
var person = ["John", "Doe", 46];
// This is object
var person = {firstName:"John", lastName:"Doe", age:46};


C++:
#include <iostream>
using namespace std;

int foo [] = {16, 2, 77, 40, 12071};
int another_foo [5] = { 16, 2, 77, 40, 12071 };

int jimmy [3][5];   // is equivalent to
int jimmy [15];     // (3 * 5 = 15) 
 
#define WIDTH 5
#define HEIGHT 3

int jimmy [HEIGHT][WIDTH];
int n,m;
int main ()
{
    for (n=0; n<HEIGHT; n++)
        for (m=0; m<WIDTH; m++) {
            jimmy[n][m]=(n+1)*(m+1);
        }
}


SystemVerilog:

  • Fixed-size (multi-dimension)
  • dynamic (single dimension)
  • queue (single dimension)
  • associative (single dimension)

typedef enum {IDLE, TEST, START} state;

Tcl/Tk:


# create array
set balloon(key) red
array set balloon {color red}
array set myArray {}
array set myArray {"name" "value"}
set myArray(name) value
array unset {this myarray}
set {this myarray(key)}
parray {this myarray}
foreach idx [array names x] {
     set x($idx) {}
}
# determine if a key exists
info exists array(key)
set value1 $myArray(name)
set value2 $myArray($idx)
eval {set ${key}($item)}
puts [set ${key}($item)]

# in a procedure, use upvar to create local reference to array
upvar $key v
puts $v($item)
set v($item) $val


# not so good
set a(key) value
value
array get a

# unset the whole array
unset myArray
# use array unset to unset a subset of keys

proc incrArrayElement {var key {incr 1}} {
    upvar $var a 
    if {[info exists a($key)]} {
        incr a($key) $incr
    } else {
        set a($key) $incr
    } 
}

array set data {
    foo,x ecks    foo,y why    foo,z zed
    bar,x ECKS    bar,y WHY    bar,z ZED
}
set data(foo)(x) ecks; set data(foo)(y) why; set data(foo)(z) zed
set data(bar)(x) ECKS; set data(bar)(y) WHY; set data(bar)(z) ZED
# join [array names data] \n


#
set a(1,1) 0 ;# set element 1,1 to 0
set a([list $i1 $i2 $i3]) 0; # set element (i1,i2,i3) of array a to 0
set a([list 1 2 3]) 0
# above i equivalent to the following
set {a(1 2 3)} 0

# multi-dimention
array set data [list                                         \
    [list foo x] ecks    [list foo y] why    [list foo z] zed\
    [list bar x] ECKS    [list bar y] WHY    [list bar z] ZED\
]
proc array_dimnames {array_var dim_index} {
    upvar 1 $array_var array
    set result [list]
    foreach name [lsort -unique -index $dim_index [array names array]] {
        lappend result [lindex $name $dim_index]
    }
    return $result
}

% array_dimnames data 0
bar foo
% array_dimnames data 1
x y z

proc declare_array arrayName {
    upvar 1 $arrayName array
    catch {unset array}
    array set array {}
} 

# array sort
proc array_sort {index val _foreach_sorting_array_ref foreachsorting_command} {
    # _foreach_sorting_array_ref is a reference this mean equivalent to &array in C
    upvar $_foreach_sorting_array_ref arrref
    upvar $index i
    upvar $val v
        
    set x [list]
    foreach {k vl} [array get arrref] {
        lappend x [list $k $vl]
    }
        
        foreach e [lsort -integer -decreasing -index 1 $x] {
        #puts "$i,$v"
                set i [lindex $e 0]
                set v [lindex $e 1]
                # ------- FOREACH BODY ------------<
        uplevel $foreachsorting_command
        # ------END FOREACH BODY----------->
        }  
}

set name(first) "Mary"
set name(last)  "Poppins"

puts "Full name: $name(first) $name(last)"
parray name

array set array1 [list {123} {Abigail Aardvark} \
                       {234} {Bob Baboon} \
                       {345} {Cathy Coyote} \
                       {456} {Daniel Dog} ]

if {[array exist array1]} {
    puts "array1 is an array"
} else {
    puts "array1 is not an array"
}

proc existence {variable} {
    upvar $variable testVar
    if { [info exists testVar] } {
 puts "$variable Exists"
    } else {
 puts "$variable Does Not Exist"
    }
}

# Create an array
for {set i 0} {$i < 5} {incr i} { set a($i) test }
existence a(0)

set mylist {}
lappend mylist a
lappend mylist b
lappend mylist c
lappend mylist d
foreach elem $mylist {
    puts $elem
}
// or if you really want to use for
for {set i 0} {$i < [length $mylist]} {incr i} {
    puts "${i}=[lindex $mylist $i]"
}

set myarr(chicken) animal
set myarr(cows) animal
set myarr(rock) mineral
set myarr(pea) vegetable

foreach key [array names myarr] {
    puts "${key}=$myarr($key)"
}

foreach {index content} [array get date] {
    put $index: $content
}

# use $array($key) or $array("abc") to access
# multi dimension, use
# set a(1,1) 0
# set a(1,2) 1



Sunday, October 23, 2016

Java Data Structure - Collections.

Collections

  • Autoboxing
  • Array List vs Linked List vs Queue
  • Hash map vs Tree map
  • untyped collections and wrapper class with untyped collections
  • Wrapper classes for primitive types
    • Byte (byte)
    • Short (short)
    • Integer (int)
    • Long (long)
    • Float (float)
    • Double (double)
    • Character (char)
    • Boolean (boolean)
  • Java Collection Framework (Collections is the basic methods):
    • Lists (ordered) - ArrayList and LinkedList
    • Sets  (no dupicate) - HashSet
    • Mapes (key value pair) - HashMap and TreeMap
  • How it's different from Arrays
    • Collections are classes in Java API, array is a Java Language feature.
    • Collection classes have methods.
    • Collections are varied in size.
    • Collections are containers for objects, not for primitive types.
    • Collections can process without indices while indices are usually required to process arrays.
  • Generic collections
    • ex. ArrayList<String> al = new ArrayList<String>();

Example
// This is an untyped array list
ArrayList al = new ArrayList();
al.add("item1");
al.add("item2");
for (Object o : al)
    { ... }

ArrayList p = new ArrayList();
p.add (new className (...));

for (int i = 0; i < p.size(); i++) {
    className c = (className)p.get(i);
    ...
}

// untyped array list will result in compiler warning
// Note: file.java uses unchecked or unsafe operations.
// Note: Recompile with -Xlint:unchecked for details.


ArrayList Numbers = new ArrayList();
numbers.add(new Interger(1));
numbers.add("Mary");

//
// and gives run time errors:
// Exception in thread "main" java.lang.ClassCastException: java.lang.String 
// cannot be cast to java.lang.Integer at Demo.main(file.java:37)

        ArrayList numbers = new ArrayList();
           numbers.add(new Integer(1));
           numbers.add(new Integer(2));
           numbers.add("Mary");
           numbers.add("Helen");

        for (int i = 0; i < numbers.size(); i++)
           {
               int number = (Integer)numbers.get(i);
               System.out.println(number);
           }



// Use collection in a generic array

ArrayList<String> codes = new ArrayList<String>();
codes.add("Mary");
codes.add("Helen");
codes.add("Raymond");
codes.add(100); //compiler error, wrong type, has to be String
System.out.println(codes);


// Using wrappers for primitives
ArrayList Numbers = new ArrayList();
numbers.add(new Integer(1));


Classes and Packages

  • java.util.Arrays
  • java.util.ArrayList
    • Constructors
      • ArrayList<E>()
      • ArrayList<E>(intCapacity)
      • ArrayList<E>(Collection)
    • Methods:
      • add(object)
      • add(index, object)
      • clear()
      • contains(object)
      • get(index)
      • indexOf(object)
      • isEmpty()
      • remove(index)
      • remove(object)
      • set(index, object)
      • size()
      • toArray()


Java Data Structure - Arrays.

Arrays
  • Array is aggregate data types that contains elements of the items in an array.
  • Built-in in Java for primitives or references.
  • Jagged array vs Retangular array
  • Enhanced for loop
  • Array Class: java.util.Arrays
    • fill (arrayName, value) // Fill out all elements to "value"
    • fill (arrayName, fromIndex, toIndes_plus_1, value)
    • equals (array1, array2)
    • copyOf (arrayFrom,  length) // JDK 1.6+ shallow copy for ref type
    • copyOfRange (arrayFrom,  fromIndes, toIndex_plus_one) // JDK 1.6+
    • sort (arrayName) // MUST implememts Comparable Interface
    • sort (arrayName, fromIndex, toIndex)
    • binarySearch (arrayName, value) // Must have compareTo, sort or binarySearch method defined and must do Arrays.sort first for binarySearch

Example
String [] sArray;
String sArray[];
sArray = new String[];
sArray = new String[10];
sArray = new String[10][];

String [] SArray = new String[];
String sArray [] = {"Mary", "Susan", "Raymond"};
double [] dArray = new double[10];
double [] prices = {12.95, 11.95, 10.95};

final int TOTAL_STUDENTS = 50;
Scanner sc = new Scanner(System.in);
int totalStudents = sc.nextInt();
String [] StudentsA = new String[TOTAL_STUDENTS];
String [] StudentsB = new String[totalStudents];

StudentsA[0] = "Mary";

String[] name1 = {"Forrest Gump", "A Beautiful Mind"};
String[] name2 = {"Forrest Gump", "A Beautiful Mind"};
// if (name1 == name2) ==> gives "false"
// if (Arrays.equals(name1, name2) ==> gives "true"

Public interface Comparable {
    int compareTo (Object obj);
}

class Item implements Comparable {
    private int number;
    private String name;
    public Item (int n, String s) {
        this.number = n;
        this.name = s;
    }

    public int getNumber () {
        return number;
    }

    // This overriding compareTo compares the first field
    //     which is the item.number in this case
    //     can be altered by supplementing with another
    //     class implementing "Comparator" interface
    //     to compare by name
    //
    @Ovrride
    public int compareTo(Object o) {
        if (o instanceof Item) {
            Item i = (Item) o;
            if (this.getNumber() < i.getNumber()) {
                return -1;
            } else if (this.getNumber() > i.getNumber()) {
                return 1;
            }
            return 0; 
        }
    }
}

public class ItemOtherCompare implements Comparator {
    public int compare (Object o1, Objece o2) {
        int i1 = ((Item) o1).getOtherField();
        int i2 = ((Item) o2).getOtherField();
        if (i1 > i2) return 1;
        if (i2 > i2) return -1;
        return 0;
    }

    public boolean equals (Object o1, Object o2) {
        int i1 = ((Item) o1).getOtherField();
        int i2 = ((Item) o2).getOtherField();
        return (i1 == i2);
        return false;
    }
}

// Arrays.sort(items); // this will sort by first field data
// Arrays.sort(items, new ItemOtherCompare()); // this will sort by other field


Tuesday, September 27, 2016

Array Initialization.

Java:
// anArray = new int[10];
int[] anArray = { 
    100, 200, 300,
    400, 500, 600, 
    700, 800, 900, 1000
};

anArray[0] = 100; // initialize first element
anArray[1] = 200; // initialize second element
anArray[2] = 300; // and so forth

System.out.println("Element 1 at index 0: " + anArray[0]);
System.out.println("Element 2 at index 1: " + anArray[1]);
System.out.println("Element 3 at index 2: " + anArray[2]);


Python:
myList=[]
for i in range(10):
    myList[i]=1

for i in range(10):
    myList.append(1)

myList=[i*i for i in range(10)]
myArray=[[1,2],[3,4]]

list_of4 = [3, "test", True, 7.4]

s = ["Lee", "Walsh", "Roberson"]
s2 = ["Williams", "Redick", "Ewing", "Dockery"]
s3 = [s, s2] # 2x2 list
s4 = s + s2; # concatenation two lists

list1, list2, list3 = [1,2,3], ['a','b','c'], [7,8,9]
all_lists = sum([list1, list2, list3], [])
# all_lists == [1, 2, 3, 'a', 'b', 'c', 7, 8, 9]

listanimal.append("cat")
listanimal.extend(["dog", "mouse"])

# This is tuple
b = ("Bob", 19, "CS")       # tuple packing
(name, age, studies) = b    # tuple unpacking

# data structure with lists and tuples
students = [
    ("John", ["CompSci", "Physics"]),
    ("Vusi", ["Maths", "CompSci", "Stats"]),
    ("Jess", ["CompSci", "Accounting", "Economics", "Management"]),
    ("Sarah", ["InfSys", "Accounting", "Economics", "CommLaw"]),
    ("Zuki", ["Sociology", "Economics", "Law", "Stats", "Music"])]

julia_more_info = ( ("Julia", "Roberts"), (8, "October", 1967),
                     "Actress", ("Atlanta", "Georgia"),
                     [ ("Duplicity", 2009),
                       ("Notting Hill", 1999),
                       ("Pretty Woman", 1990),
                       ("Erin Brockovich", 2000),
                       ("Eat Pray Love", 2010),
                       ("Mona Lisa Smile", 2003),
                       ("Oceans Twelve", 2004) ])



Perl:
my @other_array = (0,0,0,1,2,2,3,3,3,4);
my @zeroes = (0) x 5; 
my @zeroes = (0) x @other_array; # A zero for each item in @other_array.
                                 # This works because in scalar context
                                 # an array evaluates to its size.
# To get the "length" or "size" of an array, simply use it in a scalar context. 
$count = @array;
# Get the highest index
$highest_index = $#array;


Ruby:
names = Array.new(20)
puts names.size  # This returns 20
puts names.length 

names = Array.new(4, "mac")
puts "#{names}"  # This returns "["mac", "mac", "mac", "mac"]"

nums = Array.new(10) { |e| e = e * 2 }
puts "#{nums}"   # This returns "[0, 2, 4, 6, 8, 10, 12, 14, 16, 18]"

nums = Array.[](1, 2, 3, 4,5)
nums = Array[1, 2, 3, 4,5]

digits = Array(0..9)
num = digits.at(6)


JavaScript:
var cars = ["Saab", "Volvo", "BMW"];
var cars = new Array("Saab", "Volvo", "BMW");
var name = cars[0];
document.getElementById("demo").innerHTML = cars[0];

// This is array
var person = ["John", "Doe", 46];
// This is object
var person = {firstName:"John", lastName:"Doe", age:46};


C++:
#include <iostream>
using namespace std;

int foo [] = {16, 2, 77, 40, 12071};
int another_foo [5] = { 16, 2, 77, 40, 12071 };

int jimmy [3][5];   // is equivalent to
int jimmy [15];     // (3 * 5 = 15) 
 
#define WIDTH 5
#define HEIGHT 3

int jimmy [HEIGHT][WIDTH];
int n,m;
int main ()
{
    for (n=0; n<HEIGHT; n++)
        for (m=0; m<WIDTH; m++) {
            jimmy[n][m]=(n+1)*(m+1);
        }
}


SystemVerilog:

  • Fixed-size (multi-dimension)
  • dynamic (single dimension)
  • queue (single dimension)
  • associative (single dimension)

typedef enum {IDLE, TEST, START} state;
enum bit[2:0] {S0 = 'b001, S1 = 'b010, S2 = 'b100} st;
state cst, nst = IDLE;
$display ("st = %3b, nst = %s", st, nst.name;
// showing on screen: st = 0, nst = IDLE

typedef reg [7:0] octet;
octet b;
// same as reg [7:0] b;
typedef octet [3:0]
quadOctet;
quadOctet qBytes [1:10];
// same as 
// reg [3:0][7:0] qBytes [1:10];
typedef enum { circle, ellipse, freeform } ClosedCurve;
ClosedCurve c;
// same as
// enum { circle, ellipse, freeform } c;
struct {
  int x, y;
} p;
p.x = 1;
p = {1,2};
typedef struct packed {
  int x, y;
} Point;
Point p;

integer numbers[5]; // array of 5 integers, indexed 0-4
int b[2] = '{3,7};
int c[2][3] = '{{3,7,1},{5,1,9}};
byte d[7][2] = '{default:-1};
bit[31:0] a[3][2] = c;
for (int i=0; i<$dimensions(a);i++) begin
   $display ($size(a, i+1));
end

// queues
int j = 1;
int q[$] = {0,1,3,6}; // note, no' as in arrays
int b[$] = {4,5};   // no '
q.insert (2, j);    // {0,1,2,3,6}
q.insert (4, b);    // {0,1,2,3,4,5,6}
q.delete (1);       // {0,2,3,4,5,6}
q.push_front (7);   // {7,0,2,3,4,5,6}
j = q.pop_back();   // {7,0,2,3,4,5}   j = 6
q.push_back(8);     // {7,0,2,3,4,5,8}
$display($size(q)); // 7
q.delete();         // delete all elements
$display($size(q)); // 0

// Associative Arrays
integer aa[*];
integer aa_too[int];
// use aa.delete(), aa.first(), aa.next(), aa.prev(), aa.last()
// to traverse
byte ba[string], t[*], a[*];
int index;
ba["byte0"] = -8;
for (int i=0; i < 10; i++) 
   t[1<<i] = i;
a=t;
$display ("size of t array is: %0d", t.num()); // array size

// Array Methods
// num(), delete(), exists(), first(), last(), next(), prev()

byte ba[string], t[*], a[*];
int index;
ba["byte0"] = -8;
for (int i=0; i mmm 10; i++) begin
   t[1<<i] = i;
end
// t[1]=0, t[2]=1; t[4]=2, t[8]=3,...
a=t;
$display ("size of t array is: %0d", t.num()); // array size

// Array Loop : foreach (array[i]) 
// Array Methods:
// function array[$] array.find() with (item < 3) // returns {value}
// function int[$] array.find_index() with (item < 3) // returns {index}
// function array[$] array.find_first() [with (exp)]
// function int[$] array.find_first_index() [with (exp)]