Showing posts with label cse. Show all posts
Showing posts with label cse. Show all posts

Project 2 || Wong Edition || C++ Project || B.Tech Diaries

Project #2 - Sudoku (in conjunction with Algorithm project)

Implement the Sudoku game and the backtracking algorithm using functions from the STL's: <stack>, <pair>.

Solution:


#include <iostream>
#include <fstream>
#include <vector>
#include <stack>

const int N = 9, EMPTY = 0;

class Sudoku
{
private:
    std::vector<std::vector<int>> table;

public:
    Sudoku(std::string filename)
    {
        table.resize(N);
        for (int i = 0; i < N; i++)
        {
            table[i].resize(N);
        }
        get_pattern(filename);
    }

    ~Sudoku() {}

    void get_pattern(std::string filename)
    {
        std::ifstream infile;
        char n;
        int c = 0;
        infile.open(filename);
        while (infile >> n)
        {
            table[c / N][c % N] = n - '0';
            c++;
        }
        infile.close();
    }

    bool is_safe(int row, int col, int num)
    {
        int i, j;

        // Check if the number is already present in the row
        for (i = 0; i < N; i++)
            if (table[row][i] == num || table[i][col] == num)
                return false;

        // Check if the number is already present in the box
        int boxRow = row - row % 3;
        int boxCol = col - col % 3;
        for (i = boxRow; i < boxRow + 3; i++)
            for (j = boxCol; j < boxCol + 3; j++)
                if (table[i][j] == num)
                    return false;

        // If we reach here, it is safe to place the number in the given cell
        return true;
    }

    bool solve()
    {
        std::stack<std::pair<int, int>> st;

        // Find the first empty cell in the grid
        int row = -1, col = -1, r, c, num;
        for (r = 0; r < N; r++)
        {
            for (c = 0; c < N; c++)
            {
                if (table[r][c] == EMPTY)
                {
                    row = r, col = c;
                    break;
                }
            }
            if (row != -1)
                break;
        }

        // If there are no more empty cells, we have solved the puzzle
        if (row == -1)
        {
            return true;
        }

        // Push the first empty cell onto the stack
        st.push({row, col});

        while (!st.empty())
        {
            // Get next empty cell
            std::pair<int, int> p = st.top();
            st.pop();
            row = p.first, col = p.second;

            // Try each number from 1 to 9
            for (num = 1; num <= 9; num++)
            {
                if (is_safe(row, col, num))
                {
                    // Fill cell with number and continue solving
                    table[row][col] = num;
                    if (solve())
                        return true;

                    // Backtrack
                    table[row][col] = EMPTY;
                }
            }
            // No number worked, backtrack
            st.push(p);
            return false;
        }
        return true;
    }
    void print()
    {
        int r, c;
        for (r = 0; r < N; r++)
        {
            for (c = 0; c < N; c++)
            {
                std::cout << table[r][c] << " ";
            }
            std::cout << std::endl;
        }
    }
};

int main(int argc, char const *argv[])
{
    Sudoku s("sudoku_pattern/pattern01.txt");
    std::cout<<"Problem: "<<std::endl;
    s.print();

    std::cout<<"Solution: "<<std::endl;
    if (s.solve())
        s.print();
    else
        std::cout << "No solution" << std::endl;

    return 0;
}

Input (sudoku_pattern/pattern01.txt):


0 0 3 0 2 0 6 0 0
9 0 0 3 0 5 0 0 1
0 0 1 8 0 6 4 0 0
0 0 8 1 0 2 9 0 0
7 0 0 0 0 0 0 0 8
0 0 6 7 0 8 2 0 0
0 0 2 6 0 9 5 0 0
8 0 0 2 0 3 0 0 9
0 0 5 0 1 0 3 0 0

Output:


Problem: 
0 0 3 0 2 0 6 0 0
9 0 0 3 0 5 0 0 1
0 0 1 8 0 6 4 0 0
0 0 8 1 0 2 9 0 0
7 0 0 0 0 0 0 0 8
0 0 6 7 0 8 2 0 0
0 0 2 6 0 9 5 0 0
8 0 0 2 0 3 0 0 9
0 0 5 0 1 0 3 0 0
Solution:
4 8 3 9 2 1 6 5 7
9 6 7 3 4 5 8 2 1
2 5 1 8 7 6 4 9 3
5 4 8 1 3 2 9 7 6
7 2 9 5 6 4 1 3 8
1 3 6 7 9 8 2 4 5
3 7 2 6 8 9 5 1 4
8 1 4 2 5 3 7 6 9
6 9 5 4 1 7 3 8 2

Share:

DBMS Lab - Assignment 1, 2, 3, 4 || KD Edition || B.Tech Diaries

Assignment #1

  1. Create a table called EMP with the following structure:
    Name Type
    EMPNO NUMBER(6)
    ENAME VARCHAR2(20)
    JOB VARCHAR2(10)
    DEPTNO NUMBER(3)
    SAL NUMBER(7, 2)
    Allow NULL for all columns except ENAME and JOB.
    
    CREATE TABLE EMP (
        EMPNO NUMBER(6),
        ENAME VARCHAR2(20) NOT NULL,
        JOB VARCHAR2(10) NOT NULL,
        DEPTNO NUMBER(3),
        SAL NUMBER(7,2)
    );
  2. Add a column experience to the EMP table. EXPERIENCE numeric null allowed.
    
    ALTER TABLE EMP ADD (
        EXPERIENCE NUMBER(2)
    );
  3. Modify the column width of the job field of emp table.
    
    ALTER TABLE EMP MODIFY (
        JOB VARCHAR2(16)
    );
  4. Create the EMP1 table with ENAME and EMPNO, add constraints to check the EMPNO value while entering (i.e.) EMPNO>100
    
    CREATE TABLE EMP1 (
        ENAME VARCHAR2(20) NOT NULL,
        EMPNO NUMBER(6) CONSTRAINT B CHECK(EMPNO>100)
    );

