You are on page 1of 51

Algorithms For Dummies (For Dummies

(Computer/Tech)) 2nd Edition Mueller


Visit to download the full and correct content document:
https://ebookmass.com/product/algorithms-for-dummies-for-dummies-computer-tech-
2nd-edition-mueller/
Algorithms
2nd Edition

by John Paul Mueller and Luca Massaron


Algorithms For Dummies®, 2nd Edition
Published by: John Wiley & Sons, Inc., 111 River Street, Hoboken, NJ 07030-5774, www.wiley.com

Copyright © 2022 by John Wiley & Sons, Inc., Hoboken, New Jersey

Media and software compilation copyright © 2022 by John Wiley & Sons, Inc. All rights reserved.

Published simultaneously in Canada

No part of this publication may be reproduced, stored in a retrieval system or transmitted in any form or by any
means, electronic, mechanical, photocopying, recording, scanning or otherwise, except as permitted under Sections
107 or 108 of the 1976 United States Copyright Act, without the prior written permission of the Publisher. Requests to
the Publisher for permission should be addressed to the Permissions Department, John Wiley & Sons, Inc., 111 River
Street, Hoboken, NJ 07030, (201) 748-6011, fax (201) 748-6008, or online at http://www.wiley.com/go/permissions.

Trademarks: Wiley, For Dummies, the Dummies Man logo, Dummies.com, Making Everything Easier, and related
trade dress are trademarks or registered trademarks of John Wiley & Sons, Inc. and may not be used without written
permission. All other trademarks are the property of their respective owners. John Wiley & Sons, Inc. is not
associated with any product or vendor mentioned in this book.

LIMIT OF LIABILITY/DISCLAIMER OF WARRANTY: WHILE THE PUBLISHER AND AUTHORS HAVE USED THEIR
BEST EFFORTS IN PREPARING THIS WORK, THEY MAKE NO REPRESENTATIONS OR WARRANTIES WITH RESPECT
TO THE ACCURACY OR COMPLETENESS OF THE CONTENTS OF THIS WORK AND SPECIFICALLY DISCLAIM ALL
WARRANTIES, INCLUDING WITHOUT LIMITATION ANY IMPLIED WARRANTIES OF MERCHANTABILITY OR
FITNESS FOR A PARTICULAR PURPOSE. NO WARRANTY MAY BE CREATED OR EXTENDED BY SALES
REPRESENTATIVES, WRITTEN SALES MATERIALS OR PROMOTIONAL STATEMENTS FOR THIS WORK. THE FACT
THAT AN ORGANIZATION, WEBSITE, OR PRODUCT IS REFERRED TO IN THIS WORK AS A CITATION AND/OR
POTENTIAL SOURCE OF FURTHER INFORMATION DOES NOT MEAN THAT THE PUBLISHER AND AUTHORS
ENDORSE THE INFORMATION OR SERVICES THE ORGANIZATION, WEBSITE, OR PRODUCT MAY PROVIDE OR
RECOMMENDATIONS IT MAY MAKE. THIS WORK IS SOLD WITH THE UNDERSTANDING THAT THE PUBLISHER IS
NOT ENGAGED IN RENDERING PROFESSIONAL SERVICES. THE ADVICE AND STRATEGIES CONTAINED HEREIN
MAY NOT BE SUITABLE FOR YOUR SITUATION. YOU SHOULD CONSULT WITH A SPECIALIST WHERE APPROPRIATE.
FURTHER, READERS SHOULD BE AWARE THAT WEBSITES LISTED IN THIS WORK MAY HAVE CHANGED OR
DISAPPEARED BETWEEN WHEN THIS WORK WAS WRITTEN AND WHEN IT IS READ. NEITHER THE PUBLISHER
NOR AUTHORS SHALL BE LIABLE FOR ANY LOSS OF PROFIT OR ANY OTHER COMMERCIAL DAMAGES, INCLUDING
BUT NOT LIMITED TO SPECIAL, INCIDENTAL, CONSEQUENTIAL, OR OTHER DAMAGES.

For general information on our other products and services, please contact our Customer Care Department within
the U.S. at 877-762-2974, outside the U.S. at 317-572-3993, or fax 317-572-4002. For technical support, please visit
https://hub.wiley.com/community/support/dummies.

Wiley publishes in a variety of print and electronic formats and by print-on-demand. Some material included with
standard print versions of this book may not be included in e-books or in print-on-demand. If this book refers to
media such as a CD or DVD that is not included in the version you purchased, you may download this material at
http://booksupport.wiley.com. For more information about Wiley products, visit www.wiley.com.

Library of Congress Control Number: 2022934261

ISBN: 978-1-119-86998-6; 978-1-119-86999-3 (ebk); 978-1-119-87000-5 (ebk)


Contents at a Glance
Introduction. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1

Part 1: Getting Started with Algorithms. . . . . . . . . . . . . . . . . . . . . . . . 7


CHAPTER 1: Introducing Algorithms . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9
CHAPTER 2: Considering Algorithm Design. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 23
CHAPTER 3: Working with Google Colab. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 41
CHAPTER 4: Performing Essential Data Manipulations Using Python. . . . . . . . . . . . . . 59
CHAPTER 5: Developing a Matrix Computation Class. . . . . . . . . . . . . . . . . . . . . . . . . . . 79

Part 2: Understanding the Need to Sort and Search . . . . . . . . 97


CHAPTER 6: Structuring Data . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 99
CHAPTER 7: Arranging and Searching Data. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 117

Part 3: Exploring the World of Graphs . . . . . . . . . . . . . . . . . . . . . . . 139


CHAPTER 8: Understanding Graph Basics . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 141
CHAPTER 9: Reconnecting the Dots. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 161
CHAPTER 10: Discovering Graph Secrets . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 195
CHAPTER 11: Getting the Right Web page . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 207

Part 4: Wrangling Big Data. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 223


CHAPTER 12: Managing Big Data. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 225
CHAPTER 13: Parallelizing Operations. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 249
CHAPTER 14: Compressing and Concealing Data. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 267

Part 5: Challenging Difficult Problems. . . . . . . . . . . . . . . . . . . . . . . 289


CHAPTER 15: Working with Greedy Algorithms. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 291
CHAPTER 16: Relying on Dynamic Programming . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 307
CHAPTER 17: Using Randomized Algorithms. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 331
CHAPTER 18: Performing Local Search. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 349
CHAPTER 19: Employing Linear Programming. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 367
CHAPTER 20: Considering Heuristics. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 381

Part 6: The Part of Tens. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 401


CHAPTER 21: Ten Algorithms That Are Changing the World. . . . . . . . . . . . . . . . . . . . . 403
CHAPTER 22: Ten Algorithmic Problems Yet to Solve. . . . . . . . . . . . . . . . . . . . . . . . . . . 411

Index. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 417
Table of Contents
INTRODUCTION . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1
About This Book. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1
Foolish Assumptions. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3
Icons Used in This Book. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3
Beyond the Book. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4
Where to Go from Here . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5

PART 1: GETTING STARTED WITH ALGORITHMS . . . . . . . . . . . . . 7


CHAPTER 1: Introducing Algorithms. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9

Describing Algorithms . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10
The right way to make toast: Defining algorithm uses . . . . . . . . . . 12
Finding algorithms everywhere. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 14
Using Computers to Solve Problems . . . . . . . . . . . . . . . . . . . . . . . . . . . . 15
Getting the most out of modern CPUs and GPUs . . . . . . . . . . . . . . 16
Working with special-purpose chips. . . . . . . . . . . . . . . . . . . . . . . . . . 17
Networks: Sharing is more than caring . . . . . . . . . . . . . . . . . . . . . . . 18
Leveraging available data. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 18
Distinguishing between Issues and Solutions. . . . . . . . . . . . . . . . . . . . . 19
Being correct and efficient. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 19
Discovering there is no free lunch . . . . . . . . . . . . . . . . . . . . . . . . . . . 20
Adapting the strategy to the problem . . . . . . . . . . . . . . . . . . . . . . . . 20
Describing algorithms in a lingua franca. . . . . . . . . . . . . . . . . . . . . . 20
Facing problems that are like brick walls, only harder. . . . . . . . . . . 21
Structuring Data to Obtain a Solution . . . . . . . . . . . . . . . . . . . . . . . . . . . 21
Understanding a computer’s point of view. . . . . . . . . . . . . . . . . . . . 22
Arranging data makes the difference. . . . . . . . . . . . . . . . . . . . . . . . . 22

CHAPTER 2: Considering Algorithm Design . . . . . . . . . . . . . . . . . . . . . . . . . 23


Starting to Solve a Problem. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 24
Modeling real-world problems . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 25
Finding solutions and counterexamples . . . . . . . . . . . . . . . . . . . . . . 26
Standing on the shoulders of giants. . . . . . . . . . . . . . . . . . . . . . . . . . 27
Dividing and Conquering . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 28
Avoiding brute-force solutions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 29
Keeping it simple, silly (KISS) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 29
Breaking down a problem is usually better. . . . . . . . . . . . . . . . . . . . 30
Learning that Greed Can Be Good . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 30
Applying greedy reasoning. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .31
Reaching a good solution. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 31
Computing Costs and Following Heuristics. . . . . . . . . . . . . . . . . . . . . . . 32

Table of Contents v
Representing the problem as a space . . . . . . . . . . . . . . . . . . . . . . . . 33
Going random and being blessed by luck. . . . . . . . . . . . . . . . . . . . . 34
Using a heuristic and a cost function. . . . . . . . . . . . . . . . . . . . . . . . . 34
Evaluating Algorithms. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 35
Simulating using abstract machines. . . . . . . . . . . . . . . . . . . . . . . . . . 36
Getting even more abstract. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 37
Working with functions. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 38

CHAPTER 3: Working with Google Colab. . . . . . . . . . . . . . . . . . . . . . . . . . . . . 41


Defining Google Colab . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 42
Understanding what Google Colab does. . . . . . . . . . . . . . . . . . . . . . 42
Getting familiar with Google Colab features. . . . . . . . . . . . . . . . . . . 44
Working with Notebooks . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 47
Creating a new notebook. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 47
Opening existing notebooks . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 47
Saving notebooks . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 50
Performing Common Tasks. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 51
Creating code cells . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 52
Creating text cells . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 54
Creating special cells. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 54
Editing cells. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 55
Moving cells . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 55
Using Hardware Acceleration . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 55
Executing the Code. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 56
Getting Help. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 57

CHAPTER 4: Performing Essential Data Manipulations


Using Python . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 59
Performing Calculations Using Vectors and Matrixes . . . . . . . . . . . . . . 60
Understanding scalar and vector operations . . . . . . . . . . . . . . . . . . 61
Performing vector multiplication . . . . . . . . . . . . . . . . . . . . . . . . . . . . 63
Creating a matrix is the right way to start. . . . . . . . . . . . . . . . . . . . . 63
Multiplying matrixes. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 64
Defining advanced matrix operations . . . . . . . . . . . . . . . . . . . . . . . . 65
Creating Combinations the Right Way. . . . . . . . . . . . . . . . . . . . . . . . . . . 67
Distinguishing permutations. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 68
Shuffling combinations. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 69
Facing repetitions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 70
Getting the Desired Results Using Recursion . . . . . . . . . . . . . . . . . . . . . 71
Explaining recursion. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 71
Eliminating tail call recursion. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 74
Performing Tasks More Quickly . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 75
Considering divide and conquer. . . . . . . . . . . . . . . . . . . . . . . . . . . . . 75
Distinguishing between different possible solutions. . . . . . . . . . . . 78

vi Algorithms For Dummies


CHAPTER 5: Developing a Matrix Computation Class . . . . . . . . . . . . . 79
Avoiding the Use of NumPy. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 80
Understanding Why Using a Class is Important. . . . . . . . . . . . . . . . . . . 81
Building the Basic Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 82
Creating a matrix. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 83
Printing the resulting matrix . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 84
Accessing specific matrix elements . . . . . . . . . . . . . . . . . . . . . . . . . . 85
Performing scalar and matrix addition . . . . . . . . . . . . . . . . . . . . . . . 86
Performing multiplication . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 87
Manipulating the Matrix. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 90
Transposing a matrix . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 91
Calculating the determinant . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 91
Flattening the matrix. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 95

