Programming Puzzles
  • Introduction
  • CTCI
    • Arrays and Strings
      • Is Unique
      • Check Permutation
      • URLify
      • Palindrome Permutation
      • One Away
      • String Compression
      • Rotate Matrix
      • Zero Matrix
      • String Rotation
    • Linked Lists
      • Remove Dups
      • Return Kth to Last
      • Delete Middle Node
      • Sum Lists
      • Palindrome
      • Intersection
    • Trees
      • Route Between Nodes
      • Minimal Tree
      • Check Balanced
      • Build Order
      • First Common Ancestor
      • BST Sequences
      • Check Subtree
      • Random Node
    • Stacks and Queues
      • Three in One
      • Stack Min
      • Stack of Plates
      • Queue via Stacks
      • Sort Stack
    • Sorting and Searching
      • Sorted Merge
      • Group Anagrams
      • Search in Rotated Array
      • Sorted Search, No Size
      • Sparse Search
      • Sort Big File
      • Missing Int
      • Find Duplicates
      • Sorted Matrix Search
    • Bit Manipulation
      • Insertion
    • Math and Puzzles
      • Two Ropes
      • Nine Balls
      • The Heavy Pill
      • Basketball
      • Dominos
    • Recursion and Dynamic Programming
      • Triple Step
      • Robot in a Grid
      • Magic Index
      • Power Set
      • Recursive Multiply
      • Towers of Hanoi
      • Permutations without Dups
      • Parens
      • Paint Fill
      • Coins
    • Object Oriented Design
      • Circular Array
    • Moderate
      • Number Swapper
      • Word Frequencies
      • Intersection
      • Tic Tac Win
      • Factorial Zeros
      • Smallest Difference
      • Number Max
      • Operations
      • Living People
      • Diving Board
      • Bisect Squares
      • Best Line
      • Sub Sort
      • Contiguous Sequence
      • Pattern Matching
      • Pond sizes
      • T9
      • Sum Swap
      • Pairs with Sum
    • Hard
      • Add Without Plus
      • Shuffle
      • Random Set
      • Count of 25
      • Baby Names
      • Majority Element
      • Word Distance
      • The Masseuse
      • Word Transformer
      • Sparse Similarity
  • EoPI
    • Arrays and Strings
  • LeetCode
    • 3 Longest Substring Without Repeating Characters
    • 4 Median of Two Sorted Arrays
    • 5 Longest Palindromic Substring
    • 6 ZigZag Conversion
    • 7 Reverse Integer
    • 8 String to Integer (atoi)
    • 9 Palindrome Number
    • 11 Container With Most Water
    • 14 Longest Common Prefix
    • 15 3Sum
    • 16 3Sum Closest
    • 17 Letter Combinations of a Phone Number
    • 19 Remove Nth Node From End of List
    • 20 Valid Parentheses
    • 21 Merge Two Sorted Lists
    • 22 Generate Parentheses
    • 23 Merge k Sorted Lists
    • 24 Swap Nodes in Pairs
    • 26 Remove Duplicates from Sorted Array
    • 27 Remove Element
    • 28 Implement strStr()
    • 29 Divide Two Integers
    • 30 Substring with Concatenation of All Words
    • 32 Longest Valid Parentheses
    • 33 Search in Rotated Sorted Array
    • 34 Search for a Range
    • 35 Search Insert Position
    • 36 Valid Sudoku
    • 37 Sudoku Solver
    • 38 Count and Say
    • 40 Combination Sum II
    • 41 First Missing Positive
    • 42 Trapping Rain Water
    • 43 Multiply Strings
    • 44 Wildcard Matching
    • 45 Jump Game II
    • 46 Permutations
    • 48 Rotate Image
    • 49 Group Anagrams
    • 53 Maximum Subarray
    • 54 Spiral Matrix
    • 59 Spiral Matrix II
    • 62 Unique Paths
    • 64 Minimum Path Sum
    • 66 Plus One
    • 67 Add Binary
    • 68 Text Justification
    • 69 Sqrt(x)
    • 70 Climbing Stairs
    • 71 Simplify Path
    • 73 Set Matrix Zeroes
    • 74 Search a 2D Matrix
    • 75 Sort Colors
    • 80 Remove Duplicates from Sorted Array II
    • 83 Remove Duplicates from Sorted List
    • 90 Subsets II
    • 91 Decode Ways
    • 99 Recover Binary Search Tree
    • 100 Same Tree
    • 103 Binary Tree Zigzag Level Order Traversal
    • 104 Maximum Depth of Binary Tree
    • 105 Construct Binary Tree from Preorder and Inorder Traversal
    • 112 Path Sum
    • 114 Flatten Binary Tree to Linked List
    • 119 Pascal's Triangle II
    • 120 Triangle
    • 128 Longest Consecutive Sequence
    • 129 Sum Root to Leaf Numbers
    • 133 Clone Graph
    • 136 Single Number
    • 137 Single Number II
    • 138 Copy List with Random Pointer
    • 144 Binary Tree Preorder Traversal
    • 146 LRU Cache
    • 148 Sort List
    • 150 Evaluate Reverse Polish Notation
    • 155 Min Stack
    • 157 Read N Characters Given Read4
    • 161 One Edit Distance
    • 162 Find Peak Element
    • 163 Missing Ranges
    • 167 Two Sum II - Input array is sorted
    • 168 Excel Sheet Column Title
    • 170 Two Sum III - Data structure design
    • 173 Binary Search Tree Iterator
    • 186 Reverse Words in a String II
    • 189 Rotate Array
    • 199 Binary Tree Right Side View
    • 200 Number of Islands
    • 202 Happy Number
    • 207 Course Schedule
    • 210 Course Schedule II
    • 214 Shortest Palindrome
    • 216 Combination Sum III
    • 217 Contains Duplicate
    • 221 Maximal Square
    • 226 Invert Binary Tree
    • 227 Basic Calculator II
    • 228 Summary Ranges
    • 229 Majority Element II
    • 230 Kth Smallest Element in a BST
    • 234 Palindrome Linked List
    • 236 Lowest Common Ancestor of a Binary Tree
    • 237 Delete Node in a Linked List
    • 239 Sliding Window Maximum
    • 240 Search a 2D Matrix II
    • 242 Valid Anagram
    • 243 Shortest Word Distance
    • 245 Shortest Word Distance III
    • 246 Strobogrammatic Number
    • 247 Strobogrammatic Number II
    • 253 Meeting Rooms II
    • 255 Verify Preorder Sequence in Binary Search Tree
    • 256 Paint House
    • 258 Add Digits
    • 260 Single Number III
    • 261 Graph Valid Tree
    • 263 Ugly Number
    • 264 Ugly Number II
    • 266 Palindromic Permutation
    • 270 Closest Binary Search Tree Value
    • 271 Encode and Decode Strings
    • 277 Find the Celebrity
    • 279 Perfect Squares
    • 280 Wiggle Sort
    • 281 Zigzag Iterator
    • 283 Move Zeroes
    • 284 Peeking Iterator
    • 285 Inorder Successor in BST
    • 286 Walls and Gates
    • 288 Unique Word Abbreviation
    • 290 Word Pattern
    • 292 Nim Game
    • 293 Flip Game
    • 296 Best Meeting Point
    • 297 Serialize and Deserialize Binary Tree
    • 298 Binary Tree Longest Consecutive Sequence
    • 301 Remove Invalid Parentheses
    • 304 Range Sum Query 2D - Immutable
    • 310 Minimum Height Trees
    • 311 Sparse Matrix Multiplication
    • 312 Burst Balloons
    • 313 Super Ugly Number
    • 315 Count of Smaller Numbers After Self
    • 316 Remove Duplicate Letters
    • 317 Shortest Distance from All Buildings
    • 319 Bulb Switcher
    • 322 Coin Change
    • 323 Number of Connected Components in an Undirected Graph
    • 326 Power of Three
    • 330 Patching Arrays
    • 333 Largest BST Subtree
    • 334 Increasing Triplet Subsequence
    • 335 Self Crossing
    • 338 Counting Bits
    • 340 Longest Substring with At Most K Distinct Characters
    • 344 Reverse String
    • 345 Reverse Vowels of a String
    • 346 Moving Average from Data Stream
    • 347 Top K Frequent Elements
    • 349 Intersection of Two Arrays
    • 356 Line Reflection
    • 357 Count Numbers with Unique Digits
    • 359 Logger Rate Limiter
    • 361 Bomb Enemy
    • 362 Design Hit Counter
    • 366 Find Leaves of Binary Tree
    • 367 Valid Perfect Square
    • 369 Plus One Linked List
    • 379 Design Phone Directory
    • 387 First Unique Character in a String
    • 389 Find the Difference
    • 394 Decode String
    • 395 Longest Substring with At Least K Repeating Characters
    • 396 Rotate Function
    • 399 Evaluate Division
    • 403 Frog Jump
    • 404 Sum of Left Leaves
    • 406 Queue Reconstruction by Height
    • 409 Longest Palindrome
    • 417 Pacific Atlantic Water Flow
    • 418 Sentence Screen Fitting
    • 422 Valid Word Square
    • 425 Word Squares
    • 434 Number of Segments in a String
    • 435 Non-overlapping Intervals
    • 438 Find All Anagrams in a String
    • 441 Arranging Coins
    • 445 Add Two Numbers II
    • 453 Minimum Moves to Equal Array Elements
    • 476 Number Complement
    • 482 License Key Formatting
    • 494 Target Sum
    • 496 Next Greater Element I
    • 500 Keyboard Row
    • 503 Next Greater Element II
    • 505 The Maze II
    • 506 Relative Ranks
    • 507 Perfect Number
    • 513 Find Bottom Left Tree Value
    • 514 Freedom Trail
    • 517 Super Washing Machines
    • 523 Continuous Subarray Sum
    • 530 Minimum Absolute Difference in BST
    • 531 Lonely Pixel I
    • 534 Design TinyURL
    • 545 Boundary of Binary Tree
    • 551 Student Attendance Record I
    • 554 Brick Wall
    • 563 Binary Tree Tilt
    • 567 Permutation in String
    • 572 Subtree of Another Tree
    • 604 Design Compressed String Iterator
    • 605 Can Place Flowers
    • 606 Construct String from Binary Tree
    • 624 Maximum Distance in Arrays
    • 630 Course Schedule III
    • 652 Find Duplicate Subtrees
    • 654 Maximum Binary Tree
    • 657 Judge Route Circle
    • 665 Non-decreasing Array
    • 669 Trim a Binary Search Tree
    • 672 Bulb Switcher II
    • 677 Map Sum Pairs
    • 681 Next Closest Time
    • 684 Redundant Connection
    • 686 Repeated String Match
    • 690 Employee Importance
    • 692 Top K Frequent Words
    • 212 Word Search II
    • 360 Sort Transformed Array
    • 616 Add Bold Tag in String
    • 318 Maximum Product of Word Lengths
    • 341 Flatten Nested List Iterator
    • 272 Closest Binary Search Tree Value II
    • 56 Merge Intervals
    • 215 Kth Largest Element in an Array
    • 98 Validate Binary Search Tree
    • 351 Android Unlock Patterns
    • 289 Game of Life
    • 575 Distribute Candies
    • 47 Permutations II
    • 267 Palindrome Permutation II
    • 308 Range Sum Query 2D - Mutable
    • 348 Design Tic-Tac-Toe
    • 68 Text Justification
    • 125 Valid Palindrome
    • 139 Word Break
    • 661 Image Smoother
    • 485 Max Consecutive Ones
    • 208 Implement Trie (Prefix Tree)
    • 140 Word Break II
    • 487 Max Consecutive Ones II
    • 61 Rotate List
    • 498 Diagonal Traverse
    • 231 Power of Two
    • 520 Detect Capital
    • 473 Matchsticks to Square
    • 127 Word Ladder
    • 251 Flatten 2D Vector
    • 244 Shortest Word Distance II
    • 245 Shortest Word Distance III
    • 423 Reconstruct Original Digits from English
    • 676 Implement Magic Dictionary
    • 332 Reconstruct Itinerary
    • 718 Maximum Length of Repeated Subarray
    • 172 Factorial Trailing Zeroes
    • 713 Subarray Product Less Than K
    • 36 Valid Sudoku
    • 752 Open the Lock
    • 65 Valid Number
    • 760 Find Anagram Mappings
    • 582 Kill Process
    • 594 Longest Harmonious Subsequence
    • 581 Shortest Unsorted Continuous Subarray
    • 599 Minimum Index Sum of Two Lists
    • 635 Design Log Storage System
    • 642 Design Search Autocomplete System
    • 379 Design Phone Directory
    • 295 Find Median from Data Stream
    • 232 Implement Queue using Stacks
    • 383 Ransom Note
    • 278 First Bad Version
    • 206 Reverse Linked List
    • 787 Cheapest Flights Within K Stops
    • 818 Race Car
    • Categorical
    • Array and Strings
      • Max Avg Number
      • Circular Array Cycle
      • Molecular Weight
      • Itoa
      • Average GPA
      • In Fibonacci Sequence
      • Shortest Rotated Distance
      • Sub-array Factor
      • Matrix Convolution
      • Add One to Array
      • Sum Two Arrays
      • Array Transformation
      • Unique Sub Arrays
      • Reverse and Simplify String
      • Reverse String
      • Information Masking
      • Minimum Array Reduction
      • Add Numbers in Unclean Data
      • Array Operations
      • Equilibrium Index
      • Visit All Places in Minimum Time
    • Linked List
      • Double Linked List Connected Components
    • Trees and Graphs
      • Directory Sum
      • Largest Subtree
      • Shortest Path DAG Source to Sink
      • HTML Parser
      • Infix to Postfix Expression Evaluater
      • Longest Path in Undirected Acyclic Graph
      • Decompress String
      • Pythagoras Tree
      • Kings
      • All Paths
      • Leaf Nodes
      • Proper Locking
      • Number of Cities at each Distance
      • Root Path as DLL
      • Binary Replacement
      • All Root to Leaf Paths
    • Recursion and Dynamic Programming
      • Recursive to_string
      • N Loop
      • Divisible by Set
      • Brute Force Seam Carving
      • Perimeter Island
      • Knight on a Phone
      • Coin Change Problem
      • Maximum Product in Matrix
      • Largest Sum of a Path in a Triangle
      • Linked List Tree
    • Sorting and Searching
      • Three Highest Numbers
      • Common Elements in Sorted Arrays
      • Inverse Spiral Matrix
      • Number Negatives in Sorted Matrix
      • Number of Bombs in Minesweeper
      • Two Sum Less Than
      • Frequency Compression
      • N Closest Points
      • Find Sum Pairs
      • Max with no Comparitor
      • Largest Subarray
      • Single Missing Number
      • Ternary Search
      • Fastest Frog Jump
    • Design
      • Random Hash DS
      • Road Trip
      • Load Balancer
      • Haircut Appointment Scheduler
      • Conway's Game of Life
      • Design Twitter
      • LogParser
      • Permission Management for a General Tree
      • Max Stack
      • Parking Lot
    • Probability
      • Simplified Blackjack
      • Rand7
      • Shuffle
    • Combinatorics
      • Binary Permutation
      • N Queens
      • Prefix Permutation
    • Mathematics
      • Angle Between Time
      • Line Segment Intersection
      • Maximum Points View Angle
      • Collatz Conjecture
      • Convex Hull
      • Swap In Place
      • Powers of 2
      • Monte Carlo Approximation of PI
      • Perfect Power
      • Derivative of a Polynomial
    • Bit Manipulation
      • Reverse Binary
    • Cryptography
      • Message Encyption and Decryption
      • Encryption
    • Other
      • Maximum Time Combination
      • Polish Notation String Calculator
  • Competition
    • CodeDavis
  • Project Eular
    • 1 Multiples of 3 and 5
    • 2 Even Fibonacci numbers
    • 3 Largest Prime Factor
    • 4 Largest Palindrome Product
    • 5 Smallest Multiple
    • 6 Sum Square Difference
    • 7 10001st Prime
    • 8 Largest Product in a Series
    • 9 Special Pythagorean Triplet
    • 10 Summation of Primes
    • 11 Largest Product in a Grid
    • 12 Highly Divisible Triangular Number
    • 13 Large Sum
    • 14 Longest Collatz Sequence
    • 15 Lattice Paths
    • 16 Power Digit Sum
    • 17 Number Letter Counts
    • 18 Maximum path sum I
    • 19 Counting Sundays