Assignment #2

  1. Write query to select all the columns of emp table.
    
    SELECT * FROM EMP;
    EMPNO ENAME JOB MGR HIREDATE SAL COMM DEPTNO
    7839 KING PRESIDENT - 17-NOV-81 5000 - 10
    7698 BLAKE MANAGER 7839 01-MAY-81 2850 - 30
    7782 CLARK MANAGER 7839 09-JUN-81 2450 - 10
    7566 JONES MANAGER 7839 02-APR-81 2975 - 20
    7788 SCOTT ANALYST 7566 19-APR-87 3000 - 20
    7902 FORD ANALYST 7566 03-DEC-81 3000 - 20
    7369 SMITH CLERK 7902 17-DEC-80 800 - 20
    7499 ALLEN SALESMAN 7698 20-FEB-81 1600 300 30
    7521 WARD SALESMAN 7698 22-FEB-81 1250 500 30
    7654 MARTIN SALESMAN 7698 28-SEP-81 1250 1400 30
    7844 TURNER SALESMAN 7698 08-SEP-81 1500 0 30
    7876 ADAMS CLERK 7788 23-MAY-87 1100 - 20
    7900 JAMES CLERK 7698 03-DEC-81 950 - 30
    7934 MILLER CLERK 7782 23-JAN-82 1300 - 10
  2. Write query to select only EMPNAME, ENAME and JOB.
    
    SELECT ENAME, EMPNO, JOB FROM EMP;
    ENAME EMPNO JOB
    KING 7839 PRESIDENT
    BLAKE 7698 MANAGER
    CLARK 7782 MANAGER
    JONES 7566 MANAGER
    SCOTT 7788 ANALYST
    FORD 7902 ANALYST
    SMITH 7369 CLERK
    ALLEN 7499 SALESMAN
    WARD 7521 SALESMAN
    MARTIN 7654 SALESMAN
    TURNER 7844 SALESMAN
    ADAMS 7876 CLERK
    JAMES 7900 CLERK
    MILLER 7934 CLERK
  3. Write query to select unique JOBs.
    
    SELECT UNIQUE JOB FROM EMP;
    JOB
    ANALYST
    CLERK
    SALESMAN
    MANAGER
    PRESIDENT
  4. Write a query to select only those employees who are salesman.
    
    SELECT * FROM EMP 
        WHERE JOB = 'SALESMAN';
    EMPNO ENAME JOB MGR HIREDATE SAL COMM DEPTNO
    7499 ALLEN SALESMAN 7698 20-FEB-81 1600 300 30
    7521 WARD SALESMAN 7698 22-FEB-81 1250 500 30
    7654 MARTIN SALESMAN 7698 28-SEP-81 1250 1400 30
    7844 TURNER SALESMAN 7698 08-SEP-81 1500 0 30
  5. Select employee name, grade and salary in the order of their salary.
    
    SELECT ENAME, EMPNO, DEPTNO FROM EMP 
        ORDER BY SAL;
    EMPNO ENAME DEPTNO
    SMITH 7369 20
    JAMES 7900 30
    ADAMS 7876 20
    MARTIN 7654 30
    WARD 7521 30
    MILLER 7934 10
    TURNER 7844 30
    ALLEN 7499 30
    CLARK 7782 10
    BLAKE 7698 30
    JONES 7566 20
    FORD 7902 20
    SCOTT 7788 20
    KING 7839 10
  6. Mgmt is considering a pay raise, however they want to find out, if they give a flat $200 increment to all, then what % each person is getting. So in your result, display ENAME, SAL and PCTINCR
    
    SELECT ENAME, SAL, 200/SAL*100 AS PCTINCR 
        FROM EMP;
    ENAME SAL PCTINCR
    KING 5000 4
    BLAKE 2850 7.01754385964912280701754385964912280702
    CLARK 2450 8.16326530612244897959183673469387755102
    JONES 2975 6.72268907563025210084033613445378151261
    SCOTT 3000 6.66666666666666666666666666666666666667
    FORD 3000 6.66666666666666666666666666666666666667
    SMITH 800 25
    ALLEN 1600 12.5
    WARD 1250 16
    MARTIN 1250 16
    TURNER 1500 13.33333333333333333333333333333333333333
    ADAMS 1100 18.18181818181818181818181818181818181818
    JAMES 950 21.05263157894736842105263157894736842105
    MILLER 1300 15.38461538461538461538461538461538461538
  7. Express work experience of each of the employees by using sysdate and hiredate in terms of no of years.
    
    SELECT 
        TO_CHAR(HIREDATE, 'DD.MM.YYYY') "HIREDATE", 
        TO_CHAR(SYSDATE, 'DD.MM.YYYY') "Today", 
        (SYSDATE-HIREDATE)/365 "EXPERIENCE" 
    FROM EMP;
    hiredate Today experience
    17.11.1981 03.01.2023 41.15791945712836123795027904616945712849
    01.05.1981 03.01.2023 41.70586466260781329274479959411466260795
    09.06.1981 03.01.2023 41.59901534753932014205986808726534753945
    02.04.1981 03.01.2023 41.78531671740233384069000507356671740247
    19.04.1987 03.01.2023 35.73600164890918315575849822425164890932
    03.12.1981 03.01.2023 41.11408384069000507356671740233384069014
    17.12.1980 03.01.2023 42.07572767630644342973110096397767630658
    20.02.1981 03.01.2023 41.89764548452562151192288178589548452575
    22.02.1981 03.01.2023 41.89216603247082699137493658041603247096
    28.09.1981 03.01.2023 41.29490575849822425164890918315575849836
    08.09.1981 03.01.2023 41.3497002790461694571283612379502790463
    23.05.1987 03.01.2023 35.64285096397767630644342973110096397781
    03.12.1981 03.01.2023 41.11408384069000507356671740233384069014
    23.01.1982 03.01.2023 40.97435781329274479959411466260781329288