PART 2: UNDERSTANDING THE NEED


TO SORT AND SEARCH . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 97
CHAPTER 6: Structuring Data. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 99

Determining the Need for Structure. . . . . . . . . . . . . . . . . . . . . . . . . . . .100


Making it easier to see the content. . . . . . . . . . . . . . . . . . . . . . . . . . 100
Matching data from various sources . . . . . . . . . . . . . . . . . . . . . . . . 101
Considering the need for remediation. . . . . . . . . . . . . . . . . . . . . . . 102
Stacking and Piling Data in Order. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 105
Ordering in stacks. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 105
Using queues. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 107
Finding data using dictionaries. . . . . . . . . . . . . . . . . . . . . . . . . . . . . 108
Working with Trees. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 109
Understanding the basics of trees . . . . . . . . . . . . . . . . . . . . . . . . . . 109
Building a tree . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 110
Representing Relations in a Graph. . . . . . . . . . . . . . . . . . . . . . . . . . . . . 112
Going beyond trees. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 113
Building graphs . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 114

CHAPTER 7: Arranging and Searching Data . . . . . . . . . . . . . . . . . . . . . . . 117


Sorting Data Using Merge Sort and Quick Sort. . . . . . . . . . . . . . . . . . . 118
Understanding why sorting data is important . . . . . . . . . . . . . . . . 118
Employing better sort techniques. . . . . . . . . . . . . . . . . . . . . . . . . . . 122
Using Search Trees and the Heap. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 127
Considering the need to search effectively. . . . . . . . . . . . . . . . . . . 127
Building a binary search tree. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 129
Performing specialized searches using a binary heap. . . . . . . . . . 131
Relying on Hashing . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 132
Putting everything into buckets. . . . . . . . . . . . . . . . . . . . . . . . . . . . . 132
Avoiding collisions. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 134
Creating your own hash function . . . . . . . . . . . . . . . . . . . . . . . . . . . 135

Table of Contents vii


PART 3: EXPLORING THE WORLD OF GRAPHS. . . . . . . . . . . . . 139
CHAPTER 8: Understanding Graph Basics . . . . . . . . . . . . . . . . . . . . . . . . . 141
Explaining the Importance of Networks. . . . . . . . . . . . . . . . . . . . . . . . .142
Considering the essence of a graph. . . . . . . . . . . . . . . . . . . . . . . . . 142
Finding graphs everywhere . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 145
Showing the social side of graphs. . . . . . . . . . . . . . . . . . . . . . . . . . . 146
Understanding subgraphs. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 147
Defining How to Draw a Graph. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 148
Distinguishing the key attributes . . . . . . . . . . . . . . . . . . . . . . . . . . . 149
Drawing the graph. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 150
Measuring Graph Functionality. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 151
Counting edges and vertexes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 152
Computing centrality. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .154
Putting a Graph in Numeric Format. . . . . . . . . . . . . . . . . . . . . . . . . . . . 157
Adding a graph to a matrix . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 157
Using sparse representations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 158
Using a list to hold a graph . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 159

CHAPTER 9: Reconnecting the Dots . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 161


Traversing a Graph Efficiently . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 162
Creating the graph . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 163
Applying breadth-first search . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 164
Applying depth-first search . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 165
Determining which application to use. . . . . . . . . . . . . . . . . . . . . . . 167
Sorting the Graph Elements. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 168
Working on Directed Acyclic Graphs (DAGs). . . . . . . . . . . . . . . . . . 169
Relying on topological sorting. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 169
Reducing to a Minimum Spanning Tree. . . . . . . . . . . . . . . . . . . . . . . . . 170
Getting the minimum spanning tree historical context. . . . . . . . . 170
Working with unweighted versus weighted graphs. . . . . . . . . . . . 171
Creating a minimum spanning tree example . . . . . . . . . . . . . . . . . 171
Discovering the correct algorithms to use. . . . . . . . . . . . . . . . . . . . 173
Introducing priority queues. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 174
Leveraging Prim’s algorithm . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 175
Testing Kruskal’s algorithm . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 177
Determining which algorithm works best . . . . . . . . . . . . . . . . . . . . 179
Finding the Shortest Route . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 180
Defining what it means to find the shortest path. . . . . . . . . . . . . . 180
Adding a negative edge . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 182
Explaining Dijkstra’s algorithm . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 184
Explaining the Bellman-Ford algorithm. . . . . . . . . . . . . . . . . . . . . . 187
Explaining the Floyd-Warshall algorithm. . . . . . . . . . . . . . . . . . . . . 190

viii Algorithms For Dummies


CHAPTER 10: Discovering Graph Secrets. . . . . . . . . . . . . . . . . . . . . . . . . . . . 195
Envisioning Social Networks as Graphs. . . . . . . . . . . . . . . . . . . . . . . . . 196
Clustering networks in groups. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 196
Discovering communities. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 199
Navigating a Graph. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 202
Counting the degrees of separation. . . . . . . . . . . . . . . . . . . . . . . . . 202
Walking a graph randomly. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 204

CHAPTER 11: Getting the Right Web page . . . . . . . . . . . . . . . . . . . . . . . . . . 207


Finding the World in a Search Engine. . . . . . . . . . . . . . . . . . . . . . . . . . . 208
Searching the Internet for data. . . . . . . . . . . . . . . . . . . . . . . . . . . . . 208
Considering how to find the right data . . . . . . . . . . . . . . . . . . . . . . 209
Explaining the PageRank Algorithm . . . . . . . . . . . . . . . . . . . . . . . . . . . . 210
Understanding the reasoning behind the
PageRank algorithm . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 210
Explaining the nuts and bolts of PageRank. . . . . . . . . . . . . . . . . . . 212
Implementing PageRank . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 212
Implementing a Python script. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 213
Struggling with a naive implementation . . . . . . . . . . . . . . . . . . . . . 216
Introducing boredom and teleporting. . . . . . . . . . . . . . . . . . . . . . . 219
Looking inside the life of a search engine. . . . . . . . . . . . . . . . . . . . 220
Considering other uses of PageRank . . . . . . . . . . . . . . . . . . . . . . . . 221
Going Beyond the PageRank Paradigm. . . . . . . . . . . . . . . . . . . . . . . . . 221
Introducing semantic queries . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 222
Using AI for ranking search results. . . . . . . . . . . . . . . . . . . . . . . . . . 222

PART 4: WRANGLING BIG DATA. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 223


CHAPTER 12: Managing Big Data . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 225
Transforming Power into Data . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 226
Understanding Moore’s implications. . . . . . . . . . . . . . . . . . . . . . . . 226
Finding data everywhere . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 228
Getting algorithms into business . . . . . . . . . . . . . . . . . . . . . . . . . . . 231
Streaming Flows of Data . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 233
Analyzing streams with the right recipe. . . . . . . . . . . . . . . . . . . . . . 234
Reserving the right data. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 235
Sketching an Answer from Stream Data . . . . . . . . . . . . . . . . . . . . . . . . 240
Filtering stream elements by heart. . . . . . . . . . . . . . . . . . . . . . . . . . 240
Demonstrating the Bloom filter . . . . . . . . . . . . . . . . . . . . . . . . . . . . 243
Finding the number of distinct elements. . . . . . . . . . . . . . . . . . . . . 246
Learning to count objects in a stream . . . . . . . . . . . . . . . . . . . . . . . 247

Table of Contents ix
CHAPTER 13: Parallelizing Operations. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 249
Managing Immense Amounts of Data. . . . . . . . . . . . . . . . . . . . . . . . . . 250
Understanding the parallel paradigm . . . . . . . . . . . . . . . . . . . . . . . 251
Distributing files and operations. . . . . . . . . . . . . . . . . . . . . . . . . . . . 253
Employing the MapReduce solution. . . . . . . . . . . . . . . . . . . . . . . . . 255
Working Out Algorithms for MapReduce. . . . . . . . . . . . . . . . . . . . . . . . 259
Setting up a MapReduce simulation. . . . . . . . . . . . . . . . . . . . . . . . . 260
Inquiring by mapping . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 262

CHAPTER 14: Compressing and Concealing Data. . . . . . . . . . . . . . . . . . 267


Making Data Smaller. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 268
Understanding encoding . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 268
Considering the effects of compression . . . . . . . . . . . . . . . . . . . . . 270
Choosing a particular kind of compression. . . . . . . . . . . . . . . . . . . 271
Choosing your encoding wisely. . . . . . . . . . . . . . . . . . . . . . . . . . . . . 273
Encoding using Huffman compression . . . . . . . . . . . . . . . . . . . . . . 276
Remembering sequences with LZW. . . . . . . . . . . . . . . . . . . . . . . . . 278
Hiding Your Secrets with Cryptography. . . . . . . . . . . . . . . . . . . . . . . . . 282
Substituting characters. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 283
Working with AES encryption. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 285

PART 5: CHALLENGING DIFFICULT PROBLEMS. . . . . . . . . . . . 289


CHAPTER 15: Working with Greedy Algorithms. . . . . . . . . . . . . . . . . . . . 291
Deciding When It Is Better to Be Greedy. . . . . . . . . . . . . . . . . . . . . . . . 292
Understanding why greedy is good . . . . . . . . . . . . . . . . . . . . . . . . . 293
Keeping greedy algorithms under control. . . . . . . . . . . . . . . . . . . . 294
Considering NP complete problems. . . . . . . . . . . . . . . . . . . . . . . . . 297
Finding Out How Greedy Can Be Useful . . . . . . . . . . . . . . . . . . . . . . . . 299
Arranging cached computer data. . . . . . . . . . . . . . . . . . . . . . . . . . . 299
Competing for resources. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 301
Revisiting Huffman coding. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 303

CHAPTER 16: Relying on Dynamic Programming. . . . . . . . . . . . . . . . . . 307


Explaining Dynamic Programming. . . . . . . . . . . . . . . . . . . . . . . . . . . . . 308
Obtaining a historical basis . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 308
Making problems dynamic. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 309
Casting recursion dynamically. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 311
Leveraging memoization . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 314
Discovering the Best Dynamic Recipes . . . . . . . . . . . . . . . . . . . . . . . . . 316
Looking inside the knapsack . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 317
Touring around cities . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 321
Approximating string search. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 326

x Algorithms For Dummies


CHAPTER 17: Using Randomized Algorithms. . . . . . . . . . . . . . . . . . . . . . . 331
Defining How Randomization Works . . . . . . . . . . . . . . . . . . . . . . . . . . . 332
Considering why randomization is needed. . . . . . . . . . . . . . . . . . . 333
Understanding how probability works. . . . . . . . . . . . . . . . . . . . . . . 334
Understanding distributions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 335
Simulating the use of the Monte Carlo method. . . . . . . . . . . . . . . 339
Putting Randomness into your Logic . . . . . . . . . . . . . . . . . . . . . . . . . . . 341
Calculating a median using quick select. . . . . . . . . . . . . . . . . . . . . . 341
Doing simulations using Monte Carlo . . . . . . . . . . . . . . . . . . . . . . . 344
Ordering faster with quick sort. . . . . . . . . . . . . . . . . . . . . . . . . . . . . 347

CHAPTER 18: Performing Local Search . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 349


Understanding Local Search . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 350
Knowing the neighborhood. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 351
Presenting local search tricks . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 353
Explaining hill climbing with n-queens. . . . . . . . . . . . . . . . . . . . . . . 354
Discovering simulated annealing . . . . . . . . . . . . . . . . . . . . . . . . . . . 357
Avoiding repeats using Tabu Search. . . . . . . . . . . . . . . . . . . . . . . . .358
Solving Satisfiability of Boolean Circuits . . . . . . . . . . . . . . . . . . . . . . . . 359
Solving 2-SAT using randomization. . . . . . . . . . . . . . . . . . . . . . . . . .360
Implementing the Python code. . . . . . . . . . . . . . . . . . . . . . . . . . . . . 361
Realizing that the starting point is important. . . . . . . . . . . . . . . . . 365

