Prolog Cheat Sheet

Create a Pull Request. When your Instant Answer is ready for an initial review, create a pull request.Be sure to paste the link to this Instant Answer page in the PR description.

This blog post is a coding and system design interview cookbook/cheatsheet compiled by me with code pieces written by me as well. There is no particular structure nor do I pretend this to be a comprehensive guide. Also there are no explanations as the purpose is just to list important things. Moreover, this blog post is work-in-progress as I’m planning to add more things to it.

As always, opinions are mine.

Binary Search

  1. Prolog: Logic programming systems allow the programmer to state a collection of axioms from which theorems can be proven. The user of a logic program states a goal, and the language implementation attempts to find a collection of axioms and inference steps that together imply the goal. Axiomatic semantics each statement or expression is a predicate transformer (inference rule with conditions.
  2. Download the cheat sheet for all things technology at Wartburg Seminary by clicking here. Learning Accomodations Incoming students, please contact Professor Ann Fritschel ( afritschel@wartburgseminary.edu ) to set up a meeting about your documented learning accommodations or if you have questions related to learning accommodations.

Breadth First Search

Depth First Search

Just replace the queue in BFS with stack and you are done:

Backtracking

Generally a recursive algorithm attempting candidates and either accepting them or rejecting (“backtracking”) based on some condition. Below is an example of permutations generation using backtracking:

Dynamic Programming

Technique to determine result using previous results. You should be able to reason about your solution recursively and be able to deduce dp[i] using dp[i-1]. Generally you would have something like this:

Dynamic Programming: Knapsack

Union Find

When you need to figure out if something belongs to the same set you can use the following:

Binary Tree Traversals

  • Inorder: left-root-right
  • Postorder: left-rigth-root
  • Preorder: root-left-right
  • Plus each one of them could have reverse for right and left

Below are recursive and iterative versions of inorder traversal

Segment Tree

Djikstra

Simplest way to remember Djikstra is to imagine it as BFS over PriorityQueue instead of normal Queue, where values in queue are best distances to nodes pending processing.

Sheet

Prolog Programming Language Pdf

Multi-threading: Semaphore

Multi-threading: Runnable & synchronized

Strings: KMP

Hopefully no one asks you this one. It would be too much code here, but the idea is not that difficult: build LPS (example “AAABAAA” -> [0,1,2,0,1,2,3]); use LPS to skip when comparing as if you were doing it in brute-force.

Strings: Rolling Hash (Rabin-Karp)

Let’s imagine we have window of length k and string s, then the hash for the first window will be:

H(k) = s[0]*P^(k-1) + s[1]*P^(k-2) + … + s[k]*P^0

Moving the window by one, would be O(1) operation:

H(k+1) = (H(k) – s[0]*P^(k-1)) * P + s[k+1]*P^0

Here is some sample code:

Unit Testing

JUnit User guide: https://junit.org/junit5/docs/current/user-guide/

Data Structures

Many interview problems can be solved by using right data structure.

  • hashmap
  • stack
  • queue
  • priority queue
  • trees
  • linked list
  • Actually, better to go here: https://www.geeksforgeeks.org/data-structures/

System Design Topics

  • requirements gathering
  • capacity planning
  • high level design
  • components design
  • database design
  • API design
  • queue
  • map reduce
  • long poll and push models
  • load balancing
  • partitioning
  • replication
  • consistency
  • caching
  • distributed caching
  • networking

Some System Design Problems

Prolog Cheat Sheet
  • TinyURL
    • Coming up with good encoding or better pre-building keys
    • Handling collisions (if encoding or if different users have to have different key)
    • Use distributed caching, CDN, LB
    • Consider API throttling, eviction (maybe not), capacity
    • HTTP 302
  • Pastebin
    • Separate data from metadata and store separately
    • Otherwise similar to TinyURL
  • Instagram
    • Data partitioning is important here
    • Pull vs push (via long polling) applied based on number of following
    • Separate servers for viewing and posting for stability
    • Generating feed of images requires sorting, consider timestamp for photoId
  • Dropbox
    • Client and Server
    • Splitting files into chunks
    • Saving metadata about chunks
    • Local metadata database for the client
    • Queues for load handling
    • Data deduplication (user has same file in 100 places)
  • Facebook Messenger
    • poll vs push model with long polling
    • push notifications
    • Dedicate chat servers per user
    • “seeing into the future” problem solving with seq number
    • active status
  • Twitter
    • prebuild feed
    • handle celebrities differently
    • caching
    • monitoring
  • Youtube or Netflix
    • Splitting files into chunks (time and quality) via MapReduce
    • Distribution of content
    • Thumbnail generator & distribution
    • Store metadata separately (likes, views, comments, etc)
    • CDN
  • Typeahead Suggestion
    • Trie
    • For frequencies store them in nodes with suggestions
    • Propagate suggestions independently from queries (mapreduce)
    • Client implementation should delay request allowing for typing
    • Client having local history
  • API Rate Limiter
    • DDoS
    • Client identifier
    • Sliding window with counters
    • HTTP 429
  • Web Crawler
    • BFS
  • Facebook’s Newsfeed
    • Different feed components stored separately but joined
  • Yelp
    • Quad-Tree
  • Uber
    • Dynamic Quad-Tree
    • HashMap
  • Ticketmaster
    • Relational DB design
    • Concurrency handling

Resources

Well, internet is just full of all kinds of resources and blog posts on how to prepare for the technical interview plus there are numerous books and websites available. LeetCode is probably the most known of practicing websites. “Cracking The Coding Interview” is probably the most known book. I can also recommend “Guide to Competitive Programming”. As of system design, preparation resources are not so readily available. One good resource is “Grokking System Design Interview”, but it would be more valuable to practice designing large distributed systems. I also found the book “Designing Data-Intensive Applications” to be extremely helpful.

Asking for help

What are other “must know” algorithms and important system design topics to be listed in this post?

PROLOG (PROgramming in LOGic) - Cheat SheetProlog list operations

Prolog Programming Pdf

Under construction ...

Prolog originated in France [University of Marseilles(Prolog : Manuel de Reference et d'Utilisation by P. Roussel,Groupe d'Intelligence Artificielle, Marseille-Luminy, 1975]as a language for deductively analyzing logical arguments.

List Prolog

Its implementation makes it a relatively simple tool for parsingproblems which can be phrased in terms of relations which havea natural representation as tree structures.Two easily appreciated examples are - genealogy andEnglish grammar.

It also has a powerful unification mechanism which allows quickprototyping of ``template' or ``pattern matching' systems.

Here are three distinct ways of describing the form and actions of aProlog program. (Other interpretations are also useful.)

  • Procedure view
  • Logic view
  • Data view

Prolog Cheat Sheet Printable

Like normal imperative programming languages, a Prolog programconsists of procedures, which are collections of statements.A program is executed by running a sequence of statements.Each of these statements executes by 'calling' a procedure, which callsother procedures, etc.

A Prolog program consists of a collection of theorems (or rules)and axioms (its assertions). Running a program consists of askinga query (a set of 'goals') to see if it is provable fromthe axioms by using the existing theorems.

Prolog Cheat Sheet Pdf

  • Assertions aka Unit Clauses

    Examples of some assertions:

  • Theorems
  • Queries

    To determine what can be 'proved' from the given assertions andtheorems, a user issues a query:

  • Nonground Queries (aka goals).

    The above are examples of ground queries, meaning there areno variables in the goal. Variables (anything which begins withan upper case letter) can be used instead.

    Because of its 'pattern matching/unification' mechanismfor binding actual arguments to formal arguments,Prolog provides a quick way to retrieve informationstored in the fact base.

    Consider the facts of before:

    These can be considered simply as either data structures,or access procedures to extract information from thesestructures.

    Unit clauses can be thought of as data structures andprocedures can be thought of as rules for extractingdata which is not hard-wired as a fact.

    Basic Definitions
    TermDefinition
    statementone of fact, rule, or query
    fact (cf.unit clause)record (cf.data model) of assumed true information
    rule (cf.predicate)deductive formulation whereby new facts can be inferred from existing facts
    querya statement asking about the existence of a fact(s)
    logic programcollection of rules
    meaning of a logic programcollection of facts that can be deduced from any set of initial facts

    Basic Lexical Elements
    EntityExamples
    atomhomer 1.5 'plan-9' 'My name is Nobody'
    operators (are also atoms)+ - :- < >
    symbol - atoms are a special case of symbol32
    string (is not a defined data type in PROLOG, but really a list of ASCII values)'Joe Friday' 'Son of Sam'
    variable - identifier beginning with uppercase letter or underscoreX Xs Joes_IQ _total

    Under construction ...

    Basic Syntactic Elements - have meaning according to position
    EntityExplanationExamples
    listseries of terms[Name1, Name2 | Names]

    Basic Control Elements
    Task to AccomplishCommandsComments
    starting PROLOG - at Unix $> prompt$> plOn ICC machines, your path variable must contain /usr/local/bin for this to work. Get help changing your .cshrc file if necessary.
    stopping PROLOG - at | ?- prompt| ?- halt.
    consultation mode from terminalconsult(user)User controls logical and data operation.
    consultation mode from fileconsult(<filename>)User controls logical operation, but data are in file.
    asserting factsassert(<term>)User controls data operation.
    retracting factsretract(<rule-head>)User controls data operation.

    PROLOG - Description Of Common Predicates
    Notation - parameters prefixed by:
    Loading files
    predicateexamples
    consult(+Files)
    reconsult(+Files)
    Control
    predicateexamples
    abortabort
    halthalt.
    Terms
    predicateexamples
    var(?Term)
    nonvar(?Term)
    ?Term1 = ?Term2
    functor(?Term, ?Name, ?Arity)
    ?Term =.. ?List
    length(?List, ?Length)
    name(?Atom, ?Chars)
    Term Comparison
    predicateexamples
    ?Term1 ?Term2
    ?Term1 ?Term2
    Arithmetic
    predicateexamples
    ?Varis+Expression
    Arithmetic Operators
    operator(s) (infix predicate name)meaning
    + - *overloaded floating point and integer operations
    / //floating point and integer division, respectively
    remmodremainder and modulo operations, respectively
    Arithmetic relational Operators
    operator(s) (infix predicate name)meaning
    < =< > >= =:=relationships between two numeric expressions
    Input/Output
    predicateexamples
    read(-Term)
    write(?Term)
    I/O of Sentences extensions necessary for parsing natural language constructs.
    predicatenotes
    read_sentence(-ListOfAtoms) May have to be modified to handle special lexical constraints.
    write_sentence(+ListOfAtoms)
    Clause Database
    predicateexamples
    assert(+Clause)
    asserta(+Clause) note: extra parentheses required for clause with a body. This will be the most usual version for our purposes.
    assertz(+Clause) Add assertion at bottom of search path - will be found last.
    clause(+Head,?Body)
    retract(+Clause) Retract the clause matching Clause
    retractall(+Head) Retract all clauses with head matching Head E.g., retractall(stuff(_)). erases all clauses of predicate stuff/1
    abolish(+Predicates) Abolish all clauses with head matching any in the list Predicates E.g., abolish(stuff/1). erases all clauses of predicate stuff/1 and makes predicate stuff/1 unknown
    Sets and Bags
    predicateexamples
    setof(?Template,+Generator,-Set)
    member(+Term,+List)
    nonmember(+Term,+List)
    make_set(+List1,-List2) Remove duplicates from List1.
    delete(+Term,+List1,-List2) Remove item Term from List1.
    insert(+Term,+List1,-List2) Add item Term to List1.
    subset(+List1,+List2) Is List1 a subset of List2?
    equal(+List1,+List2) Do List1 and List2 have same elements?
    difference(+List1,+List2,-List3) Remove items in List2 from List1 (set difference).
    union(+List1,+List2,-List3) Add items in List2 to List1 (set union).
    append(+List1,+List2,-List3) Add items in List2 to List1 (duplicates are presered).
    nth(+List,+Number,+Term) Get nth item in a list.
    Useful extensions to the built-in predicates. (source code)

    Useful Extensions.(Some Prolog implementations have most of these built-in.)

    Under construction ...

    Note, most of these are built-in to our versionof Prolog and you should NOT re-write them. Test first!