Powered by GitBook
On this page
  • Objective
  • Assignment
  • Steps
  • Submission

Was this helpful?

  1. LeetCode
  2. Design

Haircut Appointment Scheduler

Objective

The goal of the assignment is to assess your ability to write clear readable code demonstrating object oriented programming concepts.

Assignment

Create a command-line program in an object-oriented language of your choice (C++, Java, Python) that interacts with the user using stdin and stdout. You may use any standard libraries in your solution. The user of the program is a hairdresser who needs to keep track of his or her haircut appointments. The program will support the scheduling of two types of appointments:

  • Haircut: 30 minutes

  • Shampoo & Haircut: 1 hour

Upon running of the program, the program should prompt for user input. It should accept 3 command types: 1. List: listing of all future appointments 2. Schedule: schedules either type of appointment (note that this command may take additional parameters so that the hairdresser can distinguish one appointment from another). 3. Exit: the hairdresser is done with the program; upon exit, all existing state will be destroyed (i.e. the program does not persist the appointments in between program runs)

For simplicity sake, the program may assume that appointments are always scheduled at 15-minute offsets from the hour (e.g. 12:15pm, 4:00pm, 5:45pm, 6:30pm).

Steps

  1. Start by creating an object-oriented design for the scheduler interface (i.e. public methods) and

    the model classes for the schedule and the appointments.

  2. Implement the method that lists existing appointments.

  3. Implement the method that schedules a single appointment.

  4. Wire the program together so that it can be run from the command line.