CHAPTER 19: Employing Linear Programming. . . . . . . . . . . . . . . . . . . . . 367


Using Linear Functions as a Tool. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 368
Grasping the basic math you need. . . . . . . . . . . . . . . . . . . . . . . . . . 369
Learning to simplify when planning. . . . . . . . . . . . . . . . . . . . . . . . . 371
Working with geometry using simplex. . . . . . . . . . . . . . . . . . . . . . . 372
Understanding the limitations. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 373
Using Linear Programming in Practice. . . . . . . . . . . . . . . . . . . . . . . . . . 374
Setting up PuLP at home . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 375
Optimizing production and revenue . . . . . . . . . . . . . . . . . . . . . . . . 376

CHAPTER 20: Considering Heuristics. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 381


Differentiating Heuristics. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 382
Considering the goals of heuristics. . . . . . . . . . . . . . . . . . . . . . . . . . 383
Going from genetic to AI. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 383
Routing Robots Using Heuristics. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 384
Scouting in unknown territories . . . . . . . . . . . . . . . . . . . . . . . . . . . . 385
Using distance measures as heuristics . . . . . . . . . . . . . . . . . . . . . . 387
Explaining Path Finding Algorithms . . . . . . . . . . . . . . . . . . . . . . . . . . . . 388
Creating a maze. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 388
Looking for a quick best-first route. . . . . . . . . . . . . . . . . . . . . . . . . . 392
Going heuristically around by A* . . . . . . . . . . . . . . . . . . . . . . . . . . . 396

Table of Contents xi
PART 6: THE PART OF TENS. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 401
CHAPTER 21: Ten Algorithms That Are Changing the World. . . . . 403
Using Sort Routines. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 404
Looking for Things with Search Routines. . . . . . . . . . . . . . . . . . . . . . . . 404
Shaking Things Up with Random Numbers. . . . . . . . . . . . . . . . . . . . . . 405
Performing Data Compression . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 406
Keeping Data Secret . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 406
Changing the Data Domain . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 407
Analyzing Links. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 407
Spotting Data Patterns. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 408
Dealing with Automation and Automatic Responses. . . . . . . . . . . . . . 409
Creating Unique Identifiers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 409

CHAPTER 22: Ten Algorithmic Problems Yet to Solve. . . . . . . . . . . . . 411


Solving Problems Quickly. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 412
Solving 3SUM Problems More Efficiently. . . . . . . . . . . . . . . . . . . . . . . . 412
Making Matrix Multiplication Faster. . . . . . . . . . . . . . . . . . . . . . . . . . . . 413
Determining Whether an Application Will End. . . . . . . . . . . . . . . . . . . 413
Creating and Using One-Way Functions. . . . . . . . . . . . . . . . . . . . . . . . .414
Multiplying Really Large Numbers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 414
Dividing a Resource Equally. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 415
Reducing Edit Distance Calculation Time. . . . . . . . . . . . . . . . . . . . . . . . 415
Playing the Parity Game. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 416
Understanding Spatial Issues . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 416

INDEX. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 417

xii Algorithms For Dummies


Introduction
Y
ou need to learn about algorithms for school or work. Yet, all the books
you’ve tried on the subject end up being more along the lines of really good
sleep-inducing aids rather than texts to teach you something. Assuming
that you can get past the arcane symbols obviously written by a demented
two-year-old with a penchant for squiggles, you end up having no idea of why
you’d even want to know anything about them. Most math texts are boring!
However, Algorithms For Dummies, 2nd Edition is different. The first thing you’ll
note is that this book has a definite lack of odd symbols (especially of the squiggly
sort) floating about. Yes, you see a few (it is a math book, after all), but what you
find instead are clear instructions for using algorithms that actually have names
and a history behind them and that perform useful tasks. You’ll encounter simple
coding techniques to perform amazing tasks that will intrigue your friends. You
can certainly make them jealous as you perform feats of math that they can’t
begin to understand. You get all this without having to strain your brain, even a
little, and you won’t even fall asleep (well, unless you really want to do so). New
in this edition of the book are more details about how algorithms work, and you
even get to create your own basic math package so that you know how to do it for
that next job interview.

About This Book


Algorithms For Dummies, 2nd Edition is the math book that you wanted in college
but didn’t get. You discover, for example, that algorithms aren’t new. After all,
the Babylonians used algorithms to perform simple tasks as early as 1,600 BC. If
the Babylonians could figure this stuff out, certainly you can, too! This book actu-
ally has three things that you won’t find in most math books:

»» Algorithms that have actual names and a historical basis so that you can
remember the algorithm and know why someone took time to create it

»» Simple explanations of how the algorithm performs awesome feats of data


manipulation, data analysis, or probability prediction

»» Code that shows how to use the algorithm without actually dealing with
arcane symbols that no one without a math degree can understand

Introduction 1
Part of the emphasis of this book is on using the right tools. This book uses Python
to perform various tasks. Python has special features that make working with
algorithms significantly easier. For example, Python provides access to a huge
array of packages that let you do just about anything you can imagine, and more
than a few that you can’t. However, unlike many texts that use Python, this one
doesn’t bury you in packages. We use a select group of packages that provide great
flexibility with a lot of functionality but don’t require you to pay anything. You can
go through this entire book without forking over a cent of your hard-earned
money.

You also discover some interesting techniques in this book. The most important is
that you don’t just see the algorithms used to perform tasks; you also get an
explanation of how the algorithms work. Unlike many other books, Algorithms For
Dummies, 2nd Edition enables you to fully understand what you’re doing, but
without requiring you to have a PhD in math. Every one of the examples shows the
expected output and tells you why that output is important. You aren’t left with
the feeling that something is missing.

Of course, you might still be worried about the whole programming environment
issue, and this book doesn’t leave you in the dark there, either. This book relies on
Google Colab to provide a programming environment (although you can use Jupy-
ter Notebook quite easily, too). Because you access Colab through a browser, you
can program anywhere and at any time that you have access to a browser, even on
your smartphone while at the dentist’s office or possibly while standing on your
head watching reruns of your favorite show.

To help you absorb the concepts, this book uses the following conventions:

»» Text that you’re meant to type just as it appears in the book is in bold. The
exception is when you’re working through a step list: Because each step is
bold, the text to type is not bold.

»» Words that we want you to type in that are also in italics are used as place-
holders, which means that you need to replace them with something that
works for you. For example, if you see “Type Your Name and press Enter,” you
need to replace Your Name with your actual name.

»» We also use italics for terms we define. This means that you don’t have to rely
on other sources to provide the definitions you need.

»» Web addresses and programming code appear in monofont. If you’re reading


a digital version of this book on a device connected to the Internet, you can
click the live link to visit that website, like this: http://www.dummies.com.

»» When you need to click command sequences, you see them separated by a
special arrow, like this: File ➪   New File, which tells you to click File and then
New File.

2 Algorithms For Dummies


Foolish Assumptions
You might find it difficult to believe that we’ve assumed anything about you —
after all, we haven’t even met you yet! Although most assumptions are indeed
foolish, we made certain assumptions to provide a starting point for the book.

The first assumption is that you’re familiar with the platform you want to use,
because the book doesn’t provide any guidance in this regard. (Chapter 3 does,
however, tell you how to access Google Colab from your browser and use it to work
with the code examples in the book.) To give you the maximum information about
Python with regard to algorithms, this book doesn’t discuss any platform-specific
issues. You really do need to know how to install applications, use applications, and
generally work with your chosen platform before you begin working with this book.

This book isn’t a math primer. Yes, you see lots of examples of complex math, but
the emphasis is on helping you use Python to perform common tasks using algo-
rithms rather than learning math theory. However, you do get explanations of
many of the algorithms used in the book so that you can understand how the
algorithms work. Chapters 1 and 2 guide you through a what you need to know in
order to use this book successfully. Chapter 5 is a special chapter that discusses
how to create your own math library, which significantly aids you in understand-
ing how math works with code to create a reusable package. It also looks dandy on
your resume to say that you’ve created your own math library.

This book also assumes that you can access items on the Internet. Sprinkled
throughout are numerous references to online material that will enhance your
learning experience. However, these added sources are useful only if you actually
find and use them. You must also have Internet access to use Google Colab.

Icons Used in This Book


As you read this book, you encounter icons in the margins that indicate material
of interest (or not, as the case may be). Here’s what the icons mean:

Tips are nice because they help you save time or perform some task without a lot
of extra work. The tips in this book are time-saving techniques or pointers to
resources that you should try so that you can get the maximum benefit from
Python, or in performing algorithm-related or data analysis–related tasks.

Introduction 3
We don’t want to sound like angry parents or some kind of maniacs, but you
should avoid doing anything that’s marked with a Warning icon. Otherwise, you
might find that your application fails to work as expected, you get incorrect
answers from seemingly bulletproof algorithms, or (in the worst-case scenario)
you lose data.

Whenever you see this icon, think advanced tip or technique. You might find these
tidbits of useful information just too boring for words, or they could contain the
solution you need to get a program running. Skip these bits of information when-
ever you like.

If you don’t get anything else out of a particular chapter or section, remember the
material marked by this icon. This text usually contains an essential process or a
bit of information that you must know to work with Python, or to perform
algorithm-related or data analysis–related tasks successfully.

Beyond the Book


This book isn’t the end of your Python or algorithm learning experience — it’s
really just the beginning. We provide online content to make this book more flex-
ible and better able to meet your needs. That way, as we receive email from you,
we can address questions and tell you how updates to Python, or its associated
add-ons affect book content. In fact, you gain access to all these cool additions:

»» Cheat sheet: You remember using crib notes in school to make a better mark
on a test, don’t you? You do? Well, a cheat sheet is sort of like that. It provides
you with some special notes about tasks that you can do with Python, Google
Colab, and algorithms that not every other person knows. To find the cheat
sheet for this book, go to www.dummies.com and enter Algorithms For
Dummies, 2nd Edition Cheat Sheet in the search box. The cheat sheet contains
really neat information such as finding the algorithms that you commonly
need to perform specific tasks.

»» Updates: Sometimes changes happen. For example, we might not have seen
an upcoming change when we looked into our crystal ball during the writing
of this book. In the past, this possibility simply meant that the book became
outdated and less useful, but you can now find updates to the book, if we
make any, by going to www.dummies.com and entering Algorithms For
Dummies, 2nd Edition in the search box.

In addition to these updates, check out the blog posts with answers to reader
questions and demonstrations of useful book-related techniques at http://
blog.johnmuellerbooks.com/.

4 Algorithms For Dummies


»» Companion files: Hey! Who really wants to type all the code in the book and
reconstruct all those plots manually? Most readers prefer to spend their time
actually working with Python, performing tasks using algorithms, and seeing
the interesting things they can do, rather than typing. Fortunately for you, the
examples used in the book are available for download, so all you need to do is
read the book to learn algorithm usage techniques. You can find these files by
searching Algorithms For Dummies, 2nd Edition at www.dummies.com and
scrolling down the left side of the page that opens. The source code is also at
http://www.johnmuellerbooks.com/source-code/, and https://
github.com/lmassaron/algo4d_2ed.

Where to Go from Here


It’s time to start your algorithm learning adventure! If you’re completely new to
algorithms, you should start with Chapter 1 and progress through the book at a
pace that allows you to absorb as much of the material as possible. Make sure to
read about Python, because the book uses this language as needed for the examples.

If you’re a novice who’s in an absolute rush to get going with algorithms as quickly
as possible, you can skip to Chapter 3 with the understanding that you may find
some topics a bit confusing later.

Readers who have some exposure to Python, and have the appropriate language
versions installed, can save reading time by moving directly to Chapter 5. You can
always go back to earlier chapters as necessary when you have questions. How-
ever, you do need to understand how each technique works before moving to the
next one. Every technique, coding example, and procedure has important lessons
for you, and you could miss vital content if you start skipping too much
information.

