Wednesday, February 27, 2019

Python Seaborn Library

Meet Seaborn
Why Seaborn
  • Compliments and extend matplotlib
  • Work with NumPy, Pandas data frames
  • Makes default parameters in matplotlib easy
  • Built-in themes for data analysis and machine learning algorithms
  • Matplotlib vs Seaborn
  • Matplotlib
  • import matplotlib.pyplot as plt
    import pandas as pd
    
    fg, ax = plt.subplots()
    mydt = pd.read_csv("https://path/to/data.csv")
    
    ax.violinplot(mydt["axi_label"], vert=False)
    plt.show()
    
  • Seaborn
  • # Import the necessary libraries
    import matplotlib.pyplot as plt
    import seaborn as sns
    
    mydt = sns.load_dataset("data")
    
    sns.violinplot(x = "axi_label", data=mydt)
    plt.show()
    

    Thursday, February 21, 2019

    Jupyter 101

    Jupyter notebook : IPython
  • jupyter.org
  • Install Jupyter notebook
  • Install Anaconda
  • Anaconda.org Cloud
  • Anaconda packages using pip
  • Anaconda packages development in GitHub
  • Anaconda documentation
  • # anaconda packages installation
    # conda install pip
    % conda install -c anaconda pip
    % pip install package-name 
    # to launch
    % jupyter notebook
    # Or, launch from Anaconda Navigator
    # to install new packages
    # import sys
    # !{sys.executable} -m pip install newpackage
    
    Basics
  • Dashboard
  •    File
       Run
       New
    
  • Menu Bar
  • Tool Bar
  • Create new notebook
  • Rename notebook
  • Save notebook
  • Load notebook and "run all"
  • Cell : command mode, edit mode, raw NB convert mode
  • shortcuts : command palette
  • Shift-Enter
  • Example : code cell
    import numpy as np
    print (np.__version__)
    
    import sqlite3
    # from IPython.utils.path import get_ipython_dir # moved to IPython.paths
    import pprint
    from IPython.paths import get_ipython_dir
    hist_file = '%s/profile_default/history.sqlite' % get_ipython_dir()
    print (hist_file)
    
    Example : markdown cell (use print preview or shift-enter, double click to edit)
    [esc]+m
    %matplotlib qt
    %matplotlib auto
    %matplotlib inline
    %matplotlib -l
    %matplotlib --list
    [esc]+o           ## toggle output
    %load_ext?
    %time?
    !ls
    !dir
    !pwd
    
    ### Heading1
    ## Heading2
    # Heading1
     [Link to this page](http://www.google.com)
    
    1. first
        1. first of first
    2. second
    
    - bullet
        - bullet
    *italic*
    _italic_
    **bold**
    ***italic and bold***
    ~~strike through~~
    
    Example : Markdown Table
    # use http://www.tablesgenerator.com/markdown_tables
    #     to generate the markdown code for tables
    # copy the table form Excel or Google Sheet
    #     paste to the table on This Page
    #     and click [Generate]
    # copy the Result code to your Jupyter Notebook Markdown Cell
    
    Example : Fun with matplotlib
    import matplotlib.pyplot as plt
    t = np.ones(30)
    # red dashes, blue squares and green triangles
    plt.plot(t, t, 'r--', t, t**2, 'bs', t, t**3, 'g^')
    plt.show()
    
    Example : Visualize Big O Notation
    import numpy as np
    import matplotlib.pyplot as plt
    n = np.ones(40)
    t = np.arange(1.,20.,0.5)
    lineflt = plt.plot(t, t*0, 'g--' )
    linelog = plt.plot(t, np.log(t), color='#990000', label="O(Log n)")
    #plt.plot(t, np.log(t), 'b', t, t, 'r', t, t*t,)
    linelin = plt.plot(t,t, label="O(n) linear", color='orange')
    linenlg = plt.plot(t,t*np.log(t), label="O(n Log n)")
    linen2n = plt.plot(t,t*t, 'c', label="O(n^2)")
    linen3n = plt.plot(t,t**3, color='#ffa500', label="O(n^3)")
    line2tn = plt.plot(t,2**t, 'm', label="O(2^n)")
    plt.ylim(0,100)
    plt.legend()
    plt.grid(True)
    # plt.ylabel('some numbers')
    plt.show()
    

    Wednesday, February 20, 2019

    Python Pandas Library

    What is Pandas
  • Pandas : Panel Data
  • Structure data as a virtual spreadsheet.
  • Visualize data to find issues, such as sparse dataset, missing dataset.
  • Pandas.pydata.org
  • Pandas Docs
  • Pandas Quick Overview
  • NumPy.org
  • SciPy.org
  • See PyPI for 3rd party libraries
  • >>> import pandas as pd
    >>> from pandas import DataFrame, Series
    >>> help (pd)
    
    Applications
  • For a recommendation system, create a rating matrix and predict missing ratings for each user
           based on existing reviews.
  • Classification
  • Value estimation
  • Basics
    Example : First Look at pandas
    import numpy as np
    import pandas as pd
    mysr = pd.Series ([2,4,6, np.non, 7,9])
    mydt = pd.date_range('20200202', periods = 6)     ## default frequency is daily
    mynp = np.array (np.arange(24)).reshape((6,4))
    mydf = pd.DataFrame (mynp, index = mydt, columns = list('PQST'))
    print ( mydf.head() )                             ## default print head 5 rows
    print ( mydf.tail(10) )                           ## default print tail 5 rows
    print ( mydf.values )
    print ( mydf.index )
    print ( mydf.columns )
    
    d.set_option ('display.percision', 2)
    # pandas option docs
    print ( mydf.describe() )                         ## a quick statistical summary, 
                                                      ## int will be viewed as float
    pd.set_option ('display.percision', 2)
    # pandas option docs
    
    # create data frame from python dictionary
    dcdf = pd.DataFrame ({ 
        'float' : 1., 
        'time' : pd.Timestamp ('20200808'),
        'series' : pd.Series (1, index = list (range(4)), dtype = 'float32' ),
        'array' : np.array ([3] * 4, dtype = 'int32' ),
        'categories' : pd.Categorical (['t1','t2','t3','t4']),
        'misc' : 'useless data'
        })
    print (dcdf.dtypes)
    print (dcdf.T)
    dcdf.sort_index( axis=1, ascending=False)          ## sort along the axis, default axis=0
    dcdf.sort_values (by='Q', ascending=False)
    
    Example : get json data and plot density charts
    from pandas import DataFrame, Series
    import pandas as pd
    import json
    from  collections import defaultdict
    
    def get_count(l=[]):
        res = defaultdict(int)
        for i in l:
            res[i] += 1
        return res
    
    def best_count(h={}, n=5):
        list = [ (v, k) for k, v in h.items() ]
        return list[-n:]
    
    # file.json contains list of dict, each has many fields
    data = [json.loads(line) for line in open('file.json')
    frame = DataFrame (data)
    print (frame)
    
    namelist = [item['name'] for item in data if 'name' in item]
    hcount = get_count(namelist)
    toplist = best_count(hcount)
    
    # using pandas
    ptoplist = frame['name'].value_counts()
    print( ptoplist[:5] )
    
    # cleaning dataset
    newlist = frame['name'].fillna('Missing name')       ## replace missing values
    newlist[newlist == ''] = 'Unknown'                   ## replace empty entries
    
    # Series
    results = Series ( [s.split()[0] for s in frame.key.dropna()] )
    print (results[:5])
    print (results.value_counts()[:8]
    newframe = frame [frame.key.notnull()]
    location = np.where( newframe['key'].str.contains('USA'), 'In USA', 'Out of USA' )
    by_location = newframe.groupby ( ['name', location] )
    groupcnt = by_location.size().unstack().fillna(0)
    print (groupcnt[:5])
    
    sortlist = groupcnt.sum(1).argsort()
    print (sortlist[:5])
    
    sublist = groupcnt.take( sortlist )[-12:]
    sublist.plot( kind='barh', stacked=True )
    normlist = sublist.div( sublist.sum(1), axis=0 )
    normlist.plot ( kind = 'barh', stacked=True )
    
    
    Example : view data from CSV file
    import pandas
    import webbrowser
    import os
    
    # "data_id" is the column header in the file
    data_table = pandas.read_csv("data_set.csv", index_col="data_id")
    html = data_table[0:100].to_html()
    with open("data.html", "w") as f:
        f.write(html)
     
    full_filename = os.path.abspath("data.html")
    webbrowser.open("file://{}".format(full_filename))
    
    Example : Using Pandas with NumPy
    import pandas as pd
    import numpy as np
    import webbrowser
    import os
    
    # "data_id" is the column header in the file
    data_table = pd.read_csv("data_set.csv")
    result = pd.pivot_table(data_table, index='user_id', columns='data_id', aggfunc=np.max)
    
    # write to a csv file
    result.to_csv("data.csv", na_rep="")
    
    # or generate a html and write out
    html = result[0:100].to_html(na_rep="")
    with open("data.html", "w") as f:
        f.write(html)
     
    full_filename = os.path.abspath("data.html")
    webbrowser.open("file://{}".format(full_filename))
    
    Example : Create a Recommendation matrix
    import numpy as np
    import pandas as pd
    import matrix_factorization_utilities
    
    raw_data = pd.read_csv('data.csv')
    ratings = pd.pivot_table(
              raw_data, index='user_id', columns='movie_id', aggfunc=np.max)
    
    # Apply matrix factorization to find the latent features
    x,y = matrix_factorization_utilities.low_rank_matrix_factorization(
                                                   ratings.as_matrix(),
                                                   num_features=15,
                                                   regularization_amount=0.1)
    
    # Calculate ratings by multiplying the x by y
    predicted_ratings = np.matmul(x, y)
    df = pd.DataFrame(index=ratings.index,
                      columns=ratings.columns,
                      data=predicted_ratings)
    df.to_csv("predicted_ratings.csv")
    

    Python NumPy Library

    What is NumPy
  • NumPy : Numerical Python
  • Support large multi-dimensional arrays and metrics
  • Support large collection of high-level mathematical functions on these arrays
  • NumPy.org
  • NumPy.org
  • NumPy reference docs
  • NumPy commands html
  • See PyPI for 3rd party libraries
  • >>> import numpy as np
    >>> help (np)
    >>> a = np.array([1,2,3])
    >>> b = a.tolist()
    >>> c = np.arange(4).reshape(2.2)
    >>> d = np.zeros((2,2))
    
    Basics
  • Attributes : data types, size, shape, memory consumption
  • Indexing
  • Slicing
  • Reshaping
  • Joining and splitting
  • Masking
  • Broadcasting
  • Structured arrays
  • Example : Attributes
    import numpy as np
    dir(np)
    print(np.__version__)
    nparray = np.arange(10)
    print (nparray)
    
    np.random.seed(0)
    x = np.random.randint(10, size=8)
    
    x.ndim
    x.shape
    x.size
    x.dtype
    x.dtype.str
    x.itemsize
    x.nbytes
    x.real              # for complex numbers, this returns the real part
    x.imag              # for complex numbers, this returns the imaginary part
    x.size
    
    Example : Indexing
    import numpy as np
    np.random.seed(0)
    x = np.random.randint(10, size=8)
    x[1]
    x[-1]
    x[-2]
    x[0] = 3.456 # will be truncated, dtype is int32
    
    y = np.random.randint(10, size=(5,5))
    y[1,2]
    y[1][2]             # same as y[1,2]         
    y[2,-1]
    y[0,1] = 20
    y
    
    Example : Slicing
    import numpy as np
    z = np.arange(10)
    z[:5]
    z[3:]
    z[2:8]
    z[::3]              # every third element
    z[1::2]             # every other, odd elements
    z[::-1]             # all elements in reversed order
    z[9::-4]            # every fourth element in reversed order
    
    Example : Multi-dimensional subarrays
    import numpy as np
    np.random.seed(0)
    x = np.random.randint(10, size=(3,4,3))
    x
    x[:2, :3]           # sub array taking 2 rows and three columns
    x[:3, ::2]          # sub array taking 3 rows and every other column
    x[::-1, ::-1]       # sub array reversing rows and columns
    x[::-1]             # reverse the whole array
    
    # accessing single row or column
    x[0, :]             # first row, same as x[0]
    x[:, 0]             # first column
    
    Example : Creating copies of subarrays
    # Slice sub arrays without copying will modify the original array
    # when you modify the subarray
    import numpy as np
    np.random.seed(0)
    x = np.random.randint(10, size=(3,4,3))
    x
    y = x[:2, :2]
    y[0,0] = 12345
    print(y)
    print(x)
    
    # create copy of x
    z = x[:4,:4].copy()
    # now try to change z and check x
    q = z.resize((1,2))
    q.ravel()             # flatten as a view, point to same object
    q.flatten()           # same as ravel, and allocate new memory 
    
    p = q.view()          # p and q point to same object
    id(p)
    id(q)
    p is q
    r = np.insert(p, 1, 505, axis=0)
    s = np.empty(p.shape) # create new array in same shape as 'p'
    np.copyto( s, q )
    np.delete( q, 1, axis=0 )
    
    Example : Reshaping
    import numpy as np
    x = np.arange(1,10).reshape(3,3)
    y = np.arange(1,17).reshape(4,4)
    # size of np.arange must match size of the reshaped array
    
    x1 = np.array([1,2,3])
    x1.reshape((1,3))
    x1[np.newaxis, :]     # row vector using newaxis
    x1[:, np.newaxis]     # column vector using newaxis
    x1.reshape((3,1))     # column vector using reshape
    
    Example : Concatenation and Stacking of arrays
    import numpy as np
    x = np.arange(5)
    xtriple = x*3
    print(xtriple)
    y = np.arange(10)
    z = np.concatenate([x,y])
    q = np.concatenate([x,y,z])
    
    x2d = np.array([[1,2,3],[4,5,6]])
    y2d = np.concatenate ([x2d,x2d] )
    z2d = np.concatenate ([x2d,x2d], axis=1)
    
    # using np.hstack or np.vstack
    # np.dstack will stack along the third axis
    x = np.array([1,2,3])
    x2d = np.array([[9,9,9],[8,7,6]])
    xx = np.vstack([x, x3d])
    y = np.array([[3],[3]])
    yy = np.hstack([x2d, y])
    column_stack((x,y))
    row_stack((x,y))
    
    a = arange(4)reshape(2,2)
    b = np.array([[5,6]])
    hstack((a,b))   # same as np.append(a,b,axis=1) # append along y, change (*, y, *) shape
    vstack((a,b))   # same as np.append(a,b,axis=2) # append along x, change (*, *, x) shape
    concatenate((a,b), axis=0) # same as vstack
    dstack((a,b)) # depth stacking
    column_stack((a,b)) # stack 1d array column-wise
    row_stack((a,b))
    
    Example : Splitting, squeezing and reshaping
    import numpy as np
    x = [1,2,3,4,5,6,7,8]
    a,b,c = np.split(x, [3,5])
    # np.hsplit and np.vsplit
    x2d = np.arange(16).reshape((4,4))
    upper_ary, lower_ary = np.vsplit(x2d,[2])
    # check upper and lower arrays
    left_ary, right_ary = np.hsplit(x2d,[2])
    # check left and right arrays
    
    X = np.arange(27).reshape(3,3,3)
    # split()
    # hsplit()
    # vsplit()
    # dsplit()
    
    hsplit(X)
    split(X, 3, axis=1) # same as hsplit(X,3)
    split(X, 3, axis=0) # same as vsplit(X,3)
    dsplit(array,3)      # deep split
    
    Example : linespace, zeros, ones
    import numpy as np
    # notice linspac euse closed interval where end point is included
    ary = np.linspace(7,26,9)
    ary = np.linspace(7,26,9, retstep=True)
    ary = np.zeros(5, dtype='int32')
    np.ones((7,8))
    # default dtype for zeros and ones is float
    # default dtype for arange and linspace is int
    
    ary = np.ones((2,2))
    ary.squeeze()
    
    Example : random
    import numpy as np
    # notice linspac euse closed interval where end point is included
    ary = np.random.random.rand()            ## uniform distribution
    ary = np.random.random.randn()           ## gaussian normal distribution
    np.random.random.seed(0)                 ## not thread safe
    
    Example : Mathematical operators
    import numpy as np
    m0 = np.ones(2)
    m1 = np.ones(2)*3
    np.inner (m0,m1)
    
    m0 = np.arange(4).reshape(2,2)
    m1 = np.arange(8).reshape(2,4)
    np.dot (m0,m1)
    
    nparray.shape(1,2,3)
    nparray.sum(axis=2)
    np.set_printoptions(precision=4)
    
    Example : logical operators
    import numpy as np
    ary = np.arange(12).reshape(3,4)
    x0  = 0 == (ary % 3)
    x1  = ary > 3
    x2  = np.logical_and (x0, x1)
    # y and z would result in same matrix
    y = ary[x2]
    z = ary[ary > 3]
    
    Example : structured array
    import numpy as np
    
    person_data_def = [('name','s10'), ('height','f8'), ('weight','f8'), ('age','i2')] 
    people_array = np.zeros((4), dtype=person_data_def)
    
    Example : Comparison
    import numpy as np
    
    x = [1,2,3,4,5]
    print (x*2)
    y = np.array([1,2,3,4,5])
    print (y*2)
    
    # to get the same result for x
    for i, v in enumerate (x):
        x[i] *= 2
    print(x)
    

    Tuesday, February 19, 2019

    Java Maps

    Java Map Interface
    Library
  • java.util.Map
  • java.util.TreeMap

  • Background
  • Maps are part of the Collections Framework but technically Maps are not collections
           because they do not implement the Collection interface.
  • Maps store key / value pairs and all keys must be unique.
  • All maps implement the Map interface and share a common functionality that allows
           adding a key/value pair or access the value given they key.
  • Map provides two collection-views to deal with the keys and values separately.
  • A set of the entries is obtained by calling entrySet(). It returns a Set collection.
           The Set that contains the entries, which are held in an object of type Map.Entry.
  • The key can be obtained by calling getKey().
  • The value can be obtained by calling getValue().
  • The Set of the keys can be obtained by calling keySet().
  • The Collection of the values can be obtained by calling values().

  • Methods
    # Map is a generic interface
    # interface Map<K, V>
    public void clear()
    public boolean containsKey(Object k)
    public boolean containsValue(Object v)
    public Set<Map.Entry<K, V>> entrySet()
    public V get(Object k)
    public boolean isEmpty()
    public Set<K> KeySet()
    public V put(K k, V v)
    public void putAll (Map<? extends K, ? extends V> m)
    public v remove(Object k)
    public int size()
    public Collection<V> values()
    
    Java Map example code
    import java.io.*;
    import java.util.*;
    
    class MyMaps
    {
        public static void main(String args[]) {
            // Create a tree map
            TreeMap<String, Integer> myNums = new TreeMap<String, Integer>();
            myNums.put ("this", 99);
            myNums.put ("one", 1);
            myNums.put ("two", 2);
    
            System.out.println ("the map contains " + myNums.size() + " items.");
    
            // Create a set of the entry
            Set<Map.Entry<String, Integer>> set = myNums.entrySet();
            for (Map.Entry<String, Integer> my : set) {
                System.out.println (my.getKey());
                System.out.println (my.getValue());
            }
    
            // A new map to merge with myNums
            TreeMap<String, Integer> myNums2 = new TreeMap<String, Integer>();
            myNums2.put ("three", 3);
            myNums2.put ("four", 4);
            myNums.putAll (myNums2);
    
            // To show all entries after merging
            set = myNums.entrySet();
            System.out.println (myNums.size());
    
            for (Map.Entry<String, Integer> my : set) {
                System.out.println (my.getKey());
                System.out.println (my.getValue());
            }
    
            // To search a key
            if (myNums.containsKey("six")
                 System.out.println (myNums.get("six"));
            // Search for a value
            if (my.Nums.containsValue (1))
                System.out.println ("yes");
    
            // To remove an entry
            if (myNums.remove("six") != null)
                System.out.println ("six is removed!");
            else
                System.out.println (my.getValue());
    
            // Show entries after removal
            Set<String> keys = myNums.keySet();
            for (String str : keys)
                System.out.println (str);
            // Display the value set after removal
            Collection<Integer> values = myNums.values();
            for (Integer i : values)
                System.out.println (i);
    
            // Clear the map
            myNums.clear()
            if (! myNums.isEmpty())
                System.out.println ("The map is not empty! Check again!");        
        }
    }
    

    Thursday, February 14, 2019

    Java Collections!

    Java Collections and Iterators
    Java collection framework includes:
    - Interface
    - Class of implementation
    - Algorithm
    
    Methods
    public boolean hasNext()
    public object next()
    public void remove()
    
    Java Multi Dimentional Arrays

    Examples
    import java.io.*;
    import java.util.*;
    import static java.lang.System.*;
    // import java.util.ArrayList;
    // import java.util.Arrays;
    // import java.util.List;
    
    
    public class ary2d{
        public static void main(String[] args) throws IOException {
            BufferedReader br = new BufferedReader(new FileReader("my.in"));
            PrintWriter pw = new PrintWriter(new BufferedWriter(new FileWriter("my.out")));
    
            int n = Integer.parseInt(br.readLine());
            StringTokenizer st = new StringTokenizer(br.readLine());
    
            ArrayList<String> list = new MyArrayList<String>("a", "b", "c");
            ArrayList<ArrayList<String>> array = new ArrayList<ArrayList<String>>();
    
            ArrayList<ArrayList<String>> biDemArrList = new ArrayList<ArrayList<String>>();
            ArrayList<String> temp = new ArrayList<String>(); // added () 
            temp.add("Hello world.");
            biDemArrList.add(temp);
    
            ArrayList<ArrayList<String>> matrix = new ArrayList<ArrayList<String>>();
    
            // List<ArrayList<Integer>> a = new ArrayList<>(); // java 1.7+
            List<ArrayList<Integer>> a = new ArrayList<ArrayList<Integer>>();
    
            ArrayList<Integer> a1 = new ArrayList<Integer>();
            a1.add(1);
    
        }
    }
    
    class Array2D<T> extends ArrayList<ArrayList<T>> {
        public void addToInnerArray(int index, T element) {
            while (index >= this.size()) {
                this.add(new ArrayList<T>());
            }
            this.get(index).add(element);
        }
    
        public void addToInnerArray(int index, int index2, T element) {
            while (index >= this.size()) {
                this.add(new ArrayList<T>());
            }
    
            ArrayList<T> inner = this.get(index);
            while (index2 >= inner.size()) {
                inner.add(null);
            }
    
            inner.set(index2, element);
        }
    }
    
    class TwoDimArray<T> extends ArrayList<ArrayList<T>> {
        public void addToInnerArray(int index, T element) {
            while (index >= this.size()) {
                // Create enough Arrays to get to position = index
                this.add(new ArrayList<T>()); // (as if going along Vertical axis)
            }
            // this.get(index) returns the Arraylist instance at the "index" position
            this.get(index).add(element); // (as if going along Horizontal axis)
        }
    
        public void addToInnerArray(int index, int index2, T element) {
            while (index >= this.size()) {
                this.add(new ArrayList<T>());// (as if going along Vertical
            }
            //access the inner ArrayList at the "index" position.
            ArrayList<T> inner = this.get(index);
            while (index2 >= inner.size()) {
                //add enough positions containing "null" to get to the position index 2 ..
                //.. within the inner array. (if the requested position is too far)
                inner.add(null); // (as if going along Horizontal axis)
            }
            //Overwrite "null" or "old_element" with the new "element" at the "index 2" ..
            //.. position of the chosen(index) inner ArrayList
            inner.set(index2, element); // (as if going along Horizontal axis)
        }
    }
    
    Java Collections
        ArrayList astr=new ArrayList();
        astr.add("john");
        Iterator itr=astr.iterator();
        while(itr.hasNext()){
            System.out.println(itr.next());
        }
    

    C++ arrays!

    C++ arrays
    #include <stdio.h>
    #include <algorithm>
    #include <fstream>
    #include <iostream>
    #include <map>
    
    using namespace std;
    
    int main()
    {
        ifstream fin ("text.in");
        int n;
    
        fin >> n;
        int *array = new int[3];
        cout << " array " << endl;
        for ( int i = 0; i < 3; i++ ) {
            // array[i] = new int[n];
            cout << array[i] << endl;
        }
        cout << endl;
        int** ary = new int*[3];
        for ( int i = 0; i < 3; i++ ) {
            ary[i] = new int[n];
            cout << ary[i][0];
        }
        for ( int i = 0; i<3; i++ ) {
            delete [] ary[i];
        }
        typedef int ARR1[2];
        int (*arr)[2] = new int[3][2];
        ARR1* arrtype = new ARR1[3];
        int ***arr3 = new int **[2];
        int **arrr = new int*[4];
    
        // auto arrauto = 4;
        auto arrauto = new int[4][2];
    
        printf("n %d\n", n);
        cout << "n: " << n << endl;
    
        auto ary2 = new int[5001]();    // initialize all elements with 0
        fill_n (ary2, 5001, 3);         // initialize all elements with (int)3
        // c style, cstring use memset (ary2, 0, n*sizeof(int));
    
    #include <algorithm>
    #include <fstream>
    #include <iostream>
    
    using namespace std;
    
    int main()
    {   
        ifstream fin ("game.in");
        int num_of_cup = 3;
        int n;
        fin >> n;
        auto ary = new int*[n];
        for ( int i = 0; i < n; i++ ) {
            ary[i] = new int[3];
            for ( int j = 0; j < 3; j++ ) {
                fin >> ary[i][j];
            }
        }   
                
        int maxpoint = 0; 
        for (int i = 1; i < num_of_cup + 1; i++) {
            int point = 0;
            int current = i;
            for (int j = 0; j < n; j++) {
                if (ary[j][0] == current) {current = ary[j][1];}
                else if (ary[j][1] == current) {current = ary[j][0];}
                if (ary[j][2] == current) {point++;}
            }
            maxpoint = max( maxpoint, point );
        }
        cout << maxpoint << endl;
    
        return 0;
    }
    
    #include <algorithm>
    #include <fstream>
    #include <iostream>
    
    using namespace std;
    
    int main()
    {
        ifstream fin ("sleepysort.in");
        int n;
        fin >> n;
        auto animal = new int[n];
        auto animal_name = new string[n];
        auto animal_is = new string*[n];
        for (int i = 0; i < n; i++) {
            string s;
            int k;
            fin >> s;
            fin >> k;
            for (int j = 0; j < k; j++) {
                fin >> s;
                cout << s << " ";
            }
            cout << endl;
            // fin >> animal_name[i];
        }
    }
    
    Using <vector>
    #include <algorithm>
    #include <fstream>
    #include <iostream>
    #include <vector>
    
    using namespace std;
    
    int main()
    {
        ifstream fin ("guess.in");
        int n;
        fin >> n;
        // auto animal = new int[n];
        auto animal_name = new string[n];
        auto animal_is = new string*[n];
        // pair<int,int> animal_has[n];
        // pair<string,int> *guess_has;
        // vector<pair<string,int>> guess_has;
        vector<string> has;
        vector<pair<int,string>> has_vec;
        // auto has_name  = new string[101];
        // auto has_count = new int[101];
        string has_name[101];
        int has_count[101]; 
        for (int i=0; i < n; i++) {
            int k;
            fin >> animal_name[i];
            fin >> k;
            animal_is[i] = new string[k];
            for (int j = 0; j < k; j++) {
                fin >> animal_is[i][j];
                // guess_has.push_back( make_pair(animal_is[i][j], 1) );
                has.push_back( animal_is[i][j] );
                // cout << animal_is[i][j] << " ";
            } 
        }
        sort( has.begin(), has.end() );
        
        string last_name = "";
        int index = 0;
        for (auto i : has) {
            if (last_name == i) {
                // cout << index << " same** " << i << " " << last_name << endl;
                has_count[index]++;
                // cout << index << " " << has_name[index] << " " << has_count[index] << endl;
            } else {
                // cout << index << " " << i << " " << last_name << endl;
                index ++;
                has_name[index] = i;
                has_count[index] = 1;
                last_name = i;
                // cout << index << " " << has_name[index] << " " << has_count[index] << endl;
            }
        }
    
        for (int i = 0; i < 101; i++) {
            if (has_count[i] > 0) { has_vec.push_back( make_pair( has_count[i], string(has_name[i]) ) ); }
            // if (has_count[i] > 0) { cout << i << " " << has_count[i] << " " << has_name[i] << endl; }
        }
        sort( has_vec.begin(), has_vec.end(), greater<>() );
        for (auto i : has_vec) {
            cout << i.first << " " << i.second << endl;
            int n = i.first;
            for
            for (int i=0; i<3; i++) {
            }
        }
    
        cout << endl;
    
        return 0;
    }
    

    Tuesday, February 12, 2019

    Java arrays!

    Java Arrays
    import java.util.ArrayList;
    import java.util.Arrays;
    import java.util.List;
    
    public class array {
        public static void main(String[] args) { 
    
            int i,j,k;
            i = j = k = 0;
            System.out.println("demo hello");
            
            int[] nums = new int[20];
            double[] prices = { 5.5, 3, 4.2 };
            boolean[] ans = { true,false,true };
            char[] vowels = { 'a','e','i','o','u' };
            String[] names = new String[10];
    
            nums[1] = 1;
            nums[2] = 2;
            printarray (nums);
            ArrayList list = new ArrayList<>();
            Arrays.sort (nums);
            Arrays.sort (nums);
            int[][] rents = {{},{},{}};
            
            // ArrayList can only hold Objects
            // ArrayList is a dynamic array
            List<Integer> myiary = new ArrayList<Integer>();
            myiary.add(2);
        }
     
        public static void printarray (int[] a) {
            int j = 0;
            for (int i : a) {
                System.out.printf("s[%d] = %d, " , j,i);
                j++;
                if (j % 5 == 0) {
                    System.out.println();
                }
            }
        }
     
        public static void printarray (String[] a) {
            for (String i : a) {
                System.out.printf("%s\n" , i);
            }
        }
    }
    
    Java String and Characters
    public static void main(String[] args) throws IOException {
        BufferedReader f = new BufferedReader(new FileReader("beads.in"));
        PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter("beads.out")));
        StringTokenizer st = new StringTokenizer(f.readLine());
         
        int n = Integer.parseInt(st.nextToken());
        String s = f.readLine();
        char[] sc = s.toCharArray();
        System.out.println(sc);
    
        char[] chars = {'t','h','i','s',' ','\u0024'};  // \u0024 is $ sign
        String s = new String(chars);
        System.out.println( s );
    }
    
    Insert and copy arrays
        public static void copyArray(int[] array, int index) {
             List<Integer> myiary = new ArrayList<Integer>();
             myiary.add(2);
    
             int[] tmp = new int[array.length-1];
             System.arraycopy( array, 0, tmp, 0, index);
    
             Integer[] iarray = new Integer[] { 2,3,4 };
             List<Integer>> iiarray = new ArrayList<Integer>() {{
                 add(1);add(2);add(3);
             }};
        
             List<Integer> list = new ArrayList<Integer>(Arrays.asList(iarray));
             List<Integer> iilist = new ArrayList<Integer>(iiarray);
    
             ArrayList<String> slist = new ArrayList<String>(Arrays.asList(
                 new String[] {"One","Two","Three","Four"}));
        }
    
    Modify and merge elements in arrays
        String a[] = { "A", "E", "I" };
        String b[] = { "O", "U" };
        List list = new ArrayList(Arrays.asList(a));
        list.addAll(Arrays.asList(b));
        Object[] c = list.toArray();
        System.out.println(Arrays.toString(c));
    
        int[] ia = {1,2,3};
        int[] ib = {4,5,6};
        int[] ic = new int[ ia.length + ib.length ];
        // use loop to concatenate ia, ib to ic
    
    Slice the array
        public static void sliceArray() {
            // intializing an array arr1
            byte[] arr1 = new byte[] {5, 62, 15};
    
            // printing the array arr1
            System.out.println("Printing 1st array:");
            for (int i = 0; i < arr1.length; i++) {
                System.out.println(arr1[i]);  
            }
    
            // copying array arr1 to arr2 with range from index 1 to 7
            byte[] arr2 = Arrays.copyOfRange(arr1, 1, 7);
    
            // printing the array arr2
            System.out.println("Printing new array:");
            for (int i = 0; i < arr2.length; i++) {
                System.out.println(arr2[i]);
            }
        }
    
    Remove elements in arrays
        public static void removeElement(Integer[] array, int index) {
            int[] tmp = new int[array.length-1];
            System.arraycopy( array, 0, tmp, 0, index);
    
            List<Integer> list = new ArrayList<Integer>(Arrays.asList(array));
            list.add(3);
            list.add(4);
            for (int i = 0; i < list.size(); i++) {
                if (list.get(i).equals(index)) {
                    list.remove(i);
                }
            }
        }
    
    Looping over the array
        for (<type> i : array_of_type) {
        }
        char[] chars = {'t','h','i','s',' ','\u0024'};
        // char to string
        String s = new String(chars);
        // string to char
        char[] chars2 = s.toCharArray();
        for (char c : chars) { System.out.print(c); }
        System.out.println();
    
    Using Java 8 Stream API
        List<String> nums = Stream.of("ONE", "TWO", "THREE", "FOUR")
            .collect(Collectors.toList());
    
    Using Java 8 Collections API
        List<String> places = Collections.unmodifiableList
            (Arrays.asList("One", "Two", "Three"));
    
    Using Java 9 API
        List<String> sary = List.of("One", "Two", "Three");
        List<Integer> iary = List.of(1,2,3);
    
    Using Class for Arrays
    import java.util.*;
    import java.util.Arrays;
    
    public class ary
    {
        public static void main (String[] args) {
            int iary1[] = { 1,2,3,4 };
            int iary2[] = { 5,6,7,8 };
            int iary3[] = Arrays.copyOf (iary2, 10);
            int iary4[] = Arrays.copyOfRange (iary3, 1, 3);
            int iary5[] = { 6,2,7,0,1,3,4 };
    
            System.out.println ("arrays:");
            System.out.println ( Arrays.toString(iary1));
            System.out.println ("compare two array:");
            System.out.println ( Arrays.equals(iary1, iary1));
            System.out.println ( Arrays.equals(iary1, iary4));
    
            System.out.println ("array sort:");
            Arrays.sort(iary5);
            System.out.println ( Arrays.toString(iary5));
    
            int tary1[][] = { { 9,8,7,6,5,4} };
            int tary2[][] = { { 9,6,4 } };
            System.out.println ( "Arrays comparison" );
            System.out.println ( Arrays.deepEquals (tary1, tary2 ));
            // Arrays.compare (iary1, iary2 );
            // Arrays.compareUnsigned (iary1, iary2 );
            // System.out.println ( Arrays.compare (iary1, iary2 ));
    
            ArrayList list = new MyArrayList("a", "b", "c");
        }
    }
    
    public class MyArrayList<T> extends ArrayList<T> {
        public MyArrayList(T... values) {
            super(Arrays.asList(values));
        }
    }
    

    Java Class

    Java Class
    - An object is an instance of a class.
    - Non-primitive variables are references to objects.
    - Objects can have multiple references.
    
    Creation of Instances 
    - A class can have multiple objects created/constructed.
    - A class has only one blueprint.
    - An object can only be created using the key word "new".
    - When "new" is called, the object is instantiated calling the "constructor method".
    - String values are instances of java.lang.String
    
          String str = new String("string");
          String str = "string";
    
    Static vs Dynamic * Instance variables vs Class variables - Instance variable is a member of an instance/objects, not a member of the class * Instance methods vs Class methods
    Java Strings are immutable, meaning?
    That means that once you instantiate and assign their values, you can't really change them.
    Java compiler will make it look like you can change them.
          String str = "Hello, world!";
          str = "new string";
    it looks like you are changing the object. But in fact, in the background, the Java compiler is de-referencing the original object. That object can now be cleared from memory in a process known as garbage collection, and a brand new object is created with the new value, which is now pointed to by "str". That is, Java reset the value of a String by creating a new object and give that to you.
    Examples
    public class Bicycle {
        // the Bicycle class has
        // three fields
        public int cadence;
        public int gear;
        public int speed;
            
        // the Bicycle class has
        // one constructor
        public Bicycle(int startCadence, int startSpeed, int startGear) {
            gear = startGear;
            cadence = startCadence;
            speed = startSpeed;
        }
            
        // the Bicycle class has
        // four methods
        public void setCadence(int newValue) {
            cadence = newValue;
        }
            
        public void setGear(int newValue) {
            gear = newValue;
        }
            
        public void applyBrake(int decrement) {
            speed -= decrement;
        }
            
        public void speedUp(int increment) {
            speed += increment;
        }
    }
    
    public class MountainBike extends Bicycle {
     // the MountainBike subclass has
        // one field
        public int seatHeight;
    
        // the MountainBike subclass has
        // one constructor
        public MountainBike(int startHeight, int startCadence,
                            int startSpeed, int startGear) {
            super(startCadence, startSpeed, startGear);
            seatHeight = startHeight;
        }   
            
        // the MountainBike subclass has
        // one method
        public void setHeight(int newValue) {
            seatHeight = newValue;
        }
    }
    
    import java.io.*;
    import java.util.*;
    
    class gift1 {
    
        public static void main(String[] args) throws IOException {
            BufferedReader f = new BufferedReader(new FileReader("gift1.in"));
            PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter("gift1.out")));
            StringTokenizer st = new StringTokenizer(f.readLine());
    
            int n = Integer.parseInt(st.nextToken());
            Map<String, List<String>> giveto = new HashMap giftmoney = new HashMap<String, Gift>();
    
            String[] groups = new String[n];
            for (int i = 0; i < n; i++) {
                groups[i] = f.readLine();
                System.out.println(groups[i]);
            }
            for (int i = 0; i < n; i++) {
                String s = f.readLine();
                List<String> friends = new ArrayList<String>();
    
                st = new StringTokenizer(f.readLine());
                int totalgiftmoney = Integer.parseInt(st.nextToken());
                int givetoNum = Integer.parseInt(st.nextToken());
                for (int j = 0; j < givetoNum; j++ ) {
                    String friend = f.readLine();
                    friends.add( friend );
                }
                Gift g = new Gift(totalgiftmoney, givetoNum);
                giveto.put(s, friends);
                giftmoney.put(s, g);
                for ( Map.Entry<String,Gift> m : giftmoney.entrySet() ) {
                    System.out.println(m.getKey());
                    System.out.println(m.getValue().total);
                }
            }
            f.close();
            out.close();
        }
    
    }
    
    class Gift
    {
        public int total = 0;
        public int toNum = 0;
        public void Gift () {
        }
    
        public Gift (int total, int num) {
            this.total = total;
            this.toNum = num;
        }
    }
    
    Java Class Operators
    // instanceof // Class membership
    String s = "string";
    System.out.println( s instanceof java.lang.String );
    
    // Strings cannot be compared using ==
    // Strings should use the String.equals to compare
    
    if (s1.equals(s2)) { System.out.println ("equal"); }
    else               { System.out.println ("different"); }
    

    Monday, February 11, 2019

    Java Homeworks #2

    Homework 2-1: Variations from Homework 1-1
    Read one data and convert to another format.
    
    // Practice I/O
    Read from command line.
    Read from user input.
    Read from file.
    
    // Practice loops
    Read multiple input data set until quit.
    
    // Practice conditionals
    Output different phrases depending on the temperatures.
    
    // Practice handling run time errors.
    Using Exceptions.
    Using conditionals.
    
    // Practice date time printing
    // Practice using <string>
    
    Homework 2-2: Big O
    Calculate the minimum n that will make 2 to the power of n greater than 100 * n squared.
               For some n, 2n > 100 * n 2
    Calculate the minimum n that will make n squared greater than 1000 * (n log n)
    
    Homework 2-3: Calculate this.
    6/22
    111 % 8
    55 / 2.25
    33 + 4 % 5
    77 * 9 % 8
    77 % 9 * 8
    77 % 8 * 9
    x = -55 * i++ - 7 % 8;
    
    // logical
    // Take a input integer and output result of the following logical expressions
    x < 20 && x >= -3
    !x && x >= 33
    x >= 33 && !x
    x++ == 5 || x == 9
    

    C++ Data Structure

    Data Type Limits (limits.h)
    #include <climits>
    
    int main()
    {
        printf ( "char_min %d, char_max %d, int_min %d, int_max %d\n", 
            CHAR_MIN, CHAR_MAX, INT_MIN, INT_MAX );
    }
    
    C++ Arrays
    #include <cstdio>
    #include <iostream>
    
    using namespace std;
    
    int main()
    {
        int * ia = new int[5];
        int ib[5];
        int *ip = ib;
        ib[0] = 1;
        *ib = 1;
        *ip = 2;
        ++ip;
        *ip = 3;
        *(++ip) = 4;
        int ic [] = { 1,2,3,4,5 };
        int id [5] = { 1,2,3,4,5 };
    
        // cstring, a primitive string
        char s0[] = "string";
        char s[] = { 's', 't', 'r', 'i', 'n', 'g', 0 };
        for (int i = 0; s[i] != 0; ++i ) {
            printf ( "%c ", s[i] );
        }
        cout << endl;
        for (char * cp = s; *cp; ++cp ) {
            printf ( "%c ", *cp );
        }
        cout << endl;
        // range based loop
        for (char c : s ) {
            printf ( "%c ", c );
        }
        cout << endl;
    }
    
    C++ Containers
    Sequence containers:
    - array                              - Fixed size, Direct access to any element.
    - deque                            - Rapid insertions and deletions at front or back.
    - forward_list                 - Singly linked list, rapid insertion and deletion anywhere. New in C++11
    - list                                  - Doubly linked list, rapid insertion and deletion anywhere.
    - vector<T>                     - Rapid insertions and deletions at back. Direct access.
    
    Ordered associative containers - keys are maintained in sorted order.
    - set                                  - Rapid lookup, no duplicates allowed.
    - multiset                         - Rapid lookup, duplicates allowed.
    - map                                - one-to-one mapping, no duplicates allowed. Rapid key-based lookup.
    - multimap                      - one-to-one mapping, duplicates allowed. Rapid key-based lookup.
    
    Un-ordered associative containers
    - unordered_set              - Rapid lookup, no duplicates allowed.
    - unordered_multiset     - Rapid lookup, duplicates allowed.
    - unordered_map            - one-to-one mapping, no duplicates allowed. Rapid key-based lookup.
    - unordered_multimap   - one-to-one mapping, no duplicates allowed. Rapid key-based lookup.
    
    Container adapters
    - stack                                - Last-in first-out (LIFO)
    - queue                              - First-in first-out (FIFO)
    - priority_queue              - Highest-priority element is always the first element out
    
    Sorting
    # Example
    
    
    Searching
    # Example
    
    List
    # Example
    
    
    Stack
    # Example
    
    Queue
    # Example
    
    Map
    # Example
    
    Set
    # Example
    
    Tree
    # Example
    
    
    Graph
    # Example
    

    Java Functions

    Primitives
    public class method {
        static String[] days = {"Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat" };
    
        public static void main(String[] args) {
            func1();
            func1( "John" );
            func1( 3 );
        }   
            
        static void func1() {
            System.out.println("Howdy!");
        }   
            
        static void func1( String label ) { 
            System.out.printf("Hello %s!\n" , label); 
        }   
    
        static void func1( int x ) { 
            for (int i = 0; i < x; i++) {
                System.out.println("i = " + i);
            }       
        }   
    }
    

    Java Loops

    Java Loops
    public class loop {
    
        public static void main(String[] args) {
            int m = 3;
            for (int i = 0; i < m; i++) {
                System.out.println("i = " + i);
            }
    
            String[] days = {"Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat" };
            for (String s : days) { 
                System.out.println(s);
            }
    
            for (int i = 0; i < days.length-1; i++) {
                System.out.println("for loop: " + days[i]); 
            }
    
            while (m > -1) { 
                System.out.println("while loop: " + days[m]); 
                m--;
            }
    
            m++;
            do {
                System.out.println("do while loop: " + days[m]); 
                m++;
            } while (m < days.length -1 );
    
        }
    
    }
    
    

    Java Conditionals

    Primitives
    import java.util.Scanner;
    
    public class Cond {
        public static void main(String[] args) {
            int m = 8;
            if (m > 0 && m < 4) {
                System.out.println("You are between 1 to 3.");
            } else if (m > 3 && m < 7) {
                System.out.println("You are between 4 to 6.");
            } else if (m > 6 && m < 10) {
                System.out.println("You are less than 10.");
            } else {
                System.out.println("You are bigger than 9 or less than 0.");
            }
    
            switch (m) {
                case 1:
                case 3:
                    System.out.println("M is odd and less than 4.");
                    break;
                case 2:
                case 4:
                    System.out.println("m is even number: " + m);
                    break;
                default:
                    System.out.println("m equals " + m);
            }
    
            Scanner sc = new Scanner(System.in);
            System.out.print("Please enter a day in the week: ");
            String s = sc.nextLine();
            // only works after Java 7
            switch (s) {
                case "0":
                    System.out.println("Sunday"); break;
                case "1":
                    System.out.println("Monday"); break;
                case "2":
                    System.out.println("Tuesday"); break;
                case "3":
                    System.out.println("Wednesday"); break;
                case "4":
                    System.out.println("Thursday"); break;
                case "5":
                    System.out.println("Friday"); break;
                case "6":
                    System.out.println("Saturday"); break;
            }
        }
    }
    

    Friday, February 8, 2019

    ASCII code vs Unicode

    ASCII Code
    ASCII defines 128 characters with 7-bits, because the center of the computer industry was in the USA at that time and 7 bits was originally sufficient for the binary representation of English language.
    ASCII Extended
    Some people extend the 7-bit ASCII code to 8-bit in order to encode more characters to support their language, such as French.
    The name for this are often referred to as "extended ASCII" or "8-bit ASCII".
    Unicode on the rise
    ASCII Extended solves the problem for Latin alphabetical based languages but what about the others that need a completely different set of alphabets, such as Greek, Russian, Arabic, Chinese or Japanese?

    Unicode is a superset of ASCII.
    Unicode defines up to 221 characters

    UTF Varieties Explained
    Unicode encoding: UTF-8 vs UTF-16 vs UTF-32
    UTF-8 and UTF-16 are variable length encodings.

    In UTF-8, a character may occupy a minimum of 8 bits.
    In UTF-16, a character length starts with 16 bits.
    UTF-32 is a fixed length encoding of 32 bits.

    UTF-8 uses the ASCII set for the first 128 characters. That's handy because it means ASCII text is also valid in UTF-8.

    Mnemonics:
    UTF-8: minimum 8 bits.
    UTF-16: minimum 16 bits.
    UTF-32: minimum and maximum 32 bits.
    Java Supports Unicode
    Java Char provides support for Unicode with 2 bytes size, ranging from 0 to 65535.
    More...
    ASCII and Unicode are two character encoding standards on how to represent characters in binary code.
    The main difference between the two is how they encode the character and the number of bits that they use for each. 
    
    ASCII originally used seven bits to encode each character. This was later increased to eight with Extended ASCII to address the apparent inadequacy of the original to encode languages other than English. 
    
    In contrast, Unicode can choose between 32, 16, and 8-bit encodings. Using more bits lets you use more characters at the expense of larger files while fewer bits give you a limited choice but you save a lot of space. Using fewer bits (i.e. UTF-8 or ASCII) would probably be best if you are encoding a large document in English.
    
    Unicode solves the main problem arose from the many non-standard extended ASCII programs. Unless you are using the prevalent page, which is used by Microsoft and most other software companies, then you are likely to encounter problems with your characters appearing as boxes. Unicode eliminates this problem as all the character code points were standardized.
    
    Another major advantage of Unicode is that at its maximum it can accommodate a huge number of characters. Because of this, Unicode currently contains most written languages and still has room for even more. This includes typical left-to-right scripts like English and even right-to-left scripts like Arabic. Chinese, Japanese, and the many other variants are also represented within Unicode.
    
    In order to maintain compatibility with the older ASCII, which was already in widespread use at the time, Unicode was designed in such a way that the first eight bits matched that of the most popular ASCII page. If you open an ASCII encoded file with Unicode, you still get the correct characters encoded in the file. This facilitated the adoption of Unicode as it lessened the impact of adopting a new encoding standard for those who were already using ASCII.
    
    Summary:
    1.ASCII uses an 8-bit encoding while Unicode uses a variable bit encoding.
    2.Unicode is standardized while ASCII isn’t.
    3.Unicode represents most written languages in the world while ASCII does not.
    4.ASCII has its equivalent within Unicode.
    
    Taken from here
    

    C++ Exercise #1

    Exercise 1-1
    Write a program that take inputs from command line and create a todo list.
    
    Exercise 1-2
    Take names from command line and create a list. Print out the sorted list.
    Exercise 1-3
    Take a list of students name and their score. Print the top 5 scores and their names.
    Exercise 1-4
    Take a list of pairs of numbers, which indicate pairs of nodes that is connected. Provide two functions:
    1. Output the connected clusters.
    2. Return true or false if two nodes are connected.
    Exercise 1-5 What does this print out?
    #include <cstdlib>                  // Prototypes of srand() and rand()
    #include <ctime>                    // Prototype of time()
    #include <iostream>
    using namespace std;
    int main()
    {
        int number, attempt;
        char wb = 'r';                  // Repeat or finish.
        long sec;
        time( &sec);                    // Get the time in seconds.
        srand((unsigned)sec);           // Seeds the random
                                        // number generator
        cout << "\n\n "
             << " ******* A NUMERICAL GAME *******" << endl;
        cout << "\n\nRules of the game:" << endl;
        while( wb == 'r')
        {
            cout << "I have a number between 1 and 15 in mind \n"
                 << "You have three chances to guess correctly!\n"
                 << endl;
            number = (rand() % 15) + 1;
            bool found = false; int count = 0;
            while( !found && count < 3 )
            {
                cin.sync();             // Clear input buffer
                cin.clear();
                cout << ++count << ". attempt: ";
                cin >> attempt;
                if(attempt < number) cout << "too small!"<< endl;
                else if(attempt > number) cout <<"too big!"<< endl;
                else found = true;
            }
            if( !found) {
                cout << "\nI won!"
                     << " The number in question was: "
                     << number << endl;
            } else {
                cout << "\nCongratulations! You won!" << endl;
            }
            cout << "Repeat —> <r> Finish —> <f>\n";
            do {
                cin.get(wb);
            }
            while( wb != 'r' && wb != 'f');
        }
        return 0;
    }
    Exercise 1-6
    1. Write a program that take inputs from command line and create a todo list.
    2. Take names from command line and create a list. Print out the sorted list.
    3. Take a list of numbers from input and search if a certain number is there.
             Try different ways and analyze run time.
    4. Take two n digit numbers and use an algorithm better than brute-force to multiply.
    5. Implement Karatsuba algorithm for integer multiplication
    6. Build a binary tree
    7. Take a list of pairs of indices and build a network from them. Then given any input number, search if it is in the network
    8. From above network, given any two numbers, return True if they are connected, otherwise return False.
    9. From above network, return the shortest path
    Exercise 1-7
    1. Build a graph
    2. Search a graph to see if two nodes are connected
    3. Take "car" and return how many possible way to convert it to "let", one letter at a time.
    4. Take a list of students name and their score. Print the top 5 scores and their names.

    C++ Operators

    Operator Precedence and Associativity
    C++ Operator Precendence
    
    Operators for Fundamental Types

    Arithmetic Operators
    +
    -
    *
    /
    %
    
    // Not all operators can be perform on binary numbers
    // Divisions performed with integral operands will produce integral results.
    // Remainder division or Modulus applies only to integral operands
    
    Unary Arithmetic Operators
    // Sign Operators
    +
    -
    // Increment / Decrement Operators
    ++
    --
    
    i++
    ++i
    j--
    --j
    
    Logical Operators
    &
    |
    !
    &&
    ||
    
    Relational Operators
    <
    <=
    >
    >=
    ==
    !=
    

    Java Homeworks #1

    Homework 1-1 Conditionals
    1. Convert Gallons to Liters
    2. Convert temperature from Fahrenheit to Celsius
    3. Convert number to names
    4. Create a help menu providing phone numbers for agents, institutions.
    5. Read from command line, or user input, or from file
    6. Process multiple input data set until user quit.
    7. Output different phrases or greetings depends on the input data.
    8. Handle user input errors using exceptions or conditionals.
    Homework 1-2 Lists, Loops, Files
    1. Write a program that will print A to F vertically on each new line.
    2. Create an array or list of numbers and calculate all.
    3. Make it interactive and take inputs from users until 'q' or 'Q' is presssed.
    4. Take inputs from file and print output to a file.
    Homework 1-3 Numbers and Type Conversions
    1. Compute the circumference area of a circle given the radius.
    2. Take two numbers and calculate their GCD.
    3. Take two numbers and output the max / min / mean / sum of both.
    4. Convert Coins to currency amount
    Fix it!
    class FirstFix
    {
        System.out.print( "If this text" );
        System.out.println "is what you see on your screen, ";
        print( "Then your program is working" );
    )
    

    Thursday, February 7, 2019

    C++ Initialization

    Primitives
        constexpr size_t byte = 8;
        const double pi = 3.14159;
    
        char c = 'a';
        float f(1.875);
        int x[5] = { 1,2,3,4,5 };
        char s[] = "this is a string";
    
        short int sh = c;
        long int  li = 0L;
        long long int lli = 0LL;
    
        double area, circuit, radius = 1.5;
    

    C++ Qualifiers and Macros

    type qualifier: const vs volatile
    There are two types of qualifiers, const or volatile, then there is mutable.
    Type qualifier is also known as CV qualifier, where CV stands for constant and volatile.
    Type qualifiers express additional information (quality) about a value through the type system.

    const
    const marks a variable as read-only or immutable. Its value cannot be changed once it's been defined.

    volatile
    volatile marks a variable that may be changed by another process. This is generally used for threaded code.
    The keyword volatile, which is rarely used, creates variables that can be modified not only by the program
    but also by other programs and external events. Events can be initiated by interrupts or by a hardware clock.

    mutable
    And mutable is used on a data member to make it writable from a const qualified member function.
    Examples
      // const
      // volatile
      // mutable
      
      // qualified type : constant integer
      const int cint = 0;
      
      // unqualified type : simply an integer
      int unqualified_int = 0;
      
      // mutable with lambda
      int accum = 9;
      auto x = [accum](int d) mutable -> int { return accum += d; };
      vector v1 = { 1,2,3,4,5 };
      vector v2 (v2.size());
      transform (v1.begin(), v1.end(), v2.begin(), x);
      
      Storage Duration
      static
      register
      extern
      
      Modifiers
      signed
      unsigned
      
      Operator
      sizeof(type) // byte size of data type
      
      Integer Constants
      printf ( "binary %u, decimal %d, %d, octal %o, hex %x\n", 
                0b10000, 0b10000, 16, 020, 0x10 );
      
      //------------------------------------------------------------------------------
      // Decimal      Octal           Hexadecimal             Type
      //------------------------------------------------------------------------------
      // 16           020             0x10                    int
      // 255          0377            0Xff                    int
      // 32768U       0100000U        0x8000U                 uint
      // 10L          012L            0xaL                    long
      // 27UL         033UL           0x1bUL                  unsigned long
      //
      // Binary: 0b110 (decimal 6)
      //------------------------------------------------------------------------------
      
      
      Floating-point Constants
      5.19            0.519E1         0.0519e2        519.OE-2
      12.             12.0            .12E+2          12e0
      0.75            .75             7.5e-1          75E-2
      0.00004         0.4e-4          .4E-4           4E-5
      
      Character Constants
      //------------------------------------------------------------------------------
      // Constant             Character               Constant Value (ASCII code)
      //------------------------------------------------------------------------------
      'A'                     A                               65
      'a'                     a                               97
      ' '                     blank                           32
      '.'                     dot                             46
      '0'                     digit 0                         48
      '\0'                    terminating null character      0
      //------------------------------------------------------------------------------
      
      // String "0" comprises two bytes, 
      // first byte contains the code for the character zero '0' (ASCII code 48)
      // second byte contains the value 0 ('\0')
      
      //------------------------------------------------------------------------------
      // Special Characters:
      \a      alert (BEL)                     7
      \b      backspace (BS)                  8
      \t      horizontal tab (HT)             9
      \n      line feed (LF)                  10
      \v      vertical tab (VT)               11
      \f      form feed (FF)                  12
      \r      carriage return (CR)            13
      \"      " (double quote)                34
      \'      ' (single quote)                39
      \?      ? (question mark)               63
      \\      \ (backslash)                   92
      \0      string terminating character    0
      //------------------------------------------------------------------------------
      \ooo (up to 3 octal digits)  numerical value of a character    ooo (octal)
      \xhh (hex digits)            numerical value of a character    hh (hex)
      //------------------------------------------------------------------------------
      
      
      MACROS
      #define CLEARSCREEN  ( cout << "\033[2J" )
      #define LOCATE(x,y)  ( cout << "\033[" << x << ';' << y << 'H' )
                           // LOCATE will position cursor in row x column y
      #define SQUARE(x)    ( (x)*(x) )
      
      #define PI           3.14159
      #define UPPERBOUND   10
      #define LOWERBOUND   (-3)
      #define PRINTHDR     ( cout << \
                             " ***** REPORT *****\n\n" )
      
      int main()
      {
          PRINTHDR;
      }
      
      #define MIN(x,y)     ( (x)<(y)? (x) : (y))
      // ... use MIN 
      #undef MIN
      // cannot use MIN any more
      
      #ifdef _NAME_
      #endif
      #ifndef _NAME_
      #endif
      
      #ifndef _FILE_NAME_H_
      #define _FILE_NAME_H_
      #endif
      

      C++ Homeworks #2

      Homework 2-1: Variations from Homework 1-1
      Read one data and convert to another format.
      
      // Practice I/O
      Read from command line.
      Read from user input.
      Read from file.
      
      // Practice loops
      Read multiple input data set until quit.
      
      // Practice conditionals
      Output different phrases depending on the temperatures.
      
      // Practice handling run time errors.
      Using Exceptions.
      Using conditionals.
      
      // Practice date time printing
      // Practice using <string>
      
      Homework 2-2: Big O
      Calculate the minimum n that will make 
           2 to the power of n become greater than 100 * n squared.
                 For some n, 2n > 100 * n 2
      Calculate the minimum n that will make n squared greater than 1000 * (n log n)
      
      Homework 2-3: Calculate this.
      6/22
      111 % 8
      55 / 2.25
      33 + 4 % 5
      77 * 9 % 8
      77 % 9 * 8
      77 % 8 * 9
      x = -55 * i++ - 7 % 8;
      
      // logical
      // Take a input integer and output result of the following logical expressions
      x < 20 && x >= -3
      !x && x >= 33
      x >= 33 && !x
      x++ == 5 || x == 9
      
      Homework 2-4: Random numbers
      #include <stdlib.h>                   // Prototypes of srand() and rand()
      #include <iostream>
      #include <iomanip>                    // using setw(n) for cout
      
      // Print "Please enter a number between 0 and n"
      // cin >> seed;                       // use the number as seed
      // srand ( seed )                     // seeds the random number generator
      // x = rand() % n + 1                 // generate the random number
      // Print out the random number
            
      

      C++ Homeworks #1

      Homework 1-1: Conditionals
      1. Take 2 numbers and print a multiplication table
      2. Convert Gallons to Liters
      3. Convert temperature from Fahrenheit to Celsius
      4. Convert number to names
      5. Create a help menu providing phone numbers for agents, institutions.
      Homework 1-2: Lists, Loops, Files
      1. Write a program that will print A to F vertically on each new line.
      2. Create an array or list of numbers and calculate all.
      3. Make it interactive and take inputs from users until 'q' or 'Q' is presssed.
      4. Take inputs from file and print output to a file.
      Homework 1-3: Numbers and Type Conversions
      1. Compute the circumference area of a circle given the radius.
      2. Take two numbers and calculate their GCD.
      3. Take two numbers and output the max / min / mean / sum of both.
      4. Convert Coins to currency amount
      Homework 1-4: Fix it!
      #include <stream>
      int main
      {
          cout << "If this text",
          cout >> " appears on your display, ";
          cout << " endl;"
          cout << 'you can pat yourself on '
          << " the back!" << endl.
          return 0;
      )
      
      Homework 1-5: Which of the followings are valid variable names in C++?
      a
      586_cpu
      a_very_long_name123467890
      b12
      écu
      goto
      invalid
      object-oriented
      SetTextColor
      top_of_window
      true
      US
      us
      US$
      VOID
      _var
      $var 
      
      Homework 1-6: Fix it!
      int a(2.5); 
      const long large;
      int b = '?'; 
      char c('\'');
      char z(333); 
      unsigned char ch = '\201';
      int big = 50000; 
      unsigned size(80000);
      double he's(1.7E+5); 
      float val = 54321.12345;
      
      Homework 1-7: Use sizeof operator to show the number of bits occupied in memory by a variable
      Write a c++ program that displays the memory space required by each data type.
      

      Wednesday, February 6, 2019

      C++ Variables, Conditionals, Loops, Functions, just a feel.

      Are you local? Or global? private or public?
          // Struct members are default public
          struct x {
              int a;
              float b;
              char c[10];
          };
          // class members are default private
          class z {
              int a;
              float b;
              char c[10];
            public:
              int getvalue() const;
              void setvalue( int v );
          };
      
      Conditionals
      #include <iostream>
      #include <cstdio>
      #include <cstdint>
      
      int main()
      {
          const int ZERO = 0;
          const int ONE = 1;
          const int TWO = 2;
          const int THREE = 3;
      
          int x = 42;
          int y = 73;
          if ( x < y ) {
          } else if ( y > x ) {
          } else {
          }
      
          // ternary
          printf ("This number is greater : %d\n", x > y ? x : y );
      
          switch (x) {
              case ZERO: cout << ZERO << endl; break;
              case ONE: cout << ONE << endl; break;
              case TWO: cout << TWO << endl; break;
              case THREE: cout << THREE << endl; break;
              case 42: cout << 42 << endl; break;
              case 52: cout << 52 << endl; break;
              default: cout << 99 << endl; break;
          }
      }
      
      Loops
      #include <iostream>
      #include <cstdio>
      
      int main() {
          int array[] = { 1,2,3,4,5 };
          char string[] = "string";
      
          auto j = 3;
          for( auto i : array ) {
              printf( "i is %d\n", i );
          }
      
          // c++ range based loop
          // range based loop is a compile time feature so compiler knows the size and type
          for ( int i : array ) {
              printf( "* %d / ", i );
          }
          printf( "\n" );
          // for ( char c : "abcdef" ) { // this works too!!
          // for ( char i : string ) { // this works too!!
          for ( int i : string ) { // int works with char too!!
              printf( "* %c / ", i );
          }
          printf( "\n" );
      
          // for ( int i = 0; string[i]; i++ ) { // last char in a string is '0', == false 
          for ( char *cp = string; *cp ; ++cp ) {
              printf( "* %c / ", *cp );
          }
          cout << endl;
      
          for (int i = 0; i < j; i++) {
          }
      
          int i = 0;
          while (i < 5) {
              if ( i == 2 ) {
                  i++; // important!!
                  continue;
              } else if ( i == 3 ) {
                  break;
              }
              i++;
          }
      
          do {
              i--;
          } while ( i > 0 );
      }
      
      Functions
      #include <cstdio>
      #include <iostream>
      #include <string>
      using namespace std;
      using std::cin;
      using std::cout;
      
      void func( const string * fs )
      {
              printf( "value is %s\n", fs->c_str());
      }
      
      int main( int argc, char * argv[] )
      {
              string s = "hello im a string";
              puts( "this is main()" );
              func(&s);
              printf( "string is %s\n", s.c_str());
              for (int i=0; argv[i]; i++ ) {
                      printf( argv[i] );
                      printf( "%d: %s\n", i, argv[i] );
              }
              return 0;
      }
      
      Using namespace or else
      #include <cstdio>
      #include <iostream>
      #include <string>
      using namespace std;
      
      // Another way
      #include <cstdio>
      using std::puts;
      using std::printf;
      #include <iostream>
      using std::cin;
      using std::cout;
      

      C++ literals!

      Numbers, Strings, and Boolean
      #include <iostream>
      #include <cstdio>
      #include <cstdint>
      
      int main()
      {
          constexpr size_t byte = 8;
      
          bool b;
          int i = 5;
          float f;
          int x[5] = { 1,2,3,4,5 };
          char s[] = "this is a string";
      
          short int sh;
          long int  li = 0L;
          long long int lli = 0LL;
      
          // integer types
          char iic;                   // 8-bit
          short int iis;              // 16-bit
          int iii;                    // 32-bit
          long int iil;               // 32-bit or 64-bit
          long long int iill;         // double size of long int
          cout << "char size "  << sizeof(char) << endl;
          cout << "short ing size " << sizeof(short int) << endl;
          cout << "int size "   << sizeof(int) << endl;
          cout << "long int size " << sizeof(long int) << endl;
          cout << "long long int size " << sizeof(long long int) << endl;
          cout << sizeof(iic) * byte << endl;
          cout << sizeof(iis) * byte << endl;
          cout << sizeof(iii) * byte << endl;
          cout << sizeof(iil) * byte << endl;
          cout << sizeof(iill) * byte << endl;
      
          unsigned char uic;                  // 8-bit
          unsigned short int uis;             // 16-bit
          unsigned int uii;                   // 32-bit
          // long int can be 32 bit(pc) or 64 bit(mac) depends on compiler library.
          // they are guaranteed to be in relationship to each other 
          // but not guaranteed to be particular sizes
          unsigned long int uil;              // 32-bit or 64-bit
          unsigned long long int uill;        // double size of long int
      
          uint8_t  iax;                       // unsigned
          int16_t  iay;                       // signed
          uint32_t iaz;                       // unsigned
          int64_t  iap;                       // signed
          uint64_t iaq;                       // unsigned
      
          wchar_t wct;                        // 4 byte, wide character type
          size_t  szt;                        // 8 byte
      
          float ff;
          double df;
          long double ldf;
          cout << "sizeof float " << sizeof(ff) << endl;
          cout << "sizeof double " << sizeof(df) << endl;
          cout << "sizeof long double " << sizeof(ldf) << endl;
      
          printf ( "print .3 equal .1+.1+.1 %s\n", 
              ( .3 == .1+.1+.1 )? "true" : "false" );
      }
      
      Of course strong typed!
      #include <cstdio>
      #include <iostream>
      using namespace std;
      
      int main(void)
      {
          int ia[] = { 1,2,3,4,5 };
          int x , y , z = 0;
          auto j = 3;
          for( auto i : ia ) {
              printf( "i is %d\n", i );
          }
          string str = "C++ Language";
          const char *cstr = str.c_str();
          printf ("Hello %s\n", cstr);
          cout << "Hello" << str << endl;
      
          char mystr[] = " more and more";
          printf( "hello " " \u03bc" " xxx %s" "\x40" "\n", mystr ); // \x40 is @ sign
      
      }
      
      Pointers and References
          // references, it is an alias
          int ix = 42;
          int & yx = ix;
      
          // pointer
          int * ipx = &i;
          printf ("value is %d\n", *ipx );
      
      Struct and Union
          struct x {
              int a;
              float b;
              char c[10];
          };
      
      // A union is a set of overlapping objects. This allows a single compound object 
      // to hold objects of different types at different times 
      // overlapping the same memory space.
      
          union y {
              int a;
              float b;
              char c[10];
          };
      
      Compiler Switches
      % c++ -Wall -std=c++11 -std=c++14 -std=c++17 <file.cpp>
      
      # For CodeLite
      # Right click the project name
      # Go to the bottom and select [Settings...]
      # Select C++ Compiler Options 
      #      and on the far right, [...] will show up
      # Click [...] on the right and add options for 
      #      -std=c++11, -std=c++14, -std=c++17
      

      First C++ Program!

      Hello C!
      #include "stdio.h"
      
      int main (int argc, char ** argv) {
          char cstr[] = "C Language";
          printf ("Hello World from %s! \n", cstr );
          return 0;
      }
      
      Hello C++!
      #include <cstdio>
      #include <iostream>
      using namespace std;
      
      void pr_line(), pr_message(); // prototypes
      
      int main()
      {
          printf ("Hello World\n");
      
          string str = "C++ Language";
          const char *cstr = str.c_str();
          printf ("Hello %s\n", cstr);
          cout << "Hello" << str << endl;
      
          int ia[] = { 1,2,3,4,5 };
          int x , y , z = 0;
          int numbers[10];
          cout << sizeof(numbers) << endl;
          cout << sizeof(*numbers) << endl;
          cout << sizeof(numbers[0]) << endl;
          return 0;
      }
      
      C/C++ comments
      // this is comments
      /* this is comments for multiple lines
      */
      
      C++ IO
      #include <iostream>
      #include <fstream>
      using namespace std;
      
      int main(void)
      {
          ifstream fin ("my.in");
          ofstream fout ("my.out");
          int n;
          fin >> n;
          auto b = new int[n];
          for (int = 1; i < n; i++) {
              fin >> b[2*i];
              fin >> b[2*i+1];
          }
      
          // 2D array
          auto ary = new int*[n];
          for ( int i=0; i < n; i++) {
              ary[i] = new int[2];
              for (int j=0; j < 2; j++) {
                  fin2 >> ary[i][j];
                  cout << ary[i][j] << endl;
              }
          }
      
      }
      
      # my.in
      # 2
      # 1 2
      # 3 4
      
      STL
      #include <vector>
      #include <algorithm>
      #include <fstream>
      #include <iostream>
      #include <map>
      #include <vector>
      

      Be Pythonic!

      import this

      The Zen of Python, by Tim Peters
      
      Beautiful is better than ugly.
      Explicit is better than implicit.
      Simple is better than complex.
      Complex is better than complicated.
      Flat is better than nested.
      Sparse is better than dense.
      Readability counts.
      Special cases aren't special enough to break the rules.
      Although practicality beats purity.
      Errors should never pass silently.
      Unless explicitly silenced.
      In the face of ambiguity, refuse the temptation to guess.
      There should be one-- and preferably only one --obvious way to do it.
      Although that way may not be obvious at first unless you're Dutch.
      Now is better than never.
      Although never is often better than *right* now.
      If the implementation is hard to explain, it's a bad idea.
      If the implementation is easy to explain, it may be a good idea.
      Namespaces are one honking great idea -- let's do more of those!
      
      
      EIBTI
      Don't Abuse Generators! - Mark Lutz, "Learning Python", Chapter 20
      

      Linux Shell Jumpstart!

      Linux Introduction
      • Originally released by Linus Torvalds in 1991
      • UNIX -> MINIX -> LINUX
      • Free open source under GNU General Public License
      • Many tools from the GNU Project come packaged with Linux.
          This is often referred to as "GNU-Linux".
      • Distro: (meaning distributions)
          specific group of software and conventions.
      • Major distributions (distros): Arch, Debian, Red Hat, Slackware
      • Linux Mint, Ubuntu, kali, are derived from Debian
      • CentOS, Fedora, are derived from Red Hat
      • Bash shell is available on most distros and OSes.
      • Be aware of what system you're using and
          adapt to account for differences in distributions.
        • How to setup
          • Cygwin
          • Windows 10 has subsystem for Linux,
              which provides a bash shell environment.
              It runs within Windows instead of in a VM.
          • Using a Virtual Machine
          • macOS is derived from BSD/UNIX, not from Linux
            • macOS has similar but not the same tool chains.
            • macOS includes the Bash shell.
            • Go to applications and open up a terminal. There you go.
            • Using a Cloud Provider
              • Azure, AWS, GCP, DigitalOcean, Linode and more.
              • Ubuntu/Debian available instance for low tier.
              • Record the provided username and password/key for security login
                  and SSH connection.
              • connect: ssh username@11.22.33.44
              • Early Windows system may not have SSH,
                  download PuTTY to connect to the cloud server using SSH.
                  PuTTY.org
                • Download files from GitHub
                  # open property by clocking top left logo, to select font size
                  #
                  # To run a command as administrator (uer "root"), use "sudo ".
                  % man sudo_root
                  # ctrl+shift+[+] # to enlarge
                  % sudo apt install git ## to use git
                  % git clone git://github.com/path/to/files
                  
                  Command-Line basics
                  • CLI: command line interface
                  • CLI sends typed commands to OS
                  • CLI display text output
                  • The environment we use is called "shell" or "interpreter.
                  • Early Thompson shell for UNIX in 1971
                  • Bash: Bourne-again shell
                  • General command Syntax:
                      % Command Options Arguments
                  • % ls -aFl /mnt/c/Users/username/Desktop
                    % grep "findthis" file.in
                    
                    General Commands
                    % cd
                    % pwd
                    % man cd
                    % which ls
                    % find . -name "*in"
                    % grep pattern file.txt
                    % sort -u file.txt
                    % echo text
                    % export PATH=.:$PATH
                    % man nano
                    % which nedit
                    % which kate
                    
                    login shell and profile
                    When bash is invoked as an interactive login shell, or as a non-interactive shell with the --login option, it first reads and executes commands from the file /etc/profile, if that file exists. After reading that file, it looks for ~/.bash_profile, ~/.bash_login, and ~/.profile, in that order, and reads and executes commands from the first one that exists and is readable. The --noprofile option may be used when the shell is started to inhibit this behavior. When an interactive shell that is not a login shell is started, bash reads and executes commands from /etc/bash.bashrc and ~/.bashrc, if these files exist. This may be inhibited by using the --norc option. The --rcfile file option will force bash to read and execute commands from file instead of /etc/bash.bashrc and ~/.bashrc. In general .profile - for things not related to Bash, like environment variables PATH .bashrc - for configuring the interactive Bash usage like aliases, editor and prompt
                    % export VISUAL=vim
                    % export EDITOR="$VISUAL"
                    % export PS1="\u@\h\\$ "
                    % export PS1="[\w] \!> "
                    % export PS1="\u@\[\e[31m\]\h\[\e[m\] "
                    
                    .bash_profile - for make sure .profile and .bashrc are loaded for login shells - If .bash_profile is omitted, only .profile would be loaded.
                    % . ~/.profile
                    % . ~/.bashrc