Submission

Write a short README that lists the source files and a short description of each source file (e.g. Javadocs may be used in place of the description). In the README, also specify how to run the program and a log of one or more test runs of the program. If applicable, include any design considerations that came up during the design of the program. Respond to this email with a zip file of the README and the source files for your solution. Please do not post your solution to GitHub or another public repository.

// Scheduler.h

#pragma once
#include <iostream>
#include <string>
#include <unordered_map>

#ifdef DBUILD

#include <limits>
inline void pause() { cin.ignore(numeric_limits<streamsize>::max(), '\n'); }

template<typename T>
inline void print2d(vector<vector<T>> &stuffs) {
    cout << endl;
    int count = 0;
    for (auto i : stuffs) {
        cout << count++ << ":";
        for (auto j : i)
            cout << setw(2) << j << " ";
        cout << endl;
    }
    cout << endl;
}

template<typename T>
inline void print(vector<T> &stuffs) {
    cout << endl;
    for (auto i : stuffs) cout << i << " "; cout << endl; pause();
    cout << endl;
}
#endif


using namespace std;


struct Time {
    Time(short h, short m, bool morn) {
        hr = h; min = m;
        morning = morn;
    }

    Time(short h, short m) {
        hr = h; min = m;
    }

    Time() { hr = min = 0; }