Introduction 5
1
Getting Started
with Algorithms
IN THIS PART . . .

Defining algorithms and their design

Using Google Colab to work with algorithms

Performing essential data manipulations

Building a matrix manipulation class


IN THIS CHAPTER

»» Defining what is meant by algorithm

»» Relying on computers to use


algorithms to provide solutions

»» Determining how issues differ from


solutions

»» Performing data manipulation so


that you can find a solution

Chapter 1
Introducing Algorithms

I
f you’re in the majority of people, you’re likely confused as you open this book
and begin your adventure with algorithms, because most texts never tell you
what an algorithm is, much less why you’d want to use one. Hearing about
algorithms is like being in school again with the teacher droning on; you’re falling
asleep from lack of interest because algorithms don’t seem particularly useful to
understand at the moment.

The first section of this chapter is dedicated to helping you understand precisely
what the term algorithm means and why you benefit from knowing how to use
algorithms. Far from being arcane, algorithms are actually used all over the place,
and you have probably used or been helped by them for years without really know-
ing it. So, they’re stealth knowledge! In truth, algorithms are becoming the spine
that supports and regulates what is important in an increasingly complex and
technological society like ours.

The second section of this chapter discusses how you use computers to create
solutions to problems using algorithms, how to distinguish between issues and
solutions, and what you need to do to manipulate data to discover a solution. The
goal is to help you differentiate between algorithms and other tasks that people
confuse with algorithms. In short, you discover why you really want to know
about algorithms, as well as how to apply them to data.

CHAPTER 1 Introducing Algorithms 9


The third section of the chapter discusses algorithms in a real-world manner, that
is, by viewing the terminologies used to understand algorithms and to present
algorithms in a way that shows that the real world is often less than perfect.
Understanding how to describe an algorithm in a realistic manner also helps to
temper expectations to reflect the realities of what an algorithm can actually do.

The final section of the chapter discusses data. The algorithms you work with
in this book require data input in a specific form, which sometimes means
changing the data to match the algorithm’s requirements. Data manipulation
­
doesn’t change the content of the data. Instead, it changes the presentation and
form of the data so that an algorithm can help you see new patterns that weren’t
apparent before (but were actually present in the data all along).

Describing Algorithms
Even though people have solved algorithms manually for thousands of years,
doing so can consume huge amounts of time and require many numeric computa-
tions, depending on the complexity of the problem you want to solve. Algorithms
are all about finding solutions, and the speedier and easier, the better. A huge gap
exists between mathematical algorithms historically created by geniuses of their
time, such as Euclid (https://www.britannica.com/biography/Euclid-Greek-
mathematician), Sir Isaac Newton (https://www.britannica.com/biography/
Isaac-Newton), or Carl Friedrich Gauss (https://www.britannica.com/biography/
Carl-Friedrich-Gauss), and modern algorithms created in universities as well
as private research and development laboratories. The main reason for this gap is
the use of computers. Using computers to solve problems by employing the appro-
priate algorithm speeds up the task significantly. You may notice that more prob-
lem solutions appear quickly today, in part, because computer power is both cheap
and constantly increasing.

When working with algorithms, you consider the inputs, desired outputs, and the
process (a sequence of actions) used to obtain a desired output from a given input.
However, you can get the terminology wrong and view algorithms in the wrong
way because you haven’t really considered how they work in a real-world setting.

Sources of information about algorithms often present them in a way that proves
confusing because they’re too sophisticated or even downright incorrect. Although
you may find other definitions, this book uses the following definitions for terms
that people often confuse with algorithms (but aren’t):

10 PART 1 Getting Started with Algorithms


»» Equation: Numbers and symbols that, when taken as a whole, equate to a
specific value. An equation always contains an equals sign so that you know
that the numbers and symbols represent the specific value on the other side
of the equals sign. Equations generally contain variable information presented
as a symbol, but they’re not required to use variables.

»» Formula: A combination of numbers and symbols used to express informa-


tion or ideas. Formulas normally present mathematical or logical concepts,
such as defining the Greatest Common Divisor (GCD) of two integers (the
video at https://www.khanacademy.org/math/cc-sixth-grade-math/
cc-6th-factors-and-multiples/cc-6th-gcf/v/greatest-common-
divisor tells how this works). Generally, they show the relationship between
two or more variables.

»» Algorithm: A sequence of steps used to solve a problem. The sequence


presents a unique method of addressing an issue by providing a particular
solution. An algorithm need not represent mathematical or logical concepts,
even though the presentations in this book often do fall into those categories
because people most commonly use algorithms in this manner. In order for a
process to represent an algorithm, it must be:

• Finite: The algorithm must eventually solve the problem. This book
discusses problems with a known solution so that you can evaluate
whether an algorithm solves the problem correctly.

• Well-defined: The series of steps must be precise and present steps that
are understandable. Especially because computers are involved in
algorithm use, the computer must be able to understand the steps to
create a usable algorithm.

• Effective: An algorithm must solve all cases of the problem for which
someone defined it. An algorithm should always solve the problem it has
to solve. Even though you should anticipate some failures, the incidence of
failure is rare and occurs only in situations that are acceptable for the
intended algorithm use.

With these definitions in mind, the following sections help to clarify the precise
nature of algorithms. The goal isn’t to provide a precise definition for algorithms,
but rather to help you understand how algorithms fit into the grand scheme of
things so that you can develop your own understanding of what algorithms are
and why they’re so important.

CHAPTER 1 Introducing Algorithms 11


The right way to make toast:
Defining algorithm uses
An algorithm always presents a series of steps and doesn’t necessarily perform
these steps to solve a math formula. The scope of algorithms is incredibly large.
You can find algorithms that solve problems in science, medicine, finance, indus-
trial production and supply, and communication. Algorithms provide support for
all parts of a person’s daily life. Anytime a sequence of actions achieving some-
thing in our life is finite, well-defined, and effective, you can view it as an algo-
rithm. For example, you can turn even something as trivial and simple as making
toast into an algorithm. In fact, the making toast procedure often appears in com-
puter science classes, as discussed at http://brianaspinall.com/now-thats-
how-you-make-toast-using-computer-algorithms/.

Unfortunately, the algorithm on the site is flawed. The instructor never removes
the bread from the wrapper and never plugs the toaster in, so the result is dam-
aged plain bread still in its wrapper stuffed into a nonfunctional toaster (see the
discussion at http://blog.johnmuellerbooks.com/2013/03/04/procedures-
in-technical-writing/ for details). Even so, the idea is the correct one, yet it
requires some slight, but essential, adjustments to make the algorithm finite and
effective.

One of the most common uses of algorithms is as a means of solving formulas. For
example, when working with the GCD of two integer values, you can perform the
task manually by listing each of the factors for the two integers and then selecting
the greatest factor that is common to both. For example, GCD (20, 25) is 5 because
5 is the largest number that divides evenly into both 20 and 25. However, process-
ing every GCD manually is time consuming and error prone, so the Greek mathe-
matician Euclid created a better algorithm to perform the task. You can see the
Euclidean method demonstrated at https://www.khanacademy.org/computing/
computer-science/cryptography/modarithmetic/a/the-euclidean-
algorithm.

However, a single formula, which is a presentation of symbols and numbers used


to express information or ideas, can have multiple solutions, each of which is an
algorithm. In the case of GCD, another common algorithm is one created by
Derrick Henry Lehmer (https://www.imsc.res.in/~kapil/crypto/notes/
­
node11.html). Because you can solve any formula multiple ways, people spend a
great deal of time comparing algorithms to determine which one works best in a
given situation. (See a comparison of Euclid to Lehmer at http://citeseerx.
ist.psu.edu/viewdoc/download?doi=10.1.1.31.693&rep=rep1&type=pdf.)

Because our society and its accompanying technology are changing quickly, we
need algorithms that can keep the pace. Scientific achievements such as

12 PART 1 Getting Started with Algorithms


sequencing the human genome were possible in our age because scientists found
algorithms that run fast enough to complete the task. Measuring which algorithm
is better in a given situation, or in an average usage situation, is really serious
stuff and is a topic of discussion among computer scientists.

When it comes to computer science, the same algorithm can have multiple
­presentations; why do it one way when you can invent multiple methods just for
fun? For example, you can present the Euclidean algorithm in both recursive and
iterative forms, as explained at http://cs.stackexchange.com/questions/1447/
what-is-most-efficient-for-gcd. In short, algorithms present a method of
solving formulas, but it would be a mistake to say that just one acceptable algo-
rithm exists for any given formula or that only one acceptable presentation of an
algorithm exists. Using algorithms to solve problems of various sorts has a long
history — it isn’t something that has just happened.

Even if you limit your gaze to computer science, data science, artificial intelli-
gence, and other technical areas, you find many kinds of algorithms — too many
for a single book. For example, The Art of Computer Programming, by Donald
E. Knuth (Addison-Wesley), spans 3,168 pages in four volumes (see http://
www.amazon.com/exec/obidos/ASIN/0321751043/datacservip0f-20/) and still
doesn’t manage to cover the topic (the author intended to write more volumes).
However, here are some interesting uses for you to consider:

»» Searching: Locating information or verifying that the information you see is the
information you want is an essential task. Without this ability, you couldn’t
perform many tasks online, such as finding the website on the Internet selling
the perfect coffee pot for your office. These algorithms change constantly, as
shown by Google’s recent change in its algorithm (https://www.youaretech.
com/blog/2021/1/26/webpage-experience-a-major-google-algorithm-
update-in-2021nbsp).

»» Sorting: Determining which order to use to present information is important


because most people today suffer from information overload, and putting
information in order is one way to reduce the onrush of data. Imagine going
to Amazon, finding that more than a thousand coffee pots are for sale there,
and yet not being able to sort them in order of price or the most positive
review. Moreover, many complex algorithms require data in the proper order
to work dependably, so ordering is an important requisite for solving more
problems.

»» Transforming: Converting one sort of data to another sort of data is critical


to understanding and using the data effectively. For example, you might
understand imperial weights just fine, but all your sources use the metric
system. Converting between the two systems helps you understand the data.

CHAPTER 1 Introducing Algorithms 13


»» Scheduling: Making the use of resources fair to all concerned is another way
in which algorithms make their presence known in a big way. For example,
timing lights at intersections are no longer simple devices that count down the
seconds between light changes. Modern devices consider all sorts of issues,
such as the time of day, weather conditions, and flow of traffic.

»» Graph analysis: Deciding on the shortest path between two points finds all sorts
of uses. For example, in a routing problem, your GPS couldn’t function without
this particular algorithm because it could never direct you along city streets using
the shortest route from point A to point B. And even then, your GPS might direct
you to drive into a lake (https://theweek.com/articles/464674/8-
drivers-who-blindly-followed-gps-into-disaster).

»» Cryptography: Keeping data safe is an ongoing battle with hackers constantly


attacking data sources. Algorithms make it possible to analyze data, put it into
some other form, and then return it to its original form later.

»» Pseudorandom number generation: Imagine playing games that never


varied. You start at the same place; perform the same steps, in the same
manner, every time you play. Without the capability to generate seemingly
random numbers, many computer tasks become impossible.

This list presents an incredibly short overview. People use algorithms for many
different tasks and in many different ways, and constantly create new algorithms
to solve both existing problems and new problems. The most important issue to
consider when working with algorithms is that given a particular input, you
should expect a specific output. Secondary issues include how many resources the
algorithm requires to perform its task and how long it takes to complete the task.
Depending on the kind of issue and the sort of algorithm used, you may also need
to consider issues of accuracy and consistency.

Finding algorithms everywhere


The previous section mentions the toast algorithm for a specific reason. For some
reason, making toast is probably the most popular algorithm ever created. Many
grade-school children write their equivalent of the toast algorithm long before
they can even solve the most basic math. It’s not hard to imagine how many
variations of the toast algorithm exist and what the precise output is of each of
them. The results likely vary by individual and the level of creativity employed.
There are also websites dedicated to telling children about algorithms, such as the
one at https://www.idtech.com/blog/algorithms-for-kids. In short, algo-
rithms appear in great variety and often in unexpected places.