Assignment #3

  1. List down number of employees, minimum salary, maximum salary for each department.
    
    SELECT 
        COUNT(ENAME) AS COUNT, MAX(SAL) AS MAX, MIN(SAL) AS MIN, DEPTNO 
        FROM EMP 
        GROUP BY DEPTNO;
    COUNT MAX MIN DEPTNO
    6 2850 950 30
    3 5000 1300 10
    5 3000 800 20
  2. Update Email ID, if department id is
    1. <= 10, update the EMAIL field by appending @oracle.com
      
      ALTER TABLE EMP ADD(
          EMAIL VARCHAR(32)
      );
      UPDATE EMP 
          SET EMAIL=CONCAT(LOWER(ENAME),'@oracle.com') 
          WHERE DEPTNO<=10;
    2. <= 20, update the EMAIL field by appending @oracle.co.uk
      
      UPDATE EMP 
          SET EMAIL=CONCAT(LOWER(ENAME),'@oracle.co.uk') 
          WHERE DEPTNO>10 AND DEPTNO<=20;
    3. Else update it as @oracle.co.in
      
      UPDATE EMP 
          SET EMAIL=CONCAT(LOWER(ENAME),'@oracle.co.in') 
          WHERE DEPTNO>20;
      SELECT ENAME, EMAIL FROM EMP;
      ENAME EMAIL
      KING king@oracle.com
      BLAKE blake@oracle.co.in
      CLARK clark@oracle.com
      JONES jones@oracle.co.uk
      SCOTT scott@oracle.co.uk
      FORD ford@oracle.co.uk
      SMITH smith@oracle.co.uk
      ALLEN allen@oracle.co.in
      WARD ward@oracle.co.in
      MARTIN martin@oracle.co.in
      TURNER turner@oracle.co.in
      ADAMS adams@oracle.co.uk
      JAMES james@oracle.co.in
      MILLER miller@oracle.com
    4. Apart from 'Delete' and 'Truncate' statement can also be used for deleting the rows. Comment on their difference.
      When execute the DELETE command, the DBMS logs all removed rows. This means it is easier to recover from a mistake, than it would a mistaken TRUNCATE. When we TRUNCATE a table, less information is logged. This means the TRUNCATE statement executes very fast; however, it does so at the expense of not logging each row deleted.
    5. Display a department id wise count of employees
      • Getting salary more than 1200
        
        SELECT DEPTNO, COUNT(1) AS "COUNT" FROM EMP 
        WHERE SAL > 1200 
        GROUP BY DEPTNO;
        
        DEPTNO COUNT
        30 5
        10 3
        20 3
      • Apart from the above condition, select only those departments which has an average salary in excess of 1600
        
            SELECT DEPTNO, COUNT(1) AS "COUNT" FROM EMP
            WHERE SAL > 1200 
            HAVING AVG(SAL) > 1600
            GROUP BY DEPTNO;
        DEPTNO COUNT
        30 5
        10 3
        20 3
    6. Explain how two levels of filtering is happening based on firstly WHERE clause secondly HAVING clause based on this particular scenario.
      HAVING clause is used for cases where there are aggregate functions like COUNT, SUM, AVG, etc. WHERE clause is used for extract only those records that fulfil a specified condition and works for binary operation only.
    7. We want to add a new row in the employees table with employee id 1000, First Name = 'Scott', Last Name = 'Tiger', Email = 'Stiger@oracle.co.uk', HireDate = 01/02/2014, Job id = 'PR_Prsdnt'(Title = 'Company President')
      
      INSERT INTO EMP(EMPNO, DEPTNO, ENAME, EMAIL, HIREDATE, JOB, SAL) 
      VALUES(1000, 80, 'SCOTT', 'Stiger@oracle.co.uk', TO_DATE('01/02/2014','dd/mm/yyyy'), 'PR_PRSDNT', 5000);
    8. Issue necessary insert statements
      
      INSERT INTO DEPT(DEPTNO, DNAME, LOC)
      VALUES(80, 'DATABASE', 'EDINBURGH');
    9. After the update is over in the email column, use INSTR and SUBSTR to display email id and domain information separately.
      
      SELECT 
          SUBSTR(EMAIL,1,INSTR(EMAIL,'@')-1) AS EMAIL_ID, 
          SUBSTR(EMAIL,INSTR(EMAIL,'@')+1) AS DOMAIN 
      FROM EMP WHERE EMPNO=1000;
      EMAIL_ID DOMAIN
      Stiger oracle.co.uk
    10. Display day, month and year of the hire date of the employees.
      
      SELECT EXTRACT(DAY FROM TO_DATE(HIREDATE, 'dd-mm-rr')) AS DAY, 
      EXTRACT(MONTH FROM TO_DATE(HIREDATE, 'dd-mm-rr')) AS MONTH, 
      EXTRACT(YEAR FROM TO_DATE(HIREDATE, 'dd-mm-rr')) AS YEAR FROM EMP;
      DAY MONTH YEAR
      17 11 1981
      1 5 1981
      9 6 1981
      2 4 1981
      19 4 1987
      3 12 1981
      17 12 1980
      20 2 1981
      22 2 1981
      28 9 1981
      8 9 1981
      23 5 1987
      3 12 1981
      23 1 1982
      1 2 2014

Assignment #4

Level I

  1. Display name of employees, department name and job name for each employee.
    
    SELECT ENAME, DNAME, JOB FROM EMP E, DEPT D 
        WHERE E.DEPTNO=D.DEPTNO;
    ENAME DNAME JOB
    KING ACCOUNTING PRESIDENT
    BLAKE SALES MANAGER
    CLARK ACCOUNTING MANAGER
    JONES RESEARCH MANAGER
    SCOTT RESEARCH ANALYST
    FORD RESEARCH ANALYST
    SMITH RESEARCH CLERK
    ALLEN SALES SALESMAN
    WARD SALES SALESMAN
    MARTIN SALES SALESMAN
    TURNER SALES SALESMAN
    ADAMS RESEARCH CLERK
    JAMES SALES CLERK
    MILLER ACCOUNTING CLERK
    SCOTT DATABASE PR_PRSDNT
  2. Display the department name along with no of employees and average salary of that department.
    
    SELECT DNAME, CNT, AVG_SAL
    FROM (
        SELECT DEPTNO, COUNT(*) AS CNT, AVG(SAL) AS AVG_SAL FROM EMP GROUP BY DEPTNO 
    ) E 
    INNER JOIN DEPT D
    ON D.DEPTNO = E.DEPTNO;
    DNAME CNT AVG_SAL
    SALES 6 1566.666666666666666666666666666666666667
    ACCOUNTING 3 2916.666666666666666666666666666666666667
    RESEARCH 5 2175
    DATABASE 1 5000
  3. For each department, find out no. of jobs the employees are assigned to
    
    SELECT JOBS, DNAME 
    FROM (
      SELECT COUNT(UNIQUE JOB) AS JOBS, DEPTNO FROM EMP GROUP BY DEPTNO
    ) E, DEPT D 
    WHERE E.DEPTNO=D.DEPTNO;
    JOBS DNAME
    3 SALES
    3 ACCOUNTING
    3 RESEARCH
    1 DATABASE
  4. Check for correctness of the above queries in terms of count, if you want to bring in all entries, how would you achieve the same?
    
    SELECT * FROM EMP;
  5. Group by the employees based on the first character of employee first name. Display the results in alphabetic order (descending) of first character.
    
    SELECT SUBSTR(ENAME, 1, 1) AS ALPHA, COUNT(1) AS CNT FROM EMP 
    GROUP BY SUBSTR(ENAME, 1, 1) 
    ORDER BY SUBSTR(ENAME, 1, 1) DESC;
    ALPHA CNT
    W 1
    T 1
    S 3
    M 2
    K 1
    J 2
    F 1
    C 1
    B 1
    A 2

Level II

Table - EmployeeDetails

EmpId FullName ManagerId DateOfJoining
121 John Snow 321 01/31/2014
321 Walter White 986 01/30/2015
421 Kuldeep Rana 876 27/11/2016

Table - EmployeeSalary

EmpId Project Salary
121 P1 8000
321 P2 1000
421 P1 12000