    Time(const Time &rhs)
    {
        hr = rhs.hr;
        min = rhs.min;
        morning = rhs.morning;
    }

    friend Time operator+(const Time &one, const Time &two);
    void operator +=(const Time& rhs);
    bool operator==(const Time &other) const;
    void operator=(const Time &rhs);

    short hr, min;
    bool morning;
};

Time operator+(const Time &one, const Time &two) {
    // add both minutes
    short min_total = one.min + two.min;
    short hr_carry = min_total / 60;
    short min_remaining = min_total - (hr_carry * 60);
    short total_hours = hr_carry + one.hr + two.hr;

    short number_flips = total_hours / 12;
    bool morn = one.morning;
    // odd indicates opposite daylight hrs
    if (number_flips % 2 != 0 && total_hours >= 12)
        morn = !one.morning;

    return Time((total_hours > 12) ? total_hours % 12 : total_hours, min_remaining, morn);
}

void Time::operator+=(const Time & rhs)
{
    // add both minutes
    short min_total = rhs.min + min;
    short hr_carry = min_total / 60;
    short min_remaining = min_total - (hr_carry * 60);
    short total_hours = hr_carry + rhs.hr + hr;

    short number_flips = total_hours / 12;

    hr = total_hours % 12;
    min = min_remaining;

    // odd indicates opposite daylight hrs
    if (number_flips % 2 != 0 && total_hours > 12)
        morning = !morning;
}