14 PART 1 Getting Started with Algorithms


Every task you perform on a computer involves algorithms. Some algorithms
appear as part of the computer hardware. The very act of booting a computer
involves the use of an algorithm. You also find algorithms in operating systems,
applications, and every other piece of software. Even users rely on algorithms.
Scripts help direct users to perform tasks in a specific way, but those same steps
could appear as written instructions or as part of an organizational policy
statement.

Daily routines often devolve into algorithms. Think about how you spend your
day. If you’re like most people, you perform essentially the same tasks every day
in the same order, making your day an algorithm that solves the problem of how
to live successfully while expending the least amount of energy possible. After all,
that’s what a routine does; it makes us efficient.

Throughout this book, you see the same three elements for every algorithm:

1. Describe the problem.

2. Create a series of steps to solve the problem (well defined).

3. Perform the steps to obtain a desired result (finite and effective).

Using Computers to Solve Problems


The term computer sounds quite technical and possibly a bit overwhelming to
some people, but people today are neck deep (possibly even deeper) in computers.
You wear at least one computer, your smartphone, most of the time. If you have
any sort of special device, such as a pacemaker, it also includes a computer. A car
can contain as many as 150 computers in the form of embedded microprocessors
that regulate fuel consumption, engine combustion, transmission, steering, and
stability (see https://spectrum.ieee.org/software-eating-car for details),
provide Advanced Driver-Assist Systems (ADAS), and more lines of code than a jet
fighter. A computer exists to solve problems quickly and with less effort than
solving them manually. Consequently, it shouldn’t surprise you that this book
uses still more computers to help you understand algorithms better.

Computers vary in a number of ways. The computer in a watch is quite small; the
one on a desktop quite large. Supercomputers are immense and contain many
smaller computers all tasked to work together to solve complex issues, such as
predicting tomorrow’s weather. The most complex algorithms rely on special
computer functionality to obtain solutions to the issues people design them to
solve. Yes, you could use lesser resources to perform the task, but the trade-off is
waiting a lot longer for an answer, or getting an answer that lacks sufficient

CHAPTER 1 Introducing Algorithms 15


Another random document with
no related content on Scribd:
praise God, with a loud voice, for all the mighty works that they had
seen; saying, “Blessed be the King of Israel, that cometh in the
name of the Lord! Peace in heaven! Glory in the highest! Blessed be
the kingdom of our father David! Hosanna!” These acclamations
were raised by the disciples, and heartily joined in by the multitudes
who knew his wonderful works, and more especially those who were
acquainted with the very recent miracle of raising Lazarus. A great
sensation of wonder was created throughout the city, by such a burst
of shouts from a multitude, sweeping in a long, imposing train, with
palm branches in their hands, down the mountain, on which they
could have been seen all over Jerusalem. As he entered the gates,
all the city was moved to say, “Who is this?” And the rejoicing
multitude said, “This is Jesus, the prophet of Nazareth in Galilee.”
What scorn did not this reply awaken in many of the haughty
aristocrats of Jerusalem, to learn that all this solemn parade had
been got up for no better purpose than merely to honor a dweller of
that outcast region of mongrels, Galilee! And of all places, that this
prophet, so called, should have come from Nazareth! A prophet from
Galilee, indeed! Was it from this half-heathen district, that the
favored inhabitants of the capital of Judaism were to receive a
teacher of religion? Were the strict faith, and the rigid observances of
their learned and devout, to be displaced by the presumptuous
reformations of a self-taught prophet, from such a country? Swelling
with these feelings, the Pharisees could not repress a remonstrance
with Jesus, against these noisy proceedings. But he, evidently
affected with pleasure at the honest tribute thus wrung out in spite of
sectional feeling, forcibly asserted the propriety and justice of this
free offering of praise. “I tell you, that if these should hold their
peace, the stones would immediately cry out.”

With palm-branches in their hands.――This tree, the emblem of joy and triumph in every
part of the world where it is known, was the more readily adopted on this occasion, by those
who thronged to swell the triumphal train of Jesus of Nazareth, because the palm grew
along the way-side where they passed, and the whole mount was hardly less rich in this
than in the far famed olive from which it drew its name. A proof of the abundance of the
palm-trees on Olivet is found in the name of the village of Bethany, ‫בית חיני‬, (beth-hene,)
“house of dates,” which shows that the tree which bore this fruit must have been plentiful
there. The people, as they passed on with Jesus from this village whence he started to
enter the city, would therefore find this token of triumph hanging over their heads, and
shading their path every where within reach, and the emotions of joy at their approach to
the city of God in the company of this good and mighty prophet, prompted them at once to
use the expressive emblems which hung so near at hand; and which were alike within the
reach of those who journeyed with Jesus, and those who came forth from the city to meet
and escort him in. The presence of these triumphal signs would, of course, remind them at
once of the feast of the tabernacles, the day on which, in obedience to the Mosaic statute,
all the dwellers of the city were accustomed to go forth to the mount, and bring home these
branches with songs of joy. (Leviticus xxiii. 40, Nehemiah viii. 15, 16.) The remembrance of
this festival at once recalled also the beautifully appropriate words of the noble national and
religious hymn, which they always chanted in praise of the God of their fathers on that day,
(see Kuinoel, Rosenmueller, Wolf, &c.) and which was so peculiarly applicable to him who
now “came in the name of the Lord,” to honor and to bless his people. (Psalm cxviii. 26.)

The descent of the Mount of Olives.――To imagine this scene, with something of the
force of reality, it must be remembered that the Mount of Olives, so often mentioned in the
scenes of Christ’s life, rose on the eastern side of Jerusalem beyond the valley of the
Kedron, whose little stream flowed between this mountain and Mount Moriah, on which the
temple stood. Mount Olivet was much higher than any part of the city within the walls, and
the most commanding and satisfactory view of the holy city which modern travelers and
draughtsmen have been able to present to us in a picture, is that from the more than classic
summit of this mountain. The great northern road passing through Jericho, approaches
Jerusalem on its north-eastern side, and comes directly over the top of Olivet, and as it
mounts the ridge, it brings the holy city in all its glory, directly on the traveler’s view.

Hosanna.――This also is an expression taken from the same festal hymn, (Psalm cxviii.
25,) ‫( הושיעה־נא‬hoshia-na) a pure Hebrew expression, as Drusius shows, and not Syriac,
(See Poole’s Synopsis on Matthew xxi. 9,) but corrupted in the vulgar pronunciation of this
frequently repeated hymn, into Hosanna. The meaning of the Hebrew is “save him” or “be
gracious to him,” that is in connection with the words which follow in the gospel story, “Be
gracious, O Lord, to the son of David.” This is the same Hebrew phrase which, in the psalm
above quoted, (verse 25,) is translated “Save now.” The whole expression was somewhat
like the English “God save the king,” in its import.

Nazareth.――This city, in particular, had an odious name, for the general low character
of its inhabitants. The passage in John i. 46, shows in what estimation this city and its
inhabitants were held, by their own neighbors in Galilee; and the great scorn with which all
Galileans were regarded by the Jews, must have redoubled their contempt of this poor
village, so despised even by the despicable. The consequence was that the Nazarenes
acquired so low a character, that the name became a sort of byword for what was mean and
foolish. (See Kuinoel on Matthew ii. 23, John i. 46. Also Rosenmueller on the former
passage and Bloomfield on the latter.)

Galilee.――In order to appreciate fully, the scorn and suspicion with which the Galileans
were regarded by the citizens of Jerusalem, a complete view of their sectional peculiarities
would be necessary. Such a view will hereafter be given in connection with a passage which
more directly refers to those peculiarities, and more especially requires illustration and
explanation.

the blighting of the fig-tree.


Having thus, by his public and triumphant entrance into
Jerusalem, defied and provoked the spite of the higher orders, while
he secured an attentive hearing from the common people, when he
should wish to teach them,――Jesus retired at evening, for the sake
of quiet and comfort, to the house of his friends, Lazarus, Mary and
Martha, at Bethany, in the suburbs. The next morning, as he was on
his way with his disciples, coming back from this place to Jerusalem,
hungry with the fatigues of his long walk, he came to a fig-tree, near
the path, hoping to find fruit for his refreshment, as it seemed from a
distance flourishing with abundance of leaves, and was then near
the season of bearing. But when he came near, he found nothing but
leaves on it, for it was somewhat backward, and its time of producing
figs was not yet. And Jesus, seizing the opportunity of this
disappointment to impress his disciples with his power, personifying
the tree, denounced destruction against it. “May no man eat fruit of
thee hereafter, forever.” And his disciples heard it. They returned to
Bethany, as usual, that evening, to pass the night,――but as they
passed, probably after dark, they took no notice of the fig-tree. But
the next morning, as they went back to the city, they saw that it had
dried up from the roots. Simon Peter, always ready to notice the
instances of his Master’s power, called out in surprise to Jesus, to
witness the effect of his malediction upon its object. “Master, behold,
the fig-tree which thou didst curse, is withered away.” Jesus noticing
their amazement at the apparent effect of his words, in so small a
matter, took occasion to turn their attention to other and higher
objects of faith, on which they might exert their zeal in a spirit, not of
withering denunciation and destroying wrath, such as they had seen
so tremendously efficient in this case, but in the spirit of love and
forgiveness, as well as of the holy energy that could overthrow and
overcome difficulties, not less than to uproot Mount Olivet from its
everlasting base and hurl it into the sea.

the discussions with the sectaries.

The disciples steadily remained the diligent and constant


attendants of their heavenly teacher, in his long and frequent
seasons of instruction in the temple, where he boldly met the often
renewed attacks of his various adversaries, whether Herodians,
scribes, Pharisees or Sadducees, and in spite of their long-trained
subtleties, beat them out and out, with the very weapons at which
they thought themselves so handy. The display of genius, of taste, of
learning, of ready and sarcastic wit, and of heart-searching
acuteness, was so amazing and super-human, that these few days
of open discussion established his divinely intellectual superiority
over all the elaborate science of his accomplished opponents, and at
the same time secured the fulfilment of his destiny, by the spite and
hatred which their repeated public defeats excited in them. Imagine
their rage. Exposed thus before the people, by whom they had
hitherto been regarded as the sole depositaries of learning, and
adored as the fountains of right, they saw all their honors and power,
to which they had devoted the intense study of their whole lives,
snatched coolly and easily from them, by a nameless, untaught
pretender, who was able to hold them up, baffled and disgraced, for
the amusement of the jeering multitude. Here was ground enough for
hatred;――the hatred of conceited and intolerant false learning,
against the discerning soul that had stripped and humbled it;――the
hatred of confident ambition against the heroic energy which had
discomfited it, and was doing much to free a long enslaved people
from the yoke which formal hypocrisy and empty parade had long
laid on them. And again, the intolerable thought that all this heavy
disgrace had been brought on the learned body of Judaism by a
Galilean! a mere carpenter of the lowest orders, who had come up to
Jerusalem followed by a select train of rude fishermen and outcast
publicans;――and who, not being able to command a single night’s
lodging in the city, was in the habit of boarding and lodging in a paltry
suburb, on the charity of some personal friends, from which place he
quietly walked in for the distance of two miles every morning, to
triumph over the palace-lodged heads of the Jewish faith. From such
a man, thus humbly and even pitiably circumstanced, such an
invasion and overthrow could not be endured; and his ruin was
rendered doubly easy by his very insignificance, which now
constituted the chief disgrace of their defeat. Never was cause more
closely followed by its effect, than this insulted dignity was by its
cruel vengeance.

the prophecy of the temple’s ruin.

In preparing his disciples for the great events which were to take
place in a few years, and which were to have a great influence on
their labors, Jesus foretold to them the destruction of the temple. As
he was passing out through the mighty gates of the temple on some
occasion with his disciples, one of them, admiring the gorgeous
beauty of the architecture and the materials, with all the devotion of a
Jew now visiting it for the first time, said to him, “Master, see! what
stones and what buildings!” To him, Jesus replied with the awful
prophecy, most shocking to the national pride and religious
associations of every Israelite,――that ere long, upon that glorious
pile should fall a ruin so complete, that not one of those splendid
stones should be left upon another. These words must have made a
strong impression of wonder on all who heard them; but no farther
details of the prophecy were given to the disciples at large. Not long
afterwards, however, as he sat musingly by himself, in his favorite
retirement, half-way up the Mount of Olives, over against the temple,
the four most loved and honored of the twelve, Peter, James, John
and Andrew, came to him, and asked him privately, to tell them when
these things should be, and by what omen they should know the
approach of the great and woful ruin. Sitting there, they had a full
view of the enormous pile which rose in immense masses very near
them, on the verge of mount Moriah, and was even terraced up, from
the side of the slope, presenting a vast wall, rising from the depths of
the deep ravine of Kedron, which separated the temple from mount
Olivet, where they were. It was morning when the conversation took
place, as we may fairly guess, for this spot lay on the daily walk to
Bethany, where he lodged;――the broad walls, high towers, and
pillars of the temple, were doubtless illuminated by the full splendors
of the morning sun of Palestine; for Olivet was directly east of
Jerusalem, and as they sat looking westward towards the temple,
with the sun behind them, the rays, leaving their faces in the shade,
would shine full and bright on all which crowned the highth beyond. It
was at such a time, as the Jewish historian assures us, that the
temple was seen in its fullest grandeur and sublimity; for the light,
falling on the vast roofs, which were sheeted and spiked with pure
gold, brightly polished, and upon the turrets and pinnacles which
glittered with the same precious metal, was reflected to the eye of
the gazer with an insupportable brilliancy, from the million bright
surfaces and shining points which covered it. Here, then, sat Jesus
and his four adoring chosen ones, with this splendid sight before
them crowning the mountain, now made doubly dazzling by contrast
with the deep gloom of the dark glen below, which separated them
from it. There it was, that, with all this brightness and glory and
beauty before them, Jesus solemnly foretold in detail the awful, total
ruin which was to sweep it all away, within the short lives of those
who heard him. Well might such words sink deep into their
hearts,――words coming from lips whose perfect and divine truth
they could not doubt, though the things now foretold must have gone
wofully against all the dreams of glory, in which they had made that
sacred pile the scene of the future triumphs of the faith and followers
of Christ. This sublime prophecy, which need not here be repeated
or descanted upon, is given at great length by all the first three
evangelists, and is found in Matthew xxiv. Mark xiii. and Luke xxi.

The view of the temple.――I can find no description by any writer, ancient or modern,
which gives so clear an account of the original shape of Mount Moriah, and of the
modifications it underwent to fit it to support the temple, as that given by Josephus. (Jewish
War, book V. chapter v.) In speaking of the original founding of the temple by Solomon,
(Antiquities book VIII. chapter iii. section 2,) he says, “The king laid the foundations of the
temple in the very depths, (at the bottom of the descent,) using stones of a firm structure,
and able to hold out against the attacks of time, so that growing into a union, as it were, with
the ground, they might be the basis and support of the pile that was to be reared above, and
through their strength below, easily bear the vast mass of the great superstructure, and the
immense weight of ornament also; for the weight of those things which were contrived for
beauty and magnificence was not less than that of the materials which contributed to the
highth and lateral dimension.” In the full description which he afterwards gives in the place
first quoted, of the later temple as perfected by Herod, which is the building to which the
account in the text refers, he enters more fully into the mode of shaping the ground to the
temple. “The temple was founded upon a steep hill, but in the first beginning of the structure
there was scarcely flat ground enough on the top for the sanctuary and the altar, for it was
abrupt and precipitous all around. And king Solomon, when he built the sanctuary, having
walled it out on the eastern side, (εκτειχισαντος, that is, ‘having built out a wall on that side’
for a terrace,) then reared upon the terraced earth a colonnade; but on the other sides the
sanctuary was naked,――(that is, the wall was unsupported and unornamented by
colonnades as it was on the east.) But in the course of ages, the people all the while
beating down the terraced earth with their footsteps, the hill thus growing flat, was made
broader on the top; and having taken down the wall on the north, they gained considerable
ground which was afterwards inclosed within the outer court of the temple. Finally, having
walled the hill entirely around with three terraces, and having advanced the work far beyond
any hope that could have been reasonably entertained at first, spending on it long ages,
and all the sacred treasures accumulated from the offerings sent to God from the ends of
the world, they reared around it, both the upper courts and the lower temple, walling the
latter up, in the lowest part, from a depth of three hundred cubits, (450 feet,) and in some
places more. And yet the whole depth of the foundations did not show itself, because they
had greatly filled up the ravines, with a view to bring them to a level with the streets of the
city. The stones of this work were of the size of forty cubits, (60 feet,) for the profusion of
means and the lavish zeal of the people advanced the improvements of the temple beyond
account; and a perfection far above all hope was thus attained by perseverance and time.

“And well worthy of these foundations were the works which stood upon them. For all the
colonnades were double, consisting of pillars twenty-five cubits (40 feet) in highth, each of a
single stone of the whitest marble, and were roofed with fretwork of cedar. The natural
beauty of these, their high polish and exquisite proportion, presented a most glorious show;
but their surface was not marked by the superfluous embellishments of painting and
carving. The colonnades were thirty cubits broad, (that is, forty-five feet from the front of the
columns to the wall behind them;) while their whole circuit embraced a range of six stadia,
(more than three-quarters of a mile!) including the castle of Antonia. And the whole
hypethrum (ὑπαιθρον, the floor of the courts or inclosures of the temple, which was exposed
to the open air, there being no roof above it) was variegated by the stones of all colors with
which it was laid,” (making a Mosaic pavement.) Section 1.

“The outside of the temple too, lacked nothing that could strike or dazzle the mind and
eye. For it was on all sides overlaid with massy plates of gold, so that in the first light of the
rising sun, it shot forth a most fiery splendor, which turned away the eyes of those
who compelled themselves (mid. βιαζομενους) to gaze on it, as from the rays of the sun
itself. To strangers, moreover, who were coming towards it, it shone from afar like a
complete mountain of snow: for where it was not covered with gold it was most dazzlingly
white, and above on the roof it had golden spikes, sharpened to keep the birds from lighting
on it. And some of the stones of the building were forty-five cubits long, five high, and six
broad;”――(or sixty-seven feet long, seven and a half high, and nine broad.) Section 6.

“The Antonia was placed at the angle made by the meeting of two colonnades of the
outer temple, the western and the northern. It was built upon a rock, fifty cubits high, and
precipitous on all sides. It was the work of king Herod, in which, most of all, he showed
himself a man of exalted conceptions.” Section 8.

In speaking of Solomon’s foundation, he also says, (Antiquities book VIII. chapter iii.
section 9,)

“But he made the outside of the temple wonderful beyond account, both in description
and to sight. For having piled up huge terraces, from which, on account of their immense
depth, it was hardly possible to look down, and reared them to the highth of four hundred
cubits, (six hundred feet!) he made them on the same level with the hill’s top on which the
shrine (ναος) was built, and thus the open floor of the temple (ἱερον, or the outer court’s
inclosure) was level with the shrine.”

I have drawn thus largely from the rich descriptions of this noble and faithful describer of
the old glories of the Holy Land, because this very literal translation gives the exact naked
detail of the temple’s aspect, in language as gorgeous as the most high-wrought in which it
could be presented in a mere fancy picture of the same scene; and because it will prove
that my conception of its glory, as it appeared to Christ and the four disciples who “sat over
against it upon the Mount of Olives,” is not overdrawn, since it is thus supported by the
blameless and invaluable testimony of him who saw all this splendor in its most splendid
day, and afterwards in its unequaled beauty and with all its polished gold and marble,
shining and sinking amid the flames, which swept it utterly away from his saddening eyes
forever, to a ruin the most absolute and irretrievable that ever fell upon the works of man.

This was the temple on which the sons of Jonah and Zebedee gazed, with the awful
denunciation of its utter ruin falling from their Lord’s lips, and such was the desolation to
which those terrible words devoted it. This full description of its location shows the manner
in which its terraced foundations descended with their vast fronts, six hundred feet into the
valley of Kedron, over which they looked. To give as clear an idea of the place where they
sat, and its relations to the rest of the scene, I extract from Conder’s Modern Traveler the
following description of Mount Olivet.

“The Mount of Olives forms part of a ridge of limestone hills, extending to the north and
the south-west. Pococke describes it as having four summits. On the lowest and most
northerly of these, which, he tells us, is called Sulman Tashy, the stone of Solomon, there is
a large domed sepulcher, and several other Mohammedan tombs. The ascent to this point,
which is to the north-east of the city, he describes as very gradual, through pleasant corn-
fields planted with olive-trees. The second summit is that which overlooks the city: the path
to it rises from the ruined gardens of Gethsemane, which occupy part of the valley. About
half way up the ascent is a ruined monastery, built, as the monks tell us, on the spot where
the Savior wept over Jerusalem. From this point the spectator enjoys, perhaps, the best
view of the Holy City. (Here Jesus sat, in our scene.)

“The valley of Jehoshaphat, which lies between this mountain and the hills on which
Jerusalem is built, is still used as a burial-place by the modern Jews, as it was by their
ancestors. It is, generally speaking, a rocky flat, with a few patches of earth here and there,
about half a mile in breadth from the Kedron to the foot of Mount Olivet, and nearly of the
same length from Siloa to the garden of Gethsemane. The Jews have a tradition, evidently
founded on taking literally the passage Joel iii. 12, that this narrow valley will be the scene
of the final judgment. The prophet Jeremiah evidently refers to the same valley under the
name of the valley of the Son of Hinnom, or the valley of Tophet, the situation being clearly
marked as being by the entry of the east gate. (Jeremiah xix. 2, 6.) Pococke places the
valley of Hinnom to the south of Jerusalem, but thinks it might include part of that to the
east. It formed part of the bounds between the tribes of Benjamin and Judah, (Joshua xv. 8.
xviii. 16,) but the description is somewhat obscure.” [Modern Traveler Palestine, pp. 168,
172.]
MOUNT MORIAH.

the last supper.

Meanwhile the offended and provoked dignitaries of Judaism were


fast making arrangements to crush the daring innovator, who had
done so much to bring their learning and their power into contempt.
Some of the most fiery spirits among them, were for defying all risks,
by seizing the Nazarene openly, in the midst of his audacious
denunciations of the higher orders; and the attempt was made to
execute this act of arbitrary power; but the mere hirelings sent upon
the errand, were too much awed by the unequaled majesty of the
man, and by the strong attachment of the people to him, to be willing
to execute their commission. But there were old heads among them,
that could contrive safer and surer ways of meeting the evil. By them
it was finally determined to seize Jesus when alone or unattended by
the throngs which usually encompassed him,――to hurry him at
once secretly through the forms of law necessary for his
commitment, and then to put him immediately into the hands of the
Roman governor, as a condemned rioter and rebel, who would be
obliged to order his execution in such a way as that no popular
excitement would rescue the victim from the grasp of the soldiery.
This was the plan which they were now arranging, and which they
were prepared to execute before the close of the passover, if they
could get intelligence of his motions. These fatal schemes of hate
could not have been unknown to Jesus; yet the knowledge of them
made no difference in his bold devotion to the cause for which he
came into the world. Anxious to improve the few fast fleeting hours
that remained before the time of his sufferings should come on, and
desirous to join as a Jew in this great national festival, by keeping it
in form with his disciples, he directed his two most confidential
apostles, Peter and John, to get ready the entertainment for them in
the city, by an arrangement made with a man already expecting to
receive them. This commission they faithfully executed, and Jesus
accordingly ate with his disciples the feast of the first day of the
passover, in Jerusalem, with those who sought his life so near him.
After the supper was over, he determined to use the brief remnant of
time for the purpose of uprooting that low feeling of jealous ambition
which had already made so much trouble among them, in their
anxious discussions as to who should be accounted the greatest,
and should rank as the ruler of the twelve. To impress the right view
upon their minds most effectually, he chose the oriental mode of a
ceremony which should strike their senses, and thus secure a regard
and remembrance for his words which they might fail in attaining if
they were delivered in the simple manner of trite and oft spoken oral
truisms. He therefore rose after supper, and leaving his place at the
head of the table, he laid aside his upper garments, which, though
appropriate and becoming him as a teacher in his hours of public
instruction, or social communion, were yet inconvenient in any active
exertion which needed the free use of the limbs. Being thus
disrobed, he took the position and character of a menial upon him,
and girding himself with a towel, he poured water into a basin and
began to wash the disciples’ feet in it, wiping them with his towel. He
accordingly comes to Simon Peter, in the discharge of his servile
office; but Peter, whose ideas of the majesty and ripening honors of
his Master were shocked at this extraordinary action, positively
refused to be even the passive instrument of such an indignity to one
so great and good,――first inquiring “Lord, dost thou wash my feet?”
Jesus in answer said to him, “What I do, thou knowest not now, but
thou shalt know hereafter.” That is, “this apparently degrading act
has a hidden, useful meaning, at this moment beyond your
comprehension, but which you will learn in due time.” Peter,
however, notwithstanding this plain and decided expression of
Christ’s wise determination to go through this painful ceremony, for
the instruction of those who so unwillingly submitted to see him thus
degraded,――still led on by the fiery ardor of his own headlong
genius,――manfully persisted in his refusal, and expressed himself
in the most positive terms possible, saying to Jesus, “Thou shalt
never wash my feet.” Jesus answered, “If I wash thee not, thou hast
no part with me.” This solemn remonstrance had the effect of
checking Peter’s too forward reverence, and in a tone of deeper
submission to the wise will of his Master, he yielded, replying
however, “Lord, wash not my feet only, but also my hands and my
head.” Since so low an office was to be performed by one so
venerated, he would not have the favor of his blessed touch confined
to the baser limbs, but desired that the nobler parts of the body
should share in the holy ablution. But the high purpose of Jesus
could not accommodate itself to the whims of his zealous disciple;
for his very object was to take the humblest attitude before them, by
performing those personal offices which were usually committed to
slaves. He therefore told Peter, “He that is washed needs not save to
wash his feet, but is clean in every part;”――a very familiar and
expressive illustration, alluding to the circumstance that those who
have been to a bath and there washed themselves, will on their
return find themselves wholly clean, except such dust as may cling
to their feet as they have passed through the streets on their return.
And any one may feel the force of the beautiful figure, who has ever
gone into the water for the purposes of cleanliness and refreshment,
on a warm summer’s day in this country, and has found by
experience that after all possible ablution, on coming out and
dressing himself, his wet feet in contact with the ground have
become loaded with dirt which demands new diligence to remove it;
and as all who have tried it know, it requires many ingenious efforts
to return with feet as clean as they came to the washing; and in spite
of all, after the return, an inspection may forcibly illustrate the truth,
that “he that is washed, though he is clean in every part, yet needs to
wash his feet.” Such was the figure with which Jesus expressed to
his simple-minded and unlettered disciples, the important truth, that
since they had been already washed, (baptized by John or himself,)
if that washing had been effectual, they could need the repurification
only of their feet――the cleansing away of such of the world’s
impure thoughts and feelings as had clung to them in their
journeyings through it. So, after he had washed their feet, and had
taken his garments and sat down again, he said to them, “Know ye
what I have done to you? Ye call me Master and Lord; and ye say
well, for so I am. If I then, your Lord and Master, have washed your
feet, ye also ought to wash one another’s feet. For I have given you
this as an example, that ye should do as I have done to you. Truly
the servant is not greater than his lord, neither is he that is sent
greater than him that sent him. If ye know these things, happy are ye
if ye do them.”――A charge so clear and simple, and so full, that it
needs not a word of comment to show any reader the full force of
this touching ceremony.

Shortly after, in the same place and during the same meeting,
Jesus speaking to them of his near departure, affectionately and
sadly said, “Little children, but a little while longer am I with you. Ye
shall seek me; and as I said to the Jews, ‘whither I go, ye cannot
come,’――so now I say to you.” To this Simon Peter soon after
replied by asking him, “Lord whither goest thou?” Jesus answered
him, “Whither I go thou canst not follow me now, but thou shalt follow
me afterwards.” Peter, perhaps beginning to perceive the mournful
meaning of this declaration, replied, still urging, “Lord, why cannot I
follow thee now? I will lay down my life for thy sake.” Jesus
answered, “Wilt thou lay down thy life for my sake? I tell thee
assuredly, the cock shall not crow till thou hast denied me
thrice.”――Soon after, at the same time and place, noticing the
confident assurance of this chief disciple, Jesus again warned him of
his danger and his coming fall. “Simon! Simon! behold, Satan has
desired to have you (all) that he may sift you as wheat; but I have
prayed for thee (especially) that thy faith fail not; and when thou art
converted, strengthen thy brethren.” Never before had higher and
more distinctive favor been conferred on this chief apostle, than by
this sad prophecy of danger, weakness and sin, on which he was to
fall, for a time, to his deep disgrace; but on him alone, when rescued
from ruin by his Master’s peculiar prayers, was to rest the task of
strengthening his brethren. But his Master’s kind warning was for the
present lost on his immovable self-esteem; he repeated his former
assurance of perfect devotion through every danger, “Lord, I am
ready to go with thee into prison and to death.” Where was
affectionate and heroic devotion ever more affectingly and
determinedly expressed? What heart of common man would not
have leaped to meet such love and fidelity? But He, with an eye still
clear and piercing, in spite of the tears with which affection might dim
it, saw through the veil that would have blinded the sharpest human
judgment, and coldly met these protestations of burning zeal with the
chilling prediction again uttered, “I tell thee, Peter, the cock shall not
crow this day, before thou shalt thrice deny that thou knowest me.”
Then making a sudden transition, to hint to them the nature of the
dangers which would soon try their souls, he suddenly reverted to
their former security. “When I sent you forth without purse, or scrip,
or shoes, did ye need any thing?” And they said “Nothing.” Then said
he to them “But now, let him that has a purse, take it, and likewise
his scrip; and let him that has no sword sell his cloak and buy one.”
They had hitherto, in their wanderings, every where found friends to
support and protect them; but now the world was at war with them,
and they must look to their own resources both for supplying their
wants and guarding their lives. His disciples readily apprehending
some need of personal defense, at once bestirred themselves and
mustered what arms they could on the spot, and told him that they
had two swords among them, and of these it appears that one was in
the hands of Peter. It was natural enough that among the disciples
these few arms were found, for they were all Galileans, who, as
Josephus tells us, were very pugnacious in their habits; and even the
followers of Christ, notwithstanding their peaceful calling, had not
entirely laid aside their former weapons of violence, which were the
more needed by them, as the journey from Galilee to Jerusalem was
made very dangerous by robbers, who lay in wait for the defenseless
traveler wherever the nature of the ground favored such an attack.
Of this character was that part of the road between Jerusalem and
Jericho, alluded to in the parable of the wounded traveler and the
good Samaritan,――a region so wild and rocky that it has always
been dangerous, for the same reasons, even to this day; of which a
sad instance occurred but a few years ago, in the case of an eminent
English traveler, who going down from Jerusalem to Jericho, fell
among thieves and was wounded near the same spot mentioned by
Christ, in spite of the defenses with which he was provided. It was in
reference to such dangers as these, that two of his disciples had
provided themselves with hostile weapons, and Peter may have
been instigated to carry his sword into such a peaceful feast, by the
suspicion that the danger from the chief priests, to which Christ had
often alluded, might more particularly threaten them while they were
in the city by themselves, without the safeguard of their numerous
friends in the multitude. The answer of Jesus to this report of their
means of resistance was not in a tone to excite them to the very
zealous use of them. He simply said, “It is enough,” a phrase which
was meant to quiet them, by expressing his little regard for such a
defense as they were able to offer to him, with this contemptible
armament.

Some have conjectured that this washing of feet (page 97) was a usual rite at the
Paschal feast. So Scaliger, Beza, Baronius, Casaubon and other learned men have
thought. (See Poole’s Synopsis, on John xiii. 5.) But Buxtorf has clearly shown the falsity of
their reasons, and Lightfoot has also proved that it was a perfectly unusual thing, and that
there is no passage in all the Rabbinical writings which refers to it as a custom. It is
manifest indeed, to a common reader, that the whole peculiar force of this ablution, in this
instance, consisted in its being an entirely unusual act; and all its beautiful aptness as an
illustration of the meaning of Jesus,――that they should cease their ambitious strife for
precedence,――is lost in making it anything else than a perfectly new and original
ceremony, whose impressiveness mainly consisted in its singularity. Lightfoot also illustrates
the design of Jesus still farther, by several interesting passages from the Talmudists,
showing in what way the ablution would be regarded by his disciples, who like other Jews
would look upon it as a most degraded action, never to be performed except by inferiors to
superiors. These Talmudic authorities declare, that “Among the duties to be performed by
the wife to her husband, this was one,――that she should wash his face, his hands and his
feet.” (Maimonides on the duties of women.) The same office was due from a son to his
father,――from a slave to his master, as his references show; but he says he can find no
precept that a disciple should perform such a duty to his teacher, unless it be included in
this, “The teacher should be more honored by his scholar than a father.”

He also shows that the feet were never washed separately, with any idea of legal
purification,――though the Pharisees washed their hands separately with this view, and the
priests washed their hands and feet both, as a form of purification, but never the feet alone.
And he very justly remarks upon all this testimony, that “the farther this action of Christ
recedes from common custom, the higher its fitness for their instruction,――being
performed not merely for an example but for a precept.” (Lightfoot’s Horae Hebraica in
Gospel of John xiii. 5.)

Laid aside his garments.――The simple dress of the races of western Asia, is always
distinguishable into two parts or sets of garments,――an inner, which covered more or less
of the body, fitting it tightly, but not reaching far over the legs or arms, and consisted either
of a single cloth folded around the loins, or a tunic fastened with a girdle; sometimes also a
covering for the thighs was subjoined, making something like the rudiment of a pair of
breeches. (See Jahn Archaeologia Biblica § 120.) These were the permanent parts of the
dress, and were always required to be kept on the body, by the common rules of decency.
But the second division of the garments, (“superindumenta,” Jahn,) thrown loosely over the
inner ones, might be laid aside, on any occasion, when active exertion required the most
unconstrained motion of the limbs. One of these was a simple oblong, broad piece of cloth,
of various dimensions, but generally about three yards long, and two broad, which was
wrapped around the body like a mantle, the two upper corners being drawn over the
shoulders in front, and the rest hanging down the back, and falling around the front of the
body, without any fastenings but the folding of the upper corners. This garment was called
by the Hebrews ‫ שמלה‬or ‫שלמה‬, (simlah or salmah,) and sometimes ‫( ;בגד‬begedh;)――by the
Greeks, ἱματιον. (himation.) Jahn Archaeologia Biblica. This is the garment which is always
meant by this Greek word in the New Testament, when used in the singular
number,――translated “cloak” in the common English version, as in the passage in the text
above, where Jesus exhorts him that has no sword to sell his cloak and buy one. When this
Greek word occurs in the plural, (ἱματια, himatia,) it is translated “garments,” and it is
noticeable that in most cases where it occurs, the sense actually requires that it should be
understood only of the outer dress, to which I have referred it. As in Matthew xxi. 8, where it
is said that the people spread their garments in the way,――of course only their outer ones,
which were loose and easily thrown off, without indecent exposure. So in Mark xi. 7, 8: Luke
xix. 35. There is no need then, of supposing, as Origen does, that Jesus took off all his
clothes, or was naked, in the modern sense of the term. A variety of other outer garments in
common use both among the early and the later Jews, are described minutely by Jahn in
his Archaeologia Biblica, § 122. I shall have occasion to describe some of these, in
illustration of other passages.

My exegesis on the passage “He that is washed, needs not,” &c. may strike some as
rather bold in its illustration, yet if great authorities are necessary to support the view I have
taken, I can refer at once to a legion of commentators, both ancient and modern, who all
offer the same general explanation, though not exactly the same illustration. Poole’s
Synopsis is rich in references to such. Among these, Vatablus remarks on the need of
washing the feet of one already washed, “scil. viae causa.” Medonachus says of the feet,
“quos calcata terra iterum inquinat.” Hammond says, “he that hath been initiated, and
entered into Christ, &c. is whole clean, and hath no need to be so washed again, all over.
All that is needful to him is the daily ministering of the word and grace of Christ, to cleanse
and wash off the frailties, and imperfections, and lapses of our weak nature, those feet of
the soul.” Grotius says, “Hoc tantum opus ei est, ut ab iis se purget quae ex occasione
nascuntur. Similitudo sumpta ab his qui a balneo nudis pedibus abeunt.” Besides these and
many others largely quoted by Poole, Lampius also (in commentary in Gospel of John) goes
very fully into the same view, and quotes many others in illustration. Wolfius (in Cur.
Philology) gives various illustrations, differing in no important particular, that I can see, from
each other, nor from that of Kuinoel, who calls them “contortas expositiones,” but gives one
which is the same in almost every part, but is more fully illustrated in detail, by reference to
the usage of the ancients, of going to the bath before coming to a feast, which the disciples
no doubt had done, and made themselves clean in all parts except their feet, which had
become dirtied on the way from the bath. This is the same view which Wolf also quotes
approvingly from Elsner. Wetstein is also on this point, as on all others, abundantly rich in
illustrations from classic usage, to which he refers in a great number of quotations from
Lucian, Herodotus, Plato, Terence and Plutarch.

Sift you as wheat.――The word σινιαζω (siniazo) refers to the process of winnowing the
wheat after threshing, rather than sifting in the common application of the term, which is to
the operation of separating the flour from the bran. In oriental agriculture the operation of
winnowing is performed without any machinery, by simply taking up the threshed wheat in a
large shovel, and shaking it in such a way that the grain may fall out into a place prepared
on the ground, while the wind blows away the chaff. The whole operation is well described
in the fragments appended to Taylor’s editions of Calmet’s dictionary, (Hund. i. No. 48, in
Vol. III.) and is there illustrated by a plate. The phrase then, was highly expressive of a
thorough trial of character, or of utter ruin, by violent and overwhelming misfortune, and as
such is often used in the Old Testament. As in Jeremiah xv. 7. “I will fan them with a fan,”
&c. Also in li. 3. In Psalm cxxxix. 2. “Thou winnowest my path,” &c.; compare translation
“Thou compassest my path.” The same figure is effectively used by John the Baptist, in
Matthew iii. 12, and Luke iii. 17.

Galilean pugnacity.――Josephus, who was very familiar with the Galileans by his
military service among them, thus characterizes them. “The Galileans are fighters even from
infancy, and are every where numerous, nor are they capable of fear.” Jewish War, book III.
chapter iii. section 2.

From Jerusalem to Jericho.――The English traveler here referred to, is Sir Frederic
Henniker, who in the year 1820, met with this calamity, which he thus describes in his
travels, pp. 284‒289.

“The route is over hills, rocky, barren and uninteresting; we arrived at a fountain, and
here my two attendants paused to refresh themselves; the day was so hot that I was
anxious to finish the journey, and hurried forwards. A ruined building situated on the summit
of a hill was now within sight, and I urged my horse towards it; the janissary galloped by me,
and making signs for me not to precede him, he rode into and round the building, and then
motioned me to advance. We next came to a hill, through the very apex of which has been
cut a passage, the rocks overhanging it on either side. Quaresmius, (book vi. chapter 2.)
quoting Brocardus, 200 years past, mentions that there is a place horrible to the eye, and
full of danger, called Abdomin, which signifies blood; where he, descending from Jerusalem
to Jericho, fell among thieves. I was in the act of passing through this ditch, when a bullet
whizzed by, close to my head; I saw no one, and had scarcely time to think, when another
was fired some distance in advance. I could yet see no one,――the janissary was beneath
the brow of the hill, in his descent; I looked back, but my servant was not yet within sight. I
looked up, and within a few inches of my head were three muskets, and three men taking
aim at me. Escape or resistance were alike impossible. I got off my horse. Eight men
jumped down from the rocks, and commenced a scramble for me; I observed also a party
running towards Nicholai. At this moment the janissary galloped in among us with his sword
drawn.

“A sudden panic seized the janissary; he cried on the name of the Prophet, and galloped
away. As he passed, I caught at a rope hanging from his saddle. I had hoped to leap upon
his horse, but found myself unable;――my feet were dreadfully lacerated by the honey-
combed rocks――nature would support me no longer――I fell, but still clung to the rope. In
this manner I was drawn some few yards, till, bleeding from my ancle to my shoulder, I
resigned myself to my fate. As soon as I stood up, one of my pursuers took aim at me, but
the other casually advancing between us, prevented his firing; he then ran up, and with his
sword, aimed such a blow as would not have required a second; his companion prevented
its full effect, so that it merely cut my ear in halves, and laid open one side of my face; they
then stripped me naked.

“It was now past mid-day, and burning hot; I bled profusely,――and two vultures, whose
business it is to consume corpses, were hovering over me. I should scarcely have had
strength to resist, had they chosen to attack me. At length we arrived about 3 P. M. at
Jericho.――My servant was unable to lift me to the ground; the janissary was lighting his
pipe, and the soldiers were making preparations to pursue the robbers; not one person
would assist a half-dead Christian. After some minutes a few Arabs came up and placed me
by the side of the horse-pond, just so that I could not dip my finger into the water. This pool
is resorted to by every one in search of water, and that employment falls exclusively upon
females;――they surrounded me, and seemed so earnest in their sorrow, that,
notwithstanding their veils, I almost felt pleasure at my wound. One of them in particular
held her pitcher to my lips, till she was sent away by the Chous;――I called her, she
returned, and was sent away again; and the third time she was turned out of the yard. She
wore a red veil, (the sign of not being married,) and therefore there was something
unpardonable in her attention to any man, especially to a Christian; she however returned
with her mother, and brought me some milk. I believe that Mungo Park, on some dangerous
occasion during his travels, received considerable assistance from the compassionate sex.”

the scenes of gethsemane.

After much more conversation and prayer with his disciples in the
supper-room, and having sung the hymn of praise which usually
concluded the passover feast among the Jews, Jesus went with
them out west of the city, over the brook Kedron, at the foot of the
Olive mount, where there was a garden, called Gethsemane, to
which he had often resorted with his disciples, it being retired as well
as pleasant. While they were on the way, a new occasion happened
of showing Peter’s self-confidence, which Jesus again rebuked with
the prediction that it would too soon fail him. He was telling them all,
that events would soon happen that would overthrow their present
confidence in him, and significantly quoted to them the appropriate
passage in Zechariah xiii. 7. “I will smite the shepherd, and the
sheep shall be scattered.” Peter, glad of a new opportunity to assert
his steadfast adherence to his Master, again assured him that,
though all should be offended, or lose their confidence in him, yet
would not he; but though alone, would always maintain his present
devotion to him. The third time did Jesus reply in the circumstantial
prediction of his near and certain fall. “This day, even this night,
before the cock crow twice, thou shalt deny me thrice.” This repeated
distrustful and reproachful denunciation, became, at last, too much
for Peter’s warm temper; and in a burst of offended zeal, he declared
the more vehemently, “If I should die with thee, I will not deny thee in
any wise.” To this solemn protestation against the thought of
defection, all the other apostles present gave their word of hearty
assent.

VALLEY OF THE BROOK KEDRON

between Jerusalem and the Mount of Olives.


John xviii. 1.

They now reached the garden, and when they had entered it,
Jesus spoke to all the disciples present, except his three chosen
ones, saying, “Sit ye here, while I go and pray yonder.” He retired
accordingly into some recess of the garden, with Peter and the two
sons of Zebedee, James and John; and as soon as he was alone
with them, begun to give utterance to feelings of deep distress and
depression of spirits. Leaving them, with the express injunction to
keep awake and wait for him, he went for a short time still farther,
and there, in secret and awful woe, that wrung from his bowed head
the dark sweat of an unutterable agony, yet in submission to God, he
prayed that the horrible suffering and death to which he had been so
sternly devoted, might not light on him. Returning to the three
appointed watchers, he found them asleep! Even as amid the lonely
majesty of Mount Hermon, human weakness had borne down the
willing spirit in spite of the sublime character of the place and the
persons before them; so here, not the groans of that beloved
suffering Lord, for whom they had just expressed such deep regard,
could keep their sleepy eyes open, when they were thus exhausted
with a long day’s agitating incidents, and were rendered still more
dull and stupid by the chilliness of the evening air, as well as the
lateness of the hour of the night; for it was near ten o’clock. At this
sad instance of the inability of their minds to overcome the frailties of
the body, after all their fine protestations of love and zeal, he mildly
and mournfully remonstrates with Peter in particular, who had been
so far before the rest in expressing a peculiar interest in his Master.
And he said to Peter, “Simon! sleepest thou? What! could ye not
watch with me one hour? Watch ye and pray, lest ye enter into
temptation. The spirit indeed is willing, but the flesh is weak.” Well
might he question thus the constancy of the fiery zeal which had so
lately inspired Peter to those expressions of violent attachment.
What! could not all that warm devotion, that high pride of purpose,
sustain his spirit against the effects of fatigue and cold on his body?
But they had, we may suppose, crept into some shelter from the cold
night air, where they unconsciously forgot themselves. After having
half-roused them with this fruitless appeal, he left them, and again
passed through another dreadful struggle between his human and
divine nature. The same strong entreaty,――the same mournful
submission,――were expressed as before, in that moment of solitary
agony, till again he burst away from the insupportable strife of soul,
and came to see if yet sympathy in his sorrows could keep his
sleepy disciples awake. But no; the gentle rousing he had before
given them had hardly broken their slumbers. For a few moments the
voice of their Master, in tones deep and mournful with sorrow, might
have recalled them to some sense of shame for their heedless
stupidity; and for a short time their wounded pride moved them to an
effort of self-control. A few mutual expostulations in a sleepy tone,
would pass between them;――an effort at conversation perhaps,
about the incidents of the day, and the prospect of coming danger
which their Master seemed to hint;――some wonderings probably,
as to what could thus lead him apart to dark and lonely
devotion;――very likely too, some complaint about the cold;――a
shiver――a sneeze,――then a movement to a warmer attitude, and
a wrapping closer in mantles;――then the conversation languishing,
replies coming slower and duller, the attitude meanwhile declining
from the perpendicular to the horizontal, till at last the most wakeful
waits in vain for an answer to one of his drowsy remarks, and finds
himself speaking to deaf ears; and finally overcome with impatience
at them and himself, he sinks down into his former deep repose, with
a half-murmured reproach to his companions on his lips. In short, as
every one knows who has passed through such efforts, three sleepy
men will hardly keep awake the better for each other’s company; but
so far from it, on the contrary, the force of sympathy will increase the
difficulty, and the very sound of drowsy voices will serve to lull all the
sooner into slumber. In the case of the apostles too, who were
mostly men accustomed to an active life, and who were in the habit
of going to bed as soon as it was night, whenever their business
allowed them to rest, all their modes of life served to hasten the
slumbers of men so little inured to self-control of any kind. These
lengthy reasons may serve to excite some considerate sympathy for
the weakness of the apostles, and may serve as an apology for their
repeated drowsiness on solemn occasions; for a first thought on the
subject might suggest to a common man, the irreverent notion, that
those who could slumber at the transfiguration of the Son of God on
Mount Hermon, and at his agony in Gethsemane, must be very

You might also like