CREATE TABLE EMPSAL (EMPID NUMBER(3), 
    PROJECT VARCHAR(2), 
    SAL NUMBER(7,2), 
    CONSTRAINT PK_EMPID PRIMARY KEY(EMPID) 
);
CREATE TABLE EMPDET  
(
    EMPID NUMBER(3),  
    FNAME VARCHAR(16),  
    MGID NUMBER(3), 
    JDT DATE, 
    CONSTRAINT PK_MGID PRIMARY KEY(MGID), 
    CONSTRAINT FK_EMPID FOREIGN KEY(EMPID) REFERENCES EMPSAL(EMPID) 
);
INSERT INTO EMPSAL VALUES(121, 'P1', 8000);
INSERT INTO EMPSAL VALUES(321, 'P2', 1000);
INSERT INTO EMPSAL VALUES(421, 'P1', 12000);
INSERT INTO EMPDET VALUES(121, 'JOHN SNOW', 321, DATE '2014-01-31');
INSERT INTO EMPDET VALUES(321, 'WALTER WHITE', 986, DATE '2015-01-30');
INSERT INTO EMPDET VALUES(421, 'KULDEEP RANA', 876, DATE '2016-11-27');
  1. Write a SQL query to fetch the count of employees working in project 'P1'.
    
    SELECT COUNT(*) AS COUNT FROM EMPSAL 
        WHERE PROJECT='P1';
    COUNT
    2
  2. Write a SQL query to fetch employee names having salary greater than or equal to 5000 and less than or equal 10000.
    
    SELECT FNAME FROM EMPSAL 
        INNER JOIN EMPDET ON EMPSAL.EMPID=EMPDET.EMPID 
        WHERE EMPSAL.SAL BETWEEN 5000 AND 10000;
    FNAME
    John Snow
  3. Write a SQL query to fetch project-wise count of employees sorted by project's count in descending order.
    
    SELECT PROJECT, COUNT(*) AS COUNT FROM EMPSAL 
        GROUP BY PROJECT 
        ORDER BY COUNT DESC;
    PROJECT COUNT
    P1 2
    P2 1
  4. Write a query to fetch only the first name(string before space) from the Full Name column of EmployeeDetails table.
    
    SELECT SUBSTR(FNAME,1,INSTR(FNAME,' ')-1) AS FIRSTNAME 
        FROM EMPDET;
    FIRSTNAME
    John
    Walter
    Kuldeep
  5. Write a query to fetch employee names and salary records. Return employee details even if the salary record is not present for the employee.
    
    SELECT FNAME, SAL FROM EMPDET 
    LEFT JOIN EMPSAL ON EMPSAL.EMPID=EMPDET.EMPID;
    FNAME SAL
    John Snow 8000
    Walter White 1000
    Kuldeep Rana 12000
  6. Write a SQL query to fetch all the Employees who are also managers from EmployeeDetails table.
    
    SELECT * FROM EMPDET E 
    WHERE EXISTS (SELECT * FROM EMPDET S WHERE E.EMPID = S.MGID);
    EMPID FNAME MGID JDT
    321 Walter White 986 30-JAN-15
  7. Write a SQL query to fetch all employee records from EmployeeDetails table who have a salary record in EmployeeSalary table.
    
    SELECT * FROM EMPDET E 
    WHERE EXISTS (SELECT * FROM EMPSAL S WHERE E.EMPID = S.EMPID);
    EMPID FNAME MGID JDT
    121 John Snow 321 31-JAN-14
    321 Walter White 986 30-JAN-15
    421 Kuldeep Rana 876 27-NOV-16
  8. Write a SQL query to fetch duplicate records from a table.
    
    SELECT EMPID, FNAME, MGID, JDT FROM EMPDET 
        GROUP BY EMPID, FNAME, MGID, JDT 
        HAVING COUNT(*) > 1;
  9. Write a SQL query to remove duplicates from a table without using temporary table.
    
    DELETE FROM EMPSAL 
    WHERE ROWID NOT IN (SELECT MAX(ROWID) FROM EMPSAL GROUP BY EMPID);
  10. Write a SQL query to fetch only odd rows from table.
    
    SELECT E.EMPID, E.PROJECT, E.SAL FROM ( 
    SELECT ROW_NUMBER() OVER(ORDER BY EMPID) AS ROWNUMBER, EMPID, PROJECT, SAL FROM EMPSAL) E 
    WHERE MOD(E.ROWNUMBER, 2) = 1;
    EMPID PROJECT SAL
    121 P1 8000
    421 P1 12000
  11. Write a SQL query to fetch only even rows from table.
    
    SELECT E.EMPID, E.PROJECT, E.SAL FROM ( 
    SELECT ROW_NUMBER() OVER(ORDER BY EMPID) AS ROWNUMBER, EMPID, PROJECT, SAL FROM EMPSAL) E 
    WHERE MOD(E.ROWNUMBER, 2) = 0;
    EMPID PROJECT SAL
    321 P2 1000
  12. Write a SQL query to create a new table with data and structure copied from another table.
    
    SELECT * INTO EMPSALARY 
        FROM EMPSAL;
  13. Write a SQL query to create an empty table with same structure as some other table.
    
    SELECT * INTO EMPSALARY FROM EMPSAL 
        WHERE 1=0;
  14. Write a SQL query to fetch common records between two variables.
    
    SELECT * FROM EMPSAL 
        INTERSECT SELECT * FROM MGSAL;
  15. Write a SQL query to fetch records that are present in one table but not in another table.
    
    SELECT * FROM EMPSAL 
        MINUS SELECT * FROM MGSAL;
  16. Write a SQL query to find current date-time.
    
    SELECT getdate();
  17. Write a SQL query to fetch all the Employees details from EmployeeDetails table who joined in year 2016.
    
    SELECT * FROM EMPDET 
    WHERE JDT BETWEEN DATE '2016-01-01' AND DATE '2016-12-31';
    EMPID FNAME MGID JDT
    421 Kuldeep Rana 876 27-NOV-16
  18. Write a SQL query to fetch top n records.
    
    SELECT * FROM EMPSAL 
        ORDER BY SAL DESC 
        FETCH NEXT 2 ROWS ONLY;
    EMPID PROJECT SAL
    421 P1 12000
    121 P1 8000
  19. Write a SQL query to find the nth highest salary from table.
    
    SELECT * FROM (
        SELECT * FROM EMPSAL ORDER BY SAL DESC FETCH NEXT 2 ROWS ONLY
    ) ORDER BY SAL ASC 
    FETCH NEXT 1 ROWS ONLY;
    EMPID PROJECT SAL
    121 P1 8000
  20. Write SQL query to find the 3rd highest salary from table without using TOP/limit keyword.
    
    SELECT SAL 
        FROM EMPSAL EMP1 
        WHERE 2 = ( 
            SELECT COUNT( DISTINCT( EMP2.SAL ) ) FROM EMPSAL EMP2 
            WHERE EMP2.SAL > EMP1.SAL 
        );
    SAL
    1000
Share:

Project 1 || Wong Edition || C++ Project || B.Tech Diaries

Project #1 - Sorted Date List

  • Read a sequence of dates from file input.
  • Permissible formats for dates include
    dd/mm/yyyy e.g. 01/01/1970
    
    d MMM yyyy e.g. 1 JAN 1970
    
    MMM d, 1970 e.g. JAN 1, 1970
    
    MMMM d, yyyy e.g. January 1, 1970.
    
  • Sort and output the dates such that the later dates come first.
  • Use functions from the STL's: `<string>`, `<algorithm>`, `<regex>`, `<iterator>`, `<array>`.
  • Create your customised MyDate class.

Solution:


#include <iostream>
#include <string>
#include <algorithm>
#include <regex>
#include <iterator>
#include <array>
#include <fstream>
#include <iomanip>

#define N 25