inline bool Time::operator==(const Time & other) const
{
    return (hr == other.hr && min == other.min
        && morning == other.morning);
}

inline void Time::operator=(const Time & rhs)
{
    hr = rhs.hr;
    min = rhs.min;
    morning = rhs.morning;
}

/* hash function */
namespace std {
    template <>
    struct hash<Time>
    {
        std::size_t operator()(const Time& k) const
        {
            return ((hash<short>()(k.hr)
                ^ (hash<short>()(k.min) << 1)) >> 1)
                ^ (hash<bool>()(k.morning) << 1);
        }
    };
}


struct Activity {
    Activity(string activity) {
        this->activity = activity;
    }

    bool active = false;
    string activity;
};


class Scheduler
{
public:
    Scheduler() 
    {
        Time start(12,0,1);             // 12:00am
        Time incrementor;               // 00:00
        Time static_incrementor(0, 15); // 00:15

        // creates an empty schedule
        // there are 96, 15 min intervals from 12:00am to 11:45pm
        for (int i = 0; i < 48; i++) {
            Time newTime(start + incrementor);
            newTime.morning = true;
            //cout << newTime.hr << ":" << newTime.min << newTime.morning << endl;
            schedule.insert(make_pair(Time(newTime.hr, newTime.min, newTime.morning), 
                            Activity("")));
            incrementor += static_incrementor;
        }

        Time start2(12, 0, 0); // 12:00pm
        Time incrementor2;     // 00:00
        for (int i = 0; i < 48; i++) {
            Time newTime(start2 + incrementor2);
            newTime.morning = false;
            //cout << newTime.hr << ":" << newTime.min << newTime.morning << endl;

            schedule.insert(make_pair(Time(newTime.hr, newTime.min, newTime.morning),
                            Activity("")));
            schedule.insert(make_pair(newTime, Activity("")));
            incrementor2 += static_incrementor;
        }
    };

    vector<string> appointmentTimes()
    {
        return activeAppoint;
    }

    bool appointHaircut(Time &time, const string activity) 
    {
        // check confliction
        if (schedule.find(time)->second.active) return true;

        // 30 min - add to schedule
        Time incrementor(0, 0);
        const Time incrementor_static(0, 15);
        for (int i = 0; i < 2; i++) {
            Time hashTime(time + incrementor);
            schedule.find(hashTime)->second.active = true;
            schedule.find(hashTime)->second.activity = activity;
            incrementor += incrementor_static;
        }
        // add to active schedule
        addAppointment(time, activity);
        return false;
    }

    bool appointShampooAndHairCut(Time &time, const string activity)
    {
        // check confliction
        if (schedule.find(time)->second.active) return true;

        // 1 hr
        Time incrementor(0, 0);
        const Time incrementor_static(0, 15);
        for (int i = 0; i < 4; i++) {
            Time hashTime(time + incrementor);
            schedule.find(hashTime)->second.active = 1;
            schedule.find(hashTime)->second.activity = activity;
            incrementor += incrementor_static;
        }
        // add to active schedule
        addAppointment(time, activity);
        return false;
    }

    bool isEmpty() 
    {
        return schedule.empty();
    }

private:
    unordered_map<Time, Activity> schedule;
    vector<string> activeAppoint;

    void addAppointment(Time &time, const string &activity)
    {
        string appointment;
        // formating to 2 digits: e.g. 9:[00]am
        if (time.min <= 9) {
            appointment = "  " + to_string(time.hr) + ":" +
                + "0" + to_string(time.min) + std::string((time.morning) ? ("am") : ("pm")) +
                std::string(" - ") +
                std::string((activity == "shampoo") ? ("shampoo & haircut") : (activity));;
        }
        else {
            appointment = "  " + to_string(time.hr) + ":" +
                to_string(time.min) + std::string((time.morning) ? ("am") : ("pm")) +
                std::string(" - ") + 
                std::string((activity == "shampoo") ? ("shampoo & haircut") : (activity));
        }

        activeAppoint.push_back(appointment);
    }
};

// Source.cpp

#include <iostream>
#include <string>
#include <vector>
#include <cctype>       //tolower()
#include <sstream>        //stringstream
#include "Scheduler.h"


using namespace std;

string toLower(string);
bool isIntegral(string &);
vector<string> split(const string&, char);
bool isValid(const vector<string> &);
Time getTime(const string &);


int main()
{
    string input;
    bool invalid, exit = false;
    Scheduler schedule;
    //input = "schedule shampoo & haircut 7:30pm";

    while (!exit) {
        cout << "\n> ";
        getline(cin, input);
        input = toLower(input);
        vector<string> commands = split(input, ' ');

        if (!isValid(commands)) {
            cout << "  Input command is invalid. Please try again" << endl;
            continue;
        }

        if (commands[0] == "exit") {
            exit = true;
            continue;
        }
        else if (commands[0] == "list") {
            if (schedule.isEmpty()) {
                cout << "No appointments at this time." << endl;
            }
            else {
                vector<string> appointments = schedule.appointmentTimes();
                for (string & s : appointments)
                    cout << s << endl;
                continue;
            }
        }
        // is a scheduling command
        else {
            // ensure time is properly formated
            Time appointment = (getTime(commands[commands.size() - 1]));
            //cout << getTime(commands[commands.size() - 1]).morning << endl;
            bool conflict;
            if (appointment.hr == 0 && appointment.min == 0) {
                cout << "  Appointment time has invalid format. Please try again" << endl;
                continue;
            }
            else if (commands[1] == "haircut") {
                conflict = schedule.appointHaircut(appointment, "haircut");
                if (conflict) cout << "  There is an conflict with appointment time." << endl;
            }
            else if (commands[1] == "shampoo") {
                conflict = schedule.appointShampooAndHairCut(appointment, "shampoo");
                if (conflict) cout << "  There is an conflict with appointment time." << endl;
            }
        }
    }
}



string toLower(string str)
{
    for (char& c : str)
        c = tolower(c);

    return str;
}

bool isIntegral(string &num) 
{
    for (char& c : num) {
        if (!isdigit(c)) return false;
    }
    return true;
}

vector<string> split(const string &s, char delim)
{
    vector<string> elems;
    stringstream ss;
    ss.str(s);
    string item;
    while (getline(ss, item, delim)) {
        elems.push_back(item);
    }
    return elems;
}

bool isValid(const vector<string> &commands)
{
    // no command or too many
    if (commands.empty() || commands.size() > 5) return false;
    // list or exit
    else if (commands.size() == 1) {
        return ((commands[0]) == "list" || 
                (commands[0]) == "exit");
    }
    // schedule
    else {
        // haircut
        if (commands.size() == 3)
            return ((commands[0]) == "schedule" && 
                    (commands[1]) == "haircut");
        else {
            // haircut and shampoo
            return ((commands[0]) == "schedule" &&
                    (commands[1]) == "shampoo" &&
                    (commands[2]) == "&" &&
                    (commands[3]) == "haircut");    
        }
    }
    return false;
}

Time getTime(const string &str)
{
    // XX:XXam or X:XXpm
    if (str.length() < 6 || str.length() > 7) return Time();
    int colon_index = 0;
    for (int i = 0; i < str.size(); i++) {
        if (str[i] == ':') {
            colon_index = i;
            break;
        }
    }

    string daylight = str.substr(str.size() - 2, str.size());
    if (!(daylight == "am" || daylight == "pm")) return Time();
    if (colon_index == 1) {
        string one = str.substr(0, 1);
        if (isIntegral(one) && isIntegral(str.substr(2, 2))) {
            int hr = atoi(str.substr(0, 1).c_str());
            int min = atoi(str.substr(2, 2).c_str());

            // valid minutes and hour and 15 min interval
            bool test = (daylight == "am") ? (true) : (false);
            if ((hr >= 1 && hr <= 12 ) && (min >= 0 && min <= 59) && min % 15 == 0)
                return Time(hr, min, test);
        }
    }
    else if (colon_index == 2) {
        if (isIntegral(str.substr(0, 2)) && isIntegral(str.substr(3, 2))) {
            int hr = atoi(str.substr(0, 2).c_str());
            int min = atoi(str.substr(3, 2).c_str());

            if ((hr >= 1 && hr <= 12) && (min >= 0 && min <= 59) && min % 15 == 0)
                return Time(hr, min, (daylight == "am") ? (true) : (false));
        }
    }

    return Time(); // 00:00
}
PreviousLoad BalancerNextConway's Game of Life

Last updated 5 years ago

Was this helpful?