class Date
{
private:
    int day;
    int month;
    int year;
    std::array<std::string, 12> _months = {"January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"};

public:
    Date()
    {
        day = 9999;
        month = 9999;
        year = 9999;
    }
    Date(std::string str_date)
    {
        day = 1;
        month = 1;
        year = 1970;
        _date_parser(str_date);
    }
    ~Date() {}
    bool is_valid()
    {
        if (day > 31 || day < 1)
            return false;
        if (month > 12 || month < 1)
            return false;
        if (year > 9999 || year < 1000)
            return false;
        return true;
    }
    void _date_parser(std::string str_date)
    {
        std::string _months_abbr_pattern = "", _months_pattern = "";
        for (size_t i = 0; i < _months.size(); i++)
        {
            _months_abbr_pattern += _months[i].substr(0, 3);
            if (_months.size() - 1 != i)
            {
                _months_abbr_pattern += "|";
            }
        }
        for (size_t i = 0; i < _months.size(); i++)
        {
            _months_pattern += _months[i];
            if (_months.size() - 1 != i)
            {
                _months_pattern += "|";
            }
        }

        std::array<std::regex, 10> patterns({
            std::regex("([0-2][1-9]|3[0-1])\\s*[, /\\-]\\s*(0[1-9]|1[0-2])\\s*[, /\\-]\\s*([1-5]\\d{3})"),
            std::regex("([1-9]|[1-2][1-9]|3[0-1])\\s*[, /\\-]\\s*(" + _months_abbr_pattern + ")\\s*[, /\\-]\\s*([1-5]\\d{3})", std::regex::icase),
            std::regex("(" + _months_abbr_pattern + ")\\s*[, /\\-]\\s*([1-9]|[1-2][1-9]|3[0-1])\\s*[, /\\-]\\s*([1-5]\\d{3})", std::regex::icase),
            std::regex("(" + _months_pattern + ")\\s*[, /\\-]\\s*([1-9]|[1-2][1-9]|3[0-1])\\s*[, /\\-]\\s*([1-5]\\d{3})", std::regex::icase),
        });

        std::smatch match;
        bool check = false;
        for (size_t i = 0; i < patterns.size(); i++)
        {
            if (std::regex_match(str_date, patterns[i]))
            {
                std::regex_search(str_date, match, patterns[i]);
                switch (i)
                {
                case 0:
                    day = std::stoi(match[1].str());
                    month = std::stoi(match[2].str());
                    year = std::stoi(match[3]);
                    break;
                case 1:
                    day = std::stoi(match[1].str());
                    month = _months.size();
                    for (size_t i = 0; i < _months.size(); i++)
                    {
                        if (_months[i].substr(0, 3) == match[2].str())
                        {
                            month = i + 1;
                            break;
                        }
                    }
                    year = std::stoi(match[3]);
                    break;
                case 2:
                    day = std::stoi(match[2].str());
                    month = _months.size();
                    for (size_t i = 0; i < _months.size(); i++)
                    {
                        if (_months[i].substr(0, 3) == match[1].str())
                        {
                            month = i + 1;
                            break;
                        }
                    }
                    year = std::stoi(match[3]);
                    break;
                case 3:
                    day = std::stoi(match[2].str());
                    month = _months.size();
                    for (size_t i = 0; i < _months.size(); i++)
                    {
                        if (_months[i] == match[1].str())
                        {
                            month = i + 1;
                            break;
                        }
                    }
                    year = std::stoi(match[3]);
                    break;
                }
                check = true;
                break;
            }
        }
        if (!check)
            std::cout << "Invalid Format" << std::endl;
    }

    bool operator>(Date d)
    {
        if (year > d.year)
            return true;
        else if (year == d.year)
        {
            if (month > d.month)
                return true;
            else if (month == d.month)
            {
                if (day > d.day)
                    return true;
                else
                    return false;
            }
            else
                return false;
        }
        return false;
    }

    bool operator<(Date d)
    {
        if (year < d.year)
            return true;
        else if (year == d.year)
        {
            if (month < d.month)
                return true;
            else if (month == d.month)
            {
                if (day < d.day)
                    return true;
                else
                    return false;
            }
            else
                return false;
        }
        return false;
    }

    std::string _str()
    {
        std::string str_date = "";
        str_date += std::to_string(day) + " ";
        str_date += _months[month - 1] + " ";
        str_date += std::to_string(year);
        return str_date;
    }

    friend std::ostream &operator<<(std::ostream &os, Date &date)
    {
        os << date._str();
        return os;
    }
};

std::array<Date, N> get_dates(std::string filename)
{
    std::ifstream infile;
    std::string str_date;

    std::array<Date, N> date_array;
    std::cout << "Get Dates from " << filename << " ... " << std::endl;
    int i = 0;
    infile.open(filename);
    while (std::getline(infile, str_date))
    {
        if (str_date != "")
            date_array[i++] = Date(str_date);
    }
    infile.close();

    return date_array;
}

int main(int argc, char const *argv[])
{
    std::array<Date, N> dates = get_dates("date_list.txt");

    std::cout << "Sorting Dates ... " << std::endl;
    std::sort(dates.begin(), dates.end());

    std::array<Date, N>::iterator it;
    for (it = dates.begin(); it != dates.end(); it++)
    {
        if (it->is_valid())
            std::cout << *it << std::endl;
    }

    return 0;
}

Input (date_list.txt):


30/01/3055
30-02-4849
30 01, 3459
16/11/5509
30-06/1571
13-Aug-1768
30/ Apr/1002
2 May 2668
29 JAN, 5802
31 Jul 2224
Jan 7 3106
Apr 31 1632
Mar 6 ,3214
Feb 19, 5063
Sep 6-3652
April 30, 5889
January 13 ,4035
May 21 2671
June 30, 4785
JANUARY 4 2324

Output:


Get Dates from date_list.txt ... 
Sorting Dates ...
30 April 1002
30 June 1571
31 April 1632
13 August 1768
31 July 2224
4 December 2324
2 May 2668
21 May 2671
30 January 3055
7 January 3106
6 March 3214
30 January 3459
6 September 3652
13 January 4035
30 June 4785
30 February 4849
19 February 5063
16 November 5509
29 December 5802
30 April 5889

Share:

Programming with C++ - Day8 || Wong Edition || B.Tech Diaries

Lab #8 - Standard Template Library (STL)

Resources

Question 1 - Acrobatics with Strings

Write a program that creates 2 strings then prints out the letters they have in common.

Solution:


#include <bits/stdc++.h>

// Question 1
void commonLetters(std::string s1, std::string s2)
{
    std::string s = "";
    auto it = std::set_intersection(s1.begin(), s1.end(), s2.begin(), s2.end(), std::back_inserter(s));
    std::cout << s << std::endl;
}

int main(int argc, char const *argv[])
{
    std::string s1 = "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Nec feugiat in fermentum posuere urna. Nunc sed blandit libero volutpat sed cras ornare. Commodo quis imperdiet massa tincidunt nunc pulvinar sapien et ligula. A scelerisque purus semper eget. Pellentesque elit ullamcorper dignissim cras tincidunt lobortis. Mattis aliquam faucibus purus in massa tempor nec feugiat nisl. Tortor id aliquet lectus proin. Nulla posuere sollicitudin aliquam ultrices sagittis. Sed adipiscing diam donec adipiscing. Bibendum enim facilisis gravida neque convallis a cras.",
                s2 = "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Sit amet nisl suscipit adipiscing bibendum. Sed viverra ipsum nunc aliquet bibendum enim facilisis gravida. Ipsum suspendisse ultrices gravida dictum fusce ut placerat orci nulla. Et magnis dis parturient montes. Blandit massa enim nec dui nunc mattis enim ut tellus. Tempus quam pellentesque nec nam aliquam. Aenean pharetra magna ac placerat vestibulum lectus mauris ultrices eros. Tristique nulla aliquet enim tortor at auctor urna nunc id. In fermentum et sollicitudin ac orci phasellus. Senectus et netus et malesuada fames ac.";
    commonLetters(s1, s2);
    return 0;
}

Output:


Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. ut iumvvrsuuuussrvidauv

Question 2 - Sorting Vehicles

Create instances of the Vehicle class (from Lab #7) e.g. 3 BUSes, 4 CARs, 2 AUTOs, 5 SCOOTERs.

Store them in a Vector and sort them according to size.

Solution:


#include <bits/stdc++.h>

// Question 2
class Vehicle
{
private:
    std::string name;
    int legs;
    double cost;

public:
    Vehicle()
    {
    }
    Vehicle(std::string n, int l, double c)
    {
        legs = l;
        cost = c;
        name = n;
    }
    ~Vehicle()
    {
    }

    double _cost()
    {
        return cost;
    }

    bool operator>(Vehicle v)
    {
        return (legs > v.legs) || (legs == v.legs && cost > v.cost);
    }
    bool operator<(Vehicle v)
    {
        return (legs < v.legs) || (legs == v.legs && cost < v.cost);
    }

    bool operator==(Vehicle v)
    {
        return (legs == v.legs) && (cost == v.cost);
    }

    std::string to_string()
    {
        return name + "(" + std::to_string(legs) + "," + std::to_string(cost) + ")";
    }

    operator std::string() const
    {
        return name + "(" + std::to_string(legs) + "," + std::to_string(cost) + ")";
    }

    friend std::ostream &operator<<(std::ostream &out, Vehicle &v)
    {
        out << v.to_string();
        return out;
    }
};

void sortVehicles(std::vector<Vehicle> &vehicles)
{
    struct
    {
        bool operator()(Vehicle v1, Vehicle v2)
        {
            return v1._cost() > v2._cost();
        }
    } smallerSize;

    std::sort(vehicles.begin(), vehicles.end(), smallerSize);
    // return vehicles;
}

int main(int argc, char const *argv[])
{
    std::vector<Vehicle> vehicles;
    vehicles.push_back(Vehicle("car", 4, 100));
    vehicles.push_back(Vehicle("car", 4, 200));
    vehicles.push_back(Vehicle("car", 4, 300));
    vehicles.push_back(Vehicle("car", 4, 400));
    vehicles.push_back(Vehicle("bus", 4, 400));
    vehicles.push_back(Vehicle("bus", 4, 300));
    vehicles.push_back(Vehicle("bus", 4, 200));
    vehicles.push_back(Vehicle("auto", 3, 400));
    vehicles.push_back(Vehicle("auto", 3, 300));
    vehicles.push_back(Vehicle("scooter", 2, 50));
    vehicles.push_back(Vehicle("scooter", 2, 100));
    vehicles.push_back(Vehicle("scooter", 2, 120));
    vehicles.push_back(Vehicle("scooter", 2, 150));
    vehicles.push_back(Vehicle("scooter", 2, 200));
    sortVehicles(vehicles);
    for (Vehicle v : vehicles)
    {
        std::cout << v << std::endl;
    }
    return 0;
}

Output:


car(4,400.000000)
bus(4,400.000000)
auto(3,400.000000)
car(4,300.000000)
bus(4,300.000000)
auto(3,300.000000)
car(4,200.000000)
bus(4,200.000000)
scooter(2,200.000000)
scooter(2,150.000000)
scooter(2,120.000000)
car(4,100.000000)
scooter(2,100.000000)
scooter(2,50.000000)

Question 3 - Rectangles and Squares

Using the Rectangle class from Lab #3, create a Square class.

Store instances of Rectangle and Square in a single Vector.

Sort them according to their area. [Hint: use Vector<Rectangle *>]

Solution:


    #include <bits/stdc++.h>

    // Question 3
    class Rectangle
    {
    private:
        int length, breadth;
        std::string colour;
    
    public:
        Rectangle();
        Rectangle(int, int, std::string);
        ~Rectangle();
        int getArea();
        std::string print();
        int compare(Rectangle);
        int _length();
        int _breadth();
        std::string _colour();
    };
    
    int Rectangle::_length()
    {
        return length;
    }
    
    int Rectangle::_breadth()
    {
        return breadth;
    }
    
    std::string Rectangle::_colour()
    {
        return colour;
    }
    
    Rectangle::Rectangle()
    {
        length = 0;
        breadth = 0;
        colour = "";
    }
    
    Rectangle::Rectangle(int length, int breadth, std::string colour)
    {
        this->length = length;
        this->breadth = breadth;
        this->colour = colour;
    }
    
    Rectangle::~Rectangle()
    {
    }
    
    int Rectangle::getArea()
    {
        return this->length * this->breadth;
    }
    
    std::string Rectangle::print()
    {
        std::stringstream ps;
        ps << "\nLength: " << this->length
           << "\nBreadth: " << this->breadth
           << "\nColour: " << this->colour
           << "\nArea: " << this->getArea() << std::endl;
        return ps.str();
    }
    
    int Rectangle::compare(Rectangle rect)
    {
        if (this->getArea() > rect.getArea())
            return 1;
        else if (this->getArea() < rect.getArea())
            return -1;
        return 0;
    }
    
    class Square : public Rectangle
    {
    
    private:
    public:
        Square();
        Square(int, std::string);
        ~Square();
        std::string print();
    };
    
    Square::Square()
    {
    }
    Square::Square(int side, std::string color) : Rectangle(side, side, color)
    {
    }
    
    Square::~Square()
    {
    }
    
    std::string Square::print()
    {
        std::stringstream ps;
        ps << "\nSide: " << this->_length()
           << "\nColour: " << this->_colour()
           << "\nArea: " << this->getArea() << std::endl;
        return ps.str();
    }
    
    int main(int argc, char const *argv[])
    {
        std::vector<Rectangle> rectangles;
        rectangles.push_back(Square(5, "S red"));
        rectangles.push_back(Square(10, "S blue"));
        rectangles.push_back(Square(15, "S green"));
    
        rectangles.push_back(Rectangle(5, 10, "R red"));
        rectangles.push_back(Rectangle(10, 15, "R blue"));
        rectangles.push_back(Rectangle(15, 20, "R green"));
    
        std::sort(rectangles.begin(), rectangles.end(), [](Rectangle a, Rectangle b)
                  { return a.compare(b) < 0; });
    
        for (Rectangle r : rectangles)
        {
            std::cout << r.print() << std::endl;
        }
    
        return 0;
    }      

Output:


    Length: 5
    Breadth: 5
    Colour: S red
    Area: 25
    
    
    Length: 5
    Breadth: 10
    Colour: R red
    Area: 50
    
    
    Length: 10
    Breadth: 10
    Colour: S blue
    Area: 100
    
    
    Length: 10
    Breadth: 15
    Colour: R blue
    Area: 150
    
    
    Length: 15
    Breadth: 15
    Colour: S green
    Area: 225
    
    
    Length: 15
    Breadth: 20
    Colour: R green
    Area: 300

Share:

Programming with C++ - Day7 || Wong Edition || B.Tech Diaries

Lab #7 - Templates

Question 1 - Function Template

The format for function declaration is:

template <class identifier> function_declaration;

The format for function call is:

function_name <type> (parameters);
  • Write a function template getLarger that takes two parameters of any (same) type and returns the larger of the two.
  • Write a class Vehicle and provide the implementation for the ">" operator. Use the Vehicle in the getLarger function from (a). E.g. Bus > Car > Auto > Scooter

Solution:


#include <iostream>

// question 1
class Vehicle
{
private:
    std::string name;
    int legs;
    double cost;

public:
    Vehicle()
    {
    }
    Vehicle(std::string n, int l, double c)
    {
        legs = l;
        cost = c;
        name = n;
    }
    ~Vehicle()
    {
    }
    bool operator>(Vehicle v)
    {
        return (legs > v.legs) || (legs == v.legs && cost > v.cost);
    }
    bool operator<(Vehicle v)
    {
        return (legs < v.legs) || (legs == v.legs && cost < v.cost);
    }

    bool operator==(Vehicle v)
    {
        return (legs == v.legs) && (cost == v.cost);
    }

    operator std::string() const
    {
        return name + "(" + std::to_string(legs) + "," + std::to_string(cost) + ")";
    }

    std::string to_string()
    {
        return name + "(" + std::to_string(legs) + "," + std::to_string(cost) + ")";
    }

    friend std::ostream &operator<<(std::ostream &out, const Vehicle &v);
};

template <typename T>
T getLarger(T a, T b)
{
    return (a > b) ? a : b;
}

template <typename T>
T getSmaller(T a, T b)
{
    return (a < b) ? a : b;
}

int main(int argc, char const *argv[])
{
    int N = 10;

    Vehicle vehicles[N];

    for (int i = 0; i < N; i++)
    {
        int legs = rand() % 4 + 2;
        double cost = rand() % 700 + 100;
        std::string name = "Vehicle " + std::to_string(i + 1);
        vehicles[i] = Vehicle(name, legs, cost);
    }

    std::cout << std::endl
                << "========Comparison of Vehicles========"
                << std::endl;

    for (int i = 0; i < N; i++)
    {
        for (int j = 0; j < N - i - 1; j++)
        {
            Vehicle v1 = getLarger<Vehicle>(vehicles[j + 1], vehicles[j]);
            Vehicle v2 = getSmaller<Vehicle>(vehicles[j + 1], vehicles[j]);
            vehicles[j] = v1;
            vehicles[j + 1] = v2;
        }
    }

    for (int i = 0; i < N; i++)
    {
        std::cout << vehicles[i];
        if (i != N - 1)
            std::cout << " > ";
    }
    std::cout << std::endl
                << std::endl;

    return 0;
}


========Comparison of Vehicles========
Vehicle 1(5,286.000000) > Vehicle 8(5,226.000000) > Vehicle 4(4,592.000000) > Vehicle 7(4,559.000000) > Vehicle 6(4,427.000000) > Vehicle 3(3,635.000000) > Vehicle 5(3,621.000000) > Vehicle 2(3,315.000000) > Vehicle 9(2,626.000000) > Vehicle 10(2,536.000000)

Question 2 - Class Template

The format for function declaration is:

template <class identifier> class classname
  1. Write a class template MyArray that can store up to 10 elements of any type, with the following functions:-
    • addElement
    • sort
    • print
  2. Store Vehicle instances from Question 1 in MyArray and sort them.

Solution:


...
// question 2
template <typename T>
class MyArray
{
private:
    T *arr;
    int capacity, size;

public:
    MyArray()
    {
        capacity = 8;
        arr = new T[capacity];
        size = 0;
    }
    bool addElement(T item)
    {
        if (size == capacity)
        {
            T *temp = new T[capacity * 2];
            for (int i = 0; i < size; i++)
            {
                temp[i] = arr[i];
            }
            delete[] arr;
            arr = temp;
            capacity *= 2;
        }
        arr[size++] = item;
        return true;
    }
    void sort()
    {
        for (int i = 0; i < size; i++)
        {
            for (int j = i + 1; j < size; j++)
            {
                if (arr[j] > arr[i])
                {
                    std::swap(arr[i], arr[j]);
                }
            }
        }
    }
    T get(int index)
    {
        return arr[index];
    }
    T operator[](int index)
    {
        return arr[index];
    }
    std::string print()
    {
        std::string str = "[";
        for (int i = 0; i < size; i++)
        {
            str += arr[i].to_string();
            if (i != size - 1)
                str += ", ";
        }
        str += "]";
        return str;
    }
};

int main(int argc, char const *argv[])
{
    int N = 15;

    MyArray<Vehicle> vehicles;

    for (int i = 0; i < N; i++)
    {
        int legs = rand() % 4 + 2;
        double cost = rand() % 1000 * 0.1234 + 100;
        std::string name = "Vehicle " + std::to_string(i + 1);
        vehicles.addElement(Vehicle(name, legs, cost));
    }

    std::cout << "Vehicles before sorting" << std::endl;
    std::cout << vehicles.print()
              << std::endl
              << std::endl;

    std::cout << "Vehicles after sorting" << std::endl;

    vehicles.sort();

    return 0;
}


    Vehicles before sorting
[Vehicle 1(5,209.332400), Vehicle 2(3,212.911000), Vehicle 3(3,141.339000), Vehicle 4(4,160.712800), Vehicle 5(3,151.951400), Vehicle 6(4,103.331800), Vehicle 7(4,107.280600), Vehicle 8(5,214.268400), Vehicle 9(2,152.568400), Vehicle 10(2,190.822400), Vehicle 11(5,145.411200), Vehicle 12(5,152.938600), Vehicle 13(4,165.402000), Vehicle 14(4,115.178200), Vehicle 15(5,116.659000)]

Question 3 - Friend Function

In Question 1 and Question 2, the `printTypeString()` function in the Vehicle class was used to output Vehicle information.

Overload the cout "<<" operator to output Vehicle information. Declare the "<<" function as friend in the Vehicle class, so as to access Vehicle's private attributes:-

friend ostream& operator<<(ostream &out, const Vehicle& v)

Note: friend functions and classes should be used sparingly as they break the good idea of encapsulation.

Solution:


...
// question 3
std::ostream &operator<<(std::ostream &out, const Vehicle &v)
{
    out << v.operator std::string();
    return out;
}

int main(int argc, char const *argv[])
{
    int N = 15;

    MyArray<Vehicle> vehicles;

    for (int i = 0; i < N; i++)
    {
        int legs = rand() % 4 + 2;
        double cost = rand() % 1000 * 0.1234 + 100;
        std::string name = "Vehicle " + std::to_string(i + 1);
        vehicles.addElement(Vehicle(name, legs, cost));
    }

    std::cout << "Vehicles before sorting" << std::endl;
    std::cout << vehicles.print()
                << std::endl
                << std::endl;

    std::cout << "Vehicles after sorting" << std::endl;

    vehicles.sort();

    std::cout << vehicles.print() << std::endl;
    std::cout << std::endl;

    std::cout << vehicles[0] << std::endl;

    return 0;
}    

Output:


Vehicles before sorting
[Vehicle 1(5,209.332400), Vehicle 2(3,212.911000), Vehicle 3(3,141.339000), Vehicle 4(4,160.712800), Vehicle 5(3,151.951400), Vehicle 6(4,103.331800), Vehicle 7(4,107.280600), Vehicle 8(5,214.268400), Vehicle 9(2,152.568400), Vehicle 10(2,190.822400), Vehicle 11(5,145.411200), Vehicle 12(5,152.938600), Vehicle 13(4,165.402000), Vehicle 14(4,115.178200), Vehicle 15(5,116.659000)]

Vehicles after sorting
[Vehicle 8(5,214.268400), Vehicle 1(5,209.332400), Vehicle 12(5,152.938600), Vehicle 11(5,145.411200), Vehicle 15(5,116.659000), Vehicle 13(4,165.402000), Vehicle 4(4,160.712800), Vehicle 14(4,115.178200), Vehicle 7(4,107.280600), Vehicle 6(4,103.331800), Vehicle 2(3,212.911000), Vehicle 5(3,151.951400), Vehicle 3(3,141.339000), Vehicle 10(2,190.822400), Vehicle 9(2,152.568400)]

Vehicle 8(5,214.268400)

Share:

Programming with C++ - Day5 || Wong Edition || B.Tech Diaries

Lab #5 - Inheritance and Over-Riding

Question 1 - Company Hierarchy

In a Company Hierarchy consisting of Clerk, Manager and Director, the invoice approval limits are as follows:-

  • Clerk - $100
  • Manager - $500
  • Director - $1000

The UML Class Diagram for the Clerk is as shown.

Clerk
- name : String
- designation: String
* getName : String
* getDesignation : String
* introduce() : String
* approveInvoice(in invoiceAmount:double) : boolean
  • Depict the Company Hierarchy in a UML Class Diagram.
  • Implement the Company Hierarchy. Over-Ride the approveInvoice function to ensure the approval limits are adhered to. [Hint: create the main() loop in the Director class and create instances of Clerk, Manager and Director]

Solution:


#include <iostream>

/**
    * @brief Class Clerk
*/
class Clerk
{
private:
    std::string name, designation;

public:
    Clerk(std::string);
    Clerk(std::string, std::string);
    ~Clerk();
    std::string getName();
    std::string getDesignation();
    std::string introduce();
    bool approveInvoice(double);
};

Clerk::Clerk(std::string name)
{
    this->name = name;
    this->designation = "Clerk";
}

Clerk::Clerk(std::string name, std::string designation)
{
    this->name = name;
    this->designation = designation;
}

Clerk::~Clerk()
{
}

std::string Clerk::getName()
{
    return this->name;
}

std::string Clerk::getDesignation()
{
    return this->designation;
}

std::string Clerk::introduce()
{
    return "My name is " + this->name + " and I am a " + this->designation;
}

bool Clerk::approveInvoice(double amount)
{
    if (amount <= 100)
        return true;
    else
        return false;
}

/**
    * @brief Class Manager
*/

class Manager : public Clerk
{
private:
public:
    Manager(std::string);
    Manager(std::string, std::string);
    ~Manager();
    bool approveInvoice(double);
};

Manager::Manager(std::string name) : Clerk(name, "Manager")
{
}

Manager::Manager(std::string name, std::string designation) : Clerk(name, designation)
{
}

Manager::~Manager()
{
}

bool Manager::approveInvoice(double amount)
{
    if (amount <= 500)
        return true;
    else
        return false;
}

/**
    * @brief Class Manager
*/

class Director : public Manager
{
private:
public:
    Director(std::string);
    ~Director();
    bool approveInvoice(double);
};

Director::Director(std::string name) : Manager(name, "Director")
{
}

Director::~Director()
{
}

bool Director::approveInvoice(double amount)
{
    if (amount <= 1000)
        return true;
    else
        return false;
}

// program 1
int main(int argc, char const *argv[])
{
    Clerk clerk("John");
    Manager manager("Jane");
    Director director("Jack");

    std::cout << clerk.introduce() << std::endl;
    std::cout << manager.introduce() << std::endl;
    std::cout << director.introduce() << std::endl;

    std::cout << (clerk.approveInvoice(77) ? "True" : "False") << std::endl;
    std::cout << (clerk.approveInvoice(100) ? "True" : "False") << std::endl;
    std::cout << (clerk.approveInvoice(124) ? "True" : "False") << std::endl;

    std::cout << (manager.approveInvoice(427) ? "True" : "False") << std::endl;
    std::cout << (manager.approveInvoice(500) ? "True" : "False") << std::endl;
    std::cout << (manager.approveInvoice(584) ? "True" : "False") << std::endl;

    std::cout << (director.approveInvoice(927) ? "True" : "False") << std::endl;
    std::cout << (director.approveInvoice(1000) ? "True" : "False") << std::endl;
    std::cout << (director.approveInvoice(1084) ? "True" : "False") << std::endl;
    return 0;
}    

Output:


My name is John and I am a Clerk
My name is Jane and I am a Manager
My name is Jack and I am a Director
True
True
False
True
True
False
True
True
False

Question 2 - Company Hierarchy with Outsourcing

To cut costs, the Company decided to take on Contractors.

A Contractor has a Name in the company records, but has no formal designation. A Contractor cannot approveInvoice (but of course!).

Suppose that at a Company function, everyone has to introduce himself / herself:-

    Hello, my name is xxx.  My designation is XXX.
                          or
    Hello, my name is yyy.  I am a Contractor.
  • Design the new Company Hierarchy in a UML Class Diagram, to accommodate the Contractor. [Hint: pull up the common attributes / properties and behaviour into an Abstract Class.]
  • Implement the new Company Hierarchy. Keep the main() loop in the Director class.

Solution:


...
// program 2

class Contractor : protected Clerk
{
private:

public:
    Contractor(std::string);
    ~Contractor();
    std::string introduce();
    std::string getName();
};

Contractor::Contractor(std::string name) : Clerk(name)
{
}

Contractor::~Contractor()
{
}

std::string Contractor::introduce()
{
    return "My name is " + this->getName() + " and I am a Contractor";
}

std::string Contractor::getName()
{
    return Clerk::getName();
}

int main(int argc, char const *argv[])
{
    Contractor contractor("John");
    std::cout << contractor.introduce() << std::endl;
    std::cout << contractor.getName() << std::endl;

    return 0;
}


My name is John and I am a Contractor
John

Question 3 - Fraud!

Suppose a Director in the Company tries to impersonate his Clerk at the Company function by introducing himself as a Clerk. By using casting, show how that this is possible.


Clerk* cPtr = new Manager(...);
cPtr->introduce();   

Suppose a Clerk in the Company tries to impersonate his Manager at the Company function. Explain why this is not possible.


Manager* mPtr = new Clerk(...);
mPtr->introduce();

Solution:


...
// program 3
int main(int argc, char const *argv[])
{
    Clerk *cPtr = new Manager("John");
    std::cout << cPtr->introduce() << std::endl;

    try
    {
        Manager *mPtr = new Clerk("Jane");
        mPtr->introduce();
    }
    catch (const std::exception &e)
    {
        std::cerr << e.what() << 'n';
    }

    return 0;
}


My name is John and I am a Manager

Share: